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