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/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
  };
@@ -0,0 +1,41 @@
1
+ // poad storage cp <source> <destination> [-r] [--json]
2
+ // poad storage cp ./photo.png poad:images/ disque → Stockage
3
+ // poad storage cp -r ./site poad:web/ un dossier entier
4
+ // poad storage cp poad:images/photo.png ./ Stockage → disque
5
+ // poad storage cp -r poad:images/2024 poad:archives/ Stockage → Stockage
6
+ module.exports = (args, raw) =>
7
+ require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, ({ opts, positionals, out }) => copy({ opts, positionals, out, move: false }));
8
+
9
+ /** Partagé avec mv (move : sources supprimées une fois copiées, Stockage seulement) */
10
+ async function copy({ opts, positionals, out, move }) {
11
+ const s = require('../../utils/storage');
12
+ const c = require('../../utils/storage-copy');
13
+ const { usageError } = require('../../utils/cloud/api');
14
+ const { chalk } = out;
15
+ const verb = move ? 'mv' : 'cp';
16
+ if (positionals.length !== 2) throw usageError(`Usage: poad storage ${verb} <source> <destination> [-r]${move ? '' : ' (a storage path is written poad:bucket/path)'}`);
17
+ const api = s.client(await s.target(opts));
18
+ const { items } = await c.plan(api, positionals[0], positionals[1], { recursive: opts.recursive, remoteOnly: move });
19
+ const r = await c.run(api, items, {
20
+ onDone: (it) => out.log(` ${chalk.greenBright('✔')} ${c.label(it.from)} ${chalk.grey('→')} ${c.label(it.to)} ${chalk.grey(s.size(it.size))}`),
21
+ });
22
+ let deleted = [];
23
+ if (move && r.done.length) {
24
+ // Seules les sources bien copiées sont supprimées
25
+ const byBucket = new Map();
26
+ for (const it of r.done) byBucket.set(it.from.bucket, [...(byBucket.get(it.from.bucket) || []), it.from.key]);
27
+ for (const [bucket, keys] of byBucket)
28
+ for (let i = 0; i < keys.length; i += 1000) deleted.push(...((await api.remove(bucket, keys.slice(i, i + 1000))) || []).map((o) => s.show(bucket, o.name)));
29
+ }
30
+ for (const e of r.errors) out.log(chalk.redBright(` ✖ ${c.label(e.item.from)} → ${c.label(e.item.to)}: ${e.error.message}`));
31
+ const n = r.done.length;
32
+ out.log(chalk.grey(` ${n} file${n === 1 ? '' : 's'} ${move ? 'moved' : 'copied'}, ${s.size(r.bytes)}${r.errors.length ? `, ${r.errors.length} failed${move ? ' (left in place)' : ''}` : ''}`));
33
+ out.result({
34
+ [move ? 'moved' : 'copied']: r.done.map((it) => ({ from: c.label(it.from), to: c.label(it.to), size: it.size })),
35
+ ...(move ? { deleted } : {}),
36
+ failed: r.errors.map((e) => ({ from: c.label(e.item.from), to: c.label(e.item.to), error: e.error.message })),
37
+ });
38
+ return r.errors.length ? 1 : 0;
39
+ }
40
+
41
+ module.exports.copy = copy;
@@ -0,0 +1,2 @@
1
+ // poad storage : comme poad storage ls
2
+ module.exports = require('./ls');
@@ -0,0 +1,49 @@
1
+ // poad storage ls [bucket[/dossier]] [-r] [--json] : buckets, ou le contenu d'un dossier
2
+ module.exports = (args, raw) =>
3
+ require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, async ({ opts, positionals, out }) => {
4
+ const s = require('../../utils/storage');
5
+ const { chalk } = out;
6
+ if (positionals.length > 1) throw require('../../utils/cloud/api').usageError('Usage: poad storage ls [bucket[/folder]] [-r]');
7
+ const target = await s.target(opts);
8
+ const api = s.client(target);
9
+ const date = s.when;
10
+
11
+ if (!positionals.length) {
12
+ const buckets = await api.buckets();
13
+ out.result({ buckets });
14
+ if (!buckets.length) return out.log(chalk.grey(' No bucket yet: create one in the console (Storage), or with the API.'));
15
+ const w = Math.max(...buckets.map((b) => b.id.length));
16
+ for (const b of buckets) out.log(` ${chalk.bold(b.id.padEnd(w))} ${b.public ? chalk.yellowBright('public ') : chalk.grey('private')} ${chalk.grey(date(b.updated_at || b.created_at))}`);
17
+ return;
18
+ }
19
+
20
+ const where = s.parseRemote(positionals[0]);
21
+ await api.bucket(where.bucket).catch((e) => {
22
+ throw e.status === 404 ? new (require('../../utils/cloud/api').CloudError)(`No bucket "${where.bucket}".`, { code: 'not_found' }) : e;
23
+ });
24
+ const rows = await api.list(where.bucket, where.key);
25
+ const exact = !where.dir && rows.find((o) => o.name === where.key);
26
+ const prefix = where.key ? `${where.key}/` : '';
27
+ let list;
28
+ if (exact) list = [{ kind: 'file', name: exact.name, size: Number(exact.metadata && exact.metadata.size) || 0, updated: exact.updated_at, type: exact.metadata && exact.metadata.mimetype }];
29
+ else if (opts.recursive) list = rows.filter((o) => o.name.startsWith(prefix)).map((o) => ({ kind: 'file', name: o.name.slice(prefix.length), size: Number(o.metadata && o.metadata.size) || 0, updated: o.updated_at, type: o.metadata && o.metadata.mimetype }));
30
+ else list = s.entries(rows, prefix);
31
+ out.result({ bucket: where.bucket, path: where.key, entries: list });
32
+ if (out.json) return;
33
+ if (!list.length) {
34
+ process.exitCode = where.key ? 1 : 0;
35
+ return out.log(chalk.grey(where.key ? ` ${s.show(where.bucket, where.key)}: no such file or folder` : ` Bucket "${where.bucket}" is empty.`));
36
+ }
37
+ const sizes = list.map((e) => s.size(e.size));
38
+ const sw = Math.max(...sizes.map((x) => x.length));
39
+ let total = 0;
40
+ let files = 0;
41
+ list.forEach((e, i) => {
42
+ total += e.size;
43
+ files += e.kind === 'folder' ? e.count : 1;
44
+ const name = e.kind === 'folder' ? chalk.cyanBright(`${e.name}/`) : e.name;
45
+ const extra = e.kind === 'folder' ? chalk.grey(`${e.count} file${e.count === 1 ? '' : 's'}`) : chalk.grey(e.type || '');
46
+ out.log(` ${sizes[i].padStart(sw)} ${chalk.grey(date(e.updated))} ${name} ${extra}`);
47
+ });
48
+ out.log(chalk.grey(` ${files} file${files === 1 ? '' : 's'}, ${s.size(total)}`));
49
+ });
@@ -0,0 +1,7 @@
1
+ // poad storage mv <bucket/chemin> <bucket/chemin> [-r] [--json] : déplacer ou renommer dans le Stockage
2
+ // (copie puis suppression de la source ; une source dont la copie échoue reste en place).
3
+ // « poad: » devant les chemins est facultatif ici : les deux sont dans le Stockage.
4
+ module.exports = (args, raw) =>
5
+ require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, ({ opts, positionals, out }) =>
6
+ require('./cp').copy({ opts, positionals, out, move: true }),
7
+ );
@@ -0,0 +1,39 @@
1
+ // poad storage rm <bucket/chemin…> [-r] [--yes] [--json] : fichiers, ou tout un dossier avec -r
2
+ // Le contenu est retiré du backend (disque, S3, 1fichier) par le nettoyage du Stockage, une minute après.
3
+ module.exports = (args, raw) =>
4
+ require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, async ({ opts, positionals, out }) => {
5
+ const s = require('../../utils/storage');
6
+ const cli = require('../../utils/cloud/cli');
7
+ const { usageError } = require('../../utils/cloud/api');
8
+ const { chalk } = out;
9
+ if (!positionals.length) throw usageError('Usage: poad storage rm <bucket/path…> [-r] [--yes]');
10
+ const target = await s.target(opts);
11
+ const api = s.client(target);
12
+
13
+ // Tout est résolu avant de supprimer quoi que ce soit : un chemin inconnu n'en laisse pas d'autres à moitié faits
14
+ const groups = [];
15
+ for (const p of positionals) {
16
+ const where = s.parseRemote(p);
17
+ if (!where.key && !opts.recursive) throw usageError(`${where.bucket}: a whole bucket needs -r (its files only; the bucket stays)`);
18
+ const r = await s.resolve(api, where, opts.recursive);
19
+ groups.push({ where, ...r });
20
+ }
21
+ const count = groups.reduce((n, g) => n + g.objects.length, 0);
22
+ if (groups.some((g) => g.kind === 'folder')) {
23
+ const what = groups.map((g) => `${s.show(g.where.bucket, g.where.key)}${g.kind === 'folder' ? '/' : ''}`).join(', ');
24
+ await cli.confirm(`Delete ${count} file${count === 1 ? '' : 's'} (${what}) on the ${target.label}? This cannot be undone.`, { yes: opts.yes, json: out.json });
25
+ }
26
+ const removed = [];
27
+ for (const g of groups) {
28
+ const keys = g.objects.map((o) => o.name);
29
+ for (let i = 0; i < keys.length; i += 1000) {
30
+ const rows = await api.remove(g.where.bucket, keys.slice(i, i + 1000));
31
+ for (const r of rows || []) {
32
+ removed.push(s.show(g.where.bucket, r.name));
33
+ if (g.kind === 'file') out.log(` ${chalk.greenBright('✔')} ${s.show(g.where.bucket, r.name)} ${chalk.grey('deleted')}`);
34
+ }
35
+ }
36
+ if (g.kind === 'folder') out.log(` ${chalk.greenBright('✔')} ${s.show(g.where.bucket, g.where.key)}/ ${chalk.grey(`${keys.length} file${keys.length === 1 ? '' : 's'} deleted`)}`);
37
+ }
38
+ out.result({ deleted: removed });
39
+ });
@@ -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
+ });