poad 2.60.0 → 2.61.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/global/create.js +40 -27
- package/global/start.js +6 -0
- package/global/stop.js +52 -19
- package/package.json +1 -1
- package/poad.js +25 -0
- package/project/cli.js +1 -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/upgrade.js +6 -0
- package/test/flows.test.js +256 -0
- package/test/help.test.js +18 -0
- package/test/project-lock.test.js +51 -0
- package/utils/banner.js +6 -4
- package/utils/help-details.js +35 -5
- package/utils/help.js +60 -8
- package/utils/project-lock.js +67 -0
- package/utils/reference.js +6 -3
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// poad flows run sur poad.io (--env, --project), --input, --detach ; poad --version ;
|
|
2
|
+
// les filtres de poad logs et sa base injoignable ; le résumé de poad db diff.
|
|
3
|
+
// Un faux serveur local tient lieu à la fois de poad.io (POAD_CLOUD_API) et de
|
|
4
|
+
// l'engine hébergé (/flows/v1) ; HOME est un dossier temporaire.
|
|
5
|
+
const test = require('node:test');
|
|
6
|
+
const assert = require('node:assert');
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const http = require('http');
|
|
9
|
+
const path = require('path');
|
|
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 TOKEN = 'poad_pat_FLOWSTEST0123456789abcdefSECRET';
|
|
16
|
+
const SERVICE = 'eyJ-short-service-role-NEVER-SHOWN';
|
|
17
|
+
const ANON = 'eyJ-anon-public-key-NEVER-SHOWN';
|
|
18
|
+
const PID = 'abcdef123456';
|
|
19
|
+
const RUN = '0b9f3a52-6c1d-4e8a-9a51-3f2a1c0d7e11';
|
|
20
|
+
|
|
21
|
+
/** Faux poad.io + engine : behaviour.outcome = completed | failed */
|
|
22
|
+
function fakeCloud(t, behaviour = {}) {
|
|
23
|
+
const state = { requests: [], polls: 0 };
|
|
24
|
+
const send = (res, status, body) => {
|
|
25
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
26
|
+
res.end(JSON.stringify(body));
|
|
27
|
+
};
|
|
28
|
+
const server = http.createServer((req, res) => {
|
|
29
|
+
const chunks = [];
|
|
30
|
+
req.on('data', (c) => chunks.push(c));
|
|
31
|
+
req.on('end', () => {
|
|
32
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
33
|
+
const body = raw ? JSON.parse(raw) : null;
|
|
34
|
+
const url = new URL(req.url, 'http://x');
|
|
35
|
+
state.requests.push({ method: req.method, path: url.pathname, headers: req.headers, body });
|
|
36
|
+
if (url.pathname === `/_poad/cloud/v1/projects/${PID}/storage-token` && req.method === 'POST') {
|
|
37
|
+
if (req.headers.authorization !== `Bearer ${TOKEN}`) return send(res, 401, { error: { code: 'unauthorized', message: 'session' } });
|
|
38
|
+
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() });
|
|
39
|
+
}
|
|
40
|
+
if (url.pathname.startsWith('/flows/v1/')) {
|
|
41
|
+
if (req.headers.authorization !== `Bearer ${SERVICE}` || req.headers.apikey !== ANON) return send(res, 401, { error: { code: 'unauthorized', message: 'bad token' } });
|
|
42
|
+
if (req.method === 'POST' && url.pathname === '/flows/v1/flows/hello/run') return send(res, 202, { run_id: RUN });
|
|
43
|
+
if (req.method === 'POST' && url.pathname === '/flows/v1/flows/missing/run') return send(res, 404, { error: { code: 'not_found', message: 'no flow "missing"' } });
|
|
44
|
+
if (req.method === 'GET' && url.pathname === `/flows/v1/runs/${RUN}`) {
|
|
45
|
+
state.polls++;
|
|
46
|
+
const failed = behaviour.outcome === 'failed';
|
|
47
|
+
const steps = [{ step_id: 'start', name: 'start', status: 'done', attempt: 0, duration_ms: 3, error: null }];
|
|
48
|
+
if (state.polls === 1) return send(res, 200, { id: RUN, flow: 'hello', status: 'running', steps, duration_ms: null });
|
|
49
|
+
steps.push(failed ? { step_id: 'call', name: 'call', status: 'failed', attempt: 0, duration_ms: 1200, error: 'HTTP 500 from https://example.com/api' } : { step_id: 'call', name: 'call', status: 'done', attempt: 0, duration_ms: 1200, error: null });
|
|
50
|
+
return send(res, 200, { id: RUN, flow: 'hello', status: failed ? 'failed' : 'completed', steps, duration_ms: 1250, error: failed ? 'step "call" failed' : null, output: failed ? null : { ok: true } });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
send(res, 404, { error: { code: 'not_found', message: 'route' } });
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
return new Promise((resolve) => {
|
|
57
|
+
server.listen(0, '127.0.0.1', () => {
|
|
58
|
+
t.after(() => server.close());
|
|
59
|
+
resolve({ state, api: `http://127.0.0.1:${server.address().port}/_poad/cloud` });
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** HOME temporaire (sans vérification de version sur npm) et projet lié à PID */
|
|
65
|
+
function sandbox(t, { linked = true } = {}) {
|
|
66
|
+
const dir = tmpdir(t, 'poad-flows-');
|
|
67
|
+
const home = path.join(dir, 'home');
|
|
68
|
+
fs.mkdirSync(home);
|
|
69
|
+
fs.writeFileSync(path.join(home, '.poad_last_check.json'), JSON.stringify({ date: new Date(), version: PKG.version }));
|
|
70
|
+
const app = path.join(dir, 'app');
|
|
71
|
+
fs.mkdirSync(path.join(app, 'poad'), { recursive: true });
|
|
72
|
+
fs.writeFileSync(path.join(app, 'poad', 'config.toml'), `project_id = "demo"\nproject_uuid = "poad-flows-test-not-a-container"\nengine = "0.38.0"\n[web]\nport = 1\n[db]\nport = 1\n${linked ? `[cloud]\nproject = "${PID}"\n` : ''}`);
|
|
73
|
+
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');
|
|
74
|
+
const empty = path.join(dir, 'empty');
|
|
75
|
+
fs.mkdirSync(empty);
|
|
76
|
+
return { home, app, empty };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function poad(box, api, args, { cwd, env = {} } = {}) {
|
|
80
|
+
return new Promise((resolve) => {
|
|
81
|
+
const child = spawn(process.execPath, [POAD, ...args], {
|
|
82
|
+
cwd: cwd || box.app,
|
|
83
|
+
env: { ...process.env, HOME: box.home, POAD_CLOUD_API: api, POAD_ACCESS_TOKEN: TOKEN, NODE_OPTIONS: '', FORCE_COLOR: '0', ...env },
|
|
84
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
85
|
+
});
|
|
86
|
+
let stdout = '';
|
|
87
|
+
let stderr = '';
|
|
88
|
+
child.stdout.on('data', (d) => (stdout += d));
|
|
89
|
+
child.stderr.on('data', (d) => (stderr += d));
|
|
90
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), 20000);
|
|
91
|
+
child.on('close', (status) => {
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
resolve({ status, stdout, stderr, all: stdout + stderr });
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const noSecret = (r) => {
|
|
99
|
+
for (const s of [TOKEN, SERVICE, ANON]) assert.ok(!r.all.includes(s), 'a token was printed');
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// --- poad flows run --env / --project ---------------------------------------------
|
|
103
|
+
|
|
104
|
+
test('flows run --env : jeton de poad.io, entrée --input + clé=valeur, suivi jusqu’à la fin, code 0', async (t) => {
|
|
105
|
+
const cloud = await fakeCloud(t);
|
|
106
|
+
const box = sandbox(t);
|
|
107
|
+
const r = await poad(box, cloud.api, ['flow', 'run', 'hello', '--env', 'dev', '--input', '{"city":"Lyon","n":1}', 'n=2']);
|
|
108
|
+
assert.strictEqual(r.status, 0, r.all);
|
|
109
|
+
noSecret(r);
|
|
110
|
+
const token = cloud.state.requests.find((q) => q.path.endsWith('/storage-token'));
|
|
111
|
+
assert.deepStrictEqual(token.body, { branch: 'dev' });
|
|
112
|
+
const run = cloud.state.requests.find((q) => q.path === '/flows/v1/flows/hello/run');
|
|
113
|
+
assert.deepStrictEqual(run.body, { input: { city: 'Lyon', n: 2 } });
|
|
114
|
+
assert.match(r.stdout, new RegExp(`run ${RUN}`));
|
|
115
|
+
assert.match(r.stdout, /✔ start {2}done in 3 ms/);
|
|
116
|
+
assert.match(r.stdout, /✔ call {2}done in 1\.2 s/);
|
|
117
|
+
assert.match(r.stdout, /completed in 1\.3 s/);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test('flows run --env : une exécution qui échoue donne l’erreur de l’étape et un code non nul', async (t) => {
|
|
121
|
+
const cloud = await fakeCloud(t, { outcome: 'failed' });
|
|
122
|
+
const box = sandbox(t);
|
|
123
|
+
const r = await poad(box, cloud.api, ['flows', 'run', 'hello', '--env=main']);
|
|
124
|
+
assert.strictEqual(r.status, 1, r.all);
|
|
125
|
+
noSecret(r);
|
|
126
|
+
assert.match(r.stdout, /✖ call {2}failed: HTTP 500 from https:\/\/example\.com\/api/);
|
|
127
|
+
assert.match(r.stdout, /failed in 1\.3 s/);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test('flows run --detach : seulement l’id, sans suivi', async (t) => {
|
|
131
|
+
const cloud = await fakeCloud(t);
|
|
132
|
+
const box = sandbox(t);
|
|
133
|
+
const r = await poad(box, cloud.api, ['flows', 'run', 'hello', '--env', 'dev', '--detach']);
|
|
134
|
+
assert.strictEqual(r.status, 0, r.all);
|
|
135
|
+
assert.strictEqual(r.stdout.trim(), RUN);
|
|
136
|
+
assert.strictEqual(cloud.state.polls, 0);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test('flows run --project : hors d’un dossier de projet ; flow inconnu : message du service, code non nul', async (t) => {
|
|
140
|
+
const cloud = await fakeCloud(t);
|
|
141
|
+
const box = sandbox(t);
|
|
142
|
+
const ok = await poad(box, cloud.api, ['flows', 'run', 'hello', '--project', PID, '--detach'], { cwd: box.empty });
|
|
143
|
+
assert.strictEqual(ok.status, 0, ok.all);
|
|
144
|
+
assert.strictEqual(ok.stdout.trim(), RUN);
|
|
145
|
+
const missing = await poad(box, cloud.api, ['flows', 'run', 'missing', '--project', PID], { cwd: box.empty });
|
|
146
|
+
assert.strictEqual(missing.status, 1);
|
|
147
|
+
assert.match(missing.stdout, /Flow not started: no flow "missing"/);
|
|
148
|
+
const nowhere = await poad(box, cloud.api, ['flows', 'run', 'hello', '--env', 'dev'], { cwd: box.empty });
|
|
149
|
+
assert.notStrictEqual(nowhere.status, 0);
|
|
150
|
+
assert.match(nowhere.all, /--project <id>/);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test('flows run --env sans session poad.io : poad login, code 3', async (t) => {
|
|
154
|
+
const cloud = await fakeCloud(t);
|
|
155
|
+
const box = sandbox(t);
|
|
156
|
+
const r = await poad(box, cloud.api, ['flows', 'run', 'hello', '--env', 'dev'], { env: { POAD_ACCESS_TOKEN: '' } });
|
|
157
|
+
assert.strictEqual(r.status, 3, r.all);
|
|
158
|
+
assert.match(r.all, /poad login/);
|
|
159
|
+
assert.strictEqual(cloud.state.requests.length, 0);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test('flows run : --input invalide, option inconnue → message d’usage, code 2', async (t) => {
|
|
163
|
+
const box = sandbox(t);
|
|
164
|
+
const bad = await poad(box, 'http://127.0.0.1:9', ['flows', 'run', 'hello', '--input', '[1]', '--env', 'dev']);
|
|
165
|
+
assert.strictEqual(bad.status, 2);
|
|
166
|
+
assert.match(bad.stdout, /--input: a JSON object is expected/);
|
|
167
|
+
const env = await poad(box, 'http://127.0.0.1:9', ['flows', 'run', 'hello', '--env']);
|
|
168
|
+
assert.strictEqual(env.status, 2);
|
|
169
|
+
assert.match(env.stdout, /--env needs a value/);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test('parseRunArgs, cloudOptions, explainCloud', () => {
|
|
173
|
+
const { parseRunArgs, cloudOptions, explainCloud } = require('../project/flows');
|
|
174
|
+
assert.deepStrictEqual(parseRunArgs(['hello', '--input={"a":1}', '--detach']), { name: 'hello', input: {}, file: null, inline: { a: 1 }, wait: false });
|
|
175
|
+
assert.match(parseRunArgs(['hello', '--input', 'nope']).error, /not valid JSON/);
|
|
176
|
+
assert.match(parseRunArgs(['hello', '--input']).error, /needs a value/);
|
|
177
|
+
assert.match(parseRunArgs(['hello', '-x']).error, /unknown option -x/);
|
|
178
|
+
assert.deepStrictEqual(cloudOptions(['run', 'x', '--env', 'dev', '--project=abc123']), { words: ['run', 'x'], env: 'dev', project: 'abc123' });
|
|
179
|
+
assert.match(cloudOptions(['run', '--env', '--detach']).error, /--env needs a value/);
|
|
180
|
+
assert.match(explainCloud(503, null, 'poad.io p'), /flows service of poad\.io p does not answer/);
|
|
181
|
+
assert.match(explainCloud(401, {}, 'poad.io p'), /refused the access/);
|
|
182
|
+
assert.strictEqual(explainCloud(202, {}, 'x'), null);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// --- poad --version -----------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
test('poad --version et -v : la version du CLI', async (t) => {
|
|
188
|
+
const box = sandbox(t);
|
|
189
|
+
for (const flag of ['--version', '-v']) {
|
|
190
|
+
const r = await poad(box, 'http://127.0.0.1:9', [flag], { cwd: box.empty });
|
|
191
|
+
assert.strictEqual(r.status, 0);
|
|
192
|
+
assert.strictEqual(r.stdout.trim(), PKG.version);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
// --- poad logs ------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
test('logs : filtres invalides refusés avant toute connexion', () => {
|
|
199
|
+
const { checkOptions } = require('../project/logs');
|
|
200
|
+
const { LEVELS, ATTR_OPTIONS } = require('../utils/logline');
|
|
201
|
+
const check = (args, raw = []) => checkOptions(args, raw, { LEVELS, ATTR_OPTIONS });
|
|
202
|
+
assert.match(check({ limit: -5 }), /limit=-5: a number of lines from 1 to 10000/);
|
|
203
|
+
assert.match(check({ limit: 'abc' }), /limit=abc/);
|
|
204
|
+
assert.match(check({ request: true }), /request: a value is expected/);
|
|
205
|
+
assert.match(check({ grep: true }), /grep: a value is expected/);
|
|
206
|
+
assert.match(check({ function: 0 }, ['function=']), /function=: a value is expected/);
|
|
207
|
+
assert.match(check({ level: 'nope' }), /debug, info, warn, error or fatal/);
|
|
208
|
+
assert.match(check({ since: '5x' }), /a duration such as/);
|
|
209
|
+
assert.match(check({ '--since': true }), /unknown option.*since=15m/);
|
|
210
|
+
assert.strictEqual(check({ level: 'warn', since: '15m', limit: 500, flows: true }, ['level=warn']), null);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test('logs : base du projet injoignable → une phrase, code 1, pas de trace', async (t) => {
|
|
214
|
+
const box = sandbox(t);
|
|
215
|
+
const logs = require('../project/logs');
|
|
216
|
+
const lines = [];
|
|
217
|
+
const orig = console.log;
|
|
218
|
+
console.log = (...a) => lines.push(a.join(' '));
|
|
219
|
+
const before = process.exitCode;
|
|
220
|
+
try {
|
|
221
|
+
const err = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:1'), { code: 'ECONNREFUSED' });
|
|
222
|
+
await logs({}, [], { cwd: box.app, started: async () => true, connect: async () => { throw err; } });
|
|
223
|
+
} finally {
|
|
224
|
+
console.log = orig;
|
|
225
|
+
}
|
|
226
|
+
assert.strictEqual(process.exitCode, 1);
|
|
227
|
+
process.exitCode = before;
|
|
228
|
+
assert.match(lines.join('\n'), /does not answer on 127\.0\.0\.1:1 \(ECONNREFUSED\)/);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// --- poad db diff ---------------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
test('db diff : résumé lisible (ajouté, modifié, supprimé, sans effet)', () => {
|
|
234
|
+
const { summarize, describe } = require('../project/db/diff');
|
|
235
|
+
const { compact } = require('../utils/compact');
|
|
236
|
+
const entries = [
|
|
237
|
+
{ id: 1, statement: 'create table public.todos (id bigserial primary key, title text)', commands: ['CREATE INDEX', 'CREATE SEQUENCE', 'CREATE TABLE'], objects: ['public.todos', 'public.todos_id_seq', 'public.todos_pkey'] },
|
|
238
|
+
{ id: 2, statement: 'alter table public.todos add column done boolean', commands: ['ALTER TABLE'], objects: ['public.todos'] },
|
|
239
|
+
{ id: 3, statement: 'drop index public.todos_title_idx', commands: ['DROP INDEX'], objects: ['public.todos_title_idx'] },
|
|
240
|
+
{ id: 4, statement: 'create extension vector', commands: ['CREATE EXTENSION'], objects: ['vector'] },
|
|
241
|
+
{ id: 5, statement: 'drop extension vector', commands: ['DROP EXTENSION'], objects: ['vector'] },
|
|
242
|
+
{ id: 6, statement: 'create or replace function public.f() returns int language sql as $$ select 1 $$', commands: ['CREATE FUNCTION'], objects: ['public.f()'] },
|
|
243
|
+
];
|
|
244
|
+
const s = summarize({ entries, units: compact(entries) });
|
|
245
|
+
const pick = (i) => [i.change, i.kind, i.object, i.detail];
|
|
246
|
+
assert.deepStrictEqual(s.map(pick), [
|
|
247
|
+
['added', 'table', 'public.todos', null],
|
|
248
|
+
['changed', 'table', 'public.todos', 'column done added'],
|
|
249
|
+
['removed', 'index', 'public.todos_title_idx', null],
|
|
250
|
+
['none', 'extension', 'vector', '2 changes, no net effect'],
|
|
251
|
+
['changed', 'function', 'public.f()', 'created or replaced'],
|
|
252
|
+
]);
|
|
253
|
+
assert.deepStrictEqual(s[0].others, ['public.todos_id_seq', 'public.todos_pkey']);
|
|
254
|
+
assert.strictEqual(describe({ statement: 'alter table public.t rename column a to b', commands: ['ALTER TABLE'], objects: ['public.t'] }).detail, 'column a renamed to b');
|
|
255
|
+
assert.strictEqual(describe({ statement: 'alter table public.t drop column a', commands: ['ALTER TABLE'], objects: ['public.t'] }).detail, 'column a removed');
|
|
256
|
+
});
|
package/test/help.test.js
CHANGED
|
@@ -136,3 +136,21 @@ test('--help : une description qui contient [section] plus loin n’est pas coup
|
|
|
136
136
|
assert.match(r.stdout, /start \.+\s+Start the project: engine, migrations/);
|
|
137
137
|
assert.match(r.stdout, /create \.+\s+Create a poad project/);
|
|
138
138
|
});
|
|
139
|
+
|
|
140
|
+
test('poad --help: every command, project ones too outside a project, then the sheet of each', (t) => {
|
|
141
|
+
const dir = tmpdir(t);
|
|
142
|
+
const run = (args) => spawnSync(process.execPath, [path.join(__dirname, '..', 'poad.js'), ...args], { cwd: dir, encoding: 'utf8', env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', COLUMNS: '100' } });
|
|
143
|
+
const full = run(['--help']).stdout;
|
|
144
|
+
const short = run([]).stdout;
|
|
145
|
+
assert.match(full, /Project commands \(in a project\)/);
|
|
146
|
+
assert.doesNotMatch(full, /You are not in a project directory/);
|
|
147
|
+
for (const name of [...Object.keys(require('../global/cli')), ...Object.keys(require('../project/cli'))]) {
|
|
148
|
+
assert.ok(full.includes(`── poad ${name} `), `fiche de poad ${name}`);
|
|
149
|
+
}
|
|
150
|
+
// Fiches des sous-commandes qui en ont une
|
|
151
|
+
assert.ok(full.includes('── poad storage ls '));
|
|
152
|
+
assert.ok(full.split('\n').length > 3 * short.split('\n').length, 'aide complète bien plus longue que la vue courte');
|
|
153
|
+
// poad seul : vue courte, inchangée
|
|
154
|
+
assert.match(short, /You are not in a project directory/);
|
|
155
|
+
assert.doesNotMatch(short, /── poad /);
|
|
156
|
+
});
|
|
@@ -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
|
+
});
|
package/utils/banner.js
CHANGED
|
@@ -83,7 +83,8 @@ function render({ full = false, inProject = true, columns = terminalColumns(), v
|
|
|
83
83
|
.filter(Boolean)
|
|
84
84
|
.map((e) => ({ ...e, short: SHORT[scope][e.name] }));
|
|
85
85
|
};
|
|
86
|
-
|
|
86
|
+
// Aide complète : les commandes de projet toujours listées, même hors d'un projet
|
|
87
|
+
const groups = { global: pick('global'), project: inProject || full ? pick('project') : [] };
|
|
87
88
|
const title = (e) => (full && e.subs && e.subs.length ? `${e.name} <subcommand>` : e.name);
|
|
88
89
|
const nameWidth = Math.max(...[...groups.global, ...groups.project].map((e) => title(e).length)) + 4;
|
|
89
90
|
|
|
@@ -113,16 +114,17 @@ function render({ full = false, inProject = true, columns = terminalColumns(), v
|
|
|
113
114
|
lines.push(chalk.bold(' Global commands :'));
|
|
114
115
|
table(groups.global);
|
|
115
116
|
lines.push('');
|
|
116
|
-
lines.push(chalk.bold(' Project commands :'));
|
|
117
|
-
if (!
|
|
117
|
+
lines.push(chalk.bold(full && !inProject ? ' Project commands (in a project) :' : ' Project commands :'));
|
|
118
|
+
if (!groups.project.length) lines.push(...paragraph([{ text: 'You are not in a project directory.' }], { columns }));
|
|
118
119
|
else table(groups.project);
|
|
119
120
|
lines.push('');
|
|
120
121
|
if (full) {
|
|
121
|
-
lines.push(...paragraph([{ text: '
|
|
122
|
+
lines.push(...paragraph([{ text: 'Details of every command below; one command only: ', style: chalk.grey }, { text: 'poad <command> --help', style: chalk.cyanBright }], { columns, indent: 1 }));
|
|
122
123
|
} else {
|
|
123
124
|
const more = [
|
|
124
125
|
['poad --help', 'every command and its options'],
|
|
125
126
|
['poad <command> --help', 'details of a command'],
|
|
127
|
+
['poad --version, -v', 'version of the CLI'],
|
|
126
128
|
];
|
|
127
129
|
const w = Math.max(...more.map(([k]) => k.length)) + 2;
|
|
128
130
|
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,11 +114,27 @@ 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
|
},
|
|
120
139
|
storage: {
|
|
121
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]'],
|
|
@@ -160,24 +179,35 @@ const sheets = {
|
|
|
160
179
|
usage: [
|
|
161
180
|
'poad flows new <name>',
|
|
162
181
|
'poad flows list',
|
|
163
|
-
|
|
182
|
+
"poad flows run <name> [key=value …] [input=<file.json>] [--input '<json>'] [--wait | --detach]",
|
|
164
183
|
'poad flows runs [name] [limit=20]',
|
|
165
184
|
'poad flows show <run_id>',
|
|
166
185
|
'poad flows cancel <run_id>',
|
|
186
|
+
'poad flows list | run | runs | show | cancel … --env <name> [--project <id>]',
|
|
167
187
|
],
|
|
168
188
|
text: [
|
|
169
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.',
|
|
170
191
|
],
|
|
171
192
|
options: [
|
|
172
193
|
['new <name>', 'create poad/flows/<name>.json (minimal flow)'],
|
|
173
194
|
['list', 'flows of the project, as the running engine sees them'],
|
|
174
|
-
['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)'],
|
|
175
200
|
['runs [name]', 'latest runs'],
|
|
176
201
|
['show <run_id>', 'detail of a run'],
|
|
177
202
|
['cancel <run_id>', 'cancel a running run'],
|
|
178
203
|
],
|
|
179
204
|
notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
|
|
180
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
|
+
},
|
|
181
211
|
migration: {
|
|
182
212
|
usage: ['poad migration new <name>', 'poad migration list'],
|
|
183
213
|
options: [
|
package/utils/help.js
CHANGED
|
@@ -48,13 +48,13 @@ const describe = (entry) => {
|
|
|
48
48
|
};
|
|
49
49
|
|
|
50
50
|
/**
|
|
51
|
-
*
|
|
52
|
-
*
|
|
51
|
+
* Lignes de l'aide de la commande désignée par argv, ou null si aucune commande
|
|
52
|
+
* ne correspond. L'aide propre d'un module (help()) est captée telle qu'elle s'affiche.
|
|
53
53
|
*/
|
|
54
|
-
function
|
|
54
|
+
function helpLines(argv = [], { tables = loadTables(), base = path.join(__dirname, '..') } = {}) {
|
|
55
55
|
const chalk = require('chalk-v2');
|
|
56
56
|
const cmd = resolveCommand(argv, tables);
|
|
57
|
-
if (!cmd) return
|
|
57
|
+
if (!cmd) return null;
|
|
58
58
|
// Aide détaillée exportée par le module de la commande
|
|
59
59
|
let unit = null;
|
|
60
60
|
try {
|
|
@@ -63,8 +63,15 @@ function printHelp(argv = [], { tables = loadTables(), base = path.join(__dirnam
|
|
|
63
63
|
unit = null;
|
|
64
64
|
}
|
|
65
65
|
if (unit && typeof unit.help === 'function') {
|
|
66
|
-
|
|
67
|
-
|
|
66
|
+
const captured = [];
|
|
67
|
+
const log = console.log;
|
|
68
|
+
console.log = (...args) => captured.push(args.join(' '));
|
|
69
|
+
try {
|
|
70
|
+
unit.help();
|
|
71
|
+
} finally {
|
|
72
|
+
console.log = log;
|
|
73
|
+
}
|
|
74
|
+
return captured.join('\n').split('\n');
|
|
68
75
|
}
|
|
69
76
|
const name = `poad ${cmd.dir.join(' ')}`;
|
|
70
77
|
const { row, paragraph, terminalColumns } = require('./layout');
|
|
@@ -99,8 +106,53 @@ function printHelp(argv = [], { tables = loadTables(), base = path.join(__dirnam
|
|
|
99
106
|
out.push(...paragraph(p, { columns }));
|
|
100
107
|
}
|
|
101
108
|
out.push(' ');
|
|
102
|
-
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Affiche l'aide de la commande désignée par argv. Renvoie false si aucune
|
|
114
|
+
* commande ne correspond (le répartiteur montre alors la liste générale).
|
|
115
|
+
*/
|
|
116
|
+
function printHelp(argv = [], opts = {}) {
|
|
117
|
+
const lines = helpLines(argv, opts);
|
|
118
|
+
if (!lines) return false;
|
|
119
|
+
console.log(lines.join('\n'));
|
|
103
120
|
return true;
|
|
104
121
|
}
|
|
105
122
|
|
|
106
|
-
|
|
123
|
+
/**
|
|
124
|
+
* Aide complète (poad --help) : la fiche de chaque commande, globales puis projet, chacune sous
|
|
125
|
+
* son titre ; une sous-commande qui a sa propre fiche (help-details.js) suit celle de sa commande.
|
|
126
|
+
*/
|
|
127
|
+
function allHelpLines({ tables = loadTables(), base = path.join(__dirname, '..') } = {}) {
|
|
128
|
+
const chalk = require('chalk-v2');
|
|
129
|
+
const { wrap, visible, terminalColumns } = require('./layout');
|
|
130
|
+
const columns = terminalColumns();
|
|
131
|
+
// Une ligne écrite à largeur fixe par l'aide propre d'un module, ou un long usage : coupée à la largeur du
|
|
132
|
+
// terminal, retrait gardé (suite de ligne décalée de 2) ; ses couleurs tombent, ses mots restent
|
|
133
|
+
const fit = (line) => {
|
|
134
|
+
if (visible(line) <= columns) return [line];
|
|
135
|
+
const plain = String(line).replace(/\x1b\[[0-9;]*m/g, '');
|
|
136
|
+
const lead = plain.match(/^ */)[0];
|
|
137
|
+
const parts = wrap(plain.trim(), Math.max(20, columns - lead.length - 2));
|
|
138
|
+
return parts.map((p, i) => `${i ? `${lead} ` : lead}${p}`);
|
|
139
|
+
};
|
|
140
|
+
const out = [];
|
|
141
|
+
for (const scope of ['global', 'project']) {
|
|
142
|
+
for (const [name, entry] of Object.entries(tables[scope])) {
|
|
143
|
+
const words = [[name]];
|
|
144
|
+
if (entry && typeof entry === 'object') {
|
|
145
|
+
for (const sub of Object.keys(entry)) if (sub !== 'description' && sheets[`${name} ${sub}`]) words.push([name, sub]);
|
|
146
|
+
}
|
|
147
|
+
for (const w of words) {
|
|
148
|
+
const lines = helpLines(w, { tables, base });
|
|
149
|
+
if (!lines) continue;
|
|
150
|
+
const body = lines.filter((l, i, a) => !(i === a.length - 1 && !l.trim())).flatMap(fit);
|
|
151
|
+
out.push(chalk.bold.cyan(` ── poad ${w.join(' ')} ${'─'.repeat(Math.max(2, Math.min(70, columns) - 10 - w.join(' ').length))}`), '', ...body, '');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
module.exports = { HELP_FLAGS, helpRequested, resolveCommand, printHelp, helpLines, allHelpLines };
|
|
@@ -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) {
|