poad 2.76.4 → 2.78.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.
@@ -139,17 +139,22 @@ function run(direction, raw, deps = {}) {
139
139
  if (has('refs')) out.log(chalk.yellowBright(` ⚠ reference store not readable (${e.message}): refs left out.`));
140
140
  }
141
141
  }
142
- const refTargets = registry && Array.isArray(registry.items) ? registry.items.map((s) => s.target) : [];
142
+ // Une table de référence n'a qu'un chemin : refs (ou poad deploy pour les gros fichiers). Elle sort de la
143
+ // partie base, que refs fasse partie de la copie ou non : registre de poad.io ET fichiers de poad/reference
144
+ // (un gros fichier jamais envoyé n'est pas encore au registre : il le sera par cette poussée même)
145
+ const localRefs = require('../reference').files(root).map((f) => f.replace(/\.jsonl$/, ''));
146
+ const refTargets = [...new Set([...(registry && Array.isArray(registry.items) ? registry.items.map((s) => s.target) : []), ...localRefs])];
143
147
 
144
148
  // Code
145
- if (has('code')) preview.code = push ? await codePushPreview(env, opts, out) : await codePullPreview(id, env, poadDir, out, deps);
149
+ if (has('code')) preview.code = push ? await codePushPreview(env, opts, out, { id, poadDir, deps }) : await codePullPreview(id, env, poadDir, out, deps);
146
150
 
147
151
  // Base et comptes
148
152
  if (has('base')) preview.base = await basePlan(pg, P, container, src, dst, inv, { exclude: refTargets, only: sel.tables, code: preview.code, push });
149
153
  if (has('auth')) preview.auth = await authPreview(pg, P, container, src, dst, inv);
150
154
 
151
155
  // Références
152
- if (has('refs') && registry) preview.refs = await refsPreview(registry, env, poadDir, push, has('code'), push ? null : container);
156
+ const codeRuns = Boolean(has('code') && preview.code && preview.code.todo);
157
+ if (has('refs') && registry) preview.refs = await refsPreview(registry, env, poadDir, push, codeRuns, push ? null : container);
153
158
 
154
159
  // Fichiers du Stockage
155
160
  let storage = null;
@@ -159,7 +164,17 @@ function run(direction, raw, deps = {}) {
159
164
  }
160
165
 
161
166
  // Secrets : des noms seulement
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 };
167
+ if (has('secrets')) {
168
+ 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 };
169
+ // Un condensé de chaque côté (jamais une valeur) : déjà pareils, rien à copier
170
+ try {
171
+ const exclude = [...new Set([...(inv.src.storage_credentials || []), ...(inv.dst.storage_credentials || [])])];
172
+ const [a, b] = await Promise.all([pg.query(container, src, P.secretsDigestSql(inv.srcProbe, { exclude })), pg.query(container, dst, P.secretsDigestSql(inv.dstProbe, { exclude }))]);
173
+ preview.secrets.same = Boolean(String(a).trim()) && String(a).trim() === String(b).trim();
174
+ } catch {
175
+ preview.secrets.same = false;
176
+ }
177
+ }
163
178
 
164
179
  // Place sur la cible : ce qui sera écrit (base et comptes, fichiers) et ce qui sera libéré
165
180
  const amounts = spaceAmounts(preview, { clean });
@@ -197,7 +212,7 @@ function run(direction, raw, deps = {}) {
197
212
  const target = push ? cloudLabel : 'the local project';
198
213
  if (push && env.production) await strongConfirm(id, env, opts, out);
199
214
  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 });
200
- if (has('secrets')) {
215
+ if (has('secrets') && !preview.secrets.same) {
201
216
  const s = preview.secrets;
202
217
  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 });
203
218
  }
@@ -247,11 +262,11 @@ function run(direction, raw, deps = {}) {
247
262
 
248
263
  if (has('code') && preview.code && preview.code.todo) {
249
264
  const t0 = Date.now();
250
- const r = push ? await codePush(env, opts, out) : await codePull(env, opts, out, poadDir, preview.code, localStarted);
265
+ const r = push ? await codePush(env, opts, out, deps) : await codePull(env, opts, out, poadDir, preview.code, localStarted);
251
266
  results.code = r;
252
267
  note({ part: 'code', rows: r.count || 0, outcome: r.ok ? 'done' : 'failed', duration_ms: Date.now() - t0 });
253
268
  if (!r.ok) stop('code', r.error || 'code part failed');
254
- }
269
+ } else if (has('code') && preview.code) note({ part: 'code', outcome: 'skipped', duration_ms: 0 });
255
270
 
256
271
  if (!failed && (has('base') || has('auth'))) {
257
272
  // La structure a pu changer (partie code) : inventaire et différence refaits
@@ -282,18 +297,24 @@ function run(direction, raw, deps = {}) {
282
297
  }
283
298
  if (!r) r = await transferData(pg, P, container, src, dst, { base, auth, inv, sel, out });
284
299
  for (const l of r.lines) note(l);
300
+ if (has('base') && r.ok && !r.tables.some((t) => t.part === 'base')) note({ part: 'base', outcome: 'skipped', duration_ms: 0 });
301
+ if (has('auth') && r.ok && !r.tables.some((t) => t.part === 'auth')) note({ part: 'auth', outcome: 'skipped', duration_ms: 0 });
302
+ const dl = r.lines.find((l) => l.part === 'data');
303
+ if (dl && !out.json && dl.bytes && dl.duration_ms > 2000) out.log(chalk.grey(` base: ${P.size(dl.bytes)} in ${require('../progress').duration(dl.duration_ms / 1000)} (${P.size(dl.bytes_per_s)}/s)`));
285
304
  if (has('base')) results.base = { outcome: r.ok ? 'done' : 'failed', tables: r.tables.filter((t) => t.part === 'base'), error: r.ok ? undefined : r.error };
286
305
  if (has('auth')) results.auth = { outcome: r.ok ? 'done' : 'failed', tables: r.tables.filter((t) => t.part === 'auth'), error: r.ok ? undefined : r.error };
287
306
  if (!r.ok) failed = true;
288
307
  }
