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

managedRelayState.ts

469 lines14.8 KB

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