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