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

ProviderInstanceRegistry.ts

335 lines12.0 KB

1import {
2 providerInstanceConfigEnabledFlag,
3 ProviderInstanceId,
4 type ProviderInstanceConfig,
5 type ProviderInstanceConfigMap,
6 type ProviderDriverKind,
7 type ServerProvider,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as Equal from "effect/Equal";
12import * as Exit from "effect/Exit";
13import * as Layer from "effect/Layer";
14import * as PubSub from "effect/PubSub";
15import * as Ref from "effect/Ref";
16import * as Schema from "effect/Schema";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19​
20import { buildUnavailableProviderSnapshot } from "./unavailableProviderSnapshot.ts";
21import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts";
22import type { AnyProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver";
23​
24export class ProviderInstanceRegistry extends Context.Service<
25 ProviderInstanceRegistry,
26 {
27 readonly getInstance: (
28 instanceId: ProviderInstanceId,
29 ) => Effect.Effect<ProviderInstance | undefined>;
30 readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;
31 readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;
32 /** streamChanges subscribes on consumption; use subscribeChanges before forking to avoid missing the next publish. */
33 readonly streamChanges: Stream.Stream<void>;
34 readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
35 }
36>()("t3/provider/ProviderInstanceRegistry") {}
37​
38interface LiveEntry {
39 readonly instance: ProviderInstance;
40 readonly scope: Scope.Closeable;
41 readonly entry: ProviderInstanceConfig;
43​
44interface RegistryState {
45 readonly entries: Ref.Ref<ReadonlyMap<ProviderInstanceId, LiveEntry>>;
46 readonly unavailable: Ref.Ref<ReadonlyMap<ProviderInstanceId, ServerProvider>>;
47 readonly changes: PubSub.PubSub<void>;
49​
50const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
51 Equal.equals(a, b);
52​
53/** Conflicting saved flags must preserve any explicit disable. */
54const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown): boolean => {
55 const rawConfigEnabled = providerInstanceConfigEnabledFlag(entry.config);
56 if (entry.enabled === false || rawConfigEnabled === false) {
57 return false;
58 }
59 return entry.enabled ?? providerInstanceConfigEnabledFlag(typedConfig) ?? true;
60};
61​
62const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R>(input: {
63 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
64 readonly parentScope: Scope.Scope;
65 readonly instanceId: ProviderInstanceId;
66 readonly rawInstanceId: string;
67 readonly entry: ProviderInstanceConfig;
68}): Effect.fn.Return<
69 | { readonly kind: "live"; readonly live: LiveEntry }
70 | { readonly kind: "unavailable"; readonly snapshot: ServerProvider },
71 never,
72 R
73> {
74 const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;
75 const driver = driversById.get(entry.driver);
76 if (!driver) {
77 return {
78 kind: "unavailable" as const,
79 snapshot: yield* buildUnavailableProviderSnapshot({
80 driverKind: entry.driver,
81 instanceId,
82 displayName: entry.displayName,
83 accentColor: entry.accentColor,
84 reason: `Driver '${entry.driver}' is not registered in this build.`,
85 }),
86 };
87 }
88​
89 const decoder = Schema.decodeUnknownEffect(driver.configSchema);
90 const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
91 if (decodeResult._tag === "Failure") {
92 const issue = decodeResult.failure;
93 const detail = issue.message ?? String(issue);
94 yield* Effect.logError("Failed to decode provider instance config", {
95 instanceId: rawInstanceId,
96 driver: entry.driver,
97 detail,
98 });
99 return {
100 kind: "unavailable" as const,
101 snapshot: yield* buildUnavailableProviderSnapshot({
102 driverKind: entry.driver,
103 instanceId,
104 displayName: entry.displayName,
105 accentColor: entry.accentColor,
106 reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
107 }),
108 };
109 }
110​
111 const typedConfig = decodeResult.success;
112 const childScope = yield* Scope.make();
113 yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));
114​
115 const createResult = yield* driver
116 .create({
117 instanceId,
118 displayName: entry.displayName,
119 accentColor: entry.accentColor,
120 environment: entry.environment ?? [],
121 enabled: resolveEntryEnabled(entry, typedConfig),
122 config: typedConfig,
123 })
124 .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);
125 if (createResult._tag === "Failure") {
126 yield* Effect.logError("Failed to create provider instance", {
127 instanceId: rawInstanceId,
128 driver: entry.driver,
129 detail: createResult.failure.detail,
130 });
131 yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
132 return {
133 kind: "unavailable" as const,
134 snapshot: yield* buildUnavailableProviderSnapshot({
135 driverKind: entry.driver,
136 instanceId,
137 displayName: entry.displayName,
138 accentColor: entry.accentColor,
139 reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
140 }),
141 };
142 }
143​
144 return {
145 kind: "live" as const,
146 live: {
147 instance: createResult.success,
148 scope: childScope,
149 entry,
150 },
151 };
152});
153​
154const makeReconcile = <R>(input: {
155 readonly state: RegistryState;
156 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
157 readonly parentScope: Scope.Scope;
158}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {
159 const { state, driversById, parentScope } = input;
160 return (configMap: ProviderInstanceConfigMap) =>
161 Effect.gen(function* () {
162 const previousEntries = yield* Ref.get(state.entries);
163 const previousUnavailable = yield* Ref.get(state.unavailable);
164 const nextRaw = Object.entries(configMap);
165 const nextKeys = new Set<ProviderInstanceId>(
166 nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),
167 );
168​
169 // Close changed/removed scopes before replacements to preserve one live scope per id.
170 const removedIds: Array<ProviderInstanceId> = [];
171 const replacedIds = new Set<ProviderInstanceId>();
172 for (const [instanceId, live] of previousEntries) {
173 if (!nextKeys.has(instanceId)) {
174 removedIds.push(instanceId);
175 continue;
176 }
177 const nextEntry = configMap[instanceId];
178 if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {
179 replacedIds.add(instanceId);
180 }
181 }
182 for (const id of [...removedIds, ...replacedIds]) {
183 const live = previousEntries.get(id);
184 if (live) {
185 yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);
186 }
187 }
188​
189 const builtEntries = new Map<ProviderInstanceId, LiveEntry>();
190 const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();
191 let orderChanged = false;
192 const previousOrder = [...previousEntries.keys()];
193 const nextOrder: Array<ProviderInstanceId> = [];
194​
195 for (const [rawInstanceId, entry] of nextRaw) {
196 const instanceId = ProviderInstanceId.make(rawInstanceId);
197 nextOrder.push(instanceId);
198​
199 const existing = previousEntries.get(instanceId);
200 if (existing !== undefined && !replacedIds.has(instanceId)) {
201 builtEntries.set(instanceId, existing);
202 continue;
203 }
204​
205 const result = yield* buildEntry({
206 driversById,
207 parentScope,
208 instanceId,
209 rawInstanceId,
210 entry,
211 });
212 if (result.kind === "live") {
213 builtEntries.set(instanceId, result.live);
214 } else {
215 builtUnavailable.set(instanceId, result.snapshot);
216 }
217 }
218​
219 if (previousOrder.length === nextOrder.length) {
220 for (let i = 0; i < previousOrder.length; i++) {
221 if (previousOrder[i] !== nextOrder[i]) {
222 orderChanged = true;
223 break;
224 }
225 }
226 } else {
227 orderChanged = true;
228 }
229​
230 const entriesChanged =
231 orderChanged ||
232 removedIds.length > 0 ||
233 replacedIds.size > 0 ||
234 builtEntries.size !== previousEntries.size;
235 const unavailableChanged =
236 builtUnavailable.size !== previousUnavailable.size ||
237 [...builtUnavailable].some(([id, snapshot]) => {
238 const prev = previousUnavailable.get(id);
239 return prev === undefined || !Equal.equals(prev, snapshot);
240 }) ||
241 [...previousUnavailable].some(([id]) => !builtUnavailable.has(id));
242​
243 yield* Ref.set(state.entries, builtEntries);
244 yield* Ref.set(state.unavailable, builtUnavailable);
245​
246 if (entriesChanged || unavailableChanged) {
247 yield* PubSub.publish(state.changes, undefined);
248 }
249 });
250};
251​
252export const makeProviderInstanceRegistry = Effect.fn(
253 "ProviderInstanceRegistry.makeProviderInstanceRegistry",
254)(function* <R>(input: {
255 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
256 readonly configMap: ProviderInstanceConfigMap;
257}): Effect.fn.Return<
258 {
259 readonly registry: ProviderInstanceRegistry["Service"];
260 readonly mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape;
261 },
262 never,
263 R | Scope.Scope
264> {
265 const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(
266 input.drivers.map((driver) => [driver.driverKind, driver]),
267 );
268​
269 // Capture the enclosing scope so per-instance child scopes can be
270 // attached to it at `reconcile` time. Without this, `reconcile`
271 // called later (e.g. from the hydration layer) would attach child
272 // scopes to the *caller's* scope instead of the registry's.
273 const parentScope = yield* Scope.Scope;
274​
275 const driverContext = yield* Effect.context<R>();
276​
277 const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());
278 const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());
279 const changes = yield* PubSub.unbounded<void>();
280 yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
281​
282 const state: RegistryState = { entries, unavailable, changes };
283 const reconcileWithR = makeReconcile({ state, driversById, parentScope });
284 const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] =
285 (configMap) => reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
286​
287 yield* reconcile(input.configMap);
288​
289 const registry: ProviderInstanceRegistry["Service"] = {
290 getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
291 listInstances: Ref.get(entries).pipe(
292 Effect.map(
293 (map) =>
294 Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,
295 ),
296 ),
297 listUnavailable: Ref.get(unavailable).pipe(
298 Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),
299 ),
300 get streamChanges() {
301 return Stream.fromPubSub(changes);
302 },
303 get subscribeChanges() {
304 return PubSub.subscribe(changes);
305 },
306 };
307​
308 const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = {
309 reconcile,
310 };
311​
312 return { registry, mutator };
313});
314​
315export const layer = <R>(input: {
316 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
317 readonly configMap: ProviderInstanceConfigMap;
318}): Layer.Layer<
319 ProviderInstanceRegistry | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
320 never,
321 R
322> =>
323 Layer.effectContext(
324 makeProviderInstanceRegistry(input).pipe(
325 Effect.map(({ registry, mutator }) =>
326 Context.make(ProviderInstanceRegistry, registry).pipe(
327 Context.add(ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, mutator),
328 ),
329 ),
330 ),
331 ) as Layer.Layer<
332 ProviderInstanceRegistry | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
333 never,
334 R
335 >;