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

session.ts

194 lines7.4 KB

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