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

session.ts

430 lines16.1 KB

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