Open History to see the last commit
1/**
2 * ProviderInstanceRegistryLive — runtime implementation of
3 * `ProviderInstanceRegistry` plus its sibling mutator.
4 *
5 * Materializes every entry in a `ProviderInstanceConfigMap`:
6 *
7 * - When the entry's `driver` matches a registered driver, the registry
8 * decodes the opaque `config` envelope through `driver.configSchema`
9 * and calls `driver.create()` inside a fresh child scope. The
10 * resulting `ProviderInstance` is stored keyed by instance id,
11 * alongside its scope so the entry can be torn down independently.
12 * - When the entry's `driver` is unknown to this build (fork, rollback,
13 * in-flight PR branch), the registry emits an `"unavailable"` shadow
14 * `ServerProvider` snapshot instead of failing. This is what makes
15 * downgrades and fork-hopping safe per the
16 * `forward/backward compatibility invariant` in
17 * `packages/contracts/src/providerInstance.ts`.
18 * - When the entry's config fails schema decode, the registry logs and
19 * emits a shadow snapshot with the schema detail — same bucket as an
20 * unknown driver.
21 *
22 * Unlike the pre-Slice-D layer, the registry now holds mutable state
23 * (`Ref`s + `PubSub`) and exposes an internal mutator
24 * (`ProviderInstanceRegistryMutator`) whose `reconcile` method diffs a
25 * fresh config map against the live state, tearing down removed instances
26 * and building new ones without disturbing unaffected instances.
27 *
28 * Every live instance runs inside its own child `Scope`. The registry's
29 * own scope owns all child scopes via finalizers, so closing the registry
30 * tears every instance down in reverse order; closing a single instance
31 * (via `reconcile` removing it) leaves the rest untouched.
32 *
33 * @module provider/Layers/ProviderInstanceRegistryLive
34 */
35import {
36 defaultInstanceIdForDriver,
37 ProviderInstanceId,
38 type ProviderInstanceConfig,
39 type ProviderInstanceConfigMap,
40 type ProviderDriverKind,
41 type ServerProvider,
42} from "@t3tools/contracts";
43import * as Context from "effect/Context";
44import * as Effect from "effect/Effect";
45import * as Equal from "effect/Equal";
46import * as Exit from "effect/Exit";
47import * as Layer from "effect/Layer";
48import * as PubSub from "effect/PubSub";
49import * as Ref from "effect/Ref";
50import * as Schema from "effect/Schema";
51import * as Scope from "effect/Scope";
52import * as Stream from "effect/Stream";
53
54import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
55import {
56 ProviderInstanceRegistry,
57 type ProviderInstanceRegistryShape,
58} from "../Services/ProviderInstanceRegistry.ts";
59import {
60 ProviderInstanceRegistryMutator,
61 type ProviderInstanceRegistryMutatorShape,
62} from "../Services/ProviderInstanceRegistryMutator.ts";
63import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
64
65/**
66 * Live registry entry: the materialized `ProviderInstance` + the fresh
67 * child scope its `create` effect ran in + the original `entry` envelope
68 * so `reconcile` can cheaply detect "no-op" updates.
69 */
70interface LiveEntry {
71 readonly instance: ProviderInstance;
72 readonly scope: Scope.Closeable;
73 readonly entry: ProviderInstanceConfig;
74}
75
76/**
77 * Internal state shared between the public registry service and the
78 * mutator service. Both services are thin shells around these refs.
79 */
80interface RegistryState {
81 readonly entries: Ref.Ref<ReadonlyMap<ProviderInstanceId, LiveEntry>>;
82 readonly unavailable: Ref.Ref<ReadonlyMap<ProviderInstanceId, ServerProvider>>;
83 readonly changes: PubSub.PubSub<void>;
84}
85
86/**
87 * Structural equality on `ProviderInstanceConfig` envelopes. Used by
88 * `reconcile` to skip rebuilds when settings arrive unchanged. Config
89 * payloads are opaque `unknown` at the envelope layer; `Equal.equals`
90 * falls back to structural equality for plain records, which matches how
91 * the schema decode output is constructed.
92 */
93const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
94 Equal.equals(a, b);
95
96const decodedConfigEnabled = (config: unknown): boolean | undefined => {
97 if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) {
98 return undefined;
99 }
100 const enabled = (config as { readonly enabled?: unknown }).enabled;
101 return typeof enabled === "boolean" ? enabled : undefined;
102};
103
104/**
105 * Build one live entry from a raw config envelope. Returns either a
106 * `LiveEntry` plus undefined unavailable shadow, or a shadow snapshot and
107 * undefined entry — callers dispatch to the appropriate Ref bucket.
108 */
109const buildEntry = <R>(input: {
110 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
111 readonly parentScope: Scope.Scope;
112 readonly instanceId: ProviderInstanceId;
113 readonly rawInstanceId: string;
114 readonly entry: ProviderInstanceConfig;
115}): Effect.Effect<
116 | { readonly kind: "live"; readonly live: LiveEntry }
117 | { readonly kind: "unavailable"; readonly snapshot: ServerProvider },
118 never,
119 R
120> =>
121 Effect.gen(function* () {
122 const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;
123 const driver = driversById.get(entry.driver);
124 if (!driver) {
125 return {
126 kind: "unavailable" as const,
127 snapshot: yield* buildUnavailableProviderSnapshot({
128 driverKind: entry.driver,
129 instanceId,
130 displayName: entry.displayName,
131 accentColor: entry.accentColor,
132 reason: `Driver '${entry.driver}' is not registered in this build.`,
133 }),
134 };
135 }
136
137 const decoder = Schema.decodeUnknownEffect(driver.configSchema);
138 const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
139 if (decodeResult._tag === "Failure") {
140 const issue = decodeResult.failure;
141 const detail = issue.message ?? String(issue);
142 yield* Effect.logError("Failed to decode provider instance config", {
143 instanceId: rawInstanceId,
144 driver: entry.driver,
145 detail,
146 });
147 return {
148 kind: "unavailable" as const,
149 snapshot: yield* buildUnavailableProviderSnapshot({
150 driverKind: entry.driver,
151 instanceId,
152 displayName: entry.displayName,
153 accentColor: entry.accentColor,
154 reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
155 }),
156 };
157 }
158
159 const typedConfig = decodeResult.success;
160 const childScope = yield* Scope.make();
161 // Attach the child scope to the registry's parent scope: if the
162 // registry scope closes, each surviving instance's child scope is
163 // closed through this finalizer. `reconcile` manually closes the
164 // child scope on remove/replace; subsequent close via the parent's
165 // finalizer is a no-op because `Scope.close` is idempotent.
166 yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));
167
168 const createResult = yield* driver
169 .create({
170 instanceId,
171 displayName: entry.displayName,
172 accentColor: entry.accentColor,
173 environment: entry.environment ?? [],
174 enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,
175 config: typedConfig,
176 })
177 .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);
178 if (createResult._tag === "Failure") {
179 yield* Effect.logError("Failed to create provider instance", {
180 instanceId: rawInstanceId,
181 driver: entry.driver,
182 detail: createResult.failure.detail,
183 });
184 yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
185 return {
186 kind: "unavailable" as const,
187 snapshot: yield* buildUnavailableProviderSnapshot({
188 driverKind: entry.driver,
189 instanceId,
190 displayName: entry.displayName,
191 accentColor: entry.accentColor,
192 reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
193 }),
194 };
195 }
196
197 return {
198 kind: "live" as const,
199 live: {
200 instance: createResult.success,
201 scope: childScope,
202 entry,
203 },
204 };
205 });
206
207/**
208 * Reconcile-only implementation of the mutator. Exposed to the hydration
209 * layer; never called directly by the rest of the server.
210 */
211const makeReconcile = <R>(input: {
212 readonly state: RegistryState;
213 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
214 readonly parentScope: Scope.Scope;
215}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {
216 const { state, driversById, parentScope } = input;
217 return (configMap: ProviderInstanceConfigMap) =>
218 Effect.gen(function* () {
219 const previousEntries = yield* Ref.get(state.entries);
220 const previousUnavailable = yield* Ref.get(state.unavailable);
221 const nextRaw = Object.entries(configMap);
222 const nextKeys = new Set<ProviderInstanceId>(
223 nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),
224 );
225
226 // 1. Close scopes for instances that disappeared or whose config
227 // changed. Do this BEFORE creating replacements so ids map 1-to-1
228 // to live scopes at all times.
229 const removedIds: Array<ProviderInstanceId> = [];
230 const replacedIds = new Set<ProviderInstanceId>();
231 for (const [instanceId, live] of previousEntries) {
232 if (!nextKeys.has(instanceId)) {
233 removedIds.push(instanceId);
234 continue;
235 }
236 const nextEntry = configMap[instanceId];
237 if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {
238 replacedIds.add(instanceId);
239 }
240 }
241 for (const id of [...removedIds, ...replacedIds]) {
242 const live = previousEntries.get(id);
243 if (live) {
244 yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);
245 }
246 }
247
248 // 2. Build additions and replacements. Walk `nextRaw` so the final
249 // entry order follows settings-author order.
250 const builtEntries = new Map<ProviderInstanceId, LiveEntry>();
251 const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();
252 let orderChanged = false;
253 const previousOrder = [...previousEntries.keys()];
254 const nextOrder: Array<ProviderInstanceId> = [];
255
256 for (const [rawInstanceId, entry] of nextRaw) {
257 const instanceId = ProviderInstanceId.make(rawInstanceId);
258 nextOrder.push(instanceId);
259
260 const existing = previousEntries.get(instanceId);
261 if (existing !== undefined && !replacedIds.has(instanceId)) {
262 // No-op update: keep the existing live entry and scope.
263 builtEntries.set(instanceId, existing);
264 continue;
265 }
266
267 const result = yield* buildEntry({
268 driversById,
269 parentScope,
270 instanceId,
271 rawInstanceId,
272 entry,
273 });
274 if (result.kind === "live") {
275 builtEntries.set(instanceId, result.live);
276 } else {
277 builtUnavailable.set(instanceId, result.snapshot);
278 }
279 }
280
281 if (previousOrder.length === nextOrder.length) {
282 for (let i = 0; i < previousOrder.length; i++) {
283 if (previousOrder[i] !== nextOrder[i]) {
284 orderChanged = true;
285 break;
286 }
287 }
288 } else {
289 orderChanged = true;
290 }
291
292 const entriesChanged =
293 orderChanged ||
294 removedIds.length > 0 ||
295 replacedIds.size > 0 ||
296 builtEntries.size !== previousEntries.size;
297 const unavailableChanged =
298 builtUnavailable.size !== previousUnavailable.size ||
299 [...builtUnavailable].some(([id, snapshot]) => {
300 const prev = previousUnavailable.get(id);
301 return prev === undefined || !Equal.equals(prev, snapshot);
302 }) ||
303 [...previousUnavailable].some(([id]) => !builtUnavailable.has(id));
304
305 yield* Ref.set(state.entries, builtEntries);
306 yield* Ref.set(state.unavailable, builtUnavailable);
307
308 if (entriesChanged || unavailableChanged) {
309 yield* PubSub.publish(state.changes, undefined);
310 }
311 });
312};
313
314/**
315 * Build the registry's runtime state from a concrete configMap. Returns a
316 * record containing:
317 *
318 * - `registry`: the read-only `ProviderInstanceRegistryShape` to expose
319 * under `ProviderInstanceRegistry`.
320 * - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose
321 * under `ProviderInstanceRegistryMutator`.
322 * - `reconcile`: the raw reconcile function, provided for convenience so
323 * boot-time layers can hydrate an initial map before publishing the
324 * services.
325 *
326 * The scope that this effect runs in owns every per-instance child scope
327 * created during `reconcile`. Closing that scope closes every live
328 * instance.
329 */
330export const makeProviderInstanceRegistry = <R>(input: {
331 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
332 readonly configMap: ProviderInstanceConfigMap;
333}): Effect.Effect<
334 {
335 readonly registry: ProviderInstanceRegistryShape;
336 readonly mutator: ProviderInstanceRegistryMutatorShape;
337 },
338 never,
339 R | Scope.Scope
340> =>
341 Effect.gen(function* () {
342 const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(
343 input.drivers.map((driver) => [driver.driverKind, driver]),
344 );
345
346 // Capture the enclosing scope so per-instance child scopes can be
347 // attached to it at `reconcile` time. Without this, `reconcile`
348 // called later (e.g. from the hydration layer) would attach child
349 // scopes to the *caller's* scope instead of the registry's.
350 const parentScope = yield* Scope.Scope;
351
352 // Capture the driver R context at construction time so `reconcile`
353 // can be invoked later without re-providing driver dependencies.
354 // The service tag's declared `reconcile: Effect<void>` hides R from
355 // consumers — we materialize that here.
356 const driverContext = yield* Effect.context<R>();
357
358 const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());
359 const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());
360 const changes = yield* PubSub.unbounded<void>();
361 yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
362
363 const state: RegistryState = { entries, unavailable, changes };
364 const reconcileWithR = makeReconcile({ state, driversById, parentScope });
365 const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>
366 reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
367
368 // Hydrate the initial configMap synchronously so callers can read
369 // `listInstances` immediately after this effect completes.
370 yield* reconcile(input.configMap);
371
372 const registry: ProviderInstanceRegistryShape = {
373 getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
374 listInstances: Ref.get(entries).pipe(
375 Effect.map(
376 (map) =>
377 Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,
378 ),
379 ),
380 listUnavailable: Ref.get(unavailable).pipe(
381 Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),
382 ),
383 // Getters: each read constructs a fresh Stream / Effect descriptor
384 // so multiple consumers don't share a single already-started
385 // Channel or subscription. Matches the pattern `ProviderRegistry`
386 // uses for its own `streamChanges`.
387 get streamChanges() {
388 return Stream.fromPubSub(changes);
389 },
390 // Synchronous subscribe — callers that need to consume changes
391 // from a forked fibre must acquire the subscription in their own
392 // fibre first (via `yield* registry.subscribeChanges`) and only
393 // then fork a consumer loop on `Stream.fromSubscription(...)` /
394 // `PubSub.take(...)`. See the shape docs for the race this avoids.
395 get subscribeChanges() {
396 return PubSub.subscribe(changes);
397 },
398 };
399
400 const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };
401
402 return { registry, mutator };
403 });
404
405/**
406 * Assemble a `ProviderInstanceRegistry` Layer bound to a fixed set of
407 * drivers and a pre-resolved `ProviderInstanceConfigMap`. Used by tests
408 * that want explicit control over the registry's source-of-truth without
409 * wiring up the settings watcher.
410 *
411 * Only exposes the public registry tag — hot-reload consumers should use
412 * `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.
413 */
414export const ProviderInstanceRegistryLayer = <R>(input: {
415 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
416 readonly configMap: ProviderInstanceConfigMap;
417}): Layer.Layer<ProviderInstanceRegistry, never, R> =>
418 Layer.effect(
419 ProviderInstanceRegistry,
420 makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),
421 ) as Layer.Layer<ProviderInstanceRegistry, never, R>;
422
423/**
424 * Layer variant that also exposes the mutator tag. Consumed by
425 * `ProviderInstanceRegistryHydrationLive` to reconcile on settings
426 * changes. Tests that exercise the mutator directly can pair this Layer
427 * with a test-local `ServerSettingsService`.
428 */
429export const ProviderInstanceRegistryMutableLayer = <R>(input: {
430 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
431 readonly configMap: ProviderInstanceConfigMap;
432}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>
433 Layer.effectContext(
434 makeProviderInstanceRegistry(input).pipe(
435 Effect.map(({ registry, mutator }) =>
436 Context.make(ProviderInstanceRegistry, registry).pipe(
437 Context.add(ProviderInstanceRegistryMutator, mutator),
438 ),
439 ),
440 ),
441 ) as Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R>;
442
443export { defaultInstanceIdForDriver };