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

ProviderInstanceRegistryHydration.ts

176 lines7.1 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 * subscribes to `ServerSettingsService.streamChanges` 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 { Effect, Layer, Stream } from "effect";
51​
52import { ServerSettingsService } from "../../serverSettings.ts";
53import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
54import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
55import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
56import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
57​
58/**
59 * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
60 *
61 * Strategy:
62 * 1. Copy all explicit `settings.providerInstances` entries verbatim.
63 * 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
64 * is *not* already in the explicit map, synthesize an entry from the
65 * matching legacy `settings.providers.<kind>` blob.
66 *
67 * The returned map is the input the registry consumes; pure & exported
68 * separately so the hydration logic can be exercised by unit tests
69 * without layering.
70 */
71export const deriveProviderInstanceConfigMap = (
72 settings: ServerSettings,
73): ProviderInstanceConfigMap => {
74 const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
75​
76 for (const driver of BUILT_IN_DRIVERS) {
77 const instanceId = defaultInstanceIdForDriver(driver.driverKind);
78 if (instanceId in merged) {
79 // Explicit `providerInstances` entry for this slot — user-authored
80 // config always wins over the legacy mirror.
81 continue;
82 }
83​
84 // Only built-in drivers have a legacy mirror; the registry's
85 // `providers` struct is keyed on the same literal slug as
86 // `driverKind`. Access is dynamic (the driver kind is a branded string),
87 // but it's constrained to `keyof settings.providers` by the union of
88 // built-in driver kinds.
89 const legacyKey = driver.driverKind as keyof ServerSettings["providers"];
90 const legacyConfig = settings.providers[legacyKey];
91 if (legacyConfig === undefined) {
92 continue;
93 }
94​
95 merged[instanceId] = {
96 driver: driver.driverKind,
97 config: legacyConfig,
98 };
99 }
100​
101 return merged as ProviderInstanceConfigMap;
102};
103​
104/**
105 * Layer that consumes `ProviderInstanceRegistryMutator` and forks a
106 * settings-watcher fiber. The fiber's lifetime is tied to the enclosing
107 * layer scope (process lifetime in production), so it is interrupted on
108 * shutdown without leaking.
109 *
110 * Errors inside the watcher are logged and swallowed — the registry's own
111 * "unavailable" bucket already absorbs unknown drivers and invalid
112 * configs, so the only way the watcher could fail is a settings stream
113 * tear-down, which logs and exits cleanly.
114 */
115const SettingsWatcherLive: Layer.Layer<
116 never,
117 never,
118 ProviderInstanceRegistryMutator | ServerSettingsService
119> = Layer.effectDiscard(
120 Effect.gen(function* () {
121 const mutator = yield* ProviderInstanceRegistryMutator;
122 const serverSettings = yield* ServerSettingsService;
123 yield* serverSettings.streamChanges.pipe(
124 Stream.runForEach((next) =>
125 mutator
126 .reconcile(deriveProviderInstanceConfigMap(next))
127 .pipe(
128 Effect.catchCause((cause) =>
129 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
130 ),
131 ),
132 ),
133 Effect.forkScoped,
134 );
135 }),
136);
137​
138/**
139 * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
140 * sync with subsequent `streamChanges` emissions.
141 *
142 * The Layer's two halves:
143 * - `ProviderInstanceRegistryMutableLayer` produces the registry +
144 * mutator from the initial config map. Its scope owns every
145 * per-instance child scope created during reconcile.
146 * - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber
147 * in the same scope.
148 *
149 * Composing via `Layer.provideMerge` makes the watcher's deps available
150 * from the mutable layer while still surfacing the registry as an output.
151 * The mutator tag is technically also exposed; only this module imports
152 * it, so the visibility leak is harmless in practice.
153 */
154export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
155 ProviderInstanceRegistry,
156 never,
157 BuiltInDriversEnv | ServerSettingsService
158> = Layer.unwrap(
159 Effect.gen(function* () {
160 const serverSettings = yield* ServerSettingsService;
161 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
162 Effect.orElseSucceed(() => undefined),
163 );
164 const initialConfigMap =
165 initialSettings === undefined
166 ? ({} as ProviderInstanceConfigMap)
167 : deriveProviderInstanceConfigMap(initialSettings);
168​
169 const mutableLayer = ProviderInstanceRegistryMutableLayer({
170 drivers: BUILT_IN_DRIVERS,
171 configMap: initialConfigMap,
172 });
173​
174 return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
175 }),
176) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;