const { expect } = require("chai"); require("ts-node/register/transpile-only"); const { monitorEventLoopDelay } = require("node:perf_hooks"); const { setTimeout } = require("node:timers"); const { anonymizePreview } = require("../src/core/preview-anonymizer"); const SLOW_TERM = "a+a+a+a+a+a+b(?=x)"; describe("anonymize-form preview off the main thread", function () { this.timeout(20000); it("anonymizes on a worker", async () => { const [out] = await anonymizePreview("user-ok", ["Alice wrote this"], { terms: ["Alice"] }); expect(out).to.match(/^\S+ wrote this$/); expect(out).to.not.include("Alice"); }); it("answers a backtracking term with a coded timeout and keeps the event loop free", async () => { const loop = monitorEventLoopDelay({ resolution: 10 }); loop.enable(); let failure; try { await anonymizePreview("user-slow", ["a".repeat(250)], { terms: [SLOW_TERM] }); } catch (error) { failure = error; } loop.disable(); expect(failure && failure.message).to.equal("anonymization_timeout"); expect(failure.httpStatus).to.equal(422); // The regex ran for about a second on the worker; the main loop stayed responsive. expect(loop.max / 1e6).to.be.lessThan(300); // The pool recovers after the stalled worker is replaced. const [out] = await anonymizePreview("user-slow", ["Bob"], { terms: ["Bob"] }); expect(out).to.not.include("Bob"); }); it("keeps one preview per user: a newer edit supersedes the older one", async () => { const older = anonymizePreview("user-typing", ["a".repeat(250)], { terms: [SLOW_TERM] }).then(() => null, error => error); const newer = anonymizePreview("user-typing", ["Carol"], { terms: ["Carol"] }); const [olderResult, [newerOut]] = await Promise.all([older, newer]); expect(olderResult && olderResult.message).to.equal("preview_superseded"); expect(olderResult.httpStatus).to.equal(409); expect(newerOut).to.not.include("Carol"); }); it("stops a preview whose client went away", async () => { const controller = new AbortController(); const pending = anonymizePreview("user-left", ["a".repeat(250)], { terms: [SLOW_TERM] }, controller.signal) .then(() => null, error => error); setTimeout(() => controller.abort(), 50); const started = Date.now(); const error = await pending; expect(error && error.message).to.equal("preview_superseded"); expect(Date.now() - started).to.be.lessThan(800); }); });