Open History to see the last commit
1import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";
2import * as Data from "effect/Data";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Stream from "effect/Stream";
6import * as SubscriptionRef from "effect/SubscriptionRef";
7import { HttpClient } from "effect/http";
8import { AsyncResult, Atom } from "effect/reactivity";
9
10import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
11import * as EnvironmentRegistry from "../connection/registry.ts";
12import type { PreparedConnection } from "../connection/model.ts";
13import * as EnvironmentSupervisor from "../connection/supervisor.ts";
14import * as ManagedRelay from "../relay/managedRelay.ts";
15import { safeErrorLogAttributes } from "../errors/safeLog.ts";
16import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
17import { followStreamInEnvironment } from "./environmentStreams.ts";
18
19/** @public Required to name the error in consumers' inferred session results. */
20export class SessionHttpClientUnavailable extends Data.TaggedError(
21 "SessionHttpClientUnavailable",
22) {}
23
24function initialConfigOption<E>(
25 initialConfig: Effect.Effect<ServerConfig, E>,
26): Effect.Effect<Option.Option<ServerConfig>> {
27 return initialConfig.pipe(
28 Effect.asSome,
29 Effect.catch((error) =>
30 Effect.logWarning("Could not load the initial environment configuration.").pipe(
31 Effect.annotateLogs({ ...safeErrorLogAttributes(error) }),
32 Effect.as(Option.none<ServerConfig>()),
33 ),
34 ),
35 );
36}
37
38const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;
39
40export const fetchEnvironmentSessionState = Effect.fn(
41 "clientRuntime.state.fetchEnvironmentSessionState",
42)(function* (input: {
43 readonly prepared: PreparedConnection;
44 readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
45 readonly remoteAuthorization?: Option.Option<
46 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
47 >;
48 readonly timeoutMs?: number;
49}) {
50 return yield* executeAuthenticatedEnvironmentHttpRequest({
51 ...input,
52 group: "auth",
53 method: "GET",
54 url: (urls) => urls.session(),
55 timeoutMs: input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS,
56 request: ({ client, headers }) => client.session({ headers }),
57 // This endpoint returns 200 with authenticated:false for expired credentials.
58 isUnauthorizedResponse: (response) => !response.authenticated,
59 });
60});
61
62function makeEnvironmentSessionAtoms<R, E>(
63 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
64) {
65 const initialConfigAtom = Atom.family((environmentId: EnvironmentId) =>
66 runtime.atom(
67 followStreamInEnvironment(
68 environmentId,
69 Stream.unwrap(
70 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
71 Effect.map((supervisor) =>
72 SubscriptionRef.changes(supervisor.session).pipe(
73 Stream.mapEffect(
74 Option.match({
75 onNone: () => Effect.succeed(Option.none<ServerConfig>()),
76 onSome: (session) => initialConfigOption(session.initialConfig),
77 }),
78 ),
79 ),
80 ),
81 ),
82 ),
83 ),
84 { initialValue: Option.none() },
85 ),
86 );
87
88 // This is only the bootstrap config captured when a transport session is
89 // established. Consumers that need current provider/settings state must use
90 // createServerEnvironmentAtoms(...).configValueAtom instead.
91 const initialConfigValueAtom = Atom.family((environmentId: EnvironmentId) =>
92 Atom.make((get): ServerConfig | null =>
93 Option.getOrNull(
94 Option.getOrElse(AsyncResult.value(get(initialConfigAtom(environmentId))), () =>
95 Option.none(),
96 ),
97 ),
98 ).pipe(Atom.withLabel(`environment-config-value:${environmentId}`)),
99 );
100
101 const preparedConnectionAtom = Atom.family((environmentId: EnvironmentId) =>
102 runtime.atom(
103 followStreamInEnvironment(
104 environmentId,
105 Stream.unwrap(
106 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
107 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.prepared)),
108 ),
109 ),
110 ),
111 { initialValue: Option.none<PreparedConnection>() },
112 ),
113 );
114
115 const preparedConnectionValueAtom = Atom.family((environmentId: EnvironmentId) =>
116 Atom.make((get) =>
117 Option.getOrElse(AsyncResult.value(get(preparedConnectionAtom(environmentId))), () =>
118 Option.none<PreparedConnection>(),
119 ),
120 ).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)),
121 );
122
123 const sessionStateAtom = Atom.family((environmentId: EnvironmentId) =>
124 runtime
125 .atom((get) => {
126 const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId)));
127 if (prepared === null) {
128 return Effect.never;
129 }
130 return Effect.gen(function* () {
131 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
132 const remoteAuthorization = yield* Effect.serviceOption(
133 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
134 );
135 const client = yield* Effect.serviceOption(HttpClient.HttpClient);
136 if (Option.isNone(client)) return yield* new SessionHttpClientUnavailable();
137 return yield* fetchEnvironmentSessionState({
138 prepared,
139 signer,
140 remoteAuthorization,
141 }).pipe(Effect.provideService(HttpClient.HttpClient, client.value));
142 });
143 })
144 .pipe(
145 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
146 Atom.setIdleTTL(5 * 60_000),
147 Atom.withLabel(`environment-session-state:${environmentId}`),
148 ),
149 );
150
151 const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
152 Atom.make(
153 (get): AuthSessionState | null =>
154 Option.getOrNull(AsyncResult.value(get(sessionStateAtom(environmentId)))) ?? null,
155 ).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)),
156 );
157
158 return {
159 initialConfigAtom,
160 initialConfigValueAtom,
161 preparedConnectionAtom,
162 preparedConnectionValueAtom,
163 sessionStateAtom,
164 sessionStateValueAtom,
165 };
166}
167
168const sessionAtomsByRuntime = new WeakMap<object, ReturnType<typeof makeEnvironmentSessionAtoms>>();
169
170export function createEnvironmentSessionAtoms<R, E>(
171 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
172): ReturnType<typeof makeEnvironmentSessionAtoms<R, E>> {
173 const existing = sessionAtomsByRuntime.get(runtime);
174 if (existing) return existing as ReturnType<typeof makeEnvironmentSessionAtoms<R, E>>;
175 const atoms = makeEnvironmentSessionAtoms(runtime);
176 sessionAtomsByRuntime.set(runtime, atoms);
177 return atoms;
178}