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

OutputProtocol.ts

68 lines2.4 KB

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.terminalObserve ||
26 message.tag === WS_METHODS.subscribeTerminalEvents)
27 ) {
28 const key = `${clientId}:${message.id}`;
29 if (!windows.has(key)) windows.set(key, []);
30 } else if (message._tag === "Ack") {
31 const window = windows.get(`${clientId}:${message.requestId}`);
32 if (window) {
33 const wasFull = isFull(window);
34 window.shift();
35 if (!wasFull || isFull(window)) return Effect.void;
36 }
37 }
38 return write(clientId, message);
39 }),
40 );
41 },
42 send: (clientId, response, transferables) =>
43 Effect.suspend(() => {
44 const send = protocol.send(clientId, response, transferables);
45 if (response._tag === "Exit") {
46 windows.delete(`${clientId}:${response.requestId}`);
47 } else if (response._tag === "Chunk") {
48 const window = windows.get(`${clientId}:${response.requestId}`);
49 if (window) {
50 // @effect-diagnostics-next-line preferSchemaOverJson:off
51 const size = Buffer.byteLength(JSON.stringify(response));
52 window.push(size);
53 if (!isFull(window)) {
54 return send.pipe(
55 Effect.andThen(() =>
56 receive(clientId, {
57 _tag: "Ack",
58 requestId: response.requestId,
59 }),
60 ),
61 );
62 }
63 }
64 }
65 return send;
66 }),
67 };