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 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>;
56}
57
58export interface RpcSessionOptions {
59 readonly environmentThemes?: boolean;
60 readonly usageLimitSources?: boolean;
61 /** This client answers /usage-limits itself, so the server may advertise it. */
62 readonly usageLimitsCommand?: boolean;
63}
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;
102}
103
104interface BufferedServerConfigEvent {
105 readonly event: ServerConfigStreamEvent;
106 readonly replay: ServerConfigReplayState;
107 readonly revision: number;
108}
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 ];
123}
124
125const isSocketErrorReason = Schema.is(Socket.SocketErrorReason);
126
127function mapSessionRpcError(
128 error: InitialConfigError | ProbeError | ServerConfigSubscriptionError,
129 networkHint: string,
130): ConnectionAttemptError {
131 switch (error._tag) {
132 case "EnvironmentAuthorizationError":
133 return new ConnectionBlockedError({
134 reason: "permission",
135 detail: error.message,
136 });
137 case "KeybindingsConfigParseError":
138 case "ServerSettingsError":
139 return new ConnectionTransientErrorClass({
140 reason: "remote-unavailable",
141 detail: error.message,
142 });
143 case "RpcClientError":
144 return new ConnectionTransientErrorClass({
145 reason: "transport",
146 detail: `${error.message}${isSocketErrorReason(error.reason) ? networkHint : ""}`,
147 });
148 }
149}
150
151/** @public Service construction is part of the canonical Effect module API. */
152export const make = Effect.fn("RpcSessionFactory.make")(function* (
153 options: RpcSessionOptions = {},
154) {
155 const webSocketConstructor = yield* Socket.WebSocketConstructor;
156 const serverConfigInput: ServerConfigSubscriptionInput = {
157 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
158 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
159 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
160 };
161
162 const connect = Effect.fnUntraced(function* (connection: PreparedConnection) {
163 const networkHint =
164 connection.target._tag === "RelayConnectionTarget" ? ` ${NETWORK_BLOCKING_HINT}` : "";
165 const mapRpcError = (error: Parameters<typeof mapSessionRpcError>[0]) =>
166 mapSessionRpcError(error, networkHint);
167 yield* Effect.annotateCurrentSpan({
168 "connection.environment.id": connection.environmentId,
169 });
170
171 const connected = yield* Deferred.make<void>();
172 const disconnected = yield* Deferred.make<never, ConnectionTransientError>();
173 // Set when the socket closes because the server stopped answering, so the failure says so
174 // instead of looking like the server closed the connection.
175 const pingTimedOut = yield* Ref.make(false);
176 const hooks = RpcClient.ConnectionHooks.of({
177 onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid),
178 onPingTimeout: Ref.set(pingTimedOut, true),
179 onDisconnect: Effect.all([Deferred.isDone(connected), Ref.get(pingTimedOut)]).pipe(
180 Effect.flatMap(([wasConnected, timedOut]) =>
181 Deferred.fail(
182 disconnected,
183 new ConnectionTransientErrorClass({
184 reason: "transport",
185 detail: `${
186 !wasConnected
187 ? `${connection.label} could not establish a WebSocket connection.`
188 : timedOut
189 ? `${connection.label} stopped responding.`
190 : `${connection.label} disconnected.`
191 }${networkHint}`,
192 }),
193 ),
194 ),
195 Effect.asVoid,
196 ),
197 });
198 const layerSocket = Socket.layerWebSocket(connection.socketUrl, {
199 openTimeout: SOCKET_OPEN_TIMEOUT,
200 }).pipe(Layer.provide(Layer.succeed(Socket.WebSocketConstructor, webSocketConstructor)));
201 const layerProtocol = Layer.effect(
202 RpcClient.Protocol,
203 RpcClient.makeProtocolSocket({
204 pingTimeout: PING_TIMEOUT,
205 retryTransientErrors: false,
206 retryPolicy: Schedule.recurs(0),
207 }),
208 ).pipe(
209 Layer.provide(
210 Layer.mergeAll(
211 layerSocket,
212 RpcSerialization.layerJson,
213 Layer.succeed(RpcClient.ConnectionHooks, hooks),
214 ),
215 ),
216 );
217 const protocolContext = yield* Layer.build(layerProtocol).pipe(
218 Effect.withSpan("environment.websocket.connect"),
219 );
220 const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
221 const initialConfigDeferred = yield* Deferred.make<ServerConfig>();
222 const serverConfigExit = yield* Deferred.make<void, ServerConfigSubscriptionError>();
223 const configSubscriptionClosed = yield* Deferred.make<never, ConnectionAttemptError>();
224 const serverConfigState = yield* Ref.make(Option.none<ServerConfigReplayState>());
225 const serverConfigUpdates = yield* PubSub.sliding<BufferedServerConfigEvent>(64);
226 const configSubscriptionEndedError = new ConnectionTransientErrorClass({
227 reason: "remote-unavailable",
228 detail: `${connection.label} config subscription ended.`,
229 });
230 const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
231 serverConfigInput,
232 ).pipe(
233 Stream.runForEach((event) =>
234 Effect.gen(function* () {
235 const buffered = yield* Ref.modify(serverConfigState, (current) => {
236 const projection = applyServerConfigProjection(
237 Option.map(current, (state) => state.projection),
238 event,
239 );
240 if (Option.isNone(projection)) {
241 return [Option.none<BufferedServerConfigEvent>(), current] as const;
242 }
243 const next = {
244 projection: projection.value,
245 revision: Option.match(current, {
246 onNone: () => 1,
247 onSome: (state) => state.revision + 1,
248 }),
249 themesEvent:
250 event.type === "environmentThemesUpdated"
251 ? event
252 : event.type === "snapshot" &&
253 event.config.environment.capabilities.environmentThemes !== true
254 ? undefined
255 : Option.getOrUndefined(current)?.themesEvent,
256 sourcesEvent:
257 event.type === "usageLimitSourcesUpdated"
258 ? event
259 : event.type === "snapshot" &&
260 event.config.environment.capabilities.usageLimitSources !== true
261 ? undefined
262 : Option.getOrUndefined(current)?.sourcesEvent,
263 } satisfies ServerConfigReplayState;
264 return [
265 Option.some({ event, replay: next, revision: next.revision }),
266 Option.some(next),
267 ] as const;
268 });
269 if (Option.isSome(buffered)) {
270 yield* PubSub.publish(serverConfigUpdates, buffered.value);
271 }
272 if (event.type === "snapshot") {
273 yield* Deferred.succeed(initialConfigDeferred, event.config);
274 }
275 }),
276 ),
277 Effect.onExit((exit) => {
278 if (Exit.isSuccess(exit)) {
279 return Effect.all([
280 Deferred.succeed(serverConfigExit, undefined),
281 Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError),
282 ]).pipe(Effect.asVoid);
283 }
284 if (Cause.hasInterruptsOnly(exit.cause)) {
285 return Effect.void;
286 }
287 return Effect.all([
288 Deferred.failCause(serverConfigExit, exit.cause),
289 Deferred.failCause(configSubscriptionClosed, Cause.map(exit.cause, mapRpcError)),
290 ]).pipe(Effect.asVoid);
291 }),
292 );
293 yield* serverConfigSource.pipe(Effect.forkScoped);
294 const initialConfig = Effect.raceFirst(
295 Deferred.await(initialConfigDeferred),
296 Deferred.await(serverConfigExit).pipe(
297 Effect.mapError(mapRpcError),
298 Effect.flatMap(() => Effect.fail(configSubscriptionEndedError)),
299 ),
300 ).pipe(
301 Effect.filterOrElse(
302 (config) => config.environment.environmentId === connection.environmentId,
303 (config) =>
304 environmentMismatchError({
305 expected: connection.environmentId,
306 actual: config.environment.environmentId,
307 }),
308 ),
309 Effect.withSpan("environment.initialSync"),
310 );
311 const serverConfigEvents = Stream.unwrap(
312 Effect.gen(function* () {
313 const subscription = yield* PubSub.subscribe(serverConfigUpdates);
314 const snapshot = yield* Ref.get(serverConfigState);
315 if (Option.isNone(snapshot)) {
316 return Stream.empty;
317 }
318 const updates = Stream.fromSubscription(subscription).pipe(
319 Stream.filter((buffered) => buffered.revision > snapshot.value.revision),
320 Stream.mapAccum(
321 () => snapshot.value.revision,
322 (revision, buffered) => [
323 buffered.revision,
324 buffered.revision === revision + 1
325 ? [buffered.event]
326 : serverConfigReplayEvents(buffered.replay),
327 ],
328 ),
329 );
330 const terminal = Stream.fromEffect(Deferred.await(serverConfigExit)).pipe(Stream.drain);
331 return Stream.concat(
332 Stream.fromIterable(serverConfigReplayEvents(snapshot.value)),
333 Stream.merge(updates, terminal, { haltStrategy: "either" }),
334 );
335 }),
336 ).pipe(
337 Stream.catchCause((cause) => {
338 if (Cause.hasInterruptsOnly(cause)) {
339 return Stream.failCause(cause);
340 }
341 // The supervisor keeps the original cause. Shared durable consumers
342 // need a transport-shaped failure so they wait for its replacement.
343 return Stream.fail(
344 new RpcClientError.RpcClientError({
345 reason: new RpcClientError.RpcClientDefect({
346 message: `${connection.label} config subscription failed.`,
347 cause,
348 }),
349 }),
350 );
351 }),
352 );
353 const validatedInitialConfig = initialConfig.pipe(
354 Effect.mapError(
355 (cause) =>
356 new RpcClientError.RpcClientError({
357 reason: new RpcClientError.RpcClientDefect({
358 message: `${connection.label} config subscription failed.`,
359 cause,
360 }),
361 }),
362 ),
363 );
364 const subscribeServerConfig = (input: ServerConfigSubscriptionInput) =>
365 Stream.unwrap(
366 validatedInitialConfig.pipe(
367 Effect.as(
368 Equal.equals(input, serverConfigInput)
369 ? serverConfigEvents
370 : protocolClient[WS_METHODS.subscribeServerConfig](input),
371 ),
372 ),
373 );
374 const probe = initialConfig.pipe(
375 Effect.flatMap((config) =>
376 (config.environment.capabilities.connectionProbe === true
377 ? protocolClient[WS_METHODS.serverProbe]({})
378 : protocolClient[WS_METHODS.serverGetConfig]({})
379 ).pipe(Effect.mapError(mapRpcError)),
380 ),
381 Effect.asVoid,
382 Effect.withSpan("clientRuntime.connection.rpcSession.probe"),
383 );
384
385 return {
386 client: protocolClient,
387 initialConfig,
388 subscribeServerConfig,
389 ready: Deferred.await(connected).pipe(
390 Effect.andThen(initialConfig),
391 Effect.asVoid,
392 Effect.raceFirst(Deferred.await(disconnected)),
393 ),
394 probe,
395 closed: Effect.raceFirst(
396 Deferred.await(disconnected),
397 Deferred.await(configSubscriptionClosed),
398 ),
399 } satisfies RpcSession;
400 });
401
402 return RpcSessionFactory.of({ connect });
403});
404
405export const layer = (options: RpcSessionOptions) => Layer.effect(RpcSessionFactory, make(options));