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