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

collectUint8StreamText.ts

70 lines2.0 KB

1import * as Effect from "effect/Effect";
2import * as Stream from "effect/Stream";
3​
4export interface CollectedUint8StreamText {
5 readonly text: string;
6 readonly truncated: boolean;
7 readonly bytes: number;
8}
9​
10interface CollectState {
11 chunks: Uint8Array[];
12 readonly bytes: number;
13 readonly truncated: boolean;
15​
16export const collectUint8StreamText = <E>(input: {
17 readonly stream: Stream.Stream<Uint8Array, E>;
18 readonly maxBytes?: number | undefined;
19 readonly truncatedMarker?: string | null | undefined;
20}): Effect.Effect<CollectedUint8StreamText, E> => {
21 const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;
22 const truncatedMarker = input.truncatedMarker ?? "";
23​
24 return input.stream.pipe(
25 Stream.runFold(
26 (): CollectState => ({
27 chunks: [],
28 bytes: 0,
29 truncated: false,
30 }),
31 (state, chunk): CollectState => {
32 /*
33 * keep draining after truncation so the child process can exit normally.
34 * its a know issue that on windows killing after the output cap can force an expensive taskkill operation and hurt performance
35 */
36 if (state.truncated) {
37 return state;
38 }
39​
40 const remainingBytes = maxBytes - state.bytes;
41 if (remainingBytes <= 0) {
42 return {
43 ...state,
44 truncated: true,
45 };
46 }
47​
48 const nextChunk =
49 chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
50 state.chunks.push(nextChunk);
51 const bytes = state.bytes + nextChunk.byteLength;
52 const truncated = chunk.byteLength > remainingBytes;
53​
54 return {
55 chunks: state.chunks,
56 bytes,
57 truncated,
58 };
59 },
60 ),
61 Effect.map((state): CollectedUint8StreamText => {
62 const text = Buffer.concat(state.chunks, state.bytes).toString("utf8");
63 return {
64 text: state.truncated && truncatedMarker.length > 0 ? `${text}${truncatedMarker}` : text,
65 bytes: state.bytes,
66 truncated: state.truncated,
67 };
68 }),
69 );
70};