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

managedRelayState.ts

463 lines15.0 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 Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import { AsyncResult, Atom, AtomRegistry } from "effect/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>;
33​
34export interface ManagedRelaySessionInput {
35 readonly accountId: string;
36 readonly readClerkToken: () => Promise<string | null>;
38​
39interface ManagedRelaySessionControl {
40 readonly updateReadClerkToken: (
41 readClerkToken: ManagedRelaySessionInput["readClerkToken"],
42 ) => void;
44​
45export interface ManagedRelaySnapshotState<A> {
46 readonly data: A | null;
47 readonly error: string | null;
48 readonly errorTraceId: string | null;
49 readonly isPending: boolean;
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;
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;
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));
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 );
178​
179function readSessionClerkToken(
180 session: ManagedRelaySession,
181): Effect.Effect<string, ManagedRelaySessionError> {
182 return session.readClerkToken().pipe(
183 Effect.filterOrFail(
184 (token): token is string => Boolean(token),
185 () =>
186 new ManagedRelaySessionError({
187 message: "The T3 Connect session token is unavailable.",
188 }),
189 ),
190 );
192​
193export const deregisterManagedRelayEnvironment = Effect.fn(
194 "clientRuntime.managedRelaySession.deregisterEnvironment",
195)(function* (
196 registry: AtomRegistry.AtomRegistry,
197 input: { readonly accountId: string; readonly environmentId: EnvironmentId },
198) {
199 const session = registry.get(managedRelaySessionAtom);
200 if (!session || session.accountId !== input.accountId) {
201 return yield* new ManagedRelaySessionError({
202 message: "Sign in to T3 Connect before deregistering an environment.",
203 });
204 }
205 const clerkToken = yield* readSessionClerkToken(session);
206 const relay = yield* ManagedRelay.ManagedRelayClient;
207 yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId });
208});
209​
210function requireClerkToken(
211 get: Atom.AtomContext,
212 accountId: string,
213): Effect.Effect<string, ManagedRelaySessionError> {
214 const session = get(managedRelaySessionAtom);
215 if (!session || session.accountId !== accountId) {
216 return Effect.fail(
217 new ManagedRelaySessionError({
218 message: "Sign in to T3 Connect before loading relay data.",
219 }),
220 );
221 }
222 return readSessionClerkToken(session);
224​
225function statusKey(input: {
226 readonly accountId: string;
227 readonly environment: RelayClientEnvironmentRecord;
228}): string {
229 return JSON.stringify(input);
231​
232function parseStatusKey(key: string): {
233 readonly accountId: string;
234 readonly environment: RelayClientEnvironmentRecord;
235} {
236 return JSON.parse(key) as {
237 readonly accountId: string;
238 readonly environment: RelayClientEnvironmentRecord;
239 };
241​
242function endpointMatches(
243 left: RelayClientEnvironmentRecord["endpoint"],
244 right: RelayClientEnvironmentRecord["endpoint"],
245): boolean {
246 return (
247 left.httpBaseUrl === right.httpBaseUrl &&
248 left.wsBaseUrl === right.wsBaseUrl &&
249 left.providerKind === right.providerKind
250 );
252​
253function validateEnvironmentStatus(
254 environment: RelayClientEnvironmentRecord,
255 status: RelayEnvironmentStatusResponse,
256): Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelaySnapshotError> {
257 if (status.environmentId !== environment.environmentId) {
258 return Effect.fail(
259 new ManagedRelaySnapshotError({
260 message: "Relay returned status for a different environment.",
261 }),
262 );
263 }
264 if (!endpointMatches(status.endpoint, environment.endpoint)) {
265 return Effect.fail(
266 new ManagedRelaySnapshotError({
267 message: "Relay returned status for a different endpoint.",
268 }),
269 );
270 }
271 if (status.descriptor && status.descriptor.environmentId !== environment.environmentId) {
272 return Effect.fail(
273 new ManagedRelaySnapshotError({
274 message: "Relay returned status descriptor for a different environment.",
275 }),
276 );
277 }
278 return Effect.succeed(status);
280​
281function describeManagedRelayFailure(cause: Cause.Cause<unknown>): {
282 readonly message: string;
283 readonly traceId: string | null;
284} {
285 const error = Cause.squash(cause);
286 return {
287 message:
288 isManagedRelayRequestFailedError(error) && error.relayError
289 ? relayProtectedErrorMessage(error.relayError)
290 : error instanceof Error
291 ? error.message
292 : "Could not load T3 Connect data.",
293 traceId: findErrorTraceId(error),
294 };
296​
297export function readManagedRelaySnapshotState<A>(
298 result: AsyncResult.AsyncResult<A, unknown>,
299): ManagedRelaySnapshotState<A> {
300 const failure = result._tag === "Failure" ? describeManagedRelayFailure(result.cause) : null;
301 return {
302 data: Option.getOrNull(AsyncResult.value(result)),
303 error: failure?.message ?? null,
304 errorTraceId: failure?.traceId ?? null,
305 isPending: result.waiting,
306 };
308​
309// Logged where the listing runs so each failed fetch reports once, however many
310// components read the atom.
311const logListingFailure =
312 (label: string) =>
313 <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
314 self.pipe(
315 Effect.tapCause((cause) => {
316 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
317 const { message, traceId } = describeManagedRelayFailure(cause);
318 return Effect.logError(`[t3-cloud] Relay ${label} listing failed`).pipe(
319 Effect.annotateLogs({ message, traceId }),
320 );
321 }),
322 );
323​
324export function createManagedRelayQueryManager(
325 runtime: Atom.AtomRuntime<ManagedRelay.ManagedRelayClient>,
326 options?: {
327 readonly staleTimeMs?: number;
328 readonly idleTtlMs?: number;
329 readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;
330 },
331) {
332 const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
333 const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
334 const observe = Effect.fn("managedRelayState.observe")(function* <A, E, R>(
335 input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
336 effect: Effect.Effect<A, E, R>,
337 ): Effect.fn.Return<A, E, R> {
338 options?.onQueryEvent?.({ ...input, phase: "start" });
339 return yield* effect.pipe(
340 Effect.onExit((exit) =>
341 Effect.sync(() => {
342 if (exit._tag === "Success") {
343 options?.onQueryEvent?.({ ...input, phase: "success" });
344 return;
345 }
346 const error = Cause.squash(exit.cause);
347 options?.onQueryEvent?.({
348 ...input,
349 phase: "failure",
350 message: error instanceof Error ? error.message : String(error),
351 traceId: findErrorTraceId(error),
352 });
353 }),
354 ),
355 );
356 });
357​
358 const environmentsAtom = Atom.family((accountId: string) =>
359 runtime
360 .atom((get) =>
361 Effect.gen(function* () {
362 const base = { operation: "environments" as const, accountId };
363 const clerkToken = yield* observe(
364 { ...base, stage: "clerk-token" },
365 requireClerkToken(get, accountId),
366 );
367 const relay = yield* ManagedRelay.ManagedRelayClient;
368 return yield* observe(
369 { ...base, stage: "relay-request" },
370 relay.listEnvironments({ clerkToken }),
371 );
372 }).pipe(logListingFailure("environment")),
373 )
374 .pipe(
375 Atom.swr({ staleTime, revalidateOnMount: true }),
376 Atom.setIdleTTL(idleTtl),
377 Atom.withLabel(`managed-relay:environments:${accountId}`),
378 ),
379 );
380​
381 const devicesAtom = Atom.family((accountId: string) =>
382 runtime
383 .atom((get) =>
384 Effect.gen(function* () {
385 const base = { operation: "devices" as const, accountId };
386 const clerkToken = yield* observe(
387 { ...base, stage: "clerk-token" },
388 requireClerkToken(get, accountId),
389 );
390 const relay = yield* ManagedRelay.ManagedRelayClient;
391 return yield* observe(
392 { ...base, stage: "relay-request" },
393 relay.listDevices({ clerkToken }),
394 );
395 }).pipe(logListingFailure("device")),
396 )
397 .pipe(
398 Atom.swr({ staleTime, revalidateOnMount: true }),
399 Atom.setIdleTTL(idleTtl),
400 Atom.withLabel(`managed-relay:devices:${accountId}`),
401 ),
402 );
403​
404 const environmentStatusAtom = Atom.family((key: string) => {
405 const { accountId, environment } = parseStatusKey(key);
406 return runtime
407 .atom((get) =>
408 Effect.gen(function* () {
409 const base = {
410 operation: "environment-status" as const,
411 accountId,
412 environmentId: environment.environmentId,
413 };
414 const clerkToken = yield* observe(
415 { ...base, stage: "clerk-token" },
416 requireClerkToken(get, accountId),
417 );
418 const relay = yield* ManagedRelay.ManagedRelayClient;
419 const status = yield* observe(
420 { ...base, stage: "relay-request" },
421 relay.getEnvironmentStatus({
422 clerkToken,
423 scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],
424 environmentId: environment.environmentId,
425 }),
426 );
427 return yield* observe(
428 { ...base, stage: "validation" },
429 validateEnvironmentStatus(environment, status),
430 );
431 }),
432 )
433 .pipe(
434 Atom.swr({ staleTime, revalidateOnMount: true }),
435 Atom.setIdleTTL(idleTtl),
436 Atom.withLabel(`managed-relay:environment-status:${key}`),
437 );
438 });
439​
440 return {
441 environmentsAtom,
442 devicesAtom,
443 environmentStatusAtom: (input: {
444 readonly accountId: string;
445 readonly environment: RelayClientEnvironmentRecord;
446 }) => environmentStatusAtom(statusKey(input)),
447 refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
448 registry.refresh(environmentsAtom(accountId));
449 },
450 refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {
451 registry.refresh(devicesAtom(accountId));
452 },
453 refreshEnvironmentStatus(
454 registry: AtomRegistry.AtomRegistry,
455 input: {
456 readonly accountId: string;
457 readonly environment: RelayClientEnvironmentRecord;
458 },
459 ): void {
460 registry.refresh(environmentStatusAtom(statusKey(input)));
461 },
462 };