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

managedRelayState.ts

406 lines13.4 KB

1import type { EnvironmentId } from "@t3tools/contracts";
2import { decodeRelayJwt } from "@t3tools/shared/relayJwt";
3import * as Cause from "effect/Cause";
4import * as Clock from "effect/Clock";
5import * as Data from "effect/Data";
6import * as Effect from "effect/Effect";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
10​
11import { findErrorTraceId } from "../errors/errorTrace.ts";
12import * as ManagedRelay from "./managedRelay.ts";
13import { relayProtectedErrorMessage } from "./errorPresentation.ts";
14​
15const DEFAULT_STALE_TIME_MS = 15_000;
16const DEFAULT_IDLE_TTL_MS = 5 * 60_000;
17const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000;
18const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
19​
20export interface ManagedRelaySession {
21 readonly accountId: string;
22 readonly readClerkToken: () => Effect.Effect<string | null, ManagedRelaySessionError>;
24​
25export interface ManagedRelaySessionInput {
26 readonly accountId: string;
27 readonly readClerkToken: () => Promise<string | null>;
29​
30interface ManagedRelaySessionControl {
31 readonly updateReadClerkToken: (
32 readClerkToken: ManagedRelaySessionInput["readClerkToken"],
33 ) => void;
35​
36export interface ManagedRelaySnapshotState<A> {
37 readonly data: A | null;
38 readonly error: string | null;
39 readonly errorTraceId: string | null;
40 readonly isPending: boolean;
42​
43export interface ManagedRelayQueryEvent {
44 readonly operation: "environments" | "devices" | "t3chat-link";
45 readonly stage: "clerk-token" | "relay-request";
46 readonly phase: "start" | "success" | "failure";
47 readonly accountId: string;
48 readonly environmentId?: string;
49 readonly message?: string;
50 readonly traceId?: string | null;
52​
53export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{
54 readonly message: string;
55 readonly cause?: unknown;
56}> {}
57​
58export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
59 Atom.keepAlive,
60 Atom.withLabel("managed-relay:session"),
61);
62​
63const managedRelaySessionControls = new WeakMap<ManagedRelaySession, ManagedRelaySessionControl>();
64​
65export function createManagedRelaySession(input: ManagedRelaySessionInput): ManagedRelaySession {
66 let cachedToken: { readonly token: string; readonly expiresAtMillis: number } | null = null;
67 let pendingToken: Promise<string | null> | null = null;
68 let readClerkToken = input.readClerkToken;
69 let tokenProviderGeneration = 0;
70​
71 const readCachedClerkToken = async (nowMillis: number): Promise<string | null> => {
72 if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) {
73 return cachedToken.token;
74 }
75 if (pendingToken) {
76 return await pendingToken;
77 }
78​
79 const operationGeneration = tokenProviderGeneration;
80 const operation = readClerkToken().then((token) => {
81 if (operationGeneration !== tokenProviderGeneration) {
82 return token;
83 }
84 if (!token) {
85 cachedToken = null;
86 return null;
87 }
88 const expiresAtSeconds = Effect.runSync(
89 decodeRelayJwt(token).pipe(
90 Effect.map((claims) => claims.exp),
91 Effect.orElseSucceed(() => undefined),
92 ),
93 );
94 cachedToken =
95 typeof expiresAtSeconds === "number"
96 ? { token, expiresAtMillis: expiresAtSeconds * 1_000 }
97 : null;
98 return token;
99 });
100 pendingToken = operation;
101 try {
102 return await operation;
103 } finally {
104 if (pendingToken === operation) {
105 pendingToken = null;
106 }
107 }
108 };
109​
110 const session: ManagedRelaySession = {
111 accountId: input.accountId,
112 readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () {
113 const nowMillis = yield* Clock.currentTimeMillis;
114 return yield* Effect.tryPromise({
115 try: () => readCachedClerkToken(nowMillis),
116 catch: (cause) =>
117 new ManagedRelaySessionError({
118 message: "Could not obtain the T3 Connect session token.",
119 cause,
120 }),
121 });
122 }),
123 };
124 managedRelaySessionControls.set(session, {
125 updateReadClerkToken: (nextReadClerkToken) => {
126 readClerkToken = nextReadClerkToken;
127 tokenProviderGeneration += 1;
128 pendingToken = null;
129 },
130 });
131 return session;
133​
134export function setManagedRelaySession(
135 registry: AtomRegistry.AtomRegistry,
136 input: ManagedRelaySessionInput | null,
137): void {
138 const current = registry.get(managedRelaySessionAtom);
139 if (input === null) {
140 if (current !== null) {
141 registry.set(managedRelaySessionAtom, null);
142 }
143 return;
144 }
145 if (current?.accountId === input.accountId) {
146 const control = managedRelaySessionControls.get(current);
147 if (control) {
148 // Clerk can replace its token reader during routine same-account refreshes.
149 // Keep the session stable so those refreshes do not invalidate queries or reconnect leases.
150 control.updateReadClerkToken(input.readClerkToken);
151 return;
152 }
153 }
154 registry.set(managedRelaySessionAtom, createManagedRelaySession(input));
156​
157export function managedRelayAccountChanges(
158 registry: AtomRegistry.AtomRegistry,
159): Stream.Stream<string | null> {
160 return AtomRegistry.toStream(registry, managedRelaySessionAtom).pipe(
161 Stream.map((session) => session?.accountId ?? null),
162 Stream.changes,
163 Stream.drop(1),
164 );
166​
167function readSessionClerkToken(
168 session: ManagedRelaySession,
169): Effect.Effect<string, ManagedRelaySessionError> {
170 return session.readClerkToken().pipe(
171 Effect.filterOrFail(
172 (token): token is string => Boolean(token),
173 () =>
174 new ManagedRelaySessionError({
175 message: "The T3 Connect session token is unavailable.",
176 }),
177 ),
178 );
180​
181function requireSessionClerkToken(
182 registry: AtomRegistry.AtomRegistry,
183 accountId: string,
184 action: string,
185): Effect.Effect<string, ManagedRelaySessionError> {
186 const session = registry.get(managedRelaySessionAtom);
187 if (!session || session.accountId !== accountId) {
188 return Effect.fail(
189 new ManagedRelaySessionError({ message: `Sign in to T3 Connect before ${action}.` }),
190 );
191 }
192 return readSessionClerkToken(session);
194​
195export const deregisterManagedRelayEnvironment = Effect.fn(
196 "clientRuntime.managedRelaySession.deregisterEnvironment",
197)(function* (
198 registry: AtomRegistry.AtomRegistry,
199 input: { readonly accountId: string; readonly environmentId: EnvironmentId },
200) {
201 const clerkToken = yield* requireSessionClerkToken(
202 registry,
203 input.accountId,
204 "deregistering an environment",
205 );
206 const relay = yield* ManagedRelay.ManagedRelayClient;
207 yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId });
208});
209​
210/** Returns the T3 Chat page URL where the signed-in user confirms the link. */
211export const createManagedRelayT3ChatLinkRequest = Effect.fn(
212 "clientRuntime.managedRelaySession.createT3ChatLinkRequest",
213)(function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) {
214 const clerkToken = yield* requireSessionClerkToken(registry, input.accountId, "linking T3 Chat");
215 const relay = yield* ManagedRelay.ManagedRelayClient;
216 return (yield* relay.createT3ChatLinkRequest({ clerkToken })).url;
217});
218​
219export const unlinkManagedRelayT3Chat = Effect.fn("clientRuntime.managedRelaySession.unlinkT3Chat")(
220 function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) {
221 const clerkToken = yield* requireSessionClerkToken(
222 registry,
223 input.accountId,
224 "unlinking T3 Chat",
225 );
226 const relay = yield* ManagedRelay.ManagedRelayClient;
227 yield* relay.unlinkT3Chat({ clerkToken });
228 },
229);
230​
231function requireClerkToken(
232 get: Atom.AtomContext,
233 accountId: string,
234): Effect.Effect<string, ManagedRelaySessionError> {
235 const session = get(managedRelaySessionAtom);
236 if (!session || session.accountId !== accountId) {
237 return Effect.fail(
238 new ManagedRelaySessionError({
239 message: "Sign in to T3 Connect before loading relay data.",
240 }),
241 );
242 }
243 return readSessionClerkToken(session);
245​
246function describeManagedRelayFailure(cause: Cause.Cause<unknown>): {
247 readonly message: string;
248 readonly traceId: string | null;
249} {
250 const error = Cause.squash(cause);
251 return {
252 message:
253 isManagedRelayRequestFailedError(error) && error.relayError
254 ? relayProtectedErrorMessage(error.relayError)
255 : error instanceof Error
256 ? error.message
257 : "Could not load T3 Connect data.",
258 traceId: findErrorTraceId(error),
259 };
261​
262export function readManagedRelaySnapshotState<A>(
263 result: AsyncResult.AsyncResult<A, unknown>,
264): ManagedRelaySnapshotState<A> {
265 const failure = result._tag === "Failure" ? describeManagedRelayFailure(result.cause) : null;
266 return {
267 data: AsyncResult.getOrElse(result, () => null),
268 error: failure?.message ?? null,
269 errorTraceId: failure?.traceId ?? null,
270 isPending: result.waiting,
271 };
273​
274// Logged where the listing runs so each failed fetch reports once, however many
275// components read the atom.
276const logListingFailure =
277 (label: string) =>
278 <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
279 self.pipe(
280 Effect.tapCause((cause) => {
281 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
282 const { message, traceId } = describeManagedRelayFailure(cause);
283 return Effect.logError(`[t3-cloud] Relay ${label} listing failed`).pipe(
284 Effect.annotateLogs({ message, traceId }),
285 );
286 }),
287 );
288​
289export function createManagedRelayQueryManager(
290 runtime: Atom.AtomRuntime<ManagedRelay.ManagedRelayClient>,
291 options?: {
292 readonly staleTimeMs?: number;
293 readonly idleTtlMs?: number;
294 readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;
295 },
296) {
297 const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
298 const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
299 const observe = Effect.fn("managedRelayState.observe")(function* <A, E, R>(
300 input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
301 effect: Effect.Effect<A, E, R>,
302 ): Effect.fn.Return<A, E, R> {
303 options?.onQueryEvent?.({ ...input, phase: "start" });
304 return yield* effect.pipe(
305 Effect.onExit((exit) =>
306 Effect.sync(() => {
307 if (exit._tag === "Success") {
308 options?.onQueryEvent?.({ ...input, phase: "success" });
309 return;
310 }
311 const error = Cause.squash(exit.cause);
312 options?.onQueryEvent?.({
313 ...input,
314 phase: "failure",
315 message: error instanceof Error ? error.message : String(error),
316 traceId: findErrorTraceId(error),
317 });
318 }),
319 ),
320 );
321 });
322​
323 const environmentsAtom = Atom.family((accountId: string) =>
324 runtime
325 .atom((get) =>
326 Effect.gen(function* () {
327 const base = { operation: "environments" as const, accountId };
328 const clerkToken = yield* observe(
329 { ...base, stage: "clerk-token" },
330 requireClerkToken(get, accountId),
331 );
332 const relay = yield* ManagedRelay.ManagedRelayClient;
333 return yield* observe(
334 { ...base, stage: "relay-request" },
335 relay.listEnvironments({ clerkToken }),
336 );
337 }).pipe(logListingFailure("environment")),
338 )
339 .pipe(
340 Atom.swr({ staleTime, revalidateOnMount: true }),
341 Atom.setIdleTTL(idleTtl),
342 Atom.withLabel(`managed-relay:environments:${accountId}`),
343 ),
344 );
345​
346 const devicesAtom = Atom.family((accountId: string) =>
347 runtime
348 .atom((get) =>
349 Effect.gen(function* () {
350 const base = { operation: "devices" as const, accountId };
351 const clerkToken = yield* observe(
352 { ...base, stage: "clerk-token" },
353 requireClerkToken(get, accountId),
354 );
355 const relay = yield* ManagedRelay.ManagedRelayClient;
356 return yield* observe(
357 { ...base, stage: "relay-request" },
358 relay.listDevices({ clerkToken }),
359 );
360 }).pipe(logListingFailure("device")),
361 )
362 .pipe(
363 Atom.swr({ staleTime, revalidateOnMount: true }),
364 Atom.setIdleTTL(idleTtl),
365 Atom.withLabel(`managed-relay:devices:${accountId}`),
366 ),
367 );
368​
369 const t3ChatLinkAtom = Atom.family((accountId: string) =>
370 runtime
371 .atom((get) =>
372 Effect.gen(function* () {
373 const base = { operation: "t3chat-link" as const, accountId };
374 const clerkToken = yield* observe(
375 { ...base, stage: "clerk-token" },
376 requireClerkToken(get, accountId),
377 );
378 const relay = yield* ManagedRelay.ManagedRelayClient;
379 return yield* observe(
380 { ...base, stage: "relay-request" },
381 relay.getT3ChatLink({ clerkToken }),
382 );
383 }),
384 )
385 .pipe(
386 Atom.swr({ staleTime, revalidateOnMount: true }),
387 Atom.setIdleTTL(idleTtl),
388 Atom.withLabel(`managed-relay:t3chat-link:${accountId}`),
389 ),
390 );
391​
392 return {
393 environmentsAtom,
394 devicesAtom,
395 t3ChatLinkAtom,
396 refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
397 registry.refresh(environmentsAtom(accountId));
398 },
399 refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {
400 registry.refresh(devicesAtom(accountId));
401 },
402 refreshT3ChatLink(registry: AtomRegistry.AtomRegistry, accountId: string): void {
403 registry.refresh(t3ChatLinkAtom(accountId));
404 },
405 };