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

archivedThreads.ts

68 lines2.3 KB

1import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts";
2import * as Arr from "effect/Array";
3import { pipe } from "effect/Function";
4import * as Order from "effect/Order";
5import { AsyncResult, Atom } from "effect/reactivity";
6​
7export interface ArchivedSnapshotEntry {
8 readonly environmentId: EnvironmentId;
9 readonly snapshot: OrchestrationV2ArchivedShellSnapshot;
11​
12export interface ArchivedThreadSnapshotsState {
13 readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
14 readonly error: string | null;
15 readonly isLoading: boolean;
17​
18const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
19const environmentIdOrder = Order.String as Order.Order<EnvironmentId>;
20​
21export function makeArchivedThreadsEnvironmentKey(
22 environmentIds: ReadonlyArray<EnvironmentId>,
23): string {
24 return pipe(environmentIds, Arr.sort(environmentIdOrder), (sortedEnvironmentIds) =>
25 sortedEnvironmentIds.join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR),
26 );
28​
29function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<EnvironmentId> {
30 if (key.length === 0) {
31 return [];
32 }
33 return pipe(
34 key.split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR),
35 Arr.map((environmentId) => EnvironmentId.make(environmentId)),
36 );
38​
39export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
40 readonly getSnapshotAtom: (
41 environmentId: EnvironmentId,
42 ) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2ArchivedShellSnapshot, E>>;
43 readonly labelPrefix: string;
44}) {
45 return Atom.family((environmentKey: string) =>
46 Atom.make((get): ArchivedThreadSnapshotsState => {
47 const snapshots: ArchivedSnapshotEntry[] = [];
48 let error: string | null = null;
49 let isLoading = false;
50​
51 for (const environmentId of parseArchivedThreadsEnvironmentKey(environmentKey)) {
52 const result = get(options.getSnapshotAtom(environmentId));
53 isLoading ||= result.waiting;
54​
55 const snapshot = AsyncResult.getOrElse(result, () => null);
56 if (snapshot !== null) {
57 snapshots.push({ environmentId, snapshot });
58 }
59​
60 if (error === null && result._tag === "Failure") {
61 error = "Failed to load archived threads.";
62 }
63 }
64​
65 return { snapshots, error, isLoading };
66 }).pipe(Atom.withLabel(`${options.labelPrefix}:${environmentKey}`)),
67 );