Open History to see the last commit
1import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Stream from "effect/Stream";
5import * as SubscriptionRef from "effect/SubscriptionRef";
6import type { HttpClient } from "effect/unstable/http";
7import { AsyncResult, Atom } from "effect/unstable/reactivity";
8
9import { EnvironmentRegistry } from "../connection/registry.ts";
10import type { PreparedConnection } from "../connection/model.ts";
11import { EnvironmentSupervisor } from "../connection/supervisor.ts";
12import { environmentEndpointUrl } from "../environment/endpoint.ts";
13import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
14import { safeErrorLogAttributes } from "../errors/safeLog.ts";
15import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts";
16import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
17import { followStreamInEnvironment } from "./runtime.ts";
18
19export function initialConfigOption<E>(
20 initialConfig: Effect.Effect<ServerConfig, E>,
21): Effect.Effect<Option.Option<ServerConfig>> {
22 return initialConfig.pipe(
23 Effect.map(Option.some),
24 Effect.catch((error) =>
25 Effect.logWarning("Could not load the initial environment configuration.").pipe(
26 Effect.annotateLogs({ ...safeErrorLogAttributes(error) }),
27 Effect.as(Option.none<ServerConfig>()),
28 ),
29 ),
30 );
31}
32
33// Bounded like the snapshot fetches: a wedged environment must not pin the
34// permissions check (and with it the settings UI) in a loading state for long.
35const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;
36
37/**
38 * Read the granted scopes of this client's session on one environment via its
39 * `/api/auth/session` endpoint, authenticated with whatever credential the
40 * connection was prepared with (cookie, bearer, or DPoP).
41 */
42export const fetchEnvironmentSessionState = Effect.fn(
43 "clientRuntime.state.fetchEnvironmentSessionState",
44)(function* (input: {
45 readonly prepared: PreparedConnection;
46 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
47 readonly timeoutMs?: number;
48}) {
49 const requestUrl = environmentEndpointUrl(input.prepared.httpBaseUrl, "/api/auth/session");
50 const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
51 const headers = yield* buildEnvironmentAuthHeaders(
52 input.prepared.httpAuthorization,
53 "GET",
54 requestUrl,
55 input.signer,
56 );
57 return yield* executeEnvironmentHttpRequest(
58 requestUrl,
59 input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS,
60 withEnvironmentCredentials(input.prepared.httpAuthorization, client.auth.session({ headers })),
61 );
62});
63
64export function createEnvironmentSessionAtoms<R, E>(
65 runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
66) {
67 const initialConfigAtom = Atom.family((environmentId: EnvironmentId) =>
68 runtime.atom(
69 followStreamInEnvironment(
70 environmentId,
71 Stream.unwrap(
72 EnvironmentSupervisor.pipe(
73 Effect.map((supervisor) =>
74 SubscriptionRef.changes(supervisor.session).pipe(
75 Stream.mapEffect(
76 Option.match({
77 onNone: () => Effect.succeed(Option.none<ServerConfig>()),
78 onSome: (session) => initialConfigOption(session.initialConfig),
79 }),
80 ),
81 ),
82 ),
83 ),
84 ),
85 ),
86 { initialValue: Option.none() },
87 ),
88 );
89
90 // This is only the bootstrap config captured when a transport session is
91 // established. Consumers that need current provider/settings state must use
92 // createServerEnvironmentAtoms(...).configValueAtom instead.
93 const initialConfigValueAtom = Atom.family((environmentId: EnvironmentId) =>
94 Atom.make((get): ServerConfig | null =>
95 Option.getOrNull(
96 Option.getOrElse(AsyncResult.value(get(initialConfigAtom(environmentId))), () =>
97 Option.none(),
98 ),
99 ),
100 ).pipe(Atom.withLabel(`environment-config-value:${environmentId}`)),
101 );
102
103 const preparedConnectionAtom = Atom.family((environmentId: EnvironmentId) =>
104 runtime.atom(
105 followStreamInEnvironment(
106 environmentId,
107 Stream.unwrap(
108 EnvironmentSupervisor.pipe(
109 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.prepared)),
110 ),
111 ),
112 ),
113 { initialValue: Option.none<PreparedConnection>() },
114 ),
115 );
116
117 const preparedConnectionValueAtom = Atom.family((environmentId: EnvironmentId) =>
118 Atom.make((get) =>
119 Option.getOrElse(AsyncResult.value(get(preparedConnectionAtom(environmentId))), () =>
120 Option.none<PreparedConnection>(),
121 ),
122 ).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)),
123 );
124
125 // Keyed on the prepared connection's identity: a reconnect (new credential,
126 // new base URL) swaps the prepared value, which re-runs the fetch, so scope
127 // changes from re-pairing are picked up without an explicit refresh.
128 const sessionStateAtom = Atom.family((environmentId: EnvironmentId) =>
129 runtime
130 .atom((get) => {
131 const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId)));
132 if (prepared === null) {
133 return Effect.never;
134 }
135 return Effect.gen(function* () {
136 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
137 return yield* fetchEnvironmentSessionState({ prepared, signer });
138 });
139 })
140 .pipe(
141 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
142 Atom.setIdleTTL(5 * 60_000),
143 Atom.withLabel(`environment-session-state:${environmentId}`),
144 ),
145 );
146
147 const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
148 Atom.make(
149 (get): AuthSessionState | null =>
150 Option.getOrNull(AsyncResult.value(get(sessionStateAtom(environmentId)))) ?? null,
151 ).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)),
152 );
153
154 return {
155 initialConfigAtom,
156 initialConfigValueAtom,
157 preparedConnectionAtom,
158 preparedConnectionValueAtom,
159 sessionStateAtom,
160 sessionStateValueAtom,
161 };
162}