Open History to see the last commit
1import type {
2 RelayClientEnvironmentRecord,
3 RelayEnvironmentStatusResponse,
4} from "@t3tools/contracts/relay";
5import { decodeRelayJwt } from "@t3tools/shared/relayJwt";
6import {
7 RelayEnvironmentConnectScope,
8 RelayEnvironmentStatusScope,
9} from "@t3tools/contracts/relay";
10import * as Context from "effect/Context";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Ref from "effect/Ref";
15import * as Semaphore from "effect/Semaphore";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18
19import * as ManagedRelay from "./managedRelay.ts";
20import * as ClientCapabilities from "../platform/capabilities.ts";
21import * as Connectivity from "../connection/connectivity.ts";
22import { mapManagedRelayError } from "../connection/errors.ts";
23import { ConnectionBlockedError, type ConnectionAttemptError } from "../connection/model.ts";
24import * as ConnectionWakeups from "../connection/wakeups.ts";
25
26export type RelayEnvironmentAvailability = "checking" | "online" | "offline" | "error";
27
28export interface RelayDiscoveredEnvironment {
29 readonly environment: RelayClientEnvironmentRecord;
30 readonly availability: RelayEnvironmentAvailability;
31 readonly status: Option.Option<RelayEnvironmentStatusResponse>;
32 readonly error: Option.Option<ConnectionAttemptError>;
33}
34
35export interface RelayEnvironmentDiscoveryState {
36 readonly environments: ReadonlyMap<string, RelayDiscoveredEnvironment>;
37 readonly refreshing: boolean;
38 readonly offline: boolean;
39 readonly error: Option.Option<ConnectionAttemptError>;
40}
41
42export class RelayEnvironmentDiscovery extends Context.Service<
43 RelayEnvironmentDiscovery,
44 {
45 readonly state: SubscriptionRef.SubscriptionRef<RelayEnvironmentDiscoveryState>;
46 readonly refresh: Effect.Effect<void>;
47 }
48>()("@t3tools/client-runtime/relay/discovery/RelayEnvironmentDiscovery") {}
49
50export const EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE: RelayEnvironmentDiscoveryState = {
51 environments: new Map(),
52 refreshing: false,
53 offline: false,
54 error: Option.none(),
55};
56
57function validateStatus(
58 environment: RelayClientEnvironmentRecord,
59 status: RelayEnvironmentStatusResponse,
60): Effect.Effect<RelayEnvironmentStatusResponse, ConnectionAttemptError> {
61 if (status.environmentId !== environment.environmentId) {
62 return Effect.fail(
63 new ConnectionBlockedError({
64 reason: "configuration",
65 detail: "Relay returned status for a different environment.",
66 }),
67 );
68 }
69 if (
70 status.endpoint.httpBaseUrl !== environment.endpoint.httpBaseUrl ||
71 status.endpoint.wsBaseUrl !== environment.endpoint.wsBaseUrl ||
72 status.endpoint.providerKind !== environment.endpoint.providerKind
73 ) {
74 return Effect.fail(
75 new ConnectionBlockedError({
76 reason: "configuration",
77 detail: "Relay returned status for a different environment endpoint.",
78 }),
79 );
80 }
81 if (
82 status.descriptor !== undefined &&
83 status.descriptor.environmentId !== environment.environmentId
84 ) {
85 return Effect.fail(
86 new ConnectionBlockedError({
87 reason: "configuration",
88 detail: "Relay returned a descriptor for a different environment.",
89 }),
90 );
91 }
92 return Effect.succeed(status);
93}
94
95function relayAccountId(clerkToken: string): Option.Option<string> {
96 try {
97 return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe(
98 Option.filter((subject) => subject.length > 0),
99 );
100 } catch {
101 return Option.none();
102 }
103}
104
105export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
106 const relay = yield* ManagedRelay.ManagedRelayClient;
107 const session = yield* ClientCapabilities.CloudSession;
108 const connectivity = yield* Connectivity.Connectivity;
109 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
110 const state = yield* SubscriptionRef.make(EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE);
111 const refreshLock = yield* Semaphore.make(1);
112 const hasRefreshed = yield* Ref.make(false);
113 const accountGeneration = yield* Ref.make(0);
114 const activeAccountId = yield* Ref.make<Option.Option<string>>(Option.none());
115 const refreshGeneration = yield* Ref.make(0);
116 const offlineReportFingerprints = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
117
118 const clearOfflineReport = Effect.fn("RelayEnvironmentDiscovery.clearOfflineReport")(function* (
119 environmentId: string,
120 ) {
121 yield* Ref.update(offlineReportFingerprints, (current) => {
122 if (!current.has(environmentId)) {
123 return current;
124 }
125 const next = new Map(current);
126 next.delete(environmentId);
127 return next;
128 });
129 });
130
131 const updateEnvironment = Effect.fn("RelayEnvironmentDiscovery.updateEnvironment")(function* (
132 generation: number,
133 environmentId: string,
134 update: (current: RelayDiscoveredEnvironment) => RelayDiscoveredEnvironment,
135 ) {
136 if ((yield* Ref.get(accountGeneration)) !== generation) {
137 return;
138 }
139 yield* SubscriptionRef.update(state, (current) => {
140 const entry = current.environments.get(environmentId);
141 if (entry === undefined) {
142 return current;
143 }
144 const environments = new Map(current.environments);
145 environments.set(environmentId, update(entry));
146 return { ...current, environments };
147 });
148 });
149
150 const refreshStatus = Effect.fn("RelayEnvironmentDiscovery.refreshStatus")(function* (
151 generation: number,
152 clerkToken: string,
153 environment: RelayClientEnvironmentRecord,
154 ) {
155 const result = yield* relay
156 .getEnvironmentStatus({
157 clerkToken,
158 scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],
159 environmentId: environment.environmentId,
160 })
161 .pipe(
162 Effect.mapError(mapManagedRelayError),
163 Effect.flatMap((status) => validateStatus(environment, status)),
164 Effect.result,
165 );
166
167 if (result._tag === "Success") {
168 if (result.success.status === "offline") {
169 const fingerprint = `${result.success.endpoint.httpBaseUrl}\n${result.success.error ?? ""}`;
170 const shouldReport = yield* Ref.modify(offlineReportFingerprints, (current) => {
171 if (current.get(environment.environmentId) === fingerprint) {
172 return [false, current];
173 }
174 return [true, new Map(current).set(environment.environmentId, fingerprint)];
175 });
176 if (shouldReport) {
177 yield* Effect.logWarning("Relay environment health check reported offline", {
178 environmentId: result.success.environmentId,
179 endpoint: result.success.endpoint.httpBaseUrl,
180 message: result.success.error,
181 traceId: result.success.traceId,
182 });
183 }
184 } else {
185 yield* clearOfflineReport(environment.environmentId);
186 }
187 yield* updateEnvironment(generation, environment.environmentId, (current) => ({
188 ...current,
189 availability: result.success.status,
190 status: Option.some(result.success),
191 error: Option.none(),
192 }));
193 return;
194 }
195
196 yield* clearOfflineReport(environment.environmentId);
197 yield* updateEnvironment(generation, environment.environmentId, (current) => ({
198 ...current,
199 availability: "error",
200 error: Option.some(result.failure),
201 }));
202 });
203
204 const refresh = refreshLock.withPermits(1)(
205 Effect.gen(function* () {
206 yield* Ref.set(hasRefreshed, true);
207 if ((yield* connectivity.status) === "offline") {
208 yield* SubscriptionRef.update(state, (current) => ({
209 ...current,
210 refreshing: false,
211 offline: true,
212 }));
213 return;
214 }
215
216 let generation = yield* Ref.get(accountGeneration);
217 yield* Ref.set(refreshGeneration, generation);
218 yield* SubscriptionRef.set(state, {
219 environments: new Map(),
220 refreshing: true,
221 offline: false,
222 error: Option.none(),
223 });
224
225 // Signed out is the idle state, not a failure: the proactive refresh on
226 // credentials-changed also runs on sign-out and must settle back to a
227 // clean empty list. Only the session-level "no credentials" error is
228 // benign — relay-side auth failures (expired/invalid tokens) happen
229 // after this point and must surface as errors.
230 const tokenResult = yield* Effect.result(session.clerkToken);
231 if (tokenResult._tag === "Failure") {
232 const failure = tokenResult.failure;
233 if (failure._tag === "ConnectionBlockedError" && failure.reason === "authentication") {
234 if ((yield* Ref.get(accountGeneration)) !== generation) {
235 return;
236 }
237 yield* SubscriptionRef.update(state, (current) => ({
238 ...current,
239 refreshing: false,
240 }));
241 return;
242 }
243 return yield* Effect.fail(failure);
244 }
245 const clerkToken = tokenResult.success;
246 if ((yield* Ref.get(accountGeneration)) !== generation) {
247 return;
248 }
249 const accountId = relayAccountId(clerkToken);
250 const previousAccountId = yield* Ref.get(activeAccountId);
251 if (
252 Option.isSome(previousAccountId) &&
253 (!Option.isSome(accountId) || previousAccountId.value !== accountId.value)
254 ) {
255 generation = yield* Ref.updateAndGet(accountGeneration, (current) => current + 1);
256 yield* Ref.set(refreshGeneration, generation);
257 }
258 yield* Ref.set(activeAccountId, accountId);
259
260 const environments = yield* relay
261 .listEnvironments({ clerkToken })
262 .pipe(Effect.mapError(mapManagedRelayError));
263 if ((yield* Ref.get(accountGeneration)) !== generation) {
264 return;
265 }
266 const next = new Map<string, RelayDiscoveredEnvironment>();
267 for (const environment of environments) {
268 next.set(environment.environmentId, {
269 environment,
270 availability: "checking",
271 status: Option.none(),
272 error: Option.none(),
273 });
274 }
275 yield* SubscriptionRef.update(state, (current) => ({
276 ...current,
277 environments: next,
278 }));
279
280 yield* Effect.forEach(
281 environments,
282 (environment) => refreshStatus(generation, clerkToken, environment),
283 {
284 concurrency: "unbounded",
285 discard: true,
286 },
287 );
288 if ((yield* Ref.get(accountGeneration)) !== generation) {
289 return;
290 }
291 yield* SubscriptionRef.update(state, (current) => ({
292 ...current,
293 refreshing: false,
294 }));
295 }).pipe(
296 Effect.catch((error) =>
297 Effect.gen(function* () {
298 const generation = yield* Ref.get(refreshGeneration);
299 if ((yield* Ref.get(accountGeneration)) !== generation) {
300 return;
301 }
302 yield* SubscriptionRef.update(state, (current) => ({
303 ...current,
304 refreshing: false,
305 error: Option.some(error),
306 }));
307 }),
308 ),
309 ),
310 );
311
312 yield* connectivity.changes.pipe(
313 Stream.changes,
314 Stream.runForEach((networkStatus) =>
315 networkStatus === "offline"
316 ? SubscriptionRef.update(state, (current) => ({
317 ...current,
318 refreshing: false,
319 offline: true,
320 }))
321 : Ref.get(hasRefreshed).pipe(
322 Effect.flatMap((shouldRefresh) => (shouldRefresh ? refresh : Effect.void)),
323 ),
324 ),
325 Effect.forkScoped,
326 );
327 yield* wakeups.changes.pipe(
328 Stream.runForEach((reason) =>
329 reason === "credentials-changed"
330 ? Effect.gen(function* () {
331 yield* Ref.update(accountGeneration, (current) => current + 1);
332 yield* Ref.set(activeAccountId, Option.none());
333 yield* Ref.set(offlineReportFingerprints, new Map());
334 yield* SubscriptionRef.set(state, EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE);
335 // Refresh proactively — this wakeup fires when a session activates
336 // (sign-in or cold start), and the list should be populated before
337 // any screen asks for it. A signed-out refresh settles back to the
338 // clean empty state.
339 yield* refresh.pipe(Effect.forkScoped);
340 })
341 : Effect.void,
342 ),
343 Effect.forkScoped,
344 );
345
346 return RelayEnvironmentDiscovery.of({ state, refresh });
347});
348
349export const layer = Layer.effect(RelayEnvironmentDiscovery, make());