@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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -2
  3. package/package.json +16 -4
  4. package/src/access-actions.ts +193 -0
  5. package/src/access-control.ts +333 -0
  6. package/src/call-operations.ts +176 -0
  7. package/src/cockpit-catalog.ts +99 -0
  8. package/src/describe.ts +55 -0
  9. package/src/doors.ts +272 -0
  10. package/src/host-types.ts +43 -0
  11. package/src/host.ts +3346 -0
  12. package/src/index.ts +10 -0
  13. package/src/plugin-install.ts +249 -0
  14. package/src/state.ts +261 -0
  15. package/src/stores.ts +131 -0
  16. package/test/abandon.test.ts +58 -0
  17. package/test/action-refusal-restart.test.ts +46 -0
  18. package/test/action-step.test.ts +363 -0
  19. package/test/action-wait-restart.test.ts +96 -0
  20. package/test/builtin-actions.test.ts +21 -0
  21. package/test/cancel-steps.test.ts +150 -0
  22. package/test/catch-up.test.ts +378 -0
  23. package/test/causes.test.ts +138 -0
  24. package/test/client.test.ts +190 -0
  25. package/test/cockpit-catalog.test.ts +118 -0
  26. package/test/crash-between-steps.test.ts +88 -0
  27. package/test/declared-values.test.ts +175 -0
  28. package/test/deep-nested-pause.test.ts +147 -0
  29. package/test/fixtures/action-step-host.ts +166 -0
  30. package/test/fixtures/action-wait-restart-host.ts +62 -0
  31. package/test/fixtures/catch-up-host.ts +91 -0
  32. package/test/fixtures/causes-host.ts +78 -0
  33. package/test/fixtures/client-host.ts +52 -0
  34. package/test/fixtures/crash-between-steps-host.ts +71 -0
  35. package/test/fixtures/declared-values-host.ts +110 -0
  36. package/test/fixtures/intercept-order-host.ts +112 -0
  37. package/test/fixtures/intercept-step-host.ts +106 -0
  38. package/test/fixtures/live-frames-host.ts +81 -0
  39. package/test/fixtures/long-wait-host.ts +78 -0
  40. package/test/fixtures/nested-wait-host.ts +120 -0
  41. package/test/fixtures/no-repeat-crash-host.ts +79 -0
  42. package/test/fixtures/plugin-replace-host.ts +176 -0
  43. package/test/fixtures/record-refusal-crash.ts +50 -0
  44. package/test/fixtures/recovery-contracts-host.ts +79 -0
  45. package/test/fixtures/repeated-write-host.ts +39 -0
  46. package/test/fixtures/replay-mismatch-host.ts +66 -0
  47. package/test/fixtures/single-writer-host.ts +113 -0
  48. package/test/fixtures/state-host.ts +118 -0
  49. package/test/fixtures/wait-restart-host.ts +82 -0
  50. package/test/guards.test.ts +448 -0
  51. package/test/handler-emit.test.ts +116 -0
  52. package/test/host.test.ts +114 -0
  53. package/test/intercept-adjust.test.ts +318 -0
  54. package/test/intercept-order.test.ts +276 -0
  55. package/test/intercept-step.test.ts +144 -0
  56. package/test/large-outcome.test.ts +60 -0
  57. package/test/live-frames.test.ts +150 -0
  58. package/test/live-ready.test.ts +61 -0
  59. package/test/long-wait.test.ts +168 -0
  60. package/test/nested-outcome.test.ts +75 -0
  61. package/test/nested-wait.test.ts +111 -0
  62. package/test/no-repeat-crash.test.ts +132 -0
  63. package/test/offer-replace.test.ts +39 -0
  64. package/test/plugin-async-setup.test.ts +22 -0
  65. package/test/plugin-copies.test.ts +87 -0
  66. package/test/plugin-emit.test.ts +43 -0
  67. package/test/plugin-install-failure.test.ts +121 -0
  68. package/test/plugin-install-hash.test.ts +57 -0
  69. package/test/plugin-needs.test.ts +80 -0
  70. package/test/plugin-replace.test.ts +225 -0
  71. package/test/plugin-uninstall.test.ts +70 -0
  72. package/test/plugin-version-copies.test.ts +53 -0
  73. package/test/plugin-version.test.ts +180 -0
  74. package/test/read-filter.test.ts +136 -0
  75. package/test/read-query.test.ts +92 -0
  76. package/test/record-admission.test.ts +294 -0
  77. package/test/recovery-contracts.test.ts +107 -0
  78. package/test/repeated-write.test.ts +119 -0
  79. package/test/replay-mismatch.test.ts +79 -0
  80. package/test/replay.test.ts +135 -0
  81. package/test/single-writer.test.ts +267 -0
  82. package/test/state.test.ts +246 -0
  83. package/test/step-by-name.test.ts +122 -0
  84. package/test/stores.test.ts +102 -0
  85. package/test/stream.test.ts +154 -0
  86. package/test/subscriber-stream.test.ts +71 -0
  87. package/test/subscribers.test.ts +101 -0
  88. package/test/subscriptions.test.ts +632 -0
  89. package/test/trace-call.test.ts +124 -0
  90. package/test/trigger-filter.test.ts +42 -0
  91. package/test/use-many.test.ts +151 -0
  92. package/test/wait-query.test.ts +117 -0
  93. package/test/wait-restart.test.ts +187 -0
  94. package/test/wire-read-access.test.ts +85 -0
  95. package/tsconfig.json +6 -0
