@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,176 @@
1
+ // The host program for the scenario "replacing a plugin".
2
+ //
3
+ // "With one invocation waiting, replace the plugin with a changed
4
+ // handler. The waiting invocation finishes on the old code. A new record is handled by the new
5
+ // code. Unload the plugin: its handlers no longer run and every record it wrote is still
6
+ // readable."
7
+ //
8
+ // The host runs plugin "p" in two versions with the same name and different code:
9
+ //
10
+ // v1: on Start { n } — wait for Answer { n }, then step("v1-finish")
11
+ // v2: on Start { n } — step("v2-run"), wait for Answer { n }, then step("v2-finish")
12
+ //
13
+ // The two versions are the same plugin name with changed code, so the host keeps both: an
14
+ // invocation admitted on v1 finishes on v1, and a record admitted later starts on v2: an
15
+ // invocation is pinned to the version of the plugin it started on.
16
+ //
17
+ // A second plugin, "fixture-control", registers two actions that the test calls through the
18
+ // public API:
19
+ //
20
+ // "fixture.upgrade" — niwa.use(v2), the replacement of plugin "p"
21
+ // "fixture.unload" — niwa.unload("p")
22
+ //
23
+ // The control plugin also declares the two record types. That is deliberate: after the unload,
24
+ // plugin "p" is gone and its declarations are gone with it, and the test still has to be able to
25
+ // emit a Start record to show that no handler of "p" runs any more.
26
+ //
27
+ // The home directory comes from argv[2]. The test imports this file for the record types and the
28
+ // two control actions, so the host only starts when the file is run directly.
29
+
30
+ import { action, record } from "@niwa-labs/core";
31
+ import { createNiwa } from "@niwa-labs/host";
32
+ import { plugin } from "@niwa-labs/plugin";
33
+ import type { Host } from "@niwa-labs/host";
34
+ import type { Plugin } from "@niwa-labs/plugin";
35
+ import { stubAction } from "@niwa-labs/testing";
36
+ import { z } from "zod";
37
+
38
+ /** The external input that wakes plugin "p". */
39
+ export const Start = record("plugin-replace.start", z.object({ n: z.number() }), { open: true });
40
+
41
+ /** The answer plugin "p" waits for. */
42
+ export const Answer = record("plugin-replace.answer", z.object({ n: z.number() }), { open: true });
43
+
44
+ /** The shape of the input of the two control actions. */
45
+ const NoInput = z.object({});
46
+
47
+ /** The shape of the output of the two control actions. */
48
+ const Ok = z.object({ ok: z.boolean() });
49
+
50
+ /** The host this program runs, and the two versions of plugin "p". */
51
+ let host: Host | undefined;
52
+ let pV1: Plugin | undefined;
53
+ let pV2: Plugin | undefined;
54
+
55
+ /** Replace plugin "p" with the changed version of the same plugin. */
56
+ export const upgrade = action("fixture.upgrade", {
57
+ description: "Replace plugin p with its changed version.",
58
+ input: NoInput,
59
+ output: Ok,
60
+ recovery: "repeat",
61
+ effect: "write",
62
+ run: async () => {
63
+ if (host === undefined || pV2 === undefined) {
64
+ throw new Error("fixture.upgrade: the host is not running");
65
+ }
66
+ host.use(pV2);
67
+ return { ok: true };
68
+ },
69
+ });
70
+
71
+ /** Unload plugin "p". Its registrations go; the records it wrote stay. */
72
+ export const unload = action("fixture.unload", {
73
+ description: "Unload plugin p.",
74
+ input: NoInput,
75
+ output: Ok,
76
+ recovery: "repeat",
77
+ effect: "write",
78
+ run: async () => {
79
+ if (host === undefined || pV1 === undefined) {
80
+ throw new Error("fixture.unload: the host is not running");
81
+ }
82
+ host.unload(pV1.name);
83
+ return { ok: true };
84
+ },
85
+ });
86
+
87
+ /**
88
+ * The control plugin. It registers the two actions above, and it declares the two record types
89
+ * so that they survive the unload of plugin "p".
90
+ */
91
+ const control = plugin("fixture-control", (api) => {
92
+ api.declare(Start, Answer);
93
+ api.action(upgrade);
94
+ api.action(unload);
95
+ });
96
+
97
+ /**
98
+ * The two versions of plugin "p". Same name, changed code, so the host keeps both versions and
99
+ * the work in flight is pinned to the one it started on.
100
+ */
101
+ function buildPlugins(home: string): { v1: Plugin; v2: Plugin } {
102
+ const v1Finish = stubAction("v1-finish", {
103
+ home,
104
+ input: z.object({ n: z.number() }),
105
+ output: Ok,
106
+ recovery: "repeat",
107
+ effect: "write",
108
+ result: () => ({ ok: true }),
109
+ });
110
+
111
+ const v2Run = stubAction("v2-run", {
112
+ home,
113
+ input: z.object({ n: z.number() }),
114
+ output: Ok,
115
+ recovery: "repeat",
116
+ effect: "write",
117
+ result: () => ({ ok: true }),
118
+ });
119
+
120
+ const v2Finish = stubAction("v2-finish", {
121
+ home,
122
+ input: z.object({ n: z.number() }),
123
+ output: Ok,
124
+ recovery: "repeat",
125
+ effect: "write",
126
+ result: () => ({ ok: true }),
127
+ });
128
+
129
+ // Version 1: wait for the answer, then finish.
130
+ // The record types are the control plugin's: a type has one owner. A record that arrives while another
131
+ // waits for its answer starts at once.
132
+ const v1 = plugin("p", (api) => {
133
+ api.action(v1Finish);
134
+ api.on(Start, { concurrency: Number.POSITIVE_INFINITY }, async (data, step) => {
135
+ await step.wait(Answer, { filter: { n: data.n } });
136
+ await step(v1Finish, { n: data.n });
137
+ });
138
+ });
139
+
140
+ // Version 2: run first, then wait for the answer, then finish.
141
+ const v2 = plugin("p", (api) => {
142
+ api.action(v2Run);
143
+ api.action(v2Finish);
144
+ api.on(Start, { concurrency: Number.POSITIVE_INFINITY }, async (data, step) => {
145
+ await step(v2Run, { n: data.n });
146
+ await step.wait(Answer, { filter: { n: data.n } });
147
+ await step(v2Finish, { n: data.n });
148
+ });
149
+ });
150
+
151
+ return { v1, v2 };
152
+ }
153
+
154
+ if (import.meta.main) {
155
+ const home = process.argv[2];
156
+ if (!home) {
157
+ console.error("usage: bun plugin-replace-host.ts <home>");
158
+ process.exit(2);
159
+ }
160
+
161
+ const niwa = createNiwa({ home });
162
+ host = niwa;
163
+
164
+ const plugins = buildPlugins(home);
165
+ pV1 = plugins.v1;
166
+ pV2 = plugins.v2;
167
+
168
+ niwa.use(pV1);
169
+ niwa.use(control);
170
+
171
+ await niwa.serve();
172
+
173
+ process.on("SIGTERM", () => {
174
+ void niwa.close().then(() => process.exit(0));
175
+ });
176
+ }
@@ -0,0 +1,50 @@
1
+ import {z} from "zod";
2
+ import {action, record, RecordRefused} from "@niwa-labs/core";
3
+ import {createNiwa} from "@niwa-labs/host";
4
+ import {plugin} from "@niwa-labs/plugin";
5
+ import {counter, gate} from "@niwa-labs/testing";
6
+
7
+ export const Start = record("claim.start", z.object({mode: z.enum(["escaped", "claim", "handled"])}), {open: true});
8
+ export const Wake = record("claim.wake", z.object({}), {open: true});
9
+ export const Caught = record("claim.caught", z.object({audit: z.string()}));
10
+ export const Done = record("claim.done", z.object({}));
11
+ const Held = record("claim.held", z.object({}), {guard: {
12
+ group: "claim", key: () => "one", initial: () => null, fold: () => null,
13
+ admit: () => ({code: "held", reason: "already held"}),
14
+ }});
15
+
16
+ if (import.meta.main) {
17
+ const home = process.argv[2]!;
18
+ const host = createNiwa({home});
19
+ host.use(plugin("claim", api => {
20
+ api.declare(Start, Wake, Caught, Done, Held);
21
+ const actions = (["escaped", "claim", "handled"] as const).map(mode => {
22
+ const act = action(`claim.${mode}`, {
23
+ description: "Attempt a guarded write", recovery: "do-not-repeat", effect: "write",
24
+ input: z.object({}), output: z.null(),
25
+ ...(mode === "claim" ? {terminalClaim: Held.name} : {}),
26
+ async run(_, ctx) {
27
+ counter(home, "calls").hit();
28
+ try { await ctx.emit(Held, {}); }
29
+ catch (error) {
30
+ if (mode !== "escaped") await gate(home, "after-refusal").wait();
31
+ if (mode !== "handled") throw error;
32
+ }
33
+ return null;
34
+ },
35
+ });
36
+ api.action(act);
37
+ return act;
38
+ });
39
+ api.on(Start, async ({mode}, step) => {
40
+ try { await step(actions.find(act => act.name === `claim.${mode}`)!, {}, {key: "call"}); }
41
+ catch (error) {
42
+ if (!(error instanceof RecordRefused)) throw error;
43
+ await step.emit(Caught, {audit: error.audit.id});
44
+ }
45
+ await step.wait(Wake);
46
+ await step.emit(Done, {});
47
+ });
48
+ }));
49
+ await host.serve();
50
+ }
@@ -0,0 +1,79 @@
1
+ // The host program for the scenario "the recovery contracts".
2
+ //
3
+ // The plugin declares the record Start { n }. Its handler has one step:
4
+ //
5
+ // await step(effect, { n }) // effect hits its counter, then blocks on the gate "g1"
6
+ //
7
+ // The recovery contract of the action is chosen by the third argument: "repeat" or
8
+ // "repeat-with-key". The contract says what may be done after a call whose outcome is unknown:
9
+ //
10
+ // repeat — the action may be called again, with the same operation id
11
+ // repeat-with-key — the action may be called again, with an operation id built from the
12
+ // same key, so the other side can dedupe it
13
+ //
14
+ // The test kills the host while the action is blocked, so the step has an intent and no
15
+ // outcome. On restart the contract decides: the action is called again and the invocation
16
+ // finishes. With "repeat-with-key" the operation id of the second call is the one of the first.
17
+ //
18
+ // The home directory comes from argv[2], the recovery contract from argv[3]. The test imports
19
+ // this file for the Start record type, so the host only starts when the file is run directly.
20
+
21
+ import { createNiwa } from "@niwa-labs/host";
22
+ import { plugin } from "@niwa-labs/plugin";
23
+ import { record } from "@niwa-labs/core";
24
+ import { stubAction } from "@niwa-labs/testing";
25
+ import { z } from "zod";
26
+
27
+ export const Start = record("recovery-contracts.start", z.object({ n: z.number() }), { open: true });
28
+
29
+ /** The plugin of this scenario. It needs the home: the stub counts and waits there. */
30
+ export function makePlugin(home: string, recovery: "repeat" | "repeat-with-key") {
31
+ const effect = stubAction("effect", {
32
+ home,
33
+ input: z.object({ n: z.number() }),
34
+ output: z.number(),
35
+ recovery,
36
+ effect: "write",
37
+ gate: "g1",
38
+ // The operation id of every call is recorded, so the test can compare the first call with
39
+ // the second one across the crash.
40
+ operations: "effect",
41
+ result: (input) => input.n,
42
+ });
43
+
44
+ const after = stubAction("after", {
45
+ home,
46
+ input: z.object({ n: z.number() }),
47
+ output: z.number(),
48
+ recovery: "repeat",
49
+ effect: "write",
50
+ result: (input) => input.n,
51
+ });
52
+
53
+ return plugin("recovery-contracts", (api) => {
54
+ api.declare(Start);
55
+ api.action(effect);
56
+ api.action(after);
57
+ api.on(Start, async (data, step) => {
58
+ const value = await step(effect, { n: data.n });
59
+ await step(after, { n: value });
60
+ });
61
+ });
62
+ }
63
+
64
+ if (import.meta.main) {
65
+ const home = process.argv[2];
66
+ const recovery = process.argv[3];
67
+ if (!home || (recovery !== "repeat" && recovery !== "repeat-with-key")) {
68
+ console.error("usage: bun recovery-contracts-host.ts <home> <repeat|repeat-with-key>");
69
+ process.exit(2);
70
+ }
71
+
72
+ const niwa = createNiwa({ home });
73
+ niwa.use(makePlugin(home, recovery));
74
+ await niwa.serve();
75
+
76
+ process.on("SIGTERM", () => {
77
+ void niwa.close().then(() => process.exit(0));
78
+ });
79
+ }
@@ -0,0 +1,39 @@
1
+ // The host program for the scenario "repeated write".
2
+ //
3
+ // The plugin declares one record type, Note { n }. Nothing is handled here: the
4
+ // check is about the write itself, so the record type only has to be declared
5
+ // for the host to accept it.
6
+ //
7
+ // The home directory comes from argv[2]. The test imports this file for the
8
+ // record type, so the host only starts when the file is run directly.
9
+
10
+ import { createNiwa } from "@niwa-labs/host";
11
+ import { plugin } from "@niwa-labs/plugin";
12
+ import { record } from "@niwa-labs/core";
13
+ import { z } from "zod";
14
+
15
+ /** The record the test writes. */
16
+ export const Note = record("repeated-write.note", z.object({ n: z.number() }), { open: true });
17
+
18
+ /** The plugin of this scenario. It needs no home: nothing of it counts effects. */
19
+ export function makePlugin() {
20
+ return plugin("repeated-write", (api) => {
21
+ api.declare(Note);
22
+ });
23
+ }
24
+
25
+ if (import.meta.main) {
26
+ const home = process.argv[2];
27
+ if (!home) {
28
+ console.error("usage: bun repeated-write-host.ts <home>");
29
+ process.exit(2);
30
+ }
31
+
32
+ const niwa = createNiwa({ home });
33
+ niwa.use(makePlugin());
34
+ await niwa.serve();
35
+
36
+ process.on("SIGTERM", () => {
37
+ void niwa.close().then(() => process.exit(0));
38
+ });
39
+ }
@@ -0,0 +1,66 @@
1
+ // The host program for the scenario "replay mismatch".
2
+ //
3
+ // The plugin declares the record Start { n }. Its handler has one step:
4
+ //
5
+ // await step(effect, { n: stepInput }) // stepInput comes from argv[3]
6
+ //
7
+ // The number the step is called with comes from the third argument of the host, so the test can
8
+ // restart the host with a different number under the same step key.
9
+ //
10
+ // The scenario:
11
+ //
12
+ // 1. spawn the host with n = 7, connect a client, emit Start { n }
13
+ // 2. the handler calls the action "effect", which blocks on the gate "g1"
14
+ // 3. kill the host with SIGKILL — a real crash, in the middle of the call
15
+ // 4. spawn the host again with n = 9: the invocation resumes on the same record, but the
16
+ // step is now called with a different input under the same key
17
+ // 5. the invocation pauses with a mismatch, and no second effect happens
18
+ //
19
+ // The home directory comes from argv[2], the step input from argv[3]. The test imports this
20
+ // file for the Start record type, so the host only starts when the file is run directly.
21
+
22
+ import { createNiwa } from "@niwa-labs/host";
23
+ import { plugin } from "@niwa-labs/plugin";
24
+ import { record } from "@niwa-labs/core";
25
+ import { stubAction } from "@niwa-labs/testing";
26
+ import { z } from "zod";
27
+
28
+ export const Start = record("replay-mismatch.start", z.object({ n: z.number() }), { open: true });
29
+
30
+ /** The plugin of this scenario. It needs the home: the stub counts and waits there. */
31
+ export function makePlugin(home: string, stepInput: number) {
32
+ const effect = stubAction("effect", {
33
+ home,
34
+ input: z.object({ n: z.number() }),
35
+ output: z.number(),
36
+ recovery: "repeat",
37
+ effect: "write",
38
+ gate: "g1",
39
+ result: (input) => input.n,
40
+ });
41
+
42
+ return plugin("replay-mismatch", (api) => {
43
+ api.declare(Start);
44
+ api.action(effect);
45
+ api.on(Start, async (_data, step) => {
46
+ await step(effect, { n: stepInput });
47
+ });
48
+ });
49
+ }
50
+
51
+ if (import.meta.main) {
52
+ const home = process.argv[2];
53
+ const stepInput = Number(process.argv[3]);
54
+ if (!home || !Number.isFinite(stepInput)) {
55
+ console.error("usage: bun replay-mismatch-host.ts <home> <step-input>");
56
+ process.exit(2);
57
+ }
58
+
59
+ const niwa = createNiwa({ home });
60
+ niwa.use(makePlugin(home, stepInput));
61
+ await niwa.serve();
62
+
63
+ process.on("SIGTERM", () => {
64
+ void niwa.close().then(() => process.exit(0));
65
+ });
66
+ }
@@ -0,0 +1,113 @@
1
+ // The host program for the scenario "one writer".
2
+ //
3
+ // "A second host on the same home is refused while the first lives.
4
+ // Kill the first without a clean shutdown; the second takes over. A stale holder that tries
5
+ // to write learns it has lost ownership and writes nothing."
6
+ //
7
+ // The plugin declares one record type, Start { n }, and a handler that steps through a gate:
8
+ //
9
+ // await step(block, { n }) // parks inside a step until the gate is open
10
+ // await step(finish, { n }) // what the host tries to write after the gate opens
11
+ //
12
+ // The gate is what the test uses to park the host in the middle of a step: the invocation
13
+ // holds the journal open while it waits, so the second host can be started against a live
14
+ // first host.
15
+ //
16
+ // The gate name and the plugin name come from the arguments, so two hosts on the same home do
17
+ // not share a gate: the host that is parked waits on its own gate, and the host that took the
18
+ // journal over waits on its own.
19
+ //
20
+ // The home directory comes from argv[2]. The test imports this file for the record types, so
21
+ // the host only starts when the file is run directly. The third argument is "takeover": the
22
+ // host takes the journal from a living holder when it is told to. The fourth is the gate name
23
+ // and the fifth is the plugin name.
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 external input that wakes the handler. */
32
+ export const Start = record("single-writer.start", z.object({ n: z.number() }), { open: true });
33
+
34
+ /**
35
+ * A record nobody handles.
36
+ *
37
+ * The test writes one of these to find out which host holds the journal: a write that
38
+ * succeeds means the writer is the new holder. It has no handler, so no invocation runs
39
+ * and the journal holds nothing but the record itself.
40
+ */
41
+ export const Probe = record("single-writer.probe", z.object({ n: z.number() }), { open: true });
42
+
43
+ /** The shape of the input of the actions. */
44
+ const N = z.object({ n: z.number() });
45
+
46
+ /** The shape of the output of the actions. */
47
+ const Ok = z.object({ ok: z.boolean() });
48
+
49
+ /**
50
+ * The plugin of this scenario.
51
+ *
52
+ * It needs the home: the stubs count there. The gate and the plugin name are given, so two
53
+ * hosts on the same home park on different gates and are told apart in the journal.
54
+ */
55
+ export function makePlugin(home: string, gateName = "block", pluginName = "single-writer") {
56
+ // The step the host is parked in: it waits for the gate.
57
+ const block = stubAction("block", {
58
+ home,
59
+ input: N,
60
+ output: Ok,
61
+ recovery: "repeat",
62
+ effect: "write",
63
+ gate: gateName,
64
+ result: () => ({ ok: true }),
65
+ });
66
+
67
+ // The step after the gate: the write that must fail after the take-over. Its
68
+ // name carries the plugin name, so a client can tell which host is listening:
69
+ // the description lists the actions of the host that answers.
70
+ const finish = stubAction(`${pluginName}-finish`, {
71
+ home,
72
+ input: N,
73
+ output: Ok,
74
+ recovery: "repeat",
75
+ effect: "write",
76
+ result: () => ({ ok: true }),
77
+ });
78
+
79
+ return plugin(pluginName, (api) => {
80
+ api.declare(Start, Probe);
81
+ api.action(block);
82
+ api.action(finish);
83
+ api.on(Start, async (data, step) => {
84
+ await step(block, { n: data.n });
85
+ await step(finish, { n: data.n });
86
+ });
87
+ });
88
+ }
89
+ if (import.meta.main) {
90
+ const home = process.argv[2];
91
+ if (!home) {
92
+ console.error("usage: bun single-writer-host.ts <home> [takeover] [gate] [plugin]");
93
+ process.exit(2);
94
+ }
95
+
96
+ // The arguments after the home: "takeover" says that this host takes the
97
+ // journal even from a living holder, and the gate and the plugin names tell
98
+ // two hosts on the same home apart.
99
+ const rest = process.argv.slice(3);
100
+ const takeover = rest.includes("takeover");
101
+ const names = rest.filter((argument) => argument !== "takeover");
102
+ const gateName = names[0] ?? "block";
103
+ const pluginName = names[1] ?? "single-writer";
104
+
105
+ const niwa = createNiwa({ home, takeover });
106
+ niwa.use(makePlugin(home, gateName, pluginName));
107
+ // The handler is installed before the host listens: `ready()` answers as soon as the socket
108
+ // does, and a SIGTERM in that gap would kill the process without a clean close.
109
+ process.on("SIGTERM", () => {
110
+ void niwa.close().then(() => process.exit(0));
111
+ });
112
+ await niwa.serve();
113
+ }
@@ -0,0 +1,118 @@
1
+ // The host program for the scenario "plugin state".
2
+ //
3
+ // The plugin declares five record types and two state values:
4
+ //
5
+ // counter a number, raised by two different handlers
6
+ // batch a list, filled by Fill and emptied by Take
7
+ //
8
+ // Add { n } the handler "add" raises the counter by n
9
+ // Bump { n } the handler "bump" raises the same counter by n
10
+ // Fill { items } the handler "fill" puts items into the batch
11
+ // Take { tag } the handler "take" takes the batch and then blocks in a step
12
+ // Seen { tag, items } what the handler of Take writes down: the batch it took
13
+ //
14
+ // The two handlers of the counter wait on a gate before they update, so all
15
+ // their invocations are in flight at the same time when the gate opens: the
16
+ // updates must not lose each other.
17
+ //
18
+ // The handler of Take takes the batch and then blocks in the gated step. The
19
+ // test kills the host there, so the batch was taken but the invocation never
20
+ // finished. On restart the invocation resumes: the take replays from the
21
+ // recorded read and returns the same batch, and the batch is not taken twice.
22
+ //
23
+ // The home directory comes from argv[2]. The test imports this file for the
24
+ // record types, so the host only starts when the file is run directly.
25
+
26
+ import { createNiwa } from "@niwa-labs/host";
27
+ import { plugin } from "@niwa-labs/plugin";
28
+ import { record } from "@niwa-labs/core";
29
+ import { stubAction } from "@niwa-labs/testing";
30
+ import { z } from "zod";
31
+
32
+ /** Wakes the handler that raises the counter by n. */
33
+ export const Add = record("state.add", z.object({ n: z.number() }), { open: true });
34
+
35
+ /** Wakes the other handler, which raises the same counter by n. */
36
+ export const Bump = record("state.bump", z.object({ n: z.number() }), { open: true });
37
+
38
+ /** Puts items into the batch. */
39
+ export const Fill = record("state.fill", z.object({ items: z.array(z.string()) }), { open: true });
40
+
41
+ /** Wakes the handler that takes the batch. */
42
+ export const Take = record("state.take", z.object({ tag: z.string() }), { open: true });
43
+
44
+ /** What the handler of Take writes down: the batch it took. */
45
+ export const Seen = record("state.seen", z.object({ tag: z.string(), items: z.array(z.string()) }));
46
+
47
+ /** The plugin of this scenario. It needs the home: the stubs count there. */
48
+ export function makePlugin(home: string) {
49
+ // The step the two handlers of the counter wait on. It parks them on the gate
50
+ // "g2" until the test opens it, so every one of them is in flight at once.
51
+ const tick = stubAction("tick", {
52
+ home,
53
+ input: z.object({ n: z.number() }),
54
+ output: z.number(),
55
+ recovery: "repeat",
56
+ effect: "write",
57
+ gate: "g2",
58
+ result: (input) => input.n,
59
+ });
60
+
61
+ // The step the handler of Take parks in. The test kills the host while it
62
+ // waits, so the invocation is unfinished when the host comes back.
63
+ const hold = stubAction("hold", {
64
+ home,
65
+ input: z.object({ tag: z.string() }),
66
+ output: z.object({ tag: z.string() }),
67
+ recovery: "repeat",
68
+ effect: "write",
69
+ gate: "g",
70
+ result: (input) => ({ tag: input.tag }),
71
+ });
72
+
73
+ return plugin("state", (api) => {
74
+ api.declare(Add, Bump, Fill, Take, Seen);
75
+ api.action(tick);
76
+ api.action(hold);
77
+
78
+ const counter = api.state("counter", z.number(), 0);
79
+ const batch = api.state("batch", z.array(z.string()), []);
80
+
81
+ // Every update of the counter is in flight at once: the subscriptions let them all run.
82
+ api.on(Add, { concurrency: Number.POSITIVE_INFINITY }, async (data, step) => {
83
+ await step(tick, { n: data.n });
84
+ counter.update((value) => value + data.n);
85
+ });
86
+
87
+ api.on(Bump, { concurrency: Number.POSITIVE_INFINITY }, async (data, step) => {
88
+ await step(tick, { n: data.n });
89
+ counter.update((value) => value + data.n);
90
+ });
91
+
92
+ api.on(Fill, (data) => {
93
+ batch.update((items) => [...items, ...data.items]);
94
+ });
95
+
96
+ api.on(Take, async (data, step) => {
97
+ const items = batch.take();
98
+ await step(hold, { tag: data.tag });
99
+ await step.emit(Seen, { tag: data.tag, items });
100
+ });
101
+ });
102
+ }
103
+
104
+ if (import.meta.main) {
105
+ const home = process.argv[2];
106
+ if (!home) {
107
+ console.error("usage: bun state-host.ts <home>");
108
+ process.exit(2);
109
+ }
110
+
111
+ const niwa = createNiwa({ home });
112
+ niwa.use(makePlugin(home));
113
+ await niwa.serve();
114
+
115
+ process.on("SIGTERM", () => {
116
+ void niwa.close().then(() => process.exit(0));
117
+ });
118
+ }