poad 2.75.3 → 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 +1 -1
- package/project/cli.js +2 -0
- package/project/pull.js +4 -0
- package/project/push.js +4 -0
- package/test/cloud.test.js +5 -2
- package/test/fake-storage.js +150 -0
- package/test/project-sync.test.js +413 -0
- package/test/push-resume.test.js +179 -0
- package/utils/banner.js +2 -0
- package/utils/cloud/db.js +6 -7
- package/utils/data-loss.js +4 -4
- package/utils/help-details.js +58 -3
- package/utils/project-sync/code.js +122 -0
- package/utils/project-sync/pg.js +130 -0
- package/utils/project-sync/plan.js +491 -0
- package/utils/project-sync/run.js +910 -0
- package/utils/storage-sync.js +164 -24
- package/utils/storage-tus.js +40 -4
- package/utils/storage.js +69 -19
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -63,6 +63,8 @@ module.exports = {
|
|
|
63
63
|
sync: 'Old name of env clone',
|
|
64
64
|
rm: 'Remove an environment, its database and files (confirmation, --yes); never main',
|
|
65
65
|
},
|
|
66
|
+
push: 'The whole local project to a poad.io environment, the target becoming its mirror: code (poad deploy), base (rows of the project tables), auth (accounts, password hashes), s3 (storage files), refs; preview first, backup and typed confirmation for production: push [--env <name>] [--dry-run] [--only|--skip code,base,auth,s3,refs] [--tables a,b] [--with-secrets]',
|
|
67
|
+
pull: 'A whole poad.io environment into the local project (the other way of poad push): code (migrations and files), base, auth, s3, refs; preview first, local backup: pull [--env <name>] [--dry-run] [--only|--skip …] [--tables a,b] [--with-secrets]',
|
|
66
68
|
deploy: 'Send poad/ (migrations, functions, flows, api, auth, storage…, never a secret) to poad.io: deploy [--env <name>] [--dry-run] [--yes]',
|
|
67
69
|
upgrade: 'Upgrade the engine of the project (backup first), or roll back to a backup',
|
|
68
70
|
logs: 'Unified logs of the project, every service, with filters (level, since, request, flow, function, AI…) and -f',
|
package/project/pull.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// poad pull [--env <nom>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets]
|
|
2
|
+
// [--yes] [--project <id>] [--json]
|
|
3
|
+
// Tout un environnement de poad.io vers le projet local : utils/project-sync/run.js
|
|
4
|
+
module.exports = (args, raw) => require('../utils/project-sync/run').run('pull', raw);
|
package/project/push.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// poad push [--env <nom>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets]
|
|
2
|
+
// [--allow-destructive] [--yes] [--confirm <id>] [--project <id>] [--json]
|
|
3
|
+
// Tout le projet local vers un environnement de poad.io : utils/project-sync/run.js
|
|
4
|
+
module.exports = (args, raw) => require('../utils/project-sync/run').run('push', raw);
|
package/test/cloud.test.js
CHANGED
|
@@ -81,6 +81,7 @@ function fakeCloud(t, behaviour = {}) {
|
|
|
81
81
|
if (req.method === 'GET' && rest === '/engine') return send(res, 200, { current: '0.38.0', offered: '0.39.0', available: true, reason: null });
|
|
82
82
|
if (req.method === 'POST' && rest === '/upgrade') return send(res, 202, { state: 'running', to: json().to });
|
|
83
83
|
if (req.method === 'GET' && rest === '/db-password') return send(res, 200, { user: `postgres.${id}`, password: DB_PASSWORD, host: 'db.poad.io', session_port: 5432, transaction_port: 6543 });
|
|
84
|
+
if (req.method === 'GET' && rest === '/branches/dev/db-password') return send(res, 200, { user: `postgres.${id}--dev`, password: DB_PASSWORD, host: 'db.poad.io', session_port: 5432, transaction_port: 6543 });
|
|
84
85
|
if (req.method === 'GET' && rest === '/branches') return send(res, 200, { branches: state.branches[id] });
|
|
85
86
|
if (req.method === 'POST' && rest === '/branches') {
|
|
86
87
|
const b = { name: json().name, kind: json().kind, status: 'creating' };
|
|
@@ -567,9 +568,11 @@ test('db url : mot de passe masqué par défaut, --show-password l’affiche, mo
|
|
|
567
568
|
assert.strictEqual(cloud.requests.at(-1).query.purpose, 'reveal');
|
|
568
569
|
const bad = await poad(box, cloud.api, ['db', 'url', '--mode', 'pool']);
|
|
569
570
|
assert.strictEqual(bad.status, 2);
|
|
571
|
+
// Un environnement : sa propre base (postgres.<id>--<branche>, route par branche de poad.io)
|
|
570
572
|
const dev = await poad(box, cloud.api, ['db', 'url', '--env', 'dev']);
|
|
571
|
-
assert.strictEqual(dev.status,
|
|
572
|
-
assert.match(dev.
|
|
573
|
+
assert.strictEqual(dev.status, 0, dev.all);
|
|
574
|
+
assert.match(dev.stdout, new RegExp(`postgresql://postgres\\.${PID}--dev:•+@db\\.poad\\.io:5432/postgres`));
|
|
575
|
+
assert.ok(!dev.all.includes(DB_PASSWORD));
|
|
573
576
|
});
|
|
574
577
|
|
|
575
578
|
test('db pull : pg_dump --schema-only avec PGPASSWORD (jamais en argument), nouvelle migration à chaque fois', async (t) => {
|
|
@@ -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 };
|
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
// poad push / poad pull : décisions sans base ni réseau (utils/project-sync/plan.js, code.js),
|
|
2
|
+
// puis la commande entière contre un faux poad.io et une fausse base (deps.pg).
|
|
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 http = require('http');
|
|
9
|
+
const P = require('../utils/project-sync/plan');
|
|
10
|
+
const C = require('../utils/project-sync/code');
|
|
11
|
+
|
|
12
|
+
const col = (name, type = 'text', extra = {}) => ({ name, type, generated: false, notnull: false, default: false, ...extra });
|
|
13
|
+
const tbl = (schema, name, columns, extra = {}) => ({ schema, name, columns, pk: ['id'], estimate: 10, bytes: 8192, refs: [], ...extra });
|
|
14
|
+
|
|
15
|
+
test('parseParts: all by default, --only, --skip, aliases, --tables needs base, secrets only with --with-secrets', () => {
|
|
16
|
+
assert.deepStrictEqual(P.parseParts({}), { parts: ['code', 'base', 'auth', 'refs', 's3'], tables: null });
|
|
17
|
+
assert.deepStrictEqual(P.parseParts({ only: 'db,storage' }).parts, ['base', 's3']);
|
|
18
|
+
assert.deepStrictEqual(P.parseParts({ skip: 'code,refs' }).parts, ['base', 'auth', 's3']);
|
|
19
|
+
assert.deepStrictEqual(P.parseParts({ only: 'base', withSecrets: true }).parts, ['base', 'secrets']);
|
|
20
|
+
assert.deepStrictEqual(P.parseParts({ tables: 'livres,compta.ecritures' }).tables, ['public.livres', 'compta.ecritures']);
|
|
21
|
+
assert.throws(() => P.parseParts({ only: 'base', skip: 'auth' }), /choose one/);
|
|
22
|
+
assert.throws(() => P.parseParts({ only: 'secrets' }), /--with-secrets/);
|
|
23
|
+
assert.throws(() => P.parseParts({ only: 'tout' }), /unknown part/);
|
|
24
|
+
assert.throws(() => P.parseParts({ only: 'auth', tables: 'a' }), /base part/);
|
|
25
|
+
assert.throws(() => P.parseParts({ tables: 'a;drop' }), /expected table/);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('compareTables: copiable, missing, different type, new not-null column, references left out, --tables', () => {
|
|
29
|
+
const src = [
|
|
30
|
+
tbl('public', 'livres', [col('id', 'integer'), col('titre'), col('titre_maj', 'text', { generated: true })]),
|
|
31
|
+
tbl('public', 'absente', [col('id', 'integer')]),
|
|
32
|
+
tbl('public', 'typee', [col('id', 'integer'), col('prix', 'numeric')]),
|
|
33
|
+
tbl('public', 'stricte', [col('id', 'integer')]),
|
|
34
|
+
tbl('ref', 'communes', [col('id', 'integer')]),
|
|
35
|
+
];
|
|
36
|
+
const dst = [
|
|
37
|
+
tbl('public', 'livres', [col('id', 'integer'), col('titre'), col('titre_maj', 'text', { generated: true }), col('note', 'text')]),
|
|
38
|
+
tbl('public', 'typee', [col('id', 'integer'), col('prix', 'text')]),
|
|
39
|
+
tbl('public', 'stricte', [col('id', 'integer'), col('obligatoire', 'text', { notnull: true })]),
|
|
40
|
+
tbl('ref', 'communes', [col('id', 'integer')]),
|
|
41
|
+
tbl('public', 'seulement_cible', [col('id', 'integer')]),
|
|
42
|
+
];
|
|
43
|
+
const r = P.compareTables(src, dst, { exclude: ['ref.communes'] });
|
|
44
|
+
assert.deepStrictEqual(r.tables.map((t) => [t.key, t.columns]), [['public.livres', ['id', 'titre']]]);
|
|
45
|
+
assert.deepStrictEqual(r.blocked.map((b) => [b.key, b.reason]), [['public.absente', 'missing'], ['public.typee', 'differs'], ['public.stricte', 'differs']]);
|
|
46
|
+
assert.match(r.blocked[1].detail, /numeric here, text on the target/);
|
|
47
|
+
assert.match(r.blocked[2].detail, /obligatoire \(not null, no default\) only on the target/);
|
|
48
|
+
assert.deepStrictEqual(r.excluded, [{ key: 'ref.communes', reason: 'reference' }]);
|
|
49
|
+
assert.deepStrictEqual(r.extra, ['public.seulement_cible']);
|
|
50
|
+
const only = P.compareTables(src, dst, { only: ['public.livres', 'public.inconnue'] });
|
|
51
|
+
assert.deepStrictEqual(only.tables.map((t) => t.key), ['public.livres']);
|
|
52
|
+
assert.deepStrictEqual(only.unknown, ['public.inconnue']);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('diffHashes: by primary key (added, replaced, deleted, unchanged), and as multisets without one', () => {
|
|
56
|
+
const src = ['k1 a', 'k2 b', 'k3 c'].join('\n');
|
|
57
|
+
const dst = ['k1 a', 'k2 X', 'k9 z'].join('\n');
|
|
58
|
+
assert.deepStrictEqual(P.diffHashes(src, dst, true), { added: 1, replaced: 1, deleted: 1, unchanged: 1, rows: 3, target_rows: 3, exact: true });
|
|
59
|
+
assert.deepStrictEqual(P.diffHashes('a\na\nb', 'a\nc', false), { added: 2, replaced: 0, deleted: 1, unchanged: 1, rows: 3, target_rows: 2, exact: true });
|
|
60
|
+
assert.ok(!P.changed(P.diffHashes('k1 a', 'k1 a', true)));
|
|
61
|
+
assert.ok(P.changed({ exact: false, rows: 3, target_rows: 3 }));
|
|
62
|
+
assert.ok(!P.changed({ exact: false, rows: 0, target_rows: 0 }));
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('hashSql: fingerprints of key and row over the copied columns, tokens blanked; never a value out', () => {
|
|
66
|
+
const t = { schema: 'auth', name: 'users', columns: ['id', 'email', 'confirmation_token'], pk: ['id'] };
|
|
67
|
+
assert.strictEqual(P.hashSql(t, { blank: ['confirmation_token'] }), `select md5(row("id")::text) || ' ' || md5(row("id", "email", null::text)::text) from "auth"."users"`);
|
|
68
|
+
assert.strictEqual(P.hashSql({ ...t, pk: null }), `select md5(row("id", "email", "confirmation_token")::text) from "auth"."users"`);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('fits: rows to write + 10 % + journal reserve against the room left', () => {
|
|
72
|
+
const GiB = 1024 ** 3;
|
|
73
|
+
assert.deepStrictEqual(P.fits(100, null), { known: false, ok: true });
|
|
74
|
+
const ok = P.fits(100 * 1024 ** 2, { limit: GiB, used: 0.2 * GiB });
|
|
75
|
+
assert.ok(ok.known && ok.ok);
|
|
76
|
+
assert.strictEqual(ok.reserve, 256 * 1024 ** 2);
|
|
77
|
+
assert.ok(!P.fits(700 * 1024 ** 2, { limit: GiB, used: 0.2 * GiB }).ok);
|
|
78
|
+
assert.strictEqual(P.walReserve(100), 64 * 1024 ** 2);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('sequencesFor: those of the copied tables, unowned ones only for the whole base, already equal ones skipped', () => {
|
|
82
|
+
const src = [{ schema: 'public', name: 'a_id_seq', owner: 'public.a', last: 10 }, { schema: 'public', name: 'libre', owner: null, last: 3 }, { schema: 'public', name: 'b_id_seq', owner: 'public.b', last: 5 }, { schema: 'public', name: 'egal', owner: 'public.a', last: 7 }];
|
|
83
|
+
const dst = [{ schema: 'public', name: 'a_id_seq', last: 1 }, { schema: 'public', name: 'libre', last: 1 }, { schema: 'public', name: 'egal', last: 7 }];
|
|
84
|
+
assert.deepStrictEqual(P.sequencesFor(src, dst, ['public.a']).map((s) => s.name), ['a_id_seq']);
|
|
85
|
+
assert.deepStrictEqual(P.sequencesFor(src, dst, ['public.a'], { all: true }).map((s) => s.name), ['a_id_seq', 'libre']);
|
|
86
|
+
assert.match(P.sequencesSql([{ schema: 'public', name: 'a_id_seq' }]), /setval/);
|
|
87
|
+
assert.strictEqual(P.sequencesSql([]), null);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('authPlan: common columns, columns lost, sessions closed before accounts, tokens emptied', () => {
|
|
91
|
+
const users = (extra = []) => ({ rows: 2, bytes: 100, pk: ['id'], columns: [col('id', 'uuid'), col('email'), col('confirmation_token'), ...extra] });
|
|
92
|
+
const src = { users: users([col('nouvelle')]), identities: { rows: 2, bytes: 10, pk: ['id'], columns: [col('id', 'uuid'), col('email', 'text', { generated: true })] }, sessions: { rows: 0, columns: [] } };
|
|
93
|
+
const dst = { users: users(), identities: { rows: 0, bytes: 0, pk: ['id'], columns: [col('id', 'uuid'), col('email', 'text', { generated: true })] }, sessions: { rows: 4, columns: [] }, refresh_tokens: { rows: 4, columns: [] } };
|
|
94
|
+
const a = P.authPlan(src, dst);
|
|
95
|
+
assert.deepStrictEqual(a.tables.map((t) => [t.name, t.columns]), [['users', ['id', 'email', 'confirmation_token']], ['identities', ['id']]]);
|
|
96
|
+
assert.deepStrictEqual(a.dropped, ['auth.users.nouvelle']);
|
|
97
|
+
assert.deepStrictEqual(a.clear, ['delete from auth."refresh_tokens";', 'delete from auth."sessions";', 'delete from auth."identities";', 'delete from auth."users";']);
|
|
98
|
+
assert.deepStrictEqual(a.after, [`update auth."users" set "confirmation_token" = '' where "confirmation_token" <> '';`]);
|
|
99
|
+
});
|
|
100
|
+
|
|
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' });
|
|
103
|
+
assert.match(s, /set -o pipefail/);
|
|
104
|
+
assert.match(s, /printf '%s\\n' 'begin;'/);
|
|
105
|
+
assert.match(s, /session_replication_role = replica/);
|
|
106
|
+
assert.match(s, /begin isolation level repeatable read read only;/);
|
|
107
|
+
assert.match(s, /\\echo 'COPY "public"\."l''o" \("a", "b"\) FROM stdin;'/);
|
|
108
|
+
assert.match(s, /COPY \(select "a", "b" from "public"\."l'o"\) TO STDOUT;/);
|
|
109
|
+
assert.match(s, /\\echo '\\\\\.'/);
|
|
110
|
+
assert.match(s, /\| dst -v ON_ERROR_STOP=1/);
|
|
111
|
+
assert.ok(s.indexOf("'commit;'") > s.indexOf('POAD_SRC_EOF\n printf'), 'commit after the source');
|
|
112
|
+
assert.ok(!/PGPASSWORD=/.test(s), 'no password in the script');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('secretsSql: storage credentials kept on both sides, nothing read from the target; source stops on the first error', () => {
|
|
116
|
+
const q = P.secretsSql({ variables: true, credentials: true, vault: true }, { targetStorage: ['s3-prod'] }).join('\n');
|
|
117
|
+
assert.match(q, /update _poad\.variables set value = null/);
|
|
118
|
+
assert.match(q, /slot like 'storage\.%'\)::text\[\]/);
|
|
119
|
+
assert.match(q, /array\['s3-prod'\]::text\[\]/);
|
|
120
|
+
assert.match(q, /vault\.decrypted_secrets/);
|
|
121
|
+
const sh = P.secretsScript({ srcFn: 'S', dstFn: 'D', queries: ['select 1'] });
|
|
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
|
+
});
|
|
124
|
+
|
|
125
|
+
test('parseMarkers and errorLine: timings, exit code, the ERROR line only (never CONTEXT, which quotes rows)', () => {
|
|
126
|
+
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
|
+
assert.deepStrictEqual(m.tables, { 0: { start: 1000 }, 1: { start: 1500 } });
|
|
128
|
+
assert.strictEqual(m.rc, 3);
|
|
129
|
+
assert.strictEqual(P.errorLine(m.errors), 'ERROR: duplicate key value');
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test('code: mirrored paths, plan keeps uncommitted or untracked local files', () => {
|
|
133
|
+
assert.ok(C.mirrored('functions/hello/index.ts'));
|
|
134
|
+
assert.ok(C.mirrored('seed.sql'));
|
|
135
|
+
assert.ok(!C.mirrored('migrations/20260101000000_a.sql'));
|
|
136
|
+
assert.ok(!C.mirrored('functions/node_modules/x/index.js'));
|
|
137
|
+
assert.ok(!C.mirrored('config.toml'));
|
|
138
|
+
assert.ok(!C.mirrored('reference/.gitignore'));
|
|
139
|
+
const B = (t) => Buffer.from(t);
|
|
140
|
+
const remote = new Map([['functions/a/index.ts', B('new')], ['flows/f.json', B('same')], ['functions/b/index.ts', B('remote')], ['queries/new.sql', B('q')]]);
|
|
141
|
+
const local = new Map([['functions/a/index.ts', B('old')], ['flows/f.json', B('same')], ['functions/b/index.ts', B('local edit')], ['sources/gone.yaml', B('x')], ['sources/mine.yaml', B('y')]]);
|
|
142
|
+
const git = { repo: true, tracked: new Set(['functions/a/index.ts', 'flows/f.json', 'functions/b/index.ts', 'sources/gone.yaml']), dirty: new Set(['functions/b/index.ts']) };
|
|
143
|
+
const p = C.planFiles(remote, local, git);
|
|
144
|
+
assert.deepStrictEqual(p.add, ['queries/new.sql']);
|
|
145
|
+
assert.deepStrictEqual(p.update, ['functions/a/index.ts']);
|
|
146
|
+
assert.deepStrictEqual(p.remove, ['sources/gone.yaml']);
|
|
147
|
+
assert.strictEqual(p.unchanged, 1);
|
|
148
|
+
assert.deepStrictEqual(p.kept.map((k) => [k.rel, k.reason]), [['functions/b/index.ts', 'uncommitted changes'], ['sources/mine.yaml', 'not tracked by git']]);
|
|
149
|
+
// Hors dépôt git : rien n'est remplacé ni retiré
|
|
150
|
+
const nogit = C.planFiles(remote, local, { repo: false, tracked: new Set(), dirty: new Set() });
|
|
151
|
+
assert.deepStrictEqual([nogit.update, nogit.remove], [[], []]);
|
|
152
|
+
assert.strictEqual(nogit.kept[0].reason, 'not in a git repository');
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
// --- La commande entière : faux poad.io (HTTP) et fausse base (deps.pg) ------------------------------------
|
|
156
|
+
|
|
157
|
+
function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, events = 200 } = {}) {
|
|
158
|
+
return new Promise((resolve) => {
|
|
159
|
+
const server = http.createServer((req, res) => {
|
|
160
|
+
let body = '';
|
|
161
|
+
req.on('data', (d) => (body += d)).on('end', () => {
|
|
162
|
+
seen.push({ method: req.method, url: req.url, body });
|
|
163
|
+
const send = (s, o) => (res.writeHead(s, { 'content-type': 'application/json' }), res.end(JSON.stringify(o)));
|
|
164
|
+
if (/\/branches$/.test(req.url)) return send(200, [{ name: 'main', kind: 'production' }, { name: 'dev' }]);
|
|
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 });
|
|
167
|
+
if (/\/backup$/.test(req.url)) return send(200, { file: 'pre-deploy-20261205-000000.dump', bytes: 1234 });
|
|
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
|
+
}
|
|
173
|
+
send(404, { error: { code: 'not_found', message: 'route inconnue' } });
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
server.listen(0, '127.0.0.1', () => {
|
|
177
|
+
t.after(() => server.close());
|
|
178
|
+
resolve(`http://127.0.0.1:${server.address().port}`);
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Fausse base : inventaires de la source et de la cible, empreintes, transfert enregistré */
|
|
184
|
+
function fakePg(scripts, { same = false, queries = [] } = {}) {
|
|
185
|
+
const real = require('../utils/project-sync/pg');
|
|
186
|
+
const inv = (rows) => ({
|
|
187
|
+
tables: [tbl('public', 'livres', [col('id', 'integer'), col('titre')], { pk: ['id'] }), tbl('ref', 'communes', [col('id', 'integer')])],
|
|
188
|
+
sequences: [{ schema: 'public', name: 'livres_id_seq', owner: 'public.livres', last: rows }],
|
|
189
|
+
migrations: ['20261205100000'],
|
|
190
|
+
auth: { users: { rows: 1, bytes: 10, pk: ['id'], columns: [col('id', 'uuid'), col('email')] } },
|
|
191
|
+
variables: ['MAIL_FROM'],
|
|
192
|
+
credentials: ['api-meteo'],
|
|
193
|
+
storage_credentials: [],
|
|
194
|
+
});
|
|
195
|
+
return {
|
|
196
|
+
localSide: real.localSide,
|
|
197
|
+
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)),
|
|
199
|
+
query: async (container, side, sql) => {
|
|
200
|
+
queries.push(sql);
|
|
201
|
+
// Empreintes : la source a trois livres, la cible deux (un remplacé) ; un compte identique
|
|
202
|
+
const local = side.kind === 'local';
|
|
203
|
+
const parts = sql.split(/\\echo @@T (\d+)\n/).filter(Boolean);
|
|
204
|
+
let out = '';
|
|
205
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
206
|
+
out += `@@T ${parts[i]}\n`;
|
|
207
|
+
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';
|
|
209
|
+
}
|
|
210
|
+
return out;
|
|
211
|
+
},
|
|
212
|
+
transfer: async (container, src, dst, script) => {
|
|
213
|
+
scripts.push(script);
|
|
214
|
+
return { code: 0, stdout: Buffer.alloc(0), stderr: '@@poad start 0 1000\n@@poad done 1200 0\n' };
|
|
215
|
+
},
|
|
216
|
+
dumpLocal: async () => 10,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
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'));
|
|
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');
|
|
225
|
+
const seen = [];
|
|
226
|
+
const scripts = [];
|
|
227
|
+
const base = await fakeCloud(t, seen, cloud);
|
|
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 };
|
|
229
|
+
const printed = [];
|
|
230
|
+
process.chdir(dir);
|
|
231
|
+
process.env.POAD_CLOUD_API = base;
|
|
232
|
+
process.env.POAD_ACCESS_TOKEN = 'poad_pat_test';
|
|
233
|
+
console.log = (...a) => printed.push(a.join(' '));
|
|
234
|
+
console.error = (...a) => printed.push(a.join(' '));
|
|
235
|
+
const isTTY = process.stdin.isTTY;
|
|
236
|
+
process.stdin.isTTY = tty;
|
|
237
|
+
try {
|
|
238
|
+
process.exitCode = 0;
|
|
239
|
+
await require('../utils/project-sync/run').run(args[0], args.slice(1), {
|
|
240
|
+
pg: fakePg(scripts, pg),
|
|
241
|
+
started: async () => true,
|
|
242
|
+
...deps,
|
|
243
|
+
credentials: async () => ({ user: 'postgres.pptest123456--dev', password: 'pw-never-shown', host: 'db.poad.io', port: () => 5432 }),
|
|
244
|
+
});
|
|
245
|
+
return { code: process.exitCode, out: printed.join('\n'), seen, scripts };
|
|
246
|
+
} finally {
|
|
247
|
+
process.stdin.isTTY = isTTY;
|
|
248
|
+
process.chdir(saved.cwd);
|
|
249
|
+
process.env.POAD_CLOUD_API = saved.api;
|
|
250
|
+
process.env.POAD_ACCESS_TOKEN = saved.tok;
|
|
251
|
+
if (saved.api === undefined) delete process.env.POAD_CLOUD_API;
|
|
252
|
+
if (saved.tok === undefined) delete process.env.POAD_ACCESS_TOKEN;
|
|
253
|
+
console.log = saved.log;
|
|
254
|
+
console.error = saved.err;
|
|
255
|
+
process.exitCode = saved.code;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
test('poad push --dry-run: preview per table, reference tables left to refs, nothing written, nothing logged', async (t) => {
|
|
260
|
+
const r = await runCmd(t, ['push', '--env', 'dev', '--only', 'base,auth', '--dry-run', '--json']);
|
|
261
|
+
assert.strictEqual(r.code, 0);
|
|
262
|
+
const j = JSON.parse(r.out.slice(r.out.indexOf('{')));
|
|
263
|
+
assert.strictEqual(j.dry_run, true);
|
|
264
|
+
assert.deepStrictEqual(j.preview.base.tables.map((x) => [x.table, x.added, x.replaced, x.deleted, x.unchanged]), [['public.livres', 1, 1, 0, 1]]);
|
|
265
|
+
assert.deepStrictEqual(j.preview.base.excluded, [{ key: 'ref.communes', reason: 'reference' }]);
|
|
266
|
+
assert.strictEqual(j.preview.auth.changed, false);
|
|
267
|
+
assert.strictEqual(r.scripts.length, 0);
|
|
268
|
+
assert.ok(!r.seen.some((s) => /sync-events|backup/.test(s.url)));
|
|
269
|
+
assert.ok(!r.out.includes('pw-never-shown'));
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
test('poad push to production outside a terminal: refused without --yes --confirm <id>, nothing written', async (t) => {
|
|
273
|
+
const r = await runCmd(t, ['push', '--env', 'main', '--only', 'base', '--yes']);
|
|
274
|
+
assert.strictEqual(r.code, 4);
|
|
275
|
+
assert.match(r.out, /--yes --confirm pptest123456/);
|
|
276
|
+
assert.strictEqual(r.scripts.length, 0);
|
|
277
|
+
assert.ok(!r.seen.some((s) => /backup/.test(s.url)));
|
|
278
|
+
const bad = await runCmd(t, ['push', '--env', 'main', '--only', 'base', '--yes', '--confirm', 'autre']);
|
|
279
|
+
assert.strictEqual(bad.code, 4);
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
test('poad push to production with --yes --confirm: backup first, one transfer, logs per table on poad.io (no value)', async (t) => {
|
|
283
|
+
const r = await runCmd(t, ['push', '--env', 'main', '--only', 'base,auth', '--yes', '--confirm', 'pptest123456']);
|
|
284
|
+
assert.strictEqual(r.code, 0, r.out);
|
|
285
|
+
const order = r.seen.map((s) => s.url.replace(/^.*\/branches\/[^/]+\//, '')).filter((u) => ['backup', 'sync-events'].includes(u));
|
|
286
|
+
assert.deepStrictEqual(order, ['backup', 'sync-events']);
|
|
287
|
+
assert.strictEqual(r.scripts.length, 1);
|
|
288
|
+
assert.match(r.scripts[0], /delete from "public"\."livres";/);
|
|
289
|
+
assert.ok(!/auth\."users"/.test(r.scripts[0]), 'identical accounts are not rewritten');
|
|
290
|
+
assert.match(r.scripts[0], /setval/);
|
|
291
|
+
const ev = JSON.parse(r.seen.find((s) => /sync-events/.test(s.url)).body);
|
|
292
|
+
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']]);
|
|
294
|
+
assert.strictEqual(ev.lines[1].rows, 3);
|
|
295
|
+
assert.ok(!JSON.stringify(ev).includes('pw-never-shown'));
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
test('poad pull --tables of an unknown table: stopped before anything is written', async (t) => {
|
|
299
|
+
const r = await runCmd(t, ['pull', '--env', 'dev', '--only', 'base', '--tables', 'inconnue', '--yes']);
|
|
300
|
+
assert.strictEqual(r.code, 5);
|
|
301
|
+
assert.match(r.out, /public\.inconnue not in the source/);
|
|
302
|
+
assert.strictEqual(r.scripts.length, 0);
|
|
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
|
+
});
|