@@ -0,0 +1,147 @@
1
+ // A pause two calls down: a handler calls "a", "a" calls
2
+ // "b", "b" calls "c", and "c" fails. The invocation pauses on the step of "c"; "a" and "b" are not
3
+ // failed, they are waiting for the decision. The owner's retry enters them again, "c" is called
4
+ // again, and the invocation ends with the answer.
5
+
6
+ import { expect, test } from "bun:test";
7
+
8
+ import { z } from "zod";
9
+
10
+ import { action, actionName, record, seq } from "@niwa-labs/core";
11
+ import { createNiwa } from "@niwa-labs/host";
12
+ import { plugin } from "@niwa-labs/plugin";
13
+ import type { ActionName, StoredRecord } from "@niwa-labs/core";
14
+ import { eventually, tempHome } from "@niwa-labs/testing";
15
+
16
+ const Start = record("deep.start", z.object({}));
17
+ const Answered = record("deep.answered", z.object({ value: z.number() }));
18
+
19
+ const A: ActionName = actionName("deep.a");
20
+ const B: ActionName = actionName("deep.b");
21
+ const C: ActionName = actionName("deep.c");
22
+
23
+ /** The host of the three calls; "c" fails while `state.failing`. */
24
+ function serve(path: string, state: { failing: boolean; calls: number }) {
25
+ const niwa = createNiwa({ home: path });
26
+ niwa.use(
27
+ plugin("deep", (api) => {
28
+ api.declare(Start, Answered);
29
+ const io = { input: z.object({}), output: z.object({ value: z.number() }), recovery: "do-not-repeat" as const, effect: "write" as const };
30
+ api.action(action(C, { ...io, description: "c", run: async () => {
31
+ state.calls += 1;
32
+ if (state.failing) throw new Error("c is not ready");
33
+ return { value: 3 };
34
+ } }));
35
+ // A skipped "c" gives nothing back, and "b" goes on with a value of its own.
36
+ api.action(action(B, { ...io, description: "b", run: async (_input, ctx) => {
37
+ const got = await ctx.step<unknown, { value: number } | undefined>(C, {});
38
+ return { value: got?.value ?? -1 };
39
+ } }));
40
+ api.action(action(A, { ...io, description: "a", run: async (_input, ctx) => ctx.step(B, {}) }));
41
+ api.on(Start, async (_data, step) => {
42
+ const { value } = await step<unknown, { value: number }>(A, {});
43
+ await step.emit(Answered, { value });
44
+ });
45
+ }),
46
+ );
47
+ return niwa;
48
+ }
49
+
50
+ const pausedOf = (records: StoredRecord[]) =>
51
+ records.filter((stored) => stored.type === "niwa.invocation.state" && (stored.data as { state: string }).state === "paused");
52
+
53
+ async function open(niwa: ReturnType<typeof createNiwa>): Promise<StoredRecord[]> {
54
+ await niwa.serve();
55
+ const records: StoredRecord[] = [];
56
+ void (async () => {
57
+ for await (const stored of niwa.records.since()) records.push(stored);
58
+ })();
59
+ return records;
60
+ }
61
+
62
+ test("a pause two calls down pauses every call above it, and the retry finishes them", async () => {
63
+ const state = { failing: true, calls: 0 };
64
+ const home = await tempHome();
65
+ const niwa = serve(home.path, state);
66
+ const records = await open(niwa);
67
+
68
+ try {
69
+ await niwa.emit(Start, {});
70
+ const paused = () =>
71
+ records.filter((stored) => stored.type === "niwa.invocation.state" && (stored.data as { state: string }).state === "paused");
72
+ await eventually(() => paused().length === 1, 10_000, "the invocation did not pause");
73
+ const pause = paused()[0]!.data as { invocation: string; key: string };
74
+ expect(pause.key).toBe("1.step-1.step-1");
75
+ // The calls above the one that failed have no outcome: they wait for the decision.
76
+ const outcomes = records
77
+ .filter((stored) => stored.type === "niwa.step.outcome")
78
+ .map((stored) => (stored.data as { key: string }).key);
79
+ expect(outcomes).toEqual(["1.step-1.step-1"]);
80
+
81
+ state.failing = false;
82
+ await niwa.call("niwa.invocation.resolve" as ActionName, { invocation: pause.invocation, choice: "retry" });
83
+ await eventually(() => records.some((stored) => stored.type === Answered.name), 10_000, "the retry did not finish");
84
+ expect(records.find((stored) => stored.type === Answered.name)?.data).toEqual({ value: 3 });
85
+ expect(state.calls).toBe(2);
86
+ expect(paused()).toHaveLength(1);
87
+ } finally {
88
+ await niwa.close();
89
+ await home.cleanup();
90
+ }
91
+ }, 30_000);
92
+
93
+ test("the owner's skip two calls down lets the calls above it go on without the skipped one", async () => {
94
+ const state = { failing: true, calls: 0 };
95
+ const home = await tempHome();
96
+ const niwa = serve(home.path, state);
97
+ const records = await open(niwa);
98
+ try {
99
+ await niwa.emit(Start, {});
100
+ await eventually(() => pausedOf(records).length === 1, 10_000, "the invocation did not pause");
101
+ const pause = pausedOf(records)[0]!.data as { invocation: string };
102
+ await niwa.call("niwa.invocation.resolve" as ActionName, { invocation: pause.invocation, choice: "skip" });
103
+ await eventually(() => records.some((stored) => stored.type === Answered.name), 10_000, "the skip did not finish");
104
+ expect(records.find((stored) => stored.type === Answered.name)?.data).toEqual({ value: -1 });
105
+ expect(state.calls).toBe(1);
106
+ expect(pausedOf(records)).toHaveLength(1);
107
+ } finally {
108
+ await niwa.close();
109
+ await home.cleanup();
110
+ }
111
+ }, 30_000);
112
+
113
+ test("a pause two calls down survives a restart: the paused invocation is not run again, and the retry after it finishes", async () => {
114
+ const state = { failing: true, calls: 0 };
115
+ const home = await tempHome();
116
+ const first = serve(home.path, state);
117
+ const before = await open(first);
118
+ let invocation = "";
119
+ try {
120
+ await first.emit(Start, {});
121
+ await eventually(() => pausedOf(before).length === 1, 10_000, "the invocation did not pause");
122
+ invocation = (pausedOf(before)[0]!.data as { invocation: string }).invocation;
123
+ } finally {
124
+ await first.close();
125
+ }
126
+ const second = serve(home.path, state);
127
+ const after = await open(second);
128
+ try {
129
+ await eventually(() => after.some((stored) => stored.type === Start.name), 10_000, "the journal was not read");
130
+ // Nothing runs on its own: still one call to "c", and no outcome written for "a" or "b".
131
+ expect(state.calls).toBe(1);
132
+ state.failing = false;
133
+ await second.call("niwa.invocation.resolve" as ActionName, { invocation, choice: "retry" });
134
+ await eventually(() => after.some((stored) => stored.type === Answered.name), 10_000, "the retry did not finish");
135
+ expect(after.find((stored) => stored.type === Answered.name)?.data).toEqual({ value: 3 });
136
+ expect(state.calls).toBe(2);
137
+ const outcomes = after
138
+ .filter((stored) => stored.type === "niwa.step.outcome")
139
+ .map((stored) => (stored.data as { key: string }).key);
140
+ // The calls above "c" end once each, and only now.
141
+ expect(outcomes.filter((key) => key === "1")).toHaveLength(1);
142
+ expect(outcomes.filter((key) => key === "1.step-1")).toHaveLength(1);
143
+ } finally {
144
+ await second.close();
145
+ await home.cleanup();
146
+ }
147
+ }, 30_000);
@@ -0,0 +1,166 @@
1
+ // The host program for the action-step check (an action may call another action as a step).
2
+ //
3
+ // The plugin declares one record type, four actions and one handler:
4
+ //
5
+ // on Start { n } — the handler calls the action the mode names
6
+ // "outer" — calls the action "inner" through ctx.step, by name, and returns its answer
7
+ // "inner" — an effect that counts its calls and returns a fixed result
8
+ // "missing" — calls a name nobody serves
9
+ // "outcome" — asks for the outcome of a name nobody serves
10
+ //
11
+ // The inner call is a step of the same invocation, under the key of the step that made it.
12
+ // The recovery contract of "inner" comes from the third argument: "repeat" or "do-not-repeat".
13
+ //
14
+ // The gates: "g-inner" holds the nested call, and "g-outer" holds the action after it, so a
15
+ // test can cut the run off at either point.
16
+ //
17
+ // The home directory comes from argv[2], the recovery contract from argv[3]. The test imports
18
+ // this file for the record types, so the host only starts when the file is run directly.
19
+
20
+ import { action, actionName, record } from "@niwa-labs/core";
21
+ import { createNiwa } from "@niwa-labs/host";
22
+ import { plugin } from "@niwa-labs/plugin";
23
+ import type { ActionName } from "@niwa-labs/core";
24
+ import { counter, gate, stubAction } from "@niwa-labs/testing";
25
+ import { z } from "zod";
26
+
27
+ /** Wakes the handler. */
28
+ export const Start = record("action-step.start", z.object({ n: z.number(), mode: z.string().optional() }), { open: true });
29
+
30
+ /** What the outer action wrote down: the answer the inner call gave. */
31
+ export const Answered = record("action-step.answered", z.object({ n: z.number() }));
32
+
33
+ /** The name the inner action is called by: the contract between two modules. */
34
+ export const INNER: ActionName = actionName("inner");
35
+
36
+ /** A name nobody serves: the nested call to it cannot be made. */
37
+ export const NOBODY: ActionName = actionName("nobody");
38
+
39
+ /** The plugin of the action-step check. It needs the home: the stub counts there. */
40
+ export function makePlugin(home: string, recovery: "repeat" | "do-not-repeat") {
41
+ // The inner action waits on a gate, so a test can cut the call off in the middle of it:
42
+ // the gate is closed when the host is killed, and opened when the call may finish.
43
+ const inner = stubAction("inner", {
44
+ home,
45
+ input: z.object({ n: z.number() }),
46
+ output: z.number(),
47
+ recovery,
48
+ effect: "write",
49
+ gate: "g-inner",
50
+ result: (input) => input.n,
51
+ });
52
+
53
+ const outer = action("outer", {
54
+ description: "Calls another action as a step of its own, by name.",
55
+ input: z.object({ n: z.number() }),
56
+ output: z.object({ n: z.number() }),
57
+ recovery: "repeat",
58
+ effect: "write",
59
+ async run(input, ctx) {
60
+ // The nested call: it is a step of the invocation this action runs in.
61
+ const value = await ctx.step(INNER, { n: input.n });
62
+ // The gate holds the action after the nested call, so a test can cut the run off in the
63
+ // window between the nested call's outcome and the end of this action.
64
+ await gate(home, "g-outer").wait();
65
+ return { n: value };
66
+ },
67
+ });
68
+
69
+ // An action that calls a name nobody serves: the call is a failed step, and the invocation
70
+ // pauses on it even when the code catches the error.
71
+ const missing = action("missing", {
72
+ description: "Calls an action nobody serves.",
73
+ input: z.object({ n: z.number() }),
74
+ output: z.object({ n: z.number() }),
75
+ recovery: "repeat",
76
+ effect: "write",
77
+ async run(input, ctx) {
78
+ try {
79
+ await ctx.step(NOBODY, { n: input.n });
80
+ } catch {
81
+ // The code swallows the error: the invocation still pauses.
82
+ }
83
+ return { n: input.n };
84
+ },
85
+ });
86
+
87
+ // An action that asks for the outcome of a name nobody serves: the answer is "failed", and
88
+ // the nested step still takes its key.
89
+ const outcome = action("outcome", {
90
+ description: "Asks for the outcome of an action nobody serves.",
91
+ input: z.object({ n: z.number() }),
92
+ output: z.object({ n: z.number() }),
93
+ recovery: "repeat",
94
+ effect: "write",
95
+ async run(input, ctx) {
96
+ const answer = await ctx.step.outcome(NOBODY, { n: input.n });
97
+ return { n: answer.status === "failed" ? input.n : -1 };
98
+ },
99
+ });
100
+
101
+ // An action that always fails, and an action that must not be repeated and calls it: the
102
+ // nested step fails, the invocation pauses on it, and the owner's answer is about that step.
103
+ const boom = action("boom", {
104
+ description: "Fails every time it is called.",
105
+ input: z.object({ n: z.number() }),
106
+ output: z.number(),
107
+ recovery: "repeat",
108
+ effect: "write",
109
+ async run() {
110
+ counter(home, "boom").hit();
111
+ throw new Error("boom");
112
+ },
113
+ });
114
+
115
+ const careful = action("careful", {
116
+ description: "Must not be repeated; calls an action that fails.",
117
+ input: z.object({ n: z.number() }),
118
+ output: z.object({ n: z.number() }),
119
+ recovery: "do-not-repeat",
120
+ effect: "write",
121
+ async run(input, ctx) {
122
+ return { n: await ctx.step(actionName("boom"), { n: input.n }) };
123
+ },
124
+ });
125
+
126
+ return plugin("action-step", (api) => {
127
+ api.declare(Start, Answered);
128
+ api.action(inner);
129
+ api.action(outer);
130
+ api.action(missing);
131
+ api.action(outcome);
132
+ api.action(boom);
133
+ api.action(careful);
134
+ api.on(Start, async (data, step) => {
135
+ // The mode says which action the handler calls: "outer" calls "inner", "missing" calls
136
+ // a name nobody serves, and "outcome" asks for the outcome of such a name.
137
+ const target =
138
+ data.mode === "missing"
139
+ ? missing
140
+ : data.mode === "outcome"
141
+ ? outcome
142
+ : data.mode === "careful"
143
+ ? careful
144
+ : outer;
145
+ const answer = await step(target, { n: data.n });
146
+ await step.emit(Answered, { n: answer.n });
147
+ });
148
+ });
149
+ }
150
+
151
+ if (import.meta.main) {
152
+ const home = process.argv[2];
153
+ const recovery = process.argv[3];
154
+ if (!home || (recovery !== "repeat" && recovery !== "do-not-repeat")) {
155
+ console.error("usage: bun action-step-host.ts <home> <repeat|do-not-repeat>");
156
+ process.exit(2);
157
+ }
158
+
159
+ const niwa = createNiwa({ home });
160
+ niwa.use(makePlugin(home, recovery));
161
+ await niwa.serve();
162
+
163
+ process.on("SIGTERM", () => {
164
+ void niwa.close().then(() => process.exit(0));
165
+ });
166
+ }
@@ -0,0 +1,62 @@
1
+ // The host program for the scenario "an action that waits inside itself is waiting, not cut off".
2
+ //
3
+ // The plugin declares two record types, one action and one handler:
4
+ //
5
+ // on Start { n } — call the action "waiter"
6
+ // "waiter" — an effect that must not be repeated (recovery "do-not-repeat"); it waits
7
+ // inside itself for Answer { n } and returns it
8
+ //
9
+ // The invocation suspends inside the action. After a restart the step is entered again as a
10
+ // waiting step: the recovery contract is for a call that was cut off, and this one was not.
11
+ //
12
+ // The home directory comes from argv[2]. The test imports this file for the record types, so the
13
+ // host only starts when the file is run directly.
14
+
15
+ import { action, record } from "@niwa-labs/core";
16
+ import { createNiwa } from "@niwa-labs/host";
17
+ import { plugin } from "@niwa-labs/plugin";
18
+ import { z } from "zod";
19
+
20
+ /** Wakes the handler. */
21
+ export const Start = record("action-wait-restart.start", z.object({ n: z.number() }), { open: true });
22
+
23
+ /** What the action waits for. */
24
+ export const Answer = record("action-wait-restart.answer", z.object({ n: z.number() }), { open: true });
25
+
26
+ /** The plugin of this scenario. */
27
+ export function makePlugin() {
28
+ const waiter = action("waiter", {
29
+ description: "An effect that is not repeated and waits inside itself for its answer.",
30
+ input: z.object({ n: z.number() }),
31
+ output: z.object({ n: z.number() }),
32
+ recovery: "do-not-repeat",
33
+ effect: "write",
34
+ async run(input, ctx) {
35
+ return (await ctx.wait(Answer, { filter: { n: input.n } })).data;
36
+ },
37
+ });
38
+
39
+ return plugin("action-wait-restart", (api) => {
40
+ api.declare(Start, Answer);
41
+ api.action(waiter);
42
+ api.on(Start, async (data, step) => {
43
+ await step(waiter, { n: data.n });
44
+ });
45
+ });
46
+ }
47
+
48
+ if (import.meta.main) {
49
+ const home = process.argv[2];
50
+ if (!home) {
51
+ console.error("usage: bun action-wait-restart-host.ts <home>");
52
+ process.exit(2);
53
+ }
54
+
55
+ const niwa = createNiwa({ home });
56
+ niwa.use(makePlugin());
57
+ await niwa.serve();
58
+
59
+ process.on("SIGTERM", () => {
60
+ void niwa.close().then(() => process.exit(0));
61
+ });
62
+ }
@@ -0,0 +1,91 @@
1
+ // The host program for the scenario "catching up".
2
+ //
3
+ // "Stop the host. Write records through a second, short-lived
4
+ // host or before the stop without the handler installed. Start with the handler.
5
+ // Each record is handled exactly once, in order."
6
+ //
7
+ // The plugin declares one record type, Item { n }, and one handler that calls the
8
+ // action "seen". The handler is installed or not, depending on the variant:
9
+ //
10
+ // bun catch-up-host.ts <home> nohandler — the type is declared, no handler is installed
11
+ // bun catch-up-host.ts <home> handler — the type is declared, the handler is installed
12
+ //
13
+ // The type is declared in both variants: a record of an undeclared type cannot be
14
+ // written at all, so the variant without a handler must still be able to receive
15
+ // the items it does not handle.
16
+ //
17
+ // The action "seen" is counted and returns its input, so the journal holds the
18
+ // number of the item it was called with: the order of the calls is visible in the
19
+ // records the core writes for the outcomes of the steps.
20
+ //
21
+ // The home directory comes from argv[2], the variant from argv[3]. The test imports
22
+ // this file for the record type, so the host only starts when the file is run
23
+ // directly.
24
+
25
+ import { createNiwa } from "@niwa-labs/host";
26
+ import { plugin } from "@niwa-labs/plugin";
27
+ import { record } from "@niwa-labs/core";
28
+ import { stubAction } from "@niwa-labs/testing";
29
+ import { z } from "zod";
30
+
31
+ /** The item the handler handles. */
32
+ export const Item = record("catch-up.item", z.object({ n: z.number() }), { open: true });
33
+
34
+ /** The variants this program knows. */
35
+ export const VARIANTS = ["nohandler", "handler"] as const;
36
+
37
+ /** One of the variants. */
38
+ export type Variant = (typeof VARIANTS)[number];
39
+
40
+ /**
41
+ * The plugin of this scenario.
42
+ *
43
+ * With `withHandler` the plugin handles Item and calls the action "seen" for it.
44
+ * Without it the plugin only declares the type: the records it receives stay in
45
+ * the journal, unhandled, until a host with the handler starts.
46
+ */
47
+ export function makePlugin(home: string, withHandler: boolean) {
48
+ // The work itself. Every call is counted, and the call carries the number of
49
+ // the item, so the journal shows which item was handled and in what order.
50
+ const seen = stubAction("seen", {
51
+ home,
52
+ input: z.object({ n: z.number() }),
53
+ output: z.object({ n: z.number() }),
54
+ recovery: "repeat",
55
+ effect: "write",
56
+ result: (input) => input,
57
+ });
58
+
59
+ return plugin("catch-up", (api) => {
60
+ api.declare(Item);
61
+ api.action(seen);
62
+
63
+ if (withHandler) {
64
+ // A new subscription starts where the journal is; this one asks for what was written before it.
65
+ api.on(Item, { from: "start" }, async (data, step) => {
66
+ await step(seen, { n: data.n });
67
+ });
68
+ }
69
+ });
70
+ }
71
+
72
+ if (import.meta.main) {
73
+ const home = process.argv[2];
74
+ const variant = process.argv[3];
75
+ if (!home || variant === undefined) {
76
+ console.error("usage: bun catch-up-host.ts <home> <nohandler|handler>");
77
+ process.exit(2);
78
+ }
79
+ if (!VARIANTS.includes(variant as Variant)) {
80
+ console.error(`usage: bun catch-up-host.ts <home> <nohandler|handler>: unknown variant "${variant}"`);
81
+ process.exit(2);
82
+ }
83
+
84
+ const niwa = createNiwa({ home });
85
+ niwa.use(makePlugin(home, variant === "handler"));
86
+ await niwa.serve();
87
+
88
+ process.on("SIGTERM", () => {
89
+ void niwa.close().then(() => process.exit(0));
90
+ });
91
+ }
@@ -0,0 +1,78 @@
1
+ // The host program for the scenario "causes".
2
+ //
3
+ // The plugin declares three record types:
4
+ //
5
+ // Seed { n } — the original input: the root of the chain
6
+ // Report { n } — a report: it grows from the Seed
7
+ // Merged { n } — a result merged from the reports
8
+ // Done { n } — written by a handler woken by Merged
9
+ //
10
+ // The handler of Seed writes two reports with step.emit, then one merged result
11
+ // that declares links to all three inputs: the Seed and the two reports. A
12
+ // merged result depends on more than one thing, and `cause` can hold only one of
13
+ // them, so the other two are links.
14
+ //
15
+ // The home directory comes from argv[2]. The test imports this file for the
16
+ // record types, so the host only starts when the file is run directly.
17
+
18
+ import { createNiwa } from "@niwa-labs/host";
19
+ import { plugin } from "@niwa-labs/plugin";
20
+ import { record } from "@niwa-labs/core";
21
+ import { z } from "zod";
22
+
23
+ /** The original input: the root of the chain. */
24
+ export const Seed = record("causes.seed", z.object({ n: z.number() }), { open: true });
25
+
26
+ /** A report: it grows from the seed. */
27
+ export const Report = record("causes.report", z.object({ n: z.number() }));
28
+
29
+ /** A result merged from three inputs. */
30
+ export const Merged = record("causes.merged", z.object({ n: z.number() }));
31
+
32
+ /** Written by a handler woken by a handler's own record: the chain goes two levels down. */
33
+ export const Done = record("causes.done", z.object({ n: z.number() }));
34
+
35
+ /** The data of a report, read back from the record that holds it. */
36
+ const ReportData = z.object({ n: z.number() });
37
+
38
+ /** The plugin of this scenario. It needs no home: nothing of it counts effects. */
39
+ export function makePlugin() {
40
+ return plugin("causes", (api) => {
41
+ api.declare(Seed, Report, Merged, Done);
42
+ api.on(Seed, async (data, step, record) => {
43
+ // Two reports, both caused by the seed.
44
+ const first = await step.emit(Report, { n: data.n + 1 });
45
+ const second = await step.emit(Report, { n: data.n + 2 });
46
+
47
+ // The merged result: its cause is the seed (the waking record), and it
48
+ // declares links to all three inputs it depends on.
49
+ await step.emit(
50
+ Merged,
51
+ {
52
+ n: data.n + ReportData.parse(first.data).n + ReportData.parse(second.data).n,
53
+ },
54
+ { links: [record.id, first.id, second.id] },
55
+ );
56
+ });
57
+ // Woken by the merged result: its cause is that record, its root is still the seed.
58
+ api.on(Merged, async (data, step) => {
59
+ await step.emit(Done, { n: data.n });
60
+ });
61
+ });
62
+ }
63
+
64
+ if (import.meta.main) {
65
+ const home = process.argv[2];
66
+ if (!home) {
67
+ console.error("usage: bun causes-host.ts <home>");
68
+ process.exit(2);
69
+ }
70
+
71
+ const niwa = createNiwa({ home });
72
+ niwa.use(makePlugin());
73
+ await niwa.serve();
74
+
75
+ process.on("SIGTERM", () => {
76
+ void niwa.close().then(() => process.exit(0));
77
+ });
78
+ }
@@ -0,0 +1,52 @@
1
+ // The host program for the scenario "client".
2
+ //
3
+ // The plugin declares the record Note { n } and the action "echo", which
4
+ // returns its input. The test calls the action to show that a client can call
5
+ // an action of the host, and writes the record to put notes into the journal,
6
+ // where another client reads them back.
7
+ //
8
+ // The home directory comes from argv[2]. The test imports this file for the
9
+ // Note record type and for the echo action, so the host only starts when the
10
+ // file is run directly.
11
+
12
+ import { action, record } from "@niwa-labs/core";
13
+ import { createNiwa } from "@niwa-labs/host";
14
+ import { plugin } from "@niwa-labs/plugin";
15
+ import { z } from "zod";
16
+
17
+ /** The record the clients write and read. */
18
+ export const Note = record("client.note", z.object({ n: z.number() }), { open: true });
19
+
20
+ /** The action a client calls: it returns its input, unchanged. */
21
+ export const echo = action("echo", {
22
+ description: "Returns its input.",
23
+ input: z.object({ n: z.number() }),
24
+ output: z.object({ n: z.number() }),
25
+ recovery: "repeat",
26
+ effect: "write",
27
+ run: async (input) => input,
28
+ });
29
+
30
+ /** The plugin of this scenario. It needs no home: nothing of it counts effects. */
31
+ export function makePlugin() {
32
+ return plugin("client", (api) => {
33
+ api.declare(Note);
34
+ api.action(echo);
35
+ });
36
+ }
37
+
38
+ if (import.meta.main) {
39
+ const home = process.argv[2];
40
+ if (!home) {
41
+ console.error("usage: bun client-host.ts <home>");
42
+ process.exit(2);
43
+ }
44
+
45
+ const niwa = createNiwa({ home });
46
+ niwa.use(makePlugin());
47
+ await niwa.serve();
48
+
49
+ process.on("SIGTERM", () => {
50
+ void niwa.close().then(() => process.exit(0));
51
+ });
52
+ }
@@ -0,0 +1,71 @@
1
+ // The host program for the scenario "crash between steps".
2
+ //
3
+ // The plugin declares the record Start { n }. Its handler has two steps:
4
+ //
5
+ // await step(a1, { n }) // a1 completes and its outcome is recorded
6
+ // await step(a2, { n }) // a2 hits its counter, then blocks on the gate "g2"
7
+ //
8
+ // The test kills the host while a2 is blocked, so nothing about a2 is recorded.
9
+ // On restart the invocation resumes: step 1 replays from the recorded outcome
10
+ // (a1 is not called again) and step 2 is called again (a2 is called twice in
11
+ // total). The gate is opened by the test, so a2 finishes and the invocation
12
+ // ends as done.
13
+ //
14
+ // The home directory comes from argv[2]. The test imports this file for the
15
+ // Start record type, so the host only starts when the file is run directly.
16
+
17
+ import { createNiwa } from "@niwa-labs/host";
18
+ import { plugin } from "@niwa-labs/plugin";
19
+ import { record } from "@niwa-labs/core";
20
+ import { stubAction } from "@niwa-labs/testing";
21
+ import { z } from "zod";
22
+
23
+ export const Start = record("crash-between-steps.start", z.object({ n: z.number() }), { open: true });
24
+
25
+ /** The plugin of this scenario. It needs the home: the stubs count and wait there. */
26
+ export function makePlugin(home: string) {
27
+ const a1 = stubAction("a1", {
28
+ home,
29
+ input: z.object({ n: z.number() }),
30
+ output: z.number(),
31
+ recovery: "repeat",
32
+ effect: "write",
33
+ result: (input) => input.n,
34
+ });
35
+
36
+ const a2 = stubAction("a2", {
37
+ home,
38
+ input: z.object({ n: z.number() }),
39
+ output: z.number(),
40
+ recovery: "repeat",
41
+ effect: "write",
42
+ gate: "g2",
43
+ result: (input) => input.n,
44
+ });
45
+
46
+ return plugin("crash-between-steps", (api) => {
47
+ api.declare(Start);
48
+ api.action(a1);
49
+ api.action(a2);
50
+ api.on(Start, async (data, step) => {
51
+ await step(a1, { n: data.n });
52
+ await step(a2, { n: data.n });
53
+ });
54
+ });
55
+ }
56
+
57
+ if (import.meta.main) {
58
+ const home = process.argv[2];
59
+ if (!home) {
60
+ console.error("usage: bun crash-between-steps-host.ts <home>");
61
+ process.exit(2);
62
+ }
63
+
64
+ const niwa = createNiwa({ home });
65
+ niwa.use(makePlugin(home));
66
+ await niwa.serve();
67
+
68
+ process.on("SIGTERM", () => {
69
+ void niwa.close().then(() => process.exit(0));
70
+ });
71
+ }