@operad-io/engine 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config.schema.json +2 -1
- package/package.json +1 -1
- package/src/config/config.ts +74 -45
- package/src/flow/types.ts +4 -0
- package/src/flow/validate.ts +5 -0
- package/src/http/index.ts +2 -0
- package/src/http/plugins.ts +66 -0
- package/src/http/server.ts +342 -48
- package/src/kernel/decide.ts +115 -30
- package/src/kernel/state.ts +9 -0
- package/src/kernel/types.ts +25 -40
- package/src/log/open-log.ts +2 -5
- package/src/log/sqlite.ts +127 -85
- package/src/log/types.ts +35 -9
- package/src/loop/code-watch.ts +108 -2
- package/src/loop/older-code.ts +3 -4
- package/src/loop/serve.ts +122 -95
- package/src/notify/notify.ts +2 -6
- package/src/platform/atomic-write.ts +163 -0
- package/src/platform/file-lock.ts +43 -21
- package/src/platform/index.ts +2 -0
- package/src/platform/kept-workers.ts +290 -0
- package/src/platform/process-group.ts +11 -3
- package/src/platform/sqlite-open.ts +20 -6
- package/src/platform/sqlite-schema.ts +30 -0
- package/src/platform/step-reap.ts +33 -18
- package/src/platform/watch.ts +1 -11
- package/src/plugin/action-schema.ts +59 -1
- package/src/plugin/choice-info.ts +133 -0
- package/src/plugin/context.ts +279 -0
- package/src/plugin/declared-flows.ts +3 -10
- package/src/plugin/errors.ts +9 -0
- package/src/plugin/freeze.ts +12 -0
- package/src/plugin/harness.ts +28 -0
- package/src/plugin/index.ts +8 -7
- package/src/plugin/install.ts +265 -17
- package/src/plugin/keys.ts +2 -12
- package/src/plugin/load.ts +47 -23
- package/src/plugin/logger.ts +14 -0
- package/src/plugin/open-store.ts +0 -6
- package/src/plugin/question-form.ts +323 -0
- package/src/plugin/registry.ts +512 -76
- package/src/plugin/secrets.ts +14 -24
- package/src/plugin/semver.ts +52 -0
- package/src/plugin/settings.ts +1 -9
- package/src/plugin/sqlite-store.ts +94 -64
- package/src/plugin/store.ts +5 -0
- package/src/plugin/types.ts +566 -21
- package/src/plugin/validate.ts +396 -26
- package/src/runner/answer.ts +26 -68
- package/src/runner/ask.ts +227 -28
- package/src/runner/cancel.ts +10 -7
- package/src/runner/grants.ts +2 -2
- package/src/runner/index.ts +1 -3
- package/src/runner/limits.ts +2 -2
- package/src/runner/runner.ts +15 -14
- package/src/runner/service.ts +52 -19
- package/src/runner/step-worker.ts +9 -0
- package/src/testing/answer.ts +69 -0
- package/src/testing/clock-manual.ts +152 -0
- package/src/testing/config.ts +16 -0
- package/src/testing/fs.ts +172 -0
- package/src/testing/home.ts +43 -0
- package/src/testing/index.ts +19 -0
- package/src/testing/types.ts +2 -0
- package/src/testing/world.ts +9 -2
- package/src/trigger/kernel.ts +13 -46
- package/src/trigger/rules.ts +22 -12
- package/src/trigger/types.ts +2 -6
- package/src/util.ts +99 -0
- package/src/views/event-line.ts +22 -0
- package/src/views/history.ts +36 -19
- package/src/views/live-logs.ts +313 -0
- package/src/views/pending.ts +23 -5
- package/src/views/presentation.ts +629 -81
- package/src/views/running.ts +5 -5
- package/src/views/settings.ts +205 -66
- package/src/views/types.ts +3 -2
- package/src/views/uploads.ts +15 -7
- package/triggers.schema.json +4 -0
package/src/runner/runner.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Drives one run: inputs to `decide`, facts to the log, effects to plugins. */
|
|
2
2
|
|
|
3
3
|
import type { FlowDefinition } from "../flow/types.ts";
|
|
4
|
+
import { evolve } from "../kernel/index.ts";
|
|
4
5
|
import type { Input, KernelState, StartInput } from "../kernel/types.ts";
|
|
5
6
|
import { RunEndedError, SeqConflictError } from "../log/errors.ts";
|
|
6
7
|
import type { JsonValue, LogBackend } from "../log/types.ts";
|
|
@@ -25,7 +26,7 @@ import {
|
|
|
25
26
|
import { AskHost, type AskTimer } from "./ask.ts";
|
|
26
27
|
import { StepLimits } from "./limits.ts";
|
|
27
28
|
import { accessWith, usedGrants } from "./grants.ts";
|
|
28
|
-
import { appendInput, applyInput,
|
|
29
|
+
import { appendInput, applyInput, keepState, readState } from "./service.ts";
|
|
29
30
|
|
|
30
31
|
/** The wall time a plugin step may take before the run records a failure. */
|
|
31
32
|
export const DEFAULT_STEP_TIMEOUT_MS = 5 * 60 * 1000;
|
|
@@ -521,6 +522,7 @@ export class Runner {
|
|
|
521
522
|
},
|
|
522
523
|
this.signal,
|
|
523
524
|
);
|
|
525
|
+
// Acquiring a limit appends its own facts, so the state is read again.
|
|
524
526
|
state = await readState(this.log, this.runId);
|
|
525
527
|
}
|
|
526
528
|
} catch (error) {
|
|
@@ -542,6 +544,8 @@ export class Runner {
|
|
|
542
544
|
const nestedBase = recovering
|
|
543
545
|
? await this.limits().resetNested(this.runId, effect.id)
|
|
544
546
|
: 0;
|
|
547
|
+
// A recovered step may have just released nested limits; a fresh step's
|
|
548
|
+
// markStarted already kept its state, so this costs no fact read.
|
|
545
549
|
state = await readState(this.log, this.runId);
|
|
546
550
|
outcome = await this.execute(
|
|
547
551
|
effect.use,
|
|
@@ -557,7 +561,8 @@ export class Runner {
|
|
|
557
561
|
this.asks().asker(this.runId, effect.id, effect.step, effect.grants ?? []),
|
|
558
562
|
);
|
|
559
563
|
}
|
|
560
|
-
// The
|
|
564
|
+
// The step may have opened a question, used a grant or taken a limit slot,
|
|
565
|
+
// each of which appended its own facts.
|
|
561
566
|
state = await readState(this.log, this.runId);
|
|
562
567
|
await this.recordResult(state, effect.id, outcome.result, outcome.data);
|
|
563
568
|
// The result frees the place; the next in line gets it now, or from the
|
|
@@ -666,14 +671,17 @@ export class Runner {
|
|
|
666
671
|
state: KernelState,
|
|
667
672
|
effect: NonNullable<KernelState["effect"]>,
|
|
668
673
|
): Promise<KernelState> {
|
|
669
|
-
await this.log.append(this.runId, state.lastSeq, [
|
|
674
|
+
const appended = await this.log.append(this.runId, state.lastSeq, [
|
|
670
675
|
{
|
|
671
676
|
kind: "step_started",
|
|
672
677
|
payload: { step: effect.step, effectId: effect.id, pid: process.pid },
|
|
673
678
|
cause: state.lastSeq,
|
|
674
679
|
},
|
|
675
680
|
]);
|
|
676
|
-
|
|
681
|
+
let next = state;
|
|
682
|
+
for (const fact of appended.facts) next = evolve(next, fact);
|
|
683
|
+
keepState(this.log, this.runId, next);
|
|
684
|
+
return next;
|
|
677
685
|
}
|
|
678
686
|
|
|
679
687
|
private async recordResult(
|
|
@@ -777,19 +785,10 @@ export class Runner {
|
|
|
777
785
|
);
|
|
778
786
|
}
|
|
779
787
|
|
|
780
|
-
private startInputFor(access: JsonValue | undefined): Input {
|
|
781
|
-
return {
|
|
782
|
-
kind: "start",
|
|
783
|
-
...(this.params === undefined ? {} : { params: this.params }),
|
|
784
|
-
...(access === undefined ? {} : { access }),
|
|
785
|
-
};
|
|
786
|
-
}
|
|
787
|
-
|
|
788
788
|
/** The profile given to the runner, or the one the log recorded at start. */
|
|
789
789
|
private async initialAccess(): Promise<JsonValue | undefined> {
|
|
790
790
|
if (this.access !== undefined) return this.access;
|
|
791
|
-
|
|
792
|
-
return runs.find((run) => run.runId === this.runId)?.access;
|
|
791
|
+
return (await this.log.run(this.runId))?.access;
|
|
793
792
|
}
|
|
794
793
|
|
|
795
794
|
/** The step type's own `timeoutSecs`, or the runner's step timeout. */
|
|
@@ -842,6 +841,7 @@ export class Runner {
|
|
|
842
841
|
use,
|
|
843
842
|
params,
|
|
844
843
|
flowParams,
|
|
844
|
+
flow: this.flow,
|
|
845
845
|
access,
|
|
846
846
|
settings: this.registry.pluginSettings(),
|
|
847
847
|
...(this.trigger === undefined ? {} : { trigger: this.trigger }),
|
|
@@ -1127,6 +1127,7 @@ export class Runner {
|
|
|
1127
1127
|
...(this.cwd === undefined ? {} : { cwd: this.cwd }),
|
|
1128
1128
|
...(object === undefined ? {} : { object }),
|
|
1129
1129
|
params: flowParams,
|
|
1130
|
+
flow: this.flow,
|
|
1130
1131
|
access,
|
|
1131
1132
|
...(this.trigger === undefined ? {} : { trigger: this.trigger }),
|
|
1132
1133
|
...(this.emitEvent === undefined ? {} : { emit: this.emitEvent }),
|
package/src/runner/service.ts
CHANGED
|
@@ -3,18 +3,58 @@
|
|
|
3
3
|
import type { FlowDefinition } from "../flow/types.ts";
|
|
4
4
|
import { decide, evolve, initialState } from "../kernel/index.ts";
|
|
5
5
|
import type { Decision, Input, KernelState } from "../kernel/types.ts";
|
|
6
|
+
import { RunNotFoundError } from "../log/errors.ts";
|
|
6
7
|
import type { LogBackend } from "../log/types.ts";
|
|
7
|
-
import
|
|
8
|
+
import { parseObjectId } from "../util.ts";
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
interface KeptState {
|
|
11
|
+
readonly lastSeq: number;
|
|
12
|
+
readonly state: KernelState;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The last state each log has given for a run, and the sequence it covers. */
|
|
16
|
+
const keptStates = new WeakMap<LogBackend, Map<string, KeptState>>();
|
|
17
|
+
|
|
18
|
+
/** Keeps the state a caller just built by evolving appended facts. */
|
|
19
|
+
export function keepState(log: LogBackend, runId: string, state: KernelState): void {
|
|
20
|
+
let kept = keptStates.get(log);
|
|
21
|
+
if (kept === undefined) {
|
|
22
|
+
kept = new Map();
|
|
23
|
+
keptStates.set(log, kept);
|
|
24
|
+
}
|
|
25
|
+
kept.set(runId, { lastSeq: state.lastSeq, state });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Rebuild a run's state by streaming the facts the kept state does not cover.
|
|
30
|
+
* The run's last sequence comes from its info, so an unchanged run reads no
|
|
31
|
+
* fact at all; a state that a full replay would not give is never kept, and an
|
|
32
|
+
* ended run is dropped rather than held for every run the process has read.
|
|
33
|
+
*/
|
|
10
34
|
export async function readState(
|
|
11
35
|
log: LogBackend,
|
|
12
36
|
runId: string,
|
|
13
37
|
): Promise<KernelState> {
|
|
14
|
-
|
|
15
|
-
|
|
38
|
+
const info = await log.run(runId);
|
|
39
|
+
if (info === undefined) throw new RunNotFoundError(runId);
|
|
40
|
+
const kept = keptStates.get(log);
|
|
41
|
+
const previous = kept?.get(runId);
|
|
42
|
+
if (previous !== undefined && previous.lastSeq === info.lastSeq) {
|
|
43
|
+
if (info.active) return previous.state;
|
|
44
|
+
// An ended run is not held; the call still answers from the state just read.
|
|
45
|
+
kept?.delete(runId);
|
|
46
|
+
}
|
|
47
|
+
let state = previous?.state ?? initialState();
|
|
48
|
+
let lastSeq = previous?.lastSeq ?? 0;
|
|
49
|
+
const after = lastSeq;
|
|
50
|
+
for await (const fact of log.read(runId, { after })) {
|
|
51
|
+
// A backend that ignores `after` must not evolve the same fact twice.
|
|
52
|
+
if (fact.seq <= after) continue;
|
|
16
53
|
state = evolve(state, fact);
|
|
54
|
+
lastSeq = fact.seq;
|
|
17
55
|
}
|
|
56
|
+
if (info.active) keepState(log, runId, state);
|
|
57
|
+
else kept?.delete(runId);
|
|
18
58
|
return state;
|
|
19
59
|
}
|
|
20
60
|
|
|
@@ -28,7 +68,7 @@ export async function endRunDirectly(
|
|
|
28
68
|
status: "failed" | "cancelled",
|
|
29
69
|
reason: string | null,
|
|
30
70
|
): Promise<KernelState | undefined> {
|
|
31
|
-
const run =
|
|
71
|
+
const run = await log.run(runId);
|
|
32
72
|
if (run === undefined) return undefined;
|
|
33
73
|
let state = await readState(log, runId);
|
|
34
74
|
if (state.status !== "ended") {
|
|
@@ -40,17 +80,12 @@ export async function endRunDirectly(
|
|
|
40
80
|
},
|
|
41
81
|
]);
|
|
42
82
|
for (const fact of appended.facts) state = evolve(state, fact);
|
|
83
|
+
keepState(log, runId, state);
|
|
43
84
|
}
|
|
44
85
|
await log.endRun(runId);
|
|
45
86
|
return state;
|
|
46
87
|
}
|
|
47
88
|
|
|
48
|
-
export function objectKey(object: ObjectRef | undefined): string {
|
|
49
|
-
return object === undefined
|
|
50
|
-
? "flow"
|
|
51
|
-
: `${object.type}:${object.id}`;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
89
|
/**
|
|
55
90
|
* The object a run belongs to, when its key names one. A run started without
|
|
56
91
|
* an object is keyed `flow:<plugin>/<flow>`, so that one active run per flow
|
|
@@ -59,10 +94,8 @@ export function objectKey(object: ObjectRef | undefined): string {
|
|
|
59
94
|
export function parseObjectKey(
|
|
60
95
|
key: string,
|
|
61
96
|
): { readonly type: string; readonly id: string } | undefined {
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
if (key.slice(0, colon) === "flow") return undefined;
|
|
65
|
-
return { type: key.slice(0, colon), id: key.slice(colon + 1) };
|
|
97
|
+
const object = parseObjectId(key);
|
|
98
|
+
return object === undefined || object.type === "flow" ? undefined : object;
|
|
66
99
|
}
|
|
67
100
|
|
|
68
101
|
export interface ApplyResult {
|
|
@@ -119,11 +152,11 @@ export async function appendInput(
|
|
|
119
152
|
now: number,
|
|
120
153
|
): Promise<{ readonly state: KernelState; readonly decision: Decision }> {
|
|
121
154
|
const decision = decide(flow, state, input, now);
|
|
122
|
-
const facts = decision.facts;
|
|
123
155
|
let next = state;
|
|
124
|
-
if (facts.length > 0) {
|
|
125
|
-
await log.append(runId, state.lastSeq, facts);
|
|
126
|
-
for (const fact of facts) next = evolve(next, fact);
|
|
156
|
+
if (decision.facts.length > 0) {
|
|
157
|
+
const appended = await log.append(runId, state.lastSeq, decision.facts);
|
|
158
|
+
for (const fact of appended.facts) next = evolve(next, fact);
|
|
159
|
+
keepState(log, runId, next);
|
|
127
160
|
}
|
|
128
161
|
return { state: next, decision };
|
|
129
162
|
}
|
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
StepLimitRequest,
|
|
18
18
|
} from "../plugin/types.ts";
|
|
19
19
|
import type { JsonValue } from "../log/types.ts";
|
|
20
|
+
import type { FlowDefinition } from "../flow/types.ts";
|
|
20
21
|
import { SqlitePluginStore } from "../plugin/sqlite-store.ts";
|
|
21
22
|
import type {
|
|
22
23
|
PluginStore,
|
|
@@ -34,6 +35,7 @@ export interface StepWorkerRequest {
|
|
|
34
35
|
readonly use: string;
|
|
35
36
|
readonly params: unknown;
|
|
36
37
|
readonly flowParams: JsonValue;
|
|
38
|
+
readonly flow?: FlowDefinition | undefined;
|
|
37
39
|
readonly access?: JsonValue | undefined;
|
|
38
40
|
/** The validated settings of every plugin, keyed by plugin name. */
|
|
39
41
|
readonly settings?: Readonly<Record<string, unknown>> | undefined;
|
|
@@ -200,6 +202,12 @@ export async function runStepWorker(
|
|
|
200
202
|
...(question.choices === undefined
|
|
201
203
|
? {}
|
|
202
204
|
: { choices: [...question.choices] }),
|
|
205
|
+
...(question.choiceInfo === undefined
|
|
206
|
+
? {}
|
|
207
|
+
: { choiceInfo: question.choiceInfo }),
|
|
208
|
+
...(question.questions === undefined
|
|
209
|
+
? {}
|
|
210
|
+
: { questions: question.questions }),
|
|
203
211
|
...(question.graceSecs === undefined
|
|
204
212
|
? {}
|
|
205
213
|
: { graceSecs: question.graceSecs }),
|
|
@@ -274,6 +282,7 @@ export async function runStepWorker(
|
|
|
274
282
|
runId: request.runId,
|
|
275
283
|
params: request.flowParams,
|
|
276
284
|
cwd: request.cwd,
|
|
285
|
+
...(request.flow === undefined ? {} : { flow: request.flow }),
|
|
277
286
|
access: request.access ?? null,
|
|
278
287
|
...(request.object === undefined ? {} : { object: request.object }),
|
|
279
288
|
...(request.trigger === undefined ? {} : { trigger: request.trigger }),
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Answering a person wait in the test's own process, for a test only. */
|
|
2
|
+
|
|
3
|
+
import type { FlowDefinition } from "../flow/types.ts";
|
|
4
|
+
import type { KernelState } from "../kernel/types.ts";
|
|
5
|
+
import type { LogBackend } from "../log/types.ts";
|
|
6
|
+
import type { Actor, AskQuestionAnswer } from "../plugin/types.ts";
|
|
7
|
+
import { answerInput } from "../runner/answer.ts";
|
|
8
|
+
import { StateError } from "../runner/errors.ts";
|
|
9
|
+
import { applyInput, readState } from "../runner/service.ts";
|
|
10
|
+
|
|
11
|
+
export interface AnswerOptions {
|
|
12
|
+
readonly log: LogBackend;
|
|
13
|
+
readonly flow: FlowDefinition;
|
|
14
|
+
readonly runId: string;
|
|
15
|
+
/** The one choice a question of choices takes; absent for a form's answer. */
|
|
16
|
+
readonly choice: string | undefined;
|
|
17
|
+
/** The person's answer to each question, when the question was a form. */
|
|
18
|
+
readonly answers?: readonly AskQuestionAnswer[] | undefined;
|
|
19
|
+
readonly note?: string | undefined;
|
|
20
|
+
readonly actor: Actor;
|
|
21
|
+
readonly clock?: (() => number) | undefined;
|
|
22
|
+
/** Called once when the answer ends the run. */
|
|
23
|
+
readonly onEnded?:
|
|
24
|
+
| ((runId: string, state: KernelState) => Promise<void>)
|
|
25
|
+
| undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Answers the run's current wait and appends the resulting facts. */
|
|
29
|
+
export async function answerRun(options: AnswerOptions): Promise<KernelState> {
|
|
30
|
+
const state = await readState(options.log, options.runId);
|
|
31
|
+
const wait = state.wait;
|
|
32
|
+
if (state.status !== "waiting_person" || wait === null) {
|
|
33
|
+
throw new StateError(`run ${options.runId} is not waiting for a person`);
|
|
34
|
+
}
|
|
35
|
+
// Check the choice before recording anything, exactly as a recorded answer
|
|
36
|
+
// does; the payload built here is the one `decide` applies.
|
|
37
|
+
answerInput(
|
|
38
|
+
options.runId,
|
|
39
|
+
options.choice,
|
|
40
|
+
options.answers,
|
|
41
|
+
options.note,
|
|
42
|
+
options.actor,
|
|
43
|
+
)(wait);
|
|
44
|
+
|
|
45
|
+
const now = (options.clock ?? (() => Date.now()))();
|
|
46
|
+
const result = await applyInput(
|
|
47
|
+
options.log,
|
|
48
|
+
options.flow,
|
|
49
|
+
options.runId,
|
|
50
|
+
state,
|
|
51
|
+
{
|
|
52
|
+
kind: "person_answer",
|
|
53
|
+
waitId: wait.id,
|
|
54
|
+
...(options.choice === undefined ? {} : { choice: options.choice }),
|
|
55
|
+
...(options.answers === undefined ? {} : { answers: options.answers }),
|
|
56
|
+
...(options.note === undefined ? {} : { note: options.note }),
|
|
57
|
+
actor: options.actor,
|
|
58
|
+
},
|
|
59
|
+
now,
|
|
60
|
+
"person",
|
|
61
|
+
`answer:${wait.id}:${options.choice ?? "answers"}`,
|
|
62
|
+
{
|
|
63
|
+
beforeEnd: async (runId, ended) => {
|
|
64
|
+
await options.onEnded?.(runId, ended);
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
);
|
|
68
|
+
return result.state;
|
|
69
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/** A clock the test fires, for a test only. */
|
|
2
|
+
|
|
3
|
+
import type { Clock } from "../platform/index.ts";
|
|
4
|
+
|
|
5
|
+
interface Timer {
|
|
6
|
+
readonly handler: () => void;
|
|
7
|
+
readonly ms: number;
|
|
8
|
+
readonly deadline: number;
|
|
9
|
+
live: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface Waiter {
|
|
13
|
+
readonly predicate: () => boolean;
|
|
14
|
+
readonly resolve: () => void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ManualClock extends Clock {
|
|
18
|
+
/** Fires every timeout still scheduled; returns how many there were. */
|
|
19
|
+
fireTimeouts(): number;
|
|
20
|
+
/** Alias of `fireTimeouts`, for a test that only wants the timers it made. */
|
|
21
|
+
fireTimers(): number;
|
|
22
|
+
/** Fires only the timeouts set for `ms`; the others stay armed. */
|
|
23
|
+
fireTimeoutsOf(ms: number): number;
|
|
24
|
+
/** Fires every timeout whose requested delay is at most `maxMs`. */
|
|
25
|
+
fireUpTo(maxMs?: number): number;
|
|
26
|
+
/** Fires every timeout whose requested delay is above `minMs` and at most `maxMs`. */
|
|
27
|
+
fireBetween(minMs: number, maxMs: number): number;
|
|
28
|
+
/** Moves time forward, firing only the timeouts that are then due. */
|
|
29
|
+
advance(ms: number): number;
|
|
30
|
+
/** Moves time to `ms` from the start, for a test that names a deadline. */
|
|
31
|
+
advanceTo(ms: number): number;
|
|
32
|
+
/** Resolves once `predicate` holds; every timer change rechecks it. */
|
|
33
|
+
when(predicate: () => boolean): Promise<void>;
|
|
34
|
+
/** How many timeouts are scheduled right now. */
|
|
35
|
+
readonly pending: number;
|
|
36
|
+
/** How many timeouts have been scheduled, a new one after each output line. */
|
|
37
|
+
readonly scheduled: number;
|
|
38
|
+
/** How many grace waits were requested. */
|
|
39
|
+
readonly sleeps: number;
|
|
40
|
+
/** How many timers were cancelled, which shows a stall timer was reset. */
|
|
41
|
+
readonly clears: number;
|
|
42
|
+
/** Every timer set so far, with `live` false once fired or cleared. */
|
|
43
|
+
readonly timers: readonly {
|
|
44
|
+
readonly handler: () => void;
|
|
45
|
+
readonly ms: number;
|
|
46
|
+
readonly live: boolean;
|
|
47
|
+
}[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A clock a test drives: timeouts run only when the test fires them, and a
|
|
52
|
+
* grace wait returns at once. No test waits for real time: a test that needs
|
|
53
|
+
* to know a timer exists asks `when` and is woken by a timer change.
|
|
54
|
+
*/
|
|
55
|
+
export function manualClock(): ManualClock {
|
|
56
|
+
const timers = new Set<Timer>();
|
|
57
|
+
const waiters: Waiter[] = [];
|
|
58
|
+
let sleeps = 0;
|
|
59
|
+
let scheduled = 0;
|
|
60
|
+
let clears = 0;
|
|
61
|
+
let now = 0;
|
|
62
|
+
|
|
63
|
+
const notify = (): void => {
|
|
64
|
+
for (let index = waiters.length - 1; index >= 0; index -= 1) {
|
|
65
|
+
const waiter = waiters[index];
|
|
66
|
+
if (waiter === undefined || !waiter.predicate()) continue;
|
|
67
|
+
waiters.splice(index, 1);
|
|
68
|
+
waiter.resolve();
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const fire = (due: readonly Timer[]): number => {
|
|
73
|
+
for (const timer of due) {
|
|
74
|
+
timer.live = false;
|
|
75
|
+
timers.delete(timer);
|
|
76
|
+
}
|
|
77
|
+
for (const timer of due) timer.handler();
|
|
78
|
+
notify();
|
|
79
|
+
return due.length;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const clock: ManualClock = {
|
|
83
|
+
setTimeout(handler, ms = 0) {
|
|
84
|
+
const timer = { handler, ms, deadline: now + ms, live: true };
|
|
85
|
+
timers.add(timer);
|
|
86
|
+
scheduled += 1;
|
|
87
|
+
notify();
|
|
88
|
+
return timer;
|
|
89
|
+
},
|
|
90
|
+
clearTimeout(handle) {
|
|
91
|
+
clears += 1;
|
|
92
|
+
const timer = handle as Timer;
|
|
93
|
+
timer.live = false;
|
|
94
|
+
timers.delete(timer);
|
|
95
|
+
notify();
|
|
96
|
+
},
|
|
97
|
+
sleep() {
|
|
98
|
+
sleeps += 1;
|
|
99
|
+
return Promise.resolve();
|
|
100
|
+
},
|
|
101
|
+
fireTimeouts() {
|
|
102
|
+
return fire([...timers]);
|
|
103
|
+
},
|
|
104
|
+
fireTimers() {
|
|
105
|
+
return fire([...timers]);
|
|
106
|
+
},
|
|
107
|
+
fireTimeoutsOf(ms) {
|
|
108
|
+
return fire([...timers].filter((timer) => timer.ms === ms));
|
|
109
|
+
},
|
|
110
|
+
fireUpTo(maxMs = Number.POSITIVE_INFINITY) {
|
|
111
|
+
return fire([...timers].filter((timer) => timer.ms <= maxMs));
|
|
112
|
+
},
|
|
113
|
+
fireBetween(minMs, maxMs) {
|
|
114
|
+
return fire(
|
|
115
|
+
[...timers].filter((timer) => timer.ms > minMs && timer.ms <= maxMs),
|
|
116
|
+
);
|
|
117
|
+
},
|
|
118
|
+
advance(ms) {
|
|
119
|
+
now += ms;
|
|
120
|
+
const due = [...timers]
|
|
121
|
+
.filter((timer) => timer.deadline <= now)
|
|
122
|
+
.sort((left, right) => left.deadline - right.deadline);
|
|
123
|
+
return fire(due);
|
|
124
|
+
},
|
|
125
|
+
advanceTo(ms) {
|
|
126
|
+
if (ms <= now) return 0;
|
|
127
|
+
return clock.advance(ms - now);
|
|
128
|
+
},
|
|
129
|
+
when(predicate) {
|
|
130
|
+
if (predicate()) return Promise.resolve();
|
|
131
|
+
return new Promise<void>((resolve) => {
|
|
132
|
+
waiters.push({ predicate, resolve });
|
|
133
|
+
});
|
|
134
|
+
},
|
|
135
|
+
get pending() {
|
|
136
|
+
return timers.size;
|
|
137
|
+
},
|
|
138
|
+
get scheduled() {
|
|
139
|
+
return scheduled;
|
|
140
|
+
},
|
|
141
|
+
get sleeps() {
|
|
142
|
+
return sleeps;
|
|
143
|
+
},
|
|
144
|
+
get clears() {
|
|
145
|
+
return clears;
|
|
146
|
+
},
|
|
147
|
+
get timers() {
|
|
148
|
+
return [...timers];
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
return clock;
|
|
152
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Writing a config file, for a test only. */
|
|
2
|
+
|
|
3
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
4
|
+
import { configJson, configPath, type OperadConfig } from "../config/config.ts";
|
|
5
|
+
|
|
6
|
+
/** Writes a config file, replacing it atomically enough for one command. */
|
|
7
|
+
export async function writeConfig(
|
|
8
|
+
home: string,
|
|
9
|
+
config: OperadConfig,
|
|
10
|
+
): Promise<void> {
|
|
11
|
+
await mkdir(home, { recursive: true });
|
|
12
|
+
await writeFile(
|
|
13
|
+
configPath(home),
|
|
14
|
+
`${JSON.stringify(configJson(config), null, 2)}\n`,
|
|
15
|
+
);
|
|
16
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/** Scratch directories, file and process waits, and a free port, for a test only. */
|
|
2
|
+
|
|
3
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
4
|
+
import { chmod, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { basename, dirname } from "node:path";
|
|
7
|
+
import { waitForChange } from "../platform/index.ts";
|
|
8
|
+
|
|
9
|
+
const roots: string[] = [];
|
|
10
|
+
|
|
11
|
+
/** Whether a scratch directory is removed by `cleanupTempRoots`. */
|
|
12
|
+
export interface TempRootOptions {
|
|
13
|
+
/** Register it for cleanup; true by default. A test that removes its own root sets false. */
|
|
14
|
+
readonly track?: boolean | undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A scratch directory under the OS temporary directory, removed by
|
|
19
|
+
* `cleanupTempRoots`. It is outside the repository, so a file a test leaves
|
|
20
|
+
* behind is never in a tree that tools search.
|
|
21
|
+
*/
|
|
22
|
+
export async function tempRoot(
|
|
23
|
+
prefix = "operad-test-",
|
|
24
|
+
options: TempRootOptions = {},
|
|
25
|
+
): Promise<string> {
|
|
26
|
+
const root = await mkdtemp(`${realpathSync(tmpdir())}/${prefix}`);
|
|
27
|
+
if (options.track !== false) roots.push(root);
|
|
28
|
+
return root;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A second name for a scratch directory under the OS temporary directory. */
|
|
32
|
+
export function osTempRoot(prefix = "operad-test-"): Promise<string> {
|
|
33
|
+
return tempRoot(prefix);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Every scratch directory this test process made and has not cleaned. */
|
|
37
|
+
export function tempRoots(): readonly string[] {
|
|
38
|
+
return [...roots];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function unlock(path: string): Promise<void> {
|
|
42
|
+
try {
|
|
43
|
+
await chmod(path, 0o700);
|
|
44
|
+
const entries = await readdir(path, { withFileTypes: true });
|
|
45
|
+
for (const entry of entries) {
|
|
46
|
+
if (entry.isDirectory()) await unlock(`${path}/${entry.name}`);
|
|
47
|
+
}
|
|
48
|
+
} catch {
|
|
49
|
+
// The path may already be gone, or not be a directory.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Removes every scratch directory made by `tempRoot`. */
|
|
54
|
+
export async function cleanupTempRoots(): Promise<void> {
|
|
55
|
+
for (const root of roots.splice(0)) {
|
|
56
|
+
try {
|
|
57
|
+
await rm(root, { recursive: true, force: true });
|
|
58
|
+
} catch {
|
|
59
|
+
// A test that timed out can leave a directory it locked; unlock and retry.
|
|
60
|
+
await unlock(root);
|
|
61
|
+
await rm(root, { recursive: true, force: true });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Resolves when the file exists. A directory watch is the fast path; a look
|
|
68
|
+
* every 100 ms besides covers an event a watch missed while it was starting.
|
|
69
|
+
* With a deadline, throws once the time is past instead of waiting forever.
|
|
70
|
+
*/
|
|
71
|
+
export async function waitForFile(
|
|
72
|
+
path: string,
|
|
73
|
+
deadline?: number,
|
|
74
|
+
): Promise<void> {
|
|
75
|
+
while (!existsSync(path)) {
|
|
76
|
+
if (deadline !== undefined && Date.now() > deadline) {
|
|
77
|
+
throw new Error(`timed out waiting for ${path}`);
|
|
78
|
+
}
|
|
79
|
+
await waitForChange(dirname(path), basename(path), 100);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** True for a pid a test may signal: a finite integer above 1 (never 0, 1 or a group). */
|
|
84
|
+
export function signalable(pid: number | undefined): pid is number {
|
|
85
|
+
return pid !== undefined && Number.isInteger(pid) && pid > 1;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The pid a file holds, when it holds one a test may signal. */
|
|
89
|
+
export function pidValue(text: string): number | undefined {
|
|
90
|
+
const pid = Number(text.trim());
|
|
91
|
+
return signalable(pid) ? pid : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Resolves with the pid a process wrote to `path`, once the file holds one.
|
|
96
|
+
* The file may exist empty before its write, so existence is not enough.
|
|
97
|
+
*/
|
|
98
|
+
export async function waitForPid(path: string): Promise<number> {
|
|
99
|
+
for (;;) {
|
|
100
|
+
try {
|
|
101
|
+
const pid = pidValue(readFileSync(path, "utf8"));
|
|
102
|
+
if (pid !== undefined) return pid;
|
|
103
|
+
} catch {
|
|
104
|
+
// Not there yet.
|
|
105
|
+
}
|
|
106
|
+
await waitForChange(dirname(path), basename(path), 100);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** True while `kill -0` finds the pid: a zombie its parent has not reaped still counts. */
|
|
111
|
+
export function alive(pid: number): boolean {
|
|
112
|
+
try {
|
|
113
|
+
process.kill(pid, 0);
|
|
114
|
+
return true;
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Resolves when the pid is gone. There is no pid event to wait on, so this
|
|
122
|
+
* looks on a short bound. On timeout it throws with `ps -o stat,ppid`, so a
|
|
123
|
+
* zombie is told from a live process.
|
|
124
|
+
*/
|
|
125
|
+
export async function waitForGone(pid: number, timeoutMs = 5000): Promise<void> {
|
|
126
|
+
const deadline = Date.now() + timeoutMs;
|
|
127
|
+
while (alive(pid)) {
|
|
128
|
+
if (Date.now() >= deadline) {
|
|
129
|
+
const ps = Bun.spawnSync(["ps", "-o", "stat,ppid", "-p", String(pid)]);
|
|
130
|
+
throw new Error(
|
|
131
|
+
`pid ${pid} still present after ${timeoutMs} ms; ps -o stat,ppid: ${ps.stdout.toString().trim()}`,
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
await new Promise((resolve) => globalThis.setTimeout(resolve, 10));
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Resolves when `predicate` holds, without waiting out a fixed sleep. The
|
|
140
|
+
* timer only bounds the wait; it never decides when to look again.
|
|
141
|
+
*/
|
|
142
|
+
export async function waitUntil(
|
|
143
|
+
predicate: () => boolean,
|
|
144
|
+
timeoutMs = 2000,
|
|
145
|
+
stepMs = 10,
|
|
146
|
+
): Promise<void> {
|
|
147
|
+
const deadline = Date.now() + timeoutMs;
|
|
148
|
+
while (!predicate()) {
|
|
149
|
+
if (Date.now() >= deadline) {
|
|
150
|
+
throw new Error("timed out waiting for a condition");
|
|
151
|
+
}
|
|
152
|
+
await new Promise((resolve) => globalThis.setTimeout(resolve, stepMs));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A port no listener held when the probe closed, for a server under test. */
|
|
157
|
+
export async function freePort(): Promise<number> {
|
|
158
|
+
const server = Bun.serve({
|
|
159
|
+
hostname: "127.0.0.1",
|
|
160
|
+
port: 0,
|
|
161
|
+
fetch: () => new Response(""),
|
|
162
|
+
});
|
|
163
|
+
const port = server.port;
|
|
164
|
+
await server.stop(true);
|
|
165
|
+
if (port === undefined) throw new Error("the free-port probe bound no port");
|
|
166
|
+
return port;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Makes a directory and every parent, for a test that writes a file next. */
|
|
170
|
+
export async function makeDirectory(path: string): Promise<void> {
|
|
171
|
+
await mkdir(path, { recursive: true });
|
|
172
|
+
}
|