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

ProviderInstanceRegistryLive.ts

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