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

session.ts

192 lines7.4 KB

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