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

OutputProtocol.test.ts

353 lines14.4 KB

1import { assert, describe, it } from "@effect/vitest";
2import {
3 ORCHESTRATION_V2_WS_METHODS,
4 type TerminalAttachStreamEvent,
5 TerminalAttachStreamEvent as TerminalAttachStreamEventSchema,
6 WS_METHODS,
7} from "@t3tools/contracts";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as Queue from "effect/Queue";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";
16​
17import { terminalOutputStream, withOutputWindow } from "./OutputProtocol.ts";
18​
19describe("terminal output window", () => {
20 it.effect.each([
21 { tag: WS_METHODS.terminalAttach, size: 1, limit: 8 },
22 { tag: WS_METHODS.terminalObserve, size: 1, limit: 8 },
23 { tag: WS_METHODS.terminalAttach, size: 64 * 1024, limit: 1 },
24 { tag: WS_METHODS.terminalObserve, size: 64 * 1024, limit: 1 },
25 { tag: WS_METHODS.subscribeServerConfig, size: 1, limit: 8 },
26 { tag: ORCHESTRATION_V2_WS_METHODS.subscribeShell, size: 1, limit: 8 },
27 { tag: ORCHESTRATION_V2_WS_METHODS.subscribeThread, size: 64 * 1024, limit: 8 },
28 { tag: WS_METHODS.subscribeTerminalMetadata, size: 1, limit: 1 },
29 ])("limits $tag with $size-byte values to $limit pending chunks", ({ tag, size, limit }) =>
30 Effect.gen(function* () {
31 const group = RpcGroup.make(Rpc.make(tag, { success: Schema.String, stream: true }));
32 const output = yield* Queue.unbounded<string>();
33 const responses = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
34 const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();
35 const protocol = yield* RpcServer.Protocol.make((write) =>
36 Effect.gen(function* () {
37 yield* Deferred.succeed(receive, write);
38 const serialization = yield* RpcSerialization.RpcSerialization;
39 return {
40 disconnects: yield* Queue.unbounded<number>(),
41 send: (_clientId, response) => Queue.offer(responses, response),
42 end: () => Effect.void,
43 clientIds: Effect.succeed(new Set([0])),
44 initialMessage: Effect.succeedNone,
45 supportsAck: true,
46 supportsTransferables: false,
47 supportsSpanPropagation: false,
48 supportsNotifications: true,
49 codecFor: serialization.codecFor,
50 };
51 }),
52 );
53 yield* RpcServer.make(group).pipe(
54 Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))),
55 Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol)),
56 Effect.forkScoped,
57 );
58 const write = yield* Deferred.await(receive);
59 yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] });
60​
61 for (let index = 0; index < limit; index++) {
62 const value = String(index).repeat(size);
63 yield* Queue.offer(output, value);
64 yield* TestClock.adjust(0);
65 assert.equal(yield* Queue.size(responses), 1);
66 assert.deepEqual(yield* Queue.take(responses), {
67 _tag: "Chunk",
68 requestId: "1",
69 values: [value],
70 });
71 }
72 yield* Queue.offer(output, "i".repeat(size));
73 yield* TestClock.adjust(0);
74 assert.equal(yield* Queue.size(responses), 0);
75 yield* write(0, { _tag: "Ack", requestId: "1" });
76 const resumed = yield* Queue.take(responses);
77 assert.equal(resumed._tag, "Chunk");
78 if (resumed._tag === "Chunk") assert.deepEqual(resumed.values, ["i".repeat(size)]);
79​
80 yield* Queue.offer(output, "j");
81 yield* TestClock.adjust(0);
82 assert.equal(yield* Queue.size(responses), 0);
83 yield* write(0, { _tag: "Interrupt", requestId: "1" });
84 assert.equal((yield* Queue.take(responses))._tag, "Exit");
85 }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
86 );
87});
88​
89const output = (data: string): TerminalAttachStreamEvent => ({
90 type: "output",
91 threadId: "thread-1",
92 terminalId: "default",
93 data,
94});
95​
96const snapshot = (history: string): TerminalAttachStreamEvent => ({
97 type: "snapshot",
98 snapshot: {
99 threadId: "thread-1",
100 terminalId: "default",
101 cwd: "/repo",
102 worktreePath: null,
103 status: "running",
104 pid: 1,
105 history,
106 exitCode: null,
107 exitSignal: null,
108 label: "bash",
109 updatedAt: "2026-01-01T00:00:00.000Z",
110 },
111});
112​
113// Stands in for TerminalManager's fanout: listeners run in publish order and
114// may release themselves while it iterates.
115const makePublisher = () => {
116 const listeners = new Set<(event: TerminalAttachStreamEvent) => Effect.Effect<void>>();
117 return {
118 listeners,
119 subscribe: (
120 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
121 registerCleanup?: (stop: () => void) => void,
122 ) =>
123 Effect.sync(() => {
124 listeners.add(listener);
125 const stop = () => {
126 listeners.delete(listener);
127 };
128 registerCleanup?.(stop);
129 return stop;
130 }),
131 publish: (event: TerminalAttachStreamEvent) =>
132 Effect.forEach(listeners, (listener) => listener(event), { discard: true }),
133 };
134};
135​
136// Like TerminalManager.attachStream: a snapshot, then live events.
137const attach =
138 (publisher: ReturnType<typeof makePublisher>, history: string) =>
139 (
140 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
141 registerCleanup: (stop: () => void) => void,
142 ) =>
143 publisher
144 .subscribe(listener, registerCleanup)
145 .pipe(Effect.tap(() => listener(snapshot(history))));
146​
147const chunkBytes = (message: RpcMessage.FromServerEncoded) =>
148 Buffer.byteLength(JSON.stringify(message));
149​
150describe("terminal output stream", () => {
151 it.effect.each([WS_METHODS.terminalAttach, WS_METHODS.terminalObserve])(
152 "releases only the ACK-stalled subscriber on %s and resumes safely",
153 (tag) =>
154 Effect.gen(function* () {
155 const group = RpcGroup.make(
156 Rpc.make(tag, {
157 success: TerminalAttachStreamEventSchema,
158 stream: true,
159 }),
160 );
161 const publisher = makePublisher();
162 const stalled = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
163 const healthy = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
164 const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();
165 const protocol = yield* RpcServer.Protocol.make((write) =>
166 Effect.gen(function* () {
167 yield* Deferred.succeed(receive, write);
168 const serialization = yield* RpcSerialization.RpcSerialization;
169 return {
170 disconnects: yield* Queue.unbounded<number>(),
171 send: (clientId, response) =>
172 Queue.offer(clientId === 0 ? stalled : healthy, response),
173 end: () => Effect.void,
174 clientIds: Effect.succeed(new Set([0, 1])),
175 initialMessage: Effect.succeedNone,
176 supportsAck: true,
177 supportsTransferables: false,
178 supportsSpanPropagation: false,
179 supportsNotifications: true,
180 codecFor: serialization.codecFor,
181 };
182 }),
183 );
184 const initial = snapshot("");
185 yield* RpcServer.make(group).pipe(
186 Effect.provide(
187 group.toLayerHandler(tag, () =>
188 terminalOutputStream(
189 (listener, registerCleanup) =>
190 publisher
191 .subscribe(listener, registerCleanup)
192 .pipe(Effect.tap(() => listener(initial))),
193 attach(publisher, "fresh history"),
194 256 * 1024,
195 ),
196 ),
197 ),
198 Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol)),
199 Effect.forkScoped,
200 );
201 const write = yield* Deferred.await(receive);
202 const takeChunk = Effect.fnUntraced(function* (queue: typeof stalled) {
203 const response = yield* Queue.take(queue);
204 assert.equal(response._tag, "Chunk");
205 if (response._tag !== "Chunk") throw new Error("Expected an RPC chunk");
206 assert.isAtMost(chunkBytes(response), 70 * 1024);
207 return response.values;
208 });
209 yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] });
210 assert.deepEqual(yield* takeChunk(stalled), [initial]);
211 yield* write(1, { _tag: "Request", id: "2", tag, payload: null, headers: [] });
212 assert.deepEqual(yield* takeChunk(healthy), [initial]);
213 yield* write(1, { _tag: "Ack", requestId: "2" });
214​
215 // Eight unacknowledged chunks fill only client 0's output window.
216 for (let index = 0; index < 7; index++) {
217 const event = output("before-stall-" + index);
218 yield* publisher.publish(event);
219 assert.deepEqual(yield* takeChunk(stalled), [event]);
220 assert.deepEqual(yield* takeChunk(healthy), [event]);
221 yield* write(1, { _tag: "Ack", requestId: "2" });
222 }
223 assert.equal(publisher.listeners.size, 2);
224 for (let index = 0; index < 100; index++) {
225 const event = output(index + ":" + "界".repeat(1365));
226 yield* publisher.publish(event);
227 assert.deepEqual(yield* takeChunk(healthy), [event]);
228 yield* write(1, { _tag: "Ack", requestId: "2" });
229 if (index === 31) assert.equal(publisher.listeners.size, 2);
230 }
231 assert.equal(yield* Queue.size(stalled), 0);
232 assert.equal(publisher.listeners.size, 1);
233​
234 yield* write(0, { _tag: "Ack", requestId: "1" });
235 assert.deepEqual(yield* takeChunk(stalled), [snapshot("fresh history")]);
236 assert.equal(publisher.listeners.size, 2);
237 for (let index = 0; index < 7; index++) {
238 yield* write(0, { _tag: "Ack", requestId: "1" });
239 }
240 const after = output("unique output after recovery");
241 yield* publisher.publish(after);
242 assert.deepEqual(yield* takeChunk(healthy), [after]);
243 assert.deepEqual(yield* takeChunk(stalled), [after]);
244 assert.equal(yield* Queue.size(stalled), 0);
245 }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
246 );
247​
248 it.effect("interrupts recovery while its subscription is still waiting", () =>
249 Effect.gen(function* () {
250 const publisher = makePublisher();
251 const recovering = yield* Deferred.make<void>();
252 const interrupted = yield* Deferred.make<void>();
253 const pull = yield* Stream.toPull(
254 terminalOutputStream(
255 attach(publisher, ""),
256 () =>
257 Deferred.succeed(recovering, undefined).pipe(
258 Effect.andThen(Effect.never),
259 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
260 ),
261 1024,
262 ),
263 );
264 yield* pull;
265 yield* publisher.publish(output("x".repeat(1024)));
266 yield* publisher.publish(output("x".repeat(1024)));
267 assert.equal(publisher.listeners.size, 0);
268​
269 const recovery = yield* pull.pipe(Effect.forkChild({ startImmediately: true }));
270 yield* Deferred.await(recovering);
271 yield* Fiber.interrupt(recovery);
272 yield* Deferred.await(interrupted);
273 assert.equal(publisher.listeners.size, 0);
274 }).pipe(Effect.scoped),
275 );
276​
277 it.effect("cleans listeners when cancelled during a successful acquisition handoff", () =>
278 Effect.gen(function* () {
279 const publisher = makePublisher();
280 for (const recovering of [false, true, false, true]) {
281 const handoff = yield* Deferred.make<void>();
282 const complete = yield* Deferred.make<void>();
283 const acquire: ReturnType<typeof attach> = (listener, registerCleanup) =>
284 attach(publisher, "")(listener, registerCleanup).pipe(
285 // Hold the successful exit before its cleanup handle reaches the caller.
286 Effect.onExit(() =>
287 Deferred.succeed(handoff, undefined).pipe(Effect.andThen(Deferred.await(complete))),
288 ),
289 );
290 const consumer = yield* Effect.gen(function* () {
291 const pull = yield* Stream.toPull(
292 terminalOutputStream(recovering ? attach(publisher, "") : acquire, acquire, 1024),
293 );
294 yield* pull;
295 yield* publisher.publish(output("x".repeat(1024)));
296 yield* publisher.publish(output("x".repeat(1024)));
297 yield* pull;
298 }).pipe(Effect.scoped, Effect.forkChild({ startImmediately: true }));
299 yield* Deferred.await(handoff);
300 assert.equal(publisher.listeners.size, 1);
301 const cancellation = yield* Fiber.interrupt(consumer).pipe(
302 Effect.forkChild({ startImmediately: true }),
303 );
304 yield* Deferred.succeed(complete, undefined);
305 yield* Fiber.join(cancellation);
306 assert.equal(publisher.listeners.size, 0);
307 }
308 }).pipe(Effect.scoped),
309 );
310​
311 it.effect("caps each delivered batch at the output window in UTF-8 bytes", () =>
312 Effect.gen(function* () {
313 const publisher = makePublisher();
314 const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, "")));
315 assert.deepEqual(yield* pull, [snapshot("")]);
316 // 1,024 code units but 3 KiB of UTF-8.
317 const data = "界".repeat(1024);
318 for (let index = 0; index < 1024; index++) yield* publisher.publish(output(data));
319​
320 let delivered = 0;
321 while (delivered < 1024) {
322 const batch = yield* pull;
323 assert.isAtMost(
324 batch.reduce(
325 (bytes, event) => bytes + (event.type === "output" ? Buffer.byteLength(event.data) : 0),
326 0,
327 ),
328 64 * 1024,
329 );
330 delivered += batch.length;
331 }
332 assert.equal(delivered, 1024);
333 }).pipe(Effect.scoped),
334 );
335​
336 it.effect("charges snapshot history but never overflows on one snapshot", () =>
337 Effect.gen(function* () {
338 const publisher = makePublisher();
339 const history = "界".repeat(16 * 1024);
340 const events = terminalOutputStream(attach(publisher, history), undefined, 32 * 1024);
341 const pull = yield* Stream.toPull(events);
342 // A snapshot larger than the budget is still delivered.
343 assert.deepEqual(yield* pull, [snapshot(history)]);
344 assert.equal(publisher.listeners.size, 1);
345​
346 // Queued snapshots count their history: a second one overflows.
347 yield* publisher.publish(snapshot(history));
348 assert.equal(publisher.listeners.size, 1);
349 yield* publisher.publish(snapshot(history));
350 assert.equal(publisher.listeners.size, 0);
351 }).pipe(Effect.scoped),
352 );
353});