@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,121 @@
1
+ // A plugin that fails to install changes nothing: not the plugin it would have replaced, and not
2
+ // what the host shares between plugins (the profiles and the state of the plugin).
3
+
4
+ import { expect, test } from "bun:test";
5
+
6
+ import { actionName, record } from "@niwa-labs/core";
7
+ import { createNiwa } from "@niwa-labs/host";
8
+ import { plugin, pluginName } from "@niwa-labs/plugin";
9
+ import type { PluginApi, StateHandle } from "@niwa-labs/plugin";
10
+ import { tempHome, connectAsOwner } from "@niwa-labs/testing";
11
+ import { z } from "zod";
12
+
13
+ const PROFILE_GET = actionName("access.profile.get");
14
+ const Ping = record("failing.ping", z.object({ n: z.number() }), { open: true });
15
+
16
+ /** A served host with one plugin `p` installed from `first`, and an owner connected. */
17
+ async function hosted(first: (api: PluginApi) => void) {
18
+ const home = await tempHome();
19
+ const niwa = createNiwa({ home: home.path });
20
+ niwa.use(plugin("p", first, { version: "v1" }));
21
+ await niwa.serve();
22
+ const owner = await connectAsOwner(home.path);
23
+ return {
24
+ niwa,
25
+ owner,
26
+ close: async () => {
27
+ await owner.close().catch(() => {});
28
+ await niwa.close();
29
+ await home.cleanup();
30
+ },
31
+ };
32
+ }
33
+
34
+ const profileRules = async (owner: Awaited<ReturnType<typeof connectAsOwner>>): Promise<unknown> =>
35
+ ((await owner.call(PROFILE_GET, { name: "mine" })) as { rules: unknown }).rules;
36
+
37
+ test("a replacement whose setup throws leaves the profile and the state of the installed plugin as they were", async () => {
38
+ let count: StateHandle<number> | undefined;
39
+ const h = await hosted((api) => {
40
+ api.declare(Ping);
41
+ api.profile("mine", () => ["task.*"]);
42
+ count = api.state("count", z.number(), 0);
43
+ });
44
+ try {
45
+ const installed = h.niwa.installed(pluginName("p"));
46
+ expect(await profileRules(h.owner)).toEqual(["call:task.*"]);
47
+
48
+ const failing = plugin(
49
+ "p",
50
+ (api) => {
51
+ api.profile("mine", () => ["*"]);
52
+ api.state("count", z.string(), "text");
53
+ throw new Error("the second version does not start");
54
+ },
55
+ { version: "v2" },
56
+ );
57
+ expect(() => h.niwa.use(failing)).toThrow("the second version does not start");
58
+
59
+ expect(h.niwa.installed(pluginName("p"))).toBe(installed);
60
+ expect(await profileRules(h.owner)).toEqual(["call:task.*"]);
61
+ // The state still holds what the installed plugin declared: a number.
62
+ expect(count?.set(5)).toBe(5);
63
+ expect(count?.get()).toBe(5);
64
+ } finally {
65
+ await h.close();
66
+ }
67
+ });
68
+
69
+ test("a setup that returns a promise is refused, and what it does after its first await changes nothing", async () => {
70
+ const h = await hosted((api) => {
71
+ api.declare(Ping);
72
+ api.profile("mine", () => ["task.*"]);
73
+ });
74
+ try {
75
+ const installed = h.niwa.installed(pluginName("p"));
76
+ const late = Promise.withResolvers<void>();
77
+ const asynchronous = plugin(
78
+ "p",
79
+ (api) => {
80
+ const setup = async (): Promise<void> => {
81
+ await Promise.resolve();
82
+ try {
83
+ api.profile("mine", () => ["*"]);
84
+ } catch {
85
+ // The api of a plugin that was refused does not change the host any more.
86
+ }
87
+ late.resolve();
88
+ };
89
+ // A promise is what an async setup returns, whatever the declared type of the setup says.
90
+ return setup() as unknown as void;
91
+ },
92
+ { version: "v2" },
93
+ );
94
+ expect(() => h.niwa.use(asynchronous)).toThrow(/setup .*promise/);
95
+ await late.promise;
96
+
97
+ expect(h.niwa.installed(pluginName("p"))).toBe(installed);
98
+ expect(await profileRules(h.owner)).toEqual(["call:task.*"]);
99
+ } finally {
100
+ await h.close();
101
+ }
102
+ });
103
+
104
+ test("a handler whose name contains a slash is refused, and the installed plugin stays", async () => {
105
+ const h = await hosted((api) => api.declare(Ping));
106
+ try {
107
+ const installed = h.niwa.installed(pluginName("p"));
108
+ const slashed = plugin(
109
+ "p",
110
+ (api) => {
111
+ api.declare(Ping);
112
+ api.on(Ping, { id: "a/b" }, () => {});
113
+ },
114
+ { version: "v2" },
115
+ );
116
+ expect(() => h.niwa.use(slashed)).toThrow(/handler "a\/b".*"\/"/);
117
+ expect(h.niwa.installed(pluginName("p"))).toBe(installed);
118
+ } finally {
119
+ await h.close();
120
+ }
121
+ });
@@ -0,0 +1,57 @@
1
+ // `plugin.install` names the hash the file is expected to have, and a file that is not that file is
2
+ // refused before any of its code runs: nothing of it is imported, and no copy of it is left.
3
+
4
+ import { expect, test } from "bun:test";
5
+ import { existsSync, readdirSync } from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ import { actionName } from "@niwa-labs/core";
9
+ import { createNiwa } from "@niwa-labs/host";
10
+ import { plugin, pluginName } from "@niwa-labs/plugin";
11
+ import { tempHome, connectAsOwner } from "@niwa-labs/testing";
12
+ import { z } from "zod";
13
+
14
+ const PLUGIN_ENTRY = fileURLToPath(new URL("../../plugin/src/index.ts", import.meta.url));
15
+ const INSTALL = actionName("plugin.install");
16
+ const Installed = z.object({ hash: z.string() });
17
+
18
+ /** A module that leaves a mark when it is imported, and exports the plugin `marked`. */
19
+ function moduleOf(mark: string, version: string): string {
20
+ return [
21
+ `import { writeFileSync } from "node:fs";`,
22
+ `import { plugin } from "${PLUGIN_ENTRY}";`,
23
+ `writeFileSync(${JSON.stringify(mark)}, "imported");`,
24
+ `export default plugin("marked", () => {}, { version: ${JSON.stringify(version)} });`,
25
+ "",
26
+ ].join("\n");
27
+ }
28
+
29
+ test("a file that is not the approved one is refused before it is imported, and leaves no copy", async () => {
30
+ const home = await tempHome();
31
+ const niwa = createNiwa({ home: home.path });
32
+ niwa.use(plugin("base", () => {}));
33
+ await niwa.serve();
34
+ const owner = await connectAsOwner(home.path);
35
+ try {
36
+ const path = `${home.path}/marked.ts`;
37
+ const mark = `${home.path}/imported.mark`;
38
+
39
+ await Bun.write(path, moduleOf(mark, "v1"));
40
+ const approved = Installed.parse(await owner.call(INSTALL, { plugin: "marked", module: path })).hash;
41
+ expect(existsSync(mark)).toBe(true);
42
+ await Bun.$`rm -f ${mark}`;
43
+
44
+ // The file changes after the hash was approved.
45
+ await Bun.write(path, moduleOf(mark, "v2"));
46
+ const before = readdirSync(home.path).sort();
47
+ await expect(owner.call(INSTALL, { plugin: "marked", module: path, hash: approved })).rejects.toThrow("is not the file that was approved");
48
+
49
+ expect(existsSync(mark)).toBe(false);
50
+ expect(readdirSync(home.path).sort()).toEqual(before);
51
+ expect(String(niwa.installed(pluginName("marked"))?.version)).toBe("v1");
52
+ } finally {
53
+ await owner.close();
54
+ await niwa.close();
55
+ await home.cleanup();
56
+ }
57
+ });
@@ -0,0 +1,80 @@
1
+ // What a plugin as a whole needs the host to serve is checked before the host serves.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { action, actionName, MissingNeed, record } from "@niwa-labs/core";
6
+ import { createNiwa } from "@niwa-labs/host";
7
+ import { plugin } from "@niwa-labs/plugin";
8
+ import { tempHome } from "@niwa-labs/testing";
9
+ import { z } from "zod";
10
+
11
+ const Beat = record("needs.beat", z.object({ n: z.number() }), { open: true });
12
+ const Pulse = record("needs.pulse", z.object({ n: z.number() }), { open: true });
13
+
14
+ const declares = plugin("needs-types", (api) => api.declare(Beat, Pulse));
15
+
16
+ test("a plugin that needs an action or a record type nobody serves makes the host refuse to serve", async () => {
17
+ const home = await tempHome();
18
+ try {
19
+ const missingAction = createNiwa({ home: home.path });
20
+ missingAction.use(plugin("needy", (api) => api.needs({ actions: [actionName("ask.nobody")] })));
21
+ const refused = await missingAction.serve().then(
22
+ () => undefined,
23
+ (error: unknown) => error,
24
+ );
25
+ expect(refused).toBeInstanceOf(MissingNeed);
26
+ expect(refused).toMatchObject({ plugin: "needy", kind: "action", needed: "ask.nobody" });
27
+ await missingAction.close();
28
+
29
+ const missingType = createNiwa({ home: home.path });
30
+ missingType.use(plugin("needy", (api) => api.needs({ types: ["nobody.writes"] })));
31
+ await expect(missingType.serve()).rejects.toMatchObject({ code: "MissingNeed", kind: "type", needed: "nobody.writes" });
32
+ await missingType.close();
33
+
34
+ const met = createNiwa({ home: home.path });
35
+ met.use(
36
+ declares,
37
+ plugin("needy", (api) => api.needs({ actions: ["niwa.host.status"], types: [Beat, "needs.pulse"] })),
38
+ );
39
+ await met.serve();
40
+ await met.close();
41
+ } finally {
42
+ await home.cleanup();
43
+ }
44
+ });
45
+
46
+ test("an action persisted in a plugin catalog satisfies a need before services start", async () => {
47
+ const home = await tempHome();
48
+ const dynamic = action("needs.persisted", {
49
+ description: "An action provided by a journal record", input: z.object({}), output: z.number(),
50
+ recovery: "repeat", effect: "read", run: () => 1,
51
+ });
52
+ const provider = plugin("catalog-provider", api => {
53
+ api.declare(Beat);
54
+ api.catalog(() => api.journal?.()?.find({type: Beat.name}).length ? [dynamic] : []);
55
+ });
56
+ let started = 0;
57
+ const consumer = plugin("catalog-consumer", api => {
58
+ api.needs({actions: [dynamic.name]});
59
+ api.service(() => { started++; return () => {}; });
60
+ });
61
+ let host = createNiwa({home: home.path});
62
+ try {
63
+ host.use(provider, consumer);
64
+ await expect(host.serve()).rejects.toMatchObject({code: "MissingNeed", needed: dynamic.name});
65
+ expect(started).toBe(0);
66
+ await host.close();
67
+
68
+ host = createNiwa({home: home.path});
69
+ host.use(provider);
70
+ await host.serve();
71
+ await host.emit(Beat, {n: 1});
72
+ await host.close();
73
+
74
+ host = createNiwa({home: home.path});
75
+ host.use(provider, consumer);
76
+ await host.serve();
77
+ expect(started).toBe(1);
78
+ expect(await host.call(dynamic, {})).toBe(1);
79
+ } finally { await host.close(); await home.cleanup(); }
80
+ });
@@ -0,0 +1,225 @@
1
+ // Replacing a plugin.
2
+ //
3
+ // The scenario runs against a real host process (fixtures/plugin-replace-host.ts):
4
+ //
5
+ // 1. spawn the host, connect a client, emit Start { n: 1 }
6
+ // 2. the handler of plugin "p" waits for Answer { n: 1 }; the invocation is waiting
7
+ // 3. call "fixture.upgrade" — plugin "p" is replaced by its changed version
8
+ // 4. emit Answer { n: 1 } — the waiting invocation finishes on the OLD code:
9
+ // "v1-finish" was called once, "v2-run" and "v2-finish" were not called at all
10
+ // 5. emit Start { n: 2 } — the new record is handled by the NEW code: "v2-run"
11
+ // 6. call "fixture.unload" — plugin "p" is unloaded
12
+ // 7. emit Start { n: 3 } — no handler of "p" runs any more, so "v2-run" stays at 1
13
+ // 8. every record plugin "p" wrote is still returned by records.since(0)
14
+ //
15
+ // Only the public API is used: the entries of the packages (types, connect, seq) and "@niwa-labs/testing".
16
+
17
+ import { expect, test } from "bun:test";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ import type { StoredRecord } from "@niwa-labs/core";
21
+ import { connect } from "@niwa-labs/client";
22
+ import { seq } from "@niwa-labs/core";
23
+ import { counter, eventually, spawnHost, tempHome, connectAsOwner } from "@niwa-labs/testing";
24
+ import { z } from "zod";
25
+
26
+ import { Answer, Start, unload, upgrade } from "./fixtures/plugin-replace-host.ts";
27
+
28
+ const HOST_SCRIPT = fileURLToPath(new URL("./fixtures/plugin-replace-host.ts", import.meta.url));
29
+
30
+ /** The data of a CORE.invocationState record: { invocation, state, reason? }. */
31
+ const InvocationState = z.object({
32
+ invocation: z.string(),
33
+ state: z.string(),
34
+ reason: z.string().optional(),
35
+ });
36
+
37
+ /** The data of a Start record: { n }. */
38
+ const StartData = z.object({ n: z.number() });
39
+
40
+ /** The data of a record as a plain object, or undefined when it is not one. */
41
+ function asObject(data: unknown): Record<string, unknown> | undefined {
42
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return undefined;
43
+ return data as Record<string, unknown>;
44
+ }
45
+
46
+ /**
47
+ * The state of the invocation that a record woke, as a state record says it.
48
+ *
49
+ * An invocation is identified by the handler and the record that woke it
50
+ *, so the id of that record is what tells the
51
+ * two invocations of this check apart.
52
+ */
53
+ function stateOf(record: StoredRecord, wokenBy: string): string | undefined {
54
+ if (record.type !== "niwa.invocation.state") return undefined;
55
+ const parsed = InvocationState.safeParse(record.data);
56
+ if (!parsed.success) return undefined;
57
+ if (!parsed.data.invocation.includes(wokenBy)) return undefined;
58
+ return parsed.data.state;
59
+ }
60
+
61
+ /**
62
+ * True for a record written for plugin "p".
63
+ *
64
+ * The runtime writes the records of a handler on its behalf, with the handler's
65
+ * id as the actor, and it admits an invocation with the handler's id in the
66
+ * data. A handler id is the plugin's name and the handler's own name
67
+ *.
68
+ */
69
+ function isWrittenByP(record: StoredRecord): boolean {
70
+ if (record.actor.kind === "handler") return record.actor.handler.startsWith("p/");
71
+ const handler = asObject(record.data)?.["handler"];
72
+ return typeof handler === "string" && handler.startsWith("p/");
73
+ }
74
+
75
+ /** True for a Start record with the given number. */
76
+ function isStart(record: StoredRecord, n: number): boolean {
77
+ if (record.type !== Start.name) return false;
78
+ const parsed = StartData.safeParse(record.data);
79
+ return parsed.success && parsed.data.n === n;
80
+ }
81
+
82
+ test("replacing a plugin: the waiting invocation finishes on the old code, a new record is handled by the new code, and after the unload the records stay readable", async () => {
83
+ const home = await tempHome();
84
+ const homePath = home.path;
85
+ let host: ReturnType<typeof spawnHost> | undefined;
86
+ let client: Awaited<ReturnType<typeof connect>> | undefined;
87
+ let observer: Awaited<ReturnType<typeof connect>> | undefined;
88
+ let subscription: Promise<void> | undefined;
89
+
90
+ try {
91
+ // 1. The host, with plugin "p" in its first version, and a client.
92
+ host = spawnHost(HOST_SCRIPT, homePath);
93
+ await host.ready();
94
+
95
+ client = await connectAsOwner(homePath);
96
+
97
+ // The observer reads the journal through the public subscription.
98
+ observer = await connectAsOwner(homePath);
99
+ const seen: StoredRecord[] = [];
100
+ subscription = (async () => {
101
+ for await (const record of observer.records.since()) {
102
+ seen.push(record);
103
+ }
104
+ })().catch(() => {});
105
+
106
+ // 2. The invocation of plugin "p" waits for its answer. Nothing has run
107
+ // yet: the handler of v1 waits first.
108
+ const start1 = await client.emit(Start, { n: 1 });
109
+
110
+ await eventually(
111
+ () => seen.some((record) => stateOf(record, start1.id) === "waiting"),
112
+ 10_000,
113
+ "the invocation of plugin p should be waiting for its answer",
114
+ );
115
+ expect(counter(homePath, "v1-finish").count()).toBe(0);
116
+ expect(counter(homePath, "v2-run").count()).toBe(0);
117
+
118
+ // 3. The plugin is replaced by a changed version of the same plugin.
119
+ const upgraded = await client.call(upgrade, {});
120
+ expect(upgraded.ok).toBe(true);
121
+
122
+ // 4. The answer wakes the waiting invocation, and it finishes on the OLD
123
+ // code: the new code runs "v2-run" before the wait, so a "v2-run" here
124
+ // would mean the invocation had moved onto the new version.
125
+ await client.emit(Answer, { n: 1 });
126
+ await eventually(
127
+ () => counter(homePath, "v1-finish").count() === 1,
128
+ 10_000,
129
+ "the old code should have finished the waiting invocation",
130
+ );
131
+ await eventually(
132
+ () => seen.some((record) => stateOf(record, start1.id) === "done"),
133
+ 10_000,
134
+ "the invocation should have ended as done",
135
+ );
136
+ expect(counter(homePath, "v1-finish").count()).toBe(1);
137
+ expect(counter(homePath, "v2-finish").count()).toBe(0);
138
+ expect(counter(homePath, "v2-run").count()).toBe(0);
139
+
140
+ // 5. A new record is handled by the NEW code.
141
+ const start2 = await client.emit(Start, { n: 2 });
142
+
143
+ await eventually(
144
+ () => counter(homePath, "v2-run").count() === 1,
145
+ 10_000,
146
+ "the new code should have handled the new record",
147
+ );
148
+ // The new code runs, then waits. Waiting is where it stops until the
149
+ // answer, and by then every record of this invocation is committed.
150
+ await eventually(
151
+ () => seen.some((record) => stateOf(record, start2.id) === "waiting"),
152
+ 10_000,
153
+ "the invocation of the new code should be waiting for its answer",
154
+ );
155
+ expect(counter(homePath, "v1-finish").count()).toBe(1);
156
+
157
+ // 6. The plugin is unloaded. Its handlers, actions and declarations go;
158
+ // the records it wrote stay.
159
+ const unloaded = await client.call(unload, {});
160
+ expect(unloaded.ok).toBe(true);
161
+
162
+ // 7. After the unload its handlers do not run any more. The record is
163
+ // still written — the control plugin declares the type — but no
164
+ // handler of plugin "p" picks it up.
165
+ let start3: StoredRecord;
166
+ try {
167
+ start3 = await client.emit(Start, { n: 3 });
168
+ } catch (error) {
169
+ throw new Error(
170
+ "the record after the unload could not be written: the type of plugin p must stay " +
171
+ "declared by a plugin that is still installed",
172
+ { cause: error },
173
+ );
174
+ }
175
+ await eventually(
176
+ () => seen.some((record) => isStart(record, 3)),
177
+ 10_000,
178
+ "the start record after the unload should be in the journal",
179
+ );
180
+ await Bun.sleep(500);
181
+ const admittedFor3 = seen.filter(
182
+ (record) =>
183
+ record.type === "niwa.invocation.admitted" &&
184
+ asObject(record.data)?.["record"] === start3.id,
185
+ );
186
+ expect(admittedFor3).toEqual([]);
187
+ // The same filter does find the invocations that did run: the check is not vacuous.
188
+ expect(seen.some((record) => record.type === "niwa.invocation.admitted" && asObject(record.data)?.["record"] === start2.id)).toBe(true);
189
+ expect(counter(homePath, "v2-run").count()).toBe(1);
190
+ expect(counter(homePath, "v2-finish").count()).toBe(0);
191
+ expect(counter(homePath, "v1-finish").count()).toBe(1);
192
+
193
+ // 8. Every record plugin "p" wrote is still returned by records.since(0):
194
+ // a fresh read of the journal from the beginning finds all of them.
195
+ const writtenByP = seen.filter(isWrittenByP);
196
+ expect(writtenByP.length).toBeGreaterThan(0);
197
+ const expectedIds = new Set(writtenByP.map((record) => record.id));
198
+
199
+ const reread = await connectAsOwner(homePath);
200
+ const all: StoredRecord[] = [];
201
+ const reader = (async () => {
202
+ for await (const record of reread.records.since()) {
203
+ all.push(record);
204
+ }
205
+ })().catch(() => {});
206
+
207
+ await eventually(
208
+ () => {
209
+ const found = new Set(all.map((record) => record.id));
210
+ return [...expectedIds].every((id) => found.has(id));
211
+ },
212
+ 10_000,
213
+ "every record written by plugin p should still be readable",
214
+ );
215
+
216
+ await reread.close();
217
+ await reader;
218
+ } finally {
219
+ await client?.close().catch(() => {});
220
+ await observer?.close().catch(() => {});
221
+ if (subscription !== undefined) await subscription;
222
+ await host?.kill().catch(() => {});
223
+ await home.cleanup();
224
+ }
225
+ }, 30_000);
@@ -0,0 +1,70 @@
1
+ import { expect, test } from "bun:test";
2
+ import { existsSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ import { connect } from "@niwa-labs/client";
6
+ import { CORE_TYPES, actionName, grant, principalOf } from "@niwa-labs/core";
7
+ import { createNiwa } from "@niwa-labs/host";
8
+ import { plugin, pluginName } from "@niwa-labs/plugin";
9
+ import { connectAsOwner, tempHome } from "@niwa-labs/testing";
10
+ import { z } from "zod";
11
+
12
+ const INSTALL = actionName("plugin.install");
13
+ const UNINSTALL = actionName("plugin.uninstall");
14
+ const Installed = z.object({ hash: z.string() });
15
+ const pluginEntry = fileURLToPath(new URL("../../plugin/src/index.ts", import.meta.url));
16
+
17
+ test("Restore pinned modules and remove only the selected installation", async () => {
18
+ const home = await tempHome();
19
+ const module = `${home.path}/edit.ts`;
20
+ const makeHost = async () => {
21
+ const host = createNiwa({ home: home.path });
22
+ host.use(plugin("configured", () => {}));
23
+ await host.serve();
24
+ return host;
25
+ };
26
+ const write = (version: string) => Bun.write(module, [
27
+ `import { plugin } from "${pluginEntry}";`,
28
+ `export default plugin("rin/edit", () => {}, { version: "${version}" });`,
29
+ ].join("\n"));
30
+ let host = await makeHost();
31
+ let owner = await connectAsOwner(home.path);
32
+ try {
33
+ await write("first");
34
+ await expect(owner.call(INSTALL, { plugin: "configured", module })).rejects.toThrow("configured");
35
+ const first = Installed.parse(await owner.call(INSTALL, { plugin: "rin/edit", module }));
36
+ await write("second");
37
+ await owner.close();
38
+ await host.close();
39
+
40
+ host = await makeHost();
41
+ owner = await connectAsOwner(home.path);
42
+ expect(host.installed(pluginName("rin/edit"))?.version).toBe("first");
43
+ const second = Installed.parse(await owner.call(INSTALL, { plugin: "rin/edit", module }));
44
+ await expect(owner.call(UNINSTALL, { plugin: "rin/edit", hash: first.hash })).rejects.toThrow("selected hash");
45
+ const token = host.issueToken(principalOf("session", "non-owner"), { grant: grant(["plugin.uninstall@rin/*"]) });
46
+ const session = await connect({ home: home.path, id: "non-owner", token });
47
+ try {
48
+ await expect(session.call(UNINSTALL, { plugin: "rin/edit", hash: second.hash })).rejects.toThrow("only the owner");
49
+ } finally {
50
+ await session.close();
51
+ }
52
+ await expect(owner.call(UNINSTALL, { plugin: "configured", hash: second.hash })).rejects.toThrow("not installed from a module");
53
+ await owner.call(UNINSTALL, { plugin: "rin/edit", hash: second.hash });
54
+ expect(host.installed(pluginName("rin/edit"))).toBeUndefined();
55
+ expect(existsSync(`${home.path}/.${second.hash}.ts`)).toBe(false);
56
+ expect(existsSync(module)).toBe(true);
57
+ expect(await host.records.read({ types: [CORE_TYPES.pluginUninstalled] })).toHaveLength(1);
58
+ await owner.close();
59
+ await host.close();
60
+
61
+ host = await makeHost();
62
+ owner = await connectAsOwner(home.path);
63
+ expect(host.installed(pluginName("rin/edit"))).toBeUndefined();
64
+ expect(host.installed(pluginName("configured"))).toBeDefined();
65
+ } finally {
66
+ await owner.close();
67
+ await host.close();
68
+ await home.cleanup();
69
+ }
70
+ });
@@ -0,0 +1,53 @@
1
+ // The default version of a plugin follows its handlers even when the plugin is made by another
2
+ // copy of the plugin package than the one the host loaded.
3
+
4
+ import { expect, test } from "bun:test";
5
+ import { cpSync, mkdtempSync, rmSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
8
+ import { createNiwa } from "@niwa-labs/host";
9
+ import { pluginName } from "@niwa-labs/plugin";
10
+ import type { Plugin } from "@niwa-labs/plugin";
11
+ import { tempHome } from "@niwa-labs/testing";
12
+
13
+ const PLUGIN_SRC = join(import.meta.dir, "../../plugin/src");
14
+
15
+ /** A plugin whose module imports the copy of the package at `copy` and whose handler has `body`. */
16
+ async function fromCopy(copy: string, body: string): Promise<Plugin> {
17
+ const module = join(copy, `made-${Bun.hash(body)}.ts`);
18
+ await Bun.write(
19
+ module,
20
+ `import { record } from "@niwa-labs/core";
21
+ import { z } from "zod";
22
+ import { plugin } from "./src/index.ts";
23
+ const Ping = record("copies.ping", z.object({}));
24
+ // Outside the setup, so only the sealed version sees the body.
25
+ const handle = async () => { ${body} };
26
+ export default plugin("copied", (api) => {
27
+ api.declare(Ping);
28
+ api.on(Ping, handle);
29
+ });
30
+ `,
31
+ );
32
+ return ((await import(module)) as { default: Plugin }).default;
33
+ }
34
+
35
+ test("a plugin from a second copy of the package takes a new version when a handler body changes", async () => {
36
+ const copy = mkdtempSync(join(import.meta.dir, ".plugin-copy-"));
37
+ cpSync(PLUGIN_SRC, join(copy, "src"), { recursive: true });
38
+ const home = await tempHome();
39
+ try {
40
+ const versions: string[] = [];
41
+ for (const body of ["return 1;", "return 2;"]) {
42
+ const niwa = createNiwa({ home: home.path });
43
+ niwa.use(await fromCopy(copy, body));
44
+ await niwa.serve();
45
+ versions.push(String(niwa.installed(pluginName("copied"))?.version));
46
+ await niwa.close();
47
+ }
48
+ expect(versions[0]).not.toBe(versions[1]);
49
+ } finally {
50
+ rmSync(copy, { recursive: true, force: true });
51
+ await home.cleanup();
52
+ }
53
+ });