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

OutputProtocol.ts

185 lines6.1 KB

1import { type TerminalAttachStreamEvent, type TerminalEvent, WS_METHODS } from "@t3tools/contracts";
2import type * as Arr from "effect/Array";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Latch from "effect/Latch";
6import * as Stream from "effect/Stream";
7import type { RpcServer } from "effect/rpc";
8​
9const MAX_PENDING_CHUNKS = 8;
10const MAX_PENDING_BYTES = 64 * 1024;
11const isFull = (sizes: number[]) =>
12 sizes.length >= MAX_PENDING_CHUNKS ||
13 sizes.reduce((total, size) => total + size, 0) >= MAX_PENDING_BYTES;
14​
15export function withTerminalOutputWindow(
16 protocol: RpcServer.Protocol["Service"],
17): RpcServer.Protocol["Service"] {
18 const windows = new Map<string, number[]>();
19 let receive: Parameters<RpcServer.Protocol["Service"]["run"]>[0];
20 return {
21 ...protocol,
22 run: (write) => {
23 receive = write;
24 return protocol.run((clientId, message) =>
25 Effect.suspend(() => {
26 if (
27 message._tag === "Request" &&
28 (message.tag === WS_METHODS.terminalAttach ||
29 message.tag === WS_METHODS.terminalObserve)
30 ) {
31 const key = `${clientId}:${message.id}`;
32 if (!windows.has(key)) windows.set(key, []);
33 } else if (message._tag === "Ack") {
34 const window = windows.get(`${clientId}:${message.requestId}`);
35 if (window) {
36 const wasFull = isFull(window);
37 window.shift();
38 if (!wasFull || isFull(window)) return Effect.void;
39 }
40 }
41 return write(clientId, message);
42 }),
43 );
44 },
45 send: (clientId, response, transferables) =>
46 Effect.suspend(() => {
47 const send = protocol.send(clientId, response, transferables);
48 if (response._tag === "Exit") {
49 windows.delete(`${clientId}:${response.requestId}`);
50 } else if (response._tag === "Chunk") {
51 const window = windows.get(`${clientId}:${response.requestId}`);
52 if (window) {
53 // @effect-diagnostics-next-line preferSchemaOverJson:off
54 const size = Buffer.byteLength(JSON.stringify(response));
55 window.push(size);
56 if (!isFull(window)) {
57 return send.pipe(
58 Effect.andThen(() =>
59 receive(clientId, {
60 _tag: "Ack",
61 requestId: response.requestId,
62 }),
63 ),
64 );
65 }
66 }
67 }
68 return send;
69 }),
70 };
72​
73const MAX_QUEUED_OUTPUT = 8 * 1024 * 1024;
74// Charge an envelope so tiny events cannot bypass the byte budget.
75const EVENT_OVERHEAD = 128;
76​
77type Listener<A> = (event: A) => Effect.Effect<void>;
78// Acquisition must register cleanup synchronously with installing the listener.
79type Subscribe<A, E> = (
80 listener: Listener<A>,
81 registerCleanup: (stop: () => void) => void,
82) => Effect.Effect<() => void, E>;
83​
84const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) =>
85 EVENT_OVERHEAD +
86 (event.type === "output"
87 ? Buffer.byteLength(event.data)
88 : "snapshot" in event
89 ? Buffer.byteLength(event.snapshot.history)
90 : 0);
91​
92export function terminalOutputStream<A extends TerminalEvent | TerminalAttachStreamEvent, E>(
93 subscribe: Subscribe<A, E>,
94 resync?: Subscribe<A, E>,
95 maxQueued = MAX_QUEUED_OUTPUT,
96): Stream.Stream<A, E> {
97 return Stream.unwrap(
98 Effect.gen(function* () {
99 const ready = yield* Latch.make();
100 let pending: Array<A | undefined> = [];
101 let sizes: number[] = [];
102 let head = 0;
103 let queued = 0;
104 let overflowed = false;
105 let subscription = 0;
106 let unsubscribe: (() => void) | null = null;
107 const release = () => {
108 subscription += 1;
109 unsubscribe?.();
110 unsubscribe = null;
111 pending = [];
112 sizes = [];
113 head = 0;
114 queued = 0;
115 };
116 yield* Effect.addFinalizer(() => Effect.sync(release));
117​
118 const listen = (from: Subscribe<A, E>) =>
119 Effect.suspend(() => {
120 const id = ++subscription;
121 return from(
122 (event) =>
123 Effect.sync(() => {
124 if (id !== subscription) return;
125 const size = queuedSize(event);
126 pending.push(event);
127 sizes.push(size);
128 queued += size;
129 // A single snapshot must fit even when history fills the budget.
130 if (queued - sizes[head]! > maxQueued) {
131 release();
132 overflowed = true;
133 }
134 ready.openUnsafe();
135 }),
136 (stop) => {
137 // Overflow or cancellation may invalidate acquisition before registration.
138 if (id === subscription) unsubscribe = stop;
139 else stop();
140 },
141 ).pipe(
142 Effect.asVoid,
143 Effect.onError(() => Effect.sync(release)),
144 );
145 });
146​
147 const take = () => {
148 const event = pending[head]!;
149 pending[head] = undefined;
150 head += 1;
151 return event;
152 };
153 const takeBatch = (): Arr.NonEmptyReadonlyArray<A> => {
154 let bytes = sizes[head]!;
155 const batch: [A, ...A[]] = [take()];
156 while (head < pending.length && bytes + sizes[head]! <= MAX_PENDING_BYTES) {
157 bytes += sizes[head]!;
158 batch.push(take());
159 }
160 queued -= bytes;
161 if (head * 2 >= pending.length) {
162 pending = pending.slice(head);
163 sizes = sizes.slice(head);
164 head = 0;
165 }
166 return batch;
167 };
168​
169 const pull: Effect.Effect<Arr.NonEmptyReadonlyArray<A>, E | Cause.Done> = Effect.suspend(
170 () => {
171 if (overflowed) {
172 overflowed = false;
173 return resync ? listen(resync).pipe(Effect.andThen(pull)) : Cause.done();
174 }
175 if (head < pending.length) return Effect.succeed(takeBatch());
176 ready.closeUnsafe();
177 return ready.await.pipe(Effect.andThen(pull));
178 },
179 );
180​
181 yield* listen(subscribe);
182 return Stream.fromPull(Effect.succeed(pull));
183 }),
184 );