289
308
  }
290
309
 
291
- if (!failed && has('refs') && preview.refs) {
310
+ if (!failed && has('refs') && preview.refs && !preview.refs.todo) note({ part: 'refs', outcome: 'skipped', duration_ms: 0 });
311
+ if (!failed && has('refs') && preview.refs && preview.refs.todo) {
292
312
  const t0 = Date.now();
293
313
  try {
294
- const r = await refsApply(id, env, poadDir, preview.refs, push, opts, out, config, has('code'));
314
+ const r = await refsApply(id, env, poadDir, preview.refs, push, opts, out, config, codeRuns);
295
315
  results.refs = r;
296
- for (const t of r.tables || []) note({ part: 'refs', table: t.target, rows: t.rows, outcome: t.outcome, duration_ms: t.duration_ms });
316
+ for (const t of r.tables || []) note({ part: 'refs', table: t.target, rows: t.rows, bytes: t.bytes, bytes_per_s: t.bytes && t.send_ms ? require('../progress').rateOf(t.bytes, t.send_ms) : undefined, outcome: t.outcome, duration_ms: t.duration_ms });
317
+ note({ part: 'refs', outcome: r.failed ? 'failed' : 'done', bytes: (r.tables || []).reduce((x, t) => x + (t.bytes || 0), 0), duration_ms: Date.now() - t0 });
297
318
  if (r.failed) stop('refs', 'a reference table could not be loaded');
298
319
  } catch (e) {
299
320
  note({ part: 'refs', outcome: 'failed', duration_ms: Date.now() - t0 });
@@ -301,16 +322,19 @@ function run(direction, raw, deps = {}) {
301
322
  }
302
323
  }
303
324
 
325
+ if (!failed && has('s3') && preview.s3 && !preview.s3.todo) note({ part: 's3', outcome: 'skipped', duration_ms: 0 });
304
326
  if (!failed && has('s3') && preview.s3 && preview.s3.todo) {
305
327
  const t0 = Date.now();
306
328
  const r = await storagePlan(storage, false, out, { clean, concurrency: deps.concurrency, sleep: deps.sleep });
307
329
  results.s3 = r;
308
330
  for (const l of fileLines(r)) note(l);
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 });
331
+ note({ part: 's3', rows: r.totals.added + r.totals.updated + r.totals.removed, bytes: r.totals.bytes, bytes_per_s: require('../progress').rateOf(r.totals.bytes, Date.now() - t0), outcome: r.totals.failed ? 'failed' : 'done', duration_ms: Date.now() - t0 });
332
+ if (!out.json) out.log(`${r.totals.failed ? out.chalk.yellowBright('!') : out.chalk.greenBright('✔')} s3: ${n(r.totals.added)} added, ${n(r.totals.updated)} replaced, ${n(r.totals.removed)} removed, ${n(r.totals.unchanged)} unchanged${r.totals.bytes ? `, ${P.size(r.totals.bytes)} sent in ${require('../progress').duration((Date.now() - t0) / 1000)} (${P.size(require('../progress').rateOf(r.totals.bytes, Date.now() - t0))}/s)` : ''}`);
310
333
  if (r.totals.failed) stop('s3', `${r.totals.failed} file(s) failed`);
311
334
  }
312
335
 
