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

session.ts

375 lines13.9 KB

1import {
2 type ServerConfig,
3 type ServerConfigStreamEvent,
4 WsSubscribeServerConfigRpc,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import * as Context from "effect/Context";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Equal from "effect/Equal";
12import * as Exit from "effect/Exit";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as PubSub from "effect/PubSub";
16import * as Ref from "effect/Ref";
17import * as Schedule from "effect/Schedule";
18import * as Schema from "effect/Schema";
19import type * as Scope from "effect/Scope";
20import * as Stream from "effect/Stream";
21import type * as Rpc from "effect/unstable/rpc/Rpc";
22import * as RpcClient from "effect/unstable/rpc/RpcClient";
23import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
24import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
25import * as Socket from "effect/unstable/socket/Socket";
26​
27import { makeWsRpcProtocolClient, type WsRpcProtocolClient } from "./protocol.ts";
28import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
29import type {
30 ConnectionAttemptError,
31 ConnectionTransientError,
32 PreparedConnection,
33} from "../connection/model.ts";
34import {
35 ConnectionBlockedError,
36 ConnectionTransientError as ConnectionTransientErrorClass,
37} from "../connection/model.ts";
38import {
39 applyServerConfigProjection,
40 type ServerConfigProjection,
41 withoutEnvironmentThemes,
42} from "../state/serverConfigProjection.ts";
43​
44const SOCKET_OPEN_TIMEOUT = "15 seconds";
45​
46export interface RpcSession {
47 readonly client: WsRpcProtocolClient;
48 readonly initialConfig: Effect.Effect<ServerConfig, ConnectionAttemptError>;
49 readonly subscribeServerConfig: (
50 input: ServerConfigSubscriptionInput,
51 ) => ServerConfigSubscription;
52 readonly ready: Effect.Effect<void, ConnectionAttemptError>;
53 readonly probe: Effect.Effect<void, ConnectionAttemptError>;
54 readonly closed: Effect.Effect<never, ConnectionAttemptError>;
56​
57export interface RpcSessionOptions {
58 readonly environmentThemes?: boolean;
59 readonly usageLimitSources?: boolean;
60 /** This client answers /usage-limits itself, so the server may advertise it. */
61 readonly usageLimitsCommand?: boolean;
63​
64export class RpcSessionFactory extends Context.Service<
65 RpcSessionFactory,
66 {
67 readonly connect: (
68 connection: PreparedConnection,
69 ) => Effect.Effect<RpcSession, ConnectionAttemptError, Scope.Scope>;
70 }
71>()("@t3tools/client-runtime/rpc/session/RpcSessionFactory") {}
72​
73type InitialConfigError = Effect.Error<
74 ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverGetConfig]>
75>;
76type ProbeError = Effect.Error<ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverProbe]>>;
77type ServerConfigSubscriptionError =
78 | Rpc.ErrorExit<typeof WsSubscribeServerConfigRpc>
79 | RpcClientError.RpcClientError;
80type ServerConfigSubscription = Stream.Stream<
81 ServerConfigStreamEvent,
82 ServerConfigSubscriptionError
83>;
84type ServerConfigSubscriptionInput = Parameters<
85 WsRpcProtocolClient[typeof WS_METHODS.subscribeServerConfig]
86>[0];
87type EnvironmentThemesUpdatedEvent = Extract<
88 ServerConfigStreamEvent,
89 { readonly type: "environmentThemesUpdated" }
90>;
91type UsageLimitSourcesUpdatedEvent = Extract<
92 ServerConfigStreamEvent,
93 { readonly type: "usageLimitSourcesUpdated" }
94>;
95​
96interface ServerConfigReplayState {
97 readonly projection: ServerConfigProjection;
98 readonly revision: number;
99 readonly themesEvent: EnvironmentThemesUpdatedEvent | undefined;
100 readonly sourcesEvent: UsageLimitSourcesUpdatedEvent | undefined;
102​
103interface BufferedServerConfigEvent {
104 readonly event: ServerConfigStreamEvent;
105 readonly replay: ServerConfigReplayState;
106 readonly revision: number;
108​
109function serverConfigReplayEvents(
110 state: ServerConfigReplayState,
111): ReadonlyArray<ServerConfigStreamEvent> {
112 const snapshot = {
113 version: 1 as const,
114 type: "snapshot" as const,
115 config: withoutEnvironmentThemes(state.projection.config),
116 };
117 return [
118 snapshot,
119 ...(state.themesEvent === undefined ? [] : [state.themesEvent]),
120 ...(state.sourcesEvent === undefined ? [] : [state.sourcesEvent]),
121 ];
123​
124const isSocketErrorReason = Schema.is(Socket.SocketErrorReason);
125​
126function mapSessionRpcError(
127 error: InitialConfigError | ProbeError | ServerConfigSubscriptionError,
128 networkHint: string,
129): ConnectionAttemptError {
130 switch (error._tag) {
131 case "EnvironmentAuthorizationError":
132 return new ConnectionBlockedError({
133 reason: "permission",
134 detail: error.message,
135 });
136 case "KeybindingsConfigParseError":
137 case "ServerSettingsError":
138 return new ConnectionTransientErrorClass({
139 reason: "remote-unavailable",
140 detail: error.message,
141 });
142 case "RpcClientError":
143 return new ConnectionTransientErrorClass({
144 reason: "transport",
145 detail: `${error.message}${isSocketErrorReason(error.reason) ? networkHint : ""}`,
146 });
147 }
149​
150/** @public Service construction is part of the canonical Effect module API. */
151export const make = Effect.fn("RpcSessionFactory.make")(function* (
152 options: RpcSessionOptions = {},
153) {
154 const webSocketConstructor = yield* Socket.WebSocketConstructor;
155 const serverConfigInput: ServerConfigSubscriptionInput = {
156 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
157 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
158 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
159 };
160​
161 const connect = Effect.fnUntraced(function* (connection: PreparedConnection) {
162 const networkHint =
163 connection.target._tag === "RelayConnectionTarget" ? ` ${NETWORK_BLOCKING_HINT}` : "";
164 const mapRpcError = (error: Parameters<typeof mapSessionRpcError>[0]) =>
165 mapSessionRpcError(error, networkHint);
166 yield* Effect.annotateCurrentSpan({
167 "connection.environment.id": connection.environmentId,
168 });
169​
170 const connected = yield* Deferred.make<void>();
171 const disconnected = yield* Deferred.make<never, ConnectionTransientError>();
172 const hooks = RpcClient.ConnectionHooks.of({
173 onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid),
174 onDisconnect: Deferred.isDone(connected).pipe(
175 Effect.flatMap((wasConnected) =>
176 Deferred.fail(
177 disconnected,
178 new ConnectionTransientErrorClass({
179 reason: "transport",
180 detail: `${
181 wasConnected
182 ? `${connection.label} disconnected.`
183 : `${connection.label} could not establish a WebSocket connection.`
184 }${networkHint}`,
185 }),
186 ),
187 ),
188 Effect.asVoid,
189 ),
190 });
191 const socketLayer = Socket.layerWebSocket(connection.socketUrl, {
192 openTimeout: SOCKET_OPEN_TIMEOUT,
193 }).pipe(Layer.provide(Layer.succeed(Socket.WebSocketConstructor, webSocketConstructor)));
194 const protocolLayer = Layer.effect(
195 RpcClient.Protocol,
196 RpcClient.makeProtocolSocket({
197 retryTransientErrors: false,
198 retryPolicy: Schedule.recurs(0),
199 }),
200 ).pipe(
201 Layer.provide(
202 Layer.mergeAll(
203 socketLayer,
204 RpcSerialization.layerJson,
205 Layer.succeed(RpcClient.ConnectionHooks, hooks),
206 ),
207 ),
208 );
209 const protocolContext = yield* Layer.build(protocolLayer).pipe(
210 Effect.withSpan("environment.websocket.connect"),
211 );
212 const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
213 const initialConfigDeferred = yield* Deferred.make<ServerConfig>();
214 const serverConfigExit = yield* Deferred.make<void, ServerConfigSubscriptionError>();
215 const configSubscriptionClosed = yield* Deferred.make<never, ConnectionAttemptError>();
216 const serverConfigState = yield* Ref.make(Option.none<ServerConfigReplayState>());
217 const serverConfigUpdates = yield* PubSub.sliding<BufferedServerConfigEvent>(64);
218 const configSubscriptionEndedError = new ConnectionTransientErrorClass({
219 reason: "remote-unavailable",
220 detail: `${connection.label} config subscription ended.`,
221 });
222 const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
223 serverConfigInput,
224 ).pipe(
225 Stream.runForEach((event) =>
226 Effect.gen(function* () {
227 const buffered = yield* Ref.modify(serverConfigState, (current) => {
228 const projection = applyServerConfigProjection(
229 Option.map(current, (state) => state.projection),
230 event,
231 );
232 if (Option.isNone(projection)) {
233 return [Option.none<BufferedServerConfigEvent>(), current] as const;
234 }
235 const next = {
236 projection: projection.value,
237 revision: Option.match(current, {
238 onNone: () => 1,
239 onSome: (state) => state.revision + 1,
240 }),
241 themesEvent:
242 event.type === "environmentThemesUpdated"
243 ? event
244 : event.type === "snapshot" &&
245 event.config.environment.capabilities.environmentThemes !== true
246 ? undefined
247 : Option.getOrUndefined(current)?.themesEvent,
248 sourcesEvent:
249 event.type === "usageLimitSourcesUpdated"
250 ? event
251 : event.type === "snapshot" &&
252 event.config.environment.capabilities.usageLimitSources !== true
253 ? undefined
254 : Option.getOrUndefined(current)?.sourcesEvent,
255 } satisfies ServerConfigReplayState;
256 return [
257 Option.some({ event, replay: next, revision: next.revision }),
258 Option.some(next),
259 ] as const;
260 });
261 if (Option.isSome(buffered)) {
262 yield* PubSub.publish(serverConfigUpdates, buffered.value);
263 }
264 if (event.type === "snapshot") {
265 yield* Deferred.succeed(initialConfigDeferred, event.config);
266 }
267 }),
268 ),
269 Effect.onExit((exit) => {
270 if (Exit.isSuccess(exit)) {
271 return Effect.all([
272 Deferred.succeed(serverConfigExit, undefined),
273 Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError),
274 ]).pipe(Effect.asVoid);
275 }
276 if (Cause.hasInterruptsOnly(exit.cause)) {
277 return Effect.void;
278 }
279 return Effect.all([
280 Deferred.failCause(serverConfigExit, exit.cause),
281 Deferred.failCause(configSubscriptionClosed, Cause.map(exit.cause, mapRpcError)),
282 ]).pipe(Effect.asVoid);
283 }),
284 );
285 yield* serverConfigSource.pipe(Effect.forkScoped);
286 const initialConfig = Effect.raceFirst(
287 Deferred.await(initialConfigDeferred),
288 Deferred.await(serverConfigExit).pipe(
289 Effect.mapError(mapRpcError),
290 Effect.flatMap(() => Effect.fail(configSubscriptionEndedError)),
291 ),
292 ).pipe(Effect.withSpan("environment.initialSync"));
293 const serverConfigEvents = Stream.unwrap(
294 Effect.gen(function* () {
295 const subscription = yield* PubSub.subscribe(serverConfigUpdates);
296 yield* Effect.raceFirst(
297 Deferred.await(initialConfigDeferred).pipe(Effect.asVoid),
298 Deferred.await(serverConfigExit),
299 );
300 const snapshot = yield* Ref.get(serverConfigState);
301 if (Option.isNone(snapshot)) {
302 return Stream.empty;
303 }
304 const updates = Stream.fromSubscription(subscription).pipe(
305 Stream.filter((buffered) => buffered.revision > snapshot.value.revision),
306 Stream.mapAccum(
307 () => snapshot.value.revision,
308 (revision, buffered) => [
309 buffered.revision,
310 buffered.revision === revision + 1
311 ? [buffered.event]
312 : serverConfigReplayEvents(buffered.replay),
313 ],
314 ),
315 );
316 const terminal = Stream.fromEffect(Deferred.await(serverConfigExit)).pipe(Stream.drain);
317 return Stream.concat(
318 Stream.fromIterable(serverConfigReplayEvents(snapshot.value)),
319 Stream.merge(updates, terminal, { haltStrategy: "either" }),
320 );
321 }),
322 ).pipe(
323 Stream.catchCause((cause) => {
324 if (Cause.hasInterruptsOnly(cause)) {
325 return Stream.failCause(cause);
326 }
327 // The supervisor keeps the original cause. Shared durable consumers
328 // need a transport-shaped failure so they wait for its replacement.
329 return Stream.fail(
330 new RpcClientError.RpcClientError({
331 reason: new RpcClientError.RpcClientDefect({
332 message: `${connection.label} config subscription failed.`,
333 cause,
334 }),
335 }),
336 );
337 }),
338 );
339 const subscribeServerConfig = (input: ServerConfigSubscriptionInput) =>
340 Equal.equals(input, serverConfigInput)
341 ? serverConfigEvents
342 : protocolClient[WS_METHODS.subscribeServerConfig](input);
343 const probe = initialConfig.pipe(
344 Effect.flatMap((config) =>
345 (config.environment.capabilities.connectionProbe === true
346 ? protocolClient[WS_METHODS.serverProbe]({})
347 : protocolClient[WS_METHODS.serverGetConfig]({})
348 ).pipe(Effect.mapError(mapRpcError)),
349 ),
350 Effect.asVoid,
351 Effect.withSpan("clientRuntime.connection.rpcSession.probe"),
352 );
353​
354 return {
355 client: protocolClient,
356 initialConfig,
357 subscribeServerConfig,
358 ready: Deferred.await(connected).pipe(
359 Effect.andThen(initialConfig),
360 Effect.asVoid,
361 Effect.raceFirst(Deferred.await(disconnected)),
362 ),
363 probe,
364 closed: Effect.raceFirst(
365 Deferred.await(disconnected),
366 Deferred.await(configSubscriptionClosed),
367 ),
368 } satisfies RpcSession;
369 });
370​
371 return RpcSessionFactory.of({ connect });
372});
373​
374export const layerWithOptions = (options: RpcSessionOptions) =>
375 Layer.effect(RpcSessionFactory, make(options));