Open History to see the last commit
1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type TerminalAttachStreamEvent,
4 type TerminalEvent,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import type * as Arr from "effect/Array";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Latch from "effect/Latch";
11import * as Stream from "effect/Stream";
12import type { RpcServer } from "effect/rpc";
13
14const MAX_PENDING_CHUNKS = 8;
15const MAX_PENDING_BYTES = 64 * 1024;
16const isFull = (sizes: number[]) =>
17 sizes.length >= MAX_PENDING_CHUNKS ||
18 sizes.reduce((total, size) => total + size, 0) >= MAX_PENDING_BYTES;
19// Terminal output is small chunks, so its window also caps bytes. The other streams
20// window by count only: sizing a multi-MB thread snapshot would serialize it twice.
21const BYTE_WINDOWED_STREAMS: ReadonlySet<string> = new Set([
22 WS_METHODS.terminalAttach,
23 WS_METHODS.terminalObserve,
24]);
25// One ACK round trip per chunk stalls sync on high-latency links.
26const COUNT_WINDOWED_STREAMS: ReadonlySet<string> = new Set([
27 WS_METHODS.subscribeServerConfig,
28 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
29 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
30]);
31
32interface Window {
33 readonly bytes: boolean;
34 readonly sizes: number[];
35}
36
37export function withOutputWindow(
38 protocol: RpcServer.Protocol["Service"],
39): RpcServer.Protocol["Service"] {
40 // RpcServer drops a disconnected client before its streams exit, so their Exit never
41 // reaches send; departed clients are pruned when a window opens instead.
42 const clients = new Map<number, Map<string, Window>>();
43 let receive: Parameters<RpcServer.Protocol["Service"]["run"]>[0];
44 const windowFor = (clientId: number, requestId: string) => clients.get(clientId)?.get(requestId);
45 const openWindow = Effect.fnUntraced(function* (
46 clientId: number,
47 requestId: string,
48 bytes: boolean,
49 ) {
50 const connected = yield* protocol.clientIds;
51 for (const id of clients.keys()) if (!connected.has(id)) clients.delete(id);
52 let windows = clients.get(clientId);
53 if (!windows) clients.set(clientId, (windows = new Map()));
54 if (!windows.has(requestId)) windows.set(requestId, { bytes, sizes: [] });
55 });
56 return {
57 ...protocol,
58 run: (write) => {
59 receive = write;
60 return protocol.run((clientId, message) =>
61 Effect.suspend(() => {
62 if (message._tag === "Request") {
63 const bytes = BYTE_WINDOWED_STREAMS.has(message.tag);
64 if (bytes || COUNT_WINDOWED_STREAMS.has(message.tag)) {
65 return openWindow(clientId, String(message.id), bytes).pipe(
66 Effect.andThen(write(clientId, message)),
67 );
68 }
69 } else if (message._tag === "Ack") {
70 const window = windowFor(clientId, String(message.requestId));
71 if (window) {
72 const wasFull = isFull(window.sizes);
73 window.sizes.shift();
74 if (!wasFull || isFull(window.sizes)) return Effect.void;
75 }
76 }
77 return write(clientId, message);
78 }),
79 );
80 },
81 send: (clientId, response, transferables) =>
82 Effect.suspend(() => {
83 const send = protocol.send(clientId, response, transferables);
84 if (response._tag === "Exit") {
85 clients.get(clientId)?.delete(String(response.requestId));
86 } else if (response._tag === "Chunk") {
87 const window = windowFor(clientId, String(response.requestId));
88 if (window) {
89 window.sizes.push(
90 // @effect-diagnostics-next-line globalJsonInEffect:off
91 window.bytes ? Buffer.byteLength(JSON.stringify(response)) : 0,
92 );
93 if (!isFull(window.sizes)) {
94 return send.pipe(
95 Effect.andThen(() =>
96 receive(clientId, {
97 _tag: "Ack",
98 requestId: response.requestId,
99 }),
100 ),
101 );
102 }
103 }
104 }
105 return send;
106 }),
107 };
108}
109
110const MAX_QUEUED_OUTPUT = 8 * 1024 * 1024;
111// Charge an envelope so tiny events cannot bypass the byte budget.
112const EVENT_OVERHEAD = 128;
113
114type Listener<A> = (event: A) => Effect.Effect<void>;
115// Acquisition must register cleanup synchronously with installing the listener.
116type Subscribe<A, E> = (
117 listener: Listener<A>,
118 registerCleanup: (stop: () => void) => void,
119) => Effect.Effect<() => void, E>;
120
121const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) =>
122 EVENT_OVERHEAD +
123 (event.type === "output"
124 ? Buffer.byteLength(event.data)
125 : "snapshot" in event
126 ? Buffer.byteLength(event.snapshot.history)
127 : 0);
128
129export function terminalOutputStream<A extends TerminalEvent | TerminalAttachStreamEvent, E>(
130 subscribe: Subscribe<A, E>,
131 resync?: Subscribe<A, E>,
132 maxQueued = MAX_QUEUED_OUTPUT,
133): Stream.Stream<A, E> {
134 return Stream.unwrap(
135 Effect.gen(function* () {
136 const ready = yield* Latch.make();
137 let pending: Array<A | undefined> = [];
138 let sizes: number[] = [];
139 let head = 0;
140 let queued = 0;
141 let overflowed = false;
142 let subscription = 0;
143 let unsubscribe: (() => void) | null = null;
144 const release = () => {
145 subscription += 1;
146 unsubscribe?.();
147 unsubscribe = null;
148 pending = [];
149 sizes = [];
150 head = 0;
151 queued = 0;
152 };
153 yield* Effect.addFinalizer(() => Effect.sync(release));
154
155 const listen = (from: Subscribe<A, E>) =>
156 Effect.suspend(() => {
157 const id = ++subscription;
158 return from(
159 (event) =>
160 Effect.sync(() => {
161 if (id !== subscription) return;
162 const size = queuedSize(event);
163 pending.push(event);
164 sizes.push(size);
165 queued += size;
166 // A single snapshot must fit even when history fills the budget.
167 if (queued - sizes[head]! > maxQueued) {
168 release();
169 overflowed = true;
170 }
171 ready.openUnsafe();
172 }),
173 (stop) => {
174 // Overflow or cancellation may invalidate acquisition before registration.
175 if (id === subscription) unsubscribe = stop;
176 else stop();
177 },
178 ).pipe(
179 Effect.asVoid,
180 Effect.onError(() => Effect.sync(release)),
181 );
182 });
183
184 const take = () => {
185 const event = pending[head]!;
186 pending[head] = undefined;
187 head += 1;
188 return event;
189 };
190 const takeBatch = (): Arr.NonEmptyReadonlyArray<A> => {
191 let bytes = sizes[head]!;
192 const batch: [A, ...A[]] = [take()];
193 while (head < pending.length && bytes + sizes[head]! <= MAX_PENDING_BYTES) {
194 bytes += sizes[head]!;
195 batch.push(take());
196 }
197 queued -= bytes;
198 if (head * 2 >= pending.length) {
199 pending = pending.slice(head);
200 sizes = sizes.slice(head);
201 head = 0;
202 }
203 return batch;
204 };
205
206 const pull: Effect.Effect<Arr.NonEmptyReadonlyArray<A>, E | Cause.Done> = Effect.suspend(
207 () => {
208 if (overflowed) {
209 overflowed = false;
210 return resync ? listen(resync).pipe(Effect.andThen(pull)) : Cause.done();
211 }
212 if (head < pending.length) return Effect.succeed(takeBatch());
213 ready.closeUnsafe();
214 return ready.await.pipe(Effect.andThen(pull));
215 },
216 );
217
218 yield* listen(subscribe);
219 return Stream.fromPull(Effect.succeed(pull));
220 }),
221 );
222}