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

threadTriageOutbox.ts

326 lines13.5 KB

1import {
2 CommandId,
3 type EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ThreadFamily,
6 type OrchestrationV2ThreadShell,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as SecureRandom from "effect/crypto/SecureRandom";
14import * as Schema from "effect/Schema";
15import * as Semaphore from "effect/Semaphore";
16import { Atom, type AtomRegistry } from "effect/reactivity";
17​
18import {
19 type PendingThreadTriage,
20 type PendingThreadTriages,
21 ThreadTriageOutboxStore,
22} from "../platform/threadTriageOutboxStore.ts";
23import { EnvironmentRpcUnavailableError, isRpcClientError } from "../rpc/client.ts";
24import type { EnvironmentShellStatus, ShellCommandReceipt } from "./shell.ts";
25import { type AtomCommand, provideAtomRuntime } from "./runtime.ts";
26​
27type Target<I> = { readonly environmentId: EnvironmentId; readonly input: I };
28​
29const isUnavailable = Schema.is(EnvironmentRpcUnavailableError);
30​
31/** Failures that say nothing about whether the server would accept the change. */
32const isTransient = (cause: Cause.Cause<unknown>) =>
33 cause.reasons.some(
34 (reason) =>
35 Cause.isInterruptReason(reason) ||
36 (Cause.isFailReason(reason) &&
37 (isUnavailable(reason.error) || isRpcClientError(reason.error))),
38 );
39​
40/**
41 * What the user acted on: the thread's work and every triage decision with its time. A rename,
42 * tag change or visit is left out, so it does not drop the queued change.
43 */
44function seenState(thread: OrchestrationV2ThreadShell) {
45 return JSON.stringify([
46 thread.latestRunId,
47 thread.status,
48 thread.itemCount,
49 thread.pendingRuntimeRequest?.id ?? null,
50 thread.settledOverride,
51 ...[
52 thread.settledAt,
53 thread.unsettledAt,
54 thread.snoozedUntil,
55 thread.snoozedAt,
56 thread.pinnedAt,
57 ].map((time) => (time == null ? null : DateTime.toEpochMillis(time))),
58 ]);
60​
61const sameEntries = (a: PendingThreadTriages, b: PendingThreadTriages) =>
62 a.length === b.length && a.every((entry, index) => entry.commandId === b[index]!.commandId);
63​
64/**
65 * Settle and snooze for an environment that is not connected: the change is stored on the
66 * device, shown at once, and sent when the environment's shell is synchronized again.
67 */
68export function createThreadTriageOutbox<R, E, SendError, RE>(input: {
69 readonly runtime: Atom.AtomRuntime<SecureRandom.SecureRandom | R, E>;
70 readonly sourceSnapshotAtom: (
71 environmentId: EnvironmentId,
72 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
73 readonly shellStatusAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellStatus>;
74 /** Returns the thread itself when the action cannot apply to it. */
75 readonly apply: (
76 thread: OrchestrationV2ThreadShell,
77 action: PendingThreadTriage["action"],
78 queuedAt: DateTime.Utc,
79 ) => OrchestrationV2ThreadShell;
80 /** Sends the action under its command id, which the server answers only once. */
81 readonly send: (
82 registry: AtomRegistry.AtomRegistry,
83 entry: PendingThreadTriage,
84 ) => Effect.Effect<unknown, SendError>;
85 readonly readFamily: AtomCommand<Target<{ threadId: ThreadId }>, OrchestrationV2ThreadFamily, RE>;
86}) {
87 const entriesAtom = Atom.make<PendingThreadTriages>([]).pipe(Atom.keepAlive);
88 // Storage is shared with other tabs, so memory takes each result in the order storage gave it.
89 const order = Semaphore.makeUnsafe(1);
90 const update = Effect.fn("ThreadTriageOutbox.update")(function* (
91 registry: AtomRegistry.AtomRegistry,
92 change: (stored: PendingThreadTriages) => PendingThreadTriages,
93 ) {
94 const store = yield* ThreadTriageOutboxStore;
95 return yield* store.update(change).pipe(
96 Effect.tap((entries) =>
97 Effect.sync(() => {
98 if (!sameEntries(registry.get(entriesAtom), entries)) {
99 registry.set(entriesAtom, entries);
100 }
101 }),
102 ),
103 order.withPermit,
104 );
105 });
106 const read = (registry: AtomRegistry.AtomRegistry) => update(registry, (stored) => stored);
107​
108 const pendingFor = (
109 registry: AtomRegistry.AtomRegistry,
110 environmentId: EnvironmentId,
111 threadId: ThreadId,
112 ) =>
113 registry
114 .get(entriesAtom)
115 .find((entry) => entry.environmentId === environmentId && entry.threadId === threadId);
116 /** Never fails: a change that stays stored is judged again on the next synchronized shell. */
117 const forget = (registry: AtomRegistry.AtomRegistry, commandId: CommandId | undefined) =>
118 commandId === undefined
119 ? Effect.void
120 : update(registry, (stored) =>
121 stored.some((entry) => entry.commandId === commandId)
122 ? stored.filter((entry) => entry.commandId !== commandId)
123 : stored,
124 ).pipe(provideAtomRuntime(registry, input.runtime), Effect.ignore);
125​
126 // The live shell is the server's state: it wins over a change made against an older one.
127 const replay = Effect.fn("ThreadTriageOutbox.replay")(function* (
128 registry: AtomRegistry.AtomRegistry,
129 environmentId: EnvironmentId,
130 ) {
131 for (const entry of yield* read(registry)) {
132 if (entry.environmentId !== environmentId) continue;
133 const find = (rows: OrchestrationV2ThreadFamily | null) =>
134 rows?.threads.find((candidate) => candidate.id === entry.threadId);
135 const shell = () => registry.get(input.sourceSnapshotAtom(environmentId));
136 const target = { environmentId, input: { threadId: entry.threadId } };
137 const family =
138 find(shell()) === undefined && shell()?.olderSettled !== undefined
139 ? yield* Effect.exit(input.readFamily.run(registry, target))
140 : undefined;
141 if (family?._tag === "Failure") continue;
142 // Read again: this or another tab may have cancelled or replaced it while an earlier
143 // change was being sent.
144 const stored = yield* read(registry);
145 if (!stored.some((current) => current.commandId === entry.commandId)) continue;
146 // A shell past the host's read may have changed or removed the row: replay with a new read.
147 if (family && (shell()?.snapshotSequence ?? 0) > family.value.snapshotSequence)
148 return void registry.refresh(syncAtom(environmentId));
149 // The shell may have trimmed the row while storage was read; the host may still have it.
150 if (!family && find(shell()) === undefined && shell()?.olderSettled !== undefined)
151 return void registry.refresh(syncAtom(environmentId));
152 const thread = find(family?.value ?? shell());
153 if (
154 thread !== undefined &&
155 seenState(thread) === entry.seen &&
156 input.apply(thread, entry.action, DateTime.nowUnsafe()) !== thread
157 ) {
158 const sent = yield* Effect.exit(input.send(registry, entry));
159 if (Exit.isFailure(sent) && isTransient(sent.cause)) continue;
160 }
161 yield* forget(registry, entry.commandId);
162 }
163 });
164 // Rebuilt on each shell status, which stops a replay when the shell is no longer synchronized
165 // and so keeps one replay per environment. Any other status only loads what is stored.
166 const syncAtom = Atom.family((environmentId: EnvironmentId) =>
167 input.runtime.atom((get) =>
168 get(input.shellStatusAtom(environmentId)) === "live"
169 ? replay(get.registry, environmentId)
170 : Effect.asVoid(read(get.registry)),
171 ),
172 );
173 const environmentEntriesAtom = Atom.family((environmentId: EnvironmentId) =>
174 Atom.make((get) => {
175 get.mount(syncAtom(environmentId));
176 return get(entriesAtom).filter((entry) => entry.environmentId === environmentId);
177 }),
178 );
179​
180 const snapshotAtom = Atom.family((environmentId: EnvironmentId) =>
181 Atom.make((get) => {
182 const snapshot = get(input.sourceSnapshotAtom(environmentId));
183 const entries = get(environmentEntriesAtom(environmentId));
184 if (snapshot === null || entries.length === 0) return snapshot;
185 const byThread = new Map(entries.map((entry) => [entry.threadId, entry]));
186 return {
187 ...snapshot,
188 threads: snapshot.threads.map((thread) => {
189 const entry = byThread.get(thread.id);
190 return entry === undefined ? thread : input.apply(thread, entry.action, entry.queuedAt);
191 }),
192 };
193 }),
194 );
195​
196 const pendingSyncAtom = Atom.family((environmentId: EnvironmentId) =>
197 Atom.make(
198 (get): ReadonlySet<ThreadId> =>
199 new Set(get(environmentEntriesAtom(environmentId)).map((entry) => entry.threadId)),
200 ),
201 );
202​
203 const queue = Effect.fn("ThreadTriageOutbox.queue")(function* (
204 registry: AtomRegistry.AtomRegistry,
205 environmentId: EnvironmentId,
206 thread: OrchestrationV2ThreadShell,
207 action: PendingThreadTriage["action"],
208 queuedAt: DateTime.Utc,
209 ) {
210 const random = yield* SecureRandom.SecureRandom;
211 const commandId = CommandId.make(yield* random.uuidV4());
212 const stored = yield* update(registry, (current) => {
213 const sameThread = (entry: PendingThreadTriage) =>
214 entry.environmentId === environmentId && entry.threadId === thread.id;
215 // One change per thread. A snooze cannot replace a settle, which online it keeps.
216 return action.type === "snooze" && current.find(sameThread)?.action.type === "settle"
217 ? current
218 : [
219 ...current.filter((entry) => !sameThread(entry)),
220 {
221 environmentId,
222 threadId: thread.id,
223 commandId,
224 action,
225 queuedAt,
226 seen: seenState(thread),
227 },
228 ];
229 });
230 return stored.some((entry) => entry.commandId === commandId);
231 });
232​
233 /** Queues the action on the device when its environment is not connected. */
234 function queueWhenOffline<I extends { readonly threadId: ThreadId }, CE>(
235 command: AtomCommand<Target<I>, ShellCommandReceipt, CE>,
236 toAction: (input: I) => PendingThreadTriage["action"],
237 ): typeof command {
238 return {
239 label: command.label,
240 run: (registry, target) =>
241 Effect.suspend(() => {
242 const { environmentId } = target;
243 const { threadId } = target.input;
244 // Read before sending: the change is judged against what the user saw when acting.
245 const snapshot = registry.get(input.sourceSnapshotAtom(environmentId));
246 const thread = snapshot?.threads.find((candidate) => candidate.id === threadId);
247 return command.run(registry, target).pipe(
248 // The server now has a newer decision than the queued one.
249 Effect.tap(() =>
250 forget(registry, pendingFor(registry, environmentId, threadId)?.commandId),
251 ),
252 Effect.catchIf(isUnavailable, (unavailable) => {
253 const action = toAction(target.input);
254 const queuedAt = DateTime.nowUnsafe();
255 if (
256 snapshot == null ||
257 thread === undefined ||
258 input.apply(thread, action, queuedAt) === thread
259 ) {
260 return Effect.fail(unavailable);
261 }
262 return queue(registry, environmentId, thread, action, queuedAt).pipe(
263 provideAtomRuntime(registry, input.runtime),
264 Effect.exit,
265 Effect.flatMap((queued) =>
266 Exit.isSuccess(queued) && queued.value
267 ? Effect.succeed({
268 value: { sequence: snapshot.snapshotSequence },
269 dispatched: undefined,
270 })
271 : Effect.fail(unavailable),
272 ),
273 );
274 }),
275 );
276 }),
277 };
278 }
279​
280 /**
281 * Undo of a queued change removes it from storage first, so a replay that has not reached it
282 * skips it; storage decides, so the change removed is the one stored now, also by another tab.
283 * Offline that is the whole undo, reported as `cancelledOnDevice`. While the shell is
284 * synchronized the environment is asked too, after any send already in its lane.
285 */
286 function cancelQueued<I extends { readonly threadId: ThreadId }, CE>(
287 command: AtomCommand<Target<I>, { readonly sequence: number }, CE>,
288 cancels: PendingThreadTriage["action"]["type"],
289 ) {
290 const cancelled = { sequence: 0, cancelledOnDevice: true } as const;
291 return {
292 label: command.label,
293 run: (registry: AtomRegistry.AtomRegistry, target: Target<I>) =>
294 Effect.suspend(() => {
295 const { environmentId } = target;
296 const { threadId } = target.input;
297 const live = registry.get(input.shellStatusAtom(environmentId)) === "live";
298 let removed = false;
299 const remove = update(registry, (stored) => {
300 const kept = stored.filter(
301 (entry) =>
302 entry.environmentId !== environmentId ||
303 entry.threadId !== threadId ||
304 entry.action.type !== cancels,
305 );
306 removed = kept.length !== stored.length;
307 return removed ? kept : stored;
308 }).pipe(provideAtomRuntime(registry, input.runtime));
309 const sent = command.run(registry, target).pipe(
310 Effect.tap(() =>
311 forget(registry, pendingFor(registry, environmentId, threadId)?.commandId),
312 ),
313 // The connection dropped before the shell noticed, so nothing was sent.
314 Effect.catchIf(isUnavailable, (unavailable) =>
315 removed ? Effect.succeed(cancelled) : Effect.fail(unavailable),
316 ),
317 );
318 return remove.pipe(
319 Effect.flatMap(() => (removed && !live ? Effect.succeed(cancelled) : sent)),
320 );
321 }),
322 };
323 }
324​
325 return { snapshotAtom, pendingSyncAtom, queueWhenOffline, cancelQueued };