fix: stream large project texts and scope API capabilities

Analyze UTF-8 text files as bounded batches of complete lines and reassemble only approved spans without loading entire files. Preserve line endings, BOM, Unicode offsets and source-change checks.

Scope capability checks to selected file types, report missing features and HTTP failures, and retain the required Office image-policy handling. Cover large files, chunk boundaries, mappings and failure cleanup with regression tests.
This commit is contained in:
muena
2026-11-08 10:43:40 +01:00
parent d76e6f3375
commit 11ddd6d70f
13 changed files with 802 additions and 117 deletions

View File

@@ -0,0 +1,83 @@
import { expect, it } from "bun:test";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import ts from "typescript";
import * as imagePolicy from "../src/lib/image-policy";
import * as projectCapabilities from "../src/lib/project-capabilities";
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "../src/lib/image-policy";
const policies = ["placeholder", "remove", "keep"] as const;
function response(policy = "placeholder", changes: Record<string, unknown> = {}) {
return { image_policy: policy, images_replaced: 2, images_removed: 0,
media_parts_removed: 3, warnings: [], file_base64: "UFIDBA==", mapping: {}, hits: [], ...changes };
}
it("verwendet Platzhalter als sicheren Standard und lehnt unbekannte Optionen ab", () => {
expect(DEFAULT_IMAGE_POLICY).toBe("placeholder");
for (const policy of policies) expect(checkedImagePolicy(policy)).toBe(policy);
expect(() => checkedImagePolicy("unknown")).toThrow();
});
it("verarbeitet Dokumente alter Stände und bei geänderter Bildoption erneut", () => {
for (const selected of policies) {
expect(sameImagePolicyCoverage(undefined, selected)).toBe(false);
expect(sameImagePolicyCoverage({}, selected)).toBe(false);
for (const saved of policies) expect(sameImagePolicyCoverage({ imagePolicy: saved }, selected)).toBe(saved === selected);
}
});
it("blockiert fehlende Bestätigung, ungültige Zähler und Warnungen", () => {
for (const changes of [{ image_policy: undefined }, { image_policy: "keep" },
{ images_removed: -1 }, { images_replaced: undefined }, { warnings: undefined }]) {
expect(() => checkedImageReport(response("placeholder", changes), "placeholder")).toThrow();
}
});
it("speichert nur Bildzähler und Warnungen im Dateibericht", () => {
const checked = checkedImageReport(response(), "placeholder");
expect(Object.keys(checked).sort()).toEqual(["image_policy", "images_replaced", "images_removed", "media_parts_removed", "warnings"].sort());
expect("mapping" in checked).toBe(false);
expect("file_base64" in checked).toBe(false);
});
it("zeigt auch mit sonstigen Backend-Hinweisen bei keep eine Datenschutzwarnung", () => {
const report = checkedImageReport(response("keep", { warnings: ["Anderer Hinweis"] }), "keep");
expect(report.warnings).toEqual([KEEP_IMAGE_WARNING, "Anderer Hinweis"]);
expect(summarizeImages([{ imageReport: report }, { imageReport: report }])).toEqual({
replaced: 4, removed: 0, warnings: [KEEP_IMAGE_WARNING, "Anderer Hinweis"],
});
});
it("übermittelt dieselbe Bildoption in Vorschau, Anwendung und erneutem Abgleich", async () => {
const require = createRequire(import.meta.url);
const code = ts.transpileModule(readFileSync(new URL("../src/velum.ts", import.meta.url), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2023 },
}).outputText;
const calls: FormData[] = [];
let returnedPolicy = "placeholder";
let supportsImages = true;
const mocks: Record<string, unknown> = {
"./auth": { fetchWithAuth: async (url: string, init: RequestInit = {}) => {
if (url.endsWith("capabilities")) return Response.json({ request_force_masks: true,
document_hit_review: true, document_review_mapping: true, document_restoration: true,
comment_author_review: true, revision_author_review: true, document_image_policy: supportsImages });
calls.push(init.body as FormData);
return Response.json(response(returnedPolicy));
} },
"./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) },
"./lib/image-policy": imagePolicy,
"./lib/project-capabilities": projectCapabilities,
};
const module = { exports: {} as { pseudonymizeDocument: (...args: unknown[]) => Promise<unknown>; requireProjectCapabilities: (images?: boolean) => Promise<void> } };
new Function("require", "module", "exports", code)((id: string) => mocks[id] ?? require(id), module, module.exports);
const api = module.exports;
for (const policy of policies) {
returnedPolicy = policy;
for (const accepted of [undefined, ["hit-1"], undefined, ["new-hit-1"]]) {
await api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {}, accepted, ["PERSON"], {}, policy);
expect(calls.at(-1)!.get("image_policy")).toBe(policy);
}
}
returnedPolicy = "placeholder";
await api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {});
expect(calls.at(-1)!.get("image_policy")).toBe("placeholder");
returnedPolicy = "keep";
await expect(api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {})).rejects.toThrow("bestätigt");
supportsImages = false;
await expect(api.requireProjectCapabilities(true)).rejects.toThrow();
await api.requireProjectCapabilities(false);
});

