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

session.ts

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