@dokebi/cli 0.4.90 → 0.4.91

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.
@@ -4,7 +4,7 @@
4
4
  // names every option path a file gained, lost or changed (never a value), and a change outside
5
5
  // what the command was asked for is refused before anything is written (PATH_MISMATCH).
6
6
  import { parseDocument } from 'yaml';
7
- import { resolveItems } from './config-edit.js';
7
+ import { optionsBase, resolveItems } from './config-edit.js';
8
8
  import { parseProjectConfig } from './configuration.js';
9
9
  const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
10
10
  /** The leaf paths (a scalar or a list each) that differ between the options of two sources. */
@@ -34,10 +34,26 @@ export function optionChanges(before, after) {
34
34
  if (JSON.stringify(left) !== JSON.stringify(right))
35
35
  set.push(path.join('.'));
36
36
  };
37
- const a = parseProjectConfig(before).options;
38
- const b = parseProjectConfig(after).options;
37
+ const a = parseProjectConfig(before, { process: null }).options;
38
+ const b = parseProjectConfig(after, { process: null }).options;
39
39
  for (const key of new Set([...Object.keys(a), ...Object.keys(b)]))
40
40
  walk(a[key], b[key], [key], Object.hasOwn(a, key), Object.hasOwn(b, key));
41
+ // D-0251: what each process sets itself, as `processes.<name>.options.<section>…`.
42
+ const own = (source) => {
43
+ const value = parseDocument(source, { version: '1.2' }).toJS();
44
+ return isObject(value?.processes) ? value.processes : {};
45
+ };
46
+ const left = own(before);
47
+ const right = own(after);
48
+ for (const name of new Set([...Object.keys(left), ...Object.keys(right)])) {
49
+ const options = (side) => isObject(side[name]) && isObject(side[name].options)
50
+ ? side[name].options
51
+ : {};
52
+ const x = options(left);
53
+ const y = options(right);
54
+ for (const key of new Set([...Object.keys(x), ...Object.keys(y)]))
55
+ walk(x[key], y[key], ['processes', name, 'options', key], Object.hasOwn(x, key), Object.hasOwn(y, key));
56
+ }
41
57
  return { removed, set, added };
42
58
  }
43
59
  /** Each file's changes, the files nothing changed in left out. */
@@ -57,12 +73,17 @@ export function filePaths(files) {
57
73
  * indexes in `source` (`logging.targets.studio.token` → `logging.targets.3.token`); as typed when
58
74
  * the item is not there.
59
75
  */
60
- export function requestedPath(source, section, path) {
76
+ export function requestedPath(source, section, path,
77
+ /** D-0251: a path of this process's own options (`processes.<name>.options.<section>…`). */
78
+ process) {
79
+ const base = optionsBase(process);
61
80
  const resolved = resolveItems(parseDocument(source, { version: '1.2' }), [
62
- 'options',
81
+ ...base,
63
82
  section,
64
83
  ...path,
65
84
  ]);
85
+ if (process !== undefined)
86
+ return resolved ?? [...base, section, ...path];
66
87
  return resolved ? resolved.slice(1) : [section, ...path];
67
88
  }
68
89
  /**
@@ -33,6 +33,14 @@ export interface ConfigShowResult {
33
33
  * is reloadable too). Any other change needs a restart.
34
34
  */
35
35
  readonly reloadable: string[];
36
+ /**
37
+ * D-0251: the process whose options are shown (`--process`, or the one DOKEBI_PROCESS or a
38
+ * single-process `run` picks); absent for the shared options.
39
+ */
40
+ readonly process?: string;
41
+ /** D-0251: the processes the file declares and the ones this folder starts. */
42
+ readonly processes?: readonly string[];
43
+ readonly run?: readonly string[];
36
44
  readonly warnings?: ConfigShowWarning[];
37
45
  }
38
46
  /**
@@ -77,6 +85,8 @@ export declare function configShow(root: string, target?: {
77
85
  from?: {
78
86
  readonly source: string;
79
87
  readonly file?: string;
80
- }): Promise<ConfigShowResult>;
88
+ },
89
+ /** D-0251: show the options this process gets (the shared ones with its own merged in). */
90
+ process?: string): Promise<ConfigShowResult>;
81
91
  /** The result for people: YAML, defaults marked with a comment, secrets already hidden. */
82
92
  export declare function configShowText(result: ConfigShowResult): string;
