Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadLifecycle.ts

138 lines5.1 KB

1import type {
2 EnvironmentId,
3 OrchestrationV2ShellSnapshot,
4 OrchestrationV2ThreadShell,
5 ThreadId,
6} from "@t3tools/contracts";
7import * as DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import { Atom } from "effect/reactivity";
11​
12import type { AtomCommand } from "./runtime.ts";
13import {
14 type EnvironmentShellState,
15 type ShellCommandReceipt,
16 shellCommandHistoryInvalidated,
17} from "./shell.ts";
18​
19interface PendingThreadUpdate {
20 readonly threadId: ThreadId;
21 readonly apply: (thread: OrchestrationV2ThreadShell) => OrchestrationV2ThreadShell;
22 sequence?: number;
24​
25export function createOptimisticThreadLifecycle(
26 sourceSnapshotAtom: (
27 environmentId: EnvironmentId,
28 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>,
29 commandHistoryAtom: (
30 environmentId: EnvironmentId,
31 ) => Atom.Atom<EnvironmentShellState["commandHistory"]>,
32) {
33 const pendingAtom = Atom.family((_environmentId: EnvironmentId) =>
34 Atom.make<ReadonlyArray<PendingThreadUpdate>>([]).pipe(Atom.keepAlive),
35 );
36 const snapshotAtom = Atom.family((environmentId: EnvironmentId) =>
37 Atom.make((get) => {
38 const snapshot = get(sourceSnapshotAtom(environmentId));
39 const pending = get(pendingAtom(environmentId));
40 if (snapshot === null || pending.length === 0) return snapshot;
41 const byThread = new Map<ThreadId, PendingThreadUpdate[]>();
42 for (const update of pending) {
43 if (update.sequence !== undefined && update.sequence <= snapshot.snapshotSequence) continue;
44 const updates = byThread.get(update.threadId) ?? [];
45 updates.push(update);
46 byThread.set(update.threadId, updates);
47 }
48 if (byThread.size === 0) return snapshot;
49 return {
50 ...snapshot,
51 threads: snapshot.threads.map((thread) =>
52 (byThread.get(thread.id) ?? []).reduce(
53 (current, update) => update.apply(current),
54 thread,
55 ),
56 ),
57 };
58 }),
59 );
60​
61 // Until the durable snapshot catches up, an older pending update can still replace what shows.
62 const pendingThreadIdsAtom = Atom.family((environmentId: EnvironmentId) =>
63 Atom.make(
64 (get): ReadonlySet<ThreadId> =>
65 new Set(get(pendingAtom(environmentId)).map((update) => update.threadId)),
66 ),
67 );
68​
69 function wrap<Input extends { readonly threadId: ThreadId }, E>(
70 command: AtomCommand<
71 { readonly environmentId: EnvironmentId; readonly input: Input },
72 ShellCommandReceipt,
73 E
74 >,
75 apply: (
76 thread: OrchestrationV2ThreadShell,
77 input: Input,
78 now: DateTime.Utc,
79 accepted: boolean,
80 ) => OrchestrationV2ThreadShell,
81 ): AtomCommand<
82 { readonly environmentId: EnvironmentId; readonly input: Input },
83 ShellCommandReceipt["value"],
84 E
85 > {
86 return {
87 label: command.label,
88 run: (registry, target) =>
89 Effect.suspend(() => {
90 const now = DateTime.nowUnsafe();
91 const pending = pendingAtom(target.environmentId);
92 const source = sourceSnapshotAtom(target.environmentId);
93 const history = commandHistoryAtom(target.environmentId);
94 let latestSequence = registry.get(source)?.snapshotSequence ?? -Infinity;
95 const update: PendingThreadUpdate = {
96 threadId: target.input.threadId,
97 apply: (thread) => apply(thread, target.input, now, update.sequence !== undefined),
98 };
99 const remove = () =>
100 registry.update(pending, (current) => current.filter((item) => item !== update));
101 // Stays applied after the reply until a snapshot at or past its sequence replaces it,
102 // or the shell rewinds (a restored backup) past the event log the reply refers to.
103 const confirm = ({ value: { sequence }, dispatched }: ShellCommandReceipt) => {
104 update.sequence = sequence;
105 registry.update(pending, (current) => [...current]);
106 const reconcile = () => {
107 const snapshot = registry.get(source);
108 const currentHistory = registry.get(history);
109 if (
110 shellCommandHistoryInvalidated(dispatched, currentHistory) ||
111 snapshot === null ||
112 snapshot.snapshotSequence >= sequence ||
113 (currentHistory === undefined && snapshot.snapshotSequence < latestSequence)
114 ) {
115 remove();
116 unsubscribeSource();
117 unsubscribeHistory();
118 } else {
119 latestSequence = snapshot.snapshotSequence;
120 }
121 };
122 const unsubscribeSource = registry.subscribe(source, reconcile);
123 const unsubscribeHistory = registry.subscribe(history, reconcile);
124 reconcile();
125 };
126 registry.update(pending, (current) => [...current, update]);
127 return command.run(registry, target).pipe(
128 Effect.onExit((exit) =>
129 Effect.sync(() => (Exit.isSuccess(exit) ? confirm(exit.value) : remove())),
130 ),
131 Effect.map(({ value }) => value),
132 );
133 }),
134 };
135 }
136​
137 return { snapshotAtom, pendingThreadIdsAtom, wrap };