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

session.ts

478 lines18.3 KB

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