313
- if (!failed && has('secrets')) {
336
+ if (!failed && has('secrets') && preview.secrets.same) note({ part: 'secrets', outcome: 'skipped', duration_ms: 0 });
337
+ if (!failed && has('secrets') && !preview.secrets.same) {
314
338
  const t0 = Date.now();
315
339
  const script = P.secretsScript({ srcFn: src.psql, dstFn: dst.psql, queries: P.secretsSql(inv.srcProbe, { targetStorage: inv.dst.storage_credentials }) });
316
340
  const r = await pg.transfer(container, src, dst, script);
@@ -347,10 +371,12 @@ async function inventories(pg, container, src, dst, P) {
347
371
  async function basePlan(pg, P, container, src, dst, inv, { exclude, only, code, push }) {
348
372
  const cmp = P.compareTables(inv.src.tables, inv.dst.tables, { exclude, only });
349
373
  const migrations = P.compareMigrations(inv.src.migrations, inv.dst.migrations);
350
- const items = cmp.tables.map((t) => ({ t, sql: P.diffable(t) ? P.hashSql(t) : P.countSql(t), exact: P.diffable(t) }));
374
+ // Petites tables : différence ligne à ligne (copie incrémentale possible) ; grandes : nombre de lignes et somme
375
+ // des empreintes, en un passage (identiques : sautées ; sinon réécrites en entier)
376
+ const items = cmp.tables.map((t) => ({ t, sql: P.diffable(t) ? P.hashSql(t) : P.aggSql(t), exact: P.diffable(t) }));
351
377
  const [a, b] = await Promise.all([batch(pg, container, src, items), batch(pg, container, dst, items)]);
352
378
  const tables = items.map((it, i) => {
353
- const d = it.exact ? P.diffHashes(a[i], b[i], Boolean(it.t.pk)) : { rows: Number(a[i]) || 0, target_rows: Number(b[i]) || 0, exact: false };
379
+ const d = it.exact ? P.diffHashes(a[i], b[i], Boolean(it.t.pk), { keys: true }) : P.diffAgg(a[i], b[i]);
354
380
  return { ...it.t, diff: d, changed: P.changed(d) };
355
381
  });
356
382
  const seqs = P.sequencesFor(inv.src.sequences, inv.dst.sequences, tables.map((t) => t.key), { all: !only });
@@ -377,14 +403,28 @@ const localHasData = (inv) => {
377
403
 
378
404
  const envArgs = (env, opts) => ['--env', env.branch, ...(opts.project ? ['--project', opts.project] : [])];
379
405
 
380
- async function codePushPreview(env, opts, out) {
381
- const r = await self(['deploy', ...envArgs(env, opts), '--dry-run', '--json'], { json: true });
406
+ async function codePushPreview(env, opts, out, { id, poadDir, deps = {} } = {}) {
407
+ const r = await (deps.self || self)(['deploy', ...envArgs(env, opts), '--dry-run', '--json'], { json: true });
382
408
  const d = r.data || {};
383
409
  if (d.error) return { ok: false, error: d.error.message, todo: true, structure: false };
384
410
  const m = d.migrations || {};
385
411
  const pending = (m.pending || []).length;
386
412
  const errors = (m.errors || []).map((e) => e.message || String(e));
387
- return { ok: r.code === 0, files: d.files || 0, bytes: d.bytes || 0, pending, pending_list: m.pending || [], errors, fix: d.fix || [], todo: true, structure: pending > 0, large_references: d.large_references || [] };
413
+ // Rien à redéployer : aucune migration en attente, même archive que le dernier déploiement réussi fait
414
+ // d'ici, et ce déploiement est toujours le dernier de l'environnement (utils/cloud/deploy-memo)
415
+ let same = null;
416
+ if (!pending && !errors.length && r.code === 0 && d.archive_sha256 && id && poadDir) {
417
+ const memo = require('../cloud/deploy-memo');
418
+ const last = memo.get(poadDir, id, env.branch);
419
+ if (last && last.archive_sha256 === d.archive_sha256) {
420
+ try {
421
+ const api = require('../cloud/api');
422
+ const list = await api.call('GET', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/deploys`, { what: 'deploys' });
423
+ if (memo.upToDate(last, d.archive_sha256, list.deploys)) same = { deploy_id: last.deploy_id, at: last.at };
424
+ } catch {}
425
+ }
426
+ }
427
+ return { ok: r.code === 0, files: d.files || 0, bytes: d.bytes || 0, archive_sha256: d.archive_sha256 || null, pending, pending_list: m.pending || [], errors, fix: d.fix || [], todo: !same, same, structure: pending > 0, large_references: d.large_references || [] };
388
428
  }
389
429
 
390
430
  async function codePullPreview(id, env, poadDir, out, deps) {
@@ -407,15 +447,16 @@ async function codePullPreview(id, env, poadDir, out, deps) {
407
447
  return { migrations: pull, conflicts: m.conflicts || [], unavailable: m.unavailable || [], files, error: error || (m.error && m.error.message) || null, todo, structure: pull.length > 0 };
408
448
  }
409
449
 
410
- async function codePush(env, opts, out) {
450
+ async function codePush(env, opts, out, deps = {}) {
451
+ const self_ = deps.self || self;
411
452
  const args = ['deploy', ...envArgs(env, opts), '--yes', ...(opts['allow-destructive'] || opts['accept-data-loss'] ? ['--allow-destructive'] : [])];
412
453
  if (out.json) {
413
- const r = await self([...args, '--json'], { json: true });
454
+ const r = await self_([...args, '--json'], { json: true });
414
455
  const d = r.data || {};
415
456
  return { ok: r.code === 0, changed: ((d.migrations || {}).applied || []).length > 0, count: ((d.migrations || {}).applied || []).length, deploy: d, error: r.code === 0 ? null : (d.error && d.error.message) || `poad deploy exit ${r.code}` };
416
457
  }
417
458
  out.log(out.chalk.bold('\n code: poad deploy'));
418
- const r = await self(args, { inherit: true });
459
+ const r = await self_(args, { inherit: true });
419
460
  return { ok: r.code === 0, changed: true, error: r.code === 0 ? null : `poad deploy exit ${r.code}` };
420
461
  }
421
462
 
@@ -456,31 +497,52 @@ async function transferData(pg, P, container, src, dst, { base, auth, inv, sel,
456
497
  const after = [];
457
498
  if (base) {
458
499
  for (const t of base.rewrite) {
459
- tables.push({ part: 'base', schema: t.schema, name: t.name, key: t.key, columns: t.columns, rows: t.diff.rows, bytes: t.bytes, diff: t.diff });
460
- clear.push(`delete from ${P.qname(t.schema, t.name)};`);
500
+ // Copie incrémentale (seulement les lignes ajoutées ou changées) quand la différence le permet
501
+ const w = P.rewriteOf(t);
502
+ const share = t.diff.rows ? Math.min(1, w.rows / t.diff.rows) : 1;
503
+ tables.push({ part: 'base', schema: t.schema, name: t.name, key: t.key, columns: t.columns, rows: w.rows, bytes: Math.round((t.bytes || 0) * share), diff: t.diff, where: w.where, mode: w.mode });
504
+ if (w.clear) clear.push(w.clear);
461
505
  }
462
506
  }
463
507
  if (auth && auth.changed) {
464
508
  clear.push(...auth.clear);
465
509
  after.push(...auth.after);
466
- for (const t of auth.tables) tables.push({ part: 'auth', schema: 'auth', name: t.name, key: t.key, columns: t.columns, rows: t.diff.rows, bytes: t.bytes, diff: t.diff });
510
+ for (const t of auth.tables) tables.push({ part: 'auth', schema: 'auth', name: t.name, key: t.key, columns: t.columns, rows: t.diff.rows, bytes: t.bytes, diff: t.diff, mode: 'full' });
467
511
  }
468
512
  const seqSql = base ? P.sequencesSql(base.sequences) : null;
469
513
  if (!tables.length && !seqSql) return { ok: true, lines: [], tables: [] };
470
514
  const script = P.transferScript({ srcFn: src.psql, dstFn: dst.psql, tables, clear, after, sequences: seqSql });
471
515
  const t0 = Date.now();
472
- const marks = {};
516
+ // Progression : une ligne par table (octets passés dans le tube, lignes, débit, temps restant)
517
+ const progress = require('../progress');
518
+ const sent = tables.map(() => ({ bytes: 0, lines: 0 }));
519
+ let cur = -1;
520
+ let bar = null;
521
+ const open = (i) => {
522
+ if (bar) bar.end();
523
+ const t = tables[i];
524
+ bar = progress.start({ label: t.key, phase: t.mode === 'rows' ? 'changed rows' : '', total: t.bytes || 0, rowsTotal: t.rows || 0, rows: 0, json: out.json, part: t.part, table: t.key });
525
+ };
473
526
  const r = await pg.transfer(container, src, dst, script, {
474
527
  onMarker: (l) => {
475
528
  const m = /^@@poad start (\d+) (\d+)/.exec(l);
476
- if (m) {
477
- marks[m[1]] = Number(m[2]);
478
- const t = tables[Number(m[1])];
479
- if (t && !out.json && process.stderr.isTTY) process.stderr.write(`\r\x1b[2K ${chalk.grey('copying')} ${t.key}…`);
480
- }
529
+ if (m && tables[Number(m[1])]) open((cur = Number(m[1])));
530
+ },
531
+ onData: (bytes, lines) => {
532
+ if (cur < 0) return;
533
+ const x = sent[cur];
534
+ x.bytes += bytes;
535
+ x.lines += lines;
536
+ // La première ligne d'une table est l'en-tête COPY
537
+ const t = tables[cur];
538
+ bar.update(x.bytes, { rows: Math.max(0, Math.min(t.rows || Infinity, x.lines - 1)) });
539
+ },
540
+ onSourceDone: () => {
541
+ if (bar) bar.end();
542
+ bar = progress.start({ label: 'base', phase: 'committing on the target (one transaction), then analyze', json: out.json, part: 'base', total: 0 });
481
543
  },
482
544
  });
483
- if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[2K');
545
+ if (bar) bar.end();
484
546
  const mk = P.parseMarkers(r.stderr);
485
547
  const ok = r.code === 0 && mk.rc === 0;
486
548
  const end = mk.done || Date.now();
@@ -488,20 +550,24 @@ async function transferData(pg, P, container, src, dst, { base, auth, inv, sel,
488
550
  const done = tables.map((t, i) => {
489
551
  const s = (mk.tables[i] || {}).start;
490
552
  const next = (mk.tables[i + 1] || {}).start || end;
491
- const res = { part: t.part, table: t.key, rows: t.rows, bytes: t.bytes || 0, duration_ms: s ? Math.max(0, next - s) : 0, outcome: ok ? 'done' : 'rolled_back', diff: t.diff };
492
- lines.push({ part: t.part, table: t.key, rows: t.rows, bytes: res.bytes, duration_ms: res.duration_ms, outcome: res.outcome });
553
+ // Octets réellement passés dans le tube (flux COPY), sinon l'estimation
554
+ const bytes = sent[i].bytes || t.bytes || 0;
555
+ const res = { part: t.part, table: t.key, rows: t.rows, bytes, duration_ms: s ? Math.max(0, next - s) : 0, outcome: ok ? 'done' : 'rolled_back', diff: t.diff, mode: t.mode };
556
+ lines.push({ part: t.part, table: t.key, rows: t.rows, bytes, duration_ms: res.duration_ms, bytes_per_s: progress.rateOf(bytes, res.duration_ms), outcome: res.outcome });
493
557
  if (!out.json) {
494
558
  const d = t.diff;
495
559
  const what = d.exact ? `+${n(d.added)} ~${n(d.replaced)} -${n(d.deleted)}` : `${n(d.target_rows)} → ${n(d.rows)}`;
496
- out.log(` ${ok ? chalk.greenBright('✔') : chalk.redBright('✕')} ${t.key} ${chalk.grey(`${what} ${n(t.rows)} rows, ${P.size(res.bytes)}${res.duration_ms ? `, ${(res.duration_ms / 1000).toFixed(1)} s` : ''}`)}`);
560
+ const rate = res.duration_ms > 1000 ? `, ${P.size(progress.rateOf(bytes, res.duration_ms))}/s` : '';
561
+ out.log(` ${ok ? chalk.greenBright('✔') : chalk.redBright('✕')} ${t.key} ${chalk.grey(`${what} ${n(t.rows)} row(s) ${t.mode === 'rows' ? 'sent (changed only)' : 'copied'}, ${P.size(bytes)}${res.duration_ms ? `, ${(res.duration_ms / 1000).toFixed(1)} s` : ''}${rate}`)}`);
497
562
  }
498
563
  return res;
499
564
  });
500
565
  if (base && base.sequences.length && ok && !out.json) out.log(chalk.grey(` ${base.sequences.length} sequence(s) set as on the source`));
501
566
  if (auth && auth.changed && ok && !out.json && auth.closed.length) out.log(chalk.grey(' sessions and refresh tokens of the target closed: accounts sign in again there'));
502
- const error = ok ? null : P.errorLine(mk.errors) || `exit ${r.code}`;
567
+ const error = ok ? null : r.stalled ? `no byte went through for ${Math.round(pg.stallMs ? pg.stallMs() / 1000 : 300)} s: connection lost or too slow (nothing changed on the target; run it again)` : P.errorLine(mk.errors) || `exit ${r.code}`;
503
568
  if (!ok) out.log(chalk.redBright(` ✕ data not copied, nothing changed on the target (one transaction): ${error}`));
504
- lines.push({ part: 'data', rows: tables.reduce((s, t) => s + (t.rows || 0), 0), bytes: done.reduce((s, t) => s + t.bytes, 0), duration_ms: Date.now() - t0, outcome: ok ? 'done' : 'rolled_back' });
569
+ const total = done.reduce((s, t) => s + t.bytes, 0);
570
+ lines.push({ part: 'data', rows: tables.reduce((s, t) => s + (t.rows || 0), 0), bytes: total, duration_ms: Date.now() - t0, bytes_per_s: progress.rateOf(total, Date.now() - t0), outcome: ok ? 'done' : 'rolled_back' });
505
571
  return { ok, lines, tables: done, error };
506
572
  }
507
573
 
@@ -547,7 +613,11 @@ async function refsApply(id, env, poadDir, plan, push, opts, out, config, withCo
547
613
  if (plan.large.length && !withCode) {
548
614
  const refStore = require('../reference-store');
549
615
  const r = await refStore.sendAndLoad(id, env.branch, poadDir, refStore.largeFiles(poadDir), opts, out);
550
- for (const t of r.tables) tables.push({ target: t.target, rows: t.rows || null, outcome: t.state === 'loaded' ? 'done' : t.state, duration_ms: 0 });
616
+ const steps = (r.load && r.load.steps) || [];
617
+ for (const t of r.tables) {
618
+ const st = steps.find((x) => x.target === t.target);
619
+ tables.push({ target: t.target, rows: t.rows || null, bytes: t.bytes || 0, send_ms: t.send_ms || 0, outcome: t.state === 'loaded' ? 'done' : t.state, duration_ms: (t.send_ms || 0) + ((st && st.duration_ms) || 0) });
620
+ }
551
621
  if (r.failed) return { tables, failed: true };
552
622
  }
553
623
  const rest = plan.load.filter((t) => !tables.some((x) => x.target === t));
@@ -588,9 +658,15 @@ async function storagePlan(st, dryRun, out, { clean = false, concurrency = 4, sl
588
658
  const ss = require('../storage-sync');
589
659
  const s = require('../storage');
590
660
  const P = require('./plan');
591
- const live = { failed: 0, retried: 0, shownRetries: 0 };
661
+ const live = { failed: 0, retried: 0, shownRetries: 0, listed: 0 };
592
662
  const resumes = [];
593
- const say = (line) => out && !out.json && out.log(line);
663
+ // Progression : fichiers et octets sur le total, débit, temps restant, fichier en cours ; les lignes de
664
+ // fichiers s'écrivent au-dessus (les 20 premières : au-delà, la barre et le bilan suffisent)
665
+ let bar = null;
666
+ let files = 0;
667
+ let bytesDone = 0;
668
+ const LISTED = 20;
669
+ const say = (line) => out && !out.json && (bar ? bar.log(line) : out.log(line));
594
670
  const r = await ss.sync(st.from, st.to, {
595
671
  prune: true,
596
672
  dryRun,
@@ -601,8 +677,17 @@ async function storagePlan(st, dryRun, out, { clean = false, concurrency = 4, sl
601
677
  fromLabel: st.fromT.label,
602
678
  toLabel: st.toT.label,
603
679
  confirm: async () => true,
680
+ onPlan: (pl) => {
681
+ if (dryRun || !out) return;
682
+ bar = require('../progress').start({ label: 's3', total: pl.mode === 'bytes' ? pl.bytes : 0, filesTotal: pl.files, json: out.json, part: 's3' });
683
+ },
684
+ onBytes: (d) => {
685
+ bytesDone += d;
686
+ if (bar) bar.update(bytesDone);
687
+ },
604
688
  onItem: (e) => {
605
689
  if (dryRun || !out) return;
690
+ if (e.action === 'start') return bar && bar.set({ file: `${e.bucket}/${e.name}` });
606
691
  const c = out.chalk;
607
692
  const where = `${e.bucket}${e.name ? `/${e.name}` : ''}`;
608
693
  if (e.action === 'resume') {
@@ -624,11 +709,19 @@ async function storagePlan(st, dryRun, out, { clean = false, concurrency = 4, sl
624
709
  else if (live.failed === 6) say(c.redBright(' ✖ more failures: see the summary at the end'));
625
710
  return;
626
711
  }
712
+ if (e.action === 'add' || e.action === 'update') {
713
+ files++;
714
+ if (bar) bar.update(undefined, { files });
715
+ }
627
716
  if (out.json) return;
628
717
  if (e.action === 'bucket') return say(` ${c.greenBright('+')} bucket ${e.bucket}`);
718
+ if (++live.listed > LISTED) {
719
+ if (live.listed === LISTED + 1) say(c.grey(' … the next files are counted, not listed (--json lists the totals; poad storage ls shows them)'));
720
+ return;
721
+ }
629
722
  say(` ${e.action === 'add' ? c.greenBright('+') : e.action === 'update' ? c.yellowBright('~') : c.redBright('-')} ${where}`);
630
723
  },
631
- });
724
+ }).finally(() => bar && bar.end());
632
725
  const t = r.totals;
633
726
  const sizes = (list, k = 'size') => list.reduce((m, o) => m + (Number.isFinite(o[k]) ? o[k] : 0), 0);
634
727
  const planned = r.buckets.reduce((acc, p) => acc + sizes(p.add) + sizes(p.update), 0);
@@ -703,7 +796,7 @@ function spaceAmounts(pv, { clean = false } = {}) {
703
796
  /** La sauvegarde n'a de sens que si la base va être écrite (lignes, comptes, secrets, migrations) */
704
797
  function dbWrites(pv, sel, push) {
705
798
  const has = (p) => sel.parts.includes(p);
706
- if (has('secrets')) return true;
799
+ if (has('secrets') && !(pv.secrets && pv.secrets.same)) return true;
707
800
  if (has('base') && pv.base && (pv.base.rewrite.length || pv.base.sequences.length)) return true;
708
801
  if (has('auth') && pv.auth && pv.auth.changed) return true;
709
802
  if (has('code') && pv.code) {
@@ -755,7 +848,7 @@ async function flushLogs({ api, id, env, rid, event, events, config, localStarte
755
848
  if (e.file) l.file = e.file;
756
849
  if (e.reason) l.reason = e.reason;
757
850
  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];
851
+ for (const k of ['rows', 'bytes', 'attempts', 'offset', 'bytes_per_s']) if (Number.isFinite(e[k])) l[k] = e[k];
759
852
  return l;
760
853
  });
761
854
  if (localStarted) {
@@ -799,7 +892,7 @@ function isNothing(pv, sel) {
799
892
  if (has('auth') && pv.auth && pv.auth.changed) return false;
800
893
  if (has('refs') && pv.refs && pv.refs.todo) return false;
801
894
  if (has('s3') && pv.s3 && pv.s3.todo) return false;
802
- if (has('secrets')) return false;
895
+ if (has('secrets') && !(pv.secrets && pv.secrets.same)) return false;
803
896
  return true;
804
897
  }
805
898
 
@@ -812,6 +905,7 @@ function printPreview(out, P, pv, { push, env, sel }) {
812
905
  const c = pv.code;
813
906
  if (push) {
814
907
  if (c.error) out.log(` ${pad('code')}${chalk.redBright(c.error)}`);
908
+ else if (c.same) out.log(` ${pad('code')}nothing to deploy: no migration pending, same ${c.files} file(s) as the last deploy from here ${chalk.grey(`(${c.same.deploy_id}, still the last one on ${env.branch})`)}`);
815
909
  else out.log(` ${pad('code')}poad deploy: ${c.files} file(s), ${c.pending} migration(s) to apply${c.pending_list && c.pending_list.length ? chalk.grey(` (${c.pending_list.slice(0, 5).join(', ')}${c.pending_list.length > 5 ? '…' : ''})`) : ''}`);
816
910
  for (const e of c.errors || []) out.log(` ${chalk.redBright('✕')} ${e}`);
817
911
  for (const f of c.fix || []) out.log(` ${chalk.grey('fix:')} ${chalk.cyanBright(f)}`);
@@ -830,12 +924,16 @@ function printPreview(out, P, pv, { push, env, sel }) {
830
924
  if (pv.base) {
831
925
  const b = pv.base;
832
926
  const same = b.tables.length - b.rewrite.length;
833
- out.log(` ${pad('base')}${b.tables.length} table(s): ${b.rewrite.length} to rewrite, ${same} identical${b.excluded.length ? chalk.grey(`, ${b.excluded.length} reference table(s) left to refs`) : ''}`);
927
+ out.log(` ${pad('base')}${b.tables.length} table(s): ${b.rewrite.length || b.blocked.length ? `${b.rewrite.length} to rewrite, ${same} identical` : 'all identical, nothing to copy'}${b.excluded.length ? chalk.grey(`; ${b.excluded.length} reference table(s) left to refs`) : ''}`);
834
928
  for (const t of b.rewrite) {
835
929
  const d = t.diff;
836
- const what = d.exact ? `${chalk.greenBright(`+${n(d.added)}`)} ${chalk.yellowBright(`~${n(d.replaced)}`)} ${chalk.redBright(`-${n(d.deleted)}`)}` : `${n(d.target_rows)} → ${n(d.rows)} rows (counts only: large table)`;
837
- out.log(` ${t.key.padEnd(30)} ${what} ${chalk.grey(`${n(d.rows)} rows, ${P.size(t.bytes)}`)}`);
930
+ const w = P.rewriteOf(t);
931
+ const what = d.exact ? `${chalk.greenBright(`+${n(d.added)}`)} ${chalk.yellowBright(`~${n(d.replaced)}`)} ${chalk.redBright(`-${n(d.deleted)}`)}` : `${n(d.target_rows)} → ${n(d.rows)} rows (large table: rewritten whole)`;
932
+ const how = w.mode === 'rows' ? `${n(w.rows)} row(s) to send of ${n(d.rows)}` : `${n(d.rows)} rows, ${P.size(t.bytes)}`;
933
+ out.log(` ${t.key.padEnd(30)} ${what} ${chalk.grey(how)}`);
838
934
  }
935
+ // Une table, un chemin : les tables de référence ne passent jamais par la partie base
936
+ for (const x of b.excluded) out.log(` ${chalk.grey(`${x.key}: reference table, goes through refs${sel.parts.includes('refs') ? '' : ' (left out here: --only refs to push it)'}`)}`);
839
937
  for (const x of b.blocked) out.log(` ${chalk.redBright('✕')} ${x.key}: ${x.detail}`);
840
938
  if (b.blocked.length) out.log(` ${b.structure_after_code ? chalk.grey('the code part runs first and brings the structure: checked again after it') : chalk.yellowBright(`structure first: ${push ? 'poad deploy (or --only code)' : 'poad migration pull, then poad migrate (or --only code)'}`)}`);
841
939
  if (b.migrations.missing.length) out.log(chalk.grey(` ${b.migrations.missing.length} migration(s) of the source not applied on the target${pv.code ? ' (code part)' : ''}`));
@@ -869,7 +967,8 @@ function printPreview(out, P, pv, { push, env, sel }) {
869
967
  }
870
968
  if (sel.parts.includes('secrets')) {
871
969
  const s = pv.secrets;
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(', ')})`) : ''}`);
970
+ if (s.same) out.log(` ${pad('secrets')}identical: ${s.variables.length} variable value(s), ${s.credentials.length} credential(s) ${chalk.grey('(compared by a digest, never shown)')}`);
971
+ else 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(', ')})`) : ''}`);
873
972
  } else out.log(chalk.grey(` ${'secrets'.padEnd(8)}left out (--with-secrets to copy variable values and credentials)`));
874
973
  if (pv.space) for (const [i, l] of roomLines(P, pv.space).entries()) out.log(i === 0 ? ` ${pad('room')}${l}` : ` ${l}`);
875
974
  }
@@ -908,7 +1007,7 @@ function resultOf({ direction, id, env, sel, dry, preview, blocking, events, sta
908
1007
  auth: pv.auth ? { changed: pv.auth.changed, tables: pv.auth.tables.map((t) => strip({ ...t, bytes: t.bytes, changed: pv.auth.changed })), dropped: pv.auth.dropped } : null,
909
1008
  refs: pv.refs,
910
1009
  s3: pv.s3,
911
- secrets: pv.secrets ? { variables: pv.secrets.variables.length, credentials: pv.secrets.credentials } : null,
1010
+ secrets: pv.secrets ? { variables: pv.secrets.variables.length, credentials: pv.secrets.credentials, same: Boolean(pv.secrets.same) } : null,
912
1011
  space: pv.space,
913
1012
  },
914
1013
  blocking,
@@ -182,39 +182,33 @@ async function sendAndLoad(id, branch, poadDir, files, opts, out, { dryRun = fal
182
182
  // Conversion puis envoi (contenu déjà au magasin : rien n'est renvoyé)
183
183
  const dir = S.tmpDir();
184
184
  try {
185
- let last = 0;
186
- const conv = await S.convertFile(f.abs, {
187
- format: 'jsonl',
188
- dir,
189
- onProgress: (read, total) => {
190
- if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
191
- last = Date.now();
192
- process.stderr.write(`\r ${chalk.grey('reading')} ${f.rel} ${Math.floor((read / total) * 100)}% `);
193
- }
194
- },
195
- });
196
- if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
185
+ const P = require('./progress');
186
+ const reading = P.start({ label: f.target, phase: 'reading', total: f.size, json: out.json, part: 'refs', table: f.target });
187
+ let conv;
188
+ try {
189
+ conv = await S.convertFile(f.abs, { format: 'jsonl', dir, onProgress: (read) => reading.update(read) });
190
+ } finally {
191
+ reading.end();
192
+ }
197
193
  const t = conv.tables[0];
198
194
  if (!t) throw new api.CloudError(`${f.rel}: no row`, { code: 'seed_empty' });
199
- let shown = 0;
200
- const r = await S.pushTable(id, t, {
201
- mode: 'reference',
202
- source: `poad/${f.rel}`,
203
- onProgress: (done, total) => {
204
- if (!out.json && process.stderr.isTTY && Date.now() - shown > 250) {
205
- shown = Date.now();
206
- process.stderr.write(`\r ${chalk.grey('sending')} ${t.target} ${S.fmt(done)} / ${S.fmt(total)} `);
207
- }
208
- },
209
- });
210
- if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
195
+ // Envoi au magasin : octets chiffrés envoyés sur le total, débit, temps restant
196
+ const sending = P.start({ label: t.target, phase: 'sending to the reference store', unit: 'bytes', json: out.json, part: 'refs', table: t.target });
197
+ const t0 = Date.now();
198
+ let r;
199
+ try {
200
+ r = await S.pushTable(id, t, { mode: 'reference', source: `poad/${f.rel}`, onProgress: (done, total) => sending.update(done, { total }) });
201
+ } finally {
202
+ sending.end();
203
+ }
204
+ if (r.uploaded) t.sent = { bytes: r.stored, duration_ms: Date.now() - t0 };
211
205
  cache[f.file] = { size: f.size, mtimeMs: f.mtimeMs, sha256: t.sha256, target: t.target };
212
206
  writeCache(poadDir, cache);
213
207
  // Contenu inchangé au magasin : il peut être déjà chargé (l'état lu dans la base le dit)
214
208
  const st = cloudState(registry, branch, t.target, t.sha256);
215
209
  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 });
210
+ out.log(`${loaded ? chalk.greenBright('✔') : chalk.yellow('○')} ${chalk.bold(t.target)} ${r.uploaded ? `sent to the reference store (${S.fmt(r.stored)} encrypted${t.sent ? ` in ${require('./progress').duration(t.sent.duration_ms / 1000)}, ${S.fmt(require('./progress').rateOf(r.stored, t.sent.duration_ms))}/s` : ''})` : 'already in the reference store'}${loaded ? `, already loaded in ${branch} ${chalk.grey(`(${n(st.rows)} rows, sha256 ${short(t.sha256)})`)}` : `, to load in ${branch}`}`);
211
+ tables.push({ target: t.target, action: 'sent', sha256: t.sha256, rows: t.rows, uploaded: r.uploaded, reason: st.state, bytes: r.uploaded ? r.stored : 0, send_ms: t.sent ? t.sent.duration_ms : 0 });
218
212
  if (!loaded) toLoad.push(t.target);
219
213
  } finally {
220
214
  fs.rmSync(dir, { recursive: true, force: true });
package/utils/seed/run.js CHANGED
@@ -110,7 +110,7 @@ async function pushTable(id, t, { mode, source, onProgress }) {
110
110
  const written = await encryptFile(t.file, enc, key(prep.key));
111
111
  if (written !== stored) throw new api.CloudError(`internal: encrypted size ${written} differs from ${stored}`);
112
112
  if (prep.upload.kind === 'single') {
113
- await putWithRetry(prep.upload.url, fs.readFileSync(enc));
113
+ await putWithRetry(prep.upload.url, fs.readFileSync(enc), { onSent: (n) => onProgress && onProgress(n, stored) });
114
114
  onProgress && onProgress(stored, stored);
115
115
  } else {
116
116
  const { part_size: size, urls, upload_id: uploadId } = prep.upload;
@@ -121,7 +121,8 @@ async function pushTable(id, t, { mode, source, onProgress }) {
121
121
  const len = Math.min(size, stored - i * size);
122
122
  const buf = Buffer.alloc(len);
123
123
  fs.readSync(fd, buf, 0, len, i * size);
124
- const etag = await putWithRetry(urls[i], buf);
124
+ // Octets de cette partie au fil de l'envoi : la progression avance même sur une partie de 32 Mo
125
+ const etag = await putWithRetry(urls[i], buf, { onSent: (n) => onProgress && onProgress(i * size + n, stored) });
125
126
  parts.push({ n: i + 1, etag });
126
127
  onProgress && onProgress(Math.min(stored, (i + 1) * size), stored);
127
128
  }
@@ -135,35 +136,80 @@ async function pushTable(id, t, { mode, source, onProgress }) {
135
136
  return { ...r, uploaded: !prep.exists, stored };
136
137
  }
137
138
 
138
- async function putWithRetry(url, buf, tries = 3) {
139
+ /** Délai sans aucun octet envoyé (ni réponse) avant de dire un envoi bloqué (POAD_STALL_TIMEOUT, s) */
140
+ const stallMs = () => {
141
+ const v = Number(process.env.POAD_STALL_TIMEOUT);
142
+ return Number.isFinite(v) && v > 0 ? v * 1000 : 5 * 60 * 1000;
143
+ };
144
+
145
+ /**
146
+ * PUT d'un morceau vers une URL signée, en flux de 64 Kio : onSent(octets) au fil de l'envoi. Délai
147
+ * d'INACTIVITÉ (une connexion lente qui avance n'est jamais coupée, une connexion figée l'est), puis attente
148
+ * de la réponse. Nouvelles tentatives sur coupure, délai ou 5xx : 1 s, 2 s, 4 s… (5 essais).
149
+ */
150
+ async function putWithRetry(url, buf, { tries = 5, onSent, stall = stallMs(), fetchImpl = fetch, sleep } = {}) {
151
+ const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
139
152
  let last;
140
153
  for (let i = 0; i < tries; i++) {
154
+ const ctl = new AbortController();
155
+ let timer = null;
156
+ const arm = () => {
157
+ clearTimeout(timer);
158
+ timer = setTimeout(() => ctl.abort(), stall);
159
+ };
160
+ let at = 0;
161
+ const body = new ReadableStream({
162
+ pull(c) {
163
+ if (at >= buf.length) return c.close();
164
+ const end = Math.min(buf.length, at + 64 * 1024);
165
+ c.enqueue(new Uint8Array(buf.buffer, buf.byteOffset + at, end - at));
166
+ at = end;
167
+ arm();
168
+ if (onSent) onSent(at);
169
+ },
170
+ });
171
+ arm();
141
172
  try {
142
- const res = await fetch(url, { method: 'PUT', body: buf, headers: { 'content-type': 'application/octet-stream' }, signal: AbortSignal.timeout(15 * 60 * 1000) });
173
+ const res = await fetchImpl(url, { method: 'PUT', body, duplex: 'half', headers: { 'content-type': 'application/octet-stream', 'content-length': String(buf.length) }, signal: ctl.signal });
174
+ clearTimeout(timer);
143
175
  if (res.ok) return res.headers.get('etag') || '';
144
176
  last = new Error(`storage refused the upload (HTTP ${res.status})`);
145
- if (res.status < 500) break;
177
+ if (res.status < 500 && res.status !== 408 && res.status !== 429) break;
146
178
  } catch (e) {
147
- last = e;
179
+ clearTimeout(timer);
180
+ last = ctl.signal.aborted ? new Error(`no progress for ${Math.round(stall / 1000)} s (connection lost or too slow)`) : e;
148
181
  }
149
- await new Promise((r) => setTimeout(r, 1000 * (i + 1)));
182
+ if (onSent) onSent(0);
183
+ if (i < tries - 1) await wait(Math.min(30000, 1000 * 2 ** i));
150
184
  }
151
185
  throw new api.CloudError(`Upload failed: ${last && last.message}`, { code: 'seed_upload_failed' });
152
186
  }
153
187
 
154
188
  /** Attend la fin d'un chargement hébergé ; onStep à chaque changement */
155
- async function waitLoad(id, loadId, { onStep, interval = 2000, timeout = 60 * 60 * 1000 } = {}) {
189
+ async function waitLoad(id, loadId, { onStep, interval = 2000, timeout = 4 * 60 * 60 * 1000, unreachable = 5 * 60 * 1000 } = {}) {
156
190
  const until = Date.now() + timeout;
157
191
  let seen = '';
192
+ let lost = null;
158
193
  for (;;) {
159
- const l = await api.call('GET', `v1/projects/${api.enc(id)}/seeds/loads/${api.enc(loadId)}`, { what: 'seed load' });
194
+ let l;
195
+ try {
196
+ l = await api.call('GET', `v1/projects/${api.enc(id)}/seeds/loads/${api.enc(loadId)}`, { what: 'seed load' });
197
+ lost = null;
198
+ } catch (e) {
199
+ // Connexion qui saute pendant que poad.io charge : le chargement continue là-bas, on redemande
200
+ if (e.code !== 'network_error') throw e;
201
+ lost = lost || Date.now();
202
+ if (Date.now() - lost > unreachable) throw new api.CloudError(`poad.io unreachable for ${Math.round(unreachable / 60000)} min while it loads the references (${e.message}); the load goes on there: "poad ref ls" shows it.`, { code: 'network_error' });
203
+ await new Promise((r) => setTimeout(r, interval));
204
+ continue;
205
+ }
160
206
  const sig = JSON.stringify(l.steps.map((s) => s.status));
161
207
  if (sig !== seen) {
162
208
  seen = sig;
163
209
  onStep && onStep(l);
164
210
  }
165
211
  if (l.status !== 'running') return l;
166
- if (Date.now() > until) throw new api.CloudError('Still loading after an hour: "poad seed ls" shows the progress.', { code: 'timeout' });
212
+ if (Date.now() > until) throw new api.CloudError('Still loading after 4 hours: "poad ref ls" shows the progress.', { code: 'timeout' });
167
213
  await new Promise((r) => setTimeout(r, interval));
168
214
  }
169
215
  }
@@ -276,4 +322,4 @@ function localEdges(container) {
276
322
  });
277
323
  }
278
324
 
279
- module.exports = { convertFile, pushTable, waitLoad, loadLocal, loadLocalFile, localState, localLog, localEdges, fmt, tmpDir };
325
+ module.exports = { convertFile, pushTable, putWithRetry, waitLoad, loadLocal, loadLocalFile, localState, localLog, localEdges, fmt, tmpDir };