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

session.ts

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