poad 2.27.0 → 2.28.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/.github/workflows/release.yml +19 -1
- package/global/clean.js +3 -2
- package/global/cli.js +3 -3
- package/global/run.js +103 -2
- package/global/start.js +7 -1
- package/global/stop.js +26 -1
- package/package.json +3 -2
- package/poad.js +3 -1
- package/project/cli.js +2 -0
- package/project/flow.js +2 -0
- package/project/flows.js +411 -0
- package/project/setup.js +2 -1
- package/utils/config.js +23 -2
- package/utils/engine.js +7 -1
- package/utils/report.js +3 -2
- package/utils/runner.js +100 -0
- package/utils/services.js +22 -2
|
@@ -34,4 +34,22 @@ jobs:
|
|
|
34
34
|
- name: Publish to npm
|
|
35
35
|
uses: JS-DevTools/npm-publish@v1
|
|
36
36
|
with:
|
|
37
|
-
token: ${{ secrets.NPM_TOKEN }}
|
|
37
|
+
token: ${{ secrets.NPM_TOKEN }}
|
|
38
|
+
|
|
39
|
+
# Le registre annonce une version avant que son archive soit servie
|
|
40
|
+
# partout : le workflow n'est vert que lorsqu'elle s'installe vraiment.
|
|
41
|
+
- name: Wait until the package can be installed
|
|
42
|
+
run: |
|
|
43
|
+
NAME=$(node -p "require('./package.json').name")
|
|
44
|
+
VERSION=$(node -p "require('./package.json').version")
|
|
45
|
+
URL="https://registry.npmjs.org/$NAME/-/${NAME##*/}-$VERSION.tgz"
|
|
46
|
+
for i in $(seq 1 60); do
|
|
47
|
+
if [ "$(curl -s -o /dev/null -w '%{http_code}' "$URL")" = "200" ] \
|
|
48
|
+
&& [ "$(curl -s "https://registry.npmjs.org/$NAME/latest" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).version")" = "$VERSION" ]; then
|
|
49
|
+
echo "$NAME@$VERSION is installable"
|
|
50
|
+
exit 0
|
|
51
|
+
fi
|
|
52
|
+
sleep 10
|
|
53
|
+
done
|
|
54
|
+
echo "::error::$NAME@$VERSION was published but is still not downloadable after 10 minutes"
|
|
55
|
+
exit 1
|
package/global/clean.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// poad clean restes des projets poad sur cette machine, à purger :
|
|
2
|
-
// - services annexes (Mailpit, Keycloak, Valkey
|
|
2
|
+
// - services annexes (Mailpit, Keycloak, Valkey, exécuteur
|
|
3
|
+
// des flows) dont l'engine
|
|
3
4
|
// ne tourne plus (engine arrêté hors de poad stop : Docker
|
|
4
5
|
// Desktop, redémarrage, ancienne version du CLI) ;
|
|
5
6
|
// - conteneurs poad arrêtés, réseaux des projets arrêtés ;
|
|
@@ -31,7 +32,7 @@ module.exports = async (args = {}) => {
|
|
|
31
32
|
const doomed = [];
|
|
32
33
|
for (const c of containers) {
|
|
33
34
|
const name = nameOf(c);
|
|
34
|
-
const side = new RegExp(`^(${UUID})-(mail|keycloak|valkey)$`).exec(name);
|
|
35
|
+
const side = new RegExp(`^(${UUID})-(mail|keycloak|valkey|runner)$`).exec(name);
|
|
35
36
|
if (side && !running.has(side[1])) doomed.push({ c, why: `${side[2]} of a stopped project` });
|
|
36
37
|
else if (engines.includes(c) && c.State !== 'running') doomed.push({ c, why: 'stopped engine' });
|
|
37
38
|
}
|
package/global/cli.js
CHANGED
|
@@ -10,7 +10,7 @@ module.exports = {
|
|
|
10
10
|
install: `Install poad environment`,
|
|
11
11
|
init: `Init poad project`,
|
|
12
12
|
start: 'Start the project, apply migrations, start the services chosen with poad setup, then show its state (--all: every configured service, --bare: engine and mail only)',
|
|
13
|
-
stop: 'Stop container for poad local development (stop kc|valkey: that service only)',
|
|
14
|
-
run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, --all)',
|
|
15
|
-
clean: 'Remove what stopped poad projects left on this machine: orphan Mailpit/Keycloak/Valkey, networks, unused engine images (--dry-run to list, --yes without question)',
|
|
13
|
+
stop: 'Stop container for poad local development (stop kc|valkey|runner: that service only)',
|
|
14
|
+
run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, runner, --all)',
|
|
15
|
+
clean: 'Remove what stopped poad projects left on this machine: orphan Mailpit/Keycloak/Valkey/flows runner, networks, unused engine images (--dry-run to list, --yes without question)',
|
|
16
16
|
};
|
package/global/run.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// poad run <service> : démarre un service optionnel à côté du projet.
|
|
2
2
|
// poad run keycloak | kc Keycloak local, déclaré comme fournisseur OIDC
|
|
3
3
|
// poad run valkey | redis Valkey local (REDIS_URL de l'engine)
|
|
4
|
+
// poad run runner exécuteur des flows (engine 0.18.0+, exige Valkey) :
|
|
5
|
+
// il reçoit la socket Docker de la machine
|
|
4
6
|
// poad run --all | all le projet s'il est arrêté, puis tous les services
|
|
5
7
|
// optionnels configurés dans config.toml
|
|
6
8
|
module.exports = async (args = {}) => {
|
|
@@ -19,6 +21,7 @@ module.exports = async (args = {}) => {
|
|
|
19
21
|
const kc = require('../utils/keycloak');
|
|
20
22
|
const mail = require('../utils/mail');
|
|
21
23
|
const valkey = require('../utils/valkey');
|
|
24
|
+
const runner = require('../utils/runner');
|
|
22
25
|
const { SERVICES, containerState, wantedServices, wantsAll } = require('../utils/services');
|
|
23
26
|
|
|
24
27
|
const all = wantsAll(args);
|
|
@@ -34,6 +37,7 @@ module.exports = async (args = {}) => {
|
|
|
34
37
|
console.log(' ');
|
|
35
38
|
console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
|
|
36
39
|
console.log(` ${chalk.cyanBright('valkey')} ${chalk.grey('(or redis)')} Local Valkey (Redis compatible), REDIS_URL of the engine`);
|
|
40
|
+
console.log(` ${chalk.cyanBright('runner')} Flows runner (engine 0.18.0+, needs Valkey): starts the container steps of the flows, gets the Docker socket`);
|
|
37
41
|
console.log(` ${chalk.cyanBright('--all')} ${chalk.grey('(or all)')} The project if stopped, then every service configured in config.toml`);
|
|
38
42
|
console.log(' ');
|
|
39
43
|
return;
|
|
@@ -65,12 +69,12 @@ module.exports = async (args = {}) => {
|
|
|
65
69
|
return false;
|
|
66
70
|
};
|
|
67
71
|
|
|
68
|
-
const runners = { keycloak: runKeycloak, valkey: runValkey };
|
|
72
|
+
const runners = { keycloak: runKeycloak, valkey: runValkey, runner: runRunner };
|
|
69
73
|
let targets = wanted;
|
|
70
74
|
if (all) {
|
|
71
75
|
targets = SERVICES.filter((s) => s.optional && s.configured(config));
|
|
72
76
|
if (!targets.length) {
|
|
73
|
-
console.log(chalk.grey(' No optional service configured yet: "poad run kc" or "poad run
|
|
77
|
+
console.log(chalk.grey(' No optional service configured yet: "poad run kc", "poad run valkey" or "poad run runner" adds one.'));
|
|
74
78
|
return;
|
|
75
79
|
}
|
|
76
80
|
}
|
|
@@ -284,4 +288,101 @@ module.exports = async (args = {}) => {
|
|
|
284
288
|
console.log(' ');
|
|
285
289
|
}
|
|
286
290
|
}
|
|
291
|
+
|
|
292
|
+
/** Exécuteur des flows : lance les étapes « conteneur », avec la socket Docker */
|
|
293
|
+
async function runRunner() {
|
|
294
|
+
const { supportsFlows } = require('../utils/engine');
|
|
295
|
+
// Code de sortie 1 pour « poad run runner » ; poad start et --all continuent sans lui
|
|
296
|
+
const failed = () => {
|
|
297
|
+
if (!all && !listed) process.exitCode = 1;
|
|
298
|
+
};
|
|
299
|
+
if (!supportsFlows(config)) {
|
|
300
|
+
// poad start / --all : un projet resté sur un ancien engine n'est pas une erreur
|
|
301
|
+
if (all || listed) return console.log(chalk.grey(` Flows runner not started: engine ${config.engine} has no flows ("poad upgrade" to 0.18.0 or later).`));
|
|
302
|
+
failed();
|
|
303
|
+
return console.log(chalk.redBright(`The flows runner needs engine 0.18.0 or later (this project uses ${config.engine}): "poad upgrade".`));
|
|
304
|
+
}
|
|
305
|
+
if (!valkey.enabled(config)) {
|
|
306
|
+
failed();
|
|
307
|
+
return console.log(chalk.redBright('The flows runner needs Valkey: poad run valkey'));
|
|
308
|
+
}
|
|
309
|
+
const fresh = !runner.enabled(config);
|
|
310
|
+
if (fresh) {
|
|
311
|
+
// Une fois, à l'activation : ce que ce conteneur peut faire sur la machine
|
|
312
|
+
console.log(chalk.yellowBright.bold(' Warning: Docker access'));
|
|
313
|
+
for (const line of runner.WARNING) console.log(chalk.yellowBright(` ${line}`));
|
|
314
|
+
console.log(' ');
|
|
315
|
+
}
|
|
316
|
+
if (!(await pullIfMissing(docker, runner.image(config)))) {
|
|
317
|
+
failed();
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (fresh) require('../utils/tomlfile').setKeys(root, 'flows', { runner: true });
|
|
321
|
+
// Secret partagé avec le service flows de l'engine (créé une fois, jamais affiché)
|
|
322
|
+
require('../utils/config').ensureRunnerToken(root, config);
|
|
323
|
+
config = readConfig();
|
|
324
|
+
|
|
325
|
+
// La file des étapes est sur Valkey : sans lui, l'exécuteur n'a rien à lire
|
|
326
|
+
if ((await containerState(docker, valkey.containerName(config))) !== 'running') {
|
|
327
|
+
if (!quiet) console.log(chalk.grey(' Valkey is not running: starting it first (the flows runner reads its queue there).'));
|
|
328
|
+
await runValkey();
|
|
329
|
+
if ((await containerState(docker, valkey.containerName(config))) !== 'running') {
|
|
330
|
+
failed();
|
|
331
|
+
return console.log(chalk.redBright('Flows runner not started: Valkey is not running.'));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const name = runner.containerName(config);
|
|
336
|
+
const progress = ora('Starting the flows runner').start();
|
|
337
|
+
try {
|
|
338
|
+
// Un exécuteur déjà lancé : arrêt propre (il rend compte des étapes en cours)
|
|
339
|
+
try {
|
|
340
|
+
await docker.getContainer(name).stop();
|
|
341
|
+
} catch {
|
|
342
|
+
/* pas de conteneur précédent, ou déjà arrêté */
|
|
343
|
+
}
|
|
344
|
+
try {
|
|
345
|
+
await docker.getContainer(name).remove({ force: true });
|
|
346
|
+
} catch {
|
|
347
|
+
/* déjà retiré (AutoRemove) */
|
|
348
|
+
}
|
|
349
|
+
for (let i = 0; i < 20 && (await isDockerExist(name)); i++) await new Promise((r) => setTimeout(r, 500));
|
|
350
|
+
await mail.ensureNetwork(docker, config);
|
|
351
|
+
const container = await docker.createContainer(runner.containerOptions(config));
|
|
352
|
+
await container.start();
|
|
353
|
+
// Aucun port à interroger : il doit simplement tourner encore un instant plus tard
|
|
354
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
355
|
+
if ((await containerState(docker, name)) !== 'running') throw new Error('the container stopped right after its start (bad image, Docker socket or Valkey unreachable)');
|
|
356
|
+
progress.succeed(chalk.bold('Flows runner started.'));
|
|
357
|
+
} catch (err) {
|
|
358
|
+
progress.fail(chalk.redBright(`Flows runner failed to start: ${err.message}`));
|
|
359
|
+
failed();
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Le service flows de l'engine ne tourne que si l'engine a reçu FLOWS_* à son démarrage
|
|
364
|
+
let engineReady = false;
|
|
365
|
+
try {
|
|
366
|
+
const data = await docker.getContainer(config.project_uuid).inspect();
|
|
367
|
+
engineReady = runner.engineHasFlowsEnv(data.Config && data.Config.Env, config);
|
|
368
|
+
} catch {
|
|
369
|
+
/* engine introuvable : rien à dire de plus */
|
|
370
|
+
}
|
|
371
|
+
if (!engineReady) console.log(chalk.yellowBright(' The engine was started without these flows settings: run "poad stop" then "poad start".'));
|
|
372
|
+
if (quiet) return;
|
|
373
|
+
|
|
374
|
+
console.log(' ');
|
|
375
|
+
console.log(
|
|
376
|
+
prettyoutput({
|
|
377
|
+
Image: runner.image(config),
|
|
378
|
+
Ports: 'no published port',
|
|
379
|
+
Queue: `${valkey.URL} (Valkey of the project)`,
|
|
380
|
+
'Runs steps on': `network ${mail.networkName(config)}`,
|
|
381
|
+
})
|
|
382
|
+
);
|
|
383
|
+
if (fresh) {
|
|
384
|
+
console.log(chalk.grey(` [flows] runner = true written to ${path.relative(process.cwd(), root)}: the runner now starts and stops with the project ("poad stop runner" stops it, runner = false turns it off).`));
|
|
385
|
+
console.log(' ');
|
|
386
|
+
}
|
|
387
|
+
}
|
|
287
388
|
};
|
package/global/start.js
CHANGED
|
@@ -24,6 +24,7 @@ module.exports = async (args = {}) => {
|
|
|
24
24
|
const { pullIfMissing } = require('../utils/pull');
|
|
25
25
|
const mail = require('../utils/mail');
|
|
26
26
|
const valkey = require('../utils/valkey');
|
|
27
|
+
const runner = require('../utils/runner');
|
|
27
28
|
const root = findPoadDir(process.cwd());
|
|
28
29
|
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
29
30
|
const config = require('../utils/config').readConfig(root);
|
|
@@ -55,6 +56,9 @@ module.exports = async (args = {}) => {
|
|
|
55
56
|
return console.log(chalk.redBright(`No [mail] port in ${root}: add a [mail] section with a free port.`));
|
|
56
57
|
}
|
|
57
58
|
if (mailpit && !(await pullIfMissing(docker, mail.MAILPIT_IMAGE))) return;
|
|
59
|
+
// Flows (engine 0.18.0+) : leur file est sur le Valkey du projet. Le secret
|
|
60
|
+
// partagé avec l'exécuteur est créé au premier démarrage qui s'en sert.
|
|
61
|
+
if (require('../utils/engine').supportsFlows(config) && valkey.enabled(config)) require('../utils/config').ensureRunnerToken(root, config);
|
|
58
62
|
|
|
59
63
|
// Base neuve (premier démarrage, poad db reset) : seed.sql après les migrations
|
|
60
64
|
const fsSync = require('fs');
|
|
@@ -98,6 +102,8 @@ module.exports = async (args = {}) => {
|
|
|
98
102
|
'SERVICE_ROLE_KEY=' + config.auth.service,
|
|
99
103
|
...mail.smtpEnv(config),
|
|
100
104
|
...valkey.engineEnv(config),
|
|
105
|
+
// FLOWS_* : engine 0.18.0+ et Valkey configuré ; sinon le service flows reste arrêté
|
|
106
|
+
...runner.engineEnv(config),
|
|
101
107
|
],
|
|
102
108
|
ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed },
|
|
103
109
|
HostConfig: {
|
|
@@ -108,7 +114,7 @@ module.exports = async (args = {}) => {
|
|
|
108
114
|
...gelf.bindings,
|
|
109
115
|
},
|
|
110
116
|
// poad/migrations monté : la console y écrit les migrations qu'elle crée
|
|
111
|
-
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`],
|
|
117
|
+
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`],
|
|
112
118
|
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
113
119
|
// compris sous Linux
|
|
114
120
|
ExtraHosts: ['host.docker.internal:host-gateway'],
|
package/global/stop.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
// poad stop arrête le projet : engine, Mailpit, Keycloak,
|
|
1
|
+
// poad stop arrête le projet : engine, Mailpit, Keycloak, Valkey,
|
|
2
|
+
// exécuteur des flows, réseau
|
|
2
3
|
// poad stop keycloak|kc arrête seulement Keycloak et retire le fournisseur
|
|
3
4
|
// poad stop valkey|redis arrête seulement Valkey
|
|
5
|
+
// poad stop runner arrête seulement l'exécuteur des flows
|
|
4
6
|
module.exports = async (args) => {
|
|
5
7
|
const Docker = require('dockerode');
|
|
6
8
|
const docker = new Docker();
|
|
@@ -11,6 +13,7 @@ module.exports = async (args) => {
|
|
|
11
13
|
const kc = require('../utils/keycloak');
|
|
12
14
|
const mail = require('../utils/mail');
|
|
13
15
|
const valkey = require('../utils/valkey');
|
|
16
|
+
const runner = require('../utils/runner');
|
|
14
17
|
const root = findPoadDir(process.cwd());
|
|
15
18
|
if (!root) return console.log(require('chalk-v2').redBright('You are not in a poad project directory.'));
|
|
16
19
|
const config = require('../utils/config').readConfig(root);
|
|
@@ -59,6 +62,26 @@ module.exports = async (args) => {
|
|
|
59
62
|
return true;
|
|
60
63
|
};
|
|
61
64
|
|
|
65
|
+
// L'exécuteur reçoit SIGTERM et a StopTimeout secondes pour rendre compte
|
|
66
|
+
// des étapes en cours ; AutoRemove le retire ensuite.
|
|
67
|
+
const stopRunner = async () => {
|
|
68
|
+
const name = runner.containerName(config);
|
|
69
|
+
if (!(await isDockerExist(name))) return false;
|
|
70
|
+
const progress = ora('Stopping the flows runner').start();
|
|
71
|
+
try {
|
|
72
|
+
await docker.getContainer(name).stop();
|
|
73
|
+
for (let i = 0; i < 20 && (await isDockerExist(name)); i++) await new Promise((r) => setTimeout(r, 500));
|
|
74
|
+
progress.succeed(chalk.bold('Flows runner stopped'));
|
|
75
|
+
} catch {
|
|
76
|
+
progress.fail('Error: Failed to stop the flows runner');
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
if (runner.wanted(args)) {
|
|
82
|
+
if (!(await stopRunner())) console.log(chalk.redBright('The flows runner is not running'));
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
62
85
|
if (kc.wanted(args)) {
|
|
63
86
|
if (!(await stopKeycloak())) console.log(chalk.redBright('Keycloak is not running'));
|
|
64
87
|
return;
|
|
@@ -68,6 +91,8 @@ module.exports = async (args) => {
|
|
|
68
91
|
return;
|
|
69
92
|
}
|
|
70
93
|
|
|
94
|
+
// L'exécuteur d'abord : il rend compte à l'engine, par Valkey et par HTTP
|
|
95
|
+
await stopRunner();
|
|
71
96
|
await stopKeycloak();
|
|
72
97
|
await stopValkey();
|
|
73
98
|
const engine = await isDockerExist(containerName);
|
package/package.json
CHANGED
package/poad.js
CHANGED
|
@@ -374,7 +374,9 @@ const processCommands = (args) => {
|
|
|
374
374
|
const px = parseCommandArgs(require(__dirname + '/project/cli'), args);
|
|
375
375
|
|
|
376
376
|
const unit = require(path.join(__dirname, 'project', px.dir));
|
|
377
|
-
|
|
377
|
+
// Second argument : les mots tels que tapés (parseArgs convertit les
|
|
378
|
+
// valeurs et coupe au second « = » ; poad flows run en a besoin intacts)
|
|
379
|
+
return unit(parseArgs(px.args), px.args);
|
|
378
380
|
} else {
|
|
379
381
|
log.error('Unknown command : ' + command);
|
|
380
382
|
return displayBanner();
|
package/project/cli.js
CHANGED
|
@@ -32,6 +32,8 @@ module.exports = {
|
|
|
32
32
|
migration: 'Database migrations: migration new <name>, migration list',
|
|
33
33
|
functions: 'Functions of the project (JS/TS, served on /functions/v1/<name>): functions new <name> (or create), functions list, functions types (editor autocompletion)',
|
|
34
34
|
function: 'Same as functions: function create <name>, function list',
|
|
35
|
+
flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): flows new <name>, flows list, flows run <name> [key=value …] [input=<file.json>] [--no-wait], flows runs [name] [limit=20], flows show <run_id>, flows cancel <run_id>',
|
|
36
|
+
flow: 'Same as flows: flow new <name>, flow list, flow run <name>',
|
|
35
37
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
36
38
|
gen: {
|
|
37
39
|
description: 'Génération automatique des éléments clés pour votre projet',
|
package/project/flow.js
ADDED
package/project/flows.js
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
// poad flows new <nom> crée poad/flows/<nom>.json (flow minimal)
|
|
2
|
+
// poad flows list flows du projet, vus par l'engine lancé
|
|
3
|
+
// poad flows run <nom> [clé=valeur …] [input=<fichier.json>] [--wait|--no-wait]
|
|
4
|
+
// lance un flow et suit ses étapes
|
|
5
|
+
// poad flows runs [nom] [limit=20] dernières exécutions
|
|
6
|
+
// poad flows show <run_id> détail d'une exécution
|
|
7
|
+
// poad flows cancel <run_id> annule une exécution en cours
|
|
8
|
+
//
|
|
9
|
+
// Un flow est une automatisation (déclencheur, étapes, arêtes) décrite dans
|
|
10
|
+
// poad/flows/<nom>.json. L'engine (0.18.0+) le sert sous /flows/v1 ; sa file
|
|
11
|
+
// est sur le Valkey du projet (poad run valkey). Les étapes « conteneur » sont
|
|
12
|
+
// lancées par l'exécuteur (poad run runner).
|
|
13
|
+
const NAME_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
14
|
+
const POLL_MS = 700;
|
|
15
|
+
const TIMEOUT_MS = 10000;
|
|
16
|
+
const MAX_OUTPUT = 4000;
|
|
17
|
+
const MAX_STEP_OUTPUT = 300;
|
|
18
|
+
const FINAL = ['completed', 'failed', 'cancelled'];
|
|
19
|
+
const USAGE =
|
|
20
|
+
'Usage: poad flows new <name> | list | run <name> [key=value …] [input=<file.json>] [--wait|--no-wait] | runs [name] [limit=20] | show <run_id> | cancel <run_id>';
|
|
21
|
+
const NEEDS_VALKEY = 'Flows need Valkey: "poad run valkey", then restart the project ("poad stop", "poad start").';
|
|
22
|
+
|
|
23
|
+
/** Flow minimal valide : déclencheur manuel → étape set qui rend un message. Pure. */
|
|
24
|
+
const template = (name) =>
|
|
25
|
+
`${JSON.stringify(
|
|
26
|
+
{
|
|
27
|
+
name,
|
|
28
|
+
title: name,
|
|
29
|
+
steps: [
|
|
30
|
+
{ id: 'start', name: 'start', type: 'trigger', trigger: { kind: 'manual' } },
|
|
31
|
+
{ id: 'hello', name: 'hello', type: 'set', params: { values: { message: 'Hello from poad flows' } } },
|
|
32
|
+
],
|
|
33
|
+
edges: [{ from: 'start', to: 'hello' }],
|
|
34
|
+
},
|
|
35
|
+
null,
|
|
36
|
+
2
|
|
37
|
+
)}\n`;
|
|
38
|
+
|
|
39
|
+
/** Valeur d'un clé=valeur : du JSON valide est pris tel quel, le reste est du texte. Pure. */
|
|
40
|
+
const parseValue = (text) => {
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(text);
|
|
43
|
+
} catch {
|
|
44
|
+
return text;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Arguments de `flows run`, après le mot « run ». Pure.
|
|
50
|
+
* Rend { name, input, file, wait } ou { error }. `input=<fichier>` désigne un
|
|
51
|
+
* fichier JSON (lu par l'appelant) ; les autres clé=valeur forment l'entrée.
|
|
52
|
+
*/
|
|
53
|
+
const parseRunArgs = (tokens) => {
|
|
54
|
+
const out = { name: null, input: {}, file: null, wait: true };
|
|
55
|
+
for (const token of tokens) {
|
|
56
|
+
const text = String(token);
|
|
57
|
+
if (text === '--wait') out.wait = true;
|
|
58
|
+
else if (text === '--no-wait') out.wait = false;
|
|
59
|
+
else if (text.startsWith('--')) return { error: `unknown option ${text}` };
|
|
60
|
+
else if (text.includes('=')) {
|
|
61
|
+
// Seul le premier « = » sépare : la valeur peut en contenir
|
|
62
|
+
const at = text.indexOf('=');
|
|
63
|
+
const key = text.slice(0, at);
|
|
64
|
+
const value = text.slice(at + 1);
|
|
65
|
+
if (!key) return { error: `"${text}": a key is expected before "="` };
|
|
66
|
+
if (key === 'input') out.file = value;
|
|
67
|
+
else out.input[key] = parseValue(value);
|
|
68
|
+
} else if (out.name === null) out.name = text;
|
|
69
|
+
else return { error: `"${text}": expected key=value` };
|
|
70
|
+
}
|
|
71
|
+
if (out.name === null) return { error: 'a flow name is expected' };
|
|
72
|
+
if (!NAME_RE.test(out.name)) return { error: `"${out.name}" is not a flow name` };
|
|
73
|
+
if (out.file === '') return { error: 'input=<file.json>: a file is expected' };
|
|
74
|
+
return out;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** Durée lisible : 850 ms, 1.2 s, 2 min 05 s. Pure. */
|
|
78
|
+
const duration = (ms) => {
|
|
79
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms)) return '';
|
|
80
|
+
if (ms < 1000) return `${Math.round(ms)} ms`;
|
|
81
|
+
if (ms < 59950) return `${(ms / 1000).toFixed(1)} s`;
|
|
82
|
+
const seconds = Math.round(ms / 1000);
|
|
83
|
+
return `${Math.floor(seconds / 60)} min ${String(seconds % 60).padStart(2, '0')} s`;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/** Texte coupé à max caractères, avec ce qui manque. Pure. */
|
|
87
|
+
const clip = (text, max) => (text.length > max ? `${text.slice(0, max)}… (${text.length - max} more characters)` : text);
|
|
88
|
+
|
|
89
|
+
/** Une valeur en JSON indenté, coupée à max caractères. Pure. */
|
|
90
|
+
const pretty = (value, max = MAX_OUTPUT) => clip(JSON.stringify(value === undefined ? null : value, null, 2), max);
|
|
91
|
+
|
|
92
|
+
/** Une valeur sur une ligne, coupée. Pure. */
|
|
93
|
+
const oneLine = (value, max = MAX_STEP_OUTPUT) => clip(JSON.stringify(value === undefined ? null : value), max);
|
|
94
|
+
|
|
95
|
+
/** Première ligne d'un message d'erreur. Pure. */
|
|
96
|
+
const firstLine = (text) => String(text || '').split('\n')[0];
|
|
97
|
+
|
|
98
|
+
/** Ce qui distingue deux états d'une étape : état et tentative. Pure. */
|
|
99
|
+
const stepKey = (step) => `${step.status}:${step.attempt || 0}`;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* La ligne d'une étape qui vient de changer d'état (null : rien à dire, elle attend). Pure.
|
|
103
|
+
* ✔ done, ✖ failed avec l'erreur, ○ skipped, … running
|
|
104
|
+
*/
|
|
105
|
+
const stepLine = (step) => {
|
|
106
|
+
const chalk = require('chalk-v2');
|
|
107
|
+
const name = chalk.bold(step.name);
|
|
108
|
+
const took = duration(step.duration_ms);
|
|
109
|
+
// attempt compte à partir de 0 : 1 est la première reprise
|
|
110
|
+
const attempt = step.attempt >= 1 ? chalk.grey(` (retry ${step.attempt})`) : '';
|
|
111
|
+
if (step.status === 'done') return ` ${chalk.greenBright('✔')} ${name} ${chalk.grey(`done${took ? ` in ${took}` : ''}`)}${attempt}`;
|
|
112
|
+
if (step.status === 'failed') return ` ${chalk.redBright('✖')} ${name} ${chalk.redBright(`failed: ${firstLine(step.error) || 'no error message'}`)}${attempt}`;
|
|
113
|
+
if (step.status === 'skipped') return ` ${chalk.grey('○')} ${name} ${chalk.grey('skipped')}`;
|
|
114
|
+
// Pendant une reprise, error porte l'échec de la tentative précédente
|
|
115
|
+
if (step.status === 'running') return ` ${chalk.cyan('…')} ${name} ${chalk.grey('running')}${attempt}${step.attempt >= 1 && step.error ? chalk.grey(`, after: ${firstLine(step.error)}`) : ''}`;
|
|
116
|
+
return null;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/** État d'une exécution, coloré. Pure. */
|
|
120
|
+
const paintStatus = (status) => {
|
|
121
|
+
const chalk = require('chalk-v2');
|
|
122
|
+
if (status === 'completed') return chalk.greenBright(status);
|
|
123
|
+
if (status === 'failed') return chalk.redBright(status);
|
|
124
|
+
if (status === 'cancelled') return chalk.yellowBright(status);
|
|
125
|
+
return chalk.cyan(String(status));
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/** Lignes d'un flow de la liste (GET /flows) : la seconde, s'il y en a une, est son premier problème. Pure. */
|
|
129
|
+
const flowLines = (flow, width = 0) => {
|
|
130
|
+
const chalk = require('chalk-v2');
|
|
131
|
+
const problems = Array.isArray(flow.problems) ? flow.problems : [];
|
|
132
|
+
const triggers = (flow.triggers || []).map((t) => t.kind || '?').join(', ') || 'no trigger';
|
|
133
|
+
const facts = `v${flow.version} ${flow.steps} step${flow.steps === 1 ? '' : 's'} ${triggers}${flow.enabled === false ? ' disabled' : ''}`;
|
|
134
|
+
const title = flow.title && flow.title !== flow.name ? ` ${flow.title}` : '';
|
|
135
|
+
const name = String(flow.name).padEnd(width);
|
|
136
|
+
if (!problems.length) return [` ${chalk.greenBright('✔')} ${chalk.bold(name)}${title} ${chalk.grey(facts)}`];
|
|
137
|
+
const first = problems[0] || {};
|
|
138
|
+
const more = problems.length > 1 ? ` (+${problems.length - 1} more)` : '';
|
|
139
|
+
return [
|
|
140
|
+
chalk.redBright(` ✖ ${name}${title} ${facts}`),
|
|
141
|
+
chalk.redBright(` ${first.path ? `${first.path}: ` : ''}${first.message || 'invalid definition'}${more}`),
|
|
142
|
+
];
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/** Date locale courte d'une date ISO. Pure (au fuseau près). */
|
|
146
|
+
const shortDate = (iso) => {
|
|
147
|
+
if (!iso) return '';
|
|
148
|
+
const d = new Date(iso);
|
|
149
|
+
if (Number.isNaN(d.getTime())) return String(iso);
|
|
150
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
151
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/** Ligne d'une exécution de la liste (GET /runs). Pure. */
|
|
155
|
+
const runLine = (run, width = 0) => {
|
|
156
|
+
const chalk = require('chalk-v2');
|
|
157
|
+
// L'état est complété avant d'être coloré : les codes de couleur fausseraient padEnd
|
|
158
|
+
const status = paintStatus(run.status) + ' '.repeat(Math.max(0, 9 - String(run.status).length));
|
|
159
|
+
return ` ${shortDate(run.created_at)} ${String(run.flow).padEnd(width)} ${status} ${duration(run.duration_ms).padStart(10)} ${String(run.trigger_kind || '').padEnd(7)} ${chalk.grey(run.id)}`;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Ce qu'une réponse en erreur veut dire, en une phrase (null : pas une erreur). Pure.
|
|
164
|
+
* 502/503/504, ou un 404 qui ne vient pas du service (pas de { error: { code } }) :
|
|
165
|
+
* la passerelle n'a pas de service flows derrière elle, donc pas de Valkey.
|
|
166
|
+
*/
|
|
167
|
+
const explain = (status, body) => {
|
|
168
|
+
if (status >= 200 && status < 300) return null;
|
|
169
|
+
const error = body && typeof body === 'object' && body.error && typeof body.error === 'object' ? body.error : null;
|
|
170
|
+
if (status === 502 || status === 503 || status === 504 || (status === 404 && !(error && error.code))) return NEEDS_VALKEY;
|
|
171
|
+
if (error && error.message) return `${error.message}${error.hint ? ` (${error.hint})` : ''}`;
|
|
172
|
+
if (status === 401 || status === 403) return `the engine refused the service_role key (HTTP ${status})`;
|
|
173
|
+
return `HTTP ${status}`;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
class FlowsError extends Error {}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* deps (tests) : started(config) → le projet tourne-t-il ?, fetch, sleep(ms), cwd.
|
|
180
|
+
* raw : les mots de la ligne de commande tels qu'ils ont été tapés.
|
|
181
|
+
*/
|
|
182
|
+
const main = async (args = {}, raw, deps = {}) => {
|
|
183
|
+
const chalk = require('chalk-v2');
|
|
184
|
+
const fs = require('fs');
|
|
185
|
+
const path = require('path');
|
|
186
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
187
|
+
const { readConfig } = require('../utils/config');
|
|
188
|
+
const { supportsFlows } = require('../utils/engine');
|
|
189
|
+
const cwd = deps.cwd || process.cwd();
|
|
190
|
+
const doFetch = deps.fetch || fetch;
|
|
191
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
192
|
+
const started = deps.started || ((config) => require('../utils/docker').isDockerExist(config.project_uuid));
|
|
193
|
+
|
|
194
|
+
const root = findPoadDir(cwd);
|
|
195
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
196
|
+
const dir = path.join(path.dirname(root), 'flows');
|
|
197
|
+
const rel = (p) => path.relative(cwd, p) || p;
|
|
198
|
+
// Les mots tels que tapés : parseArgs convertit les valeurs et coupe au second « = »
|
|
199
|
+
const words = Array.isArray(raw) ? raw.map(String) : Object.keys(args);
|
|
200
|
+
const command = words[0] || 'list';
|
|
201
|
+
const fail = (message) => {
|
|
202
|
+
process.exitCode = 1;
|
|
203
|
+
console.log(chalk.redBright(message));
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/** Configuration d'un projet prêt à répondre, ou null (message affiché) */
|
|
207
|
+
const ready = async () => {
|
|
208
|
+
const config = readConfig(root);
|
|
209
|
+
if (!supportsFlows(config)) return fail(`Flows need engine 0.18.0 or later (this project uses ${config.engine}): "poad upgrade".`) || null;
|
|
210
|
+
if (!(await started(config))) return fail('The project is not started: run "poad start".') || null;
|
|
211
|
+
return config;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
/** Appel de /flows/v1 avec la clé service_role ; lève FlowsError avec un message à afficher */
|
|
215
|
+
const call = async (config, method, route, body) => {
|
|
216
|
+
const key = config.auth.service;
|
|
217
|
+
const base = `http://localhost:${config.web.port}`;
|
|
218
|
+
let res;
|
|
219
|
+
try {
|
|
220
|
+
res = await doFetch(`${base}/flows/v1${route}`, {
|
|
221
|
+
method,
|
|
222
|
+
headers: { apikey: key, authorization: `Bearer ${key}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
|
|
223
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
224
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
225
|
+
});
|
|
226
|
+
} catch (err) {
|
|
227
|
+
const timedOut = err && (err.name === 'TimeoutError' || err.name === 'AbortError');
|
|
228
|
+
throw new FlowsError(timedOut ? `The engine did not answer within ${TIMEOUT_MS / 1000} s (${base}).` : `The engine does not answer on ${base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
|
|
229
|
+
}
|
|
230
|
+
const json = await res.json().catch(() => null);
|
|
231
|
+
const problem = explain(res.status, json);
|
|
232
|
+
if (problem) throw new FlowsError(problem);
|
|
233
|
+
return json || {};
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
// ------------------------------------------------------------------ new
|
|
237
|
+
if (command === 'new' || command === 'create') {
|
|
238
|
+
const name = String(words[1] || '');
|
|
239
|
+
if (!NAME_RE.test(name)) return fail('Flow name: a letter first, then a-z, 0-9 and "-" (poad flows new send-report).');
|
|
240
|
+
const file = path.join(dir, `${name}.json`);
|
|
241
|
+
if (fs.existsSync(file)) return fail(`${rel(file)} already exists.`);
|
|
242
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
243
|
+
fs.writeFileSync(file, template(name), { flag: 'wx' });
|
|
244
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(rel(file))}`);
|
|
245
|
+
console.log(chalk.grey(` A manual trigger, then a "set" step. The engine reads it on save: poad flows run ${name} (read an input with {{ input.name }} and pass it as name=poad)`));
|
|
246
|
+
const config = readConfig(root);
|
|
247
|
+
if (!supportsFlows(config)) console.log(chalk.yellowBright(` Engine ${config.engine} has no flows: "poad upgrade" to 0.18.0 or later.`));
|
|
248
|
+
else if (!require('../utils/valkey').enabled(config)) console.log(chalk.yellowBright(` ${NEEDS_VALKEY}`));
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ------------------------------------------------------------------ list
|
|
253
|
+
if (command === 'list') {
|
|
254
|
+
const config = await ready();
|
|
255
|
+
if (!config) return;
|
|
256
|
+
let flows;
|
|
257
|
+
try {
|
|
258
|
+
flows = (await call(config, 'GET', '/flows')).flows || [];
|
|
259
|
+
} catch (err) {
|
|
260
|
+
if (!(err instanceof FlowsError)) throw err;
|
|
261
|
+
return fail(err.message);
|
|
262
|
+
}
|
|
263
|
+
console.log(`${chalk.bold('Flows')} ${chalk.grey(rel(dir))}`);
|
|
264
|
+
console.log(' ');
|
|
265
|
+
if (!flows.length) return console.log(chalk.grey(' None yet: "poad flows new <name>".'));
|
|
266
|
+
const width = Math.max(...flows.map((f) => String(f.name).length));
|
|
267
|
+
for (const flow of flows) for (const line of flowLines(flow, width)) console.log(line);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ------------------------------------------------------------------ run
|
|
272
|
+
if (command === 'run') {
|
|
273
|
+
const parsed = parseRunArgs(words.slice(1));
|
|
274
|
+
if (parsed.error) {
|
|
275
|
+
fail(`poad flows run: ${parsed.error}.`);
|
|
276
|
+
return console.log(chalk.grey(' Usage: poad flows run <name> [key=value …] [input=<file.json>] [--wait|--no-wait]'));
|
|
277
|
+
}
|
|
278
|
+
// Le fichier d'abord, les clé=valeur par-dessus
|
|
279
|
+
let input = parsed.input;
|
|
280
|
+
if (parsed.file !== null) {
|
|
281
|
+
let fromFile;
|
|
282
|
+
try {
|
|
283
|
+
fromFile = JSON.parse(fs.readFileSync(path.resolve(cwd, parsed.file), 'utf-8'));
|
|
284
|
+
} catch (err) {
|
|
285
|
+
return fail(`input=${parsed.file}: ${err.code === 'ENOENT' ? 'no such file' : `not readable as JSON (${err.message})`}.`);
|
|
286
|
+
}
|
|
287
|
+
if (typeof fromFile !== 'object' || fromFile === null || Array.isArray(fromFile)) return fail(`input=${parsed.file}: the file must contain a JSON object.`);
|
|
288
|
+
input = { ...fromFile, ...parsed.input };
|
|
289
|
+
}
|
|
290
|
+
const config = await ready();
|
|
291
|
+
if (!config) return;
|
|
292
|
+
let runId;
|
|
293
|
+
try {
|
|
294
|
+
runId = (await call(config, 'POST', `/flows/${parsed.name}/run`, { input })).run_id;
|
|
295
|
+
} catch (err) {
|
|
296
|
+
if (!(err instanceof FlowsError)) throw err;
|
|
297
|
+
return fail(`Flow not started: ${err.message}`);
|
|
298
|
+
}
|
|
299
|
+
if (!parsed.wait) return console.log(runId);
|
|
300
|
+
|
|
301
|
+
console.log(`${chalk.bold(parsed.name)} ${chalk.grey(`run ${runId}`)}`);
|
|
302
|
+
const seen = new Map();
|
|
303
|
+
let misses = 0;
|
|
304
|
+
let view = null;
|
|
305
|
+
for (;;) {
|
|
306
|
+
try {
|
|
307
|
+
view = await call(config, 'GET', `/runs/${runId}`);
|
|
308
|
+
misses = 0;
|
|
309
|
+
} catch (err) {
|
|
310
|
+
if (!(err instanceof FlowsError)) throw err;
|
|
311
|
+
// Une lecture ratée n'arrête pas le suivi ; cinq de suite, si
|
|
312
|
+
if (++misses >= 5) {
|
|
313
|
+
fail(`Lost track of the run: ${err.message}`);
|
|
314
|
+
return console.log(chalk.grey(` It may still be running: poad flows show ${runId}`));
|
|
315
|
+
}
|
|
316
|
+
await sleep(POLL_MS);
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
for (const step of view.steps || []) {
|
|
320
|
+
const key = stepKey(step);
|
|
321
|
+
if (seen.get(step.step_id) === key) continue;
|
|
322
|
+
seen.set(step.step_id, key);
|
|
323
|
+
const line = stepLine(step);
|
|
324
|
+
if (line) console.log(line);
|
|
325
|
+
}
|
|
326
|
+
if (FINAL.includes(view.status)) break;
|
|
327
|
+
await sleep(POLL_MS);
|
|
328
|
+
}
|
|
329
|
+
console.log(' ');
|
|
330
|
+
console.log(`${paintStatus(view.status)}${view.duration_ms === null || view.duration_ms === undefined ? '' : chalk.grey(` in ${duration(view.duration_ms)}`)}`);
|
|
331
|
+
if (view.error) console.log(chalk.redBright(` ${firstLine(view.error)}`));
|
|
332
|
+
if (view.output !== null && view.output !== undefined) console.log(pretty(view.output));
|
|
333
|
+
if (view.status !== 'completed') process.exitCode = 1;
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// ------------------------------------------------------------------ runs
|
|
338
|
+
if (command === 'runs') {
|
|
339
|
+
let flow = null;
|
|
340
|
+
let limit = 20;
|
|
341
|
+
for (const word of words.slice(1)) {
|
|
342
|
+
if (word.startsWith('limit=')) {
|
|
343
|
+
limit = /^\d{1,6}$/.test(word.slice(6)) ? Number(word.slice(6)) : 0;
|
|
344
|
+
if (limit < 1) return fail('limit=<n>: a positive integer is expected (200 at most).');
|
|
345
|
+
} else if (flow === null && NAME_RE.test(word)) flow = word;
|
|
346
|
+
else return fail(`poad flows runs [name] [limit=20]: "${word}" is not a flow name.`);
|
|
347
|
+
}
|
|
348
|
+
const config = await ready();
|
|
349
|
+
if (!config) return;
|
|
350
|
+
let runs;
|
|
351
|
+
try {
|
|
352
|
+
runs = (await call(config, 'GET', `/runs?limit=${limit}${flow ? `&flow=${flow}` : ''}`)).runs || [];
|
|
353
|
+
} catch (err) {
|
|
354
|
+
if (!(err instanceof FlowsError)) throw err;
|
|
355
|
+
return fail(err.message);
|
|
356
|
+
}
|
|
357
|
+
console.log(`${chalk.bold('Runs')}${flow ? ` ${chalk.grey(flow)}` : ''}`);
|
|
358
|
+
console.log(' ');
|
|
359
|
+
if (!runs.length) return console.log(chalk.grey(flow ? ` No run of "${flow}" yet: poad flows run ${flow}` : ' No run yet: poad flows run <name>'));
|
|
360
|
+
const width = Math.max(...runs.map((r) => String(r.flow).length));
|
|
361
|
+
for (const run of runs) console.log(runLine(run, width));
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// ------------------------------------------------------------------ show, cancel
|
|
366
|
+
if (command === 'show' || command === 'cancel') {
|
|
367
|
+
const id = String(words[1] || '');
|
|
368
|
+
if (!id) return fail(`Usage: poad flows ${command} <run_id> ("poad flows runs" lists them).`);
|
|
369
|
+
const config = await ready();
|
|
370
|
+
if (!config) return;
|
|
371
|
+
try {
|
|
372
|
+
if (command === 'cancel') {
|
|
373
|
+
await call(config, 'POST', `/runs/${encodeURIComponent(id)}/cancel`);
|
|
374
|
+
return console.log(`${chalk.greenBright('✔')} Run ${id} cancelled.`);
|
|
375
|
+
}
|
|
376
|
+
const view = await call(config, 'GET', `/runs/${encodeURIComponent(id)}`);
|
|
377
|
+
console.log(`${chalk.bold(view.flow)} ${chalk.grey(`v${view.flow_version}`)} ${paintStatus(view.status)}${view.duration_ms === null || view.duration_ms === undefined ? '' : chalk.grey(` in ${duration(view.duration_ms)}`)}`);
|
|
378
|
+
console.log(chalk.grey(` run ${view.id} ${shortDate(view.created_at)} trigger: ${view.trigger_kind} (${view.trigger_step})`));
|
|
379
|
+
if (view.error) console.log(chalk.redBright(` ${firstLine(view.error)}`));
|
|
380
|
+
console.log(' ');
|
|
381
|
+
console.log(chalk.bold('Input'));
|
|
382
|
+
console.log(pretty(view.input));
|
|
383
|
+
console.log(' ');
|
|
384
|
+
console.log(chalk.bold('Steps'));
|
|
385
|
+
const steps = view.steps || [];
|
|
386
|
+
if (!steps.length) console.log(chalk.grey(' None started yet.'));
|
|
387
|
+
for (const step of steps) {
|
|
388
|
+
// Une étape en attente n'a pas de ligne d'état : on la montre quand même ici
|
|
389
|
+
console.log(stepLine(step) || ` ${chalk.grey('·')} ${chalk.bold(step.name)} ${chalk.grey(step.status)}`);
|
|
390
|
+
const facts = [step.type, step.runner ? `runner ${step.runner}` : '', Array.isArray(step.ports) && step.ports.length ? `port ${step.ports.join(', ')}` : ''].filter(Boolean).join(', ');
|
|
391
|
+
console.log(chalk.grey(` ${facts}`));
|
|
392
|
+
if (step.status === 'failed' && String(step.error || '').includes('\n')) for (const l of clip(String(step.error), MAX_OUTPUT).split('\n').slice(1)) console.log(chalk.redBright(` ${l}`));
|
|
393
|
+
if (step.output !== null && step.output !== undefined) console.log(chalk.grey(` output: ${oneLine(step.output)}`));
|
|
394
|
+
}
|
|
395
|
+
if (view.output !== null && view.output !== undefined) {
|
|
396
|
+
console.log(' ');
|
|
397
|
+
console.log(chalk.bold('Output'));
|
|
398
|
+
console.log(pretty(view.output));
|
|
399
|
+
}
|
|
400
|
+
return;
|
|
401
|
+
} catch (err) {
|
|
402
|
+
if (!(err instanceof FlowsError)) throw err;
|
|
403
|
+
return fail(err.message);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
fail(USAGE);
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
module.exports = (args, raw) => main(args, raw);
|
|
411
|
+
Object.assign(module.exports, { main, template, parseValue, parseRunArgs, duration, clip, pretty, stepKey, stepLine, flowLines, runLine, explain, NAME_RE, NEEDS_VALKEY });
|
package/project/setup.js
CHANGED
|
@@ -29,7 +29,8 @@ module.exports = async (args = {}) => {
|
|
|
29
29
|
const root = findPoadDir(process.cwd());
|
|
30
30
|
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
31
31
|
let config = readConfig(root);
|
|
32
|
-
|
|
32
|
+
// L'exécuteur des flows se règle ailleurs (poad run runner, [flows] runner)
|
|
33
|
+
const optional = SERVICES.filter((s) => s.optional && s.setup !== false);
|
|
33
34
|
console.log(' ');
|
|
34
35
|
|
|
35
36
|
// ------------------------------------------------------------ lecture
|
package/utils/config.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Configuration d'un projet poad, en deux fichiers :
|
|
2
2
|
// poad/config.toml versionné : ports, engine, services… aucun secret
|
|
3
3
|
// poad/secrets.toml propre à la machine, hors git : secret JWT et clés
|
|
4
|
-
// (anon, service_role, admin) signées avec lui
|
|
4
|
+
// (anon, service_role, admin) signées avec lui, mot de
|
|
5
|
+
// passe SMTP, secret de l'exécuteur des flows
|
|
5
6
|
//
|
|
6
7
|
// loadConfig() fusionne les deux : le reste du CLI lit config.auth.secret,
|
|
7
8
|
// config.auth.anon… comme avant. Un ancien config.toml qui contient encore
|
|
@@ -52,6 +53,24 @@ function writeSmtpPass(root, pass) {
|
|
|
52
53
|
setKeys(file, 'smtp', { pass }, { mode: 0o600 });
|
|
53
54
|
}
|
|
54
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Secret partagé entre le service flows de l'engine et l'exécuteur des étapes :
|
|
58
|
+
* secrets.toml ([flows] runner_token), 32 octets aléatoires en hexadécimal.
|
|
59
|
+
* Créé au premier besoin, puis gardé ; jamais affiché. Complète config.flows.
|
|
60
|
+
*/
|
|
61
|
+
function ensureRunnerToken(root, config) {
|
|
62
|
+
const existing = config.flows && config.flows.runner_token;
|
|
63
|
+
if (existing) return String(existing);
|
|
64
|
+
const { setKeys } = require('./tomlfile');
|
|
65
|
+
const file = secretsFile(root);
|
|
66
|
+
const token = require('crypto').randomBytes(32).toString('hex');
|
|
67
|
+
if (!fs.existsSync(file)) fs.writeFileSync(file, '# Secrets du projet poad local : hors git (poad/.gitignore)\n', { mode: 0o600 });
|
|
68
|
+
setKeys(file, 'flows', { runner_token: token }, { mode: 0o600 });
|
|
69
|
+
ensureGitignore(root);
|
|
70
|
+
config.flows = { ...(config.flows || {}), runner_token: token };
|
|
71
|
+
return token;
|
|
72
|
+
}
|
|
73
|
+
|
|
55
74
|
/** poad/.gitignore : data/, secrets.toml et backups/ (complète un fichier existant) */
|
|
56
75
|
function ensureGitignore(root) {
|
|
57
76
|
const file = path.join(poadDir(root), '.gitignore');
|
|
@@ -120,6 +139,8 @@ function loadConfig(root, notices = []) {
|
|
|
120
139
|
|
|
121
140
|
config.auth = { ...auth, ...Object.fromEntries(SECRET_KEYS.map((k) => [k, secrets[k]])) };
|
|
122
141
|
if (config.smtp && stored.smtp && stored.smtp.pass !== undefined) config.smtp.pass = String(stored.smtp.pass);
|
|
142
|
+
// Secret de l'exécuteur des flows : seulement s'il a déjà été créé (ensureRunnerToken)
|
|
143
|
+
if (stored.flows && stored.flows.runner_token) config.flows = { ...(config.flows || {}), runner_token: String(stored.flows.runner_token) };
|
|
123
144
|
return config;
|
|
124
145
|
}
|
|
125
146
|
|
|
@@ -134,4 +155,4 @@ function readConfig(root) {
|
|
|
134
155
|
return config;
|
|
135
156
|
}
|
|
136
157
|
|
|
137
|
-
module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, writeSmtpPass, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
|
|
158
|
+
module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, writeSmtpPass, ensureRunnerToken, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
|
package/utils/engine.js
CHANGED
|
@@ -41,6 +41,12 @@ const supportsConsole = (config) => {
|
|
|
41
41
|
return major > 0 || minor >= 11;
|
|
42
42
|
};
|
|
43
43
|
|
|
44
|
+
// Engine 0.18.0 et plus : flows (/flows/v1), définis dans poad/flows
|
|
45
|
+
const supportsFlows = (config) => {
|
|
46
|
+
const [major, minor] = String(config.engine || '').split('.').map(Number);
|
|
47
|
+
return major > 0 || minor >= 18;
|
|
48
|
+
};
|
|
49
|
+
|
|
44
50
|
const consoleUrl = (config) => `http://localhost:${config.web.port}/console`;
|
|
45
51
|
|
|
46
52
|
const dataInfo = (config) =>
|
|
@@ -58,7 +64,7 @@ const dataInfo = (config) =>
|
|
|
58
64
|
}
|
|
59
65
|
: {};
|
|
60
66
|
|
|
61
|
-
module.exports = { usesMinio, storageInfo, supportsData, supportsRealtime, supportsConsole, consoleUrl, dataInfo };
|
|
67
|
+
module.exports = { usesMinio, storageInfo, supportsData, supportsRealtime, supportsConsole, supportsFlows, consoleUrl, dataInfo };
|
|
62
68
|
|
|
63
69
|
// Projet resté sur un engine plus ancien que celui du CLI : propose de mettre
|
|
64
70
|
// à jour `engine` dans config.toml. La mise à jour migre poad/data : le projet
|
package/utils/report.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Affichage de l'état du projet, commun à poad info et poad start : le projet
|
|
2
2
|
// (URL, base, clés, migrations), puis le panneau des services (Mailpit,
|
|
3
|
-
// Keycloak, Valkey) avec leur état et leurs accès.
|
|
3
|
+
// Keycloak, Valkey, exécuteur des flows) avec leur état et leurs accès.
|
|
4
4
|
const path = require('path');
|
|
5
5
|
|
|
6
6
|
async function migrationsLine(root, config) {
|
|
@@ -73,6 +73,7 @@ async function printServices(root, config) {
|
|
|
73
73
|
for (const s of SERVICES) {
|
|
74
74
|
const configured = s.configured(config);
|
|
75
75
|
if (!configured && !s.optional) continue; // Mailpit remplacé par un vrai SMTP
|
|
76
|
+
if (!configured && s.available && !s.available(config)) continue; // engine sans ce service
|
|
76
77
|
const state = configured ? await containerState(docker, s.container(config)) : null;
|
|
77
78
|
// Keycloak partagé : il peut tourner pour un autre projet sans servir celui-ci
|
|
78
79
|
const sharedKc = s.id === 'keycloak' && require('./keycloak-shared').isShared(config);
|
|
@@ -99,7 +100,7 @@ async function printServices(root, config) {
|
|
|
99
100
|
const how = s.optional ? `poad run ${s.cmd}` : 'poad stop && poad start';
|
|
100
101
|
console.log(`${chalk.yellowBright('○')} ${label} ${chalk.yellowBright('stopped')}${tag} ${chalk.grey(`(${how})`)}`);
|
|
101
102
|
} else {
|
|
102
|
-
console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}, or poad setup`)}`);
|
|
103
|
+
console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}${s.setup === false ? '' : ', or poad setup'}`)}`);
|
|
103
104
|
}
|
|
104
105
|
}
|
|
105
106
|
console.log(rule);
|
package/utils/runner.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Exécuteur des flows, optionnel : `poad run runner` / `poad stop runner`.
|
|
2
|
+
//
|
|
3
|
+
// Les étapes « conteneur » d'un flow ne sont pas lancées par l'engine (il n'a
|
|
4
|
+
// aucun accès à Docker) mais par ce conteneur à part :
|
|
5
|
+
// - un conteneur par projet : <project_uuid>-runner (image poadio/runner) ;
|
|
6
|
+
// - il reçoit la socket Docker de la machine : il peut donc lancer des
|
|
7
|
+
// conteneurs. Il n'expose aucun port et ne lance que les étapes des flows
|
|
8
|
+
// du projet, sur le réseau du projet ;
|
|
9
|
+
// - il prend son travail dans une file BullMQ sur le Valkey du projet, et
|
|
10
|
+
// rend compte au service flows de l'engine avec un secret partagé
|
|
11
|
+
// (secrets.toml, [flows] runner_token) ;
|
|
12
|
+
// - activé par [flows] runner = true dans config.toml : il démarre et
|
|
13
|
+
// s'arrête alors avec le projet. Il exige Valkey ([valkey]).
|
|
14
|
+
//
|
|
15
|
+
// Ce module ne parle pas à Docker : tout y est calculé à partir de la
|
|
16
|
+
// configuration (global/run.js et global/stop.js créent et arrêtent le conteneur).
|
|
17
|
+
|
|
18
|
+
const mail = require('./mail');
|
|
19
|
+
const valkey = require('./valkey');
|
|
20
|
+
|
|
21
|
+
// Version de l'image par défaut (aussi dans package.json, champ "runner")
|
|
22
|
+
const RUNNER_VERSION = '0.1.0';
|
|
23
|
+
const NAMES = ['runner'];
|
|
24
|
+
const ALIAS = 'runner';
|
|
25
|
+
const DOCKER_SOCKET = '/var/run/docker.sock';
|
|
26
|
+
// Délai laissé à l'arrêt pour rendre compte des étapes en cours (secondes)
|
|
27
|
+
const STOP_TIMEOUT = 30;
|
|
28
|
+
// Port interne de la passerelle de l'engine (publié sur [web] port)
|
|
29
|
+
const GATEWAY_PORT = 8000;
|
|
30
|
+
|
|
31
|
+
const containerName = (config) => `${config.project_uuid}-runner`;
|
|
32
|
+
|
|
33
|
+
/** Le drapeau désigne-t-il l'exécuteur ? ({ runner: true }) */
|
|
34
|
+
const wanted = (args = {}) => NAMES.some((n) => args[n]);
|
|
35
|
+
|
|
36
|
+
/** Le projet lance-t-il l'exécuteur ? ([flows] runner = true) */
|
|
37
|
+
const enabled = (config) => Boolean(config.flows && config.flows.runner === true);
|
|
38
|
+
|
|
39
|
+
/** Image : [flows] runner_image, sinon la version inscrite dans le CLI */
|
|
40
|
+
const image = (config) => {
|
|
41
|
+
const custom = config.flows && typeof config.flows.runner_image === 'string' ? config.flows.runner_image.trim() : '';
|
|
42
|
+
return custom || `poadio/runner:${RUNNER_VERSION}`;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const token = (config) => (config.flows && config.flows.runner_token ? String(config.flows.runner_token) : '');
|
|
46
|
+
|
|
47
|
+
/** Adresse de la passerelle de l'engine vue d'un conteneur du réseau du projet */
|
|
48
|
+
const publicUrl = (config) => `http://${config.project_uuid}:${GATEWAY_PORT}`;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Variables de l'engine pour son service flows : engine 0.18.0 et plus, Valkey
|
|
52
|
+
* configuré, secret créé (ensureRunnerToken). Sans elles, le service reste arrêté.
|
|
53
|
+
*/
|
|
54
|
+
const engineEnv = (config) => {
|
|
55
|
+
if (!require('./engine').supportsFlows(config) || !valkey.enabled(config) || !token(config)) return [];
|
|
56
|
+
return [`FLOWS_REDIS_URL=${valkey.URL}`, `FLOWS_RUNNER_TOKEN=${token(config)}`, `FLOWS_PUBLIC_URL=${publicUrl(config)}`];
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** L'engine lancé a-t-il reçu ces variables ? (Env de son conteneur) */
|
|
60
|
+
const engineHasFlowsEnv = (env, config) => {
|
|
61
|
+
const list = Array.isArray(env) ? env : [];
|
|
62
|
+
const expected = engineEnv(config);
|
|
63
|
+
return expected.length > 0 && expected.every((line) => list.includes(line));
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Options de création du conteneur. Pure : ne dépend que de la configuration. */
|
|
67
|
+
const containerOptions = (config) => {
|
|
68
|
+
const net = mail.onNetwork(config, ALIAS);
|
|
69
|
+
return {
|
|
70
|
+
name: containerName(config),
|
|
71
|
+
Image: image(config),
|
|
72
|
+
Env: [
|
|
73
|
+
`POAD_RUNNER_REDIS_URL=${valkey.URL}`,
|
|
74
|
+
`POAD_RUNNER_TOKEN=${token(config)}`,
|
|
75
|
+
`POAD_RUNNER_NETWORK=${mail.networkName(config)}`,
|
|
76
|
+
`POAD_RUNNER_PROJECT=${config.project_uuid}`,
|
|
77
|
+
'POAD_RUNNER_NAME=docker',
|
|
78
|
+
'POAD_MODE=development',
|
|
79
|
+
],
|
|
80
|
+
StopTimeout: STOP_TIMEOUT,
|
|
81
|
+
NetworkingConfig: net.endpoint,
|
|
82
|
+
// Aucun port publié (ni ExposedPorts, ni PortBindings)
|
|
83
|
+
HostConfig: {
|
|
84
|
+
NetworkMode: net.NetworkMode,
|
|
85
|
+
Binds: [`${DOCKER_SOCKET}:${DOCKER_SOCKET}`],
|
|
86
|
+
// Comme les autres services du projet : retiré à l'arrêt, relancé par poad start
|
|
87
|
+
AutoRemove: true,
|
|
88
|
+
...require('./logs').containerLogConfig(config),
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/** Avertissement affiché une fois, à l'activation */
|
|
94
|
+
const WARNING = [
|
|
95
|
+
'The flows runner gets the Docker socket of this machine: it can start containers here.',
|
|
96
|
+
'It publishes no port and only starts the steps of the flows of this project.',
|
|
97
|
+
'The engine itself has no access to Docker.',
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
module.exports = { RUNNER_VERSION, NAMES, ALIAS, STOP_TIMEOUT, WARNING, containerName, wanted, enabled, image, token, publicUrl, engineEnv, engineHasFlowsEnv, containerOptions };
|
package/utils/services.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
// Services qui tournent à côté de l'engine, chacun dans son conteneur :
|
|
2
2
|
// - Mailpit : lancé par `poad start` (sauf si [smtp] désigne un vrai serveur) ;
|
|
3
3
|
// - Keycloak : optionnel, `poad run kc` ;
|
|
4
|
-
// - Valkey : optionnel, `poad run valkey
|
|
4
|
+
// - Valkey : optionnel, `poad run valkey` ;
|
|
5
|
+
// - Exécuteur des flows : optionnel, `poad run runner` (engine 0.18.0+).
|
|
5
6
|
// Un service optionnel est « configuré » quand config.toml a sa section (port
|
|
6
7
|
// choisi au premier lancement) : `poad run --all` relance ceux-là.
|
|
7
8
|
// Avec autostart = true dans sa section, `poad start` le lance aussi
|
|
8
|
-
// (`poad setup` règle ces options).
|
|
9
|
+
// (`poad setup` règle ces options). L'exécuteur des flows n'a ni port ni
|
|
10
|
+
// autostart : [flows] runner = true suffit, il suit alors le projet.
|
|
9
11
|
|
|
10
12
|
const kc = require('./keycloak');
|
|
11
13
|
const valkey = require('./valkey');
|
|
14
|
+
const runner = require('./runner');
|
|
12
15
|
const mail = require('./mail');
|
|
13
16
|
const path = require('path');
|
|
14
17
|
|
|
@@ -71,6 +74,23 @@ const SERVICES = [
|
|
|
71
74
|
savePort: (root, port) => valkey.savePort(root, port),
|
|
72
75
|
info: (config) => ({ URL: `redis://127.0.0.1:${config.valkey.port}`, 'From the engine': valkey.URL }),
|
|
73
76
|
},
|
|
77
|
+
{
|
|
78
|
+
id: 'runner',
|
|
79
|
+
label: 'Flows runner',
|
|
80
|
+
optional: true,
|
|
81
|
+
names: runner.NAMES,
|
|
82
|
+
cmd: 'runner',
|
|
83
|
+
section: 'flows',
|
|
84
|
+
// Hors de poad setup : activé par poad run runner (avertissement sur la socket Docker)
|
|
85
|
+
setup: false,
|
|
86
|
+
// Proposé seulement quand l'engine a des flows
|
|
87
|
+
available: (config) => require('./engine').supportsFlows(config),
|
|
88
|
+
container: (config) => runner.containerName(config),
|
|
89
|
+
configured: (config) => runner.enabled(config),
|
|
90
|
+
// Configuré = lancé avec le projet
|
|
91
|
+
autostart: (config) => runner.enabled(config),
|
|
92
|
+
info: (config) => ({ Image: runner.image(config), Ports: 'no published port', Docker: 'socket of this machine (starts the steps of the flows)' }),
|
|
93
|
+
},
|
|
74
94
|
];
|
|
75
95
|
|
|
76
96
|
/** État d'un conteneur : 'running', 'stopped' (existe mais arrêté) ou null (absent) */
|