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

ProviderSessionDirectory.ts

212 lines7.6 KB

1import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7​
8import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
9import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
10import {
11 ProviderSessionDirectory,
12 type ProviderRuntimeBinding,
13 type ProviderRuntimeBindingWithMetadata,
14 type ProviderSessionDirectoryShape,
15} from "../Services/ProviderSessionDirectory.ts";
16const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
17​
18function toPersistenceError(operation: string) {
19 return (cause: unknown) =>
20 new ProviderSessionDirectoryPersistenceError({
21 operation,
22 detail: `Failed to execute ${operation}.`,
23 cause,
24 });
26​
27function decodeProviderDriverKind(
28 providerName: string,
29 operation: string,
30): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
31 return decodeProviderDriverKindValue(providerName).pipe(
32 Effect.mapError(
33 (cause) =>
34 new ProviderSessionDirectoryPersistenceError({
35 operation,
36 detail: `Unknown persisted provider '${providerName}'.`,
37 cause,
38 }),
39 ),
40 );
42​
43function isRecord(value: unknown): value is Record<string, unknown> {
44 return value !== null && typeof value === "object" && !Array.isArray(value);
46​
47function mergeRuntimePayload(
48 existing: unknown | null,
49 next: unknown | null | undefined,
50): unknown | null {
51 if (next === undefined) {
52 return existing ?? null;
53 }
54 if (isRecord(existing) && isRecord(next)) {
55 return { ...existing, ...next };
56 }
57 return next;
59​
60function toRuntimeBinding(
61 runtime: ProviderSessionRuntime.ProviderSessionRuntime,
62 operation: string,
63): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
64 return decodeProviderDriverKind(runtime.providerName, operation).pipe(
65 Effect.map(
66 (provider) =>
67 ({
68 threadId: runtime.threadId,
69 provider,
70 // Migration boundary only: rows written before the instance split
71 // have a null provider_instance_id. Promote them as they leave
72 // persistence so hot routing code never has to infer an instance
73 // from a driver kind.
74 providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),
75 adapterKey: runtime.adapterKey,
76 runtimeMode: runtime.runtimeMode,
77 status: runtime.status,
78 resumeCursor: runtime.resumeCursor,
79 runtimePayload: runtime.runtimePayload,
80 lastSeenAt: runtime.lastSeenAt,
81 }) satisfies ProviderRuntimeBindingWithMetadata,
82 ),
83 );
85​
86const makeProviderSessionDirectory = Effect.gen(function* () {
87 const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
88​
89 const getBinding = (threadId: ThreadId) =>
90 repository.getByThreadId({ threadId }).pipe(
91 Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")),
92 Effect.flatMap((runtime) =>
93 Option.match(runtime, {
94 onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
95 onSome: (value) =>
96 toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
97 Effect.map((binding) => Option.some(binding)),
98 ),
99 }),
100 ),
101 );
102​
103 const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) {
104 const existing = yield* repository
105 .getByThreadId({ threadId: binding.threadId })
106 .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
107​
108 const existingRuntime = Option.getOrUndefined(existing);
109 const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;
110 if (!resolvedThreadId) {
111 return yield* new ProviderValidationError({
112 operation: "ProviderSessionDirectory.upsert",
113 issue: "threadId must be a non-empty string.",
114 });
115 }
116​
117 const now = DateTime.formatIso(yield* DateTime.now);
118 const providerChanged =
119 existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
120 const providerInstanceId =
121 binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);
122 if (providerInstanceId === null || providerInstanceId === undefined) {
123 return yield* new ProviderValidationError({
124 operation: "ProviderSessionDirectory.upsert",
125 issue: "providerInstanceId is required for provider session runtime bindings.",
126 });
127 }
128 yield* repository
129 .upsert({
130 threadId: resolvedThreadId,
131 providerName: binding.provider,
132 providerInstanceId,
133 adapterKey:
134 binding.adapterKey ??
135 (providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
136 runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
137 status: binding.status ?? existingRuntime?.status ?? "running",
138 lastSeenAt: now,
139 resumeCursor:
140 binding.resumeCursor !== undefined
141 ? binding.resumeCursor
142 : (existingRuntime?.resumeCursor ?? null),
143 runtimePayload: mergeRuntimePayload(
144 existingRuntime?.runtimePayload ?? null,
145 binding.runtimePayload,
146 ),
147 })
148 .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
149 });
150​
151 const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) =>
152 getBinding(threadId).pipe(
153 Effect.flatMap((binding) =>
154 Option.match(binding, {
155 onSome: (value) => Effect.succeed(value.provider),
156 onNone: () =>
157 Effect.fail(
158 new ProviderSessionDirectoryPersistenceError({
159 operation: "ProviderSessionDirectory.getProvider",
160 detail: `No persisted provider binding found for thread '${threadId}'.`,
161 }),
162 ),
163 }),
164 ),
165 );
166​
167 const updateResumeCursorIfCurrentInstance: ProviderSessionDirectoryShape["updateResumeCursorIfCurrentInstance"] =
168 Effect.fn(function* (input) {
169 const lastSeenAt = DateTime.formatIso(yield* DateTime.now);
170 return yield* repository
171 .updateResumeCursorIfCurrentInstance({ ...input, lastSeenAt })
172 .pipe(
173 Effect.mapError(
174 toPersistenceError(
175 "ProviderSessionDirectory.updateResumeCursorIfCurrentInstance:update",
176 ),
177 ),
178 );
179 });
180​
181 const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
182 repository.list().pipe(
183 Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
184 Effect.map((rows) => rows.map((row) => row.threadId)),
185 );
186​
187 const listBindings: ProviderSessionDirectoryShape["listBindings"] = () =>
188 repository.list().pipe(
189 Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
190 Effect.flatMap((rows) =>
191 Effect.forEach(
192 rows,
193 (row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
194 { concurrency: "unbounded" },
195 ),
196 ),
197 );
198​
199 return {
200 upsert,
201 getProvider,
202 getBinding,
203 updateResumeCursorIfCurrentInstance,
204 listThreadIds,
205 listBindings,
206 } satisfies ProviderSessionDirectoryShape;
207});
208​
209export const ProviderSessionDirectoryLive = Layer.effect(
210 ProviderSessionDirectory,
211 makeProviderSessionDirectory,
212);