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

ProviderInstanceRegistryLive.ts

434 lines17.1 KB

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