@git.zone/cli 7.2.7 → 7.3.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.
@@ -0,0 +1,655 @@
1
+ import * as plugins from "./mod.plugins.js";
2
+ import * as paths from "../paths.js";
3
+ import { InterProcessLock } from "../mod_services/classes.interprocesslock.js";
4
+ import {
5
+ ReleaseJournalStore,
6
+ resolveGitCommonDirectory,
7
+ } from "./classes.releasejournal.js";
8
+
9
+ /**
10
+ * A detached release runs as two processes in a session of their own: a
11
+ * supervisor, which holds the project's detached-release lock, and the release
12
+ * itself (the worker), the supervisor's child. The supervisor records the run
13
+ * beside the release journals, writes the worker's output to the run's log, and
14
+ * records how the worker ended, also when it was killed.
15
+ *
16
+ * <release storage>/detached.lock held by the supervisor for the run
17
+ * <release storage>/detached/<id>.json the run record
18
+ * <release storage>/detached/<id>.log stdout and stderr of the release
19
+ */
20
+
21
+ export const detachedReleaseRunKind = "gitzone-release-detached-run" as const;
22
+
23
+ /** Names the supervisor role and carries its launch data; never inherited by the worker. */
24
+ const supervisorEnvironmentKey = "GITZONE_RELEASE_DETACHED_SUPERVISOR";
25
+ const runIdPattern = /^[0-9a-f]{32}$/;
26
+ const supervisorStartTimeoutMs = 60_000;
27
+ /** How long a supervisor the launcher terminates has before it is killed. */
28
+ const supervisorStopTimeoutMs = 10_000;
29
+ const forwardedSignals = ["SIGHUP", "SIGINT", "SIGTERM"] as const;
30
+
31
+ export type TDetachedReleaseRunState = "running" | "succeeded" | "failed";
32
+
33
+ export interface IDetachedReleaseRun {
34
+ kind: typeof detachedReleaseRunKind;
35
+ id: string;
36
+ /** The gitzone arguments the worker runs. */
37
+ command: string[];
38
+ /** The version the launch resolved or resumes. */
39
+ version: string;
40
+ cwd: string;
41
+ /** Leader of the run's process group. */
42
+ supervisorPid: number;
43
+ workerPid: number;
44
+ logPath: string;
45
+ startedAt: string;
46
+ state: TDetachedReleaseRunState;
47
+ exitCode: number | null;
48
+ signal: string | null;
49
+ finishedAt: string | null;
50
+ }
51
+
52
+ interface ISupervisorHandoff {
53
+ version: string;
54
+ }
55
+
56
+ type TSupervisorMessage =
57
+ | { kind: "started"; run: IDetachedReleaseRun }
58
+ | { kind: "refused"; error: string };
59
+
60
+ const isPlainObject = (
61
+ valueArg: unknown,
62
+ ): valueArg is Record<string, unknown> =>
63
+ typeof valueArg === "object" && valueArg !== null && !Array.isArray(valueArg);
64
+
65
+ const isTimestamp = (valueArg: unknown): valueArg is string =>
66
+ typeof valueArg === "string" &&
67
+ !Number.isNaN(Date.parse(valueArg)) &&
68
+ new Date(valueArg).toISOString() === valueArg;
69
+
70
+ const isPid = (valueArg: unknown): valueArg is number =>
71
+ Number.isSafeInteger(valueArg) && (valueArg as number) > 0;
72
+
73
+ const isExitCode = (valueArg: unknown): valueArg is number =>
74
+ Number.isSafeInteger(valueArg) &&
75
+ (valueArg as number) >= 0 &&
76
+ (valueArg as number) <= 255;
77
+
78
+ const isSignalName = (valueArg: unknown): valueArg is NodeJS.Signals =>
79
+ typeof valueArg === "string" &&
80
+ Object.hasOwn(plugins.os.constants.signals, valueArg);
81
+
82
+ const runKeys = [
83
+ "kind",
84
+ "id",
85
+ "command",
86
+ "version",
87
+ "cwd",
88
+ "supervisorPid",
89
+ "workerPid",
90
+ "logPath",
91
+ "startedAt",
92
+ "state",
93
+ "exitCode",
94
+ "signal",
95
+ "finishedAt",
96
+ ];
97
+
98
+ export const assertDetachedReleaseRun = (
99
+ valueArg: unknown,
100
+ ): IDetachedReleaseRun => {
101
+ if (
102
+ !isPlainObject(valueArg) ||
103
+ Object.keys(valueArg).length !== runKeys.length ||
104
+ runKeys.some((keyArg) => !Object.hasOwn(valueArg, keyArg))
105
+ ) {
106
+ throw new Error("Detached release run record has an invalid shape.");
107
+ }
108
+ const run = valueArg;
109
+ const finished = run.state === "succeeded" || run.state === "failed";
110
+ if (
111
+ run.kind !== detachedReleaseRunKind ||
112
+ typeof run.id !== "string" ||
113
+ !runIdPattern.test(run.id) ||
114
+ !Array.isArray(run.command) ||
115
+ run.command.some((argArg) => typeof argArg !== "string") ||
116
+ typeof run.version !== "string" ||
117
+ typeof run.cwd !== "string" ||
118
+ !plugins.path.isAbsolute(run.cwd) ||
119
+ !isPid(run.supervisorPid) ||
120
+ !isPid(run.workerPid) ||
121
+ typeof run.logPath !== "string" ||
122
+ !plugins.path.isAbsolute(run.logPath) ||
123
+ !isTimestamp(run.startedAt) ||
124
+ !(run.state === "running" || finished) ||
125
+ !(run.exitCode === null || isExitCode(run.exitCode)) ||
126
+ !(run.signal === null || isSignalName(run.signal)) ||
127
+ !(run.finishedAt === null || isTimestamp(run.finishedAt))
128
+ ) {
129
+ throw new Error("Detached release run record is invalid.");
130
+ }
131
+ if (
132
+ finished !== (run.finishedAt !== null) ||
133
+ (finished && (run.exitCode === null) === (run.signal === null)) ||
134
+ (run.state === "succeeded" && run.exitCode !== 0) ||
135
+ (run.state === "failed" && run.exitCode === 0) ||
136
+ (run.state === "running" && (run.exitCode !== null || run.signal !== null))
137
+ ) {
138
+ throw new Error(
139
+ "Detached release run record states an impossible outcome.",
140
+ );
141
+ }
142
+ return run as unknown as IDetachedReleaseRun;
143
+ };
144
+
145
+ /** Detached runs of one project, stored beside its release journals. */
146
+ export class DetachedReleaseRuns {
147
+ public readonly storageRoot: string;
148
+ public readonly directory: string;
149
+ public readonly lock: InterProcessLock;
150
+
151
+ constructor(releaseStorageRootArg: string) {
152
+ if (!plugins.path.isAbsolute(releaseStorageRootArg)) {
153
+ throw new Error("Detached release storage requires an absolute path.");
154
+ }
155
+ this.storageRoot = plugins.path.resolve(releaseStorageRootArg);
156
+ this.directory = plugins.path.join(this.storageRoot, "detached");
157
+ this.lock = new InterProcessLock({
158
+ lockPath: plugins.path.join(this.storageRoot, "detached.lock"),
159
+ description: "Detached release of this project",
160
+ // A launch never waits for a running release; it is refused at once.
161
+ timeoutMs: 1,
162
+ });
163
+ }
164
+
165
+ public getRecordPath(idArg: string): string {
166
+ return plugins.path.join(this.directory, `${this.assertId(idArg)}.json`);
167
+ }
168
+
169
+ public getLogPath(idArg: string): string {
170
+ return plugins.path.join(this.directory, `${this.assertId(idArg)}.log`);
171
+ }
172
+
173
+ public async read(idArg: string): Promise<IDetachedReleaseRun> {
174
+ const content = await plugins.fs.readFile(
175
+ this.getRecordPath(idArg),
176
+ "utf8",
177
+ );
178
+ const run = assertDetachedReleaseRun(JSON.parse(content));
179
+ if (run.id !== idArg) {
180
+ throw new Error("Detached release run record path and id do not match.");
181
+ }
182
+ return run;
183
+ }
184
+
185
+ /** Every recorded run, the latest first. */
186
+ public async list(): Promise<IDetachedReleaseRun[]> {
187
+ let entries: string[];
188
+ try {
189
+ entries = await plugins.fs.readdir(this.directory);
190
+ } catch (error) {
191
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
192
+ throw new Error("Detached release runs could not be listed.", {
193
+ cause: error,
194
+ });
195
+ }
196
+ const runs: IDetachedReleaseRun[] = [];
197
+ for (const entry of entries) {
198
+ const match = /^([0-9a-f]{32})\.json$/.exec(entry);
199
+ if (match) runs.push(await this.read(match[1]));
200
+ }
201
+ return runs.sort((leftArg, rightArg) =>
202
+ rightArg.startedAt.localeCompare(leftArg.startedAt),
203
+ );
204
+ }
205
+
206
+ public async write(runArg: IDetachedReleaseRun): Promise<void> {
207
+ const run = assertDetachedReleaseRun(runArg);
208
+ const recordPath = this.getRecordPath(run.id);
209
+ const temporaryPath = `${recordPath}.tmp-${process.pid}-${plugins.crypto.randomBytes(12).toString("hex")}`;
210
+ try {
211
+ await plugins.fs.writeFile(
212
+ temporaryPath,
213
+ `${JSON.stringify(run, null, 2)}\n`,
214
+ { encoding: "utf8", flag: "wx", mode: 0o600 },
215
+ );
216
+ await plugins.fs.rename(temporaryPath, recordPath);
217
+ } catch (error) {
218
+ await plugins.fs.rm(temporaryPath, { force: true });
219
+ throw new Error(`Detached release run ${run.id} could not be recorded.`, {
220
+ cause: error,
221
+ });
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Refuses to start a release while a detached release of this project runs.
227
+ * The run's own worker, a child of the supervisor that holds the lock, passes.
228
+ */
229
+ public async assertNoForeignRun(): Promise<void> {
230
+ const holder = await this.lock.readHolder();
231
+ if (!holder || (holder.pid !== null && holder.pid === process.ppid)) return;
232
+ throw new Error(
233
+ `A detached release of this project is running (supervisor pid ${holder.pid ?? "unknown"}, started ${holder.createdAt ?? "unknown"}). ` +
234
+ `\`gitzone release inspect\` shows its state. If that process no longer exists, inspect and remove ${this.lock.lockPath}.`,
235
+ );
236
+ }
237
+
238
+ private assertId(idArg: string): string {
239
+ if (!runIdPattern.test(idArg)) {
240
+ throw new Error("Invalid detached release run id.");
241
+ }
242
+ return idArg;
243
+ }
244
+ }
245
+
246
+ /** The detached runs of the repository that contains `cwdArg`. */
247
+ export const openDetachedReleaseRuns = async (
248
+ cwdArg: string,
249
+ ): Promise<DetachedReleaseRuns> => {
250
+ const smartshell = new plugins.smartshell.Smartshell({
251
+ executor: "bash",
252
+ sourceFilePaths: [],
253
+ });
254
+ return new DetachedReleaseRuns(
255
+ new ReleaseJournalStore(await resolveGitCommonDirectory(smartshell, cwdArg))
256
+ .rootPath,
257
+ );
258
+ };
259
+
260
+ /**
261
+ * The worker's arguments: the launcher's own, without `--detach`. Everything
262
+ * after `--` is an operand and stays.
263
+ */
264
+ export const getDetachedWorkerArguments = (rawArgvArg: string[]): string[] => {
265
+ const separator = rawArgvArg.indexOf("--");
266
+ const options =
267
+ separator === -1 ? rawArgvArg : rawArgvArg.slice(0, separator);
268
+ const operands = separator === -1 ? [] : rawArgvArg.slice(separator);
269
+ const workerOptions = options.filter((argArg) => argArg !== "--detach");
270
+ if (workerOptions.length === options.length) {
271
+ throw new Error(
272
+ "--detach must be given as the bare flag on the command line.",
273
+ );
274
+ }
275
+ return [...workerOptions, ...operands];
276
+ };
277
+
278
+ export interface ILaunchDetachedReleaseOptions {
279
+ /** The detached runs of the project the release belongs to. */
280
+ runs: DetachedReleaseRuns;
281
+ /** The directory the release runs in. */
282
+ cwd: string;
283
+ workerArguments: string[];
284
+ version: string;
285
+ /** How long the supervisor has to report whether it started the release. */
286
+ startTimeoutMs?: number;
287
+ }
288
+
289
+ const describeExit = (
290
+ codeArg: number | null,
291
+ signalArg: NodeJS.Signals | null,
292
+ ): string =>
293
+ codeArg !== null ? `exit code ${codeArg}` : `signal ${signalArg}`;
294
+
295
+ /** The supervisor's report, validated; anything else throws. */
296
+ const readSupervisorMessage = (valueArg: unknown): TSupervisorMessage => {
297
+ if (isPlainObject(valueArg)) {
298
+ if (valueArg.kind === "refused" && typeof valueArg.error === "string") {
299
+ return { kind: "refused", error: valueArg.error };
300
+ }
301
+ if (valueArg.kind === "started") {
302
+ return { kind: "started", run: assertDetachedReleaseRun(valueArg.run) };
303
+ }
304
+ }
305
+ throw new Error("The detached release supervisor sent an invalid report.");
306
+ };
307
+
308
+ const signalProcessGroup = (
309
+ groupArg: number,
310
+ signalArg: NodeJS.Signals,
311
+ ): void => {
312
+ try {
313
+ process.kill(-groupArg, signalArg);
314
+ } catch (error) {
315
+ // A group that is gone already has nothing left to stop.
316
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
317
+ }
318
+ };
319
+
320
+ /**
321
+ * Starts the supervisor in a new session and returns once it reports the
322
+ * release running, or throws when it refused to start one. A supervisor that
323
+ * does not report in time is terminated with its whole process group before
324
+ * this throws, and the error says whether a release had started.
325
+ */
326
+ export const launchDetachedRelease = async (
327
+ optionsArg: ILaunchDetachedReleaseOptions,
328
+ ): Promise<IDetachedReleaseRun> => {
329
+ const startTimeoutMs = optionsArg.startTimeoutMs ?? supervisorStartTimeoutMs;
330
+ if (!Number.isSafeInteger(startTimeoutMs) || startTimeoutMs <= 0) {
331
+ throw new Error("The supervisor start timeout must be a positive integer.");
332
+ }
333
+ const handoff: ISupervisorHandoff = { version: optionsArg.version };
334
+ // The supervisor runs the same gitzone build as a plain `node <entry>`, the
335
+ // way the `gitzone` binary does; the launcher's own Node flags (an inspector
336
+ // port, for instance) are not carried over.
337
+ const supervisor = plugins.childProcess.spawn(
338
+ process.execPath,
339
+ [paths.cliEntryPath, ...optionsArg.workerArguments],
340
+ {
341
+ cwd: optionsArg.cwd,
342
+ detached: true,
343
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
344
+ env: {
345
+ ...process.env,
346
+ [supervisorEnvironmentKey]: JSON.stringify(handoff),
347
+ },
348
+ },
349
+ );
350
+ let startTimer: ReturnType<typeof setTimeout> | undefined;
351
+ let stopTimer: ReturnType<typeof setTimeout> | undefined;
352
+ try {
353
+ return await new Promise<IDetachedReleaseRun>((resolve, reject) => {
354
+ let terminated = false;
355
+ let killed = false;
356
+ let lateReport: TSupervisorMessage | undefined;
357
+ let lateReportError: unknown;
358
+
359
+ /** The supervisor did not report in time: stop everything it runs. */
360
+ const terminate = () => {
361
+ const group = supervisor.pid;
362
+ // A supervisor without a pid never started; its `error` rejects.
363
+ if (group === undefined) return;
364
+ terminated = true;
365
+ try {
366
+ // The supervisor leads its own process group; the release and
367
+ // everything the release started belong to it as well.
368
+ signalProcessGroup(group, "SIGTERM");
369
+ stopTimer = setTimeout(() => {
370
+ killed = true;
371
+ try {
372
+ signalProcessGroup(group, "SIGKILL");
373
+ } catch (error) {
374
+ reject(
375
+ new Error(
376
+ `The detached release supervisor (pid ${supervisor.pid}) could not be killed.`,
377
+ { cause: error },
378
+ ),
379
+ );
380
+ }
381
+ }, supervisorStopTimeoutMs);
382
+ } catch (error) {
383
+ reject(
384
+ new Error(
385
+ `The detached release supervisor (pid ${supervisor.pid}) did not report within ${startTimeoutMs / 1000} s and could not be terminated.`,
386
+ { cause: error },
387
+ ),
388
+ );
389
+ }
390
+ };
391
+
392
+ /** What the terminated supervisor had done, once it is gone. */
393
+ const describeTermination = (): string => {
394
+ const stopped = killed
395
+ ? `killed with SIGKILL after it did not stop within ${supervisorStopTimeoutMs / 1000} s of SIGTERM`
396
+ : "terminated";
397
+ const summary = `The detached release supervisor (pid ${supervisor.pid}) did not report within ${startTimeoutMs / 1000} s whether it started the release, so its process group was ${stopped}.`;
398
+ if (lateReport?.kind === "started") {
399
+ return (
400
+ `${summary} It reported run ${lateReport.run.id} started as it was stopped, so that release was stopped as well. ` +
401
+ `\`gitzone release inspect\` shows the recorded outcome of the run and what the release of v${lateReport.run.version} published.`
402
+ );
403
+ }
404
+ if (lateReport?.kind === "refused") {
405
+ return `${summary} It had not started the release: ${lateReport.error}`;
406
+ }
407
+ if (lateReportError) {
408
+ return `${summary} Its report could not be read, so whether it had started the release is unknown: \`gitzone release inspect\` lists a run if it did.`;
409
+ }
410
+ if (killed) {
411
+ return (
412
+ `${summary} Whether it had started the release is unknown: \`gitzone release inspect\` lists a run if it did. ` +
413
+ `If ${optionsArg.runs.lock.lockPath} still exists, the killed supervisor left it; remove it after checking that no process of the run is left.`
414
+ );
415
+ }
416
+ return `${summary} It had not started the release.`;
417
+ };
418
+
419
+ startTimer = setTimeout(terminate, startTimeoutMs);
420
+ supervisor.once("error", (error) =>
421
+ reject(
422
+ new Error("The detached release supervisor could not be started.", {
423
+ cause: error,
424
+ }),
425
+ ),
426
+ );
427
+ supervisor.on("message", (messageArg: unknown) => {
428
+ let message: TSupervisorMessage;
429
+ try {
430
+ message = readSupervisorMessage(messageArg);
431
+ } catch (error) {
432
+ if (terminated) lateReportError ??= error;
433
+ else reject(error);
434
+ return;
435
+ }
436
+ // Only the first report counts; one arriving while the supervisor is
437
+ // stopped is told with the termination.
438
+ if (terminated) lateReport ??= message;
439
+ else if (message.kind === "started") resolve(message.run);
440
+ else reject(new Error(message.error));
441
+ });
442
+ // `close` follows every report the supervisor sent before it ended.
443
+ supervisor.once("close", (codeArg, signalArg) =>
444
+ reject(
445
+ new Error(
446
+ terminated
447
+ ? describeTermination()
448
+ : `The detached release supervisor exited (${describeExit(codeArg, signalArg)}) before it started the release.`,
449
+ ),
450
+ ),
451
+ );
452
+ });
453
+ } finally {
454
+ clearTimeout(startTimer);
455
+ clearTimeout(stopTimer);
456
+ if (supervisor.connected) supervisor.disconnect();
457
+ supervisor.unref();
458
+ }
459
+ };
460
+
461
+ export const describeDetachedReleaseLaunch = (
462
+ runArg: IDetachedReleaseRun,
463
+ ): string =>
464
+ `Release running detached: run ${runArg.id}, process group ${runArg.supervisorPid}, log ${runArg.logPath}. ` +
465
+ `Follow it with \`tail -f ${runArg.logPath}\`; \`gitzone release inspect\` shows its outcome.`;
466
+
467
+ /** True in the process a detached launch started as its supervisor. */
468
+ export const isDetachedReleaseSupervisor = (): boolean =>
469
+ process.env[supervisorEnvironmentKey] !== undefined;
470
+
471
+ const readSupervisorHandoff = (): ISupervisorHandoff => {
472
+ const raw = process.env[supervisorEnvironmentKey];
473
+ // The worker and everything it runs must not take the supervisor role.
474
+ delete process.env[supervisorEnvironmentKey];
475
+ let handoff: unknown;
476
+ try {
477
+ handoff = JSON.parse(raw ?? "");
478
+ } catch (error) {
479
+ throw new Error("The detached release launch data is not valid JSON.", {
480
+ cause: error,
481
+ });
482
+ }
483
+ if (!isPlainObject(handoff) || typeof handoff.version !== "string") {
484
+ throw new Error("The detached release launch data is invalid.");
485
+ }
486
+ return { version: handoff.version };
487
+ };
488
+
489
+ interface IWorkerStart {
490
+ process: plugins.childProcess.ChildProcess;
491
+ exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
492
+ spawnFailed: Promise<Error>;
493
+ }
494
+
495
+ /** Starts the release with its output in the log; never awaits. */
496
+ const startWorker = (commandArg: string[], logFdArg: number): IWorkerStart => {
497
+ const worker = plugins.childProcess.spawn(
498
+ process.execPath,
499
+ [paths.cliEntryPath, ...commandArg],
500
+ { cwd: process.cwd(), stdio: ["ignore", logFdArg, logFdArg] },
501
+ );
502
+ // Both listeners exist before anything is awaited, so a spawn error is
503
+ // always observed.
504
+ return {
505
+ process: worker,
506
+ exited: new Promise((resolve) =>
507
+ worker.once("exit", (code, signal) => resolve({ code, signal })),
508
+ ),
509
+ spawnFailed: new Promise((resolve) => worker.once("error", resolve)),
510
+ };
511
+ };
512
+
513
+ /**
514
+ * The supervisor: holds the project's detached-release lock, starts the
515
+ * release with its output in the run's log, reports the start to the
516
+ * launcher, and records how the release ended.
517
+ */
518
+ export const superviseDetachedRelease = async (): Promise<void> => {
519
+ const sendToLauncher = process.send?.bind(process);
520
+ const disconnectLauncher = process.disconnect?.bind(process);
521
+ if (!sendToLauncher || !disconnectLauncher) {
522
+ delete process.env[supervisorEnvironmentKey];
523
+ throw new Error(
524
+ "The detached release supervisor runs only when `gitzone release --detach` starts it.",
525
+ );
526
+ }
527
+ const report = (messageArg: TSupervisorMessage): Promise<void> =>
528
+ new Promise((resolve) => {
529
+ if (!process.connected) return resolve();
530
+ sendToLauncher(messageArg, undefined, {}, () => {
531
+ if (process.connected) disconnectLauncher();
532
+ resolve();
533
+ });
534
+ });
535
+
536
+ // No signal ends the supervisor while it holds the lock or a release runs.
537
+ // Until the release is started, a signal cancels the launch; from then on
538
+ // it is passed on to the release, each signal once, and the supervisor
539
+ // stays to record how the release ended. Either way the lock is released.
540
+ let worker: plugins.childProcess.ChildProcess | undefined;
541
+ let cancelledBy: NodeJS.Signals | undefined;
542
+ const forwarded = new Set<NodeJS.Signals>();
543
+ const onSignal = (signalArg: NodeJS.Signals) => {
544
+ if (!worker) {
545
+ cancelledBy ??= signalArg;
546
+ return;
547
+ }
548
+ if (
549
+ forwarded.has(signalArg) ||
550
+ worker.exitCode !== null ||
551
+ worker.signalCode !== null
552
+ ) {
553
+ return;
554
+ }
555
+ forwarded.add(signalArg);
556
+ worker.kill(signalArg);
557
+ };
558
+ const assertNotCancelled = () => {
559
+ if (cancelledBy) {
560
+ throw new Error(
561
+ `The detached release supervisor received ${cancelledBy} before it started the release; nothing was started.`,
562
+ );
563
+ }
564
+ };
565
+ for (const signal of forwardedSignals) process.on(signal, onSignal);
566
+
567
+ let logPath: string | undefined;
568
+ try {
569
+ const handoff = readSupervisorHandoff();
570
+ const runs = await openDetachedReleaseRuns(process.cwd());
571
+ const command = process.argv.slice(2);
572
+ assertNotCancelled();
573
+ await runs.lock.runExclusive(async () => {
574
+ await plugins.fs.mkdir(runs.directory, { recursive: true, mode: 0o700 });
575
+ const id = plugins.crypto.randomBytes(16).toString("hex");
576
+ const runLogPath = runs.getLogPath(id);
577
+ const log = await plugins.fs.open(runLogPath, "wx", 0o600);
578
+ let started: IWorkerStart | undefined;
579
+ try {
580
+ // Nothing is awaited between this check and the spawn, so a signal
581
+ // either cancels the launch here or reaches the started release.
582
+ if (cancelledBy === undefined) {
583
+ started = startWorker(command, log.fd);
584
+ if (started.process.pid !== undefined) worker = started.process;
585
+ }
586
+ } finally {
587
+ // The worker holds its own descriptors of the log.
588
+ await log.close();
589
+ }
590
+ const workerPid = worker?.pid;
591
+ if (!started || !worker || workerPid === undefined) {
592
+ // No run exists, so its log is removed with it.
593
+ await plugins.fs.rm(runLogPath, { force: true });
594
+ assertNotCancelled();
595
+ throw new Error("The detached release could not be started.", {
596
+ cause: await started?.spawnFailed,
597
+ });
598
+ }
599
+ logPath = runLogPath;
600
+ const run: IDetachedReleaseRun = {
601
+ kind: detachedReleaseRunKind,
602
+ id,
603
+ command,
604
+ version: handoff.version,
605
+ cwd: process.cwd(),
606
+ supervisorPid: process.pid,
607
+ workerPid,
608
+ logPath: runLogPath,
609
+ startedAt: new Date().toISOString(),
610
+ state: "running",
611
+ exitCode: null,
612
+ signal: null,
613
+ finishedAt: null,
614
+ };
615
+ try {
616
+ await runs.write(run);
617
+ } catch (error) {
618
+ // Nothing may run that the run record does not name.
619
+ worker.kill("SIGKILL");
620
+ await started.exited;
621
+ throw error;
622
+ }
623
+ await report({ kind: "started", run });
624
+ const { code, signal } = await started.exited;
625
+ await plugins.fs.appendFile(
626
+ runLogPath,
627
+ `\nDetached release finished: ${describeExit(code, signal)}\n`,
628
+ );
629
+ await runs.write({
630
+ ...run,
631
+ state: code === 0 ? "succeeded" : "failed",
632
+ exitCode: code,
633
+ signal,
634
+ finishedAt: new Date().toISOString(),
635
+ });
636
+ process.exitCode = code ?? 1;
637
+ });
638
+ } catch (error) {
639
+ const message = error instanceof Error ? error.message : String(error);
640
+ if (process.connected) {
641
+ await report({ kind: "refused", error: message });
642
+ } else if (logPath) {
643
+ // The launcher is gone; the log is the one place left to say why.
644
+ await plugins.fs
645
+ .appendFile(
646
+ logPath,
647
+ `\nDetached release supervisor failed: ${message}\n`,
648
+ )
649
+ .catch(() => {});
650
+ }
651
+ throw error;
652
+ } finally {
653
+ for (const signal of forwardedSignals) process.off(signal, onSignal);
654
+ }
655
+ };