omkit 0.0.9 → 0.0.10
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/dist/actions/chrome-page.d.ts +1 -1
- package/dist/actions/chrome-page.js +1 -1
- package/dist/actions/command.d.ts +1 -1
- package/dist/actions/command.js +5 -6
- package/dist/actions/healthcheck.d.ts +1 -1
- package/dist/actions/healthcheck.js +1 -1
- package/dist/actions/prompt.d.ts +1 -1
- package/dist/actions/prompt.js +1 -1
- package/dist/actions/tail-log.d.ts +1 -1
- package/dist/actions/tail-log.js +1 -1
- package/dist/actions/until-log.d.ts +2 -2
- package/dist/actions/until-log.js +1 -1
- package/dist/actions/watch-dir.d.ts +1 -1
- package/dist/actions/watch-dir.js +1 -1
- package/dist/actions/watch.d.ts +1 -1
- package/dist/actions/watch.js +1 -1
- package/dist/index.d.ts +13 -17
- package/dist/index.js +15 -17
- package/dist/orchestration/action/action.d.ts +23 -0
- package/dist/orchestration/action/action.js +254 -0
- package/dist/{core/action.d.ts → orchestration/action/types.d.ts} +31 -27
- package/dist/orchestration/action/types.js +1 -0
- package/dist/{core → orchestration/events}/events.d.ts +9 -1
- package/dist/{core → orchestration/events}/events.js +14 -22
- package/dist/orchestration/spin/SpinHost.d.ts +105 -0
- package/dist/orchestration/spin/SpinHost.js +303 -0
- package/dist/orchestration/spin/spin.d.ts +24 -0
- package/dist/orchestration/spin/spin.js +56 -0
- package/dist/orchestration/spin/types.d.ts +56 -0
- package/dist/orchestration/spin/types.js +1 -0
- package/dist/output/Output.d.ts +24 -0
- package/dist/output/Output.js +27 -0
- package/dist/output/folder/RunFolder.d.ts +29 -0
- package/dist/output/folder/RunFolder.js +56 -0
- package/dist/output/index.d.ts +11 -0
- package/dist/output/index.js +11 -0
- package/dist/output/log/LogRenderer.d.ts +73 -0
- package/dist/output/log/LogRenderer.js +131 -0
- package/dist/{core/log-collector → output/log}/LogsCollector.d.ts +14 -0
- package/dist/{core/log-collector → output/log}/LogsCollector.js +24 -1
- package/dist/output/log/RunLog.d.ts +44 -0
- package/dist/output/log/RunLog.js +119 -0
- package/dist/output/snapshot/SnapshotStore.d.ts +49 -0
- package/dist/output/snapshot/SnapshotStore.js +61 -0
- package/dist/system/fs/FolderCache.d.ts +47 -0
- package/dist/system/fs/FolderCache.js +117 -0
- package/dist/system/fs/streams.d.ts +11 -0
- package/dist/system/fs/streams.js +14 -0
- package/dist/{core → system/process}/process.d.ts +9 -8
- package/dist/{core → system/process}/process.js +8 -9
- package/dist/utils/format.d.ts +9 -0
- package/dist/utils/format.js +9 -0
- package/dist/utils/serialize.d.ts +2 -0
- package/dist/utils/serialize.js +12 -0
- package/package.json +1 -1
- package/dist/core/action.js +0 -201
- package/dist/core/folder-cache.d.ts +0 -39
- package/dist/core/folder-cache.js +0 -109
- package/dist/core/log-collector/global.d.ts +0 -7
- package/dist/core/log-collector/global.js +0 -7
- package/dist/core/log-collector/render.d.ts +0 -68
- package/dist/core/log-collector/render.js +0 -132
- package/dist/core/markers.d.ts +0 -9
- package/dist/core/markers.js +0 -13
- package/dist/core/output.d.ts +0 -68
- package/dist/core/output.js +0 -213
- package/dist/core/run.d.ts +0 -88
- package/dist/core/run.js +0 -257
- package/dist/core/spin.d.ts +0 -72
- package/dist/core/spin.js +0 -45
- /package/dist/{core/helpers → utils}/AsyncQueue.d.ts +0 -0
- /package/dist/{core/helpers → utils}/AsyncQueue.js +0 -0
|
@@ -18,6 +18,14 @@ export interface Emitter<Events extends object> {
|
|
|
18
18
|
listen<K extends keyof Events>(key: K, handler: EventHandler<Events[K]>): () => void;
|
|
19
19
|
/** Like {@link Emitter.listen} but auto-unsubscribes after the first delivery (snapshot counts). */
|
|
20
20
|
listenOnce<K extends keyof Events>(key: K, handler: EventHandler<Events[K]>): () => void;
|
|
21
|
+
/**
|
|
22
|
+
* Observe **every** live emit on this bus, whatever the key — the cross-cutting
|
|
23
|
+
* hook the bus itself stays out of. Used by the action engine to log each emit
|
|
24
|
+
* onto the run timeline (through the action's scoped logger), so the bus is pure
|
|
25
|
+
* pub/sub and logging is layered on top. Fires only for live emits, not snapshot
|
|
26
|
+
* replays. Returns an unsubscribe.
|
|
27
|
+
*/
|
|
28
|
+
onAny(handler: (key: keyof Events, payload: unknown) => void): () => void;
|
|
21
29
|
}
|
|
22
|
-
export declare const events: <Events extends object>(
|
|
30
|
+
export declare const events: <Events extends object>(_namespace?: string) => Emitter<Events>;
|
|
23
31
|
export {};
|
|
@@ -1,29 +1,15 @@
|
|
|
1
|
-
|
|
2
|
-
import { captureSnapshot } from "./output.js";
|
|
3
|
-
export const events = (namespace) => {
|
|
1
|
+
export const events = (_namespace) => {
|
|
4
2
|
const handlers = new Map();
|
|
5
3
|
const snapshots = new Map();
|
|
4
|
+
const anyHandlers = new Set();
|
|
6
5
|
const emit = (key, ...args) => {
|
|
7
6
|
const payload = args[0];
|
|
8
7
|
snapshots.set(key, payload);
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const fields = [namespace, String(key)];
|
|
15
|
-
if (typeof payload === "string") {
|
|
16
|
-
fields.push(payload);
|
|
17
|
-
}
|
|
18
|
-
else if (payload !== undefined) {
|
|
19
|
-
const name = `event-${[namespace, String(key)].filter(Boolean).join("-")}`;
|
|
20
|
-
fields.push(`→ ${captureSnapshot(name, payload).rel}`);
|
|
21
|
-
}
|
|
22
|
-
log.append({
|
|
23
|
-
source: "event",
|
|
24
|
-
level: "event",
|
|
25
|
-
message: fields.filter(Boolean).join(" · "),
|
|
26
|
-
});
|
|
8
|
+
// Notify the cross-cutting observers first (they log the emit onto the
|
|
9
|
+
// timeline), then the keyed handlers — the bus does no logging of its own.
|
|
10
|
+
// Copy so an observer unsubscribing mid-emit doesn't disturb iteration.
|
|
11
|
+
for (const handler of [...anyHandlers])
|
|
12
|
+
handler(key, payload);
|
|
27
13
|
const set = handlers.get(key);
|
|
28
14
|
if (!set)
|
|
29
15
|
return;
|
|
@@ -57,5 +43,11 @@ export const events = (namespace) => {
|
|
|
57
43
|
});
|
|
58
44
|
return off;
|
|
59
45
|
};
|
|
60
|
-
|
|
46
|
+
const onAny = (handler) => {
|
|
47
|
+
anyHandlers.add(handler);
|
|
48
|
+
return () => {
|
|
49
|
+
anyHandlers.delete(handler);
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
return { emit, listen, listenOnce, onAny };
|
|
61
53
|
};
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { AnyActionInstance } from "../action/types.ts";
|
|
2
|
+
import { LogsCollector } from "../../output/log/LogsCollector.ts";
|
|
3
|
+
import { Output } from "../../output/Output.ts";
|
|
4
|
+
import type { SpinResult, SpinState } from "./types.ts";
|
|
5
|
+
/**
|
|
6
|
+
* A live spin over its own append-only log: constructing one launches the given
|
|
7
|
+
* actions in parallel under a single abort controller and drives them to a terminal
|
|
8
|
+
* {@link SpinResult}. Stop it with `.cancel()`, `await` its `.done` for the verdict.
|
|
9
|
+
*
|
|
10
|
+
* **A spin owns its world.** Each construction creates its *own* {@link LogsCollector}
|
|
11
|
+
* and {@link Output} — the run's log, folder, and snapshots — rather than sharing a
|
|
12
|
+
* process global, so runs don't bleed into each other and a fresh run can be created
|
|
13
|
+
* in a living process (sequential re-runs, in-process tests). Attach further actions
|
|
14
|
+
* to a running spin — including event-driven ones — via its `.run(…)` method.
|
|
15
|
+
*
|
|
16
|
+
* Each action runs against its own child logger (which headers and indents its
|
|
17
|
+
* lines into this run's log) and the spin's shared abort signal — both injected
|
|
18
|
+
* into its context, where the framework also binds a `proc` and the run's `output`
|
|
19
|
+
* so child processes stream into the right log and die on teardown. A **failing
|
|
20
|
+
* action never tears the spin down** — its `{ ok: false }` outcome is recorded in
|
|
21
|
+
* the verdict (and sets exit code 1) and the spin keeps running. Teardown to
|
|
22
|
+
* `closed` happens only on Ctrl-C, `.cancel()`, natural completion, or an uncaught
|
|
23
|
+
* fatal. The process-level hooks (SIGINT/uncaught handlers, `exitCode`) are owned by
|
|
24
|
+
* the run and cleaned at finalize, so they don't outlive it.
|
|
25
|
+
*/
|
|
26
|
+
export declare class SpinHost {
|
|
27
|
+
/** This run's append-only log — its own store, not a process global. */
|
|
28
|
+
readonly logs: LogsCollector;
|
|
29
|
+
/** This run's output subsystem (folder + snapshots + run-log writer), wired to {@link logs}. */
|
|
30
|
+
readonly output: Output;
|
|
31
|
+
/** The spin's abort signal — for consumers that want to observe teardown. */
|
|
32
|
+
readonly signal: AbortSignal;
|
|
33
|
+
/** Settles once the spin reaches `closed`, carrying the terminal verdict. Never rejects. */
|
|
34
|
+
readonly done: Promise<SpinResult>;
|
|
35
|
+
private readonly controller;
|
|
36
|
+
private phase;
|
|
37
|
+
/** The current lifecycle state — see {@link SpinState}. */
|
|
38
|
+
get state(): SpinState;
|
|
39
|
+
private readonly failures;
|
|
40
|
+
private readonly inFlight;
|
|
41
|
+
private readonly launched;
|
|
42
|
+
private readonly streaming;
|
|
43
|
+
private readonly onSigint;
|
|
44
|
+
private readonly onUncaught;
|
|
45
|
+
private readonly onUnhandled;
|
|
46
|
+
constructor(...actions: AnyActionInstance[]);
|
|
47
|
+
/**
|
|
48
|
+
* Launch more actions into this same spin — same controller, same log. Chainable.
|
|
49
|
+
*
|
|
50
|
+
* Throws if the spin is no longer `open`.
|
|
51
|
+
*/
|
|
52
|
+
run(...more: AnyActionInstance[]): this;
|
|
53
|
+
/**
|
|
54
|
+
* Launch `instance` into the spin under an optional `parentPath` (the nodding
|
|
55
|
+
* action's path, or `undefined` for a top-level nod). The single guarded entry to
|
|
56
|
+
* launching — `run` (top-level) and an action's own scoped `nod` both route here,
|
|
57
|
+
* so the "spin is open" check lives in one place.
|
|
58
|
+
*/
|
|
59
|
+
private nodInto;
|
|
60
|
+
/** Begin teardown: abort the signal (killing procs, unblocking waits, stopping daemons). */
|
|
61
|
+
cancel(): void;
|
|
62
|
+
/**
|
|
63
|
+
* Live-render the log to the console. Started automatically from the constructor
|
|
64
|
+
* — every spin drains, with no flag to disable and nothing for the caller to
|
|
65
|
+
* invoke (for now). A single {@link LogRenderer} applies grouping/indentation as
|
|
66
|
+
* entries stream by; its state spans the replayed history and live entries as one
|
|
67
|
+
* continuous stream. The subscription ends itself when the run tears down (the
|
|
68
|
+
* collector closes it), so this loop simply runs to completion.
|
|
69
|
+
*/
|
|
70
|
+
private drain;
|
|
71
|
+
/** Narrate a run-lifecycle milestone into this run's log (renders as a `[run]` line). */
|
|
72
|
+
private narrate;
|
|
73
|
+
/**
|
|
74
|
+
* Move `open → closing`: abort the signal (unwinding procs, waits, and
|
|
75
|
+
* daemons), narrate the cause once, and stop accepting new actions. Idempotent
|
|
76
|
+
* — only the first caller transitions; later triggers (a second failure, a
|
|
77
|
+
* `cancel()` during teardown) are no-ops. This is the *only* path to abort, so
|
|
78
|
+
* every teardown reason flows through one place.
|
|
79
|
+
*/
|
|
80
|
+
private beginClosing;
|
|
81
|
+
/**
|
|
82
|
+
* Record a genuine fault in the verdict. It does **not** tear the spin down — a
|
|
83
|
+
* failing action is data, and the spin keeps running (only Ctrl-C / cancel /
|
|
84
|
+
* completion / an uncaught fatal close it).
|
|
85
|
+
*/
|
|
86
|
+
private recordFailure;
|
|
87
|
+
/**
|
|
88
|
+
* A throw or rejection that escaped every action's own handling. Without a
|
|
89
|
+
* handler Node prints it and exits *immediately* — before the run can flush its
|
|
90
|
+
* log, which leaves a silent, empty log directory and no verdict. So catch it,
|
|
91
|
+
* log it, fold it into the verdict, and drive teardown so the log still flushes
|
|
92
|
+
* and the exit code reflects the fault — degrading a stray throw to a recorded
|
|
93
|
+
* failure instead of a hard crash. Removed at finalize, so it only governs
|
|
94
|
+
* while this run owns the process.
|
|
95
|
+
*/
|
|
96
|
+
private onFatal;
|
|
97
|
+
private launch;
|
|
98
|
+
/**
|
|
99
|
+
* Drives the run to `closed`. The loop re-checks `inFlight` because actions can
|
|
100
|
+
* be added (or daemons can settle on abort) while we await. A synchronous
|
|
101
|
+
* `.run(…)` from a settling action's lifecycle event lands before that action's
|
|
102
|
+
* `finally` removes it, so `inFlight` never spuriously hits 0 mid-handoff.
|
|
103
|
+
*/
|
|
104
|
+
private drive;
|
|
105
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { relative } from "node:path";
|
|
2
|
+
import { producerOfRef } from "../action/action.js";
|
|
3
|
+
import { LogsCollector, ScopedLogger } from "../../output/log/LogsCollector.js";
|
|
4
|
+
import { LogRenderer } from "../../output/log/LogRenderer.js";
|
|
5
|
+
import { Output } from "../../output/Output.js";
|
|
6
|
+
/** The entry script, relative to where node was invoked (so the log says what produced it). */
|
|
7
|
+
const scriptPath = () => {
|
|
8
|
+
const entry = process.argv[1];
|
|
9
|
+
return entry ? relative(process.cwd(), entry) : "(unknown)";
|
|
10
|
+
};
|
|
11
|
+
/** A constructed instance is an object carrying a `start` function. */
|
|
12
|
+
const isActionInstance = (value) => typeof value === "object" &&
|
|
13
|
+
value !== null &&
|
|
14
|
+
typeof value.start === "function";
|
|
15
|
+
/** An *uncalled* action: the callable `action(name).run(…)` returns before it's invoked. */
|
|
16
|
+
const isUncalledAction = (value) => typeof value === "function" && typeof value.actionName === "string";
|
|
17
|
+
/**
|
|
18
|
+
* Guard each launch argument: an action *instance* is required, not the action
|
|
19
|
+
* itself. Forgetting the trailing `()` is an easy slip (the callable has no
|
|
20
|
+
* `.start`), and silently treating it as something else would report a false
|
|
21
|
+
* green — so fail loudly with the fix.
|
|
22
|
+
*/
|
|
23
|
+
function assertInstance(value) {
|
|
24
|
+
if (isActionInstance(value))
|
|
25
|
+
return;
|
|
26
|
+
const hint = isUncalledAction(value)
|
|
27
|
+
? ` — that looks like an action that wasn't invoked; construct an instance by calling it: action("…").run(…)()`
|
|
28
|
+
: "";
|
|
29
|
+
throw new Error(`run() expects action instances; received ${typeof value}${hint}`);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A live spin over its own append-only log: constructing one launches the given
|
|
33
|
+
* actions in parallel under a single abort controller and drives them to a terminal
|
|
34
|
+
* {@link SpinResult}. Stop it with `.cancel()`, `await` its `.done` for the verdict.
|
|
35
|
+
*
|
|
36
|
+
* **A spin owns its world.** Each construction creates its *own* {@link LogsCollector}
|
|
37
|
+
* and {@link Output} — the run's log, folder, and snapshots — rather than sharing a
|
|
38
|
+
* process global, so runs don't bleed into each other and a fresh run can be created
|
|
39
|
+
* in a living process (sequential re-runs, in-process tests). Attach further actions
|
|
40
|
+
* to a running spin — including event-driven ones — via its `.run(…)` method.
|
|
41
|
+
*
|
|
42
|
+
* Each action runs against its own child logger (which headers and indents its
|
|
43
|
+
* lines into this run's log) and the spin's shared abort signal — both injected
|
|
44
|
+
* into its context, where the framework also binds a `proc` and the run's `output`
|
|
45
|
+
* so child processes stream into the right log and die on teardown. A **failing
|
|
46
|
+
* action never tears the spin down** — its `{ ok: false }` outcome is recorded in
|
|
47
|
+
* the verdict (and sets exit code 1) and the spin keeps running. Teardown to
|
|
48
|
+
* `closed` happens only on Ctrl-C, `.cancel()`, natural completion, or an uncaught
|
|
49
|
+
* fatal. The process-level hooks (SIGINT/uncaught handlers, `exitCode`) are owned by
|
|
50
|
+
* the run and cleaned at finalize, so they don't outlive it.
|
|
51
|
+
*/
|
|
52
|
+
export class SpinHost {
|
|
53
|
+
/** This run's append-only log — its own store, not a process global. */
|
|
54
|
+
logs = new LogsCollector();
|
|
55
|
+
/** This run's output subsystem (folder + snapshots + run-log writer), wired to {@link logs}. */
|
|
56
|
+
output = new Output(this.logs);
|
|
57
|
+
/** The spin's abort signal — for consumers that want to observe teardown. */
|
|
58
|
+
signal;
|
|
59
|
+
/** Settles once the spin reaches `closed`, carrying the terminal verdict. Never rejects. */
|
|
60
|
+
done;
|
|
61
|
+
controller = new AbortController();
|
|
62
|
+
// ── Lifecycle state ──────────────────────────────────────────────────────
|
|
63
|
+
// The single source of truth for "where in its life is this run". Only
|
|
64
|
+
// `beginClosing` and the finalize step below mutate it, and only forward.
|
|
65
|
+
// The log stays open through teardown and is closed once at finalize (after the
|
|
66
|
+
// last entry), so `streamLog` captures the whole run — including lines logged
|
|
67
|
+
// *during* teardown — and its run.jsonl is complete before `writeLog` reads it.
|
|
68
|
+
phase = "open";
|
|
69
|
+
/** The current lifecycle state — see {@link SpinState}. */
|
|
70
|
+
get state() {
|
|
71
|
+
return this.phase;
|
|
72
|
+
}
|
|
73
|
+
// Genuine failures (not teardown cascade). Frozen into the verdict at close.
|
|
74
|
+
failures = [];
|
|
75
|
+
// Every launched action's promise lives here until it settles; the drive loop
|
|
76
|
+
// empties this set. Daemons keep it non-empty until the controller aborts.
|
|
77
|
+
inFlight = new Set();
|
|
78
|
+
// Instances launched so far — used to verify a `.ref` dependency was launched
|
|
79
|
+
// before the action that consumes its handle.
|
|
80
|
+
launched = new WeakSet();
|
|
81
|
+
// The incremental crash-insurance stream; awaited at finalize before writeLog.
|
|
82
|
+
streaming;
|
|
83
|
+
// Ctrl-C tears the spin down gracefully through the lifecycle, like cancel().
|
|
84
|
+
onSigint = () => this.beginClosing("interrupted (SIGINT)");
|
|
85
|
+
onUncaught = this.onFatal("uncaughtException");
|
|
86
|
+
onUnhandled = this.onFatal("unhandledRejection");
|
|
87
|
+
constructor(...actions) {
|
|
88
|
+
// Validate eagerly so a bad argument throws cleanly before any work begins.
|
|
89
|
+
for (const instance of actions)
|
|
90
|
+
assertInstance(instance);
|
|
91
|
+
this.signal = this.controller.signal;
|
|
92
|
+
process.once("SIGINT", this.onSigint);
|
|
93
|
+
process.on("uncaughtException", this.onUncaught);
|
|
94
|
+
process.on("unhandledRejection", this.onUnhandled);
|
|
95
|
+
this.narrate(`run started · ${scriptPath()}`);
|
|
96
|
+
// Start streaming log entries to disk immediately — incremental writes survive
|
|
97
|
+
// hard kills where the final writeLog never runs. Kept so finalize can await it
|
|
98
|
+
// *before* writeLog rewrites the same files: otherwise a late flush from this
|
|
99
|
+
// stream lands past writeLog's truncation and the OS zero-fills the gap (a
|
|
100
|
+
// multi-MB NUL run in run.log).
|
|
101
|
+
this.streaming = this.output.runLog.stream(this.logs).catch(() => { });
|
|
102
|
+
// Live-render the log to the console for the whole run (replay + live). Always
|
|
103
|
+
// on — the run's terminal output, no flag or call required.
|
|
104
|
+
this.drain();
|
|
105
|
+
for (const instance of actions)
|
|
106
|
+
this.launch(instance, undefined);
|
|
107
|
+
// Launch before driving: the drive loop breaks on an empty `inFlight`, so it
|
|
108
|
+
// must not start until the initial actions have populated it.
|
|
109
|
+
this.done = this.drive();
|
|
110
|
+
// `done` resolves with the verdict and never rejects; guard anyway so a stray
|
|
111
|
+
// finalize error can't surface as an unhandled rejection.
|
|
112
|
+
this.done.catch(() => { });
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Launch more actions into this same spin — same controller, same log. Chainable.
|
|
116
|
+
*
|
|
117
|
+
* Throws if the spin is no longer `open`.
|
|
118
|
+
*/
|
|
119
|
+
run(...more) {
|
|
120
|
+
for (const instance of more)
|
|
121
|
+
this.nodInto(instance, undefined);
|
|
122
|
+
return this;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Launch `instance` into the spin under an optional `parentPath` (the nodding
|
|
126
|
+
* action's path, or `undefined` for a top-level nod). The single guarded entry to
|
|
127
|
+
* launching — `run` (top-level) and an action's own scoped `nod` both route here,
|
|
128
|
+
* so the "spin is open" check lives in one place.
|
|
129
|
+
*/
|
|
130
|
+
nodInto(instance, parentPath) {
|
|
131
|
+
if (this.phase !== "open") {
|
|
132
|
+
throw new Error(`spin.run(…) rejected: the spin is "${this.phase}", not "open". Launch actions before ` +
|
|
133
|
+
`teardown, or from a lifecycle event of an action that is still running.`);
|
|
134
|
+
}
|
|
135
|
+
this.launch(instance, parentPath);
|
|
136
|
+
}
|
|
137
|
+
/** Begin teardown: abort the signal (killing procs, unblocking waits, stopping daemons). */
|
|
138
|
+
cancel() {
|
|
139
|
+
this.beginClosing("cancelled");
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Live-render the log to the console. Started automatically from the constructor
|
|
143
|
+
* — every spin drains, with no flag to disable and nothing for the caller to
|
|
144
|
+
* invoke (for now). A single {@link LogRenderer} applies grouping/indentation as
|
|
145
|
+
* entries stream by; its state spans the replayed history and live entries as one
|
|
146
|
+
* continuous stream. The subscription ends itself when the run tears down (the
|
|
147
|
+
* collector closes it), so this loop simply runs to completion.
|
|
148
|
+
*/
|
|
149
|
+
drain() {
|
|
150
|
+
void (async () => {
|
|
151
|
+
const renderer = new LogRenderer();
|
|
152
|
+
for await (const entry of this.logs.subscribe({ replay: true }))
|
|
153
|
+
console.log(renderer.render(entry));
|
|
154
|
+
})().catch(() => { });
|
|
155
|
+
}
|
|
156
|
+
/** Narrate a run-lifecycle milestone into this run's log (renders as a `[run]` line). */
|
|
157
|
+
narrate(message) {
|
|
158
|
+
this.logs.append({ source: "run", level: "run", message });
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Move `open → closing`: abort the signal (unwinding procs, waits, and
|
|
162
|
+
* daemons), narrate the cause once, and stop accepting new actions. Idempotent
|
|
163
|
+
* — only the first caller transitions; later triggers (a second failure, a
|
|
164
|
+
* `cancel()` during teardown) are no-ops. This is the *only* path to abort, so
|
|
165
|
+
* every teardown reason flows through one place.
|
|
166
|
+
*/
|
|
167
|
+
beginClosing(reason) {
|
|
168
|
+
if (this.phase !== "open")
|
|
169
|
+
return;
|
|
170
|
+
this.phase = "closing";
|
|
171
|
+
this.narrate(`tearing down · ${reason}`);
|
|
172
|
+
this.controller.abort();
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Record a genuine fault in the verdict. It does **not** tear the spin down — a
|
|
176
|
+
* failing action is data, and the spin keeps running (only Ctrl-C / cancel /
|
|
177
|
+
* completion / an uncaught fatal close it).
|
|
178
|
+
*/
|
|
179
|
+
recordFailure(action, error) {
|
|
180
|
+
this.failures.push({ action, error });
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* A throw or rejection that escaped every action's own handling. Without a
|
|
184
|
+
* handler Node prints it and exits *immediately* — before the run can flush its
|
|
185
|
+
* log, which leaves a silent, empty log directory and no verdict. So catch it,
|
|
186
|
+
* log it, fold it into the verdict, and drive teardown so the log still flushes
|
|
187
|
+
* and the exit code reflects the fault — degrading a stray throw to a recorded
|
|
188
|
+
* failure instead of a hard crash. Removed at finalize, so it only governs
|
|
189
|
+
* while this run owns the process.
|
|
190
|
+
*/
|
|
191
|
+
onFatal(kind) {
|
|
192
|
+
return (error) => {
|
|
193
|
+
this.logs.append({
|
|
194
|
+
source: kind,
|
|
195
|
+
level: "error",
|
|
196
|
+
message: error instanceof Error ? (error.stack ?? error.message) : String(error),
|
|
197
|
+
});
|
|
198
|
+
// Genuine fault vs. teardown fallout: only one that surfaces *before* the
|
|
199
|
+
// signal aborts is the spin's own (mirrors `launch`'s cascade rule); a throw
|
|
200
|
+
// during unwind is logged but doesn't pollute the verdict. Either way tear
|
|
201
|
+
// down — unlike an action's own failure, an *uncaught* fatal leaves the
|
|
202
|
+
// process state undefined, so we always finish and flush.
|
|
203
|
+
if (!this.controller.signal.aborted)
|
|
204
|
+
this.failures.push({ action: kind, error });
|
|
205
|
+
this.beginClosing(kind);
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
launch(instance, parentPath) {
|
|
209
|
+
// A consumer built with another action's `.ref` (e.g. `chromePage(driver.ref)`)
|
|
210
|
+
// must be launched *after* that producer — otherwise it awaits a handle that
|
|
211
|
+
// never arrives and the spin hangs silently. Catch it and say how to fix it.
|
|
212
|
+
for (const arg of instance.args) {
|
|
213
|
+
const producer = producerOfRef(arg);
|
|
214
|
+
if (producer && !this.launched.has(producer)) {
|
|
215
|
+
throw new Error(`${instance.name} was launched before its dependency ${producer.name}: it ` +
|
|
216
|
+
`consumes ${producer.name}'s .ref, so nod ${producer.name} first.`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
this.launched.add(instance);
|
|
220
|
+
// The action's path: its name for a top-level nod, or `<parent> › <name>` when a
|
|
221
|
+
// parent action nodded it. Top-level actions keep this run's logger (output
|
|
222
|
+
// unchanged); a child gets a ScopedLogger so its every line — and its `proc`'s,
|
|
223
|
+
// and any grandchildren's — is prefixed with this path. Its own `nod` carries
|
|
224
|
+
// this path down, so scoping composes automatically.
|
|
225
|
+
const path = parentPath ? `${parentPath} › ${instance.name}` : instance.name;
|
|
226
|
+
const scoped = parentPath === undefined ? this.logs : new ScopedLogger(this.logs, path);
|
|
227
|
+
const nod = (child) => {
|
|
228
|
+
this.nodInto(child, path);
|
|
229
|
+
return child;
|
|
230
|
+
};
|
|
231
|
+
this.narrate(`launch ${path}`);
|
|
232
|
+
// The action logs into this run's shared store (entries carry their `source`;
|
|
233
|
+
// grouping is applied at render time) and gets the spin's signal directly; the
|
|
234
|
+
// framework injects a `proc` and the run's `output` bound to both, so there's no
|
|
235
|
+
// ambient context. `start()` resolves with the action's Outcome — it never
|
|
236
|
+
// rejects for the action's own failure — so a failure is handled here as data.
|
|
237
|
+
const record = (error) => {
|
|
238
|
+
// Always record the fault in the action's own log, under its path.
|
|
239
|
+
this.logs.append({
|
|
240
|
+
source: path,
|
|
241
|
+
level: "error",
|
|
242
|
+
message: error instanceof Error ? (error.stack ?? error.message) : String(error),
|
|
243
|
+
});
|
|
244
|
+
// Genuine failure vs. teardown fallout: if the signal was already aborted
|
|
245
|
+
// when this surfaced, the failure is almost certainly the abort killing the
|
|
246
|
+
// action (a cascade), not its own fault — so it must not pollute the verdict.
|
|
247
|
+
if (!this.controller.signal.aborted)
|
|
248
|
+
this.recordFailure(path, error);
|
|
249
|
+
};
|
|
250
|
+
const promise = instance
|
|
251
|
+
.start({ logs: scoped, signal: this.controller.signal, nod, output: this.output })
|
|
252
|
+
.then((outcome) => {
|
|
253
|
+
if (!outcome.ok)
|
|
254
|
+
record(outcome.error);
|
|
255
|
+
})
|
|
256
|
+
// Defensive: `start()` shouldn't reject, but if the framework itself throws,
|
|
257
|
+
// treat it as a fault rather than losing it to an unhandled rejection.
|
|
258
|
+
.catch(record);
|
|
259
|
+
this.inFlight.add(promise);
|
|
260
|
+
void promise.finally(() => this.inFlight.delete(promise));
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Drives the run to `closed`. The loop re-checks `inFlight` because actions can
|
|
264
|
+
* be added (or daemons can settle on abort) while we await. A synchronous
|
|
265
|
+
* `.run(…)` from a settling action's lifecycle event lands before that action's
|
|
266
|
+
* `finally` removes it, so `inFlight` never spuriously hits 0 mid-handoff.
|
|
267
|
+
*/
|
|
268
|
+
async drive() {
|
|
269
|
+
for (;;) {
|
|
270
|
+
if (this.inFlight.size === 0) {
|
|
271
|
+
// Nothing left to run. If still open, every action finished on its own —
|
|
272
|
+
// natural completion; tear down so daemons/listeners unwind uniformly.
|
|
273
|
+
// If already closing, teardown is simply complete.
|
|
274
|
+
if (this.phase === "open")
|
|
275
|
+
this.beginClosing("completed");
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
await Promise.allSettled([...this.inFlight]);
|
|
279
|
+
}
|
|
280
|
+
// ── Finalize (reached exactly once) ──────────────────────────────────────
|
|
281
|
+
this.phase = "closed";
|
|
282
|
+
process.off("SIGINT", this.onSigint);
|
|
283
|
+
process.off("uncaughtException", this.onUncaught);
|
|
284
|
+
process.off("unhandledRejection", this.onUnhandled);
|
|
285
|
+
this.narrate("finished");
|
|
286
|
+
// Close the log now (after the last entry) so `streamLog` drains and finishes
|
|
287
|
+
// writing the complete run.jsonl, then wait for it to fully close its files —
|
|
288
|
+
// both so its last flush can't corrupt run.log later, and so run.jsonl is done
|
|
289
|
+
// before `writeLog` streams it into the final collapsed run.log.
|
|
290
|
+
this.logs.close();
|
|
291
|
+
await this.streaming;
|
|
292
|
+
const file = await this.output.runLog.write();
|
|
293
|
+
// Direct to the terminal — the file's already written, so this line isn't in it.
|
|
294
|
+
console.log(LogRenderer.marker("run", `log → ${file}`));
|
|
295
|
+
const result = { ok: this.failures.length === 0, failures: this.failures };
|
|
296
|
+
// One process = one run = one verdict; reflect pass/fail in the exit code so
|
|
297
|
+
// shells and CI see it without parsing the log. Only set it on failure, so a
|
|
298
|
+
// code a failing action's own handler may have set isn't clobbered to 0.
|
|
299
|
+
if (!result.ok)
|
|
300
|
+
process.exitCode = 1;
|
|
301
|
+
return result;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { SpinBody } from "./types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Runs a linear orchestration. You pass a plain (async) function; omkit hosts it
|
|
4
|
+
* in a single in-flight action and hands it a {@link Nod}. Because that host
|
|
5
|
+
* stays in-flight while your body `await`s, the spin never idles shut between
|
|
6
|
+
* steps — so you write `await` / `if` control flow instead of nested callbacks.
|
|
7
|
+
* When the body returns, the daemons it nodded in keep the spin alive until
|
|
8
|
+
* teardown.
|
|
9
|
+
*
|
|
10
|
+
* A failing action **never throws into the body** — `await nod(x).done` yields an
|
|
11
|
+
* {@link import("./action.ts").Outcome} you inspect, and the spin keeps going
|
|
12
|
+
* (the failure is recorded in the verdict and sets exit code 1):
|
|
13
|
+
*
|
|
14
|
+
* spin({ drain: false }, async ({ nod }) => {
|
|
15
|
+
* const ans = await nod(prompt({ … })).done; // Outcome — never throws
|
|
16
|
+
* if (ans.ok && ans.value === "yes") await nod(test).done;
|
|
17
|
+
* nod(devServer); // fire-and-forget daemon
|
|
18
|
+
* const chrome = nod(chromedriver({ … }));
|
|
19
|
+
* nod(chromePage(chrome.ref)); // data deps via .ref
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* Auto-drains by default;
|
|
23
|
+
*/
|
|
24
|
+
export declare function spin(body: SpinBody): void;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { action } from "../action/action.js";
|
|
2
|
+
import { SpinHost } from "./SpinHost.js";
|
|
3
|
+
/**
|
|
4
|
+
* Runs a linear orchestration. You pass a plain (async) function; omkit hosts it
|
|
5
|
+
* in a single in-flight action and hands it a {@link Nod}. Because that host
|
|
6
|
+
* stays in-flight while your body `await`s, the spin never idles shut between
|
|
7
|
+
* steps — so you write `await` / `if` control flow instead of nested callbacks.
|
|
8
|
+
* When the body returns, the daemons it nodded in keep the spin alive until
|
|
9
|
+
* teardown.
|
|
10
|
+
*
|
|
11
|
+
* A failing action **never throws into the body** — `await nod(x).done` yields an
|
|
12
|
+
* {@link import("./action.ts").Outcome} you inspect, and the spin keeps going
|
|
13
|
+
* (the failure is recorded in the verdict and sets exit code 1):
|
|
14
|
+
*
|
|
15
|
+
* spin({ drain: false }, async ({ nod }) => {
|
|
16
|
+
* const ans = await nod(prompt({ … })).done; // Outcome — never throws
|
|
17
|
+
* if (ans.ok && ans.value === "yes") await nod(test).done;
|
|
18
|
+
* nod(devServer); // fire-and-forget daemon
|
|
19
|
+
* const chrome = nod(chromedriver({ … }));
|
|
20
|
+
* nod(chromePage(chrome.ref)); // data deps via .ref
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* Auto-drains by default;
|
|
24
|
+
*/
|
|
25
|
+
export function spin(body) {
|
|
26
|
+
// `run(...)` below assigns `host` synchronously, before the action's async body
|
|
27
|
+
// ever runs — so the closures here capture the spin safely.
|
|
28
|
+
let hostRun;
|
|
29
|
+
const hostAction = action("omkit:Spin").run(async (ctx) => {
|
|
30
|
+
const nod = (instance) => {
|
|
31
|
+
hostRun.run(instance);
|
|
32
|
+
return instance;
|
|
33
|
+
};
|
|
34
|
+
await body({
|
|
35
|
+
nod,
|
|
36
|
+
// TODO: maybe add a reason for cancel ???
|
|
37
|
+
cancel: () => hostRun.cancel(),
|
|
38
|
+
signal: ctx.signal,
|
|
39
|
+
// The host action runs inside the SpinHost, so its ctx already carries the
|
|
40
|
+
// run's output subsystem — surface the folder and a snapshot convenience to
|
|
41
|
+
// the body from there rather than reaching for a module singleton.
|
|
42
|
+
artifactsFolder: ctx.artifactsFolder,
|
|
43
|
+
snapshot: (name, value) => ctx.output.snapshots.snapshot(name, value),
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
const mainSpinAction = hostAction();
|
|
47
|
+
hostRun = new SpinHost(mainSpinAction);
|
|
48
|
+
// The body is the orchestrator, not a peer action: if it throws, tear the whole
|
|
49
|
+
// spin down. Regular action failures only get recorded (they don't stop the
|
|
50
|
+
// spin), but the orchestrator crashing must end the run — otherwise any daemon
|
|
51
|
+
// it already nodded keeps the process alive forever on a pipeline bug.
|
|
52
|
+
void mainSpinAction.done.then((outcome) => {
|
|
53
|
+
if (!outcome.ok)
|
|
54
|
+
hostRun.cancel();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export type { Nod } from "../action/types.ts";
|
|
2
|
+
import type { Nod } from "../action/types.ts";
|
|
3
|
+
/** What a {@link spin} body receives. */
|
|
4
|
+
export interface SpinContext {
|
|
5
|
+
/** Launch an action into the spin; returns the instance for awaiting/chaining. */
|
|
6
|
+
readonly nod: Nod;
|
|
7
|
+
/**
|
|
8
|
+
* Tear the spin down (abort the signal, stopping daemons). Use it to end a spin
|
|
9
|
+
* whose work is finished but which is held open by a daemon — e.g. once a
|
|
10
|
+
* one-shot build completes while a watcher is still running.
|
|
11
|
+
*/
|
|
12
|
+
readonly cancel: () => void;
|
|
13
|
+
/** The spin's abort signal — honor it to stop early. */
|
|
14
|
+
readonly signal: AbortSignal;
|
|
15
|
+
/**
|
|
16
|
+
* Absolute path to this spin's output folder (`logs/<name>/<date>/<time>/`),
|
|
17
|
+
* created up front. Hand it to actions (or use `ctx.artifactsFolder` inside
|
|
18
|
+
* one) to write artifacts beside `run.log`.
|
|
19
|
+
*/
|
|
20
|
+
readonly artifactsFolder: string;
|
|
21
|
+
/**
|
|
22
|
+
* Capture a JSON snapshot into this run's output folder and drop a `[snapshot]`
|
|
23
|
+
* line on the timeline — for run-level inputs the log should narrate (a build
|
|
24
|
+
* config, resolved options). Resolves with the snapshot's relative path. The
|
|
25
|
+
* run-scoped counterpart to the action `ctx.output.snapshots`.
|
|
26
|
+
*/
|
|
27
|
+
readonly snapshot: (name: string, value: unknown) => Promise<string>;
|
|
28
|
+
}
|
|
29
|
+
/** The body of a {@link spin}: any (async) function — it isn't named or wrapped by you. */
|
|
30
|
+
export type SpinBody = (ctx: SpinContext) => void | Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* A single action's failure, captured for the spin's verdict. Cascade failures —
|
|
33
|
+
* actions that settled `{ ok: false }` only because teardown aborted them — are
|
|
34
|
+
* deliberately excluded (see `launch`'s outcome handling), so this records
|
|
35
|
+
* genuine faults, not fallout.
|
|
36
|
+
*/
|
|
37
|
+
export interface ActionFailure {
|
|
38
|
+
/** The failing action's name. */
|
|
39
|
+
readonly action: string;
|
|
40
|
+
/** Whatever it failed with (the Outcome's `error`). */
|
|
41
|
+
readonly error: unknown;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The terminal verdict of a spin: did everything that mattered succeed, and if
|
|
45
|
+
* not, what failed. {@link SpinHost.done} resolves (never rejects) with this, so a
|
|
46
|
+
* single `await` yields the outcome instead of forcing a try/catch on awaiters.
|
|
47
|
+
* A failing action is *recorded* here (so `ok` is false and the exit code is 1)
|
|
48
|
+
* but does **not** tear the spin down — see {@link SpinHost}.
|
|
49
|
+
*/
|
|
50
|
+
export interface SpinResult {
|
|
51
|
+
/** True when no genuine failure was recorded. */
|
|
52
|
+
readonly ok: boolean;
|
|
53
|
+
/** The genuine failures, in the order they surfaced. Empty when `ok`. */
|
|
54
|
+
readonly failures: readonly ActionFailure[];
|
|
55
|
+
}
|
|
56
|
+
export type SpinState = "open" | "closing" | "closed";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Logger } from "./log/LogsCollector.ts";
|
|
2
|
+
import { RunFolder } from "./folder/RunFolder.ts";
|
|
3
|
+
import { SnapshotStore } from "./snapshot/SnapshotStore.ts";
|
|
4
|
+
import { RunLog } from "./log/RunLog.ts";
|
|
5
|
+
/**
|
|
6
|
+
* The run's output subsystem — the composition root that owns the per-run folder and
|
|
7
|
+
* the writers layered on it, and hands them to the rest of the process.
|
|
8
|
+
*
|
|
9
|
+
* Each run owns one of these: its {@link SpinHost} constructs an `Output` over the
|
|
10
|
+
* run's log and threads it to actions as `ctx.output`. Everything that was
|
|
11
|
+
* module-global in the old `output.ts` (the folder path, the mkdir latch, the
|
|
12
|
+
* snapshot sequence) now lives inside these three members, reachable as
|
|
13
|
+
* `output.folder`, `output.snapshots`, `output.runLog` — so callers reach for a named
|
|
14
|
+
* layer instead of a free function, and the shared state has one owner per run.
|
|
15
|
+
*/
|
|
16
|
+
export declare class Output {
|
|
17
|
+
/** The per-run directory and artifact drop. */
|
|
18
|
+
readonly folder: RunFolder;
|
|
19
|
+
/** Sequenced JSON/text snapshot files + `[snapshot]` timeline lines. */
|
|
20
|
+
readonly snapshots: SnapshotStore;
|
|
21
|
+
/** The `run.jsonl` / `run.log` writer. */
|
|
22
|
+
readonly runLog: RunLog;
|
|
23
|
+
constructor(logger: Logger);
|
|
24
|
+
}
|