@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,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time permissions. An answered question may give the step that asked a
|
|
3
|
+
* permission for the exact call it asked about. The permission is used up by
|
|
4
|
+
* recording `grant_used` with the question's wait id, before the call runs; the
|
|
5
|
+
* fact is the only record, so a crash after it cannot grant the call twice.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { SeqConflictError } from "../log/errors.ts";
|
|
9
|
+
import type { JsonValue, LogBackend } from "../log/types.ts";
|
|
10
|
+
import type { Grant } from "../kernel/types.ts";
|
|
11
|
+
import { isRecord } from "../util.ts";
|
|
12
|
+
|
|
13
|
+
/** The wait ids whose permission the run has used. */
|
|
14
|
+
export async function usedGrants(
|
|
15
|
+
log: LogBackend,
|
|
16
|
+
runId: string,
|
|
17
|
+
): Promise<ReadonlySet<string>> {
|
|
18
|
+
const used = new Set<string>();
|
|
19
|
+
for await (const fact of log.read(runId)) {
|
|
20
|
+
if (
|
|
21
|
+
fact.kind === "grant_used" &&
|
|
22
|
+
isRecord(fact.payload) &&
|
|
23
|
+
typeof fact.payload.waitId === "string"
|
|
24
|
+
) {
|
|
25
|
+
used.add(fact.payload.waitId);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return used;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Uses up the permission of `waitId`. True when this call used it; false when
|
|
33
|
+
* it was already used or the step has no such permission.
|
|
34
|
+
*/
|
|
35
|
+
export async function useGrant(
|
|
36
|
+
log: LogBackend,
|
|
37
|
+
runId: string,
|
|
38
|
+
step: string,
|
|
39
|
+
grants: readonly Grant[],
|
|
40
|
+
waitId: string,
|
|
41
|
+
): Promise<boolean> {
|
|
42
|
+
const grant = grants.find((item) => item.waitId === waitId);
|
|
43
|
+
if (grant === undefined) return false;
|
|
44
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
45
|
+
let lastSeq = 0;
|
|
46
|
+
let used = false;
|
|
47
|
+
for await (const fact of log.read(runId)) {
|
|
48
|
+
lastSeq = fact.seq;
|
|
49
|
+
if (
|
|
50
|
+
fact.kind === "grant_used" &&
|
|
51
|
+
isRecord(fact.payload) &&
|
|
52
|
+
fact.payload.waitId === waitId
|
|
53
|
+
) {
|
|
54
|
+
used = true;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (used) return false;
|
|
58
|
+
try {
|
|
59
|
+
await log.append(runId, lastSeq, [
|
|
60
|
+
{
|
|
61
|
+
kind: "grant_used",
|
|
62
|
+
payload: {
|
|
63
|
+
waitId,
|
|
64
|
+
step,
|
|
65
|
+
kind: grant.kind,
|
|
66
|
+
value: grant.value,
|
|
67
|
+
...(grant.tool === undefined ? {} : { tool: grant.tool }),
|
|
68
|
+
},
|
|
69
|
+
cause: lastSeq >= 1 ? lastSeq : "grant",
|
|
70
|
+
},
|
|
71
|
+
]);
|
|
72
|
+
return true;
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (error instanceof SeqConflictError && attempt < 8) continue;
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The run's access profile with the permissions that are still unused. */
|
|
81
|
+
export function accessWith(
|
|
82
|
+
access: JsonValue,
|
|
83
|
+
grants: readonly Grant[] | undefined,
|
|
84
|
+
used: ReadonlySet<string>,
|
|
85
|
+
): JsonValue {
|
|
86
|
+
const open = (grants ?? []).filter((grant) => !used.has(grant.waitId));
|
|
87
|
+
if (open.length === 0) return access;
|
|
88
|
+
return {
|
|
89
|
+
...(isRecord(access) ? access : {}),
|
|
90
|
+
grants: open.map((grant) => ({ ...grant })),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export * from "./errors.ts";
|
|
2
|
+
export { answerRun, recordAnswer } from "./answer.ts";
|
|
3
|
+
export type {
|
|
4
|
+
AnswerOptions,
|
|
5
|
+
RecordAnswerOptions,
|
|
6
|
+
RecordedAnswerPayload,
|
|
7
|
+
} from "./answer.ts";
|
|
8
|
+
export { cancelRun } from "./cancel.ts";
|
|
9
|
+
export type { CancelRunOptions } from "./cancel.ts";
|
|
10
|
+
export {
|
|
11
|
+
acquireLock,
|
|
12
|
+
lockHeld,
|
|
13
|
+
pidAlive,
|
|
14
|
+
readLockPid,
|
|
15
|
+
runLockPath,
|
|
16
|
+
serveLockPath,
|
|
17
|
+
} from "./lock.ts";
|
|
18
|
+
export type { LockHandle, LockOptions } from "./lock.ts";
|
|
19
|
+
export {
|
|
20
|
+
appendInput,
|
|
21
|
+
applyInput,
|
|
22
|
+
endRunDirectly,
|
|
23
|
+
objectKey,
|
|
24
|
+
parseObjectKey,
|
|
25
|
+
readState,
|
|
26
|
+
} from "./service.ts";
|
|
27
|
+
export type { ApplyHooks, ApplyResult } from "./service.ts";
|
|
28
|
+
export { DEFAULT_STEP_TIMEOUT_MS, Runner } from "./runner.ts";
|
|
29
|
+
export type { RunnerOptions, RunnerOutcome } from "./runner.ts";
|
|
30
|
+
export { queuedSteps, scanLimits, StepLimits } from "./limits.ts";
|
|
31
|
+
export type { LimitClaim, LimitEntry, StepLimitsOptions } from "./limits.ts";
|
|
32
|
+
export { AskHost, askWaitId, DEFAULT_ASK_GRACE_SECS, scanAsks } from "./ask.ts";
|
|
33
|
+
export type { AskHostOptions, AskRecord, AskTimer } from "./ask.ts";
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Step limits: at most `concurrent` running steps per key in one operad home.
|
|
3
|
+
*
|
|
4
|
+
* The facts of the runs are the only record. A step writes `step_queued`
|
|
5
|
+
* before it waits and `step_slot` is written when its place is granted; the
|
|
6
|
+
* place is held until the step's effect has a result (or is interrupted or
|
|
7
|
+
* abandoned) or the run ends. A step that a step starts through `ctx.runStep`
|
|
8
|
+
* has an effect id of its own, `<outer effect id>#<n>`, and gives its place
|
|
9
|
+
* back with `step_released`. Nothing is kept in memory: every grant rebuilds
|
|
10
|
+
* the held places and the queues from the logs, so a restart loses nothing.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { evolve, initialState } from "../kernel/index.ts";
|
|
14
|
+
import type { KernelState } from "../kernel/types.ts";
|
|
15
|
+
import { SeqConflictError } from "../log/errors.ts";
|
|
16
|
+
import type { JsonValue, LogBackend } from "../log/types.ts";
|
|
17
|
+
import type { StepLimiter, StepLimitRequest } from "../plugin/types.ts";
|
|
18
|
+
import { withLockFile } from "../platform/index.ts";
|
|
19
|
+
import { join } from "node:path";
|
|
20
|
+
import { isRecord } from "../util.ts";
|
|
21
|
+
|
|
22
|
+
/** How often a waiting step looks again when no change was announced. */
|
|
23
|
+
const RECHECK_MS = 1000;
|
|
24
|
+
|
|
25
|
+
/** One step that holds a place under a key or waits for one. */
|
|
26
|
+
export interface LimitEntry {
|
|
27
|
+
readonly runId: string;
|
|
28
|
+
readonly effectId: string;
|
|
29
|
+
readonly step: string | null;
|
|
30
|
+
readonly key: string;
|
|
31
|
+
readonly concurrent: number;
|
|
32
|
+
/** When and where `step_queued` was written; this orders each queue. */
|
|
33
|
+
readonly time: number;
|
|
34
|
+
readonly seq: number;
|
|
35
|
+
readonly granted: boolean;
|
|
36
|
+
/** True for a wait a step reports for a place it manages itself; grants skip it. */
|
|
37
|
+
readonly reported: boolean;
|
|
38
|
+
/** For a reported wait: the waiters ahead of it, as its plugin counts them. */
|
|
39
|
+
readonly ahead?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The effect id of the step that a nested effect id belongs to. */
|
|
43
|
+
function outerOf(effectId: string): string {
|
|
44
|
+
const hash = effectId.indexOf("#");
|
|
45
|
+
return hash < 0 ? effectId : effectId.slice(0, hash);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The live entries of one run: places held and places waited for. */
|
|
49
|
+
async function scanRun(
|
|
50
|
+
log: LogBackend,
|
|
51
|
+
runId: string,
|
|
52
|
+
): Promise<{ readonly entries: LimitEntry[]; readonly lastSeq: number }> {
|
|
53
|
+
let state: KernelState = initialState();
|
|
54
|
+
const found = new Map<string, LimitEntry & { released: boolean }>();
|
|
55
|
+
let lastSeq = 0;
|
|
56
|
+
for await (const fact of log.read(runId)) {
|
|
57
|
+
state = evolve(state, fact);
|
|
58
|
+
lastSeq = fact.seq;
|
|
59
|
+
if (
|
|
60
|
+
fact.kind !== "step_queued" &&
|
|
61
|
+
fact.kind !== "step_slot" &&
|
|
62
|
+
fact.kind !== "step_released"
|
|
63
|
+
) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const payload = fact.payload;
|
|
67
|
+
if (!isRecord(payload) || typeof payload.effectId !== "string") continue;
|
|
68
|
+
const effectId = payload.effectId;
|
|
69
|
+
const existing = found.get(effectId);
|
|
70
|
+
if (fact.kind === "step_queued") {
|
|
71
|
+
// A queue entry that was released is over; queueing again starts afresh.
|
|
72
|
+
if (existing !== undefined && !existing.released) continue;
|
|
73
|
+
if (typeof payload.key !== "string") continue;
|
|
74
|
+
if (typeof payload.concurrent !== "number") continue;
|
|
75
|
+
found.set(effectId, {
|
|
76
|
+
runId,
|
|
77
|
+
effectId,
|
|
78
|
+
step: typeof payload.step === "string" ? payload.step : null,
|
|
79
|
+
key: payload.key,
|
|
80
|
+
concurrent: payload.concurrent,
|
|
81
|
+
time: fact.time,
|
|
82
|
+
seq: fact.seq,
|
|
83
|
+
granted: false,
|
|
84
|
+
reported: payload.reported === true,
|
|
85
|
+
...(payload.reported === true && typeof payload.ahead === "number"
|
|
86
|
+
? { ahead: payload.ahead }
|
|
87
|
+
: {}),
|
|
88
|
+
released: false,
|
|
89
|
+
});
|
|
90
|
+
} else if (existing !== undefined) {
|
|
91
|
+
found.set(
|
|
92
|
+
effectId,
|
|
93
|
+
fact.kind === "step_slot"
|
|
94
|
+
? { ...existing, granted: true }
|
|
95
|
+
: { ...existing, released: true },
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const entries: LimitEntry[] = [];
|
|
100
|
+
for (const entry of found.values()) {
|
|
101
|
+
if (entry.released) continue;
|
|
102
|
+
if (state.effects[outerOf(entry.effectId)] !== "outstanding") continue;
|
|
103
|
+
entries.push({
|
|
104
|
+
runId: entry.runId,
|
|
105
|
+
effectId: entry.effectId,
|
|
106
|
+
step: entry.step,
|
|
107
|
+
key: entry.key,
|
|
108
|
+
concurrent: entry.concurrent,
|
|
109
|
+
time: entry.time,
|
|
110
|
+
seq: entry.seq,
|
|
111
|
+
granted: entry.granted,
|
|
112
|
+
reported: entry.reported,
|
|
113
|
+
...(entry.ahead === undefined ? {} : { ahead: entry.ahead }),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return { entries, lastSeq };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Every live entry of every active run. */
|
|
120
|
+
export async function scanLimits(log: LogBackend): Promise<LimitEntry[]> {
|
|
121
|
+
const all: LimitEntry[] = [];
|
|
122
|
+
for (const run of await log.runs({ active: true })) {
|
|
123
|
+
try {
|
|
124
|
+
all.push(...(await scanRun(log, run.runId)).entries);
|
|
125
|
+
} catch {
|
|
126
|
+
// A run that cannot be read holds nothing; its own runner reports it.
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return all;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function compareQueue(left: LimitEntry, right: LimitEntry): number {
|
|
133
|
+
if (left.time !== right.time) return left.time - right.time;
|
|
134
|
+
if (left.runId !== right.runId) return left.runId < right.runId ? -1 : 1;
|
|
135
|
+
return left.seq - right.seq;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The queued entries of one key, first in line first. */
|
|
139
|
+
export function queueOf(
|
|
140
|
+
entries: readonly LimitEntry[],
|
|
141
|
+
key: string,
|
|
142
|
+
): LimitEntry[] {
|
|
143
|
+
return entries
|
|
144
|
+
.filter((entry) => entry.key === key && !entry.granted)
|
|
145
|
+
.sort(compareQueue);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** For each run with a queued step: its key and how many are ahead of it. */
|
|
149
|
+
export async function queuedSteps(
|
|
150
|
+
log: LogBackend,
|
|
151
|
+
): Promise<Map<string, { readonly key: string; readonly ahead: number }>> {
|
|
152
|
+
const entries = await scanLimits(log);
|
|
153
|
+
const result = new Map<string, { readonly key: string; readonly ahead: number }>();
|
|
154
|
+
for (const key of new Set(entries.map((entry) => entry.key))) {
|
|
155
|
+
queueOf(entries, key).forEach((entry, ahead) => {
|
|
156
|
+
if (!result.has(entry.runId)) {
|
|
157
|
+
result.set(entry.runId, { key, ahead: entry.ahead ?? ahead });
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface StepLimitsOptions {
|
|
165
|
+
readonly log: LogBackend;
|
|
166
|
+
/** The store root; the grant lock lives under `<root>/locks`. */
|
|
167
|
+
readonly lockRoot?: string | undefined;
|
|
168
|
+
readonly clock?: (() => number) | undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Serializes grants made inside one process that has no lock root. */
|
|
172
|
+
const localTails = new WeakMap<LogBackend, Promise<unknown>>();
|
|
173
|
+
|
|
174
|
+
export interface LimitClaim {
|
|
175
|
+
readonly runId: string;
|
|
176
|
+
readonly effectId: string;
|
|
177
|
+
readonly step: string | null;
|
|
178
|
+
readonly key: string;
|
|
179
|
+
readonly concurrent: number;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export class StepLimits {
|
|
183
|
+
private readonly log: LogBackend;
|
|
184
|
+
private readonly lockRoot: string | undefined;
|
|
185
|
+
|
|
186
|
+
constructor(options: StepLimitsOptions) {
|
|
187
|
+
this.log = options.log;
|
|
188
|
+
this.lockRoot = options.lockRoot;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Takes a place for the claim: writes `step_queued` unless the run already
|
|
193
|
+
* has it, then waits until `step_slot` is written. A step whose place was
|
|
194
|
+
* granted before a crash returns at once. An abort stops the wait and
|
|
195
|
+
* releases the claim.
|
|
196
|
+
*/
|
|
197
|
+
async acquire(claim: LimitClaim, signal?: AbortSignal): Promise<void> {
|
|
198
|
+
const own = await scanRun(this.log, claim.runId);
|
|
199
|
+
const have = own.entries.find((entry) => entry.effectId === claim.effectId);
|
|
200
|
+
if (have === undefined) {
|
|
201
|
+
await this.appendFact(claim.runId, "step_queued", {
|
|
202
|
+
step: claim.step,
|
|
203
|
+
effectId: claim.effectId,
|
|
204
|
+
key: claim.key,
|
|
205
|
+
concurrent: claim.concurrent,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
if (have?.granted === true) return;
|
|
209
|
+
|
|
210
|
+
for (;;) {
|
|
211
|
+
if (signal?.aborted === true) {
|
|
212
|
+
await this.release(claim);
|
|
213
|
+
throw new Error("the step was cancelled while it waited for a place");
|
|
214
|
+
}
|
|
215
|
+
await this.grant();
|
|
216
|
+
const now = await scanRun(this.log, claim.runId);
|
|
217
|
+
if (
|
|
218
|
+
now.entries.some(
|
|
219
|
+
(entry) => entry.effectId === claim.effectId && entry.granted,
|
|
220
|
+
)
|
|
221
|
+
) {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
await this.changed(signal);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Records that a step waits for a place it manages itself (one the kernel
|
|
230
|
+
* does not grant): the run shows queued under `key`, with the reports
|
|
231
|
+
* ahead of it counted. `release` ends the wait.
|
|
232
|
+
*/
|
|
233
|
+
async report(
|
|
234
|
+
claim: Omit<LimitClaim, "concurrent"> & { readonly ahead?: number | undefined },
|
|
235
|
+
): Promise<void> {
|
|
236
|
+
await this.appendFact(claim.runId, "step_queued", {
|
|
237
|
+
step: claim.step,
|
|
238
|
+
effectId: claim.effectId,
|
|
239
|
+
key: claim.key,
|
|
240
|
+
concurrent: 0,
|
|
241
|
+
reported: true,
|
|
242
|
+
...(claim.ahead === undefined ? {} : { ahead: claim.ahead }),
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Gives a claim's place back, or leaves the queue. */
|
|
247
|
+
async release(claim: LimitClaim): Promise<void> {
|
|
248
|
+
const own = await scanRun(this.log, claim.runId);
|
|
249
|
+
if (own.entries.some((entry) => entry.effectId === claim.effectId)) {
|
|
250
|
+
await this.appendFact(claim.runId, "step_released", {
|
|
251
|
+
effectId: claim.effectId,
|
|
252
|
+
key: claim.key,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
await this.grant();
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Gives back every place that steps of this effect still hold (after a crash
|
|
260
|
+
* the process that held them is gone) and returns the highest number a
|
|
261
|
+
* nested step of this effect used, so new ones never reuse an id.
|
|
262
|
+
*/
|
|
263
|
+
async resetNested(runId: string, effectId: string): Promise<number> {
|
|
264
|
+
const own = await scanRun(this.log, runId);
|
|
265
|
+
let highest = 0;
|
|
266
|
+
for (const entry of own.entries) {
|
|
267
|
+
if (outerOf(entry.effectId) !== effectId || entry.effectId === effectId) {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
await this.appendFact(runId, "step_released", {
|
|
271
|
+
effectId: entry.effectId,
|
|
272
|
+
key: entry.key,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
// Ids are never reused, released or not.
|
|
276
|
+
for await (const fact of this.log.read(runId)) {
|
|
277
|
+
if (fact.kind !== "step_queued" || !isRecord(fact.payload)) continue;
|
|
278
|
+
const id = fact.payload.effectId;
|
|
279
|
+
if (typeof id !== "string" || outerOf(id) !== effectId) continue;
|
|
280
|
+
const suffix = Number(id.slice(effectId.length + 1));
|
|
281
|
+
if (Number.isInteger(suffix) && suffix > highest) highest = suffix;
|
|
282
|
+
}
|
|
283
|
+
return highest;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Grants every place that is free to the first in line of its key. It is the
|
|
288
|
+
* only writer of `step_slot`, and it runs under one lock for the home.
|
|
289
|
+
*/
|
|
290
|
+
async grant(): Promise<void> {
|
|
291
|
+
await this.locked(async () => {
|
|
292
|
+
const entries = await scanLimits(this.log);
|
|
293
|
+
for (const key of new Set(entries.map((entry) => entry.key))) {
|
|
294
|
+
let held = entries.filter(
|
|
295
|
+
(entry) => entry.key === key && entry.granted,
|
|
296
|
+
).length;
|
|
297
|
+
for (const next of queueOf(entries, key).filter((entry) => !entry.reported)) {
|
|
298
|
+
if (held >= next.concurrent) break;
|
|
299
|
+
await this.appendFact(next.runId, "step_slot", {
|
|
300
|
+
step: next.step,
|
|
301
|
+
effectId: next.effectId,
|
|
302
|
+
key,
|
|
303
|
+
});
|
|
304
|
+
held += 1;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** A `StepLimiter` for the steps that the step of `effectId` starts. */
|
|
311
|
+
limiterFor(
|
|
312
|
+
runId: string,
|
|
313
|
+
effectId: string,
|
|
314
|
+
step: string | null,
|
|
315
|
+
firstNumber: number,
|
|
316
|
+
): StepLimiter {
|
|
317
|
+
let next = firstNumber;
|
|
318
|
+
return {
|
|
319
|
+
acquire: async (request: StepLimitRequest) => {
|
|
320
|
+
next += 1;
|
|
321
|
+
const claim: LimitClaim = {
|
|
322
|
+
runId,
|
|
323
|
+
effectId: `${effectId}#${next}`,
|
|
324
|
+
step,
|
|
325
|
+
key: request.key,
|
|
326
|
+
concurrent: request.concurrent,
|
|
327
|
+
};
|
|
328
|
+
await this.acquire(claim, request.signal);
|
|
329
|
+
return () => this.release(claim);
|
|
330
|
+
},
|
|
331
|
+
report: async (request) => {
|
|
332
|
+
next += 1;
|
|
333
|
+
const claim = {
|
|
334
|
+
runId,
|
|
335
|
+
effectId: `${effectId}#${next}`,
|
|
336
|
+
step,
|
|
337
|
+
key: request.key,
|
|
338
|
+
ahead: request.ahead,
|
|
339
|
+
};
|
|
340
|
+
await this.report(claim);
|
|
341
|
+
return () => this.release({ ...claim, concurrent: 0 });
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
private async locked<T>(work: () => Promise<T>): Promise<T> {
|
|
347
|
+
const hold = (): Promise<T> =>
|
|
348
|
+
this.lockRoot === undefined
|
|
349
|
+
? work()
|
|
350
|
+
: withLockFile(join(this.lockRoot, "locks", "limits.lock"), work, {
|
|
351
|
+
label: "limits",
|
|
352
|
+
onLog: () => undefined,
|
|
353
|
+
});
|
|
354
|
+
// Grants in one process take turns before the file lock, so only one of
|
|
355
|
+
// them waits on it; the others wait here, where a slow read is not a
|
|
356
|
+
// timeout that would fail the step that asked.
|
|
357
|
+
const tail = localTails.get(this.log) ?? Promise.resolve();
|
|
358
|
+
const run = tail.then(hold, hold);
|
|
359
|
+
localTails.set(
|
|
360
|
+
this.log,
|
|
361
|
+
run.catch(() => undefined),
|
|
362
|
+
);
|
|
363
|
+
return run;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Appends one fact to a run, following the run's own writes. */
|
|
367
|
+
private async appendFact(
|
|
368
|
+
runId: string,
|
|
369
|
+
kind: "step_queued" | "step_slot" | "step_released",
|
|
370
|
+
payload: Record<string, JsonValue>,
|
|
371
|
+
): Promise<void> {
|
|
372
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
373
|
+
let lastSeq = 0;
|
|
374
|
+
for await (const fact of this.log.read(runId)) lastSeq = fact.seq;
|
|
375
|
+
try {
|
|
376
|
+
await this.log.append(runId, lastSeq, [
|
|
377
|
+
{ kind, payload, cause: lastSeq },
|
|
378
|
+
]);
|
|
379
|
+
return;
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (error instanceof SeqConflictError && attempt < 5) continue;
|
|
382
|
+
throw error;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Resolves on the next change to any run, a recheck tick, or an abort. */
|
|
388
|
+
private changed(signal?: AbortSignal): Promise<void> {
|
|
389
|
+
return new Promise((resolve) => {
|
|
390
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
391
|
+
let unsubscribe: (() => void) | undefined;
|
|
392
|
+
const done = (): void => {
|
|
393
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
394
|
+
unsubscribe?.();
|
|
395
|
+
signal?.removeEventListener("abort", done);
|
|
396
|
+
resolve();
|
|
397
|
+
};
|
|
398
|
+
unsubscribe = this.log.subscribe?.(done);
|
|
399
|
+
timer = setTimeout(done, RECHECK_MS);
|
|
400
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/** One lock file per run and one per home, with a stale-PID check. */
|
|
2
|
+
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { LockHeldError } from "./errors.ts";
|
|
6
|
+
|
|
7
|
+
interface LockContents {
|
|
8
|
+
readonly pid: number;
|
|
9
|
+
readonly at: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface LockOptions {
|
|
13
|
+
readonly pid?: number | undefined;
|
|
14
|
+
readonly clock?: (() => number) | undefined;
|
|
15
|
+
/** Test hook; defaults to asking the OS whether the PID exists. */
|
|
16
|
+
readonly isAlive?: ((pid: number) => boolean) | undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface LockHandle {
|
|
20
|
+
readonly path: string;
|
|
21
|
+
release(): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** True when the OS knows the PID (it may belong to another user). */
|
|
25
|
+
export function pidAlive(pid: number): boolean {
|
|
26
|
+
return defaultIsAlive(pid);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function defaultIsAlive(pid: number): boolean {
|
|
30
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
31
|
+
try {
|
|
32
|
+
process.kill(pid, 0);
|
|
33
|
+
return true;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
return (
|
|
36
|
+
typeof error === "object" &&
|
|
37
|
+
error !== null &&
|
|
38
|
+
"code" in error &&
|
|
39
|
+
error.code === "EPERM"
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function readLock(path: string): LockContents | undefined {
|
|
45
|
+
try {
|
|
46
|
+
const raw: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
47
|
+
if (
|
|
48
|
+
typeof raw === "object" &&
|
|
49
|
+
raw !== null &&
|
|
50
|
+
"pid" in raw &&
|
|
51
|
+
typeof raw.pid === "number"
|
|
52
|
+
) {
|
|
53
|
+
return {
|
|
54
|
+
pid: raw.pid,
|
|
55
|
+
at:
|
|
56
|
+
"at" in raw && typeof raw.at === "number" ? raw.at : 0,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
} catch {
|
|
60
|
+
// A torn or deleted lock is stale.
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The PID a lock file names, or undefined when there is no lock or it cannot
|
|
67
|
+
* be read. It never removes a file, so a caller can look without touching.
|
|
68
|
+
*/
|
|
69
|
+
export function readLockPid(path: string): number | undefined {
|
|
70
|
+
if (!existsSync(path)) return undefined;
|
|
71
|
+
return readLock(path)?.pid;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** True when a live process holds `path`. A stale lock is removed. */
|
|
75
|
+
export function lockHeld(path: string, options: LockOptions = {}): boolean {
|
|
76
|
+
if (!existsSync(path)) return false;
|
|
77
|
+
const contents = readLock(path);
|
|
78
|
+
if (contents === undefined) {
|
|
79
|
+
rmSync(path, { force: true });
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
const isAlive = options.isAlive ?? defaultIsAlive;
|
|
83
|
+
if (isAlive(contents.pid)) return true;
|
|
84
|
+
rmSync(path, { force: true });
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Creates `path` holding this PID, unless a live process already holds it.
|
|
90
|
+
* A lock whose PID is gone is replaced.
|
|
91
|
+
*/
|
|
92
|
+
export function acquireLock(path: string, options: LockOptions = {}): LockHandle {
|
|
93
|
+
const pid = options.pid ?? process.pid;
|
|
94
|
+
const clock = options.clock ?? (() => Date.now());
|
|
95
|
+
const isAlive = options.isAlive ?? defaultIsAlive;
|
|
96
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
97
|
+
|
|
98
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
99
|
+
try {
|
|
100
|
+
writeFileSync(
|
|
101
|
+
path,
|
|
102
|
+
`${JSON.stringify({ pid, at: clock() } satisfies LockContents)}\n`,
|
|
103
|
+
{ flag: "wx" },
|
|
104
|
+
);
|
|
105
|
+
return {
|
|
106
|
+
path,
|
|
107
|
+
release: () => {
|
|
108
|
+
const contents = readLock(path);
|
|
109
|
+
if (contents?.pid === pid) rmSync(path, { force: true });
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (
|
|
114
|
+
!(
|
|
115
|
+
typeof error === "object" &&
|
|
116
|
+
error !== null &&
|
|
117
|
+
"code" in error &&
|
|
118
|
+
error.code === "EEXIST"
|
|
119
|
+
)
|
|
120
|
+
) {
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
const contents = readLock(path);
|
|
124
|
+
if (contents !== undefined && isAlive(contents.pid)) {
|
|
125
|
+
throw new LockHeldError(path, `run ${contents.pid} is still alive`);
|
|
126
|
+
}
|
|
127
|
+
// Stale or ours: remove it and try once more.
|
|
128
|
+
rmSync(path, { force: true });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
throw new LockHeldError(path, "could not take it");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function runLockPath(lockRoot: string, runId: string): string {
|
|
135
|
+
return join(lockRoot, "locks", "runs", `${runId}.lock`);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function serveLockPath(home: string): string {
|
|
139
|
+
return join(home, "serve.lock");
|
|
140
|
+
}
|