poad 2.59.0 → 2.61.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 +6 -0
- package/global/stop.js +52 -19
- package/package.json +1 -1
- package/poad.js +23 -0
- package/project/cli.js +8 -1
- package/project/db/diff.js +99 -1
- package/project/flows.js +133 -39
- package/project/logs.js +92 -43
- package/project/migrate.js +2 -1
- package/project/storage/cp.js +41 -0
- package/project/storage/index.js +2 -0
- package/project/storage/ls.js +49 -0
- package/project/storage/mv.js +7 -0
- package/project/storage/rm.js +39 -0
- package/project/upgrade.js +6 -0
- package/test/flows.test.js +256 -0
- package/test/project-lock.test.js +51 -0
- package/test/storage.test.js +186 -0
- package/utils/banner.js +1 -0
- package/utils/help-details.js +62 -5
- package/utils/project-lock.js +67 -0
- package/utils/reference.js +6 -3
- package/utils/storage-copy.js +141 -0
- package/utils/storage.js +275 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const { test } = require('node:test');
|
|
2
|
+
const assert = require('node:assert');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { acquire, busyMessage, lockFile } = require('../utils/project-lock');
|
|
7
|
+
|
|
8
|
+
const project = () => {
|
|
9
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-lock-'));
|
|
10
|
+
fs.mkdirSync(path.join(dir, 'poad'));
|
|
11
|
+
return path.join(dir, 'poad', 'config.toml');
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
test('project lock: a second command is refused while the first one runs', () => {
|
|
15
|
+
const root = project();
|
|
16
|
+
const first = acquire(root, 'upgrade', { pid: 1001, isAlive: () => true });
|
|
17
|
+
assert.equal(first.ok, true);
|
|
18
|
+
const second = acquire(root, 'start', { pid: 1002, isAlive: () => true });
|
|
19
|
+
assert.equal(second.ok, false);
|
|
20
|
+
assert.equal(second.held.command, 'upgrade');
|
|
21
|
+
assert.match(busyMessage(second.held), /poad upgrade", pid 1001/);
|
|
22
|
+
first.release();
|
|
23
|
+
assert.equal(fs.existsSync(lockFile(root)), false);
|
|
24
|
+
assert.equal(acquire(root, 'start', { pid: 1002, isAlive: () => true }).ok, true);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('project lock: reentrant in the same process (upgrade calls stop, then start)', () => {
|
|
28
|
+
const root = project();
|
|
29
|
+
assert.equal(acquire(root, 'upgrade', { pid: 2001, isAlive: () => true }).ok, true);
|
|
30
|
+
assert.equal(acquire(root, 'stop', { pid: 2001, isAlive: () => true }).ok, true);
|
|
31
|
+
assert.equal(acquire(root, 'start', { pid: 2001, isAlive: () => true }).ok, true);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('project lock: a lock left by a dead process, or unreadable, is taken over', () => {
|
|
35
|
+
const root = project();
|
|
36
|
+
assert.equal(acquire(root, 'start', { pid: 3001, isAlive: () => true }).ok, true);
|
|
37
|
+
const taken = acquire(root, 'start', { pid: 3002, isAlive: (pid) => pid !== 3001 });
|
|
38
|
+
assert.equal(taken.ok, true);
|
|
39
|
+
assert.equal(JSON.parse(fs.readFileSync(lockFile(root), 'utf8')).pid, 3002);
|
|
40
|
+
fs.writeFileSync(lockFile(root), 'not json');
|
|
41
|
+
assert.equal(acquire(root, 'stop', { pid: 3003, isAlive: () => true }).ok, true);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('project lock: release leaves the lock of another process alone', () => {
|
|
45
|
+
const root = project();
|
|
46
|
+
const mine = acquire(root, 'start', { pid: 4001, isAlive: () => false });
|
|
47
|
+
// Un autre processus a repris le verrou (le mien passait pour mort)
|
|
48
|
+
assert.equal(acquire(root, 'stop', { pid: 4002, isAlive: () => false }).ok, true);
|
|
49
|
+
mine.release();
|
|
50
|
+
assert.equal(JSON.parse(fs.readFileSync(lockFile(root), 'utf8')).pid, 4002);
|
|
51
|
+
});
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
const { test } = require('node:test');
|
|
2
|
+
const assert = require('node:assert');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const s = require('../utils/storage');
|
|
7
|
+
const c = require('../utils/storage-copy');
|
|
8
|
+
|
|
9
|
+
test('parseRemote: bucket, key, folder', () => {
|
|
10
|
+
assert.deepStrictEqual(s.parseRemote('poad:images/a/b.png'), { bucket: 'images', key: 'a/b.png', dir: false });
|
|
11
|
+
assert.deepStrictEqual(s.parseRemote('poad://images/'), { bucket: 'images', key: '', dir: true });
|
|
12
|
+
assert.deepStrictEqual(s.parseRemote('images'), { bucket: 'images', key: '', dir: true });
|
|
13
|
+
assert.deepStrictEqual(s.parseRemote('images/2024/'), { bucket: 'images', key: '2024', dir: true });
|
|
14
|
+
assert.deepStrictEqual(s.parseRemote('images//a//b'), { bucket: 'images', key: 'a/b', dir: false });
|
|
15
|
+
assert.throws(() => s.parseRemote('poad:'), /storage path/);
|
|
16
|
+
assert.throws(() => s.parseRemote('images/../x'), /not allowed/);
|
|
17
|
+
assert.throws(() => s.parseRemote('bad name/x'), /not a bucket/);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('isRemote, size, joinKey, mimeOf', () => {
|
|
21
|
+
assert.ok(s.isRemote('poad:a/b'));
|
|
22
|
+
assert.ok(!s.isRemote('./poad:a'));
|
|
23
|
+
assert.strictEqual(s.size(0), '0 B');
|
|
24
|
+
assert.strictEqual(s.size(1536), '1.5 KB');
|
|
25
|
+
assert.strictEqual(s.size(3 * 1024 * 1024), '3.0 MB');
|
|
26
|
+
assert.strictEqual(s.joinKey('', 'a.png'), 'a.png');
|
|
27
|
+
assert.strictEqual(s.joinKey('x/', 'a.png'), 'x/a.png');
|
|
28
|
+
assert.strictEqual(s.mimeOf('A.PNG'), 'image/png');
|
|
29
|
+
assert.strictEqual(s.mimeOf('data.unknown'), 'application/octet-stream');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('entries: folders first with count and size, then files', () => {
|
|
33
|
+
const o = (name, size) => ({ name, metadata: { size }, updated_at: '2026-12-01T10:00:00Z' });
|
|
34
|
+
const list = s.entries([o('a.txt', 3), o('site/index.html', 10), o('site/css/s.css', 5), o('data/x', 1), o('other', 9)], '');
|
|
35
|
+
assert.deepStrictEqual(list.map((e) => `${e.kind}:${e.name}`), ['folder:data', 'folder:site', 'file:a.txt', 'file:other']);
|
|
36
|
+
assert.strictEqual(list[1].count, 2);
|
|
37
|
+
assert.strictEqual(list[1].size, 15);
|
|
38
|
+
assert.deepStrictEqual(s.entries([o('site/index.html', 1), o('site/css/s.css', 1), o('sitemap', 1)], 'site/').map((e) => e.name), ['css', 'index.html']);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Faux Stockage en mémoire, derrière un fetch : les routes que le CLI appelle
|
|
42
|
+
function fakeStorage(initial = {}) {
|
|
43
|
+
const objects = new Map(Object.entries(initial));
|
|
44
|
+
const seen = [];
|
|
45
|
+
const doFetch = async (url, init = {}) => {
|
|
46
|
+
const u = new URL(url);
|
|
47
|
+
const route = decodeURIComponent(u.pathname.replace('/storage/v1', ''));
|
|
48
|
+
seen.push({ method: init.method, route, auth: init.headers.authorization });
|
|
49
|
+
const json = (status, body) => new Response(body === undefined ? null : JSON.stringify(body), { status });
|
|
50
|
+
let m;
|
|
51
|
+
if ((m = /^\/object\/list\/([^/]+)$/.exec(route))) {
|
|
52
|
+
const { prefix, limit, offset } = JSON.parse(init.body);
|
|
53
|
+
const rows = [...objects.keys()]
|
|
54
|
+
.filter((k) => k.startsWith(`${m[1]}/${prefix}`))
|
|
55
|
+
.sort()
|
|
56
|
+
.slice(offset, offset + limit)
|
|
57
|
+
.map((k) => ({ name: k.slice(m[1].length + 1), metadata: { size: objects.get(k).body.length, mimetype: objects.get(k).type }, updated_at: '2026-12-01T10:00:00Z' }));
|
|
58
|
+
return json(200, rows);
|
|
59
|
+
}
|
|
60
|
+
if ((m = /^\/object\/([^/]+)$/.exec(route)) && init.method === 'DELETE') {
|
|
61
|
+
const { prefixes } = JSON.parse(init.body);
|
|
62
|
+
const gone = prefixes.filter((p) => objects.delete(`${m[1]}/${p}`)).map((name) => ({ name }));
|
|
63
|
+
return json(200, gone);
|
|
64
|
+
}
|
|
65
|
+
if ((m = /^\/object\/(.+)$/.exec(route))) {
|
|
66
|
+
if (init.method === 'PUT') {
|
|
67
|
+
const chunks = [];
|
|
68
|
+
for await (const ch of init.body) chunks.push(Buffer.from(ch));
|
|
69
|
+
objects.set(m[1], { body: Buffer.concat(chunks), type: init.headers['content-type'] });
|
|
70
|
+
return json(201, { name: m[1] });
|
|
71
|
+
}
|
|
72
|
+
const o = objects.get(m[1]);
|
|
73
|
+
if (!o) return json(404, { message: 'objet introuvable' });
|
|
74
|
+
return new Response(o.body, { status: 200, headers: { 'content-type': `${o.type}; charset=utf-8` } });
|
|
75
|
+
}
|
|
76
|
+
return json(404, { message: 'route inconnue' });
|
|
77
|
+
};
|
|
78
|
+
const obj = (body, type = 'text/plain') => ({ body: Buffer.from(body), type });
|
|
79
|
+
return { objects, seen, doFetch, obj };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const filled = () => {
|
|
83
|
+
const f = fakeStorage();
|
|
84
|
+
f.objects.set('img/a.png', f.obj('AAA', 'image/png'));
|
|
85
|
+
f.objects.set('img/2024/b.png', f.obj('BB', 'image/png'));
|
|
86
|
+
f.objects.set('img/2024/sub/c.png', f.obj('C', 'image/png'));
|
|
87
|
+
return f;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
test('client: list pages, sends the key only in headers', async () => {
|
|
91
|
+
const f = filled();
|
|
92
|
+
const api = s.client({ base: 'http://localhost:1', key: 'secret-key', fetch: f.doFetch });
|
|
93
|
+
const rows = await api.list('img', '2024/');
|
|
94
|
+
assert.deepStrictEqual(rows.map((r) => r.name), ['2024/b.png', '2024/sub/c.png']);
|
|
95
|
+
assert.ok(f.seen.every((x) => x.auth === 'Bearer secret-key' && !x.route.includes('secret-key')));
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('client: an HTTP error becomes a message, never the key', async () => {
|
|
99
|
+
const api = s.client({ base: 'http://localhost:1', key: 'secret-key', fetch: async () => new Response(JSON.stringify({ message: 'invalid token' }), { status: 401 }) });
|
|
100
|
+
await assert.rejects(api.buckets(), (e) => /refused by the storage \(HTTP 401\)/.test(e.message) && !e.message.includes('secret-key'));
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('resolve: file, folder needs -r, unknown path', async () => {
|
|
104
|
+
const f = filled();
|
|
105
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
106
|
+
assert.strictEqual((await s.resolve(api, s.parseRemote('img/a.png'), false)).kind, 'file');
|
|
107
|
+
await assert.rejects(s.resolve(api, s.parseRemote('img/2024'), false), /is a folder: add -r/);
|
|
108
|
+
const r = await s.resolve(api, s.parseRemote('img/2024'), true);
|
|
109
|
+
assert.strictEqual(r.objects.length, 2);
|
|
110
|
+
await assert.rejects(s.resolve(api, s.parseRemote('img/none'), true), /no such file or folder/);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test('plan and run: storage → storage keeps the base name and the original type', async () => {
|
|
114
|
+
const f = filled();
|
|
115
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
116
|
+
const { items } = await c.plan(api, 'poad:img/2024', 'poad:archive/', { recursive: true });
|
|
117
|
+
assert.deepStrictEqual(items.map((i) => i.to.key).sort(), ['2024/b.png', '2024/sub/c.png']);
|
|
118
|
+
const r = await c.run(api, items);
|
|
119
|
+
assert.strictEqual(r.errors.length, 0);
|
|
120
|
+
assert.strictEqual(r.bytes, 3);
|
|
121
|
+
assert.strictEqual(f.objects.get('archive/2024/sub/c.png').type, 'image/png');
|
|
122
|
+
// Renommer un fichier : la destination est le nouveau nom
|
|
123
|
+
const one = await c.plan(api, 'poad:img/a.png', 'poad:img/z.png');
|
|
124
|
+
assert.strictEqual(one.items[0].to.key, 'z.png');
|
|
125
|
+
// Copie dans elle-même refusée
|
|
126
|
+
await assert.rejects(c.plan(api, 'poad:img/2024', 'poad:img/2024/', { recursive: true }), /inside/);
|
|
127
|
+
// Les deux chemins sur le disque : refusé
|
|
128
|
+
await assert.rejects(c.plan(api, 'a', 'b'), /must be in the storage/);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('plan and run: disk ↔ storage', async () => {
|
|
132
|
+
const f = fakeStorage();
|
|
133
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
134
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-storage-'));
|
|
135
|
+
try {
|
|
136
|
+
fs.mkdirSync(path.join(dir, 'site', 'css'), { recursive: true });
|
|
137
|
+
fs.writeFileSync(path.join(dir, 'site', 'index.html'), '<h1>x</h1>');
|
|
138
|
+
fs.writeFileSync(path.join(dir, 'site', 'css', 's.css'), 'body{}');
|
|
139
|
+
await assert.rejects(c.plan(api, path.join(dir, 'site'), 'poad:web/'), /is a folder: add -r/);
|
|
140
|
+
const up = await c.plan(api, path.join(dir, 'site'), 'poad:web/', { recursive: true });
|
|
141
|
+
await c.run(api, up.items);
|
|
142
|
+
assert.deepStrictEqual([...f.objects.keys()].sort(), ['web/site/css/s.css', 'web/site/index.html']);
|
|
143
|
+
assert.strictEqual(f.objects.get('web/site/css/s.css').type, 'text/css');
|
|
144
|
+
// Dossier existant dans le Stockage : la source y entre sous son nom
|
|
145
|
+
const again = await c.plan(api, path.join(dir, 'site', 'index.html'), 'poad:web/site');
|
|
146
|
+
assert.strictEqual(again.items[0].to.key, 'site/index.html');
|
|
147
|
+
// Retour sur le disque, dans un dossier qui existe
|
|
148
|
+
const out = path.join(dir, 'out');
|
|
149
|
+
fs.mkdirSync(out);
|
|
150
|
+
const down = await c.plan(api, 'poad:web/site', out, { recursive: true });
|
|
151
|
+
const r = await c.run(api, down.items);
|
|
152
|
+
assert.strictEqual(r.errors.length, 0);
|
|
153
|
+
assert.strictEqual(fs.readFileSync(path.join(out, 'site', 'css', 's.css'), 'utf8'), 'body{}');
|
|
154
|
+
assert.ok(!fs.existsSync(path.join(out, 'site', 'css', 's.css.poad-part')));
|
|
155
|
+
} finally {
|
|
156
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test('each: runs everything, collects errors', async () => {
|
|
161
|
+
const done = [];
|
|
162
|
+
const errors = await s.each([1, 2, 3, 4, 5], async (n) => {
|
|
163
|
+
if (n === 3) throw new Error('boom');
|
|
164
|
+
done.push(n);
|
|
165
|
+
}, 2);
|
|
166
|
+
assert.deepStrictEqual(done.sort(), [1, 2, 4, 5]);
|
|
167
|
+
assert.strictEqual(errors.length, 1);
|
|
168
|
+
assert.strictEqual(errors[0].item, 3);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test('client: hosted, anon key for the gateway, storage token renewed before it expires', async () => {
|
|
172
|
+
const seen = [];
|
|
173
|
+
const doFetch = async (url, init) => (seen.push([init.headers.apikey, init.headers.authorization]), new Response('[]', { status: 200 }));
|
|
174
|
+
let asked = 0;
|
|
175
|
+
const soon = new Date(Date.now() + 30000).toISOString();
|
|
176
|
+
const later = new Date(Date.now() + 900000).toISOString();
|
|
177
|
+
const api = s.client({ base: 'https://p.example.com', key: 'tok1', apikey: 'anon', fetch: doFetch, renew: { first: soon, next: async () => (asked++, { token: 'tok2', anon_key: 'anon', expires_at: later }) } });
|
|
178
|
+
await api.buckets();
|
|
179
|
+
await api.buckets();
|
|
180
|
+
assert.strictEqual(asked, 1);
|
|
181
|
+
assert.deepStrictEqual(seen, [['anon', 'Bearer tok2'], ['anon', 'Bearer tok2']]);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test('target: --env or --project goes to poad.io, else the local engine', async () => {
|
|
185
|
+
await assert.rejects(s.target({}, { started: async () => true }), /not in a poad project|service_role|started/);
|
|
186
|
+
});
|
package/utils/banner.js
CHANGED
|
@@ -123,6 +123,7 @@ function render({ full = false, inProject = true, columns = terminalColumns(), v
|
|
|
123
123
|
const more = [
|
|
124
124
|
['poad --help', 'every command and its options'],
|
|
125
125
|
['poad <command> --help', 'details of a command'],
|
|
126
|
+
['poad --version, -v', 'version of the CLI'],
|
|
126
127
|
];
|
|
127
128
|
const w = Math.max(...more.map(([k]) => k.length)) + 2;
|
|
128
129
|
for (const [k, v] of more) lines.push(...row({ name: k, nameStyle: chalk.cyanBright, nameWidth: w, columns, indent: 1, dots: false, segments: [{ text: v, style: chalk.grey }] }));
|
package/utils/help-details.js
CHANGED
|
@@ -40,7 +40,10 @@ const sheets = {
|
|
|
40
40
|
},
|
|
41
41
|
stop: {
|
|
42
42
|
usage: ['poad stop [keycloak | valkey | runner]'],
|
|
43
|
-
text: [
|
|
43
|
+
text: [
|
|
44
|
+
'Stop the project: engine, Mailpit, Keycloak, Valkey, flows runner, network. Its data stays in poad/data.',
|
|
45
|
+
'A project already stopped is not an error: "nothing to stop", exit code 0. Docker not answering, or a container that refuses to stop, gives its cause and exit code 1.',
|
|
46
|
+
],
|
|
44
47
|
options: [
|
|
45
48
|
['keycloak (or kc)', 'Keycloak only (a shared Keycloak is released, and stops when no project uses it any more)'],
|
|
46
49
|
['valkey (or redis)', 'Valkey only'],
|
|
@@ -111,12 +114,55 @@ const sheets = {
|
|
|
111
114
|
['event=<event>', 'an event, e.g. ai_default_model_changed'],
|
|
112
115
|
['table=<table>', 'lines about a table: realtime subscriptions and changes delivered (engine 0.32+), data errors'],
|
|
113
116
|
['channel=<name>', 'a realtime channel (engine 0.32+): joins, leaves, subscriptions, deliveries'],
|
|
114
|
-
['limit=100', 'number of lines'],
|
|
117
|
+
['limit=100', 'number of lines, from 1 to 10000'],
|
|
115
118
|
['-f, --follow', 'follow live'],
|
|
116
119
|
['--json', 'one JSON line per entry (for jq)'],
|
|
117
120
|
],
|
|
118
|
-
notes: [
|
|
121
|
+
notes: [
|
|
122
|
+
'Everything combines: poad logs flows run=dafb44e1 step=call level=warn -f',
|
|
123
|
+
'A filter without a value (level=, request) or out of range (limit=0) is refused before anything is read, exit code 1. A log store that does not answer (engine starting or stopping, Docker stopped) is said in one sentence; POAD_DEBUG=1 shows the details of an unexpected error.',
|
|
124
|
+
],
|
|
125
|
+
},
|
|
126
|
+
'db diff': {
|
|
127
|
+
usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --discard', 'poad db diff --json'],
|
|
128
|
+
text: [
|
|
129
|
+
'Structure changes made outside the migrations (console SQL, psql, a tool), noted by the change journal of the engine (0.11.0+).',
|
|
130
|
+
'First a summary, one object per line: + added, ~ changed (with the column added, removed, renamed or changed when it can be read), - removed, · no net effect (created then dropped…); then the SQL of each change, as it will be written.',
|
|
131
|
+
],
|
|
132
|
+
options: [
|
|
133
|
+
['(nothing)', 'summary, then the SQL'],
|
|
134
|
+
['<name>', 'write them to poad/migrations/<timestamp>_<name>.sql (already applied here: not replayed), then the summary of what it holds'],
|
|
135
|
+
['--discard', 'forget them (they stay in the database)'],
|
|
136
|
+
['--json', 'entries, groups, SQL and the summary (summary: change, kind, object, others, detail)'],
|
|
137
|
+
],
|
|
119
138
|
},
|
|
139
|
+
storage: {
|
|
140
|
+
usage: ['poad storage ls [bucket[/folder]] [-r]', 'poad storage cp <source> <destination> [-r]', 'poad storage mv <bucket/path> <bucket/path> [-r]', 'poad storage rm <bucket/path…> [-r] [--yes]'],
|
|
141
|
+
text: [
|
|
142
|
+
'Files of the project storage, local engine (poad start) or poad.io (--env), whatever its backend: engine disk, S3 or 1fichier. A storage path is bucket/path; folders exist through their files ("a/b/c.png"), as in the console. For cp, write a storage path poad:bucket/path so that it is not taken for a file of the disk.',
|
|
143
|
+
],
|
|
144
|
+
options: [
|
|
145
|
+
['ls', 'buckets; ls <bucket[/folder]>: its folders (files, size) then its files'],
|
|
146
|
+
['cp ./a.png poad:images/', 'disk → storage; a destination ending with "/", a bucket alone or an existing folder keeps the source name'],
|
|
147
|
+
['cp poad:images/a.png ./', 'storage → disk'],
|
|
148
|
+
['cp poad:images/a.png poad:backup/a.png', 'storage → storage'],
|
|
149
|
+
['mv', 'move or rename inside the storage: copy, then delete each source copied (a failed copy leaves its source in place)'],
|
|
150
|
+
['rm', 'delete files; a folder or a whole bucket needs -r and a confirmation (the bucket itself stays)'],
|
|
151
|
+
['-r', 'folders, recursively'],
|
|
152
|
+
['--env <name>', 'the storage of a poad.io environment of the linked project (main: production) instead of the local engine'],
|
|
153
|
+
['--project <id>', 'another poad.io project (poad login); with --env for one of its environments'],
|
|
154
|
+
['--yes', 'no question (required outside a terminal for rm -r)'],
|
|
155
|
+
['--json', 'the result as JSON'],
|
|
156
|
+
],
|
|
157
|
+
notes: [
|
|
158
|
+
'Transfers stream through the CLI (4 at a time). Local engine: the service_role key of poad/config.toml, never shown. poad.io: a storage token of 15 minutes given to the owner (renewed during long transfers), never the service_role key. A file already there is replaced. Every request is logged by the storage service: poad logs storage.',
|
|
159
|
+
'Deleted content leaves the backend a minute later (storage sweeper).',
|
|
160
|
+
],
|
|
161
|
+
},
|
|
162
|
+
'storage ls': { usage: ['poad storage ls [bucket[/folder]] [-r] [--json]'], text: ['Buckets, or the folders then files of a folder (-r: every file under it, full path).'] },
|
|
163
|
+
'storage cp': { usage: ['poad storage cp <source> <destination> [-r] [--json]'], text: ['Copy between the disk and the storage, or inside the storage. A storage path is written poad:bucket/path. Example: poad storage cp -r ./site poad:web/'] },
|
|
164
|
+
'storage mv': { usage: ['poad storage mv <bucket/path> <bucket/path> [-r] [--json]'], text: ['Move or rename inside the storage: copy, then delete each source copied.'] },
|
|
165
|
+
'storage rm': { usage: ['poad storage rm <bucket/path…> [-r] [--yes] [--json]'], text: ['Delete files; -r for a folder or every file of a bucket, after a confirmation (--yes outside a terminal).'] },
|
|
120
166
|
functions: {
|
|
121
167
|
usage: ['poad functions new <name>', 'poad functions list', 'poad functions types'],
|
|
122
168
|
text: [
|
|
@@ -133,24 +179,35 @@ const sheets = {
|
|
|
133
179
|
usage: [
|
|
134
180
|
'poad flows new <name>',
|
|
135
181
|
'poad flows list',
|
|
136
|
-
|
|
182
|
+
"poad flows run <name> [key=value …] [input=<file.json>] [--input '<json>'] [--wait | --detach]",
|
|
137
183
|
'poad flows runs [name] [limit=20]',
|
|
138
184
|
'poad flows show <run_id>',
|
|
139
185
|
'poad flows cancel <run_id>',
|
|
186
|
+
'poad flows list | run | runs | show | cancel … --env <name> [--project <id>]',
|
|
140
187
|
],
|
|
141
188
|
text: [
|
|
142
189
|
'Flows of the project: automations (trigger, steps, edges) described in poad/flows/<name>.json, served by the engine (0.18.0+) on /flows/v1. Their queue is on the Valkey of the project (poad run valkey); container steps are started by the runner (poad run runner).',
|
|
190
|
+
'With --env or --project, the commands act on the project hosted on poad.io (session of poad login, owner only) instead of the local engine: poad.io gives an access of 15 minutes, renewed while a long run is followed, never shown.',
|
|
143
191
|
],
|
|
144
192
|
options: [
|
|
145
193
|
['new <name>', 'create poad/flows/<name>.json (minimal flow)'],
|
|
146
194
|
['list', 'flows of the project, as the running engine sees them'],
|
|
147
|
-
['run <name>', 'start a flow
|
|
195
|
+
['run <name>', 'start a flow, print its run id, then follow it step by step (duration, error) until it ends; exit code 1 if the run fails or is cancelled'],
|
|
196
|
+
["--input '<json>'", 'the input of the run as a JSON object; input=<file.json> is read first, key=value pairs go on top'],
|
|
197
|
+
['--detach (or --no-wait)', 'print the run id only, without following it'],
|
|
198
|
+
['--env <name>', 'an environment of the linked poad.io project (main: production)'],
|
|
199
|
+
['--project <id>', 'a poad.io project other than the one linked to this folder (no project folder needed)'],
|
|
148
200
|
['runs [name]', 'latest runs'],
|
|
149
201
|
['show <run_id>', 'detail of a run'],
|
|
150
202
|
['cancel <run_id>', 'cancel a running run'],
|
|
151
203
|
],
|
|
152
204
|
notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
|
|
153
205
|
},
|
|
206
|
+
migrate: {
|
|
207
|
+
usage: ['poad migrate', 'poad migrate --force-reference'],
|
|
208
|
+
text: ['Apply pending migrations of poad/migrations and named queries of poad/queries, then the reference tables of poad/reference (the file is the source of truth).'],
|
|
209
|
+
options: [['--force-reference', 'also apply a reference file that would remove many rows: an empty file for a table that has rows, or more than 20% of its rows (refused otherwise, nothing removed)']],
|
|
210
|
+
},
|
|
154
211
|
migration: {
|
|
155
212
|
usage: ['poad migration new <name>', 'poad migration list'],
|
|
156
213
|
options: [
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Verrou d'un projet local : une seule commande qui démarre, arrête ou met à jour ses conteneurs à la fois.
|
|
2
|
+
//
|
|
3
|
+
// Sans lui, un « poad start » lancé pendant un « poad upgrade » voyait les ports du projet tenus un instant
|
|
4
|
+
// par l'engine qui redémarrait, les croyait pris par un autre programme et les réécrivait dans config.toml.
|
|
5
|
+
//
|
|
6
|
+
// Fichier poad/data/.poad-lock (data/ est hors git) : { pid, command, at }. Réentrant dans un même
|
|
7
|
+
// processus (upgrade appelle stop puis start). Un verrou laissé par un processus mort est repris.
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
|
|
11
|
+
const lockFile = (root) => path.join(path.dirname(root), 'data', '.poad-lock');
|
|
12
|
+
|
|
13
|
+
const alive = (pid) => {
|
|
14
|
+
try {
|
|
15
|
+
process.kill(pid, 0);
|
|
16
|
+
return true;
|
|
17
|
+
} catch (err) {
|
|
18
|
+
// EPERM : le processus existe, mais appartient à un autre utilisateur
|
|
19
|
+
return Boolean(err && err.code === 'EPERM');
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const read = (file) => {
|
|
24
|
+
try {
|
|
25
|
+
const held = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
26
|
+
return Number.isInteger(held.pid) ? held : null;
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Prend le verrou du projet pour `command`. Renvoie { ok: true, release } ou { ok: false, held } (le
|
|
34
|
+
* verrou d'une autre commande en cours). Le verrou est rendu à la sortie du processus dans tous les cas.
|
|
35
|
+
*/
|
|
36
|
+
const acquire = (root, command, { pid = process.pid, isAlive = alive } = {}) => {
|
|
37
|
+
const file = lockFile(root);
|
|
38
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
39
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
40
|
+
try {
|
|
41
|
+
const fd = fs.openSync(file, 'wx');
|
|
42
|
+
fs.writeSync(fd, JSON.stringify({ pid, command, at: new Date().toISOString() }));
|
|
43
|
+
fs.closeSync(fd);
|
|
44
|
+
const release = () => {
|
|
45
|
+
const held = read(file);
|
|
46
|
+
if (held && held.pid === pid) fs.rmSync(file, { force: true });
|
|
47
|
+
};
|
|
48
|
+
if (pid === process.pid) process.once('exit', release);
|
|
49
|
+
return { ok: true, release };
|
|
50
|
+
} catch (err) {
|
|
51
|
+
if (err.code !== 'EEXIST') throw err;
|
|
52
|
+
const held = read(file);
|
|
53
|
+
// Même processus (upgrade → stop → start) : déjà à lui
|
|
54
|
+
if (held && held.pid === pid) return { ok: true, release: () => {} };
|
|
55
|
+
if (held && isAlive(held.pid)) return { ok: false, held };
|
|
56
|
+
// Laissé par un processus disparu, ou illisible : repris
|
|
57
|
+
fs.rmSync(file, { force: true });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return { ok: false, held: read(file) || { command: 'unknown' } };
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** Message d'une commande refusée parce qu'une autre tient le projet */
|
|
64
|
+
const busyMessage = (held) =>
|
|
65
|
+
`Another poad command is running on this project ("poad ${held.command}", pid ${held.pid}${held.at ? `, since ${held.at}` : ''}): wait for it to finish, then run this one again.`;
|
|
66
|
+
|
|
67
|
+
module.exports = { acquire, busyMessage, lockFile };
|
package/utils/reference.js
CHANGED
|
@@ -17,18 +17,21 @@ const files = (root) => {
|
|
|
17
17
|
};
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
|
-
* Demande la synchronisation et l'affiche.
|
|
20
|
+
* Demande la synchronisation et l'affiche. force : l'engine applique aussi une suppression massive
|
|
21
|
+
* (fichier vide ou tronqué) qu'il refuse sinon (poad migrate --force-reference). Renvoie false si une table n'a pas
|
|
21
22
|
* pu être synchronisée ; true sinon (y compris sans table, ou avec un engine
|
|
22
23
|
* qui ne connaît pas encore les tables de référence).
|
|
23
24
|
*/
|
|
24
|
-
const sync = async (root, config) => {
|
|
25
|
+
const sync = async (root, config, { force = false } = {}) => {
|
|
25
26
|
const chalk = require('chalk-v2');
|
|
26
27
|
if (!files(root).length) return true;
|
|
27
28
|
let res;
|
|
28
29
|
try {
|
|
29
30
|
res = await fetch(`http://localhost:${config.web.port}/meta/v1/reference/sync`, {
|
|
30
31
|
method: 'POST',
|
|
31
|
-
headers: { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}
|
|
32
|
+
headers: { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}`, 'content-type': 'application/json' },
|
|
33
|
+
// force : une suppression massive (fichier vide ou tronqué) est refusée par l'engine sans elle
|
|
34
|
+
body: JSON.stringify(force ? { force: true } : {}),
|
|
32
35
|
signal: AbortSignal.timeout(120000),
|
|
33
36
|
});
|
|
34
37
|
} catch (err) {
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Copie pour poad storage cp et mv : plan (quoi va où), puis transferts en flux.
|
|
2
|
+
//
|
|
3
|
+
// Règles, comme cp -r :
|
|
4
|
+
// - une source dossier (du disque ou du Stockage) demande -r ;
|
|
5
|
+
// - une destination qui finit par « / », un bucket seul, ou un dossier qui existe déjà
|
|
6
|
+
// reçoit la source sous son nom de base ; sinon la destination est le nouveau nom.
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const { Readable } = require('stream');
|
|
10
|
+
const { pipeline } = require('stream/promises');
|
|
11
|
+
const { CloudError, usageError } = require('./cloud/api');
|
|
12
|
+
const s = require('./storage');
|
|
13
|
+
|
|
14
|
+
const base = (key, bucket) => (key ? key.split('/').pop() : bucket);
|
|
15
|
+
|
|
16
|
+
/** Le dossier du Stockage existe-t-il (au moins un fichier dessous) ? */
|
|
17
|
+
async function remoteFolder(api, { bucket, key }) {
|
|
18
|
+
if (!key) return true;
|
|
19
|
+
const rows = await api.list(bucket, `${key}/`);
|
|
20
|
+
return rows.length > 0;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Plan : { items: [{ from, to, size }], kind } ; from/to : { local } ou { bucket, key }.
|
|
25
|
+
* api : client du Stockage ; src/dst : mots tapés.
|
|
26
|
+
*/
|
|
27
|
+
async function plan(api, srcText, dstText, { recursive = false, remoteOnly = false } = {}) {
|
|
28
|
+
const srcRemote = remoteOnly || s.isRemote(srcText);
|
|
29
|
+
const dstRemote = remoteOnly || s.isRemote(dstText);
|
|
30
|
+
if (!srcRemote && !dstRemote) throw usageError('One of the two paths must be in the storage: write it poad:bucket/path (poad storage cp ./a.png poad:photos/).');
|
|
31
|
+
const items = [];
|
|
32
|
+
|
|
33
|
+
if (!srcRemote) {
|
|
34
|
+
// Disque → Stockage
|
|
35
|
+
const src = path.resolve(String(srcText));
|
|
36
|
+
let st;
|
|
37
|
+
try {
|
|
38
|
+
st = fs.statSync(src);
|
|
39
|
+
} catch {
|
|
40
|
+
throw new CloudError(`${srcText}: no such file or folder`, { code: 'not_found' });
|
|
41
|
+
}
|
|
42
|
+
const dst = s.parseRemote(dstText);
|
|
43
|
+
if (st.isDirectory()) {
|
|
44
|
+
if (!recursive) throw usageError(`${srcText} is a folder: add -r`);
|
|
45
|
+
const into = dst.dir || (await remoteFolder(api, dst)) ? s.joinKey(dst.key, path.basename(src)) : dst.key;
|
|
46
|
+
for (const rel of s.walk(src)) {
|
|
47
|
+
const file = path.join(src, ...rel.split('/'));
|
|
48
|
+
items.push({ from: { local: file }, to: { bucket: dst.bucket, key: s.joinKey(into, rel) }, size: fs.statSync(file).size });
|
|
49
|
+
}
|
|
50
|
+
if (!items.length) throw new CloudError(`${srcText}: empty folder, nothing to copy`, { code: 'empty' });
|
|
51
|
+
return { items, kind: 'folder' };
|
|
52
|
+
}
|
|
53
|
+
if (!st.isFile()) throw usageError(`${srcText} is not a file`);
|
|
54
|
+
const key = dst.dir || (await remoteFolder(api, dst)) ? s.joinKey(dst.key, path.basename(src)) : dst.key;
|
|
55
|
+
items.push({ from: { local: src }, to: { bucket: dst.bucket, key }, size: st.size });
|
|
56
|
+
return { items, kind: 'file' };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const src = s.parseRemote(srcText);
|
|
60
|
+
const found = await s.resolve(api, src, recursive);
|
|
61
|
+
const name = base(found.base, src.bucket);
|
|
62
|
+
const relOf = (o) => (found.base ? o.name.slice(found.base.length + 1) : o.name);
|
|
63
|
+
const sizeOf = (o) => Number(o.metadata && o.metadata.size) || 0;
|
|
64
|
+
// Le type d'origine (fiche de l'objet), pas celui de la réponse HTTP (qui peut gagner « ; charset=… »)
|
|
65
|
+
const typeOf = (o) => (o.metadata && o.metadata.mimetype) || undefined;
|
|
66
|
+
|
|
67
|
+
if (!dstRemote) {
|
|
68
|
+
// Stockage → disque
|
|
69
|
+
const dst = path.resolve(String(dstText));
|
|
70
|
+
const isDir = String(dstText).endsWith('/') || String(dstText).endsWith(path.sep) || (fs.existsSync(dst) && fs.statSync(dst).isDirectory());
|
|
71
|
+
if (found.kind === 'file') {
|
|
72
|
+
items.push({ from: { bucket: src.bucket, key: found.objects[0].name }, to: { local: isDir ? path.join(dst, name) : dst }, size: sizeOf(found.objects[0]) });
|
|
73
|
+
} else {
|
|
74
|
+
const into = isDir ? path.join(dst, name) : dst;
|
|
75
|
+
for (const o of found.objects) items.push({ from: { bucket: src.bucket, key: o.name }, to: { local: path.join(into, ...relOf(o).split('/')) }, size: sizeOf(o) });
|
|
76
|
+
}
|
|
77
|
+
return { items, kind: found.kind };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Stockage → Stockage
|
|
81
|
+
const dst = s.parseRemote(dstText);
|
|
82
|
+
const isDir = dst.dir || (await remoteFolder(api, dst));
|
|
83
|
+
if (found.kind === 'file') {
|
|
84
|
+
items.push({ from: { bucket: src.bucket, key: found.objects[0].name }, to: { bucket: dst.bucket, key: isDir ? s.joinKey(dst.key, name) : dst.key }, size: sizeOf(found.objects[0]), type: typeOf(found.objects[0]) });
|
|
85
|
+
} else {
|
|
86
|
+
const into = isDir ? s.joinKey(dst.key, name) : dst.key;
|
|
87
|
+
if (dst.bucket === src.bucket && (into === found.base || (found.base ? into.startsWith(`${found.base}/`) : true)))
|
|
88
|
+
throw usageError(`${s.show(dst.bucket, into)} is inside ${s.show(src.bucket, found.base)}: choose another destination`);
|
|
89
|
+
for (const o of found.objects) items.push({ from: { bucket: src.bucket, key: o.name }, to: { bucket: dst.bucket, key: s.joinKey(into, relOf(o)) }, size: sizeOf(o), type: typeOf(o) });
|
|
90
|
+
}
|
|
91
|
+
for (const it of items) {
|
|
92
|
+
if (it.from.bucket === it.to.bucket && it.from.key === it.to.key) throw usageError(`${s.show(it.from.bucket, it.from.key)}: source and destination are the same`);
|
|
93
|
+
}
|
|
94
|
+
return { items, kind: found.kind };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Un bout de la copie, lisible : chemin relatif s'il est sous le dossier courant, sinon absolu */
|
|
98
|
+
const label = (end) => {
|
|
99
|
+
if (end.local === undefined) return s.show(end.bucket, end.key);
|
|
100
|
+
const rel = path.relative(process.cwd(), end.local);
|
|
101
|
+
return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : end.local;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/** Un transfert, en flux ; rend le nombre d'octets */
|
|
105
|
+
async function transfer(api, { from, to, size, type }) {
|
|
106
|
+
if (from.local !== undefined) {
|
|
107
|
+
await api.put(to.bucket, to.key, fs.createReadStream(from.local), { type: s.mimeOf(from.local) });
|
|
108
|
+
return size;
|
|
109
|
+
}
|
|
110
|
+
const res = await api.get(from.bucket, from.key);
|
|
111
|
+
if (to.local !== undefined) {
|
|
112
|
+
fs.mkdirSync(path.dirname(to.local), { recursive: true });
|
|
113
|
+
// Écrit à côté puis renomme : jamais de fichier à moitié écrit sous le nom final
|
|
114
|
+
const tmp = `${to.local}.poad-part`;
|
|
115
|
+
try {
|
|
116
|
+
await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(tmp));
|
|
117
|
+
fs.renameSync(tmp, to.local);
|
|
118
|
+
} catch (e) {
|
|
119
|
+
fs.rmSync(tmp, { force: true });
|
|
120
|
+
throw e;
|
|
121
|
+
}
|
|
122
|
+
return fs.statSync(to.local).size;
|
|
123
|
+
}
|
|
124
|
+
await api.put(to.bucket, to.key, res.body, { type: type || res.headers.get('content-type') || 'application/octet-stream' });
|
|
125
|
+
return size;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Exécute le plan ; rend { done: [item], errors: [{ item, error }], bytes } */
|
|
129
|
+
async function run(api, items, { onDone } = {}) {
|
|
130
|
+
const done = [];
|
|
131
|
+
let bytes = 0;
|
|
132
|
+
const errors = await s.each(items, async (item) => {
|
|
133
|
+
const n = await transfer(api, item);
|
|
134
|
+
bytes += n || 0;
|
|
135
|
+
done.push(item);
|
|
136
|
+
if (onDone) onDone(item);
|
|
137
|
+
});
|
|
138
|
+
return { done, errors, bytes };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = { plan, run, transfer, label };
|