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

session.ts

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