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

session.ts

571 lines22.4 KB

1import { msg } from "gt-i18n";
2import { translatableDetail } from "../errors/translatable.ts";
3import {
4 type ServerConfig,
5 type ServerConfigStreamEvent,
6 WsSubscribeServerConfigRpc,
7 WS_METHODS,
8} from "@t3tools/contracts";
9import {
10 joinSocketFrameParts,
11 SOCKET_FRAME_PARTS_QUERY_PARAM,
12} from "@t3tools/shared/socketFrameParts";
13import * as Cause from "effect/Cause";
14import * as Clock from "effect/Clock";
15import * as Context from "effect/Context";
16import * as Deferred from "effect/Deferred";
17import * as Duration from "effect/Duration";
18import * as Effect from "effect/Effect";
19import * as Equal from "effect/Equal";
20import * as Exit from "effect/Exit";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as PubSub from "effect/PubSub";
24import * as Ref from "effect/Ref";
25import * as Schedule from "effect/Schedule";
26import * as Schema from "effect/Schema";
27import type * as Scope from "effect/Scope";
28import * as Stream from "effect/Stream";
29import type * as Rpc from "effect/rpc/Rpc";
30import * as RpcClient from "effect/rpc/RpcClient";
31import * as RpcClientError from "effect/rpc/RpcClientError";
32import * as RpcSerialization from "effect/rpc/RpcSerialization";
33import * as Socket from "effect/socket/Socket";
34​
35import { makeWsRpcProtocolClient, PING_TIMEOUT, type WsRpcProtocolClient } from "./protocol.ts";
36import { NETWORK_BLOCKING_HINT, UNRESPONSIVE_HOST_HINT } from "../errors/network.ts";
37import type {
38 ConnectionAttemptError,
39 ConnectionTransientError,
40 PreparedConnection,
41} from "../connection/model.ts";
42import {
43 ConnectionBlockedError,
44 ConnectionTransientError as ConnectionTransientErrorClass,
45} from "../connection/model.ts";
46import {
47 applyServerConfigProjection,
48 type ServerConfigProjection,
49 withoutEnvironmentThemes,
50} from "../state/serverConfigProjection.ts";
51import { environmentMismatchError } from "../connection/errors.ts";
52import { recordServerClock } from "../clock.ts";
53​
54const SOCKET_OPEN_TIMEOUT = "15 seconds";
55​
56export interface RpcSession {
57 readonly client: WsRpcProtocolClient;
58 readonly initialConfig: Effect.Effect<ServerConfig, ConnectionAttemptError>;
59 readonly subscribeServerConfig: (
60 input?: ServerConfigSubscriptionInput,
61 ) => ServerConfigSubscription;
62 readonly ready: Effect.Effect<void, ConnectionAttemptError>;
63 readonly probe: Effect.Effect<void, ConnectionAttemptError>;
64 /** Frames received so far: proof the socket is alive that needs no reply. */
65 readonly inboundFrames: Effect.Effect<number>;
66 /** Whether a request went out after the last frame came in. */
67 readonly awaitingReply: Effect.Effect<boolean>;
68 readonly closed: Effect.Effect<never, ConnectionAttemptError>;
70​
71export interface RpcSessionOptions {
72 readonly omitKeybindings?: boolean;
73 readonly environmentThemes?: boolean;
74 readonly usageLimitSources?: boolean;
75 readonly hostPressure?: boolean;
76 readonly usageLimitsCommand?: boolean;
77 readonly providerCatalogsOnDemand?: boolean;
78 readonly providerCatalogDigests?: boolean;
79 readonly providerStatusDeltas?: boolean;
80 readonly pingInterval?: Duration.Input;
81 readonly onInitialConfig?: () => void;
83​
84export class RpcSessionFactory extends Context.Service<
85 RpcSessionFactory,
86 {
87 readonly connect: (
88 connection: PreparedConnection,
89 ) => Effect.Effect<RpcSession, ConnectionAttemptError, Scope.Scope>;
90 }
91>()("@t3tools/client-runtime/rpc/session/RpcSessionFactory") {}
92​
93type InitialConfigError = Effect.Error<
94 ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverGetConfig]>
95>;
96type ProbeError = Effect.Error<ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverProbe]>>;
97type ServerConfigSubscriptionError =
98 | Rpc.ErrorExit<typeof WsSubscribeServerConfigRpc>
99 | RpcClientError.RpcClientError;
100type ServerConfigSubscription = Stream.Stream<
101 ServerConfigStreamEvent,
102 ServerConfigSubscriptionError
103>;
104type ServerConfigSubscriptionInput = Parameters<
105 WsRpcProtocolClient[typeof WS_METHODS.subscribeServerConfig]
106>[0];
107type EnvironmentThemesUpdatedEvent = Extract<
108 ServerConfigStreamEvent,
109 { readonly type: "environmentThemesUpdated" }
110>;
111type UsageLimitSourcesUpdatedEvent = Extract<
112 ServerConfigStreamEvent,
113 { readonly type: "usageLimitSourcesUpdated" }
114>;
115type HostPressureUpdatedEvent = Extract<
116 ServerConfigStreamEvent,
117 { readonly type: "hostPressureUpdated" }
118>;
119​
120interface ServerConfigReplayState {
121 readonly projection: ServerConfigProjection;
122 readonly revision: number;
123 readonly themesEvent: EnvironmentThemesUpdatedEvent | undefined;
124 readonly sourcesEvent: UsageLimitSourcesUpdatedEvent | undefined;
125 readonly pressureEvent: HostPressureUpdatedEvent | undefined;
127​
128interface BufferedServerConfigEvent {
129 readonly event: ServerConfigStreamEvent;
130 readonly replay: ServerConfigReplayState;
131 readonly revision: number;
133​
134function serverConfigReplayEvents(
135 state: ServerConfigReplayState,
136): ReadonlyArray<ServerConfigStreamEvent> {
137 const snapshot = {
138 version: 1 as const,
139 type: "snapshot" as const,
140 config: withoutEnvironmentThemes(state.projection.config),
141 };
142 return [
143 snapshot,
144 ...(state.themesEvent === undefined ? [] : [state.themesEvent]),
145 ...(state.sourcesEvent === undefined ? [] : [state.sourcesEvent]),
146 ...(state.pressureEvent === undefined ? [] : [state.pressureEvent]),
147 ];
149​
150const isSocketErrorReason = Schema.is(Socket.SocketErrorReason);
151const PING_TIMEOUT_SECONDS = Duration.toSeconds(PING_TIMEOUT);
152​
153function mapSessionRpcError(
154 error: InitialConfigError | ProbeError | ServerConfigSubscriptionError | ConnectionAttemptError,
155 via: "relay" | "direct",
156 socketFailure: () => ConnectionTransientError,
157): ConnectionAttemptError {
158 switch (error._tag) {
159 case "ConnectionBlockedError":
160 case "ConnectionTransientError":
161 return error;
162 case "EnvironmentAuthorizationError":
163 return new ConnectionBlockedError({
164 reason: "permission",
165 detail: error.message,
166 hop: "server",
167 via,
168 });
169 case "KeybindingsConfigParseError":
170 case "ServerSettingsError":
171 return new ConnectionTransientErrorClass({
172 reason: "remote-unavailable",
173 detail: error.message,
174 hop: "server",
175 via,
176 });
177 case "RpcClientError":
178 return isSocketErrorReason(error.reason)
179 ? socketFailure()
180 : new ConnectionTransientErrorClass({
181 reason: "transport",
182 detail: error.message,
183 ...socketFailureLocation(via),
184 });
185 }
187​
188/** Over T3 Connect the relay already reached the host, so a socket that drops failed between this device and the tunnel. */
189function socketFailureLocation(via: "relay" | "direct") {
190 return { hop: via === "relay" ? "tunnel" : "server", via } as const;
192​
193/** @public */
194export const make = Effect.fn("RpcSessionFactory.make")(function* (
195 options: RpcSessionOptions = {},
196) {
197 const webSocketConstructor = yield* Socket.WebSocketConstructor;
198 const serverConfigInput: ServerConfigSubscriptionInput = {
199 ...(options.omitKeybindings === true ? { omitKeybindings: true } : {}),
200 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
201 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
202 ...(options.hostPressure === true ? { hostPressure: true } : {}),
203 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
204 ...(options.providerCatalogsOnDemand === true ? { providerCatalogsOnDemand: true } : {}),
205 ...(options.providerCatalogDigests === true ? { providerCatalogDigests: true } : {}),
206 ...(options.providerStatusDeltas === true ? { providerStatusDeltas: true } : {}),
207 };
208 // Config state merges the snapshots it fetches back in, so no subscriber needs them broadcast.
209 const onDemandSnapshots = (input: ServerConfigSubscriptionInput) => ({
210 ...input,
211 workspaceSnapshotsOnDemand: true,
212 });
213​
214 const connect = Effect.fnUntraced(function* (connection: PreparedConnection) {
215 const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct";
216 yield* Effect.annotateCurrentSpan({
217 "connection.environment.id": connection.environmentId,
218 });
219​
220 const connected = yield* Deferred.make<void>();
221 const disconnected = yield* Deferred.make<never, ConnectionTransientError>();
222 let pingTimedOut = false;
223 const socketFailure = () =>
224 new ConnectionTransientErrorClass({
225 reason: "transport",
226 // The network hint only fits a socket that never opened. Once it
227 // opened, the path worked, and a host that goes quiet is more
228 // often overloaded or asleep than blocked.
229 ...(!Deferred.isDoneUnsafe(connected)
230 ? translatableDetail(
231 msg`${{ host: connection.label }} could not establish a WebSocket connection.`,
232 ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []),
233 )
234 : pingTimedOut
235 ? translatableDetail(
236 msg`${{ host: connection.label }} stopped responding for ${{ seconds: String(PING_TIMEOUT_SECONDS) }}s.`,
237 UNRESPONSIVE_HOST_HINT,
238 )
239 : translatableDetail(msg`${{ host: connection.label }} disconnected.`)),
240 ...socketFailureLocation(via),
241 });
242 const mapRpcError = (error: Parameters<typeof mapSessionRpcError>[0]) =>
243 mapSessionRpcError(error, via, socketFailure);
244 const hooks = RpcClient.ConnectionHooks.of({
245 onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid),
246 onDisconnect: Effect.suspend(() => Deferred.fail(disconnected, socketFailure())).pipe(
247 Effect.asVoid,
248 ),
249 });
250 // The protocol never reopens its socket, so every frame counted here came
251 // from this session's one socket.
252 let inboundFrames = 0;
253 let awaitingReply = false;
254 const countingWebSocketConstructor: typeof webSocketConstructor = (url, options) => {
255 const socket = webSocketConstructor(url, options);
256 socket.addEventListener("message", () => {
257 inboundFrames += 1;
258 awaitingReply = false;
259 });
260 return socket;
261 };
262 const socketUrl = new URL(connection.socketUrl);
263 socketUrl.searchParams.set(SOCKET_FRAME_PARTS_QUERY_PARAM, "1");
264 const layerSocket = Layer.effect(
265 Socket.Socket,
266 Effect.map(Effect.service(Socket.Socket), joinSocketFrameParts),
267 ).pipe(
268 Layer.provide(
269 Socket.layerWebSocket(socketUrl.toString(), {
270 openTimeout: SOCKET_OPEN_TIMEOUT,
271 ...(connection.socketHeaders ? { headers: connection.socketHeaders } : {}),
272 }),
273 ),
274 Layer.provide(Layer.succeed(Socket.WebSocketConstructor, countingWebSocketConstructor)),
275 );
276 const layerProtocol = Layer.effect(
277 RpcClient.Protocol,
278 RpcClient.makeProtocolSocket({
279 pingInterval: options.pingInterval,
280 pingTimeout: PING_TIMEOUT,
281 retryTransientErrors: false,
282 retryPolicy: Schedule.recurs(0),
283 // RpcClient runs this before it fails the open requests.
284 onPingTimeout: Effect.sync(() => {
285 pingTimedOut = true;
286 }),
287 }).pipe(
288 // Teardown sends an interrupt per open stream, and a write to a closed
289 // socket waits out the client's 1s interrupt timeout before reconnecting.
290 // Requests still go through, so they fail with the protocol error.
291 Effect.map((protocol) => ({
292 ...protocol,
293 send: (clientId, request, transferables) =>
294 request._tag === "Request"
295 ? Effect.sync(() => {
296 awaitingReply = true;
297 }).pipe(Effect.andThen(protocol.send(clientId, request, transferables)))
298 : Deferred.isDoneUnsafe(disconnected)
299 ? Effect.void
300 : protocol.send(clientId, request, transferables),
301 })),
302 ),
303 ).pipe(
304 Layer.provide(
305 Layer.mergeAll(
306 layerSocket,
307 RpcSerialization.layerJson,
308 Layer.succeed(RpcClient.ConnectionHooks, hooks),
309 ),
310 ),
311 );
312 const protocolContext = yield* Layer.build(layerProtocol).pipe(
313 Effect.withSpan("environment.websocket.connect"),
314 );
315 // Building the protocol only starts the socket; this span times the
316 // handshake up to the first open, without making `connect` wait for it.
317 yield* Deferred.await(connected).pipe(
318 Effect.raceFirst(Deferred.await(disconnected)),
319 Effect.withSpan("environment.websocket.open"),
320 Effect.ignore,
321 Effect.forkScoped,
322 );
323 const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
324 const initialConfigDeferred = yield* Deferred.make<ServerConfig>();
325 const serverConfigExit = yield* Deferred.make<
326 void,
327 ServerConfigSubscriptionError | ConnectionAttemptError
328 >();
329 const configSubscriptionClosed = yield* Deferred.make<never, ConnectionAttemptError>();
330 const serverConfigState = yield* Ref.make(Option.none<ServerConfigReplayState>());
331 const serverConfigUpdates = yield* PubSub.sliding<BufferedServerConfigEvent>(64);
332 const configSubscriptionEndedError = new ConnectionTransientErrorClass({
333 reason: "remote-unavailable",
334 detail: `${connection.label} config subscription ended.`,
335 });
336 // An interrupt while the session is not closing came from the server; it ends the subscription.
337 let closingSession = false;
338 const configRequestedAtMs = yield* Clock.currentTimeMillis;
339 const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
340 onDemandSnapshots(serverConfigInput),
341 ).pipe(
342 Stream.runForEach((event) =>
343 Effect.gen(function* () {
344 const isInitialConfig =
345 event.type === "snapshot" && !Deferred.isDoneUnsafe(initialConfigDeferred);
346 if (isInitialConfig) options.onInitialConfig?.();
347 const buffered = yield* Ref.modify(serverConfigState, (current) => {
348 const projection = applyServerConfigProjection(
349 Option.map(current, (state) => state.projection),
350 event,
351 );
352 if (Option.isNone(projection)) {
353 return [Option.none<BufferedServerConfigEvent>(), current] as const;
354 }
355 const next = {
356 projection: projection.value,
357 revision: Option.match(current, {
358 onNone: () => 1,
359 onSome: (state) => state.revision + 1,
360 }),
361 themesEvent:
362 event.type === "environmentThemesUpdated"
363 ? event
364 : Option.getOrUndefined(current)?.themesEvent,
365 sourcesEvent:
366 event.type === "usageLimitSourcesUpdated"
367 ? event
368 : Option.getOrUndefined(current)?.sourcesEvent,
369 pressureEvent:
370 event.type === "hostPressureUpdated"
371 ? event
372 : Option.getOrUndefined(current)?.pressureEvent,
373 } satisfies ServerConfigReplayState;
374 return [
375 Option.some({ event, replay: next, revision: next.revision }),
376 Option.some(next),
377 ] as const;
378 });
379 // Config subscribers wait for readiness and replay the first snapshot from the ref.
380 if (!isInitialConfig && Option.isSome(buffered)) {
381 yield* PubSub.publish(serverConfigUpdates, buffered.value);
382 }
383 if (event.type === "snapshot") {
384 // Later snapshots may repeat the first one's serverTime. Record
385 // before readiness so the first timers already use its clock.
386 if (isInitialConfig) {
387 const { serverTime } = event.config;
388 recordServerClock(connection.environmentId, {
389 serverTimeMs: serverTime === undefined ? undefined : Date.parse(serverTime),
390 requestedAtMs: configRequestedAtMs,
391 receivedAtMs: yield* Clock.currentTimeMillis,
392 });
393 }
394 yield* Deferred.succeed(initialConfigDeferred, event.config);
395 }
396 }),
397 ),
398 // An unreadable first snapshot means the versions are incompatible. A later
399 // unreadable update ends the session, and the reconnect's snapshot decides.
400 Effect.catchDefect((defect) =>
401 Schema.isSchemaError(defect)
402 ? Effect.logWarning("Server configuration failed to decode.", {
403 environmentId: connection.environmentId,
404 issue: defect.message,
405 }).pipe(
406 Effect.andThen(
407 Effect.fail(
408 Deferred.isDoneUnsafe(initialConfigDeferred)
409 ? new ConnectionTransientErrorClass({
410 reason: "remote-unavailable",
411 ...translatableDetail(
412 msg`${{ host: connection.label }} sent a server configuration update this client could not read.`,
413 ),
414 hop: "server",
415 via,
416 })
417 : new ConnectionBlockedError({
418 reason: "unsupported",
419 ...translatableDetail(
420 msg`${{ host: connection.label }} sent an incompatible server configuration.`,
421 msg("Update the client and server to compatible versions."),
422 ),
423 hop: "server",
424 via,
425 }),
426 ),
427 ),
428 )
429 : Effect.die(defect),
430 ),
431 Effect.onExit((exit) => {
432 if (Exit.isSuccess(exit) || (Cause.hasInterruptsOnly(exit.cause) && !closingSession)) {
433 return Effect.all([
434 Deferred.succeed(serverConfigExit, undefined),
435 Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError),
436 ]).pipe(Effect.asVoid);
437 }
438 if (Cause.hasInterruptsOnly(exit.cause)) {
439 return Effect.void;
440 }
441 return Effect.all([
442 Deferred.failCause(serverConfigExit, exit.cause),
443 Deferred.failCause(configSubscriptionClosed, Cause.map(exit.cause, mapRpcError)),
444 ]).pipe(Effect.asVoid);
445 }),
446 );
447 yield* serverConfigSource.pipe(Effect.forkScoped);
448 // Finalizers run in reverse, so this is set before the fork above is interrupted.
449 yield* Effect.addFinalizer(() =>
450 Effect.sync(() => {
451 closingSession = true;
452 }),
453 );
454 const initialConfig = Effect.raceFirst(
455 Deferred.await(initialConfigDeferred),
456 Deferred.await(serverConfigExit).pipe(
457 Effect.mapError(mapRpcError),
458 Effect.flatMap(() => Effect.fail(configSubscriptionEndedError)),
459 ),
460 ).pipe(
461 Effect.filterOrElse(
462 (config) => config.environment.environmentId === connection.environmentId,
463 (config) =>
464 environmentMismatchError({
465 expected: connection.environmentId,
466 actual: config.environment.environmentId,
467 }),
468 ),
469 Effect.withSpan("environment.initialSync"),
470 );
471 const serverConfigEvents = Stream.unwrap(
472 Effect.gen(function* () {
473 const subscription = yield* PubSub.subscribe(serverConfigUpdates);
474 const snapshot = yield* Ref.get(serverConfigState);
475 if (Option.isNone(snapshot)) {
476 return Stream.empty;
477 }
478 const updates = Stream.fromSubscription(subscription).pipe(
479 Stream.filter((buffered) => buffered.revision > snapshot.value.revision),
480 Stream.mapAccum(
481 () => snapshot.value.revision,
482 (revision, buffered) => [
483 buffered.revision,
484 buffered.revision === revision + 1
485 ? [buffered.event]
486 : serverConfigReplayEvents(buffered.replay),
487 ],
488 ),
489 );
490 const terminal = Stream.fromEffect(Deferred.await(serverConfigExit)).pipe(Stream.drain);
491 return Stream.concat(
492 Stream.fromIterable(serverConfigReplayEvents(snapshot.value)),
493 Stream.merge(updates, terminal, { haltStrategy: "either" }),
494 );
495 }),
496 ).pipe(
497 Stream.catchCause((cause) => {
498 if (Cause.hasInterruptsOnly(cause)) {
499 return Stream.failCause(
500 Cause.fromReasons<never>(cause.reasons.filter(Cause.isInterruptReason)),
501 );
502 }
503 // The supervisor keeps the original cause. Shared durable consumers
504 // need a transport-shaped failure so they wait for its replacement.
505 return Stream.fail(
506 new RpcClientError.RpcClientError({
507 reason: new RpcClientError.RpcClientDefect({
508 message: `${connection.label} config subscription failed.`,
509 cause,
510 }),
511 }),
512 );
513 }),
514 );
515 const validatedInitialConfig = initialConfig.pipe(
516 Effect.mapError(
517 (cause) =>
518 new RpcClientError.RpcClientError({
519 reason: new RpcClientError.RpcClientDefect({
520 message: `${connection.label} config subscription failed.`,
521 cause,
522 }),
523 }),
524 ),
525 );
526 const subscribeServerConfig = (input: ServerConfigSubscriptionInput = serverConfigInput) =>
527 Stream.unwrap(
528 validatedInitialConfig.pipe(
529 Effect.as(
530 Equal.equals(input, serverConfigInput)
531 ? serverConfigEvents
532 : protocolClient[WS_METHODS.subscribeServerConfig](onDemandSnapshots(input)),
533 ),
534 ),
535 );
536 const probe = initialConfig.pipe(
537 Effect.flatMap(() =>
538 Effect.gen(function* () {
539 const requestedAtMs = yield* Clock.currentTimeMillis;
540 const result = yield* protocolClient[WS_METHODS.serverProbe]({}).pipe(
541 Effect.mapError(mapRpcError),
542 );
543 if (result.serverTime !== undefined) {
544 recordServerClock(connection.environmentId, {
545 serverTimeMs: Date.parse(result.serverTime),
546 requestedAtMs,
547 receivedAtMs: yield* Clock.currentTimeMillis,
548 });
549 }
550 }),
551 ),
552 Effect.withSpan("clientRuntime.connection.rpcSession.probe"),
553 );
554​
555 return {
556 client: protocolClient,
557 initialConfig,
558 subscribeServerConfig,
559 ready: initialConfig.pipe(Effect.asVoid),
560 probe,
561 inboundFrames: Effect.sync(() => inboundFrames),
562 awaitingReply: Effect.sync(() => awaitingReply),
563 // The config stream also fails on disconnect, and only it can report a decode failure.
564 closed: Deferred.await(configSubscriptionClosed),
565 } satisfies RpcSession;
566 });
567​
568 return RpcSessionFactory.of({ connect });
569});
570​
571export const layer = (options: RpcSessionOptions) => Layer.effect(RpcSessionFactory, make(options));