poad 2.77.0 → 2.78.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.
@@ -99,7 +99,7 @@ test('authPlan: common columns, columns lost, sessions closed before accounts, t
99
99
  });
100
100
 
101
101
  test('transferScript: one target transaction, replica role, one consistent source snapshot, quoted names, stop on error', () => {
102
- const s = P.transferScript({ srcFn: 'SRC', dstFn: 'DST', tables: [{ schema: 'public', name: "l'o", columns: ['a', 'b'] }], clear: ['delete from "public"."l\'o";'], sequences: 'select 1' });
102
+ const { produce: s, consume } = P.transferScript({ srcFn: 'SRC', dstFn: 'DST', tables: [{ schema: 'public', name: "l'o", columns: ['a', 'b'] }], clear: ['delete from "public"."l\'o";'], sequences: 'select 1' });
103
103
  assert.match(s, /set -o pipefail/);
104
104
  assert.match(s, /printf '%s\\n' 'begin;'/);
105
105
  assert.match(s, /session_replication_role = replica/);
@@ -107,7 +107,7 @@ test('transferScript: one target transaction, replica role, one consistent sourc
107
107
  assert.match(s, /\\echo 'COPY "public"\."l''o" \("a", "b"\) FROM stdin;'/);
108
108
  assert.match(s, /COPY \(select "a", "b" from "public"\."l'o"\) TO STDOUT;/);
109
109
  assert.match(s, /\\echo '\\\\\.'/);
110
- assert.match(s, /\| dst -v ON_ERROR_STOP=1/);
110
+ assert.strictEqual(consume, 'DST -v ON_ERROR_STOP=1 > /dev/null');
111
111
  assert.ok(s.indexOf("'commit;'") > s.indexOf('POAD_SRC_EOF\n printf'), 'commit after the source');
112
112
  assert.ok(!/PGPASSWORD=/.test(s), 'no password in the script');
113
113
  });
@@ -122,6 +122,31 @@ test('secretsSql: storage credentials kept on both sides, nothing read from the
122
122
  assert.match(sh, /src -v ON_ERROR_STOP=1 -tA -c 'select 1' 2> \/dev\/null \| dst -v ON_ERROR_STOP=1 > \/dev\/null 2>&1/);
123
123
  });
124
124
 