View File

@@ -140,3 +140,23 @@ it("verweigert das stumme Zerschneiden eines überlangen Worts", () => {
"ohne Trennstelle",
);
});
it("zerlegt HTTP 413 ohne bestehende Zuordnungen oder Dateigrenzen zu verlieren", async () => {
const [batch] = makeTextBatches([{ key: "a", text: "Anna" }, { key: "b", text: "Berta" }]);
let calls = 0;
const result = await analyzeProjectBatch(batch, {}, ["PERSON"], {}, async (text, mapping) => {
calls++; if (text.includes("Anna") && text.includes("Berta")) throw new Error("Velum API request failed: 413 Payload Too Large");
return response(text, mapping);
}, "Test");
expect(calls).toBe(3); expect(Object.keys(result.mapping)).toHaveLength(2);
});
it("wiederholt Authentifizierungs- und Validierungsfehler nicht", async () => {
const [batch] = makeTextBatches([{ key: "a", text: "Anna" }, { key: "b", text: "Berta" }]);
for (const status of [401, 403, 422]) {
let calls = 0;
await expect(analyzeProjectBatch(batch, {}, ["PERSON"], {}, async () => {
calls++; throw new Error(`Velum API request failed: ${status}`);
}, "Test")).rejects.toThrow(String(status));
expect(calls).toBe(1);
}
});

View File

@@ -0,0 +1,42 @@
import { expect, it } from "bun:test";
import { checkProjectCapabilities, requiredProjectCapabilities } from "../src/lib/project-capabilities";
const url = "https://velum.invalid/api/project-capabilities";
const reply = (value: unknown) => async () => Response.json(value);
it("reproduziert die alte Meldung: Textprojekt benötigt keine Office-Fähigkeiten", async () => {
const olderBackend = { request_force_masks: true, document_hit_review: true, document_restoration: true };
await checkProjectCapabilities(url, false, reply(olderBackend));
await expect(checkProjectCapabilities(url, true, reply(olderBackend))).rejects.toThrow("document_review_mapping");
});
it("prüft jede Office-Schutzfunktion strikt, einschließlich Bilder und Autoren", async () => {
const complete = Object.fromEntries(requiredProjectCapabilities(true).map((key) => [key, true]));
await checkProjectCapabilities(url, true, reply(complete));
for (const key of Object.keys(complete)) {
const missing = { ...complete }; delete missing[key];
await expect(checkProjectCapabilities(url, true, reply(missing))).rejects.toThrow(key);
await expect(checkProjectCapabilities(url, true, reply({ ...complete, [key]: "true" }))).rejects.toThrow(key);
}
});
it("unterscheidet fehlende Endpunkte, Anmeldung, Größenlimits und Gateway-Fehler", async () => {
for (const status of [401, 403, 404, 405, 413, 502, 504]) {
await expect(checkProjectCapabilities(url, false, async () => new Response("", { status })))
.rejects.toThrow(`HTTP ${status}`);
}
await expect(checkProjectCapabilities(url, false, async () => new Response("Login", {
headers: { "content-type": "text/html" },
}))).rejects.toThrow("Keine JSON-Antwort");
});
it("meldet URL, fehlende Fähigkeit, ungültige Antwort und Zeitlimit", async () => {
await expect(checkProjectCapabilities(url, false, reply({}))).rejects.toThrow("request_force_masks");
for (const value of [null, [], true]) await expect(checkProjectCapabilities(url, false, reply(value)))
.rejects.toThrow("Ungültige Projektfähigkeiten");
await expect(checkProjectCapabilities(url, false, async (_url, init) => {
expect(init.signal).toBeDefined(); throw new DOMException("Deadline", "TimeoutError");
})).rejects.toThrow("Zeitlimit");
});
it("reproduziert die Live-API vom 8. November ohne document_image_policy", async () => {
const live = { request_force_masks: true, document_hit_review: true, document_review_mapping: true,
document_restoration: true, comment_author_review: true, revision_author_review: true };
await checkProjectCapabilities(url, false, reply(live));
await expect(checkProjectCapabilities(url, true, reply(live))).rejects.toThrow("document_image_policy");
});

View File

