Open History to see the last commit
1import { pipe } from "effect/Function";
2import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Stream from "effect/Stream";
7import * as SubscriptionRef from "effect/SubscriptionRef";
8import { HttpClient } from "effect/http";
9import { AsyncResult, Atom } from "effect/reactivity";
10
11import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
12import * as EnvironmentRegistry from "../connection/registry.ts";
13import type { PreparedConnection } from "../connection/model.ts";
14import * as EnvironmentSupervisor from "../connection/supervisor.ts";
15import * as ManagedRelay from "../relay/managedRelay.ts";
16import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
17import type { RpcSession } from "../rpc/session.ts";
18import { safeErrorLogAttributes } from "../errors/safeLog.ts";
19import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
20import { followStreamInEnvironment } from "./environmentStreams.ts";
21
22/** @public Required to name the error in consumers' inferred session results. */
23export class SessionHttpClientUnavailable extends Data.TaggedError(
24 "SessionHttpClientUnavailable",
25) {}
26
27function initialConfigOption<E>(
28 initialConfig: Effect.Effect<ServerConfig, E>,
29): Effect.Effect<Option.Option<ServerConfig>> {
30 return initialConfig.pipe(
31 Effect.asSome,
32 Effect.catch((error) =>
33 Effect.logWarning("Could not load the initial environment configuration.").pipe(
34 Effect.annotateLogs({ ...safeErrorLogAttributes(error) }),
35 Effect.as(Option.none<ServerConfig>()),
36 ),
37 ),
38 );
39}
40
41const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;
42const MAX_SESSION_STATE_TIMEOUT_MS = 60_000;
43const SESSION_STATE_RETRY_BASE_MS = 2_000;
44const SESSION_STATE_RETRY_MAX_MS = 60_000;
45
46export const fetchEnvironmentSessionState = Effect.fn(
47 "clientRuntime.state.fetchEnvironmentSessionState",
48)(function* (input: {
49 readonly prepared: PreparedConnection;
50 readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
51 readonly remoteAuthorization?: Option.Option<
52 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
53 >;
54 readonly timeoutMs?: number;
55}) {
56 const request = (
57 timeoutMs: number,
58 ): Effect.Effect<AuthSessionState, RemoteEnvironmentRequestError, HttpClient.HttpClient> =>
59 executeAuthenticatedEnvironmentHttpRequest({
60 ...input,
61 group: "auth",
62 method: "GET",
63 url: (urls) => urls.session(),
64 timeoutMs,
65 request: ({ client, headers }) => client.session({ headers }),
66 // This endpoint returns 200 with authenticated:false for expired credentials.
67 isUnauthorizedResponse: (response) => !response.authenticated,
68 }).pipe(
69 // A timeout says nothing about grants; failing would show a busy host as read-only.
70 Effect.catchTags({
71 RemoteEnvironmentAuthTimeoutError: (error) => {
72 const nextTimeoutMs = Math.min(timeoutMs * 2, MAX_SESSION_STATE_TIMEOUT_MS);
73 return nextTimeoutMs > timeoutMs ? request(nextTimeoutMs) : Effect.fail(error);
74 },
75 }),
76 );
77 return yield* request(input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS);
78});
79
80function makeEnvironmentSessionAtoms<R, E>(
81 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
82) {
83 const initialConfigAtom = Atom.family((environmentId: EnvironmentId) =>
84 runtime.atom(
85 followStreamInEnvironment(
86 environmentId,
87 Stream.unwrap(
88 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
89 Effect.map((supervisor) =>
90 SubscriptionRef.changes(supervisor.session).pipe(
91 Stream.mapEffect(
92 Option.match({
93 onNone: () => Effect.succeed(Option.none<ServerConfig>()),
94 onSome: (session) => initialConfigOption(session.initialConfig),
95 }),
96 ),
97 ),
98 ),
99 ),
100 ),
101 ),
102 { initialValue: Option.none() },
103 ),
104 );
105
106 // This is only the bootstrap config captured when a transport session is
107 // established. Consumers that need current provider/settings state must use
108 // createServerEnvironmentAtoms(...).configValueAtom instead.
109 const initialConfigValueAtom = Atom.family((environmentId: EnvironmentId) =>
110 Atom.make((get): ServerConfig | null =>
111 pipe(
112 get(initialConfigAtom(environmentId)),
113 AsyncResult.value,
114 Option.flatten,
115 Option.getOrNull,
116 ),
117 ).pipe(Atom.withLabel(`environment-config-value:${environmentId}`)),
118 );
119
120 const preparedConnectionAtom = Atom.family((environmentId: EnvironmentId) =>
121 runtime.atom(
122 followStreamInEnvironment(
123 environmentId,
124 Stream.unwrap(
125 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
126 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.prepared)),
127 ),
128 ),
129 ),
130 { initialValue: Option.none<PreparedConnection>() },
131 ),
132 );
133
134 const preparedConnectionValueAtom = Atom.family((environmentId: EnvironmentId) =>
135 Atom.make((get) =>
136 AsyncResult.getOrElse(get(preparedConnectionAtom(environmentId)), () =>
137 Option.none<PreparedConnection>(),
138 ),
139 ).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)),
140 );
141
142 const transportSessionAtom = Atom.family((environmentId: EnvironmentId) =>
143 runtime.atom(
144 followStreamInEnvironment(
145 environmentId,
146 Stream.unwrap(
147 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
148 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.session)),
149 ),
150 ),
151 ),
152 { initialValue: Option.none() },
153 ),
154 );
155
156 const sessionStateAtom = Atom.family((environmentId: EnvironmentId) => {
157 let consecutiveFailures = 0;
158 let backoffConnection: RpcSession | null = null;
159 return runtime
160 .atom((get) => {
161 const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId)));
162 // Each established connection fetches anew, and a failure retries while it stays up,
163 // so a fetch that failed mid-reconnect cannot outlive the socket that recovered.
164 const connection = AsyncResult.getOrElse(get(transportSessionAtom(environmentId)), () =>
165 Option.none(),
166 );
167 if (prepared === null || Option.isNone(connection)) {
168 return Effect.never;
169 }
170 if (connection.value !== backoffConnection) {
171 backoffConnection = connection.value;
172 consecutiveFailures = 0;
173 }
174 return Effect.gen(function* () {
175 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
176 const remoteAuthorization = yield* Effect.serviceOption(
177 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
178 );
179 const client = yield* Effect.serviceOption(HttpClient.HttpClient);
180 if (Option.isNone(client)) return yield* new SessionHttpClientUnavailable();
181 return yield* fetchEnvironmentSessionState({
182 prepared,
183 signer,
184 remoteAuthorization,
185 }).pipe(Effect.provideService(HttpClient.HttpClient, client.value));
186 }).pipe(
187 Effect.tap(() =>
188 Effect.sync(() => {
189 consecutiveFailures = 0;
190 }),
191 ),
192 Effect.tapError(() => {
193 const delayMs = Math.min(
194 SESSION_STATE_RETRY_BASE_MS * 2 ** consecutiveFailures,
195 SESSION_STATE_RETRY_MAX_MS,
196 );
197 consecutiveFailures += 1;
198 return Effect.sleep(delayMs).pipe(
199 Effect.andThen(Effect.sync(() => get.refreshSelf())),
200 Effect.forkScoped,
201 );
202 }),
203 );
204 })
205 .pipe(
206 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
207 Atom.setIdleTTL(5 * 60_000),
208 Atom.withLabel(`environment-session-state:${environmentId}`),
209 );
210 });
211
212 const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
213 Atom.make(
214 (get): AuthSessionState | null =>
215 AsyncResult.getOrElse(get(sessionStateAtom(environmentId)), () => null) ?? null,
216 ).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)),
217 );
218
219 return {
220 initialConfigAtom,
221 initialConfigValueAtom,
222 preparedConnectionAtom,
223 preparedConnectionValueAtom,
224 sessionStateAtom,
225 sessionStateValueAtom,
226 };
227}
228
229const sessionAtomsByRuntime = new WeakMap<object, ReturnType<typeof makeEnvironmentSessionAtoms>>();
230
231export function createEnvironmentSessionAtoms<R, E>(
232 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
233): ReturnType<typeof makeEnvironmentSessionAtoms<R, E>> {
234 const existing = sessionAtomsByRuntime.get(runtime);
235 if (existing) return existing as ReturnType<typeof makeEnvironmentSessionAtoms<R, E>>;
236 const atoms = makeEnvironmentSessionAtoms(runtime);
237 sessionAtomsByRuntime.set(runtime, atoms);
238 return atoms;
239}