@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,168 @@
1
+ // A long wait blocks nothing.
2
+ //
3
+ // The scenario runs against a real host process (fixtures/long-wait-host.ts):
4
+ //
5
+ // 1. spawn the host, connect a client, emit Ask { n: 0 }
6
+ // 2. the handler waits (step.wait) for Answer { n: 0 }; the invocation's
7
+ // state becomes "waiting" — a state record the host wrote
8
+ // 3. emit Job { n: 1 } … Job { n: 10 }; each one calls the action "job",
9
+ // which is counted
10
+ // 4. the counter of "job" reaches 10 while the Ask invocation is still
11
+ // waiting: no invocation of the Ask handler is done, and its latest
12
+ // state is "waiting"
13
+ // 5. emit Answer { n: 0 }; the wait is satisfied, the invocation ends as
14
+ // done
15
+ //
16
+ // The counter is the count of real calls, not an inference: ten calls of "job"
17
+ // are ten hits of the stub. The state of the waiting invocation is read from
18
+ // the records the host wrote.
19
+ //
20
+ // Only the public API is used: the entries of the packages and "@niwa-labs/testing".
21
+
22
+ import { expect, test } from "bun:test";
23
+ import { fileURLToPath } from "node:url";
24
+
25
+ import { connect } from "@niwa-labs/client";
26
+ import { seq } from "@niwa-labs/core";
27
+ import type { StoredRecord } from "@niwa-labs/core";
28
+ import { counter, eventually, spawnHost, tempHome, connectAsOwner } from "@niwa-labs/testing";
29
+ import { z } from "zod";
30
+
31
+ import { Answer, Ask, Job } from "./fixtures/long-wait-host.ts";
32
+
33
+ const HOST_SCRIPT = fileURLToPath(new URL("./fixtures/long-wait-host.ts", import.meta.url));
34
+
35
+ /** The type the core writes for every change of an invocation's state. */
36
+ const STATE_TYPE = "niwa.invocation.state";
37
+
38
+ /** The type the core writes when an invocation is admitted. */
39
+ const ADMITTED_TYPE = "niwa.invocation.admitted";
40
+
41
+ /** The handler of the invocation that waits. */
42
+ const ASK_HANDLER = "long-wait/long-wait.ask";
43
+
44
+ /** From the beginning of the journal. */
45
+ const FROM_START = seq(0);
46
+
47
+ /** The data of a CORE.invocationState record: { invocation, state, reason? }. */
48
+ const InvocationState = z.object({
49
+ invocation: z.string(),
50
+ state: z.string(),
51
+ reason: z.string().optional(),
52
+ });
53
+
54
+ /** The data of a CORE.invocationAdmitted record: { invocation, handler, … }. */
55
+ const Admitted = z.object({
56
+ invocation: z.string(),
57
+ handler: z.string(),
58
+ });
59
+
60
+ /**
61
+ * The invocation of the Ask handler: the journal says which invocation the
62
+ * waiting record woke.
63
+ */
64
+ function askInvocation(records: StoredRecord[]): string | undefined {
65
+ for (const record of records) {
66
+ if (record.type !== ADMITTED_TYPE) continue;
67
+ const parsed = Admitted.safeParse(record.data);
68
+ if (parsed.success && parsed.data.handler === ASK_HANDLER) return parsed.data.invocation;
69
+ }
70
+ return undefined;
71
+ }
72
+
73
+ /**
74
+ * The states of one invocation, in the order the journal holds them.
75
+ */
76
+ function statesOf(records: StoredRecord[], invocation: string): string[] {
77
+ const states: string[] = [];
78
+ for (const record of records) {
79
+ if (record.type !== STATE_TYPE) continue;
80
+ const parsed = InvocationState.safeParse(record.data);
81
+ if (parsed.success && parsed.data.invocation === invocation) states.push(parsed.data.state);
82
+ }
83
+ return states;
84
+ }
85
+
86
+ test("a long wait blocks nothing: the ten jobs are handled while the first invocation still waits", async () => {
87
+ const home = await tempHome();
88
+ const homePath = home.path;
89
+ const clients: Array<{ close(): Promise<void> }> = [];
90
+ let host: ReturnType<typeof spawnHost> | undefined;
91
+
92
+ try {
93
+ // 1. The host, a client that writes and an observer that reads.
94
+ host = spawnHost(HOST_SCRIPT, homePath);
95
+ await host.ready();
96
+
97
+ const client = await connectAsOwner(homePath);
98
+ clients.push(client);
99
+ const observer = await connectAsOwner(homePath);
100
+ clients.push(observer);
101
+ const seen: StoredRecord[] = [];
102
+ const watch = (async () => {
103
+ for await (const record of observer.records.since()) {
104
+ seen.push(record);
105
+ }
106
+ })().catch(() => {});
107
+
108
+ // 2. The Ask record wakes the invocation that waits.
109
+ await client.emit(Ask, { n: 0 });
110
+
111
+ // The invocation waits: the host wrote the state "waiting" for it, and it
112
+ // did not finish.
113
+ await eventually(
114
+ () => {
115
+ const invocation = askInvocation(seen);
116
+ if (invocation === undefined) return false;
117
+ const states = statesOf(seen, invocation);
118
+ return states.includes("waiting");
119
+ },
120
+ 15_000,
121
+ "the invocation should be waiting for its answer",
122
+ );
123
+
124
+ const waiting = askInvocation(seen);
125
+ expect(waiting).toBeDefined();
126
+ if (waiting === undefined) throw new Error("the invocation was not admitted");
127
+
128
+ // 3. Ten more records, written while the first invocation waits.
129
+ for (const n of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) {
130
+ await client.emit(Job, { n });
131
+ }
132
+
133
+ // 4. All ten are handled while the first still waits.
134
+ await eventually(
135
+ () => counter(homePath, "job").count() === 10,
136
+ 15_000,
137
+ "the ten jobs should have been handled while the first invocation waits",
138
+ );
139
+
140
+ expect(counter(homePath, "job").count()).toBe(10);
141
+
142
+ // The waiting invocation is still waiting: its latest state is "waiting"
143
+ // and it has not ended.
144
+ const states = statesOf(seen, waiting);
145
+ expect(states[states.length - 1]).toBe("waiting");
146
+ expect(states).not.toContain("done");
147
+ expect(states).not.toContain("paused");
148
+
149
+ // 5. The answer arrives: the wait is satisfied and the invocation ends.
150
+ await client.emit(Answer, { n: 0 });
151
+
152
+ await eventually(
153
+ () => statesOf(seen, waiting).includes("done"),
154
+ 15_000,
155
+ "the waiting invocation should end as done once the answer arrives",
156
+ );
157
+
158
+ // The ten jobs were handled exactly once each, and the answer did not make
159
+ // the host run them again.
160
+ expect(counter(homePath, "job").count()).toBe(10);
161
+ } finally {
162
+ for (const client of clients) {
163
+ await client.close().catch(() => {});
164
+ }
165
+ await host?.kill().catch(() => {});
166
+ await home.cleanup();
167
+ }
168
+ }, 60_000);
@@ -0,0 +1,75 @@
1
+ // What a direct call made from inside an action says about its outcome. A call that is refused
2
+ // before its body starts cannot have had an effect; one whose body ran and whose answer was not
3
+ // valid may have.
4
+
5
+ import { expect, test } from "bun:test";
6
+
7
+ import { NotSent, action } from "@niwa-labs/core";
8
+ import type { Outcome } from "@niwa-labs/core";
9
+ import { createNiwa } from "@niwa-labs/host";
10
+ import { plugin } from "@niwa-labs/plugin";
11
+ import { tempHome } from "@niwa-labs/testing";
12
+ import { z } from "zod";
13
+
14
+ const Wrong = action("nested-outcome.wrong", {
15
+ description: "Does its work and answers with something its output does not allow.",
16
+ input: z.object({}),
17
+ output: z.object({ n: z.number() }),
18
+ recovery: "repeat",
19
+ effect: "write",
20
+ run: async () => ({ n: "not a number" }) as unknown as { n: number },
21
+ });
22
+
23
+ const Strict = action("nested-outcome.strict", {
24
+ description: "Needs a number.",
25
+ input: z.object({ n: z.number() }),
26
+ output: z.object({}),
27
+ recovery: "repeat",
28
+ effect: "write",
29
+ run: async () => ({}),
30
+ });
31
+
32
+ const Unsent = action("nested-outcome.unsent", {
33
+ description: "Fails before anything it does goes out.",
34
+ input: z.object({}),
35
+ output: z.object({}),
36
+ recovery: "do-not-repeat",
37
+ effect: "write",
38
+ run: async () => {
39
+ throw new NotSent("nothing went out");
40
+ },
41
+ });
42
+
43
+ const Outer = action("nested-outcome.outer", {
44
+ description: "Calls the other two and reports their outcomes.",
45
+ input: z.object({}),
46
+ output: z.object({ wrong: z.unknown(), badInput: z.unknown(), unsent: z.unknown() }),
47
+ recovery: "repeat",
48
+ effect: "write",
49
+ run: async (_input, ctx) => ({
50
+ wrong: await ctx.step.outcome(Wrong, {}),
51
+ badInput: await ctx.step.outcome(Strict, { n: "x" } as unknown as { n: number }),
52
+ unsent: await ctx.step.outcome(Unsent, {}),
53
+ }),
54
+ });
55
+
56
+ test("a nested call whose output is not valid may have had an effect; one whose input is not valid, or that sent nothing, cannot", async () => {
57
+ const home = await tempHome();
58
+ const niwa = createNiwa({ home: home.path });
59
+ niwa.use(plugin("nested-outcome", (api) => {
60
+ api.action(Wrong);
61
+ api.action(Strict);
62
+ api.action(Unsent);
63
+ api.action(Outer);
64
+ }));
65
+ await niwa.serve();
66
+ try {
67
+ const { wrong, badInput, unsent } = (await niwa.call(Outer, {})) as Record<"wrong" | "badInput" | "unsent", Outcome<unknown>>;
68
+ expect(wrong).toMatchObject({ status: "failed", effectPossible: true });
69
+ expect(badInput).toMatchObject({ status: "failed", effectPossible: false });
70
+ expect(unsent).toMatchObject({ status: "failed", effectPossible: false });
71
+ } finally {
72
+ await niwa.close();
73
+ await home.cleanup();
74
+ }
75
+ });
@@ -0,0 +1,111 @@
1
+ // A wait inside a nested call is waiting after a restart, not cut off: waiting is a step too, and
2
+ // recovery contracts are for cut-off calls.
3
+ //
4
+ // 1. a chain three calls deep of do-not-repeat actions, the deepest waiting: after a SIGKILL
5
+ // and a restart the invocation is waiting again, no call of the chain is judged as cut off, and
6
+ // the answer ends the invocation as done
7
+ // 2. a call whose wait was answered and whose next nested call is cut off is not waiting:
8
+ // the nested call's own recovery contract judges it and the invocation pauses
9
+
10
+ import { expect, test } from "bun:test";
11
+
12
+ import { CORE_TYPES } from "@niwa-labs/core";
13
+ import type { StoredRecord } from "@niwa-labs/core";
14
+ import { counter, eventually, spawnHost, tempHome, lastState, watch, connectAsOwner } from "@niwa-labs/testing";
15
+
16
+ import { Answer, Start } from "./fixtures/nested-wait-host.ts";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ const HOST_SCRIPT = fileURLToPath(new URL("./fixtures/nested-wait-host.ts", import.meta.url));
20
+
21
+ /** The states the invocation went through, in the order the journal holds them. */
22
+ function statesOf(seen: StoredRecord[]): string[] {
23
+ return seen.filter((record) => record.type === CORE_TYPES.invocationState).map((record) => (record.data as { state: string }).state);
24
+ }
25
+
26
+ /** How many times the invocation became waiting. */
27
+ function waitings(seen: StoredRecord[]): number {
28
+ return statesOf(seen).filter((state) => state === "waiting").length;
29
+ }
30
+
31
+ test("a wait three calls deep survives a restart: it is not judged as cut off and the answer ends it as done", async () => {
32
+ const home = await tempHome();
33
+ const homePath = home.path;
34
+ let first: ReturnType<typeof spawnHost> | undefined;
35
+ let second: ReturnType<typeof spawnHost> | undefined;
36
+ let watcher: Awaited<ReturnType<typeof watch>> | undefined;
37
+
38
+ try {
39
+ first = spawnHost(HOST_SCRIPT, homePath);
40
+ await first.ready();
41
+ watcher = await watch(homePath);
42
+ const client = await connectAsOwner(homePath);
43
+ await client.emit(Start, { n: 1, mode: "top" });
44
+ await eventually(
45
+ () => lastState(watcher!.seen)?.state === "waiting",
46
+ 15_000,
47
+ "the chain should be waiting",
48
+ );
49
+
50
+ await first.kill();
51
+ await watcher.stop();
52
+ second = spawnHost(HOST_SCRIPT, homePath);
53
+ await second.ready();
54
+ // A watcher of the restarted host reads the whole history.
55
+ watcher = await watch(homePath);
56
+
57
+ await eventually(
58
+ () => waitings(watcher!.seen) >= 2,
59
+ 15_000,
60
+ "the restarted host should resume the chain as waiting",
61
+ );
62
+ expect(lastState(watcher!.seen)?.state).toBe("waiting");
63
+
64
+ await client.emit(Answer, { n: 1 });
65
+ await eventually(() => lastState(watcher!.seen)?.state === "done", 15_000, "the invocation should end as done");
66
+ expect(statesOf(watcher.seen)).not.toContain("paused");
67
+ await client.close().catch(() => {});
68
+ } finally {
69
+ await watcher?.stop();
70
+ await first?.kill().catch(() => {});
71
+ await second?.kill().catch(() => {});
72
+ await home.cleanup();
73
+ }
74
+ }, 60_000);
75
+
76
+ test("a nested call cut off after an answered wait is judged by its own contract", async () => {
77
+ const home = await tempHome();
78
+ const homePath = home.path;
79
+ let first: ReturnType<typeof spawnHost> | undefined;
80
+ let second: ReturnType<typeof spawnHost> | undefined;
81
+ let watcher: Awaited<ReturnType<typeof watch>> | undefined;
82
+
83
+ try {
84
+ first = spawnHost(HOST_SCRIPT, homePath);
85
+ await first.ready();
86
+ watcher = await watch(homePath);
87
+ const client = await connectAsOwner(homePath);
88
+ await client.emit(Start, { n: 2, mode: "after" });
89
+ await eventually(
90
+ () => lastState(watcher!.seen)?.state === "waiting",
91
+ 15_000,
92
+ "the call should be waiting",
93
+ );
94
+ // The answer lets the waiter finish; "slow" starts and stays on its closed gate.
95
+ await client.emit(Answer, { n: 2 });
96
+ await eventually(() => counter(homePath, "slow").count() === 1, 15_000, "slow should have started");
97
+
98
+ await first.kill();
99
+ second = spawnHost(HOST_SCRIPT, homePath);
100
+ await second.ready();
101
+
102
+ await eventually(() => lastState(watcher!.seen)?.state === "paused", 15_000, "the cut-off call should pause it");
103
+ expect(counter(homePath, "slow").count()).toBe(1);
104
+ await client.close().catch(() => {});
105
+ } finally {
106
+ await watcher?.stop();
107
+ await first?.kill().catch(() => {});
108
+ await second?.kill().catch(() => {});
109
+ await home.cleanup();
110
+ }
111
+ }, 60_000);
@@ -0,0 +1,132 @@
1
+ // Crash in the middle of a call that must not be repeated.
2
+ //
3
+ // The scenario runs against a real host process (fixtures/no-repeat-crash-host.ts):
4
+ //
5
+ // 1. spawn the host, connect a client, emit Start { n }
6
+ // 2. the handler calls the action "effect", which blocks on the gate "g1"
7
+ // 3. kill the host with SIGKILL — a real crash, in the middle of the call
8
+ // 4. spawn the host again: the step has an intent and no outcome
9
+ // 5. the invocation is paused, and the pause offers retry, skip, cancel
10
+ // 6. the test calls "niwa.invocation.resolve" with "retry": the action is called again
11
+ // 7. the same, with "skip": the action is not called again and the code continues
12
+ //
13
+ // Only the public API is used: the entries of the packages (types) and "@niwa-labs/testing".
14
+
15
+ import { expect, test } from "bun:test";
16
+
17
+ import { connect } from "@niwa-labs/client";
18
+ import type { ActionName } from "@niwa-labs/core";
19
+ import { counter, eventually, gate, spawnHost, tempHome, invocationOf, lastState, watch, connectAsOwner } from "@niwa-labs/testing";
20
+
21
+ import { Start } from "./fixtures/no-repeat-crash-host.ts";
22
+ import { fileURLToPath } from "node:url";
23
+
24
+ const HOST_SCRIPT = fileURLToPath(new URL("./fixtures/no-repeat-crash-host.ts", import.meta.url));
25
+ const RESOLVE = "niwa.invocation.resolve" as ActionName;
26
+
27
+ /**
28
+ * Run the crash and the restart, and hand over the second host with the invocation paused.
29
+ * `cleanup` stops everything that was started.
30
+ */
31
+ async function pausedAfterCrash() {
32
+ const home = await tempHome();
33
+ const homePath = home.path;
34
+ const hosts: Array<ReturnType<typeof spawnHost>> = [];
35
+ let watcher: Awaited<ReturnType<typeof watch>> | undefined;
36
+ const cleanup = async (): Promise<void> => {
37
+ await watcher?.stop();
38
+ for (const host of hosts) await host.kill().catch(() => {});
39
+ await home.cleanup();
40
+ };
41
+
42
+ try {
43
+ // 1. The first host. It is killed in the middle of the call.
44
+ const first = spawnHost(HOST_SCRIPT, homePath);
45
+ hosts.push(first);
46
+ await first.ready();
47
+
48
+ const observed = await watch(homePath);
49
+ watcher = observed;
50
+ const client = await connectAsOwner(homePath);
51
+ await client.emit(Start, { n: 7 });
52
+
53
+ // 2. The action is blocked on the gate: it was called, and its outcome is not recorded.
54
+ await eventually(
55
+ () => counter(homePath, "effect").count() >= 1,
56
+ 10_000,
57
+ "the effect should have been called once before the crash",
58
+ );
59
+
60
+ // 3. A real crash: SIGKILL, no clean shutdown.
61
+ await first.kill();
62
+ await client.close().catch(() => {});
63
+
64
+ // 4. The second host resumes the unfinished invocation. The gate is opened right away:
65
+ // a host that called the action again on its own would let it through.
66
+ const second = spawnHost(HOST_SCRIPT, homePath);
67
+ hosts.push(second);
68
+ gate(homePath, "g1").open();
69
+ await second.ready();
70
+
71
+ // 5. The invocation is paused: the call was cut off, and "do-not-repeat" cannot call it
72
+ // again on its own. The observer of the first host carried over to the second.
73
+ await eventually(
74
+ () => lastState(observed.seen)?.state === "paused",
75
+ 15_000,
76
+ "the invocation should have paused",
77
+ );
78
+ return { homePath, seen: observed.seen, cleanup };
79
+ } catch (error) {
80
+ await cleanup();
81
+ throw error;
82
+ }
83
+ }
84
+
85
+ test("crash in a call that must not be repeated: the invocation pauses, and retry calls the action again", async () => {
86
+ const run = await pausedAfterCrash();
87
+ try {
88
+ const paused = lastState(run.seen);
89
+ expect(paused?.choices).toEqual(["retry", "skip", "cancel"]);
90
+ expect(paused?.key).toBe("1");
91
+
92
+ // The step's outcome is "unknown", and the action was called at most once.
93
+ const outcomes = run.seen.filter((record) => record.type === "niwa.step.outcome");
94
+ expect(outcomes.map((record) => (record.data as { outcome?: { status?: string } }).outcome?.status)).toEqual([
95
+ "unknown",
96
+ ]);
97
+ expect(counter(run.homePath, "effect").count()).toBe(1);
98
+
99
+ // The owner chooses retry: the step is called again, and the invocation finishes.
100
+ const client = await connectAsOwner(run.homePath);
101
+ await client.call(RESOLVE, { invocation: invocationOf(run.seen), choice: "retry" });
102
+ await eventually(
103
+ () => lastState(run.seen)?.state === "done",
104
+ 15_000,
105
+ "the invocation should have finished after the retry",
106
+ );
107
+ expect(counter(run.homePath, "effect").count()).toBe(2);
108
+ expect(counter(run.homePath, "after").count()).toBe(1);
109
+ await client.close();
110
+ } finally {
111
+ await run.cleanup();
112
+ }
113
+ }, 40_000);
114
+
115
+ test("skip: the owner skips the cut-off step and the code continues without it", async () => {
116
+ const run = await pausedAfterCrash();
117
+ try {
118
+ const client = await connectAsOwner(run.homePath);
119
+ await client.call(RESOLVE, { invocation: invocationOf(run.seen), choice: "skip" });
120
+ await eventually(
121
+ () => lastState(run.seen)?.state === "done",
122
+ 15_000,
123
+ "the invocation should have finished after the skip",
124
+ );
125
+ // The skipped step was not called again; the step after it ran.
126
+ expect(counter(run.homePath, "effect").count()).toBe(1);
127
+ expect(counter(run.homePath, "after").count()).toBe(1);
128
+ await client.close();
129
+ } finally {
130
+ await run.cleanup();
131
+ }
132
+ }, 40_000);
@@ -0,0 +1,39 @@
1
+ // A point a plugin read when it was installed is not changed under it by a replacement of the plugin that offers there.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { createNiwa } from "@niwa-labs/host";
6
+ import { offerKey, plugin } from "@niwa-labs/plugin";
7
+ import type { Plugin } from "@niwa-labs/plugin";
8
+ import { tempHome } from "@niwa-labs/testing";
9
+
10
+ const POINT = offerKey<string[]>("contract.point", "contract-reader");
11
+
12
+ /** A provider that offers `values` at the point, and a reader that collects them in its setup. */
13
+ function provider(values: string[], version: string): Plugin {
14
+ return plugin("contract-provider", (api) => api.offer(POINT, values), { version });
15
+ }
16
+ const reader = (collected: string[][]): Plugin =>
17
+ plugin("contract-reader", (api) => void collected.push(api.offers(POINT).flatMap((one) => one.value)), { version: "1" });
18
+
19
+ test("replacing a provider with other offers at a point an installed plugin read is refused and names the reader", async () => {
20
+ const home = await tempHome();
21
+ const niwa = createNiwa({ home: home.path });
22
+ const collected: string[][] = [];
23
+ try {
24
+ niwa.use(provider(["old"], "1"), reader(collected));
25
+ expect(collected).toEqual([["old"]]);
26
+ const refused = provider(["new"], "2");
27
+ expect(() => niwa.use(refused)).toThrow(/contract-provider".*"contract.point".*"contract-reader" read when it was installed/);
28
+ expect(niwa.installed(refused.name)).not.toBe(refused);
29
+ // What it offered before is still what is offered, and an identical offer is a replacement as before.
30
+ const same = provider(["old"], "3");
31
+ niwa.use(same);
32
+ expect(niwa.installed(same.name)).toBe(same);
33
+ // So is a provider that withdraws its offer.
34
+ expect(() => niwa.use(plugin("contract-provider", () => undefined, { version: "4" }))).toThrow(/"contract-reader"/);
35
+ } finally {
36
+ await niwa.close();
37
+ await home.cleanup();
38
+ }
39
+ });
@@ -0,0 +1,22 @@
1
+ // A plugin made without one of its handlers is held to the same setup as the plugin it is made from.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { record } from "@niwa-labs/core";
6
+ import { createNiwa } from "@niwa-labs/host";
7
+ import { plugin, withoutHandler } from "@niwa-labs/plugin";
8
+ import type { PluginApi } from "@niwa-labs/plugin";
9
+ import { z } from "zod";
10
+
11
+ const Beat = record("async-setup.beat", z.object({ n: z.number() }), { open: true });
12
+
13
+ test("a setup that returns a promise is refused whole and without a handler", () => {
14
+ const asynchronous = plugin("async-setup", ((api: PluginApi) => {
15
+ api.on(Beat, { id: "x" }, () => undefined);
16
+ api.on(Beat, { id: "y" }, () => undefined);
17
+ return Promise.resolve();
18
+ }) as never);
19
+ const host = createNiwa({ home: "/nonexistent" });
20
+ expect(() => host.use(asynchronous)).toThrow(/asynchronous setup/);
21
+ expect(() => host.use(withoutHandler(asynchronous, "x"))).toThrow(/asynchronous setup/);
22
+ });
@@ -0,0 +1,87 @@
1
+ // The copies `plugin.install` imports (`.<hash><ext>`, beside the file) do not pile up:
2
+ // a plugin installed again with a new hash takes the copy of its
3
+ // previous file away, and a host start takes away the copies no installation is made from.
4
+
5
+ import { expect, test } from "bun:test";
6
+ import { existsSync } from "node:fs";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ import { actionName } from "@niwa-labs/core";
10
+ import { createNiwa } from "@niwa-labs/host";
11
+ import { plugin, pluginName } from "@niwa-labs/plugin";
12
+ import { tempHome, connectAsOwner } from "@niwa-labs/testing";
13
+ import { z } from "zod";
14
+
15
+ const PLUGIN_ENTRY = fileURLToPath(new URL("../../plugin/src/index.ts", import.meta.url));
16
+ const INSTALL = actionName("plugin.install");
17
+ /** A host with one plugin of its own: the actions of the host are served once a plugin is installed. */
18
+ const withBase = (home: string) => {
19
+ const niwa = createNiwa({ home });
20
+ niwa.use(plugin("base", () => {}));
21
+ return niwa;
22
+ };
23
+ const Installed = z.object({ hash: z.string() });
24
+
25
+ /** Write a module that exports the plugin `swapped` at this version. */
26
+ async function write(path: string, version: string): Promise<void> {
27
+ await Bun.write(path, `import { plugin } from "${PLUGIN_ENTRY}";\nexport default plugin("swapped", () => {}, { version: "${version}" });\n`);
28
+ }
29
+
30
+ test("a plugin installed again with a new hash takes the copy of its previous file away; the same hash keeps it", async () => {
31
+ const home = await tempHome();
32
+ const niwa = withBase(home.path);
33
+ await niwa.serve();
34
+ const owner = await connectAsOwner(home.path);
35
+ try {
36
+ const path = `${home.path}/swapped.ts`;
37
+ await write(path, "v1");
38
+ const first = Installed.parse(await owner.call(INSTALL, { plugin: "swapped", module: path }));
39
+ const copyOf = (hash: string) => `${home.path}/.${hash}.ts`;
40
+ expect(existsSync(copyOf(first.hash))).toBe(true);
41
+
42
+ // The same file again: it is the copy the plugin is made from, so it stays.
43
+ await owner.call(INSTALL, { plugin: "swapped", module: path });
44
+ expect(existsSync(copyOf(first.hash))).toBe(true);
45
+
46
+ await write(path, "v2");
47
+ const second = Installed.parse(await owner.call(INSTALL, { plugin: "swapped", module: path }));
48
+ expect(second.hash).not.toBe(first.hash);
49
+ expect(existsSync(copyOf(first.hash))).toBe(false);
50
+ expect(existsSync(copyOf(second.hash))).toBe(true);
51
+ expect(String(niwa.installed(pluginName("swapped"))?.version)).toBe("v2");
52
+ } finally {
53
+ await owner.close();
54
+ await niwa.close();
55
+ await home.cleanup();
56
+ }
57
+ });
58
+
59
+ test("a host start takes away the copies the installations are not made from, and nothing else", async () => {
60
+ const home = await tempHome();
61
+ const path = `${home.path}/swapped.ts`;
62
+ const first = withBase(home.path);
63
+ await first.serve();
64
+ const owner = await connectAsOwner(home.path);
65
+ await write(path, "v1");
66
+ const installed = Installed.parse(await owner.call(INSTALL, { plugin: "swapped", module: path }));
67
+ await owner.close();
68
+ await first.close();
69
+
70
+ // What a proposal that was never installed, or an install that was cut off, may have left.
71
+ const stale = `${home.path}/.${"a".repeat(64)}.ts`;
72
+ const own = `${home.path}/.${installed.hash}.ts`;
73
+ const others = [`${home.path}/.hidden.ts`, `${home.path}/notes.txt`, `${home.path}/.${"b".repeat(63)}.ts`];
74
+ await Bun.write(stale, "stale");
75
+ for (const other of others) await Bun.write(other, "mine");
76
+
77
+ const second = withBase(home.path);
78
+ await second.serve();
79
+ try {
80
+ expect(existsSync(stale)).toBe(false);
81
+ expect(existsSync(own)).toBe(true);
82
+ for (const other of others) expect(existsSync(other)).toBe(true);
83
+ } finally {
84
+ await second.close();
85
+ await home.cleanup();
86
+ }
87
+ });
@@ -0,0 +1,43 @@
1
+ // A plugin's own `emit` writes only the types that plugin declared.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { createNiwa } from "@niwa-labs/host";
6
+ import { plugin } from "@niwa-labs/plugin";
7
+ import { record, seq } from "@niwa-labs/core";
8
+ import type { PluginApi } from "@niwa-labs/plugin";
9
+ import type { StoredRecord } from "@niwa-labs/core";
10
+ import { tempHome } from "@niwa-labs/testing";
11
+ import { z } from "zod";
12
+
13
+ const Mine = record("emit-test.mine", z.object({ n: z.number() }));
14
+ const Theirs = record("emit-test.theirs", z.object({ n: z.number() }));
15
+
16
+ test("a plugin emits its own type as the host, and is refused another plugin's type", async () => {
17
+ const home = await tempHome();
18
+ const niwa = createNiwa({ home: home.path });
19
+ let api: PluginApi | undefined;
20
+ niwa.use(
21
+ plugin("emit-mine", (a) => {
22
+ a.declare(Mine);
23
+ api = a;
24
+ }),
25
+ );
26
+ niwa.use(plugin("emit-theirs", (a) => a.declare(Theirs)));
27
+ try {
28
+ await niwa.serve();
29
+ const written = await api?.emit(Mine, { n: 1 });
30
+ expect(written?.actor).toEqual({ kind: "host" });
31
+ expect(written?.cause).toBeNull();
32
+ await expect(api?.emit(Theirs, { n: 1 })).rejects.toThrow("emit-test.theirs");
33
+ const seen: StoredRecord[] = [];
34
+ for await (const found of niwa.records.since()) {
35
+ seen.push(found);
36
+ if (found.type === Mine.name) break;
37
+ }
38
+ expect(seen.map((r) => r.type)).toContain(Mine.name);
39
+ } finally {
40
+ await niwa.close();
41
+ await home.cleanup();
42
+ }
43
+ });