refactor(evidence): keep the first serialized page with its cursor (#16709)

This commit is contained in:
Vincent Koc authored and GitHub committed 2026-12-04 19:47:32 +08:00
1 parent c51ab81d88
commit 7caaf69643
1 file changed
+12 -26
+12 -26
View File
@@ -110,12 +110,20 @@ class EvidenceJsonWindow {
constructor(
evidence: Evidence,
readonly totalLength: number,
private readonly initial: {
readonly from: number;
readonly to: number;
readonly document: SerializedEvidenceJson;
},
) {
this.#parts = jsonParts(evidence);
}
read(evidence: Evidence, from: number, to: number): SerializedEvidenceJson {
// A page resized to its delivery budget can reuse the first scan.
const initial = this.initial;
if (from >= initial.from && to <= initial.to) return initial.document;
const { totalLength } = initial.document;
if (from < this.#from) {
this.#parts = jsonParts(evidence);
this.#position = 0;
@@ -133,7 +141,7 @@ class EvidenceJsonWindow {
starts.push(start);
}
}
while (this.#position < Math.min(to, this.totalLength)) {
while (this.#position < Math.min(to, totalLength)) {
const part = this.#parts.next();
if (part.done) break;
const start = this.#position;
@@ -145,7 +153,7 @@ class EvidenceJsonWindow {
}
this.#chunks = chunks;
this.#starts = starts;
return { chunks, starts, totalLength: this.totalLength };
return { chunks, starts, totalLength };
}
}
@@ -205,17 +213,6 @@ export class EvidenceJsonSerializationCache {
}
const from = Math.max(0, offset - WINDOW_MARGIN_CODE_UNITS);
const to = offset + window + WINDOW_MARGIN_CODE_UNITS;
// A page sized to its budget is projected again with a smaller window;
// the last window of a record too large to cache serves it without
// another full scan.
const last = this.#lastWindow;
if (
cacheable &&
last?.record.deref() === evidence &&
from >= last.from &&
to <= last.to
)
return last.document;
const activeWindow = this.#windows.get(evidence);
if (activeWindow !== undefined)
return activeWindow.read(evidence, from, to);
@@ -235,24 +232,13 @@ export class EvidenceJsonSerializationCache {
if (previous !== undefined) this.#windows.delete(previous);
this.#windows.set(
evidence,
new EvidenceJsonWindow(evidence, document.totalLength),
new EvidenceJsonWindow(evidence, { from, to, document }),
);
this.#windowOwner = new WeakRef(evidence);
this.#lastWindow = { record: new WeakRef(evidence), from, to, document };
}
return document;
}
/** The window last scanned from an immutable record too large to cache. */
#lastWindow:
| {
readonly record: WeakRef<object>;
readonly from: number;
readonly to: number;
readonly document: SerializedEvidenceJson;
}
| undefined;
#remember(record: object, document: SerializedEvidenceJson): void {
const charged = this.#budget.chargeEvicting(document.totalLength, () => {
const oldest = this.#order.values().next().value;