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

session.ts

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