@operad-io/engine 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +11 -2
- package/config.schema.json +188 -0
- package/keys.schema.json +12 -0
- package/package.json +22 -4
- package/src/config/config.ts +627 -0
- package/src/config/index.ts +1 -0
- package/src/flow/define-flow.ts +57 -0
- package/src/flow/index.ts +5 -0
- package/src/flow/load.ts +41 -0
- package/src/flow/types.ts +107 -0
- package/src/flow/validate.ts +296 -0
- package/src/http/address.ts +142 -0
- package/src/http/index.ts +25 -0
- package/src/http/link.ts +20 -0
- package/src/http/server.ts +920 -0
- package/src/http/token.ts +90 -0
- package/src/index.ts +18 -0
- package/src/kernel/decide.ts +689 -0
- package/src/kernel/index.ts +3 -0
- package/src/kernel/state.ts +275 -0
- package/src/kernel/types.ts +366 -0
- package/src/log/errors.ts +77 -0
- package/src/log/facts.ts +50 -0
- package/src/log/index.ts +6 -0
- package/src/log/json-value.ts +67 -0
- package/src/log/open-log.ts +17 -0
- package/src/log/schema.ts +5 -0
- package/src/log/secret.ts +30 -0
- package/src/log/sqlite.ts +1011 -0
- package/src/log/types.ts +230 -0
- package/src/loop/code-watch.ts +486 -0
- package/src/loop/index.ts +3 -0
- package/src/loop/older-code.ts +58 -0
- package/src/loop/serve.ts +483 -0
- package/src/markdown.ts +451 -0
- package/src/notify/index.ts +10 -0
- package/src/notify/notify.ts +256 -0
- package/src/platform/file-lock.ts +385 -0
- package/src/platform/index.ts +13 -0
- package/src/platform/load.ts +18 -0
- package/src/platform/process-group.ts +675 -0
- package/src/platform/process-watch.ts +152 -0
- package/src/platform/sqlite-open.ts +104 -0
- package/src/platform/step-reap.ts +668 -0
- package/src/platform/watch.ts +158 -0
- package/src/platform/worker-reports.ts +34 -0
- package/src/plugin/action-schema.ts +550 -0
- package/src/plugin/declared-flows.ts +74 -0
- package/src/plugin/define-plugin.ts +12 -0
- package/src/plugin/errors.ts +73 -0
- package/src/plugin/filters.ts +46 -0
- package/src/plugin/harness.ts +50 -0
- package/src/plugin/home.ts +13 -0
- package/src/plugin/index.ts +65 -0
- package/src/plugin/install.ts +268 -0
- package/src/plugin/keys.ts +63 -0
- package/src/plugin/load.ts +256 -0
- package/src/plugin/logger.ts +30 -0
- package/src/plugin/object-facts.ts +132 -0
- package/src/plugin/open-store.ts +32 -0
- package/src/plugin/paging.ts +133 -0
- package/src/plugin/registry.ts +1786 -0
- package/src/plugin/secrets.ts +141 -0
- package/src/plugin/semver.ts +110 -0
- package/src/plugin/settings.ts +64 -0
- package/src/plugin/sqlite-store.ts +756 -0
- package/src/plugin/store.ts +318 -0
- package/src/plugin/types.ts +1243 -0
- package/src/plugin/usage.ts +157 -0
- package/src/plugin/validate.ts +1028 -0
- package/src/runner/answer.ts +156 -0
- package/src/runner/ask.ts +483 -0
- package/src/runner/cancel.ts +51 -0
- package/src/runner/errors.ts +20 -0
- package/src/runner/grants.ts +92 -0
- package/src/runner/index.ts +33 -0
- package/src/runner/limits.ts +403 -0
- package/src/runner/lock.ts +140 -0
- package/src/runner/runner.ts +1175 -0
- package/src/runner/service.ts +184 -0
- package/src/runner/step-worker.ts +303 -0
- package/src/testing/clock.ts +67 -0
- package/src/testing/index.ts +90 -0
- package/src/testing/types.ts +116 -0
- package/src/testing/world.ts +369 -0
- package/src/trigger/cron.ts +193 -0
- package/src/trigger/index.ts +32 -0
- package/src/trigger/kernel.ts +1221 -0
- package/src/trigger/rules.ts +300 -0
- package/src/trigger/store.ts +233 -0
- package/src/trigger/types.ts +156 -0
- package/src/util.ts +50 -0
- package/src/views/history.ts +634 -0
- package/src/views/index.ts +7 -0
- package/src/views/pending.ts +209 -0
- package/src/views/presentation.ts +2609 -0
- package/src/views/running.ts +255 -0
- package/src/views/settings.ts +452 -0
- package/src/views/types.ts +72 -0
- package/src/views/uploads.ts +228 -0
- package/triggers.schema.json +48 -0
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The notification hook. When an object starts waiting for a person, `serve`
|
|
3
|
+
* runs the configured command once for that wait.
|
|
4
|
+
*
|
|
5
|
+
* One notification is identified by `notify:<runId>:<waitId>`: the run, and the
|
|
6
|
+
* wait's own id, which names the step and its visit (`ask:2` is the second time
|
|
7
|
+
* the run reached `ask`). A run that waits at the same step again is a new wait
|
|
8
|
+
* and notifies again; a restart of `serve` while the same wait is open is not.
|
|
9
|
+
*
|
|
10
|
+
* The notification is recorded as one global fact of kind `notified`, written
|
|
11
|
+
* with that key as its unique key, after the command has ended. A crash between
|
|
12
|
+
* the command and the fact therefore causes at most one extra notification when
|
|
13
|
+
* `serve` starts again; a crash before the command loses nothing, because
|
|
14
|
+
* nothing was recorded and the next pass sends it. A command that fails or
|
|
15
|
+
* times out is recorded too and is not retried.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { NotifyConfig } from "../config/config.ts";
|
|
19
|
+
import { objectLink } from "../http/link.ts";
|
|
20
|
+
import type { LogBackend } from "../log/types.ts";
|
|
21
|
+
import { messageOf } from "../plugin/errors.ts";
|
|
22
|
+
import { runLine } from "../platform/process-group.ts";
|
|
23
|
+
import { parseObjectKey, readState } from "../runner/service.ts";
|
|
24
|
+
|
|
25
|
+
/** The fact kind a recorded notification has. */
|
|
26
|
+
export const NOTIFIED_FACT = "notified";
|
|
27
|
+
|
|
28
|
+
/** How long the command may run. */
|
|
29
|
+
export const NOTIFY_TIMEOUT_MS = 30_000;
|
|
30
|
+
|
|
31
|
+
/** How many lines of the command's output a failure report keeps. */
|
|
32
|
+
const TAIL_LINES = 5;
|
|
33
|
+
|
|
34
|
+
/** What one run of the command did. */
|
|
35
|
+
export interface HookOutcome {
|
|
36
|
+
readonly exitCode: number | null;
|
|
37
|
+
readonly timedOut: boolean;
|
|
38
|
+
readonly cancelled: boolean;
|
|
39
|
+
readonly error: string | undefined;
|
|
40
|
+
readonly tail: readonly string[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Runs the command; a test replaces it to count and to crash. */
|
|
44
|
+
export type HookRunner = (
|
|
45
|
+
line: string,
|
|
46
|
+
env: Readonly<Record<string, string>>,
|
|
47
|
+
signal: AbortSignal,
|
|
48
|
+
) => Promise<HookOutcome>;
|
|
49
|
+
|
|
50
|
+
export interface NotifierOptions {
|
|
51
|
+
readonly home: string;
|
|
52
|
+
readonly config: NotifyConfig;
|
|
53
|
+
readonly log: LogBackend;
|
|
54
|
+
/** The title of an object, for `OPERAD_TITLE`; failing means the id is used. */
|
|
55
|
+
readonly titleOf?: ((type: string, id: string) => Promise<string>) | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* True when the object's plugin answers its wait itself; no notice is sent
|
|
58
|
+
* for it, and none is recorded, so a wait that stays unanswered is noticed
|
|
59
|
+
* by a later scan. A failing hook means false.
|
|
60
|
+
*/
|
|
61
|
+
readonly answeredAutomatically?:
|
|
62
|
+
| ((object: { readonly type: string; readonly id: string }) => Promise<boolean>)
|
|
63
|
+
| undefined;
|
|
64
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
65
|
+
readonly run?: HookRunner | undefined;
|
|
66
|
+
/** Replaces the write of the `notified` fact; a test makes it fail. */
|
|
67
|
+
readonly record?:
|
|
68
|
+
| ((key: string, payload: Record<string, string | number | boolean | null>) => Promise<void>)
|
|
69
|
+
| undefined;
|
|
70
|
+
readonly timeoutMs?: number | undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The key that identifies one notification. */
|
|
74
|
+
export function notificationKey(runId: string, waitId: string): string {
|
|
75
|
+
return `notify:${runId}:${waitId}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The default runner: `sh -c` in the home, in a process group of its own. */
|
|
79
|
+
export function shellHookRunner(home: string, timeoutMs: number): HookRunner {
|
|
80
|
+
return async (line, env, signal) => {
|
|
81
|
+
const outcome = await runLine({
|
|
82
|
+
line,
|
|
83
|
+
cwd: home,
|
|
84
|
+
env,
|
|
85
|
+
timeoutMs,
|
|
86
|
+
signal,
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
exitCode: outcome.exitCode,
|
|
90
|
+
timedOut: outcome.timedOut,
|
|
91
|
+
cancelled: outcome.cancelled,
|
|
92
|
+
error: outcome.spawnError,
|
|
93
|
+
tail: outcome.tail,
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function describeFailure(outcome: HookOutcome): string {
|
|
99
|
+
const how = outcome.timedOut
|
|
100
|
+
? "timed out"
|
|
101
|
+
: outcome.error !== undefined
|
|
102
|
+
? `could not start: ${outcome.error}`
|
|
103
|
+
: `exited ${outcome.exitCode ?? "without a code"}`;
|
|
104
|
+
const tail = outcome.tail.slice(-TAIL_LINES).join("\n");
|
|
105
|
+
return tail.length === 0 ? how : `${how}\n${tail}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Finds the waits that need a notification and runs the command for each. */
|
|
109
|
+
export class Notifier {
|
|
110
|
+
private readonly options: NotifierOptions;
|
|
111
|
+
private readonly run: HookRunner;
|
|
112
|
+
private readonly controller = new AbortController();
|
|
113
|
+
private recorded: Set<string> | undefined;
|
|
114
|
+
private running: Promise<void> | undefined;
|
|
115
|
+
|
|
116
|
+
constructor(options: NotifierOptions) {
|
|
117
|
+
this.options = options;
|
|
118
|
+
this.run =
|
|
119
|
+
options.run ??
|
|
120
|
+
shellHookRunner(options.home, options.timeoutMs ?? NOTIFY_TIMEOUT_MS);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private get enabled(): boolean {
|
|
124
|
+
return (
|
|
125
|
+
this.options.config.command !== null &&
|
|
126
|
+
this.options.config.on.includes("waiting")
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private log(message: string): void {
|
|
131
|
+
this.options.onLog?.(message);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private async loadRecorded(): Promise<Set<string>> {
|
|
135
|
+
if (this.recorded !== undefined) return this.recorded;
|
|
136
|
+
const keys = new Set<string>();
|
|
137
|
+
for await (const fact of this.options.log.readGlobal()) {
|
|
138
|
+
if (fact.kind !== NOTIFIED_FACT) continue;
|
|
139
|
+
const payload = fact.payload;
|
|
140
|
+
if (
|
|
141
|
+
typeof payload === "object" &&
|
|
142
|
+
payload !== null &&
|
|
143
|
+
!Array.isArray(payload) &&
|
|
144
|
+
typeof payload.key === "string"
|
|
145
|
+
) {
|
|
146
|
+
keys.add(payload.key);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
this.recorded = keys;
|
|
150
|
+
return keys;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* One scan: every wait without a recorded notification gets its command.
|
|
155
|
+
* A scan that is still running when the next is asked for is not repeated.
|
|
156
|
+
*/
|
|
157
|
+
pass(): Promise<void> {
|
|
158
|
+
if (!this.enabled) return Promise.resolve();
|
|
159
|
+
if (this.running !== undefined) return this.running;
|
|
160
|
+
const current = this.scan().finally(() => {
|
|
161
|
+
this.running = undefined;
|
|
162
|
+
});
|
|
163
|
+
this.running = current;
|
|
164
|
+
return current;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Stops commands that are running (they are not recorded) and waits for the scan. */
|
|
168
|
+
async stop(): Promise<void> {
|
|
169
|
+
this.controller.abort();
|
|
170
|
+
await this.running?.catch(() => undefined);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private async scan(): Promise<void> {
|
|
174
|
+
const recorded = await this.loadRecorded();
|
|
175
|
+
const runs = await this.options.log.runs({ active: true });
|
|
176
|
+
for (const run of runs) {
|
|
177
|
+
if (this.controller.signal.aborted) return;
|
|
178
|
+
const object = parseObjectKey(run.object);
|
|
179
|
+
if (object === undefined) continue;
|
|
180
|
+
let state;
|
|
181
|
+
try {
|
|
182
|
+
state = await readState(this.options.log, run.runId);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
this.log(`notify: run "${run.runId}": ${messageOf(error)}`);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (state.status !== "waiting_person" || state.wait === null) continue;
|
|
188
|
+
const key = notificationKey(run.runId, state.wait.id);
|
|
189
|
+
if (recorded.has(key)) continue;
|
|
190
|
+
try {
|
|
191
|
+
if ((await this.options.answeredAutomatically?.(object)) === true) continue;
|
|
192
|
+
} catch {
|
|
193
|
+
// A hook that fails answers nothing: the person is told.
|
|
194
|
+
}
|
|
195
|
+
await this.notify(key, run.runId, state.wait.id, object, state.wait.prompt);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private async notify(
|
|
200
|
+
key: string,
|
|
201
|
+
runId: string,
|
|
202
|
+
waitId: string,
|
|
203
|
+
object: { readonly type: string; readonly id: string },
|
|
204
|
+
prompt: string,
|
|
205
|
+
): Promise<void> {
|
|
206
|
+
const command = this.options.config.command;
|
|
207
|
+
if (command === null) return;
|
|
208
|
+
const id = `${object.type}:${object.id}`;
|
|
209
|
+
let title = object.id;
|
|
210
|
+
try {
|
|
211
|
+
title = (await this.options.titleOf?.(object.type, object.id)) ?? title;
|
|
212
|
+
} catch {
|
|
213
|
+
// The id is a title good enough for a notice.
|
|
214
|
+
}
|
|
215
|
+
const outcome = await this.run(
|
|
216
|
+
command,
|
|
217
|
+
{
|
|
218
|
+
OPERAD_ID: id,
|
|
219
|
+
OPERAD_TITLE: title,
|
|
220
|
+
OPERAD_REASON: prompt,
|
|
221
|
+
OPERAD_LINK: objectLink(object.type, object.id),
|
|
222
|
+
},
|
|
223
|
+
this.controller.signal,
|
|
224
|
+
);
|
|
225
|
+
// A stop is not a failure and not a notification: the next `serve` sends it.
|
|
226
|
+
if (outcome.cancelled) return;
|
|
227
|
+
const ok =
|
|
228
|
+
outcome.exitCode === 0 && !outcome.timedOut && outcome.error === undefined;
|
|
229
|
+
if (!ok) {
|
|
230
|
+
this.log(`notify: the command for ${id} ${describeFailure(outcome)}`);
|
|
231
|
+
}
|
|
232
|
+
const payload = {
|
|
233
|
+
key,
|
|
234
|
+
runId,
|
|
235
|
+
waitId,
|
|
236
|
+
object: id,
|
|
237
|
+
ok,
|
|
238
|
+
exitCode: outcome.exitCode,
|
|
239
|
+
timedOut: outcome.timedOut,
|
|
240
|
+
};
|
|
241
|
+
try {
|
|
242
|
+
if (this.options.record !== undefined) {
|
|
243
|
+
await this.options.record(key, payload);
|
|
244
|
+
} else {
|
|
245
|
+
await this.options.log.appendGlobal(
|
|
246
|
+
{ kind: NOTIFIED_FACT, payload, cause: runId },
|
|
247
|
+
key,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
this.recorded?.add(key);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
// Not recorded: the next `serve` sends this one again, once.
|
|
253
|
+
this.log(`notify: could not record the notice for ${id}: ${messageOf(error)}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File locks. Two kinds live here, and a plugin picks one instead of writing a
|
|
3
|
+
* third:
|
|
4
|
+
*
|
|
5
|
+
* - `withFileLock`: an advisory `flock(2)` on an open file, released by the
|
|
6
|
+
* kernel when the process dies. For a short critical section.
|
|
7
|
+
* - `withLockFile`: a lock file made with link/rename and a nonce, whose record
|
|
8
|
+
* names the holder's pid so a dead holder can be taken over. For a section
|
|
9
|
+
* that spans awaits and processes.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { dlopen, FFIType } from "bun:ffi";
|
|
13
|
+
import { randomBytes } from "node:crypto";
|
|
14
|
+
import {
|
|
15
|
+
closeSync,
|
|
16
|
+
linkSync,
|
|
17
|
+
mkdirSync,
|
|
18
|
+
openSync,
|
|
19
|
+
readFileSync,
|
|
20
|
+
renameSync,
|
|
21
|
+
statSync,
|
|
22
|
+
unlinkSync,
|
|
23
|
+
writeFileSync,
|
|
24
|
+
} from "node:fs";
|
|
25
|
+
import { dirname } from "node:path";
|
|
26
|
+
import { waitForChange } from "./watch.ts";
|
|
27
|
+
|
|
28
|
+
const LOCK_EX = 2;
|
|
29
|
+
|
|
30
|
+
type Flock = (fd: number, operation: number) => number;
|
|
31
|
+
|
|
32
|
+
let flockFunction: Flock | undefined;
|
|
33
|
+
|
|
34
|
+
function loadFlock(): Flock {
|
|
35
|
+
if (flockFunction) return flockFunction;
|
|
36
|
+
|
|
37
|
+
const candidates =
|
|
38
|
+
process.platform === "darwin"
|
|
39
|
+
? ["libc.dylib"]
|
|
40
|
+
: process.platform === "linux"
|
|
41
|
+
? ["libc.so.6", "libc.so", `libc.musl-${process.arch}.so.1`]
|
|
42
|
+
: [];
|
|
43
|
+
|
|
44
|
+
for (const library of candidates) {
|
|
45
|
+
try {
|
|
46
|
+
const { symbols } = dlopen(library, {
|
|
47
|
+
flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
|
|
48
|
+
});
|
|
49
|
+
const symbol = symbols.flock;
|
|
50
|
+
if (symbol) {
|
|
51
|
+
flockFunction = (fd, operation) => symbol(fd, operation);
|
|
52
|
+
return flockFunction;
|
|
53
|
+
}
|
|
54
|
+
} catch {
|
|
55
|
+
// Try the next library name.
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
throw new Error(
|
|
60
|
+
`this needs flock(2), which is not available on ${process.platform}`,
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Run `fn` while holding an exclusive advisory lock on `path`.
|
|
66
|
+
*
|
|
67
|
+
* The lock lives on the open file, so the kernel releases it when the process
|
|
68
|
+
* dies, even with SIGKILL. The lock file itself may stay behind; that is fine.
|
|
69
|
+
*/
|
|
70
|
+
export function withFileLock<T>(path: string, fn: () => T): T {
|
|
71
|
+
const fd = openSync(path, "a+");
|
|
72
|
+
try {
|
|
73
|
+
if (loadFlock()(fd, LOCK_EX) !== 0) {
|
|
74
|
+
throw new Error(`could not lock ${path}`);
|
|
75
|
+
}
|
|
76
|
+
return fn();
|
|
77
|
+
} finally {
|
|
78
|
+
// Closing the descriptor releases the flock.
|
|
79
|
+
closeSync(fd);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Hard-links `source` to `target`. Returns false when `target` exists; the link
|
|
85
|
+
* either creates `target` with the full content of `source` or fails, so a
|
|
86
|
+
* crash never leaves a half-written `target`.
|
|
87
|
+
*/
|
|
88
|
+
export function linkExclusive(source: string, target: string): boolean {
|
|
89
|
+
try {
|
|
90
|
+
linkSync(source, target);
|
|
91
|
+
return true;
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (errorCode(error) === "EEXIST") return false;
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** How long a waiter accepts a live holder before it gives up. */
|
|
99
|
+
export const LOCK_TIMEOUT_MS = 10_000;
|
|
100
|
+
|
|
101
|
+
/** The fallback check interval when no watch event arrives. */
|
|
102
|
+
const LOCK_POLL_MS = 200;
|
|
103
|
+
|
|
104
|
+
/** An unreadable lock counts as dead once its mtime is this old. */
|
|
105
|
+
const STALE_UNREADABLE_MS = 30_000;
|
|
106
|
+
|
|
107
|
+
/** Thrown when a live holder keeps the lock past the waiter's timeout. */
|
|
108
|
+
export class LockTimeoutError extends Error {
|
|
109
|
+
readonly lockPath: string;
|
|
110
|
+
/** `pid N` for a readable record, `unknown pid` for an unreadable one. */
|
|
111
|
+
readonly holder: string;
|
|
112
|
+
|
|
113
|
+
constructor(lockPath: string, holder: string) {
|
|
114
|
+
super(`${lockPath} is held by ${holder}`);
|
|
115
|
+
this.name = "LockTimeoutError";
|
|
116
|
+
this.lockPath = lockPath;
|
|
117
|
+
this.holder = holder;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** What a waiter may inject: the clock, how it waits, and where a log goes. */
|
|
122
|
+
export interface LockFileOptions {
|
|
123
|
+
readonly clock?: (() => number) | undefined;
|
|
124
|
+
readonly wait?: ((ms: number) => Promise<void>) | undefined;
|
|
125
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
126
|
+
/** Names the lock in log lines; defaults to `lock`. */
|
|
127
|
+
readonly label?: string | undefined;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Test-only hooks. Production code never sets them; the protocol must hold
|
|
132
|
+
* without them. `beforeLink` stands for a crash between the tmp write and the
|
|
133
|
+
* link; `beforeTakeoverRename` lets a test put a newer live lock in place.
|
|
134
|
+
*/
|
|
135
|
+
export const lockTestHooks: {
|
|
136
|
+
beforeLink?: ((tmpPath: string, lockPath: string) => void) | undefined;
|
|
137
|
+
beforeTakeoverRename?: ((lockPath: string) => void) | undefined;
|
|
138
|
+
} = {};
|
|
139
|
+
|
|
140
|
+
interface LockRecord {
|
|
141
|
+
readonly pid: number;
|
|
142
|
+
readonly startedAt: number | null;
|
|
143
|
+
readonly nonce: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
interface LockFile {
|
|
147
|
+
readonly raw: string | undefined;
|
|
148
|
+
readonly record: LockRecord | undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function errorCode(error: unknown): unknown {
|
|
152
|
+
return typeof error === "object" && error !== null && "code" in error
|
|
153
|
+
? error.code
|
|
154
|
+
: undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function newNonce(): string {
|
|
158
|
+
return randomBytes(16).toString("hex");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function readLockFile(path: string): LockFile {
|
|
162
|
+
let raw: string;
|
|
163
|
+
try {
|
|
164
|
+
raw = readFileSync(path, "utf8");
|
|
165
|
+
} catch {
|
|
166
|
+
return { raw: undefined, record: undefined };
|
|
167
|
+
}
|
|
168
|
+
let parsed: unknown;
|
|
169
|
+
try {
|
|
170
|
+
parsed = JSON.parse(raw);
|
|
171
|
+
} catch {
|
|
172
|
+
return { raw, record: undefined };
|
|
173
|
+
}
|
|
174
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { raw, record: undefined };
|
|
175
|
+
const fields = parsed as Record<string, unknown>;
|
|
176
|
+
const pid = fields.pid;
|
|
177
|
+
const nonce = fields.nonce;
|
|
178
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
|
|
179
|
+
return { raw, record: undefined };
|
|
180
|
+
}
|
|
181
|
+
if (typeof nonce !== "string" || nonce.length === 0) {
|
|
182
|
+
return { raw, record: undefined };
|
|
183
|
+
}
|
|
184
|
+
const startedAt = fields.startedAt;
|
|
185
|
+
return {
|
|
186
|
+
raw,
|
|
187
|
+
record: {
|
|
188
|
+
pid,
|
|
189
|
+
startedAt: typeof startedAt === "number" ? startedAt : null,
|
|
190
|
+
nonce,
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** True while a process with this pid exists; `EPERM` means it exists too. */
|
|
196
|
+
export function isAlive(pid: number): boolean {
|
|
197
|
+
try {
|
|
198
|
+
process.kill(pid, 0);
|
|
199
|
+
return true;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
return errorCode(error) !== "ESRCH";
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
let myStartedAt: number | null | undefined;
|
|
206
|
+
|
|
207
|
+
/** The start time of this process, when the platform will say; best effort. */
|
|
208
|
+
function myStart(): number | null {
|
|
209
|
+
if (myStartedAt !== undefined) return myStartedAt;
|
|
210
|
+
const pid = process.pid;
|
|
211
|
+
try {
|
|
212
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
213
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
214
|
+
const ticks = Number(fields[19]);
|
|
215
|
+
if (Number.isFinite(ticks)) {
|
|
216
|
+
myStartedAt = ticks;
|
|
217
|
+
return ticks;
|
|
218
|
+
}
|
|
219
|
+
} catch {
|
|
220
|
+
// Not Linux.
|
|
221
|
+
}
|
|
222
|
+
try {
|
|
223
|
+
const result = Bun.spawnSync({
|
|
224
|
+
cmd: ["ps", "-p", String(pid), "-o", "lstart="],
|
|
225
|
+
stdout: "pipe",
|
|
226
|
+
stderr: "pipe",
|
|
227
|
+
});
|
|
228
|
+
const at = Date.parse(result.stdout.toString().trim());
|
|
229
|
+
myStartedAt = Number.isFinite(at) ? at : null;
|
|
230
|
+
} catch {
|
|
231
|
+
myStartedAt = null;
|
|
232
|
+
}
|
|
233
|
+
return myStartedAt;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function safeUnlink(path: string): void {
|
|
237
|
+
try {
|
|
238
|
+
unlinkSync(path);
|
|
239
|
+
} catch {
|
|
240
|
+
// Already gone.
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function isStaleUnreadable(path: string, clock: () => number): boolean {
|
|
245
|
+
try {
|
|
246
|
+
return clock() - statSync(path).mtimeMs > STALE_UNREADABLE_MS;
|
|
247
|
+
} catch {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Takes over a lock whose record is dead. Takers go one at a time, under a
|
|
254
|
+
* kernel `flock` on a guard file that dies with its holder, and each re-reads
|
|
255
|
+
* the lock under the guard: it removes the file only if it is still the dead
|
|
256
|
+
* record the taker decided on. While that file exists nobody can link a new
|
|
257
|
+
* lock, and only a taker removes a dead record, so the removal cannot hit a
|
|
258
|
+
* live lock another process has just made. (An earlier version let every taker
|
|
259
|
+
* rename the file and put back a live lock it had renamed by mistake; with five
|
|
260
|
+
* waiters the put-back could find a third lock in its place, and two holders
|
|
261
|
+
* entered together.)
|
|
262
|
+
*/
|
|
263
|
+
function takeOver(lockPath: string, dead: LockFile): void {
|
|
264
|
+
withFileLock(`${lockPath}.takeover`, () => {
|
|
265
|
+
lockTestHooks.beforeTakeoverRename?.(lockPath);
|
|
266
|
+
const now = readLockFile(lockPath);
|
|
267
|
+
if (now.raw === undefined) return;
|
|
268
|
+
const same =
|
|
269
|
+
dead.record !== undefined && now.record !== undefined
|
|
270
|
+
? dead.record.nonce === now.record.nonce
|
|
271
|
+
: dead.raw === now.raw;
|
|
272
|
+
if (!same) return;
|
|
273
|
+
safeUnlink(lockPath);
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function acquire(
|
|
278
|
+
lockPath: string,
|
|
279
|
+
clock: () => number,
|
|
280
|
+
wait: (ms: number) => Promise<void>,
|
|
281
|
+
log: (message: string) => void,
|
|
282
|
+
): Promise<LockRecord> {
|
|
283
|
+
const started = clock();
|
|
284
|
+
for (;;) {
|
|
285
|
+
const mine: LockRecord = {
|
|
286
|
+
pid: process.pid,
|
|
287
|
+
startedAt: myStart(),
|
|
288
|
+
nonce: newNonce(),
|
|
289
|
+
};
|
|
290
|
+
const tmp = `${lockPath}.${mine.nonce}.tmp`;
|
|
291
|
+
writeFileSync(tmp, JSON.stringify(mine), { flag: "wx" });
|
|
292
|
+
lockTestHooks.beforeLink?.(tmp, lockPath);
|
|
293
|
+
|
|
294
|
+
let linked = false;
|
|
295
|
+
try {
|
|
296
|
+
// `link` either creates the lock with its full content or fails EEXIST.
|
|
297
|
+
linked = linkExclusive(tmp, lockPath);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
safeUnlink(tmp);
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
if (linked) {
|
|
303
|
+
safeUnlink(tmp);
|
|
304
|
+
return mine;
|
|
305
|
+
}
|
|
306
|
+
safeUnlink(tmp);
|
|
307
|
+
|
|
308
|
+
const holder = readLockFile(lockPath);
|
|
309
|
+
if (holder.raw === undefined) {
|
|
310
|
+
// The holder released between the link and the read; try again.
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
const dead =
|
|
314
|
+
holder.record === undefined
|
|
315
|
+
? isStaleUnreadable(lockPath, clock)
|
|
316
|
+
: !isAlive(holder.record.pid);
|
|
317
|
+
if (dead) {
|
|
318
|
+
takeOver(lockPath, holder);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (clock() - started > LOCK_TIMEOUT_MS) {
|
|
323
|
+
const who =
|
|
324
|
+
holder.record === undefined ? "unknown pid" : `pid ${holder.record.pid}`;
|
|
325
|
+
throw new LockTimeoutError(lockPath, who);
|
|
326
|
+
}
|
|
327
|
+
await wait(LOCK_POLL_MS);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Releases this process's lock, never deleting a record that is not ours. */
|
|
332
|
+
function release(
|
|
333
|
+
lockPath: string,
|
|
334
|
+
mine: LockRecord,
|
|
335
|
+
log: (message: string) => void,
|
|
336
|
+
): void {
|
|
337
|
+
const released = `${lockPath}.release.${mine.nonce}`;
|
|
338
|
+
try {
|
|
339
|
+
renameSync(lockPath, released);
|
|
340
|
+
} catch (error) {
|
|
341
|
+
if (errorCode(error) === "ENOENT") return;
|
|
342
|
+
throw error;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const file = readLockFile(released);
|
|
346
|
+
if (file.record?.nonce === mine.nonce) {
|
|
347
|
+
safeUnlink(released);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
try {
|
|
352
|
+
linkSync(released, lockPath);
|
|
353
|
+
safeUnlink(released);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
356
|
+
log(`${lockPath} changed while releasing; kept ${released}`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Holds the lock file at `lockPath` while `work` runs. The file makes two
|
|
362
|
+
* callers in two processes take turns; callers in one process wait too. A lock
|
|
363
|
+
* whose holder died is taken over; a live holder past the timeout throws
|
|
364
|
+
* `LockTimeoutError`.
|
|
365
|
+
*/
|
|
366
|
+
export async function withLockFile<T>(
|
|
367
|
+
lockPath: string,
|
|
368
|
+
work: () => Promise<T> | T,
|
|
369
|
+
options: LockFileOptions = {},
|
|
370
|
+
): Promise<T> {
|
|
371
|
+
mkdirSync(dirname(lockPath), { recursive: true });
|
|
372
|
+
const clock = options.clock ?? (() => Date.now());
|
|
373
|
+
const wait =
|
|
374
|
+
options.wait ??
|
|
375
|
+
((ms: number) => waitForChange(dirname(lockPath), lockPath, ms));
|
|
376
|
+
const label = options.label ?? "lock";
|
|
377
|
+
const onLog = options.onLog ?? ((message: string) => console.error(message));
|
|
378
|
+
const log = (message: string): void => onLog(`${label}: ${message}`);
|
|
379
|
+
const mine = await acquire(lockPath, clock, wait, log);
|
|
380
|
+
try {
|
|
381
|
+
return await work();
|
|
382
|
+
} finally {
|
|
383
|
+
release(lockPath, mine, log);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The platform module: the pieces every plugin that touches processes, files or
|
|
3
|
+
* a database needs, written once. A plugin imports them from
|
|
4
|
+
* `@operad-io/engine/platform` and never writes its own.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export * from "./file-lock.ts";
|
|
8
|
+
export * from "./process-group.ts";
|
|
9
|
+
export * from "./sqlite-open.ts";
|
|
10
|
+
export * from "./watch.ts";
|
|
11
|
+
export * from "./step-reap.ts";
|
|
12
|
+
export * from "./load.ts";
|
|
13
|
+
export * from "./worker-reports.ts";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** The machine's load, for a reader deciding whether a failure was load. */
|
|
2
|
+
|
|
3
|
+
import { availableParallelism, loadavg } from "node:os";
|
|
4
|
+
|
|
5
|
+
/** The 1-minute load average and the number of cores. */
|
|
6
|
+
export interface MachineLoad {
|
|
7
|
+
readonly load1: number;
|
|
8
|
+
readonly cores: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Reads the load now. A platform with no load average reports 0. */
|
|
12
|
+
export function machineLoad(): MachineLoad {
|
|
13
|
+
const [load1] = loadavg();
|
|
14
|
+
return {
|
|
15
|
+
load1: Math.round((load1 ?? 0) * 100) / 100,
|
|
16
|
+
cores: availableParallelism(),
|
|
17
|
+
};
|
|
18
|
+
}
|