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

archivedThreadsState.ts

106 lines3.6 KB

1import { useAtomValue } from "@effect/atom-react";
2import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
3import { AsyncResult, Atom } from "effect/unstable/reactivity";
4import { useCallback, useMemo } from "react";
5import * as Cause from "effect/Cause";
6import * as Effect from "effect/Effect";
7import * as Option from "effect/Option";
8import { readEnvironmentApi } from "../environmentApi";
9import { appAtomRegistry } from "../rpc/atomRegistry";
10​
11const ARCHIVED_THREADS_STALE_TIME_MS = 5_000;
12const ARCHIVED_THREADS_IDLE_TTL_MS = 5 * 60_000;
13const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
14​
15export type ArchivedSnapshotEntry = {
16 readonly environmentId: EnvironmentId;
17 readonly snapshot: OrchestrationShellSnapshot;
18};
19​
20const knownArchivedThreadEnvironmentKeys = new Set<string>();
21​
22function makeArchivedThreadsEnvironmentKey(environmentIds: ReadonlyArray<EnvironmentId>): string {
23 return environmentIds.toSorted().join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR);
25​
26function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<EnvironmentId> {
27 if (key.length === 0) {
28 return [];
29 }
30 return key
31 .split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR)
32 .map((environmentId) => EnvironmentId.make(environmentId));
34​
35const archivedThreadSnapshotsAtom = Atom.family((environmentKey: string) => {
36 knownArchivedThreadEnvironmentKeys.add(environmentKey);
37 return Atom.make(
38 Effect.promise(async (): Promise<ReadonlyArray<ArchivedSnapshotEntry>> => {
39 const environmentIds = parseArchivedThreadsEnvironmentKey(environmentKey);
40 const snapshots = await Promise.all(
41 environmentIds.map(async (environmentId) => {
42 const api = readEnvironmentApi(environmentId);
43 if (!api) {
44 return null;
45 }
46 return {
47 environmentId,
48 snapshot: await api.orchestration.getArchivedShellSnapshot(),
49 };
50 }),
51 );
52 return snapshots.filter((snapshot) => snapshot !== null);
53 }),
54 ).pipe(
55 Atom.swr({
56 staleTime: ARCHIVED_THREADS_STALE_TIME_MS,
57 revalidateOnMount: true,
58 }),
59 Atom.setIdleTTL(ARCHIVED_THREADS_IDLE_TTL_MS),
60 Atom.withLabel(`archived-thread-snapshots:${environmentKey}`),
61 );
62});
63​
64function readArchivedThreadsError(
65 result: AsyncResult.AsyncResult<ReadonlyArray<ArchivedSnapshotEntry>, unknown>,
66): string | null {
67 if (result._tag !== "Failure") {
68 return null;
69 }
70​
71 const error = Cause.squash(result.cause);
72 return error instanceof Error ? error.message : "Failed to load archived threads.";
74​
75export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
76 for (const key of knownArchivedThreadEnvironmentKeys) {
77 if (parseArchivedThreadsEnvironmentKey(key).includes(environmentId)) {
78 appAtomRegistry.refresh(archivedThreadSnapshotsAtom(key));
79 }
80 }
82​
83export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
84 readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
85 readonly error: string | null;
86 readonly isLoading: boolean;
87 readonly refresh: () => void;
88} {
89 const environmentKey = useMemo(
90 () => makeArchivedThreadsEnvironmentKey(environmentIds),
91 [environmentIds],
92 );
93 const atom = archivedThreadSnapshotsAtom(environmentKey);
94 const result = useAtomValue(atom);
95 const snapshots = Option.getOrElse(AsyncResult.value(result), () => []);
96 const refresh = useCallback(() => {
97 appAtomRegistry.refresh(atom);
98 }, [atom]);
99​
100 return {
101 snapshots,
102 error: readArchivedThreadsError(result),
103 isLoading: result.waiting,
104 refresh,
105 };