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

managedRelayState.ts

443 lines14.2 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​
281export function readManagedRelaySnapshotState<A>(
282 result: AsyncResult.AsyncResult<A, unknown>,
283): ManagedRelaySnapshotState<A> {
284 let error: string | null = null;
285 let errorTraceId: string | null = null;
286 if (result._tag === "Failure") {
287 const cause = Cause.squash(result.cause);
288 error =
289 isManagedRelayRequestFailedError(cause) && cause.relayError
290 ? relayProtectedErrorMessage(cause.relayError)
291 : cause instanceof Error
292 ? cause.message
293 : "Could not load T3 Connect data.";
294 errorTraceId = findErrorTraceId(cause);
295 }
296 return {
297 data: Option.getOrNull(AsyncResult.value(result)),
298 error,
299 errorTraceId,
300 isPending: result.waiting,
301 };
303​
304export function createManagedRelayQueryManager(
305 runtime: Atom.AtomRuntime<ManagedRelay.ManagedRelayClient>,
306 options?: {
307 readonly staleTimeMs?: number;
308 readonly idleTtlMs?: number;
309 readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;
310 },
311) {
312 const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
313 const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
314 const observe = Effect.fn("managedRelayState.observe")(function* <A, E, R>(
315 input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
316 effect: Effect.Effect<A, E, R>,
317 ): Effect.fn.Return<A, E, R> {
318 options?.onQueryEvent?.({ ...input, phase: "start" });
319 return yield* effect.pipe(
320 Effect.onExit((exit) =>
321 Effect.sync(() => {
322 if (exit._tag === "Success") {
323 options?.onQueryEvent?.({ ...input, phase: "success" });
324 return;
325 }
326 const error = Cause.squash(exit.cause);
327 options?.onQueryEvent?.({
328 ...input,
329 phase: "failure",
330 message: error instanceof Error ? error.message : String(error),
331 traceId: findErrorTraceId(error),
332 });
333 }),
334 ),
335 );
336 });
337​
338 const environmentsAtom = Atom.family((accountId: string) =>
339 runtime
340 .atom((get) =>
341 Effect.gen(function* () {
342 const base = { operation: "environments" as const, accountId };
343 const clerkToken = yield* observe(
344 { ...base, stage: "clerk-token" },
345 requireClerkToken(get, accountId),
346 );
347 const relay = yield* ManagedRelay.ManagedRelayClient;
348 return yield* observe(
349 { ...base, stage: "relay-request" },
350 relay.listEnvironments({ clerkToken }),
351 );
352 }),
353 )
354 .pipe(
355 Atom.swr({ staleTime, revalidateOnMount: true }),
356 Atom.setIdleTTL(idleTtl),
357 Atom.withLabel(`managed-relay:environments:${accountId}`),
358 ),
359 );
360​
361 const devicesAtom = Atom.family((accountId: string) =>
362 runtime
363 .atom((get) =>
364 Effect.gen(function* () {
365 const base = { operation: "devices" as const, accountId };
366 const clerkToken = yield* observe(
367 { ...base, stage: "clerk-token" },
368 requireClerkToken(get, accountId),
369 );
370 const relay = yield* ManagedRelay.ManagedRelayClient;
371 return yield* observe(
372 { ...base, stage: "relay-request" },
373 relay.listDevices({ clerkToken }),
374 );
375 }),
376 )
377 .pipe(
378 Atom.swr({ staleTime, revalidateOnMount: true }),
379 Atom.setIdleTTL(idleTtl),
380 Atom.withLabel(`managed-relay:devices:${accountId}`),
381 ),
382 );
383​
384 const environmentStatusAtom = Atom.family((key: string) => {
385 const { accountId, environment } = parseStatusKey(key);
386 return runtime
387 .atom((get) =>
388 Effect.gen(function* () {
389 const base = {
390 operation: "environment-status" as const,
391 accountId,
392 environmentId: environment.environmentId,
393 };
394 const clerkToken = yield* observe(
395 { ...base, stage: "clerk-token" },
396 requireClerkToken(get, accountId),
397 );
398 const relay = yield* ManagedRelay.ManagedRelayClient;
399 const status = yield* observe(
400 { ...base, stage: "relay-request" },
401 relay.getEnvironmentStatus({
402 clerkToken,
403 scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],
404 environmentId: environment.environmentId,
405 }),
406 );
407 return yield* observe(
408 { ...base, stage: "validation" },
409 validateEnvironmentStatus(environment, status),
410 );
411 }),
412 )
413 .pipe(
414 Atom.swr({ staleTime, revalidateOnMount: true }),
415 Atom.setIdleTTL(idleTtl),
416 Atom.withLabel(`managed-relay:environment-status:${key}`),
417 );
418 });
419​
420 return {
421 environmentsAtom,
422 devicesAtom,
423 environmentStatusAtom: (input: {
424 readonly accountId: string;
425 readonly environment: RelayClientEnvironmentRecord;
426 }) => environmentStatusAtom(statusKey(input)),
427 refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
428 registry.refresh(environmentsAtom(accountId));
429 },
430 refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {
431 registry.refresh(devicesAtom(accountId));
432 },
433 refreshEnvironmentStatus(
434 registry: AtomRegistry.AtomRegistry,
435 input: {
436 readonly accountId: string;
437 readonly environment: RelayClientEnvironmentRecord;
438 },
439 ): void {
440 registry.refresh(environmentStatusAtom(statusKey(input)));
441 },
442 };