@niwa-labs/requests 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.
@@ -0,0 +1,265 @@
1
+ // A call under an `ask` rule creates a request to the owner and waits for
2
+ // the answer. `once` lets this call through, `run` lasts as long as the subject's grant, `always` is
3
+ // written into the grant, and no answer is a denial. The answers in force survive a restart.
4
+
5
+ import { afterEach, expect, test } from "bun:test";
6
+ import { z } from "zod";
7
+
8
+ import { CORE_TYPES, action, actionName, deny, grant, owner as ownerAddress, principalOf, seq } from "@niwa-labs/core";
9
+ import type { RuleSpec, Token } from "@niwa-labs/core";
10
+ import { plugin } from "@niwa-labs/plugin";
11
+ import { HostError, connect, createNiwa, eventually, tempHome, testClock, connectAsOwner, pick } from "@niwa-labs/testing";
12
+ import type { Host, NiwaApi, TestClock } from "@niwa-labs/testing";
13
+
14
+ import { REQUEST_ANSWER, REQUEST_CANCEL, REQUEST_OPEN, RequestAnswered, requests } from "../src/index.ts";
15
+
16
+
17
+ /** The inputs the probe was run with, in order: what the owner let through is what ran. */
18
+ const ran: string[] = [];
19
+
20
+ const probe = plugin("ask-probe", (api) => {
21
+ const make = (name: string) =>
22
+ action(name, {
23
+ description: `Records the call: ${name}.`,
24
+ input: z.object({ n: z.string() }),
25
+ output: z.object({ ran: z.string() }),
26
+ recovery: "repeat",
27
+ effect: "write",
28
+ run: async (input) => {
29
+ ran.push(`${name}:${input.n}`);
30
+ return { ran: input.n };
31
+ },
32
+ });
33
+ const guarded = make("probe.guarded");
34
+ api.action(make("probe.run"));
35
+ api.action(make("probe.other"));
36
+ api.action(guarded);
37
+ api.guard(guarded, (input) => (input.n === "no" ? deny("the guard says no") : undefined));
38
+ });
39
+
40
+ const AskedList = z.object({
41
+ requests: z.array(
42
+ z.object({
43
+ id: z.string(),
44
+ question: z.string().optional(),
45
+ input: z.unknown(),
46
+ }),
47
+ ),
48
+ });
49
+
50
+ interface Served {
51
+ readonly host: Host;
52
+ readonly home: string;
53
+ readonly clock: TestClock;
54
+ readonly owner: NiwaApi;
55
+ readonly secret: Token;
56
+ readonly subject: NiwaApi;
57
+ /** The answer the owner gives to the question that is open now. */
58
+ answer(value: string): Promise<void>;
59
+ /** The questions that wait for the owner now. */
60
+ open(): Promise<z.infer<typeof AskedList>["requests"]>;
61
+ close(): Promise<void>;
62
+ }
63
+
64
+ const cleanups: Array<() => Promise<void>> = [];
65
+ afterEach(async () => {
66
+ for (const cleanup of cleanups.splice(0)) await cleanup();
67
+ ran.length = 0;
68
+ });
69
+
70
+ async function served(
71
+ rules: RuleSpec[],
72
+ opts: { requests?: boolean; home?: { path: string; cleanup(): Promise<void> } } = {},
73
+ ): Promise<Served> {
74
+ const home = opts.home ?? (await tempHome());
75
+ const clock = testClock(1_700_000_000_000);
76
+ const host = createNiwa({ home: home.path, clock });
77
+ host.use(probe, ...(opts.requests === false ? [] : [requests()]));
78
+ await host.serve();
79
+ const secret = host.issueToken(principalOf("session", "s1"), { grant: grant(rules) });
80
+ const clients: NiwaApi[] = [];
81
+ const owner = await connectAsOwner(home.path);
82
+ const subject = await connect({ home: home.path, token: secret });
83
+ clients.push(owner, subject);
84
+ const open = async () => AskedList.parse(await owner.call(REQUEST_OPEN, {})).requests;
85
+ const served: Served = {
86
+ host,
87
+ home: home.path,
88
+ clock,
89
+ owner,
90
+ secret,
91
+ subject,
92
+ open,
93
+ async answer(value) {
94
+ await eventually(async () => (await open()).length > 0);
95
+ const [first] = await open();
96
+ await owner.call(REQUEST_ANSWER, { id: first?.id ?? "", answer: pick(value) });
97
+ },
98
+ async close() {
99
+ for (const client of clients) await client.close();
100
+ await host.close();
101
+ },
102
+ };
103
+ cleanups.push(async () => {
104
+ await served.close().catch(() => undefined);
105
+ if (opts.home === undefined) await home.cleanup();
106
+ });
107
+ return served;
108
+ }
109
+
110
+ const call = (api: NiwaApi, name: string, n: string, reason?: string) =>
111
+ api.call(actionName(name), { n }, reason === undefined ? undefined : { reason });
112
+
113
+ async function denial(promise: Promise<unknown>): Promise<HostError> {
114
+ const error = await promise.then(
115
+ () => undefined,
116
+ (thrown: unknown) => thrown,
117
+ );
118
+ expect(error).toBeInstanceOf(HostError);
119
+ return error as HostError;
120
+ }
121
+
122
+ test("a call under an ask rule asks the owner with who, what, the input and the reason", async () => {
123
+ const s = await served([{ do: "probe.run", ask: true }]);
124
+ const pending = call(s.subject, "probe.run", "alpha", "to finish the release");
125
+ await eventually(async () => (await s.open()).length === 1);
126
+ const [asked] = await s.open();
127
+ expect(asked?.question).toBe("access.ask");
128
+ // The question is a permission, and its subject holds the input of the call as it is.
129
+ expect(asked?.input).toMatchObject({
130
+ kind: "permission",
131
+ options: [{ id: "once" }, { id: "run" }, { id: "always" }, { id: "no" }],
132
+ subject: { who: "session:s1", action: "probe.run", rule: "call:probe.run", input: { n: "alpha" }, reason: "to finish the release" },
133
+ });
134
+ // Nothing ran while the owner had not answered.
135
+ expect(ran).toEqual([]);
136
+ await s.answer("once");
137
+ expect(await pending).toEqual({ ran: "alpha" });
138
+ expect(ran).toEqual(["probe.run:alpha"]);
139
+ });
140
+
141
+ test("once lets only this call through; the next call asks again, whatever its input", async () => {
142
+ const s = await served([{ do: "probe.run", ask: true }]);
143
+ const first = call(s.subject, "probe.run", "a");
144
+ await s.answer("once");
145
+ await first;
146
+
147
+ const second = denial(call(s.subject, "probe.run", "b"));
148
+ await eventually(async () => (await s.open()).length === 1);
149
+ expect(ran).toEqual(["probe.run:a"]);
150
+ const again = denial(call(s.subject, "probe.run", "a"));
151
+ await eventually(async () => (await s.open()).length === 2);
152
+ await s.answer("no");
153
+ await s.answer("no");
154
+ expect((await second).message).toContain("refused by the owner");
155
+ await again;
156
+ expect(ran).toEqual(["probe.run:a"]);
157
+ });
158
+
159
+ test("run lasts for the subject's grant and survives a restart", async () => {
160
+ const home = await tempHome();
161
+ const first = await served([{ do: "probe.run", ask: true }], { home });
162
+ const pending = call(first.subject, "probe.run", "a");
163
+ await first.answer("run");
164
+ await pending;
165
+ // Any input passes now, without a question; another action still asks.
166
+ await call(first.subject, "probe.run", "b");
167
+ expect(await first.open()).toEqual([]);
168
+ const rows = await first.host.records.read({ types: [CORE_TYPES.accessAnswered] });
169
+ expect(rows.map((row) => (row.data as { scope: string }).scope)).toEqual(["run"]);
170
+
171
+ // The same home, the same token: the answer in force is a record, so it is still in force.
172
+ const secret = first.secret;
173
+ await first.close();
174
+ const host = createNiwa({ home: home.path });
175
+ host.use(probe, requests());
176
+ await host.serve();
177
+ const again = await connect({ home: home.path, token: secret });
178
+ try {
179
+ expect(await call(again, "probe.run", "c")).toEqual({ ran: "c" });
180
+ const owner = await connectAsOwner(home.path);
181
+ expect(AskedList.parse(await owner.call(REQUEST_OPEN, {})).requests).toEqual([]);
182
+ await owner.close();
183
+ } finally {
184
+ await again.close();
185
+ await host.close();
186
+ await home.cleanup();
187
+ }
188
+ });
189
+
190
+ test("always is written into the grant as an exact rule; a sibling the owner was not asked about asks", async () => {
191
+ const s = await served([{ do: "probe.*", ask: true }, "access.mine"]);
192
+ const pending = call(s.subject, "probe.run", "a");
193
+ await s.answer("always");
194
+ await pending;
195
+
196
+ const mine = z.object({ rules: z.array(z.union([z.string(), z.object({ do: z.string(), ask: z.boolean().optional() })])) }).parse(await s.subject.call(actionName("access.mine"), {}));
197
+ expect(mine.rules).toContain("call:probe.run");
198
+ expect(mine.rules).toContainEqual({ do: "call:probe.*", ask: true });
199
+
200
+ await call(s.subject, "probe.run", "b");
201
+ expect(await s.open()).toEqual([]);
202
+ const sibling = denial(call(s.subject, "probe.other", "x"));
203
+ await eventually(async () => (await s.open()).length === 1);
204
+ await s.answer("no");
205
+ await sibling;
206
+ expect(ran).toEqual(["probe.run:a", "probe.run:b"]);
207
+ });
208
+
209
+ test("no answer in time is a typed denial 'not answered', and the request ends as expired", async () => {
210
+ const s = await served([{ do: "probe.run", ask: true }]);
211
+ const pending = denial(call(s.subject, "probe.run", "a"));
212
+ await eventually(async () => (await s.open()).length === 1);
213
+ await s.clock.advance(11 * 60 * 1000);
214
+ const error = await pending;
215
+ expect(error.message).toContain("not answered");
216
+ expect(error.denied).toMatchObject({ missing: "call:probe.run" });
217
+ expect(await s.open()).toEqual([]);
218
+ expect(ran).toEqual([]);
219
+ });
220
+
221
+ test("a cancelled question and a host with nobody to ask are denials too", async () => {
222
+ const s = await served([{ do: "probe.run", ask: true }]);
223
+ const pending = denial(call(s.subject, "probe.run", "a"));
224
+ await eventually(async () => (await s.open()).length === 1);
225
+ const [asked] = await s.open();
226
+ await s.owner.call(REQUEST_CANCEL, { id: asked?.id ?? "" });
227
+ expect((await pending).message).toContain("not answered");
228
+
229
+ const bare = await served([{ do: "probe.run", ask: true }], { requests: false });
230
+ expect((await denial(call(bare.subject, "probe.run", "a"))).message).toContain("not answered");
231
+ expect(ran).toEqual([]);
232
+ });
233
+
234
+ test("the guards still run after an allowed ask and may refuse", async () => {
235
+ const s = await served([{ do: "probe.guarded", ask: true }]);
236
+ const pending = denial(call(s.subject, "probe.guarded", "no"));
237
+ await s.answer("run");
238
+ expect((await pending).message).toContain("the guard says no");
239
+ expect(ran).toEqual([]);
240
+ });
241
+
242
+ test("the decision of an allowed ask records the scope that let it through", async () => {
243
+ const s = await served([{ do: "probe.run", ask: true }]);
244
+ const pending = call(s.subject, "probe.run", "a");
245
+ await s.answer("once");
246
+ await pending;
247
+ const rows = await s.host.records.read({ types: [CORE_TYPES.accessDecided] });
248
+ expect(rows.map((row) => row.data)).toContainEqual(
249
+ expect.objectContaining({ name: "probe.run", outcome: "allowed", answered: "once", rule: "call:probe.run" }),
250
+ );
251
+ });
252
+
253
+ test("an emit grant on a provider-only answer leaves the question open for its owner", async () => {
254
+ const s = await served([{ do: "probe.run", ask: true }, "emit:request.answered"]);
255
+ const pending = call(s.subject, "probe.run", "a");
256
+ await eventually(async () => (await s.open()).length === 1);
257
+ const [asked] = await s.open();
258
+ await expect(s.subject.emit(RequestAnswered, { id: asked?.id as never, answer: pick("always"), by: ownerAddress })).rejects.toThrow(/closed/);
259
+ expect(await s.open()).toHaveLength(1);
260
+ expect(ran).toEqual([]);
261
+ const rows = await s.host.records.read({ types: [CORE_TYPES.accessAnswered] });
262
+ expect(rows).toEqual([]);
263
+ await s.answer("once");
264
+ expect(await pending).toEqual({ ran: "a" });
265
+ });
@@ -0,0 +1,36 @@
1
+ // The copy of the request actions the cockpit module keeps reads what the host answers and sends what it takes.
2
+
3
+ import { expect, test } from "bun:test";
4
+ import { unreadable, unsendable } from "@niwa-labs/testing";
5
+
6
+ import { requestAnswer, requestOpen, requestResolve } from "../src/index.ts";
7
+ import { answerAction, openAction, overrideAction } from "../src/cockpit/actions.ts";
8
+
9
+ test("the open requests are read from what the host lists", () => {
10
+ expect(openAction.name).toBe(String(requestOpen.name));
11
+ expect(unreadable(openAction.output, requestOpen.output)).toEqual([]);
12
+ });
13
+
14
+ test("an open request keeps its deadline through the host and the cockpit schemas", () => {
15
+ const deadline = 1_790_000_000_000;
16
+ const value = requestOpen.output.parse({ requests: [{
17
+ id: "req-123456",
18
+ question: "fixture.deadline",
19
+ input: { kind: "text", title: "When?" },
20
+ to: { kind: "owner" },
21
+ deadline,
22
+ }] });
23
+ expect(openAction.output.parse(value)).toMatchObject({ requests: [{ deadline }] });
24
+ });
25
+
26
+ test("an answer is sent as the host takes it, and the host's reply is read", () => {
27
+ expect(answerAction.name).toBe(String(requestAnswer.name));
28
+ expect(unsendable(answerAction.input, requestAnswer.input)).toEqual([]);
29
+ expect(unreadable(answerAction.output, requestAnswer.output)).toEqual([]);
30
+ });
31
+
32
+ test("an explicit override uses the host's ordinary resolution contract", () => {
33
+ expect(overrideAction.name).toBe(String(requestResolve.name));
34
+ expect(unsendable(overrideAction.input, requestResolve.input)).toEqual([]);
35
+ expect(unreadable(overrideAction.output, requestResolve.output)).toEqual([]);
36
+ });
@@ -0,0 +1,77 @@
1
+ // What the answer forms of the requests page turn into.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import type { Question } from "../src/cockpit/actions.ts";
6
+ import { addressText, answerOf, EMPTY, otherAnswer, subjectLines } from "../src/cockpit/answers.ts";
7
+
8
+ const options = [
9
+ { id: "yes", label: "Yes", flavor: "plain" },
10
+ { id: "no", label: "No", flavor: "plain" },
11
+ ];
12
+ const choice: Question = { kind: "choice", title: "Go?", options };
13
+ const multi: Question = { kind: "multi", title: "Which?", options };
14
+
15
+ test("a choice takes exactly one option", () => {
16
+ expect(answerOf(choice, EMPTY)).toEqual({ problem: "Выберите вариант." });
17
+ expect(answerOf(choice, { picked: ["yes", "no"], text: "" })).toEqual({ problem: "Выберите один вариант." });
18
+ expect(answerOf(choice, { picked: ["yes"], text: "" })).toEqual({ answer: { ids: ["yes"] } });
19
+ });
20
+
21
+ test("a multiple choice accepts zero or more options", () => {
22
+ expect(answerOf(multi, EMPTY)).toEqual({ answer: { ids: [] } });
23
+ expect(answerOf(multi, { picked: ["yes", "no"], text: "" })).toEqual({ answer: { ids: ["yes", "no"] } });
24
+ });
25
+
26
+ test("a text question takes a text that is not blank", () => {
27
+ const text: Question = { kind: "text", title: "Why?" };
28
+ expect(answerOf(text, { picked: [], text: " " })).toEqual({ problem: "Напишите ответ." });
29
+ expect(answerOf(text, { picked: [], text: "because" })).toEqual({ answer: { text: "because" } });
30
+ expect(otherAnswer("elsewhere")).toEqual({ answer: { text: "elsewhere" } });
31
+ expect(otherAnswer("")).toEqual({ problem: "Напишите ответ." });
32
+ });
33
+
34
+ test("a form sends the typed values collected from its fields", () => {
35
+ const form: Question = { kind: "form", title: "Fill", schema: {} };
36
+ expect(answerOf(form, EMPTY)).toEqual({ problem: "Заполните форму." });
37
+ expect(answerOf(form, { ...EMPTY, form: { a: 1, approved: false } })).toEqual({ answer: { form: { a: 1, approved: false } } });
38
+ expect(answerOf(form, { ...EMPTY, form: null })).toEqual({ answer: { form: null } });
39
+ });
40
+
41
+ test("an address is named by its kind and what it names", () => {
42
+ expect(addressText({ kind: "owner" })).toBe("Владелец");
43
+ expect(addressText({ kind: "agent", id: "rin" })).toBe("Агент rin");
44
+ expect(addressText({ kind: "session", harness: "claude", id: "abc" })).toBe("Сессия claude · abc");
45
+ });
46
+
47
+ test("a permission shows what the owner decides on: the input of the call, the rule and the reason", () => {
48
+ const subject = { who: "session:s1", action: "git.push@origin", rule: "call:git.*", input: { branch: "main", force: true }, reason: "to ship" };
49
+ expect(subjectLines(subject)).toEqual([
50
+ { label: "who", value: "session:s1" },
51
+ { label: "action", value: "git.push@origin" },
52
+ { label: "rule", value: "call:git.*" },
53
+ { label: "input", value: { branch: "main", force: true } },
54
+ { label: "reason", value: "to ship" },
55
+ ]);
56
+ // Two calls of one action that differ only in their input do not look the same.
57
+ const other = subjectLines({ ...subject, input: { branch: "main", force: false } });
58
+ expect(other).not.toEqual(subjectLines(subject));
59
+ });
60
+
61
+ test("a permission of a tool shows the tool and what it acts on", () => {
62
+ expect(subjectLines({ tool: "Bash", kind: "execute", target: "rm -rf build" })).toEqual([
63
+ { label: "tool", value: "Bash" },
64
+ { label: "kind", value: "execute" },
65
+ { label: "target", value: "rm -rf build" },
66
+ ]);
67
+ });
68
+
69
+ test("a question that takes other sends the text when nothing is picked, and refuses text with a pick", () => {
70
+ const open: Question = { kind: "multi", title: "Which?", options, allowOther: true };
71
+ expect(answerOf(open, EMPTY)).toEqual({ answer: { ids: [] } });
72
+ expect(answerOf(open, { picked: [], text: "something else" })).toEqual({ answer: { text: "something else" } });
73
+ expect(answerOf(open, { picked: ["yes"], text: "something else" })).toEqual({ problem: "Выберите вариант или напишите свой ответ." });
74
+ expect(answerOf(open, { picked: ["yes"], text: " " })).toEqual({ answer: { ids: ["yes"] } });
75
+ // The same holds for a choice, which has always taken its other answer.
76
+ expect(answerOf({ ...choice, allowOther: true }, { picked: [], text: "else" })).toEqual({ answer: { text: "else" } });
77
+ });
@@ -0,0 +1,40 @@
1
+ // A request whose deadline passed takes no answer, even before the timer has written the expiry.
2
+
3
+ import { afterEach, expect, test } from "bun:test";
4
+ import { z } from "zod";
5
+
6
+ import { owner } from "@niwa-labs/core";
7
+ import { connectAsOwner, createNiwa, pick, tempHome, testClock } from "@niwa-labs/testing";
8
+
9
+ import { REQUEST_ANSWER, REQUEST_ASK, REQUEST_GET, requests } from "../src/index.ts";
10
+
11
+ const cleanups: Array<() => Promise<void>> = [];
12
+ afterEach(async () => {
13
+ for (const cleanup of cleanups.splice(0)) await cleanup();
14
+ });
15
+
16
+ test("an answer after the deadline is not accepted before the timer ran, and the request is expired", async () => {
17
+ const home = await tempHome();
18
+ // The clock is not advanced, so the timer never fires: only the answer can notice the deadline.
19
+ const host = createNiwa({ home: home.path, clock: testClock(1_700_000_000_000) });
20
+ host.use(requests());
21
+ await host.serve();
22
+ const client = await connectAsOwner(home.path);
23
+ cleanups.push(async () => {
24
+ await client.close();
25
+ await host.close();
26
+ await home.cleanup();
27
+ });
28
+
29
+ const { id } = z.object({ id: z.string() }).parse(
30
+ await client.call(REQUEST_ASK, {
31
+ to: owner,
32
+ question: "q.late",
33
+ input: { kind: "choice", title: "Go?", options: [{ id: "yes", label: "Yes", flavor: "plain" }] },
34
+ deadline: 0,
35
+ }),
36
+ );
37
+ const answered = await client.call(REQUEST_ANSWER, { id, answer: pick("yes") });
38
+ expect(answered).toEqual({ id, accepted: false, reason: "expired" });
39
+ expect(await client.call(REQUEST_GET, { id })).toMatchObject({ status: "expired" });
40
+ });
@@ -0,0 +1,223 @@
1
+ // How the actions that end a request behave when the world moves under them: a try that is made again,
2
+ // a request that ends while a resolver works, an answer that does not fit, a deadline that passed.
3
+ // The actions run on a journal held in memory, so the order of the writes is the test's.
4
+
5
+ import { expect, test } from "bun:test";
6
+ import { z } from "zod";
7
+
8
+ import { owner, recordId, seq, streamId } from "@niwa-labs/core";
9
+ import type { ActionContext, Address, Caller, JournalReader, OperationId, RecordType, StoredRecord, Timestamp } from "@niwa-labs/core";
10
+
11
+ import { requestActions } from "../src/index.ts";
12
+ import type { Expiry } from "../src/index.ts";
13
+ import { REQUEST_TYPES, RequestAnswered, RequestCancelledRecord, RequestCreated, RequestExpiredRecord, RequestId, expiryId } from "../src/records.ts";
14
+ import { ResolverRegistry } from "../src/resolver.ts";
15
+ import type { Resolver } from "../src/resolver.ts";
16
+ import { question } from "../src/question.ts";
17
+ import { RequestLedger } from "../src/state.ts";
18
+
19
+ const run = "run:abc";
20
+ const asker: Address = { kind: "client", id: run };
21
+ const text = question("t.text", { kind: "text", title: "Say something" });
22
+
23
+ /** A journal in memory that the ledger reads and the stub context writes. */
24
+ class Memory {
25
+ readonly rows: StoredRecord[] = [];
26
+
27
+ readonly reader = {
28
+ get: (id: string) => this.rows.find((row) => row.id === id),
29
+ since: (from: number, types?: string[]) => this.rows.filter((row) => row.seq > from && (types === undefined || types.includes(row.type))),
30
+ } as unknown as JournalReader;
31
+
32
+ append<T>(type: RecordType<T>, data: T, id?: string, actor: StoredRecord["actor"] = { kind: "host" }): StoredRecord {
33
+ const placed = id ?? `m${String(this.rows.length + 1)}`;
34
+ const existing = this.rows.find((row) => row.id === placed);
35
+ if (existing !== undefined) return existing;
36
+ const row: StoredRecord = {
37
+ id: recordId(placed),
38
+ seq: seq(this.rows.length + 1),
39
+ stream: streamId("test"),
40
+ type: type.name,
41
+ schema: 1,
42
+ data,
43
+ actor,
44
+ cause: null,
45
+ root: recordId(placed),
46
+ at: 0 as Timestamp,
47
+ };
48
+ this.rows.push(row);
49
+ return row;
50
+ }
51
+
52
+ typesOf(): string[] {
53
+ return this.rows.map((row) => row.type);
54
+ }
55
+ }
56
+
57
+ interface World {
58
+ readonly memory: Memory;
59
+ readonly time: { now: Timestamp | undefined };
60
+ readonly actions: ReturnType<typeof requestActions>;
61
+ /** The context of one call: its operation, and what it writes as the record of that operation. */
62
+ context(operation: string, caller?: Caller): ActionContext;
63
+ }
64
+
65
+ function world(resolver?: Resolver, asSurface?: (caller: Caller) => Address | undefined): World {
66
+ const memory = new Memory();
67
+ const ledger = new RequestLedger(REQUEST_TYPES.map((type) => type.name), () => memory.reader);
68
+ const resolvers = new ResolverRegistry();
69
+ if (resolver !== undefined) resolvers.register(text, resolver);
70
+ const time: { now: Timestamp | undefined } = { now: undefined };
71
+ const expiry: Expiry = {
72
+ now: () => time.now,
73
+ expire: async (id) => {
74
+ memory.append(RequestExpiredRecord, { id }, String(expiryId(id)));
75
+ },
76
+ };
77
+ const bind = (caller: Caller): Address | undefined => (caller.kind === "client" ? (caller.id === "owner" ? owner : { kind: "client", id: caller.id }) : asSurface?.(caller));
78
+ return {
79
+ memory,
80
+ time,
81
+ actions: requestActions(ledger, bind, resolvers, expiry),
82
+ context: (operation, caller = { kind: "client", id: "owner", principal: { kind: "owner", id: "owner" } } as Caller) =>
83
+ ({
84
+ operationId: operation as OperationId,
85
+ caller,
86
+ emit: async <T>(type: RecordType<T>, data: T) => memory.append(type, data, `${operation}/emit/1`, { ...caller, issuedBy: "requests" }),
87
+ }) as unknown as ActionContext,
88
+ };
89
+ }
90
+
91
+ const ID = RequestId.parse("req-aaaaaa");
92
+ const born = (memory: Memory, over: Partial<z.input<typeof RequestCreated.schema>> = {}): void => {
93
+ memory.append(RequestCreated, RequestCreated.schema.parse({ id: ID, to: owner, question: text.question, input: text.input, from: asker, ...over }));
94
+ };
95
+
96
+ test("an answer by run that was written before the cut-off is found again, not refused as having no open ask", async () => {
97
+ const w = world();
98
+ born(w.memory);
99
+ const first = await w.actions.answer.run({ run: "abc" as never, answer: { text: "yes" } }, w.context("op-1"));
100
+ expect(first).toEqual({ id: ID, accepted: true });
101
+ // The host stopped before it saved the result: the same operation is made again.
102
+ const again = await w.actions.answer.run({ run: "abc" as never, answer: { text: "yes" } }, w.context("op-1"));
103
+ expect(again).toEqual({ id: ID, accepted: true });
104
+ expect(w.memory.typesOf()).toEqual([RequestCreated.name, RequestAnswered.name]);
105
+ });
106
+
107
+ test("a cancel by run that was written before the cut-off is found again", async () => {
108
+ const w = world();
109
+ born(w.memory);
110
+ await w.actions.cancel.run({ run: "abc" as never }, w.context("op-1"));
111
+ expect(await w.actions.cancel.run({ run: "abc" as never }, w.context("op-1"))).toEqual({ id: ID });
112
+ expect(w.memory.typesOf()).toEqual([RequestCreated.name, RequestCancelledRecord.name]);
113
+ });
114
+
115
+ test("a resolve that answered before the cut-off says so when it is made again", async () => {
116
+ const w = world(() => ({ answered: true, answer: { text: "from the resolver" } }));
117
+ born(w.memory, { from: undefined });
118
+ const resolver = w.context("op-1", { kind: "host" });
119
+ expect(await w.actions.resolve.run({ id: ID }, resolver)).toEqual({ answered: true });
120
+ expect(await w.actions.resolve.run({ id: ID }, resolver)).toEqual({ answered: true });
121
+ expect(w.memory.typesOf().filter((type) => type === RequestAnswered.name)).toHaveLength(1);
122
+ });
123
+
124
+ test("a request cancelled while its resolver works is not answered afterwards", async () => {
125
+ let release: () => void = () => undefined;
126
+ const held = new Promise<void>((resolve) => {
127
+ release = resolve;
128
+ });
129
+ const w = world(async () => {
130
+ await held;
131
+ return { answered: true, answer: { text: "too late" } };
132
+ });
133
+ born(w.memory);
134
+ const pending = w.actions.resolve.run({ id: ID }, w.context("op-1", { kind: "host" }));
135
+ await w.actions.cancel.run({ id: ID }, w.context("op-2"));
136
+ release();
137
+ expect(await pending).toEqual({ answered: false });
138
+ expect(w.memory.typesOf()).toEqual([RequestCreated.name, RequestCancelledRecord.name]);
139
+ });
140
+
141
+ test("an answer of a resolver that does not fit the question is not written, and the request stays open", async () => {
142
+ const w = world(() => ({ answered: true, answer: { ids: [] } }));
143
+ born(w.memory);
144
+ const quiet = console.error;
145
+ console.error = () => undefined;
146
+ try {
147
+ expect(await w.actions.resolve.run({ id: ID }, w.context("op-1", { kind: "host" }))).toEqual({ answered: false });
148
+ } finally {
149
+ console.error = quiet;
150
+ }
151
+ expect(w.memory.typesOf()).toEqual([RequestCreated.name]);
152
+ });
153
+
154
+ test("an answer after the deadline ends the request as expired and is not taken, before the timer runs", async () => {
155
+ const w = world();
156
+ born(w.memory, { deadline: 1_000 as Timestamp });
157
+ w.time.now = 1_000 as Timestamp;
158
+ const result = await w.actions.answer.run({ id: ID, answer: { text: "late" } }, w.context("op-1"));
159
+ expect(result).toEqual({ id: ID, accepted: false, reason: "expired" });
160
+ expect(w.memory.typesOf()).toEqual([RequestCreated.name, RequestExpiredRecord.name]);
161
+ expect(w.memory.rows[1]?.id).toBe(expiryId(ID));
162
+ });
163
+
164
+ test("a resolver that answers after the deadline passed is not taken either", async () => {
165
+ // The time passes while the resolver works.
166
+ const w = world(() => {
167
+ w.time.now = 1_001 as Timestamp;
168
+ return { answered: true, answer: { text: "late" } };
169
+ });
170
+ born(w.memory, { deadline: 1_000 as Timestamp });
171
+ w.time.now = 999 as Timestamp;
172
+ expect(await w.actions.resolve.run({ id: ID }, w.context("op-1", { kind: "host" }))).toEqual({ answered: false });
173
+ expect(w.memory.typesOf()).toEqual([RequestCreated.name, RequestExpiredRecord.name]);
174
+ });
175
+
176
+ test("a resolve names the request by its whole id: one that does not exist is not taken for a longer id", async () => {
177
+ const w = world(() => ({ answered: true, answer: { text: "for whom?" } }));
178
+ born(w.memory, { id: RequestId.parse("req-1234567") });
179
+ expect(await w.actions.resolve.run({ id: RequestId.parse("req-123456") }, w.context("op-1", { kind: "host" }))).toEqual({ answered: false });
180
+ expect(w.memory.typesOf()).toEqual([RequestCreated.name]);
181
+ });
182
+
183
+ test("a try made again after an answer that landed behind a cancel says it did not stand", async () => {
184
+ const w = world();
185
+ born(w.memory);
186
+ w.memory.append(RequestCancelledRecord, { id: ID });
187
+ // The answer of an earlier try of this operation was written after the cancel: the cancel is the end.
188
+ w.memory.append(RequestAnswered, { id: ID, answer: { text: "behind" }, by: owner }, "op-1/emit/1");
189
+ expect(await w.actions.answer.run({ id: ID, answer: { text: "behind" } }, w.context("op-1"))).toEqual({ id: ID, accepted: false, reason: "cancelled" });
190
+ expect(await w.actions.resolve.run({ id: ID, answer: { text: "behind" } }, w.context("op-1"))).toEqual({ answered: false });
191
+ });
192
+
193
+ test("an owner-only decision can be answered only through the addressee action", async () => {
194
+ let calls = 0;
195
+ const w = world(() => {
196
+ calls++;
197
+ return { answered: true, answer: { text: "automatic" } };
198
+ });
199
+ born(w.memory, { answerPolicy: "owner-only" });
200
+ expect(await w.actions.resolve.run({ id: ID }, w.context("automatic"))).toEqual({ answered: false });
201
+ expect(await w.actions.resolve.run({ id: ID, answer: { text: "forwarded" } }, w.context("forwarded", { kind: "host" }))).toEqual({ answered: false });
202
+ expect(calls).toBe(0);
203
+ expect(await w.actions.answer.run({ id: ID, answer: { text: "operator" } }, w.context("operator"))).toEqual({ id: ID, accepted: true });
204
+ });
205
+
206
+
207
+ test("only the configured owner handler is credited for a direct ordinary resolution", async () => {
208
+ const trusted = { kind: "handler", handler: "surface/input", invocation: "inv-in" } as Caller;
209
+ const ordinary = { kind: "handler", handler: "surface/worker", invocation: "inv-work" } as Caller;
210
+ for (const [caller, forwarded, expected] of [[trusted, false, owner], [ordinary, false, undefined], [trusted, true, undefined]] as const) {
211
+ const w = world(undefined, (who) => who.kind === "handler" && who.handler === "surface/input" ? owner : undefined);
212
+ born(w.memory, { to: { kind: "agent", id: "judge" } });
213
+ const result = await w.actions.resolve.run({
214
+ id: ID, answer: { text: "chosen" }, ...(forwarded ? { info: { how: "forwarded" } } : {}),
215
+ }, w.context("op", caller));
216
+ expect(result.answered).toBe(true);
217
+ expect(RequestAnswered.schema.parse(w.memory.rows.at(-1)?.data).by).toEqual(expected);
218
+ }
219
+ const w = world(undefined, () => owner);
220
+ born(w.memory, { answerPolicy: "owner-only" });
221
+ expect(await w.actions.resolve.run({ id: ID, answer: { text: "chosen" } }, w.context("op", trusted))).toEqual({ answered: false });
222
+ expect(w.memory.typesOf()).toEqual([RequestCreated.name]);
223
+ });
@@ -0,0 +1,18 @@
1
+ // What a list and a read show of a request, whatever the asker wrote as its title.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { descriptionOf } from "../src/entity.ts";
6
+ import { RequestId } from "../src/records.ts";
7
+ import { question } from "../src/question.ts";
8
+
9
+ const id = RequestId.parse("req-abcdef");
10
+
11
+ test("a title too short to read is put after the name of the question", () => {
12
+ expect(descriptionOf({ id, question: question("rel.ok", { kind: "text", title: "ok" }).question, input: { kind: "text", title: "ok" } })).toBe("rel.ok ok");
13
+ });
14
+
15
+ test("a request whose name and title are both too short is described by its id, and can still be read", () => {
16
+ const asked = question("q", { kind: "text", title: " " });
17
+ expect(descriptionOf({ id, question: asked.question, input: asked.input })).toBe(id);
18
+ });