Open History to see the last commit
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 * 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 yield* serverSettings.streamChanges.pipe(
122 Stream.runForEach((next) =>
123 mutator
124 .reconcile(deriveProviderInstanceConfigMap(next))
125 .pipe(
126 Effect.catchCause((cause) =>
127 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
128 ),
129 ),
130 ),
131 Effect.forkScoped,
132 );
133 }),
134);
135
136/**
137 * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
138 * sync with subsequent `streamChanges` emissions.
139 *
140 * The Layer's two halves:
141 * - `ProviderInstanceRegistryMutableLayer` produces the registry +
142 * mutator from the initial config map. Its scope owns every
143 * per-instance child scope created during reconcile.
144 * - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber
145 * in the same scope.
146 *
147 * Composing via `Layer.provideMerge` makes the watcher's deps available
148 * from the mutable layer while still surfacing the registry as an output.
149 * The mutator tag is technically also exposed; only this module imports
150 * it, so the visibility leak is harmless in practice.
151 */
152export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
153 ProviderInstanceRegistry,
154 never,
155 BuiltInDriversEnv | ServerSettingsService
156> = Layer.unwrap(
157 Effect.gen(function* () {
158 const serverSettings = yield* ServerSettingsService;
159 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
160 Effect.orElseSucceed(() => undefined),
161 );
162 const initialConfigMap =
163 initialSettings === undefined
164 ? ({} as ProviderInstanceConfigMap)
165 : deriveProviderInstanceConfigMap(initialSettings);
166
167 const mutableLayer = ProviderInstanceRegistryMutableLayer({
168 drivers: BUILT_IN_DRIVERS,
169 configMap: initialConfigMap,
170 });
171
172 return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
173 }),
174) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;