Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

discovery.ts

328 lines11.1 KB

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>;
34​
35export interface RelayEnvironmentDiscoveryState {
36 readonly environments: ReadonlyMap<string, RelayDiscoveredEnvironment>;
37 readonly refreshing: boolean;
38 readonly offline: boolean;
39 readonly error: Option.Option<ConnectionAttemptError>;
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);
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 }
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 const clerkToken = yield* session.clerkToken;
226 if ((yield* Ref.get(accountGeneration)) !== generation) {
227 return;
228 }
229 const accountId = relayAccountId(clerkToken);
230 const previousAccountId = yield* Ref.get(activeAccountId);
231 if (
232 Option.isSome(previousAccountId) &&
233 (!Option.isSome(accountId) || previousAccountId.value !== accountId.value)
234 ) {
235 generation = yield* Ref.updateAndGet(accountGeneration, (current) => current + 1);
236 yield* Ref.set(refreshGeneration, generation);
237 }
238 yield* Ref.set(activeAccountId, accountId);
239​
240 const environments = yield* relay
241 .listEnvironments({ clerkToken })
242 .pipe(Effect.mapError(mapManagedRelayError));
243 if ((yield* Ref.get(accountGeneration)) !== generation) {
244 return;
245 }
246 const next = new Map<string, RelayDiscoveredEnvironment>();
247 for (const environment of environments) {
248 next.set(environment.environmentId, {
249 environment,
250 availability: "checking",
251 status: Option.none(),
252 error: Option.none(),
253 });
254 }
255 yield* SubscriptionRef.update(state, (current) => ({
256 ...current,
257 environments: next,
258 }));
259​
260 yield* Effect.forEach(
261 environments,
262 (environment) => refreshStatus(generation, clerkToken, environment),
263 {
264 concurrency: "unbounded",
265 discard: true,
266 },
267 );
268 if ((yield* Ref.get(accountGeneration)) !== generation) {
269 return;
270 }
271 yield* SubscriptionRef.update(state, (current) => ({
272 ...current,
273 refreshing: false,
274 }));
275 }).pipe(
276 Effect.catch((error) =>
277 Effect.gen(function* () {
278 const generation = yield* Ref.get(refreshGeneration);
279 if ((yield* Ref.get(accountGeneration)) !== generation) {
280 return;
281 }
282 yield* SubscriptionRef.update(state, (current) => ({
283 ...current,
284 refreshing: false,
285 error: Option.some(error),
286 }));
287 }),
288 ),
289 ),
290 );
291​
292 yield* connectivity.changes.pipe(
293 Stream.changes,
294 Stream.runForEach((networkStatus) =>
295 networkStatus === "offline"
296 ? SubscriptionRef.update(state, (current) => ({
297 ...current,
298 refreshing: false,
299 offline: true,
300 }))
301 : Ref.get(hasRefreshed).pipe(
302 Effect.flatMap((shouldRefresh) => (shouldRefresh ? refresh : Effect.void)),
303 ),
304 ),
305 Effect.forkScoped,
306 );
307 yield* wakeups.changes.pipe(
308 Stream.runForEach((reason) =>
309 reason === "credentials-changed"
310 ? Effect.gen(function* () {
311 yield* Ref.update(accountGeneration, (current) => current + 1);
312 yield* Ref.set(activeAccountId, Option.none());
313 yield* Ref.set(offlineReportFingerprints, new Map());
314 const shouldRefresh = yield* Ref.get(hasRefreshed);
315 yield* SubscriptionRef.set(state, EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE);
316 if (shouldRefresh) {
317 yield* refresh.pipe(Effect.forkScoped);
318 }
319 })
320 : Effect.void,
321 ),
322 Effect.forkScoped,
323 );
324​
325 return RelayEnvironmentDiscovery.of({ state, refresh });
326});
327​
328export const layer = Layer.effect(RelayEnvironmentDiscovery, make());