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

threadHistoryController.ts

86 lines3.0 KB

1import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Ref from "effect/Ref";
6​
7import { threadKey } from "./entities.ts";
8​
9export type ThreadHistoryLoadEarlierResult =
10 | { readonly _tag: "loaded" }
11 | { readonly _tag: "noop" }
12 | { readonly _tag: "busy" }
13 | { readonly _tag: "error"; readonly message: string };
14​
15export type ThreadHistoryHandler = {
16 readonly loadEarlier: (throughEntryId?: string) => Effect.Effect<ThreadHistoryLoadEarlierResult>;
17};
18​
19export type ThreadHistoryRegistration = {
20 readonly environmentId: EnvironmentId;
21 readonly threadId: ThreadId;
22 readonly handler: ThreadHistoryHandler;
23};
24​
25export class ThreadHistoryController extends Context.Service<
26 ThreadHistoryController,
27 {
28 readonly register: (
29 environmentId: EnvironmentId,
30 threadId: ThreadId,
31 handler: ThreadHistoryHandler,
32 ) => Effect.Effect<ThreadHistoryRegistration>;
33 readonly unregister: (registration: ThreadHistoryRegistration) => Effect.Effect<void>;
34 readonly loadEarlier: (
35 environmentId: EnvironmentId,
36 threadId: ThreadId,
37 throughEntryId?: string,
38 ) => Effect.Effect<ThreadHistoryLoadEarlierResult>;
39 }
40>()("@t3tools/client-runtime/state/threadHistoryController") {}
41​
42export const layer: Layer.Layer<ThreadHistoryController> = Layer.effect(
43 ThreadHistoryController,
44 Effect.gen(function* () {
45 const handlers = yield* Ref.make(new Map<string, ThreadHistoryHandler>());
46 return ThreadHistoryController.of({
47 register: (environmentId, threadId, handler) =>
48 Ref.update(handlers, (current) => {
49 const next = new Map(current);
50 next.set(threadKey({ environmentId, threadId }), handler);
51 return next;
52 }).pipe(
53 Effect.as({
54 environmentId,
55 threadId,
56 handler,
57 } satisfies ThreadHistoryRegistration),
58 ),
59 unregister: (registration) =>
60 Ref.update(handlers, (current) => {
61 const key = threadKey({
62 environmentId: registration.environmentId,
63 threadId: registration.threadId,
64 });
65 // Only remove when this registration still owns the slot. An older
66 // fiber finalizer must not delete a newer handler for the same key.
67 if (current.get(key) !== registration.handler) {
68 return current;
69 }
70 const next = new Map(current);
71 next.delete(key);
72 return next;
73 }),
74 loadEarlier: (environmentId, threadId, throughEntryId) =>
75 Ref.get(handlers).pipe(
76 Effect.flatMap((current) => {
77 const handler = current.get(threadKey({ environmentId, threadId }));
78 if (handler === undefined) {
79 return Effect.succeed({ _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult);
80 }
81 return handler.loadEarlier(throughEntryId);
82 }),
83 ),
84 });
85 }),
86);