@niwa-labs/tasks 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,520 @@
1
+ // The plain executor: the plain way of doing a task.
2
+ //
3
+ // The scenario runs in one process, against a real host on a temporary home:
4
+ //
5
+ // 1. a task is created for the executor of a harness
6
+ // 2. the Assignment goes to the executor address, and the executor starts one session
7
+ // 3. the session is asked for the result, and the task ends done with that answer
8
+ // 4. the end of the task is reported where the task says to report
9
+ // 5. an assignment for somebody else wakes no executor at all
10
+ //
11
+ // Only the public API is used: the entries of the packages.
12
+
13
+ import { expect, test } from "bun:test";
14
+
15
+ import { CORE_TYPES, grant, principalOf, seq } from "@niwa-labs/core";
16
+ import type { RecordTypeName, StoredRecord } from "@niwa-labs/core";
17
+ import { MessageSent, messageSendRef } from "@niwa-labs/messages/records";
18
+ import {
19
+ connect,
20
+ createNiwa,
21
+ eventually,
22
+ harnessId,
23
+ harnessKind,
24
+ machineId,
25
+ messages,
26
+ sessionId,
27
+ sessions,
28
+ tempHome,
29
+ } from "@niwa-labs/testing";
30
+ import type {
31
+ Host,
32
+ AskAnswer,
33
+ AskOptions,
34
+ DeliveryReceipt,
35
+ Harness,
36
+ LifeEvent,
37
+ SessionControl,
38
+ SessionId,
39
+ SessionState,
40
+ } from "@niwa-labs/testing";
41
+ import { TaskCreated, TaskDone, TaskId, executor, taskCreate, taskResult, tasks } from "../src/index.ts";
42
+
43
+ /** The harness the fake control side serves. */
44
+ const HARNESS = "fake-harness";
45
+
46
+ /** The session the fake names. */
47
+ const SESSION = "session-1";
48
+
49
+ /** The text of the work. */
50
+ const TEXT = "Move the parsing into its own module.";
51
+
52
+ /** The answer the fake session gives. */
53
+ const ANSWER = "The parsing lives in its own module now.";
54
+
55
+ /** The address that asks for the work. */
56
+ const ASKER = { kind: "owner" } as const;
57
+
58
+ /** The address the result is reported to. */
59
+ const REPORTER = { kind: "owner" } as const;
60
+
61
+ /** The few words that describe the work. */
62
+ const DESCRIPTION = "Move argument parsing";
63
+
64
+ /**
65
+ * The fake control side.
66
+ *
67
+ * It names one session, it records the prompts it was given, and it answers an ask with a
68
+ * fixed value.
69
+ */
70
+ class FakeControl implements SessionControl {
71
+ /** The prompts the sessions were started with, in order. */
72
+ readonly started: string[] = [];
73
+ /** The questions the session was asked, in order. */
74
+ readonly asked: string[] = [];
75
+ /** How many times a session was started. */
76
+ starts = 0;
77
+ /** Whether an ask blocks instead of answering. */
78
+ blockAsk = false;
79
+ /** What the session answers: the text of the plain result, unless a test says otherwise. */
80
+ answer: unknown = { result: ANSWER };
81
+ /** Whether the answer of the session fits the schema of each ask, in order. */
82
+ readonly fits: boolean[] = [];
83
+
84
+ async start(options: { prompt: { sections: { text: string }[] } }): Promise<{ session: SessionId }> {
85
+ this.starts += 1;
86
+ this.started.push(options.prompt.sections.map((section) => section.text).join("\n"));
87
+ return { session: sessionId(harnessId(HARNESS), SESSION) };
88
+ }
89
+
90
+ async resume(): Promise<void> {}
91
+
92
+ async send(_id: SessionId, _message: string): Promise<DeliveryReceipt> {
93
+ return { status: "started", turn: 1 };
94
+ }
95
+
96
+ async interrupt(): Promise<void> {}
97
+
98
+ async ask<T>(_id: SessionId, options: AskOptions<T>): Promise<AskAnswer<T>> {
99
+ this.asked.push(options.prompt.sections.map((section) => section.text).join("\n"));
100
+ if (this.blockAsk) await new Promise<void>(() => {});
101
+ this.fits.push(options.schema.safeParse(this.answer).success);
102
+ return { session: sessionId(harnessId(HARNESS), SESSION), value: this.answer as T, at: 0 as never };
103
+ }
104
+
105
+ async *life(): AsyncIterable<LifeEvent> {
106
+ // The signs of life are not what this test is about.
107
+ }
108
+
109
+ async state(): Promise<SessionState> {
110
+ return "idle";
111
+ }
112
+ }
113
+
114
+ /** The installation the fake control side serves. */
115
+ function installation(): Harness {
116
+ return {
117
+ id: harnessId(HARNESS),
118
+ kind: harnessKind("fake-kind"),
119
+ machine: machineId("machine-1"),
120
+ home: "/tmp/fake-home",
121
+ sides: {
122
+ control: {
123
+ start: true,
124
+ resume: true,
125
+ send: true,
126
+ interrupt: false,
127
+ ask: true,
128
+ structuredOutput: true, launch: { model: false, effort: [], modes: [] },
129
+ },
130
+ },
131
+ };
132
+ }
133
+
134
+ /** A host with the messages module, the sessions module and the tasks module over the fake. */
135
+ async function serve(control: FakeControl, home: string, options?: Parameters<typeof tasks>[0]): Promise<Host> {
136
+ const niwa = createNiwa({ home });
137
+ niwa.use(messages({ bind: () => undefined }));
138
+ niwa.use(sessions({ harnesses: [{ instance: installation(), control }] }));
139
+ niwa.use(tasks(options));
140
+ await niwa.serve();
141
+ return niwa;
142
+ }
143
+
144
+ /** The records of one type the host holds. */
145
+ async function recordsOf(niwa: Host, type: RecordTypeName): Promise<StoredRecord[]> {
146
+ return niwa.records.read({ types: [type] });
147
+ }
148
+
149
+ test("the executor: a task for an executor starts one session and ends done with the answer", async () => {
150
+ const home = await tempHome();
151
+ const control = new FakeControl();
152
+ const niwa = await serve(control, home.path);
153
+
154
+ try {
155
+ // The task is created and returns at once, with its id.
156
+ const created = await niwa.call(taskCreate, {
157
+ kind: "change",
158
+ description: DESCRIPTION,
159
+ text: TEXT,
160
+ askedBy: ASKER,
161
+ responsible: executor(HARNESS),
162
+ reportTo: REPORTER,
163
+ });
164
+ const TASK_ID = created.id;
165
+ expect(TASK_ID).toMatch(/^task-[0-9a-f]{6,8}$/);
166
+
167
+ // The Assignment went to the executor address.
168
+ const sent = await recordsOf(niwa, MessageSent.name);
169
+ const envelope = sent[0]?.data as { to: { kind: string; id: string }; task?: string; body: { type: string } };
170
+ expect(envelope.to).toEqual({ kind: "agent", id: `executor:${HARNESS}` });
171
+ expect(envelope.task).toBe(TASK_ID);
172
+ expect(envelope.body.type).toBe("assignment");
173
+
174
+ // The session was started once, with the assignment as its prompt.
175
+ await eventually(() => control.starts === 1, 10_000, "the executor should have started a session");
176
+ expect(control.starts).toBe(1);
177
+ expect(control.started[0]).toContain(TEXT);
178
+
179
+ // The session was asked for the result.
180
+ await eventually(() => control.asked.length === 1, 10_000, "the session should have been asked");
181
+ expect(control.asked[0]).toContain("Give the result of the task.");
182
+
183
+ // The task ends done, with what the session said.
184
+ await eventually(
185
+ async () => (await recordsOf(niwa, TaskDone.name)).length === 1,
186
+ 10_000,
187
+ "the task should have ended",
188
+ );
189
+ const done = await recordsOf(niwa, TaskDone.name);
190
+ expect(done[0]?.data).toEqual({
191
+ task: TASK_ID,
192
+ outcome: { status: "result", result: ANSWER },
193
+ });
194
+
195
+ // The result of the task is what the session said.
196
+ const result = await niwa.call(taskResult, { task: TASK_ID });
197
+ expect(result).toEqual({
198
+ task: TASK_ID,
199
+ outcome: { status: "result", result: ANSWER },
200
+ });
201
+
202
+ // The end of the task is reported where the task says to report.
203
+ await eventually(
204
+ async () =>
205
+ (await recordsOf(niwa, MessageSent.name)).some(
206
+ (record) => (record.data as { body: { type: string } }).body.type === "result",
207
+ ),
208
+ 10_000,
209
+ "the owner should have been told how the task ended",
210
+ );
211
+
212
+ // One session was started: the executor does not start a second one.
213
+ expect(control.starts).toBe(1);
214
+
215
+ // The task was created once, and the trace holds the whole chain.
216
+ const taskRecords = await recordsOf(niwa, TaskCreated.name);
217
+ expect(taskRecords).toHaveLength(1);
218
+ } finally {
219
+ await niwa.close();
220
+ await home.cleanup();
221
+ }
222
+ }, 30_000);
223
+
224
+ test("the executor: a restart after the session was started starts no second session", async () => {
225
+ const home = await tempHome();
226
+ const control = new FakeControl();
227
+ // The ask blocks: the invocation of the executor is unfinished when the host stops.
228
+ control.blockAsk = true;
229
+ const first = await serve(control, home.path);
230
+
231
+ try {
232
+ await first.call(taskCreate, {
233
+ kind: "change",
234
+ description: DESCRIPTION,
235
+ text: TEXT,
236
+ askedBy: ASKER,
237
+ responsible: executor(HARNESS),
238
+ reportTo: REPORTER,
239
+ });
240
+
241
+ // The session was started and the ask was reached: the outcome of the start is recorded.
242
+ await eventually(() => control.asked.length === 1, 10_000, "the session should have been asked");
243
+ expect(control.starts).toBe(1);
244
+ } finally {
245
+ await first.close();
246
+ }
247
+
248
+ // The second host runs the unfinished invocation again. The start is answered from the
249
+ // record, so no second session is started, and the ask is not made again: a call that was
250
+ // cut off cannot be repeated, so the invocation pauses for a decision.
251
+ const second = await serve(control, home.path);
252
+ try {
253
+ await eventually(
254
+ async () =>
255
+ (await recordsOf(second, CORE_TYPES.invocationState)).some(
256
+ (record) => (record.data as { state?: string }).state === "paused",
257
+ ),
258
+ 10_000,
259
+ "the invocation should have paused on the cut-off ask",
260
+ );
261
+ expect(control.starts).toBe(1);
262
+ expect(control.asked).toHaveLength(1);
263
+ expect(await recordsOf(second, TaskDone.name)).toHaveLength(0);
264
+ } finally {
265
+ await second.close();
266
+ await home.cleanup();
267
+ }
268
+ }, 30_000);
269
+
270
+ test("the executor: an assignment for somebody else wakes no executor", async () => {
271
+ const home = await tempHome();
272
+ const control = new FakeControl();
273
+ const niwa = await serve(control, home.path);
274
+
275
+ try {
276
+ await niwa.call(taskCreate, {
277
+ kind: "change",
278
+ description: DESCRIPTION,
279
+ text: TEXT,
280
+ askedBy: ASKER,
281
+ responsible: { kind: "agent", id: "somebody-else" },
282
+ reportTo: REPORTER,
283
+ });
284
+
285
+ // The Assignment went out, and no session was started: the executor is not its addressee.
286
+ await eventually(
287
+ async () => (await recordsOf(niwa, MessageSent.name)).length === 1,
288
+ 10_000,
289
+ "the assignment should have been sent",
290
+ );
291
+ expect(control.starts).toBe(0);
292
+ expect(control.asked).toHaveLength(0);
293
+ } finally {
294
+ await niwa.close();
295
+ await home.cleanup();
296
+ }
297
+ }, 30_000);
298
+
299
+ test("the executor: an assignment for a task the executor is not responsible for starts no session", async () => {
300
+ const home = await tempHome();
301
+ const control = new FakeControl();
302
+ const niwa = await serve(control, home.path);
303
+
304
+ try {
305
+ const notMine = await niwa.call(taskCreate, {
306
+ kind: "change",
307
+ description: DESCRIPTION,
308
+ text: TEXT,
309
+ askedBy: ASKER,
310
+ responsible: { kind: "agent", id: "somebody-else" },
311
+ reportTo: REPORTER,
312
+ });
313
+ // A second assignment of the same task, addressed to the executor, who is not responsible.
314
+ await niwa.call(messageSendRef, {
315
+ from: ASKER,
316
+ to: executor(HARNESS),
317
+ task: notMine.id,
318
+ body: { type: "assignment", text: TEXT, kind: "change" },
319
+ });
320
+
321
+ await eventually(
322
+ async () =>
323
+ (await recordsOf(niwa, CORE_TYPES.invocationState)).some(
324
+ (record) => ["paused", "failed"].includes((record.data as { state?: string }).state ?? ""),
325
+ ),
326
+ 10_000,
327
+ "the invocation should have stopped on the refusal",
328
+ );
329
+ expect(control.starts).toBe(0);
330
+ expect(await recordsOf(niwa, TaskDone.name)).toHaveLength(0);
331
+ } finally {
332
+ await niwa.close();
333
+ await home.cleanup();
334
+ }
335
+ }, 30_000);
336
+
337
+ test("the executor: a task that declares a result schema asks the session by it, and the answer is the result", async () => {
338
+ const home = await tempHome();
339
+ const control = new FakeControl();
340
+ const shape = { type: "object", properties: { files: { type: "number" } }, required: ["files"] };
341
+ control.answer = { files: 2 };
342
+ const niwa = await serve(control, home.path);
343
+
344
+ try {
345
+ const { id } = await niwa.call(taskCreate, {
346
+ kind: "change",
347
+ description: DESCRIPTION,
348
+ text: TEXT,
349
+ askedBy: ASKER,
350
+ responsible: executor(HARNESS),
351
+ reportTo: REPORTER,
352
+ result: shape,
353
+ });
354
+
355
+ // The assignment carries the schema, so the session that does the work is shown it.
356
+ await eventually(() => control.starts === 1, 10_000, "the executor should have started a session");
357
+ expect(control.started[0]).toContain("The result must fit this JSON Schema:");
358
+ expect(control.started[0]).toContain('"required":["files"]');
359
+ const sent = await recordsOf(niwa, MessageSent.name);
360
+ expect((sent[0]?.data as { body: { result?: unknown } }).body.result).toEqual(shape);
361
+
362
+ // The session is asked by the declared schema, and its whole answer is the result.
363
+ await eventually(async () => (await recordsOf(niwa, TaskDone.name)).length === 1, 10_000, "the task should have ended");
364
+ expect(control.fits).toEqual([true]);
365
+ expect(await niwa.call(taskResult, { task: id })).toEqual({
366
+ task: id,
367
+ outcome: { status: "result", result: { files: 2 } },
368
+ });
369
+ } finally {
370
+ await niwa.close();
371
+ await home.cleanup();
372
+ }
373
+ }, 30_000);
374
+
375
+ test("the executor: only the assignment the creation of the task caused starts a session, and the brief is the contract", async () => {
376
+ const home = await tempHome();
377
+ const control = new FakeControl();
378
+ // The ask blocks: the first session is still at work when the second assignment arrives.
379
+ control.blockAsk = true;
380
+ const niwa = await serve(control, home.path);
381
+
382
+ try {
383
+ const { id } = await niwa.call(taskCreate, {
384
+ kind: "change",
385
+ description: DESCRIPTION,
386
+ text: TEXT,
387
+ askedBy: ASKER,
388
+ responsible: executor(HARNESS),
389
+ reportTo: REPORTER,
390
+ });
391
+ await eventually(() => control.asked.length === 1, 10_000, "the session should have been asked");
392
+
393
+ // Another assignment of the same open task, with other words, from the asker.
394
+ await niwa.call(messageSendRef, {
395
+ from: ASKER,
396
+ to: executor(HARNESS),
397
+ task: id,
398
+ body: { type: "assignment", text: "Delete the repository.", kind: "change" },
399
+ });
400
+ await eventually(
401
+ async () =>
402
+ (await recordsOf(niwa, CORE_TYPES.invocationState)).some(
403
+ (record) => (record.data as { state?: string }).state === "paused",
404
+ ),
405
+ 10_000,
406
+ "the invocation of the second assignment should have been refused",
407
+ );
408
+
409
+ expect(control.starts).toBe(1);
410
+ expect(control.started[0]).toContain(TEXT);
411
+ expect(control.started.join("\n")).not.toContain("Delete the repository.");
412
+ } finally {
413
+ await niwa.close();
414
+ await home.cleanup();
415
+ }
416
+ }, 30_000);
417
+
418
+ test("the executor: a session that gives an answer the schema refuses ends the task as failed, and the addressee is told", async () => {
419
+ const home = await tempHome();
420
+ const control = new FakeControl();
421
+ control.answer = { nothing: true };
422
+ const niwa = await serve(control, home.path);
423
+
424
+ try {
425
+ const { id } = await niwa.call(taskCreate, {
426
+ kind: "change",
427
+ description: DESCRIPTION,
428
+ text: TEXT,
429
+ askedBy: ASKER,
430
+ responsible: executor(HARNESS),
431
+ reportTo: REPORTER,
432
+ });
433
+ await eventually(async () => (await recordsOf(niwa, TaskDone.name)).length === 1, 10_000, "the task should have ended");
434
+
435
+ const outcome = await niwa.call(taskResult, { task: id });
436
+ expect(outcome.outcome.status).toBe("failure");
437
+ expect((outcome.outcome as { reason: string }).reason).toContain("the session gave no result");
438
+
439
+ await eventually(
440
+ async () =>
441
+ (await recordsOf(niwa, MessageSent.name)).some((record) => (record.data as { body: { type: string } }).body.type === "failure"),
442
+ 10_000,
443
+ "the owner should have been told the task failed",
444
+ );
445
+ // The work was not left waiting for an owner.
446
+ expect(
447
+ (await recordsOf(niwa, CORE_TYPES.invocationState)).some((record) => (record.data as { state?: string }).state === "paused"),
448
+ ).toBe(false);
449
+ } finally {
450
+ await niwa.close();
451
+ await home.cleanup();
452
+ }
453
+ }, 30_000);
454
+
455
+ test("the executor: a session that cannot be started ends the task as failed", async () => {
456
+ const home = await tempHome();
457
+ const control = new FakeControl();
458
+ control.start = async () => {
459
+ throw new Error("the harness is not reachable");
460
+ };
461
+ const niwa = await serve(control, home.path);
462
+
463
+ try {
464
+ const { id } = await niwa.call(taskCreate, {
465
+ kind: "change",
466
+ description: DESCRIPTION,
467
+ text: TEXT,
468
+ askedBy: ASKER,
469
+ responsible: executor(HARNESS),
470
+ reportTo: REPORTER,
471
+ });
472
+ await eventually(async () => (await recordsOf(niwa, TaskDone.name)).length === 1, 10_000, "the task should have ended");
473
+ const outcome = await niwa.call(taskResult, { task: id });
474
+ expect(outcome.outcome).toEqual({
475
+ status: "failure",
476
+ reason: "the session could not be started: the harness is not reachable",
477
+ });
478
+ } finally {
479
+ await niwa.close();
480
+ await home.cleanup();
481
+ }
482
+ }, 30_000);
483
+
484
+
485
+ test("the executor checks the creating client's grant against its assigned harness", async () => {
486
+ const home = await tempHome();
487
+ const control = new FakeControl();
488
+ const niwa = await serve(control, home.path, { messages: { bind: (caller) =>
489
+ caller.kind === "client" && caller.principal !== undefined ? { kind: "client", id: caller.principal.id } : undefined,
490
+ } });
491
+ const clients = [];
492
+ try {
493
+ for (const [label, harness] of [["denied", "different"], ["allowed", HARNESS]] as const) {
494
+ const principal = principalOf("client", label);
495
+ const token = niwa.issueToken(principal, { grant: grant(["task.create", `session.start@${harness}`, "session.ask"]) });
496
+ const client = await connect({ home: home.path, id: label, token });
497
+ clients.push(client);
498
+ const { id } = await client.call(taskCreate, {
499
+ kind: "change", description: DESCRIPTION, text: TEXT,
500
+ askedBy: { kind: "client", id: label }, responsible: executor(HARNESS), reportTo: REPORTER,
501
+ });
502
+ const { outcome } = await niwa.call(taskResult, { task: id });
503
+ if (label === "denied") {
504
+ expect(outcome).toMatchObject({ status: "failure" });
505
+ expect(control.starts).toBe(0);
506
+ } else {
507
+ expect(outcome.status).toBe("result");
508
+ const granted = await recordsOf(niwa, CORE_TYPES.accessGranted);
509
+ expect(granted.some((r) => {
510
+ const g = r.data as { principal: { kind: string }; parent?: { principal: { id: string } } };
511
+ return g.principal.kind === "session" && g.parent?.principal.id === label;
512
+ })).toBe(true);
513
+ }
514
+ }
515
+ } finally {
516
+ for (const client of clients) await client.close();
517
+ await niwa.close();
518
+ await home.cleanup();
519
+ }
520
+ }, 30000);
@@ -0,0 +1,172 @@
1
+ // The ledger of tasks: what the journal says of a task is read from its own records.
2
+ //
3
+ // Updates change neither the creation nor the end of a task, so a reader of one task, and the
4
+ // state of every task, never reads them: a series of reports costs nothing to the reads after it.
5
+ // A call that was cut off asks the record it wrote first what it did.
6
+
7
+ import { expect, test } from "bun:test";
8
+
9
+ import { recordId, seq } from "@niwa-labs/core";
10
+ import type { Address, Caller, JournalQuery, JournalReader, OperationId, RecordTypeName, StoredRecord } from "@niwa-labs/core";
11
+ import { plugin } from "@niwa-labs/plugin";
12
+ import type { CallerBinding } from "@niwa-labs/plugin";
13
+ import { connectAsOwner, createNiwa, messages, tempHome } from "@niwa-labs/testing";
14
+ import type { Host } from "@niwa-labs/testing";
15
+
16
+ import { TaskCreated, TaskDone, TaskUpdated, taskActions, taskCreate, taskFail, taskFinish, taskIds, taskLedger, taskReport } from "../src/index.ts";
17
+ import type { TaskActions, TaskContract, TaskLedger } from "../src/index.ts";
18
+
19
+ const ASKER: Address = { kind: "owner" };
20
+ const WORKER: Address = { kind: "agent", id: "worker" };
21
+
22
+ const CONTRACT: TaskContract = {
23
+ id: "task-aaaaaa" as TaskContract["id"],
24
+ kind: "change",
25
+ description: "Move argument parsing" as TaskContract["description"],
26
+ text: "Move it.",
27
+ askedBy: ASKER,
28
+ responsible: WORKER,
29
+ reportTo: ASKER,
30
+ };
31
+
32
+ /** A journal reader over a list of records that counts the records it hands out. */
33
+ function counting(records: StoredRecord[]): { reader: JournalReader; handedOut: () => number } {
34
+ let out = 0;
35
+ const give = (rows: StoredRecord[]) => {
36
+ out += rows.length;
37
+ return rows;
38
+ };
39
+ const at = (query: JournalQuery) => (row: StoredRecord) => {
40
+ if (row.type !== query.type) return false;
41
+ if (query.field === undefined) return true;
42
+ return (row.data as Record<string, unknown>)[query.field] === query.equals;
43
+ };
44
+ const reader: JournalReader = {
45
+ get: (id) => records.find((row) => row.id === id),
46
+ since: (from, types) => give(records.filter((row) => row.seq > from && (types === undefined || types.includes(row.type)))),
47
+ find: (query) => give(records.filter(at(query))),
48
+ query: () => [],
49
+ last: () => seq(records.length),
50
+ };
51
+ return { reader, handedOut: () => out };
52
+ }
53
+
54
+ function stored(position: number, type: RecordTypeName, data: unknown): StoredRecord {
55
+ return {
56
+ id: recordId(`r-${String(position)}`),
57
+ seq: seq(position),
58
+ stream: "s" as never,
59
+ type,
60
+ schema: 1,
61
+ data,
62
+ actor: { kind: "host" } as Caller,
63
+ cause: null,
64
+ root: recordId(`r-${String(position)}`),
65
+ at: 0 as never,
66
+ };
67
+ }
68
+
69
+ test("the state of one task, and of every task, is read without the updates", () => {
70
+ const records: StoredRecord[] = [stored(1, TaskCreated.name, CONTRACT)];
71
+ for (let index = 0; index < 300; index += 1) {
72
+ records.push(stored(2 + index, TaskUpdated.name, { task: CONTRACT.id, text: `step ${String(index)}` }));
73
+ }
74
+ records.push(stored(400, TaskDone.name, { task: CONTRACT.id, outcome: { status: "result", result: 1 } }));
75
+
76
+ const one = counting(records);
77
+ const state = taskLedger(() => one.reader).state(CONTRACT.id);
78
+ expect(state?.status).toBe("done");
79
+ // Its creation and its end, whatever the journal holds besides.
80
+ expect(one.handedOut()).toBe(2);
81
+
82
+ const all = counting(records);
83
+ expect(taskLedger(() => all.reader).states().get(CONTRACT.id)?.status).toBe("done");
84
+ expect(all.handedOut()).toBe(2);
85
+
86
+ // A task that was never created is not found, and nothing else is read for it.
87
+ const none = counting(records);
88
+ expect(taskLedger(() => none.reader).state("task-bbbbbb")).toBeUndefined();
89
+ expect(none.handedOut()).toBe(0);
90
+ });
91
+
92
+ /** The actions of the module and its ledger, taken from inside a plugin of a running host. */
93
+ async function served(
94
+ run: (taken: { ledger: TaskLedger; acts: TaskActions }, host: Host, home: string) => Promise<void>,
95
+ ) {
96
+ const home = await tempHome();
97
+ // A client speaks as the worker, which is responsible for the tasks; the host stands for nobody.
98
+ const bind: CallerBinding = (caller) => (caller.kind === "client" ? WORKER : undefined);
99
+ const niwa = createNiwa({ home: home.path });
100
+ niwa.use(messages({ bind }));
101
+ let taken: { ledger: TaskLedger; acts: TaskActions } | undefined;
102
+ niwa.use(
103
+ plugin("tasks", (api) => {
104
+ const ledger = taskLedger(() => api.journal?.());
105
+ const acts = taskActions(ledger, taskIds(() => api.journal?.()), bind);
106
+ api.declare(TaskCreated, TaskUpdated, TaskDone);
107
+ api.action(acts.create);
108
+ api.action(acts.report);
109
+ api.action(acts.finish);
110
+ api.action(acts.fail);
111
+ taken = { ledger, acts };
112
+ }),
113
+ );
114
+ await niwa.serve();
115
+ try {
116
+ if (taken === undefined) throw new Error("the plugin did not run");
117
+ await run(taken, niwa, home.path);
118
+ } finally {
119
+ await niwa.close().catch(() => {});
120
+ await home.cleanup();
121
+ }
122
+ }
123
+
124
+ /** The operation id a record was written under: the record is `<operation>/emit/1`. */
125
+ const operationOf = (written: StoredRecord | undefined) => (written?.id ?? "").slice(0, -"/emit/1".length) as OperationId;
126
+
127
+ test("a call that was cut off is answered from the record it wrote: create, report, finish and fail", async () => {
128
+ await served(async ({ ledger, acts }, niwa, home) => {
129
+ const caller: Caller = { kind: "host" };
130
+ const asked = (operation: OperationId) => ({ operationId: operation, caller });
131
+ const input = { kind: "change", description: CONTRACT.description, text: CONTRACT.text, askedBy: ASKER, responsible: WORKER, reportTo: ASKER };
132
+ const worker = await connectAsOwner(home, "worker");
133
+ try {
134
+ const { id } = await niwa.call(taskCreate, input);
135
+ await worker.call(taskReport, { task: id, text: "half way" });
136
+ await worker.call(taskFinish, { task: id, result: "done" });
137
+
138
+ // The task has ended, so the same report made again would be refused; the one that was
139
+ // written stands, and the check says so.
140
+ const reported = operationOf((await niwa.records.read({ types: [TaskUpdated.name] }))[0]);
141
+ expect(await acts.report.check?.(reported, asked(reported))).toEqual({
142
+ status: "completed",
143
+ value: { task: id },
144
+ });
145
+ const made = operationOf(ledger.created(id));
146
+ expect(await acts.create.check?.(made, asked(made))).toEqual({ status: "completed", value: { id } });
147
+ const [end] = await niwa.records.read({ types: [TaskDone.name] });
148
+ const finished = operationOf(end);
149
+ expect(await acts.finish.check?.(finished, asked(finished))).toEqual({
150
+ status: "completed",
151
+ value: { task: id, outcome: { status: "result", result: "done" } },
152
+ });
153
+
154
+ const failing = (await niwa.call(taskCreate, input)).id;
155
+ await worker.call(taskFail, { task: failing, reason: "broke" });
156
+ const ends = await niwa.records.read({ types: [TaskDone.name] });
157
+ const failed = operationOf(ends[1]);
158
+ expect(await acts.fail.check?.(failed, asked(failed))).toEqual({
159
+ status: "completed",
160
+ value: { task: failing, outcome: { status: "failure", reason: "broke" } },
161
+ });
162
+
163
+ // An operation that wrote nothing is not known to have done anything, and one that wrote
164
+ // another kind of fact is not an answer to the question.
165
+ const none = "op-none" as OperationId;
166
+ expect(await acts.create.check?.(none, asked(none))).toEqual({ status: "unknown" });
167
+ expect(await acts.finish.check?.(made, asked(made))).toEqual({ status: "unknown" });
168
+ } finally {
169
+ await worker.close().catch(() => {});
170
+ }
171
+ });
172
+ }, 30_000);