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

threadVisits.ts

306 lines12.7 KB

1// @effect-diagnostics globalTimers:off globalDate:off - The tracker runs in atom subscriptions, outside an Effect runtime.
2import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
3import { AsyncResult, Atom } from "effect/reactivity";
4​
5import { parseThreadKey, threadKey } from "./entities.ts";
6import { type AtomCommand, runAtomCommand } from "./runtime.ts";
7import { claimThreadOpen, releaseThreadOpen } from "./threadSearch.ts";
8import type { VisitThreadInput } from "../operations/commands.ts";
9​
10// During an active turn the thread's updatedAt advances several times per
11// second, and every server-side visit is a full command dispatch plus a
12// broadcast to all shell subscribers.
13export const VISIT_DISPATCH_THROTTLE_MS = 10_000;
14​
15const IDLE_TRACKER: Atom.Atom<void> = Atom.make(undefined).pipe(
16 Atom.withLabel("thread-visit-tracker:idle"),
17);
18​
19interface VisitedShell {
20 readonly environmentId: EnvironmentId;
21 readonly id: ThreadId;
22 readonly updatedAt: string;
23 readonly lastVisitedAt?: string | null | undefined;
24 readonly opens?: { readonly openedAt: number } | null | undefined;
25 readonly latestRun: { readonly completedAt: string | null } | null;
26 /**
27 * When a scheduled wake the user is looking at took effect. A wake later
28 * than `updatedAt` is an update the server never sent, so the watermark
29 * advances to it, and at once: leaving within the throttle would cancel
30 * the dispatch and keep the thread marked Woke.
31 */
32 readonly wokeAt?: string | null | undefined;
34​
35export interface ThreadVisitTrackerOptions {
36 readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<VisitedShell | null>;
37 readonly sessionGenerationAtom: (environmentId: EnvironmentId) => Atom.Atom<number>;
38 readonly visit: AtomCommand<
39 { readonly environmentId: EnvironmentId; readonly input: VisitThreadInput },
40 unknown,
41 unknown
42 >;
43 /**
44 * Servers without visit tracking leave `lastVisitedAt` undefined; a client
45 * that keeps its own watermark for them records the visit here instead.
46 */
47 readonly markLocalVisit?: (ref: ScopedThreadRef, visitedAt: string) => void;
48 /**
49 * Whether the user can see the thread right now. While false, nothing is
50 * recorded; the open and the watermark catch up when it turns true.
51 */
52 readonly viewingAtom?: Atom.Atom<boolean>;
54​
55/**
56 * While mounted and `viewingAtom` holds, a tracker counts as the user viewing the thread: mounting it
57 * records one open (which also feeds search ranking), and every shell update
58 * after that advances the visit watermark, throttled while a run streams.
59 */
60export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
61 const family = Atom.family((key: string) => {
62 const ref = parseThreadKey(key);
63 return Atom.make((get) => {
64 const registry = get.registry;
65 // Showing the thread is the open, whether or not its shell has arrived;
66 // the shell only decides when the server hears about it.
67 // Recorded even when the server cannot take opens, so recents follow
68 // it. A palette pick already sent the open with its query.
69 let openPending = claimThreadOpen(ref.environmentId, ref.threadId, Date.now());
70 // Dedupe per watermark: the shell updates again before the command's echo
71 // lands. It also keeps a mark-unread on the open thread sticky, since the
72 // rewind leaves updatedAt untouched.
73 let lastDispatchedUpdatedAt: string | null = null;
74 let lastAcceptedUpdatedAt: string | null = null;
75 let retryPending = false;
76 let pendingOpenConfirmation: {
77 readonly openedAtBefore: number | null;
78 readonly alreadySeenBefore: boolean;
79 } | null = null;
80 const sessionGenerationAtom = options.sessionGenerationAtom(ref.environmentId);
81 let lastDispatchGeneration = registry.get(sessionGenerationAtom);
82 let active = true;
83 let lastDispatchAt = 0;
84 let timer: ReturnType<typeof setTimeout> | undefined;
85 const clearTimer = () => {
86 if (timer === undefined) return;
87 clearTimeout(timer);
88 timer = undefined;
89 };
90 get.addFinalizer(() => {
91 active = false;
92 clearTimer();
93 releaseThreadOpen(ref.environmentId, ref.threadId);
94 });
95​
96 const accept = (visitedAt: string) => {
97 const visitedAtMs = Date.parse(visitedAt);
98 if (Number.isNaN(visitedAtMs)) return;
99 if (lastAcceptedUpdatedAt === null || visitedAtMs > Date.parse(lastAcceptedUpdatedAt))
100 lastAcceptedUpdatedAt = visitedAt;
101 };
102​
103 const openAdvanced = (currentShell: VisitedShell | null, openedAtBefore: number | null) => {
104 const currentOpenedAt = currentShell?.opens?.openedAt ?? null;
105 return (
106 currentOpenedAt !== null && (openedAtBefore === null || currentOpenedAt > openedAtBefore)
107 );
108 };
109​
110 // A lost-ack open followed by a mark-unread looks like another device's open of an
111 // older shell; only the server's rewind to 1ms before the latest completion tells them apart.
112 const markedUnread = (currentShell: VisitedShell | null) => {
113 const completedAt = currentShell?.latestRun?.completedAt;
114 const lastVisitedAt = currentShell?.lastVisitedAt;
115 return (
116 completedAt != null &&
117 lastVisitedAt != null &&
118 Date.parse(lastVisitedAt) === Date.parse(completedAt) - 1
119 );
120 };
121​
122 const openConfirmedByShell = (
123 currentShell: VisitedShell | null,
124 baseline: {
125 readonly openedAtBefore: number | null;
126 readonly alreadySeenBefore: boolean;
127 },
128 targetVisitedAtMs: number,
129 ) =>
130 openAdvanced(currentShell, baseline.openedAtBefore) ||
131 (!baseline.alreadySeenBefore &&
132 lastAcceptedUpdatedAt !== null &&
133 Date.parse(lastAcceptedUpdatedAt) >= targetVisitedAtMs);
134​
135 const dispatch = (
136 shell: VisitedShell,
137 visitedAt: string,
138 opened: boolean,
139 requestVisitedAt = visitedAt,
140 ) => {
141 clearTimer();
142 retryPending = false;
143 if (opened) pendingOpenConfirmation = null;
144 const visitedAtMs = Date.parse(visitedAt);
145 const alreadySeenBefore =
146 !Number.isNaN(visitedAtMs) &&
147 ((lastAcceptedUpdatedAt !== null && Date.parse(lastAcceptedUpdatedAt) >= visitedAtMs) ||
148 (shell.lastVisitedAt != null && Date.parse(shell.lastVisitedAt) >= visitedAtMs));
149 const openedAtBefore = shell.opens?.openedAt ?? null;
150 lastDispatchedUpdatedAt = visitedAt;
151 lastDispatchAt = Date.now();
152 lastDispatchGeneration = registry.get(sessionGenerationAtom);
153 void runAtomCommand(
154 registry,
155 options.visit,
156 {
157 environmentId: shell.environmentId,
158 input: {
159 threadId: shell.id,
160 visitedAt: requestVisitedAt,
161 ...(opened ? { opened: true } : {}),
162 },
163 },
164 { reportFailure: false },
165 ).then((result) => {
166 if (!active) return;
167 if (!AsyncResult.isFailure(result)) {
168 accept(requestVisitedAt);
169 return;
170 }
171 const currentShell = registry.get(options.threadShellAtom(ref));
172 const baseline = { openedAtBefore, alreadySeenBefore };
173 const openConfirmed =
174 !opened || openConfirmedByShell(currentShell, baseline, visitedAtMs);
175 const watermarkConfirmed =
176 lastAcceptedUpdatedAt !== null && Date.parse(lastAcceptedUpdatedAt) >= visitedAtMs;
177 // Keep acceptance across a subsequent mark-unread, even if the ack was lost.
178 if (openConfirmed && watermarkConfirmed) return;
179 if (opened && openAdvanced(currentShell, openedAtBefore) && markedUnread(currentShell))
180 return;
181 if (lastDispatchedUpdatedAt !== visitedAt) return;
182 if (opened && !openConfirmed) {
183 openPending = true;
184 pendingOpenConfirmation = baseline;
185 }
186 retryPending = true;
187 onShell(currentShell);
188 });
189 };
190​
191 const onShell = (shell: VisitedShell | null) => {
192 clearTimer();
193 if (shell === null) return;
194 if (options.viewingAtom && !registry.get(options.viewingAtom)) return;
195​
196 const shellUpdatedAtMs = Date.parse(shell.updatedAt);
197 if (Number.isNaN(shellUpdatedAtMs)) return;
198 const wokeAtMs = shell.wokeAt ? Date.parse(shell.wokeAt) : NaN;
199 const wakeIsLatest = wokeAtMs > shellUpdatedAtMs;
200 const visitedAt = wakeIsLatest && shell.wokeAt ? shell.wokeAt : shell.updatedAt;
201 const updatedAtMs = wakeIsLatest ? wokeAtMs : shellUpdatedAtMs;
202 if (shell.lastVisitedAt === undefined) {
203 options.markLocalVisit?.(ref, visitedAt);
204 return;
205 }
206 if (shell.lastVisitedAt) accept(shell.lastVisitedAt);
207 if (
208 openPending &&
209 pendingOpenConfirmation !== null &&
210 openAdvanced(shell, pendingOpenConfirmation.openedAtBefore)
211 ) {
212 openPending = false;
213 pendingOpenConfirmation = null;
214 if (markedUnread(shell)) retryPending = false;
215 }
216 if (
217 retryPending &&
218 lastAcceptedUpdatedAt !== null &&
219 lastDispatchedUpdatedAt !== null &&
220 Date.parse(lastAcceptedUpdatedAt) >= Date.parse(lastDispatchedUpdatedAt)
221 ) {
222 const dispatchedAtMs = Date.parse(lastDispatchedUpdatedAt);
223 if (
224 !openPending ||
225 (pendingOpenConfirmation !== null &&
226 openConfirmedByShell(shell, pendingOpenConfirmation, dispatchedAtMs))
227 ) {
228 openPending = false;
229 pendingOpenConfirmation = null;
230 retryPending = false;
231 }
232 }
233 // A rejected visit waits for a new session, even if streaming changes the shell.
234 if (retryPending && registry.get(sessionGenerationAtom) === lastDispatchGeneration) return;
235 const elapsed = Date.now() - lastDispatchAt;
236 if (retryPending && elapsed < VISIT_DISPATCH_THROTTLE_MS) {
237 timer = setTimeout(
238 () => onShell(registry.get(options.threadShellAtom(ref))),
239 VISIT_DISPATCH_THROTTLE_MS - elapsed,
240 );
241 return;
242 }
243 // The open rides on the first visit the server hears, however late
244 // the shell arrives, so it still counts toward search ranking.
245 if (openPending) {
246 openPending = false;
247 pendingOpenConfirmation = null;
248 const acceptedWatermark =
249 lastAcceptedUpdatedAt !== null && Date.parse(lastAcceptedUpdatedAt) >= updatedAtMs
250 ? lastAcceptedUpdatedAt
251 : null;
252 // Retry an open without replaying an accepted watermark over a subsequent mark-unread.
253 dispatch(
254 shell,
255 acceptedWatermark ?? visitedAt,
256 true,
257 acceptedWatermark !== null && shell.lastVisitedAt != null
258 ? shell.lastVisitedAt
259 : visitedAt,
260 );
261 return;
262 }
263 const lastVisitedAtMs = shell.lastVisitedAt ? Date.parse(shell.lastVisitedAt) : NaN;
264 if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= updatedAtMs) {
265 // Already seen, so a later mark-unread stays sticky even when no open was sent.
266 if (lastDispatchedUpdatedAt === null || Date.parse(lastDispatchedUpdatedAt) < updatedAtMs)
267 lastDispatchedUpdatedAt = visitedAt;
268 return;
269 }
270 if (
271 !retryPending &&
272 lastDispatchedUpdatedAt !== null &&
273 Date.parse(lastDispatchedUpdatedAt) >= updatedAtMs
274 )
275 return;
276​
277 const completedAtMs = shell.latestRun?.completedAt
278 ? Date.parse(shell.latestRun.completedAt)
279 : NaN;
280 const hasUnseenCompletion =
281 !Number.isNaN(completedAtMs) &&
282 (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
283 if (hasUnseenCompletion || wakeIsLatest || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
284 dispatch(shell, visitedAt, false);
285 return;
286 }
287 timer = setTimeout(
288 () => dispatch(shell, visitedAt, false),
289 VISIT_DISPATCH_THROTTLE_MS - elapsed,
290 );
291 };
292​
293 // `subscribe`, not `get`: a rebuild would reset the open and throttle
294 // state on every streaming tick.
295 get.subscribe(options.threadShellAtom(ref), onShell, { immediate: true });
296 get.subscribe(sessionGenerationAtom, () =>
297 onShell(registry.get(options.threadShellAtom(ref))),
298 );
299 if (options.viewingAtom)
300 get.subscribe(options.viewingAtom, () =>
301 onShell(registry.get(options.threadShellAtom(ref))),
302 );
303 }).pipe(Atom.withLabel(`thread-visit-tracker:${key}`));
304 });
305 return (ref: ScopedThreadRef | null) => (ref === null ? IDLE_TRACKER : family(threadKey(ref)));