@@ -0,0 +1,124 @@
import { afterEach, expect, it } from "bun:test";
import { promises as fs } from "node:fs";
import { createHash } from "node:crypto";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { analyzeProjectTextFiles } from "../src/lib/project-analysis";
import { decodedText, fileTextParts, hashProjectFile, inspectTextFile, textLines, writeReplacedTextFile } from "../src/lib/project-text-stream";
import type { PlaceholderMapping } from "../src/types";
const roots: string[] = [];
afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
async function fixture() { const root = await fs.mkdtemp(join(tmpdir(), "velum-stream-")); roots.push(root); return root; }
it("trennt vollständige Zeilen und bewahrt CRLF, CR, LF und die letzte Zeile", async () => {
async function* chunks() { yield "eins\r"; yield "\nzwei\rdr"; yield "ei\n😀Ende"; }
const lines = [];
for await (const line of textLines(chunks())) lines.push(line);
expect(lines).toEqual(["eins\r\n", "zwei\r", "drei\n", "😀Ende"]);
});
it("erhält auch bei byteweisen Lesevorgängen BOM, Umlaute und Emoji", async () => {
const root = await fixture(); const source = join(root, "unicode.txt");
await fs.writeFile(source, "\uFEFFÄ😀\r\nEnde");
let text = "";
for await (const part of decodedText(source, undefined, 1)) text += part;
expect(text).toBe("\uFEFFÄ😀\r\nEnde");
});
it("schneidet weder eine Zeile noch ein Wort an der Paketgrenze durch", async () => {
const root = await fixture(); const source = join(root, "lines.txt");
const text = "\uFEFF" + "Lange Füllzeile mit 😀.\r\n".repeat(800) + "Max Mustermann\r\nletzte Zeile";
await fs.writeFile(source, text);
let rebuilt = ""; let count = 0;
for await (const part of fileTextParts(source)) {
const core = text.slice(part.coreStart, part.coreEnd);
expect(part.text.slice(part.coreStart - part.scanStart, part.coreEnd - part.scanStart)).toBe(core);
if (part.coreEnd < text.length) expect(core.endsWith("\n")).toBe(true);
expect(part.text.length).toBeLessThan(24_000);
rebuilt += core; count++;
}
expect(count).toBeGreaterThan(1); expect(rebuilt).toBe(text);
});
it("analysiert mehr als 20 MiB und fügt nur bestätigte Treffer verlustfrei zur Datei zusammen", async () => {
const root = await fixture(); const source = join(root, "large.txt"); const target = join(root, "masked.txt");
const first = "\uFEFF😀 Max Mustermann\r\n"; const last = "Anna Berger ohne abschließenden Umbruch";
const filler = "Text ohne Treffer.\r\n".repeat(26_214);
const expected = createHash("sha256").update("\uFEFF😀 PERSON_01\r\n");
const handle = await fs.open(source, "w");
await handle.writeFile(first);
for (let i = 0; i < 64; i++) { await handle.writeFile(filler); expected.update(filler); }
await handle.writeFile(last); expected.update(last); await handle.close();
expect((await fs.stat(source)).size).toBeGreaterThan(20 * 1024 * 1024);
const hash = await inspectTextFile(source);
let requests = 0, active = 0, maxActive = 0;
const result = await analyzeProjectTextFiles([{ key: "large.txt", path: source }], {}, ["PERSON"], {}, async (text, previous) => {
requests++; active++; maxActive = Math.max(maxActive, active);
expect(text.length).toBeLessThanOrEqual(24_000);
await Promise.resolve();
const mapping: PlaceholderMapping = { ...previous };
const spans = [...text.matchAll(/Max Mustermann|Anna Berger/g)].map((match) => {
const placeholder = match[0] === "Max Mustermann" ? "PERSON_01" : "PERSON_02";
mapping[placeholder] = { original: match[0], type: "PERSON" };
const start = [...text.slice(0, match.index)].length;
return { start, end: start + match[0].length, original: match[0], placeholder, type: "PERSON", score: 1 };
});
active--;
return { pseudonymized_text: text, mapping, spans, entity_count: Object.keys(mapping).length, selected_entity_types: ["PERSON"] };
}, () => undefined);
const spans = result.spansByFile.get("large.txt")!.map((span, i) => ({ ...span, id: String(i) }));
expect(spans.map((span) => span.original)).toEqual(["Max Mustermann", "Anna Berger"]);
expect(spans[0].start).toBe(first.indexOf("Max"));
expect(spans[1].start).toBe(first.length + 64 * filler.length);
expect(Object.keys(result.mapping)).toEqual(["PERSON_01", "PERSON_02"]);
const outputHash = await writeReplacedTextFile(source, target, spans, new Set(["0"]), hash);
expect(outputHash).toBe(expected.digest("hex"));
expect(await hashProjectFile(target)).toBe(outputHash);
expect(await hashProjectFile(source)).toBe(hash);
expect(requests).toBeGreaterThan(1000); expect(maxActive).toBe(1);
}, 30_000);
it("ersetzt einen Treffer über einer Lesegrenze und erhält unveränderte Bytes", async () => {
const root = await fixture(); const source = join(root, "cross.txt"); const target = join(root, "out.txt");
const text = "x".repeat(65_531) + "Max Mustermann 😀\r\nEnde";
await fs.writeFile(source, text);
await writeReplacedTextFile(source, target, [{ id: "hit", start: 65_531, end: 65_545, placeholder: "PERSON_01" }], new Set(["hit"]), await hashProjectFile(source));
expect(await fs.readFile(target, "utf8")).toBe("x".repeat(65_531) + "PERSON_01 😀\r\nEnde");
});
it("hält Zuordnungen und Offsets über viele Dateien hinweg getrennt", async () => {
const root = await fixture(); const files = [];
for (let i = 0; i < 100; i++) { const path = join(root, `${i}.txt`); await fs.writeFile(path, "😀 Anna\r\n"); files.push({ key: String(i), path }); }
let requests = 0;
const result = await analyzeProjectTextFiles(files, {}, ["PERSON"], {}, async (text, mapping) => {
requests++;
return { pseudonymized_text: text, mapping: { ...mapping, PERSON_01: { original: "Anna", type: "PERSON" } }, selected_entity_types: ["PERSON"], entity_count: 1,
spans: [...text.matchAll(/Anna/g)].map((match) => ({ start: [...text.slice(0, match.index)].length, end: [...text.slice(0, match.index)].length + 4, original: "Anna", type: "PERSON", score: 1, placeholder: "PERSON_01" })) };
}, () => undefined);
expect(requests).toBe(1); expect(result.spansByFile.size).toBe(100);
for (const spans of result.spansByFile.values()) { expect(spans).toHaveLength(1); expect(spans[0].start).toBe(3); }
});
it("bricht überlange Zeilen ab und entfernt bei Quelländerungen die unvollständige Ausgabe", async () => {
const root = await fixture(); const source = join(root, "long.txt"); const target = join(root, "partial.txt");
await fs.writeFile(source, "x".repeat(20_001));
await expect(analyzeProjectTextFiles([{ key: "long.txt", path: source }], {}, [], {}, async () => { throw Error("should not call"); }, () => undefined)).rejects.toThrow("Zeile 1");
await expect(writeReplacedTextFile(source, target, [], new Set(), "old-hash")).rejects.toThrow("geändert");
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
expect((await fs.stat(source)).size).toBe(20_001);
});
it("verwirft Binärdaten und unvollständiges UTF-8 ohne fertige Ausgabedatei", async () => {
const root = await fixture();
for (const data of [Buffer.from([65, 0, 66]), Buffer.from([65, 0xc3])]) {
const source = join(root, "invalid.txt"); const target = join(root, "partial.txt"); await fs.writeFile(source, data);
await expect(inspectTextFile(source)).rejects.toThrow();
await expect(writeReplacedTextFile(source, target, [], new Set(), await hashProjectFile(source))).rejects.toThrow();
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
}
});
it("erkennt einen Namen auch über zwei Zeilen und eine Paketgrenze hinweg genau einmal", async () => {
const root = await fixture(); const path = join(root, "boundary.txt");
const prefix = "x\n".repeat(4997);
await fs.writeFile(path, prefix + "Max\r\nMustermann\r\nEnde");
const result = await analyzeProjectTextFiles([{ key: "boundary.txt", path }], {}, ["PERSON"], {}, async (text, mapping) => {
const spans = [...text.matchAll(/Max\r\nMustermann/g)].map((match) => ({ start: match.index, end: match.index + match[0].length,
original: match[0], placeholder: "PERSON_01", type: "PERSON", score: 1 }));
return { pseudonymized_text: text, mapping, spans, entity_count: spans.length, selected_entity_types: ["PERSON"] };
}, () => undefined);
expect(result.spansByFile.get("boundary.txt")!.map((span) => [span.start, span.end])).toEqual([[prefix.length, prefix.length + 15]]);
});

View File

@@ -498,3 +498,13 @@ describe("Velum-Projektstände", () => {
expect(project.sameEntityTypeCoverage(run, ["PERSON", "EMAIL", "URL"])).toBe(false);
});
});
it("erfasst große Textdateien weiterhin, behält aber die Office-Uploadgrenze", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-large-scan-")); roots.push(root);
for (const name of ["large.txt", "large.docx"]) {
const handle = await fs.open(join(root, name), "w"); await handle.truncate(21 * 1024 * 1024); await handle.close();
}
const result = await project.scanProjectFiles(root, undefined, false);
expect(result.files.map((file) => file.relPath)).toEqual(["large.txt"]);
expect(result.skipped).toEqual([{ path: "large.docx", reason: "Datei zu groß (Grenze: 20 MiB)" }]);
});