Open History to see the last commit
1import { pipe } from "effect/Function";
2import * as Order from "effect/Order";
3import * as Arr from "effect/Array";
4import * as DateTime from "effect/DateTime";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import type {
9 OrchestrationThread,
10 OrchestrationThreadStreamItem,
11 EnvironmentId,
12 ThreadId as ThreadIdType,
13} from "@t3tools/contracts";
14import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
15
16import {
17 DEFAULT_THREAD_DETAIL_LIMITS,
18 applyThreadDetailEvent,
19 type ThreadDetailRetentionLimits,
20} from "./threadDetailReducer.ts";
21import type { WsRpcClient } from "./wsRpcClient.ts";
22
23export interface ThreadDetailState {
24 readonly data: OrchestrationThread | null;
25 readonly error: string | null;
26 readonly isPending: boolean;
27 readonly isDeleted: boolean;
28}
29
30export interface ThreadDetailTarget {
31 readonly environmentId: EnvironmentId | null;
32 readonly threadId: ThreadIdType | null;
33}
34
35export type ThreadDetailClient = Pick<WsRpcClient["orchestration"], "subscribeThread">;
36
37export interface ThreadDetailRetentionPolicy {
38 readonly idleTtlMs: number;
39 readonly maxRetainedEntries: number;
40 readonly shouldKeepWarm?: (
41 target: { readonly environmentId: EnvironmentId; readonly threadId: ThreadIdType },
42 state: ThreadDetailState,
43 ) => boolean;
44}
45
46interface ThreadDetailEntry {
47 readonly target: {
48 readonly environmentId: EnvironmentId;
49 readonly threadId: ThreadIdType;
50 };
51 watcherCount: number;
52 retainCount: number;
53 teardown: () => void;
54 lastAccessedAt: number;
55 evictionFiber: Fiber.Fiber<void, never> | null;
56}
57
58const NOOP: () => void = () => undefined;
59const nowMs = () => DateTime.toEpochMillis(DateTime.nowUnsafe());
60
61function clearEntryEviction(entry: ThreadDetailEntry): void {
62 if (entry.evictionFiber !== null) {
63 Effect.runFork(Fiber.interrupt(entry.evictionFiber));
64 entry.evictionFiber = null;
65 }
66}
67
68export const EMPTY_THREAD_DETAIL_STATE = Object.freeze<ThreadDetailState>({
69 data: null,
70 error: null,
71 isPending: false,
72 isDeleted: false,
73});
74
75const INITIAL_THREAD_DETAIL_STATE = Object.freeze<ThreadDetailState>({
76 data: null,
77 error: null,
78 isPending: true,
79 isDeleted: false,
80});
81
82const knownThreadDetailKeys = new Set<string>();
83
84export const threadDetailStateAtom = Atom.family((key: string) => {
85 knownThreadDetailKeys.add(key);
86 return Atom.make(INITIAL_THREAD_DETAIL_STATE).pipe(
87 Atom.keepAlive,
88 Atom.withLabel(`thread-detail:${key}`),
89 );
90});
91
92export const EMPTY_THREAD_DETAIL_ATOM = Atom.make(EMPTY_THREAD_DETAIL_STATE).pipe(
93 Atom.keepAlive,
94 Atom.withLabel("thread-detail:null"),
95);
96
97export function getThreadDetailTargetKey(target: ThreadDetailTarget): string | null {
98 if (target.environmentId === null || target.threadId === null) {
99 return null;
100 }
101
102 return `${target.environmentId}:${target.threadId}`;
103}
104
105export interface ThreadDetailManagerConfig {
106 readonly getRegistry: () => AtomRegistry.AtomRegistry;
107 readonly getClient: (environmentId: EnvironmentId) => ThreadDetailClient | null;
108 readonly getClientIdentity?: (environmentId: EnvironmentId) => string | null;
109 readonly subscribeClientChanges?: (listener: () => void) => () => void;
110 readonly limits?: ThreadDetailRetentionLimits;
111 readonly retention?: ThreadDetailRetentionPolicy;
112}
113
114export function createThreadDetailManager(config: ThreadDetailManagerConfig) {
115 const entries = new Map<string, ThreadDetailEntry>();
116
117 function getSnapshot(target: ThreadDetailTarget): ThreadDetailState {
118 const targetKey = getThreadDetailTargetKey(target);
119 if (targetKey === null) {
120 return EMPTY_THREAD_DETAIL_STATE;
121 }
122
123 return config.getRegistry().get(threadDetailStateAtom(targetKey));
124 }
125
126 function setState(targetKey: string, nextState: ThreadDetailState): void {
127 config.getRegistry().set(threadDetailStateAtom(targetKey), nextState);
128 reconcileRetention(targetKey);
129 }
130
131 function markPending(targetKey: string): void {
132 const current = config.getRegistry().get(threadDetailStateAtom(targetKey));
133 setState(targetKey, {
134 ...current,
135 error: null,
136 isPending: true,
137 });
138 }
139
140 function setData(targetKey: string, thread: OrchestrationThread): void {
141 setState(targetKey, {
142 data: thread,
143 error: null,
144 isPending: false,
145 isDeleted: false,
146 });
147 }
148
149 function setDeleted(targetKey: string): void {
150 setState(targetKey, {
151 data: null,
152 error: null,
153 isPending: false,
154 isDeleted: true,
155 });
156 }
157
158 function shouldKeepWarm(entry: ThreadDetailEntry): boolean {
159 return config.retention?.shouldKeepWarm?.(entry.target, getSnapshot(entry.target)) ?? false;
160 }
161
162 function disposeEntry(targetKey: string): void {
163 const entry = entries.get(targetKey);
164 if (!entry) {
165 return;
166 }
167
168 clearEntryEviction(entry);
169 entry.teardown();
170 entries.delete(targetKey);
171 }
172
173 function evictIdleEntriesToCapacity(): void {
174 const retention = config.retention;
175 if (!retention || entries.size <= retention.maxRetainedEntries) {
176 return;
177 }
178
179 const idleEntries = pipe(
180 Arr.fromIterable(entries),
181 Arr.filter(
182 ([, entry]) =>
183 entry.watcherCount === 0 && entry.retainCount === 0 && !shouldKeepWarm(entry),
184 ),
185 Arr.sortWith(([, e]) => e.lastAccessedAt, Order.Number),
186 );
187
188 for (const [targetKey] of idleEntries) {
189 if (entries.size <= retention.maxRetainedEntries) {
190 return;
191 }
192 disposeEntry(targetKey);
193 }
194 }
195
196 function scheduleEviction(targetKey: string, entry: ThreadDetailEntry): void {
197 const retention = config.retention;
198 clearEntryEviction(entry);
199
200 if (!retention) {
201 disposeEntry(targetKey);
202 return;
203 }
204
205 if (retention.idleTtlMs <= 0) {
206 disposeEntry(targetKey);
207 return;
208 }
209
210 entry.evictionFiber = Effect.runFork(
211 Effect.sleep(Duration.millis(retention.idleTtlMs)).pipe(
212 Effect.andThen(
213 Effect.sync(() => {
214 const current = entries.get(targetKey);
215 if (!current) {
216 return;
217 }
218
219 current.evictionFiber = null;
220 if (current.watcherCount > 0 || current.retainCount > 0 || shouldKeepWarm(current)) {
221 return;
222 }
223
224 disposeEntry(targetKey);
225 }),
226 ),
227 ),
228 );
229 }
230
231 function reconcileRetention(targetKey: string): void {
232 const entry = entries.get(targetKey);
233 if (!entry) {
234 return;
235 }
236
237 clearEntryEviction(entry);
238 if (entry.watcherCount > 0 || entry.retainCount > 0 || shouldKeepWarm(entry)) {
239 return;
240 }
241
242 scheduleEviction(targetKey, entry);
243 evictIdleEntriesToCapacity();
244 }
245
246 function applyStreamItem(
247 targetKey: string,
248 item: OrchestrationThreadStreamItem,
249 threadId: ThreadIdType,
250 ): void {
251 if (item.kind === "snapshot") {
252 setData(targetKey, item.snapshot.thread);
253 return;
254 }
255
256 const current = getSnapshot({
257 environmentId: entries.get(targetKey)?.target.environmentId ?? null,
258 threadId,
259 }).data;
260
261 if (current === null) {
262 if (item.event.type === "thread.deleted") {
263 setDeleted(targetKey);
264 }
265 return;
266 }
267
268 const result = applyThreadDetailEvent(
269 current,
270 item.event,
271 config.limits ?? DEFAULT_THREAD_DETAIL_LIMITS,
272 );
273
274 if (result.kind === "updated") {
275 setData(targetKey, result.thread);
276 return;
277 }
278
279 if (result.kind === "deleted") {
280 setDeleted(targetKey);
281 }
282 }
283
284 function subscribeStream(
285 targetKey: string,
286 target: { readonly environmentId: EnvironmentId; readonly threadId: ThreadIdType },
287 client: ThreadDetailClient,
288 ): () => void {
289 markPending(targetKey);
290 return client.subscribeThread(
291 { threadId: target.threadId },
292 (item) => applyStreamItem(targetKey, item, target.threadId),
293 {
294 onResubscribe: () => markPending(targetKey),
295 },
296 );
297 }
298
299 function createDynamicSubscription(
300 targetKey: string,
301 target: { readonly environmentId: EnvironmentId; readonly threadId: ThreadIdType },
302 ): () => void {
303 let currentIdentity: string | null = null;
304 let currentUnsub = NOOP;
305
306 const sync = () => {
307 const client = config.getClient(target.environmentId);
308 const identity = client
309 ? (config.getClientIdentity?.(target.environmentId) ?? target.environmentId)
310 : null;
311
312 if (!client || identity === null) {
313 if (currentIdentity !== null) {
314 currentUnsub();
315 currentUnsub = NOOP;
316 currentIdentity = null;
317 }
318 markPending(targetKey);
319 return;
320 }
321
322 if (currentIdentity === identity) {
323 return;
324 }
325
326 currentUnsub();
327 currentIdentity = identity;
328 currentUnsub = subscribeStream(targetKey, target, client);
329 };
330
331 const unsubChanges = config.subscribeClientChanges!(sync);
332 sync();
333
334 return () => {
335 unsubChanges();
336 currentUnsub();
337 };
338 }
339
340 function acquire(
341 target: ThreadDetailTarget,
342 kind: "watcher" | "retain",
343 client?: ThreadDetailClient,
344 ): () => void {
345 const targetKey = getThreadDetailTargetKey(target);
346 if (targetKey === null || target.environmentId === null || target.threadId === null) {
347 return NOOP;
348 }
349
350 const existing = entries.get(targetKey);
351 if (existing) {
352 clearEntryEviction(existing);
353 existing.lastAccessedAt = nowMs();
354 if (kind === "watcher") {
355 existing.watcherCount += 1;
356 } else {
357 existing.retainCount += 1;
358 }
359 return () => release(targetKey, kind);
360 }
361
362 let teardown: () => void;
363 const resolvedTarget = {
364 environmentId: target.environmentId,
365 threadId: target.threadId,
366 };
367
368 if (client) {
369 teardown = subscribeStream(targetKey, resolvedTarget, client);
370 } else if (config.subscribeClientChanges) {
371 teardown = createDynamicSubscription(targetKey, resolvedTarget);
372 } else {
373 const resolved = config.getClient(target.environmentId);
374 if (!resolved) {
375 return NOOP;
376 }
377 teardown = subscribeStream(targetKey, resolvedTarget, resolved);
378 }
379
380 entries.set(targetKey, {
381 target: resolvedTarget,
382 watcherCount: kind === "watcher" ? 1 : 0,
383 retainCount: kind === "retain" ? 1 : 0,
384 teardown,
385 lastAccessedAt: nowMs(),
386 evictionFiber: null,
387 });
388 evictIdleEntriesToCapacity();
389 return () => release(targetKey, kind);
390 }
391
392 function release(targetKey: string, kind: "watcher" | "retain"): void {
393 const entry = entries.get(targetKey);
394 if (!entry) {
395 return;
396 }
397
398 if (kind === "watcher") {
399 entry.watcherCount = Math.max(0, entry.watcherCount - 1);
400 } else {
401 entry.retainCount = Math.max(0, entry.retainCount - 1);
402 }
403 entry.lastAccessedAt = nowMs();
404 reconcileRetention(targetKey);
405 }
406
407 function watch(target: ThreadDetailTarget, client?: ThreadDetailClient): () => void {
408 return acquire(target, "watcher", client);
409 }
410
411 function retain(target: ThreadDetailTarget, client?: ThreadDetailClient): () => void {
412 return acquire(target, "retain", client);
413 }
414
415 function invalidate(target?: ThreadDetailTarget): void {
416 if (target) {
417 const targetKey = getThreadDetailTargetKey(target);
418 if (targetKey !== null) {
419 disposeEntry(targetKey);
420 config.getRegistry().set(threadDetailStateAtom(targetKey), EMPTY_THREAD_DETAIL_STATE);
421 }
422 return;
423 }
424
425 for (const targetKey of entries.keys()) {
426 disposeEntry(targetKey);
427 }
428 for (const key of knownThreadDetailKeys) {
429 config.getRegistry().set(threadDetailStateAtom(key), EMPTY_THREAD_DETAIL_STATE);
430 }
431 }
432
433 function reset(): void {
434 invalidate();
435 }
436
437 return {
438 watch,
439 retain,
440 getSnapshot,
441 invalidate,
442 reset,
443 };
444}