@niwa-labs/host 0.0.0-stage → 0.0.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 +2 -2
- package/package.json +16 -4
- package/src/access-actions.ts +193 -0
- package/src/access-control.ts +333 -0
- package/src/call-operations.ts +176 -0
- package/src/cockpit-catalog.ts +99 -0
- package/src/describe.ts +55 -0
- package/src/doors.ts +272 -0
- package/src/host-types.ts +43 -0
- package/src/host.ts +3346 -0
- package/src/index.ts +10 -0
- package/src/plugin-install.ts +249 -0
- package/src/state.ts +261 -0
- package/src/stores.ts +131 -0
- package/test/abandon.test.ts +58 -0
- package/test/action-refusal-restart.test.ts +46 -0
- package/test/action-step.test.ts +363 -0
- package/test/action-wait-restart.test.ts +96 -0
- package/test/builtin-actions.test.ts +21 -0
- package/test/cancel-steps.test.ts +150 -0
- package/test/catch-up.test.ts +378 -0
- package/test/causes.test.ts +138 -0
- package/test/client.test.ts +190 -0
- package/test/cockpit-catalog.test.ts +118 -0
- package/test/crash-between-steps.test.ts +88 -0
- package/test/declared-values.test.ts +175 -0
- package/test/deep-nested-pause.test.ts +147 -0
- package/test/fixtures/action-step-host.ts +166 -0
- package/test/fixtures/action-wait-restart-host.ts +62 -0
- package/test/fixtures/catch-up-host.ts +91 -0
- package/test/fixtures/causes-host.ts +78 -0
- package/test/fixtures/client-host.ts +52 -0
- package/test/fixtures/crash-between-steps-host.ts +71 -0
- package/test/fixtures/declared-values-host.ts +110 -0
- package/test/fixtures/intercept-order-host.ts +112 -0
- package/test/fixtures/intercept-step-host.ts +106 -0
- package/test/fixtures/live-frames-host.ts +81 -0
- package/test/fixtures/long-wait-host.ts +78 -0
- package/test/fixtures/nested-wait-host.ts +120 -0
- package/test/fixtures/no-repeat-crash-host.ts +79 -0
- package/test/fixtures/plugin-replace-host.ts +176 -0
- package/test/fixtures/record-refusal-crash.ts +50 -0
- package/test/fixtures/recovery-contracts-host.ts +79 -0
- package/test/fixtures/repeated-write-host.ts +39 -0
- package/test/fixtures/replay-mismatch-host.ts +66 -0
- package/test/fixtures/single-writer-host.ts +113 -0
- package/test/fixtures/state-host.ts +118 -0
- package/test/fixtures/wait-restart-host.ts +82 -0
- package/test/guards.test.ts +448 -0
- package/test/handler-emit.test.ts +116 -0
- package/test/host.test.ts +114 -0
- package/test/intercept-adjust.test.ts +318 -0
- package/test/intercept-order.test.ts +276 -0
- package/test/intercept-step.test.ts +144 -0
- package/test/large-outcome.test.ts +60 -0
- package/test/live-frames.test.ts +150 -0
- package/test/live-ready.test.ts +61 -0
- package/test/long-wait.test.ts +168 -0
- package/test/nested-outcome.test.ts +75 -0
- package/test/nested-wait.test.ts +111 -0
- package/test/no-repeat-crash.test.ts +132 -0
- package/test/offer-replace.test.ts +39 -0
- package/test/plugin-async-setup.test.ts +22 -0
- package/test/plugin-copies.test.ts +87 -0
- package/test/plugin-emit.test.ts +43 -0
- package/test/plugin-install-failure.test.ts +121 -0
- package/test/plugin-install-hash.test.ts +57 -0
- package/test/plugin-needs.test.ts +80 -0
- package/test/plugin-replace.test.ts +225 -0
- package/test/plugin-uninstall.test.ts +70 -0
- package/test/plugin-version-copies.test.ts +53 -0
- package/test/plugin-version.test.ts +180 -0
- package/test/read-filter.test.ts +136 -0
- package/test/read-query.test.ts +92 -0
- package/test/record-admission.test.ts +294 -0
- package/test/recovery-contracts.test.ts +107 -0
- package/test/repeated-write.test.ts +119 -0
- package/test/replay-mismatch.test.ts +79 -0
- package/test/replay.test.ts +135 -0
- package/test/single-writer.test.ts +267 -0
- package/test/state.test.ts +246 -0
- package/test/step-by-name.test.ts +122 -0
- package/test/stores.test.ts +102 -0
- package/test/stream.test.ts +154 -0
- package/test/subscriber-stream.test.ts +71 -0
- package/test/subscribers.test.ts +101 -0
- package/test/subscriptions.test.ts +632 -0
- package/test/trace-call.test.ts +124 -0
- package/test/trigger-filter.test.ts +42 -0
- package/test/use-many.test.ts +151 -0
- package/test/wait-query.test.ts +117 -0
- package/test/wait-restart.test.ts +187 -0
- package/test/wire-read-access.test.ts +85 -0
- package/tsconfig.json +6 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The host program for the scenario "waiting survives a restart".
|
|
2
|
+
//
|
|
3
|
+
// The plugin declares two record types: Start { q } wakes the handler, and
|
|
4
|
+
// Answer { q, text } is what the handler waits for. Its handler has three steps:
|
|
5
|
+
//
|
|
6
|
+
// await step(ask, { q }) // the question: counted, and its outcome recorded
|
|
7
|
+
// await step.wait(Answer, { filter: { q: q } }) // the wait: the invocation suspends
|
|
8
|
+
// await step(after, { text: answer.text }) // what happens once the answer arrives
|
|
9
|
+
//
|
|
10
|
+
// The test kills the host while the invocation is waiting, so the answer never
|
|
11
|
+
// arrives in the first process. On restart the invocation resumes: the question
|
|
12
|
+
// replays from its recorded outcome (ask is not called again) and the wait is
|
|
13
|
+
// still open. The answer that arrives afterwards satisfies the wait, the second
|
|
14
|
+
// step runs, and the invocation ends as done.
|
|
15
|
+
//
|
|
16
|
+
// The home directory comes from argv[2]. The test imports this file for the
|
|
17
|
+
// record types, so the host only starts when the file is run directly.
|
|
18
|
+
|
|
19
|
+
import { createNiwa } from "@niwa-labs/host";
|
|
20
|
+
import { plugin } from "@niwa-labs/plugin";
|
|
21
|
+
import { record } from "@niwa-labs/core";
|
|
22
|
+
import { stubAction } from "@niwa-labs/testing";
|
|
23
|
+
import { z } from "zod";
|
|
24
|
+
|
|
25
|
+
/** Wakes the handler. */
|
|
26
|
+
export const Start = record("wait-restart.start", z.object({ q: z.string() }), { open: true });
|
|
27
|
+
|
|
28
|
+
/** What the handler waits for. */
|
|
29
|
+
export const Answer = record("wait-restart.answer", z.object({ q: z.string(), text: z.string() }), { open: true });
|
|
30
|
+
|
|
31
|
+
/** The plugin of this scenario. It needs the home: the stubs count there. */
|
|
32
|
+
export function makePlugin(home: string) {
|
|
33
|
+
// The question. Every call is counted, so the test can tell "asked once" from
|
|
34
|
+
// "asked again" across the crash.
|
|
35
|
+
const ask = stubAction("ask", {
|
|
36
|
+
home,
|
|
37
|
+
input: z.object({ q: z.string() }),
|
|
38
|
+
output: z.boolean(),
|
|
39
|
+
recovery: "repeat",
|
|
40
|
+
effect: "write",
|
|
41
|
+
result: () => true,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// What happens after the answer arrives. Counted too.
|
|
45
|
+
const after = stubAction("after", {
|
|
46
|
+
home,
|
|
47
|
+
input: z.object({ text: z.string() }),
|
|
48
|
+
output: z.string(),
|
|
49
|
+
recovery: "repeat",
|
|
50
|
+
effect: "write",
|
|
51
|
+
result: (input) => input.text,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
return plugin("wait-restart", (api) => {
|
|
55
|
+
api.declare(Start, Answer);
|
|
56
|
+
api.action(ask);
|
|
57
|
+
api.action(after);
|
|
58
|
+
api.on(Start, async (data, step) => {
|
|
59
|
+
await step(ask, { q: data.q });
|
|
60
|
+
|
|
61
|
+
const { data: answer } = await step.wait(Answer, { filter: { q: data.q } });
|
|
62
|
+
|
|
63
|
+
await step(after, { text: answer.text });
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (import.meta.main) {
|
|
69
|
+
const home = process.argv[2];
|
|
70
|
+
if (!home) {
|
|
71
|
+
console.error("usage: bun wait-restart-host.ts <home>");
|
|
72
|
+
process.exit(2);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const niwa = createNiwa({ home });
|
|
76
|
+
niwa.use(makePlugin(home));
|
|
77
|
+
await niwa.serve();
|
|
78
|
+
|
|
79
|
+
process.on("SIGTERM", () => {
|
|
80
|
+
void niwa.close().then(() => process.exit(0));
|
|
81
|
+
});
|
|
82
|
+
}
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
// Guards of the invocation: step keys, a swallowed refusal of the journal, a retry of a wait.
|
|
2
|
+
|
|
3
|
+
import { expect, test } from "bun:test";
|
|
4
|
+
|
|
5
|
+
import { action, deny, record, seq } from "@niwa-labs/core";
|
|
6
|
+
import { createNiwa } from "@niwa-labs/host";
|
|
7
|
+
import { plugin } from "@niwa-labs/plugin";
|
|
8
|
+
import type { ActionContext, NewRecord, StoredRecord } from "@niwa-labs/core";
|
|
9
|
+
import type { StateHandle } from "@niwa-labs/plugin";
|
|
10
|
+
import { eventually, tempHome, connectAsOwner } from "@niwa-labs/testing";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
|
|
13
|
+
import { runInvocation, NO_INTERCEPTS, openJournal } from "@niwa-labs/core/journal";
|
|
14
|
+
import type { InvocationSpec, RunnerDeps } from "@niwa-labs/core/journal";
|
|
15
|
+
import { CORE_TYPES, recordId, streamId } from "@niwa-labs/core";
|
|
16
|
+
import type { HandlerId, InvocationId } from "@niwa-labs/core";
|
|
17
|
+
|
|
18
|
+
const Start = record("guards.start", z.object({}));
|
|
19
|
+
const Note = record("guards.note", z.object({}));
|
|
20
|
+
const Other = record("guards.other", z.object({}));
|
|
21
|
+
|
|
22
|
+
const STATE_TYPE = "niwa.invocation.state";
|
|
23
|
+
|
|
24
|
+
type StateData = { invocation: string; state: string; reason?: string; choices?: string[] };
|
|
25
|
+
|
|
26
|
+
/** An in-process host with a plugin, and the states of its invocations as they are recorded. */
|
|
27
|
+
async function hosted(setup: Parameters<typeof plugin>[1]) {
|
|
28
|
+
const home = await tempHome();
|
|
29
|
+
const niwa = createNiwa({ home: home.path });
|
|
30
|
+
niwa.use(plugin("guards", setup));
|
|
31
|
+
await niwa.serve();
|
|
32
|
+
const seen: StoredRecord[] = [];
|
|
33
|
+
const watching = (async () => {
|
|
34
|
+
for await (const rec of niwa.records.since()) seen.push(rec);
|
|
35
|
+
})();
|
|
36
|
+
return {
|
|
37
|
+
niwa,
|
|
38
|
+
home: home.path,
|
|
39
|
+
states: (): StateData[] =>
|
|
40
|
+
seen.filter((r) => r.type === STATE_TYPE).map((r) => r.data as StateData),
|
|
41
|
+
close: async () => {
|
|
42
|
+
await niwa.close();
|
|
43
|
+
await watching.catch(() => {});
|
|
44
|
+
await home.cleanup();
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
test("a step key with a separator is refused at the call", async () => {
|
|
50
|
+
for (const key of ["a/b", "a#2"]) {
|
|
51
|
+
const h = await hosted((api) => {
|
|
52
|
+
api.declare(Start);
|
|
53
|
+
api.on(Start, async (_data, step) => {
|
|
54
|
+
await step.now({ key });
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
try {
|
|
58
|
+
await h.niwa.emit(Start, {});
|
|
59
|
+
await eventually(() => h.states().at(-1)?.state === "paused", 10_000, "the key is refused");
|
|
60
|
+
expect(h.states().at(-1)?.reason).toContain('step key must not contain "/" or "#"');
|
|
61
|
+
} finally {
|
|
62
|
+
await h.close();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("a handler that swallows the refusal of the journal does not continue", async () => {
|
|
68
|
+
const home = await tempHome();
|
|
69
|
+
const journal = openJournal(home.path);
|
|
70
|
+
const refuse = new Error("disk full");
|
|
71
|
+
let refusing = false;
|
|
72
|
+
const deps: RunnerDeps = {
|
|
73
|
+
journal,
|
|
74
|
+
now: () => Date.now(),
|
|
75
|
+
append: (recs: NewRecord[]) => {
|
|
76
|
+
if (refusing && recs.some((r) => r.type === CORE_TYPES.stepIntent)) throw refuse;
|
|
77
|
+
return journal.appendMany(recs);
|
|
78
|
+
},
|
|
79
|
+
appendAll: (entries) => journal.appendAll(entries),
|
|
80
|
+
resolveAction: () => undefined,
|
|
81
|
+
interceptsOf: () => NO_INTERCEPTS,
|
|
82
|
+
emit: () => Promise.reject(new Error("no emit in this test")),
|
|
83
|
+
};
|
|
84
|
+
const wake = journal.append({
|
|
85
|
+
id: recordId("rec-wake"),
|
|
86
|
+
stream: streamId("test"),
|
|
87
|
+
type: Start.name,
|
|
88
|
+
schema: 1,
|
|
89
|
+
data: {},
|
|
90
|
+
actor: { kind: "host" },
|
|
91
|
+
cause: null,
|
|
92
|
+
root: recordId("rec-wake"),
|
|
93
|
+
});
|
|
94
|
+
let after = 0;
|
|
95
|
+
const send = action("guards.send", {
|
|
96
|
+
description: "never runs",
|
|
97
|
+
input: z.object({}),
|
|
98
|
+
output: z.object({}),
|
|
99
|
+
recovery: "repeat",
|
|
100
|
+
effect: "write",
|
|
101
|
+
run: async () => ({}),
|
|
102
|
+
});
|
|
103
|
+
const spec: InvocationSpec = {
|
|
104
|
+
id: "inv:guards/start:rec-wake" as InvocationId,
|
|
105
|
+
handlerId: "guards/start" as HandlerId,
|
|
106
|
+
record: wake,
|
|
107
|
+
parse: (data) => data,
|
|
108
|
+
handler: async (_data, step) => {
|
|
109
|
+
try {
|
|
110
|
+
await step(send, {});
|
|
111
|
+
} catch {
|
|
112
|
+
// swallowed
|
|
113
|
+
}
|
|
114
|
+
after += 1;
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
try {
|
|
118
|
+
refusing = true;
|
|
119
|
+
await expect(runInvocation(deps, spec)).rejects.toBe(refuse);
|
|
120
|
+
expect(after).toBe(1);
|
|
121
|
+
const states = journal.find({ type: CORE_TYPES.invocationState }).map((r) => r.data);
|
|
122
|
+
expect(states.some((d) => (d as StateData).state === "done")).toBe(false);
|
|
123
|
+
} finally {
|
|
124
|
+
journal.close();
|
|
125
|
+
await home.cleanup();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("a wait step cannot be retried, only cancelled", async () => {
|
|
130
|
+
let run = 0;
|
|
131
|
+
const h = await hosted((api) => {
|
|
132
|
+
api.declare(Start, Note, Other);
|
|
133
|
+
api.on(Start, async (_data, step) => {
|
|
134
|
+
run += 1;
|
|
135
|
+
if (run === 1) await step.wait(Note, { key: "k" });
|
|
136
|
+
else await step.wait(Other, { key: "k" });
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
try {
|
|
140
|
+
await h.niwa.emit(Start, {});
|
|
141
|
+
await eventually(() => h.states().at(-1)?.state === "waiting", 10_000, "run 1 waits");
|
|
142
|
+
await h.niwa.emit(Note, {});
|
|
143
|
+
await eventually(() => h.states().at(-1)?.state === "paused", 10_000, "run 2 pauses");
|
|
144
|
+
const invocation = h.states().at(-1)?.invocation ?? "";
|
|
145
|
+
expect(h.states().at(-1)?.reason).toBe("replay mismatch at step k");
|
|
146
|
+
// The pause offers what the core accepts for it: a wait is only cancelled.
|
|
147
|
+
expect(h.states().at(-1)?.choices).toEqual(["cancel"]);
|
|
148
|
+
for (const choice of ["retry", "skip"]) {
|
|
149
|
+
await expect(
|
|
150
|
+
h.niwa.call("niwa.invocation.resolve" as never, { invocation, choice } as never),
|
|
151
|
+
).rejects.toThrow("is a wait");
|
|
152
|
+
}
|
|
153
|
+
await h.niwa.call("niwa.invocation.resolve" as never, { invocation, choice: "cancel" } as never);
|
|
154
|
+
await eventually(() => h.states().at(-1)?.state === "done", 10_000, "cancelled");
|
|
155
|
+
} finally {
|
|
156
|
+
await h.close();
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("a pause on no step offers retry and cancel, and the core refuses a skip it does not offer", async () => {
|
|
161
|
+
let run = 0;
|
|
162
|
+
const h = await hosted((api) => {
|
|
163
|
+
api.declare(Start);
|
|
164
|
+
api.on(Start, async () => {
|
|
165
|
+
run += 1;
|
|
166
|
+
if (run === 1) throw new Error("boom");
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
try {
|
|
170
|
+
await h.niwa.emit(Start, {});
|
|
171
|
+
await eventually(() => h.states().at(-1)?.state === "paused", 10_000, "the handler error pauses");
|
|
172
|
+
const paused = h.states().at(-1);
|
|
173
|
+
expect(paused).toMatchObject({ reason: "handler error: boom", choices: ["retry", "cancel"] });
|
|
174
|
+
const invocation = paused?.invocation ?? "";
|
|
175
|
+
await expect(
|
|
176
|
+
h.niwa.call("niwa.invocation.resolve" as never, { invocation, choice: "skip" } as never),
|
|
177
|
+
).rejects.toThrow("does not offer skip");
|
|
178
|
+
await h.niwa.call("niwa.invocation.resolve" as never, { invocation, choice: "retry" } as never);
|
|
179
|
+
await eventually(() => h.states().at(-1)?.state === "done", 10_000, "the retry goes on");
|
|
180
|
+
} finally {
|
|
181
|
+
await h.close();
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
test("the answer to a paused invocation is written by the caller who gave it", async () => {
|
|
186
|
+
let run = 0;
|
|
187
|
+
const h = await hosted((api) => {
|
|
188
|
+
api.declare(Start, Note, Other);
|
|
189
|
+
api.on(Start, async (_data, step) => {
|
|
190
|
+
run += 1;
|
|
191
|
+
if (run === 1) await step.wait(Note, { key: "k" });
|
|
192
|
+
else await step.wait(Other, { key: "k" });
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
try {
|
|
196
|
+
await h.niwa.emit(Start, {});
|
|
197
|
+
await eventually(() => h.states().at(-1)?.state === "waiting", 10_000, "run 1 waits");
|
|
198
|
+
await h.niwa.emit(Note, {});
|
|
199
|
+
await eventually(() => h.states().at(-1)?.state === "paused", 10_000, "run 2 pauses");
|
|
200
|
+
const invocation = h.states().at(-1)?.invocation ?? "";
|
|
201
|
+
const client = await connectAsOwner(h.home);
|
|
202
|
+
try {
|
|
203
|
+
await client.call("niwa.invocation.resolve" as never, { invocation, choice: "cancel" } as never);
|
|
204
|
+
const resolved: StoredRecord[] = [];
|
|
205
|
+
for await (const rec of client.records.since({ types: ["niwa.invocation.resolved" as never] })) {
|
|
206
|
+
resolved.push(rec);
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
expect(resolved[0]?.actor.kind).toBe("client");
|
|
210
|
+
} finally {
|
|
211
|
+
await client.close();
|
|
212
|
+
}
|
|
213
|
+
} finally {
|
|
214
|
+
await h.close();
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("a wake of a call waiting inside an action asks no guard again and writes nothing", async () => {
|
|
219
|
+
const Reply = record("guards.reply", z.object({ ok: z.boolean() }));
|
|
220
|
+
let guards = 0;
|
|
221
|
+
const ran: string[] = [];
|
|
222
|
+
const ask = action("guards.ask", {
|
|
223
|
+
description: "Waits for a good reply.",
|
|
224
|
+
input: z.object({ text: z.string() }),
|
|
225
|
+
output: z.object({ text: z.string() }),
|
|
226
|
+
recovery: "do-not-repeat",
|
|
227
|
+
effect: "write",
|
|
228
|
+
async run(input, ctx) {
|
|
229
|
+
ran.push(input.text);
|
|
230
|
+
await ctx.wait(Reply, { filter: { ok: true } });
|
|
231
|
+
return input;
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
const h = await hosted((api) => {
|
|
235
|
+
api.declare(Start, Reply);
|
|
236
|
+
api.action(ask);
|
|
237
|
+
api.guard(ask, () => ((guards += 1) > 1 ? deny("asked again") : undefined));
|
|
238
|
+
api.on(Start, async (_data, step) => {
|
|
239
|
+
await step(ask, { text: "requested" });
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
try {
|
|
243
|
+
await h.niwa.emit(Start, {});
|
|
244
|
+
await eventually(() => h.states().at(-1)?.state === "waiting", 10_000, "the call waits");
|
|
245
|
+
const before = (await h.niwa.records.read()).filter((r) => r.stream.startsWith("invocation:")).length;
|
|
246
|
+
|
|
247
|
+
await h.niwa.emit(Reply, { ok: false });
|
|
248
|
+
await eventually(() => ran.length === 2, 10_000, "the wake does not enter the call again");
|
|
249
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
250
|
+
expect((await h.niwa.records.read()).filter((r) => r.stream.startsWith("invocation:"))).toHaveLength(before);
|
|
251
|
+
expect(guards).toBe(1);
|
|
252
|
+
|
|
253
|
+
await h.niwa.emit(Reply, { ok: true });
|
|
254
|
+
await eventually(() => h.states().at(-1)?.state === "done", 10_000, "the answer ends it");
|
|
255
|
+
expect(ran).toEqual(["requested", "requested", "requested"]);
|
|
256
|
+
expect(guards).toBe(1);
|
|
257
|
+
} finally {
|
|
258
|
+
await h.close();
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
test("a waiting call whose adjust now decides otherwise is decided again, and a denial is recorded", async () => {
|
|
263
|
+
const Reply = record("guards.reply", z.object({ ok: z.boolean() }));
|
|
264
|
+
let adjusts = 0;
|
|
265
|
+
const ask = action("guards.ask", {
|
|
266
|
+
description: "Waits for a good reply.",
|
|
267
|
+
input: z.object({ text: z.string() }),
|
|
268
|
+
output: z.object({ text: z.string() }),
|
|
269
|
+
recovery: "do-not-repeat",
|
|
270
|
+
effect: "write",
|
|
271
|
+
async run(input, ctx) {
|
|
272
|
+
await ctx.wait(Reply, { filter: { ok: true } });
|
|
273
|
+
return input;
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
const h = await hosted((api) => {
|
|
277
|
+
api.declare(Start, Reply);
|
|
278
|
+
api.action(ask);
|
|
279
|
+
api.adjust(ask, () => ({ text: `adjusted-${String((adjusts += 1))}` }));
|
|
280
|
+
api.guard(ask, (input) => (input.text === "adjusted-1" ? undefined : deny("changed")));
|
|
281
|
+
api.on(Start, async (_data, step) => {
|
|
282
|
+
await step(ask, { text: "requested" });
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
try {
|
|
286
|
+
await h.niwa.emit(Start, {});
|
|
287
|
+
await eventually(() => h.states().at(-1)?.state === "waiting", 10_000, "the call waits");
|
|
288
|
+
await h.niwa.emit(Reply, { ok: false });
|
|
289
|
+
await eventually(() => h.states().at(-1)?.state === "paused", 10_000, "the denial pauses it");
|
|
290
|
+
const decisions = (await h.niwa.records.read()).filter((r) => r.type === CORE_TYPES.stepDecision);
|
|
291
|
+
expect(decisions.map((r) => (r.data as { denied: boolean; reason?: string }).reason)).toEqual([undefined, "changed"]);
|
|
292
|
+
} finally {
|
|
293
|
+
await h.close();
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
/** The waiting action of the wake tests: it enters again on every reply, and `again` runs from the second entry on. */
|
|
298
|
+
function waitingAsk(entered: { count: number }, again: (ctx: ActionContext) => void | Promise<void>, Reply: ReturnType<typeof record<{ ok: boolean }>>) {
|
|
299
|
+
return action("guards.ask", {
|
|
300
|
+
description: "Waits for a good reply.",
|
|
301
|
+
input: z.object({ text: z.string() }),
|
|
302
|
+
output: z.object({ text: z.string() }),
|
|
303
|
+
recovery: "do-not-repeat",
|
|
304
|
+
effect: "write",
|
|
305
|
+
async run(input, ctx) {
|
|
306
|
+
entered.count += 1;
|
|
307
|
+
if (entered.count === 2) await again(ctx);
|
|
308
|
+
await ctx.wait(Reply, { filter: { ok: true } });
|
|
309
|
+
return input;
|
|
310
|
+
},
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
test("a re-decision that matches the latest recorded one is not recorded again", async () => {
|
|
315
|
+
const Reply = record("guards.reply", z.object({ ok: z.boolean() }));
|
|
316
|
+
const entered = { count: 0 };
|
|
317
|
+
let adjusts = 0;
|
|
318
|
+
const ask = waitingAsk(entered, () => {}, Reply);
|
|
319
|
+
const h = await hosted((api) => {
|
|
320
|
+
api.declare(Start, Reply);
|
|
321
|
+
api.action(ask);
|
|
322
|
+
// The first call is adjusted to "a", every later one to "b": the decision changes once and settles.
|
|
323
|
+
api.adjust(ask, () => ({ text: (adjusts += 1) === 1 ? "a" : "b" }));
|
|
324
|
+
api.on(Start, async (_data, step) => {
|
|
325
|
+
await step(ask, { text: "requested" });
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
try {
|
|
329
|
+
await h.niwa.emit(Start, {});
|
|
330
|
+
await eventually(() => h.states().at(-1)?.state === "waiting", 10_000, "the call waits");
|
|
331
|
+
await h.niwa.emit(Reply, { ok: false });
|
|
332
|
+
await eventually(() => entered.count === 2, 10_000, "the first wake");
|
|
333
|
+
await h.niwa.emit(Reply, { ok: false });
|
|
334
|
+
await eventually(() => entered.count === 3, 10_000, "the second wake");
|
|
335
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
336
|
+
const decisions = (await h.niwa.records.read()).filter((r) => r.type === CORE_TYPES.stepDecision);
|
|
337
|
+
expect(decisions.map((r) => (r.data as { final: { text: string } }).final.text)).toEqual(["a", "b"]);
|
|
338
|
+
} finally {
|
|
339
|
+
await h.close();
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
test("a guard that denies a waiting call on the same final input records the denial", async () => {
|
|
344
|
+
const Reply = record("guards.reply", z.object({ ok: z.boolean() }));
|
|
345
|
+
const entered = { count: 0 };
|
|
346
|
+
let guards = 0;
|
|
347
|
+
const ask = waitingAsk(entered, () => {}, Reply);
|
|
348
|
+
const h = await hosted((api) => {
|
|
349
|
+
api.declare(Start, Reply);
|
|
350
|
+
api.action(ask);
|
|
351
|
+
// The adjust always gives the same final input, so only the guard's answer differs between wakes.
|
|
352
|
+
api.adjust(ask, () => ({ text: "fixed" }));
|
|
353
|
+
api.guard(ask, () => ((guards += 1) > 1 ? deny("not any more") : undefined));
|
|
354
|
+
api.on(Start, async (_data, step) => {
|
|
355
|
+
await step(ask, { text: "requested" });
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
try {
|
|
359
|
+
await h.niwa.emit(Start, {});
|
|
360
|
+
await eventually(() => h.states().at(-1)?.state === "waiting", 10_000, "the call waits");
|
|
361
|
+
await h.niwa.emit(Reply, { ok: false });
|
|
362
|
+
await eventually(() => h.states().at(-1)?.state === "paused", 10_000, "the denial pauses it");
|
|
363
|
+
const decisions = (await h.niwa.records.read()).filter((r) => r.type === CORE_TYPES.stepDecision);
|
|
364
|
+
expect(decisions.map((r) => (r.data as { denied: boolean }).denied)).toEqual([false, true]);
|
|
365
|
+
} finally {
|
|
366
|
+
await h.close();
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
for (const op of ["get", "set", "update", "take", "emit"] as const) {
|
|
371
|
+
test(`a woken run that first writes with a state ${op} says running before that write, once`, async () => {
|
|
372
|
+
const Reply = record("guards.reply", z.object({ ok: z.boolean() }));
|
|
373
|
+
const entered = { count: 0 };
|
|
374
|
+
let box: StateHandle<number> | undefined;
|
|
375
|
+
const ask = waitingAsk(
|
|
376
|
+
entered,
|
|
377
|
+
async (ctx) => {
|
|
378
|
+
if (box === undefined) throw new Error("the plugin is not set up");
|
|
379
|
+
if (op === "get") box.get();
|
|
380
|
+
if (op === "set") box.set(1);
|
|
381
|
+
if (op === "update") box.update((n) => n + 1);
|
|
382
|
+
if (op === "take") box.take();
|
|
383
|
+
if (op === "emit") await ctx.emit(Note, {});
|
|
384
|
+
},
|
|
385
|
+
Reply,
|
|
386
|
+
);
|
|
387
|
+
const h = await hosted((api) => {
|
|
388
|
+
api.declare(Start, Reply, Note);
|
|
389
|
+
api.action(ask);
|
|
390
|
+
box = api.state("box", z.number(), 0);
|
|
391
|
+
api.on(Start, async (_data, step) => {
|
|
392
|
+
await step(ask, { text: "requested" });
|
|
393
|
+
});
|
|
394
|
+
});
|
|
395
|
+
try {
|
|
396
|
+
await h.niwa.emit(Start, {});
|
|
397
|
+
await eventually(() => h.states().at(-1)?.state === "waiting", 10_000, "the call waits");
|
|
398
|
+
await h.niwa.emit(Reply, { ok: false });
|
|
399
|
+
await eventually(() => h.states().map((s) => s.state).join() === "running,waiting,running,waiting", 10_000, "the wake");
|
|
400
|
+
const written = (await h.niwa.records.read()).filter((r) =>
|
|
401
|
+
[STATE_TYPE, CORE_TYPES.stateRead, CORE_TYPES.stateChanged, Note.name].includes(r.type),
|
|
402
|
+
);
|
|
403
|
+
const first = written.findIndex((r) => r.type !== STATE_TYPE && r.seq > written[1]!.seq);
|
|
404
|
+
expect(first).toBeGreaterThan(-1);
|
|
405
|
+
expect((written[first - 1]!.data as StateData).state).toBe("running");
|
|
406
|
+
expect(written.slice(first - 1).filter((r) => r.type === STATE_TYPE).map((r) => (r.data as StateData).state)).toEqual(["running", "waiting"]);
|
|
407
|
+
} finally {
|
|
408
|
+
await h.close();
|
|
409
|
+
}
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
test("a plain wake of a call that emitted before finds its record and writes nothing", async () => {
|
|
414
|
+
const Reply = record("guards.reply", z.object({ ok: z.boolean() }));
|
|
415
|
+
const entered = { count: 0 };
|
|
416
|
+
const ask = action("guards.ask", {
|
|
417
|
+
description: "Emits, then waits for a good reply.",
|
|
418
|
+
input: z.object({ text: z.string() }),
|
|
419
|
+
output: z.object({ text: z.string() }),
|
|
420
|
+
recovery: "do-not-repeat",
|
|
421
|
+
effect: "write",
|
|
422
|
+
async run(input, ctx) {
|
|
423
|
+
entered.count += 1;
|
|
424
|
+
await ctx.emit(Note, {});
|
|
425
|
+
await ctx.wait(Reply, { filter: { ok: true } });
|
|
426
|
+
return input;
|
|
427
|
+
},
|
|
428
|
+
});
|
|
429
|
+
const h = await hosted((api) => {
|
|
430
|
+
api.declare(Start, Reply, Note);
|
|
431
|
+
api.action(ask);
|
|
432
|
+
api.on(Start, async (_data, step) => {
|
|
433
|
+
await step(ask, { text: "requested" });
|
|
434
|
+
});
|
|
435
|
+
});
|
|
436
|
+
try {
|
|
437
|
+
await h.niwa.emit(Start, {});
|
|
438
|
+
await eventually(() => h.states().at(-1)?.state === "waiting", 10_000, "the call waits");
|
|
439
|
+
const before = (await h.niwa.records.read()).length;
|
|
440
|
+
await h.niwa.emit(Reply, { ok: false });
|
|
441
|
+
await eventually(() => entered.count === 2, 10_000, "the wake");
|
|
442
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
443
|
+
// Only the reply itself is new.
|
|
444
|
+
expect(await h.niwa.records.read()).toHaveLength(before + 1);
|
|
445
|
+
} finally {
|
|
446
|
+
await h.close();
|
|
447
|
+
}
|
|
448
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// What a handler writes is held to the same rules as a record written over the wire: the plugin
|
|
2
|
+
// that owns the type writes it, or a grant lets the writer; the data is read through the owner's
|
|
3
|
+
// schema. And a type has one owner.
|
|
4
|
+
|
|
5
|
+
import { expect, test } from "bun:test";
|
|
6
|
+
|
|
7
|
+
import { CORE_TYPES, record, seq } from "@niwa-labs/core";
|
|
8
|
+
import type { StoredRecord } from "@niwa-labs/core";
|
|
9
|
+
import { createNiwa } from "@niwa-labs/host";
|
|
10
|
+
import { plugin } from "@niwa-labs/plugin";
|
|
11
|
+
import type { Plugin } from "@niwa-labs/plugin";
|
|
12
|
+
import { eventually, tempHome } from "@niwa-labs/testing";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
|
|
15
|
+
const Item = record("sub-test.item", z.object({ n: z.number() }));
|
|
16
|
+
const Answer = record("sub-test.answer", z.object({ n: z.number() }));
|
|
17
|
+
const Echo = record("sub-test.echo", z.object({ n: z.number() }));
|
|
18
|
+
|
|
19
|
+
/** The plugin that declares the types and nothing else: what writes the records. */
|
|
20
|
+
const producer = (): Plugin => plugin("sub-producer", (api) => api.declare(Item, Answer));
|
|
21
|
+
|
|
22
|
+
type Host = ReturnType<typeof createNiwa>;
|
|
23
|
+
|
|
24
|
+
/** Serve a host on a home with these plugins. */
|
|
25
|
+
async function serving(home: string, plugins: Plugin[]): Promise<Host> {
|
|
26
|
+
const niwa = createNiwa({ home });
|
|
27
|
+
for (const one of plugins) niwa.use(one);
|
|
28
|
+
await niwa.serve();
|
|
29
|
+
return niwa;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const recordsOf = (niwa: Host, type?: string): Promise<StoredRecord[]> =>
|
|
33
|
+
niwa.records.read().then((rows) => (type === undefined ? rows : rows.filter((row) => row.type === type)));
|
|
34
|
+
|
|
35
|
+
const statesOf = async (niwa: Host): Promise<Array<{ invocation: string; state: string }>> =>
|
|
36
|
+
(await recordsOf(niwa, CORE_TYPES.invocationState)).map((row) => row.data as { invocation: string; state: string });
|
|
37
|
+
|
|
38
|
+
test("a handler may not write a type another plugin owns without a grant", async () => {
|
|
39
|
+
const home = await tempHome();
|
|
40
|
+
try {
|
|
41
|
+
const niwa = await serving(home.path, [
|
|
42
|
+
producer(),
|
|
43
|
+
plugin("sub-intruder", (api) => {
|
|
44
|
+
api.declare(Echo);
|
|
45
|
+
api.on(Echo, { from: "start" }, async (data, step) => {
|
|
46
|
+
await step.emit(Answer, { n: data.n });
|
|
47
|
+
});
|
|
48
|
+
}),
|
|
49
|
+
]);
|
|
50
|
+
await niwa.emit(Echo, { n: 1 });
|
|
51
|
+
await eventually(async () => (await statesOf(niwa)).some((one) => one.state === "paused"));
|
|
52
|
+
const paused = (await recordsOf(niwa, CORE_TYPES.invocationState)).find((row) => (row.data as { state: string }).state === "paused");
|
|
53
|
+
expect(String((paused?.data as { reason?: string }).reason)).toContain("sub-producer");
|
|
54
|
+
expect(await recordsOf(niwa, Answer.name)).toEqual([]);
|
|
55
|
+
await niwa.close();
|
|
56
|
+
} finally {
|
|
57
|
+
await home.cleanup();
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("a handler's record is checked against the schema of the type's owner, not the handler's copy", async () => {
|
|
62
|
+
const home = await tempHome();
|
|
63
|
+
try {
|
|
64
|
+
const Loose = record("sub-test.echo", z.object({ n: z.unknown() }));
|
|
65
|
+
const niwa = await serving(home.path, [
|
|
66
|
+
producer(),
|
|
67
|
+
plugin("sub-consumer", (api) => {
|
|
68
|
+
api.declare(Echo);
|
|
69
|
+
api.on(Item, async (_data, step) => {
|
|
70
|
+
await step.emit(Loose, { n: "not a number" });
|
|
71
|
+
});
|
|
72
|
+
}),
|
|
73
|
+
]);
|
|
74
|
+
await niwa.emit(Item, { n: 1 });
|
|
75
|
+
await eventually(async () => (await statesOf(niwa)).some((one) => one.state === "paused"));
|
|
76
|
+
expect(await recordsOf(niwa, Echo.name)).toEqual([]);
|
|
77
|
+
await niwa.close();
|
|
78
|
+
} finally {
|
|
79
|
+
await home.cleanup();
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("two plugins may not own one type, whether by name or under a family", async () => {
|
|
84
|
+
const exact = createNiwa({ home: (await tempHome()).path });
|
|
85
|
+
exact.use(producer());
|
|
86
|
+
expect(() => exact.use(plugin("sub-twin", (api) => api.declare(Item)))).toThrow(/sub-producer/);
|
|
87
|
+
const family = createNiwa({ home: (await tempHome()).path });
|
|
88
|
+
family.use(producer());
|
|
89
|
+
expect(() => family.use(plugin("sub-family", (api) => api.declare(record("sub-test.*", z.unknown()))))).toThrow(/sub-producer/);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("a plugin whose name has a slash writes its own types from its handlers, and not another's", async () => {
|
|
93
|
+
const home = await tempHome();
|
|
94
|
+
try {
|
|
95
|
+
const Own = record("slash-test.own", z.object({ n: z.number() }));
|
|
96
|
+
const niwa = await serving(home.path, [
|
|
97
|
+
producer(),
|
|
98
|
+
plugin("org", (api) => api.declare(Echo)),
|
|
99
|
+
plugin("org/app", (api) => {
|
|
100
|
+
api.declare(Own);
|
|
101
|
+
api.on(Item, async (data, step) => {
|
|
102
|
+
await step.emit(Own, { n: data.n });
|
|
103
|
+
if (data.n === 2) await step.emit(Echo, { n: data.n });
|
|
104
|
+
});
|
|
105
|
+
}),
|
|
106
|
+
]);
|
|
107
|
+
await niwa.emit(Item, { n: 1 });
|
|
108
|
+
await eventually(async () => (await recordsOf(niwa, Own.name)).length === 1);
|
|
109
|
+
await niwa.emit(Item, { n: 2 });
|
|
110
|
+
await eventually(async () => (await statesOf(niwa)).some((one) => one.state === "paused"));
|
|
111
|
+
expect(await recordsOf(niwa, Echo.name)).toEqual([]);
|
|
112
|
+
await niwa.close();
|
|
113
|
+
} finally {
|
|
114
|
+
await home.cleanup();
|
|
115
|
+
}
|
|
116
|
+
});
|