Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

session.ts

209 lines7.9 KB

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