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