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

OutputProtocol.ts

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