125
+ test('OAuth authorizations: never copied (base, secrets, auth), named in the plan', () => {
126
+ // Rien ne lit ni n'écrit _poad.oauth_tokens ni les secrets oauth.* : _poad est système, --with-secrets ne prend que credential.%
127
+ assert.ok(P.SYSTEM_SCHEMAS.includes('_poad') && P.SYSTEM_SCHEMAS.includes('vault'));
128
+ const q = P.secretsSql({ variables: true, credentials: true, vault: true, oauth: true }, { targetStorage: [] }).join('\n');
129
+ assert.doesNotMatch(q, /oauth/i);
130
+ assert.match(q, /name like 'credential\.%'/);
131
+ assert.doesNotMatch(P.secretsDigestSql({ variables: true, credentials: true, vault: true, oauth: true }), /oauth/i);
132
+ // L'inventaire n'en lit que des noms et des nombres
133
+ const inv = P.inventorySql({ oauth: true, auth: [] });
134
+ assert.match(inv, /'oauth', \(select coalesce\(json_agg\(json_build_object\('connection', connection, 'project', project, 'users', users\)/);
135
+ assert.doesNotMatch(inv, /decrypted_secret|oauth_get|vault\./);
136
+ assert.match(P.inventorySql({}), /'oauth', '\[\]'::json/);
137
+ const lines = P.oauthPlan(
138
+ [{ connection: 'todoist', project: true, users: 2 }, { connection: 'agenda', project: true, users: 0 }, { connection: 'notion@mcp', project: false, users: 1 }],
139
+ [{ connection: 'agenda', project: true, users: 0 }, { connection: 'todoist', project: false, users: 5 }],
140
+ );
141
+ assert.deepStrictEqual(lines.map((l) => l.text), [
142
+ 'OAuth connection todoist: authorize again on the target',
143
+ 'OAuth connection todoist: 2 user account(s) connected here, never copied: each user connects again on the target',
144
+ 'OAuth connection agenda: the target keeps its own authorization (never copied)',
145
+ 'OAuth connection notion (MCP server): 1 user account(s) connected here, never copied: each user connects again on the target',
146
+ ]);
147
+ assert.deepStrictEqual(P.oauthPlan([], [{ connection: 'x', project: true, users: 1 }]), []);
148
+ });
149
+
125
150
  test('parseMarkers and errorLine: timings, exit code, the ERROR line only (never CONTEXT, which quotes rows)', () => {
126
151
  const m = P.parseMarkers('@@poad start 0 1000\n@@poad start 1 1500\npsql:<stdin>:9: ERROR: duplicate key value\nCONTEXT: COPY t, line 1: "secret row"\n@@poad done 2000 3\n');
127
152
  assert.deepStrictEqual(m.tables, { 0: { start: 1000 }, 1: { start: 1500 } });
@@ -164,6 +189,7 @@ function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, eve
164
189
  if (/\/branches$/.test(req.url)) return send(200, [{ name: 'main', kind: 'production' }, { name: 'dev' }]);
165
190
  if (/\/seeds(\?.*)?$/.test(req.url)) return send(200, { store: true, items: [{ target: 'ref.communes', sha256: 'aa', rows: 5 }], applied: { dev: { 'ref.communes': { sha256: 'aa' } } }, quota: {}, loads: [] });
166
191
  if (/\/sync-plan$/.test(req.url)) return send(200, { space });
192
+ if (/\/deploys$/.test(req.url)) return send(200, { deploys: [{ deploy_id: 'dep-1', outcome: 'success', dry_run: false }] });
167
193
  if (/\/backup$/.test(req.url)) return send(200, { file: 'pre-deploy-20261205-000000.dump', bytes: 1234 });
168
194
  if (/\/sync-events$/.test(req.url)) {
169
195
  // poad.io d'avant la 2.76.1 : refuse les lignes par fichier
@@ -181,10 +207,13 @@ function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, eve
181
207
  }
182
208
 
183
209
  /** Fausse base : inventaires de la source et de la cible, empreintes, transfert enregistré */
184
- function fakePg(scripts, { same = false, queries = [] } = {}) {
210
+ function fakePg(scripts, { same = false, queries = [], state = null, extraTables = [] } = {}) {
185
211
  const real = require('../utils/project-sync/pg');
212
+ // state : la cible devient le miroir après un transfert réussi (state.base, state.secrets) ; state.cut : le
213
+ // prochain transfert de la base est coupé (tube figé : rien n'arrive sur la cible)
214
+ const isSame = () => same || Boolean(state && state.base);
186
215
  const inv = (rows) => ({
187
- tables: [tbl('public', 'livres', [col('id', 'integer'), col('titre')], { pk: ['id'] }), tbl('ref', 'communes', [col('id', 'integer')])],
216
+ tables: [tbl('public', 'livres', [col('id', 'integer'), col('titre')], { pk: ['id'] }), tbl('ref', 'communes', [col('id', 'integer')]), ...extraTables],
188
217
  sequences: [{ schema: 'public', name: 'livres_id_seq', owner: 'public.livres', last: rows }],
189
218
  migrations: ['20261205100000'],
190
219
  auth: { users: { rows: 1, bytes: 10, pk: ['id'], columns: [col('id', 'uuid'), col('email')] } },
@@ -195,9 +224,11 @@ function fakePg(scripts, { same = false, queries = [] } = {}) {
195
224
  return {
196
225
  localSide: real.localSide,
197
226
  cloudSide: real.cloudSide,
198
- json: async (container, side, sql) => (sql === P.PROBE_SQL ? { history: true, variables: true, credentials: true, vault: true, auth: ['users'] } : inv(side.kind === 'local' || same ? 3 : 2)),
227
+ json: async (container, side, sql) => (sql === P.PROBE_SQL ? { history: true, variables: true, credentials: true, vault: true, auth: ['users'] } : inv(side.kind === 'local' || isSame() ? 3 : 2)),
199
228
  query: async (container, side, sql) => {
200
229
  queries.push(sql);
230
+ // Condensé des secrets : pareil une fois copiés
231
+ if (/^select md5\(/.test(sql)) return side.kind === 'local' || (state && state.secrets) ? 'd1g3st\n' : 'other\n';
201
232
  // Empreintes : la source a trois livres, la cible deux (un remplacé) ; un compte identique
202
233
  const local = side.kind === 'local';
203
234
  const parts = sql.split(/\\echo @@T (\d+)\n/).filter(Boolean);
@@ -205,22 +236,34 @@ function fakePg(scripts, { same = false, queries = [] } = {}) {
205
236
  for (let i = 0; i < parts.length; i += 2) {
206
237
  out += `@@T ${parts[i]}\n`;
207
238
  if (/"auth"\."users"/.test(parts[i + 1])) out += 'u1 h\n';
208
- else out += local || same ? 'k1 a\nk2 b\nk3 c\n' : 'k1 a\nk2 X\n';
239
+ else out += local || isSame() ? 'k1 a\nk2 b\nk3 c\n' : 'k1 a\nk2 X\n';
209
240
  }
210
241
  return out;
211
242
  },
212
243
  transfer: async (container, src, dst, script) => {
213
- scripts.push(script);
244
+ scripts.push(typeof script === 'string' ? script : script.produce);
245
+ if (state && typeof script === 'string') state.secrets = true;
246
+ if (state && typeof script !== 'string') {
247
+ if (state.cut) {
248
+ state.cut = false;
249
+ return { code: 124, stalled: true, stdout: Buffer.alloc(0), stderr: '@@poad start 0 1000\nno byte went through\n@@poad done 1200 124\n' };
250
+ }
251
+ state.base = true;
252
+ }
214
253
  return { code: 0, stdout: Buffer.alloc(0), stderr: '@@poad start 0 1000\n@@poad done 1200 0\n' };
215
254
  },
216
255
  dumpLocal: async () => 10,
217
256
  };
218
257
  }
219
258
 
220
- async function runCmd(t, args, { tty = false, deps = {}, cloud = {}, pg = {} } = {}) {
221
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-pp-'));
222
- t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
223
- fs.mkdirSync(path.join(dir, 'poad'));
259
+ async function runCmd(t, args, { tty = false, deps = {}, cloud = {}, pg = {}, dir: given = null, files = {} } = {}) {
260
+ const dir = given || fs.mkdtempSync(path.join(os.tmpdir(), 'poad-pp-'));
261
+ if (!given) t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
262
+ fs.mkdirSync(path.join(dir, 'poad'), { recursive: true });
263
+ for (const [rel, body] of Object.entries(files)) {
264
+ fs.mkdirSync(path.dirname(path.join(dir, 'poad', rel)), { recursive: true });
265
+ fs.writeFileSync(path.join(dir, 'poad', rel), body);
266
+ }
224
267
  fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), 'project_id = "t"\nproject_uuid = "ppuuid1"\nengine = "0.73.1"\n[db]\nport = 1\n[web]\nport = 2\n[cloud]\nproject = "pptest123456"\n');
225
268
  const seen = [];
226
269
  const scripts = [];
@@ -242,7 +285,7 @@ async function runCmd(t, args, { tty = false, deps = {}, cloud = {}, pg = {} } =
242
285
  ...deps,
243
286
  credentials: async () => ({ user: 'postgres.pptest123456--dev', password: 'pw-never-shown', host: 'db.poad.io', port: () => 5432 }),
244
287
  });
245
- return { code: process.exitCode, out: printed.join('\n'), seen, scripts };
288
+ return { code: process.exitCode, out: printed.join('\n'), seen, scripts, dir };
246
289
  } finally {
247
290
  process.stdin.isTTY = isTTY;
248
291
  process.chdir(saved.cwd);
@@ -290,7 +333,7 @@ test('poad push to production with --yes --confirm: backup first, one transfer,
290
333
  assert.match(r.scripts[0], /setval/);
291
334
  const ev = JSON.parse(r.seen.find((s) => /sync-events/.test(s.url)).body);
292
335
  assert.strictEqual(ev.event, 'project_push');
293
- assert.deepStrictEqual(ev.lines.map((l) => [l.part, l.table || null, l.outcome]), [['backup', null, 'done'], ['base', 'public.livres', 'done'], ['data', null, 'done'], ['all', null, 'done']]);
336
+ assert.deepStrictEqual(ev.lines.map((l) => [l.part, l.table || null, l.outcome]), [['backup', null, 'done'], ['base', 'public.livres', 'done'], ['data', null, 'done'], ['auth', null, 'skipped'], ['all', null, 'done']]);
294
337
  assert.strictEqual(ev.lines[1].rows, 3);
295
338
  assert.ok(!JSON.stringify(ev).includes('pw-never-shown'));
296
339
  });
@@ -411,3 +454,88 @@ test('poad push to production: no backup when the base has nothing to write (a r
411
454
  assert.ok(!r.seen.some((x) => /\/backup$/.test(x.url)), 'no backup');
412
455
  assert.strictEqual(r.scripts.length, 0, 'nothing written in the base');
413
456
  });
457
+
458
+ // --- 2.78.0 : un seul chemin par donnée, poussée incrémentale et idempotente, reprise -------------------------
459
+
460
+ test('poad push: a reference table of poad/reference is never copied by the base part, even before it is in the registry', async (t) => {
461
+ const commune = tbl('public', 'commune', [col('id', 'integer'), col('nom')], { pk: ['id'], estimate: 35247, bytes: 525e6 });
462
+ for (const only of ['base', 'base,refs']) {
463
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', only, '--yes'], { files: { 'reference/public.commune.jsonl': '{"id":1,"nom":"A"}\n' }, pg: { extraTables: [commune] } });
464
+ assert.strictEqual(r.code, 0, r.out);
465
+ const plain = r.out.replace(/\x1b\[[0-9;]*m/g, '');
466
+ assert.match(plain, /public\.commune: reference table, goes through refs/);
467
+ if (only === 'base') assert.match(plain, /left out here: --only refs to push it/);
468
+ for (const sc of r.scripts) assert.ok(!/"public"\."commune"/.test(sc), 'commune never in the base transfer');
469
+ }
470
+ });
471
+
472
+ /** Un projet complet, deux côtés : code, base, comptes, références, fichiers, secrets */
473
+ async function fullProject(t) {
474
+ const { local, cloud, deps } = await sides(t);
475
+ local.put('docs', 'a.txt', 'premier');
476
+ local.put('docs', 'b.bin', Buffer.alloc(200 * 1024, 3));
477
+ const calls = [];
478
+ deps.self = async (args) => {
479
+ calls.push(args.join(' '));
480
+ // poad deploy : archive reproductible ; le vrai deploy note son dernier déploiement réussi
481
+ if (args.includes('--dry-run')) return { code: 0, data: { files: 3, bytes: 900, archive_sha256: 'abc123', migrations: { pending: [], errors: [] } } };
482
+ require('../utils/cloud/deploy-memo').record(path.join(process.cwd(), 'poad'), 'pptest123456', 'dev', { deploy_id: 'dep-1', archive_sha256: 'abc123' });
483
+ return { code: 0, data: { migrations: { applied: [] } } };
484
+ };
485
+ return { local, cloud, deps, calls, state: {} };
486
+ }
487
+
488
+ test('poad push twice in a row: the second one transfers nothing and says so, part by part', async (t) => {
489
+ const p = await fullProject(t);
490
+ const args = ['push', '--env', 'dev', '--with-secrets', '--yes', '--json'];
491
+ const first = await runCmd(t, args, { deps: p.deps, pg: { state: p.state } });
492
+ assert.strictEqual(first.code, 0, first.out);
493
+ const j1 = JSON.parse(first.out.slice(first.out.indexOf('{\n')));
494
+ assert.ok(j1.results.code && j1.results.base && j1.results.secrets && j1.results.s3, JSON.stringify(Object.keys(j1.results)));
495
+ assert.strictEqual(p.cloud.objects.size, 2);
496
+ const putsAfterFirst = p.cloud.stats.put + p.cloud.stats.patchBytes;
497
+
498
+ const second = await runCmd(t, args, { deps: p.deps, pg: { state: p.state }, dir: first.dir });
499
+ t.after(() => fs.rmSync(first.dir, { recursive: true, force: true }));
500
+ assert.strictEqual(second.code, 0, second.out);
501
+ const j2 = JSON.parse(second.out.slice(second.out.indexOf('{\n')));
502
+ assert.strictEqual(j2.preview.code.todo, false, 'same archive as the last deploy, still the last one');
503
+ assert.deepStrictEqual(j2.preview.base.tables.filter((x) => x.rewrite), []);
504
+ assert.strictEqual(j2.preview.auth.changed, false);
505
+ assert.strictEqual(j2.preview.refs.todo, false);
506
+ assert.strictEqual(j2.preview.s3.todo, false);
507
+ assert.strictEqual(j2.preview.secrets.same, true);
508
+ assert.strictEqual(j2.results, null, 'nothing run');
509
+ assert.strictEqual(second.scripts.length, 0, 'no transfer');
510
+ assert.strictEqual(p.cloud.stats.put + p.cloud.stats.patchBytes, putsAfterFirst, 'no file sent');
511
+ assert.strictEqual(p.calls.filter((c) => !c.includes('--dry-run')).length, 1, 'one real deploy only, by the first push');
512
+
513
+ // En texte : « rien à faire » dit pour chaque partie
514
+ const third = await runCmd(t, ['push', '--env', 'dev', '--with-secrets', '--yes'], { deps: p.deps, pg: { state: p.state }, dir: first.dir });
515
+ const plain = third.out.replace(/\x1b\[[0-9;]*m/g, '');
516
+ assert.match(plain, /code\s+nothing to deploy/);
517
+ assert.match(plain, /base\s+\d+ table\(s\): all identical, nothing to copy/);
518
+ assert.match(plain, /secrets\s+identical/);
519
+ assert.match(plain, /Nothing to copy: the target is already the mirror of the source/);
520
+ });
521
+
522
+ test('poad push cut in the middle of the base, then run again: what arrived is skipped, the rest goes', async (t) => {
523
+ const p = await fullProject(t);
524
+ p.state.cut = true;
525
+ const args = ['push', '--env', 'dev', '--yes', '--json'];
526
+ const first = await runCmd(t, args, { deps: p.deps, pg: { state: p.state } });
527
+ t.after(() => fs.rmSync(first.dir, { recursive: true, force: true }));
528
+ assert.strictEqual(first.code, 5, first.out);
529
+ const j1 = JSON.parse(first.out.slice(first.out.indexOf('{\n')));
530
+ assert.strictEqual(j1.results.base.outcome, 'failed');
531
+ assert.match(j1.results.base.error, /no byte went through/);
532
+ assert.strictEqual(j1.results.s3, undefined, 'the push stops at the first failed part');
533
+
534
+ const again = await runCmd(t, args, { deps: p.deps, pg: { state: p.state }, dir: first.dir });
535
+ assert.strictEqual(again.code, 0, again.out);
536
+ const j2 = JSON.parse(again.out.slice(again.out.indexOf('{\n')));
537
+ assert.strictEqual(j2.preview.code.todo, false, 'the code deployed by the first run is not deployed again');
538
+ assert.strictEqual(j2.results.base.outcome, 'done');
539
+ assert.strictEqual(j2.results.s3.totals.added, 2);
540
+ assert.strictEqual(p.calls.filter((c) => !c.includes('--dry-run')).length, 1);
541
+ });
@@ -0,0 +1,181 @@
1
+ // poad push (CLI 2.78.0) : progression, copie incrémentale, empreinte des grandes tables, condensé des secrets,
2
+ // tube compté et coupé quand il ne bouge plus.
3
+ const test = require('node:test');
4
+ const assert = require('node:assert');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const P = require('../utils/project-sync/plan');
9
+ const progress = require('../utils/progress');
10
+ const memo = require('../utils/cloud/deploy-memo');
11
+
12
+ const plain = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
13
+
14
+ test('progress line: bar, percent, rows, bytes, rate, ETA, file; two spaces between items, never glued', () => {
15
+ const l = progress.line({ label: 'public.commune', done: 251.2 * 1024 ** 2, total: 525.9 * 1024 ** 2, unit: 'bytes', rows: 12345, rowsTotal: 35247, rate: 1.2 * 1024 ** 2, eta: 220 });
16
+ assert.match(l, /^ {2}public\.commune {2}[█░]{20} {2} 35 % {2}12,345 \/ 35,247 rows {2}251\.2 MB sent {2}1\.2 MB\/s {2}ETA 3 min 40 s$/);
17
+ const s3 = progress.line({ label: 's3', done: 10, total: 100, files: 3, filesTotal: 12629, rate: 0, file: 'docs/a.pdf', elapsed: 4 });
18
+ assert.match(s3, /3 \/ 12,629 files {2}10 B \/ 100 B {2}4 s {2}docs\/a\.pdf$/);
19
+ assert.ok(!/\S {3,}\S/.test(l.replace(/ +\d+ %/, ' %')), 'no wide gap');
20
+ assert.ok(!/[A-Za-z0-9)][█░]|[█░][A-Za-z0-9(]/.test(l), 'the bar is never glued to text');
21
+ // Trop large pour le terminal : le fichier est raccourci, la ligne tient
22
+ const narrow = progress.line({ label: 's3', done: 1, total: 2, file: 'x'.repeat(200) }, { width: 80 });
23
+ assert.ok(narrow.length < 80, narrow);
24
+ assert.strictEqual(progress.duration(3725), '1 h 02 min');
25
+ });
26
+
27
+ test('progress: nothing before 2 s, then at most 4 redraws a second on a terminal; JSON events every 5 s with --json', () => {
28
+ let t = 0;
29
+ const writes = [];
30
+ const stream = { isTTY: true, columns: 120, write: (s) => writes.push(s) };
31
+ const p = progress.start({ label: 'x', total: 1000, stream, now: () => t, tick: false });
32
+ for (; t < 1900; t += 50) p.update(t / 10);
33
+ assert.strictEqual(writes.length, 0, 'short transfers show nothing');
34
+ for (; t < 4000; t += 50) p.update(t / 10);
35
+ assert.ok(writes.length >= 7 && writes.length <= 9, `${writes.length} redraws in 2 s`);
36
+ assert.match(plain(writes[writes.length - 1]), /\r?.*x {2}[█░]+ {2} *\d+ %/);
37
+ p.end();
38
+ assert.strictEqual(writes[writes.length - 1], '\r\x1b[2K', 'the line is cleared at the end');
39
+
40
+ const js = [];
41
+ t = 0;
42
+ const q = progress.start({ label: 'base', total: 100, json: true, part: 'base', table: 'public.a', stream: { isTTY: false, write: (s) => js.push(s) }, now: () => t, tick: false });
43
+ for (; t <= 12000; t += 100) q.update(t / 200);
44
+ q.end();
45
+ assert.ok(js.length >= 2 && js.length <= 3, String(js.length));
46
+ const ev = JSON.parse(js[0]);
47
+ assert.deepStrictEqual([ev.event, ev.part, ev.table, ev.unit], ['progress', 'base', 'public.a', 'bytes']);
48
+
49
+ // Hors terminal (fichier, CI) et sans --json : pas de barre, des lignes simples espacées de 15 s, sans couleur
50
+ const lines = [];
51
+ t = 0;
52
+ const r = progress.start({ label: 'public.commune', total: 40000, stream: { isTTY: false, write: (s) => lines.push(s) }, now: () => t, tick: false });
53
+ for (; t < 1900; t += 100) r.update(t);
54
+ assert.strictEqual(lines.length, 0, 'short transfers say nothing');
55
+ for (; t <= 33000; t += 100) r.update(t);
56
+ r.end();
57
+ assert.strictEqual(lines.length, 3, lines.join(''));
58
+ for (const l of lines) {
59
+ assert.ok(l.endsWith('\n') && !l.includes('\r') && !l.includes('\x1b') && !/[█░]/.test(l), JSON.stringify(l));
60
+ assert.match(l, /^ {2}public\.commune {2}\d+ % {2}[\d.]+ KB \/ 39\.1 KB/);
61
+ }
62
+ });
63
+
64
+ test('diffHashes keys and rewriteOf: few changes → only those rows (delete by key, copy by key); many → whole table', () => {
65
+ const src = Array.from({ length: 10 }, (_, i) => `${String(i).padStart(32, 'a')} h${i}`).join('\n');
66
+ const dst = Array.from({ length: 10 }, (_, i) => `${String(i).padStart(32, 'a')} h${i === 3 ? 'X' : i}`).filter((_, i) => i !== 9).join('\n') + `\n${'f'.repeat(32)} old`;
67
+ const d = P.diffHashes(src, dst, true, { keys: true });
68
+ assert.deepStrictEqual([d.added, d.replaced, d.deleted, d.unchanged], [1, 1, 1, 8]);
69
+ assert.deepStrictEqual(Object.keys(d).includes('keys'), false, 'keys never in the JSON output');
70
+ const t = { schema: 'public', name: 'livres', pk: ['id'], columns: ['id', 'titre'], diff: d };
71
+ const w = P.rewriteOf(t);
72
+ assert.strictEqual(w.mode, 'rows');
73
+ assert.strictEqual(w.rows, 2);
74
+ assert.match(w.clear, /^delete from "public"\."livres" where md5\(row\("id"\)::text\) = any\('\{[0-9a]{32},f{32}\}'::text\[\]\);$/);
75
+ assert.match(w.where, /^md5\(row\("id"\)::text\) = any\('\{[0-9a]{32},[0-9a]{32}\}'::text\[\]\)$/);
76
+ // Le même calcul que l'empreinte de la différence
77
+ assert.ok(P.hashSql(t).startsWith(`select ${P.keyHashSql(['id'])}`));
78
+ const s = P.transferScript({ srcFn: 'S', dstFn: 'D', tables: [{ ...t, where: w.where }], clear: [w.clear] }).produce;
79
+ assert.ok(s.includes(`COPY (select "id", "titre" from "public"."livres" where ${w.where}) TO STDOUT;`));
80
+ // Table vide sur la cible, ou sans clé : réécrite en entier
81
+ assert.strictEqual(P.rewriteOf({ ...t, diff: P.diffHashes(src, '', true, { keys: true }) }).mode, 'full');
82
+ assert.strictEqual(P.rewriteOf({ ...t, pk: null, diff: P.diffHashes(src, dst, false) }).mode, 'full');
83
+ });
84
+
85
+ test('large tables: count and order-independent sum of row fingerprints; identical → skipped, else rewritten', () => {
86
+ const t = { schema: 'public', name: 'commune', columns: ['id', 'nom'] };
87
+ assert.match(P.aggSql(t), /^select count\(\*\) \|\| ' ' \|\| coalesce\(sum\(\('x' \|\| substr\(md5\(row\("id", "nom"\)::text\), 1, 15\)\)::bit\(60\)::bigint::numeric\), 0\) from "public"\."commune"$/);
88
+ const same = P.diffAgg('35247 123456789\n', '35247 123456789');
89
+ assert.deepStrictEqual(same, { rows: 35247, target_rows: 35247, exact: false, same: true });
90
+ assert.strictEqual(P.changed(same), false);
91
+ assert.strictEqual(P.changed(P.diffAgg('35247 1', '35247 2')), true);
92
+ assert.strictEqual(P.changed(P.diffAgg('0 0', '0 0')), false);
93
+ });
94
+
95
+ test('secrets digest: one md5 over names and values, storage credentials of both sides left out; no value out', () => {
96
+ const q = P.secretsDigestSql({ variables: true, credentials: true, vault: true }, { exclude: ['s3-prod'] });
97
+ assert.match(q, /^select md5\(/);
98
+ assert.match(q, /array\['s3-prod'\]::text\[\]/);
99
+ assert.match(q, /md5\(decrypted_secret\)/);
100
+ assert.strictEqual(P.secretsDigestSql({}), "select ''");
101
+ });
102
+
103
+ test('deploy memo: up to date only with the same archive AND that deploy still the last real one of the environment', () => {
104
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-memo-'));
105
+ t_after(() => fs.rmSync(dir, { recursive: true, force: true }));
106
+ memo.record(dir, 'p1', 'main', { deploy_id: 'd2', archive_sha256: 'aaa' });
107
+ const m = memo.get(dir, 'p1', 'main');
108
+ const list = [{ deploy_id: 'x', dry_run: true, outcome: 'success' }, { deploy_id: 'd2', dry_run: false, outcome: 'success' }];
109
+ assert.strictEqual(memo.upToDate(m, 'aaa', list), true);
110
+ assert.strictEqual(memo.upToDate(m, 'bbb', list), false, 'archive changed');
111
+ assert.strictEqual(memo.upToDate(m, 'aaa', [{ deploy_id: 'd3', dry_run: false, outcome: 'success' }, ...list]), false, 'someone deployed since');
112
+ assert.strictEqual(memo.upToDate(m, 'aaa', [{ deploy_id: 'd2', dry_run: false, outcome: 'failed' }]), false);
113
+ assert.strictEqual(memo.get(dir, 'p1', 'dev'), null);
114
+ });
115
+ const t_after = (fn) => test.after(fn);
116
+
117
+ // --- Tube compté, coupé quand il ne bouge plus (faux docker : bash sur ce poste) --------------------------
118
+
119
+ function fakeDocker() {
120
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-docker-'));
121
+ const bin = path.join(dir, 'docker');
122
+ // docker exec -i [-e X]… <conteneur> bash (-s | -c script) → bash localement
123
+ fs.writeFileSync(bin, '#!/bin/bash\nshift\n[ "$1" = "-i" ] && shift\nwhile [ "$1" = "-e" ]; do shift 2; done\nshift\nexec "$@"\n', { mode: 0o755 });
124
+ test.after(() => fs.rmSync(dir, { recursive: true, force: true }));
125
+ return bin;
126
+ }
127
+
128
+ test('pipeTransfer: every byte and line between source and target is counted; markers followed', async () => {
129
+ const pg = require('../utils/project-sync/pg');
130
+ const docker = fakeDocker();
131
+ const out = path.join(path.dirname(docker), 'cible.txt');
132
+ const produce = 'echo "@@poad start 0 1" >&2\nfor i in $(seq 1 2000); do echo "ligne $i"; done\n';
133
+ let bytes = 0;
134
+ let lines = 0;
135
+ const marks = [];
136
+ let srcDone = false;
137
+ const r = await pg.pipeTransfer('c', { vars: {} }, { vars: {} }, { produce, consume: `cat > ${out}` }, { docker, onData: (b, l) => ((bytes += b), (lines += l)), onMarker: (m) => marks.push(m), onSourceDone: () => (srcDone = true) });
138
+ assert.strictEqual(r.code, 0, r.stderr);
139
+ assert.strictEqual(lines, 2000);
140
+ assert.strictEqual(bytes, fs.statSync(out).size);
141
+ assert.deepStrictEqual(marks, ['@@poad start 0 1']);
142
+ assert.ok(srcDone);
143
+ assert.match(r.stderr, /@@poad done \d+ 0/);
144
+ });
145
+
146
+ test('pipeTransfer: a pipe that stops moving is cut after the stall delay; a slow one that moves is not', async () => {
147
+ const pg = require('../utils/project-sync/pg');
148
+ const docker = fakeDocker();
149
+ // Lent mais vivant : une ligne toutes les 150 ms pendant 1,2 s, délai 600 ms
150
+ const slow = await pg.pipeTransfer('c', { vars: {} }, { vars: {} }, { produce: 'for i in 1 2 3 4 5 6 7 8; do echo $i; sleep 0.15; done\n', consume: 'cat > /dev/null' }, { docker, stall: 600 });
151
+ assert.strictEqual(slow.code, 0, slow.stderr);
152
+ assert.strictEqual(slow.stalled, false);
153
+ // Figé : rien pendant 3 s, délai 500 ms → coupé, code 124, rien de validé
154
+ const t0 = Date.now();
155
+ const stuck = await pg.pipeTransfer('c', { vars: {} }, { vars: {} }, { produce: 'echo debut; sleep 3; echo commit\n', consume: 'cat > /dev/null' }, { docker, stall: 500 });
156
+ assert.strictEqual(stuck.stalled, true);
157
+ assert.strictEqual(stuck.code, 124);
158
+ assert.match(stuck.stderr, /no byte went through for 1 s|no byte went through for 0 s/);
159
+ assert.ok(Date.now() - t0 < 2500, 'cut before the end');
160
+ });
161
+
162
+ test('putWithRetry: streams with progress; a stalled upload is retried then fails with a clear message', async (t) => {
163
+ const http = require('http');
164
+ const S = require('../utils/seed/run');
165
+ let mode = 'ok';
166
+ let got = 0;
167
+ const server = http.createServer((req, res) => {
168
+ if (mode === 'stall') return; // ne lit rien, ne répond jamais
169
+ req.on('data', (d) => (got += d.length)).on('end', () => (res.writeHead(200, { etag: '"e1"' }), res.end()));
170
+ });
171
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
172
+ t.after(() => server.close());
173
+ const url = `http://127.0.0.1:${server.address().port}/part`;
174
+ const seen = [];
175
+ const etag = await S.putWithRetry(url, Buffer.alloc(1024 * 1024, 1), { onSent: (n) => seen.push(n) });
176
+ assert.strictEqual(etag, '"e1"');
177
+ assert.strictEqual(got, 1024 * 1024);
178
+ assert.ok(seen.length >= 16 && seen[seen.length - 1] === 1024 * 1024, 'progress by 64 KiB pieces');
179
+ mode = 'stall';
180
+ await assert.rejects(S.putWithRetry(url, Buffer.alloc(8 * 1024 * 1024, 1), { stall: 300, tries: 2, sleep: async () => {} }), /Upload failed: no progress for 0 s|Upload failed: no progress for 1 s|Upload failed: no progress for \d+ s/);
181
+ });
@@ -40,7 +40,13 @@ function fakeTus({ cut = new Set(), tus = true, limit = Infinity } = {}) {
40
40
  if (init.method === 'PATCH') {
41
41
  patches++;
42
42
  if (Number(h['upload-offset']) !== u.got.length) return res(409, { 'upload-offset': String(u.got.length) });
43
- const body = Buffer.from(init.body);
43
+ // Morceau envoyé en flux (pièces de 64 Kio, CLI 2.78.0) ou d'un bloc
44
+ let body;
45
+ if (init.body instanceof ReadableStream) {
46
+ const parts = [];
47
+ for await (const ch of init.body) parts.push(Buffer.from(ch));
48
+ body = Buffer.concat(parts);
49
+ } else body = Buffer.from(init.body);
44
50
  if (cut.has(patches)) {
45
51
  u.got = Buffer.concat([u.got, body.subarray(0, body.length >> 1)]);
46
52
  throw new TypeError('fetch failed');
@@ -68,7 +68,7 @@ const userAgent = () => `poad-cli/${require('../../package.json').version} (${pr
68
68
  * Requête brute : { status, data (JSON ou null), headers }. Ne lève que pour
69
69
  * une erreur réseau. body : objet (JSON) ou Buffer (avec contentType).
70
70
  */
71
- async function raw(method, route, { token, body, contentType, headers = {}, timeout = 30000, env = process.env } = {}) {
71
+ async function raw(method, route, { token, body, contentType, headers = {}, timeout = 30000, env = process.env, onUpload, idleTimeout = (Number(env.POAD_STALL_TIMEOUT) > 0 ? Number(env.POAD_STALL_TIMEOUT) : 300) * 1000 } = {}) {
72
72
  const url = `${apiBase(env)}/${String(route).replace(/^\/+/, '')}`;
73
73
  const h = { accept: 'application/json', 'user-agent': userAgent(), ...headers };
74
74
  if (token) h.authorization = `Bearer ${token}`;
@@ -80,14 +80,50 @@ async function raw(method, route, { token, body, contentType, headers = {}, time
80
80
  payload = JSON.stringify(body);
81
81
  h['content-type'] = 'application/json';
82
82
  }
83
+ // Envoi suivi (onUpload) : le corps part en morceaux de 64 Kio ; le délai est d'INACTIVITÉ pendant l'envoi
84
+ // (idleTimeout : une connexion lente qui avance n'est jamais coupée, une connexion figée l'est), puis
85
+ // timeout pour l'attente de la réponse
86
+ const ctl = new AbortController();
87
+ let timer = null;
88
+ let limit = timeout;
89
+ const arm = (ms) => {
90
+ clearTimeout(timer);
91
+ limit = ms;
92
+ timer = setTimeout(() => ctl.abort(), ms);
93
+ };
94
+ let fetchBody = payload;
95
+ const extra = {};
96
+ if (onUpload && Buffer.isBuffer(payload)) {
97
+ const total = payload.length;
98
+ let at = 0;
99
+ h['content-length'] = String(total);
100
+ fetchBody = new ReadableStream({
101
+ pull(c) {
102
+ if (at >= total) {
103
+ c.close();
104
+ arm(timeout);
105
+ return;
106
+ }
107
+ const end = Math.min(total, at + 64 * 1024);
108
+ c.enqueue(new Uint8Array(payload.buffer, payload.byteOffset + at, end - at));
109
+ at = end;
110
+ arm(idleTimeout);
111
+ onUpload(at, total);
112
+ },
113
+ });
114
+ extra.duplex = 'half';
115
+ arm(idleTimeout);
116
+ } else arm(timeout);
83
117
  let res;
84
118
  try {
85
- res = await fetch(url, { method, headers: h, body: payload, redirect: 'error', signal: AbortSignal.timeout(timeout) });
119
+ res = await fetch(url, { method, headers: h, body: fetchBody, redirect: 'error', signal: ctl.signal, ...extra });
86
120
  } catch (err) {
87
- const why = err && err.name === 'TimeoutError' ? 'timeout' : (err && err.cause && err.cause.code) || (err && err.message) || String(err);
121
+ clearTimeout(timer);
122
+ const why = ctl.signal.aborted ? `no answer for ${Math.round(limit / 1000)} s` : (err && err.cause && err.cause.code) || (err && err.message) || String(err);
88
123
  throw new CloudError(`poad.io cannot be reached (${why}).`, { code: 'network_error' });
89
124
  }
90
125
  const text = await res.text().catch(() => '');
126
+ clearTimeout(timer);
91
127
  let data = null;
92
128
  if (text) {
93
129
  try {
@@ -0,0 +1,46 @@
1
+ // Dernier déploiement réussi de ce poste, par projet et environnement : l'empreinte de l'archive envoyée et
2
+ // l'identifiant du déploiement (poad/data/deploy-state.json, jamais versionné, aucun secret).
3
+ //
4
+ // poad push s'en sert pour ne rien redéployer quand rien n'a changé : même archive (reproductible) que le
5
+ // dernier déploiement fait d'ici ET ce déploiement est toujours le dernier de l'environnement sur poad.io
6
+ // (personne n'a déployé autre chose depuis, d'ici ou d'ailleurs). Au moindre doute : redéployer.
7
+ 'use strict';
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ const file = (poadDir) => path.join(poadDir, 'data', 'deploy-state.json');
12
+
13
+ function read(poadDir) {
14
+ try {
15
+ return JSON.parse(fs.readFileSync(file(poadDir), 'utf8'));
16
+ } catch {
17
+ return {};
18
+ }
19
+ }
20
+
21
+ const keyOf = (id, branch) => `${id}/${branch}`;
22
+
23
+ function get(poadDir, id, branch) {
24
+ return read(poadDir)[keyOf(id, branch)] || null;
25
+ }
26
+
27
+ function record(poadDir, id, branch, entry) {
28
+ const all = read(poadDir);
29
+ all[keyOf(id, branch)] = { ...entry, at: new Date().toISOString() };
30
+ try {
31
+ fs.mkdirSync(path.dirname(file(poadDir)), { recursive: true });
32
+ fs.writeFileSync(file(poadDir), JSON.stringify(all, null, 2) + '\n');
33
+ } catch {}
34
+ }
35
+
36
+ /**
37
+ * Le code de ce poste est-il déjà celui de l'environnement ? Pure.
38
+ * memo : get(...) ; archive : empreinte de l'archive à envoyer ; deploys : GET …/deploys (récents d'abord)
39
+ */
40
+ function upToDate(memo, archive, deploys) {
41
+ if (!memo || !archive || memo.archive_sha256 !== archive) return false;
42
+ const last = (Array.isArray(deploys) ? deploys : []).find((d) => d && !d.dry_run);
43
+ return Boolean(last && String(last.deploy_id) === String(memo.deploy_id) && last.outcome === 'success');
44
+ }
45
+
46
+ module.exports = { read, get, record, upToDate, file };