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

ProviderInstanceRegistryLive.ts

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