Open History to see the last commit
1/**
2 * ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.
3 *
4 * `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one
5 * adapter via the four `<X>AdapterLive` singleton Layers. The per-instance
6 * refactor moved adapter construction inside each `ProviderDriver.create()`:
7 * adapters are now bundled on the `ProviderInstance` that the
8 * `ProviderInstanceRegistry` owns.
9 *
10 * This facade fulfills the `ProviderAdapterRegistryShape` contract by doing
11 * dynamic look-ups against `ProviderInstanceRegistry` on every call. That
12 * means settings-driven hot-reload shows up here automatically — adding a
13 * new instance via settings makes `getByInstance` resolve immediately
14 * without rebuilding the facade.
15 *
16 * @module ProviderAdapterRegistryLive
17 */
18import { ProviderInstanceId, ProviderSetupError, type ProviderSession } from "@t3tools/contracts";
19import * as Effect from "effect/Effect";
20import * as Schema from "effect/Schema";
21import * as Layer from "effect/Layer";
22import type * as Scope from "effect/Scope";
23
24import {
25 ProviderUnsupportedError,
26 ProviderAdapterValidationError,
27 type ProviderAdapterError,
28} from "../Errors.ts";
29import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
30import {
31 ProviderAdapterRegistry,
32 type ProviderAdapterRegistryShape,
33} from "../Services/ProviderAdapterRegistry.ts";
34
35import type { ProviderInstance } from "../ProviderDriver.ts";
36import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
37
38const isSetupError = Schema.is(ProviderSetupError);
39
40const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
41 const registry = yield* ProviderInstanceRegistry;
42 // Stable identity keeps ProviderService's event subscriptions attached once.
43 const guarded = new WeakMap<ProviderInstance, ProviderAdapterShape<ProviderAdapterError>>();
44 const guard = (instance: ProviderInstance) => {
45 const auth = instance.auth;
46 if (!auth || (!auth.withAccess && !auth.isChangingCredentials && !auth.credentialBinding))
47 return instance.adapter;
48 const cached = guarded.get(instance);
49 if (cached) return cached;
50 const adapter: ProviderAdapterShape<ProviderAdapterError> = {
51 ...instance.adapter,
52 startSession: (input) => {
53 const start = Effect.gen(function* () {
54 const binding = auth.credentialBinding;
55 const related = binding
56 ? (yield* registry.listInstances).filter(
57 (peer) =>
58 peer.auth?.credentialBinding?.key === binding.key &&
59 peer.auth.credentialBinding.owner === binding.owner,
60 )
61 : [instance];
62 for (const peer of related) {
63 if (peer.auth?.isChangingCredentials && (yield* peer.auth.isChangingCredentials)) {
64 return yield* new ProviderSetupError({
65 instanceId: instance.instanceId,
66 operation: "session",
67 detail: "Provider sign-in is changing. Try again after it finishes.",
68 });
69 }
70 }
71 let admitted: Effect.Effect<
72 ProviderSession,
73 ProviderAdapterError | ProviderSetupError,
74 Scope.Scope
75 > = instance.adapter.startSession(input);
76 // Every shared owner holds the startup scope. A credential change
77 // interrupts admitted startup before it can escape the session drain.
78 for (const peer of related) {
79 if (peer.auth?.withAccess) admitted = peer.auth.withAccess(admitted);
80 }
81 return yield* Effect.scoped(admitted);
82 });
83 // Adapters own established session lifetimes. This scope guards startup;
84 // ProviderAuthService drains routed sessions before changing credentials.
85 return start.pipe(
86 Effect.mapError((cause) =>
87 isSetupError(cause)
88 ? new ProviderAdapterValidationError({
89 provider: instance.driverKind,
90 operation: "startSession",
91 issue: cause.detail,
92 })
93 : cause,
94 ),
95 );
96 },
97 };
98 guarded.set(instance, adapter);
99 return adapter;
100 };
101
102 const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) =>
103 registry.getInstance(instanceId).pipe(
104 Effect.flatMap((instance) =>
105 instance === undefined
106 ? Effect.fail(
107 new ProviderUnsupportedError({
108 provider: instanceId,
109 }),
110 )
111 : Effect.succeed(guard(instance)),
112 ),
113 );
114
115 const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>
116 registry.getInstance(instanceId).pipe(
117 Effect.flatMap((instance) =>
118 instance === undefined
119 ? Effect.fail(
120 new ProviderUnsupportedError({
121 provider: instanceId,
122 }),
123 )
124 : Effect.succeed({
125 instanceId: instance.instanceId,
126 driverKind: instance.driverKind,
127 displayName: instance.displayName,
128 accentColor: instance.accentColor,
129 enabled: instance.enabled,
130 continuationIdentity: instance.continuationIdentity,
131 }),
132 ),
133 );
134
135 const listInstances: ProviderAdapterRegistryShape["listInstances"] = () =>
136 registry.listInstances.pipe(
137 Effect.map((instances) => instances.map((instance) => instance.instanceId)),
138 );
139
140 return {
141 getByInstance,
142 getInstanceInfo,
143 listInstances,
144 subscribeChanges: registry.subscribeChanges,
145 } satisfies ProviderAdapterRegistryShape;
146});
147
148export const ProviderAdapterRegistryLive = Layer.effect(
149 ProviderAdapterRegistry,
150 makeProviderAdapterRegistry(),
151);
152
153// Re-export for consumers (including tests) that construct a
154// `ProviderInstanceId` before calling `getByInstance`.
155export { ProviderInstanceId };