Open History to see the last commit
1import {
2 EnvironmentId,
3 OrchestrationSearchThreadsInput,
4 type OrchestrationSearchThreadsResult,
5 type OrchestrationThreadSearchMatch,
6} from "@t3tools/contracts";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import { AsyncResult, Atom } from "effect/reactivity";
10
11export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchMatch {
12 readonly environmentId: EnvironmentId;
13}
14
15export interface ThreadSearchResultsState {
16 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
17 readonly isLoading: boolean;
18}
19
20const ThreadSearchKey = Schema.fromJsonString(
21 Schema.Tuple([Schema.Array(EnvironmentId), OrchestrationSearchThreadsInput.fields.query]),
22);
23const decodeThreadSearchKey = Schema.decodeUnknownOption(ThreadSearchKey);
24
25export function makeThreadSearchKey(
26 environmentIds: ReadonlyArray<EnvironmentId>,
27 query: string,
28): string {
29 return JSON.stringify([
30 [...environmentIds].sort((left, right) => left.localeCompare(right)),
31 query,
32 ]);
33}
34
35function parseThreadSearchKey(key: string) {
36 return decodeThreadSearchKey(key);
37}
38
39export function threadSearchMatchKey(
40 match: Pick<EnvironmentThreadSearchMatch, "environmentId" | "threadId">,
41): string {
42 return JSON.stringify([match.environmentId, match.threadId]);
43}
44
45export function createThreadSearchResultsAtomFamily<E>(options: {
46 readonly getSearchAtom: (
47 environmentId: EnvironmentId,
48 query: string,
49 ) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationSearchThreadsResult, E>>;
50 readonly labelPrefix: string;
51}) {
52 return Atom.family((key: string) =>
53 Atom.make((get): ThreadSearchResultsState => {
54 const parsedKey = parseThreadSearchKey(key);
55 if (Option.isNone(parsedKey)) {
56 return { matches: [], isLoading: false };
57 }
58
59 const [environmentIds, query] = parsedKey.value;
60 const matches: EnvironmentThreadSearchMatch[] = [];
61 let isLoading = false;
62
63 for (const environmentId of environmentIds) {
64 const result = get(options.getSearchAtom(environmentId, query));
65 isLoading ||= result.waiting;
66 const value = Option.getOrNull(AsyncResult.value(result));
67 if (value !== null) {
68 matches.push(
69 ...value.matches.map((match) => ({
70 ...match,
71 environmentId,
72 })),
73 );
74 }
75 }
76
77 return { matches, isLoading };
78 }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)),
79 );
80}