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

session.ts

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