From c5efbffc95646b4f17802b0ebbbddc168e8cbb2d Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:47:13 -0500 Subject: [PATCH] perf(sourcemaps/browser/uefi): event-driven wait, pre-sorted redaction, O(1) queue (#13707) * perf(sourcemaps/browser/uefi): event-driven wait, pre-sorted redaction, O(1) queue * refactor(uefi): share LZMA frame byte queue --- src/browser/BrowserScenarioSecrets.ts | 56 +++++++++-------- src/javascript/sourceMaps/SourceMapCommand.ts | 10 ++- src/uefi/UefiLzmaByteQueue.ts | 61 +++++++++++++++++++ src/uefi/UefiLzmaSession.ts | 26 ++------ src/uefi/UefiLzmaWorker.ts | 28 ++------- 5 files changed, 110 insertions(+), 71 deletions(-) create mode 100644 src/uefi/UefiLzmaByteQueue.ts diff --git a/src/browser/BrowserScenarioSecrets.ts b/src/browser/BrowserScenarioSecrets.ts index b44a465b5a..cfc33072e5 100644 --- a/src/browser/BrowserScenarioSecrets.ts +++ b/src/browser/BrowserScenarioSecrets.ts @@ -348,7 +348,11 @@ export class BrowserScenarioSecrets { "text", this.textPatterns, ); - this.textNeedles = secretNeedles(this.textReplacements); + this.textNeedles = secretNeedles(this.textReplacements).sort( + (left, right) => + right.needle.length - left.needle.length || + (left.id < right.id ? -1 : left.id > right.id ? 1 : 0), + ); this.redactionCostPerCharacter = this.costOf( this.textReplacements, this.urlReplacements, @@ -760,39 +764,37 @@ export class BrowserScenarioSecrets { hasPercentPatterns && value.indexOf(37) >= 0 ? normalizePercentEscapesBytes(value) : value; - const sortedCandidates = candidates - .map((candidate) => ({ - ...candidate, - index: (candidate.percentInsensitive ? normalizedValue : value).indexOf( - candidate.needle, - ), - })) - .sort( - (left, right) => - right.needle.length - left.needle.length || - (left.id < right.id ? -1 : left.id > right.id ? 1 : 0), - ); + const indices = new Int32Array(candidates.length).fill(-2); const parts: Buffer[] = []; let offset = 0; while (true) { - let next: (typeof sortedCandidates)[number] | undefined; - for (const candidate of sortedCandidates) { - if (candidate.index >= 0 && candidate.index < offset) - candidate.index = ( + let nextIndex = -1; + let nextPos = -1; + let nextLen = -1; + for (let i = 0; i < candidates.length; i += 1) { + const candidate = candidates[i]!; + let pos = indices[i]!; + if (pos === -2 || (pos >= 0 && pos < offset)) { + pos = ( candidate.percentInsensitive ? normalizedValue : value ).indexOf(candidate.needle, offset); + indices[i] = pos; + } if ( - candidate.index >= 0 && - (next === undefined || - candidate.index < next.index || - (candidate.index === next.index && - candidate.needle.length > next.needle.length)) - ) - next = candidate; + pos >= 0 && + (nextIndex < 0 || + pos < nextPos || + (pos === nextPos && candidate.needle.length > nextLen)) + ) { + nextIndex = i; + nextPos = pos; + nextLen = candidate.needle.length; + } } - if (next === undefined) break; - parts.push(value.subarray(offset, next.index), next.marker); - offset = next.index + next.needle.length; + if (nextIndex < 0) break; + const next = candidates[nextIndex]!; + parts.push(value.subarray(offset, nextPos), next.marker); + offset = nextPos + nextLen; } if (parts.length === 0) return value; parts.push(value.subarray(offset)); diff --git a/src/javascript/sourceMaps/SourceMapCommand.ts b/src/javascript/sourceMaps/SourceMapCommand.ts index 5900d9a05d..2c1b9d803a 100644 --- a/src/javascript/sourceMaps/SourceMapCommand.ts +++ b/src/javascript/sourceMaps/SourceMapCommand.ts @@ -17,6 +17,7 @@ import { AnalysisOutputError, AnalysisResourceConstraintError, AnalysisTimeoutError, + OwnerCancellation, cancelledBy, carriedReason, } from "../../domain/analysisErrorCore.js"; @@ -262,6 +263,7 @@ class OwnedCodec implements SourceMapCleanupOwner { #cleanupRelease: AnalysisCleanupRelease | undefined; #outcome: CodecOutcome | undefined; #drainStop: CodecPhysicalObservation | undefined; + readonly #wakeController = new AbortController(); readonly #onInterruption: () => void; constructor( readonly path: string, @@ -390,7 +392,11 @@ class OwnedCodec implements SourceMapCleanupOwner { const supervisor = this.#supervisor; if (supervisor === undefined) throw new Error("Codec process was not acquired"); - while (!(await supervisor.waitForOutputClose(50))) { + const wakeSignal = AbortSignal.any([ + this.deadline.signal, + this.#wakeController.signal, + ]); + while (!(await supervisor.waitForOutputClose(undefined, wakeSignal))) { const outcome = this.#outcome; if ( outcome?.kind !== "physical" || @@ -476,6 +482,8 @@ class OwnedCodec implements SourceMapCleanupOwner { this.#outcome = { kind: "physical", observation }; else if (observation.kind !== "exit" && this.#drainStop === undefined) this.#drainStop = observation; + if (observation.kind !== "exit" && !this.#wakeController.signal.aborted) + this.#wakeController.abort(OwnerCancellation.noLongerNeeded); } #physicalFailure(observation: CodecPhysicalObservation): AnalysisError { diff --git a/src/uefi/UefiLzmaByteQueue.ts b/src/uefi/UefiLzmaByteQueue.ts new file mode 100644 index 0000000000..4e6a111ae2 --- /dev/null +++ b/src/uefi/UefiLzmaByteQueue.ts @@ -0,0 +1,61 @@ +import { Buffer } from "node:buffer"; + +export class UefiLzmaByteQueue { + readonly #chunks: (Buffer | undefined)[] = []; + #head = 0; + #available = 0; + + get available(): number { + return this.#available; + } + + append(chunk: Buffer): boolean { + if (chunk.length === 0) return false; + this.#chunks.push(chunk); + this.#available += chunk.length; + return true; + } + + /** Read a positive length after the caller has checked availability. */ + read(length: number): Buffer { + const first = this.#chunks[this.#head]!; + let result: Buffer; + if (first.length === length) { + result = first; + this.#consumeHead(); + } else { + result = this.#copy(length); + } + this.#available -= length; + if (this.#available === 0) { + this.#chunks.length = 0; + this.#head = 0; + } else if (this.#head >= 64 && this.#head * 2 >= this.#chunks.length) { + this.#chunks.splice(0, this.#head); + this.#head = 0; + } + return result; + } + + #copy(length: number): Buffer { + const result = Buffer.allocUnsafe(length); + let copied = 0; + while (copied < length) { + const head = this.#chunks[this.#head]!; + const take = Math.min(head.length, length - copied); + head.copy(result, copied, 0, take); + copied += take; + if (take === head.length) { + this.#consumeHead(); + } else { + this.#chunks[this.#head] = head.subarray(take); + } + } + return result; + } + + #consumeHead(): void { + this.#chunks[this.#head] = undefined; + this.#head += 1; + } +} diff --git a/src/uefi/UefiLzmaSession.ts b/src/uefi/UefiLzmaSession.ts index 7688206aff..138ec80ef9 100644 --- a/src/uefi/UefiLzmaSession.ts +++ b/src/uefi/UefiLzmaSession.ts @@ -38,6 +38,7 @@ import { import type { UefiDecodeFormat } from "./FfsSections.js"; import { uefiFailureDialect } from "./UefiFailures.js"; import type { UefiDecodeResult } from "./UefiImageScan.js"; +import { UefiLzmaByteQueue } from "./UefiLzmaByteQueue.js"; import { encodeLzmaFrame, LZMA_FRAME_HEADER_BYTES, @@ -71,8 +72,7 @@ const throwIfWorkerAborted = ( }; class ActiveWorkerReader { - #chunks: Buffer[] = []; - #buffered = 0; + readonly #queue = new UefiLzmaByteQueue(); #ended = false; #error: Error | undefined; #waiter: (() => void) | undefined; @@ -87,9 +87,7 @@ class ActiveWorkerReader { } readonly #onData = (chunk: Buffer): void => { - if (chunk.length === 0) return; - this.#chunks.push(chunk); - this.#buffered += chunk.length; + if (!this.#queue.append(chunk)) return; this.#wake(); }; @@ -118,7 +116,7 @@ class ActiveWorkerReader { async readExact(length: number, signal: AbortSignal): Promise { if (length === 0) return Buffer.alloc(0); - while (this.#buffered < length) { + while (this.#queue.available < length) { throwIfWorkerAborted(signal, this.supervisor.snapshot()); if (this.#error !== undefined) { throw new OwnedCommandFailure( @@ -156,21 +154,7 @@ class ActiveWorkerReader { }; }); } - const out = Buffer.allocUnsafe(length); - let copied = 0; - while (copied < length) { - const head = this.#chunks[0]!; - const take = Math.min(head.length, length - copied); - head.copy(out, copied, 0, take); - copied += take; - this.#buffered -= take; - if (take === head.length) { - this.#chunks.shift(); - } else { - this.#chunks[0] = head.subarray(take); - } - } - return out; + return this.#queue.read(length); } } diff --git a/src/uefi/UefiLzmaWorker.ts b/src/uefi/UefiLzmaWorker.ts index 6fb719da32..9e01bee05f 100644 --- a/src/uefi/UefiLzmaWorker.ts +++ b/src/uefi/UefiLzmaWorker.ts @@ -15,6 +15,7 @@ import { import { UEFI_FIRMWARE_LIMITS } from "../domain/uefi/uefiLimits.js"; import { errorMessage } from "../kernel/errorMessage.js"; import { sha256Hex } from "../kernel/sha256Hex.js"; +import { UefiLzmaByteQueue } from "./UefiLzmaByteQueue.js"; import { encodeLzmaFrame, LZMA_FRAME_HEADER_BYTES, @@ -217,17 +218,14 @@ const serializeReply = ( }; class FramedByteReader { - #chunks: Buffer[] = []; - #buffered = 0; + readonly #queue = new UefiLzmaByteQueue(); #ended = false; #error: unknown; #waiter: (() => void) | undefined; constructor(stream: Readable) { stream.on("data", (chunk: Buffer) => { - if (chunk.length === 0) return; - this.#chunks.push(chunk); - this.#buffered += chunk.length; + if (!this.#queue.append(chunk)) return; const wake = this.#waiter; this.#waiter = undefined; wake?.(); @@ -251,31 +249,17 @@ class FramedByteReader { allowCleanEof = false, ): Promise { if (length === 0) return Buffer.alloc(0); - while (this.#buffered < length) { + while (this.#queue.available < length) { if (this.#error !== undefined) throw this.#error; if (this.#ended) { - if (allowCleanEof && this.#buffered === 0) return null; + if (allowCleanEof && this.#queue.available === 0) return null; throw new Error("Truncated LZMA worker frame."); } await new Promise((resolve) => { this.#waiter = resolve; }); } - const result = Buffer.allocUnsafe(length); - let copied = 0; - while (copied < length) { - const head = this.#chunks[0]!; - const take = Math.min(head.length, length - copied); - head.copy(result, copied, 0, take); - copied += take; - this.#buffered -= take; - if (take === head.length) { - this.#chunks.shift(); - } else { - this.#chunks[0] = head.subarray(take); - } - } - return result; + return this.#queue.read(length); } }