poad 2.76.0 → 2.76.2
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/package.json +1 -1
- package/project/deploy.js +23 -8
- package/project/migrate.js +1 -1
- package/project/ref/index.js +2 -2
- package/project/ref/load.js +58 -18
- package/project/ref/ls.js +14 -4
- package/project/upgrade.js +1 -1
- package/test/api-exposure.test.js +40 -0
- package/test/fake-storage.js +150 -0
- package/test/project-sync.test.js +126 -10
- package/test/push-resume.test.js +179 -0
- package/test/reference-reload.test.js +94 -4
- package/utils/api-exposure/api-exposure.sql +11 -2
- package/utils/api-exposure/index.js +33 -11
- package/utils/help-details.js +13 -6
- package/utils/migrate-run.js +1 -1
- package/utils/project-sync/plan.js +55 -0
- package/utils/project-sync/run.js +216 -62
- package/utils/reference-store.js +93 -23
- package/utils/reference.js +87 -4
- package/utils/seed/apply.js +68 -4
- package/utils/seed/run.js +62 -2
- package/utils/storage-sync.js +164 -24
- package/utils/storage-tus.js +40 -4
- package/utils/storage.js +69 -19
|
@@ -18,7 +18,7 @@ const fs = require('fs');
|
|
|
18
18
|
const path = require('path');
|
|
19
19
|
const { randomUUID } = require('crypto');
|
|
20
20
|
|
|
21
|
-
const SPEC = { values: ['env', 'project', 'only', 'skip', 'tables', 'confirm'], flags: ['dry-run', 'with-secrets', 'allow-destructive', 'accept-data-loss'], alias: { n: 'dry-run' } };
|
|
21
|
+
const SPEC = { values: ['env', 'project', 'only', 'skip', 'tables', 'confirm'], flags: ['dry-run', 'with-secrets', 'allow-destructive', 'accept-data-loss', 'clean'], alias: { n: 'dry-run' } };
|
|
22
22
|
|
|
23
23
|
/** Relance le CLI lui-même (poad deploy, poad migration pull, poad migrate) ; json : sortie analysée */
|
|
24
24
|
function self(args, { json = false, inherit = false } = {}) {
|
|
@@ -76,7 +76,7 @@ function run(direction, raw, deps = {}) {
|
|
|
76
76
|
const push = direction === 'push';
|
|
77
77
|
const event = push ? 'project_push' : 'project_pull';
|
|
78
78
|
const dry = Boolean(opts['dry-run']) || positionals[0] === 'status';
|
|
79
|
-
if (positionals.length && !(positionals.length === 1 && positionals[0] === 'status')) throw api.usageError(`poad ${direction}: unexpected "${positionals[0]}". Usage: poad ${direction} [--env <name>] [--dry-run] [--only code,base,auth,s3,refs] [--skip …] [--tables a,b] [--with-secrets] [--yes] [--json]`);
|
|
79
|
+
if (positionals.length && !(positionals.length === 1 && positionals[0] === 'status')) throw api.usageError(`poad ${direction}: unexpected "${positionals[0]}". Usage: poad ${direction} [--env <name>] [--dry-run] [--only code,base,auth,s3,refs] [--skip …] [--tables a,b] [--with-secrets] [--clean] [--yes] [--json]`);
|
|
80
80
|
|
|
81
81
|
let sel;
|
|
82
82
|
try {
|
|
@@ -108,7 +108,8 @@ function run(direction, raw, deps = {}) {
|
|
|
108
108
|
const head = `${push ? 'Push' : 'Pull'}${dry ? ' (dry run)' : ''}`;
|
|
109
109
|
const arrow = push ? `local → ${env.production ? chalk.magenta.bold(cloudLabel) : chalk.cyan.bold(cloudLabel)}` : `${env.production ? chalk.magenta.bold(cloudLabel) : chalk.cyan.bold(cloudLabel)} → local`;
|
|
110
110
|
out.log(` ${chalk.bold(head)} ${arrow}${chalk.grey(env.source === 'git' ? ' (git branch)' : env.source === 'default' && env.git ? ` (git branch ${env.git} not on poad.io)` : '')}`);
|
|
111
|
-
|
|
111
|
+
const clean = Boolean(opts.clean);
|
|
112
|
+
out.log(chalk.grey(` parts: ${sel.parts.join(', ')}${sel.tables ? ` tables: ${sel.tables.join(', ')}` : ''}${clean ? ' --clean: what is replaced is emptied first' : ''}`));
|
|
112
113
|
|
|
113
114
|
// --- Aperçu (rien ne change) -------------------------------------------------------------------
|
|
114
115
|
const preview = { code: null, base: null, auth: null, refs: null, s3: null, secrets: null, space: null };
|
|
@@ -131,7 +132,8 @@ function run(direction, raw, deps = {}) {
|
|
|
131
132
|
let registry = null;
|
|
132
133
|
if (has('refs') || has('base')) {
|
|
133
134
|
try {
|
|
134
|
-
|
|
135
|
+
// Poussée : poad.io lit l'état réel dans la base de l'environnement (marque posée au chargement, lignes)
|
|
136
|
+
registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds?verify=${push ? encodeURIComponent(env.branch) : '0'}`, { what: 'references' });
|
|
135
137
|
} catch (e) {
|
|
136
138
|
registry = null;
|
|
137
139
|
if (has('refs')) out.log(chalk.yellowBright(` ⚠ reference store not readable (${e.message}): refs left out.`));
|
|
@@ -147,7 +149,7 @@ function run(direction, raw, deps = {}) {
|
|
|
147
149
|
if (has('auth')) preview.auth = await authPreview(pg, P, container, src, dst, inv);
|
|
148
150
|
|
|
149
151
|
// Références
|
|
150
|
-
if (has('refs') && registry) preview.refs = refsPreview(registry, env, poadDir, push, has('code'));
|
|
152
|
+
if (has('refs') && registry) preview.refs = await refsPreview(registry, env, poadDir, push, has('code'), push ? null : container);
|
|
151
153
|
|
|
152
154
|
// Fichiers du Stockage
|
|
153
155
|
let storage = null;
|
|
@@ -159,16 +161,16 @@ function run(direction, raw, deps = {}) {
|
|
|
159
161
|
// Secrets : des noms seulement
|
|
160
162
|
if (has('secrets')) preview.secrets = { variables: inv.src.variables, credentials: inv.src.credentials, target_variables: inv.dst.variables, target_credentials: inv.dst.credentials, target_storage: inv.dst.storage_credentials };
|
|
161
163
|
|
|
162
|
-
// Place sur la cible : ce qui sera
|
|
163
|
-
const
|
|
164
|
-
if (need > 0) preview.space = await spaceCheck(id, env, poadDir, push,
|
|
164
|
+
// Place sur la cible : ce qui sera écrit (base et comptes, fichiers) et ce qui sera libéré
|
|
165
|
+
const amounts = spaceAmounts(preview, { clean });
|
|
166
|
+
if (amounts.need.base + amounts.need.files > 0) preview.space = await spaceCheck(id, env, poadDir, push, amounts, P);
|
|
165
167
|
|
|
166
168
|
printPreview(out, P, preview, { push, env, cloudLabel, sel });
|
|
167
169
|
|
|
168
170
|
const blocking = [];
|
|
169
171
|
if (preview.code && push && (preview.code.error || (preview.code.errors || []).length)) blocking.push(`code: poad deploy would be refused (${preview.code.error || preview.code.errors[0]})`);
|
|
170
172
|
if (preview.base && preview.base.blocked.length && !(preview.code && preview.code.structure)) blocking.push('base: the structure of the target differs (see above)');
|
|
171
|
-
if (preview.space && preview.space.known && !preview.space.ok) blocking.push(
|
|
173
|
+
if (preview.space && preview.space.known && !preview.space.ok) blocking.push(`not enough room on the target (${P.size(preview.space.missing)} missing${!clean && spaceAmounts(preview, { clean: true }).freed.base > 0 ? '; --clean would empty the tables to rewrite first' : ''})`);
|
|
172
174
|
if (preview.base && preview.base.unknown.length) blocking.push(`--tables: ${preview.base.unknown.join(', ')} not in the source`);
|
|
173
175
|
const nothing = isNothing(preview, sel);
|
|
174
176
|
|
|
@@ -194,7 +196,7 @@ function run(direction, raw, deps = {}) {
|
|
|
194
196
|
// --- Confirmations -------------------------------------------------------------------------------
|
|
195
197
|
const target = push ? cloudLabel : 'the local project';
|
|
196
198
|
if (push && env.production) await strongConfirm(id, env, opts, out);
|
|
197
|
-
else await cli.confirm(`Make ${target} the mirror of ${push ? 'the local project' : cloudLabel} for ${sel.parts.filter((p) => p !== 'secrets').join(', ')}? What the target has of its own in these parts is replaced
|
|
199
|
+
else await cli.confirm(`Make ${target} the mirror of ${push ? 'the local project' : cloudLabel} for ${sel.parts.filter((p) => p !== 'secrets').join(', ')}? What the target has of its own in these parts is replaced.${clean ? ' --clean: the tables and files to replace are emptied FIRST, outside the transaction (a failure leaves them empty until the next run).' : ''}`, { yes: opts.yes, json: out.json });
|
|
198
200
|
if (has('secrets')) {
|
|
199
201
|
const s = preview.secrets;
|
|
200
202
|
await cli.confirm(`Also copy the values of ${s.variables.length} variable(s) and ${s.credentials.length} credential(s)${s.credentials.length ? ` (${s.credentials.slice(0, 8).join(', ')})` : ''} to ${target}? Values are never shown nor logged.`, { yes: opts.yes, json: out.json });
|
|
@@ -202,7 +204,9 @@ function run(direction, raw, deps = {}) {
|
|
|
202
204
|
|
|
203
205
|
// --- Sauvegarde -----------------------------------------------------------------------------------
|
|
204
206
|
let backup = null;
|
|
205
|
-
|
|
207
|
+
// Seulement si la base va vraiment être écrite : une poussée relancée qui n'a plus que des fichiers à
|
|
208
|
+
// envoyer ne refait pas de sauvegarde de la production
|
|
209
|
+
const writesDb = dbWrites(preview, sel, push);
|
|
206
210
|
if (push && env.production && writesDb) {
|
|
207
211
|
const t0 = Date.now();
|
|
208
212
|
try {
|
|
@@ -263,7 +267,20 @@ function run(direction, raw, deps = {}) {
|
|
|
263
267
|
stop('base', 'the structure of the target differs');
|
|
264
268
|
note({ part: 'base', outcome: 'refused', duration_ms: 0 });
|
|
265
269
|
} else {
|
|
266
|
-
|
|
270
|
+
let r = null;
|
|
271
|
+
if (clean && base && base.rewrite.length) {
|
|
272
|
+
const t0 = Date.now();
|
|
273
|
+
try {
|
|
274
|
+
await pg.query(container, dst, P.truncateSql(base.rewrite));
|
|
275
|
+
note({ part: 'base', outcome: 'done', rows: base.rewrite.length, bytes: base.rewrite.reduce((x, t) => x + ((t.target && t.target.bytes) || 0), 0), duration_ms: Date.now() - t0, step: 'clean' });
|
|
276
|
+
out.log(`${chalk.greenBright('✔')} --clean: ${base.rewrite.length} table(s) emptied on the target ${chalk.grey(`(${P.size(base.rewrite.reduce((x, t) => x + ((t.target && t.target.bytes) || 0), 0))} freed)`)}`);
|
|
277
|
+
} catch (e) {
|
|
278
|
+
note({ part: 'base', outcome: 'failed', duration_ms: Date.now() - t0, step: 'clean' });
|
|
279
|
+
out.log(chalk.redBright(` ✕ --clean: the tables could not be emptied, nothing changed (${e.message})`));
|
|
280
|
+
r = { ok: false, lines: [], tables: [], error: `--clean: ${e.message}` };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (!r) r = await transferData(pg, P, container, src, dst, { base, auth, inv, sel, out });
|
|
267
284
|
for (const l of r.lines) note(l);
|
|
268
285
|
if (has('base')) results.base = { outcome: r.ok ? 'done' : 'failed', tables: r.tables.filter((t) => t.part === 'base'), error: r.ok ? undefined : r.error };
|
|
269
286
|
if (has('auth')) results.auth = { outcome: r.ok ? 'done' : 'failed', tables: r.tables.filter((t) => t.part === 'auth'), error: r.ok ? undefined : r.error };
|
|
@@ -286,8 +303,9 @@ function run(direction, raw, deps = {}) {
|
|
|
286
303
|
|
|
287
304
|
if (!failed && has('s3') && preview.s3 && preview.s3.todo) {
|
|
288
305
|
const t0 = Date.now();
|
|
289
|
-
const r = await storagePlan(storage, false, out);
|
|
306
|
+
const r = await storagePlan(storage, false, out, { clean, concurrency: deps.concurrency, sleep: deps.sleep });
|
|
290
307
|
results.s3 = r;
|
|
308
|
+
for (const l of fileLines(r)) note(l);
|
|
291
309
|
note({ part: 's3', rows: r.totals.added + r.totals.updated + r.totals.removed, bytes: r.totals.bytes, outcome: r.totals.failed ? 'failed' : 'done', duration_ms: Date.now() - t0 });
|
|
292
310
|
if (r.totals.failed) stop('s3', `${r.totals.failed} file(s) failed`);
|
|
293
311
|
}
|
|
@@ -307,6 +325,7 @@ function run(direction, raw, deps = {}) {
|
|
|
307
325
|
await flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction });
|
|
308
326
|
|
|
309
327
|
out.log(' ');
|
|
328
|
+
if (results.s3 && results.s3.totals.failed) printFailures(out, results.s3, { direction, env, opts });
|
|
310
329
|
if (failed) out.log(chalk.redBright(` ${push ? 'Push' : 'Pull'} stopped: ${Object.entries(results).filter(([, r]) => r && r.outcome === 'failed').map(([p, r]) => `${p} (${r.error})`).join(', ')}.`));
|
|
311
330
|
else out.log(`${chalk.greenBright('✔')} ${push ? `Pushed to ${env.branch}` : `Pulled from ${env.branch}`} in ${((Date.now() - started) / 1000).toFixed(1)} s.`);
|
|
312
331
|
out.log(chalk.grey(` Logs: poad logs cli event=${event}${push ? ` (and --env ${env.branch} on poad.io)` : ''}`));
|
|
@@ -488,27 +507,37 @@ async function transferData(pg, P, container, src, dst, { base, auth, inv, sel,
|
|
|
488
507
|
|
|
489
508
|
// --- Références -------------------------------------------------------------------------------------------
|
|
490
509
|
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
}
|
|
498
|
-
};
|
|
499
|
-
|
|
500
|
-
function refsPreview(registry, env, poadDir, push, withCode) {
|
|
510
|
+
/**
|
|
511
|
+
* Ce qui attend chaque table de référence de l'autre côté, lu dans SA base (marque posée au chargement, lignes) :
|
|
512
|
+
* tables: [{ target, action: loaded | load | send, state, rows, sha256, … }] ; load : celles à charger hors gros
|
|
513
|
+
* fichiers du dossier (ceux-là passent par l'envoi au magasin, ou par poad deploy avec la partie code).
|
|
514
|
+
*/
|
|
515
|
+
async function refsPreview(registry, env, poadDir, push, withCode, container) {
|
|
501
516
|
const items = Array.isArray(registry.items) ? registry.items : [];
|
|
517
|
+
const refStore = require('../reference-store');
|
|
502
518
|
if (push) {
|
|
503
|
-
const refStore = require('../reference-store');
|
|
504
519
|
const large = refStore.largeFiles(poadDir);
|
|
505
|
-
const
|
|
506
|
-
const
|
|
507
|
-
|
|
520
|
+
const planned = refStore.plan(registry, env.branch, poadDir, large);
|
|
521
|
+
const others = items.filter((s) => !large.some((f) => f.target === s.target)).map((s) => {
|
|
522
|
+
const st = refStore.cloudState(registry, env.branch, s.target, s.sha256);
|
|
523
|
+
return { target: s.target, action: st.state === 'loaded' ? 'loaded' : 'load', state: st.state, rows: st.rows, mark_rows: st.mark_rows, sha256: st.sha256 || s.sha256, expected_rows: s.rows, checked: st.checked };
|
|
524
|
+
});
|
|
525
|
+
const tables = [...planned, ...others];
|
|
526
|
+
const load = others.filter((t) => t.action === 'load').map((t) => t.target);
|
|
527
|
+
return { store: Boolean(registry.store), large: large.map((f) => ({ rel: f.rel, target: f.target, bytes: f.size })), large_by_code: withCode, tables, load, todo: tables.some((t) => t.action !== 'loaded') };
|
|
508
528
|
}
|
|
509
|
-
|
|
510
|
-
const
|
|
511
|
-
|
|
529
|
+
// Tirer : l'état de la base locale ; une base remise à zéro ou une table vidée redeviennent « à charger »
|
|
530
|
+
const S = require('../seed/run');
|
|
531
|
+
const A = require('../seed/apply');
|
|
532
|
+
const st = container ? await S.localState(container, items.map((s) => s.target)) : null;
|
|
533
|
+
const tables = items.map((s) => {
|
|
534
|
+
const raw = st ? st[s.target] : null;
|
|
535
|
+
const state = st ? A.referenceState(s.sha256, raw) : 'unknown';
|
|
536
|
+
return { target: s.target, sha256: s.sha256, rows: raw ? raw.rows : null, mark_rows: raw ? raw.mark_rows : null, expected_rows: s.rows, state, action: state === 'loaded' ? 'loaded' : 'load' };
|
|
537
|
+
});
|
|
538
|
+
if (container && st) await S.localLog(container, tables.map((t) => ({ msg: `reference ${t.target}: ${t.state}`, attrs: { event: 'reference_state', table: t.target, state: t.state, rows: t.rows, mark_rows: t.mark_rows, sha256: t.sha256.slice(0, 12), env: 'local', via: 'poad pull' } })));
|
|
539
|
+
const load = tables.filter((t) => t.action === 'load' && t.state !== 'no_table').map((t) => ({ target: t.target, sha256: t.sha256, rows: t.expected_rows }));
|
|
540
|
+
return { store: Boolean(registry.store), tables, load, todo: load.length > 0 };
|
|
512
541
|
}
|
|
513
542
|
|
|
514
543
|
async function refsApply(id, env, poadDir, plan, push, opts, out, config, withCode) {
|
|
@@ -533,16 +562,12 @@ async function refsApply(id, env, poadDir, plan, push, opts, out, config, withCo
|
|
|
533
562
|
const S = require('../seed/run');
|
|
534
563
|
const A = require('../seed/apply');
|
|
535
564
|
const order = A.loadOrder(plan.load.map((s) => s.target), await S.localEdges(config.project_uuid));
|
|
536
|
-
const loaded = readJson(localRefsFile(poadDir));
|
|
537
565
|
const tables = [];
|
|
538
566
|
for (const target of order) {
|
|
539
567
|
const t0 = Date.now();
|
|
540
568
|
const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `reference ${target}` });
|
|
569
|
+
// La marque (empreinte, lignes) est posée dans la base locale, dans la transaction du chargement
|
|
541
570
|
const r = await S.loadLocal(config.project_uuid, d);
|
|
542
|
-
const s = plan.load.find((x) => x.target === target);
|
|
543
|
-
loaded[target] = s.sha256;
|
|
544
|
-
fs.mkdirSync(path.dirname(localRefsFile(poadDir)), { recursive: true });
|
|
545
|
-
fs.writeFileSync(localRefsFile(poadDir), JSON.stringify(loaded, null, 2) + '\n');
|
|
546
571
|
out.log(`${out.chalk.greenBright('✔')} ${target} loaded locally: ${n(r.written)} rows written, ${n(r.deleted)} removed`);
|
|
547
572
|
tables.push({ target, rows: r.written, outcome: 'done', duration_ms: Date.now() - t0 });
|
|
548
573
|
}
|
|
@@ -559,49 +584,152 @@ async function storageSides(env, opts, push, deps) {
|
|
|
559
584
|
return { fromT, toT, from: (deps.client || s.client)(fromT), to: (deps.client || s.client)(toT) };
|
|
560
585
|
}
|
|
561
586
|
|
|
562
|
-
async function storagePlan(st, dryRun, out) {
|
|
587
|
+
async function storagePlan(st, dryRun, out, { clean = false, concurrency = 4, sleep } = {}) {
|
|
563
588
|
const ss = require('../storage-sync');
|
|
564
589
|
const s = require('../storage');
|
|
590
|
+
const P = require('./plan');
|
|
591
|
+
const live = { failed: 0, retried: 0, shownRetries: 0 };
|
|
592
|
+
const resumes = [];
|
|
593
|
+
const say = (line) => out && !out.json && out.log(line);
|
|
565
594
|
const r = await ss.sync(st.from, st.to, {
|
|
566
595
|
prune: true,
|
|
567
596
|
dryRun,
|
|
568
597
|
copyBytes: false,
|
|
569
|
-
concurrency
|
|
598
|
+
concurrency,
|
|
599
|
+
sleep,
|
|
600
|
+
freeFirst: clean,
|
|
570
601
|
fromLabel: st.fromT.label,
|
|
571
602
|
toLabel: st.toT.label,
|
|
572
603
|
confirm: async () => true,
|
|
573
604
|
onItem: (e) => {
|
|
574
|
-
if (dryRun || !out
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
605
|
+
if (dryRun || !out) return;
|
|
606
|
+
const c = out.chalk;
|
|
607
|
+
const where = `${e.bucket}${e.name ? `/${e.name}` : ''}`;
|
|
608
|
+
if (e.action === 'resume') {
|
|
609
|
+
// Une reprise par fichier et par offset (un envoi qui retombe au même endroit ne se répète pas)
|
|
610
|
+
if (resumes.some((x) => x.bucket === e.bucket && x.name === e.name && x.offset === e.offset)) return;
|
|
611
|
+
resumes.push({ bucket: e.bucket, name: e.name, offset: e.offset, size: e.size });
|
|
612
|
+
return say(` ${c.cyanBright('↻')} ${where}: resumed at ${P.size(e.offset)} of ${P.size(e.size)}`);
|
|
613
|
+
}
|
|
614
|
+
if (e.action === 'retry') {
|
|
615
|
+
live.retried++;
|
|
616
|
+
if (live.shownRetries++ < 10) say(c.grey(` ↻ ${where}: ${e.reason}; try ${e.attempt + 1} in ${Math.max(1, Math.round(e.delay / 1000))} s`));
|
|
617
|
+
else if (live.shownRetries === 11) say(c.grey(' ↻ more retries (counted at the end)'));
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
if (e.action === 'concurrency') return say(c.grey(` ${e.concurrency} transfer(s) at once now (${e.concurrency < concurrency ? 'errors: slowing down' : 'going back up'})`));
|
|
621
|
+
if (e.error) {
|
|
622
|
+
// Les premiers échecs au fil de l'eau ; tous dans le bilan de fin (repliés) et dans --json
|
|
623
|
+
if (++live.failed <= 5) say(c.redBright(` ✖ ${where}: ${s.reason(e.error)}`));
|
|
624
|
+
else if (live.failed === 6) say(c.redBright(' ✖ more failures: see the summary at the end'));
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
if (out.json) return;
|
|
628
|
+
if (e.action === 'bucket') return say(` ${c.greenBright('+')} bucket ${e.bucket}`);
|
|
629
|
+
say(` ${e.action === 'add' ? c.greenBright('+') : e.action === 'update' ? c.yellowBright('~') : c.redBright('-')} ${where}`);
|
|
578
630
|
},
|
|
579
631
|
});
|
|
580
632
|
const t = r.totals;
|
|
581
|
-
const
|
|
582
|
-
const
|
|
583
|
-
|
|
633
|
+
const sizes = (list, k = 'size') => list.reduce((m, o) => m + (Number.isFinite(o[k]) ? o[k] : 0), 0);
|
|
634
|
+
const planned = r.buckets.reduce((acc, p) => acc + sizes(p.add) + sizes(p.update), 0);
|
|
635
|
+
// Place libérée sur la cible : fichiers retirés, versions remplacées (retirées par le Stockage une minute après)
|
|
636
|
+
const freed = r.buckets.reduce((acc, p) => acc + sizes(p.remove) + sizes(p.update, 'targetSize'), 0);
|
|
637
|
+
const bytes = dryRun && r.mode === 'bytes' ? planned : t.bytes || 0;
|
|
638
|
+
const totals = { added: t.added, updated: t.updated, removed: t.removed, unchanged: t.unchanged, buckets_created: t.buckets_created || 0, failed: t.failed || 0, retried: t.retried || live.retried || 0, resumed: resumes.length, bytes };
|
|
639
|
+
return {
|
|
640
|
+
mode: r.mode,
|
|
641
|
+
totals,
|
|
642
|
+
planned_bytes: r.mode === 'bytes' ? planned : 0,
|
|
643
|
+
freed_bytes: freed,
|
|
644
|
+
todo: totals.added + totals.updated + totals.removed + totals.buckets_created > 0,
|
|
645
|
+
buckets: r.buckets.map((p) => ({ bucket: p.bucket, created: p.create, added: p.add.length, updated: p.update.length, removed: p.remove.length })),
|
|
646
|
+
failures: r.errors,
|
|
647
|
+
resumes,
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/** Lignes du puits pour les fichiers : un échec, une reprise (nom et tailles, jamais le contenu) ; 200 au plus */
|
|
652
|
+
function fileLines(r, max = 200) {
|
|
653
|
+
const out = [];
|
|
654
|
+
for (const f of r.failures || []) {
|
|
655
|
+
if (out.length >= max) break;
|
|
656
|
+
out.push({ part: 's3', file: `${f.bucket}/${f.name}`.slice(0, 512), outcome: 'failed', reason: reasonCode(f.error), attempts: f.attempts || 1, duration_ms: 0 });
|
|
657
|
+
}
|
|
658
|
+
for (const x of r.resumes || []) {
|
|
659
|
+
if (out.length >= max) break;
|
|
660
|
+
out.push({ part: 's3', file: `${x.bucket}/${x.name}`.slice(0, 512), outcome: 'resumed', offset: x.offset, bytes: x.size, duration_ms: 0 });
|
|
661
|
+
}
|
|
662
|
+
return out;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** Catégorie d'un échec de transfert (le puits garde une catégorie, pas un message libre). Pure. */
|
|
666
|
+
function reasonCode(message) {
|
|
667
|
+
const m = String(message || '');
|
|
668
|
+
if (/did not answer within/.test(m)) return 'timeout';
|
|
669
|
+
if (/too large|HTTP 413/.test(m)) return 'too_large';
|
|
670
|
+
if (/does not answer on|connection lost|fetch failed|ECONNRESET|socket/i.test(m)) return 'network';
|
|
671
|
+
if (/after the upload/.test(m)) return 'verify';
|
|
672
|
+
if (/refused by the storage/.test(m)) return 'refused';
|
|
673
|
+
if (/not available \(HTTP 50/.test(m)) return 'unavailable';
|
|
674
|
+
const h = /HTTP (\d{3})/.exec(m);
|
|
675
|
+
return h ? `http_${h[1]}` : 'other';
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** Bilan des fichiers en échec : les 5 premiers, « et N autres », puis comment reprendre */
|
|
679
|
+
function printFailures(out, r, { direction, env, opts }) {
|
|
680
|
+
const { chalk } = out;
|
|
681
|
+
if (out.json) return;
|
|
682
|
+
const s = require('../storage');
|
|
683
|
+
const list = r.failures || [];
|
|
684
|
+
const n = list.length;
|
|
685
|
+
out.log(chalk.redBright(` ✖ ${n} file(s) failed${r.totals.retried ? chalk.grey(` (after ${r.totals.retried} retr${r.totals.retried > 1 ? 'ies' : 'y'})`) : ''}:`));
|
|
686
|
+
for (const f of list.slice(0, 5)) out.log(` ${f.bucket}/${f.name}: ${f.error}`);
|
|
687
|
+
if (n > 5) out.log(chalk.grey(` and ${n - 5} other(s): --json lists them all; poad logs cli event=project_push`));
|
|
688
|
+
const again = `poad ${direction}${opts.env ? ` --env ${env.branch}` : ''}`;
|
|
689
|
+
out.log(` Run ${chalk.cyanBright(again)} again (or ${chalk.cyanBright(`${again} --only s3`)}) to resume: files already there are not sent again, a cut upload goes on from where it stopped.`);
|
|
584
690
|
}
|
|
585
691
|
|
|
586
692
|
// --- Place, confirmation, journaux ------------------------------------------------------------------------
|
|
587
693
|
|
|
588
|
-
|
|
694
|
+
/** Ce que la copie écrira et libérera sur la cible, par partie (octets) */
|
|
695
|
+
function spaceAmounts(pv, { clean = false } = {}) {
|
|
696
|
+
const rewrite = pv.base ? pv.base.rewrite : [];
|
|
697
|
+
const needBase = rewrite.reduce((x, t) => x + (t.bytes || 0), 0) + (pv.auth && pv.auth.changed ? pv.auth.tables.reduce((x, t) => x + (t.bytes || 0), 0) : 0);
|
|
698
|
+
const freedBase = clean ? rewrite.reduce((x, t) => x + ((t.target && t.target.bytes) || 0), 0) : 0;
|
|
699
|
+
const s3 = pv.s3 && pv.s3.mode === 'bytes' ? pv.s3 : null;
|
|
700
|
+
return { need: { base: needBase, files: s3 ? s3.planned_bytes || 0 : 0 }, freed: { base: freedBase, files: s3 ? s3.freed_bytes || 0 : 0 } };
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** La sauvegarde n'a de sens que si la base va être écrite (lignes, comptes, secrets, migrations) */
|
|
704
|
+
function dbWrites(pv, sel, push) {
|
|
705
|
+
const has = (p) => sel.parts.includes(p);
|
|
706
|
+
if (has('secrets')) return true;
|
|
707
|
+
if (has('base') && pv.base && (pv.base.rewrite.length || pv.base.sequences.length)) return true;
|
|
708
|
+
if (has('auth') && pv.auth && pv.auth.changed) return true;
|
|
709
|
+
if (has('code') && pv.code) {
|
|
710
|
+
if (push && (pv.code.pending > 0 || pv.code.error)) return true;
|
|
711
|
+
if (!push && pv.code.migrations && pv.code.migrations.length > 0) return true;
|
|
712
|
+
}
|
|
713
|
+
return false;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
async function spaceCheck(id, env, poadDir, push, amounts, P) {
|
|
589
717
|
const api = require('../cloud/api');
|
|
590
718
|
if (push) {
|
|
591
719
|
try {
|
|
592
720
|
const r = await api.call('GET', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/sync-plan`, { what: 'room on poad.io' });
|
|
593
|
-
const sp = r.space && Number.isFinite(Number(r.space.limit)) ? { limit: Number(r.space.limit), used: Number(r.space.used) } : null;
|
|
594
|
-
return {
|
|
721
|
+
const sp = r.space && Number.isFinite(Number(r.space.limit)) ? { limit: Number(r.space.limit), used: Number(r.space.used), storage: r.space.storage === undefined || r.space.storage === null ? null : Number(r.space.storage) } : null;
|
|
722
|
+
return { where: env.branch, volume: true, ...P.room({ ...amounts, space: sp }) };
|
|
595
723
|
} catch (e) {
|
|
596
|
-
return {
|
|
724
|
+
return { where: env.branch, ...P.room(amounts), note: e.status === 404 ? 'this poad.io does not tell the room left yet' : e.message };
|
|
597
725
|
}
|
|
598
726
|
}
|
|
599
727
|
try {
|
|
600
728
|
const st = fs.statfsSync(path.join(poadDir, 'data'));
|
|
601
729
|
const limit = st.blocks * st.bsize;
|
|
602
|
-
return {
|
|
730
|
+
return { where: 'local disk', ...P.room({ ...amounts, space: { limit, used: limit - st.bavail * st.bsize, reserve: amounts.need.base > 0 ? 64 * 1024 ** 2 : 0 } }) };
|
|
603
731
|
} catch {
|
|
604
|
-
return {
|
|
732
|
+
return { where: 'local disk', ...P.room(amounts) };
|
|
605
733
|
}
|
|
606
734
|
}
|
|
607
735
|
|
|
@@ -624,8 +752,10 @@ async function flushLogs({ api, id, env, rid, event, events, config, localStarte
|
|
|
624
752
|
const lines = events.map((e) => {
|
|
625
753
|
const l = { part: e.part, outcome: e.outcome, duration_ms: e.duration_ms };
|
|
626
754
|
if (e.table) l.table = e.table;
|
|
627
|
-
if (
|
|
628
|
-
if (
|
|
755
|
+
if (e.file) l.file = e.file;
|
|
756
|
+
if (e.reason) l.reason = e.reason;
|
|
757
|
+
if (e.step) l.step = e.step;
|
|
758
|
+
for (const k of ['rows', 'bytes', 'attempts', 'offset']) if (Number.isFinite(e[k])) l[k] = e[k];
|
|
629
759
|
return l;
|
|
630
760
|
});
|
|
631
761
|
if (localStarted) {
|
|
@@ -633,8 +763,8 @@ async function flushLogs({ api, id, env, rid, event, events, config, localStarte
|
|
|
633
763
|
try {
|
|
634
764
|
client = await require('../migrations').connect(config);
|
|
635
765
|
for (const l of lines) {
|
|
636
|
-
const level =
|
|
637
|
-
const msg = `${direction} ${l.part}${l.table ? ` ${l.table}` : ''}: ${l.outcome}`;
|
|
766
|
+
const level = ['done', 'resumed', 'skipped', 'loaded'].includes(l.outcome) ? 'info' : 'warn';
|
|
767
|
+
const msg = `${direction} ${l.part}${l.table ? ` ${l.table}` : ''}${l.file ? ` ${l.file}` : ''}${l.step ? ` (${l.step})` : ''}: ${l.outcome}${l.reason ? ` (${l.reason})` : ''}`;
|
|
638
768
|
await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), $1, 'cli', $2, $3::jsonb)", [level, msg, JSON.stringify({ event, request_id: rid, project: id, env: env.branch, direction, ...l })]);
|
|
639
769
|
}
|
|
640
770
|
} catch {
|
|
@@ -643,10 +773,15 @@ async function flushLogs({ api, id, env, rid, event, events, config, localStarte
|
|
|
643
773
|
if (client) await client.end().catch(() => {});
|
|
644
774
|
}
|
|
645
775
|
}
|
|
776
|
+
const send = (body) => api.call('POST', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/sync-events`, { body, what: 'logs', timeout: 15000 });
|
|
646
777
|
try {
|
|
647
|
-
await
|
|
778
|
+
await send({ event, request_id: rid, lines: lines.slice(0, 500) });
|
|
648
779
|
} catch (e) {
|
|
649
|
-
|
|
780
|
+
// poad.io plus ancien : il refuse les lignes par fichier (outcome resumed, champ file) ; les autres passent
|
|
781
|
+
const plain = lines.filter((l) => !l.file && l.outcome !== 'resumed').map(({ reason, step, attempts, offset, ...l }) => l);
|
|
782
|
+
let sent = false;
|
|
783
|
+
if (e.status === 400 && plain.length) sent = await send({ event, request_id: rid, lines: plain.slice(0, 500) }).then(() => true, () => false);
|
|
784
|
+
if (!sent) out.log(out.chalk.grey(` (logs not written on poad.io: ${e.status === 404 ? 'this poad.io does not take them yet' : e.message})`));
|
|
650
785
|
}
|
|
651
786
|
}
|
|
652
787
|
|
|
@@ -719,8 +854,14 @@ function printPreview(out, P, pv, { push, env, sel }) {
|
|
|
719
854
|
}
|
|
720
855
|
if (pv.refs) {
|
|
721
856
|
const r = pv.refs;
|
|
722
|
-
|
|
723
|
-
|
|
857
|
+
// Une ligne par table, lue dans la base de l'autre côté : déjà chargée (lignes, empreinte) / à charger (pourquoi)
|
|
858
|
+
const refStore = require('../reference-store');
|
|
859
|
+
const tables = r.tables || [];
|
|
860
|
+
const count = (a) => tables.filter((t) => t.action === a).length;
|
|
861
|
+
const where = push ? `in ${env.branch}` : 'locally';
|
|
862
|
+
out.log(` ${pad('refs')}${tables.length ? `${tables.length} table(s): ${count('loaded')} already loaded, ${count('load')} to load${count('send') ? `, ${count('send')} to send then load` : ''}${push && r.large.length && r.large_by_code ? chalk.grey(' (large files: by poad deploy)') : ''}` : 'no reference table'}`);
|
|
863
|
+
for (const t of tables.slice(0, 30)) out.log(` ${refStore.stateLine(t, where, chalk)}`);
|
|
864
|
+
if (tables.length > 30) out.log(chalk.grey(` … and ${tables.length - 30} more (--json lists them all)`));
|
|
724
865
|
}
|
|
725
866
|
if (pv.s3) {
|
|
726
867
|
const t = pv.s3.totals;
|
|
@@ -730,11 +871,24 @@ function printPreview(out, P, pv, { push, env, sel }) {
|
|
|
730
871
|
const s = pv.secrets;
|
|
731
872
|
out.log(` ${pad('secrets')}${s.variables.length} variable value(s), ${s.credentials.length} credential(s)${s.credentials.length ? chalk.grey(` (${s.credentials.slice(0, 8).join(', ')})`) : ''}${s.target_storage.length ? chalk.grey(`; storage credentials of the target kept (${s.target_storage.join(', ')})`) : ''}`);
|
|
732
873
|
} else out.log(chalk.grey(` ${'secrets'.padEnd(8)}left out (--with-secrets to copy variable values and credentials)`));
|
|
733
|
-
if (pv.space) {
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
874
|
+
if (pv.space) for (const [i, l] of roomLines(P, pv.space).entries()) out.log(i === 0 ? ` ${pad('room')}${l}` : ` ${l}`);
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** Lignes de la place (aperçu) : à écrire par partie, le volume (base et fichiers à part), libéré, verdict */
|
|
878
|
+
function roomLines(P, s) {
|
|
879
|
+
const chalk = require('chalk-v2');
|
|
880
|
+
const parts = [s.need.base ? `base ${P.size(s.need.base)}` : null, s.need.files ? `files ${P.size(s.need.files)}` : null].filter(Boolean).join(', ');
|
|
881
|
+
const lines = [`to write on ${s.where}: ${parts || 'nothing'}${s.need.base ? chalk.grey(` (base + 10 % + ${P.size(s.reserve || 0)} of journal)`) : ''}`];
|
|
882
|
+
if (!s.known) {
|
|
883
|
+
if (s.note) lines.push(chalk.grey(`room left unknown (${s.note})`));
|
|
884
|
+
return lines;
|
|
737
885
|
}
|
|
886
|
+
const split = s.used_files !== null && s.used_files !== undefined ? ` (base ${P.size(s.used_base)}, files ${P.size(s.used_files)})` : '';
|
|
887
|
+
lines.push(`${s.volume ? 'volume' : 'disk'} ${P.size(s.limit)}: ${P.size(s.used)} used${split}, ${s.over ? chalk.redBright(`exceeded by ${P.size(s.over)}`) : `${P.size(s.free)} free`}`);
|
|
888
|
+
const fr = s.freed.base + s.freed.files;
|
|
889
|
+
if (fr) lines.push(chalk.grey(`freed on the way: ${[s.freed.files ? `files ${P.size(s.freed.files)} (replaced or removed)` : null, s.freed.base ? `base ${P.size(s.freed.base)} (--clean)` : null].filter(Boolean).join(', ')}`));
|
|
890
|
+
lines.push(s.ok ? `${chalk.greenBright('fits')}: ${P.size(s.required)} needed, ${P.size(s.available)} available` : `${chalk.redBright('not enough')}: ${P.size(s.required)} needed, ${P.size(s.available)} available, ${chalk.redBright(`${P.size(s.missing)} missing`)} (a larger plan, or fewer files: --skip s3)`);
|
|
891
|
+
return lines;
|
|
738
892
|
}
|
|
739
893
|
|
|
740
894
|
function resultOf({ direction, id, env, sel, dry, preview, blocking, events, started, results, backup, failed }) {
|
package/utils/reference-store.js
CHANGED
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
// Rien n'est refait pour rien : poad/data/reference-store.json garde, par fichier,
|
|
9
9
|
// sa taille, sa date et l'empreinte de son contenu converti. Fichier inchangé et
|
|
10
10
|
// déjà chargé dans l'environnement : ni conversion, ni envoi, ni chargement.
|
|
11
|
+
// « Déjà chargé » se lit dans la base de l'environnement (marque posée au
|
|
12
|
+
// chargement, nombre de lignes : poad.io la lit, GET seeds?verify) : un volume
|
|
13
|
+
// recréé vide ou une base remise à zéro redonnent « à charger » (CLI 2.76.2).
|
|
11
14
|
'use strict';
|
|
12
15
|
const fs = require('fs');
|
|
13
16
|
const path = require('path');
|
|
@@ -83,33 +86,97 @@ function writeCache(poadDir, cache) {
|
|
|
83
86
|
fs.writeFileSync(cachePath(poadDir), JSON.stringify(cache, null, 2) + '\n');
|
|
84
87
|
}
|
|
85
88
|
|
|
89
|
+
// --- État des tables dans un environnement --------------------------------
|
|
90
|
+
|
|
91
|
+
/** Pourquoi une table est à charger, en clair */
|
|
92
|
+
const WHY = {
|
|
93
|
+
empty: 'table empty',
|
|
94
|
+
unmarked: 'rows without the load mark',
|
|
95
|
+
outdated: 'another version is loaded',
|
|
96
|
+
incomplete: 'fewer rows than loaded',
|
|
97
|
+
no_table: 'table not created yet',
|
|
98
|
+
not_loaded: 'not loaded yet',
|
|
99
|
+
};
|
|
100
|
+
const n = (x) => Number(x || 0).toLocaleString('en-US');
|
|
101
|
+
const short = (sha) => (sha ? String(sha).slice(0, 12) : '?');
|
|
102
|
+
|
|
86
103
|
/**
|
|
87
|
-
*
|
|
88
|
-
*
|
|
104
|
+
* État d'une table dans un environnement hébergé : celui que poad.io a lu dans la base (registry.state, poad.io
|
|
105
|
+
* avec ?verify) ; sinon son registre (applied), dit « non vérifié ». { state, rows, sha256, checked }
|
|
89
106
|
*/
|
|
90
|
-
|
|
107
|
+
function cloudState(registry, branch, target, sha256) {
|
|
108
|
+
const st = registry.state && registry.state[branch] && registry.state[branch][target];
|
|
109
|
+
if (st && st.state && st.state !== 'unknown' && st.state !== 'not_running') {
|
|
110
|
+
// Lu dans la base contre l'empreinte du registre ; une autre empreinte attendue (fichier changé) : à charger
|
|
111
|
+
const state = st.state === 'loaded' && sha256 && st.sha256 && st.sha256 !== sha256 ? 'outdated' : st.state;
|
|
112
|
+
return { state, rows: st.rows, mark_rows: st.mark_rows, sha256: st.sha256, checked: true };
|
|
113
|
+
}
|
|
114
|
+
const a = registry.applied && registry.applied[branch] && registry.applied[branch][target];
|
|
115
|
+
if (a && (!sha256 || a.sha256 === sha256)) return { state: 'loaded', rows: a.rows, sha256: a.sha256, checked: false, why: st ? st.state : 'not_verified' };
|
|
116
|
+
return { state: a ? 'outdated' : 'not_loaded', checked: false, why: st ? st.state : 'not_verified' };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Ce qui attend chaque gros fichier dans l'environnement, sans rien envoyer : loaded (déjà chargée), load (au
|
|
121
|
+
* magasin, à charger), send (fichier changé ou jamais envoyé : à envoyer puis charger). [{ file, target, action, … }]
|
|
122
|
+
*/
|
|
123
|
+
function plan(registry, branch, poadDir, files) {
|
|
124
|
+
const stored = new Map((registry.items || []).map((s) => [s.target, s]));
|
|
125
|
+
const cache = readCache(poadDir);
|
|
126
|
+
return files.map((f) => {
|
|
127
|
+
const c = cache[f.file];
|
|
128
|
+
const item = stored.get(f.target);
|
|
129
|
+
const same = c && c.size === f.size && c.mtimeMs === f.mtimeMs && c.sha256 && item && item.sha256 === c.sha256;
|
|
130
|
+
if (!same) return { file: f.file, rel: f.rel, target: f.target, action: 'send', why: item ? 'file changed since it was sent' : 'never sent' };
|
|
131
|
+
const st = cloudState(registry, branch, f.target, c.sha256);
|
|
132
|
+
return { file: f.file, rel: f.rel, target: f.target, action: st.state === 'loaded' ? 'loaded' : 'load', state: st.state, rows: st.rows, mark_rows: st.mark_rows, expected_rows: item.rows, sha256: c.sha256, checked: st.checked };
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Une ligne par table : déjà chargée (lignes, empreinte) / à charger (pourquoi) / à envoyer puis charger.
|
|
138
|
+
* where : « in main », « locally »… ; p : { target, action: loaded|load|send, state, rows, mark_rows, sha256, expected_rows, checked, why }
|
|
139
|
+
*/
|
|
140
|
+
function stateLine(p, where, chalk, { dryRun = false } = {}) {
|
|
141
|
+
const t = chalk.bold(p.target);
|
|
142
|
+
const at = where.startsWith('in ') || where === 'locally' ? where : `in ${where}`;
|
|
143
|
+
if (p.action === 'loaded') return `${chalk.greenBright('✔')} ${t} already loaded ${at} ${chalk.grey(`(${n(p.rows)} rows, sha256 ${short(p.sha256)}${p.checked === false ? ', as recorded by poad.io: not checked in the database' : ''})`)}`;
|
|
144
|
+
if (p.action === 'load') {
|
|
145
|
+
const why = p.state === 'incomplete' ? `${n(p.rows)} of ${n(p.mark_rows)} rows` : p.state === 'forced' ? 'already loaded, --force' : WHY[p.state] || p.state;
|
|
146
|
+
return `${chalk.yellow('○')} ${t} ${dryRun ? 'would be loaded' : 'to load'} ${at} ${chalk.grey(`(${why}${p.expected_rows !== undefined && p.expected_rows !== null ? `; ${n(p.expected_rows)} rows to load` : ''})`)}`;
|
|
147
|
+
}
|
|
148
|
+
return `${chalk.yellow('○')} ${t} ${dryRun ? 'would be sent, then loaded' : 'to send, then load'} ${at} ${chalk.grey(`(${p.why})`)}`;
|
|
149
|
+
}
|
|
150
|
+
const planLine = (p, branch, chalk, o) => stateLine(p, `in ${branch}`, chalk, o);
|
|
151
|
+
|
|
152
|
+
/** Registre et état réel dans cet environnement (poad.io lit la base de l'engine) */
|
|
153
|
+
const registryOf = (id, branch) => require('./cloud/api').call('GET', `v1/projects/${require('./cloud/api').enc(id)}/seeds?verify=${encodeURIComponent(branch)}`, { what: 'references' });
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Envoie et charge les grosses références dans un environnement ; dryRun : dit seulement ce qui attend chaque
|
|
157
|
+
* table. Renvoie { tables: [{ target, action: 'unchanged'|'load'|'sent', state, … }], load, failed }.
|
|
158
|
+
*/
|
|
159
|
+
async function sendAndLoad(id, branch, poadDir, files, opts, out, { dryRun = false } = {}) {
|
|
91
160
|
const api = require('./cloud/api');
|
|
92
161
|
const S = require('./seed/run');
|
|
93
162
|
const { startAndWait } = require('../project/ref/push');
|
|
94
163
|
const { chalk } = out;
|
|
95
|
-
const registry = await
|
|
96
|
-
if (!registry.store) throw new api.CloudError('The reference store is not configured on this poad.io instance: large reference tables cannot be sent.', { code: 'store_missing' });
|
|
97
|
-
const
|
|
98
|
-
|
|
164
|
+
const registry = await registryOf(id, branch);
|
|
165
|
+
if (!registry.store && !dryRun) throw new api.CloudError('The reference store is not configured on this poad.io instance: large reference tables cannot be sent.', { code: 'store_missing' });
|
|
166
|
+
const planned = plan(registry, branch, poadDir, files);
|
|
167
|
+
if (dryRun) {
|
|
168
|
+
for (const p of planned) out.log(planLine(p, branch, chalk, { dryRun: true }));
|
|
169
|
+
return { tables: planned.map((p) => ({ target: p.target, action: p.action === 'loaded' ? 'unchanged' : p.action, state: p.action === 'loaded' ? 'loaded' : 'pending', rows: p.rows ?? null, sha256: p.sha256 || null, reason: p.state || p.why, checked: p.checked ?? null })), load: null, failed: false, dry_run: true };
|
|
170
|
+
}
|
|
99
171
|
const cache = readCache(poadDir);
|
|
100
172
|
const tables = [];
|
|
101
173
|
const toLoad = [];
|
|
102
|
-
for (const
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
tables.push({ target: f.target, action: 'unchanged', sha256: c.sha256 });
|
|
109
|
-
} else {
|
|
110
|
-
tables.push({ target: f.target, action: 'load', sha256: c.sha256 });
|
|
111
|
-
toLoad.push(f.target);
|
|
112
|
-
}
|
|
174
|
+
for (const p of planned) {
|
|
175
|
+
const f = files.find((x) => x.file === p.file);
|
|
176
|
+
if (p.action !== 'send') {
|
|
177
|
+
out.log(planLine(p, branch, chalk));
|
|
178
|
+
tables.push({ target: p.target, action: p.action === 'loaded' ? 'unchanged' : 'load', sha256: p.sha256, rows: p.rows ?? null, reason: p.state, checked: p.checked });
|
|
179
|
+
if (p.action === 'load') toLoad.push(p.target);
|
|
113
180
|
continue;
|
|
114
181
|
}
|
|
115
182
|
// Conversion puis envoi (contenu déjà au magasin : rien n'est renvoyé)
|
|
@@ -141,11 +208,14 @@ async function sendAndLoad(id, branch, poadDir, files, opts, out) {
|
|
|
141
208
|
},
|
|
142
209
|
});
|
|
143
210
|
if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
144
|
-
out.log(`${chalk.greenBright('✔')} ${chalk.bold(t.target)} ${r.uploaded ? `sent to the reference store (${S.fmt(r.stored)} encrypted)` : 'already in the reference store'}`);
|
|
145
211
|
cache[f.file] = { size: f.size, mtimeMs: f.mtimeMs, sha256: t.sha256, target: t.target };
|
|
146
212
|
writeCache(poadDir, cache);
|
|
147
|
-
|
|
148
|
-
|
|
213
|
+
// Contenu inchangé au magasin : il peut être déjà chargé (l'état lu dans la base le dit)
|
|
214
|
+
const st = cloudState(registry, branch, t.target, t.sha256);
|
|
215
|
+
const loaded = st.state === 'loaded';
|
|
216
|
+
out.log(`${loaded ? chalk.greenBright('✔') : chalk.yellow('○')} ${chalk.bold(t.target)} ${r.uploaded ? `sent to the reference store (${S.fmt(r.stored)} encrypted)` : 'already in the reference store'}${loaded ? `, already loaded in ${branch} ${chalk.grey(`(${n(st.rows)} rows, sha256 ${short(t.sha256)})`)}` : `, to load in ${branch}`}`);
|
|
217
|
+
tables.push({ target: t.target, action: 'sent', sha256: t.sha256, rows: t.rows, uploaded: r.uploaded, reason: st.state });
|
|
218
|
+
if (!loaded) toLoad.push(t.target);
|
|
149
219
|
} finally {
|
|
150
220
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
151
221
|
}
|
|
@@ -155,11 +225,11 @@ async function sendAndLoad(id, branch, poadDir, files, opts, out) {
|
|
|
155
225
|
// État de chaque table dans cet environnement : loaded, pending (pas encore chargée), refused (place), failed
|
|
156
226
|
for (const t of tables) {
|
|
157
227
|
const st = load && (load.steps || []).find((x) => x.target === t.target);
|
|
158
|
-
if (t.
|
|
228
|
+
if (!toLoad.includes(t.target)) t.state = 'loaded';
|
|
159
229
|
else if (st) t.state = st.status === 'done' ? 'loaded' : st.status === 'failed' ? (st.reason === 'space' ? 'refused' : 'failed') : 'pending';
|
|
160
230
|
else t.state = 'pending';
|
|
161
231
|
}
|
|
162
232
|
return { tables, load, failed: Boolean(load && load.status === 'failed') };
|
|
163
233
|
}
|
|
164
234
|
|
|
165
|
-
module.exports = { LARGE, largeFiles, ensureGitignore, ignoreText, sendAndLoad, IGNORE_HEADER };
|
|
235
|
+
module.exports = { LARGE, largeFiles, ensureGitignore, ignoreText, sendAndLoad, IGNORE_HEADER, plan, planLine, stateLine, cloudState, readCache, WHY };
|