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