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