@@ -376,11 +376,16 @@ export async function configShow(root, target,
376
376
  * Another document than the settings file (config diff reads the sample's secrets with it, and
377
377
  * the settings its transaction read).
378
378
  */
379
- from) {
379
+ from,
380
+ /** D-0251: show the options this process gets (the shared ones with its own merged in). */
381
+ process) {
380
382
  const state = readState(parseObject(await readText(root, '.dokebi/state.json'), 'state'));
381
383
  const read = from ? undefined : await readSettings(root);
382
384
  const file = from?.file ?? read?.target.file ?? CONFIG_FILE;
383
- const options = parseProjectConfig(from?.source ?? read?.source ?? '').options;
385
+ const parsed = parseProjectConfig(from?.source ?? read?.source ?? '', process === undefined ? undefined : { process });
386
+ const options = parsed.options;
387
+ // The process the options are of: asked, else what the DOKEBI_PROCESS rule picked.
388
+ const chosen = parsed.process;
384
389
  const sections = { ...options };
385
390
  // D-0151: the logger host's options are options.logging (optionsKey).
386
391
  for (const plugin of state.plugins)
@@ -524,6 +529,10 @@ from) {
524
529
  defaults: defaults.filter(inside),
525
530
  secrets: secrets.filter(inside),
526
531
  reloadable: reloadable.filter((path) => inside(path) || at.startsWith(`${path}.`)),
532
+ ...(chosen === undefined ? {} : { process: chosen }),
533
+ ...(parsed.processes
534
+ ? { processes: parsed.processes, run: parsed.run ?? parsed.processes }
535
+ : {}),
527
536
  ...(warnings.length ? { warnings } : {}),
528
537
  };
529
538
  }
@@ -1,3 +1,4 @@
1
+ import { type ProcessSelection } from '@dokebi/config';
1
2
  import { type Document } from 'yaml';
2
3
  import { CliError } from './errors.js';
3
4
  import { type ProjectConfig } from './project-state.js';
@@ -74,7 +75,11 @@ export declare function configOutsideProject(target: ConfigTarget): CliError;
74
75
  * `path`: the file DOKEBI_CONFIG names (configTarget), else dokebi.yaml of `root`.
75
76
  */
76
77
  export declare function readProjectConfigSource(root: string, path?: string): Promise<string>;
77
- export declare function parseProjectConfig(source: string): ProjectConfig;
78
+ /**
79
+ * The settings document, checked. `selection` (D-0251) picks the process whose options are read
80
+ * (`null`: the shared options alone); left out, @dokebi/config's DOKEBI_PROCESS rule applies.
81
+ */
82
+ export declare function parseProjectConfig(source: string, selection?: ProcessSelection): ProjectConfig;
78
83
  export declare function addConfigSection(source: string, id: string): string;
79
84
  export declare function migrateConfig(source: string): string;
80
85
  export declare function ignoreConfig(source: string): string;
@@ -215,9 +215,13 @@ export async function readProjectConfigSource(root, path) {
215
215
  await handle.close();
216
216
  }
217
217
  }
