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

ProviderInstanceRegistryHydration.ts

157 lines6.3 KB

1/**
2 * ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap`
3 * from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it.
4 *
5 * `settings.providerInstances` is the source of truth. Every built-in driver
6 * with a default instance also runs at `defaultInstanceIdForDriver(kind)`
7 * when that slot has no entry, using the driver's default config, so a fresh
8 * install shows its built-in providers without writing settings first.
9 *
10 * Hot-reload
11 * ----------
12 * On layer build we:
13 * 1. Read the current `ServerSettings` once and use it to seed the
14 * registry's initial state via `ProviderInstanceRegistry.layer`.
15 * 2. Fork a daemon fiber (lifetime tied to the layer's scope) that
16 * acquires `ServerSettingsService.subscribeChanges` and calls
17 * `ProviderInstanceRegistryMutator.reconcile` on every emission.
18 *
19 * Failures inside the watcher are logged and swallowed so a single bad
20 * settings emission cannot kill the registry. Unknown drivers and invalid
21 * configs already round-trip through the registry's own "unavailable"
22 * shadow bucket.
23 *
24 * @module provider/ProviderInstanceRegistryHydration
25 */
26import {
27 defaultInstanceIdForDriver,
28 type ProviderInstanceConfig,
29 type ProviderInstanceConfigMap,
30 ServerSettings,
31} from "@t3tools/contracts";
32import * as Effect from "effect/Effect";
33import * as Layer from "effect/Layer";
34import * as Stream from "effect/Stream";
35​
36import * as Settings from "../serverSettings.ts";
37import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "./builtInDrivers.ts";
38import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
39import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts";
40import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts";
41import * as AcpRegistrySupport from "./acp/AcpRegistrySupport.ts";
42import * as AcpRegistryCatalog from "./AcpRegistryCatalog.ts";
43import * as ProviderHostLive from "./ProviderHostLive.ts";
44import type { ProviderHost } from "@t3tools/provider-core/server/ProviderHost";
45import type * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
46import type * as ServerConfig from "../config.ts";
47​
48type ProviderInstanceRegistryHydrationEnv =
49 | Exclude<
50 BuiltInDriversEnv,
51 | ProviderOrchestrationAdapterInfrastructure.ProviderOrchestrationAdapterInfrastructure
52 | AcpRegistrySupport.AcpRegistryCatalog
53 | ProviderHost
54 >
55 | Settings.ServerSettingsService
56 // Requirements of the `ProviderHost` the drivers receive.
57 | BackgroundPolicy.BackgroundPolicy
58 | ServerConfig.ServerConfig;
59​
60/**
61 * Explicit `providerInstances` entries plus an implicit default instance for
62 * each built-in driver whose default slot is empty. Pure so the hydration
63 * rule can be tested without layers.
64 */
65export const deriveProviderInstanceConfigMap = (
66 settings: ServerSettings,
67): ProviderInstanceConfigMap => {
68 const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
69​
70 for (const driver of BUILT_IN_DRIVERS) {
71 if (driver.metadata.hasDefaultInstance === false) continue;
72 const instanceId = defaultInstanceIdForDriver(driver.driverKind);
73 if (instanceId in merged) continue;
74 merged[instanceId] = { driver: driver.driverKind };
75 }
76​
77 return merged as ProviderInstanceConfigMap;
78};
79​
80/**
81 * Layer that consumes `ProviderInstanceRegistryMutator` and forks a
82 * settings-watcher fiber. The fiber's lifetime is tied to the enclosing
83 * layer scope (process lifetime in production), so it is interrupted on
84 * shutdown without leaking.
85 *
86 * Errors inside the watcher are logged and swallowed — the registry's own
87 * "unavailable" bucket already absorbs unknown drivers and invalid
88 * configs, so the only way the watcher could fail is a settings stream
89 * tear-down, which logs and exits cleanly.
90 */
91const layerSettingsWatcher = Layer.effectDiscard(
92 Effect.gen(function* () {
93 const mutator = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator;
94 const serverSettings = yield* Settings.ServerSettingsService;
95 const settingsChanges = yield* serverSettings.subscribeChanges;
96 yield* settingsChanges.pipe(
97 Stream.runForEach((next) =>
98 mutator
99 .reconcile(deriveProviderInstanceConfigMap(next))
100 .pipe(
101 Effect.catchCause((cause) =>
102 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
103 ),
104 ),
105 ),
106 Effect.forkScoped,
107 );
108 }),
109);
110​
111/**
112 * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
113 * sync with subsequent `streamChanges` emissions.
114 *
115 * The Layer's two halves:
116 * - `ProviderInstanceRegistry.layer` produces the registry +
117 * mutator from the initial config map. Its scope owns every
118 * per-instance child scope created during reconcile.
119 * - `SettingsWatcherLive` consumes the mutator, acquires its settings
120 * subscription before forking, and runs a daemon fiber in the same scope.
121 *
122 * Composing via `Layer.provideMerge` makes the watcher's deps available
123 * from the mutable layer while still surfacing the registry as an output.
124 * The mutator tag is technically also exposed; only this module imports
125 * it, so the visibility leak is harmless in practice.
126 */
127export const layer: Layer.Layer<
128 ProviderInstanceRegistry.ProviderInstanceRegistry,
129 never,
130 ProviderInstanceRegistryHydrationEnv
131> = Layer.unwrap(
132 Effect.gen(function* () {
133 const serverSettings = yield* Settings.ServerSettingsService;
134 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
135 Effect.orElseSucceed(() => undefined),
136 );
137 const initialConfigMap =
138 initialSettings === undefined
139 ? ({} as ProviderInstanceConfigMap)
140 : deriveProviderInstanceConfigMap(initialSettings);
141​
142 const layerMutable = ProviderInstanceRegistry.layer({
143 drivers: BUILT_IN_DRIVERS,
144 configMap: initialConfigMap,
145 }).pipe(
146 Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer),
147 Layer.provide(AcpRegistryCatalog.layer),
148 Layer.provide(ProviderHostLive.layer),
149 );
150​
151 return layerSettingsWatcher.pipe(Layer.provideMerge(layerMutable));
152 }),
153) as Layer.Layer<
154 ProviderInstanceRegistry.ProviderInstanceRegistry,
155 never,
156 ProviderInstanceRegistryHydrationEnv
157>;