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

session.ts

161 lines6.3 KB

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 );
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 group: "auth",
53 method: "GET",
54 url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/auth/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​
62export function createEnvironmentSessionAtoms<R, E>(
63 runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
64) {
65 const initialConfigAtom = Atom.family((environmentId: EnvironmentId) =>
66 runtime.atom(
67 followStreamInEnvironment(
68 environmentId,
69 Stream.unwrap(
70 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.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 // Keyed on the prepared connection's identity: a reconnect (new credential,
124 // new base URL) swaps the prepared value, which re-runs the fetch, so scope
125 // changes from re-pairing are picked up without an explicit refresh.
126 const sessionStateAtom = Atom.family((environmentId: EnvironmentId) =>
127 runtime
128 .atom((get) => {
129 const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId)));
130 if (prepared === null) {
131 return Effect.never;
132 }
133 return Effect.gen(function* () {
134 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
135 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
136 return yield* fetchEnvironmentSessionState({ prepared, signer, remoteAuthorization });
137 });
138 })
139 .pipe(
140 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
141 Atom.setIdleTTL(5 * 60_000),
142 Atom.withLabel(`environment-session-state:${environmentId}`),
143 ),
144 );
145​
146 const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
147 Atom.make(
148 (get): AuthSessionState | null =>
149 Option.getOrNull(AsyncResult.value(get(sessionStateAtom(environmentId)))) ?? null,
150 ).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)),
151 );
152​
153 return {
154 initialConfigAtom,
155 initialConfigValueAtom,
156 preparedConnectionAtom,
157 preparedConnectionValueAtom,
158 sessionStateAtom,
159 sessionStateValueAtom,
160 };