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

threadTriageOutbox.ts

308 lines12.4 KB

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