poad 2.61.1 → 2.63.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/global/start.js +5 -1
- package/package.json +1 -1
- package/project/cli.js +6 -3
- package/project/logs.js +7 -0
- package/project/source.js +286 -0
- package/project/sources.js +2 -0
- package/project/storage/cp.js +45 -15
- package/project/storage/ls.js +20 -6
- package/project/storage/mv.js +5 -5
- package/project/storage/sync.js +101 -0
- package/test/logs.test.js +8 -0
- package/test/source.test.js +245 -0
- package/test/storage-sync.test.js +283 -0
- package/test/storage.test.js +233 -4
- package/utils/cloud/bundle.js +2 -2
- package/utils/help-details.js +64 -5
- package/utils/logline.js +2 -2
- package/utils/storage-copy.js +91 -15
- package/utils/storage-sync.js +277 -0
- package/utils/storage.js +94 -3
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// poad source ls | refresh : engine local (main avec deps) et poad.io (--env, faux serveur
|
|
2
|
+
// qui tient lieu de poad.io et de l'engine hébergé) ; filtre source= de poad logs ;
|
|
3
|
+
// poad/sources dans l'archive de poad deploy.
|
|
4
|
+
const test = require('node:test');
|
|
5
|
+
const assert = require('node:assert');
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const http = require('http');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const zlib = require('zlib');
|
|
10
|
+
const { spawn } = require('child_process');
|
|
11
|
+
const { tmpdir } = require('./helpers');
|
|
12
|
+
|
|
13
|
+
const POAD = path.join(__dirname, '..', 'poad.js');
|
|
14
|
+
const PKG = require('../package.json');
|
|
15
|
+
const source = require('../project/source');
|
|
16
|
+
const TOKEN = 'poad_pat_SOURCETEST0123456789abcdefSECRET';
|
|
17
|
+
const SERVICE = 'eyJ-short-service-role-NEVER-SHOWN';
|
|
18
|
+
const ANON = 'eyJ-anon-public-key-NEVER-SHOWN';
|
|
19
|
+
const PID = 'abcdef123456';
|
|
20
|
+
const RUN = '7c2e1d90-4b3a-4f1e-8d2c-5a6b7c8d9e0f';
|
|
21
|
+
|
|
22
|
+
const LIST = {
|
|
23
|
+
available: true,
|
|
24
|
+
dir: 'poad/sources',
|
|
25
|
+
sources: [
|
|
26
|
+
{ name: 'communes', file: 'poad/sources/communes.yaml', valid: true, problems: [], title: 'Communes', mode: 'synchronized', table: 'public.communes', flow: { name: 'source-communes', enabled: true, version: 1 }, api: true, rows: 34969, drift: { issues: [], sql: [] }, last_run: { id: RUN, status: 'completed' }, age_seconds: 300, next_run_at: '2026-12-03T04:00:00.000Z' },
|
|
27
|
+
{ name: 'gares', file: 'poad/sources/gares.yaml', valid: false, problems: [{ path: 'key', line: 4, message: 'la clé « id » ne fait pas partie des colonnes' }], title: null, mode: null, table: null, flow: null },
|
|
28
|
+
],
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const BILAN = { source: 'communes', table: 'public.communes', received: 34969, kept: 34969, inserted: 34969, updated: 0, deleted: 0, unchanged: 0, rows: 34969, forced: false, problems: [], duration_ms: 812 };
|
|
32
|
+
const GUARD = 'source « communes » : 34 700 ligne(s) sur 34 969 seraient supprimées (plus de 20 %). Aucune ligne n\'a été modifiée.';
|
|
33
|
+
|
|
34
|
+
/** Faux poad.io + engine : behaviour.outcome = completed | guard */
|
|
35
|
+
function fakeCloud(t, behaviour = {}) {
|
|
36
|
+
const state = { requests: [], polls: 0 };
|
|
37
|
+
const send = (res, status, body) => {
|
|
38
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
39
|
+
res.end(JSON.stringify(body));
|
|
40
|
+
};
|
|
41
|
+
const server = http.createServer((req, res) => {
|
|
42
|
+
const chunks = [];
|
|
43
|
+
req.on('data', (c) => chunks.push(c));
|
|
44
|
+
req.on('end', () => {
|
|
45
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
46
|
+
const body = raw ? JSON.parse(raw) : null;
|
|
47
|
+
const url = new URL(req.url, 'http://x');
|
|
48
|
+
state.requests.push({ method: req.method, path: url.pathname, headers: req.headers, body });
|
|
49
|
+
if (url.pathname === `/_poad/cloud/v1/projects/${PID}/storage-token` && req.method === 'POST') {
|
|
50
|
+
if (req.headers.authorization !== `Bearer ${TOKEN}`) return send(res, 401, { error: { code: 'unauthorized', message: 'session' } });
|
|
51
|
+
return send(res, 200, { url: `http://127.0.0.1:${server.address().port}`, anon_key: ANON, token: SERVICE, expires_at: new Date(Date.now() + 900000).toISOString() });
|
|
52
|
+
}
|
|
53
|
+
if (url.pathname.startsWith('/meta/v1/') || url.pathname.startsWith('/flows/v1/')) {
|
|
54
|
+
if (req.headers.authorization !== `Bearer ${SERVICE}` || req.headers.apikey !== ANON) return send(res, 401, { error: { code: 'unauthorized', message: 'bad token' } });
|
|
55
|
+
if (req.method === 'GET' && url.pathname === '/meta/v1/sources') return send(res, 200, LIST);
|
|
56
|
+
if (req.method === 'POST' && url.pathname === '/meta/v1/sources/communes/refresh') return send(res, 202, { source: 'communes', flow: 'source-communes', run_id: RUN, force: body && body.force === true, drift: { issues: [], sql: [] } });
|
|
57
|
+
if (req.method === 'POST' && url.pathname === '/meta/v1/sources/inconnue/refresh') return send(res, 404, { error: { code: 'not_found', message: 'source inconnue : inconnue', hint: 'déclarez-la dans poad/sources/inconnue.yaml' } });
|
|
58
|
+
if (req.method === 'GET' && url.pathname === `/flows/v1/runs/${RUN}`) {
|
|
59
|
+
state.polls++;
|
|
60
|
+
const guard = behaviour.outcome === 'guard';
|
|
61
|
+
const steps = [
|
|
62
|
+
{ step_id: 'declencheur', name: 'a_la_demande', status: 'done', attempt: 0, duration_ms: 2 },
|
|
63
|
+
{ step_id: 'telecharger', name: 'telecharger', status: 'done', attempt: 0, duration_ms: 1500 },
|
|
64
|
+
];
|
|
65
|
+
if (state.polls === 1) return send(res, 200, { id: RUN, flow: 'source-communes', status: 'running', steps, duration_ms: null });
|
|
66
|
+
steps.push({ step_id: 'lire', name: 'lire', status: 'done', attempt: 0, duration_ms: 900, output: { rows: 34969, file: 'rows.jsonl', problems: { count: 0, examples: [] } } });
|
|
67
|
+
steps.push({ step_id: 'deposer', name: 'deposer', status: 'done', attempt: 0, duration_ms: 700 });
|
|
68
|
+
steps.push(guard ? { step_id: 'appliquer', name: 'appliquer', status: 'failed', attempt: 0, duration_ms: 300, error: GUARD } : { step_id: 'appliquer', name: 'appliquer', status: 'done', attempt: 0, duration_ms: 900, output: { rows: [{ bilan: BILAN }] } });
|
|
69
|
+
return send(res, 200, { id: RUN, flow: 'source-communes', status: guard ? 'failed' : 'completed', steps, duration_ms: 4400, error: guard ? 'step "appliquer" failed' : null });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
send(res, 404, { error: { code: 'not_found', message: 'route' } });
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
server.listen(0, '127.0.0.1', () => {
|
|
77
|
+
t.after(() => server.close());
|
|
78
|
+
resolve({ state, api: `http://127.0.0.1:${server.address().port}/_poad/cloud` });
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function sandbox(t, { engine = '0.64.0' } = {}) {
|
|
84
|
+
const dir = tmpdir(t, 'poad-source-');
|
|
85
|
+
const home = path.join(dir, 'home');
|
|
86
|
+
fs.mkdirSync(home);
|
|
87
|
+
fs.writeFileSync(path.join(home, '.poad_last_check.json'), JSON.stringify({ date: new Date(), version: PKG.version }));
|
|
88
|
+
const app = path.join(dir, 'app');
|
|
89
|
+
fs.mkdirSync(path.join(app, 'poad'), { recursive: true });
|
|
90
|
+
fs.writeFileSync(path.join(app, 'poad', 'config.toml'), `project_id = "demo"\nproject_uuid = "poad-source-test-not-a-container"\nengine = "${engine}"\n[web]\nport = 1\n[db]\nport = 1\n[cloud]\nproject = "${PID}"\n`);
|
|
91
|
+
fs.writeFileSync(path.join(app, 'poad', 'secrets.toml'), '[auth]\nsecret = "LOCAL-SECRET-x"\nanon = "LOCAL-ANON-x"\nservice = "LOCAL-SERVICE-x"\nadmin = "LOCAL-ADMIN-x"\n');
|
|
92
|
+
return { dir, home, app };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function poad(box, api, args) {
|
|
96
|
+
return new Promise((resolve) => {
|
|
97
|
+
const child = spawn(process.execPath, [POAD, ...args], {
|
|
98
|
+
cwd: box.app,
|
|
99
|
+
env: { ...process.env, HOME: box.home, POAD_CLOUD_API: api, POAD_ACCESS_TOKEN: TOKEN, NODE_OPTIONS: '', FORCE_COLOR: '0' },
|
|
100
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
101
|
+
});
|
|
102
|
+
let stdout = '';
|
|
103
|
+
let stderr = '';
|
|
104
|
+
child.stdout.on('data', (d) => (stdout += d));
|
|
105
|
+
child.stderr.on('data', (d) => (stderr += d));
|
|
106
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), 30000);
|
|
107
|
+
child.on('close', (status) => {
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
resolve({ status, stdout, stderr, all: stdout + stderr });
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const noSecret = (r) => {
|
|
115
|
+
for (const s of [TOKEN, SERVICE, ANON, 'LOCAL-SERVICE-x']) assert.ok(!r.all.includes(s), 'a key or token was printed');
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// --- poad.io (--env) -----------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
test('source ls --env : jeton de poad.io, une ligne par source, la déclaration invalide signalée, code 1', async (t) => {
|
|
121
|
+
const cloud = await fakeCloud(t);
|
|
122
|
+
const box = sandbox(t);
|
|
123
|
+
const r = await poad(box, cloud.api, ['source', 'ls', '--env', 'dev']);
|
|
124
|
+
noSecret(r);
|
|
125
|
+
assert.strictEqual(r.status, 1, r.all);
|
|
126
|
+
assert.deepStrictEqual(cloud.state.requests.find((q) => q.path.endsWith('/storage-token')).body, { branch: 'dev' });
|
|
127
|
+
assert.match(r.stdout, /✔ communes .*synchronized {2}public\.communes {2}34,969 rows {2}synced 5 min ago {2}next 2026-12-03 04:00 UTC {2}api/);
|
|
128
|
+
assert.match(r.stdout, /✖ gares/);
|
|
129
|
+
assert.match(r.stdout, /line 4: la clé « id » ne fait pas partie des colonnes/);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test('source refresh --env : suivi des étapes, bilan, code 0', async (t) => {
|
|
133
|
+
const cloud = await fakeCloud(t);
|
|
134
|
+
const box = sandbox(t);
|
|
135
|
+
const r = await poad(box, cloud.api, ['sources', 'refresh', 'communes', '--env=dev']);
|
|
136
|
+
noSecret(r);
|
|
137
|
+
assert.strictEqual(r.status, 0, r.all);
|
|
138
|
+
assert.deepStrictEqual(cloud.state.requests.find((q) => q.path === '/meta/v1/sources/communes/refresh').body, { force: false });
|
|
139
|
+
assert.match(r.stdout, /flow source-communes, run 7c2e1d90/);
|
|
140
|
+
assert.match(r.stdout, /✔ telecharger {2}done in 1\.5 s/);
|
|
141
|
+
assert.match(r.stdout, /✔ appliquer {2}done/);
|
|
142
|
+
assert.match(r.stdout, /completed in 4\.4 s/);
|
|
143
|
+
assert.match(r.stdout, /34,969 received, 34,969 added, 0 updated, 0 removed, 0 unchanged/);
|
|
144
|
+
assert.match(r.stdout, /public\.communes: 34,969 rows, applied in 812 ms/);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('source refresh : refus du garde-fou, rien changé, --force proposé, code 1 ; --force transmis', async (t) => {
|
|
148
|
+
const cloud = await fakeCloud(t, { outcome: 'guard' });
|
|
149
|
+
const box = sandbox(t);
|
|
150
|
+
const r = await poad(box, cloud.api, ['source', 'refresh', 'communes', '--env', 'dev']);
|
|
151
|
+
noSecret(r);
|
|
152
|
+
assert.strictEqual(r.status, 1, r.all);
|
|
153
|
+
assert.match(r.stdout, /✖ appliquer {2}failed: source « communes » : 34 700 ligne\(s\)/);
|
|
154
|
+
assert.match(r.stdout, /poad source refresh communes --force --env dev/);
|
|
155
|
+
assert.match(r.stdout, /poad logs source=communes/);
|
|
156
|
+
const f = await poad(box, cloud.api, ['source', 'refresh', 'communes', '--force', '--env', 'dev', '--detach']);
|
|
157
|
+
assert.strictEqual(f.status, 0, f.all);
|
|
158
|
+
assert.strictEqual(f.stdout.trim(), RUN);
|
|
159
|
+
assert.deepStrictEqual(cloud.state.requests.filter((q) => q.path === '/meta/v1/sources/communes/refresh').pop().body, { force: true });
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test('source refresh : source inconnue (message de meta), nom invalide et usage', async (t) => {
|
|
163
|
+
const cloud = await fakeCloud(t);
|
|
164
|
+
const box = sandbox(t);
|
|
165
|
+
const r = await poad(box, cloud.api, ['source', 'refresh', 'inconnue', '--env', 'dev']);
|
|
166
|
+
assert.strictEqual(r.status, 1, r.all);
|
|
167
|
+
assert.match(r.stdout, /source inconnue : inconnue \(déclarez-la dans poad\/sources\/inconnue\.yaml\)/);
|
|
168
|
+
const bad = await poad(box, cloud.api, ['source', 'refresh', 'Mauvais_Nom']);
|
|
169
|
+
assert.strictEqual(bad.status, 2, bad.all);
|
|
170
|
+
const none = await poad(box, cloud.api, ['source', 'refresh']);
|
|
171
|
+
assert.strictEqual(none.status, 2, none.all);
|
|
172
|
+
const other = await poad(box, cloud.api, ['source', 'bogus']);
|
|
173
|
+
assert.strictEqual(other.status, 2, other.all);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
// --- engine local (main avec deps) -----------------------------------------------
|
|
177
|
+
|
|
178
|
+
test('source ls en local : clé service_role du projet, engine 0.64.0 exigé, projet lancé exigé', async (t) => {
|
|
179
|
+
const box = sandbox(t);
|
|
180
|
+
const calls = [];
|
|
181
|
+
const fakeFetch = async (url, init) => {
|
|
182
|
+
calls.push({ url, headers: init.headers });
|
|
183
|
+
return { status: 200, json: async () => ({ available: true, sources: [] }) };
|
|
184
|
+
};
|
|
185
|
+
const logs = [];
|
|
186
|
+
const orig = console.log;
|
|
187
|
+
console.log = (...a) => logs.push(a.join(' '));
|
|
188
|
+
try {
|
|
189
|
+
await source.main({}, ['ls'], { cwd: box.app, fetch: fakeFetch, started: async () => true });
|
|
190
|
+
await source.main({}, ['ls'], { cwd: box.app, fetch: fakeFetch, started: async () => false });
|
|
191
|
+
} finally {
|
|
192
|
+
console.log = orig;
|
|
193
|
+
process.exitCode = 0;
|
|
194
|
+
}
|
|
195
|
+
assert.strictEqual(calls.length, 1);
|
|
196
|
+
assert.strictEqual(calls[0].url, 'http://localhost:1/meta/v1/sources');
|
|
197
|
+
assert.strictEqual(calls[0].headers.authorization, 'Bearer LOCAL-SERVICE-x');
|
|
198
|
+
assert.ok(logs.some((l) => /None yet: declare one in poad\/sources\/<name>\.yaml\./.test(l)));
|
|
199
|
+
assert.ok(logs.some((l) => /The project is not started/.test(l)));
|
|
200
|
+
|
|
201
|
+
const old = sandbox(t, { engine: '0.63.8' });
|
|
202
|
+
const said = [];
|
|
203
|
+
console.log = (...a) => said.push(a.join(' '));
|
|
204
|
+
try {
|
|
205
|
+
await source.main({}, ['ls'], { cwd: old.app, fetch: fakeFetch, started: async () => true });
|
|
206
|
+
} finally {
|
|
207
|
+
console.log = orig;
|
|
208
|
+
process.exitCode = 0;
|
|
209
|
+
}
|
|
210
|
+
assert.ok(said.some((l) => /Sources need engine 0\.64\.0 or later/.test(l)));
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// --- fonctions pures -------------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
test('reportOf, guardRefused, supportsSources', () => {
|
|
216
|
+
assert.deepStrictEqual(source.reportOf({ steps: [{ step_id: 'appliquer', output: { rows: [{ bilan: BILAN }] } }] }), BILAN);
|
|
217
|
+
assert.strictEqual(source.reportOf({ steps: [{ step_id: 'appliquer', output: null }] }), null);
|
|
218
|
+
assert.strictEqual(source.guardRefused(GUARD), true);
|
|
219
|
+
assert.strictEqual(source.guardRefused('HTTP 500'), false);
|
|
220
|
+
assert.strictEqual(source.supportsSources({ engine: '0.64.0' }), true);
|
|
221
|
+
assert.strictEqual(source.supportsSources({ engine: '0.63.8' }), false);
|
|
222
|
+
assert.strictEqual(source.supportsSources({ engine: '1.0.0' }), true);
|
|
223
|
+
assert.strictEqual(source.NAME_RE.test('communes-2026'), true);
|
|
224
|
+
assert.strictEqual(source.NAME_RE.test('2communes'), false);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
// --- poad logs source=, poad deploy ----------------------------------------------
|
|
228
|
+
|
|
229
|
+
test('poad logs source=<nom> filtre attrs.source_name', () => {
|
|
230
|
+
const { attrConditions } = require('../utils/logline');
|
|
231
|
+
assert.deepStrictEqual(attrConditions({ source: 'communes' }).conditions, [["attrs->>'source_name' = ?", 'communes']]);
|
|
232
|
+
assert.match(attrConditions({ source: true }).error, /source=<name>: a value is expected, such as source=communes/);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test('poad deploy : poad/sources est dans l’archive', (t) => {
|
|
236
|
+
const dir = tmpdir(t, 'poad-source-bundle-');
|
|
237
|
+
fs.mkdirSync(path.join(dir, 'sources'));
|
|
238
|
+
fs.writeFileSync(path.join(dir, 'config.toml'), 'project_id = "demo"\n');
|
|
239
|
+
fs.writeFileSync(path.join(dir, 'sources', 'communes.yaml'), 'title: Communes\n');
|
|
240
|
+
const bundle = require('../utils/cloud/bundle');
|
|
241
|
+
assert.ok(bundle.DIRS.includes('sources'));
|
|
242
|
+
const { files } = bundle.build(dir);
|
|
243
|
+
assert.ok(files.some((f) => f.path === 'sources/communes.yaml'), JSON.stringify(files));
|
|
244
|
+
assert.ok(zlib.gunzipSync(bundle.build(dir).tgz).includes(Buffer.from('sources/communes.yaml')));
|
|
245
|
+
});
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
const { test } = require('node:test');
|
|
2
|
+
const assert = require('node:assert');
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const ss = require('../utils/storage-sync');
|
|
5
|
+
|
|
6
|
+
const md5 = (t) => crypto.createHash('md5').update(t).digest('hex');
|
|
7
|
+
const obj = (name, text, extra = {}) => ({ name, key: null, size: Buffer.byteLength(text), etag: md5(text), mimetype: 'text/plain', cacheControl: 'no-cache', ...extra });
|
|
8
|
+
|
|
9
|
+
test('plan: added, updated, unchanged by name, size and MD5', () => {
|
|
10
|
+
const p = ss.plan([obj('a', 'x'), obj('b', 'new'), obj('c', 'same')], [obj('b', 'old'), obj('c', 'same'), obj('z', 'gone')]);
|
|
11
|
+
assert.deepStrictEqual(p.add.map((o) => o.name), ['a']);
|
|
12
|
+
assert.deepStrictEqual(p.update.map((o) => o.name), ['b']);
|
|
13
|
+
assert.deepStrictEqual(p.unchanged.map((o) => o.name), ['c']);
|
|
14
|
+
assert.deepStrictEqual(p.remove, []); // rien n'est retiré sans --prune
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('plan --prune: removes what the source lacks, keeps a reference the source still uses', () => {
|
|
18
|
+
const src = [obj('a', 'x', { key: 'm/aa/aa1' })];
|
|
19
|
+
const dst = [obj('a', 'x', { key: 'm/aa/aa1' }), obj('old', 'y', { key: 'm/bb/bb1' }), obj('renamed', 'x', { key: 'm/aa/aa1' })];
|
|
20
|
+
const p = ss.plan(src, dst, { prune: true });
|
|
21
|
+
assert.deepStrictEqual(p.unchanged.map((o) => o.name), ['a']);
|
|
22
|
+
assert.deepStrictEqual(p.remove.map((o) => o.name), ['old']);
|
|
23
|
+
assert.deepStrictEqual(p.kept.map((o) => o.name), ['renamed']);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('sameContent: same key, or same size + MD5 + type', () => {
|
|
27
|
+
assert.ok(ss.sameContent({ key: 'k' }, { key: 'k' }));
|
|
28
|
+
assert.ok(ss.sameContent(obj('a', 'x'), obj('a', 'x', { key: 'other' })));
|
|
29
|
+
assert.ok(!ss.sameContent(obj('a', 'x'), obj('a', 'x', { mimetype: 'image/png' })));
|
|
30
|
+
assert.ok(!ss.sameContent(obj('a', 'x', { etag: null }), obj('a', 'x', { etag: null })));
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const P1 = { cloud: 'proj1', local: null, environment: 'main' };
|
|
34
|
+
const P1_LOCAL = { cloud: 'proj1', local: 'uuid1', environment: 'local' };
|
|
35
|
+
const P2 = { cloud: 'proj2', local: null, environment: 'main' };
|
|
36
|
+
|
|
37
|
+
test('sameProject: environments of one project only', () => {
|
|
38
|
+
assert.ok(ss.sameProject(P1, P1_LOCAL));
|
|
39
|
+
assert.ok(ss.sameProject(P1, { ...P1, environment: 'recette' }));
|
|
40
|
+
assert.ok(!ss.sameProject(P1, P2));
|
|
41
|
+
assert.ok(!ss.sameProject(P1, { cloud: null, local: 'uuid1', environment: 'local' }));
|
|
42
|
+
assert.ok(!ss.sameProject(null, P1));
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('decideMode: disk → bytes; same project at the same place → references; never shared between projects', () => {
|
|
46
|
+
const s3 = { backend: 's3', location: 'https://s3.example.test|media|p/', fingerprint: 'f1', shareable: true, sync: true, project: P1_LOCAL };
|
|
47
|
+
const cloud = { ...s3, project: P1 };
|
|
48
|
+
assert.strictEqual(ss.decideMode({ backend: 'file', shareable: false, sync: true }, cloud).mode, 'bytes');
|
|
49
|
+
assert.strictEqual(ss.decideMode(s3, cloud).mode, 'references');
|
|
50
|
+
assert.strictEqual(ss.decideMode(cloud, { ...cloud, project: { ...P1, environment: 'recette' } }).mode, 'references');
|
|
51
|
+
// Destination sur le disque : les octets, d'office, et la raison le dit
|
|
52
|
+
assert.deepStrictEqual(ss.decideMode(s3, { backend: 'file', shareable: false, sync: false }), { mode: 'bytes', reason: 'destination on the engine disk: sending the bytes' });
|
|
53
|
+
assert.strictEqual(ss.decideMode({ backend: 'file', shareable: false, sync: false }, { sync: false }).mode, 'bytes');
|
|
54
|
+
// Lieux différents : arrêt, --copy-bytes proposé
|
|
55
|
+
assert.throws(() => ss.decideMode(s3, { ...cloud, fingerprint: 'f2', location: 'https://s3.example.test|media|q/' }), (e) => e.code === 'location_mismatch' && /--copy-bytes/.test(e.message) && /Nothing was copied/.test(e.message));
|
|
56
|
+
assert.strictEqual(ss.decideMode(s3, { ...cloud, fingerprint: 'f2' }, { copyBytes: true }).mode, 'bytes');
|
|
57
|
+
assert.strictEqual(ss.decideMode(s3, { ...cloud, fingerprint: 'f2', project: P2 }, { copyBytes: true }).mode, 'bytes'); // copie explicite vers un autre projet, ailleurs
|
|
58
|
+
// Deux projets au même lieu : erreur de configuration, rien de copié, même avec --copy-bytes
|
|
59
|
+
for (const copyBytes of [false, true])
|
|
60
|
+
assert.throws(
|
|
61
|
+
() => ss.decideMode(s3, { ...cloud, project: P2 }, { copyBytes }),
|
|
62
|
+
(e) => e.code === 'different_projects' && /two different projects: a storage location is never shared between projects/.test(e.message) && /configuration error/.test(e.message) && !/--copy-bytes/.test(e.message),
|
|
63
|
+
);
|
|
64
|
+
// Identité inconnue (poste non lié, ou engine lancé avant le lien) : rien ne prouve le même projet
|
|
65
|
+
assert.throws(() => ss.decideMode({ ...s3, project: { cloud: null, local: null } }, cloud, { srcLabel: 'local engine' }), (e) => e.code === 'project_unknown' && /local engine cannot tell/.test(e.message) && /poad link/.test(e.message));
|
|
66
|
+
assert.throws(() => ss.decideMode({ ...s3, project: { cloud: null, local: 'uuid1', environment: 'local' } }, cloud), (e) => e.code === 'project_unknown');
|
|
67
|
+
// Storage trop ancien
|
|
68
|
+
assert.throws(() => ss.decideMode(s3, { backend: 's3', sync: false }), (e) => e.code === 'location_unknown' && /0\.4\.0/.test(e.message));
|
|
69
|
+
assert.throws(() => ss.decideMode({ backend: 's3', shareable: null, sync: false }, cloud), (e) => e.code === 'location_unknown');
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('engineEnv: project_uuid and linked poad.io project, nothing else', () => {
|
|
73
|
+
const s = require('../utils/storage');
|
|
74
|
+
assert.deepStrictEqual(s.engineEnv({ project_uuid: 'yin4cnq8', cloud: { project: 'abc123' } }), ['POAD_PROJECT_UUID=yin4cnq8', 'POAD_CLOUD_PROJECT=abc123']);
|
|
75
|
+
assert.deepStrictEqual(s.engineEnv({ project_uuid: 'yin4cnq8' }), ['POAD_PROJECT_UUID=yin4cnq8']);
|
|
76
|
+
assert.deepStrictEqual(s.engineEnv({ project_uuid: 'a b', cloud: { project: 'x;y' } }), []);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// Faux Stockage : la surface du client (utils/storage.client) que sync appelle
|
|
80
|
+
function fakeSide({ location, sync = true, buckets = {}, provider }) {
|
|
81
|
+
const store = new Map(); // `${bucket}/${name}` → { version, text, mimetype, cacheControl }
|
|
82
|
+
const ids = new Set(Object.keys(buckets));
|
|
83
|
+
const calls = [];
|
|
84
|
+
const keyOf = (b, v) => `${b}/${v.slice(0, 2)}/${v}`;
|
|
85
|
+
const row = (b, name, o) => ({ name, key: keyOf(b, o.version), size: Buffer.byteLength(o.text), etag: md5(o.text), mimetype: o.mimetype, cacheControl: o.cacheControl });
|
|
86
|
+
const write = (b, name, text, mimetype = 'text/plain') => {
|
|
87
|
+
const version = crypto.randomUUID();
|
|
88
|
+
provider.set(keyOf(b, version), text);
|
|
89
|
+
store.set(`${b}/${name}`, { version, text, mimetype, cacheControl: 'no-cache' });
|
|
90
|
+
};
|
|
91
|
+
for (const [b, files] of Object.entries(buckets)) for (const [n, t] of Object.entries(files)) write(b, n, t);
|
|
92
|
+
const notFound = () => Object.assign(new Error('HTTP 404'), { status: 404, code: 'not_found' });
|
|
93
|
+
const api = {
|
|
94
|
+
calls,
|
|
95
|
+
store,
|
|
96
|
+
write,
|
|
97
|
+
buckets: async () => [...ids].map((id) => ({ id, name: id, public: false })),
|
|
98
|
+
createBucket: async (id) => (calls.push(['createBucket', id]), ids.add(id), {}),
|
|
99
|
+
status: async () => ({ backend: location.backend }),
|
|
100
|
+
syncLocation: async () => {
|
|
101
|
+
if (!sync) throw notFound();
|
|
102
|
+
return location;
|
|
103
|
+
},
|
|
104
|
+
syncList: async (b) => {
|
|
105
|
+
if (!sync) throw notFound();
|
|
106
|
+
return { objects: [...store].filter(([k]) => k.startsWith(`${b}/`)).map(([k, o]) => row(b, k.slice(b.length + 1), o)), next: null };
|
|
107
|
+
},
|
|
108
|
+
list: async (b) => [...store].filter(([k]) => k.startsWith(`${b}/`)).map(([k, o]) => ({ name: k.slice(b.length + 1), metadata: { size: Buffer.byteLength(o.text), etag: md5(o.text), mimetype: o.mimetype } })),
|
|
109
|
+
get: async (b, n) => {
|
|
110
|
+
const o = store.get(`${b}/${n}`);
|
|
111
|
+
return { body: o.text, headers: new Map([['content-type', o.mimetype]]) };
|
|
112
|
+
},
|
|
113
|
+
put: async (b, n, body, { type }) => (calls.push(['put', `${b}/${n}`]), write(b, n, body, type), {}),
|
|
114
|
+
remove: async (b, names) => (calls.push(['remove', ...names]), names.filter((n) => store.delete(`${b}/${n}`)).map((name) => ({ name }))),
|
|
115
|
+
markShared: async (project, fingerprint) => {
|
|
116
|
+
calls.push(['markShared', project && project.environment]);
|
|
117
|
+
if (fingerprint !== location.fingerprint || !ss.sameProject(project, location.project)) throw Object.assign(new Error('refused'), { status: 409 });
|
|
118
|
+
return { shared: true };
|
|
119
|
+
},
|
|
120
|
+
reference: async (b, project, fingerprint, objects) => {
|
|
121
|
+
calls.push(['reference', ...objects.map((o) => o.name)]);
|
|
122
|
+
if (fingerprint !== location.fingerprint) throw Object.assign(new Error('LocationMismatch'), { status: 409 });
|
|
123
|
+
if (!ss.sameProject(project, location.project)) throw Object.assign(new Error('DifferentProject'), { status: 409 });
|
|
124
|
+
return {
|
|
125
|
+
results: objects.map((o) => {
|
|
126
|
+
if (!provider.has(o.key)) return { name: o.name, status: 'error', message: 'contenu introuvable chez le fournisseur' };
|
|
127
|
+
const version = o.key.split('/')[2];
|
|
128
|
+
const before = store.get(`${b}/${o.name}`);
|
|
129
|
+
store.set(`${b}/${o.name}`, { version, text: provider.get(o.key), mimetype: o.mimetype, cacheControl: o.cacheControl });
|
|
130
|
+
return { name: o.name, status: before ? 'updated' : 'created' };
|
|
131
|
+
}),
|
|
132
|
+
};
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
return api;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
test('sync, disk → poad.io: bytes sent, bucket created, nothing removed without --prune', async () => {
|
|
139
|
+
const disk = new Map();
|
|
140
|
+
const remoteDisk = new Map();
|
|
141
|
+
const local = fakeSide({ location: { backend: 'file', shareable: false, fingerprint: null }, buckets: { photos: { 'a.txt': 'A', 'b.txt': 'B' }, 'poad-flows': { x: 'internal' } }, provider: disk });
|
|
142
|
+
const cloud = fakeSide({ location: { backend: 'file', shareable: false, fingerprint: null }, buckets: {}, provider: remoteDisk });
|
|
143
|
+
const r = await ss.sync(local, cloud, {});
|
|
144
|
+
assert.strictEqual(r.mode, 'bytes');
|
|
145
|
+
assert.deepStrictEqual(r.totals, { buckets_created: 1, added: 2, updated: 0, unchanged: 0, removed: 0, kept: 0, failed: 0, bytes: 2 });
|
|
146
|
+
assert.strictEqual(cloud.store.get('photos/a.txt').text, 'A');
|
|
147
|
+
assert.ok(!cloud.calls.some((c) => c[1] === 'poad-flows')); // bucket interne laissé de côté
|
|
148
|
+
|
|
149
|
+
// Deuxième passage : tout est identique
|
|
150
|
+
const again = await ss.sync(local, cloud, {});
|
|
151
|
+
assert.strictEqual(again.totals.unchanged, 2);
|
|
152
|
+
assert.strictEqual(again.totals.added + again.totals.updated, 0);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test('sync --dry-run changes nothing; --prune asks first, then removes', async () => {
|
|
156
|
+
const local = fakeSide({ location: { backend: 'file', shareable: false }, buckets: { photos: { 'a.txt': 'A2' } }, provider: new Map() });
|
|
157
|
+
const cloud = fakeSide({ location: { backend: 'file', shareable: false }, buckets: { photos: { 'a.txt': 'A1', 'old.txt': 'O' } }, provider: new Map() });
|
|
158
|
+
const dry = await ss.sync(local, cloud, { prune: true, dryRun: true });
|
|
159
|
+
assert.deepStrictEqual([dry.totals.updated, dry.totals.removed], [1, 1]);
|
|
160
|
+
assert.strictEqual(cloud.calls.length, 0);
|
|
161
|
+
|
|
162
|
+
let asked = null;
|
|
163
|
+
const r = await ss.sync(local, cloud, { prune: true, confirm: async (t) => (asked = t) });
|
|
164
|
+
assert.deepStrictEqual([asked.updated, asked.removed], [1, 1]);
|
|
165
|
+
assert.deepStrictEqual([r.totals.updated, r.totals.removed], [1, 1]);
|
|
166
|
+
assert.deepStrictEqual([...cloud.store.keys()], ['photos/a.txt']);
|
|
167
|
+
|
|
168
|
+
// Refus de la confirmation : rien n'est fait
|
|
169
|
+
const local2 = fakeSide({ location: { backend: 'file', shareable: false }, buckets: { photos: {} }, provider: new Map() });
|
|
170
|
+
await assert.rejects(ss.sync(local2, cloud, { prune: true, confirm: async () => { throw new Error('no'); } }), /no/);
|
|
171
|
+
assert.ok(cloud.store.has('photos/a.txt'));
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test('sync, same S3 place on both sides: references only, no byte read or sent', async () => {
|
|
175
|
+
const bucketS3 = new Map(); // le fournisseur commun
|
|
176
|
+
const loc = { backend: 's3', location: 'https://s3.example.test|media|p/', fingerprint: 'same', shareable: true, sync: true };
|
|
177
|
+
const local = fakeSide({ location: { ...loc, project: P1_LOCAL }, buckets: { photos: { 'a.txt': 'A', 'b.txt': 'B' } }, provider: bucketS3 });
|
|
178
|
+
const cloud = fakeSide({ location: { ...loc, project: P1 }, buckets: { photos: {} }, provider: bucketS3 });
|
|
179
|
+
local.get = async () => assert.fail('no byte must be read');
|
|
180
|
+
cloud.put = async () => assert.fail('no byte must be sent');
|
|
181
|
+
const r = await ss.sync(local, cloud, {});
|
|
182
|
+
assert.strictEqual(r.mode, 'references');
|
|
183
|
+
assert.deepStrictEqual([r.totals.added, r.totals.bytes, r.totals.failed], [2, 0, 0]);
|
|
184
|
+
assert.strictEqual(cloud.store.get('photos/a.txt').version, local.store.get('photos/a.txt').version);
|
|
185
|
+
// La source a noté que son lieu sert aussi à l'autre environnement, avant toute référence
|
|
186
|
+
assert.deepStrictEqual(local.calls[0], ['markShared', 'main']);
|
|
187
|
+
|
|
188
|
+
// Un autre projet au même lieu : refus avant toute écriture
|
|
189
|
+
const stranger = fakeSide({ location: { ...loc, project: P2 }, buckets: {}, provider: bucketS3 });
|
|
190
|
+
await assert.rejects(ss.sync(local, stranger, { copyBytes: true }), (e) => e.code === 'different_projects');
|
|
191
|
+
assert.strictEqual(stranger.calls.length, 0);
|
|
192
|
+
|
|
193
|
+
// Un contenu absent chez le fournisseur : erreur par fichier, le reste passe
|
|
194
|
+
local.write('photos', 'ghost.txt', 'G');
|
|
195
|
+
bucketS3.delete([...bucketS3.keys()].find((k) => bucketS3.get(k) === 'G'));
|
|
196
|
+
const r2 = await ss.sync(local, cloud, {});
|
|
197
|
+
assert.strictEqual(r2.totals.failed, 1);
|
|
198
|
+
assert.match(r2.errors[0].error, /introuvable/);
|
|
199
|
+
assert.strictEqual(r2.totals.unchanged, 2);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test('sync, S3 on both sides but not the same place: stops before any write', async () => {
|
|
203
|
+
const local = fakeSide({ location: { backend: 's3', location: 'a|b|p/', fingerprint: 'f1', shareable: true, project: P1_LOCAL }, buckets: { photos: { 'a.txt': 'A' } }, provider: new Map() });
|
|
204
|
+
const cloud = fakeSide({ location: { backend: 's3', location: 'a|b|q/', fingerprint: 'f2', shareable: true, project: P1 }, buckets: {}, provider: new Map() });
|
|
205
|
+
await assert.rejects(ss.sync(local, cloud, {}), (e) => e.code === 'location_mismatch' && /a\|b\|p\//.test(e.message) && /a\|b\|q\//.test(e.message));
|
|
206
|
+
assert.strictEqual(cloud.calls.length, 0);
|
|
207
|
+
const r = await ss.sync(local, cloud, { copyBytes: true });
|
|
208
|
+
assert.deepStrictEqual([r.mode, r.totals.added], ['bytes', 1]);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
test('sync --pull from an engine without /sync (older storage) on the disk: bytes, through the public list', async () => {
|
|
212
|
+
const cloud = fakeSide({ location: { backend: 'file' }, sync: false, buckets: { docs: { 'r.txt': 'R' } }, provider: new Map() });
|
|
213
|
+
const local = fakeSide({ location: { backend: 'file', shareable: false }, buckets: {}, provider: new Map() });
|
|
214
|
+
const r = await ss.sync(cloud, local, { bucket: 'docs' });
|
|
215
|
+
assert.deepStrictEqual([r.mode, r.totals.added], ['bytes', 1]);
|
|
216
|
+
assert.strictEqual(local.store.get('docs/r.txt').text, 'R');
|
|
217
|
+
await assert.rejects(ss.sync(cloud, local, { bucket: 'nope' }), /no such bucket/);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
test('sync: onMode tells how before any file; --prune never deletes a bucket', async () => {
|
|
221
|
+
const local = fakeSide({ location: { backend: 'file', shareable: false }, buckets: { photos: {} }, provider: new Map() });
|
|
222
|
+
const cloud = fakeSide({ location: { backend: 'file', shareable: false }, buckets: { photos: { 'x.txt': 'X' }, old: { 'y.txt': 'Y' } }, provider: new Map() });
|
|
223
|
+
const seen = [];
|
|
224
|
+
const r = await ss.sync(local, cloud, { prune: true, confirm: async () => {}, onMode: (m) => seen.push(['mode', m.reason]), onItem: (e) => seen.push([e.action, e.name]) });
|
|
225
|
+
assert.deepStrictEqual(seen[0], ['mode', 'source on the engine disk: sending the bytes']);
|
|
226
|
+
assert.strictEqual(r.totals.removed, 1);
|
|
227
|
+
assert.ok(cloud.store.has('old/y.txt')); // bucket absent de la source : ni lui ni ses fichiers ne sont touchés
|
|
228
|
+
assert.ok(!cloud.calls.some((c) => /bucket/i.test(c[0]) && c[0] !== 'createBucket'));
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
test('poad storage sync: failures listed at the end, exit code 1, run again only retries what is missing', async () => {
|
|
232
|
+
const { CloudError } = require('../utils/cloud/api');
|
|
233
|
+
const local = fakeSide({ location: { backend: 'file', shareable: false }, buckets: { photos: { 'a.txt': 'A', 'big.bin': 'XXXXXXXXXXXX', 'c.txt': 'C' } }, provider: new Map() });
|
|
234
|
+
const cloud = fakeSide({ location: { backend: 'file', shareable: false }, buckets: {}, provider: new Map() });
|
|
235
|
+
const put = cloud.put;
|
|
236
|
+
cloud.put = async (b, n, body, o) => {
|
|
237
|
+
if (n === 'big.bin') throw new CloudError('taille maximale : 10 octets', { status: 413 });
|
|
238
|
+
return put(b, n, body, o);
|
|
239
|
+
};
|
|
240
|
+
let inFlight = 0;
|
|
241
|
+
let max = 0;
|
|
242
|
+
const get = local.get;
|
|
243
|
+
local.get = async (...a) => {
|
|
244
|
+
max = Math.max(max, ++inFlight);
|
|
245
|
+
await new Promise((r) => setTimeout(r, 2));
|
|
246
|
+
inFlight--;
|
|
247
|
+
return get(...a);
|
|
248
|
+
};
|
|
249
|
+
const deps = {
|
|
250
|
+
localTarget: async () => ({ label: 'local engine', side: local }),
|
|
251
|
+
cloudTarget: async () => ({ label: 'poad.io p1', side: cloud }),
|
|
252
|
+
client: (t) => t.side,
|
|
253
|
+
};
|
|
254
|
+
const sync = require('../project/storage/sync');
|
|
255
|
+
const run = async (raw) => {
|
|
256
|
+
const lines = [];
|
|
257
|
+
const [log, err, before] = [console.log, console.error, process.exitCode];
|
|
258
|
+
process.exitCode = undefined;
|
|
259
|
+
console.log = console.error = (...a) => lines.push(a.join(' '));
|
|
260
|
+
try {
|
|
261
|
+
await sync({}, raw, deps);
|
|
262
|
+
return { code: process.exitCode || 0, text: lines.join('\n').replace(/\x1b\[[0-9;]*m/g, '') };
|
|
263
|
+
} finally {
|
|
264
|
+
[console.log, console.error, process.exitCode] = [log, err, before];
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
const r = await run(['--env', 'main', '--concurrency', '1']);
|
|
268
|
+
assert.strictEqual(r.code, 1);
|
|
269
|
+
assert.strictEqual(max, 1);
|
|
270
|
+
const tail = r.text.split('\n').slice(-2);
|
|
271
|
+
assert.match(tail[0], /1 failure:/);
|
|
272
|
+
assert.strictEqual(tail[1].trim(), '✖ photos/big.bin: too large: the storage accepts at most 10 bytes (10 B) per file');
|
|
273
|
+
|
|
274
|
+
const again = await run(['--env', 'main', '--json']);
|
|
275
|
+
assert.strictEqual(again.code, 1);
|
|
276
|
+
const j = JSON.parse(again.text);
|
|
277
|
+
assert.deepStrictEqual([j.totals.added, j.totals.unchanged, j.totals.failed], [0, 2, 1]);
|
|
278
|
+
assert.deepStrictEqual(j.failures, [{ path: 'photos/big.bin', reason: 'too large: the storage accepts at most 10 bytes (10 B) per file' }]);
|
|
279
|
+
assert.deepStrictEqual(cloud.calls.filter((c) => c[0] === 'put').map((c) => c[1]).sort(), ['photos/a.txt', 'photos/c.txt']);
|
|
280
|
+
|
|
281
|
+
const bad = await run(['--env', 'main', '--concurrency', '0']);
|
|
282
|
+
assert.strictEqual(bad.code, 2);
|
|
283
|
+
});
|