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

session.ts

425 lines15.9 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 Service construction is part of the canonical Effect module API. */
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​
174 const connect = Effect.fnUntraced(function* (connection: PreparedConnection) {
175 const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct";
176 const networkHint = via === "relay" ? ` ${NETWORK_BLOCKING_HINT}` : "";
177 const mapRpcError = (error: Parameters<typeof mapSessionRpcError>[0]) =>
178 mapSessionRpcError(error, networkHint, via);
179 yield* Effect.annotateCurrentSpan({
180 "connection.environment.id": connection.environmentId,
181 });
182​
183 const connected = yield* Deferred.make<void>();
184 const disconnected = yield* Deferred.make<never, ConnectionTransientError>();
185 const pingTimedOut = yield* Ref.make(false);
186 const hooks = RpcClient.ConnectionHooks.of({
187 onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid),
188 onDisconnect: Effect.all([Deferred.isDone(connected), Ref.get(pingTimedOut)]).pipe(
189 Effect.flatMap(([wasConnected, timedOut]) =>
190 Deferred.fail(
191 disconnected,
192 new ConnectionTransientErrorClass({
193 reason: "transport",
194 // The network hint only fits a socket that never opened. Once it
195 // opened, the path worked, and a host that goes quiet is more
196 // often overloaded or asleep than blocked.
197 detail: !wasConnected
198 ? `${connection.label} could not establish a WebSocket connection.${networkHint}`
199 : timedOut
200 ? `${connection.label} stopped responding for ${PING_TIMEOUT_SECONDS}s. ${UNRESPONSIVE_HOST_HINT}`
201 : `${connection.label} disconnected.`,
202 ...socketFailureLocation(via),
203 }),
204 ),
205 ),
206 Effect.asVoid,
207 ),
208 });
209 const layerSocket = Socket.layerWebSocket(connection.socketUrl, {
210 openTimeout: SOCKET_OPEN_TIMEOUT,
211 }).pipe(Layer.provide(Layer.succeed(Socket.WebSocketConstructor, webSocketConstructor)));
212 const layerProtocol = Layer.effect(
213 RpcClient.Protocol,
214 RpcClient.makeProtocolSocket({
215 pingTimeout: PING_TIMEOUT,
216 retryTransientErrors: false,
217 retryPolicy: Schedule.recurs(0),
218 onPingTimeout: Ref.set(pingTimedOut, true),
219 }),
220 ).pipe(
221 Layer.provide(
222 Layer.mergeAll(
223 layerSocket,
224 RpcSerialization.layerJson,
225 Layer.succeed(RpcClient.ConnectionHooks, hooks),
226 ),
227 ),
228 );
229 const protocolContext = yield* Layer.build(layerProtocol).pipe(
230 Effect.withSpan("environment.websocket.connect"),
231 );
232 // Building the protocol only starts the socket; this span times the
233 // handshake up to the first open, without making `connect` wait for it.
234 yield* Deferred.await(connected).pipe(
235 Effect.raceFirst(Deferred.await(disconnected)),
236 Effect.withSpan("environment.websocket.open"),
237 Effect.ignore,
238 Effect.forkScoped,
239 );
240 const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
241 const initialConfigDeferred = yield* Deferred.make<ServerConfig>();
242 const serverConfigExit = yield* Deferred.make<void, ServerConfigSubscriptionError>();
243 const configSubscriptionClosed = yield* Deferred.make<never, ConnectionAttemptError>();
244 const serverConfigState = yield* Ref.make(Option.none<ServerConfigReplayState>());
245 const serverConfigUpdates = yield* PubSub.sliding<BufferedServerConfigEvent>(64);
246 const configSubscriptionEndedError = new ConnectionTransientErrorClass({
247 reason: "remote-unavailable",
248 detail: `${connection.label} config subscription ended.`,
249 });
250 const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
251 serverConfigInput,
252 ).pipe(
253 Stream.runForEach((event) =>
254 Effect.gen(function* () {
255 const buffered = yield* Ref.modify(serverConfigState, (current) => {
256 const projection = applyServerConfigProjection(
257 Option.map(current, (state) => state.projection),
258 event,
259 );
260 if (Option.isNone(projection)) {
261 return [Option.none<BufferedServerConfigEvent>(), current] as const;
262 }
263 const next = {
264 projection: projection.value,
265 revision: Option.match(current, {
266 onNone: () => 1,
267 onSome: (state) => state.revision + 1,
268 }),
269 themesEvent:
270 event.type === "environmentThemesUpdated"
271 ? event
272 : event.type === "snapshot" &&
273 event.config.environment.capabilities.environmentThemes !== true
274 ? undefined
275 : Option.getOrUndefined(current)?.themesEvent,
276 sourcesEvent:
277 event.type === "usageLimitSourcesUpdated"
278 ? event
279 : event.type === "snapshot" &&
280 event.config.environment.capabilities.usageLimitSources !== true
281 ? undefined
282 : Option.getOrUndefined(current)?.sourcesEvent,
283 } satisfies ServerConfigReplayState;
284 return [
285 Option.some({ event, replay: next, revision: next.revision }),
286 Option.some(next),
287 ] as const;
288 });
289 if (Option.isSome(buffered)) {
290 yield* PubSub.publish(serverConfigUpdates, buffered.value);
291 }
292 if (event.type === "snapshot") {
293 yield* Deferred.succeed(initialConfigDeferred, event.config);
294 }
295 }),
296 ),
297 Effect.onExit((exit) => {
298 if (Exit.isSuccess(exit)) {
299 return Effect.all([
300 Deferred.succeed(serverConfigExit, undefined),
301 Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError),
302 ]).pipe(Effect.asVoid);
303 }
304 if (Cause.hasInterruptsOnly(exit.cause)) {
305 return Effect.void;
306 }
307 return Effect.all([
308 Deferred.failCause(serverConfigExit, exit.cause),
309 Deferred.failCause(configSubscriptionClosed, Cause.map(exit.cause, mapRpcError)),
310 ]).pipe(Effect.asVoid);
311 }),
312 );
313 yield* serverConfigSource.pipe(Effect.forkScoped);
314 const initialConfig = Effect.raceFirst(
315 Deferred.await(initialConfigDeferred),
316 Deferred.await(serverConfigExit).pipe(
317 Effect.mapError(mapRpcError),
318 Effect.flatMap(() => Effect.fail(configSubscriptionEndedError)),
319 ),
320 ).pipe(
321 Effect.filterOrElse(
322 (config) => config.environment.environmentId === connection.environmentId,
323 (config) =>
324 environmentMismatchError({
325 expected: connection.environmentId,
326 actual: config.environment.environmentId,
327 }),
328 ),
329 Effect.withSpan("environment.initialSync"),
330 );
331 const serverConfigEvents = Stream.unwrap(
332 Effect.gen(function* () {
333 const subscription = yield* PubSub.subscribe(serverConfigUpdates);
334 const snapshot = yield* Ref.get(serverConfigState);
335 if (Option.isNone(snapshot)) {
336 return Stream.empty;
337 }
338 const updates = Stream.fromSubscription(subscription).pipe(
339 Stream.filter((buffered) => buffered.revision > snapshot.value.revision),
340 Stream.mapAccum(
341 () => snapshot.value.revision,
342 (revision, buffered) => [
343 buffered.revision,
344 buffered.revision === revision + 1
345 ? [buffered.event]
346 : serverConfigReplayEvents(buffered.replay),
347 ],
348 ),
349 );
350 const terminal = Stream.fromEffect(Deferred.await(serverConfigExit)).pipe(Stream.drain);
351 return Stream.concat(
352 Stream.fromIterable(serverConfigReplayEvents(snapshot.value)),
353 Stream.merge(updates, terminal, { haltStrategy: "either" }),
354 );
355 }),
356 ).pipe(
357 Stream.catchCause((cause) => {
358 if (Cause.hasInterruptsOnly(cause)) {
359 return Stream.failCause(cause);
360 }
361 // The supervisor keeps the original cause. Shared durable consumers
362 // need a transport-shaped failure so they wait for its replacement.
363 return Stream.fail(
364 new RpcClientError.RpcClientError({
365 reason: new RpcClientError.RpcClientDefect({
366 message: `${connection.label} config subscription failed.`,
367 cause,
368 }),
369 }),
370 );
371 }),
372 );
373 const validatedInitialConfig = initialConfig.pipe(
374 Effect.mapError(
375 (cause) =>
376 new RpcClientError.RpcClientError({
377 reason: new RpcClientError.RpcClientDefect({
378 message: `${connection.label} config subscription failed.`,
379 cause,
380 }),
381 }),
382 ),
383 );
384 const subscribeServerConfig = (input: ServerConfigSubscriptionInput) =>
385 Stream.unwrap(
386 validatedInitialConfig.pipe(
387 Effect.as(
388 Equal.equals(input, serverConfigInput)
389 ? serverConfigEvents
390 : protocolClient[WS_METHODS.subscribeServerConfig](input),
391 ),
392 ),
393 );
394 const probe = initialConfig.pipe(
395 Effect.flatMap((config) =>
396 (config.environment.capabilities.connectionProbe === true
397 ? protocolClient[WS_METHODS.serverProbe]({})
398 : protocolClient[WS_METHODS.serverGetConfig]({})
399 ).pipe(Effect.mapError(mapRpcError)),
400 ),
401 Effect.asVoid,
402 Effect.withSpan("clientRuntime.connection.rpcSession.probe"),
403 );
404​
405 return {
406 client: protocolClient,
407 initialConfig,
408 subscribeServerConfig,
409 ready: Deferred.await(connected).pipe(
410 Effect.andThen(initialConfig),
411 Effect.asVoid,
412 Effect.raceFirst(Deferred.await(disconnected)),
413 ),
414 probe,
415 closed: Effect.raceFirst(
416 Deferred.await(disconnected),
417 Deferred.await(configSubscriptionClosed),
418 ),
419 } satisfies RpcSession;
420 });
421​
422 return RpcSessionFactory.of({ connect });
423});
424​
425export const layer = (options: RpcSessionOptions) => Layer.effect(RpcSessionFactory, make(options));