Open History to see the last commit
1import type {
2 RelayClientEnvironmentRecord,
3 RelayEnvironmentStatusResponse,
4} from "@t3tools/contracts/relay";
5import {
6 RelayEnvironmentConnectScope,
7 RelayEnvironmentStatusScope,
8} from "@t3tools/contracts/relay";
9import * as Cause from "effect/Cause";
10import * as Data from "effect/Data";
11import * as Effect from "effect/Effect";
12import * as Option from "effect/Option";
13import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity";
14
15import { ManagedRelayClient } from "./managedRelay.ts";
16
17const DEFAULT_STALE_TIME_MS = 15_000;
18const DEFAULT_IDLE_TTL_MS = 5 * 60_000;
19
20export interface ManagedRelaySession {
21 readonly accountId: string;
22 readonly readClerkToken: () => Effect.Effect<string | null, ManagedRelaySessionError>;
23}
24
25export interface ManagedRelaySnapshotState<A> {
26 readonly data: A | null;
27 readonly error: string | null;
28 readonly isPending: boolean;
29}
30
31export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{
32 readonly message: string;
33 readonly cause?: unknown;
34}> {}
35
36export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySnapshotError")<{
37 readonly message: string;
38}> {}
39
40export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
41 Atom.keepAlive,
42 Atom.withLabel("managed-relay:session"),
43);
44
45export function createManagedRelaySession(input: {
46 readonly accountId: string;
47 readonly readClerkToken: () => Promise<string | null>;
48}): ManagedRelaySession {
49 return {
50 accountId: input.accountId,
51 readClerkToken: () =>
52 Effect.tryPromise({
53 try: input.readClerkToken,
54 catch: (cause) =>
55 new ManagedRelaySessionError({
56 message: "Could not obtain the T3 Connect session token.",
57 cause,
58 }),
59 }),
60 };
61}
62
63export function setManagedRelaySession(
64 registry: AtomRegistry.AtomRegistry,
65 session: ManagedRelaySession | null,
66): void {
67 registry.set(managedRelaySessionAtom, session);
68}
69
70function readSessionClerkToken(
71 session: ManagedRelaySession,
72): Effect.Effect<string, ManagedRelaySessionError> {
73 return session.readClerkToken().pipe(
74 Effect.flatMap((token) =>
75 token
76 ? Effect.succeed(token)
77 : Effect.fail(
78 new ManagedRelaySessionError({
79 message: "The T3 Connect session token is unavailable.",
80 }),
81 ),
82 ),
83 );
84}
85
86export function waitForManagedRelayClerkToken(
87 registry: AtomRegistry.AtomRegistry,
88): Effect.Effect<string, ManagedRelaySessionError> {
89 return Effect.callback<string, ManagedRelaySessionError>((resume) => {
90 let unsubscribe: (() => void) | undefined;
91 let completed = false;
92 const readCurrentSession = () => {
93 if (completed) {
94 return true;
95 }
96 const session = registry.get(managedRelaySessionAtom);
97 if (!session) {
98 return false;
99 }
100 completed = true;
101 unsubscribe?.();
102 resume(readSessionClerkToken(session));
103 return true;
104 };
105
106 if (readCurrentSession()) {
107 return;
108 }
109
110 unsubscribe = registry.subscribe(managedRelaySessionAtom, readCurrentSession);
111 readCurrentSession();
112 return Effect.sync(() => unsubscribe?.());
113 });
114}
115
116function requireClerkToken(
117 get: Atom.AtomContext,
118 accountId: string,
119): Effect.Effect<string, ManagedRelaySessionError> {
120 const session = get(managedRelaySessionAtom);
121 if (!session || session.accountId !== accountId) {
122 return Effect.fail(
123 new ManagedRelaySessionError({
124 message: "Sign in to T3 Connect before loading relay data.",
125 }),
126 );
127 }
128 return readSessionClerkToken(session);
129}
130
131function statusKey(input: {
132 readonly accountId: string;
133 readonly environment: RelayClientEnvironmentRecord;
134}): string {
135 return JSON.stringify(input);
136}
137
138function parseStatusKey(key: string): {
139 readonly accountId: string;
140 readonly environment: RelayClientEnvironmentRecord;
141} {
142 return JSON.parse(key) as {
143 readonly accountId: string;
144 readonly environment: RelayClientEnvironmentRecord;
145 };
146}
147
148function endpointMatches(
149 left: RelayClientEnvironmentRecord["endpoint"],
150 right: RelayClientEnvironmentRecord["endpoint"],
151): boolean {
152 return (
153 left.httpBaseUrl === right.httpBaseUrl &&
154 left.wsBaseUrl === right.wsBaseUrl &&
155 left.providerKind === right.providerKind
156 );
157}
158
159function validateEnvironmentStatus(
160 environment: RelayClientEnvironmentRecord,
161 status: RelayEnvironmentStatusResponse,
162): Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelaySnapshotError> {
163 if (status.environmentId !== environment.environmentId) {
164 return Effect.fail(
165 new ManagedRelaySnapshotError({
166 message: "Relay returned status for a different environment.",
167 }),
168 );
169 }
170 if (!endpointMatches(status.endpoint, environment.endpoint)) {
171 return Effect.fail(
172 new ManagedRelaySnapshotError({
173 message: "Relay returned status for a different endpoint.",
174 }),
175 );
176 }
177 if (status.descriptor && status.descriptor.environmentId !== environment.environmentId) {
178 return Effect.fail(
179 new ManagedRelaySnapshotError({
180 message: "Relay returned status descriptor for a different environment.",
181 }),
182 );
183 }
184 return Effect.succeed(status);
185}
186
187export function readManagedRelaySnapshotState<A>(
188 result: AsyncResult.AsyncResult<A, unknown>,
189): ManagedRelaySnapshotState<A> {
190 let error: string | null = null;
191 if (result._tag === "Failure") {
192 const cause = Cause.squash(result.cause);
193 error = cause instanceof Error ? cause.message : "Could not load T3 Connect data.";
194 }
195 return {
196 data: Option.getOrNull(AsyncResult.value(result)),
197 error,
198 isPending: result.waiting,
199 };
200}
201
202export function createManagedRelayQueryManager(
203 runtime: Atom.AtomRuntime<ManagedRelayClient>,
204 options?: {
205 readonly staleTimeMs?: number;
206 readonly idleTtlMs?: number;
207 },
208) {
209 const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
210 const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
211
212 const environmentsAtom = Atom.family((accountId: string) =>
213 runtime
214 .atom((get) =>
215 Effect.gen(function* () {
216 const clerkToken = yield* requireClerkToken(get, accountId);
217 const relay = yield* ManagedRelayClient;
218 return yield* relay.listEnvironments({ clerkToken });
219 }),
220 )
221 .pipe(
222 Atom.swr({ staleTime, revalidateOnMount: true }),
223 Atom.setIdleTTL(idleTtl),
224 Atom.withLabel(`managed-relay:environments:${accountId}`),
225 ),
226 );
227
228 const devicesAtom = Atom.family((accountId: string) =>
229 runtime
230 .atom((get) =>
231 Effect.gen(function* () {
232 const clerkToken = yield* requireClerkToken(get, accountId);
233 const relay = yield* ManagedRelayClient;
234 return yield* relay.listDevices({ clerkToken });
235 }),
236 )
237 .pipe(
238 Atom.swr({ staleTime, revalidateOnMount: true }),
239 Atom.setIdleTTL(idleTtl),
240 Atom.withLabel(`managed-relay:devices:${accountId}`),
241 ),
242 );
243
244 const environmentStatusAtom = Atom.family((key: string) => {
245 const { accountId, environment } = parseStatusKey(key);
246 return runtime
247 .atom((get) =>
248 Effect.gen(function* () {
249 const clerkToken = yield* requireClerkToken(get, accountId);
250 const relay = yield* ManagedRelayClient;
251 const status = yield* relay.getEnvironmentStatus({
252 clerkToken,
253 scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],
254 environmentId: environment.environmentId,
255 });
256 return yield* validateEnvironmentStatus(environment, status);
257 }),
258 )
259 .pipe(
260 Atom.swr({ staleTime, revalidateOnMount: true }),
261 Atom.setIdleTTL(idleTtl),
262 Atom.withLabel(`managed-relay:environment-status:${key}`),
263 );
264 });
265
266 return {
267 environmentsAtom,
268 devicesAtom,
269 environmentStatusAtom: (input: {
270 readonly accountId: string;
271 readonly environment: RelayClientEnvironmentRecord;
272 }) => environmentStatusAtom(statusKey(input)),
273 refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
274 registry.refresh(environmentsAtom(accountId));
275 },
276 refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {
277 registry.refresh(devicesAtom(accountId));
278 },
279 refreshEnvironmentStatus(
280 registry: AtomRegistry.AtomRegistry,
281 input: {
282 readonly accountId: string;
283 readonly environment: RelayClientEnvironmentRecord;
284 },
285 ): void {
286 registry.refresh(environmentStatusAtom(statusKey(input)));
287 },
288 };
289}