Open History to see the last commit
1/**
2 * ProviderRegistryLive — aggregates per-instance snapshot streams into a
3 * single materialized list.
4 *
5 * Historically this Layer composed four per-kind Live Layers
6 * (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
7 * `ServerProviderShape`. Those Lives were deleted during the driver /
8 * instance refactor — every driver now carries its `snapshot: ServerProviderShape`
9 * bundled onto the `ProviderInstance` the registry produces.
10 *
11 * Each configured instance (including multi-instance setups like
12 * `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
13 * keyed by `instanceId`. Instances whose driver is unavailable or whose
14 * config failed to decode are merged from `instanceRegistry.listUnavailable`
15 * as shadow snapshots so the UI can render their exact unavailable reason.
16 *
17 * Cache paths on disk are now keyed by `instanceId`. Because
18 * `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
19 * `<kind>.json` files remain the on-disk location for that driver's default
20 * instance. Identity-less legacy cache contents are ignored and replaced by
21 * the first live refresh.
22 *
23 * @module ProviderRegistryLive
24 */
25import {
26 defaultInstanceIdForDriver,
27 ProviderDriverKind,
28 type ProviderInstanceId,
29 type ServerProvider,
30 type ServerProviderUpdateState,
31} from "@t3tools/contracts";
32import * as Cause from "effect/Cause";
33import * as Effect from "effect/Effect";
34import * as Equal from "effect/Equal";
35import * as FileSystem from "effect/FileSystem";
36import * as Layer from "effect/Layer";
37import * as Path from "effect/Path";
38import * as PubSub from "effect/PubSub";
39import * as Ref from "effect/Ref";
40import * as Stream from "effect/Stream";
41import * as Semaphore from "effect/Semaphore";
42
43import { ServerConfig } from "../../config.ts";
44import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
45import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
46import {
47 hydrateCachedProvider,
48 isCachedProviderCorrelated,
49 orderProviderSnapshots,
50 readProviderStatusCache,
51 resolveProviderStatusCachePath,
52 writeProviderStatusCache,
53} from "../providerStatusCache.ts";
54import type { ProviderInstance } from "../ProviderDriver.ts";
55import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
56import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
57
58const loadProviders = (
59 providerSources: ReadonlyArray<ProviderSnapshotSource>,
60): Effect.Effect<ReadonlyArray<ServerProvider>> =>
61 Effect.forEach(
62 providerSources,
63 (providerSource) =>
64 providerSource.getSnapshot.pipe(
65 Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
66 ),
67 {
68 concurrency: "unbounded",
69 },
70 );
71
72const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
73 makeManualOnlyProviderMaintenanceCapabilities({
74 provider,
75 packageName: null,
76 });
77
78const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
79 (model.capabilities?.optionDescriptors?.length ?? 0) > 0;
80
81const mergeProviderModels = (
82 previousModels: ReadonlyArray<ServerProvider["models"][number]>,
83 nextModels: ReadonlyArray<ServerProvider["models"][number]>,
84): ReadonlyArray<ServerProvider["models"][number]> => {
85 if (nextModels.length === 0 && previousModels.length > 0) {
86 return previousModels;
87 }
88
89 const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
90 const mergedModels = nextModels.map((model) => {
91 const previousModel = previousBySlug.get(model.slug);
92 if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
93 return model;
94 }
95 return {
96 ...model,
97 capabilities: previousModel.capabilities,
98 };
99 });
100 const nextSlugs = new Set(nextModels.map((model) => model.slug));
101 return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
102};
103
104export const mergeProviderSnapshot = (
105 previousProvider: ServerProvider | undefined,
106 nextProvider: ServerProvider,
107): ServerProvider =>
108 !previousProvider
109 ? nextProvider
110 : {
111 ...nextProvider,
112 models: mergeProviderModels(previousProvider.models, nextProvider.models),
113 };
114
115export const mergeProviderSnapshots = (
116 previousProviders: ReadonlyArray<ServerProvider>,
117 nextProviders: ReadonlyArray<ServerProvider>,
118): ReadonlyArray<ServerProvider> => {
119 const mergedProviders = new Map(
120 previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
121 );
122
123 for (const provider of nextProviders) {
124 mergedProviders.set(
125 snapshotInstanceKey(provider),
126 mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
127 );
128 }
129
130 return orderProviderSnapshots([...mergedProviders.values()]);
131};
132
133export const selectProvidersByKind = (
134 providers: ReadonlyArray<ServerProvider>,
135 providerKinds: ReadonlySet<ProviderDriverKind>,
136): ReadonlyArray<ServerProvider> =>
137 providers.filter((provider) => providerKinds.has(provider.driver));
138
139export const haveProvidersChanged = (
140 previousProviders: ReadonlyArray<ServerProvider>,
141 nextProviders: ReadonlyArray<ServerProvider>,
142): boolean => !Equal.equals(previousProviders, nextProviders);
143
144const correlateSnapshotWithSource = (
145 source: ProviderSnapshotSource,
146 snapshot: ServerProvider,
147): Effect.Effect<ServerProvider> => {
148 if (snapshot.instanceId !== source.instanceId) {
149 return Effect.die(
150 new Error(
151 `Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
152 ),
153 );
154 }
155 if (snapshot.driver !== source.driverKind) {
156 return Effect.die(
157 new Error(
158 `Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
159 ),
160 );
161 }
162 return Effect.succeed(snapshot);
163};
164
165/**
166 * Key a snapshot for aggregation and persistence. Snapshot sources
167 * must be correlated by instance id before reaching this map; missing
168 * identities are defects, not runtime routing fallbacks.
169 */
170const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
171 return provider.instanceId;
172};
173
174// Project a live `ProviderInstance` into the aggregator's consumption
175// shape. Each call re-captures the instance's `snapshot` closures, so
176// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
177// its settings changed), a fresh source rides the new PubSub instead
178// of a closed one.
179const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
180 instanceId: instance.instanceId,
181 driverKind: instance.driverKind,
182 getSnapshot: instance.snapshot.getSnapshot,
183 refresh: instance.snapshot.refresh,
184 streamChanges: instance.snapshot.streamChanges,
185});
186
187export const ProviderRegistryLive = Layer.effect(
188 ProviderRegistry,
189 Effect.gen(function* () {
190 const instanceRegistry = yield* ProviderInstanceRegistry;
191 const config = yield* ServerConfig;
192 const fileSystem = yield* FileSystem.FileSystem;
193 const path = yield* Path.Path;
194
195 // Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
196 // coalesced updates across every instance.
197 const changesPubSub = yield* Effect.acquireRelease(
198 PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
199 PubSub.shutdown,
200 );
201
202 // Boot-only: hydrate `providersRef` from the on-disk per-instance
203 // cache so the UI has something to render during the first refresh.
204 // Instances added post-boot skip this path; their first entry in
205 // `providersRef` comes from the reactive `syncLiveSources` pass
206 // below.
207 const bootInstances = yield* instanceRegistry.listInstances;
208 const bootSources = bootInstances.map(buildSnapshotSource);
209 const fallbackProviders = yield* loadProviders(bootSources);
210 const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
211 for (let index = 0; index < fallbackProviders.length; index++) {
212 const provider = fallbackProviders[index];
213 const source = bootSources[index];
214 if (provider === undefined || source === undefined) {
215 continue;
216 }
217 fallbackByInstance.set(source.instanceId, provider);
218 }
219
220 const cachedProviders = yield* Effect.forEach(
221 bootSources,
222 (source) =>
223 Effect.gen(function* () {
224 // One cache file per configured instance. For the default
225 // instance of a built-in kind the path equals `<kind>.json` —
226 // identical to the legacy filename. We still require the cache
227 // payload to carry matching instance id + driver kind; old
228 // identity-less payloads are discarded and the awaited refresh
229 // below repopulates the cache.
230 const filePath = yield* resolveProviderStatusCachePath({
231 cacheDir: config.providerStatusCacheDir,
232 instanceId: source.instanceId,
233 }).pipe(Effect.provideService(Path.Path, path));
234 const fallbackProvider = fallbackByInstance.get(source.instanceId);
235 if (fallbackProvider === undefined) {
236 return undefined;
237 }
238 return yield* readProviderStatusCache(filePath).pipe(
239 Effect.provideService(FileSystem.FileSystem, fileSystem),
240 Effect.flatMap((cachedProvider) => {
241 if (cachedProvider === undefined) {
242 return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
243 }
244 const correlation = {
245 cachedProvider,
246 fallbackProvider,
247 } as const;
248 if (!isCachedProviderCorrelated(correlation)) {
249 return Effect.logWarning("provider status cache identity mismatch, ignoring", {
250 path: filePath,
251 instanceId: source.instanceId,
252 cachedInstanceId: cachedProvider.instanceId ?? null,
253 driver: source.driverKind,
254 cachedDriver: cachedProvider.driver ?? null,
255 }).pipe(Effect.as(undefined as ServerProvider | undefined));
256 }
257 return Effect.succeed(hydrateCachedProvider(correlation));
258 }),
259 );
260 }),
261 { concurrency: "unbounded" },
262 ).pipe(
263 Effect.map((providers) =>
264 orderProviderSnapshots(
265 providers.filter((provider): provider is ServerProvider => provider !== undefined),
266 ),
267 ),
268 );
269 const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
270 const maintenanceActionStatesRef = yield* Ref.make<
271 ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
272 >(new Map());
273
274 // Live-source registry — the dynamic counterpart to the boot-time
275 // `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
276 // reference is used for identity equality so "no-op" reconciles
277 // (settings unchanged) skip re-subscribing + re-probing.
278 const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(
279 new Map(),
280 );
281 // Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
282 // interleave two passes clobbering each other's fiber bookkeeping.
283 const syncSemaphore = yield* Semaphore.make(1);
284
285 const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
286 liveSubsRef,
287 ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
288
289 const persistProvider = (provider: ServerProvider) =>
290 Effect.gen(function* () {
291 // Persist every instance — the file name is the instance id, so
292 // multi-instance setups (e.g. `codex_personal`, `codex_work`) each
293 // get their own cache. We resolve the path fresh so snapshots
294 // produced by newly-added instances post-boot still land on disk
295 // without the aggregator holding a stale `cachePathByInstance`
296 // entry.
297 const key = snapshotInstanceKey(provider);
298 const filePath = yield* resolveProviderStatusCachePath({
299 cacheDir: config.providerStatusCacheDir,
300 instanceId: key,
301 }).pipe(Effect.provideService(Path.Path, path));
302 yield* writeProviderStatusCache({ filePath, provider }).pipe(
303 Effect.provideService(FileSystem.FileSystem, fileSystem),
304 Effect.provideService(Path.Path, path),
305 Effect.tapError(Effect.logError),
306 Effect.ignore,
307 );
308 });
309
310 const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
311 provider: ServerProvider,
312 ) {
313 const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
314 const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
315 if (!updateState) {
316 const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
317 return providerWithoutUpdateState;
318 }
319 return {
320 ...provider,
321 updateState,
322 };
323 });
324
325 const upsertProviders = Effect.fn("upsertProviders")(function* (
326 nextProviders: ReadonlyArray<ServerProvider>,
327 options?: {
328 readonly publish?: boolean;
329 readonly persist?: boolean;
330 readonly replace?: boolean;
331 },
332 ) {
333 const nextProvidersWithUpdateState = yield* Effect.forEach(
334 nextProviders,
335 applyProviderUpdateState,
336 {
337 concurrency: "unbounded",
338 },
339 );
340 const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
341 providersRef,
342 (previousProviders) => {
343 const mergedProviders = new Map(
344 previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
345 );
346 const updatedKeys = new Set<ProviderInstanceId>();
347
348 for (const provider of nextProvidersWithUpdateState) {
349 const key = snapshotInstanceKey(provider);
350 updatedKeys.add(key);
351 mergedProviders.set(
352 key,
353 options?.replace === true
354 ? provider
355 : mergeProviderSnapshot(mergedProviders.get(key), provider),
356 );
357 }
358
359 const providers = orderProviderSnapshots([...mergedProviders.values()]);
360 const providersToPersist = providers.filter((provider) =>
361 updatedKeys.has(snapshotInstanceKey(provider)),
362 );
363 return [[previousProviders, providers, providersToPersist] as const, providers];
364 },
365 );
366
367 if (haveProvidersChanged(previousProviders, providers)) {
368 if (options?.persist !== false) {
369 yield* Effect.forEach(providersToPersist, persistProvider, {
370 concurrency: "unbounded",
371 discard: true,
372 });
373 }
374 if (options?.publish !== false) {
375 yield* PubSub.publish(changesPubSub, providers);
376 }
377 }
378
379 return providers;
380 });
381
382 const syncProvider = Effect.fn("syncProvider")(function* (
383 provider: ServerProvider,
384 options?: {
385 readonly publish?: boolean;
386 },
387 ) {
388 return yield* upsertProviders([provider], options);
389 });
390
391 const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
392 function* (input: {
393 readonly instanceId: ProviderInstanceId;
394 readonly action: "update";
395 readonly state: ServerProviderUpdateState | null;
396 }) {
397 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
398 const previousActions = previous.get(input.instanceId);
399 const nextActions = { ...previousActions };
400 if (input.state === null || input.state.status === "idle") {
401 delete nextActions[input.action];
402 } else {
403 nextActions[input.action] = input.state;
404 }
405
406 const next = new Map(previous);
407 if (Object.keys(nextActions).length === 0) {
408 next.delete(input.instanceId);
409 } else {
410 next.set(input.instanceId, nextActions);
411 }
412 return next;
413 });
414
415 const existingProviders = yield* Ref.get(providersRef);
416 const matchingProvider = existingProviders.find(
417 (candidate) => candidate.instanceId === input.instanceId,
418 );
419 if (!matchingProvider) {
420 return existingProviders;
421 }
422
423 const nextProvider = yield* applyProviderUpdateState(matchingProvider);
424 return yield* upsertProviders([nextProvider], {
425 persist: false,
426 });
427 },
428 );
429
430 const refreshOneSource = Effect.fn("refreshOneSource")(function* (
431 providerSource: ProviderSnapshotSource,
432 ) {
433 return yield* providerSource.refresh.pipe(
434 Effect.flatMap((nextProvider) =>
435 correlateSnapshotWithSource(providerSource, nextProvider).pipe(
436 Effect.flatMap(syncProvider),
437 ),
438 ),
439 );
440 });
441
442 const refreshAll = Effect.fn("refreshAll")(function* () {
443 const sources = yield* getLiveSources;
444 return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
445 concurrency: "unbounded",
446 discard: true,
447 }).pipe(Effect.andThen(Ref.get(providersRef)));
448 });
449
450 const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
451 if (provider === undefined) {
452 return yield* refreshAll();
453 }
454 // Kind-scoped refreshes target the default instance for that driver.
455 const defaultInstanceId = defaultInstanceIdForDriver(provider);
456 const sources = yield* getLiveSources;
457 const providerSource = sources.find(
458 (candidate) => candidate.instanceId === defaultInstanceId,
459 );
460 if (!providerSource) {
461 return yield* Ref.get(providersRef);
462 }
463 return yield* refreshOneSource(providerSource);
464 });
465
466 const refreshInstance = Effect.fn("refreshInstance")(function* (
467 instanceId: ProviderInstanceId,
468 ) {
469 const sources = yield* getLiveSources;
470 const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
471 if (!providerSource) {
472 return yield* Ref.get(providersRef);
473 }
474 return yield* refreshOneSource(providerSource);
475 });
476
477 const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
478 "getProviderMaintenanceCapabilitiesForInstance",
479 )(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
480 const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
481 (candidate) => candidate.instanceId === instanceId,
482 );
483 return (
484 instance?.snapshot.maintenanceCapabilities ??
485 makeManualProviderMaintenanceCapabilities(provider)
486 );
487 });
488
489 /**
490 * Diff the aggregator's live-source set against the current
491 * `ProviderInstanceRegistry` and:
492 * - subscribe to each newly-added or rebuilt instance's
493 * `streamChanges` (so periodic + enrichment refreshes land in
494 * `providersRef`);
495 * - read each newly-added/rebuilt instance's current snapshot after
496 * subscribing, closing the race with its independently-running
497 * background startup probe;
498 * - prune `providersRef` of instances that no longer exist.
499 *
500 * Provider refreshes are owned by each managed provider and never run
501 * on this layer's construction path. Consumers see cached or pending
502 * snapshots immediately, then receive live probe results through the
503 * already-attached change stream.
504 *
505 * Per-instance subscription fibers are not tracked explicitly. When
506 * a rebuilt instance's old child scope closes, its PubSub shuts
507 * down and our `Stream.runForEach` fiber exits naturally.
508 */
509 const syncLiveSources = syncSemaphore.withPermits(1)(
510 Effect.gen(function* () {
511 const instances = yield* instanceRegistry.listInstances;
512 const unavailableProviders = yield* instanceRegistry.listUnavailable;
513 const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
514 instances.map((instance) => [instance.instanceId, instance] as const),
515 );
516 const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
517 for (const provider of unavailableProviders) {
518 knownInstanceIds.add(snapshotInstanceKey(provider));
519 }
520 const previousSubs = yield* Ref.get(liveSubsRef);
521
522 // Carry over subscriptions for instances whose identity is
523 // unchanged (reconcile treated them as no-op). Instances that
524 // disappeared, or were rebuilt with a different reference,
525 // fall through to the "newly-added" branch below.
526 const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
527 for (const [instanceId, previousInstance] of previousSubs) {
528 const nextInstance = nextByInstance.get(instanceId);
529 if (nextInstance !== undefined && nextInstance === previousInstance) {
530 carriedOver.set(instanceId, previousInstance);
531 }
532 }
533
534 // Collect new/rebuilt instances in `nextByInstance` insertion
535 // order (which preserves settings-author order).
536 const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
537 for (const [instanceId, instance] of nextByInstance) {
538 if (carriedOver.has(instanceId)) {
539 continue;
540 }
541 newlyAdded.push([instanceId, instance] as const);
542 }
543
544 // Fork long-lived subscriptions to each new/rebuilt instance's
545 // change stream before reading its current snapshot. If the
546 // driver's own initial probe finishes during this sync, either
547 // the current read or the active subscriber observes the result.
548 for (const [, instance] of newlyAdded) {
549 const source = buildSnapshotSource(instance);
550 yield* Stream.runForEach(source.streamChanges, (provider) =>
551 correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
552 ).pipe(Effect.forkScoped);
553 }
554 yield* Effect.yieldNow;
555
556 // Snapshot current state without starting a probe. Managed providers
557 // launch their startup refresh independently, so this closes the
558 // subscription race without putting external work on the registry
559 // or HTTP server construction path.
560 yield* Effect.forEach(
561 newlyAdded,
562 ([, instance]) =>
563 Effect.gen(function* () {
564 const source = buildSnapshotSource(instance);
565 const provider = yield* source.getSnapshot;
566 yield* correlateSnapshotWithSource(source, provider).pipe(
567 Effect.flatMap(syncProvider),
568 );
569 }).pipe(Effect.ignoreCause({ log: true })),
570 { concurrency: "unbounded", discard: true },
571 );
572 yield* upsertProviders(unavailableProviders, {
573 persist: false,
574 replace: true,
575 });
576
577 const nextSubs = new Map(carriedOver);
578 for (const [instanceId, instance] of newlyAdded) {
579 nextSubs.set(instanceId, instance);
580 }
581 yield* Ref.set(liveSubsRef, nextSubs);
582
583 // Drop aggregator state for instances that have disappeared —
584 // otherwise the UI would keep rendering ghosts.
585 const [previousProviders, providers] = yield* Ref.modify(
586 providersRef,
587 (previousProviders) => {
588 const providers = orderProviderSnapshots(
589 previousProviders.filter((provider) =>
590 knownInstanceIds.has(snapshotInstanceKey(provider)),
591 ),
592 );
593 return [[previousProviders, providers] as const, providers];
594 },
595 );
596 if (haveProvidersChanged(previousProviders, providers)) {
597 yield* PubSub.publish(changesPubSub, providers);
598 }
599 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
600 const next = new Map(previous);
601 for (const instanceId of previous.keys()) {
602 if (!knownInstanceIds.has(instanceId)) {
603 next.delete(instanceId);
604 }
605 }
606 return next;
607 });
608 }),
609 );
610 const syncLiveSourcesAndContinue = syncLiveSources.pipe(
611 Effect.catchCause((cause) => {
612 if (Cause.hasInterruptsOnly(cause)) {
613 return Effect.interrupt;
614 }
615 return Effect.logError(
616 "provider registry instance sync failed; keeping subscription alive",
617 {
618 cause: Cause.pretty(cause),
619 },
620 );
621 }),
622 );
623
624 // Seed `providersRef` with the boot-time fallback snapshots so
625 // consumers calling `getProviders` immediately after layer build see
626 // a populated list — even before the first `syncLiveSources` refresh
627 // resolves. Cached snapshots (already in `providersRef`) merge with
628 // these via `upsertProviders` so on-disk state wins where present
629 // and pending fallbacks fill the gaps.
630 yield* upsertProviders(fallbackProviders, { publish: false });
631 // Subscribe to registry mutations BEFORE running the initial sync.
632 // `subscribeChanges` acquires the dequeue synchronously in this
633 // fibre; the subscription is active the instant this `yield*`
634 // returns. Forking the consumer loop later cannot lose a publish
635 // because no publish can reach a not-yet-subscribed dequeue.
636 //
637 // (Contrast with the pre-fix code that did
638 // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
639 // `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,
640 // and `forkScoped` only schedules the fibre — so a reconcile that
641 // published between "fibre scheduled" and "fibre starts running"
642 // was dropped, which made any settings change that replaced an
643 // instance never propagate to the aggregator's `providersRef`.)
644 // Subscribe to registry mutations BEFORE running the initial sync.
645 // `subscribeChanges` acquires the `PubSub.Subscription` synchronously
646 // in this fibre; the subscription is registered with the PubSub the
647 // instant this `yield*` returns, so any subsequent publish is
648 // buffered in the subscription regardless of when the consumer
649 // fibre below actually starts running.
650 //
651 // (Contrast with the pre-fix code that did
652 // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
653 // `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
654 // which defers `PubSub.subscribe` to stream start. `forkScoped` only
655 // schedules the consumer fibre — so a reconcile that published
656 // between "fibre scheduled" and "fibre starts running + subscribes"
657 // was dropped, which made any settings change that replaced an
658 // instance never propagate to the aggregator's `providersRef`.)
659 const instanceChanges = yield* instanceRegistry.subscribeChanges;
660 // Initial sync attaches subscriptions and snapshots current state for
661 // every instance present at boot. Provider probes are already running in
662 // their managed background fibers and never block this layer.
663 yield* syncLiveSources;
664 // React to registry mutations — instance added / removed / rebuilt.
665 // `Stream.fromSubscription` builds a stream over the pre-acquired
666 // subscription rather than subscribing on stream start, which is
667 // what closes the race.
668 yield* Stream.runForEach(
669 Stream.fromSubscription(instanceChanges),
670 () => syncLiveSourcesAndContinue,
671 ).pipe(Effect.forkScoped);
672
673 const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
674 cause: Cause.Cause<unknown>,
675 ) {
676 if (Cause.hasInterruptsOnly(cause)) {
677 return yield* Effect.interrupt;
678 }
679 yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
680 cause: Cause.pretty(cause),
681 });
682 return yield* Ref.get(providersRef);
683 });
684
685 return {
686 getProviders: Ref.get(providersRef),
687 refresh: (provider?: ProviderDriverKind) =>
688 refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
689 refreshInstance: (instanceId: ProviderInstanceId) =>
690 refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
691 getProviderMaintenanceCapabilitiesForInstance,
692 setProviderMaintenanceActionState,
693 get streamChanges() {
694 return Stream.fromPubSub(changesPubSub);
695 },
696 } satisfies ProviderRegistryShape;
697 }),
698);