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