fix(perf): prevent memory leak and TextEncoder allocation on hot path

- Add performance.clearMarks/clearMeasures before creating new marks to
  prevent timeline accumulation in long-lived processes.
- Replace new TextEncoder().encode(str).length with Buffer.byteLength to
  avoid allocating a full Uint8Array just to measure byte length.
This commit is contained in:
oyi77
2026-07-14 04:16:21 +07:00
parent b48ba21c42
commit c35e8a9b44
2 changed files with 4 additions and 1 deletions

View File

@@ -72,6 +72,9 @@ export function assembleStreamingPipeline(
},
deps: StreamingPipelineDeps = DEFAULT_DEPS
) {
performance.clearMarks(PIPELINE_START);
performance.clearMarks(PIPELINE_END);
performance.clearMeasures(PIPELINE_MEASURE);
performance.mark(PIPELINE_START);
// ── Phase 9.3: Progress tracking (opt-in) ──
const progressEnabled = deps.wantsProgress(args.clientRawRequestHeaders);

View File

@@ -644,7 +644,7 @@ export function createSSEStream(options: StreamOptions = {}) {
// tools can query performance.getEntriesByType("mark") filtered by name.
let bodySize = 0;
try {
bodySize = body ? new TextEncoder().encode(JSON.stringify(body)).length : 0;
bodySize = body ? Buffer.byteLength(JSON.stringify(body), "utf8") : 0;
} catch {
/* body may not be JSON-serialisable (e.g. FormData, Blob) — metric stays 0 */
}