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 providerInstanceConfigEnabledFlag,
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
96/**
97 * Resolve an entry's enabled state. An explicit false on either the
98 * envelope or the raw config blob wins (most restrictive) — old settings
99 * files can carry both flags with conflicting values, and a user's disable
100 * must never be silently undone. Otherwise the envelope flag wins, then the
101 * decoded config's flag (which carries the driver schema's default for
102 * built-ins and forks alike), then enabled by default.
103 */
104const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown): boolean => {
105 const rawConfigEnabled = providerInstanceConfigEnabledFlag(entry.config);
106 if (entry.enabled === false || rawConfigEnabled === false) {
107 return false;
108 }
109 return entry.enabled ?? providerInstanceConfigEnabledFlag(typedConfig) ?? true;
110};
111
112/**
113 * Build one live entry from a raw config envelope. Returns either a
114 * `LiveEntry` plus undefined unavailable shadow, or a shadow snapshot and
115 * undefined entry — callers dispatch to the appropriate Ref bucket.
116 */
117const buildEntry = <R>(input: {
118 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
119 readonly parentScope: Scope.Scope;
120 readonly instanceId: ProviderInstanceId;
121 readonly rawInstanceId: string;
122 readonly entry: ProviderInstanceConfig;
123}): Effect.Effect<
124 | { readonly kind: "live"; readonly live: LiveEntry }
125 | { readonly kind: "unavailable"; readonly snapshot: ServerProvider },
126 never,
127 R
128> =>
129 Effect.gen(function* () {
130 const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;
131 const driver = driversById.get(entry.driver);
132 if (!driver) {
133 return {
134 kind: "unavailable" as const,
135 snapshot: yield* buildUnavailableProviderSnapshot({
136 driverKind: entry.driver,
137 instanceId,
138 displayName: entry.displayName,
139 accentColor: entry.accentColor,
140 reason: `Driver '${entry.driver}' is not registered in this build.`,
141 }),
142 };
143 }
144
145 const decoder = Schema.decodeUnknownEffect(driver.configSchema);
146 const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
147 if (decodeResult._tag === "Failure") {
148 const issue = decodeResult.failure;
149 const detail = issue.message ?? String(issue);
150 yield* Effect.logError("Failed to decode provider instance config", {
151 instanceId: rawInstanceId,
152 driver: entry.driver,
153 detail,
154 });
155 return {
156 kind: "unavailable" as const,
157 snapshot: yield* buildUnavailableProviderSnapshot({
158 driverKind: entry.driver,
159 instanceId,
160 displayName: entry.displayName,
161 accentColor: entry.accentColor,
162 reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
163 }),
164 };
165 }
166
167 const typedConfig = decodeResult.success;
168 const childScope = yield* Scope.make();
169 // Attach the child scope to the registry's parent scope: if the
170 // registry scope closes, each surviving instance's child scope is
171 // closed through this finalizer. `reconcile` manually closes the
172 // child scope on remove/replace; subsequent close via the parent's
173 // finalizer is a no-op because `Scope.close` is idempotent.
174 yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));
175
176 const createResult = yield* driver
177 .create({
178 instanceId,
179 displayName: entry.displayName,
180 accentColor: entry.accentColor,
181 environment: entry.environment ?? [],
182 enabled: resolveEntryEnabled(entry, typedConfig),
183 config: typedConfig,
184 })
185 .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);
186 if (createResult._tag === "Failure") {
187 yield* Effect.logError("Failed to create provider instance", {
188 instanceId: rawInstanceId,
189 driver: entry.driver,
190 detail: createResult.failure.detail,
191 });
192 yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
193 return {
194 kind: "unavailable" as const,
195 snapshot: yield* buildUnavailableProviderSnapshot({
196 driverKind: entry.driver,
197 instanceId,
198 displayName: entry.displayName,
199 accentColor: entry.accentColor,
200 reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
201 }),
202 };
203 }
204
205 return {
206 kind: "live" as const,
207 live: {
208 instance: createResult.success,
209 scope: childScope,
210 entry,
211 },
212 };
213 });
214
215/**
216 * Reconcile-only implementation of the mutator. Exposed to the hydration
217 * layer; never called directly by the rest of the server.
218 */
219const makeReconcile = <R>(input: {
220 readonly state: RegistryState;
221 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
222 readonly parentScope: Scope.Scope;
223}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {
224 const { state, driversById, parentScope } = input;
225 return (configMap: ProviderInstanceConfigMap) =>
226 Effect.gen(function* () {
227 const previousEntries = yield* Ref.get(state.entries);
228 const previousUnavailable = yield* Ref.get(state.unavailable);
229 const nextRaw = Object.entries(configMap);
230 const nextKeys = new Set<ProviderInstanceId>(
231 nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),
232 );
233
234 // 1. Close scopes for instances that disappeared or whose config
235 // changed. Do this BEFORE creating replacements so ids map 1-to-1
236 // to live scopes at all times.
237 const removedIds: Array<ProviderInstanceId> = [];
238 const replacedIds = new Set<ProviderInstanceId>();
239 for (const [instanceId, live] of previousEntries) {
240 if (!nextKeys.has(instanceId)) {
241 removedIds.push(instanceId);
242 continue;
243 }
244 const nextEntry = configMap[instanceId];
245 if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {
246 replacedIds.add(instanceId);
247 }
248 }
249 for (const id of [...removedIds, ...replacedIds]) {
250 const live = previousEntries.get(id);
251 if (live) {
252 yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);
253 }
254 }
255
256 // 2. Build additions and replacements. Walk `nextRaw` so the final
257 // entry order follows settings-author order.
258 const builtEntries = new Map<ProviderInstanceId, LiveEntry>();
259 const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();
260 let orderChanged = false;
261 const previousOrder = [...previousEntries.keys()];
262 const nextOrder: Array<ProviderInstanceId> = [];
263
264 for (const [rawInstanceId, entry] of nextRaw) {
265 const instanceId = ProviderInstanceId.make(rawInstanceId);
266 nextOrder.push(instanceId);
267
268 const existing = previousEntries.get(instanceId);
269 if (existing !== undefined && !replacedIds.has(instanceId)) {
270 // No-op update: keep the existing live entry and scope.
271 builtEntries.set(instanceId, existing);
272 continue;
273 }
274
275 const result = yield* buildEntry({
276 driversById,
277 parentScope,
278 instanceId,
279 rawInstanceId,
280 entry,
281 });
282 if (result.kind === "live") {
283 builtEntries.set(instanceId, result.live);
284 } else {
285 builtUnavailable.set(instanceId, result.snapshot);
286 }
287 }
288
289 if (previousOrder.length === nextOrder.length) {
290 for (let i = 0; i < previousOrder.length; i++) {
291 if (previousOrder[i] !== nextOrder[i]) {
292 orderChanged = true;
293 break;
294 }
295 }
296 } else {
297 orderChanged = true;
298 }
299
300 const entriesChanged =
301 orderChanged ||
302 removedIds.length > 0 ||
303 replacedIds.size > 0 ||
304 builtEntries.size !== previousEntries.size;
305 const unavailableChanged =
306 builtUnavailable.size !== previousUnavailable.size ||
307 [...builtUnavailable].some(([id, snapshot]) => {
308 const prev = previousUnavailable.get(id);
309 return prev === undefined || !Equal.equals(prev, snapshot);
310 }) ||
311 [...previousUnavailable].some(([id]) => !builtUnavailable.has(id));
312
313 yield* Ref.set(state.entries, builtEntries);
314 yield* Ref.set(state.unavailable, builtUnavailable);
315
316 if (entriesChanged || unavailableChanged) {
317 yield* PubSub.publish(state.changes, undefined);
318 }
319 });
320};
321
322/**
323 * Build the registry's runtime state from a concrete configMap. Returns a
324 * record containing:
325 *
326 * - `registry`: the read-only `ProviderInstanceRegistryShape` to expose
327 * under `ProviderInstanceRegistry`.
328 * - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose
329 * under `ProviderInstanceRegistryMutator`.
330 * - `reconcile`: the raw reconcile function, provided for convenience so
331 * boot-time layers can hydrate an initial map before publishing the
332 * services.
333 *
334 * The scope that this effect runs in owns every per-instance child scope
335 * created during `reconcile`. Closing that scope closes every live
336 * instance.
337 */
338export const makeProviderInstanceRegistry = <R>(input: {
339 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
340 readonly configMap: ProviderInstanceConfigMap;
341}): Effect.Effect<
342 {
343 readonly registry: ProviderInstanceRegistryShape;
344 readonly mutator: ProviderInstanceRegistryMutatorShape;
345 },
346 never,
347 R | Scope.Scope
348> =>
349 Effect.gen(function* () {
350 const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(
351 input.drivers.map((driver) => [driver.driverKind, driver]),
352 );
353
354 // Capture the enclosing scope so per-instance child scopes can be
355 // attached to it at `reconcile` time. Without this, `reconcile`
356 // called later (e.g. from the hydration layer) would attach child
357 // scopes to the *caller's* scope instead of the registry's.
358 const parentScope = yield* Scope.Scope;
359
360 // Capture the driver R context at construction time so `reconcile`
361 // can be invoked later without re-providing driver dependencies.
362 // The service tag's declared `reconcile: Effect<void>` hides R from
363 // consumers — we materialize that here.
364 const driverContext = yield* Effect.context<R>();
365
366 const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());
367 const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());
368 const changes = yield* PubSub.unbounded<void>();
369 yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
370
371 const state: RegistryState = { entries, unavailable, changes };
372 const reconcileWithR = makeReconcile({ state, driversById, parentScope });
373 const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>
374 reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
375
376 // Hydrate the initial configMap synchronously so callers can read
377 // `listInstances` immediately after this effect completes.
378 yield* reconcile(input.configMap);
379
380 const registry: ProviderInstanceRegistryShape = {
381 getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
382 listInstances: Ref.get(entries).pipe(
383 Effect.map(
384 (map) =>
385 Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,
386 ),
387 ),
388 listUnavailable: Ref.get(unavailable).pipe(
389 Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),
390 ),
391 // Getters: each read constructs a fresh Stream / Effect descriptor
392 // so multiple consumers don't share a single already-started
393 // Channel or subscription. Matches the pattern `ProviderRegistry`
394 // uses for its own `streamChanges`.
395 get streamChanges() {
396 return Stream.fromPubSub(changes);
397 },
398 // Synchronous subscribe — callers that need to consume changes
399 // from a forked fibre must acquire the subscription in their own
400 // fibre first (via `yield* registry.subscribeChanges`) and only
401 // then fork a consumer loop on `Stream.fromSubscription(...)` /
402 // `PubSub.take(...)`. See the shape docs for the race this avoids.
403 get subscribeChanges() {
404 return PubSub.subscribe(changes);
405 },
406 };
407
408 const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };
409
410 return { registry, mutator };
411 });
412
413/**
414 * Layer variant that also exposes the mutator tag. Consumed by
415 * `ProviderInstanceRegistryHydrationLive` to reconcile on settings
416 * changes. Tests that exercise the mutator directly can pair this Layer
417 * with a test-local `ServerSettingsService`.
418 */
419export const ProviderInstanceRegistryMutableLayer = <R>(input: {
420 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
421 readonly configMap: ProviderInstanceConfigMap;
422}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>
423 Layer.effectContext(
424 makeProviderInstanceRegistry(input).pipe(
425 Effect.map(({ registry, mutator }) =>
426 Context.make(ProviderInstanceRegistry, registry).pipe(
427 Context.add(ProviderInstanceRegistryMutator, mutator),
428 ),
429 ),
430 ),
431 ) as Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R>;