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

olderSettledThreads.ts

471 lines19.9 KB

1import {
2 isListedThreadLineage,
3 isOlderSettledThreadShell,
4 ORCHESTRATION_V2_WS_METHODS,
5 type EnvironmentId,
6 type OrchestrationV2OlderSettledCursor,
7 type OrchestrationV2OlderSettledThreadsPage,
8 type OrchestrationV2SearchThreadsInput,
9 type OrchestrationV2ThreadFamily,
10 type OrchestrationV2ThreadShell,
11 type ProjectId,
12 type ThreadId,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Option from "effect/Option";
17import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
18​
19import type * as EnvironmentRegistry from "../connection/registry.ts";
20import { request } from "../rpc/client.ts";
21import { createEnvironmentQueryAtomFamily, selectEnvironmentQueryData } from "./runtime.ts";
22import type { EnvironmentShellState } from "./shell.ts";
23import { threadFamilyRead } from "./threadFamilies.ts";
24​
25// Rows per page of older settled threads: one "Show more" step of the Settled shelf.
26const OLDER_SETTLED_PAGE_SIZE = 25;
27// A burst of changes (a PR sync touching many old threads) costs one count read.
28const COUNT_REREAD_DELAY = "500 millis";
29​
30/** Where an environment's shell cut settled threads, and how many are older per project. */
31export interface OlderSettled {
32 readonly before: string;
33 readonly beforeMs: number;
34 readonly counts: ReadonlyMap<ProjectId, number>;
36​
37/** The scope's projects in one environment, or null for all of them. */
38export interface OlderSettledScope {
39 readonly environmentId: EnvironmentId;
40 readonly projectIds: ReadonlyArray<ProjectId> | null;
42​
43/**
44 * The pages read below an environment's cut. Everything at or above `frontier` is local: pages
45 * hold the rows that were there when read, and shell deltas keep that range current. A null
46 * frontier means no more can load: every older thread is loaded, or this session has no snapshot.
47 */
48export interface OlderSettledPages {
49 readonly reads: ReadonlyArray<OrchestrationV2ThreadFamily>;
50 readonly frontier: OrchestrationV2OlderSettledCursor | null;
51 readonly status: "ready" | "pending" | "failed";
53​
54const NO_PAGES: OlderSettledPages = { reads: [], frontier: null, status: "ready" };
55​
56type OlderSettledRow = Pick<
57 OrchestrationV2ThreadShell,
58 "id" | "projectId" | "lineage" | "settledOverride" | "settledAt"
59>;
60​
61export interface OlderSettledShelfEnvironment {
62 readonly older: OlderSettled | null;
63 readonly pages: OlderSettledPages;
65​
66/**
67 * Changes whenever the older count can: any removal (by largest sequence, so a repeat counts), an
68 * older row that arrives or changes, or an old row arriving outside the set (unsettled). Threads
69 * created after the cut never enter it, as threads settle after creation. Archived-thread events
70 * arrive as removals too, each costing one count read.
71 */
72export function olderSettledCountKey(
73 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
74 beforeMs: number,
75 removedAt: ReadonlyMap<ThreadId, number>,
76): string {
77 let lastRemoval = 0;
78 for (const sequence of removedAt.values()) lastRemoval = Math.max(lastRemoval, sequence);
79 const rows: string[] = [];
80 for (const thread of threads) {
81 if (!isListedThreadLineage(thread.lineage)) continue;
82 const older = isOlderSettledThreadShell(thread, beforeMs);
83 if (older || DateTime.toEpochMillis(thread.createdAt) < beforeMs) {
84 rows.push(`${thread.id}:${older ? 1 : 0}`);
85 }
86 }
87 return `${lastRemoval}|${rows.sort().join(",")}`;
89​
90/** Whether a row sits at or above a page cursor in the server's order (settle time desc, id asc). */
91function atOrAboveCursor(
92 thread: Pick<OrchestrationV2ThreadShell, "id" | "settledAt">,
93 cursor: OrchestrationV2OlderSettledCursor,
94): boolean {
95 if (thread.settledAt === null) return true;
96 const settledAt = DateTime.formatIso(thread.settledAt);
97 return !(
98 settledAt < cursor.settledAt ||
99 (cursor.threadId !== undefined && settledAt === cursor.settledAt && thread.id > cursor.threadId)
100 );
102​
103/**
104 * Where a shelf over these environments stops listing: the highest frontier of any environment
105 * that can still load older threads (its cut until its first page). Rows below it could sort under
106 * rows not loaded yet, so the merged list is a correct prefix even while a page loads. A failed
107 * environment holds no one back; its Retry rejoins it.
108 */
109export function settledShelfFrontier(
110 environments: ReadonlyArray<OlderSettledShelfEnvironment>,
111): OrchestrationV2OlderSettledCursor | null {
112 let highest: OrchestrationV2OlderSettledCursor | null = null;
113 for (const { older, pages } of environments) {
114 if (older === null || pages.frontier === null || pages.status === "failed") continue;
115 const frontier = pages.frontier;
116 // On a settle-time tie, a cursor with an id stops above one without, and a smaller id higher.
117 if (
118 highest === null ||
119 frontier.settledAt > highest.settledAt ||
120 (frontier.settledAt === highest.settledAt &&
121 frontier.threadId !== undefined &&
122 (highest.threadId === undefined || frontier.threadId < highest.threadId))
123 ) {
124 highest = frontier;
125 }
126 }
127 return highest;
129​
130/**
131 * Whether the Settled shelf may list a row: at or above the shelf's frontier. So a row that turns
132 * older mid-session (a backdated auto-settle, a snooze that ends, an unarchive) waits for the
133 * range that holds it.
134 */
135export function isListedSettledThread(
136 thread: Pick<OrchestrationV2ThreadShell, "id" | "settledAt">,
137 frontier: OrchestrationV2OlderSettledCursor | null,
138): boolean {
139 return frontier === null || atOrAboveCursor(thread, frontier);
141​
142/**
143 * Older settled threads in scope that this client does not hold: the server's counts minus the
144 * older rows it has. Add it to the local rows for the Settled label or a project's thread count.
145 */
146export function unloadedOlderSettledCount(input: {
147 readonly olderSettled: (environmentId: EnvironmentId) => OlderSettled | null;
148 readonly scopes: ReadonlyArray<OlderSettledScope>;
149 /** Every row the client holds in scope, in any section. */
150 readonly threads: ReadonlyArray<{
151 readonly environmentId: EnvironmentId;
152 readonly source: OlderSettledRow;
153 }>;
154}): number {
155 let unloaded = 0;
156 for (const scope of input.scopes) {
157 const older = input.olderSettled(scope.environmentId);
158 if (older === null) continue;
159 if (scope.projectIds === null) {
160 for (const count of older.counts.values()) unloaded += count;
161 } else {
162 for (const projectId of scope.projectIds) unloaded += older.counts.get(projectId) ?? 0;
163 }
164 for (const thread of input.threads) {
165 if (
166 thread.environmentId === scope.environmentId &&
167 (scope.projectIds === null || scope.projectIds.includes(thread.source.projectId)) &&
168 isOlderSettledThreadShell(thread.source, older.beforeMs)
169 ) {
170 unloaded -= 1;
171 }
172 }
173 }
174 return Math.max(0, unloaded);
176​
177/**
178 * The pages each environment should read: while the shelf lists fewer than `visibleCount` rows,
179 * one more for each environment whose frontier is the shelf's, once its pages have loaded. A
180 * short page ends an environment's chain; counts can lag a backdated settle, so they do not gate.
181 */
182export function wantedOlderSettledPages(input: {
183 readonly requested: ReadonlyMap<EnvironmentId, number>;
184 readonly environments: ReadonlyMap<EnvironmentId, OlderSettledShelfEnvironment>;
185 readonly listedCount: number;
186 readonly visibleCount: number;
187}): ReadonlyMap<EnvironmentId, number> {
188 if (input.listedCount >= input.visibleCount) return input.requested;
189 const frontier = settledShelfFrontier([...input.environments.values()]);
190 if (frontier === null) return input.requested;
191 let next: Map<EnvironmentId, number> | null = null;
192 for (const [environmentId, { older, pages }] of input.environments) {
193 if (older === null || pages.status !== "ready" || pages.frontier === null) continue;
194 if (
195 pages.frontier.settledAt !== frontier.settledAt ||
196 pages.frontier.threadId !== frontier.threadId
197 ) {
198 continue;
199 }
200 next ??= new Map(input.requested);
201 next.set(environmentId, (input.requested.get(environmentId) ?? 0) + 1);
202 }
203 return next ?? input.requested;
205​
206/**
207 * Shells that omit older settled threads (`omitOlderSettled`) name the cut and count what they left
208 * out. These atoms keep those counts current and read older threads in pages for the Settled shelf.
209 */
210export function createOlderSettledThreadAtoms<R, ER, E>(
211 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
212 shellStateAtom: (
213 environmentId: EnvironmentId,
214 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, E>>,
215) {
216 const shellStateValue = (state: AsyncResult.AsyncResult<EnvironmentShellState, E>) =>
217 AsyncResult.getOrElse(state, () => null);
218​
219 const countReadAtom = createEnvironmentQueryAtomFamily(runtime, {
220 label: "environment-data:orchestration:older-settled-counts",
221 staleTimeMs: Number.POSITIVE_INFINITY,
222 // A newer key unmounts this read; with no idle time its wait is interrupted before the RPC.
223 idleTtlMs: 0,
224 execute: Effect.fn("OlderSettledThreads.readCounts")(function* (input: {
225 readonly generation: number;
226 readonly before: string;
227 readonly key: string;
228 }) {
229 yield* Effect.sleep(COUNT_REREAD_DELAY);
230 return yield* request(ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads, {
231 before: { settledAt: input.before },
232 limit: 0,
233 });
234 }),
235 });
236​
237 const pageReadAtom = createEnvironmentQueryAtomFamily(runtime, {
238 label: "environment-data:orchestration:older-settled-page",
239 staleTimeMs: Number.POSITIVE_INFINITY,
240 // A collapsed shelf keeps no read alive, as an idle one runs again when a reconnect replaces
241 // the session.
242 idleTtlMs: 0,
243 execute: Effect.fn("OlderSettledThreads.readPage")(function* (input: {
244 readonly generation: number;
245 readonly projectIds: ReadonlyArray<ProjectId> | null;
246 readonly before: OrchestrationV2OlderSettledCursor;
247 }) {
248 return yield* request(ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads, {
249 before: input.before,
250 ...(input.projectIds === null ? {} : { projectIds: input.projectIds }),
251 limit: OLDER_SETTLED_PAGE_SIZE,
252 });
253 }),
254 });
255​
256 const countsOf = (source: {
257 readonly counts: OrchestrationV2OlderSettledThreadsPage["counts"];
258 }) => new Map(source.counts.map(({ projectId, count }) => [projectId, count] as const));
259​
260 const olderSettledAtom = Atom.family((environmentId: EnvironmentId) => {
261 let generation = -1;
262 // The key of the first state seen this generation, when that state is the snapshot itself.
263 let snapshotKey: string | null = null;
264 let keyInputs: { readonly threads: unknown; readonly removedAt: unknown } | null = null;
265 let key = "";
266 let fromSnapshot: OlderSettled | null = null;
267 let lastRead: OlderSettled | null = null;
268 let lastReadPage: OrchestrationV2OlderSettledThreadsPage | null = null;
269 return Atom.make((get): OlderSettled | null => {
270 const state = shellStateValue(get(shellStateAtom(environmentId)));
271 const snapshot = state === null ? null : Option.getOrNull(state.snapshot);
272 const cut = snapshot?.olderSettled;
273 if (state === null || snapshot === null || cut === undefined) return null;
274 if (fromSnapshot?.before !== cut.before || state.generation !== generation) {
275 fromSnapshot = {
276 before: cut.before,
277 beforeMs: DateTime.toEpochMillis(DateTime.makeUnsafe(cut.before)),
278 counts: countsOf(cut),
279 };
280 }
281 // Most shell updates move only the cursor; the key needs new rows or removals.
282 if (keyInputs?.threads !== snapshot.threads || keyInputs.removedAt !== state.removedAt) {
283 keyInputs = { threads: snapshot.threads, removedAt: state.removedAt };
284 key = olderSettledCountKey(snapshot.threads, fromSnapshot.beforeMs, state.removedAt);
285 }
286 if (state.generation !== generation) {
287 generation = state.generation;
288 snapshotKey = snapshot.snapshotSequence === cut.asOfSequence ? key : null;
289 lastRead = null;
290 }
291 // Generation 0 is a cached shell: no reads until this session's first snapshot.
292 if (key === snapshotKey || state.generation === 0) return fromSnapshot;
293 const read = selectEnvironmentQueryData(
294 get(
295 countReadAtom({
296 environmentId,
297 input: { generation: state.generation, before: cut.before, key },
298 }),
299 ),
300 );
301 if (read !== null && read !== lastReadPage) {
302 lastReadPage = read;
303 lastRead = { ...fromSnapshot, counts: countsOf(read) };
304 }
305 return lastRead ?? fromSnapshot;
306 }).pipe(Atom.withLabel(`environment-older-settled:${environmentId}`));
307 });
308​
309 const pagesKey = (scope: OlderSettledScope, pages: number) =>
310 JSON.stringify([
311 scope.environmentId,
312 scope.projectIds === null ? null : [...scope.projectIds].sort(),
313 pages,
314 ]);
315​
316 const pagesAtom = Atom.family((key: string) => {
317 const [environmentId, projectIds, pages] = JSON.parse(key) as [
318 EnvironmentId,
319 ReadonlyArray<ProjectId> | null,
320 number,
321 ];
322 let previous = NO_PAGES;
323 const keep = (next: OlderSettledPages): OlderSettledPages => {
324 const same =
325 next.status === previous.status &&
326 next.frontier?.settledAt === previous.frontier?.settledAt &&
327 next.frontier?.threadId === previous.frontier?.threadId &&
328 (next.frontier === null) === (previous.frontier === null) &&
329 next.reads.length === previous.reads.length &&
330 next.reads.every((read, index) => read === previous.reads[index]);
331 if (!same) previous = next;
332 return previous;
333 };
334 return Atom.make((get) => {
335 const state = shellStateValue(get(shellStateAtom(environmentId)));
336 const cut = state === null ? undefined : Option.getOrNull(state.snapshot)?.olderSettled;
337 // A cached shell (an environment not connected yet, or offline) must not hold the shelf
338 // back for other environments, so it lists what it holds until its first snapshot.
339 if (state === null || cut === undefined || state.generation === 0) return keep(NO_PAGES);
340 let frontier: OrchestrationV2OlderSettledCursor = { settledAt: cut.before };
341 if (pages === 0) return keep({ reads: [], frontier, status: "ready" });
342 const reads: OrchestrationV2ThreadFamily[] = [];
343 for (let index = 0; index < pages; index += 1) {
344 const result = get(
345 pageReadAtom({
346 environmentId,
347 input: { generation: state.generation, projectIds, before: frontier },
348 }),
349 );
350 const page = selectEnvironmentQueryData(result);
351 if (page === null) {
352 return keep({
353 reads,
354 frontier,
355 status: threadFamilyRead(result) === "failed" ? "failed" : "pending",
356 });
357 }
358 reads.push(page);
359 const last = page.threads.at(-1);
360 if (page.threads.length < OLDER_SETTLED_PAGE_SIZE || last?.settledAt == null) {
361 return keep({ reads, frontier: null, status: "ready" });
362 }
363 frontier = { settledAt: DateTime.formatIso(last.settledAt), threadId: last.id };
364 }
365 return keep({ reads, frontier, status: "ready" });
366 }).pipe(Atom.withLabel(`environment-older-settled-pages:${key}`));
367 });
368​
369 const pageRowsAtom = Atom.family((key: string) =>
370 Atom.map(pagesAtom(key), (pages) => pages.reads).pipe(
371 Atom.withLabel(`environment-older-settled-page-rows:${key}`),
372 ),
373 );
374​
375 const searchGenerationAtom = Atom.family((environmentId: EnvironmentId) =>
376 Atom.make((get): number | "waiting" | "none" => {
377 const state = shellStateValue(get(shellStateAtom(environmentId)));
378 if (state !== null && state.generation > 0) return state.generation;
379 return state?.status === "synchronizing" ? "waiting" : "none";
380 }),
381 );
382 const searchReadAtom = createEnvironmentQueryAtomFamily(runtime, {
383 label: "environment-data:orchestration:older-settled-search",
384 idleTtlMs: 60_000,
385 execute: Effect.fn("OlderSettledThreads.search")(function* (input: {
386 readonly generation: number;
387 readonly search: OrchestrationV2SearchThreadsInput;
388 }) {
389 return yield* request(ORCHESTRATION_V2_WS_METHODS.searchThreads, input.search);
390 }),
391 });
392 // Keyed by shell generation like pages: rows read before a new snapshot do not merge, so the
393 // search reads them again.
394 const searchAtom = Atom.family((key: string) => {
395 const [environmentId, search] = JSON.parse(key) as [
396 EnvironmentId,
397 OrchestrationV2SearchThreadsInput,
398 ];
399 return Atom.make((get) => {
400 const generation = get(searchGenerationAtom(environmentId));
401 // Nothing is read before this session's first snapshot, which would drop the rows. It shows
402 // as loading only while that snapshot is on its way, so an offline environment never spins.
403 return typeof generation === "number"
404 ? get(searchReadAtom({ environmentId, input: { generation, search } }))
405 : AsyncResult.initial(generation === "waiting");
406 }).pipe(Atom.withLabel(`environment-older-settled-search:${key}`));
407 });
408​
409 // One read for a shelf that spans environments: each one's cut, counts and pages.
410 const shelfAtom = Atom.family((key: string) => {
411 const entries = JSON.parse(key) as ReadonlyArray<readonly [string, string]>;
412 let previous: ReadonlyMap<EnvironmentId, OlderSettledShelfEnvironment> = new Map();
413 return Atom.make((get): ReadonlyMap<EnvironmentId, OlderSettledShelfEnvironment> => {
414 const shelf = new Map<EnvironmentId, OlderSettledShelfEnvironment>();
415 let changed = previous.size !== entries.length;
416 for (const [environmentId, pagesKey] of entries) {
417 const older = get(olderSettledAtom(environmentId as EnvironmentId));
418 const pages = get(pagesAtom(pagesKey));
419 const prior = previous.get(environmentId as EnvironmentId);
420 changed ||= prior?.older !== older || prior.pages !== pages;
421 shelf.set(environmentId as EnvironmentId, { older, pages });
422 }
423 if (changed) previous = shelf;
424 return previous;
425 }).pipe(Atom.withLabel(`environment-older-settled-shelf:${key}`));
426 });
427​
428 /** Reads a failed page again (a no-op when none failed); the pages after it follow. */
429 const retryPages = (
430 registry: AtomRegistry.AtomRegistry,
431 scope: OlderSettledScope,
432 pages: number,
433 ) => {
434 const state = shellStateValue(registry.get(shellStateAtom(scope.environmentId)));
435 const result = registry.get(pagesAtom(pagesKey(scope, pages)));
436 if (state === null || result.status !== "failed" || result.frontier === null) return;
437 registry.refresh(
438 pageReadAtom({
439 environmentId: scope.environmentId,
440 input: {
441 generation: state.generation,
442 projectIds: scope.projectIds === null ? null : [...scope.projectIds].sort(),
443 before: result.frontier,
444 },
445 }),
446 );
447 };
448​
449 return {
450 /** The environment's cut and current counts, or null when its shell keeps every settled thread. */
451 olderSettledAtom,
452 /** Each scope's cut, counts and first `pages` pages. */
453 shelfAtom: (
454 scopes: ReadonlyArray<{ readonly scope: OlderSettledScope; readonly pages: number }>,
455 ) =>
456 shelfAtom(
457 JSON.stringify(
458 scopes.map(({ scope, pages }) => [scope.environmentId, pagesKey(scope, pages)] as const),
459 ),
460 ),
461 retryPages,
462 /** The first `pages` pages below the cut for one scope, read in order. */
463 pagesAtom: (scope: OlderSettledScope, pages: number) => pagesAtom(pagesKey(scope, pages)),
464 /** Their rows, for `createThreadFamilyAtoms(...).mountRows`, under `rowsKey`. */
465 pageRowsAtom: (scope: OlderSettledScope, pages: number) => pageRowsAtom(pagesKey(scope, pages)),
466 rowsKey: (scope: OlderSettledScope, pages: number) => `older-settled:${pagesKey(scope, pages)}`,
467 /** `orchestration.searchThreads` for a search that asks for older settled rows. */
468 searchAtom: (environmentId: EnvironmentId, search: OrchestrationV2SearchThreadsInput) =>
469 searchAtom(JSON.stringify([environmentId, search])),
470 };