@operad-io/engine 0.1.1 → 0.2.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/config.schema.json +2 -1
- package/package.json +1 -1
- package/src/config/config.ts +74 -45
- package/src/flow/types.ts +4 -0
- package/src/flow/validate.ts +5 -0
- package/src/http/index.ts +2 -0
- package/src/http/plugins.ts +66 -0
- package/src/http/server.ts +342 -48
- package/src/kernel/decide.ts +115 -30
- package/src/kernel/state.ts +9 -0
- package/src/kernel/types.ts +25 -40
- package/src/log/open-log.ts +2 -5
- package/src/log/sqlite.ts +127 -85
- package/src/log/types.ts +35 -9
- package/src/loop/code-watch.ts +108 -2
- package/src/loop/older-code.ts +3 -4
- package/src/loop/serve.ts +122 -95
- package/src/notify/notify.ts +2 -6
- package/src/platform/atomic-write.ts +163 -0
- package/src/platform/file-lock.ts +43 -21
- package/src/platform/index.ts +2 -0
- package/src/platform/kept-workers.ts +290 -0
- package/src/platform/process-group.ts +11 -3
- package/src/platform/sqlite-open.ts +20 -6
- package/src/platform/sqlite-schema.ts +30 -0
- package/src/platform/step-reap.ts +33 -18
- package/src/platform/watch.ts +1 -11
- package/src/plugin/action-schema.ts +59 -1
- package/src/plugin/choice-info.ts +133 -0
- package/src/plugin/context.ts +279 -0
- package/src/plugin/declared-flows.ts +3 -10
- package/src/plugin/errors.ts +9 -0
- package/src/plugin/freeze.ts +12 -0
- package/src/plugin/harness.ts +28 -0
- package/src/plugin/index.ts +8 -7
- package/src/plugin/install.ts +265 -17
- package/src/plugin/keys.ts +2 -12
- package/src/plugin/load.ts +47 -23
- package/src/plugin/logger.ts +14 -0
- package/src/plugin/open-store.ts +0 -6
- package/src/plugin/question-form.ts +323 -0
- package/src/plugin/registry.ts +512 -76
- package/src/plugin/secrets.ts +14 -24
- package/src/plugin/semver.ts +52 -0
- package/src/plugin/settings.ts +1 -9
- package/src/plugin/sqlite-store.ts +94 -64
- package/src/plugin/store.ts +5 -0
- package/src/plugin/types.ts +566 -21
- package/src/plugin/validate.ts +396 -26
- package/src/runner/answer.ts +26 -68
- package/src/runner/ask.ts +227 -28
- package/src/runner/cancel.ts +10 -7
- package/src/runner/grants.ts +2 -2
- package/src/runner/index.ts +1 -3
- package/src/runner/limits.ts +2 -2
- package/src/runner/runner.ts +15 -14
- package/src/runner/service.ts +52 -19
- package/src/runner/step-worker.ts +9 -0
- package/src/testing/answer.ts +69 -0
- package/src/testing/clock-manual.ts +152 -0
- package/src/testing/config.ts +16 -0
- package/src/testing/fs.ts +172 -0
- package/src/testing/home.ts +43 -0
- package/src/testing/index.ts +19 -0
- package/src/testing/types.ts +2 -0
- package/src/testing/world.ts +9 -2
- package/src/trigger/kernel.ts +13 -46
- package/src/trigger/rules.ts +22 -12
- package/src/trigger/types.ts +2 -6
- package/src/util.ts +99 -0
- package/src/views/event-line.ts +22 -0
- package/src/views/history.ts +36 -19
- package/src/views/live-logs.ts +313 -0
- package/src/views/pending.ts +23 -5
- package/src/views/presentation.ts +629 -81
- package/src/views/running.ts +5 -5
- package/src/views/settings.ts +205 -66
- package/src/views/types.ts +3 -2
- package/src/views/uploads.ts +15 -7
- package/triggers.schema.json +4 -0
package/src/loop/code-watch.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { dirname, join, resolve, sep } from "node:path";
|
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
15
|
import { systemClock, watchDirectory } from "../platform/index.ts";
|
|
16
16
|
import type { Clock } from "../platform/index.ts";
|
|
17
|
+
import { messageOf } from "../plugin/errors.ts";
|
|
17
18
|
|
|
18
19
|
/** A file or directory whose files count as code, under the name a log line uses. */
|
|
19
20
|
export interface CodeRoot {
|
|
@@ -349,6 +350,22 @@ export interface CodeWatchOptions {
|
|
|
349
350
|
* "keep" leaves the process on its old code until the files change again.
|
|
350
351
|
*/
|
|
351
352
|
readonly onChange: CodeChangeHandler;
|
|
353
|
+
/**
|
|
354
|
+
* How long a check may run before the watch keeps the old code and tries
|
|
355
|
+
* again later. Zero or less waits without end. Default 90 s.
|
|
356
|
+
*/
|
|
357
|
+
readonly checkTimeoutMs?: number | undefined;
|
|
358
|
+
/**
|
|
359
|
+
* How often a kept change is offered again when no file changed: one bad
|
|
360
|
+
* moment must not leave the process on old code for good. Zero retries only
|
|
361
|
+
* at the next change. Default 5 min.
|
|
362
|
+
*/
|
|
363
|
+
readonly retryMs?: number | undefined;
|
|
364
|
+
/**
|
|
365
|
+
* Called when a change is kept for a reason the handler could not report
|
|
366
|
+
* itself: the check failed, or it did not finish in `checkTimeoutMs`.
|
|
367
|
+
*/
|
|
368
|
+
readonly onKept?: ((change: CodeChange, reason: string) => void) | undefined;
|
|
352
369
|
/**
|
|
353
370
|
* Called when the process starts or stops running older code than the files
|
|
354
371
|
* on disk: true once a change is on disk and the process has not taken it up.
|
|
@@ -356,6 +373,18 @@ export interface CodeWatchOptions {
|
|
|
356
373
|
readonly onOlder?: ((older: boolean) => void) | undefined;
|
|
357
374
|
}
|
|
358
375
|
|
|
376
|
+
/** How long a check may run before the watch keeps the old code by default. */
|
|
377
|
+
export const DEFAULT_CHECK_TIMEOUT_MS = 90_000;
|
|
378
|
+
|
|
379
|
+
/** How often a kept change is offered again by default. */
|
|
380
|
+
export const DEFAULT_RETRY_MS = 300_000;
|
|
381
|
+
|
|
382
|
+
/** A duration as the log line says it, in seconds. */
|
|
383
|
+
export function secondsOf(ms: number): string {
|
|
384
|
+
const seconds = ms / 1_000;
|
|
385
|
+
return `${Number.isInteger(seconds) ? seconds : Math.round(seconds * 10) / 10} s`;
|
|
386
|
+
}
|
|
387
|
+
|
|
359
388
|
/** Watches code files and reports a change once, after a quiet period. */
|
|
360
389
|
export class CodeWatch {
|
|
361
390
|
private readonly options: CodeWatchOptions;
|
|
@@ -365,6 +394,12 @@ export class CodeWatch {
|
|
|
365
394
|
private readonly watchers = new Map<string, () => void>();
|
|
366
395
|
private quiet: unknown;
|
|
367
396
|
private poll: unknown;
|
|
397
|
+
/** The timer that ends a check that runs too long. */
|
|
398
|
+
private checkTimer: unknown;
|
|
399
|
+
/** The timer that offers a kept change again. */
|
|
400
|
+
private retry: unknown;
|
|
401
|
+
/** Set by the retry timer, so the next check offers the kept change again. */
|
|
402
|
+
private retryWanted = false;
|
|
368
403
|
private busy = false;
|
|
369
404
|
private closed = false;
|
|
370
405
|
private older = false;
|
|
@@ -403,10 +438,28 @@ export class CodeWatch {
|
|
|
403
438
|
this.closed = true;
|
|
404
439
|
if (this.quiet !== undefined) this.clock.clearTimeout(this.quiet);
|
|
405
440
|
if (this.poll !== undefined) this.clock.clearTimeout(this.poll);
|
|
441
|
+
if (this.checkTimer !== undefined) this.clock.clearTimeout(this.checkTimer);
|
|
442
|
+
this.checkTimer = undefined;
|
|
443
|
+
this.cancelRetry();
|
|
406
444
|
for (const close of this.watchers.values()) close();
|
|
407
445
|
this.watchers.clear();
|
|
408
446
|
}
|
|
409
447
|
|
|
448
|
+
private planRetry(): void {
|
|
449
|
+
const retryMs = this.options.retryMs ?? DEFAULT_RETRY_MS;
|
|
450
|
+
if (this.closed || retryMs <= 0 || this.retry !== undefined) return;
|
|
451
|
+
this.retry = this.clock.setTimeout(() => {
|
|
452
|
+
this.retry = undefined;
|
|
453
|
+
this.retryWanted = true;
|
|
454
|
+
this.schedule();
|
|
455
|
+
}, retryMs);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
private cancelRetry(): void {
|
|
459
|
+
if (this.retry !== undefined) this.clock.clearTimeout(this.retry);
|
|
460
|
+
this.retry = undefined;
|
|
461
|
+
}
|
|
462
|
+
|
|
410
463
|
private setOlder(older: boolean): void {
|
|
411
464
|
if (this.older === older) return;
|
|
412
465
|
this.older = older;
|
|
@@ -445,12 +498,53 @@ export class CodeWatch {
|
|
|
445
498
|
this.quiet = this.clock.setTimeout(() => {
|
|
446
499
|
this.quiet = undefined;
|
|
447
500
|
this.check().catch(() => {
|
|
448
|
-
//
|
|
501
|
+
// An unexpected failure keeps the old code; the next change or the
|
|
502
|
+
// slow timer tries again.
|
|
449
503
|
this.busy = false;
|
|
450
504
|
});
|
|
451
505
|
}, this.options.quietMs);
|
|
452
506
|
}
|
|
453
507
|
|
|
508
|
+
/**
|
|
509
|
+
* Runs the handler, but not without end: a check that never finishes must
|
|
510
|
+
* not stop the watch. A failure or a timeout is a kept change with a reason.
|
|
511
|
+
*/
|
|
512
|
+
private answerWithin(
|
|
513
|
+
change: CodeChange,
|
|
514
|
+
): Promise<{ readonly answer: "reload" | "keep"; readonly reason?: string | undefined }> {
|
|
515
|
+
const timeoutMs = this.options.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
|
|
516
|
+
return new Promise((resolve) => {
|
|
517
|
+
let settled = false;
|
|
518
|
+
const finish = (value: { answer: "reload" | "keep"; reason?: string }): void => {
|
|
519
|
+
if (settled) return;
|
|
520
|
+
settled = true;
|
|
521
|
+
if (this.checkTimer !== undefined) this.clock.clearTimeout(this.checkTimer);
|
|
522
|
+
this.checkTimer = undefined;
|
|
523
|
+
resolve(value);
|
|
524
|
+
};
|
|
525
|
+
if (timeoutMs > 0) {
|
|
526
|
+
this.checkTimer = this.clock.setTimeout(() => {
|
|
527
|
+
finish({
|
|
528
|
+
answer: "keep",
|
|
529
|
+
reason: `the check did not finish within ${secondsOf(timeoutMs)}`,
|
|
530
|
+
});
|
|
531
|
+
}, timeoutMs);
|
|
532
|
+
}
|
|
533
|
+
let running: Promise<"reload" | "keep">;
|
|
534
|
+
try {
|
|
535
|
+
running = Promise.resolve(this.options.onChange(change));
|
|
536
|
+
} catch (error) {
|
|
537
|
+
finish({ answer: "keep", reason: `the check failed: ${messageOf(error)}` });
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
running.then(
|
|
541
|
+
(answer) => finish({ answer }),
|
|
542
|
+
(error: unknown) =>
|
|
543
|
+
finish({ answer: "keep", reason: `the check failed: ${messageOf(error)}` }),
|
|
544
|
+
);
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
|
|
454
548
|
private async check(): Promise<void> {
|
|
455
549
|
if (this.closed || this.busy || this.baseline === undefined) return;
|
|
456
550
|
const current = fingerprintCode(this.options.roots, this.cache);
|
|
@@ -458,28 +552,40 @@ export class CodeWatch {
|
|
|
458
552
|
this.sync(current, settings);
|
|
459
553
|
const change = diffFingerprints(this.baseline, current);
|
|
460
554
|
if (change === undefined) {
|
|
555
|
+
this.retryWanted = false;
|
|
556
|
+
this.cancelRetry();
|
|
461
557
|
this.setOlder(false);
|
|
462
558
|
return;
|
|
463
559
|
}
|
|
464
560
|
if (
|
|
561
|
+
!this.retryWanted &&
|
|
465
562
|
this.declined !== undefined &&
|
|
466
563
|
diffFingerprints(this.declined.code, current) === undefined &&
|
|
467
564
|
diffFingerprints(this.declined.settings, settings) === undefined
|
|
468
565
|
) {
|
|
566
|
+
// This change was tried and kept; the slow timer offers it again.
|
|
469
567
|
this.setOlder(true);
|
|
568
|
+
this.planRetry();
|
|
470
569
|
return;
|
|
471
570
|
}
|
|
571
|
+
this.retryWanted = false;
|
|
572
|
+
this.cancelRetry();
|
|
472
573
|
this.busy = true;
|
|
473
574
|
let answer: "reload" | "keep" = "keep";
|
|
474
575
|
try {
|
|
475
|
-
|
|
576
|
+
const outcome = await this.answerWithin(change);
|
|
577
|
+
answer = outcome.answer;
|
|
578
|
+
if (outcome.reason !== undefined) this.options.onKept?.(change, outcome.reason);
|
|
476
579
|
} finally {
|
|
477
580
|
if (answer === "reload") {
|
|
478
581
|
this.stop();
|
|
582
|
+
} else if (this.closed) {
|
|
583
|
+
this.busy = false;
|
|
479
584
|
} else {
|
|
480
585
|
this.declined = { code: current, settings };
|
|
481
586
|
this.busy = false;
|
|
482
587
|
this.setOlder(true);
|
|
588
|
+
this.planRetry();
|
|
483
589
|
}
|
|
484
590
|
}
|
|
485
591
|
}
|
package/src/loop/older-code.ts
CHANGED
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
* serve is another process, so the item leaves with it.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import { readFileSync,
|
|
11
|
+
import { readFileSync, rmSync } from "node:fs";
|
|
12
12
|
import { join } from "node:path";
|
|
13
|
+
import { writeJsonAtomicSync } from "../platform/index.ts";
|
|
13
14
|
import { pidAlive, readLockPid, serveLockPath } from "../runner/lock.ts";
|
|
14
15
|
|
|
15
16
|
function noticePath(home: string): string {
|
|
@@ -34,9 +35,7 @@ export function olderCodeNotice(home: string, pid: number = process.pid): {
|
|
|
34
35
|
clear();
|
|
35
36
|
return;
|
|
36
37
|
}
|
|
37
|
-
|
|
38
|
-
writeFileSync(temporary, `${JSON.stringify({ pid })}\n`);
|
|
39
|
-
renameSync(temporary, noticePath(home));
|
|
38
|
+
writeJsonAtomicSync(noticePath(home), { pid });
|
|
40
39
|
},
|
|
41
40
|
clear,
|
|
42
41
|
};
|
package/src/loop/serve.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** The kernel loop: one per operad home, one child process per run. */
|
|
2
2
|
|
|
3
|
+
import { messageOf } from "../plugin/errors.ts";
|
|
3
4
|
import { ActiveRunError, SeqConflictError } from "../log/errors.ts";
|
|
4
5
|
import type { InputRecord, JsonValue, LogBackend } from "../log/types.ts";
|
|
5
6
|
import { StartRefusedError } from "../plugin/errors.ts";
|
|
@@ -12,9 +13,12 @@ import type { TriggerRule } from "../trigger/types.ts";
|
|
|
12
13
|
import { acquireLock, lockHeld, runLockPath, serveLockPath } from "../runner/lock.ts";
|
|
13
14
|
import type { LockHandle } from "../runner/lock.ts";
|
|
14
15
|
import { StepLimits } from "../runner/limits.ts";
|
|
15
|
-
import { applyInput,
|
|
16
|
+
import { applyInput, parseObjectKey, readState } from "../runner/service.ts";
|
|
17
|
+
import { isBusy } from "../platform/index.ts";
|
|
16
18
|
import { reapStale } from "../platform/step-reap.ts";
|
|
17
|
-
import {
|
|
19
|
+
import { stopAllKeptWorkers } from "../platform/kept-workers.ts";
|
|
20
|
+
import type { AskQuestionAnswer } from "../plugin/types.ts";
|
|
21
|
+
import { isRecord, objectKey } from "../util.ts";
|
|
18
22
|
|
|
19
23
|
export interface SpawnRunOptions {
|
|
20
24
|
/** The previous process died mid-step; recover before doing anything else. */
|
|
@@ -62,10 +66,13 @@ function recordedAnswer(payload: JsonValue): PersonAnswerInput | undefined {
|
|
|
62
66
|
if (!isRecord(payload) || payload.kind !== "person_answer") return undefined;
|
|
63
67
|
const waitId = payload.waitId;
|
|
64
68
|
const choice = payload.choice;
|
|
69
|
+
const answers = payload.answers;
|
|
65
70
|
const actor = payload.actor;
|
|
66
71
|
if (
|
|
67
72
|
typeof waitId !== "string" ||
|
|
68
|
-
typeof choice !== "string" ||
|
|
73
|
+
(choice !== undefined && typeof choice !== "string") ||
|
|
74
|
+
(answers !== undefined && !Array.isArray(answers)) ||
|
|
75
|
+
(choice === undefined && answers === undefined) ||
|
|
69
76
|
!isRecord(actor) ||
|
|
70
77
|
typeof actor.via !== "string" ||
|
|
71
78
|
typeof actor.id !== "string"
|
|
@@ -75,14 +82,15 @@ function recordedAnswer(payload: JsonValue): PersonAnswerInput | undefined {
|
|
|
75
82
|
return {
|
|
76
83
|
kind: "person_answer",
|
|
77
84
|
waitId,
|
|
78
|
-
choice,
|
|
85
|
+
...(choice === undefined ? {} : { choice }),
|
|
86
|
+
...(answers === undefined ? {} : { answers: answers as unknown as readonly AskQuestionAnswer[] }),
|
|
79
87
|
...(typeof payload.note === "string" ? { note: payload.note } : {}),
|
|
80
88
|
actor: { via: actor.via, id: actor.id },
|
|
81
89
|
};
|
|
82
90
|
}
|
|
83
91
|
|
|
84
92
|
/** The kernel facts a plugin's tick may ask about. */
|
|
85
|
-
function runLookup(log: LogBackend): RunLookup {
|
|
93
|
+
export function runLookup(log: LogBackend): RunLookup {
|
|
86
94
|
return {
|
|
87
95
|
active: async (object) => {
|
|
88
96
|
const runs = await log.runs({ active: true });
|
|
@@ -271,106 +279,118 @@ export async function serveOnce(
|
|
|
271
279
|
const started: string[] = [];
|
|
272
280
|
const spawned: string[] = [];
|
|
273
281
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
282
|
+
try {
|
|
283
|
+
options.registry.useRunLookup(runLookup(options.log));
|
|
284
|
+
await options.registry.tick(runLookup(options.log));
|
|
285
|
+
const requests = [...options.registry.startedRuns];
|
|
286
|
+
for (const request of requests) {
|
|
287
|
+
if (options.shouldStop?.() === true) break;
|
|
288
|
+
const object = startObjectKey(request);
|
|
289
|
+
try {
|
|
290
|
+
const result = await kernel.start({
|
|
291
|
+
flow: request.flow,
|
|
292
|
+
object,
|
|
293
|
+
...(request.params === undefined ? {} : { params: request.params }),
|
|
294
|
+
...(request.trigger === undefined ? {} : { trigger: request.trigger }),
|
|
295
|
+
...(request.inputId === undefined ? {} : { inputId: request.inputId }),
|
|
296
|
+
...(request.access === undefined ? {} : { access: request.access }),
|
|
297
|
+
});
|
|
298
|
+
if (result.kind === "started") started.push(result.runId);
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error instanceof StartRefusedError) {
|
|
301
|
+
options.onLog?.(`${request.plugin}/${request.flow}: ${error.message}`);
|
|
302
|
+
} else if (!(error instanceof ActiveRunError)) throw error;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
// Only a pass that tried every request in its snapshot drains them, and
|
|
306
|
+
// only those: a request pushed meanwhile waits for the next pass. A busy
|
|
307
|
+
// store leaves them in place, so the next pass tries the same starts again.
|
|
308
|
+
options.registry.takeStartedRuns(requests.length);
|
|
309
|
+
|
|
310
|
+
if (options.shouldStop?.() !== true) {
|
|
311
|
+
await applyRecordedAnswers({
|
|
312
|
+
log: options.log,
|
|
313
|
+
registry: options.registry,
|
|
314
|
+
kernel,
|
|
315
|
+
clock,
|
|
316
|
+
...(options.shouldStop === undefined
|
|
317
|
+
? {}
|
|
318
|
+
: { shouldStop: options.shouldStop }),
|
|
287
319
|
});
|
|
288
|
-
if (result.kind === "started") started.push(result.runId);
|
|
289
|
-
} catch (error) {
|
|
290
|
-
if (error instanceof StartRefusedError) {
|
|
291
|
-
options.onLog?.(`${request.plugin}/${request.flow}: ${error.message}`);
|
|
292
|
-
} else if (!(error instanceof ActiveRunError)) throw error;
|
|
293
320
|
}
|
|
294
|
-
}
|
|
295
321
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
...(options.shouldStop === undefined
|
|
303
|
-
? {}
|
|
304
|
-
: { shouldStop: options.shouldStop }),
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
// Places freed while no process was left to hand them on (a crash after a
|
|
309
|
-
// step's result, a run that ended) go to the next in line before runs are
|
|
310
|
-
// given processes.
|
|
311
|
-
if (options.shouldStop?.() !== true) {
|
|
312
|
-
await new StepLimits({ log: options.log, lockRoot: options.lockRoot }).grant();
|
|
313
|
-
}
|
|
322
|
+
// Places freed while no process was left to hand them on (a crash after a
|
|
323
|
+
// step's result, a run that ended) go to the next in line before runs are
|
|
324
|
+
// given processes.
|
|
325
|
+
if (options.shouldStop?.() !== true) {
|
|
326
|
+
await new StepLimits({ log: options.log, lockRoot: options.lockRoot }).grant();
|
|
327
|
+
}
|
|
314
328
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
329
|
+
const active = await options.log.runs({ active: true });
|
|
330
|
+
for (const run of active) {
|
|
331
|
+
if (options.shouldStop?.() === true) break;
|
|
332
|
+
const state = await readState(options.log, run.runId);
|
|
319
333
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
334
|
+
if (state.status === "ended") {
|
|
335
|
+
// Recording the end event comes first; `emitRunEnd` ends the run before
|
|
336
|
+
// routing it, so a recovered run can start the same flow on the object.
|
|
337
|
+
await kernel.emitRunEnd(run.runId, state);
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (state.status === "waiting_person") continue;
|
|
341
|
+
|
|
342
|
+
// A run no loaded plugin declares has no graph to drive it. It fails now,
|
|
343
|
+
// naming its flow, instead of sitting at starting while a child retries.
|
|
344
|
+
if (options.registry.flow(run.flow) === undefined) {
|
|
345
|
+
const reason = `flow "${run.flow}" is not loaded`;
|
|
346
|
+
options.onLog?.(`run ${run.runId}: ${reason}`);
|
|
347
|
+
await kernel.failRun(run.runId, reason);
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
336
350
|
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
351
|
+
const now = clock();
|
|
352
|
+
if (
|
|
353
|
+
state.effect?.kind === "schedule_wake" &&
|
|
354
|
+
state.effect.due !== null &&
|
|
355
|
+
now < state.effect.due
|
|
356
|
+
) {
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
345
359
|
|
|
346
|
-
|
|
347
|
-
|
|
360
|
+
if (isRunnerAlive(run.runId)) continue;
|
|
361
|
+
if (options.isRecentlySpawned?.(run.runId) === true) continue;
|
|
348
362
|
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
363
|
+
// A step the flow needs went missing: the run waits for the plugin.
|
|
364
|
+
const problem = options.registry.startProblem(run.flow);
|
|
365
|
+
if (problem !== undefined) {
|
|
366
|
+
options.onLog?.(`run ${run.runId}: ${problem}`);
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
355
369
|
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
370
|
+
// A start that died after creating its run must not become a run with no
|
|
371
|
+
// record of the event that made it: restore the start files first, so the
|
|
372
|
+
// child starts from the intended input and sees the same event.
|
|
373
|
+
kernel.adoptStart(run);
|
|
360
374
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
375
|
+
await options.spawnRun(run.runId, {
|
|
376
|
+
recover:
|
|
377
|
+
state.status === "running" &&
|
|
378
|
+
state.effect !== null &&
|
|
379
|
+
state.effectStarted === state.effect.id,
|
|
380
|
+
});
|
|
381
|
+
spawned.push(run.runId);
|
|
382
|
+
}
|
|
369
383
|
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
384
|
+
// A recorded event whose routing was interrupted is routed again. Outcomes
|
|
385
|
+
// are derived from the log by input id, so a second pass cannot repeat one.
|
|
386
|
+
if (options.shouldStop?.() !== true) {
|
|
387
|
+
await kernel.recoverUnrouted();
|
|
388
|
+
}
|
|
389
|
+
} catch (error) {
|
|
390
|
+
// A store another process holds past the busy timeout fails this pass,
|
|
391
|
+
// not the serve: the work that needs it is tried again on the next pass.
|
|
392
|
+
if (!isBusy(error)) throw error;
|
|
393
|
+
options.onLog?.(`serve: ${messageOf(error)}`);
|
|
374
394
|
}
|
|
375
395
|
|
|
376
396
|
return { started, spawned };
|
|
@@ -450,7 +470,14 @@ export async function serve(options: ServeOptions): Promise<void> {
|
|
|
450
470
|
log: (message) => options.onLog?.(message),
|
|
451
471
|
});
|
|
452
472
|
} catch (error) {
|
|
453
|
-
options.onLog?.(`serve start: could not look for left-over processes: ${
|
|
473
|
+
options.onLog?.(`serve start: could not look for left-over processes: ${messageOf(error)}`);
|
|
474
|
+
}
|
|
475
|
+
// A kept worker runs the code of the serve that started it: a serve that
|
|
476
|
+
// starts or takes over the home ends them all before serving new code.
|
|
477
|
+
try {
|
|
478
|
+
await stopAllKeptWorkers({ home: options.home });
|
|
479
|
+
} catch (error) {
|
|
480
|
+
options.onLog?.(`serve start: could not end kept workers: ${messageOf(error)}`);
|
|
454
481
|
}
|
|
455
482
|
while (!stopped) {
|
|
456
483
|
inPass = true;
|
package/src/notify/notify.ts
CHANGED
|
@@ -21,6 +21,7 @@ import type { LogBackend } from "../log/types.ts";
|
|
|
21
21
|
import { messageOf } from "../plugin/errors.ts";
|
|
22
22
|
import { runLine } from "../platform/process-group.ts";
|
|
23
23
|
import { parseObjectKey, readState } from "../runner/service.ts";
|
|
24
|
+
import { isRecord } from "../util.ts";
|
|
24
25
|
|
|
25
26
|
/** The fact kind a recorded notification has. */
|
|
26
27
|
export const NOTIFIED_FACT = "notified";
|
|
@@ -137,12 +138,7 @@ export class Notifier {
|
|
|
137
138
|
for await (const fact of this.options.log.readGlobal()) {
|
|
138
139
|
if (fact.kind !== NOTIFIED_FACT) continue;
|
|
139
140
|
const payload = fact.payload;
|
|
140
|
-
if (
|
|
141
|
-
typeof payload === "object" &&
|
|
142
|
-
payload !== null &&
|
|
143
|
-
!Array.isArray(payload) &&
|
|
144
|
-
typeof payload.key === "string"
|
|
145
|
-
) {
|
|
141
|
+
if (isRecord(payload) && typeof payload.key === "string") {
|
|
146
142
|
keys.add(payload.key);
|
|
147
143
|
}
|
|
148
144
|
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writing a file whole. A writer puts the new text in a temporary file in the
|
|
3
|
+
* same directory, flushes it, then renames it over the target, so a crash or a
|
|
4
|
+
* second writer leaves the old file or the new one, never half of either.
|
|
5
|
+
*
|
|
6
|
+
* The temporary name carries the process id and a random value, so two writers
|
|
7
|
+
* never share one. Writing through one helper also keeps the target's mode: a
|
|
8
|
+
* file that already exists keeps it, and a caller that names a mode gets it
|
|
9
|
+
* exactly, even under a umask.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import {
|
|
14
|
+
chmodSync,
|
|
15
|
+
closeSync,
|
|
16
|
+
fsyncSync,
|
|
17
|
+
mkdirSync,
|
|
18
|
+
openSync,
|
|
19
|
+
renameSync,
|
|
20
|
+
rmSync,
|
|
21
|
+
statSync,
|
|
22
|
+
writeSync,
|
|
23
|
+
} from "node:fs";
|
|
24
|
+
import { chmod, mkdir, open, rename, rm, stat } from "node:fs/promises";
|
|
25
|
+
import { basename, dirname, join } from "node:path";
|
|
26
|
+
|
|
27
|
+
/** What a synchronous atomic write may adjust. */
|
|
28
|
+
export interface AtomicWriteOptions {
|
|
29
|
+
/** The mode the file has afterwards; default keeps the mode of a file that exists. */
|
|
30
|
+
readonly mode?: number | undefined;
|
|
31
|
+
/** Called once the temporary file is complete, before it replaces the target. */
|
|
32
|
+
readonly beforeRename?:
|
|
33
|
+
| ((temporary: string, file: string) => void)
|
|
34
|
+
| undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** What an asynchronous atomic write may adjust. */
|
|
38
|
+
export interface AsyncAtomicWriteOptions {
|
|
39
|
+
/** The mode the file has afterwards; default keeps the mode of a file that exists. */
|
|
40
|
+
readonly mode?: number | undefined;
|
|
41
|
+
/** Called once the temporary file is complete, before it replaces the target. */
|
|
42
|
+
readonly beforeRename?:
|
|
43
|
+
| ((temporary: string, file: string) => Promise<void> | void)
|
|
44
|
+
| undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** How a JSON value is written; the file gets a newline unless told otherwise. */
|
|
48
|
+
export interface JsonWriteOptions extends AtomicWriteOptions {
|
|
49
|
+
/** The indentation `JSON.stringify` uses; none by default. */
|
|
50
|
+
readonly space?: number | undefined;
|
|
51
|
+
/** Whether a newline follows the JSON; true by default. */
|
|
52
|
+
readonly newline?: boolean | undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The asynchronous form of {@link JsonWriteOptions}. */
|
|
56
|
+
export interface AsyncJsonWriteOptions extends AsyncAtomicWriteOptions {
|
|
57
|
+
/** The indentation `JSON.stringify` uses; none by default. */
|
|
58
|
+
readonly space?: number | undefined;
|
|
59
|
+
/** Whether a newline follows the JSON; true by default. */
|
|
60
|
+
readonly newline?: boolean | undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function temporaryPath(file: string): string {
|
|
64
|
+
return join(
|
|
65
|
+
dirname(file),
|
|
66
|
+
`.${basename(file)}.${process.pid}.${randomUUID()}.tmp`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function jsonText(value: unknown, space: number | undefined, newline: boolean): string {
|
|
71
|
+
const text = JSON.stringify(value, null, space);
|
|
72
|
+
return newline ? `${text}\n` : text;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Writes `text` to `path` through a temporary file and a rename. The parent
|
|
77
|
+
* directory is created when it is missing.
|
|
78
|
+
*/
|
|
79
|
+
export async function writeFileAtomic(
|
|
80
|
+
path: string,
|
|
81
|
+
text: string,
|
|
82
|
+
options: AsyncAtomicWriteOptions = {},
|
|
83
|
+
): Promise<void> {
|
|
84
|
+
await mkdir(dirname(path), { recursive: true });
|
|
85
|
+
const temporary = temporaryPath(path);
|
|
86
|
+
const existing = await stat(path).then(
|
|
87
|
+
(info) => info.mode & 0o777,
|
|
88
|
+
() => undefined,
|
|
89
|
+
);
|
|
90
|
+
const mode = options.mode ?? existing;
|
|
91
|
+
try {
|
|
92
|
+
const handle = await open(temporary, "w", options.mode ?? 0o666);
|
|
93
|
+
try {
|
|
94
|
+
await handle.writeFile(text);
|
|
95
|
+
await handle.sync();
|
|
96
|
+
} finally {
|
|
97
|
+
await handle.close();
|
|
98
|
+
}
|
|
99
|
+
if (mode !== undefined) await chmod(temporary, mode);
|
|
100
|
+
await options.beforeRename?.(temporary, path);
|
|
101
|
+
await rename(temporary, path);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The synchronous form of {@link writeFileAtomic}. */
|
|
109
|
+
export function writeFileAtomicSync(
|
|
110
|
+
path: string,
|
|
111
|
+
text: string,
|
|
112
|
+
options: AtomicWriteOptions = {},
|
|
113
|
+
): void {
|
|
114
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
115
|
+
const temporary = temporaryPath(path);
|
|
116
|
+
const existing = readMode(path);
|
|
117
|
+
const mode = options.mode ?? existing;
|
|
118
|
+
try {
|
|
119
|
+
const fd = openSync(temporary, "w", options.mode ?? 0o666);
|
|
120
|
+
try {
|
|
121
|
+
writeSync(fd, text);
|
|
122
|
+
fsyncSync(fd);
|
|
123
|
+
} finally {
|
|
124
|
+
closeSync(fd);
|
|
125
|
+
}
|
|
126
|
+
if (mode !== undefined) chmodSync(temporary, mode);
|
|
127
|
+
options.beforeRename?.(temporary, path);
|
|
128
|
+
renameSync(temporary, path);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
try {
|
|
131
|
+
rmSync(temporary, { force: true });
|
|
132
|
+
} catch {
|
|
133
|
+
// The temporary file was never made, or is already gone.
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function readMode(path: string): number | undefined {
|
|
140
|
+
try {
|
|
141
|
+
return statSync(path).mode & 0o777;
|
|
142
|
+
} catch {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Writes `value` as JSON through a temporary file and a rename. */
|
|
148
|
+
export async function writeJsonAtomic(
|
|
149
|
+
path: string,
|
|
150
|
+
value: unknown,
|
|
151
|
+
options: AsyncJsonWriteOptions = {},
|
|
152
|
+
): Promise<void> {
|
|
153
|
+
await writeFileAtomic(path, jsonText(value, options.space, options.newline ?? true), options);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The synchronous form of {@link writeJsonAtomic}. */
|
|
157
|
+
export function writeJsonAtomicSync(
|
|
158
|
+
path: string,
|
|
159
|
+
value: unknown,
|
|
160
|
+
options: JsonWriteOptions = {},
|
|
161
|
+
): void {
|
|
162
|
+
writeFileAtomicSync(path, jsonText(value, options.space, options.newline ?? true), options);
|
|
163
|
+
}
|