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

managedRelayState.ts

447 lines14.3 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/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>;
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.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 );
194​
195/** Removes an environment from the signed-in account without contacting that environment. */
196export const deregisterManagedRelayEnvironment = Effect.fn(
197 "clientRuntime.managedRelaySession.deregisterEnvironment",
198)(function* (
199 registry: AtomRegistry.AtomRegistry,
200 input: { readonly accountId: string; readonly environmentId: EnvironmentId },
201) {
202 const session = registry.get(managedRelaySessionAtom);
203 if (!session || session.accountId !== input.accountId) {
204 return yield* new ManagedRelaySessionError({
205 message: "Sign in to T3 Connect before deregistering an environment.",
206 });
207 }
208 const clerkToken = yield* readSessionClerkToken(session);
209 const relay = yield* ManagedRelay.ManagedRelayClient;
210 yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId });
211});
212​
213function requireClerkToken(
214 get: Atom.AtomContext,
215 accountId: string,
216): Effect.Effect<string, ManagedRelaySessionError> {
217 const session = get(managedRelaySessionAtom);
218 if (!session || session.accountId !== accountId) {
219 return Effect.fail(
220 new ManagedRelaySessionError({
221 message: "Sign in to T3 Connect before loading relay data.",
222 }),
223 );
224 }
225 return readSessionClerkToken(session);
227​
228function statusKey(input: {
229 readonly accountId: string;
230 readonly environment: RelayClientEnvironmentRecord;
231}): string {
232 return JSON.stringify(input);
234​
235function parseStatusKey(key: string): {
236 readonly accountId: string;
237 readonly environment: RelayClientEnvironmentRecord;
238} {
239 return JSON.parse(key) as {
240 readonly accountId: string;
241 readonly environment: RelayClientEnvironmentRecord;
242 };
244​
245function endpointMatches(
246 left: RelayClientEnvironmentRecord["endpoint"],
247 right: RelayClientEnvironmentRecord["endpoint"],
248): boolean {
249 return (
250 left.httpBaseUrl === right.httpBaseUrl &&
251 left.wsBaseUrl === right.wsBaseUrl &&
252 left.providerKind === right.providerKind
253 );
255​
256function validateEnvironmentStatus(
257 environment: RelayClientEnvironmentRecord,
258 status: RelayEnvironmentStatusResponse,
259): Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelaySnapshotError> {
260 if (status.environmentId !== environment.environmentId) {
261 return Effect.fail(
262 new ManagedRelaySnapshotError({
263 message: "Relay returned status for a different environment.",
264 }),
265 );
266 }
267 if (!endpointMatches(status.endpoint, environment.endpoint)) {
268 return Effect.fail(
269 new ManagedRelaySnapshotError({
270 message: "Relay returned status for a different endpoint.",
271 }),
272 );
273 }
274 if (status.descriptor && status.descriptor.environmentId !== environment.environmentId) {
275 return Effect.fail(
276 new ManagedRelaySnapshotError({
277 message: "Relay returned status descriptor for a different environment.",
278 }),
279 );
280 }
281 return Effect.succeed(status);
283​
284export function readManagedRelaySnapshotState<A>(
285 result: AsyncResult.AsyncResult<A, unknown>,
286): ManagedRelaySnapshotState<A> {
287 let error: string | null = null;
288 let errorTraceId: string | null = null;
289 if (result._tag === "Failure") {
290 const cause = Cause.squash(result.cause);
291 error =
292 isManagedRelayRequestFailedError(cause) && cause.relayError
293 ? relayProtectedErrorMessage(cause.relayError)
294 : cause instanceof Error
295 ? cause.message
296 : "Could not load T3 Connect data.";
297 errorTraceId = findErrorTraceId(cause);
298 }
299 return {
300 data: Option.getOrNull(AsyncResult.value(result)),
301 error,
302 errorTraceId,
303 isPending: result.waiting,
304 };
306​
307export function createManagedRelayQueryManager(
308 runtime: Atom.AtomRuntime<ManagedRelay.ManagedRelayClient>,
309 options?: {
310 readonly staleTimeMs?: number;
311 readonly idleTtlMs?: number;
312 readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;
313 },
314) {
315 const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
316 const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
317 const observe = <A, E, R>(
318 input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
319 effect: Effect.Effect<A, E, R>,
320 ): Effect.Effect<A, E, R> =>
321 Effect.gen(function* () {
322 options?.onQueryEvent?.({ ...input, phase: "start" });
323 return yield* effect.pipe(
324 Effect.onExit((exit) =>
325 Effect.sync(() => {
326 if (exit._tag === "Success") {
327 options?.onQueryEvent?.({ ...input, phase: "success" });
328 return;
329 }
330 const error = Cause.squash(exit.cause);
331 options?.onQueryEvent?.({
332 ...input,
333 phase: "failure",
334 message: error instanceof Error ? error.message : String(error),
335 traceId: findErrorTraceId(error),
336 });
337 }),
338 ),
339 );
340 });
341​
342 const environmentsAtom = Atom.family((accountId: string) =>
343 runtime
344 .atom((get) =>
345 Effect.gen(function* () {
346 const base = { operation: "environments" as const, accountId };
347 const clerkToken = yield* observe(
348 { ...base, stage: "clerk-token" },
349 requireClerkToken(get, accountId),
350 );
351 const relay = yield* ManagedRelay.ManagedRelayClient;
352 return yield* observe(
353 { ...base, stage: "relay-request" },
354 relay.listEnvironments({ clerkToken }),
355 );
356 }),
357 )
358 .pipe(
359 Atom.swr({ staleTime, revalidateOnMount: true }),
360 Atom.setIdleTTL(idleTtl),
361 Atom.withLabel(`managed-relay:environments:${accountId}`),
362 ),
363 );
364​
365 const devicesAtom = Atom.family((accountId: string) =>
366 runtime
367 .atom((get) =>
368 Effect.gen(function* () {
369 const base = { operation: "devices" as const, accountId };
370 const clerkToken = yield* observe(
371 { ...base, stage: "clerk-token" },
372 requireClerkToken(get, accountId),
373 );
374 const relay = yield* ManagedRelay.ManagedRelayClient;
375 return yield* observe(
376 { ...base, stage: "relay-request" },
377 relay.listDevices({ clerkToken }),
378 );
379 }),
380 )
381 .pipe(
382 Atom.swr({ staleTime, revalidateOnMount: true }),
383 Atom.setIdleTTL(idleTtl),
384 Atom.withLabel(`managed-relay:devices:${accountId}`),
385 ),
386 );
387​
388 const environmentStatusAtom = Atom.family((key: string) => {
389 const { accountId, environment } = parseStatusKey(key);
390 return runtime
391 .atom((get) =>
392 Effect.gen(function* () {
393 const base = {
394 operation: "environment-status" as const,
395 accountId,
396 environmentId: environment.environmentId,
397 };
398 const clerkToken = yield* observe(
399 { ...base, stage: "clerk-token" },
400 requireClerkToken(get, accountId),
401 );
402 const relay = yield* ManagedRelay.ManagedRelayClient;
403 const status = yield* observe(
404 { ...base, stage: "relay-request" },
405 relay.getEnvironmentStatus({
406 clerkToken,
407 scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],
408 environmentId: environment.environmentId,
409 }),
410 );
411 return yield* observe(
412 { ...base, stage: "validation" },
413 validateEnvironmentStatus(environment, status),
414 );
415 }),
416 )
417 .pipe(
418 Atom.swr({ staleTime, revalidateOnMount: true }),
419 Atom.setIdleTTL(idleTtl),
420 Atom.withLabel(`managed-relay:environment-status:${key}`),
421 );
422 });
423​
424 return {
425 environmentsAtom,
426 devicesAtom,
427 environmentStatusAtom: (input: {
428 readonly accountId: string;
429 readonly environment: RelayClientEnvironmentRecord;
430 }) => environmentStatusAtom(statusKey(input)),
431 refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
432 registry.refresh(environmentsAtom(accountId));
433 },
434 refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {
435 registry.refresh(devicesAtom(accountId));
436 },
437 refreshEnvironmentStatus(
438 registry: AtomRegistry.AtomRegistry,
439 input: {
440 readonly accountId: string;
441 readonly environment: RelayClientEnvironmentRecord;
442 },
443 ): void {
444 registry.refresh(environmentStatusAtom(statusKey(input)));
445 },
446 };