218
- export function parseProjectConfig(source) {
218
+ /**
219
+ * The settings document, checked. `selection` (D-0251) picks the process whose options are read
220
+ * (`null`: the shared options alone); left out, @dokebi/config's DOKEBI_PROCESS rule applies.
221
+ */
222
+ export function parseProjectConfig(source, selection) {
219
223
  try {
220
- return readConfig(parseConfig(source));
224
+ return readConfig(selection === undefined ? parseConfig(source) : parseConfig(source, undefined, selection));
221
225
  }
222
226
  catch (cause) {
223
227
  if (cause instanceof ConfigError) {
@@ -16,10 +16,18 @@ export interface InstanceLayout {
16
16
  readonly database: string;
17
17
  }
18
18
  export declare function layout(app: string, instance: string, port: number): InstanceLayout;
19
- export declare function systemdUnit(at: InstanceLayout): string;
19
+ /**
20
+ * The unit of an instance. With `processes` (D-0251: the settings run several) it is a template
21
+ * unit, `<unit>@.service`: one `<unit>@<process>` per process, each with DOKEBI_PROCESS set.
22
+ */
23
+ export declare function systemdUnit(at: InstanceLayout, processes?: readonly string[]): string;
20
24
  export declare function backupService(at: InstanceLayout): string;
21
25
  export declare function backupTimer(at: InstanceLayout): string;
22
- export declare function composeFile(at: InstanceLayout): string;
26
+ /**
27
+ * The compose file of an instance. With `processes` (D-0251) one service per process,
28
+ * `app-<process>`, each with DOKEBI_PROCESS set; else one service, `app`.
29
+ */
30
+ export declare function composeFile(at: InstanceLayout, processes?: readonly string[]): string;
23
31
  export interface GuideInput {
24
32
  readonly app: string;
25
33
  readonly target: 'systemd' | 'compose';
@@ -28,6 +36,8 @@ export interface GuideInput {
28
36
  readonly plugins: readonly string[];
29
37
  /** The secret paths the samples leave to the secrets file, per instance (the same list). */
30
38
  readonly secrets: readonly string[];
39
+ /** D-0251: the processes the instance settings run, when more than one (a unit each). */
40
+ readonly processes?: readonly string[];
31
41
  }
32
42
  /** DEPLOY.md: the instance table, setup, a release, rollback, backups (D-0184 §5, §6). */
33
43
  export declare function deployGuide(input: GuideInput): string;
@@ -16,9 +16,14 @@ export function layout(app, instance, port) {
16
16
  database: `${app}_${instance}`.replaceAll('-', '_'),
17
17
  };
18
18
  }
19
- export function systemdUnit(at) {
19
+ /**
20
+ * The unit of an instance. With `processes` (D-0251: the settings run several) it is a template
21
+ * unit, `<unit>@.service`: one `<unit>@<process>` per process, each with DOKEBI_PROCESS set.
22
+ */
23
+ export function systemdUnit(at, processes) {
24
+ const each = processes !== undefined && processes.length > 1;
20
25
  return `[Unit]
21
- Description=${at.app} (${at.instance})
26
+ Description=${at.app} (${at.instance}${each ? ', process %i' : ''})
22
27
  Documentation=file://${at.code}/current/DEPLOY.md
23
28
  After=network-online.target
24
29
  Wants=network-online.target
@@ -32,7 +37,11 @@ Group=${at.unit}
32
37
  WorkingDirectory=${at.code}/current
33
38
  Environment=NODE_ENV=production
34
39
  Environment=DOKEBI_CONFIG=${at.settings}
35
- Environment=DOKEBI_SECRETS=${at.secrets}
40
+ Environment=DOKEBI_SECRETS=${at.secrets}${each
41
+ ? `
42
+ # The process of the settings this unit runs (processes.<name>, D-0251): ${(processes ?? []).map((name) => `${at.unit}@${name}`).join(', ')}.
43
+ Environment=DOKEBI_PROCESS=%i`
44
+ : ''}
36
45
  # The node of the server (command -v node); Node.js 24 or later.
37
46
  ExecStart=/usr/bin/node src/main.ts
38
47
  # The app drains on SIGTERM; keep TimeoutStopSec above its drain and cleanup budget.
@@ -47,7 +56,7 @@ StateDirectory=${at.app}/${at.instance}
47
56
  StateDirectoryMode=0700
48
57
  LogsDirectory=${at.app}/${at.instance}
49
58
  LogsDirectoryMode=0750
50
- SyslogIdentifier=${at.unit}
59
+ SyslogIdentifier=${at.unit}${each ? '-%i' : ''}
51
60
  UMask=0077
52
61
  NoNewPrivileges=yes
53
62
  ProtectSystem=strict
@@ -102,16 +111,13 @@ Persistent=true
102
111
  WantedBy=timers.target
103
112
  `;
104
113
  }
105
- export function composeFile(at) {
106
- return `# ${at.app} (${at.instance}): docker compose -f deploy/compose/${at.instance}.yaml up -d --build
107
- # The container uses the host network, as the systemd unit would: ${at.port
108
- ? `the app listens on
109
- # 127.0.0.1:${at.port} (settings) behind the reverse proxy of the host, and`
110
- : 'the app'} reaches databases
111
- # on the host at 127.0.0.1. Settings and secrets are mounted read-only from /etc.
112
- name: ${at.unit}
113
- services:
114
- app:
114
+ /**
115
+ * The compose file of an instance. With `processes` (D-0251) one service per process,
116
+ * `app-<process>`, each with DOKEBI_PROCESS set; else one service, `app`.
117
+ */
118
+ export function composeFile(at, processes) {
119
+ const names = processes !== undefined && processes.length > 1 ? processes : undefined;
120
+ const service = (name) => ` ${name === undefined ? 'app' : `app-${name}`}:
115
121
  build:
116
122
  context: ../..
117
123
  image: ${at.app}:${at.instance}
@@ -122,7 +128,7 @@ services:
122
128
  environment:
123
129
  NODE_ENV: production
124
130
  DOKEBI_CONFIG: ${at.settings}
125
- DOKEBI_SECRETS: ${at.secrets}
131
+ DOKEBI_SECRETS: ${at.secrets}${name === undefined ? '' : `\n DOKEBI_PROCESS: ${name}`}
126
132
  volumes:
127
133
  - type: bind
128
134
  source: /etc/${at.app}/${at.instance}
@@ -148,6 +154,15 @@ services:
148
154
  max-size: 10m
149
155
  max-file: "5"
150
156
  `;
157
+ return `# ${at.app} (${at.instance}): docker compose -f deploy/compose/${at.instance}.yaml up -d --build
158
+ # The container uses the host network, as the systemd unit would: ${at.port
159
+ ? `the app listens on
160
+ # 127.0.0.1:${at.port} (settings) behind the reverse proxy of the host, and`
161
+ : 'the app'} reaches databases
162
+ # on the host at 127.0.0.1. Settings and secrets are mounted read-only from /etc.
163
+ name: ${at.unit}
164
+ services:
165
+ ${(names ?? [undefined]).map(service).join('')}`;
151
166
  }
152
167
  /** DEPLOY.md: the instance table, setup, a release, rollback, backups (D-0184 §5, §6). */
153
168
  export function deployGuide(input) {
@@ -157,6 +172,13 @@ export function deployGuide(input) {
157
172
  const db = input.plugins.includes('dokebi-db');
158
173
  const storage = input.plugins.includes('dokebi-storage');
159
174
  const first = input.instances[0];
175
+ // D-0251: several processes run as <unit>@<process> (a template unit), or compose services
176
+ // app-<process>.
177
+ const each = input.processes && input.processes.length > 1 ? input.processes : undefined;
178
+ const unitFile = each ? `${first.unit}@.service` : `${first.unit}.service`;
179
+ const units = each ? each.map((name) => `${first.unit}@${name}`).join(' ') : first.unit;
180
+ const allUnits = each ? `'${first.unit}@*'` : first.unit;
181
+ const service = each ? '' : ' app';
160
182
  const rows = input.instances
161
183
  .map((at) => `| ${at.instance} | \`${at.unit}\` | ${at.port ? `127.0.0.1:${at.port}` : '— (no web server)'} | \`${at.settings}\` | \`${at.secrets}\` | \`${at.code}/current\` | \`${at.data}\` | \`${at.logs}\` | \`${at.backups}\` | \`${at.database}\` |`)
162
184
  .join('\n');
@@ -199,7 +221,7 @@ ${systemd ? '' : `sudo install -d -o ${first.unit} -g ${first.unit} -m 0700 ${fi
199
221
  Fill the settings file: the placeholders left in it (\`<…>\`), \`dokebi-app.domains\` with the
200
222
  public names, and \`dokebi-web.trustProxy\` with the addresses of the reverse proxy (127.0.0.1
201
223
  and ::1 when it runs on the same server). ${db ? `Create the database \`${first.database}\` and its own user for this instance; its URL goes in the secrets file.` : ''}
202
- ${systemd ? `\nInstall the units: \`sudo cp deploy/systemd/${first.unit}.service deploy/systemd/${first.unit}-backup.service deploy/systemd/${first.unit}-backup.timer /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl enable ${first.unit} ${first.unit}-backup.timer\`.` : `\nThe compose file runs the container as \`DOKEBI_UID\`:\`DOKEBI_GID\`: set them to the uid and gid of \`${first.unit}\`, the owner of the secrets file.`}
224
+ ${systemd ? `\nInstall the units: \`sudo cp deploy/systemd/${unitFile} deploy/systemd/${first.unit}-backup.service deploy/systemd/${first.unit}-backup.timer /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl enable ${units} ${first.unit}-backup.timer\`.${each ? ` The settings run ${each.join(', ')} (\`run\`, D-0251): one unit per process, each with \`DOKEBI_PROCESS\` set.` : ''}` : `\nThe compose file runs the container as \`DOKEBI_UID\`:\`DOKEBI_GID\`: set them to the uid and gid of \`${first.unit}\`, the owner of the secrets file.`}
203
225
 
204
226
  Before the first start, check the instance with the settings it will read:
205
227
 
@@ -224,10 +246,10 @@ Run as the instance's user, in this order; stop at the first step that fails.
224
246
  working with them. With \`options.dokebi-migrate.onPending: fail\` the new release refuses to
225
247
  start while a pre-deploy file is pending.`
226
248
  : ''}
227
- ${migrate ? '3' : '2'}. **Switch:** \`ln -sfn releases/<id> ${first.code}/current\` and ${systemd ? `\`sudo systemctl restart ${first.unit}\`` : `\`docker compose -f deploy/compose/${first.instance}.yaml up -d --build\``}.
249
+ ${migrate ? '3' : '2'}. **Switch:** \`ln -sfn releases/<id> ${first.code}/current\` and ${systemd ? `\`sudo systemctl restart ${allUnits}\`` : `\`docker compose -f deploy/compose/${first.instance}.yaml up -d --build\``}.
228
250
  The old process drains on SIGTERM.
229
251
  ${migrate ? '4' : '3'}. **Check:** \`npx -y @dokebi/cli verify --remote https://<domain> --json\` (TLS, health, security
230
- headers; exit 1 on a failure) and \`${systemd ? `journalctl -u ${first.unit} -n 100` : `docker compose -f deploy/compose/${first.instance}.yaml logs --tail 100 app`}\`.${migrate
252
+ headers; exit 1 on a failure) and \`${systemd ? `journalctl -u ${allUnits} -n 100` : `docker compose -f deploy/compose/${first.instance}.yaml logs --tail 100${service}`}\`.${migrate
231
253
  ? `
232
254
  5. **Migrate after the switch:** \`${env(first)} npx dokebi-migrate up --json\` applies the
233
255
  post-deploy files (backfills, constraints, dropping what the old release used).`
@@ -236,7 +258,7 @@ ${migrate ? '6' : '4'}. Keep the last 5 release folders; remove older ones.
236
258
 
237
259
  ## 3. Rollback
238
260
 
239
- Point \`current\` back to the previous release and restart ${systemd ? `(\`sudo systemctl restart ${first.unit}\`)` : '(`docker compose ... up -d --build`)'}.${migrate
261
+ Point \`current\` back to the previous release and restart ${systemd ? `(\`sudo systemctl restart ${allUnits}\`)` : '(`docker compose ... up -d --build`)'}.${migrate
240
262
  ? ` The
241
263
  pre-deploy migrations of the new release stay: they only added, so the previous release works
242
264
  with them. Run \`npx dokebi-migrate down --to <name>\` only when a migration itself must go, after
@@ -278,7 +300,7 @@ the settings (the secrets stay in your secret store).
278
300
 
279
301
  ## 5. Logs
280
302
 
281
- Records go to stdout as JSON lines: ${systemd ? `\`journalctl -u ${first.unit}\`` : `\`docker compose -f deploy/compose/${first.instance}.yaml logs app\``}.
303
+ Records go to stdout as JSON lines: ${systemd ? `\`journalctl -u ${allUnits}\`` : `\`docker compose -f deploy/compose/${first.instance}.yaml logs${service}\``}.
282
304
  A file target of @dokebi/logger writes under \`${first.logs}\`.
283
305
  `;
284
306
  }
package/dist/deploy.js CHANGED
@@ -389,20 +389,23 @@ export async function deployInit(input, options) {
389
389
  ];
390
390
  const all = [...new Set([...known.keys(), ...names])].sort((a, b) => a === 'production' ? -1 : b === 'production' ? 1 : a.localeCompare(b));
391
391
  const layouts = all.map((name) => layout(app, name, ports.get(name) ?? (web ? known.get(name) : 0) ?? 0));
392
+ // D-0251: settings that run several processes get a unit (or compose service) per process.
393
+ const run = parseConfig(sample, undefined, { process: null }).run;
394
+ const processes = run && run.length > 1 ? run : undefined;
392
395
  const files = [];
393
396
  const add = (path, body) => files.push({ path, content: withMarker(path, body) });
394
397
  for (const at of layouts.filter((item) => names.includes(item.instance))) {
395
398
  add(`deploy/${at.instance}/${EXAMPLE}`, instanceSample(sample, at, options.target, plugins, secrets, schemas));
396
399
  add(`deploy/${at.instance}/secrets.example.yaml`, secretsSample(at, secrets, sources, schemas));
397
400
  if (options.target === 'systemd') {
398
- add(`deploy/systemd/${at.unit}.service`, systemdUnit(at));
401
+ add(processes ? `deploy/systemd/${at.unit}@.service` : `deploy/systemd/${at.unit}.service`, systemdUnit(at, processes));
399
402
  if (plugins.includes('dokebi-db')) {
400
403
  add(`deploy/systemd/${at.unit}-backup.service`, backupService(at));
401
404
  add(`deploy/systemd/${at.unit}-backup.timer`, backupTimer(at));
402
405
  }
403
406
  }
404
407
  else
405
- add(`deploy/compose/${at.instance}.yaml`, composeFile(at));
408
+ add(`deploy/compose/${at.instance}.yaml`, composeFile(at, processes));
406
409
  }
407
410
  if (plugins.includes('dokebi-db')) {
408
411
  add('deploy/backup.mjs', BACKUP_SCRIPT);
@@ -412,7 +415,14 @@ export async function deployInit(input, options) {
412
415
  for (const name of ['Dockerfile', '.dockerignore'])
413
416
  if (!(await exists(join(root, name))))
414
417
  files.push({ path: name, content: DEPLOYMENT_FILES[name] });
415
- add('DEPLOY.md', deployGuide({ app, target: options.target, instances: layouts, plugins, secrets }));
418
+ add('DEPLOY.md', deployGuide({
419
+ app,
420
+ target: options.target,
421
+ instances: layouts,
422
+ plugins,
423
+ secrets,
424
+ ...(processes ? { processes } : {}),
425
+ }));
416
426
  const written = await writeFiles(root, files, options.dryRun === true);
417
427
  written.warnings.push(...unreadableWarning(unreadable));
418
428
  debug('Deployment files planned', {
@@ -4,7 +4,10 @@
4
4
  // losing lines. It ignores SIGTERM/SIGINT/SIGHUP (dokebi stop signals the app, not the writer)
5
5
  // and exits once the app has exited and its pipes are drained.
6
6
  //
7
- // Usage: log-writer <log file> <max bytes> <rotated files to keep> <entry>
7
+ // Usage: log-writer <log file> <max bytes> <rotated files to keep> <entry> [process...]
8
+ // D-0251: with processes (the `run` of the settings file) it starts `entry` with DOKEBI_PROCESS set
9
+ // for one, and process-set.js for several (it starts each and tags their lines); readiness then
10
+ // comes from the IPC message alone, since every process writes its own start line.
8
11
  // The CLI listens on the IPC channel until the start is decided: { spawned: pid }, { ready: true }
9
12
  // when the start line passes, { exited: code, signal } and { failed: text }. The writer's own
10
13
  // errors go to its stderr, which the CLI points at `.dokebi/run/log-writer.log`.
@@ -15,9 +18,11 @@
15
18
  // parent, to stop it. Both sides prove the app's DOKEBI_INSTANCE_TOKEN first.
16
19
  import { spawn } from 'node:child_process';
17
20
  import { setTimeout as delay } from 'node:timers/promises';
21
+ import { fileURLToPath } from 'node:url';
18
22
  import { debug, describeError, reportError } from './diagnostics.js';
19
23
  import { ControlServer } from './log-writer-control.js';
20
24
  import { endLeftovers, PROCESS_GROUPS } from './process-group.js';
25
+ import { PROCESS_VARIABLE } from './process-tags.js';
21
26
  import { forwardOutput, LineBuffer, RotatingLog } from './rotating-log.js';
22
27
  /** Written by the generated `src/main.ts` once `app.start()` resolved. */
23
28
  const STARTED = 'Dokebi application started';
@@ -42,7 +47,7 @@ function send(message, then) {
42
47
  then?.();
43
48
  });
44
49
  }
45
- const [file, maxArg, keepArg, entry] = process.argv.slice(2);
50
+ const [file, maxArg, keepArg, entry, ...processes] = process.argv.slice(2);
46
51
  const maxBytes = Number(maxArg);
47
52
  const keep = Number(keepArg);
48
53
  if (!file ||
@@ -51,7 +56,7 @@ if (!file ||
51
56
  maxBytes < 1 ||
52
57
  !Number.isSafeInteger(keep) ||
53
58
  keep < 1) {
54
- const text = `usage: log-writer <log file> <max bytes> <files> <entry> (got ${JSON.stringify(process.argv.slice(2))})`;
59
+ const text = `usage: log-writer <log file> <max bytes> <files> <entry> [process...] (got ${JSON.stringify(process.argv.slice(2))})`;
55
60
  reportError('LOG_WRITER_USAGE', 'Invalid log writer arguments', new Error(text));
56
61
  send({ failed: text }, () => process.exit(2));
57
62
  }
@@ -91,9 +96,16 @@ function run(file, maxBytes, keep, entry, control) {
91
96
  // logging.level above info hides the start line, and the app is still up.
92
97
  // The app leads a process group of its own (POSIX): what it starts and leaves behind when it
93
98
  // exits (stopped, crashed or killed) is found there and ended, never left holding a port.
94
- const app = spawn(process.execPath, [entry], {
99
+ const several = processes.length > 1;
100
+ const app = spawn(process.execPath, several
101
+ ? [fileURLToPath(new URL('./process-set.js', import.meta.url)), entry, ...processes]
102
+ : [entry], {
95
103
  stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
96
- env: { ...process.env, DOKEBI_LOG_WRITER: '1' },
104
+ env: {
105
+ ...process.env,
106
+ DOKEBI_LOG_WRITER: '1',
107
+ ...(processes.length === 1 ? { [PROCESS_VARIABLE]: processes[0] } : {}),
108
+ },
97
109
  detached: PROCESS_GROUPS,
98
110
  });
99
111
  let announced = false;
@@ -109,7 +121,9 @@ function run(file, maxBytes, keep, entry, control) {
109
121
  ready('ipc message');
110
122
  });
111
123
  // `ready` goes to the CLI after the start line is in app.log (forwardOutput), or on the message.
112
- const write = forwardOutput(log, STARTED, () => ready('start line'));
124
+ const write = several
125
+ ? (data) => log.write(data)
126
+ : forwardOutput(log, STARTED, () => ready('start line'));
113
127
  let exit;
114
128
  let leftovers = Promise.resolve('none');
115
129
  let open = 2;
package/dist/output.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export declare const CLI_VERSION = "0.4.90";
1
+ export declare const CLI_VERSION = "0.4.91";
2
2
  export declare function envelope(command: string, result: unknown, ok?: boolean): object;
3
3
  export declare function failure(command: string, error: unknown, mutationStarted: boolean): object;
package/dist/output.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CliError } from './errors.js';
2
- export const CLI_VERSION = '0.4.90';
2
+ export const CLI_VERSION = '0.4.91';
3
3
  export function envelope(command, result, ok = true) {
4
4
  return { schemaVersion: 1, cliVersion: CLI_VERSION, command, ok, result, error: null };
5
5
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,161 @@
1
+ // The processes of one folder under `dokebi start` (D-0251). The log writer starts this instead
2
+ // of the app when `run` of the settings file names more than one process; it starts
3
+ // `node <entry>` once per process with DOKEBI_PROCESS set, and stands for them toward the writer:
4
+ //
5
+ // - their output goes on to the writer with each line tagged (a JSON record gets `"process"`,
6
+ // any other line a `[name] ` prefix), so app.log tells them apart;
7
+ // - `{ dokebi: 'started' }` goes to the writer once every process said it (its IPC message, or
8
+ // its start line);
9
+ // - SIGTERM, SIGINT and SIGHUP (a reload) go on to every process;
10
+ // - one process that ends while the others run is written to the log and the others are stopped:
11
+ // the set runs whole or not at all, as one app did. The exit code is the first failure's.
12
+ //
13
+ // Usage: process-set <entry> <process> <process>...
14
+ // The processes share this one's process group (the writer spawned it detached), so what any of
15
+ // them leaves behind is ended with it.
16
+ import { spawn } from 'node:child_process';
17
+ import { debug, reportError } from './diagnostics.js';
18
+ import { PROCESS_VARIABLE, tagLines } from './process-tags.js';
19
+ import { LineBuffer } from './rotating-log.js';
20
+ /** Written by the generated `src/main.ts` once the app started. */
21
+ const STARTED = 'Dokebi application started';
22
+ /** An unfinished line is written after this much quiet. */
23
+ const PARTIAL_MS = 200;
24
+ /** The reload status file (D-0154): each process gets its own beside it. */
25
+ const RELOAD_STATUS_ENV = 'DOKEBI_RELOAD_STATUS';
26
+ const [entry, ...names] = process.argv.slice(2);
27
+ if (!entry || names.length < 2) {
28
+ reportError('INVALID_ARGUMENTS', 'usage: process-set <entry> <process> <process>...', new Error(`got ${JSON.stringify(process.argv.slice(2))}`));
29
+ process.exit(2);
30
+ }
31
+ /** One line of this supervisor in the app log, in the records' shape. */
32
+ function record(level, message, fields) {
33
+ const line = `${JSON.stringify({ time: new Date().toISOString(), level, message, ...fields })}\n`;
34
+ // dokebi-check: allow console-output the supervisor's records go to the log writer like the processes' own
35
+ (level === 'error' ? process.stderr : process.stdout).write(line);
36
+ }
37
+ let stopping = false;
38
+ let failure;
39
+ const children = new Map();
40
+ const ready = new Set();
41
+ let announced = false;
42
+ function started(name, how) {
43
+ if (ready.has(name))
44
+ return;
45
+ ready.add(name);
46
+ debug('Process started', { process: name, how });
47
+ if (announced || ready.size < names.length)
48
+ return;
49
+ announced = true;
50
+ record('info', `Processes started: ${names.join(', ')}`, {
51
+ code: 'PROCESSES_STARTED',
52
+ processes: names,
53
+ });
54
+ if (process.connected)
55
+ process.send?.({ dokebi: 'started' });
56
+ }
57
+ /** Copies a process's output to ours, tagged, holding it while ours is full (back pressure). */
58
+ function follow(name, from, to) {
59
+ if (!from)
60
+ return;
61
+ const lines = new LineBuffer();
62
+ let timer;
63
+ const write = (data) => {
64
+ if (data.length === 0)
65
+ return;
66
+ if (data.includes(STARTED))
67
+ started(name, 'start line');
68
+ // dokebi-check: allow console-output the processes' output goes on to the log writer as it was, tagged
69
+ if (!to.write(tagLines(name, data))) {
70
+ from.pause();
71
+ to.once('drain', () => from.resume());
72
+ }
73
+ };
74
+ from.on('data', (chunk) => {
75
+ const whole = lines.push(chunk);
76
+ if (whole)
77
+ write(whole);
78
+ clearTimeout(timer);
79
+ if (lines.pending)
80
+ timer = setTimeout(() => write(lines.take()), PARTIAL_MS);
81
+ });
82
+ from.once('error', (error) => reportError('PROCESS_OUTPUT_FAILED', `Unable to read the output of process ${name}`, error));
83
+ from.once('close', () => {
84
+ clearTimeout(timer);
85
+ if (lines.pending)
86
+ write(lines.take());
87
+ });
88
+ }
89
+ function signalAll(signal) {
90
+ for (const [name, child] of children) {
91
+ if (child.exitCode !== null || child.signalCode !== null)
92
+ continue;
93
+ try {
94
+ child.kill(signal);
95
+ }
96
+ catch (error) {
97
+ reportError('PROCESS_SIGNAL_FAILED', `Unable to signal process ${name}`, error);
98
+ }
99
+ }
100
+ }
101
+ function stopAll(reason) {
102
+ if (stopping)
103
+ return;
104
+ stopping = true;
105
+ debug('Stopping every process', { reason });
106
+ signalAll('SIGTERM');
107
+ }
108
+ function exited(name, code, signal) {
109
+ if (!stopping) {
110
+ // Ending on its own while the others run is a failure of the set, also with code 0.
111
+ record('error', 'A process ended; stopping the others', {
112
+ code: 'PROCESS_EXITED',
113
+ process: name,
114
+ exitCode: code,
115
+ signal,
116
+ });
117
+ failure ??= { code: code || 1 };
118
+ stopAll(`process ${name} ended`);
119
+ }
120
+ else if (code !== null && code !== 0)
121
+ failure ??= { code };
122
+ else if (signal !== null && signal !== 'SIGTERM' && signal !== 'SIGINT')
123
+ failure ??= { code: 1 };
124
+ children.delete(name);
125
+ if (children.size === 0)
126
+ process.exit(failure?.code ?? 0);
127
+ }
128
+ for (const name of names) {
129
+ const status = process.env[RELOAD_STATUS_ENV];
130
+ const child = spawn(process.execPath, [entry], {
131
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
132
+ env: {
133
+ ...process.env,
134
+ [PROCESS_VARIABLE]: name,
135
+ ...(status ? { [RELOAD_STATUS_ENV]: `${status}.${name}` } : {}),
136
+ },
137
+ });
138
+ children.set(name, child);
139
+ child.on('message', (message) => {
140
+ if (message?.dokebi === 'started')
141
+ started(name, 'ipc message');
142
+ });
143
+ child.once('error', (error) => {
144
+ reportError('PROCESS_SPAWN_FAILED', `Unable to start process ${name}`, error);
145
+ exited(name, 1, null);
146
+ });
147
+ child.once('exit', (code, signal) => exited(name, code, signal));
148
+ follow(name, child.stdout, process.stdout);
149
+ follow(name, child.stderr, process.stderr);
150
+ debug('Process spawned', { process: name, pid: child.pid });
151
+ }
152
+ process.on('SIGTERM', () => stopAll('SIGTERM'));
153
+ process.on('SIGINT', () => stopAll('SIGINT'));
154
+ // A reload: every process reads its settings again.
155
+ process.on('SIGHUP', () => signalAll('SIGHUP'));
156
+ process.on('disconnect', () => debug('The log writer closed the IPC channel', {}));
157
+ // The writer went away (its pipe closed): nothing can be logged any more; stop the set.
158
+ process.stdout.on('error', (error) => {
159
+ reportError('PROCESS_SET_OUTPUT_FAILED', 'The log writer pipe closed', error);
160
+ stopAll('output closed');
161
+ });
@@ -0,0 +1,10 @@
1
+ /** The variable naming the process (as @dokebi/config's PROCESS_VARIABLE). */
2
+ export declare const PROCESS_VARIABLE = "DOKEBI_PROCESS";
3
+ /**
4
+ * A line of process `name`'s output with its name: a JSON record gets a leading `"process"` field
5
+ * (no parse: the record's own fields follow, so a record that names a process keeps its own),
6
+ * anything else a `[name] ` prefix.
7
+ */
8
+ export declare function tagLine(name: string, line: string): string;
9
+ /** Whole lines of process `name` (a LineBuffer's output), each tagged (tagLine). */
10
+ export declare function tagLines(name: string, data: Buffer): Buffer;