Open History to see the last commit
1import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
2import * as Arr from "effect/Array";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import { pipe } from "effect/Function";
6import * as Order from "effect/Order";
7import * as Option from "effect/Option";
8import * as Result from "effect/Result";
9import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity";
10
11export type ArchivedSnapshotEntry = {
12 readonly environmentId: EnvironmentId;
13 readonly snapshot: OrchestrationShellSnapshot;
14};
15
16export interface ArchivedThreadsClient {
17 readonly getArchivedShellSnapshot: () => Promise<OrchestrationShellSnapshot>;
18}
19
20export interface ArchivedThreadsSnapshotState {
21 readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
22 readonly error: string | null;
23 readonly isLoading: boolean;
24}
25
26const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
27const DEFAULT_ARCHIVED_THREADS_STALE_TIME_MS = 5_000;
28const DEFAULT_ARCHIVED_THREADS_IDLE_TTL_MS = 5 * 60_000;
29const environmentIdOrder = Order.String as Order.Order<EnvironmentId>;
30
31export function makeArchivedThreadsEnvironmentKey(
32 environmentIds: ReadonlyArray<EnvironmentId>,
33): string {
34 return pipe(environmentIds, Arr.sort(environmentIdOrder), (sortedEnvironmentIds) =>
35 sortedEnvironmentIds.join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR),
36 );
37}
38
39export function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<EnvironmentId> {
40 if (key.length === 0) {
41 return [];
42 }
43 return pipe(
44 key.split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR),
45 Arr.map((environmentId) => EnvironmentId.make(environmentId)),
46 );
47}
48
49export function readArchivedThreadsSnapshotState(
50 result: AsyncResult.AsyncResult<ReadonlyArray<ArchivedSnapshotEntry>, unknown>,
51): ArchivedThreadsSnapshotState {
52 const snapshots = Option.getOrElse(AsyncResult.value(result), () => []);
53 let error: string | null = null;
54 if (result._tag === "Failure") {
55 const cause = Cause.squash(result.cause);
56 error = cause instanceof Error ? cause.message : "Failed to load archived threads.";
57 }
58
59 return {
60 snapshots,
61 error,
62 isLoading: result.waiting,
63 };
64}
65
66export function createArchivedThreadsManager(config: {
67 readonly getRegistry: () => AtomRegistry.AtomRegistry;
68 readonly getClient: (environmentId: EnvironmentId) => ArchivedThreadsClient | null;
69 readonly staleTimeMs?: number;
70 readonly idleTtlMs?: number;
71}) {
72 const knownEnvironmentKeys = new Set<string>();
73 const knownEnvironmentIdsByKey = new Map<string, ReadonlySet<EnvironmentId>>();
74 const staleTime = config.staleTimeMs ?? DEFAULT_ARCHIVED_THREADS_STALE_TIME_MS;
75 const idleTtl = config.idleTtlMs ?? DEFAULT_ARCHIVED_THREADS_IDLE_TTL_MS;
76
77 const snapshotsAtom = Atom.family((environmentKey: string) => {
78 knownEnvironmentKeys.add(environmentKey);
79 knownEnvironmentIdsByKey.set(
80 environmentKey,
81 new Set(parseArchivedThreadsEnvironmentKey(environmentKey)),
82 );
83 return Atom.make(
84 Effect.promise(async (): Promise<ReadonlyArray<ArchivedSnapshotEntry>> => {
85 const snapshots = await Promise.all(
86 pipe(
87 parseArchivedThreadsEnvironmentKey(environmentKey),
88 Arr.map(async (environmentId) => {
89 const client = config.getClient(environmentId);
90 if (!client) {
91 return null;
92 }
93 return {
94 environmentId,
95 snapshot: await client.getArchivedShellSnapshot(),
96 };
97 }),
98 ),
99 );
100 return pipe(
101 snapshots,
102 Arr.filterMap((snapshot) =>
103 snapshot !== null ? Result.succeed(snapshot) : Result.failVoid,
104 ),
105 );
106 }),
107 ).pipe(
108 Atom.swr({
109 staleTime,
110 revalidateOnMount: true,
111 }),
112 Atom.setIdleTTL(idleTtl),
113 Atom.withLabel(`archived-thread-snapshots:${environmentKey}`),
114 );
115 });
116
117 function getAtom(environmentKey: string) {
118 return snapshotsAtom(environmentKey);
119 }
120
121 function refresh(environmentIds: ReadonlyArray<EnvironmentId>): void {
122 config.getRegistry().refresh(getAtom(makeArchivedThreadsEnvironmentKey(environmentIds)));
123 }
124
125 function refreshForEnvironment(environmentId: EnvironmentId): void {
126 for (const environmentKey of knownEnvironmentKeys) {
127 if (knownEnvironmentIdsByKey.get(environmentKey)?.has(environmentId)) {
128 config.getRegistry().refresh(getAtom(environmentKey));
129 }
130 }
131 }
132
133 return {
134 getAtom,
135 refresh,
136 refreshForEnvironment,
137 };
138}