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