poad 2.76.0 → 2.76.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.76.0",
3
+ "version": "2.76.1",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
@@ -0,0 +1,150 @@
1
+ // Faux Stockage poad en HTTP (storage 0.6+) pour les essais de poad push / pull et de poad storage sync :
2
+ // buckets, /sync/location, /sync/list, objets (GET avec Range, PUT, DELETE), envois TUS (POST, HEAD, PATCH).
3
+ // opts.backend 'file' (disque de l'engine) par défaut
4
+ // opts.slowPut ms d'attente entre deux morceaux lus d'un PUT (serveur lent)
5
+ // opts.stallPut le PUT n'est jamais lu (serveur figé)
6
+ // opts.cutAfter octets reçus par TUS au-delà desquels toute requête PATCH coupe la connexion (panne) ;
7
+ // fake.heal() rétablit
8
+ // opts.truncate un PUT n'enregistre que la moitié du contenu (serveur fautif)
9
+ // opts.ranges false : le service ignore Range (rend tout l'objet)
10
+ 'use strict';
11
+ const http = require('http');
12
+ const crypto = require('crypto');
13
+
14
+ const md5 = (b) => crypto.createHash('md5').update(b).digest('hex');
15
+
16
+ function fakeStorage(t, opts = {}) {
17
+ const buckets = new Set(opts.buckets || []);
18
+ const objects = new Map(); // "bucket/name" → { body, type }
19
+ const uploads = new Map();
20
+ const stats = { put: 0, patchBytes: 0, rangeReads: 0, posts: 0, heads: 0 };
21
+ let cutAfter = opts.cutAfter ?? Infinity;
22
+ const put = (bucket, name, body, type = 'application/octet-stream') => {
23
+ buckets.add(bucket);
24
+ objects.set(`${bucket}/${name}`, { body: Buffer.from(body), type });
25
+ };
26
+ const row = (k, o) => ({ name: k.slice(k.indexOf('/') + 1), key: null, size: o.body.length, etag: md5(o.body), mimetype: o.type, cacheControl: 'no-cache' });
27
+
28
+ const server = http.createServer(async (req, res) => {
29
+ const url = new URL(req.url, 'http://x');
30
+ const route = decodeURIComponent(url.pathname.replace(/^\/storage\/v1/, ''));
31
+ const json = (status, body, headers = {}) => {
32
+ res.writeHead(status, { 'content-type': 'application/json', ...headers });
33
+ res.end(body === undefined ? '' : JSON.stringify(body));
34
+ };
35
+ const readAll = async () => {
36
+ const chunks = [];
37
+ for await (const c of req) chunks.push(c);
38
+ return Buffer.concat(chunks);
39
+ };
40
+ try {
41
+ if (req.method === 'GET' && route === '/bucket') return json(200, [...buckets].map((id) => ({ id, name: id, public: false })));
42
+ if (req.method === 'POST' && route === '/bucket') {
43
+ const b = JSON.parse((await readAll()).toString());
44
+ if (buckets.has(b.name)) return json(409, { message: 'exists' });
45
+ buckets.add(b.name);
46
+ return json(200, { name: b.name });
47
+ }
48
+ if (req.method === 'GET' && route === '/sync/location') return json(200, { backend: opts.backend || 'file', location: null, fingerprint: null, shareable: false, project: {} });
49
+ if (req.method === 'GET' && route === '/status') return json(200, { backend: opts.backend || 'file' });
50
+ let m = /^\/sync\/list\/(.+)$/.exec(route);
51
+ if (req.method === 'POST' && m) {
52
+ await readAll();
53
+ if (!buckets.has(m[1])) return json(404, { message: 'bucket introuvable' });
54
+ return json(200, { objects: [...objects].filter(([k]) => k.startsWith(`${m[1]}/`)).map(([k, o]) => row(k, o)), next: null });
55
+ }
56
+ m = /^\/object\/([^/]+)$/.exec(route);
57
+ if (req.method === 'DELETE' && m) {
58
+ const { prefixes } = JSON.parse((await readAll()).toString());
59
+ const gone = prefixes.filter((n) => objects.delete(`${m[1]}/${n}`));
60
+ return json(200, gone.map((name) => ({ name })));
61
+ }
62
+ m = /^\/object\/([^/]+)\/(.+)$/.exec(route);
63
+ if (m && req.method === 'GET') {
64
+ const o = objects.get(`${m[1]}/${m[2]}`);
65
+ if (!o) return json(404, { message: 'introuvable' });
66
+ const r = /^bytes=(\d+)-(\d+)$/.exec(req.headers.range || '');
67
+ if (r && opts.ranges !== false) {
68
+ stats.rangeReads++;
69
+ const a = Number(r[1]);
70
+ const b = Math.min(o.body.length - 1, Number(r[2]));
71
+ res.writeHead(206, { 'content-type': o.type, 'content-length': String(b - a + 1), 'content-range': `bytes ${a}-${b}/${o.body.length}` });
72
+ return res.end(o.body.subarray(a, b + 1));
73
+ }
74
+ res.writeHead(200, { 'content-type': o.type, 'content-length': String(o.body.length) });
75
+ return res.end(o.body);
76
+ }
77
+ if (m && req.method === 'PUT') {
78
+ stats.put++;
79
+ if (opts.stallPut) return req.pause();
80
+ const chunks = [];
81
+ for await (const c of req) {
82
+ chunks.push(c);
83
+ if (opts.slowPut) {
84
+ req.pause();
85
+ await new Promise((r) => setTimeout(r, opts.slowPut));
86
+ req.resume();
87
+ }
88
+ }
89
+ const body = Buffer.concat(chunks);
90
+ put(m[1], m[2], opts.truncate ? body.subarray(0, body.length >> 1) : body, req.headers['content-type']);
91
+ return json(200, { name: m[2] });
92
+ }
93
+ if (req.method === 'POST' && route === '/upload/resumable') {
94
+ stats.posts++;
95
+ await readAll();
96
+ const meta = Object.fromEntries(String(req.headers['upload-metadata']).split(',').map((p) => p.split(' ')).map(([k, v]) => [k, Buffer.from(v, 'base64').toString()]));
97
+ const id = crypto.randomUUID();
98
+ uploads.set(id, { length: Number(req.headers['upload-length']), got: Buffer.alloc(0), meta });
99
+ return json(201, undefined, { location: `/storage/v1/upload/resumable/${id}` });
100
+ }
101
+ m = /^\/upload\/resumable\/(.+)$/.exec(route);
102
+ if (m) {
103
+ const u = uploads.get(m[1]);
104
+ if (!u) return json(404, { message: 'envoi introuvable' });
105
+ if (req.method === 'HEAD') {
106
+ stats.heads++;
107
+ res.writeHead(200, { 'upload-offset': String(u.got.length), 'upload-length': String(u.length) });
108
+ return res.end();
109
+ }
110
+ if (req.method === 'PATCH') {
111
+ if (Number(req.headers['upload-offset']) !== u.got.length) return json(409, { message: 'offset' }, { 'upload-offset': String(u.got.length) });
112
+ if (u.got.length >= cutAfter) return req.socket.destroy();
113
+ const body = await readAll();
114
+ u.got = Buffer.concat([u.got, body]);
115
+ stats.patchBytes += body.length;
116
+ if (u.got.length === u.length) {
117
+ put(u.meta.bucketName, u.meta.objectName, u.got, u.meta.contentType);
118
+ uploads.delete(m[1]);
119
+ }
120
+ res.writeHead(204, { 'upload-offset': String(u.got.length) });
121
+ return res.end();
122
+ }
123
+ }
124
+ json(404, { message: 'route inconnue' });
125
+ } catch (e) {
126
+ if (!res.headersSent) json(500, { message: e.message });
127
+ }
128
+ });
129
+ return new Promise((resolve) => {
130
+ server.listen(0, '127.0.0.1', () => {
131
+ t.after(() => {
132
+ server.closeAllConnections?.();
133
+ server.close();
134
+ });
135
+ resolve({
136
+ base: `http://127.0.0.1:${server.address().port}`,
137
+ objects,
138
+ uploads,
139
+ buckets,
140
+ stats,
141
+ put,
142
+ heal: () => (cutAfter = Infinity),
143
+ cut: (n) => (cutAfter = n),
144
+ md5,
145
+ });
146
+ });
147
+ });
148
+ }
149
+
150
+ module.exports = { fakeStorage, md5 };
@@ -154,7 +154,7 @@ test('code: mirrored paths, plan keeps uncommitted or untracked local files', ()
154
154
 
155
155
  // --- La commande entière : faux poad.io (HTTP) et fausse base (deps.pg) ------------------------------------
156
156
 
157
- function fakeCloud(t, seen) {
157
+ function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, events = 200 } = {}) {
158
158
  return new Promise((resolve) => {
159
159
  const server = http.createServer((req, res) => {
160
160
  let body = '';
@@ -163,9 +163,13 @@ function fakeCloud(t, seen) {
163
163
  const send = (s, o) => (res.writeHead(s, { 'content-type': 'application/json' }), res.end(JSON.stringify(o)));
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
- if (/\/sync-plan$/.test(req.url)) return send(200, { space: { limit: 1024 ** 3, used: 1024 ** 2 } });
166
+ if (/\/sync-plan$/.test(req.url)) return send(200, { space });
167
167
  if (/\/backup$/.test(req.url)) return send(200, { file: 'pre-deploy-20261205-000000.dump', bytes: 1234 });
168
- if (/\/sync-events$/.test(req.url)) return send(200, { written: JSON.parse(body).lines.length });
168
+ if (/\/sync-events$/.test(req.url)) {
169
+ // poad.io d'avant la 2.76.1 : refuse les lignes par fichier
170
+ if (events === 'old' && JSON.parse(body).lines.some((l) => l.file)) return send(400, { error: { code: 'invalid_events', message: 'ligne : part et outcome attendus' } });
171
+ return send(200, { written: JSON.parse(body).lines.length });
172
+ }
169
173
  send(404, { error: { code: 'not_found', message: 'route inconnue' } });
170
174
  });
171
175
  });
@@ -177,7 +181,7 @@ function fakeCloud(t, seen) {
177
181
  }
178
182
 
179
183
  /** Fausse base : inventaires de la source et de la cible, empreintes, transfert enregistré */
180
- function fakePg(scripts) {
184
+ function fakePg(scripts, { same = false, queries = [] } = {}) {
181
185
  const real = require('../utils/project-sync/pg');
182
186
  const inv = (rows) => ({
183
187
  tables: [tbl('public', 'livres', [col('id', 'integer'), col('titre')], { pk: ['id'] }), tbl('ref', 'communes', [col('id', 'integer')])],
@@ -191,8 +195,9 @@ function fakePg(scripts) {
191
195
  return {
192
196
  localSide: real.localSide,
193
197
  cloudSide: real.cloudSide,
194
- json: async (container, side, sql) => (sql === P.PROBE_SQL ? { history: true, variables: true, credentials: true, vault: true, auth: ['users'] } : inv(side.kind === 'local' ? 3 : 2)),
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)),
195
199
  query: async (container, side, sql) => {
200
+ queries.push(sql);
196
201
  // Empreintes : la source a trois livres, la cible deux (un remplacé) ; un compte identique
197
202
  const local = side.kind === 'local';
198
203
  const parts = sql.split(/\\echo @@T (\d+)\n/).filter(Boolean);
@@ -200,7 +205,7 @@ function fakePg(scripts) {
200
205
  for (let i = 0; i < parts.length; i += 2) {
201
206
  out += `@@T ${parts[i]}\n`;
202
207
  if (/"auth"\."users"/.test(parts[i + 1])) out += 'u1 h\n';
203
- else out += local ? 'k1 a\nk2 b\nk3 c\n' : 'k1 a\nk2 X\n';
208
+ else out += local || same ? 'k1 a\nk2 b\nk3 c\n' : 'k1 a\nk2 X\n';
204
209
  }
205
210
  return out;
206
211
  },
@@ -212,14 +217,14 @@ function fakePg(scripts) {
212
217
  };
213
218
  }
214
219
 
215
- async function runCmd(t, args, { tty = false } = {}) {
220
+ async function runCmd(t, args, { tty = false, deps = {}, cloud = {}, pg = {} } = {}) {
216
221
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-pp-'));
217
222
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
218
223
  fs.mkdirSync(path.join(dir, 'poad'));
219
224
  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');
220
225
  const seen = [];
221
226
  const scripts = [];
222
- const base = await fakeCloud(t, seen);
227
+ const base = await fakeCloud(t, seen, cloud);
223
228
  const saved = { cwd: process.cwd(), api: process.env.POAD_CLOUD_API, tok: process.env.POAD_ACCESS_TOKEN, log: console.log, err: console.error, code: process.exitCode };
224
229
  const printed = [];
225
230
  process.chdir(dir);
@@ -232,8 +237,9 @@ async function runCmd(t, args, { tty = false } = {}) {
232
237
  try {
233
238
  process.exitCode = 0;
234
239
  await require('../utils/project-sync/run').run(args[0], args.slice(1), {
235
- pg: fakePg(scripts),
240
+ pg: fakePg(scripts, pg),
236
241
  started: async () => true,
242
+ ...deps,
237
243
  credentials: async () => ({ user: 'postgres.pptest123456--dev', password: 'pw-never-shown', host: 'db.poad.io', port: () => 5432 }),
238
244
  });
239
245
  return { code: process.exitCode, out: printed.join('\n'), seen, scripts };
@@ -295,3 +301,113 @@ test('poad pull --tables of an unknown table: stopped before anything is written
295
301
  assert.match(r.out, /public\.inconnue not in the source/);
296
302
  assert.strictEqual(r.scripts.length, 0);
297
303
  });
304
+
305
+ // --- 2.76.1 : reprise, place, sauvegarde seulement si la base est écrite --------------------------------------
306
+
307
+ const { fakeStorage, md5 } = require('./fake-storage');
308
+ const storage = require('../utils/storage');
309
+
310
+ async function sides(t, cloudOpts = {}) {
311
+ const local = await fakeStorage(t);
312
+ const cloud = await fakeStorage(t, cloudOpts);
313
+ const deps = {
314
+ localTarget: async () => ({ base: local.base, key: 'svc', label: 'local engine' }),
315
+ cloudTarget: async () => ({ base: cloud.base, key: 'svc', label: 'poad.io pptest123456 (dev)' }),
316
+ client: (x) => storage.client({ base: x.base, key: x.key }),
317
+ sleep: async () => {},
318
+ };
319
+ return { local, cloud, deps };
320
+ }
321
+
322
+ test('poad push: files cut in the middle → summary folded, exit 5, logs per file; run again → only the rest is sent', async (t) => {
323
+ process.env.POAD_UPLOADS_FILE = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'poad-up-')), 'uploads.json');
324
+ const { local, cloud, deps } = await sides(t, { cutAfter: 6 * 1024 * 1024 });
325
+ const big = Buffer.alloc(14 * 1024 * 1024, 7);
326
+ local.put('ressources', 'video.mp4', big, 'video/mp4');
327
+ for (let i = 0; i < 7; i++) local.put('ressources', `doc${i}.txt`, `document ${i}`, 'text/plain');
328
+ // Sept petits fichiers refusés (413), un gros coupé : 8 échecs, 5 montrés
329
+ const client = deps.client;
330
+ deps.client = (x) => {
331
+ const c = client(x);
332
+ if (x.base !== cloud.base) return c;
333
+ const put = c.put;
334
+ c.put = async (b, n, ...rest) => {
335
+ if (/^doc/.test(n) && cloud.cutting !== false) throw Object.assign(new (require('../utils/cloud/api').CloudError)('taille maximale : 4 octets', { status: 413 }), { retriable: false });
336
+ return put(b, n, ...rest);
337
+ };
338
+ return c;
339
+ };
340
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 's3', '--yes'], { deps });
341
+ assert.strictEqual(r.code, 5, r.out);
342
+ const plain = r.out.replace(/\x1b\[[0-9;]*m/g, '');
343
+ assert.match(plain, /✖ 8 file\(s\) failed/);
344
+ assert.match(plain, /and 3 other\(s\)/);
345
+ assert.match(plain, /Run poad push --env dev again \(or poad push --env dev --only s3\) to resume/);
346
+ const ev = JSON.parse(r.seen.find((x) => /sync-events/.test(x.url)).body);
347
+ const files = ev.lines.filter((l) => l.file && l.outcome === 'failed');
348
+ assert.strictEqual(files.length, 8, JSON.stringify(files.slice(0, 12)));
349
+ assert.ok(ev.lines.filter((l) => l.outcome === 'resumed').length <= 1, 'one resume line per file and offset');
350
+ assert.deepStrictEqual(files.find((l) => l.file === 'ressources/video.mp4').reason, 'network');
351
+ assert.ok(files.every((l) => !('error' in l)));
352
+ assert.ok(!cloud.objects.has('ressources/video.mp4'));
353
+
354
+ // Relance : la panne est passée ; le gros fichier reprend à 6 Mio, les petits partent
355
+ cloud.heal();
356
+ cloud.cutting = false;
357
+ const before = cloud.stats.patchBytes;
358
+ const again = await runCmd(t, ['push', '--env', 'dev', '--only', 's3', '--yes'], { deps });
359
+ assert.strictEqual(again.code, 0, again.out);
360
+ assert.strictEqual(cloud.stats.patchBytes - before, 8 * 1024 * 1024, 'only the 8 MiB left');
361
+ assert.match(again.out.replace(/\x1b\[[0-9;]*m/g, ''), /ressources\/video\.mp4: resumed at 6\.0 MB of 14\.0 MB/);
362
+ assert.strictEqual(md5(cloud.objects.get('ressources/video.mp4').body), md5(big));
363
+ const ev2 = JSON.parse(again.seen.find((x) => /sync-events/.test(x.url)).body);
364
+ assert.deepStrictEqual(ev2.lines.filter((l) => l.file).map((l) => [l.file, l.outcome, l.offset]), [['ressources/video.mp4', 'resumed', 6 * 1024 * 1024]]);
365
+ });
366
+
367
+ test('poad push: an older poad.io refusing the lines per file still gets the others', async (t) => {
368
+ const { local, cloud, deps } = await sides(t, { truncate: true });
369
+ local.put('docs', 'a.txt', 'contenu');
370
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 's3', '--yes'], { deps, cloud: { events: 'old' } });
371
+ assert.strictEqual(r.code, 5);
372
+ const posts = r.seen.filter((x) => /sync-events/.test(x.url)).map((x) => JSON.parse(x.body));
373
+ assert.strictEqual(posts.length, 2);
374
+ assert.ok(!posts[1].lines.some((l) => l.file || l.reason));
375
+ assert.doesNotMatch(r.out, /logs not written on poad\.io/);
376
+ });
377
+
378
+ test('poad push: room — files counted apart from the base, a volume over its size never shows negative bytes', async (t) => {
379
+ const { local, deps } = await sides(t);
380
+ local.put('ressources', 'gros.bin', Buffer.alloc(300 * 1024, 1));
381
+ const space = { limit: 2 * 1024 ** 2, used: 3 * 1024 ** 2, storage: 2.5 * 1024 ** 2 };
382
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 'base,s3', '--yes'], { deps, cloud: { space } });
383
+ assert.strictEqual(r.code, 5);
384
+ const plain = r.out.replace(/\x1b\[[0-9;]*m/g, '');
385
+ assert.match(plain, /to write on dev: base \S+ KB, files 300\.0 KB/);
386
+ assert.match(plain, /volume 2\.0 MB: 3\.0 MB used \(base 512\.0 KB, files 2\.5 MB\), exceeded by 1\.0 MB/);
387
+ assert.match(plain, /not enough room on the target/);
388
+ assert.doesNotMatch(plain, /-\d[\d.]* ?[KMG]?B/);
389
+ assert.strictEqual(r.scripts.length, 0);
390
+ });
391
+
392
+ test('poad push --clean: the tables to rewrite are emptied first (TRUNCATE, own transaction), their room counted as freed', async (t) => {
393
+ const queries = [];
394
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 'base', '--clean', '--yes', '--json'], { pg: { queries }, cloud: { space: { limit: 1024 ** 3, used: 1024 ** 2 } } });
395
+ assert.strictEqual(r.code, 0, r.out);
396
+ const trunc = queries.findIndex((q) => /truncate table "public"\."livres"/.test(q));
397
+ assert.ok(trunc >= 0);
398
+ assert.match(queries[trunc], /begin;[\s\S]*commit;/);
399
+ assert.strictEqual(r.scripts.length, 1);
400
+ const j = JSON.parse(r.out.slice(r.out.indexOf('{')));
401
+ assert.ok(j.preview.space.freed.base > 0);
402
+ const ev = JSON.parse(r.seen.find((x) => /sync-events/.test(x.url)).body);
403
+ assert.ok(ev.lines.some((l) => l.part === 'base' && l.outcome === 'done' && !l.table));
404
+ });
405
+
406
+ test('poad push to production: no backup when the base has nothing to write (a relaunch with files only)', async (t) => {
407
+ const { local, deps } = await sides(t);
408
+ local.put('docs', 'a.txt', 'contenu');
409
+ const r = await runCmd(t, ['push', '--env', 'main', '--only', 'base,auth,s3', '--yes', '--confirm', 'pptest123456'], { deps, pg: { same: true } });
410
+ assert.strictEqual(r.code, 0, r.out);
411
+ assert.ok(!r.seen.some((x) => /\/backup$/.test(x.url)), 'no backup');
412
+ assert.strictEqual(r.scripts.length, 0, 'nothing written in the base');
413
+ });
@@ -0,0 +1,179 @@
1
+ // poad push / pull, partie fichiers : gros fichiers, reprise, objets tronqués, place (CLI 2.76.1).
2
+ // Contre un vrai serveur HTTP (test/fake-storage.js) et le vrai client du Stockage (utils/storage.js).
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 crypto = require('crypto');
9
+ const s = require('../utils/storage');
10
+ const ss = require('../utils/storage-sync');
11
+ const P = require('../utils/project-sync/plan');
12
+ const { fakeStorage, md5 } = require('./fake-storage');
13
+
14
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-resume-'));
15
+ process.env.POAD_UPLOADS_FILE = path.join(tmp, 'uploads.json');
16
+ test.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
17
+
18
+ const noSleep = async () => {};
19
+ const MiB = 1024 * 1024;
20
+ const bytes = (n, seed = 1) => {
21
+ const b = Buffer.alloc(n);
22
+ let x = seed;
23
+ for (let i = 0; i < n; i += 4) b.writeUInt32LE((x = (x * 1103515245 + 12345) >>> 0), i);
24
+ return b;
25
+ };
26
+ const client = (side, timeout) => s.client({ base: side.base, key: 'service-role-test', ...(timeout ? { timeout } : {}) });
27
+ const sync = (from, to, extra = {}) => ss.sync(from, to, { prune: true, concurrency: 2, sleep: noSleep, fromLabel: 'local engine', toLabel: 'poad.io', ...extra });
28
+
29
+ // --- Place ----------------------------------------------------------------------------------------------
30
+
31
+ test('room: never a negative number; a volume already over its size says "exceeded by"', () => {
32
+ const r = P.room({ need: { files: 3.1e9 }, space: { limit: 2 * 1024 ** 3, used: 3.3e9, storage: 3.2e9 } });
33
+ assert.strictEqual(r.ok, false);
34
+ assert.strictEqual(r.free, 0);
35
+ assert.strictEqual(r.available, 0);
36
+ assert.strictEqual(r.over, 3.3e9 - 2 * 1024 ** 3);
37
+ assert.deepStrictEqual([r.used_files, r.used_base], [3.2e9, 0.1e9]);
38
+ assert.ok(r.missing > 0);
39
+ for (const v of Object.values(r)) if (typeof v === 'number') assert.ok(v >= 0, `negative: ${v}`);
40
+ });
41
+
42
+ test('room: files replaced or removed free their room; base only with --clean; journal reserve only if the base writes', () => {
43
+ const space = { limit: 1000, used: 900 };
44
+ const files = P.room({ need: { files: 300 }, freed: { files: 250 }, space });
45
+ assert.deepStrictEqual([files.ok, files.required, files.available, files.reserve], [true, 300, 350, 0]);
46
+ const base = P.room({ need: { base: 100 }, space: { ...space, reserve: 10 } });
47
+ assert.deepStrictEqual([base.ok, base.required], [false, 120]);
48
+ const clean = P.room({ need: { base: 100 }, freed: { base: 200 }, space: { ...space, reserve: 10 } });
49
+ assert.strictEqual(clean.ok, true);
50
+ assert.deepStrictEqual(P.room({ need: { base: 1 } }).known, false);
51
+ });
52
+
53
+ // --- Nouvelles tentatives, concurrence ------------------------------------------------------------------
54
+
55
+ test('adaptive: a passing error is retried after a growing wait; concurrency halves, then comes back; a refusal is not retried', async () => {
56
+ const { CloudError } = require('../utils/cloud/api');
57
+ const waits = [];
58
+ const levels = [];
59
+ const tries = new Map();
60
+ const errs = await ss.adaptive(
61
+ ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'refus'],
62
+ async (x) => {
63
+ tries.set(x, (tries.get(x) || 0) + 1);
64
+ if (x === 'refus') throw new CloudError('too large', { status: 413 });
65
+ if (x === 'b' && tries.get(x) < 3) throw Object.assign(new CloudError('timeout', { code: 'timeout' }), { retriable: true });
66
+ },
67
+ { concurrency: 4, sleep: async (ms) => waits.push(ms), onConcurrency: (n) => levels.push(n) },
68
+ );
69
+ assert.deepStrictEqual(errs.map((e) => [e.item, e.attempts]), [['refus', 1]]);
70
+ assert.strictEqual(tries.get('b'), 3);
71
+ assert.strictEqual(waits.length, 2);
72
+ assert.ok(waits[0] >= 750 && waits[0] <= 1250 && waits[1] >= 1500 && waits[1] <= 2500, String(waits));
73
+ assert.strictEqual(levels[0], 2);
74
+ assert.ok(levels.length > 2 && levels[levels.length - 1] > 1, `goes back up: ${levels}`);
75
+ assert.strictEqual(ss.retriable(new CloudError('x', { status: 503 })), true);
76
+ assert.strictEqual(ss.retriable(new CloudError('x', { status: 403 })), false);
77
+ });
78
+
79
+ // --- Délai : d'inactivité, pas total ------------------------------------------------------------------------
80
+
81
+ test('client: a slow upload that keeps moving is never cut by the timeout; a stuck one is', async (t) => {
82
+ const slow = await fakeStorage(t, { slowPut: 25, buckets: ['b'] });
83
+ const body = bytes(6 * MiB);
84
+ const t0 = Date.now();
85
+ const pieces = [];
86
+ for (let i = 0; i < body.length; i += 64 * 1024) pieces.push(body.subarray(i, i + 64 * 1024));
87
+ await client(slow, 1000).put('b', 'lent.bin', require('stream').Readable.from(pieces), { length: body.length });
88
+ assert.ok(Date.now() - t0 > 1000, `the upload took longer than the timeout (${Date.now() - t0} ms)`);
89
+ assert.strictEqual(md5(slow.objects.get('b/lent.bin').body), md5(body));
90
+
91
+ const stuck = await fakeStorage(t, { stallPut: true, buckets: ['b'] });
92
+ await assert.rejects(client(stuck, 300).put('b', 'x.bin', require('stream').Readable.from([bytes(8 * MiB)])), (e) => e.code === 'timeout' && e.retriable === true && /did not answer within/.test(e.message));
93
+ });
94
+
95
+ // --- Gros fichier : en morceaux, reprise d'une commande à l'autre ------------------------------------------
96
+
97
+ test('sync: a large file goes in resumable chunks read by ranges; cut in the middle, the next run sends only the rest', async (t) => {
98
+ const local = await fakeStorage(t);
99
+ const cloud = await fakeStorage(t, { cutAfter: 12 * MiB });
100
+ const big = bytes(20 * MiB, 7);
101
+ local.put('videos', 'film.mp4', big, 'video/mp4');
102
+ local.put('videos', 'petit.txt', 'bonjour', 'text/plain');
103
+
104
+ const first = await sync(client(local), client(cloud), { retries: 1 });
105
+ assert.strictEqual(first.totals.failed, 1);
106
+ assert.strictEqual(first.errors[0].name, 'film.mp4');
107
+ assert.ok(!cloud.objects.has('videos/film.mp4'), 'never a partial object');
108
+ assert.ok(cloud.objects.has('videos/petit.txt'));
109
+ assert.strictEqual(cloud.stats.patchBytes, 12 * MiB);
110
+ assert.ok(local.stats.rangeReads >= 2, 'the source is read by ranges');
111
+
112
+ // Nouvelle commande (nouveaux clients) : rien de ce qui est arrivé n'est renvoyé
113
+ cloud.heal();
114
+ const events = [];
115
+ const again = await sync(client(local), client(cloud), { onItem: (e) => events.push(e) });
116
+ assert.strictEqual(again.totals.failed, 0);
117
+ assert.deepStrictEqual([again.totals.added, again.totals.unchanged], [1, 1]);
118
+ assert.strictEqual(cloud.stats.patchBytes, 20 * MiB, 'only the 8 MiB left were sent');
119
+ assert.deepStrictEqual(events.filter((e) => e.action === 'resume').map((e) => [e.name, e.offset]), [['film.mp4', 12 * MiB]]);
120
+ assert.strictEqual(md5(cloud.objects.get('videos/film.mp4').body), md5(big));
121
+ assert.strictEqual(cloud.objects.get('videos/film.mp4').type, 'video/mp4');
122
+
123
+ // Troisième fois : tout est là, rien ne part
124
+ const third = await sync(client(local), client(cloud));
125
+ assert.deepStrictEqual([third.totals.added, third.totals.updated, third.totals.unchanged], [0, 0, 2]);
126
+ });
127
+
128
+ test('sync: a source that does not serve ranges still sends a large file in chunks (from the stream)', async (t) => {
129
+ const local = await fakeStorage(t, { ranges: false });
130
+ const cloud = await fakeStorage(t);
131
+ const big = bytes(7 * MiB, 3);
132
+ local.put('docs', 'gros.pdf', big, 'application/pdf');
133
+ const r = await sync(client(local), client(cloud));
134
+ assert.strictEqual(r.totals.failed, 0);
135
+ assert.strictEqual(cloud.stats.put, 0);
136
+ assert.strictEqual(md5(cloud.objects.get('docs/gros.pdf').body), md5(big));
137
+ });
138
+
139
+ // --- Objets tronqués -----------------------------------------------------------------------------------
140
+
141
+ test('sync: a truncated object on the target is never "unchanged" (size + checksum), and is sent again', async (t) => {
142
+ const local = await fakeStorage(t);
143
+ const cloud = await fakeStorage(t);
144
+ const body = bytes(64 * 1024, 5);
145
+ local.put('docs', 'a.bin', body);
146
+ cloud.put('docs', 'a.bin', body.subarray(0, 32 * 1024));
147
+ const dry = await sync(client(local), client(cloud), { dryRun: true });
148
+ assert.deepStrictEqual([dry.totals.updated, dry.totals.unchanged], [1, 0]);
149
+ assert.strictEqual(dry.buckets[0].update[0].targetSize, 32 * 1024);
150
+ await sync(client(local), client(cloud));
151
+ assert.strictEqual(md5(cloud.objects.get('docs/a.bin').body), md5(body));
152
+ });
153
+
154
+ test('sync: an object that arrives different (faulty target) is a failure, never counted as done', async (t) => {
155
+ const local = await fakeStorage(t);
156
+ const cloud = await fakeStorage(t, { truncate: true });
157
+ local.put('docs', 'a.txt', 'contenu entier');
158
+ const r = await sync(client(local), client(cloud));
159
+ assert.strictEqual(r.totals.added, 0);
160
+ assert.strictEqual(r.totals.failed, 1);
161
+ assert.match(r.errors[0].error, /different on the target after the upload/);
162
+ });
163
+
164
+ test('sync --clean (freeFirst): what will be replaced is removed before the uploads; removals always come first', async (t) => {
165
+ const local = await fakeStorage(t);
166
+ const cloud = await fakeStorage(t);
167
+ local.put('docs', 'a.txt', 'nouveau');
168
+ cloud.put('docs', 'a.txt', 'ancien');
169
+ cloud.put('docs', 'vieux.txt', 'à retirer');
170
+ const order = [];
171
+ const to = client(cloud);
172
+ const [remove, put] = [to.remove, to.put];
173
+ to.remove = async (...a) => (order.push(['remove', ...a[1]]), remove(...a));
174
+ to.put = async (...a) => (order.push(['put', a[1]]), put(...a));
175
+ const r = await sync(client(local), to, { freeFirst: true });
176
+ assert.deepStrictEqual(order, [['remove', 'vieux.txt', 'a.txt'], ['put', 'a.txt']]);
177
+ assert.deepStrictEqual([r.totals.updated, r.totals.removed], [1, 1]);
178
+ assert.strictEqual(cloud.objects.get('docs/a.txt').body.toString(), 'nouveau');
179
+ });
@@ -505,7 +505,7 @@ Object.assign(sheets, {
505
505
  },
506
506
  push: {
507
507
  usage: [
508
- 'poad push [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--yes] [--json]',
508
+ 'poad push [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--clean] [--yes] [--json]',
509
509
  'poad push --env main --yes --confirm <project id> (production, outside a terminal)',
510
510
  ],
511
511
  text: [
@@ -513,6 +513,8 @@ Object.assign(sheets, {
513
513
  'A preview always comes first, part by part and table by table: rows added (+), replaced (~), deleted (-) and identical, compared row by row with fingerprints of the primary key and of each row (never a value; above 200,000 rows a table is compared by counts only), sizes, room left on the target. An identical table is not rewritten.',
514
514
  'Base and auth go in ONE transaction, through the direct database access of poad.io (db.poad.io), run by the PostgreSQL tools of the local engine: the source is read in one consistent snapshot, the target is written with triggers and foreign keys paused during the load (nothing cascades), sequences are set as on the source; any error and nothing changes. Sessions and refresh tokens of the target are closed (accounts sign in again there), confirmation and recovery tokens are emptied. The structure must match first: a table missing or different on the target stops the base part before anything is written, and the code part (when chosen) runs first and is checked again after it.',
515
515
  'Secrets only with --with-secrets, after a confirmation of their own: the values of the variables of the engine and the credentials (fields, uses, vault values), except those of the storage, which each environment keeps. Values are never shown, written to a file or logged; keys of the engine, auth provider secrets and MCP tokens are never copied.',
516
+ 'Files: compared by name, size and checksum (MD5): what is already there is not sent again, a truncated or different object is. Above 6 MiB a file goes in resumable chunks (read from the source by ranges): an upload cut by the network, or by the end of the command, goes on from where the target is at the next run. The timeout is one of inactivity (an upload that moves is never cut); a passing error (network, timeout, 5xx, 429) is tried again after 1 s, 2 s, 4 s… and the number of transfers at once halves while errors come, then goes back up. Each file sent is read back on the target (size and checksum).',
517
+ 'Run again: poad push resumes. Code is deployed again (idempotent), identical tables and accounts are not rewritten (and production is not backed up again when the base has nothing to write), files already there are skipped. Failed files are summed up at the end (the first 5; all of them in --json and in the logs), with the command to run again; exit code 5.',
516
518
  ],
517
519
  options: [
518
520
  ['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
@@ -521,6 +523,7 @@ Object.assign(sheets, {
521
523
  ['--skip <parts>', 'all parts but these'],
522
524
  ['--tables <a,b>', 'only these tables of the base part (table or schema.table)'],
523
525
  ['--with-secrets', 'also the values of variables and credentials (asks separately)'],
526
+ ['--clean', 'free the room first: the tables to rewrite are emptied (TRUNCATE, in a transaction of its own) and the files to replace removed before the copy; identical ones are kept. Not all or nothing any more: a failure leaves them empty until the next run'],
524
527
  ['--allow-destructive', 'passed to poad deploy (alias --accept-data-loss): migrations that lose data are applied on production without asking'],
525
528
  ['--yes', 'no question (required outside a terminal)'],
526
529
  ['--confirm <id>', 'production: the project id, typed in the command (outside a terminal: with --yes)'],
@@ -528,13 +531,14 @@ Object.assign(sheets, {
528
531
  JSON_OPT,
529
532
  ],
530
533
  notes: [
531
- 'Production (main): a backup of its database first (kept in its volume, 3 kept), a check of the room left (rows to write + 10 % + the journal of the database), and a strong confirmation: type the project id; outside a terminal, --yes --confirm <id>, else nothing changes.',
532
- 'The local project must be started (poad start). Logs, one line per part and per table (part, table, rows, bytes, duration_ms, outcome; never a value): poad logs cli event=project_push here, and in the logs of the environment on poad.io (poad logs --project … event=project_push).',
534
+ 'Production (main): a backup of its database first when the base is to be written (kept in its volume, 3 kept), and a strong confirmation: type the project id; outside a terminal, --yes --confirm <id>, else nothing changes.',
535
+ 'Room: what will be written (base: rows + 10 % + the journal of the database; files: their size) against the volume of the target, base and files told apart; files replaced or removed count as freed (removed first), tables only with --clean. A volume already over its size says "exceeded by"; not enough room stops before anything is written.',
536
+ 'The local project must be started (poad start). Logs, one line per part and per table (part, table, rows, bytes, duration_ms, outcome; never a value), and one per file that failed (file, reason: timeout, network, too_large, verify…, attempts) or resumed (offset): poad logs cli event=project_push here, and in the logs of the environment on poad.io (poad logs --project … event=project_push).',
533
537
  EXIT_NOTE.replace('5 deploy failed', '5 a part failed (the base part is all or nothing)'),
534
538
  ],
535
539
  },
536
540
  pull: {
537
- usage: ['poad pull [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--yes] [--json]'],
541
+ usage: ['poad pull [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--clean] [--yes] [--json]'],
538
542
  text: [
539
543
  'The other way of poad push: make the local project the mirror of an environment of poad.io, part by part: code (the migrations written there, by poad migration pull, then the deployed files of queries, auth, storage, functions, flows, api, reference, sources, transforms, connections, variables and seed.sql, then poad migrate), base, auth, refs (the reference tables of the store, loaded into the local engine), s3 (files of the storage).',
540
544
  'A local file is replaced or removed only when git tracks it without uncommitted change; otherwise it is kept and named (commit or stash it, then pull again). Migrations are never overwritten (a version used here under another name is a conflict, said and left alone).',
@@ -547,6 +551,7 @@ Object.assign(sheets, {
547
551
  ['--skip <parts>', 'all parts but these'],
548
552
  ['--tables <a,b>', 'only these tables of the base part'],
549
553
  ['--with-secrets', 'also the values of variables and credentials (asks separately)'],
554
+ ['--clean', 'free the room first (as for poad push)'],
550
555
  ['--yes', 'no question (required outside a terminal)'],
551
556
  PROJECT_OPT,
552
557
  JSON_OPT,