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 * `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 "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
42import * as ProviderHostLive from "./ProviderHostLive.ts";
43import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
44import type * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
45import type * as ServerConfig from "../config.ts";
46
47type ProviderInstanceRegistryHydrationEnv =
48 | Exclude<
49 BuiltInDriversEnv,
50 | ProviderOrchestrationAdapterInfrastructure.ProviderOrchestrationAdapterInfrastructure
51 | AcpRegistrySupport.AcpRegistryCatalog
52 | ProviderHost.ProviderHost
53 >
54 | Settings.ServerSettingsService
55 // Requirements of the `ProviderHost.ProviderHost` the drivers receive.
56 | BackgroundPolicy.BackgroundPolicy
57 | ServerConfig.ServerConfig;
58
59/**
60 * Explicit `providerInstances` entries plus an implicit default instance for
61 * each built-in driver whose default slot is empty. Pure so the hydration
62 * rule can be tested without layers.
63 */
64export const deriveProviderInstanceConfigMap = (
65 settings: ServerSettings,
66): ProviderInstanceConfigMap => {
67 const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
68
69 for (const driver of BUILT_IN_DRIVERS) {
70 if (driver.metadata.hasDefaultInstance === false) continue;
71 const instanceId = defaultInstanceIdForDriver(driver.driverKind);
72 if (instanceId in merged) continue;
73 merged[instanceId] = { driver: driver.driverKind };
74 }
75
76 return merged as ProviderInstanceConfigMap;
77};
78
79/**
80 * Layer that consumes `ProviderInstanceRegistryMutator` and forks a
81 * settings-watcher fiber. The fiber's lifetime is tied to the enclosing
82 * layer scope (process lifetime in production), so it is interrupted on
83 * shutdown without leaking.
84 *
85 * Errors inside the watcher are logged and swallowed — the registry's own
86 * "unavailable" bucket already absorbs unknown drivers and invalid
87 * configs, so the only way the watcher could fail is a settings stream
88 * tear-down, which logs and exits cleanly.
89 */
90const layerSettingsWatcher = Layer.effectDiscard(
91 Effect.gen(function* () {
92 const mutator = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator;
93 const serverSettings = yield* Settings.ServerSettingsService;
94 const settingsChanges = yield* serverSettings.subscribeChanges;
95 yield* settingsChanges.pipe(
96 Stream.runForEach((next) =>
97 mutator
98 .reconcile(deriveProviderInstanceConfigMap(next))
99 .pipe(
100 Effect.catchCause((cause) =>
101 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
102 ),
103 ),
104 ),
105 Effect.forkScoped,
106 );
107 }),
108);
109
110/**
111 * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
112 * sync with subsequent `streamChanges` emissions.
113 *
114 * The Layer's two halves:
115 * - `ProviderInstanceRegistry.layer` produces the registry +
116 * mutator from the initial config map. Its scope owns every
117 * per-instance child scope created during reconcile.
118 * - `SettingsWatcherLive` consumes the mutator, acquires its settings
119 * subscription before forking, and runs a daemon fiber in the same scope.
120 *
121 * Composing via `Layer.provideMerge` makes the watcher's deps available
122 * from the mutable layer while still surfacing the registry as an output.
123 * The mutator tag is technically also exposed; only this module imports
124 * it, so the visibility leak is harmless in practice.
125 */
126export const layer: Layer.Layer<
127 ProviderInstanceRegistry.ProviderInstanceRegistry,
128 never,
129 ProviderInstanceRegistryHydrationEnv
130> = Layer.unwrap(
131 Effect.gen(function* () {
132 const serverSettings = yield* Settings.ServerSettingsService;
133 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
134 Effect.orElseSucceed(() => undefined),
135 );
136 const initialConfigMap =
137 initialSettings === undefined
138 ? ({} as ProviderInstanceConfigMap)
139 : deriveProviderInstanceConfigMap(initialSettings);
140
141 const layerMutable = ProviderInstanceRegistry.layer({
142 drivers: BUILT_IN_DRIVERS,
143 configMap: initialConfigMap,
144 }).pipe(
145 Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer),
146 Layer.provide(AcpRegistrySupport.layerFromHost),
147 Layer.provide(ProviderHostLive.layer),
148 );
149
150 return layerSettingsWatcher.pipe(Layer.provideMerge(layerMutable));
151 }),
152) as Layer.Layer<
153 ProviderInstanceRegistry.ProviderInstanceRegistry,
154 never,
155 ProviderInstanceRegistryHydrationEnv
156>;