Open History to see the last commit
1import { Duration, Effect, Exit, ManagedRuntime, Option, Scope, Stream } from "effect";
2
3import {
4 createWsRpcProtocolLayer,
5 makeWsRpcProtocolClient,
6 type WsRpcProtocolClient,
7} from "./rpc/protocol";
8import { RpcClient } from "effect/unstable/rpc";
9
10interface SubscribeOptions {
11 readonly retryDelay?: Duration.Input;
12}
13
14interface RequestOptions {
15 readonly timeout?: Option.Option<Duration.Input>;
16}
17
18const DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS = Duration.millis(250);
19
20function formatErrorMessage(error: unknown): string {
21 if (error instanceof Error && error.message.trim().length > 0) {
22 return error.message;
23 }
24 return String(error);
25}
26
27export class WsTransport {
28 private readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
29 private readonly clientScope: Scope.Closeable;
30 private readonly clientPromise: Promise<WsRpcProtocolClient>;
31 private disposed = false;
32
33 constructor(url?: string) {
34 this.runtime = ManagedRuntime.make(createWsRpcProtocolLayer(url));
35 this.clientScope = this.runtime.runSync(Scope.make());
36 this.clientPromise = this.runtime.runPromise(
37 Scope.provide(this.clientScope)(makeWsRpcProtocolClient),
38 );
39 }
40
41 async request<TSuccess>(
42 execute: (client: WsRpcProtocolClient) => Effect.Effect<TSuccess, Error, never>,
43 _options?: RequestOptions,
44 ): Promise<TSuccess> {
45 if (this.disposed) {
46 throw new Error("Transport disposed");
47 }
48
49 const client = await this.clientPromise;
50 return await this.runtime.runPromise(Effect.suspend(() => execute(client)));
51 }
52
53 async requestStream<TValue>(
54 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
55 listener: (value: TValue) => void,
56 ): Promise<void> {
57 if (this.disposed) {
58 throw new Error("Transport disposed");
59 }
60
61 const client = await this.clientPromise;
62 await this.runtime.runPromise(
63 Stream.runForEach(connect(client), (value) =>
64 Effect.sync(() => {
65 try {
66 listener(value);
67 } catch {
68 // Swallow listener errors so the stream can finish cleanly.
69 }
70 }),
71 ),
72 );
73 }
74
75 subscribe<TValue>(
76 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
77 listener: (value: TValue) => void,
78 options?: SubscribeOptions,
79 ): () => void {
80 if (this.disposed) {
81 return () => undefined;
82 }
83
84 let active = true;
85 const retryDelayMs = options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS;
86 const cancel = this.runtime.runCallback(
87 Effect.promise(() => this.clientPromise).pipe(
88 Effect.flatMap((client) =>
89 Stream.runForEach(connect(client), (value) =>
90 Effect.sync(() => {
91 if (!active) {
92 return;
93 }
94 try {
95 listener(value);
96 } catch {
97 // Swallow listener errors so the stream stays live.
98 }
99 }),
100 ),
101 ),
102 Effect.catch((error) => {
103 if (!active || this.disposed) {
104 return Effect.interrupt;
105 }
106 return Effect.sync(() => {
107 console.warn("WebSocket RPC subscription disconnected", {
108 error: formatErrorMessage(error),
109 });
110 }).pipe(Effect.andThen(Effect.sleep(retryDelayMs)));
111 }),
112 Effect.forever,
113 ),
114 );
115
116 return () => {
117 active = false;
118 cancel();
119 };
120 }
121
122 async dispose() {
123 if (this.disposed) {
124 return;
125 }
126 this.disposed = true;
127 await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void)).finally(() => {
128 this.runtime.dispose();
129 });
130 }
131}