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 : Option.getOrUndefined(current)?.themesEvent,
292 sourcesEvent:
293 event.type === "usageLimitSourcesUpdated"
294 ? event
295 : Option.getOrUndefined(current)?.sourcesEvent,
296 } satisfies ServerConfigReplayState;
297 return [
298 Option.some({ event, replay: next, revision: next.revision }),
299 Option.some(next),
300 ] as const;
301 });
302 if (Option.isSome(buffered)) {
303 yield* PubSub.publish(serverConfigUpdates, buffered.value);
304 }
305 if (event.type === "snapshot") {
306 yield* Deferred.succeed(initialConfigDeferred, event.config);
307 }
308 }),
309 ),
310 Effect.onExit((exit) => {
311 if (Exit.isSuccess(exit)) {
312 return Effect.all([
313 Deferred.succeed(serverConfigExit, undefined),
314 Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError),
315 ]).pipe(Effect.asVoid);
316 }
317 if (Cause.hasInterruptsOnly(exit.cause)) {
318 return Effect.void;
319 }
320 return Effect.all([
321 Deferred.failCause(serverConfigExit, exit.cause),
322 Deferred.failCause(configSubscriptionClosed, Cause.map(exit.cause, mapRpcError)),
323 ]).pipe(Effect.asVoid);
324 }),
325 );
326 yield* serverConfigSource.pipe(Effect.forkScoped);
327 const initialConfig = Effect.raceFirst(
328 Deferred.await(initialConfigDeferred),
329 Deferred.await(serverConfigExit).pipe(
330 Effect.mapError(mapRpcError),
331 Effect.flatMap(() => Effect.fail(configSubscriptionEndedError)),
332 ),
333 ).pipe(
334 Effect.filterOrElse(
335 (config) => config.environment.environmentId === connection.environmentId,
336 (config) =>
337 environmentMismatchError({
338 expected: connection.environmentId,
339 actual: config.environment.environmentId,
340 }),
341 ),
342 Effect.withSpan("environment.initialSync"),
343 );
344 const serverConfigEvents = Stream.unwrap(
345 Effect.gen(function* () {
346 const subscription = yield* PubSub.subscribe(serverConfigUpdates);
347 const snapshot = yield* Ref.get(serverConfigState);
348 if (Option.isNone(snapshot)) {
349 return Stream.empty;
350 }
351 const updates = Stream.fromSubscription(subscription).pipe(
352 Stream.filter((buffered) => buffered.revision > snapshot.value.revision),
353 Stream.mapAccum(
354 () => snapshot.value.revision,
355 (revision, buffered) => [
356 buffered.revision,
357 buffered.revision === revision + 1
358 ? [buffered.event]
359 : serverConfigReplayEvents(buffered.replay),
360 ],
361 ),
362 );
363 const terminal = Stream.fromEffect(Deferred.await(serverConfigExit)).pipe(Stream.drain);
364 return Stream.concat(
365 Stream.fromIterable(serverConfigReplayEvents(snapshot.value)),
366 Stream.merge(updates, terminal, { haltStrategy: "either" }),
367 );
368 }),
369 ).pipe(
370 Stream.catchCause((cause) => {
371 if (Cause.hasInterruptsOnly(cause)) {
372 return Stream.failCause(cause);
373 }
374 // The supervisor keeps the original cause. Shared durable consumers
375 // need a transport-shaped failure so they wait for its replacement.
376 return Stream.fail(
377 new RpcClientError.RpcClientError({
378 reason: new RpcClientError.RpcClientDefect({
379 message: `${connection.label} config subscription failed.`,
380 cause,
381 }),
382 }),
383 );
384 }),
385 );
386 const validatedInitialConfig = initialConfig.pipe(
387 Effect.mapError(
388 (cause) =>
389 new RpcClientError.RpcClientError({
390 reason: new RpcClientError.RpcClientDefect({
391 message: `${connection.label} config subscription failed.`,
392 cause,
393 }),
394 }),
395 ),
396 );
397 const subscribeServerConfig = (input: ServerConfigSubscriptionInput = serverConfigInput) =>
398 Stream.unwrap(
399 validatedInitialConfig.pipe(
400 Effect.as(
401 Equal.equals(input, serverConfigInput)
402 ? serverConfigEvents
403 : protocolClient[WS_METHODS.subscribeServerConfig](onDemandSnapshots(input)),
404 ),
405 ),
406 );
407 const probe = initialConfig.pipe(
408 Effect.flatMap(() =>
409 protocolClient[WS_METHODS.serverProbe]({}).pipe(Effect.mapError(mapRpcError)),
410 ),
411 Effect.asVoid,
412 Effect.withSpan("clientRuntime.connection.rpcSession.probe"),
413 );
414
415 return {
416 client: protocolClient,
417 initialConfig,
418 subscribeServerConfig,
419 ready: Deferred.await(connected).pipe(
420 Effect.andThen(initialConfig),
421 Effect.asVoid,
422 Effect.raceFirst(Deferred.await(disconnected)),
423 ),
424 probe,
425 inboundFrames: Effect.sync(() => inboundFrames),
426 closed: Effect.raceFirst(
427 Deferred.await(disconnected),
428 Deferred.await(configSubscriptionClosed),
429 ),
430 } satisfies RpcSession;
431 });
432
433 return RpcSessionFactory.of({ connect });
434});
435
436export const layer = (options: RpcSessionOptions) => Layer.effect(RpcSessionFactory, make(options));