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

queuedRunEdit.ts

206 lines7.1 KB

1/**
2 * A queued-message edit ends on save, cancel, or when its run leaves the queue.
3 * The store owns one watcher per edit, so "run left the queue" is handled exactly
4 * once, when the projection reports it, wherever the user is in the app. It also
5 * owns the edit's save, because a save outlives the view that started it.
6 */
7import type { RunId } from "@t3tools/contracts";
8import { Atom, type AtomRegistry } from "effect/reactivity";
9​
10export interface QueuedRunStatus {
11 readonly id: RunId;
12 readonly status: string;
14​
15/** The thread's runs, or null while they are unknown (detail not loaded yet). */
16export type QueuedRunsAtom = Atom.Atom<ReadonlyArray<QueuedRunStatus> | null>;
17​
18interface ShellThreadPresence {
19 readonly id: string;
20 readonly deletedAt: unknown;
22​
23/**
24 * The edited thread's runs. A deleted thread (shell `deletedAt` or detail status
25 * `deleted`) reads as no runs, so its edit ends. Absence from the shell is not
26 * deletion: archived threads are dropped there but keep an editable queue, so
27 * everything else reads the detail's runs, unknown until it loads.
28 */
29export function makeQueuedRunsAtom(input: {
30 readonly threadId: string;
31 readonly snapshot: Atom.Atom<{ readonly threads: ReadonlyArray<ShellThreadPresence> } | null>;
32 readonly detailStatus: Atom.Atom<string>;
33 readonly runs: Atom.Atom<ReadonlyArray<QueuedRunStatus> | null>;
34}): QueuedRunsAtom {
35 return Atom.make((get) => {
36 const shellThread = get(input.snapshot)?.threads.find(
37 (candidate) => candidate.id === input.threadId,
38 );
39 if (shellThread !== undefined && shellThread.deletedAt !== null) return [];
40 if (get(input.detailStatus) === "deleted") return [];
41 return get(input.runs);
42 });
44​
45function runLeftQueue(runs: ReadonlyArray<QueuedRunStatus> | null, runId: RunId): boolean {
46 if (runs === null) return false;
47 return !runs.some((run) => run.id === runId && run.status === "queued");
49​
50/**
51 * What happens to an open edit when its run leaves the queue: an unchanged
52 * edit just closes; a changed one moves into the thread's own draft when that
53 * draft is empty, and is dropped otherwise so it never overwrites the user's
54 * other work.
55 */
56export function resolveQueuedEditExit(input: {
57 readonly editChanged: boolean;
58 readonly threadDraftEmpty: boolean;
59}): "kept" | "discarded" | "clean" {
60 if (!input.editChanged) return "clean";
61 return input.threadDraftEmpty ? "kept" : "discarded";
63​
64interface ExitWatch<E> {
65 readonly runs: QueuedRunsAtom;
66 readonly runId: RunId;
67 readonly onRunLeftQueue: (threadKey: string, edit: E) => void;
68 cancel: (() => void) | null;
70​
71/**
72 * Settles a save started with `startSave`. Returns false, changing nothing,
73 * when the edit the save started from was ended or begun again meanwhile; the
74 * caller must then leave the edit's drafts alone. Otherwise success ends the
75 * edit and failure resumes its exit watch.
76 */
77export type FinishQueuedRunEditSave = (succeeded: boolean) => boolean;
78​
79export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(options: {
80 readonly registry: AtomRegistry.AtomRegistry;
81 readonly label: string;
82}) {
83 const { registry } = options;
84 const atom = Atom.make<Readonly<Record<string, E>>>({}).pipe(
85 Atom.keepAlive,
86 Atom.withLabel(options.label),
87 );
88 const savingAtom = Atom.make<Readonly<Record<string, true>>>({}).pipe(
89 Atom.keepAlive,
90 Atom.withLabel(`${options.label}-saving`),
91 );
92 // Each begin creates a new watch, so the watch is the edit's identity.
93 const watches = new Map<string, ExitWatch<E>>();
94​
95 const setSaving = (threadKey: string, saving: boolean) => {
96 const current = registry.get(savingAtom);
97 if (threadKey in current === saving) return;
98 const next = { ...current };
99 if (saving) next[threadKey] = true;
100 else delete next[threadKey];
101 registry.set(savingAtom, next);
102 };
103​
104 const get = (threadKey: string | null): E | null =>
105 threadKey === null ? null : (registry.get(atom)[threadKey] ?? null);
106​
107 const write = (threadKey: string, edit: E | null) => {
108 const current = registry.get(atom);
109 if (edit === null) {
110 if (!(threadKey in current)) return;
111 const next = { ...current };
112 delete next[threadKey];
113 registry.set(atom, next);
114 return;
115 }
116 registry.set(atom, { ...current, [threadKey]: edit });
117 };
118​
119 const unsubscribe = (watch: ExitWatch<E>) => {
120 watch.cancel?.();
121 watch.cancel = null;
122 };
123​
124 const subscribe = (threadKey: string, watch: ExitWatch<E>) => {
125 const check = (runs: ReadonlyArray<QueuedRunStatus> | null) => {
126 if (watches.get(threadKey) !== watch || watch.cancel === null) return;
127 if (!runLeftQueue(runs, watch.runId)) return;
128 unsubscribe(watch);
129 watches.delete(threadKey);
130 const edit = get(threadKey);
131 if (edit === null || edit.runId !== watch.runId) return;
132 write(threadKey, null);
133 watch.onRunLeftQueue(threadKey, edit);
134 };
135 watch.cancel = registry.subscribe(watch.runs, check);
136 check(registry.get(watch.runs));
137 };
138​
139 const stopWatch = (threadKey: string) => {
140 const watch = watches.get(threadKey);
141 if (watch === undefined) return;
142 unsubscribe(watch);
143 watches.delete(threadKey);
144 };
145​
146 return {
147 atom,
148 /** Thread keys whose edit has a save in flight. */
149 savingAtom,
150 get,
151 /**
152 * Starts an edit, replacing any edit already open on the thread. When the
153 * run leaves the queue the edit is removed and `onRunLeftQueue` receives
154 * it; if the run already left, that happens immediately.
155 */
156 begin(
157 threadKey: string,
158 edit: E,
159 watch: {
160 readonly runs: QueuedRunsAtom;
161 readonly onRunLeftQueue: (threadKey: string, edit: E) => void;
162 },
163 ) {
164 stopWatch(threadKey);
165 write(threadKey, edit);
166 const next: ExitWatch<E> = { ...watch, runId: edit.runId, cancel: null };
167 watches.set(threadKey, next);
168 subscribe(threadKey, next);
169 },
170 update(threadKey: string, f: (edit: E) => E) {
171 const edit = get(threadKey);
172 if (edit !== null) write(threadKey, f(edit));
173 },
174 end(threadKey: string) {
175 stopWatch(threadKey);
176 write(threadKey, null);
177 },
178 /**
179 * Claims the open edit for a save, or returns null when there is no edit
180 * or a save is in flight. The exit watch pauses so the save's result decides
181 * the edit's fate. The claim outlives the edit: the server orders saves by
182 * arrival, so an overlapping older save could overwrite a newer one.
183 */
184 startSave(threadKey: string): FinishQueuedRunEditSave | null {
185 const watch = watches.get(threadKey);
186 if (watch === undefined || threadKey in registry.get(savingAtom)) return null;
187 setSaving(threadKey, true);
188 unsubscribe(watch);
189 let settled = false;
190 return (succeeded) => {
191 if (!settled) {
192 settled = true;
193 setSaving(threadKey, false);
194 }
195 if (watches.get(threadKey) !== watch) return false;
196 if (succeeded) {
197 stopWatch(threadKey);
198 write(threadKey, null);
199 } else {
200 subscribe(threadKey, watch);
201 }
202 return true;
203 };
204 },
205 };