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

managedRelayState.ts

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