poad 2.61.2 → 2.64.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.
@@ -0,0 +1,444 @@
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
+ // poad source import <fichier> [--table t] charge un fichier (CSV, JSON, GeoJSON, JSONL, gzip) dans une table :
4
+ // source « Fichier envoyé » (nouvelle, ou nouvelle version d'une source envoyée)
5
+ // poad source pull <nom> [--force] rapatrie la déclaration d'une source (créée dans la console
6
+ // de poad.io avec --env) dans poad/sources/<nom>.yaml
7
+ //
8
+ // Une source est une table du projet tenue à jour depuis une adresse (JSON,
9
+ // GeoJSON, CSV, JSONL) : l'engine (0.64.0+, meta /meta/v1/sources) crée la
10
+ // table par une migration et génère le flow source-<nom> qui la remplit
11
+ // (télécharger → lire → déposer → appliquer). Le garde-fou des suppressions
12
+ // (safety.maxDeletePercent) refuse une source qui perdrait trop de lignes ;
13
+ // --force le passe pour cette exécution.
14
+ //
15
+ // --env <environnement> (production : main) et --project <id> : le projet
16
+ // hébergé sur poad.io (session de poad login) au lieu de l'engine local.
17
+ // poad.io remet au propriétaire un jeton service_role de 15 minutes (route
18
+ // storage-token du plan de contrôle, renouvelé pendant un long suivi) et la
19
+ // clé anon : jamais affichés. En local : la clé service_role du projet.
20
+ const flows = require('./flows');
21
+
22
+ const NAME_RE = /^(?:[a-z][a-z0-9-]{0,55}|[a-z_][a-z0-9_]{0,62})$/; // meta, sources.ts : SOURCE_NAME_RE (nom de table, ou d'avant 0.65.0)
23
+ const POLL_MS = 1000;
24
+ const TIMEOUT_MS = 30000;
25
+ const FINAL = ['completed', 'failed', 'cancelled'];
26
+ const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | import <file> [--table <table>] [--name <source>] | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
27
+
28
+ // Engine 0.64.0 et plus : sources (/meta/v1/sources), déclarées dans poad/sources
29
+ const supportsSources = (config) => {
30
+ const [major, minor] = String(config.engine || '').split('.').map(Number);
31
+ return major > 0 || minor >= 64;
32
+ };
33
+
34
+ /** Âge lisible : 12 s, 5 min, 3 h, 2 d. Pure. */
35
+ const age = (seconds) => {
36
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds)) return '';
37
+ if (seconds < 60) return `${Math.round(seconds)} s`;
38
+ if (seconds < 3600) return `${Math.round(seconds / 60)} min`;
39
+ if (seconds < 86400) return `${Math.round(seconds / 3600)} h`;
40
+ return `${Math.round(seconds / 86400)} d`;
41
+ };
42
+
43
+ /** Nombre avec séparateur de milliers. Pure. */
44
+ const count = (n) => (typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('en-US') : '?');
45
+
46
+ /**
47
+ * Lignes d'une source de GET /sources : nom, mode, table, lignes, dernière
48
+ * synchronisation, prochaine ; puis ses problèmes (déclaration, écart de
49
+ * structure, dernier échec). Pure.
50
+ */
51
+ const sourceLines = (s, width = 0) => {
52
+ const chalk = require('chalk-v2');
53
+ const name = String(s.name).padEnd(width);
54
+ if (!s.valid) {
55
+ const first = (s.problems || [])[0] || {};
56
+ const more = (s.problems || []).length > 1 ? ` (+${s.problems.length - 1} more)` : '';
57
+ return [chalk.redBright(` ✖ ${name} ${s.file}`), chalk.redBright(` ${first.line ? `line ${first.line}: ` : first.path ? `${first.path}: ` : ''}${first.message || 'invalid declaration'}${more}`)];
58
+ }
59
+ const last = s.last_run;
60
+ const failed = last && last.status === 'failed';
61
+ const state = !last ? 'never run' : last.status === 'completed' ? `synced ${age(s.age_seconds)} ago` : last.status;
62
+ 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' : '']
63
+ .filter(Boolean)
64
+ .join(' ');
65
+ const mark = failed || (s.drift && s.drift.issues && s.drift.issues.length) || (s.problems && s.problems.length) ? chalk.yellowBright('!') : chalk.greenBright('✔');
66
+ const out = [` ${mark} ${chalk.bold(name)} ${chalk.grey(facts)}`];
67
+ if (s.title && s.title !== s.name) out[0] += ` ${s.title}`;
68
+ for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
69
+ 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)}`));
70
+ if (failed && last.error) out.push(chalk.redBright(` last run failed: ${String(last.error).split('\n')[0].slice(0, 300)}`));
71
+ return out;
72
+ };
73
+
74
+ /** Bilan de l'étape « appliquer » ({ rows: [{ bilan }] }), ou null. Pure. */
75
+ const reportOf = (view) => {
76
+ const step = ((view && view.steps) || []).find((x) => x.step_id === 'appliquer');
77
+ const rows = step && step.output && Array.isArray(step.output.rows) ? step.output.rows : null;
78
+ const bilan = rows && rows[0] && rows[0].bilan;
79
+ return bilan && typeof bilan === 'object' && !Array.isArray(bilan) ? bilan : null;
80
+ };
81
+
82
+ /** Lignes du bilan d'une synchronisation. Pure. */
83
+ const reportLines = (r) => {
84
+ const chalk = require('chalk-v2');
85
+ const out = [
86
+ ` ${count(r.received)} received, ${count(r.inserted)} added, ${count(r.updated)} updated, ${count(r.deleted)} removed, ${count(r.unchanged)} unchanged`,
87
+ 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)}` : ''}`),
88
+ ];
89
+ 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)`));
90
+ for (const p of Array.isArray(r.problems) ? r.problems : []) out.push(chalk.yellowBright(` ${p}`));
91
+ return out;
92
+ };
93
+
94
+ /** Le refus du garde-fou des suppressions, reconnu dans l'erreur de l'étape. Pure. */
95
+ const guardRefused = (error) => /seraient supprimées|would be (deleted|removed)/.test(String(error || ''));
96
+
97
+ /**
98
+ * deps (tests) : started(config), fetch, sleep(ms), cwd, cloudTarget(opts).
99
+ * raw : les mots de la ligne de commande tels qu'ils ont été tapés.
100
+ */
101
+ const main = async (args = {}, raw, deps = {}) => {
102
+ const chalk = require('chalk-v2');
103
+ const path = require('path');
104
+ const { findPoadDir } = require('../utils/findpoad');
105
+ const { readConfig } = require('../utils/config');
106
+ const fs = require('fs');
107
+ const cwd = deps.cwd || process.cwd();
108
+ const doFetch = deps.fetch || fetch;
109
+ const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
110
+ const started = deps.started || ((config) => require('../utils/docker').isDockerExist(config.project_uuid));
111
+ const cloudTarget = deps.cloudTarget || ((opts) => require('../utils/storage').cloudTarget(opts));
112
+ const fail = (message, code = 1) => {
113
+ process.exitCode = code;
114
+ console.log(chalk.redBright(message));
115
+ };
116
+
117
+ const typed = flows.cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
118
+ if (typed.error) return fail(`poad source: ${typed.error}.`, 2);
119
+ const json = typed.words.includes('--json');
120
+ const words = typed.words.filter((w) => w !== '--json');
121
+ const command = words[0] || 'ls';
122
+ const cloud = Boolean(typed.env || typed.project);
123
+ const where = cloud ? ` ${[typed.env ? `--env ${typed.env}` : '', typed.project ? `--project ${typed.project}` : ''].filter(Boolean).join(' ')}` : '';
124
+
125
+ const root = findPoadDir(cwd);
126
+ 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.');
127
+
128
+ /** Engine visé, prêt à répondre, ou null (message affiché) */
129
+ const ready = async () => {
130
+ if (cloud) {
131
+ try {
132
+ const t = await cloudTarget({ env: typed.env, project: typed.project });
133
+ 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 };
134
+ } catch (err) {
135
+ return fail((err && err.message) || String(err), (err && err.exit) || 1) || null;
136
+ }
137
+ }
138
+ const config = readConfig(root);
139
+ if (!supportsSources(config)) return fail(`Sources need engine 0.64.0 or later (this project uses ${config.engine}): "poad upgrade".`) || null;
140
+ if (!(await started(config))) return fail('The project is not started: run "poad start".') || null;
141
+ const key = config.auth.service;
142
+ return { base: `http://localhost:${config.web.port}`, key, apikey: key, label: 'local engine', cloud: false };
143
+ };
144
+
145
+ /** Jeton poad.io renouvelé une minute avant son expiration */
146
+ const fresh = async (t) => {
147
+ if (!t.renew || !t.expires || t.expires - Date.now() > 60000) return;
148
+ const n = await t.renew.next();
149
+ Object.assign(t, { key: n.token, apikey: n.anon_key || t.apikey, expires: Date.parse(n.expires_at) });
150
+ };
151
+
152
+ class SourceError extends Error {}
153
+
154
+ /** Appel de l'engine (route complète : /meta/v1/…, /flows/v1/…) avec le jeton service_role */
155
+ const call = async (t, method, route, body) => {
156
+ try {
157
+ await fresh(t);
158
+ } catch (err) {
159
+ throw new SourceError(`poad.io gave no new access: ${(err && err.message) || err}`);
160
+ }
161
+ let res;
162
+ try {
163
+ res = await doFetch(`${t.base}${route}`, {
164
+ method,
165
+ headers: { apikey: t.apikey, authorization: `Bearer ${t.key}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
166
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
167
+ signal: AbortSignal.timeout(TIMEOUT_MS),
168
+ });
169
+ } catch (err) {
170
+ const timedOut = err && (err.name === 'TimeoutError' || err.name === 'AbortError');
171
+ const who = t.cloud ? t.label : 'The engine';
172
+ 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}`);
173
+ }
174
+ const data = await res.json().catch(() => null);
175
+ if (res.status >= 200 && res.status < 300) return data || {};
176
+ const error = data && typeof data === 'object' && data.error && typeof data.error === 'object' ? data.error : null;
177
+ if (error && error.message) throw new SourceError(`${error.message}${error.hint ? ` (${error.hint})` : ''}`);
178
+ // Fichier envoyé, échantillon, rapprochement : engine 0.65.0 ; le reste : 0.64.0
179
+ const needs = /\/sources\/(uploads|sample|propose|preview|tables)\b/.test(route) ? '0.65.0' : '0.64.0';
180
+ if (res.status === 404) throw new SourceError(`${t.cloud ? t.label : 'The engine'} has no ${needs === '0.65.0' ? 'such sources API' : 'sources API'} (HTTP 404): engine ${needs} or later is needed.`);
181
+ 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})`);
182
+ throw new SourceError(`HTTP ${res.status}`);
183
+ };
184
+
185
+ const guard = async (fn) => {
186
+ try {
187
+ return await fn();
188
+ } catch (err) {
189
+ if (!(err instanceof SourceError)) throw err;
190
+ fail(err.message);
191
+ return undefined;
192
+ }
193
+ };
194
+
195
+ /** Suit l'exécution d'une synchronisation lancée (started : réponse de /refresh ou de la création) jusqu'au bilan */
196
+ const followRun = async (t, name, started, force, wait) => {
197
+ const runId = started.run_id;
198
+ if (!runId) return fail('Source not refreshed: the engine gave no run id.');
199
+ if (!wait) {
200
+ console.log(runId);
201
+ if (process.stderr.isTTY) console.error(chalk.grey(` Follow it: poad flows show ${runId}${where}`));
202
+ return;
203
+ }
204
+ const drift = started.drift && Array.isArray(started.drift.issues) ? started.drift.issues : [];
205
+ console.log(`${chalk.bold(name)} ${chalk.grey(`flow ${started.flow}, run ${runId}${force ? ', --force' : ''}${cloud ? ` ${t.label}` : ''}`)}`);
206
+ for (const issue of drift.slice(0, 5)) console.log(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
207
+ const seen = new Map();
208
+ let misses = 0;
209
+ let view = null;
210
+ for (;;) {
211
+ try {
212
+ view = await call(t, 'GET', `/flows/v1/runs/${encodeURIComponent(runId)}`);
213
+ misses = 0;
214
+ } catch (err) {
215
+ if (!(err instanceof SourceError)) throw err;
216
+ if (++misses >= 5) {
217
+ fail(`Lost track of the run: ${err.message}`);
218
+ return console.log(chalk.grey(` It may still be running: poad flows show ${runId}${where}`));
219
+ }
220
+ await sleep(POLL_MS);
221
+ continue;
222
+ }
223
+ for (const step of view.steps || []) {
224
+ const key = flows.stepKey(step);
225
+ if (seen.get(step.step_id) === key) continue;
226
+ seen.set(step.step_id, key);
227
+ const line = flows.stepLine(step);
228
+ if (line) console.log(line);
229
+ }
230
+ if (FINAL.includes(view.status)) break;
231
+ await sleep(POLL_MS);
232
+ }
233
+ console.log(' ');
234
+ const took = view.duration_ms === null || view.duration_ms === undefined ? '' : chalk.grey(` in ${flows.duration(view.duration_ms)}`);
235
+ if (view.status === 'completed') {
236
+ console.log(`${chalk.greenBright('completed')}${took}`);
237
+ const report = reportOf(view);
238
+ if (report) for (const line of reportLines(report)) console.log(line);
239
+ const read = (view.steps || []).find((x) => x.step_id === 'lire');
240
+ const unread = read && read.output && read.output.problems && read.output.problems.count;
241
+ if (unread) console.log(chalk.yellowBright(` ${count(unread)} value(s) not converted while reading (kept as null): poad flows show ${runId}${where}`));
242
+ return;
243
+ }
244
+ process.exitCode = 1;
245
+ console.log(`${view.status === 'cancelled' ? chalk.yellowBright('cancelled') : chalk.redBright(view.status)}${took}`);
246
+ const failedStep = (view.steps || []).find((x) => x.status === 'failed');
247
+ const error = (failedStep && failedStep.error) || view.error;
248
+ if (error) console.log(chalk.redBright(` ${String(error).split('\n')[0].slice(0, 500)}`));
249
+ if (guardRefused(error) && !force) console.log(chalk.grey(` Nothing was changed. If the source is right: poad source refresh ${name} --force${where}`));
250
+ console.log(chalk.grey(` Details: poad flows show ${runId}${where} · poad logs source=${name}`));
251
+ return;
252
+ };
253
+
254
+ // ------------------------------------------------------------------ ls
255
+ if (command === 'ls' || command === 'list') {
256
+ if (words.length > 1) return fail(USAGE, 2);
257
+ const t = await ready();
258
+ if (!t) return;
259
+ const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
260
+ if (!list) return;
261
+ if (json) return console.log(JSON.stringify(list.sources || [], null, 2));
262
+ const all = list.sources || [];
263
+ console.log(`${chalk.bold('Sources')} ${chalk.grey(cloud ? t.label : 'poad/sources')}`);
264
+ console.log(' ');
265
+ if (!all.length) return console.log(chalk.grey(` None yet: declare one in poad/sources/<name>.yaml${cloud ? ', then "poad deploy"' : ''}.`));
266
+ const width = Math.max(...all.map((s) => String(s.name).length));
267
+ for (const s of all) for (const line of sourceLines(s, width)) console.log(line);
268
+ if (all.some((s) => !s.valid)) process.exitCode = 1;
269
+ return;
270
+ }
271
+
272
+ // ------------------------------------------------------------------ refresh
273
+ if (command === 'refresh' || command === 'sync') {
274
+ let name = null;
275
+ let force = false;
276
+ let wait = true;
277
+ for (const w of words.slice(1)) {
278
+ if (w === '--force') force = true;
279
+ else if (w === '--detach' || w === '--no-wait' || w === '-d') wait = false;
280
+ else if (w === '--wait') wait = true;
281
+ else if (w.startsWith('-')) return fail(`poad source refresh: unknown option ${w}.`, 2);
282
+ else if (name === null) name = w;
283
+ else return fail(`poad source refresh: one source at a time ("${w}").`, 2);
284
+ }
285
+ if (!name) return fail('Usage: poad source refresh <name> [--force] [--detach] [--env <name>] ("poad source ls" lists them).', 2);
286
+ 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);
287
+ const t = await ready();
288
+ if (!t) return;
289
+ const started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force }));
290
+ if (!started) return;
291
+ return followRun(t, name, started, force, wait);
292
+ }
293
+
294
+ // ------------------------------------------------------------------ import
295
+ // Un fichier (CSV, JSON, GeoJSON, JSONL, gzip accepté) chargé dans une table, par une source « Fichier envoyé » :
296
+ // envoyé dans le bucket système poad-sources, lu en flux par le flow de la source (aucune limite de taille).
297
+ // Nouvelle source : échantillon lu par l'engine, nouvelle table (ou --existing), déclaration écrite, chargement.
298
+ // Source déjà envoyée (--name, ou le nom tiré du fichier) : nouvelle version au même chemin, puis chargement.
299
+ if (command === 'import') {
300
+ const opts = { file: null, name: null, table: null, key: null, format: null, root: null, existing: false, wait: true };
301
+ const rest = words.slice(1);
302
+ for (let i = 0; i < rest.length; i++) {
303
+ const w = rest[i];
304
+ const value = () => {
305
+ const v = rest[++i];
306
+ if (v === undefined || v.startsWith('--')) throw new SourceError(`poad source import: ${w} needs a value.`);
307
+ return v;
308
+ };
309
+ try {
310
+ if (w === '--name') opts.name = value();
311
+ else if (w === '--table') opts.table = value().replace(/^public\./, '');
312
+ else if (w === '--key') opts.key = value().split(',').map((x) => x.trim()).filter(Boolean);
313
+ else if (w === '--format') opts.format = value();
314
+ else if (w === '--root') opts.root = value();
315
+ else if (w === '--existing') opts.existing = true;
316
+ else if (w === '--detach' || w === '-d') opts.wait = false;
317
+ else if (w.startsWith('-')) return fail(`poad source import: unknown option ${w}.`, 2);
318
+ else if (opts.file === null) opts.file = w;
319
+ else return fail(`poad source import: one file at a time ("${w}").`, 2);
320
+ } catch (err) {
321
+ return fail(err.message, 2);
322
+ }
323
+ }
324
+ const usage = 'Usage: poad source import <file> [--table <table>] [--name <source>] [--key <col,…>] [--existing] [--format csv|json|geojson|jsonl] [--root <path>] [--detach] [--env <name>]';
325
+ if (!opts.file) return fail(usage, 2);
326
+ const file = path.resolve(cwd, opts.file);
327
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return fail(`${opts.file}: no such file.`);
328
+ if (opts.format && !['csv', 'json', 'geojson', 'jsonl'].includes(opts.format)) return fail(`--format: csv, json, geojson or jsonl (got "${opts.format}").`, 2);
329
+ if (opts.existing && !opts.table) return fail('--existing needs --table <table> (the table of the project to load).', 2);
330
+ const base = path.basename(file).replace(/\.gz$/i, '').replace(/\.[a-z0-9]+$/i, '');
331
+ const { cleanIdent } = require('../utils/naming');
332
+ // Nouvelle table : nom nettoyé (accents, espaces, chiffre en tête…) ; table existante : telle quelle
333
+ const table = opts.existing ? String(opts.table).replace(/^public\./, '') : cleanIdent(String(opts.table || base).replace(/^public\./, ''), 'table');
334
+ if (opts.table && !opts.existing && table !== String(opts.table).replace(/^public\./, '')) console.log(chalk.grey(` table name cleaned: "${opts.table}" → ${table}`));
335
+ const t = await ready();
336
+ if (!t) return;
337
+ const size = fs.statSync(file).size;
338
+ const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
339
+ if (!list) return;
340
+ // Le nom d'une source est celui de sa table (engine 0.65.0). --name reste accepté : une source existante de ce
341
+ // nom (même d'avant 0.65.0) reçoit une nouvelle version ; sinon il est ignoré s'il diffère de la table.
342
+ const byName = (n) => (list.sources || []).find((x) => x.name === n);
343
+ let name = table;
344
+ if (opts.name && byName(opts.name)) name = opts.name;
345
+ else if (opts.name && opts.name !== table) console.log(chalk.yellowBright(` --name ${opts.name} ignored: a source is named after its table (${table}).`));
346
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name: --table <table> (a-z, 0-9 and "_").`, 2);
347
+ const known = byName(name);
348
+ if (known && !(known.origin && known.origin.kind === 'upload')) return fail(`The source "${name}" reads an address: "poad source refresh ${name}" reloads it (or --table <another table>).`);
349
+ const target = await guard(() => call(t, 'POST', '/meta/v1/sources/uploads', known ? { source: name, size, file_name: path.basename(file) } : { file_name: path.basename(file), size, kind: 'source' }));
350
+ if (!target) return;
351
+ const { uploadImportFile, progressLine } = deps.upload || require('../utils/import-upload');
352
+ const bar = progressLine(path.basename(file));
353
+ const startedAt = Date.now();
354
+ let sent;
355
+ try {
356
+ sent = await uploadImportFile({ base: t.base, file, target, onProgress: bar.update, fetch: doFetch, auth: async () => (await fresh(t), { apikey: t.apikey, authorization: `Bearer ${t.key}` }) });
357
+ } catch (err) {
358
+ bar.done();
359
+ return fail(`Upload failed: ${(err && err.message) || err}`);
360
+ } finally {
361
+ bar.done();
362
+ }
363
+ console.log(`${chalk.greenBright('✔')} ${path.basename(file)} ${chalk.grey(`${(size / 1048576).toFixed(1)} MB sent in ${((Date.now() - startedAt) / 1000).toFixed(1)} s (${sent.method === 'tus' ? 'resumable' : 'simple'} upload) → ${target.path}`)}`);
364
+ let started;
365
+ if (known) {
366
+ // Nouvelle version : même chemin, la déclaration ne change pas
367
+ started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force: false }));
368
+ } else {
369
+ const sample = await guard(() => call(t, 'POST', '/meta/v1/sources/sample', { path: target.path, ...(opts.format ? { format: opts.format } : {}), ...(opts.root ? { root: opts.root } : {}) }));
370
+ if (!sample) return;
371
+ console.log(chalk.grey(` ${sample.format}${sample.gzip ? ' (gzip)' : ''}, ${(sample.fields || []).length} field(s): ${(sample.fields || []).map((f) => `${f.path} ${f.type}`).slice(0, 12).join(', ')}${(sample.fields || []).length > 12 ? '…' : ''}`));
372
+ const proposal = await guard(() => call(t, 'POST', '/meta/v1/sources/propose', { fields: sample.fields, format: sample.format, path: target.path, table, ...(opts.existing ? { existing: true, name } : {}) }));
373
+ if (!proposal) return;
374
+ let columns;
375
+ let key;
376
+ if (opts.existing) {
377
+ const blocking = (proposal.problems || []).filter((p) => p.level === 'error');
378
+ if (blocking.length) return fail(`public.${table} cannot take this file: ${blocking.map((p) => p.message).join(' ; ')}`);
379
+ columns = (proposal.matches || []).filter((m) => m.field).map((m) => ({ name: m.column, from: m.field, ...(m.transform ? { transform: m.transform } : {}) }));
380
+ key = opts.key || proposal.key || [];
381
+ } else {
382
+ if (proposal.table_exists) return fail(`public.${table} already exists: --table <another name>, or --existing to load into it.`);
383
+ columns = (proposal.columns || []).filter((c) => c.include !== false).map((c) => ({ name: c.name, from: c.from, type: c.type, ...(c.transform ? { transform: c.transform } : {}) }));
384
+ key = opts.key || proposal.key || [];
385
+ }
386
+ if (!key.length) return fail(`No key found for public.${table}: --key <column> (a column whose values are unique).`, 2);
387
+ const draft = {
388
+ mode: 'imported',
389
+ origin: { kind: 'upload', path: target.path, format: sample.format, ...(sample.root ? { root: sample.root } : {}), ...(sample.format === 'csv' && sample.csv ? { csv: { delimiter: sample.csv.delimiter, ...(sample.csv.encoding ? { encoding: sample.csv.encoding } : {}) } } : {}) },
390
+ table: `public.${table}`,
391
+ existing: opts.existing,
392
+ key,
393
+ columns,
394
+ };
395
+ const created = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft, run: true, ...(opts.existing ? { confirm: { existing: true } } : {}) }));
396
+ if (!created) return;
397
+ if (created.name) name = created.name;
398
+ for (const w of created.warnings || []) console.log(chalk.yellowBright(` ${w}`));
399
+ console.log(`${chalk.greenBright('✔')} source ${chalk.bold(name)} ${chalk.grey(`${created.file || 'created in the console'} → public.${table}, key ${key.join(', ')}`)}`);
400
+ started = created.run_id ? { run_id: created.run_id, flow: `source-${name.replace(/_/g, '-')}` } : null;
401
+ if (!started) return fail('The source was declared but no load was started: poad source refresh ' + name + where);
402
+ }
403
+ if (!started) return;
404
+ return followRun(t, name, started, false, opts.wait);
405
+ }
406
+
407
+ // ------------------------------------------------------------------ pull
408
+ // La déclaration d'une source (créée dans la console hébergée, gardée en base) écrite dans poad/sources :
409
+ // le fichier fait foi ensuite (poad deploy l'envoie ; sur poad.io, un fichier déployé l'emporte).
410
+ if (command === 'pull') {
411
+ let name = null;
412
+ let force = false;
413
+ let toStdout = false;
414
+ for (const w of words.slice(1)) {
415
+ if (w === '--force' || w === '-f') force = true;
416
+ else if (w === '--stdout') toStdout = true;
417
+ else if (w.startsWith('-')) return fail(`poad source pull: unknown option ${w}.`, 2);
418
+ else if (name === null) name = w;
419
+ else return fail(`poad source pull: one source at a time ("${w}").`, 2);
420
+ }
421
+ if (!name) return fail('Usage: poad source pull <name> [--force] [--stdout] --env <name> ("poad source ls --env <name>" lists them).', 2);
422
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name (the name of its table: a-z, 0-9 and "_"; or, before engine 0.65.0, a-z, 0-9 and "-").`, 2);
423
+ if (!root && !toStdout) return fail('Not in a poad project folder: cd into one, or pass --stdout.');
424
+ const target = root ? path.join(path.dirname(root), 'sources', `${name}.yaml`) : null;
425
+ if (target && !toStdout && !force && (fs.existsSync(target) || fs.existsSync(target.replace(/\.yaml$/, '.yml'))))
426
+ return fail(`poad/sources/${name}.yaml already exists: --force replaces it (check "git diff" afterwards), or --stdout prints the declaration.`);
427
+ const t = await ready();
428
+ if (!t) return;
429
+ const got = await guard(() => call(t, 'GET', `/meta/v1/sources/${encodeURIComponent(name)}/yaml`));
430
+ if (!got) return;
431
+ if (typeof got.yaml !== 'string' || !got.yaml.trim()) return fail('The engine gave no declaration.');
432
+ if (toStdout) return process.stdout.write(got.yaml.endsWith('\n') ? got.yaml : `${got.yaml}\n`);
433
+ fs.mkdirSync(path.dirname(target), { recursive: true });
434
+ fs.writeFileSync(target, got.yaml.endsWith('\n') ? got.yaml : `${got.yaml}\n`);
435
+ console.log(`${chalk.greenBright('✔')} poad/sources/${name}.yaml ${chalk.grey(`from ${cloud ? t.label : 'the local engine'}${got.stored === 'console' ? ', created in the console' : ''}`)}`);
436
+ if (got.stored === 'console' && cloud) console.log(chalk.grey(` Commit it, then "poad deploy${where}": the deployed file then wins over the console copy.`));
437
+ return;
438
+ }
439
+
440
+ fail(USAGE, 2);
441
+ };
442
+
443
+ module.exports = (args, raw) => main(args, raw);
444
+ Object.assign(module.exports, { main, supportsSources, sourceLines, reportOf, reportLines, guardRefused, age, NAME_RE });
@@ -0,0 +1,2 @@
1
+ // poad sources … : alias de poad source …
2
+ module.exports = require('./source');
@@ -1,41 +1,73 @@
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
- module.exports = (args, raw) =>
7
- require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, ({ opts, positionals, out }) => copy({ opts, positionals, out, move: false }));
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
- /** Partagé avec mv (move : sources supprimées une fois copiées, Stockage seulement) */
10
- async function copy({ opts, positionals, out, move }) {
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 api = s.client(await s.target(opts));
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 });
32
+ // Gros fichiers : en morceaux reprenables (storage 0.6.0+) ; une reprise est dite
33
+ for (const it of items) it.onResume = (offset) => out.log(chalk.grey(` ↻ ${c.label(it.from)}: resuming at ${s.size(offset)} of ${s.size(it.size)}`));
19
34
  const r = await c.run(api, items, {
20
- onDone: (it) => out.log(` ${chalk.greenBright('✔')} ${c.label(it.from)} ${chalk.grey('→')} ${c.label(it.to)} ${chalk.grey(s.size(it.size))}`),
35
+ concurrency,
36
+ onDone: (it) => out.log(` ${chalk.greenBright('✔')} ${c.label(it.from)} ${chalk.grey('→')} ${c.label(it.to)} ${chalk.grey(`${s.size(it.size)}${it.chunked ? ', in chunks' : ''}${it.resumedFrom ? `, resumed at ${s.size(it.resumedFrom)}` : ''}`)}`),
37
+ onError: (it, e) => out.log(chalk.redBright(` ✖ ${c.label(it.from)} → ${c.label(it.to)}: ${s.reason(e)}`)),
21
38
  });
22
39
  let deleted = [];
23
- if (move && r.done.length) {
24
- // Seules les sources bien copiées sont supprimées
40
+ // Seules les sources bien copiées (ou déjà identiques à la destination) sont supprimées
41
+ const moved = [...r.done, ...r.unchanged];
42
+ if (move && moved.length) {
25
43
  const byBucket = new Map();
26
- for (const it of r.done) byBucket.set(it.from.bucket, [...(byBucket.get(it.from.bucket) || []), it.from.key]);
44
+ for (const it of moved) byBucket.set(it.from.bucket, [...(byBucket.get(it.from.bucket) || []), it.from.key]);
27
45
  for (const [bucket, keys] of byBucket)
28
46
  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
47
  }
30
- for (const e of r.errors) out.log(chalk.redBright(` ✖ ${c.label(e.item.from)} → ${c.label(e.item.to)}: ${e.error.message}`));
48
+ const failures = c.failures(r.errors);
31
49
  const n = r.done.length;
32
- out.log(chalk.grey(` ${n} file${n === 1 ? '' : 's'} ${move ? 'moved' : 'copied'}, ${s.size(r.bytes)}${r.errors.length ? `, ${r.errors.length} failed${move ? ' (left in place)' : ''}` : ''}`));
50
+ const same = r.unchanged.length;
51
+ out.log(
52
+ chalk.grey(
53
+ ` ${n} file${n === 1 ? '' : 's'} ${move ? 'moved' : 'copied'}, ${s.size(r.bytes)}` +
54
+ `${same ? `, ${same} already identical at the destination${move ? ' (source deleted)' : ''}` : ''}` +
55
+ `${failures.length ? `, ${failures.length} failed${move ? ' (left in place)' : ''}` : ''}`,
56
+ ),
57
+ );
58
+ printFailures(out, failures);
59
+ const row = (it) => ({ from: c.label(it.from), to: c.label(it.to), size: it.size, ...(it.chunked ? { chunked: true } : {}), ...(it.resumedFrom ? { resumed_from: it.resumedFrom } : {}) });
33
60
  out.result({
34
- [move ? 'moved' : 'copied']: r.done.map((it) => ({ from: c.label(it.from), to: c.label(it.to), size: it.size })),
61
+ [move ? 'moved' : 'copied']: r.done.map(row),
62
+ unchanged: r.unchanged.map(row),
35
63
  ...(move ? { deleted } : {}),
36
- failed: r.errors.map((e) => ({ from: c.label(e.item.from), to: c.label(e.item.to), error: e.error.message })),
64
+ failures,
65
+ // Ancien nom, gardé pour les scripts existants
66
+ failed: r.errors.map((e) => ({ from: c.label(e.item.from), to: c.label(e.item.to), error: s.reason(e.error) })),
37
67
  });
38
- return r.errors.length ? 1 : 0;
68
+ return failures.length ? 1 : 0;
39
69
  }
40
70
 
41
71
  module.exports.copy = copy;
72
+ module.exports.SPEC = SPEC;
73
+ module.exports.printFailures = printFailures;
@@ -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
- let list;
28
- if (exact) list = [{ kind: 'file', name: exact.name, size: Number(exact.metadata && exact.metadata.size) || 0, updated: exact.updated_at, type: exact.metadata && exact.metadata.mimetype }];
29
- 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 }));
30
- else list = s.entries(rows, prefix);
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) {
@@ -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
- require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, ({ opts, positionals, out }) =>
6
- require('./cp').copy({ opts, positionals, out, move: true }),
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
+ };