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

session.ts

399 lines14.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/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";
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 /** This client answers /usage-limits itself, so the server may advertise it. */
62 readonly usageLimitsCommand?: boolean;
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;
103​
104interface BufferedServerConfigEvent {
105 readonly event: ServerConfigStreamEvent;
106 readonly replay: ServerConfigReplayState;
107 readonly revision: number;
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 ];
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 }
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 const hooks = RpcClient.ConnectionHooks.of({
174 onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid),
175 onDisconnect: Deferred.isDone(connected).pipe(
176 Effect.flatMap((wasConnected) =>
177 Deferred.fail(
178 disconnected,
179 new ConnectionTransientErrorClass({
180 reason: "transport",
181 detail: `${
182 wasConnected
183 ? `${connection.label} disconnected.`
184 : `${connection.label} could not establish a WebSocket connection.`
185 }${networkHint}`,
186 }),
187 ),
188 ),
189 Effect.asVoid,
190 ),
191 });
192 const socketLayer = Socket.layerWebSocket(connection.socketUrl, {
193 openTimeout: SOCKET_OPEN_TIMEOUT,
194 }).pipe(Layer.provide(Layer.succeed(Socket.WebSocketConstructor, webSocketConstructor)));
195 const protocolLayer = Layer.effect(
196 RpcClient.Protocol,
197 RpcClient.makeProtocolSocket({
198 retryTransientErrors: false,
199 retryPolicy: Schedule.recurs(0),
200 }),
201 ).pipe(
202 Layer.provide(
203 Layer.mergeAll(
204 socketLayer,
205 RpcSerialization.layerJson,
206 Layer.succeed(RpcClient.ConnectionHooks, hooks),
207 ),
208 ),
209 );
210 const protocolContext = yield* Layer.build(protocolLayer).pipe(
211 Effect.withSpan("environment.websocket.connect"),
212 );
213 const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
214 const initialConfigDeferred = yield* Deferred.make<ServerConfig>();
215 const serverConfigExit = yield* Deferred.make<void, ServerConfigSubscriptionError>();
216 const configSubscriptionClosed = yield* Deferred.make<never, ConnectionAttemptError>();
217 const serverConfigState = yield* Ref.make(Option.none<ServerConfigReplayState>());
218 const serverConfigUpdates = yield* PubSub.sliding<BufferedServerConfigEvent>(64);
219 const configSubscriptionEndedError = new ConnectionTransientErrorClass({
220 reason: "remote-unavailable",
221 detail: `${connection.label} config subscription ended.`,
222 });
223 const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
224 serverConfigInput,
225 ).pipe(
226 Stream.runForEach((event) =>
227 Effect.gen(function* () {
228 const buffered = yield* Ref.modify(serverConfigState, (current) => {
229 const projection = applyServerConfigProjection(
230 Option.map(current, (state) => state.projection),
231 event,
232 );
233 if (Option.isNone(projection)) {
234 return [Option.none<BufferedServerConfigEvent>(), current] as const;
235 }
236 const next = {
237 projection: projection.value,
238 revision: Option.match(current, {
239 onNone: () => 1,
240 onSome: (state) => state.revision + 1,
241 }),
242 themesEvent:
243 event.type === "environmentThemesUpdated"
244 ? event
245 : event.type === "snapshot" &&
246 event.config.environment.capabilities.environmentThemes !== true
247 ? undefined
248 : Option.getOrUndefined(current)?.themesEvent,
249 sourcesEvent:
250 event.type === "usageLimitSourcesUpdated"
251 ? event
252 : event.type === "snapshot" &&
253 event.config.environment.capabilities.usageLimitSources !== true
254 ? undefined
255 : Option.getOrUndefined(current)?.sourcesEvent,
256 } satisfies ServerConfigReplayState;
257 return [
258 Option.some({ event, replay: next, revision: next.revision }),
259 Option.some(next),
260 ] as const;
261 });
262 if (Option.isSome(buffered)) {
263 yield* PubSub.publish(serverConfigUpdates, buffered.value);
264 }
265 if (event.type === "snapshot") {
266 yield* Deferred.succeed(initialConfigDeferred, event.config);
267 }
268 }),
269 ),
270 Effect.onExit((exit) => {
271 if (Exit.isSuccess(exit)) {
272 return Effect.all([
273 Deferred.succeed(serverConfigExit, undefined),
274 Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError),
275 ]).pipe(Effect.asVoid);
276 }
277 if (Cause.hasInterruptsOnly(exit.cause)) {
278 return Effect.void;
279 }
280 return Effect.all([
281 Deferred.failCause(serverConfigExit, exit.cause),
282 Deferred.failCause(configSubscriptionClosed, Cause.map(exit.cause, mapRpcError)),
283 ]).pipe(Effect.asVoid);
284 }),
285 );
286 yield* serverConfigSource.pipe(Effect.forkScoped);
287 const initialConfig = Effect.raceFirst(
288 Deferred.await(initialConfigDeferred),
289 Deferred.await(serverConfigExit).pipe(
290 Effect.mapError(mapRpcError),
291 Effect.flatMap(() => Effect.fail(configSubscriptionEndedError)),
292 ),
293 ).pipe(
294 Effect.flatMap((config) =>
295 config.environment.environmentId === connection.environmentId
296 ? Effect.succeed(config)
297 : environmentMismatchError({
298 expected: connection.environmentId,
299 actual: config.environment.environmentId,
300 }),
301 ),
302 Effect.withSpan("environment.initialSync"),
303 );
304 const serverConfigEvents = Stream.unwrap(
305 Effect.gen(function* () {
306 const subscription = yield* PubSub.subscribe(serverConfigUpdates);
307 const snapshot = yield* Ref.get(serverConfigState);
308 if (Option.isNone(snapshot)) {
309 return Stream.empty;
310 }
311 const updates = Stream.fromSubscription(subscription).pipe(
312 Stream.filter((buffered) => buffered.revision > snapshot.value.revision),
313 Stream.mapAccum(
314 () => snapshot.value.revision,
315 (revision, buffered) => [
316 buffered.revision,
317 buffered.revision === revision + 1
318 ? [buffered.event]
319 : serverConfigReplayEvents(buffered.replay),
320 ],
321 ),
322 );
323 const terminal = Stream.fromEffect(Deferred.await(serverConfigExit)).pipe(Stream.drain);
324 return Stream.concat(
325 Stream.fromIterable(serverConfigReplayEvents(snapshot.value)),
326 Stream.merge(updates, terminal, { haltStrategy: "either" }),
327 );
328 }),
329 ).pipe(
330 Stream.catchCause((cause) => {
331 if (Cause.hasInterruptsOnly(cause)) {
332 return Stream.failCause(cause);
333 }
334 // The supervisor keeps the original cause. Shared durable consumers
335 // need a transport-shaped failure so they wait for its replacement.
336 return Stream.fail(
337 new RpcClientError.RpcClientError({
338 reason: new RpcClientError.RpcClientDefect({
339 message: `${connection.label} config subscription failed.`,
340 cause,
341 }),
342 }),
343 );
344 }),
345 );
346 const validatedInitialConfig = initialConfig.pipe(
347 Effect.mapError(
348 (cause) =>
349 new RpcClientError.RpcClientError({
350 reason: new RpcClientError.RpcClientDefect({
351 message: `${connection.label} config subscription failed.`,
352 cause,
353 }),
354 }),
355 ),
356 );
357 const subscribeServerConfig = (input: ServerConfigSubscriptionInput) =>
358 Stream.unwrap(
359 validatedInitialConfig.pipe(
360 Effect.as(
361 Equal.equals(input, serverConfigInput)
362 ? serverConfigEvents
363 : protocolClient[WS_METHODS.subscribeServerConfig](input),
364 ),
365 ),
366 );
367 const probe = initialConfig.pipe(
368 Effect.flatMap((config) =>
369 (config.environment.capabilities.connectionProbe === true
370 ? protocolClient[WS_METHODS.serverProbe]({})
371 : protocolClient[WS_METHODS.serverGetConfig]({})
372 ).pipe(Effect.mapError(mapRpcError)),
373 ),
374 Effect.asVoid,
375 Effect.withSpan("clientRuntime.connection.rpcSession.probe"),
376 );
377​
378 return {
379 client: protocolClient,
380 initialConfig,
381 subscribeServerConfig,
382 ready: Deferred.await(connected).pipe(
383 Effect.andThen(initialConfig),
384 Effect.asVoid,
385 Effect.raceFirst(Deferred.await(disconnected)),
386 ),
387 probe,
388 closed: Effect.raceFirst(
389 Deferred.await(disconnected),
390 Deferred.await(configSubscriptionClosed),
391 ),
392 } satisfies RpcSession;
393 });
394​
395 return RpcSessionFactory.of({ connect });
396});
397​
398export const layerWithOptions = (options: RpcSessionOptions) =>
399 Layer.effect(RpcSessionFactory, make(options));