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

ProviderInstanceRegistryHydration.ts

175 lines7.2 KB

1/**
2 * ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap`
3 * from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it.
4 *
5 * The server still reads two shapes:
6 *
7 * 1. `settings.providerInstances` — the new driver-agnostic map the
8 * registry expects. Keyed by `ProviderInstanceId`, values are
9 * `ProviderInstanceConfig` envelopes.
10 * 2. `settings.providers.<kind>` — the legacy single-instance-per-driver
11 * fields (`providers.codex`, `providers.claudeAgent`, …). These are
12 * the source of truth for every deployment that hasn't been migrated
13 * yet to an explicit `providerInstances` entry.
14 *
15 * This module bridges (2) into (1) and wires the resulting map into a
16 * mutable registry. For every built-in driver whose id is not already
17 * present in `providerInstances` (keyed on
18 * `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a
19 * routing slug), we synthesize an envelope from the legacy field. The
20 * registry decodes both flavours through the same `configSchema` and ends
21 * up with one uniform `ProviderInstance` per entry.
22 *
23 * Explicit `providerInstances` entries always win — users can already
24 * override the legacy `providers.<kind>` blob by authoring a
25 * `providerInstances.codex` entry with a matching driver, and we don't
26 * want the synthesized envelope to silently stomp their config.
27 *
28 * Hot-reload
29 * ----------
30 * On layer build we:
31 * 1. Read the current `ServerSettings` once and use it to seed the
32 * registry's initial state via `ProviderInstanceRegistryMutableLayer`.
33 * 2. Fork a daemon fiber (lifetime tied to the layer's scope) that
34 * acquires `ServerSettingsService.subscribeChanges` and calls
35 * `ProviderInstanceRegistryMutator.reconcile` on every emission.
36 *
37 * Failures inside the watcher are logged and swallowed so a single bad
38 * settings emission cannot kill the registry. Unknown drivers and invalid
39 * configs already round-trip through the registry's own "unavailable"
40 * shadow bucket.
41 *
42 * @module provider/Layers/ProviderInstanceRegistryHydration
43 */
44import {
45 defaultInstanceIdForDriver,
46 type ProviderInstanceConfig,
47 type ProviderInstanceConfigMap,
48 ServerSettings,
49} from "@t3tools/contracts";
50import * as Effect from "effect/Effect";
51import * as Layer from "effect/Layer";
52import * as Stream from "effect/Stream";
53​
54import { ServerSettingsService } from "../../serverSettings.ts";
55import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
56import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
57import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
58import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
59​
60/**
61 * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
62 *
63 * Strategy:
64 * 1. Copy all explicit `settings.providerInstances` entries verbatim.
65 * 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
66 * is *not* already in the explicit map, synthesize an entry from the
67 * matching legacy `settings.providers.<kind>` blob.
68 *
69 * The returned map is the input the registry consumes; pure & exported
70 * separately so the hydration logic can be exercised by unit tests
71 * without layering.
72 */
73export const deriveProviderInstanceConfigMap = (
74 settings: ServerSettings,
75): ProviderInstanceConfigMap => {
76 const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
77​
78 for (const driver of BUILT_IN_DRIVERS) {
79 const instanceId = defaultInstanceIdForDriver(driver.driverKind);
80 if (instanceId in merged) {
81 // Explicit `providerInstances` entry for this slot — user-authored
82 // config always wins over the legacy mirror.
83 continue;
84 }
85​
86 // Only built-in drivers have a legacy mirror; the registry's
87 // `providers` struct is keyed on the same literal slug as
88 // `driverKind`. Access is dynamic (the driver kind is a branded string),
89 // but it's constrained to `keyof settings.providers` by the union of
90 // built-in driver kinds.
91 const legacyKey = driver.driverKind as keyof ServerSettings["providers"];
92 const legacyConfig = settings.providers[legacyKey];
93 if (legacyConfig === undefined) {
94 continue;
95 }
96​
97 merged[instanceId] = {
98 driver: driver.driverKind,
99 config: legacyConfig,
100 };
101 }
102​
103 return merged as ProviderInstanceConfigMap;
104};
105​
106/**
107 * Layer that consumes `ProviderInstanceRegistryMutator` and forks a
108 * settings-watcher fiber. The fiber's lifetime is tied to the enclosing
109 * layer scope (process lifetime in production), so it is interrupted on
110 * shutdown without leaking.
111 *
112 * Errors inside the watcher are logged and swallowed — the registry's own
113 * "unavailable" bucket already absorbs unknown drivers and invalid
114 * configs, so the only way the watcher could fail is a settings stream
115 * tear-down, which logs and exits cleanly.
116 */
117const SettingsWatcherLive = Layer.effectDiscard(
118 Effect.gen(function* () {
119 const mutator = yield* ProviderInstanceRegistryMutator;
120 const serverSettings = yield* ServerSettingsService;
121 const settingsChanges = yield* serverSettings.subscribeChanges;
122 yield* settingsChanges.pipe(
123 Stream.runForEach((next) =>
124 mutator
125 .reconcile(deriveProviderInstanceConfigMap(next))
126 .pipe(
127 Effect.catchCause((cause) =>
128 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
129 ),
130 ),
131 ),
132 Effect.forkScoped,
133 );
134 }),
135);
136​
137/**
138 * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
139 * sync with subsequent `streamChanges` emissions.
140 *
141 * The Layer's two halves:
142 * - `ProviderInstanceRegistryMutableLayer` produces the registry +
143 * mutator from the initial config map. Its scope owns every
144 * per-instance child scope created during reconcile.
145 * - `SettingsWatcherLive` consumes the mutator, acquires its settings
146 * subscription before forking, and runs a daemon fiber in the same scope.
147 *
148 * Composing via `Layer.provideMerge` makes the watcher's deps available
149 * from the mutable layer while still surfacing the registry as an output.
150 * The mutator tag is technically also exposed; only this module imports
151 * it, so the visibility leak is harmless in practice.
152 */
153export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
154 ProviderInstanceRegistry,
155 never,
156 BuiltInDriversEnv | ServerSettingsService
157> = Layer.unwrap(
158 Effect.gen(function* () {
159 const serverSettings = yield* ServerSettingsService;
160 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
161 Effect.orElseSucceed(() => undefined),
162 );
163 const initialConfigMap =
164 initialSettings === undefined
165 ? ({} as ProviderInstanceConfigMap)
166 : deriveProviderInstanceConfigMap(initialSettings);
167​
168 const mutableLayer = ProviderInstanceRegistryMutableLayer({
169 drivers: BUILT_IN_DRIVERS,
170 configMap: initialConfigMap,
171 });
172​
173 return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
174 }),
175) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;