@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,190 @@
1
+ // Client.
2
+ //
3
+ // The scenario runs against a real host process (fixtures/client-host.ts),
4
+ // with the clients in this process:
5
+ //
6
+ // 1. spawn the host, connect client A, call the action "echo" and check the
7
+ // value it returns
8
+ // 2. A writes the notes 1..3
9
+ // 3. client B subscribes from the beginning of the journal, filtered to the
10
+ // record type Note, and collects what it receives
11
+ // 4. A writes the notes 4..6; B sees them
12
+ // 5. the host is killed with SIGKILL and spawned again
13
+ // 6. A, which stayed open, writes the notes 7..9: its call connection is reopened by itself
14
+ // 7. B ends up with all nine notes: the numbers 1..9 in order, positions
15
+ // strictly increasing, no record twice; and a subscriber that read everything
16
+ // from the start, unfiltered, saw exactly what a fresh read of the journal returns
17
+ //
18
+ // A second check holds a consumer that reads slowly: the subscription holds off the
19
+ // socket, and still delivers every record once, in order.
20
+ //
21
+ // The position is the point of the check. B subscribes from seq(0) and keeps
22
+ // its position across the restart, so the notes written before B connected
23
+ // and the notes written after the host came back arrive exactly once each:
24
+ // no gap, no duplicate.
25
+ //
26
+ // Only the public API is used: the entries of the packages (types, connect, seq) and "@niwa-labs/testing".
27
+
28
+ import { expect, test } from "bun:test";
29
+ import { fileURLToPath } from "node:url";
30
+
31
+ import type { NiwaApi } from "@niwa-labs/client";
32
+ import type { RecordQuery, StoredRecord } from "@niwa-labs/core";
33
+ import { connect } from "@niwa-labs/client";
34
+ import { seq } from "@niwa-labs/core";
35
+ import { eventually, spawnHost, tempHome, connectAsOwner } from "@niwa-labs/testing";
36
+ import { z } from "zod";
37
+
38
+ import { Note, echo } from "./fixtures/client-host.ts";
39
+
40
+ const HOST_SCRIPT = fileURLToPath(new URL("./fixtures/client-host.ts", import.meta.url));
41
+
42
+ /** The data of a Note record: { n }. */
43
+ const NoteData = z.object({ n: z.number() });
44
+
45
+ /** Read a subscription into a list until it is closed. */
46
+ function collect(client: NiwaApi, query?: RecordQuery): { records: StoredRecord[]; done: Promise<void> } {
47
+ const records: StoredRecord[] = [];
48
+ const done = (async () => {
49
+ for await (const record of client.records.since(query)) records.push(record);
50
+ })().catch(() => {});
51
+ return { records, done };
52
+ }
53
+
54
+ test("client: the action is called, the records arrive with no gap and no duplicate, and the subscriber continues after a restart", async () => {
55
+ const home = await tempHome();
56
+ const homePath = home.path;
57
+ let first: ReturnType<typeof spawnHost> | undefined;
58
+ let second: ReturnType<typeof spawnHost> | undefined;
59
+
60
+ try {
61
+ // 1. The first host, and a client that calls an action of it.
62
+ first = spawnHost(HOST_SCRIPT, homePath);
63
+ await first.ready();
64
+
65
+ const clientA = await connectAsOwner(homePath);
66
+ const echoed = await clientA.call(echo, { n: 42 });
67
+ expect(echoed).toEqual({ n: 42 });
68
+
69
+ // 2. The notes 1..3 are written before anybody subscribes.
70
+ for (const n of [1, 2, 3]) {
71
+ await clientA.emit(Note, { n });
72
+ }
73
+
74
+ // 3. Client B subscribes from the beginning of the journal, and collects
75
+ // what it receives. The subscription keeps its position, so it survives
76
+ // the restart of the host below.
77
+ const clientB = await connectAsOwner(homePath);
78
+ const { records: collected, done: subscription } = collect(clientB, { types: [Note] });
79
+ // An unfiltered subscriber from the start sees the whole journal, core records included.
80
+ const clientU = await connectAsOwner(homePath);
81
+ const { records: everything, done: everythingDone } = collect(clientU);
82
+
83
+ await eventually(
84
+ () => collected.length >= 3,
85
+ 15_000,
86
+ "the subscriber should have received the notes written before it connected",
87
+ );
88
+
89
+ // 4. The notes 4..6 are written while B is subscribed.
90
+ for (const n of [4, 5, 6]) {
91
+ await clientA.emit(Note, { n });
92
+ }
93
+
94
+ await eventually(
95
+ () => collected.length >= 6,
96
+ 15_000,
97
+ "the subscriber should have received the notes written while it was subscribed",
98
+ );
99
+
100
+ // 5. A real crash: SIGKILL, no clean shutdown.
101
+ await first.kill();
102
+
103
+ // 6. The host comes back on the same home.
104
+ second = spawnHost(HOST_SCRIPT, homePath);
105
+ await second.ready();
106
+
107
+ // 7. A writes the notes 7..9 on the same client: its connection died with the host.
108
+ for (const n of [7, 8, 9]) {
109
+ await clientA.emit(Note, { n });
110
+ }
111
+
112
+ await eventually(
113
+ () => collected.length >= 9,
114
+ 20_000,
115
+ "the subscriber should have received the notes written after the restart",
116
+ );
117
+
118
+ // Everything is written: a fresh read of the journal from the start is the truth. The
119
+ // unfiltered subscriber must hold exactly that — no gap and no duplicate, whatever the
120
+ // restart did to its connection.
121
+ const clientF = await connectAsOwner(homePath);
122
+ const { records: truth, done: truthDone } = collect(clientF);
123
+ const lastNote = collected[collected.length - 1];
124
+ await eventually(
125
+ () => truth.some((record) => record.id === lastNote?.id),
126
+ 15_000,
127
+ "a fresh read should reach the last note",
128
+ );
129
+ await eventually(
130
+ () => everything.length >= truth.length,
131
+ 15_000,
132
+ "the long-lived subscriber should have caught up with the journal",
133
+ );
134
+ const upToLast = (records: StoredRecord[]) => records.slice(0, records.findIndex((r) => r.id === lastNote?.id) + 1);
135
+ expect(upToLast(everything).map((record) => record.id)).toEqual(upToLast(truth).map((record) => record.id));
136
+
137
+ // 8. The nine notes: the numbers 1..9 in order, positions strictly
138
+ // increasing, no record twice.
139
+ const notes = collected.map((record) => NoteData.parse(record.data));
140
+ expect(notes.map((note) => note.n)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
141
+
142
+ const ids = collected.map((record) => record.id);
143
+ expect(new Set(ids).size).toBe(ids.length);
144
+
145
+ for (let i = 1; i < collected.length; i++) {
146
+ const previous = collected[i - 1];
147
+ const current = collected[i];
148
+ if (!previous || !current) throw new Error("the collection has a hole in it");
149
+ expect(current.seq).toBeGreaterThan(previous.seq);
150
+ }
151
+
152
+ await Promise.all([clientA, clientB, clientU, clientF].map((client) => client.close()));
153
+ await Promise.all([subscription, everythingDone, truthDone]);
154
+ } finally {
155
+ await first?.kill().catch(() => {});
156
+ await second?.kill().catch(() => {});
157
+ await home.cleanup();
158
+ }
159
+ }, 60_000);
160
+
161
+ test("slow consumer: the subscription holds off a full queue and still delivers every record once, in order", async () => {
162
+ const home = await tempHome();
163
+ let host: ReturnType<typeof spawnHost> | undefined;
164
+ const total = 3000; // well past the records a subscription queues for its consumer
165
+
166
+ try {
167
+ host = spawnHost(HOST_SCRIPT, home.path);
168
+ await host.ready();
169
+ const writer = await connectAsOwner(home.path);
170
+ await Promise.all(Array.from({ length: total }, (_unused, n) => writer.emit(Note, { n })));
171
+
172
+ const reader = await connectAsOwner(home.path);
173
+ const received: StoredRecord[] = [];
174
+ for await (const record of reader.records.since({ types: [Note] })) {
175
+ received.push(record);
176
+ // The first record is held for a while: the queue behind it fills and the connection is dropped.
177
+ if (received.length === 1) await new Promise((resolve) => setTimeout(resolve, 500));
178
+ if (received.length === total) break;
179
+ }
180
+
181
+ expect(new Set(received.map((record) => record.id)).size).toBe(total);
182
+ for (let i = 1; i < received.length; i++) {
183
+ expect(received[i]!.seq).toBeGreaterThan(received[i - 1]!.seq);
184
+ }
185
+ await Promise.all([writer.close(), reader.close()]);
186
+ } finally {
187
+ await host?.kill().catch(() => {});
188
+ await home.cleanup();
189
+ }
190
+ }, 60_000);
@@ -0,0 +1,118 @@
1
+ // The host lists the cockpit modules its plugins offer, with a hash of each module's code. It reads the point
2
+ // itself, so a plugin may offer a module with no reader installed.
3
+ //
4
+ // 1. a host whose plugin offers a module serves, and the catalogue lists it with the plugin's version
5
+ // 2. the hash covers the entry and the local files it imports, and nothing else
6
+ // 3. an offer that names no file, or a bad id, is refused when the catalogue is read
7
+ // 4. an offer to a reader that is not installed is still refused at start
8
+
9
+ import { expect, test } from "bun:test";
10
+ import { mkdir, writeFile } from "node:fs/promises";
11
+ import { join } from "node:path";
12
+
13
+ import { CATALOG_ACTION, CatalogOutput } from "@niwa-labs/client";
14
+ import { createNiwa } from "@niwa-labs/host";
15
+ import { COCKPIT_MODULE, offerKey, plugin } from "@niwa-labs/plugin";
16
+ import type { CockpitModuleOffer } from "@niwa-labs/plugin";
17
+ import { tempHome } from "@niwa-labs/testing";
18
+
19
+ async function withHost(
20
+ offers: (dir: string) => CockpitModuleOffer[],
21
+ run: (catalog: () => Promise<ReturnType<typeof CatalogOutput.parse>>, dir: string) => Promise<void>,
22
+ ): Promise<void> {
23
+ const home = await tempHome();
24
+ const dir = join(home.path, "module");
25
+ await mkdir(dir, { recursive: true });
26
+ await writeFile(join(dir, "index.tsx"), `import { page } from "./page.tsx";\nexport default page;\n`);
27
+ await writeFile(join(dir, "page.tsx"), `export const page = 1;\n`);
28
+ await writeFile(join(dir, "unrelated.ts"), `export const unrelated = 1;\n`);
29
+ const niwa = createNiwa({ home: home.path });
30
+ niwa.use(
31
+ plugin("offers", (api) => {
32
+ for (const offer of offers(dir)) api.offer(COCKPIT_MODULE, offer);
33
+ }),
34
+ );
35
+ await niwa.serve();
36
+ try {
37
+ await run(async () => CatalogOutput.parse(await niwa.call(CATALOG_ACTION, {})), dir);
38
+ } finally {
39
+ await niwa.close();
40
+ await home.cleanup();
41
+ }
42
+ }
43
+
44
+ test("a host whose plugin offers a cockpit module serves and lists it", () =>
45
+ withHost(
46
+ (dir) => [{ id: "demo", entry: join(dir, "index.tsx") }],
47
+ async (catalog) => {
48
+ const { modules } = await catalog();
49
+ expect(modules).toHaveLength(1);
50
+ expect(modules[0]).toMatchObject({ id: "demo", plugin: "offers", styles: [] });
51
+ expect(modules[0]?.hash).toMatch(/^[0-9a-f]{64}$/);
52
+ expect(modules[0]?.version).not.toBe("");
53
+ },
54
+ ));
55
+
56
+ test("the hash of a module follows the files it imports and no others", () =>
57
+ withHost(
58
+ (dir) => [{ id: "demo", entry: join(dir, "index.tsx"), styles: [join(dir, "unrelated.ts")] }],
59
+ async (catalog, dir) => {
60
+ const before = (await catalog()).modules[0]!;
61
+ expect((await catalog()).modules[0]?.hash).toBe(before.hash);
62
+
63
+ await writeFile(join(dir, "unrelated.ts"), `export const unrelated = 2;\n`);
64
+ const afterUnrelated = (await catalog()).modules[0]!;
65
+ expect(afterUnrelated.hash).toBe(before.hash);
66
+ // A stylesheet is hashed on its own: the page that links it needs the new address.
67
+ expect(afterUnrelated.styles[0]?.hash).not.toBe(before.styles[0]?.hash);
68
+
69
+ await writeFile(join(dir, "page.tsx"), `export const page = 2;\n`);
70
+ expect((await catalog()).modules[0]?.hash).not.toBe(before.hash);
71
+ },
72
+ ));
73
+
74
+ test("a module with a file that does not parse is still listed, so the others are", () =>
75
+ withHost(
76
+ (dir) => [{ id: "demo", entry: join(dir, "index.tsx") }],
77
+ async (catalog, dir) => {
78
+ const before = (await catalog()).modules[0]!;
79
+ await writeFile(join(dir, "page.tsx"), `export const page = (;\n`);
80
+ const after = (await catalog()).modules[0]!;
81
+ expect(after.id).toBe("demo");
82
+ expect(after.hash).not.toBe(before.hash);
83
+ },
84
+ ));
85
+
86
+ test("an offer that names no file or a bad id is refused when the catalogue is read", async () => {
87
+ await withHost(
88
+ (dir) => [{ id: "demo", entry: join(dir, "missing.tsx") }],
89
+ async (catalog) => {
90
+ await expect(catalog()).rejects.toThrow(/is not a file/);
91
+ },
92
+ );
93
+ await withHost(
94
+ (dir) => [{ id: "Not A Plugin", entry: join(dir, "index.tsx") }],
95
+ async (catalog) => {
96
+ await expect(catalog()).rejects.toThrow(/lowercase words/);
97
+ },
98
+ );
99
+ await withHost(
100
+ () => [{ id: "demo", entry: "relative/index.tsx" }],
101
+ async (catalog) => {
102
+ await expect(catalog()).rejects.toThrow(/not an absolute path/);
103
+ },
104
+ );
105
+ });
106
+
107
+ test("an offer to a reader that is not installed is refused at start", async () => {
108
+ const home = await tempHome();
109
+ const niwa = createNiwa({ home: home.path });
110
+ const orphan = offerKey<string>("orphan.point", "nobody");
111
+ niwa.use(plugin("offers", (api) => api.offer(orphan, "lost")));
112
+ try {
113
+ await expect(niwa.serve()).rejects.toThrow(/nobody/);
114
+ } finally {
115
+ await niwa.close();
116
+ await home.cleanup();
117
+ }
118
+ });
@@ -0,0 +1,88 @@
1
+ // Crash between steps.
2
+ //
3
+ // The scenario runs against a real host process (fixtures/crash-between-steps-host.ts):
4
+ //
5
+ // 1. spawn the host, connect a client, emit Start { n }
6
+ // 2. the handler calls a1 (its outcome is recorded) and then a2, which
7
+ // blocks on the gate "g2"; a2's counter reaching 1 proves step 1's
8
+ // outcome is already recorded
9
+ // 3. kill the host with SIGKILL — a real crash, in the middle of step 2
10
+ // 4. spawn the host again; the invocation resumes on the same record
11
+ // 5. open the gate "g2"; the second step finishes
12
+ // 6. a record of type "niwa.invocation.state" with state "done" appears
13
+ // 7. a1 was called once in total, a2 twice
14
+ //
15
+ // Only the public API is used: the entries of the packages (types) and "@niwa-labs/testing".
16
+
17
+ import { expect, test } from "bun:test";
18
+
19
+ import { connect } from "@niwa-labs/client";
20
+ import { counter, eventually, gate, spawnHost, tempHome, lastState, watch, connectAsOwner } from "@niwa-labs/testing";
21
+
22
+ import { Start } from "./fixtures/crash-between-steps-host.ts";
23
+ import { fileURLToPath } from "node:url";
24
+
25
+ const HOST_SCRIPT = fileURLToPath(new URL("./fixtures/crash-between-steps-host.ts", import.meta.url));
26
+
27
+ test("crash between steps: the first action is called once, the second step runs, the invocation ends as done", async () => {
28
+ const home = await tempHome();
29
+ const homePath = home.path;
30
+ let first: ReturnType<typeof spawnHost> | undefined;
31
+ let second: ReturnType<typeof spawnHost> | undefined;
32
+ let watcher: Awaited<ReturnType<typeof watch>> | undefined;
33
+
34
+ try {
35
+ // 1. The first host. It is killed in the middle of the second step.
36
+ first = spawnHost(HOST_SCRIPT, homePath);
37
+ await first.ready();
38
+
39
+ // One observer for the whole check: it reconnects to the second host by itself.
40
+ const observed = await watch(homePath);
41
+ watcher = observed;
42
+ const client = await connectAsOwner(homePath);
43
+ await client.emit(Start, { n: 7 });
44
+
45
+ // 2. a2 is only reached after step 1 returned, so its counter reaching 1
46
+ // is the proof that step 1's outcome was recorded. The gate is still
47
+ // closed, so a2 blocks and its own outcome is not recorded.
48
+ await eventually(
49
+ () => counter(homePath, "a2").count() >= 1,
50
+ 10_000,
51
+ "a2 should have been called once before the crash",
52
+ );
53
+ expect(counter(homePath, "a1").count()).toBe(1);
54
+ await eventually(
55
+ () => observed.seen.some((record) => record.type === "niwa.step.outcome"),
56
+ 10_000,
57
+ "the outcome of the first step should be recorded 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
65
+ // right away, before waiting for the socket: the resumed step must not
66
+ // block the host from accepting connections.
67
+ second = spawnHost(HOST_SCRIPT, homePath);
68
+ gate(homePath, "g2").open();
69
+ await second.ready();
70
+
71
+ // 5. The observer sees the invocation end.
72
+ await eventually(
73
+ () => lastState(observed.seen)?.state === "done",
74
+ 15_000,
75
+ "the invocation should have ended as done",
76
+ );
77
+
78
+ // 6. The first action was called once in total; the second step ran again.
79
+ expect(counter(homePath, "a1").count()).toBe(1);
80
+ expect(counter(homePath, "a2").count()).toBe(2);
81
+
82
+ } finally {
83
+ await watcher?.stop();
84
+ await first?.kill().catch(() => {});
85
+ await second?.kill().catch(() => {});
86
+ await home.cleanup();
87
+ }
88
+ }, 30_000);
@@ -0,0 +1,175 @@
1
+ // Declared values.
2
+ //
3
+ // The scenario runs against a real host process (fixtures/declared-values-host.ts):
4
+ //
5
+ // 1. the declared action is in the description, with its schemas, its description and
6
+ // its recovery contract
7
+ // 2. writing a record of a type no plugin declares is refused, and nothing is written
8
+ // 3. a record of a type that no plugin declares any more is still returned by
9
+ // records.since, with its raw data, and no handler runs on it
10
+ //
11
+ // Only the public API is used: the entries of the packages and "@niwa-labs/testing".
12
+
13
+ import { expect, test } from "bun:test";
14
+
15
+ import type { StoredRecord } from "@niwa-labs/core";
16
+ import { JsonSchemaValue, record, seq } from "@niwa-labs/core";
17
+ import { connect } from "@niwa-labs/client";
18
+ import { counter, eventually, spawnHost, tempHome, connectAsOwner } from "@niwa-labs/testing";
19
+ import { z } from "zod";
20
+
21
+ import { Note, unloadExtra } from "./fixtures/declared-values-host.ts";
22
+ import { fileURLToPath } from "node:url";
23
+
24
+ const HOST_SCRIPT = fileURLToPath(new URL("./fixtures/declared-values-host.ts", import.meta.url));
25
+
26
+ /** From the beginning of the journal. */
27
+ const FROM_START = seq(0);
28
+
29
+ /** A type no plugin declares. */
30
+ const Undeclared = record("declared-values.undeclared", z.object({ text: z.string() }));
31
+
32
+ /** The type of the extra plugin: it is declared only while that plugin is installed. */
33
+ const Extra = record("declared-values.extra", z.object({ text: z.string() }), { open: true });
34
+
35
+ /**
36
+ * Read the journal through the public subscription.
37
+ *
38
+ * A subscription never ends by itself, so the read stops itself: it waits for the journal to
39
+ * settle and then closes the subscription.
40
+ */
41
+ async function readJournal(
42
+ client: Awaited<ReturnType<typeof connect>>,
43
+ settleMs = 500,
44
+ ): Promise<StoredRecord[]> {
45
+ const records: StoredRecord[] = [];
46
+ const reading = (async () => {
47
+ for await (const record of client.records.since()) {
48
+ records.push(record);
49
+ }
50
+ })().catch(() => {});
51
+ await Bun.sleep(settleMs);
52
+ await client.close().catch(() => {});
53
+ await reading;
54
+ return records;
55
+ }
56
+
57
+ test("declared values: a declared action is described with its schemas, an undeclared type is refused, and a record of an unknown type is still readable", async () => {
58
+ const home = await tempHome();
59
+ const homePath = home.path;
60
+ let host: ReturnType<typeof spawnHost> | undefined;
61
+ let client: Awaited<ReturnType<typeof connect>> | undefined;
62
+
63
+ try {
64
+ host = spawnHost(HOST_SCRIPT, homePath);
65
+ await host.ready();
66
+ client = await connectAsOwner(homePath);
67
+
68
+ // 1. The declared action is in the self-description, with its schemas.
69
+ const description = await client.describe();
70
+ const described = description.actions.find((action) => action.name === "declared-values.shout");
71
+ expect(described).toBeDefined();
72
+ expect(described?.description).toBe("Returns its input, upper-cased.");
73
+ expect(described?.recovery).toBe("do-not-repeat");
74
+
75
+ // Nothing is listed twice, nothing is missing and nothing is invented: the description is the
76
+ // registered actions (the host's own resolve, move, install, observation and access actions are among them).
77
+ expect(description.actions.map((action) => String(action.name)).sort()).toEqual([
78
+ "access.explain",
79
+ "access.grant.change",
80
+ "access.grant.close",
81
+ "access.mine",
82
+ "access.profile.get",
83
+ "access.profile.set",
84
+ "access.switch",
85
+ "declared-values-handle",
86
+ "declared-values.shout",
87
+ "declared-values.unload-extra",
88
+ "niwa.causes",
89
+ "niwa.cockpit.catalog",
90
+ "niwa.describe",
91
+ "niwa.host.status",
92
+ "niwa.host.stop",
93
+ "niwa.invocation.cancel-steps",
94
+ "niwa.invocation.move",
95
+ "niwa.invocation.resolve",
96
+ "niwa.records.read",
97
+ "niwa.records.search",
98
+ "niwa.trace",
99
+ "plugin.install",
100
+ "plugin.uninstall",
101
+ ]);
102
+
103
+ // The input is a JSON Schema with the declared property.
104
+ const input = described?.input as { type?: string; properties?: Record<string, unknown> };
105
+ expect(input.type).toBe("object");
106
+ expect(input.properties?.text).toBeDefined();
107
+
108
+ // The output is a JSON Schema too.
109
+ const output = described?.output as { type?: string; properties?: Record<string, unknown> };
110
+ expect(output.type).toBe("object");
111
+ expect(output.properties?.text).toBeDefined();
112
+ expect(described?.input).toEqual(JsonSchemaValue.parse(z.toJSONSchema(z.object({ text: z.string() }), { io: "input" })));
113
+
114
+ // The declared record type is in the description as well.
115
+ const describedType = description.types.find((entry) => entry.name === "declared-values.note");
116
+ expect(describedType).toBeDefined();
117
+ expect(describedType?.version).toBe(1);
118
+
119
+ // 2. Writing a record of an undeclared type is refused, and nothing is
120
+ // written: the host does not know that type.
121
+ let refused: unknown;
122
+ try {
123
+ await client.emit(Undeclared, { text: "no" });
124
+ } catch (error) {
125
+ refused = error;
126
+ }
127
+ expect(refused).toBeDefined();
128
+ expect((refused as { code?: string }).code).toBe("UnknownType");
129
+
130
+ const afterRefusal = await readJournal(await connectAsOwner(homePath));
131
+ expect(afterRefusal.some((entry) => entry.type === Undeclared.name)).toBe(false);
132
+
133
+ // 3. A record of a type that no plugin declares any more is still returned
134
+ // by records.since, with its raw data, and no handler runs on it.
135
+ //
136
+ // The record is written while the plugin still declares the type.
137
+ const extra = await client.emit(Extra, { text: "kept" });
138
+ await eventually(
139
+ () => counter(homePath, "declared-values-handle").count() === 0,
140
+ 5_000,
141
+ "no handler of the extra type should have run",
142
+ );
143
+
144
+ // The plugin is unloaded: no plugin declares the type any more.
145
+ const unloaded = await client.call(unloadExtra, {});
146
+ expect(unloaded.ok).toBe(true);
147
+
148
+ const descriptionAfter = await client.describe();
149
+ expect(descriptionAfter.types.find((entry) => entry.name === Extra.name)).toBeUndefined();
150
+
151
+ // The record of the type nobody declares any more is still there, with its
152
+ // raw data.
153
+ const records = await readJournal(await connectAsOwner(homePath));
154
+ const found = records.find((entry) => entry.id === extra.id);
155
+ expect(found).toBeDefined();
156
+ expect(found?.type).toBe(Extra.name);
157
+ expect(found?.data).toEqual({ text: "kept" });
158
+
159
+ // And no handler ran on it: the type has no handler, so nothing was called.
160
+ expect(counter(homePath, "declared-values-handle").count()).toBe(0);
161
+
162
+ // The handler of the declared type still runs: the record of Note is
163
+ // handled, and the unknown one did not disturb it.
164
+ await client.emit(Note, { text: "hello" });
165
+ await eventually(
166
+ () => counter(homePath, "declared-values-handle").count() === 1,
167
+ 10_000,
168
+ "the handler of the declared type should run",
169
+ );
170
+ } finally {
171
+ await client?.close().catch(() => {});
172
+ await host?.kill().catch(() => {});
173
+ await home.cleanup();
174
+ }
175
+ }, 30_000);