@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.
package/src/index.ts ADDED
@@ -0,0 +1,516 @@
1
+ /**
2
+ * The tasks module: a task is a contract and nothing else.
3
+ *
4
+ * - **task.create** returns at once with the id niwa issues (`task-3fa9c2`); the Assignment goes to the
5
+ * responsible address. The creator gives a short description, and may declare the shape the result
6
+ * must have (`result`, a JSON Schema of an object).
7
+ * - **task.report** is what the responsible party says while the work goes on.
8
+ * - **task.finish** ends the task with its result, **task.fail** ends it as failed, with the reason.
9
+ * A task ends once: the first end stands. A result that does not fit the declared schema is
10
+ * refused, and the task stays open.
11
+ * - **task.result** gives the result, and waits for it when the task is not done yet.
12
+ * - **task.list** and **task.get** show the tasks; **task.assigned** shows the caller the open tasks
13
+ * it is responsible for, with the result schema of the ones that declared one.
14
+ *
15
+ * Where a task says to report, that is where the updates and the end go: the Update on every
16
+ * report, the Result or the Failure when the task is done. Both go from the responsible party
17
+ * to the address of the contract.
18
+ *
19
+ * The state of a task is folded from the journal (`owner.ts`, `ledger.ts`). The actions are values: a
20
+ * responsible party holds the one it needs and calls it as a step of its own invocation.
21
+ *
22
+ * Who asks is who the caller is: a client asks as the address it is bound to, and only the host
23
+ * and the handlers of plugins, which stand for nobody, may ask in another's name.
24
+ */
25
+
26
+ import { z } from "zod";
27
+
28
+ import { ARTIFACT_THRESHOLD, IdIndex, RECORD_DATA_LIMIT, action } from "@niwa-labs/core";
29
+ import type { Action, ActionContext, Address, ArtifactStore, Caller, CheckResult, JournalReader, Seq, Step, StoredRecord } from "@niwa-labs/core";
30
+ import { bindingOf, COCKPIT_MODULE, plugin } from "@niwa-labs/plugin";
31
+ import { fileURLToPath } from "node:url";
32
+ import type { CallerBinding, MessagesOptions, Plugin } from "@niwa-labs/plugin";
33
+ import { MessageSent, birthOf, issuedIds, messageSendRef } from "@niwa-labs/messages/records";
34
+ import type { MessageBody } from "@niwa-labs/messages/records";
35
+
36
+ import { taskLedger } from "./ledger.ts";
37
+ import type { TaskLedger } from "./ledger.ts";
38
+ import { TaskRefusal, decide, sameAddress } from "./owner.ts";
39
+ import type { TaskState } from "./owner.ts";
40
+ import {
41
+ CreateInput,
42
+ FailInput,
43
+ FinishInput,
44
+ OutcomeOutput,
45
+ ReportInput,
46
+ taskAssigned,
47
+ taskCreate,
48
+ taskFail,
49
+ taskFinish,
50
+ taskGet,
51
+ taskList,
52
+ taskReport,
53
+ taskResult as taskResultRef,
54
+ } from "./actions.ts";
55
+ import type { TaskEntity } from "./actions.ts";
56
+ import { TaskContract, TaskCreated, TaskDone, TaskId, TaskOutcome, TaskUpdated } from "./records.ts";
57
+ import { ExecutorAssignment, executorHandler } from "./executor.ts";
58
+
59
+ /** The ids of tasks: a task is born in the record that creates it. */
60
+ export function taskIds(journal: () => JournalReader | undefined): IdIndex<"task"> {
61
+ return new IdIndex("task", () => issuedIds(journal(), [TaskCreated], (contract) => contract.id));
62
+ }
63
+
64
+ /** The actions that write facts about a task. */
65
+ export interface TaskActions {
66
+ readonly create: Action<z.infer<typeof CreateInput>, { id: TaskId }, z.input<typeof CreateInput>>;
67
+ readonly report: Action<z.infer<typeof ReportInput>, { task: TaskId }, z.input<typeof ReportInput>>;
68
+ readonly finish: Action<
69
+ z.infer<typeof FinishInput>,
70
+ z.infer<typeof OutcomeOutput>,
71
+ z.input<typeof FinishInput>
72
+ >;
73
+ readonly fail: Action<z.infer<typeof FailInput>, z.infer<typeof OutcomeOutput>, z.input<typeof FailInput>>;
74
+ }
75
+
76
+ /** What the plugin is given. */
77
+ export interface TasksOptions {
78
+ /** The binding says what address a caller speaks as: the same one the messages module uses. */
79
+ readonly messages?: MessagesOptions;
80
+ }
81
+
82
+ /** The tasks module. */
83
+ export function tasks(opts: TasksOptions = {}): Plugin {
84
+ const bind = bindingOf(opts.messages);
85
+ const waiters = new TaskWaiters();
86
+
87
+ return plugin("tasks", (api) => {
88
+ // The page of this plugin in the cockpit: a client module, offered by the path of its source.
89
+ api.offer(COCKPIT_MODULE, { id: "tasks", entry: fileURLToPath(new URL("./cockpit/index.tsx", import.meta.url)) });
90
+ const journal = () => api.journal?.();
91
+ const ledger = taskLedger(journal);
92
+ const ids = taskIds(journal);
93
+ const written = taskActions(ledger, ids, bind);
94
+ const result = taskResultAction(ledger, waiters);
95
+ const reads = taskReads(ledger, ids, bind);
96
+
97
+ api.declare(TaskCreated, TaskUpdated, TaskDone);
98
+
99
+ api.action(written.create);
100
+ api.action(written.report);
101
+ api.action(written.finish);
102
+ api.action(written.fail);
103
+ api.action(result);
104
+ api.action(reads.list);
105
+ api.action(reads.get);
106
+ api.action(reads.assigned);
107
+
108
+ // Hand the work over: the Assignment goes to the responsible address, on behalf of the asker.
109
+ // It carries the result schema the task declared, so whoever does the work is shown it.
110
+ api.on(TaskCreated, async (data, step) => {
111
+ await step(messageSendRef, {
112
+ from: data.askedBy,
113
+ to: data.responsible,
114
+ task: data.id,
115
+ body: {
116
+ type: "assignment",
117
+ text: data.text,
118
+ kind: data.kind,
119
+ ...(data.result === undefined ? {} : { result: data.result }),
120
+ },
121
+ });
122
+ });
123
+
124
+ // An assignment for an executor is work to do: the executor starts a session, asks it for
125
+ // the result and ends the task with what the session said.
126
+ // Each task is worked on by its own session, for as long as it takes.
127
+ api.on(ExecutorAssignment, { concurrency: Number.POSITIVE_INFINITY }, executorHandler(ledger, api.authorize));
128
+
129
+ // The updates go where the task says to report: from the responsible party to that address.
130
+ api.on(TaskUpdated, async (data, step) => {
131
+ const contract = ledger.state(data.task)?.contract;
132
+ if (contract === undefined) return;
133
+ await step(messageSendRef, {
134
+ from: contract.responsible,
135
+ to: contract.reportTo,
136
+ task: data.task,
137
+ body: {
138
+ type: "update",
139
+ text: data.text,
140
+ ...(data.data === undefined ? {} : { data: data.data }),
141
+ },
142
+ });
143
+ });
144
+
145
+ // The end of the task goes there too: the Result, or the Failure, after the updates written
146
+ // before it. The outcomes of two tasks owe each other nothing, so one that waits for its
147
+ // updates holds no other.
148
+ api.on(
149
+ TaskDone,
150
+ { id: "task.done.report", concurrency: Number.POSITIVE_INFINITY, requires: [MessageSent] },
151
+ async (data, step, record) => {
152
+ const contract = ledger.state(data.task)?.contract;
153
+ if (contract === undefined) return;
154
+ await updatesDelivered(ledger, step, data.task, record.seq);
155
+ await step(messageSendRef, {
156
+ from: contract.responsible,
157
+ to: contract.reportTo,
158
+ task: data.task,
159
+ body: outcomeBody(data.outcome, api.artifacts),
160
+ });
161
+ },
162
+ );
163
+
164
+ // Wake the callers waiting for the result: they read it from the journal.
165
+ api.on(
166
+ TaskDone,
167
+ { id: "task.done.wake" },
168
+ async (data) => {
169
+ waiters.wake(data.task);
170
+ },
171
+ );
172
+ });
173
+ }
174
+
175
+ /**
176
+ * Wait until the updates written before the end of a task have been sent, so the addressee never
177
+ * reads a progress report after the result.
178
+ *
179
+ * Each update is sent by a handler of its own, which may be late. Whatever is not sent yet is sent
180
+ * after the end was written, so the wait starts at the end: a message sent while this looks is not
181
+ * missed, and each message that arrives takes the wait one step on.
182
+ */
183
+ async function updatesDelivered(ledger: TaskLedger, step: Step, task: TaskId, end: Seq): Promise<void> {
184
+ const pending = () => {
185
+ const delivered = ledger.deliveredUpdates(task);
186
+ return ledger.updates(task).some((update) => update.seq < end && !delivered.has(update.id));
187
+ };
188
+ let from = end;
189
+ for (let round = 1; pending(); round += 1) {
190
+ const arrived = await step.wait(MessageSent, { key: `updates-${String(round)}`, from, filter: { task, "body.type": "update" } });
191
+ from = arrived.at;
192
+ }
193
+ }
194
+
195
+ /** The callers that wait for the end of a task in this process, by task. */
196
+ export class TaskWaiters {
197
+ readonly #by = new Map<string, Set<() => void>>();
198
+
199
+ /** Watch for the end of a task. Watching starts before the state is read, so no end is missed. */
200
+ watch(task: string): { woken: Promise<void>; stop(): void } {
201
+ let wake = () => {};
202
+ const woken = new Promise<void>((resolve) => (wake = resolve));
203
+ const set = this.#by.get(task) ?? new Set();
204
+ set.add(wake);
205
+ this.#by.set(task, set);
206
+ return {
207
+ woken,
208
+ stop: () => {
209
+ set.delete(wake);
210
+ if (set.size === 0 && this.#by.get(task) === set) this.#by.delete(task);
211
+ },
212
+ };
213
+ }
214
+
215
+ /** The task ended: wake whoever waits for it. */
216
+ wake(task: string): void {
217
+ const wakes = this.#by.get(task);
218
+ this.#by.delete(task);
219
+ for (const wake of wakes ?? []) wake();
220
+ }
221
+
222
+ /** How many tasks have a caller waiting. */
223
+ get size(): number {
224
+ return this.#by.size;
225
+ }
226
+ }
227
+
228
+ /** The actions that write facts, made from the ledger and the binding of callers to addresses. */
229
+ export function taskActions(ledger: TaskLedger, ids: IdIndex<"task">, bind: CallerBinding): TaskActions {
230
+ /** The address the caller speaks as; a caller that is bound to none speaks for nobody. */
231
+ const speaksAs = (caller: Caller): Address => {
232
+ const address = bind(caller);
233
+ if (address === undefined) {
234
+ throw new TaskRefusal("unbound", "the caller is not bound to an address, so it speaks for no task");
235
+ }
236
+ return address;
237
+ };
238
+
239
+ /**
240
+ * Who asks for the work: the address the caller is bound to, and a payload that names another is
241
+ * refused. The host and the handlers of plugins stand for nobody and may ask in another's name;
242
+ * a client the binding does not know may not choose an address.
243
+ */
244
+ const askedBy = (caller: Caller, given: Address): Address => {
245
+ const bound = bind(caller);
246
+ if (bound === undefined) {
247
+ if (caller.kind === "client") {
248
+ throw new TaskRefusal("unbound", "the caller is not bound to an address, so it cannot ask for a task");
249
+ }
250
+ return given;
251
+ }
252
+ if (!sameAddress(bound, given)) {
253
+ throw new TaskRefusal("not-asker", "a task is asked for by the address the caller speaks as, not by one the input names");
254
+ }
255
+ return bound;
256
+ };
257
+
258
+ /** What a call that was cut off did, read from the record it wrote first. */
259
+ const recorded = <T>(operation: string, read: (stored: StoredRecord) => T | undefined): CheckResult<T> => {
260
+ const stored = ledger.written(operation);
261
+ const value = stored === undefined ? undefined : read(stored);
262
+ return value === undefined ? { status: "unknown" } : { status: "completed", value };
263
+ };
264
+
265
+ const create = action(taskCreate, {
266
+ // A task is made once: a create that was cut off may have made the task, and a second
267
+ // create of the same task is refused. So the call is not made again; the record the call
268
+ // wrote says whether it was made.
269
+ recovery: "do-not-repeat",
270
+ effect: "record",
271
+ world: "niwa",
272
+ async run(input, ctx) {
273
+ const contract: TaskContract = { ...input, askedBy: askedBy(ctx.caller, input.askedBy), id: ids.issue(birthOf(ctx)) };
274
+ decide(ledger.state(contract.id), { kind: "create", contract });
275
+ await ctx.emit(TaskCreated, { ...contract, ...(ctx.caller.kind === "client" ? { initiator: ctx.caller.principal } : {}) });
276
+ return { id: contract.id };
277
+ },
278
+ async check(operation) {
279
+ return recorded(operation, (stored) => {
280
+ const created = TaskCreated.schema.safeParse(stored.data);
281
+ return created.success ? { id: created.data.id } : undefined;
282
+ });
283
+ },
284
+ });
285
+
286
+ const report = action(taskReport, {
287
+ // A report is a fact written on the task: the same report may be written again, so
288
+ // it may be made again. One that was written before the task ended stands after it.
289
+ recovery: "repeat",
290
+ effect: "record",
291
+ world: "niwa",
292
+ async run(input, ctx) {
293
+ decide(ledger.state(input.task), {
294
+ kind: "report",
295
+ task: input.task,
296
+ by: speaksAs(ctx.caller),
297
+ });
298
+ await ctx.emit(TaskUpdated, input);
299
+ return { task: input.task };
300
+ },
301
+ async check(operation) {
302
+ return recorded(operation, (stored) => {
303
+ const updated = TaskUpdated.schema.safeParse(stored.data);
304
+ return updated.success ? { task: updated.data.task } : undefined;
305
+ });
306
+ },
307
+ });
308
+
309
+ /** End a task with an outcome: the fact is written once, and the first end stands. */
310
+ const end = async (
311
+ ctx: ActionContext,
312
+ task: TaskId,
313
+ outcome: TaskOutcome,
314
+ ): Promise<z.infer<typeof OutcomeOutput>> => {
315
+ decide(ledger.state(task), { kind: "finish", task, by: speaksAs(ctx.caller), outcome });
316
+ await ctx.emit(TaskDone, { task, outcome });
317
+ return { task, outcome };
318
+ };
319
+
320
+ /** What a call that ended a task and was cut off did: the end it wrote. */
321
+ const ended = (operation: string): CheckResult<z.infer<typeof OutcomeOutput>> =>
322
+ recorded(operation, (stored) => {
323
+ const done = TaskDone.schema.safeParse(stored.data);
324
+ return done.success ? { task: done.data.task, outcome: done.data.outcome } : undefined;
325
+ });
326
+
327
+ const finish = action(taskFinish, {
328
+ // A task ends once: an end that was cut off may have written it, so it is not
329
+ // made again; the record the call wrote says whether it was.
330
+ recovery: "do-not-repeat",
331
+ effect: "record",
332
+ world: "niwa",
333
+ run: (input, ctx) => end(ctx, input.task, { status: "result", result: input.result }),
334
+ check: async (operation) => ended(operation),
335
+ });
336
+
337
+ const fail = action(taskFail, {
338
+ // The same as finish: the end may have been written.
339
+ recovery: "do-not-repeat",
340
+ effect: "record",
341
+ world: "niwa",
342
+ run: (input, ctx) => end(ctx, input.task, { status: "failure", reason: input.reason }),
343
+ check: async (operation) => ended(operation),
344
+ });
345
+
346
+ return { create, report, finish, fail };
347
+ }
348
+
349
+ /** What a task is, as `task.get` shows it. */
350
+ function entityOf(state: TaskState): TaskEntity {
351
+ return { ...state.contract, status: state.status, ...(state.status === "done" ? { outcome: state.outcome } : {}) };
352
+ }
353
+
354
+ /** The actions that read tasks: the list, one task, and the open tasks of the caller. */
355
+ function taskReads(ledger: TaskLedger, ids: IdIndex<"task">, bind: CallerBinding) {
356
+ const list = action(taskList, {
357
+ recovery: "repeat",
358
+ effect: "read",
359
+ world: "niwa",
360
+ run: async (input) => ({
361
+ items: [...ledger.states().values()]
362
+ .filter((state) => input.status === undefined || state.status === input.status)
363
+ .map((state) => ({
364
+ id: state.contract.id,
365
+ description: state.contract.description,
366
+ status: state.status,
367
+ kind: state.contract.kind,
368
+ responsible: state.contract.responsible,
369
+ })),
370
+ }),
371
+ });
372
+
373
+ const get = action(taskGet, {
374
+ recovery: "repeat",
375
+ effect: "read",
376
+ world: "niwa",
377
+ run: async (input) => {
378
+ const id = ids.require(input.id);
379
+ const state = ledger.state(id);
380
+ if (state === undefined) throw new TaskRefusal("unknown", `the task "${id}" does not exist`);
381
+ return entityOf(state);
382
+ },
383
+ });
384
+
385
+ const assigned = action(taskAssigned, {
386
+ recovery: "repeat",
387
+ effect: "read",
388
+ world: "niwa",
389
+ run: async (_input, ctx) => {
390
+ const me = bind(ctx.caller);
391
+ if (me === undefined) return { tasks: [] };
392
+ return {
393
+ tasks: [...ledger.states().values()].flatMap((state) =>
394
+ state.status === "open" && sameAddress(state.contract.responsible, me)
395
+ ? [
396
+ {
397
+ task: state.contract.id,
398
+ description: state.contract.description,
399
+ ...(state.contract.result === undefined ? {} : { result: state.contract.result }),
400
+ },
401
+ ]
402
+ : [],
403
+ ),
404
+ };
405
+ },
406
+ });
407
+
408
+ return { list, get, assigned };
409
+ }
410
+
411
+ /**
412
+ * The action that gives the result of a task, and waits for it when the task is not done.
413
+ *
414
+ * Inside an invocation the wait is the invocation's own: it is waiting for the end of the task, it
415
+ * holds nothing in memory and it survives a restart. It looks from the creation of the task, so an
416
+ * end written between the read and the wait is not missed. A direct call has no invocation to
417
+ * suspend: it blocks in this process until the end is written.
418
+ */
419
+ export function taskResultAction(ledger: TaskLedger, waiters: TaskWaiters) {
420
+ return action(taskResultRef, {
421
+ // The result is read from the journal: it may be asked again.
422
+ recovery: "repeat",
423
+ effect: "read",
424
+ world: "niwa",
425
+ async run(input, ctx) {
426
+ for (;;) {
427
+ const watch = ctx.invocation === undefined ? waiters.watch(input.task) : undefined;
428
+ try {
429
+ const state = ledger.state(input.task);
430
+ if (state === undefined) {
431
+ throw new TaskRefusal("unknown", `the task "${input.task}" does not exist`);
432
+ }
433
+ if (state.status === "done") return { task: input.task, outcome: state.outcome };
434
+ if (watch === undefined) {
435
+ const created = ledger.created(input.task);
436
+ await ctx.wait(TaskDone, { filter: { task: input.task }, ...(created === undefined ? {} : { from: created.seq }) });
437
+ } else {
438
+ await watch.woken;
439
+ }
440
+ } finally {
441
+ watch?.stop();
442
+ }
443
+ }
444
+ },
445
+ });
446
+ }
447
+
448
+ /**
449
+ * The body of the message that says how the task ended: the Result, or the Failure.
450
+ *
451
+ * The text says what came of it, so a reader that only unfolds the envelope knows how the work
452
+ * went; the result and the reason are carried along as they are. What is too large for a message
453
+ * is kept as an artifact: the message says so and points at it, and `task.result` still gives the
454
+ * whole of it.
455
+ */
456
+ function outcomeBody(outcome: TaskOutcome, artifacts: ArtifactStore): MessageBody {
457
+ if (outcome.status === "failure") {
458
+ if (Buffer.byteLength(outcome.reason) <= ARTIFACT_THRESHOLD) {
459
+ return { type: "failure", text: outcome.reason, reason: outcome.reason };
460
+ }
461
+ const kept = artifacts.put(outcome.reason, "text/plain");
462
+ const start = `${outcome.reason.slice(0, PREVIEW_CHARS)}…`;
463
+ return { type: "failure", text: start, reason: start, data: { artifact: kept } };
464
+ }
465
+ const text = textOf(outcome.result);
466
+ if (Buffer.byteLength(text) <= ARTIFACT_THRESHOLD) {
467
+ return { type: "result", text, data: outcome.result };
468
+ }
469
+ const kept = artifacts.put(JSON.stringify(outcome.result), "application/json");
470
+ return {
471
+ type: "result",
472
+ text: `The result is ${String(kept.size)} bytes, too large to carry in a message: it is kept as an artifact, and task.result gives it whole. It begins: ${text.slice(0, PREVIEW_CHARS)}…`,
473
+ data: { artifact: kept },
474
+ };
475
+ }
476
+
477
+ /** How much of a text that is too large for a message the message still shows. */
478
+ const PREVIEW_CHARS = 1000;
479
+
480
+ /**
481
+ * The text of a result: what it is, as a reader sees it.
482
+ *
483
+ * A body always carries text, so a result that says nothing in words still says that the work
484
+ * is done.
485
+ */
486
+ function textOf(result: unknown): string {
487
+ if (typeof result === "string") return result.length === 0 ? "the task is done" : result;
488
+ if (result === undefined) return "the task is done";
489
+ try {
490
+ return JSON.stringify(result) ?? "the task is done";
491
+ } catch {
492
+ return "the task is done";
493
+ }
494
+ }
495
+
496
+ export {
497
+ CreateInput,
498
+ TaskEntity,
499
+ TaskStatus,
500
+ taskAssigned,
501
+ taskCreate,
502
+ taskFail,
503
+ taskFinish,
504
+ taskGet,
505
+ taskList,
506
+ taskReport,
507
+ taskResult,
508
+ } from "./actions.ts";
509
+ export { TaskCreated, TaskDone, TaskId, TaskUpdated, TASK_TYPES } from "./records.ts";
510
+ export type { TaskContract, TaskKind, TaskOutcome } from "./records.ts";
511
+ export { TaskRefusal, decide, fitsRecord, fold, sameAddress, stateOf } from "./owner.ts";
512
+ export type { Command, TaskRefusalCode, TaskState } from "./owner.ts";
513
+ export { taskLedger } from "./ledger.ts";
514
+ export type { TaskLedger } from "./ledger.ts";
515
+ export { ExecutorAssignment, executor, executorHandler } from "./executor.ts";
516
+ export type { Strategy, TaskAnswer } from "./strategy.ts";
package/src/ledger.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The ledger of tasks: what the journal says of them, read the way each question needs.
3
+ *
4
+ * A task is born in the record that creates it and ends in the record that ends it; an update
5
+ * changes neither. So the state of every task is folded from the creations and the ends, and the
6
+ * state of one task is read from its own two records, never from the journal as a whole.
7
+ */
8
+
9
+ import { recordId, seq } from "@niwa-labs/core";
10
+ import type { JournalReader, StoredRecord } from "@niwa-labs/core";
11
+ import { MessageSent } from "@niwa-labs/messages/records";
12
+
13
+ import { fold } from "./owner.ts";
14
+ import type { TaskState } from "./owner.ts";
15
+ import { TaskCreated, TaskDone, TaskUpdated } from "./records.ts";
16
+
17
+ /** What the journal says of the tasks. */
18
+ export interface TaskLedger {
19
+ /** The state of every task, folded from the records that create and end them. */
20
+ states(): Map<string, TaskState>;
21
+ /** The state of one task, from its own records. */
22
+ state(task: string): TaskState | undefined;
23
+ /** The record that created a task. */
24
+ created(task: string): StoredRecord | undefined;
25
+ /** The updates of a task, in the order they were written. */
26
+ updates(task: string): StoredRecord[];
27
+ /**
28
+ * The Assignment of a task: the first message of that kind the creation of the task caused. A
29
+ * message that only says it is the assignment of the task is not it.
30
+ */
31
+ assignment(task: string): StoredRecord | undefined;
32
+ /** The record a call wrote first under an operation id: what a call that was cut off may have done. */
33
+ written(operation: string): StoredRecord | undefined;
34
+ /** The ids of the records that the updates of a task caused to be sent, as messages. */
35
+ deliveredUpdates(task: string): Set<string>;
36
+ }
37
+
38
+ /** The ledger of the tasks in the journal of a plugin. */
39
+ export function taskLedger(journal: () => JournalReader | undefined): TaskLedger {
40
+ const createdIn = (reader: JournalReader, task: string): StoredRecord | undefined =>
41
+ reader
42
+ .find({ type: TaskCreated.name, field: "id", equals: task })
43
+ .find((stored) => TaskCreated.schema.safeParse(stored.data).success);
44
+
45
+ return {
46
+ states() {
47
+ const reader = journal();
48
+ if (reader === undefined) return new Map();
49
+ return fold(reader.since(seq(0), [TaskCreated.name, TaskDone.name]).map((stored) => stored.data));
50
+ },
51
+ state(task) {
52
+ const reader = journal();
53
+ if (reader === undefined) return undefined;
54
+ const created = createdIn(reader, task);
55
+ if (created === undefined) return undefined;
56
+ const ends = reader.find({ type: TaskDone.name, field: "task", equals: task });
57
+ return fold([created.data, ...ends.map((stored) => stored.data)]).get(task);
58
+ },
59
+ created(task) {
60
+ const reader = journal();
61
+ return reader === undefined ? undefined : createdIn(reader, task);
62
+ },
63
+ assignment(task) {
64
+ const reader = journal();
65
+ if (reader === undefined) return undefined;
66
+ const created = createdIn(reader, task);
67
+ if (created === undefined) return undefined;
68
+ return reader
69
+ .find({ type: MessageSent.name, field: "task", equals: task })
70
+ .find((stored) => stored.cause === created.id && MessageSent.schema.safeParse(stored.data).data?.body.type === "assignment");
71
+ },
72
+ written(operation) {
73
+ return journal()?.get(recordId(`${operation}/emit/1`));
74
+ },
75
+ deliveredUpdates(task) {
76
+ const delivered = new Set<string>();
77
+ for (const stored of journal()?.find({ type: MessageSent.name, field: "task", equals: task }) ?? []) {
78
+ if (stored.cause !== null && MessageSent.schema.safeParse(stored.data).data?.body.type === "update") delivered.add(stored.cause);
79
+ }
80
+ return delivered;
81
+ },
82
+ updates(task) {
83
+ return (journal()?.find({ type: TaskUpdated.name, field: "task", equals: task }) ?? []).filter(
84
+ (stored) => TaskUpdated.schema.safeParse(stored.data).success,
85
+ );
86
+ },
87
+ };
88
+ }