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 Clock from "effect/Clock";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Latch from "effect/Latch";
13import * as Stream from "effect/Stream";
14import type { RpcServer } from "effect/rpc";
15
16const MAX_PENDING_CHUNKS = 8;
17const MAX_PENDING_BYTES = 64 * 1024;
18// Charge an envelope so tiny events cannot bypass the byte budget.
19const EVENT_OVERHEAD = 128;
20const isFull = (sizes: number[]) =>
21 sizes.length >= MAX_PENDING_CHUNKS ||
22 sizes.reduce((total, size) => total + size, 0) >= MAX_PENDING_BYTES;
23// Terminal output is small chunks, so its window also caps bytes. The other streams
24// window by count only: sizing a multi-MB thread snapshot would serialize it twice.
25const BYTE_WINDOWED_STREAMS: ReadonlySet<string> = new Set([
26 WS_METHODS.terminalAttach,
27 WS_METHODS.terminalObserve,
28]);
29// One ACK round trip per chunk stalls sync on high-latency links.
30const COUNT_WINDOWED_STREAMS: ReadonlySet<string> = new Set([
31 WS_METHODS.subscribeServerConfig,
32 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
33 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
34]);
35
36const byteLengthOf = (value: unknown) => (typeof value === "string" ? Buffer.byteLength(value) : 0);
37
38// Charges every variable-size field a terminal event can carry, so the byte
39// budgets below cannot be bypassed by a large payload in an uncharged field.
40const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) =>
41 EVENT_OVERHEAD +
42 ("threadId" in event ? byteLengthOf(event.threadId) + byteLengthOf(event.terminalId) : 0) +
43 (event.type === "output"
44 ? byteLengthOf(event.data)
45 : event.type === "error"
46 ? byteLengthOf(event.message)
47 : event.type === "activity"
48 ? byteLengthOf(event.label)
49 : event.type === "cleared"
50 ? byteLengthOf(event.pendingControlSequence)
51 : "snapshot" in event
52 ? byteLengthOf(event.snapshot.threadId) +
53 byteLengthOf(event.snapshot.terminalId) +
54 byteLengthOf(event.snapshot.history) +
55 byteLengthOf(event.snapshot.cwd) +
56 byteLengthOf(event.snapshot.worktreePath) +
57 byteLengthOf(event.snapshot.label)
58 : 0);
59
60// Byte-windowed streams carry TerminalAttachStreamEvent, whose encoded form is the
61// event itself, so charge it like the output queue does instead of serializing twice.
62const chunkSize = (values: ReadonlyArray<unknown>) =>
63 values.reduce<number>(
64 (total, value) => total + queuedSize(value as TerminalAttachStreamEvent),
65 EVENT_OVERHEAD,
66 );
67
68interface Window {
69 readonly bytes: boolean;
70 readonly sizes: number[];
71}
72
73export function withOutputWindow(
74 protocol: RpcServer.Protocol["Service"],
75): RpcServer.Protocol["Service"] {
76 // RpcServer drops a disconnected client before its streams exit, so their Exit never
77 // reaches send; departed clients are pruned when a window opens instead.
78 const clients = new Map<number, Map<string, Window>>();
79 let receive: Parameters<RpcServer.Protocol["Service"]["run"]>[0];
80 const windowFor = (clientId: number, requestId: string) => clients.get(clientId)?.get(requestId);
81 const openWindow = Effect.fnUntraced(function* (
82 clientId: number,
83 requestId: string,
84 bytes: boolean,
85 ) {
86 const connected = yield* protocol.clientIds;
87 for (const id of clients.keys()) if (!connected.has(id)) clients.delete(id);
88 let windows = clients.get(clientId);
89 if (!windows) clients.set(clientId, (windows = new Map()));
90 if (!windows.has(requestId)) windows.set(requestId, { bytes, sizes: [] });
91 });
92 return {
93 ...protocol,
94 run: (write) => {
95 receive = write;
96 return protocol.run((clientId, message) =>
97 Effect.suspend(() => {
98 if (message._tag === "Request") {
99 const bytes = BYTE_WINDOWED_STREAMS.has(message.tag);
100 if (bytes || COUNT_WINDOWED_STREAMS.has(message.tag)) {
101 return openWindow(clientId, String(message.id), bytes).pipe(
102 Effect.andThen(write(clientId, message)),
103 );
104 }
105 } else if (message._tag === "Ack") {
106 const window = windowFor(clientId, String(message.requestId));
107 if (window) {
108 const wasFull = isFull(window.sizes);
109 window.sizes.shift();
110 if (!wasFull || isFull(window.sizes)) return Effect.void;
111 }
112 }
113 return write(clientId, message);
114 }),
115 );
116 },
117 send: (clientId, response, transferables) =>
118 Effect.suspend(() => {
119 const send = protocol.send(clientId, response, transferables);
120 if (response._tag === "Exit") {
121 clients.get(clientId)?.delete(String(response.requestId));
122 } else if (response._tag === "Chunk") {
123 const window = windowFor(clientId, String(response.requestId));
124 if (window) {
125 window.sizes.push(window.bytes ? chunkSize(response.values) : 0);
126 if (!isFull(window.sizes)) {
127 return send.pipe(
128 Effect.andThen(() =>
129 receive(clientId, {
130 _tag: "Ack",
131 requestId: response.requestId,
132 }),
133 ),
134 );
135 }
136 }
137 }
138 return send;
139 }),
140 };
141}
142
143const MAX_QUEUED_OUTPUT = 8 * 1024 * 1024;
144// Output that follows an emission this closely waits and rides along in one batch,
145// so a PTY that delivers one line per callback (ConPTY) is not sent one frame per line.
146const OUTPUT_WINDOW_NANOS = 2_000_000n;
147
148type Listener<A> = (event: A) => Effect.Effect<void>;
149// Acquisition must register cleanup synchronously with installing the listener.
150type Subscribe<A, E> = (
151 listener: Listener<A>,
152 registerCleanup: (stop: () => void) => void,
153) => Effect.Effect<() => void, E>;
154
155export function terminalOutputStream<A extends TerminalEvent | TerminalAttachStreamEvent, E>(
156 subscribe: Subscribe<A, E>,
157 resync?: Subscribe<A, E>,
158 maxQueued = MAX_QUEUED_OUTPUT,
159): Stream.Stream<A, E> {
160 return Stream.unwrap(
161 Effect.gen(function* () {
162 const clock = yield* Clock.Clock;
163 const ready = yield* Latch.make();
164 let pending: Array<A | undefined> = [];
165 let sizes: number[] = [];
166 let head = 0;
167 let queued = 0;
168 // Pending events other than output; any of them flushes the window early.
169 let lifecycle = 0;
170 let deadline = 0n;
171 let overflowed = false;
172 let subscription = 0;
173 let unsubscribe: (() => void) | null = null;
174 const release = () => {
175 subscription += 1;
176 unsubscribe?.();
177 unsubscribe = null;
178 pending = [];
179 sizes = [];
180 head = 0;
181 queued = 0;
182 lifecycle = 0;
183 };
184 const urgent = () => lifecycle > 0 || queued >= MAX_PENDING_BYTES;
185 yield* Effect.addFinalizer(() => Effect.sync(release));
186
187 const listen = (from: Subscribe<A, E>) =>
188 Effect.suspend(() => {
189 const id = ++subscription;
190 return from(
191 (event) =>
192 Effect.sync(() => {
193 if (id !== subscription) return;
194 const wasEmpty = head === pending.length;
195 const size = queuedSize(event);
196 pending.push(event);
197 sizes.push(size);
198 queued += size;
199 if (event.type !== "output") lifecycle += 1;
200 // A single snapshot must fit even when history fills the budget.
201 if (queued - sizes[head]! > maxQueued) {
202 release();
203 overflowed = true;
204 }
205 // The current or next pull handles the pending output deadline.
206 if (wasEmpty || overflowed || urgent()) ready.openUnsafe();
207 }),
208 (stop) => {
209 // Overflow or cancellation may invalidate acquisition before registration.
210 if (id === subscription) unsubscribe = stop;
211 else stop();
212 },
213 ).pipe(
214 Effect.asVoid,
215 Effect.onError(() => Effect.sync(release)),
216 );
217 });
218
219 const take = () => {
220 const event = pending[head]!;
221 pending[head] = undefined;
222 head += 1;
223 if (event.type !== "output") lifecycle -= 1;
224 return event;
225 };
226 const takeBatch = (): Arr.NonEmptyReadonlyArray<A> => {
227 let bytes = sizes[head]!;
228 const batch: [A, ...A[]] = [take()];
229 while (head < pending.length && bytes + sizes[head]! <= MAX_PENDING_BYTES) {
230 bytes += sizes[head]!;
231 batch.push(take());
232 }
233 queued -= bytes;
234 if (head * 2 >= pending.length) {
235 pending = pending.slice(head);
236 sizes = sizes.slice(head);
237 head = 0;
238 }
239 return batch;
240 };
241
242 const pull: Effect.Effect<Arr.NonEmptyReadonlyArray<A>, E | Cause.Done> = Effect.suspend(
243 () => {
244 if (overflowed) {
245 overflowed = false;
246 return resync ? listen(resync).pipe(Effect.andThen(pull)) : Cause.done();
247 }
248 ready.closeUnsafe();
249 if (head === pending.length) return ready.await.pipe(Effect.andThen(pull));
250 const now = clock.monotonicTimeNanosUnsafe();
251 if (now >= deadline || urgent()) {
252 deadline = now + OUTPUT_WINDOW_NANOS;
253 return Effect.succeed(takeBatch());
254 }
255 return Effect.raceFirst(ready.await, Effect.sleep(Duration.nanos(deadline - now))).pipe(
256 Effect.andThen(pull),
257 );
258 },
259 );
260
261 yield* listen(subscribe);
262 return Stream.fromPull(Effect.succeed(pull));
263 }),
264 );
265}