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

session.ts

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