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 = <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.Effect<
80 | { readonly kind: "live"; readonly live: LiveEntry }
81 | { readonly kind: "unavailable"; readonly snapshot: ServerProvider },
82 never,
83 R
84> =>
85 Effect.gen(function* () {
86 const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;
87 const driver = driversById.get(entry.driver);
88 if (!driver) {
89 return {
90 kind: "unavailable" as const,
91 snapshot: yield* buildUnavailableProviderSnapshot({
92 driverKind: entry.driver,
93 instanceId,
94 displayName: entry.displayName,
95 accentColor: entry.accentColor,
96 reason: `Driver '${entry.driver}' is not registered in this build.`,
97 }),
98 };
99 }
100
101 const decoder = Schema.decodeUnknownEffect(driver.configSchema);
102 const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
103 if (decodeResult._tag === "Failure") {
104 const issue = decodeResult.failure;
105 const detail = issue.message ?? String(issue);
106 yield* Effect.logError("Failed to decode provider instance config", {
107 instanceId: rawInstanceId,
108 driver: entry.driver,
109 detail,
110 });
111 return {
112 kind: "unavailable" as const,
113 snapshot: yield* buildUnavailableProviderSnapshot({
114 driverKind: entry.driver,
115 instanceId,
116 displayName: entry.displayName,
117 accentColor: entry.accentColor,
118 reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
119 }),
120 };
121 }
122
123 const typedConfig = decodeResult.success;
124 const childScope = yield* Scope.make();
125 yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));
126
127 const createResult = yield* driver
128 .create({
129 instanceId,
130 displayName: entry.displayName,
131 accentColor: entry.accentColor,
132 environment: entry.environment ?? [],
133 enabled: resolveEntryEnabled(entry, typedConfig),
134 config: typedConfig,
135 })
136 .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);
137 if (createResult._tag === "Failure") {
138 yield* Effect.logError("Failed to create provider instance", {
139 instanceId: rawInstanceId,
140 driver: entry.driver,
141 detail: createResult.failure.detail,
142 });
143 yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
144 return {
145 kind: "unavailable" as const,
146 snapshot: yield* buildUnavailableProviderSnapshot({
147 driverKind: entry.driver,
148 instanceId,
149 displayName: entry.displayName,
150 accentColor: entry.accentColor,
151 reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
152 }),
153 };
154 }
155
156 return {
157 kind: "live" as const,
158 live: {
159 instance: createResult.success,
160 scope: childScope,
161 entry,
162 },
163 };
164 });
165
166const makeReconcile = <R>(input: {
167 readonly state: RegistryState;
168 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
169 readonly parentScope: Scope.Scope;
170}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {
171 const { state, driversById, parentScope } = input;
172 return (configMap: ProviderInstanceConfigMap) =>
173 Effect.gen(function* () {
174 const previousEntries = yield* Ref.get(state.entries);
175 const previousUnavailable = yield* Ref.get(state.unavailable);
176 const nextRaw = Object.entries(configMap);
177 const nextKeys = new Set<ProviderInstanceId>(
178 nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),
179 );
180
181 // 1. Close scopes for instances that disappeared or whose config
182 // changed. Do this BEFORE creating replacements so ids map 1-to-1
183 // to live scopes at all times.
184 const removedIds: Array<ProviderInstanceId> = [];
185 const replacedIds = new Set<ProviderInstanceId>();
186 for (const [instanceId, live] of previousEntries) {
187 if (!nextKeys.has(instanceId)) {
188 removedIds.push(instanceId);
189 continue;
190 }
191 const nextEntry = configMap[instanceId];
192 if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {
193 replacedIds.add(instanceId);
194 }
195 }
196 for (const id of [...removedIds, ...replacedIds]) {
197 const live = previousEntries.get(id);
198 if (live) {
199 yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);
200 }
201 }
202
203 const builtEntries = new Map<ProviderInstanceId, LiveEntry>();
204 const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();
205 let orderChanged = false;
206 const previousOrder = [...previousEntries.keys()];
207 const nextOrder: Array<ProviderInstanceId> = [];
208
209 for (const [rawInstanceId, entry] of nextRaw) {
210 const instanceId = ProviderInstanceId.make(rawInstanceId);
211 nextOrder.push(instanceId);
212
213 const existing = previousEntries.get(instanceId);
214 if (existing !== undefined && !replacedIds.has(instanceId)) {
215 builtEntries.set(instanceId, existing);
216 continue;
217 }
218
219 const result = yield* buildEntry({
220 driversById,
221 parentScope,
222 instanceId,
223 rawInstanceId,
224 entry,
225 });
226 if (result.kind === "live") {
227 builtEntries.set(instanceId, result.live);
228 } else {
229 builtUnavailable.set(instanceId, result.snapshot);
230 }
231 }
232
233 if (previousOrder.length === nextOrder.length) {
234 for (let i = 0; i < previousOrder.length; i++) {
235 if (previousOrder[i] !== nextOrder[i]) {
236 orderChanged = true;
237 break;
238 }
239 }
240 } else {
241 orderChanged = true;
242 }
243
244 const entriesChanged =
245 orderChanged ||
246 removedIds.length > 0 ||
247 replacedIds.size > 0 ||
248 builtEntries.size !== previousEntries.size;
249 const unavailableChanged =
250 builtUnavailable.size !== previousUnavailable.size ||
251 [...builtUnavailable].some(([id, snapshot]) => {
252 const prev = previousUnavailable.get(id);
253 return prev === undefined || !Equal.equals(prev, snapshot);
254 }) ||
255 [...previousUnavailable].some(([id]) => !builtUnavailable.has(id));
256
257 yield* Ref.set(state.entries, builtEntries);
258 yield* Ref.set(state.unavailable, builtUnavailable);
259
260 if (entriesChanged || unavailableChanged) {
261 yield* PubSub.publish(state.changes, undefined);
262 }
263 });
264};
265
266export const makeProviderInstanceRegistry = <R>(input: {
267 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
268 readonly configMap: ProviderInstanceConfigMap;
269}): Effect.Effect<
270 {
271 readonly registry: ProviderInstanceRegistry["Service"];
272 readonly mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape;
273 },
274 never,
275 R | Scope.Scope
276> =>
277 Effect.gen(function* () {
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 >;