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 { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
10import { EnvironmentRegistry } from "../connection/registry.ts";
11import type { PreparedConnection } from "../connection/model.ts";
12import { EnvironmentSupervisor } from "../connection/supervisor.ts";
13import { environmentEndpointUrl } from "../environment/endpoint.ts";
14import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
15import { safeErrorLogAttributes } from "../errors/safeLog.ts";
16import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
17import { followStreamInEnvironment } from "./runtime.ts";
18
19function 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, using the connection's authentication method
40 * and refreshing relay credentials when needed.
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 remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
48 readonly timeoutMs?: number;
49}) {
50 return yield* executeAuthenticatedEnvironmentHttpRequest({
51 ...input,
52 method: "GET",
53 url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/auth/session"),
54 timeoutMs: input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS,
55 request: ({ client, headers }) => client.auth.session({ headers }),
56 // This endpoint returns 200 with authenticated:false for expired credentials.
57 isUnauthorizedResponse: (response) => !response.authenticated,
58 });
59});
60
61export function createEnvironmentSessionAtoms<R, E>(
62 runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
63) {
64 const initialConfigAtom = Atom.family((environmentId: EnvironmentId) =>
65 runtime.atom(
66 followStreamInEnvironment(
67 environmentId,
68 Stream.unwrap(
69 EnvironmentSupervisor.pipe(
70 Effect.map((supervisor) =>
71 SubscriptionRef.changes(supervisor.session).pipe(
72 Stream.mapEffect(
73 Option.match({
74 onNone: () => Effect.succeed(Option.none<ServerConfig>()),
75 onSome: (session) => initialConfigOption(session.initialConfig),
76 }),
77 ),
78 ),
79 ),
80 ),
81 ),
82 ),
83 { initialValue: Option.none() },
84 ),
85 );
86
87 // This is only the bootstrap config captured when a transport session is
88 // established. Consumers that need current provider/settings state must use
89 // createServerEnvironmentAtoms(...).configValueAtom instead.
90 const initialConfigValueAtom = Atom.family((environmentId: EnvironmentId) =>
91 Atom.make((get): ServerConfig | null =>
92 Option.getOrNull(
93 Option.getOrElse(AsyncResult.value(get(initialConfigAtom(environmentId))), () =>
94 Option.none(),
95 ),
96 ),
97 ).pipe(Atom.withLabel(`environment-config-value:${environmentId}`)),
98 );
99
100 const preparedConnectionAtom = Atom.family((environmentId: EnvironmentId) =>
101 runtime.atom(
102 followStreamInEnvironment(
103 environmentId,
104 Stream.unwrap(
105 EnvironmentSupervisor.pipe(
106 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.prepared)),
107 ),
108 ),
109 ),
110 { initialValue: Option.none<PreparedConnection>() },
111 ),
112 );
113
114 const preparedConnectionValueAtom = Atom.family((environmentId: EnvironmentId) =>
115 Atom.make((get) =>
116 Option.getOrElse(AsyncResult.value(get(preparedConnectionAtom(environmentId))), () =>
117 Option.none<PreparedConnection>(),
118 ),
119 ).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)),
120 );
121
122 // Keyed on the prepared connection's identity: a reconnect (new credential,
123 // new base URL) swaps the prepared value, which re-runs the fetch, so scope
124 // changes from re-pairing are picked up without an explicit refresh.
125 const sessionStateAtom = Atom.family((environmentId: EnvironmentId) =>
126 runtime
127 .atom((get) => {
128 const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId)));
129 if (prepared === null) {
130 return Effect.never;
131 }
132 return Effect.gen(function* () {
133 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
134 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
135 return yield* fetchEnvironmentSessionState({ prepared, signer, remoteAuthorization });
136 });
137 })
138 .pipe(
139 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
140 Atom.setIdleTTL(5 * 60_000),
141 Atom.withLabel(`environment-session-state:${environmentId}`),
142 ),
143 );
144
145 const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
146 Atom.make(
147 (get): AuthSessionState | null =>
148 Option.getOrNull(AsyncResult.value(get(sessionStateAtom(environmentId)))) ?? null,
149 ).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)),
150 );
151
152 return {
153 initialConfigAtom,
154 initialConfigValueAtom,
155 preparedConnectionAtom,
156 preparedConnectionValueAtom,
157 sessionStateAtom,
158 sessionStateValueAtom,
159 };
160}