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 const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
218 const initialConfigDeferred = yield* Deferred.make<ServerConfig>();
219 const serverConfigExit = yield* Deferred.make<void, ServerConfigSubscriptionError>();
220 const configSubscriptionClosed = yield* Deferred.make<never, ConnectionAttemptError>();
221 const serverConfigState = yield* Ref.make(Option.none<ServerConfigReplayState>());
222 const serverConfigUpdates = yield* PubSub.sliding<BufferedServerConfigEvent>(64);
223 const configSubscriptionEndedError = new ConnectionTransientErrorClass({
224 reason: "remote-unavailable",
225 detail: `${connection.label} config subscription ended.`,
226 });
227 const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
228 serverConfigInput,
229 ).pipe(
230 Stream.runForEach((event) =>
231 Effect.gen(function* () {
232 const buffered = yield* Ref.modify(serverConfigState, (current) => {
233 const projection = applyServerConfigProjection(
234 Option.map(current, (state) => state.projection),
235 event,
236 );
237 if (Option.isNone(projection)) {
238 return [Option.none<BufferedServerConfigEvent>(), current] as const;
239 }
240 const next = {
241 projection: projection.value,
242 revision: Option.match(current, {
243 onNone: () => 1,
244 onSome: (state) => state.revision + 1,
245 }),
246 themesEvent:
247 event.type === "environmentThemesUpdated"
248 ? event
249 : event.type === "snapshot" &&
250 event.config.environment.capabilities.environmentThemes !== true
251 ? undefined
252 : Option.getOrUndefined(current)?.themesEvent,
253 sourcesEvent:
254 event.type === "usageLimitSourcesUpdated"
255 ? event
256 : event.type === "snapshot" &&
257 event.config.environment.capabilities.usageLimitSources !== true
258 ? undefined
259 : Option.getOrUndefined(current)?.sourcesEvent,
260 } satisfies ServerConfigReplayState;
261 return [
262 Option.some({ event, replay: next, revision: next.revision }),
263 Option.some(next),
264 ] as const;
265 });
266 if (Option.isSome(buffered)) {
267 yield* PubSub.publish(serverConfigUpdates, buffered.value);
268 }
269 if (event.type === "snapshot") {
270 yield* Deferred.succeed(initialConfigDeferred, event.config);
271 }
272 }),
273 ),
274 Effect.onExit((exit) => {
275 if (Exit.isSuccess(exit)) {
276 return Effect.all([
277 Deferred.succeed(serverConfigExit, undefined),
278 Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError),
279 ]).pipe(Effect.asVoid);
280 }
281 if (Cause.hasInterruptsOnly(exit.cause)) {
282 return Effect.void;
283 }
284 return Effect.all([
285 Deferred.failCause(serverConfigExit, exit.cause),
286 Deferred.failCause(configSubscriptionClosed, Cause.map(exit.cause, mapRpcError)),
287 ]).pipe(Effect.asVoid);
288 }),
289 );
290 yield* serverConfigSource.pipe(Effect.forkScoped);
291 const initialConfig = Effect.raceFirst(
292 Deferred.await(initialConfigDeferred),
293 Deferred.await(serverConfigExit).pipe(
294 Effect.mapError(mapRpcError),
295 Effect.flatMap(() => Effect.fail(configSubscriptionEndedError)),
296 ),
297 ).pipe(
298 Effect.filterOrElse(
299 (config) => config.environment.environmentId === connection.environmentId,
300 (config) =>
301 environmentMismatchError({
302 expected: connection.environmentId,
303 actual: config.environment.environmentId,
304 }),
305 ),
306 Effect.withSpan("environment.initialSync"),
307 );
308 const serverConfigEvents = Stream.unwrap(
309 Effect.gen(function* () {
310 const subscription = yield* PubSub.subscribe(serverConfigUpdates);
311 const snapshot = yield* Ref.get(serverConfigState);
312 if (Option.isNone(snapshot)) {
313 return Stream.empty;
314 }
315 const updates = Stream.fromSubscription(subscription).pipe(
316 Stream.filter((buffered) => buffered.revision > snapshot.value.revision),
317 Stream.mapAccum(
318 () => snapshot.value.revision,
319 (revision, buffered) => [
320 buffered.revision,
321 buffered.revision === revision + 1
322 ? [buffered.event]
323 : serverConfigReplayEvents(buffered.replay),
324 ],
325 ),
326 );
327 const terminal = Stream.fromEffect(Deferred.await(serverConfigExit)).pipe(Stream.drain);
328 return Stream.concat(
329 Stream.fromIterable(serverConfigReplayEvents(snapshot.value)),
330 Stream.merge(updates, terminal, { haltStrategy: "either" }),
331 );
332 }),
333 ).pipe(
334 Stream.catchCause((cause) => {
335 if (Cause.hasInterruptsOnly(cause)) {
336 return Stream.failCause(cause);
337 }
338 // The supervisor keeps the original cause. Shared durable consumers
339 // need a transport-shaped failure so they wait for its replacement.
340 return Stream.fail(
341 new RpcClientError.RpcClientError({
342 reason: new RpcClientError.RpcClientDefect({
343 message: `${connection.label} config subscription failed.`,
344 cause,
345 }),
346 }),
347 );
348 }),
349 );
350 const validatedInitialConfig = initialConfig.pipe(
351 Effect.mapError(
352 (cause) =>
353 new RpcClientError.RpcClientError({
354 reason: new RpcClientError.RpcClientDefect({
355 message: `${connection.label} config subscription failed.`,
356 cause,
357 }),
358 }),
359 ),
360 );
361 const subscribeServerConfig = (input: ServerConfigSubscriptionInput) =>
362 Stream.unwrap(
363 validatedInitialConfig.pipe(
364 Effect.as(
365 Equal.equals(input, serverConfigInput)
366 ? serverConfigEvents
367 : protocolClient[WS_METHODS.subscribeServerConfig](input),
368 ),
369 ),
370 );
371 const probe = initialConfig.pipe(
372 Effect.flatMap((config) =>
373 (config.environment.capabilities.connectionProbe === true
374 ? protocolClient[WS_METHODS.serverProbe]({})
375 : protocolClient[WS_METHODS.serverGetConfig]({})
376 ).pipe(Effect.mapError(mapRpcError)),
377 ),
378 Effect.asVoid,
379 Effect.withSpan("clientRuntime.connection.rpcSession.probe"),
380 );
381
382 return {
383 client: protocolClient,
384 initialConfig,
385 subscribeServerConfig,
386 ready: Deferred.await(connected).pipe(
387 Effect.andThen(initialConfig),
388 Effect.asVoid,
389 Effect.raceFirst(Deferred.await(disconnected)),
390 ),
391 probe,
392 closed: Effect.raceFirst(
393 Deferred.await(disconnected),
394 Deferred.await(configSubscriptionClosed),
395 ),
396 } satisfies RpcSession;
397 });
398
399 return RpcSessionFactory.of({ connect });
400});
401
402export const layer = (options: RpcSessionOptions) => Layer.effect(RpcSessionFactory, make(options));