poad 2.60.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/project/logs.js CHANGED
@@ -38,68 +38,69 @@
38
38
  // dit pas. Le CLI lit _logs.entries dans la base du projet : ces filtres
39
39
  // portent sur la colonne attrs et valent pour tout engine qui a le collecteur
40
40
  // (les index qui les accélèrent arrivent avec l'engine 0.18.1).
41
- module.exports = async (args = {}, raw = []) => {
41
+ // deps (tests) : started(config), connect(config), cwd.
42
+ module.exports = async (args = {}, raw = [], deps = {}) => {
42
43
  const chalk = require('chalk-v2');
43
44
  const { findPoadDir } = require('../utils/findpoad');
44
- const { isDockerExist } = require('../utils/docker');
45
45
  const { readConfig } = require('../utils/config');
46
46
  const { supportsLogs } = require('../utils/logs');
47
- const { connect } = require('../utils/migrations');
48
47
  const { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine, parseToken, resolveTokenIds, tokenCondition } = require('../utils/logline');
49
-
50
- const root = findPoadDir(process.cwd());
51
- if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
52
- const config = readConfig(root);
53
- if (!supportsLogs(config)) {
54
- process.exitCode = 1;
55
- return console.log(chalk.redBright(`Engine ${config.engine} has no log collector: "poad upgrade" to 0.8.1 or later (meanwhile: docker logs ${config.project_uuid}).`));
56
- }
57
- if (!(await isDockerExist(config.project_uuid))) {
48
+ const connect = deps.connect || require('../utils/migrations').connect;
49
+ const started = deps.started || (async (config) => {
50
+ // Docker muet n'est pas un projet arrêté
51
+ const Docker = require('dockerode');
52
+ try {
53
+ await new Docker().ping();
54
+ } catch (err) {
55
+ throw new LogsError(`Docker does not answer (${(err && err.code) || (err && err.message) || err}): start Docker, then "poad start".`);
56
+ }
57
+ return require('../utils/docker').isDockerExist(config.project_uuid);
58
+ });
59
+ const fail = (message) => {
58
60
  process.exitCode = 1;
59
- return console.log(chalk.redBright('The project is not started: run "poad start".'));
61
+ console.log(chalk.redBright(message));
62
+ };
63
+
64
+ const root = findPoadDir(deps.cwd || process.cwd());
65
+ if (!root) return fail('You are not in a poad project directory.');
66
+ let config;
67
+ try {
68
+ config = readConfig(root);
69
+ } catch (err) {
70
+ return fail(`poad/config.toml is not readable: ${err.message}`);
60
71
  }
72
+ if (!supportsLogs(config)) return fail(`Engine ${config.engine} has no log collector: "poad upgrade" to 0.8.1 or later (meanwhile: docker logs ${config.project_uuid}).`);
61
73
 
62
- const OPTIONS = ['level', 'since', 'request', 'grep', 'limit', 'run', 'token', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
74
+ // Les filtres d'abord : une faute de frappe se dit même projet arrêté
75
+ const problem = checkOptions(args, raw, { LEVELS, ATTR_OPTIONS });
76
+ if (problem) return fail(problem);
77
+ const OPTIONS = optionNames(ATTR_OPTIONS);
63
78
  const flag = (...names) => names.some((n) => args[n] === true);
64
79
  const follow = flag('-f', '--follow', 'follow');
65
80
  const asJson = flag('--json', 'json');
66
- // « --since 5m » était accepté en silence : --since ignoré, « 5m » pris pour un nom de service, et aucune ligne.
67
- // Une option s'écrit nom=valeur : mieux vaut le dire que de répondre « No log line matches ».
68
- const unknown = Object.keys(args).filter((k) => k.startsWith('-') && !OPTIONS.includes(k));
69
- if (unknown.length) {
70
- const hint = unknown.map((k) => k.replace(/^-+/, '')).find((k) => OPTIONS.includes(k));
71
- return console.log(chalk.redBright(`${unknown.join(', ')}: unknown option. Options are written name=value${hint ? `, for example ${hint}=${hint === 'since' ? '15m' : '…'}` : ' (level=warn since=15m flow=<name>), plus -f and --json'}.`));
72
- }
73
81
  const services = Object.keys(args).filter((k) => args[k] === true && !OPTIONS.includes(k) && !k.startsWith('-'));
74
82
  const level = args.level ? String(args.level).toLowerCase() : null;
75
- if (level && !LEVELS.includes(level)) {
76
- process.exitCode = 1;
77
- return console.log(chalk.redBright(`level=${level}: debug, info, warn, error or fatal`));
78
- }
79
83
  let since = null;
80
84
  if (args.since) {
81
85
  const m = /^(\d+)\s*(s|m|h|d)$/.exec(String(args.since));
82
- if (!m) {
83
- process.exitCode = 1;
84
- return console.log(chalk.redBright(`since=${args.since}: a duration such as 30s, 15m, 2h, 1d`));
85
- }
86
86
  since = `${m[1]} ${{ s: 'seconds', m: 'minutes', h: 'hours', d: 'days' }[m[2]]}`;
87
87
  }
88
88
  // Attributs d'une ligne : flow=, run=, step=, function=
89
89
  const attrs = attrConditions(args);
90
- if (attrs.error) {
91
- process.exitCode = 1;
92
- return console.log(chalk.redBright(attrs.error));
93
- }
90
+ if (attrs.error) return fail(attrs.error);
94
91
  // token= : la valeur telle que tapée (parseArgs ferait d'un préfixe tout en chiffres un nombre)
95
- const typed = raw.find((w) => typeof w === 'string' && w.startsWith('token='));
92
+ const typed = (raw || []).find((w) => typeof w === 'string' && w.startsWith('token='));
96
93
  const token = parseToken(typed !== undefined ? typed.slice('token='.length) : args.token);
97
- if (token && token.error) {
98
- process.exitCode = 1;
99
- return console.log(chalk.redBright(token.error));
100
- }
94
+ if (token && token.error) return fail(token.error);
101
95
  const limit = Math.min(Number(args.limit) || (args.request ? 1000 : 100), 10000);
102
96
 
97
+ try {
98
+ if (!(await started(config))) return fail('The project is not started: run "poad start".');
99
+ } catch (err) {
100
+ if (err instanceof LogsError) return fail(err.message);
101
+ throw err;
102
+ }
103
+
103
104
  // Conditions communes à la première lecture et au suivi
104
105
  const where = [];
105
106
  const values = [];
@@ -120,12 +121,17 @@ module.exports = async (args = {}, raw = []) => {
120
121
 
121
122
  const print = (r) => console.log(asJson ? JSON.stringify(r) : formatLine(r, chalk));
122
123
 
123
- const client = await connect(config);
124
- // Le jeton par son nom actuel, son préfixe ou le début de son id : ses lignes, même sous un ancien nom
125
- if (token) add(...tokenCondition(token, await resolveTokenIds(client, token)));
124
+ let client;
125
+ try {
126
+ client = await connect(config);
127
+ } catch (err) {
128
+ return fail(unreachable(config, err));
129
+ }
126
130
  const from = (extra) => fromClause([...where, ...(extra ? [extra] : [])].join(' and ') || 'true', attrs.prefix);
127
131
  let lastId = 0;
128
132
  try {
133
+ // Le jeton par son nom actuel, son préfixe ou le début de son id : ses lignes, même sous un ancien nom
134
+ if (token) add(...tokenCondition(token, await resolveTokenIds(client, token)));
129
135
  const first = await client.query(
130
136
  `select id, ts, level, service, msg, request_id, attrs from ${from()} order by ts desc, id desc limit ${limit}`,
131
137
  values,
@@ -154,9 +160,52 @@ module.exports = async (args = {}, raw = []) => {
154
160
  }
155
161
  }
156
162
  } catch (err) {
157
- process.exitCode = 1;
158
- console.log(chalk.redBright(`Logs not readable: ${err.message}`));
163
+ // Connexion perdue (engine arrêté pendant le suivi), ou erreur de la base : une phrase, pas une trace
164
+ const lost = err && ['ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'ETIMEDOUT'].includes(err.code);
165
+ fail(lost || /Connection terminated/i.test(String(err && err.message)) ? unreachable(config, err, true) : `Logs not readable: ${(err && err.message) || err}`);
159
166
  } finally {
160
167
  await client.end().catch(() => {});
161
168
  }
162
169
  };
170
+
171
+ class LogsError extends Error {}
172
+
173
+ /** Noms d'options reconnus (le reste, sans « - » devant, sont des services). Pure. */
174
+ const optionNames = (ATTR_OPTIONS) => ['level', 'since', 'request', 'grep', 'limit', 'run', 'token', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
175
+
176
+ /**
177
+ * Ce qui ne va pas dans les options, en une phrase (null : tout va bien). Pure.
178
+ * raw : les mots tels que tapés (parseArgs fait d'un « clé= » vide le nombre 0).
179
+ */
180
+ function checkOptions(args = {}, raw = [], { LEVELS, ATTR_OPTIONS }) {
181
+ const OPTIONS = optionNames(ATTR_OPTIONS);
182
+ // « --since 5m » était accepté en silence : --since ignoré, « 5m » pris pour un nom de service, et aucune ligne.
183
+ // Une option s'écrit nom=valeur : mieux vaut le dire que de répondre « No log line matches ».
184
+ const unknown = Object.keys(args).filter((k) => k.startsWith('-') && !OPTIONS.includes(k));
185
+ if (unknown.length) {
186
+ const hint = unknown.map((k) => k.replace(/^-+/, '').split('=')[0]).find((k) => OPTIONS.includes(k));
187
+ return `${unknown.join(', ')}: unknown option. Options are written name=value${hint ? `, for example ${hint}=${hint === 'since' ? '15m' : '…'}` : ' (level=warn since=15m flow=<name>), plus -f and --json'}.`;
188
+ }
189
+ const valued = OPTIONS.filter((o) => !o.startsWith('-') && !['follow', 'json'].includes(o));
190
+ for (const word of (raw || []).map(String)) {
191
+ const m = /^([a-z]+)=$/.exec(word);
192
+ if (m && valued.includes(m[1])) return `${m[1]}=: a value is expected${m[1] === 'since' ? ', such as since=15m' : m[1] === 'level' ? ' (debug, info, warn, error or fatal)' : ''}.`;
193
+ }
194
+ for (const o of ['level', 'since', 'request', 'grep', 'limit']) if (args[o] === true) return `${o}: a value is expected, written ${o}=<value>${o === 'since' ? ' (since=15m)' : o === 'level' ? ' (level=warn)' : o === 'limit' ? ' (limit=500)' : ''}.`;
195
+ if (args.level !== undefined && args.level !== '') {
196
+ const level = String(args.level).toLowerCase();
197
+ if (!LEVELS.includes(level)) return `level=${args.level}: debug, info, warn, error or fatal.`;
198
+ }
199
+ if (args.since !== undefined && args.since !== '' && !/^(\d+)\s*(s|m|h|d)$/.test(String(args.since))) return `since=${args.since}: a duration such as 30s, 15m, 2h, 1d.`;
200
+ if (args.limit !== undefined && args.limit !== '' && !(/^\d+$/.test(String(args.limit)) && Number(args.limit) >= 1 && Number(args.limit) <= 10000)) return `limit=${args.limit}: a number of lines from 1 to 10000.`;
201
+ return null;
202
+ }
203
+
204
+ /** Base du projet injoignable : ce qu'il faut savoir et faire. Pure. */
205
+ function unreachable(config, err, during = false) {
206
+ const port = config && config.db && config.db.port;
207
+ const why = (err && err.code) || (err && err.message) || String(err);
208
+ return `${during ? 'Lost the connection to' : 'The log store (database of the project) does not answer on'} 127.0.0.1:${port} (${why}). The engine may be starting or stopping: wait a few seconds, or check it with "poad info" ("poad start" if it is stopped).`;
209
+ }
210
+
211
+ Object.assign(module.exports, { checkOptions, unreachable, optionNames });
@@ -14,5 +14,6 @@ module.exports = async () => {
14
14
  const ok = await require('../utils/migrate-run')(root, config);
15
15
  if (!ok) process.exitCode = 1;
16
16
  // Tables de référence : après les migrations, quand leur structure est à jour
17
- else if (!(await require('../utils/reference').sync(root, config))) process.exitCode = 1;
17
+ // --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
18
+ else if (!(await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') }))) process.exitCode = 1;
18
19
  };
@@ -21,6 +21,12 @@ module.exports = async (args = {}) => {
21
21
 
22
22
  const root = findPoadDir(process.cwd());
23
23
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
24
+ // Une seule commande à la fois sur les conteneurs du projet (utils/project-lock.js)
25
+ const lock = require('../utils/project-lock').acquire(root, 'upgrade');
26
+ if (!lock.ok) {
27
+ process.exitCode = 1;
28
+ return console.log(chalk.redBright(require('../utils/project-lock').busyMessage(lock.held)));
29
+ }
24
30
  const config = readConfig(root);
25
31
  const flag = (name) => Boolean(args[name] || args[`--${name}`]);
26
32
  const yes = flag('yes') || Boolean(args['-y']);
@@ -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
+ });
@@ -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
@@ -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 }] }));
@@ -40,7 +40,10 @@ const sheets = {
40
40
  },
41
41
  stop: {
42
42
  usage: ['poad stop [keycloak | valkey | runner]'],
43
- text: ['Stop the project: engine, Mailpit, Keycloak, Valkey, flows runner, network. Its data stays in poad/data.'],
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: ['Everything combines: poad logs flows run=dafb44e1 step=call level=warn -f'],
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
- 'poad flows run <name> [key=value …] [input=<file.json>] [--wait | --no-wait]',
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 and follow its steps'],
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: [