Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Smoothen event source parser by feeding in smaller chunks #151

Merged
merged 4 commits into from
Feb 11, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions packages/proxy/src/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,12 +328,24 @@ export async function proxyV1({
stream = new ReadableStream<Uint8Array>({
start(controller) {
if ("body" in cachedData && cachedData.body) {
controller.enqueue(new TextEncoder().encode(cachedData.body));
for (const line of cachedData.body.split("\n")) {
controller.enqueue(new TextEncoder().encode(line));
}
} else if ("data" in cachedData && cachedData.data) {
const data = Buffer.from(cachedData.data, "base64");
const uint8Array = new Uint8Array(data);
controller.enqueue(uint8Array);
let start = 0;
for (let i = 0; i < data.length; i++) {
if (data[i] === 10) {
// 10 is ASCII/UTF-8 code for \n
controller.enqueue(data.subarray(start, i + 1));
start = i + 1;
}
}
if (start < data.length) {
controller.enqueue(data.subarray(start));
}
}

controller.close();
},
});
Expand Down Expand Up @@ -485,7 +497,6 @@ export async function proxyV1({
cacheKey,
JSON.stringify({ headers: proxyResponseHeaders, data: dataB64 }),
);
controller.terminate();
},
});

Expand Down Expand Up @@ -590,7 +601,11 @@ export async function proxyV1({
});
}
if (isStreaming) {
eventSourceParser?.feed(new TextDecoder().decode(chunk));
const start = Date.now();
let textChunks = new TextDecoder().decode(chunk);
eventSourceParser?.feed(textChunks);
const end = Date.now();
console.log(`time to feed ${chunk.length} bytes: ${end - start}ms`);
} else {
allChunks.push(chunk);
}
Expand Down