poad 2.76.0 → 2.76.1

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.
@@ -243,6 +243,59 @@ function fits(need, space) {
243
243
  return { known: true, ok: required <= free, required, free, reserve, limit: space.limit };
244
244
  }
245
245
 
246
+ /**
247
+ * --clean : vide d'abord, en une transaction à part, les tables à réécrire (TRUNCATE rend leur place tout de
248
+ * suite, contrairement à DELETE). Une table de la cible qui y renvoie par clé étrangère et n'est pas vidée
249
+ * fait échouer le tout : rien n'est vidé. Pure.
250
+ */
251
+ function truncateSql(tables = []) {
252
+ if (!tables.length) return 'select 1;';
253
+ return `set lock_timeout = '30s';\nbegin;\ntruncate table ${tables.map((t) => qname(t.schema, t.name)).join(', ')};\ncommit;`;
254
+ }
255
+
256
+ /**
257
+ * Place sur la cible de poad push / pull, parties ensemble. Pure.
258
+ * need { base, files } octets à écrire : lignes réécrites (base et comptes), fichiers envoyés
259
+ * freed { base, files } octets libérés avant ou pendant la copie : fichiers retirés ou remplacés (le
260
+ * Stockage retire leur contenu une minute après), tables vidées d'abord (--clean). Les lignes
261
+ * remplacées dans la transaction de la base ne libèrent rien avant la fin de celle-ci : 0 sans --clean.
262
+ * space { limit, used, storage?, reserve? } volume de la cible ; storage : la part des fichiers, si connue
263
+ * La base demande + 10 % et la réserve du journal ; les fichiers, leur taille. Jamais d'octets négatifs : un
264
+ * volume déjà rempli au-delà de sa taille se dit « dépassé de » (over).
265
+ */
266
+ function room({ need = {}, freed = {}, space } = {}) {
267
+ const pos = (v) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Math.round(Number(v)) : 0);
268
+ const nb = pos(need.base);
269
+ const nf = pos(need.files);
270
+ const fb = pos(freed.base);
271
+ const ff = pos(freed.files);
272
+ const base = { need: { base: nb, files: nf }, freed: { base: fb, files: ff } };
273
+ if (!space || !Number.isFinite(Number(space.limit)) || !Number.isFinite(Number(space.used)) || Number(space.limit) <= 0) return { known: false, ok: true, ...base };
274
+ const limit = Number(space.limit);
275
+ const used = Math.max(0, Number(space.used));
276
+ const reserve = nb > 0 ? (space.reserve !== undefined ? pos(space.reserve) : walReserve(limit)) : 0;
277
+ const required = Math.ceil((nb * 11) / 10 + reserve + nf);
278
+ const left = limit - used;
279
+ const available = left + fb + ff;
280
+ const ok = required <= available;
281
+ const files = Number.isFinite(Number(space.storage)) && space.storage !== null ? Math.min(used, pos(space.storage)) : null;
282
+ return {
283
+ known: true,
284
+ ok,
285
+ ...base,
286
+ required,
287
+ reserve,
288
+ limit,
289
+ used,
290
+ used_files: files,
291
+ used_base: files === null ? null : used - files,
292
+ free: Math.max(0, left),
293
+ over: Math.max(0, -left),
294
+ available: Math.max(0, available),
295
+ missing: ok ? 0 : required - available,
296
+ };
297
+ }
298
+
246
299
  /**
247
300
  * Script bash du transfert des données (base et comptes), lancé dans le conteneur de l'engine local.
248
301
  * srcFn / dstFn commandes psql vers la source / la cible
@@ -424,6 +477,8 @@ module.exports = {
424
477
  changed,
425
478
  walReserve,
426
479
  fits,
480
+ room,
481
+ truncateSql,
427
482
  transferScript,
428
483
  sequencesSql,
429
484
  sequencesFor,
@@ -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
- out.log(chalk.grey(` parts: ${sel.parts.join(', ')}${sel.tables ? ` tables: ${sel.tables.join(', ')}` : ''}`));
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 };
@@ -159,16 +160,16 @@ function run(direction, raw, deps = {}) {
159
160
  // Secrets : des noms seulement
160
161
  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
162
 
162
- // Place sur la cible : ce qui sera réécrit (base et comptes)
163
- const need = (preview.base ? preview.base.rewrite.reduce((s, t) => s + t.bytes, 0) : 0) + (preview.auth && preview.auth.changed ? preview.auth.tables.reduce((s, t) => s + t.bytes, 0) : 0);
164
- if (need > 0) preview.space = await spaceCheck(id, env, poadDir, push, need, P);
163
+ // Place sur la cible : ce qui sera écrit (base et comptes, fichiers) et ce qui sera libéré
164
+ const amounts = spaceAmounts(preview, { clean });
165
+ if (amounts.need.base + amounts.need.files > 0) preview.space = await spaceCheck(id, env, poadDir, push, amounts, P);
165
166
 
166
167
  printPreview(out, P, preview, { push, env, cloudLabel, sel });
167
168
 
168
169
  const blocking = [];
169
170
  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
171
  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('not enough room on the target');
172
+ 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
173
  if (preview.base && preview.base.unknown.length) blocking.push(`--tables: ${preview.base.unknown.join(', ')} not in the source`);
173
174
  const nothing = isNothing(preview, sel);
174
175
 
@@ -194,7 +195,7 @@ function run(direction, raw, deps = {}) {
194
195
  // --- Confirmations -------------------------------------------------------------------------------
195
196
  const target = push ? cloudLabel : 'the local project';
196
197
  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.`, { yes: opts.yes, json: out.json });
198
+ 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
199
  if (has('secrets')) {
199
200
  const s = preview.secrets;
200
201
  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 +203,9 @@ function run(direction, raw, deps = {}) {
202
203
 
203
204
  // --- Sauvegarde -----------------------------------------------------------------------------------
204
205
  let backup = null;
205
- const writesDb = has('base') || has('auth') || has('secrets') || (has('code') && (push || (preview.code && preview.code.migrations && preview.code.migrations.length > 0)));
206
+ // Seulement si la base va vraiment être écrite : une poussée relancée qui n'a plus que des fichiers à
207
+ // envoyer ne refait pas de sauvegarde de la production
208
+ const writesDb = dbWrites(preview, sel, push);
206
209
  if (push && env.production && writesDb) {
207
210
  const t0 = Date.now();
208
211
  try {
@@ -263,7 +266,20 @@ function run(direction, raw, deps = {}) {
263
266
  stop('base', 'the structure of the target differs');
264
267
  note({ part: 'base', outcome: 'refused', duration_ms: 0 });
265
268
  } else {
266
- const r = await transferData(pg, P, container, src, dst, { base, auth, inv, sel, out });
269
+ let r = null;
270
+ if (clean && base && base.rewrite.length) {
271
+ const t0 = Date.now();
272
+ try {
273
+ await pg.query(container, dst, P.truncateSql(base.rewrite));
274
+ 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' });
275
+ 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)`)}`);
276
+ } catch (e) {
277
+ note({ part: 'base', outcome: 'failed', duration_ms: Date.now() - t0, step: 'clean' });
278
+ out.log(chalk.redBright(` ✕ --clean: the tables could not be emptied, nothing changed (${e.message})`));
279
+ r = { ok: false, lines: [], tables: [], error: `--clean: ${e.message}` };
280
+ }
281
+ }
282
+ if (!r) r = await transferData(pg, P, container, src, dst, { base, auth, inv, sel, out });
267
283
  for (const l of r.lines) note(l);
268
284
  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
285
  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 +302,9 @@ function run(direction, raw, deps = {}) {
286
302
 
287
303
  if (!failed && has('s3') && preview.s3 && preview.s3.todo) {
288
304
  const t0 = Date.now();
289
- const r = await storagePlan(storage, false, out);
305
+ const r = await storagePlan(storage, false, out, { clean, concurrency: deps.concurrency, sleep: deps.sleep });
290
306
  results.s3 = r;
307
+ for (const l of fileLines(r)) note(l);
291
308
  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
309
  if (r.totals.failed) stop('s3', `${r.totals.failed} file(s) failed`);
293
310
  }
@@ -307,6 +324,7 @@ function run(direction, raw, deps = {}) {
307
324
  await flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction });
308
325
 
309
326
  out.log(' ');
327
+ if (results.s3 && results.s3.totals.failed) printFailures(out, results.s3, { direction, env, opts });
310
328
  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
329
  else out.log(`${chalk.greenBright('✔')} ${push ? `Pushed to ${env.branch}` : `Pulled from ${env.branch}`} in ${((Date.now() - started) / 1000).toFixed(1)} s.`);
312
330
  out.log(chalk.grey(` Logs: poad logs cli event=${event}${push ? ` (and --env ${env.branch} on poad.io)` : ''}`));
@@ -559,49 +577,152 @@ async function storageSides(env, opts, push, deps) {
559
577
  return { fromT, toT, from: (deps.client || s.client)(fromT), to: (deps.client || s.client)(toT) };
560
578
  }
561
579
 
562
- async function storagePlan(st, dryRun, out) {
580
+ async function storagePlan(st, dryRun, out, { clean = false, concurrency = 4, sleep } = {}) {
563
581
  const ss = require('../storage-sync');
564
582
  const s = require('../storage');
583
+ const P = require('./plan');
584
+ const live = { failed: 0, retried: 0, shownRetries: 0 };
585
+ const resumes = [];
586
+ const say = (line) => out && !out.json && out.log(line);
565
587
  const r = await ss.sync(st.from, st.to, {
566
588
  prune: true,
567
589
  dryRun,
568
590
  copyBytes: false,
569
- concurrency: 4,
591
+ concurrency,
592
+ sleep,
593
+ freeFirst: clean,
570
594
  fromLabel: st.fromT.label,
571
595
  toLabel: st.toT.label,
572
596
  confirm: async () => true,
573
597
  onItem: (e) => {
574
- if (dryRun || !out || out.json) return;
575
- if (e.error) return out.log(out.chalk.redBright(` ✖ ${e.bucket}${e.name ? `/${e.name}` : ''}: ${s.reason(e.error)}`));
576
- if (e.action === 'bucket') return out.log(` ${out.chalk.greenBright('+')} bucket ${e.bucket}`);
577
- out.log(` ${e.action === 'add' ? out.chalk.greenBright('+') : e.action === 'update' ? out.chalk.yellowBright('~') : out.chalk.redBright('-')} ${e.bucket}/${e.name}`);
598
+ if (dryRun || !out) return;
599
+ const c = out.chalk;
600
+ const where = `${e.bucket}${e.name ? `/${e.name}` : ''}`;
601
+ if (e.action === 'resume') {
602
+ // Une reprise par fichier et par offset (un envoi qui retombe au même endroit ne se répète pas)
603
+ if (resumes.some((x) => x.bucket === e.bucket && x.name === e.name && x.offset === e.offset)) return;
604
+ resumes.push({ bucket: e.bucket, name: e.name, offset: e.offset, size: e.size });
605
+ return say(` ${c.cyanBright('↻')} ${where}: resumed at ${P.size(e.offset)} of ${P.size(e.size)}`);
606
+ }
607
+ if (e.action === 'retry') {
608
+ live.retried++;
609
+ if (live.shownRetries++ < 10) say(c.grey(` ↻ ${where}: ${e.reason}; try ${e.attempt + 1} in ${Math.max(1, Math.round(e.delay / 1000))} s`));
610
+ else if (live.shownRetries === 11) say(c.grey(' ↻ more retries (counted at the end)'));
611
+ return;
612
+ }
613
+ if (e.action === 'concurrency') return say(c.grey(` ${e.concurrency} transfer(s) at once now (${e.concurrency < concurrency ? 'errors: slowing down' : 'going back up'})`));
614
+ if (e.error) {
615
+ // Les premiers échecs au fil de l'eau ; tous dans le bilan de fin (repliés) et dans --json
616
+ if (++live.failed <= 5) say(c.redBright(` ✖ ${where}: ${s.reason(e.error)}`));
617
+ else if (live.failed === 6) say(c.redBright(' ✖ more failures: see the summary at the end'));
618
+ return;
619
+ }
620
+ if (out.json) return;
621
+ if (e.action === 'bucket') return say(` ${c.greenBright('+')} bucket ${e.bucket}`);
622
+ say(` ${e.action === 'add' ? c.greenBright('+') : e.action === 'update' ? c.yellowBright('~') : c.redBright('-')} ${where}`);
578
623
  },
579
624
  });
580
625
  const t = r.totals;
581
- const bytes = dryRun && r.mode === 'bytes' ? r.buckets.reduce((acc, p) => acc + [...p.add, ...p.update].reduce((m, o) => m + (o.size || 0), 0), 0) : t.bytes || 0;
582
- const totals = { added: t.added, updated: t.updated, removed: t.removed, unchanged: t.unchanged, buckets_created: t.buckets_created || 0, failed: t.failed || 0, bytes };
583
- return { mode: r.mode, totals, todo: totals.added + totals.updated + totals.removed + totals.buckets_created > 0, buckets: r.buckets.map((p) => ({ bucket: p.bucket, created: p.create, added: p.add.length, updated: p.update.length, removed: p.remove.length })), failures: r.errors };
626
+ const sizes = (list, k = 'size') => list.reduce((m, o) => m + (Number.isFinite(o[k]) ? o[k] : 0), 0);
627
+ const planned = r.buckets.reduce((acc, p) => acc + sizes(p.add) + sizes(p.update), 0);
628
+ // Place libérée sur la cible : fichiers retirés, versions remplacées (retirées par le Stockage une minute après)
629
+ const freed = r.buckets.reduce((acc, p) => acc + sizes(p.remove) + sizes(p.update, 'targetSize'), 0);
630
+ const bytes = dryRun && r.mode === 'bytes' ? planned : t.bytes || 0;
631
+ 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 };
632
+ return {
633
+ mode: r.mode,
634
+ totals,
635
+ planned_bytes: r.mode === 'bytes' ? planned : 0,
636
+ freed_bytes: freed,
637
+ todo: totals.added + totals.updated + totals.removed + totals.buckets_created > 0,
638
+ buckets: r.buckets.map((p) => ({ bucket: p.bucket, created: p.create, added: p.add.length, updated: p.update.length, removed: p.remove.length })),
639
+ failures: r.errors,
640
+ resumes,
641
+ };
642
+ }
643
+
644
+ /** Lignes du puits pour les fichiers : un échec, une reprise (nom et tailles, jamais le contenu) ; 200 au plus */
645
+ function fileLines(r, max = 200) {
646
+ const out = [];
647
+ for (const f of r.failures || []) {
648
+ if (out.length >= max) break;
649
+ 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 });
650
+ }
651
+ for (const x of r.resumes || []) {
652
+ if (out.length >= max) break;
653
+ out.push({ part: 's3', file: `${x.bucket}/${x.name}`.slice(0, 512), outcome: 'resumed', offset: x.offset, bytes: x.size, duration_ms: 0 });
654
+ }
655
+ return out;
656
+ }
657
+
658
+ /** Catégorie d'un échec de transfert (le puits garde une catégorie, pas un message libre). Pure. */
659
+ function reasonCode(message) {
660
+ const m = String(message || '');
661
+ if (/did not answer within/.test(m)) return 'timeout';
662
+ if (/too large|HTTP 413/.test(m)) return 'too_large';
663
+ if (/does not answer on|connection lost|fetch failed|ECONNRESET|socket/i.test(m)) return 'network';
664
+ if (/after the upload/.test(m)) return 'verify';
665
+ if (/refused by the storage/.test(m)) return 'refused';
666
+ if (/not available \(HTTP 50/.test(m)) return 'unavailable';
667
+ const h = /HTTP (\d{3})/.exec(m);
668
+ return h ? `http_${h[1]}` : 'other';
669
+ }
670
+
671
+ /** Bilan des fichiers en échec : les 5 premiers, « et N autres », puis comment reprendre */
672
+ function printFailures(out, r, { direction, env, opts }) {
673
+ const { chalk } = out;
674
+ if (out.json) return;
675
+ const s = require('../storage');
676
+ const list = r.failures || [];
677
+ const n = list.length;
678
+ out.log(chalk.redBright(` ✖ ${n} file(s) failed${r.totals.retried ? chalk.grey(` (after ${r.totals.retried} retr${r.totals.retried > 1 ? 'ies' : 'y'})`) : ''}:`));
679
+ for (const f of list.slice(0, 5)) out.log(` ${f.bucket}/${f.name}: ${f.error}`);
680
+ if (n > 5) out.log(chalk.grey(` and ${n - 5} other(s): --json lists them all; poad logs cli event=project_push`));
681
+ const again = `poad ${direction}${opts.env ? ` --env ${env.branch}` : ''}`;
682
+ 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
683
  }
585
684
 
586
685
  // --- Place, confirmation, journaux ------------------------------------------------------------------------
587
686
 
588
- async function spaceCheck(id, env, poadDir, push, need, P) {
687
+ /** Ce que la copie écrira et libérera sur la cible, par partie (octets) */
688
+ function spaceAmounts(pv, { clean = false } = {}) {
689
+ const rewrite = pv.base ? pv.base.rewrite : [];
690
+ 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);
691
+ const freedBase = clean ? rewrite.reduce((x, t) => x + ((t.target && t.target.bytes) || 0), 0) : 0;
692
+ const s3 = pv.s3 && pv.s3.mode === 'bytes' ? pv.s3 : null;
693
+ return { need: { base: needBase, files: s3 ? s3.planned_bytes || 0 : 0 }, freed: { base: freedBase, files: s3 ? s3.freed_bytes || 0 : 0 } };
694
+ }
695
+
696
+ /** La sauvegarde n'a de sens que si la base va être écrite (lignes, comptes, secrets, migrations) */
697
+ function dbWrites(pv, sel, push) {
698
+ const has = (p) => sel.parts.includes(p);
699
+ if (has('secrets')) return true;
700
+ if (has('base') && pv.base && (pv.base.rewrite.length || pv.base.sequences.length)) return true;
701
+ if (has('auth') && pv.auth && pv.auth.changed) return true;
702
+ if (has('code') && pv.code) {
703
+ if (push && (pv.code.pending > 0 || pv.code.error)) return true;
704
+ if (!push && pv.code.migrations && pv.code.migrations.length > 0) return true;
705
+ }
706
+ return false;
707
+ }
708
+
709
+ async function spaceCheck(id, env, poadDir, push, amounts, P) {
589
710
  const api = require('../cloud/api');
590
711
  if (push) {
591
712
  try {
592
713
  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 { need, where: env.branch, ...P.fits(need, sp) };
714
+ 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;
715
+ return { where: env.branch, volume: true, ...P.room({ ...amounts, space: sp }) };
595
716
  } catch (e) {
596
- return { need, where: env.branch, known: false, ok: true, note: e.status === 404 ? 'this poad.io does not tell the room left yet' : e.message };
717
+ return { where: env.branch, ...P.room(amounts), note: e.status === 404 ? 'this poad.io does not tell the room left yet' : e.message };
597
718
  }
598
719
  }
599
720
  try {
600
721
  const st = fs.statfsSync(path.join(poadDir, 'data'));
601
722
  const limit = st.blocks * st.bsize;
602
- return { need, where: 'local disk', ...P.fits(need, { limit, used: limit - st.bavail * st.bsize, reserve: 64 * 1024 ** 2 }) };
723
+ 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
724
  } catch {
604
- return { need, where: 'local disk', known: false, ok: true };
725
+ return { where: 'local disk', ...P.room(amounts) };
605
726
  }
606
727
  }
607
728
 
@@ -624,8 +745,10 @@ async function flushLogs({ api, id, env, rid, event, events, config, localStarte
624
745
  const lines = events.map((e) => {
625
746
  const l = { part: e.part, outcome: e.outcome, duration_ms: e.duration_ms };
626
747
  if (e.table) l.table = e.table;
627
- if (Number.isFinite(e.rows)) l.rows = e.rows;
628
- if (Number.isFinite(e.bytes)) l.bytes = e.bytes;
748
+ if (e.file) l.file = e.file;
749
+ if (e.reason) l.reason = e.reason;
750
+ if (e.step) l.step = e.step;
751
+ for (const k of ['rows', 'bytes', 'attempts', 'offset']) if (Number.isFinite(e[k])) l[k] = e[k];
629
752
  return l;
630
753
  });
631
754
  if (localStarted) {
@@ -633,8 +756,8 @@ async function flushLogs({ api, id, env, rid, event, events, config, localStarte
633
756
  try {
634
757
  client = await require('../migrations').connect(config);
635
758
  for (const l of lines) {
636
- const level = l.outcome === 'done' ? 'info' : 'warn';
637
- const msg = `${direction} ${l.part}${l.table ? ` ${l.table}` : ''}: ${l.outcome}`;
759
+ const level = ['done', 'resumed', 'skipped', 'loaded'].includes(l.outcome) ? 'info' : 'warn';
760
+ const msg = `${direction} ${l.part}${l.table ? ` ${l.table}` : ''}${l.file ? ` ${l.file}` : ''}${l.step ? ` (${l.step})` : ''}: ${l.outcome}${l.reason ? ` (${l.reason})` : ''}`;
638
761
  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
762
  }
640
763
  } catch {
@@ -643,10 +766,15 @@ async function flushLogs({ api, id, env, rid, event, events, config, localStarte
643
766
  if (client) await client.end().catch(() => {});
644
767
  }
645
768
  }
769
+ const send = (body) => api.call('POST', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/sync-events`, { body, what: 'logs', timeout: 15000 });
646
770
  try {
647
- await api.call('POST', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/sync-events`, { body: { event, request_id: rid, lines }, what: 'logs', timeout: 15000 });
771
+ await send({ event, request_id: rid, lines: lines.slice(0, 500) });
648
772
  } catch (e) {
649
- out.log(out.chalk.grey(` (logs not written on poad.io: ${e.status === 404 ? 'this poad.io does not take them yet' : e.message})`));
773
+ // poad.io plus ancien : il refuse les lignes par fichier (outcome resumed, champ file) ; les autres passent
774
+ const plain = lines.filter((l) => !l.file && l.outcome !== 'resumed').map(({ reason, step, attempts, offset, ...l }) => l);
775
+ let sent = false;
776
+ if (e.status === 400 && plain.length) sent = await send({ event, request_id: rid, lines: plain.slice(0, 500) }).then(() => true, () => false);
777
+ 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
778
  }
651
779
  }
652
780
 
@@ -730,11 +858,24 @@ function printPreview(out, P, pv, { push, env, sel }) {
730
858
  const s = pv.secrets;
731
859
  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
860
  } else out.log(chalk.grey(` ${'secrets'.padEnd(8)}left out (--with-secrets to copy variable values and credentials)`));
733
- if (pv.space) {
734
- const s = pv.space;
735
- if (!s.known) out.log(chalk.grey(` ${'room'.padEnd(8)}${P.size(s.need)} to write on ${s.where}${s.note ? ` (${s.note})` : ''}`));
736
- else out.log(` ${pad('room')}${s.ok ? '' : chalk.redBright('not enough: ')}${P.size(s.need)} + 10 % + ${P.size(s.reserve)} of journal = ${P.size(s.required)} needed, ${P.size(s.free)} free on ${s.where}`);
861
+ if (pv.space) for (const [i, l] of roomLines(P, pv.space).entries()) out.log(i === 0 ? ` ${pad('room')}${l}` : ` ${l}`);
862
+ }
863
+
864
+ /** Lignes de la place (aperçu) : à écrire par partie, le volume (base et fichiers à part), libéré, verdict */
865
+ function roomLines(P, s) {
866
+ const chalk = require('chalk-v2');
867
+ 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(', ');
868
+ const lines = [`to write on ${s.where}: ${parts || 'nothing'}${s.need.base ? chalk.grey(` (base + 10 % + ${P.size(s.reserve || 0)} of journal)`) : ''}`];
869
+ if (!s.known) {
870
+ if (s.note) lines.push(chalk.grey(`room left unknown (${s.note})`));
871
+ return lines;
737
872
  }
873
+ const split = s.used_files !== null && s.used_files !== undefined ? ` (base ${P.size(s.used_base)}, files ${P.size(s.used_files)})` : '';
874
+ 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`}`);
875
+ const fr = s.freed.base + s.freed.files;
876
+ 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(', ')}`));
877
+ 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)`);
878
+ return lines;
738
879
  }
739
880
 
740
881
  function resultOf({ direction, id, env, sel, dry, preview, blocking, events, started, results, backup, failed }) {
@@ -137,7 +137,8 @@ function plan(src, dst, { prune = false } = {}) {
137
137
  const d = byName.get(o.name);
138
138
  if (!d) out.add.push(o);
139
139
  else if (sameContent(o, d)) out.unchanged.push(o);
140
- else out.update.push(o);
140
+ // Taille de ce qui est remplacé : place libérée sur la destination (contrôle de place de poad push)
141
+ else out.update.push({ ...o, targetSize: Number.isFinite(d.size) ? d.size : null });
141
142
  }
142
143
  if (prune)
143
144
  for (const d of dst) {
@@ -148,13 +149,112 @@ function plan(src, dst, { prune = false } = {}) {
148
149
  return out;
149
150
  }
150
151
 
151
- /** Copie des octets d'un objet, en flux ; rend sa taille */
152
- async function copyBytes(from, to, bucket, o) {
152
+ /**
153
+ * Copie des octets d'un objet ; rend sa taille. Au-delà d'un morceau (6 Mio) et si la destination connaît
154
+ * TUS : envoi en morceaux reprenables, la source lue par plages (Range) — un envoi coupé, même par la fin de
155
+ * la commande, reprend là où la destination en est (clé de reprise : destination + empreinte du contenu).
156
+ * Sinon : une requête, en flux, sous un délai d'inactivité (utils/storage.js).
157
+ */
158
+ async function copyBytes(from, to, bucket, o, { onResume, sleep } = {}) {
159
+ const t = require('./storage-tus');
160
+ if (Number.isFinite(o.size) && o.size > t.CHUNK && to.raw && !to.noTus) {
161
+ const type = o.mimetype || 'application/octet-stream';
162
+ let source = await t.rangeSource(from, bucket, o.name, o.size).catch(() => null);
163
+ let res = null;
164
+ if (!source) {
165
+ res = await from.get(bucket, o.name);
166
+ source = t.streamSource(res.body, o.size);
167
+ }
168
+ try {
169
+ await t.tusUpload(to, source, { bucket, key: o.name, type, cacheControl: o.cacheControl || undefined, upsert: true, base: to.base, version: o.etag || o.key || null, onResume, sleep });
170
+ return o.size;
171
+ } catch (e) {
172
+ if (e.code !== 'tus_unsupported') throw e;
173
+ to.noTus = true;
174
+ if (res) await res.body?.cancel().catch(() => {});
175
+ }
176
+ }
153
177
  const res = await from.get(bucket, o.name);
154
- await to.put(bucket, o.name, res.body, { type: o.mimetype || res.headers.get('content-type') || 'application/octet-stream', cacheControl: o.cacheControl || undefined });
178
+ await to.put(bucket, o.name, res.body, { type: o.mimetype || res.headers.get('content-type') || 'application/octet-stream', cacheControl: o.cacheControl || undefined, length: Number.isFinite(o.size) ? o.size : undefined });
155
179
  return o.size || Number(res.headers.get('content-length')) || 0;
156
180
  }
157
181
 
182
+ /** Une nouvelle tentative a-t-elle un sens (coupure, délai, 5xx, 429) ? Un refus (4xx) est définitif. Pure. */
183
+ function retriable(e) {
184
+ if (!e) return false;
185
+ if (e.retriable) return true;
186
+ if (['network', 'timeout'].includes(e.code)) return true;
187
+ return [408, 425, 429, 500, 502, 503, 504].includes(e.status);
188
+ }
189
+
190
+ /** Attente avant la tentative n (1, 2, 3…) : 1 s, 2 s, 4 s… plafonnée à 30 s, ±25 %. Pure (au hasard près). */
191
+ const backoff = (n, rnd = Math.random) => Math.round(Math.min(30_000, 1000 * 2 ** (n - 1)) * (0.75 + rnd() * 0.5));
192
+
193
+ /**
194
+ * Exécute fn sur chaque élément, avec nouvelles tentatives et une concurrence qui baisse quand les erreurs
195
+ * montent : une erreur passagère divise le nombre de transferts en parallèle par deux (au moins 1), puis
196
+ * chaque série de succès le remonte d'un cran jusqu'à la valeur de départ. Rend les erreurs { item, error }.
197
+ * opts : { concurrency, retries, sleep, onRetry(item, attempt, error, delay), onConcurrency(n) }
198
+ */
199
+ async function adaptive(items, fn, opts = {}) {
200
+ const max = Number.isInteger(opts.concurrency) && opts.concurrency > 0 ? opts.concurrency : s.PARALLEL;
201
+ const retries = Number.isInteger(opts.retries) ? opts.retries : 4;
202
+ const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
203
+ const errors = [];
204
+ let limit = max;
205
+ let active = 0;
206
+ let streak = 0;
207
+ let next = 0;
208
+ const lower = () => {
209
+ const was = limit;
210
+ limit = Math.max(1, Math.floor(limit / 2));
211
+ streak = 0;
212
+ if (limit !== was && opts.onConcurrency) opts.onConcurrency(limit);
213
+ };
214
+ const raise = () => {
215
+ if (limit >= max) return;
216
+ if (++streak >= limit * 2) {
217
+ limit++;
218
+ streak = 0;
219
+ if (opts.onConcurrency) opts.onConcurrency(limit);
220
+ }
221
+ };
222
+ const worker = async (slot) => {
223
+ while (next < items.length) {
224
+ // Au-delà de la concurrence permise : on attend qu'elle remonte, ou la fin
225
+ if (slot >= limit) {
226
+ await new Promise((r) => setTimeout(r, 100));
227
+ continue;
228
+ }
229
+ const item = items[next++];
230
+ active++;
231
+ try {
232
+ for (let attempt = 1; ; attempt++) {
233
+ try {
234
+ await fn(item, attempt);
235
+ raise();
236
+ break;
237
+ } catch (error) {
238
+ if (!retriable(error) || attempt > retries) {
239
+ errors.push({ item, error, attempts: attempt });
240
+ if (retriable(error)) lower();
241
+ break;
242
+ }
243
+ lower();
244
+ const delay = backoff(attempt);
245
+ if (opts.onRetry) opts.onRetry(item, attempt, error, delay);
246
+ await sleep(delay);
247
+ }
248
+ }
249
+ } finally {
250
+ active--;
251
+ }
252
+ }
253
+ };
254
+ await Promise.all(Array.from({ length: Math.min(max, items.length) }, (_, i) => worker(i)));
255
+ return errors;
256
+ }
257
+
158
258
  /**
159
259
  * Synchronise. from/to : clients du Stockage (utils/storage.client) ; opts : { bucket, prune,
160
260
  * dryRun, copyBytes, concurrency, fromLabel, toLabel, confirm(summary), onItem(event) }.
@@ -223,19 +323,71 @@ async function sync(from, to, opts = {}) {
223
323
  }
224
324
  }
225
325
  }
326
+ // Retraits d'abord : la place qu'ils occupaient se libère avant les envois (le service retire les
327
+ // contenus une minute après). --clean (freeFirst) : ce qui va être remplacé part aussi d'abord.
328
+ const freeing = opts.freeFirst ? p.update.map((o) => o.name) : [];
329
+ const names = [...p.remove.map((o) => o.name), ...freeing];
330
+ for (let i = 0; i < names.length; i += 1000) {
331
+ const slice = names.slice(i, i + 1000);
332
+ try {
333
+ const rows = (await to.remove(p.bucket, slice)) || [];
334
+ for (const r of rows) {
335
+ if (freeing.includes(r.name)) continue;
336
+ totals.removed++;
337
+ event({ bucket: p.bucket, name: r.name, action: 'remove' });
338
+ }
339
+ } catch (e) {
340
+ for (const n of slice) fail(p.bucket, n, freeing.includes(n) ? 'update' : 'remove', e);
341
+ }
342
+ }
226
343
  const work = [...p.add.map((o) => ['add', o]), ...p.update.map((o) => ['update', o])];
227
344
  const done = (action, o) => {
228
345
  totals[action === 'add' ? 'added' : 'updated']++;
229
346
  event({ bucket: p.bucket, name: o.name, action, size: o.size });
230
347
  };
231
348
  if (mode === 'bytes') {
232
- const errs = await s.each(work, async ([action, o]) => {
233
- // Lu après l'attente : « totals.bytes += await … » perdrait les transferts parallèles
234
- const n = await copyBytes(from, to, p.bucket, o);
235
- totals.bytes += n;
236
- done(action, o);
237
- }, opts.concurrency);
238
- for (const { item, error } of errs) fail(p.bucket, item[1].name, item[0], error);
349
+ const sent = [];
350
+ const errs = await adaptive(
351
+ work,
352
+ async ([action, o]) => {
353
+ // Lu après l'attente : « totals.bytes += await … » perdrait les transferts parallèles
354
+ const n = await copyBytes(from, to, p.bucket, o, { sleep: opts.sleep, onResume: (offset) => offset > 0 && event({ bucket: p.bucket, name: o.name, action: 'resume', offset, size: o.size }) });
355
+ totals.bytes += n;
356
+ sent.push([action, o]);
357
+ done(action, o);
358
+ },
359
+ {
360
+ concurrency: opts.concurrency,
361
+ retries: opts.retries,
362
+ sleep: opts.sleep,
363
+ onRetry: ([action, o], attempt, error, delay) => {
364
+ totals.retried = (totals.retried || 0) + 1;
365
+ event({ bucket: p.bucket, name: o.name, action: 'retry', attempt, delay, reason: s.reason(error) });
366
+ },
367
+ onConcurrency: (n) => event({ bucket: p.bucket, action: 'concurrency', concurrency: n }),
368
+ },
369
+ );
370
+ for (const { item, error, attempts } of errs) {
371
+ fail(p.bucket, item[1].name, item[0], error);
372
+ result.errors[result.errors.length - 1].attempts = attempts;
373
+ }
374
+ // Ce qui est arrivé est relu : taille et empreinte (MD5) doivent être celles de la source ; un objet
375
+ // tronqué ou différent n'est jamais compté comme fait (et la prochaine poussée le renverra)
376
+ if (sent.length && opts.verify !== false) {
377
+ let after = null;
378
+ try {
379
+ after = new Map((await listObjects(to, p.bucket, dstLoc.sync)).map((o) => [o.name, o]));
380
+ } catch {}
381
+ if (after)
382
+ for (const [action, o] of sent) {
383
+ const d = after.get(o.name);
384
+ const same = d && d.size === o.size && (!o.etag || !d.etag || d.etag === o.etag);
385
+ if (same) continue;
386
+ totals[action === 'add' ? 'added' : 'updated']--;
387
+ totals.bytes -= o.size || 0;
388
+ fail(p.bucket, o.name, action, new CloudError(d ? `different on the target after the upload (${d.size} bytes there, ${o.size} here, or another checksum)` : 'missing on the target after the upload', { code: 'verify' }));
389
+ }
390
+ }
239
391
  } else {
240
392
  for (let i = 0; i < work.length; i += REF_BATCH) {
241
393
  const batch = work.slice(i, i + REF_BATCH);
@@ -258,20 +410,8 @@ async function sync(from, to, opts = {}) {
258
410
  });
259
411
  }
260
412
  }
261
- const names = p.remove.map((o) => o.name);
262
- for (let i = 0; i < names.length; i += 1000) {
263
- try {
264
- const rows = (await to.remove(p.bucket, names.slice(i, i + 1000))) || [];
265
- for (const r of rows) {
266
- totals.removed++;
267
- event({ bucket: p.bucket, name: r.name, action: 'remove' });
268
- }
269
- } catch (e) {
270
- for (const n of names.slice(i, i + 1000)) fail(p.bucket, n, 'remove', e);
271
- }
272
- }
273
413
  }
274
414
  return result;
275
415
  }
276
416
 
277
- module.exports = { sync, plan, decideMode, sameProject, locate, listObjects, sameContent, INTERNAL };
417
+ module.exports = { sync, plan, adaptive, retriable, backoff, copyBytes, decideMode, sameProject, locate, listObjects, sameContent, INTERNAL };