poad 2.61.2 → 2.63.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/global/start.js +5 -1
- package/package.json +1 -1
- package/project/cli.js +6 -3
- package/project/source.js +286 -0
- package/project/sources.js +2 -0
- package/project/storage/cp.js +45 -15
- package/project/storage/ls.js +20 -6
- package/project/storage/mv.js +5 -5
- package/project/storage/sync.js +101 -0
- package/test/source.test.js +245 -0
- package/test/storage-sync.test.js +283 -0
- package/test/storage.test.js +233 -4
- package/utils/cloud/bundle.js +2 -2
- package/utils/help-details.js +64 -5
- package/utils/logline.js +2 -2
- package/utils/storage-copy.js +91 -15
- package/utils/storage-sync.js +277 -0
- package/utils/storage.js +94 -3
package/global/start.js
CHANGED
|
@@ -160,6 +160,9 @@ module.exports = async (args = {}) => {
|
|
|
160
160
|
...aiSettings.env,
|
|
161
161
|
// Fronts : port de chacun, réserve, nom du projet (page « En construction »)
|
|
162
162
|
...(withFronts ? fronts.engineEnv(config) : []),
|
|
163
|
+
// Identité du projet (project_uuid, projet poad.io lié) : poad storage sync entre
|
|
164
|
+
// environnements d'un même projet seulement (storage 0.4.0+)
|
|
165
|
+
...require('../utils/storage').engineEnv(config),
|
|
163
166
|
],
|
|
164
167
|
ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed, ...frontPorts.exposed },
|
|
165
168
|
HostConfig: {
|
|
@@ -174,7 +177,8 @@ module.exports = async (args = {}) => {
|
|
|
174
177
|
// poad/auth et poad/storage : manifestes versionnés des réglages d'auth et des buckets.
|
|
175
178
|
// poad/reference : contenu des tables de référence, un fichier par table
|
|
176
179
|
// poad/api : définitions de l'API publiée du projet, un fichier par version
|
|
177
|
-
|
|
180
|
+
// poad/sources : déclarations des sources (<nom>.yaml), lues par meta (engine 0.64.0+)
|
|
181
|
+
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`, `${ensureDir(path.join(path.dirname(root), 'auth'))}:/project/auth`, `${ensureDir(path.join(path.dirname(root), 'storage'))}:/project/storage`, `${ensureDir(path.join(path.dirname(root), 'reference'))}:/project/reference`, `${ensureDir(path.join(path.dirname(root), 'sources'))}:/project/sources`, `${ensureDir(path.join(path.dirname(root), 'api'))}:/project/api`],
|
|
178
182
|
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
179
183
|
// compris sous Linux
|
|
180
184
|
ExtraHosts: ['host.docker.internal:host-gateway'],
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -40,11 +40,12 @@ module.exports = {
|
|
|
40
40
|
rm: 'Same as poad ref rm',
|
|
41
41
|
},
|
|
42
42
|
storage: {
|
|
43
|
-
description: 'Files of the project storage, local engine or poad.io (--env <name>): ls, cp (disk ↔ storage, storage → storage), mv, rm; a storage path is bucket/path (poad:bucket/path for cp)',
|
|
43
|
+
description: 'Files of the project storage, local engine or poad.io (--env <name>): ls, cp (disk ↔ storage, storage → storage), mv, rm, sync (local ↔ poad.io); a storage path is bucket/path (poad:bucket/path for cp)',
|
|
44
44
|
ls: 'Buckets, or the files and folders of a folder: ls [bucket[/folder]] [-r] [--json]',
|
|
45
|
-
cp: 'Copy files, -r for a folder: cp ./a.png poad:images/ | cp poad:images/a.png ./ | cp -r poad:images/2024 poad:archives/',
|
|
46
|
-
mv: 'Move or rename inside the storage (copy, then delete the source): mv <bucket/path> <bucket/path> [-r]',
|
|
45
|
+
cp: 'Copy files, -r for a folder: cp ./a.png poad:images/ | cp poad:images/a.png ./ | cp -r poad:images/2024 poad:archives/ [--concurrency <n>]',
|
|
46
|
+
mv: 'Move or rename inside the storage (copy, then delete the source): mv <bucket/path> <bucket/path> [-r] [--concurrency <n>]',
|
|
47
47
|
rm: 'Delete files, or a whole folder with -r (asks first, --yes outside a terminal): rm <bucket/path…> [-r] [--yes]',
|
|
48
|
+
sync: 'Align the storage of a poad.io environment on the local one (--pull: the other way): sync --env <name> [--pull] [--bucket <name>] [--prune] [--dry-run] [--copy-bytes] [--concurrency <n>]',
|
|
48
49
|
},
|
|
49
50
|
link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
|
|
50
51
|
unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
|
|
@@ -70,6 +71,8 @@ module.exports = {
|
|
|
70
71
|
function: 'Alias of poad functions',
|
|
71
72
|
flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): new, list, run, runs, show, cancel; --env <name> for poad.io',
|
|
72
73
|
flow: 'Alias of poad flows',
|
|
74
|
+
source: 'Sources of the project (tables kept up to date from a URL, poad/sources/<name>.yaml, engine 0.64.0+): ls, refresh <name> [--force]; --env <name> for poad.io',
|
|
75
|
+
sources: 'Alias of poad source',
|
|
73
76
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
74
77
|
gen: {
|
|
75
78
|
description: 'Génération automatique des éléments clés pour votre projet',
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
// poad source ls sources du projet (poad/sources/<nom>.yaml) et leur état
|
|
2
|
+
// poad source refresh <nom> [--force] synchronise une source maintenant et suit son exécution
|
|
3
|
+
//
|
|
4
|
+
// Une source est une table du projet tenue à jour depuis une adresse (JSON,
|
|
5
|
+
// GeoJSON, CSV, JSONL) : l'engine (0.64.0+, meta /meta/v1/sources) crée la
|
|
6
|
+
// table par une migration et génère le flow source-<nom> qui la remplit
|
|
7
|
+
// (télécharger → lire → déposer → appliquer). Le garde-fou des suppressions
|
|
8
|
+
// (safety.maxDeletePercent) refuse une source qui perdrait trop de lignes ;
|
|
9
|
+
// --force le passe pour cette exécution.
|
|
10
|
+
//
|
|
11
|
+
// --env <environnement> (production : main) et --project <id> : le projet
|
|
12
|
+
// hébergé sur poad.io (session de poad login) au lieu de l'engine local.
|
|
13
|
+
// poad.io remet au propriétaire un jeton service_role de 15 minutes (route
|
|
14
|
+
// storage-token du plan de contrôle, renouvelé pendant un long suivi) et la
|
|
15
|
+
// clé anon : jamais affichés. En local : la clé service_role du projet.
|
|
16
|
+
const flows = require('./flows');
|
|
17
|
+
|
|
18
|
+
const NAME_RE = /^[a-z][a-z0-9-]{0,55}$/; // meta, sources.ts : SOURCE_NAME_RE
|
|
19
|
+
const POLL_MS = 1000;
|
|
20
|
+
const TIMEOUT_MS = 15000;
|
|
21
|
+
const FINAL = ['completed', 'failed', 'cancelled'];
|
|
22
|
+
const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach], and --env <name> | --project <id> for poad.io';
|
|
23
|
+
|
|
24
|
+
// Engine 0.64.0 et plus : sources (/meta/v1/sources), déclarées dans poad/sources
|
|
25
|
+
const supportsSources = (config) => {
|
|
26
|
+
const [major, minor] = String(config.engine || '').split('.').map(Number);
|
|
27
|
+
return major > 0 || minor >= 64;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** Âge lisible : 12 s, 5 min, 3 h, 2 d. Pure. */
|
|
31
|
+
const age = (seconds) => {
|
|
32
|
+
if (typeof seconds !== 'number' || !Number.isFinite(seconds)) return '';
|
|
33
|
+
if (seconds < 60) return `${Math.round(seconds)} s`;
|
|
34
|
+
if (seconds < 3600) return `${Math.round(seconds / 60)} min`;
|
|
35
|
+
if (seconds < 86400) return `${Math.round(seconds / 3600)} h`;
|
|
36
|
+
return `${Math.round(seconds / 86400)} d`;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Nombre avec séparateur de milliers. Pure. */
|
|
40
|
+
const count = (n) => (typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('en-US') : '?');
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Lignes d'une source de GET /sources : nom, mode, table, lignes, dernière
|
|
44
|
+
* synchronisation, prochaine ; puis ses problèmes (déclaration, écart de
|
|
45
|
+
* structure, dernier échec). Pure.
|
|
46
|
+
*/
|
|
47
|
+
const sourceLines = (s, width = 0) => {
|
|
48
|
+
const chalk = require('chalk-v2');
|
|
49
|
+
const name = String(s.name).padEnd(width);
|
|
50
|
+
if (!s.valid) {
|
|
51
|
+
const first = (s.problems || [])[0] || {};
|
|
52
|
+
const more = (s.problems || []).length > 1 ? ` (+${s.problems.length - 1} more)` : '';
|
|
53
|
+
return [chalk.redBright(` ✖ ${name} ${s.file}`), chalk.redBright(` ${first.line ? `line ${first.line}: ` : first.path ? `${first.path}: ` : ''}${first.message || 'invalid declaration'}${more}`)];
|
|
54
|
+
}
|
|
55
|
+
const last = s.last_run;
|
|
56
|
+
const failed = last && last.status === 'failed';
|
|
57
|
+
const state = !last ? 'never run' : last.status === 'completed' ? `synced ${age(s.age_seconds)} ago` : last.status;
|
|
58
|
+
const facts = [s.mode, s.table, s.rows === null || s.rows === undefined ? '' : `${count(s.rows)} rows`, state, s.next_run_at ? `next ${s.next_run_at.replace('T', ' ').slice(0, 16)} UTC` : '', s.api ? 'api' : '']
|
|
59
|
+
.filter(Boolean)
|
|
60
|
+
.join(' ');
|
|
61
|
+
const mark = failed || (s.drift && s.drift.issues && s.drift.issues.length) || (s.problems && s.problems.length) ? chalk.yellowBright('!') : chalk.greenBright('✔');
|
|
62
|
+
const out = [` ${mark} ${chalk.bold(name)} ${chalk.grey(facts)}`];
|
|
63
|
+
if (s.title && s.title !== s.name) out[0] += ` ${s.title}`;
|
|
64
|
+
for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
|
|
65
|
+
if (s.drift && s.drift.issues) for (const issue of s.drift.issues.slice(0, 5)) out.push(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
|
|
66
|
+
if (failed && last.error) out.push(chalk.redBright(` last run failed: ${String(last.error).split('\n')[0].slice(0, 300)}`));
|
|
67
|
+
return out;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** Bilan de l'étape « appliquer » ({ rows: [{ bilan }] }), ou null. Pure. */
|
|
71
|
+
const reportOf = (view) => {
|
|
72
|
+
const step = ((view && view.steps) || []).find((x) => x.step_id === 'appliquer');
|
|
73
|
+
const rows = step && step.output && Array.isArray(step.output.rows) ? step.output.rows : null;
|
|
74
|
+
const bilan = rows && rows[0] && rows[0].bilan;
|
|
75
|
+
return bilan && typeof bilan === 'object' && !Array.isArray(bilan) ? bilan : null;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/** Lignes du bilan d'une synchronisation. Pure. */
|
|
79
|
+
const reportLines = (r) => {
|
|
80
|
+
const chalk = require('chalk-v2');
|
|
81
|
+
const out = [
|
|
82
|
+
` ${count(r.received)} received, ${count(r.inserted)} added, ${count(r.updated)} updated, ${count(r.deleted)} removed, ${count(r.unchanged)} unchanged`,
|
|
83
|
+
chalk.grey(` ${r.table || ''}: ${count(r.rows)} rows${r.forced ? ', deletion guard lifted (--force)' : ''}${typeof r.duration_ms === 'number' ? `, applied in ${flows.duration(r.duration_ms)}` : ''}`),
|
|
84
|
+
];
|
|
85
|
+
if (typeof r.received === 'number' && typeof r.kept === 'number' && r.kept < r.received) out.push(chalk.yellowBright(` ${count(r.received - r.kept)} received row(s) left out (no key, or the same key twice)`));
|
|
86
|
+
for (const p of Array.isArray(r.problems) ? r.problems : []) out.push(chalk.yellowBright(` ${p}`));
|
|
87
|
+
return out;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/** Le refus du garde-fou des suppressions, reconnu dans l'erreur de l'étape. Pure. */
|
|
91
|
+
const guardRefused = (error) => /seraient supprimées|would be (deleted|removed)/.test(String(error || ''));
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* deps (tests) : started(config), fetch, sleep(ms), cwd, cloudTarget(opts).
|
|
95
|
+
* raw : les mots de la ligne de commande tels qu'ils ont été tapés.
|
|
96
|
+
*/
|
|
97
|
+
const main = async (args = {}, raw, deps = {}) => {
|
|
98
|
+
const chalk = require('chalk-v2');
|
|
99
|
+
const path = require('path');
|
|
100
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
101
|
+
const { readConfig } = require('../utils/config');
|
|
102
|
+
const cwd = deps.cwd || process.cwd();
|
|
103
|
+
const doFetch = deps.fetch || fetch;
|
|
104
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
105
|
+
const started = deps.started || ((config) => require('../utils/docker').isDockerExist(config.project_uuid));
|
|
106
|
+
const cloudTarget = deps.cloudTarget || ((opts) => require('../utils/storage').cloudTarget(opts));
|
|
107
|
+
const fail = (message, code = 1) => {
|
|
108
|
+
process.exitCode = code;
|
|
109
|
+
console.log(chalk.redBright(message));
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const typed = flows.cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
|
|
113
|
+
if (typed.error) return fail(`poad source: ${typed.error}.`, 2);
|
|
114
|
+
const json = typed.words.includes('--json');
|
|
115
|
+
const words = typed.words.filter((w) => w !== '--json');
|
|
116
|
+
const command = words[0] || 'ls';
|
|
117
|
+
const cloud = Boolean(typed.env || typed.project);
|
|
118
|
+
const where = cloud ? ` ${[typed.env ? `--env ${typed.env}` : '', typed.project ? `--project ${typed.project}` : ''].filter(Boolean).join(' ')}` : '';
|
|
119
|
+
|
|
120
|
+
const root = findPoadDir(cwd);
|
|
121
|
+
if (!root && !(cloud && typed.project)) return fail(cloud ? 'Not in a poad project folder: cd into one, or pass --project <id>.' : 'You are not in a poad project directory.');
|
|
122
|
+
|
|
123
|
+
/** Engine visé, prêt à répondre, ou null (message affiché) */
|
|
124
|
+
const ready = async () => {
|
|
125
|
+
if (cloud) {
|
|
126
|
+
try {
|
|
127
|
+
const t = await cloudTarget({ env: typed.env, project: typed.project });
|
|
128
|
+
return { base: t.base, key: t.key, apikey: t.apikey || t.key, label: t.label, cloud: true, renew: t.renew, expires: t.renew && t.renew.first ? Date.parse(t.renew.first) : null };
|
|
129
|
+
} catch (err) {
|
|
130
|
+
return fail((err && err.message) || String(err), (err && err.exit) || 1) || null;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const config = readConfig(root);
|
|
134
|
+
if (!supportsSources(config)) return fail(`Sources need engine 0.64.0 or later (this project uses ${config.engine}): "poad upgrade".`) || null;
|
|
135
|
+
if (!(await started(config))) return fail('The project is not started: run "poad start".') || null;
|
|
136
|
+
const key = config.auth.service;
|
|
137
|
+
return { base: `http://localhost:${config.web.port}`, key, apikey: key, label: 'local engine', cloud: false };
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/** Jeton poad.io renouvelé une minute avant son expiration */
|
|
141
|
+
const fresh = async (t) => {
|
|
142
|
+
if (!t.renew || !t.expires || t.expires - Date.now() > 60000) return;
|
|
143
|
+
const n = await t.renew.next();
|
|
144
|
+
Object.assign(t, { key: n.token, apikey: n.anon_key || t.apikey, expires: Date.parse(n.expires_at) });
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
class SourceError extends Error {}
|
|
148
|
+
|
|
149
|
+
/** Appel de l'engine (route complète : /meta/v1/…, /flows/v1/…) avec le jeton service_role */
|
|
150
|
+
const call = async (t, method, route, body) => {
|
|
151
|
+
try {
|
|
152
|
+
await fresh(t);
|
|
153
|
+
} catch (err) {
|
|
154
|
+
throw new SourceError(`poad.io gave no new access: ${(err && err.message) || err}`);
|
|
155
|
+
}
|
|
156
|
+
let res;
|
|
157
|
+
try {
|
|
158
|
+
res = await doFetch(`${t.base}${route}`, {
|
|
159
|
+
method,
|
|
160
|
+
headers: { apikey: t.apikey, authorization: `Bearer ${t.key}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
|
|
161
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
162
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
163
|
+
});
|
|
164
|
+
} catch (err) {
|
|
165
|
+
const timedOut = err && (err.name === 'TimeoutError' || err.name === 'AbortError');
|
|
166
|
+
const who = t.cloud ? t.label : 'The engine';
|
|
167
|
+
throw new SourceError(timedOut ? `${who} did not answer within ${TIMEOUT_MS / 1000} s (${t.base}).` : `${who} does not answer on ${t.base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
|
|
168
|
+
}
|
|
169
|
+
const data = await res.json().catch(() => null);
|
|
170
|
+
if (res.status >= 200 && res.status < 300) return data || {};
|
|
171
|
+
const error = data && typeof data === 'object' && data.error && typeof data.error === 'object' ? data.error : null;
|
|
172
|
+
if (error && error.message) throw new SourceError(`${error.message}${error.hint ? ` (${error.hint})` : ''}`);
|
|
173
|
+
if (res.status === 404) throw new SourceError(`${t.cloud ? t.label : 'The engine'} has no sources API (HTTP 404): engine 0.64.0 or later is needed.`);
|
|
174
|
+
if (res.status === 401 || res.status === 403) throw new SourceError(t.cloud ? `${t.label} refused the access (HTTP ${res.status}): "poad login" again, or check that you own the project.` : `the engine refused the service_role key (HTTP ${res.status})`);
|
|
175
|
+
throw new SourceError(`HTTP ${res.status}`);
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const guard = async (fn) => {
|
|
179
|
+
try {
|
|
180
|
+
return await fn();
|
|
181
|
+
} catch (err) {
|
|
182
|
+
if (!(err instanceof SourceError)) throw err;
|
|
183
|
+
fail(err.message);
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// ------------------------------------------------------------------ ls
|
|
189
|
+
if (command === 'ls' || command === 'list') {
|
|
190
|
+
if (words.length > 1) return fail(USAGE, 2);
|
|
191
|
+
const t = await ready();
|
|
192
|
+
if (!t) return;
|
|
193
|
+
const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
|
|
194
|
+
if (!list) return;
|
|
195
|
+
if (json) return console.log(JSON.stringify(list.sources || [], null, 2));
|
|
196
|
+
const all = list.sources || [];
|
|
197
|
+
console.log(`${chalk.bold('Sources')} ${chalk.grey(cloud ? t.label : 'poad/sources')}`);
|
|
198
|
+
console.log(' ');
|
|
199
|
+
if (!all.length) return console.log(chalk.grey(` None yet: declare one in poad/sources/<name>.yaml${cloud ? ', then "poad deploy"' : ''}.`));
|
|
200
|
+
const width = Math.max(...all.map((s) => String(s.name).length));
|
|
201
|
+
for (const s of all) for (const line of sourceLines(s, width)) console.log(line);
|
|
202
|
+
if (all.some((s) => !s.valid)) process.exitCode = 1;
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ------------------------------------------------------------------ refresh
|
|
207
|
+
if (command === 'refresh' || command === 'sync') {
|
|
208
|
+
let name = null;
|
|
209
|
+
let force = false;
|
|
210
|
+
let wait = true;
|
|
211
|
+
for (const w of words.slice(1)) {
|
|
212
|
+
if (w === '--force') force = true;
|
|
213
|
+
else if (w === '--detach' || w === '--no-wait' || w === '-d') wait = false;
|
|
214
|
+
else if (w === '--wait') wait = true;
|
|
215
|
+
else if (w.startsWith('-')) return fail(`poad source refresh: unknown option ${w}.`, 2);
|
|
216
|
+
else if (name === null) name = w;
|
|
217
|
+
else return fail(`poad source refresh: one source at a time ("${w}").`, 2);
|
|
218
|
+
}
|
|
219
|
+
if (!name) return fail('Usage: poad source refresh <name> [--force] [--detach] [--env <name>] ("poad source ls" lists them).', 2);
|
|
220
|
+
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name (poad/sources/<name>.yaml: a-z, 0-9 and "-", a letter first, 56 characters at most).`, 2);
|
|
221
|
+
const t = await ready();
|
|
222
|
+
if (!t) return;
|
|
223
|
+
const started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force }));
|
|
224
|
+
if (!started) return;
|
|
225
|
+
const runId = started.run_id;
|
|
226
|
+
if (!runId) return fail('Source not refreshed: the engine gave no run id.');
|
|
227
|
+
if (!wait) {
|
|
228
|
+
console.log(runId);
|
|
229
|
+
if (process.stderr.isTTY) console.error(chalk.grey(` Follow it: poad flows show ${runId}${where}`));
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const drift = started.drift && Array.isArray(started.drift.issues) ? started.drift.issues : [];
|
|
233
|
+
console.log(`${chalk.bold(name)} ${chalk.grey(`flow ${started.flow}, run ${runId}${force ? ', --force' : ''}${cloud ? ` ${t.label}` : ''}`)}`);
|
|
234
|
+
for (const issue of drift.slice(0, 5)) console.log(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
|
|
235
|
+
const seen = new Map();
|
|
236
|
+
let misses = 0;
|
|
237
|
+
let view = null;
|
|
238
|
+
for (;;) {
|
|
239
|
+
try {
|
|
240
|
+
view = await call(t, 'GET', `/flows/v1/runs/${encodeURIComponent(runId)}`);
|
|
241
|
+
misses = 0;
|
|
242
|
+
} catch (err) {
|
|
243
|
+
if (!(err instanceof SourceError)) throw err;
|
|
244
|
+
if (++misses >= 5) {
|
|
245
|
+
fail(`Lost track of the run: ${err.message}`);
|
|
246
|
+
return console.log(chalk.grey(` It may still be running: poad flows show ${runId}${where}`));
|
|
247
|
+
}
|
|
248
|
+
await sleep(POLL_MS);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
for (const step of view.steps || []) {
|
|
252
|
+
const key = flows.stepKey(step);
|
|
253
|
+
if (seen.get(step.step_id) === key) continue;
|
|
254
|
+
seen.set(step.step_id, key);
|
|
255
|
+
const line = flows.stepLine(step);
|
|
256
|
+
if (line) console.log(line);
|
|
257
|
+
}
|
|
258
|
+
if (FINAL.includes(view.status)) break;
|
|
259
|
+
await sleep(POLL_MS);
|
|
260
|
+
}
|
|
261
|
+
console.log(' ');
|
|
262
|
+
const took = view.duration_ms === null || view.duration_ms === undefined ? '' : chalk.grey(` in ${flows.duration(view.duration_ms)}`);
|
|
263
|
+
if (view.status === 'completed') {
|
|
264
|
+
console.log(`${chalk.greenBright('completed')}${took}`);
|
|
265
|
+
const report = reportOf(view);
|
|
266
|
+
if (report) for (const line of reportLines(report)) console.log(line);
|
|
267
|
+
const read = (view.steps || []).find((x) => x.step_id === 'lire');
|
|
268
|
+
const unread = read && read.output && read.output.problems && read.output.problems.count;
|
|
269
|
+
if (unread) console.log(chalk.yellowBright(` ${count(unread)} value(s) not converted while reading (kept as null): poad flows show ${runId}${where}`));
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
process.exitCode = 1;
|
|
273
|
+
console.log(`${view.status === 'cancelled' ? chalk.yellowBright('cancelled') : chalk.redBright(view.status)}${took}`);
|
|
274
|
+
const failedStep = (view.steps || []).find((x) => x.status === 'failed');
|
|
275
|
+
const error = (failedStep && failedStep.error) || view.error;
|
|
276
|
+
if (error) console.log(chalk.redBright(` ${String(error).split('\n')[0].slice(0, 500)}`));
|
|
277
|
+
if (guardRefused(error) && !force) console.log(chalk.grey(` Nothing was changed. If the source is right: poad source refresh ${name} --force${where}`));
|
|
278
|
+
console.log(chalk.grey(` Details: poad flows show ${runId}${where} · poad logs source=${name}`));
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
fail(USAGE, 2);
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
module.exports = (args, raw) => main(args, raw);
|
|
286
|
+
Object.assign(module.exports, { main, supportsSources, sourceLines, reportOf, reportLines, guardRefused, age, NAME_RE });
|
package/project/storage/cp.js
CHANGED
|
@@ -1,41 +1,71 @@
|
|
|
1
|
-
// poad storage cp <source> <destination> [-r] [--json]
|
|
1
|
+
// poad storage cp <source> <destination> [-r] [--concurrency <n>] [--json]
|
|
2
2
|
// poad storage cp ./photo.png poad:images/ disque → Stockage
|
|
3
3
|
// poad storage cp -r ./site poad:web/ un dossier entier
|
|
4
4
|
// poad storage cp poad:images/photo.png ./ Stockage → disque
|
|
5
5
|
// poad storage cp -r poad:images/2024 poad:archives/ Stockage → Stockage
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
// Un fichier déjà identique à la destination (même taille, même MD5) n'est pas recopié :
|
|
7
|
+
// relancer la même commande ne fait que ce qui manque. Au moins un échec : code de sortie 1,
|
|
8
|
+
// et le bilan final redonne la liste des échecs (chemin, raison).
|
|
9
|
+
const SPEC = { values: ['env', 'project', 'concurrency'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } };
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
+
module.exports = (args, raw, deps) => require('../../utils/cloud/cli').run(raw, SPEC, ({ opts, positionals, out }) => copy({ opts, positionals, out, move: false, deps }));
|
|
12
|
+
|
|
13
|
+
/** Bilan des échecs, à la fin (pas noyé au milieu de milliers de lignes) */
|
|
14
|
+
function printFailures(out, list) {
|
|
15
|
+
if (!list.length) return;
|
|
16
|
+
const { chalk } = out;
|
|
17
|
+
out.log(chalk.redBright(` ${list.length} failure${list.length === 1 ? '' : 's'}:`));
|
|
18
|
+
for (const f of list) out.log(chalk.redBright(` ✖ ${f.path}: ${f.reason}`));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Partagé avec mv (move : sources supprimées une fois copiées, Stockage seulement). deps.target (tests) */
|
|
22
|
+
async function copy({ opts, positionals, out, move, deps = {} }) {
|
|
11
23
|
const s = require('../../utils/storage');
|
|
12
24
|
const c = require('../../utils/storage-copy');
|
|
13
25
|
const { usageError } = require('../../utils/cloud/api');
|
|
14
26
|
const { chalk } = out;
|
|
15
27
|
const verb = move ? 'mv' : 'cp';
|
|
16
|
-
if (positionals.length !== 2) throw usageError(`Usage: poad storage ${verb} <source> <destination> [-r]${move ? '' : ' (a storage path is written poad:bucket/path)'}`);
|
|
17
|
-
const
|
|
28
|
+
if (positionals.length !== 2) throw usageError(`Usage: poad storage ${verb} <source> <destination> [-r] [--concurrency <n>]${move ? '' : ' (a storage path is written poad:bucket/path)'}`);
|
|
29
|
+
const concurrency = s.concurrency(opts.concurrency);
|
|
30
|
+
const api = s.client(await (deps.target || s.target)(opts));
|
|
18
31
|
const { items } = await c.plan(api, positionals[0], positionals[1], { recursive: opts.recursive, remoteOnly: move });
|
|
19
32
|
const r = await c.run(api, items, {
|
|
33
|
+
concurrency,
|
|
20
34
|
onDone: (it) => out.log(` ${chalk.greenBright('✔')} ${c.label(it.from)} ${chalk.grey('→')} ${c.label(it.to)} ${chalk.grey(s.size(it.size))}`),
|
|
35
|
+
onError: (it, e) => out.log(chalk.redBright(` ✖ ${c.label(it.from)} → ${c.label(it.to)}: ${s.reason(e)}`)),
|
|
21
36
|
});
|
|
22
37
|
let deleted = [];
|
|
23
|
-
|
|
24
|
-
|
|
38
|
+
// Seules les sources bien copiées (ou déjà identiques à la destination) sont supprimées
|
|
39
|
+
const moved = [...r.done, ...r.unchanged];
|
|
40
|
+
if (move && moved.length) {
|
|
25
41
|
const byBucket = new Map();
|
|
26
|
-
for (const it of
|
|
42
|
+
for (const it of moved) byBucket.set(it.from.bucket, [...(byBucket.get(it.from.bucket) || []), it.from.key]);
|
|
27
43
|
for (const [bucket, keys] of byBucket)
|
|
28
44
|
for (let i = 0; i < keys.length; i += 1000) deleted.push(...((await api.remove(bucket, keys.slice(i, i + 1000))) || []).map((o) => s.show(bucket, o.name)));
|
|
29
45
|
}
|
|
30
|
-
|
|
46
|
+
const failures = c.failures(r.errors);
|
|
31
47
|
const n = r.done.length;
|
|
32
|
-
|
|
48
|
+
const same = r.unchanged.length;
|
|
49
|
+
out.log(
|
|
50
|
+
chalk.grey(
|
|
51
|
+
` ${n} file${n === 1 ? '' : 's'} ${move ? 'moved' : 'copied'}, ${s.size(r.bytes)}` +
|
|
52
|
+
`${same ? `, ${same} already identical at the destination${move ? ' (source deleted)' : ''}` : ''}` +
|
|
53
|
+
`${failures.length ? `, ${failures.length} failed${move ? ' (left in place)' : ''}` : ''}`,
|
|
54
|
+
),
|
|
55
|
+
);
|
|
56
|
+
printFailures(out, failures);
|
|
57
|
+
const row = (it) => ({ from: c.label(it.from), to: c.label(it.to), size: it.size });
|
|
33
58
|
out.result({
|
|
34
|
-
[move ? 'moved' : 'copied']: r.done.map(
|
|
59
|
+
[move ? 'moved' : 'copied']: r.done.map(row),
|
|
60
|
+
unchanged: r.unchanged.map(row),
|
|
35
61
|
...(move ? { deleted } : {}),
|
|
36
|
-
|
|
62
|
+
failures,
|
|
63
|
+
// Ancien nom, gardé pour les scripts existants
|
|
64
|
+
failed: r.errors.map((e) => ({ from: c.label(e.item.from), to: c.label(e.item.to), error: s.reason(e.error) })),
|
|
37
65
|
});
|
|
38
|
-
return
|
|
66
|
+
return failures.length ? 1 : 0;
|
|
39
67
|
}
|
|
40
68
|
|
|
41
69
|
module.exports.copy = copy;
|
|
70
|
+
module.exports.SPEC = SPEC;
|
|
71
|
+
module.exports.printFailures = printFailures;
|
package/project/storage/ls.js
CHANGED
|
@@ -21,13 +21,27 @@ module.exports = (args, raw) =>
|
|
|
21
21
|
await api.bucket(where.bucket).catch((e) => {
|
|
22
22
|
throw e.status === 404 ? new (require('../../utils/cloud/api').CloudError)(`No bucket "${where.bucket}".`, { code: 'not_found' }) : e;
|
|
23
23
|
});
|
|
24
|
-
const rows = await api.list(where.bucket, where.key);
|
|
25
|
-
const exact = !where.dir && rows.find((o) => o.name === where.key);
|
|
26
24
|
const prefix = where.key ? `${where.key}/` : '';
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
const fileEntry = (o) => [{ kind: 'file', name: o.name, size: Number(o.metadata && o.metadata.size) || 0, updated: o.updated_at, type: o.metadata && o.metadata.mimetype }];
|
|
26
|
+
let list = null;
|
|
27
|
+
// Sans -r : la vue du dossier calculée par le service (storage 0.5+), tous les sous-dossiers d'un coup ;
|
|
28
|
+
// un service plus ancien rend une liste d'objets (null ici) : l'ancienne manière, plus bas
|
|
29
|
+
if (!opts.recursive) {
|
|
30
|
+
const view = await api.browse(where.bucket, where.key);
|
|
31
|
+
if (view) {
|
|
32
|
+
if (!view.folders.length && !view.files.length && where.key && !where.dir) {
|
|
33
|
+
const [first] = (await api.page(where.bucket, where.key, 1)) || [];
|
|
34
|
+
list = first && first.name === where.key ? fileEntry(first) : [];
|
|
35
|
+
} else list = s.viewEntries(view);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (!list) {
|
|
39
|
+
const rows = await api.list(where.bucket, where.key);
|
|
40
|
+
const exact = !where.dir && rows.find((o) => o.name === where.key);
|
|
41
|
+
if (exact) list = fileEntry(exact);
|
|
42
|
+
else if (opts.recursive) list = rows.filter((o) => o.name.startsWith(prefix)).map((o) => ({ kind: 'file', name: o.name.slice(prefix.length), size: Number(o.metadata && o.metadata.size) || 0, updated: o.updated_at, type: o.metadata && o.metadata.mimetype }));
|
|
43
|
+
else list = s.entries(rows, prefix);
|
|
44
|
+
}
|
|
31
45
|
out.result({ bucket: where.bucket, path: where.key, entries: list });
|
|
32
46
|
if (out.json) return;
|
|
33
47
|
if (!list.length) {
|
package/project/storage/mv.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// poad storage mv <bucket/chemin> <bucket/chemin> [-r] [--json] : déplacer ou renommer dans le Stockage
|
|
1
|
+
// poad storage mv <bucket/chemin> <bucket/chemin> [-r] [--concurrency <n>] [--json] : déplacer ou renommer dans le Stockage
|
|
2
2
|
// (copie puis suppression de la source ; une source dont la copie échoue reste en place).
|
|
3
3
|
// « poad: » devant les chemins est facultatif ici : les deux sont dans le Stockage.
|
|
4
|
-
module.exports = (args, raw) =>
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
module.exports = (args, raw, deps) => {
|
|
5
|
+
const cp = require('./cp');
|
|
6
|
+
return require('../../utils/cloud/cli').run(raw, cp.SPEC, ({ opts, positionals, out }) => cp.copy({ opts, positionals, out, move: true, deps }));
|
|
7
|
+
};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// poad storage sync --env <nom> [--project <id>] [--pull] [--bucket <nom>] [--prune] [--dry-run] [--copy-bytes] [--concurrency <n>] [--yes] [--json]
|
|
2
|
+
//
|
|
3
|
+
// Aligne le Stockage du projet local (engine lancé) sur celui d'un environnement poad.io,
|
|
4
|
+
// ou l'inverse avec --pull. Voir utils/storage-sync.js pour les deux façons de faire
|
|
5
|
+
// (octets, ou références quand les deux côtés rangent au même endroit). Relancée, elle ne
|
|
6
|
+
// refait que ce qui manque (nom, taille, MD5) ; au moins un échec : code de sortie 1 et liste
|
|
7
|
+
// des échecs dans le bilan final.
|
|
8
|
+
// deps (tests) : localTarget, cloudTarget, client
|
|
9
|
+
module.exports = (args, raw, deps = {}) =>
|
|
10
|
+
require('../../utils/cloud/cli').run(
|
|
11
|
+
raw,
|
|
12
|
+
{ values: ['env', 'project', 'bucket', 'concurrency'], flags: ['pull', 'prune', 'dry-run', 'copy-bytes'], alias: { n: 'dry-run' } },
|
|
13
|
+
async ({ opts, positionals, out }) => {
|
|
14
|
+
const s = require('../../utils/storage');
|
|
15
|
+
const ss = require('../../utils/storage-sync');
|
|
16
|
+
const cli = require('../../utils/cloud/cli');
|
|
17
|
+
const { usageError } = require('../../utils/cloud/api');
|
|
18
|
+
const { chalk } = out;
|
|
19
|
+
if (positionals.length) throw usageError(`unexpected argument "${positionals[0]}". Usage: poad storage sync --env <name> [--pull] [--bucket <name>] [--prune] [--dry-run] [--copy-bytes]`);
|
|
20
|
+
if (!opts.env && !opts.project) throw usageError('poad storage sync needs the poad.io environment to sync with: --env <name> (main: production), or --project <id>.');
|
|
21
|
+
const concurrency = s.concurrency(opts.concurrency);
|
|
22
|
+
if (opts.bucket !== undefined && !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,62}$/.test(opts.bucket)) throw usageError(`"${opts.bucket}" is not a bucket name`);
|
|
23
|
+
|
|
24
|
+
const local = await (deps.localTarget || s.localTarget)();
|
|
25
|
+
const cloud = await (deps.cloudTarget || s.cloudTarget)(opts);
|
|
26
|
+
const [fromT, toT] = opts.pull ? [cloud, local] : [local, cloud];
|
|
27
|
+
const from = (deps.client || s.client)(fromT);
|
|
28
|
+
const to = (deps.client || s.client)(toT);
|
|
29
|
+
const dry = Boolean(opts['dry-run']);
|
|
30
|
+
|
|
31
|
+
out.log(chalk.grey(` ${fromT.label} → ${toT.label}${dry ? ' (dry run: nothing is changed)' : ''}`));
|
|
32
|
+
const mark = { add: chalk.greenBright('+'), update: chalk.yellowBright('~'), remove: chalk.redBright('-'), bucket: chalk.greenBright('+') };
|
|
33
|
+
const r = await ss.sync(from, to, {
|
|
34
|
+
bucket: opts.bucket,
|
|
35
|
+
prune: Boolean(opts.prune),
|
|
36
|
+
dryRun: dry,
|
|
37
|
+
copyBytes: Boolean(opts['copy-bytes']),
|
|
38
|
+
concurrency,
|
|
39
|
+
fromLabel: fromT.label,
|
|
40
|
+
toLabel: toT.label,
|
|
41
|
+
confirm: (t) =>
|
|
42
|
+
cli.confirm(
|
|
43
|
+
`On the ${toT.label}: replace ${t.updated} file${t.updated === 1 ? '' : 's'}${t.removed ? ` and delete ${t.removed}` : ''}${t.added ? ` (and add ${t.added})` : ''}?`,
|
|
44
|
+
{ yes: opts.yes, json: out.json },
|
|
45
|
+
),
|
|
46
|
+
// Dit tout de suite comment la copie se fait (octets ou références), avant le premier fichier
|
|
47
|
+
onMode: (m) => out.log(chalk.grey(` ${m.reason}`)),
|
|
48
|
+
onItem: (e) => {
|
|
49
|
+
if (e.error) return out.log(chalk.redBright(` ✖ ${e.bucket}${e.name ? `/${e.name}` : ''}: ${s.reason(e.error)}`));
|
|
50
|
+
if (e.action === 'bucket') return out.log(` ${mark.bucket} bucket ${e.bucket} ${chalk.grey('created')}`);
|
|
51
|
+
out.log(` ${mark[e.action]} ${e.bucket}/${e.name}${Number.isFinite(e.size) ? ` ${chalk.grey(s.size(e.size))}` : ''}`);
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const t = r.totals;
|
|
56
|
+
if (r.mode === 'references') out.log(chalk.grey(' Same place for both environments: deleting a file on the side that wrote it erases it for the other side too.'));
|
|
57
|
+
if (dry)
|
|
58
|
+
for (const p of r.buckets) {
|
|
59
|
+
if (p.create) out.log(` ${mark.bucket} bucket ${p.bucket} ${chalk.grey('would be created')}`);
|
|
60
|
+
for (const o of p.add) out.log(` ${mark.add} ${p.bucket}/${o.name} ${chalk.grey(s.size(o.size))}`);
|
|
61
|
+
for (const o of p.update) out.log(` ${mark.update} ${p.bucket}/${o.name} ${chalk.grey(s.size(o.size))}`);
|
|
62
|
+
for (const o of p.remove) out.log(` ${mark.remove} ${p.bucket}/${o.name}`);
|
|
63
|
+
}
|
|
64
|
+
for (const p of r.buckets)
|
|
65
|
+
for (const o of p.kept) out.log(chalk.yellowBright(` ! ${p.bucket}/${o.name} kept: the ${fromT.label} still uses its content under another name (same place)`));
|
|
66
|
+
|
|
67
|
+
const verb = dry ? 'would be ' : '';
|
|
68
|
+
const bytes = r.mode === 'bytes' ? r.buckets.reduce((n, p) => n + [...p.add, ...p.update].reduce((m, o) => m + (o.size || 0), 0), 0) : 0;
|
|
69
|
+
out.log(
|
|
70
|
+
chalk.grey(
|
|
71
|
+
` ${t.added} ${verb}added, ${t.updated} ${verb}updated, ${t.unchanged} unchanged, ${t.removed} ${verb}removed` +
|
|
72
|
+
`${t.kept ? `, ${t.kept} kept` : ''}${t.buckets_created ? `, ${t.buckets_created} bucket${t.buckets_created === 1 ? '' : 's'} ${verb}created` : ''}` +
|
|
73
|
+
`, ${s.size(dry ? bytes : t.bytes)} ${dry ? 'to transfer' : 'transferred'}${t.failed ? `, ${t.failed} failed` : ''}` +
|
|
74
|
+
'',
|
|
75
|
+
),
|
|
76
|
+
);
|
|
77
|
+
// Les échecs, redits à la fin : pas noyés au milieu de milliers de lignes
|
|
78
|
+
const failures = r.errors.map((e) => ({ path: `${e.bucket}${e.name ? `/${e.name}` : ''}`, reason: e.error })).sort((a, b) => a.path.localeCompare(b.path));
|
|
79
|
+
require('./cp').printFailures(out, failures);
|
|
80
|
+
out.result({
|
|
81
|
+
mode: r.mode,
|
|
82
|
+
dry_run: dry,
|
|
83
|
+
from: fromT.label,
|
|
84
|
+
to: toT.label,
|
|
85
|
+
location: r.mode === 'references' ? { backend: r.from.backend, location: r.from.location } : undefined,
|
|
86
|
+
totals: { ...t, ...(dry ? { bytes } : {}) },
|
|
87
|
+
buckets: r.buckets.map((p) => ({
|
|
88
|
+
bucket: p.bucket,
|
|
89
|
+
created: p.create,
|
|
90
|
+
added: p.add.map((o) => o.name),
|
|
91
|
+
updated: p.update.map((o) => o.name),
|
|
92
|
+
unchanged: p.unchanged.length,
|
|
93
|
+
removed: p.remove.map((o) => o.name),
|
|
94
|
+
kept: p.kept.map((o) => o.name),
|
|
95
|
+
})),
|
|
96
|
+
failures,
|
|
97
|
+
failed: r.errors,
|
|
98
|
+
});
|
|
99
|
+
return t.failed ? 1 : 0;
|
|
100
|
+
},
|
|
101
|
+
);
|