Open History to see the last commit
1import { WS_METHODS } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import type { RpcServer } from "effect/rpc";
4
5const MAX_PENDING_CHUNKS = 8;
6const MAX_PENDING_BYTES = 64 * 1024;
7const isFull = (sizes: number[]) =>
8 sizes.length >= MAX_PENDING_CHUNKS ||
9 sizes.reduce((total, size) => total + size, 0) >= MAX_PENDING_BYTES;
10
11export function withTerminalOutputWindow(
12 protocol: RpcServer.Protocol["Service"],
13): RpcServer.Protocol["Service"] {
14 const windows = new Map<string, number[]>();
15 let receive: Parameters<RpcServer.Protocol["Service"]["run"]>[0];
16 return {
17 ...protocol,
18 run: (write) => {
19 receive = write;
20 return protocol.run((clientId, message) =>
21 Effect.suspend(() => {
22 if (
23 message._tag === "Request" &&
24 (message.tag === WS_METHODS.terminalAttach ||
25 message.tag === WS_METHODS.subscribeTerminalEvents)
26 ) {
27 const key = `${clientId}:${message.id}`;
28 if (!windows.has(key)) windows.set(key, []);
29 } else if (message._tag === "Ack") {
30 const window = windows.get(`${clientId}:${message.requestId}`);
31 if (window) {
32 const wasFull = isFull(window);
33 window.shift();
34 if (!wasFull || isFull(window)) return Effect.void;
35 }
36 }
37 return write(clientId, message);
38 }),
39 );
40 },
41 send: (clientId, response, transferables) =>
42 Effect.suspend(() => {
43 const send = protocol.send(clientId, response, transferables);
44 if (response._tag === "Exit") {
45 windows.delete(`${clientId}:${response.requestId}`);
46 } else if (response._tag === "Chunk") {
47 const window = windows.get(`${clientId}:${response.requestId}`);
48 if (window) {
49 // @effect-diagnostics-next-line preferSchemaOverJson:off
50 const size = Buffer.byteLength(JSON.stringify(response));
51 window.push(size);
52 if (!isFull(window)) {
53 return send.pipe(
54 Effect.andThen(() =>
55 receive(clientId, {
56 _tag: "Ack",
57 requestId: response.requestId,
58 }),
59 ),
60 );
61 }
62 }
63 }
64 return send;
65 }),
66 };
67}