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