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.
- package/README.md +49 -0
- package/global/cli.js +1 -0
- package/global/doctor.js +41 -0
- package/global/init.js +6 -0
- package/global/start.js +4 -0
- package/package.json +4 -1
- package/project/deploy.js +13 -1
- package/project/link.js +2 -0
- package/project/logs.js +2 -0
- package/project/ref/push.js +42 -29
- package/test/doctor.test.js +159 -0
- package/test/graphql.test.js +25 -0
- package/test/project-sync.test.js +116 -13
- package/test/push-progress.test.js +181 -0
- package/test/storage-tus.test.js +7 -1
- package/utils/cloud/api.js +39 -3
- package/utils/cloud/deploy-memo.js +46 -0
- package/utils/doctor.js +368 -0
- package/utils/graphql.js +41 -0
- package/utils/help-details.js +18 -0
- package/utils/logline.js +4 -2
- package/utils/progress.js +198 -0
- package/utils/project-sync/pg.js +106 -3
- package/utils/project-sync/plan.js +102 -11
- package/utils/project-sync/run.js +146 -47
- package/utils/reference-store.js +20 -26
- package/utils/seed/run.js +57 -11
- package/utils/storage-sync.js +28 -6
- package/utils/storage.js +18 -2
|
@@ -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.
|
|
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
|
});
|
|
@@ -164,6 +164,7 @@ function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, eve
|
|
|
164
164
|
if (/\/branches$/.test(req.url)) return send(200, [{ name: 'main', kind: 'production' }, { name: 'dev' }]);
|
|
165
165
|
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
166
|
if (/\/sync-plan$/.test(req.url)) return send(200, { space });
|
|
167
|
+
if (/\/deploys$/.test(req.url)) return send(200, { deploys: [{ deploy_id: 'dep-1', outcome: 'success', dry_run: false }] });
|
|
167
168
|
if (/\/backup$/.test(req.url)) return send(200, { file: 'pre-deploy-20261205-000000.dump', bytes: 1234 });
|
|
168
169
|
if (/\/sync-events$/.test(req.url)) {
|
|
169
170
|
// poad.io d'avant la 2.76.1 : refuse les lignes par fichier
|
|
@@ -181,10 +182,13 @@ function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, eve
|
|
|
181
182
|
}
|
|
182
183
|
|
|
183
184
|
/** Fausse base : inventaires de la source et de la cible, empreintes, transfert enregistré */
|
|
184
|
-
function fakePg(scripts, { same = false, queries = [] } = {}) {
|
|
185
|
+
function fakePg(scripts, { same = false, queries = [], state = null, extraTables = [] } = {}) {
|
|
185
186
|
const real = require('../utils/project-sync/pg');
|
|
187
|
+
// state : la cible devient le miroir après un transfert réussi (state.base, state.secrets) ; state.cut : le
|
|
188
|
+
// prochain transfert de la base est coupé (tube figé : rien n'arrive sur la cible)
|
|
189
|
+
const isSame = () => same || Boolean(state && state.base);
|
|
186
190
|
const inv = (rows) => ({
|
|
187
|
-
tables: [tbl('public', 'livres', [col('id', 'integer'), col('titre')], { pk: ['id'] }), tbl('ref', 'communes', [col('id', 'integer')])],
|
|
191
|
+
tables: [tbl('public', 'livres', [col('id', 'integer'), col('titre')], { pk: ['id'] }), tbl('ref', 'communes', [col('id', 'integer')]), ...extraTables],
|
|
188
192
|
sequences: [{ schema: 'public', name: 'livres_id_seq', owner: 'public.livres', last: rows }],
|
|
189
193
|
migrations: ['20261205100000'],
|
|
190
194
|
auth: { users: { rows: 1, bytes: 10, pk: ['id'], columns: [col('id', 'uuid'), col('email')] } },
|
|
@@ -195,9 +199,11 @@ function fakePg(scripts, { same = false, queries = [] } = {}) {
|
|
|
195
199
|
return {
|
|
196
200
|
localSide: real.localSide,
|
|
197
201
|
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' ||
|
|
202
|
+
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
203
|
query: async (container, side, sql) => {
|
|
200
204
|
queries.push(sql);
|
|
205
|
+
// Condensé des secrets : pareil une fois copiés
|
|
206
|
+
if (/^select md5\(/.test(sql)) return side.kind === 'local' || (state && state.secrets) ? 'd1g3st\n' : 'other\n';
|
|
201
207
|
// Empreintes : la source a trois livres, la cible deux (un remplacé) ; un compte identique
|
|
202
208
|
const local = side.kind === 'local';
|
|
203
209
|
const parts = sql.split(/\\echo @@T (\d+)\n/).filter(Boolean);
|
|
@@ -205,22 +211,34 @@ function fakePg(scripts, { same = false, queries = [] } = {}) {
|
|
|
205
211
|
for (let i = 0; i < parts.length; i += 2) {
|
|
206
212
|
out += `@@T ${parts[i]}\n`;
|
|
207
213
|
if (/"auth"\."users"/.test(parts[i + 1])) out += 'u1 h\n';
|
|
208
|
-
else out += local ||
|
|
214
|
+
else out += local || isSame() ? 'k1 a\nk2 b\nk3 c\n' : 'k1 a\nk2 X\n';
|
|
209
215
|
}
|
|
210
216
|
return out;
|
|
211
217
|
},
|
|
212
218
|
transfer: async (container, src, dst, script) => {
|
|
213
|
-
scripts.push(script);
|
|
219
|
+
scripts.push(typeof script === 'string' ? script : script.produce);
|
|
220
|
+
if (state && typeof script === 'string') state.secrets = true;
|
|
221
|
+
if (state && typeof script !== 'string') {
|
|
222
|
+
if (state.cut) {
|
|
223
|
+
state.cut = false;
|
|
224
|
+
return { code: 124, stalled: true, stdout: Buffer.alloc(0), stderr: '@@poad start 0 1000\nno byte went through\n@@poad done 1200 124\n' };
|
|
225
|
+
}
|
|
226
|
+
state.base = true;
|
|
227
|
+
}
|
|
214
228
|
return { code: 0, stdout: Buffer.alloc(0), stderr: '@@poad start 0 1000\n@@poad done 1200 0\n' };
|
|
215
229
|
},
|
|
216
230
|
dumpLocal: async () => 10,
|
|
217
231
|
};
|
|
218
232
|
}
|
|
219
233
|
|
|
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'));
|
|
234
|
+
async function runCmd(t, args, { tty = false, deps = {}, cloud = {}, pg = {}, dir: given = null, files = {} } = {}) {
|
|
235
|
+
const dir = given || fs.mkdtempSync(path.join(os.tmpdir(), 'poad-pp-'));
|
|
236
|
+
if (!given) t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
237
|
+
fs.mkdirSync(path.join(dir, 'poad'), { recursive: true });
|
|
238
|
+
for (const [rel, body] of Object.entries(files)) {
|
|
239
|
+
fs.mkdirSync(path.dirname(path.join(dir, 'poad', rel)), { recursive: true });
|
|
240
|
+
fs.writeFileSync(path.join(dir, 'poad', rel), body);
|
|
241
|
+
}
|
|
224
242
|
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
243
|
const seen = [];
|
|
226
244
|
const scripts = [];
|
|
@@ -242,7 +260,7 @@ async function runCmd(t, args, { tty = false, deps = {}, cloud = {}, pg = {} } =
|
|
|
242
260
|
...deps,
|
|
243
261
|
credentials: async () => ({ user: 'postgres.pptest123456--dev', password: 'pw-never-shown', host: 'db.poad.io', port: () => 5432 }),
|
|
244
262
|
});
|
|
245
|
-
return { code: process.exitCode, out: printed.join('\n'), seen, scripts };
|
|
263
|
+
return { code: process.exitCode, out: printed.join('\n'), seen, scripts, dir };
|
|
246
264
|
} finally {
|
|
247
265
|
process.stdin.isTTY = isTTY;
|
|
248
266
|
process.chdir(saved.cwd);
|
|
@@ -290,7 +308,7 @@ test('poad push to production with --yes --confirm: backup first, one transfer,
|
|
|
290
308
|
assert.match(r.scripts[0], /setval/);
|
|
291
309
|
const ev = JSON.parse(r.seen.find((s) => /sync-events/.test(s.url)).body);
|
|
292
310
|
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']]);
|
|
311
|
+
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
312
|
assert.strictEqual(ev.lines[1].rows, 3);
|
|
295
313
|
assert.ok(!JSON.stringify(ev).includes('pw-never-shown'));
|
|
296
314
|
});
|
|
@@ -411,3 +429,88 @@ test('poad push to production: no backup when the base has nothing to write (a r
|
|
|
411
429
|
assert.ok(!r.seen.some((x) => /\/backup$/.test(x.url)), 'no backup');
|
|
412
430
|
assert.strictEqual(r.scripts.length, 0, 'nothing written in the base');
|
|
413
431
|
});
|
|
432
|
+
|
|
433
|
+
// --- 2.78.0 : un seul chemin par donnée, poussée incrémentale et idempotente, reprise -------------------------
|
|
434
|
+
|
|
435
|
+
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) => {
|
|
436
|
+
const commune = tbl('public', 'commune', [col('id', 'integer'), col('nom')], { pk: ['id'], estimate: 35247, bytes: 525e6 });
|
|
437
|
+
for (const only of ['base', 'base,refs']) {
|
|
438
|
+
const r = await runCmd(t, ['push', '--env', 'dev', '--only', only, '--yes'], { files: { 'reference/public.commune.jsonl': '{"id":1,"nom":"A"}\n' }, pg: { extraTables: [commune] } });
|
|
439
|
+
assert.strictEqual(r.code, 0, r.out);
|
|
440
|
+
const plain = r.out.replace(/\x1b\[[0-9;]*m/g, '');
|
|
441
|
+
assert.match(plain, /public\.commune: reference table, goes through refs/);
|
|
442
|
+
if (only === 'base') assert.match(plain, /left out here: --only refs to push it/);
|
|
443
|
+
for (const sc of r.scripts) assert.ok(!/"public"\."commune"/.test(sc), 'commune never in the base transfer');
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
/** Un projet complet, deux côtés : code, base, comptes, références, fichiers, secrets */
|
|
448
|
+
async function fullProject(t) {
|
|
449
|
+
const { local, cloud, deps } = await sides(t);
|
|
450
|
+
local.put('docs', 'a.txt', 'premier');
|
|
451
|
+
local.put('docs', 'b.bin', Buffer.alloc(200 * 1024, 3));
|
|
452
|
+
const calls = [];
|
|
453
|
+
deps.self = async (args) => {
|
|
454
|
+
calls.push(args.join(' '));
|
|
455
|
+
// poad deploy : archive reproductible ; le vrai deploy note son dernier déploiement réussi
|
|
456
|
+
if (args.includes('--dry-run')) return { code: 0, data: { files: 3, bytes: 900, archive_sha256: 'abc123', migrations: { pending: [], errors: [] } } };
|
|
457
|
+
require('../utils/cloud/deploy-memo').record(path.join(process.cwd(), 'poad'), 'pptest123456', 'dev', { deploy_id: 'dep-1', archive_sha256: 'abc123' });
|
|
458
|
+
return { code: 0, data: { migrations: { applied: [] } } };
|
|
459
|
+
};
|
|
460
|
+
return { local, cloud, deps, calls, state: {} };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
test('poad push twice in a row: the second one transfers nothing and says so, part by part', async (t) => {
|
|
464
|
+
const p = await fullProject(t);
|
|
465
|
+
const args = ['push', '--env', 'dev', '--with-secrets', '--yes', '--json'];
|
|
466
|
+
const first = await runCmd(t, args, { deps: p.deps, pg: { state: p.state } });
|
|
467
|
+
assert.strictEqual(first.code, 0, first.out);
|
|
468
|
+
const j1 = JSON.parse(first.out.slice(first.out.indexOf('{\n')));
|
|
469
|
+
assert.ok(j1.results.code && j1.results.base && j1.results.secrets && j1.results.s3, JSON.stringify(Object.keys(j1.results)));
|
|
470
|
+
assert.strictEqual(p.cloud.objects.size, 2);
|
|
471
|
+
const putsAfterFirst = p.cloud.stats.put + p.cloud.stats.patchBytes;
|
|
472
|
+
|
|
473
|
+
const second = await runCmd(t, args, { deps: p.deps, pg: { state: p.state }, dir: first.dir });
|
|
474
|
+
t.after(() => fs.rmSync(first.dir, { recursive: true, force: true }));
|
|
475
|
+
assert.strictEqual(second.code, 0, second.out);
|
|
476
|
+
const j2 = JSON.parse(second.out.slice(second.out.indexOf('{\n')));
|
|
477
|
+
assert.strictEqual(j2.preview.code.todo, false, 'same archive as the last deploy, still the last one');
|
|
478
|
+
assert.deepStrictEqual(j2.preview.base.tables.filter((x) => x.rewrite), []);
|
|
479
|
+
assert.strictEqual(j2.preview.auth.changed, false);
|
|
480
|
+
assert.strictEqual(j2.preview.refs.todo, false);
|
|
481
|
+
assert.strictEqual(j2.preview.s3.todo, false);
|
|
482
|
+
assert.strictEqual(j2.preview.secrets.same, true);
|
|
483
|
+
assert.strictEqual(j2.results, null, 'nothing run');
|
|
484
|
+
assert.strictEqual(second.scripts.length, 0, 'no transfer');
|
|
485
|
+
assert.strictEqual(p.cloud.stats.put + p.cloud.stats.patchBytes, putsAfterFirst, 'no file sent');
|
|
486
|
+
assert.strictEqual(p.calls.filter((c) => !c.includes('--dry-run')).length, 1, 'one real deploy only, by the first push');
|
|
487
|
+
|
|
488
|
+
// En texte : « rien à faire » dit pour chaque partie
|
|
489
|
+
const third = await runCmd(t, ['push', '--env', 'dev', '--with-secrets', '--yes'], { deps: p.deps, pg: { state: p.state }, dir: first.dir });
|
|
490
|
+
const plain = third.out.replace(/\x1b\[[0-9;]*m/g, '');
|
|
491
|
+
assert.match(plain, /code\s+nothing to deploy/);
|
|
492
|
+
assert.match(plain, /base\s+\d+ table\(s\): all identical, nothing to copy/);
|
|
493
|
+
assert.match(plain, /secrets\s+identical/);
|
|
494
|
+
assert.match(plain, /Nothing to copy: the target is already the mirror of the source/);
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
test('poad push cut in the middle of the base, then run again: what arrived is skipped, the rest goes', async (t) => {
|
|
498
|
+
const p = await fullProject(t);
|
|
499
|
+
p.state.cut = true;
|
|
500
|
+
const args = ['push', '--env', 'dev', '--yes', '--json'];
|
|
501
|
+
const first = await runCmd(t, args, { deps: p.deps, pg: { state: p.state } });
|
|
502
|
+
t.after(() => fs.rmSync(first.dir, { recursive: true, force: true }));
|
|
503
|
+
assert.strictEqual(first.code, 5, first.out);
|
|
504
|
+
const j1 = JSON.parse(first.out.slice(first.out.indexOf('{\n')));
|
|
505
|
+
assert.strictEqual(j1.results.base.outcome, 'failed');
|
|
506
|
+
assert.match(j1.results.base.error, /no byte went through/);
|
|
507
|
+
assert.strictEqual(j1.results.s3, undefined, 'the push stops at the first failed part');
|
|
508
|
+
|
|
509
|
+
const again = await runCmd(t, args, { deps: p.deps, pg: { state: p.state }, dir: first.dir });
|
|
510
|
+
assert.strictEqual(again.code, 0, again.out);
|
|
511
|
+
const j2 = JSON.parse(again.out.slice(again.out.indexOf('{\n')));
|
|
512
|
+
assert.strictEqual(j2.preview.code.todo, false, 'the code deployed by the first run is not deployed again');
|
|
513
|
+
assert.strictEqual(j2.results.base.outcome, 'done');
|
|
514
|
+
assert.strictEqual(j2.results.s3.totals.added, 2);
|
|
515
|
+
assert.strictEqual(p.calls.filter((c) => !c.includes('--dry-run')).length, 1);
|
|
516
|
+
});
|
|
@@ -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
|
+
});
|
package/test/storage-tus.test.js
CHANGED
|
@@ -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
|
-
|
|
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');
|
package/utils/cloud/api.js
CHANGED
|
@@ -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:
|
|
119
|
+
res = await fetch(url, { method, headers: h, body: fetchBody, redirect: 'error', signal: ctl.signal, ...extra });
|
|
86
120
|
} catch (err) {
|
|
87
|
-
|
|
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 };
|