Open History to see the last commit
1import type {
2 RelayClientEnvironmentRecord,
3 RelayEnvironmentStatusResponse,
4} from "@t3tools/contracts/relay";
5import type { EnvironmentId } from "@t3tools/contracts";
6import {
7 RelayEnvironmentConnectScope,
8 RelayEnvironmentStatusScope,
9} from "@t3tools/contracts/relay";
10import { decodeRelayJwt } from "@t3tools/shared/relayJwt";
11import * as Cause from "effect/Cause";
12import * as Clock from "effect/Clock";
13import * as Data from "effect/Data";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
19
20import { findErrorTraceId } from "../errors/errorTrace.ts";
21import * as ManagedRelay from "./managedRelay.ts";
22import { relayProtectedErrorMessage } from "./errorPresentation.ts";
23
24const DEFAULT_STALE_TIME_MS = 15_000;
25const DEFAULT_IDLE_TTL_MS = 5 * 60_000;
26const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000;
27const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
28
29export interface ManagedRelaySession {
30 readonly accountId: string;
31 readonly readClerkToken: () => Effect.Effect<string | null, ManagedRelaySessionError>;
32}
33
34export interface ManagedRelaySessionInput {
35 readonly accountId: string;
36 readonly readClerkToken: () => Promise<string | null>;
37}
38
39interface ManagedRelaySessionControl {
40 readonly updateReadClerkToken: (
41 readClerkToken: ManagedRelaySessionInput["readClerkToken"],
42 ) => void;
43}
44
45export interface ManagedRelaySnapshotState<A> {
46 readonly data: A | null;
47 readonly error: string | null;
48 readonly errorTraceId: string | null;
49 readonly isPending: boolean;
50}
51
52export interface ManagedRelayQueryEvent {
53 readonly operation: "environments" | "devices" | "environment-status";
54 readonly stage: "clerk-token" | "relay-request" | "validation";
55 readonly phase: "start" | "success" | "failure";
56 readonly accountId: string;
57 readonly environmentId?: string;
58 readonly message?: string;
59 readonly traceId?: string | null;
60}
61
62export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{
63 readonly message: string;
64 readonly cause?: unknown;
65}> {}
66
67export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySnapshotError")<{
68 readonly message: string;
69}> {}
70
71export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
72 Atom.keepAlive,
73 Atom.withLabel("managed-relay:session"),
74);
75
76const managedRelaySessionControls = new WeakMap<ManagedRelaySession, ManagedRelaySessionControl>();
77
78export function createManagedRelaySession(input: ManagedRelaySessionInput): ManagedRelaySession {
79 let cachedToken: { readonly token: string; readonly expiresAtMillis: number } | null = null;
80 let pendingToken: Promise<string | null> | null = null;
81 let readClerkToken = input.readClerkToken;
82 let tokenProviderGeneration = 0;
83
84 const readCachedClerkToken = async (nowMillis: number): Promise<string | null> => {
85 if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) {
86 return cachedToken.token;
87 }
88 if (pendingToken) {
89 return await pendingToken;
90 }
91
92 const operationGeneration = tokenProviderGeneration;
93 const operation = readClerkToken().then((token) => {
94 if (operationGeneration !== tokenProviderGeneration) {
95 return token;
96 }
97 if (!token) {
98 cachedToken = null;
99 return null;
100 }
101 try {
102 const expiresAtSeconds = decodeRelayJwt(token).exp;
103 cachedToken =
104 typeof expiresAtSeconds === "number"
105 ? { token, expiresAtMillis: expiresAtSeconds * 1_000 }
106 : null;
107 } catch {
108 cachedToken = null;
109 }
110 return token;
111 });
112 pendingToken = operation;
113 try {
114 return await operation;
115 } finally {
116 if (pendingToken === operation) {
117 pendingToken = null;
118 }
119 }
120 };
121
122 const session: ManagedRelaySession = {
123 accountId: input.accountId,
124 readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () {
125 const nowMillis = yield* Clock.currentTimeMillis;
126 return yield* Effect.tryPromise({
127 try: () => readCachedClerkToken(nowMillis),
128 catch: (cause) =>
129 new ManagedRelaySessionError({
130 message: "Could not obtain the T3 Connect session token.",
131 cause,
132 }),
133 });
134 }),
135 };
136 managedRelaySessionControls.set(session, {
137 updateReadClerkToken: (nextReadClerkToken) => {
138 readClerkToken = nextReadClerkToken;
139 tokenProviderGeneration += 1;
140 pendingToken = null;
141 },
142 });
143 return session;
144}
145
146export function setManagedRelaySession(
147 registry: AtomRegistry.AtomRegistry,
148 input: ManagedRelaySessionInput | null,
149): void {
150 const current = registry.get(managedRelaySessionAtom);
151 if (input === null) {
152 if (current !== null) {
153 registry.set(managedRelaySessionAtom, null);
154 }
155 return;
156 }
157 if (current?.accountId === input.accountId) {
158 const control = managedRelaySessionControls.get(current);
159 if (control) {
160 // Clerk can replace its token reader during routine same-account refreshes.
161 // Keep the session stable so those refreshes do not invalidate queries or reconnect leases.
162 control.updateReadClerkToken(input.readClerkToken);
163 return;
164 }
165 }
166 registry.set(managedRelaySessionAtom, createManagedRelaySession(input));
167}
168
169export function managedRelayAccountChanges(
170 registry: AtomRegistry.AtomRegistry,
171): Stream.Stream<string | null> {
172 return AtomRegistry.toStream(registry, managedRelaySessionAtom).pipe(
173 Stream.map((session) => session?.accountId ?? null),
174 Stream.changes,
175 Stream.drop(1),
176 );
177}
178
179function readSessionClerkToken(
180 session: ManagedRelaySession,
181): Effect.Effect<string, ManagedRelaySessionError> {
182 return session.readClerkToken().pipe(
183 Effect.flatMap((token) =>
184 token
185 ? Effect.succeed(token)
186 : Effect.fail(
187 new ManagedRelaySessionError({
188 message: "The T3 Connect session token is unavailable.",
189 }),
190 ),
191 ),
192 );
193}
194
195export const waitForManagedRelayClerkToken = Effect.fn(
196 "clientRuntime.managedRelaySession.waitForClerkToken",
197)(function* (registry: AtomRegistry.AtomRegistry) {
198 return yield* Effect.callback<string, ManagedRelaySessionError>((resume) => {
199 let unsubscribe: (() => void) | undefined;
200 let completed = false;
201 const readCurrentSession = () => {
202 if (completed) {
203 return true;
204 }
205 const session = registry.get(managedRelaySessionAtom);
206 if (!session) {
207 return false;
208 }
209 completed = true;
210 unsubscribe?.();
211 resume(readSessionClerkToken(session));
212 return true;
213 };
214
215 if (readCurrentSession()) {
216 return;
217 }
218
219 unsubscribe = registry.subscribe(managedRelaySessionAtom, readCurrentSession);
220 readCurrentSession();
221 return Effect.sync(() => unsubscribe?.());
222 });
223});
224
225/** Removes an environment from the signed-in account without contacting that environment. */
226export const deregisterManagedRelayEnvironment = Effect.fn(
227 "clientRuntime.managedRelaySession.deregisterEnvironment",
228)(function* (
229 registry: AtomRegistry.AtomRegistry,
230 input: { readonly accountId: string; readonly environmentId: EnvironmentId },
231) {
232 const session = registry.get(managedRelaySessionAtom);
233 if (!session || session.accountId !== input.accountId) {
234 return yield* new ManagedRelaySessionError({
235 message: "Sign in to T3 Connect before deregistering an environment.",
236 });
237 }
238 const clerkToken = yield* readSessionClerkToken(session);
239 const relay = yield* ManagedRelay.ManagedRelayClient;
240 yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId });
241});
242
243function requireClerkToken(
244 get: Atom.AtomContext,
245 accountId: string,
246): Effect.Effect<string, ManagedRelaySessionError> {
247 const session = get(managedRelaySessionAtom);
248 if (!session || session.accountId !== accountId) {
249 return Effect.fail(
250 new ManagedRelaySessionError({
251 message: "Sign in to T3 Connect before loading relay data.",
252 }),
253 );
254 }
255 return readSessionClerkToken(session);
256}
257
258function statusKey(input: {
259 readonly accountId: string;
260 readonly environment: RelayClientEnvironmentRecord;
261}): string {
262 return JSON.stringify(input);
263}
264
265function parseStatusKey(key: string): {
266 readonly accountId: string;
267 readonly environment: RelayClientEnvironmentRecord;
268} {
269 return JSON.parse(key) as {
270 readonly accountId: string;
271 readonly environment: RelayClientEnvironmentRecord;
272 };
273}
274
275function endpointMatches(
276 left: RelayClientEnvironmentRecord["endpoint"],
277 right: RelayClientEnvironmentRecord["endpoint"],
278): boolean {
279 return (
280 left.httpBaseUrl === right.httpBaseUrl &&
281 left.wsBaseUrl === right.wsBaseUrl &&
282 left.providerKind === right.providerKind
283 );
284}
285
286function validateEnvironmentStatus(
287 environment: RelayClientEnvironmentRecord,
288 status: RelayEnvironmentStatusResponse,
289): Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelaySnapshotError> {
290 if (status.environmentId !== environment.environmentId) {
291 return Effect.fail(
292 new ManagedRelaySnapshotError({
293 message: "Relay returned status for a different environment.",
294 }),
295 );
296 }
297 if (!endpointMatches(status.endpoint, environment.endpoint)) {
298 return Effect.fail(
299 new ManagedRelaySnapshotError({
300 message: "Relay returned status for a different endpoint.",
301 }),
302 );
303 }
304 if (status.descriptor && status.descriptor.environmentId !== environment.environmentId) {
305 return Effect.fail(
306 new ManagedRelaySnapshotError({
307 message: "Relay returned status descriptor for a different environment.",
308 }),
309 );
310 }
311 return Effect.succeed(status);
312}
313
314export function readManagedRelaySnapshotState<A>(
315 result: AsyncResult.AsyncResult<A, unknown>,
316): ManagedRelaySnapshotState<A> {
317 let error: string | null = null;
318 let errorTraceId: string | null = null;
319 if (result._tag === "Failure") {
320 const cause = Cause.squash(result.cause);
321 error =
322 isManagedRelayRequestFailedError(cause) && cause.relayError
323 ? relayProtectedErrorMessage(cause.relayError)
324 : cause instanceof Error
325 ? cause.message
326 : "Could not load T3 Connect data.";
327 errorTraceId = findErrorTraceId(cause);
328 }
329 return {
330 data: Option.getOrNull(AsyncResult.value(result)),
331 error,
332 errorTraceId,
333 isPending: result.waiting,
334 };
335}
336
337export function createManagedRelayQueryManager(
338 runtime: Atom.AtomRuntime<ManagedRelay.ManagedRelayClient>,
339 options?: {
340 readonly staleTimeMs?: number;
341 readonly idleTtlMs?: number;
342 readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;
343 },
344) {
345 const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
346 const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
347 const observe = <A, E, R>(
348 input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
349 effect: Effect.Effect<A, E, R>,
350 ): Effect.Effect<A, E, R> =>
351 Effect.gen(function* () {
352 options?.onQueryEvent?.({ ...input, phase: "start" });
353 return yield* effect.pipe(
354 Effect.onExit((exit) =>
355 Effect.sync(() => {
356 if (exit._tag === "Success") {
357 options?.onQueryEvent?.({ ...input, phase: "success" });
358 return;
359 }
360 const error = Cause.squash(exit.cause);
361 options?.onQueryEvent?.({
362 ...input,
363 phase: "failure",
364 message: error instanceof Error ? error.message : String(error),
365 traceId: findErrorTraceId(error),
366 });
367 }),
368 ),
369 );
370 });
371
372 const environmentsAtom = Atom.family((accountId: string) =>
373 runtime
374 .atom((get) =>
375 Effect.gen(function* () {
376 const base = { operation: "environments" as const, accountId };
377 const clerkToken = yield* observe(
378 { ...base, stage: "clerk-token" },
379 requireClerkToken(get, accountId),
380 );
381 const relay = yield* ManagedRelay.ManagedRelayClient;
382 return yield* observe(
383 { ...base, stage: "relay-request" },
384 relay.listEnvironments({ clerkToken }),
385 );
386 }),
387 )
388 .pipe(
389 Atom.swr({ staleTime, revalidateOnMount: true }),
390 Atom.setIdleTTL(idleTtl),
391 Atom.withLabel(`managed-relay:environments:${accountId}`),
392 ),
393 );
394
395 const devicesAtom = Atom.family((accountId: string) =>
396 runtime
397 .atom((get) =>
398 Effect.gen(function* () {
399 const base = { operation: "devices" as const, accountId };
400 const clerkToken = yield* observe(
401 { ...base, stage: "clerk-token" },
402 requireClerkToken(get, accountId),
403 );
404 const relay = yield* ManagedRelay.ManagedRelayClient;
405 return yield* observe(
406 { ...base, stage: "relay-request" },
407 relay.listDevices({ clerkToken }),
408 );
409 }),
410 )
411 .pipe(
412 Atom.swr({ staleTime, revalidateOnMount: true }),
413 Atom.setIdleTTL(idleTtl),
414 Atom.withLabel(`managed-relay:devices:${accountId}`),
415 ),
416 );
417
418 const environmentStatusAtom = Atom.family((key: string) => {
419 const { accountId, environment } = parseStatusKey(key);
420 return runtime
421 .atom((get) =>
422 Effect.gen(function* () {
423 const base = {
424 operation: "environment-status" as const,
425 accountId,
426 environmentId: environment.environmentId,
427 };
428 const clerkToken = yield* observe(
429 { ...base, stage: "clerk-token" },
430 requireClerkToken(get, accountId),
431 );
432 const relay = yield* ManagedRelay.ManagedRelayClient;
433 const status = yield* observe(
434 { ...base, stage: "relay-request" },
435 relay.getEnvironmentStatus({
436 clerkToken,
437 scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],
438 environmentId: environment.environmentId,
439 }),
440 );
441 return yield* observe(
442 { ...base, stage: "validation" },
443 validateEnvironmentStatus(environment, status),
444 );
445 }),
446 )
447 .pipe(
448 Atom.swr({ staleTime, revalidateOnMount: true }),
449 Atom.setIdleTTL(idleTtl),
450 Atom.withLabel(`managed-relay:environment-status:${key}`),
451 );
452 });
453
454 return {
455 environmentsAtom,
456 devicesAtom,
457 environmentStatusAtom: (input: {
458 readonly accountId: string;
459 readonly environment: RelayClientEnvironmentRecord;
460 }) => environmentStatusAtom(statusKey(input)),
461 refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
462 registry.refresh(environmentsAtom(accountId));
463 },
464 refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {
465 registry.refresh(devicesAtom(accountId));
466 },
467 refreshEnvironmentStatus(
468 registry: AtomRegistry.AtomRegistry,
469 input: {
470 readonly accountId: string;
471 readonly environment: RelayClientEnvironmentRecord;
472 },
473 ): void {
474 registry.refresh(environmentStatusAtom(statusKey(input)));
475 },
476 };
477}