droboticflow/tests/frontend/review-decision-controller.test.mjs

485 lines
17 KiB
JavaScript

import assert from "node:assert/strict";
import test from "node:test";
import { createReviewDecisionController } from "../../src/lib/review-decision-controller.js";
class HttpError extends Error {
constructor(status) {
super(`HTTP ${status}`);
this.status = status;
}
}
const deferred = () => {
let resolve, reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
};
const input = {
itemId: "item-a",
taskId: "task-a",
path: "/reviews",
decision: "approved",
title: "Synthetic",
scopeText: "Synthetic",
payload: { draftVersion: 8, resultVersion: "r1" },
};
function fixture(options = {}) {
const values = new Map(),
calls = [],
recovered = [];
const storage = {
keys: () => [...values.keys()],
getItem: (key) => values.get(key) || null,
setItem: (key, value) => values.set(key, value),
removeItem: (key) => values.delete(key),
};
const api = {
send: async (path, payload, headers) => {
calls.push(["send", path, payload, headers]);
},
get: async (itemId, operationId) => {
calls.push(["get", itemId, operationId]);
return { status: "completed", itemId, operationId };
},
reconcile: async (...args) => {
calls.push(["reconcile", ...args]);
},
};
let counter = 0;
const configuration = {
key: "review-decision:user:project:quality",
api,
storage,
isApiError: (e) => e instanceof HttpError,
onRecovered: (...args) => recovered.push(args),
newOperationId: () => `op-${++counter}`,
...options,
};
const controller = createReviewDecisionController(configuration);
controller.activate();
return { controller, configuration, values, calls, storage, api, recovered, state: controller.getSnapshot };
}
test("confirmation and cancel issue no write or durable marker", async () => {
const f = fixture();
const result = f.controller.request(input, () => ({ lease: "one" }));
assert.equal(f.state().confirmation.operationId, "op-1");
assert.deepEqual(f.calls, []);
assert.equal(f.values.size, 0);
f.controller.cancel();
assert.equal(await result, null);
assert.equal(f.state().confirmation, null);
});
test("formal dispatch persists first, keeps payload and uses the latest lease headers", async () => {
const f = fixture();
let lease = "old";
f.api.send = async (_path, payload, headers) => {
assert.equal(JSON.parse(f.storage.getItem(f.configuration.key)).operationId, payload.operationId);
assert.deepEqual(payload, { ...input.payload, operationId: "op-1" });
assert.deepEqual(headers, { lease: "new" });
};
const result = f.controller.request(input, () => ({ lease }));
lease = "new";
await f.controller.confirm();
assert.equal((await result).status, "completed");
assert.equal(f.state().pending, null);
assert.equal(f.values.size, 0);
assert.deepEqual(f.recovered, []);
});
test("double confirm, duplicate request and cancel cannot race an in-flight decision", async () => {
const wait = deferred(),
f = fixture();
f.api.send = async () => {
f.calls.push(["send"]);
await wait.promise;
};
const result = f.controller.request(input, () => ({}));
const send = f.controller.confirm();
await Promise.resolve();
await f.controller.confirm();
f.controller.cancel();
assert.equal(await f.controller.request(input, () => ({})), null);
assert.equal(f.calls.filter(([kind]) => kind === "send").length, 1);
assert.equal(f.state().busy, true);
wait.resolve();
await send;
assert.equal((await result).status, "completed");
});
test("storage failure prevents a formal request and permits another attempt", async () => {
const f = fixture();
f.storage.setItem = () => {
throw new Error("storage blocked");
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
assert.equal(await result, null);
assert.deepEqual(f.calls, []);
assert.equal(f.state().busy, false);
assert.equal(f.state().pending, null);
assert.match(f.state().message, /storage blocked/);
});
for (const allowed of [false, true]) {
test(`continuation preparation is awaited (allowed=${allowed})`, async () => {
const wait = deferred(),
f = fixture({ beforeSend: () => wait.promise });
const result = f.controller.request(input, () => ({}));
const send = f.controller.confirm();
assert.equal(f.values.size, 0);
assert.deepEqual(f.calls, []);
wait.resolve(allowed);
await send;
assert.equal(Boolean(await result), allowed);
assert.equal(
f.calls.some(([kind]) => kind === "send"),
allowed,
);
});
}
test("invalidated preparation cannot dispatch or persist even after returning to the same scope", async () => {
const wait = deferred(),
f = fixture({ beforeSend: () => wait.promise });
const result = f.controller.request(input, () => ({}));
const send = f.controller.confirm();
f.controller.deactivate();
f.controller.activate();
wait.resolve(true);
await send;
assert.equal(await result, null);
assert.deepEqual(f.calls, []);
assert.equal(f.values.size, 0);
});
test("missing lease headers stop dispatch before persisting a pending decision", async () => {
const f = fixture();
const result = f.controller.request(input, () => {
throw new Error("lease lost");
});
await f.controller.confirm();
assert.equal(await result, null);
assert.deepEqual(f.calls, []);
assert.equal(f.values.size, 0);
});
for (const status of ["failed_before_effects", "prepared", "applying"]) {
test(`a successful transport with receipt ${status} never reports success`, async () => {
const f = fixture();
f.api.get = async () => ({ status, error: "提交前校验未通过" });
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
assert.equal(await result, null);
assert.equal(Boolean(f.state().pending), status !== "failed_before_effects");
assert.equal(f.state().failureVersion, 1);
assert.equal(f.state().busy, false);
});
}
for (const receipt of ["completed", "failed_before_effects", "unavailable"]) {
test(`HTTP error uses the durable receipt (${receipt}) rather than the transport status`, async () => {
const f = fixture();
f.api.send = async () => {
throw new HttpError(500);
};
f.api.get = async () => {
if (receipt === "unavailable") throw new Error("network");
return { status: receipt };
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
assert.equal(Boolean(await result), receipt === "completed");
assert.equal(Boolean(f.state().pending), receipt === "unavailable");
});
}
test("a 4xx rejection plus missing receipt unlocks; a 5xx plus missing receipt stays protected", async () => {
for (const status of [409, 500]) {
const f = fixture();
f.api.send = async () => {
throw new HttpError(status);
};
f.api.get = async () => {
throw new HttpError(404);
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
assert.equal(await result, null);
assert.equal(Boolean(f.state().pending), status === 500);
}
});
test("response loss survives reload and reconciles without a duplicate formal write", async () => {
const f = fixture();
f.api.send = async () => {
f.calls.push(["send"]);
throw new Error("response lost");
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
assert.equal(await result, null);
assert.equal(f.state().pending.operationId, "op-1");
f.controller.deactivate();
const next = createReviewDecisionController(f.configuration);
next.activate();
assert.equal(next.getSnapshot().pending.operationId, "op-1");
await next.reconcile();
assert.equal(next.getSnapshot().pending, null);
assert.equal(f.calls.filter(([kind]) => kind === "send").length, 1);
assert.equal(f.recovered.length, 1);
});
test("read-only reconciliation never resumes prepared effects; explicit resume does", async () => {
const f = fixture();
f.api.send = async () => {
throw new Error("response lost");
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
await result;
let status = "prepared";
f.api.get = async () => ({ status });
f.api.reconcile = async () => {
f.calls.push(["reconcile"]);
status = "completed";
};
await f.controller.reconcile(false);
assert.equal(f.calls.length, 0);
assert.ok(f.state().pending);
await f.controller.reconcile();
assert.deepEqual(f.calls, [["reconcile"]]);
assert.equal(f.state().pending, null);
});
test("explicit retry keeps its operation ID and never replaces headers during a busy retry", async () => {
const f = fixture();
f.api.send = async () => {
throw new Error("response lost");
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
await result;
f.api.get = async () => {
throw new HttpError(404);
};
await f.controller.reconcile();
assert.equal(f.state().canRetry, true);
const wait = deferred();
f.configuration.beforeSend = () => wait.promise;
// A fresh controller models reload of the same persisted operation.
const next = createReviewDecisionController(f.configuration);
next.activate();
let sent;
f.api.send = async (_path, payload, headers) => {
sent = { payload, headers };
};
f.api.get = async () => ({ status: "completed" });
const retry = next.retry(() => ({ lease: "first" }));
await next.retry(() => ({ lease: "second" }));
wait.resolve(true);
await retry;
assert.equal(sent.payload.operationId, "op-1");
assert.deepEqual(sent.headers, { lease: "first" });
});
for (const action of ["send", "reconcile"]) {
test(`late ${action} receipt cannot clear a replacement marker or complete a new lifetime`, async () => {
const wait = deferred(),
f = fixture();
f.api.send = async () => {
throw new Error("response lost");
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
await result;
f.api.get = () => wait.promise;
let pending;
if (action === "send") {
f.api.send = async () => {};
pending = f.controller.retry(() => ({}));
await Promise.resolve();
await Promise.resolve();
} else pending = f.controller.reconcile();
f.controller.deactivate();
f.controller.activate();
const replacement = { ...input, operationId: "replacement" };
f.storage.setItem(f.configuration.key, JSON.stringify(replacement));
wait.resolve({ status: "completed" });
await pending;
assert.equal(JSON.parse(f.storage.getItem(f.configuration.key)).operationId, "replacement");
assert.deepEqual(f.recovered, []);
});
}
test("render ownership changes invalidate an old instance before effect cleanup", async () => {
let owned = true;
const wait = deferred(),
f = fixture({ isCurrent: () => owned, beforeSend: () => wait.promise });
const result = f.controller.request(input, () => ({}));
const send = f.controller.confirm();
owned = false;
wait.resolve(true);
await send;
assert.deepEqual(f.calls, []);
f.controller.deactivate();
assert.equal(await result, null);
});
test("unreadable storage reports recovery failure without throwing during activation", () => {
const f = fixture();
f.storage.getItem = () => {
throw new Error("blocked");
};
f.controller.activate();
assert.match(f.state().message, /找不到/);
assert.equal(f.state().pending, null);
});
for (const asynchronous of [false, true]) {
test(`completed receipt stays complete when recovered follow-up fails (async=${asynchronous})`, async () => {
const f = fixture({
onRecovered: () => {
if (asynchronous) return Promise.reject(new Error("queue lost"));
throw new Error("queue lost");
},
});
f.api.send = async () => {
throw new Error("response lost");
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
await result;
await f.controller.reconcile();
await Promise.resolve();
assert.equal(f.state().pending, null);
assert.equal(f.values.size, 0);
assert.match(f.state().message, /提交完成/);
assert.match(f.state().message, /无法更新/);
});
}
for (const status of ["completed", "failed_before_effects"]) {
test(`terminal ${status} receipt is adopted even if local cleanup is blocked`, async () => {
const f = fixture();
f.storage.removeItem = () => {
throw new Error("cleanup blocked");
};
f.api.get = async () => ({ status });
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
assert.equal(Boolean(await result), status === "completed");
assert.equal(f.state().pending, null);
assert.equal(f.state().busy, false);
assert.match(f.state().message, /未能清理/);
// The verified terminal marker must not permanently block new work.
const next = f.controller.request(input, () => ({}));
await f.controller.confirm();
assert.equal(Boolean(await next), status === "completed");
});
}
test("another active tab's unknown operation blocks a new dispatch rather than overwriting it", async () => {
const f = fixture();
const second = createReviewDecisionController({ ...f.configuration, newOperationId: () => "tab-two" });
second.activate();
f.api.send = async () => {
throw new Error("response lost");
};
const first = f.controller.request(input, () => ({}));
await f.controller.confirm();
await first;
const next = second.request({ ...input, itemId: "item-b" }, () => ({}));
await second.confirm();
await next;
assert.equal(second.getSnapshot().pending.operationId, "op-1");
assert.equal(JSON.parse(f.storage.getItem(f.configuration.key)).operationId, "op-1");
assert.ok(![...f.values.keys()].some((key) => key.endsWith("tab-two")));
});
test("per-operation journal survives another tab's mirror overwrite and terminal cleanup", async () => {
const f = fixture();
const held = deferred();
f.api.send = async () => {};
f.api.get = () => held.promise;
const result = f.controller.request(input, () => ({}));
const send = f.controller.confirm();
await Promise.resolve();
await Promise.resolve();
const other = { ...input, itemId: "item-b", operationId: "other-tab" };
f.storage.setItem(f.configuration.key, JSON.stringify(other));
f.storage.setItem(f.configuration.key + ":operation:other-tab", JSON.stringify(other));
held.resolve({ status: "completed" });
await send;
assert.ok(await result);
assert.equal(JSON.parse(f.storage.getItem(f.configuration.key)).operationId, "other-tab");
assert.equal(f.state().pending.operationId, "other-tab");
// An old frontend can delete the mirror. New clients still find its journal.
f.storage.removeItem(f.configuration.key);
const reloaded = createReviewDecisionController(f.configuration);
reloaded.activate();
assert.equal(reloaded.getSnapshot().pending.operationId, "other-tab");
});
test("legacy single-record markers remain recoverable without a journal", async () => {
const f = fixture();
f.controller.deactivate();
f.storage.setItem(f.configuration.key, JSON.stringify({ ...input, operationId: "legacy" }));
f.controller.activate();
assert.equal(f.state().pending.operationId, "legacy");
await f.controller.reconcile();
assert.equal(f.state().pending, null);
assert.equal(f.values.size, 0);
});
for (const responseLost of [false, true]) {
test(`legacy mirror quota failure leaves the journal sufficient (response lost=${responseLost})`, async () => {
const f = fixture(),
set = f.storage.setItem;
f.storage.setItem = (key, value) => {
if (key === f.configuration.key) throw new Error("mirror quota");
set(key, value);
};
if (responseLost)
f.api.send = async () => {
throw new Error("response lost");
};
const result = f.controller.request(input, () => ({}));
await f.controller.confirm();
assert.equal(Boolean(await result), !responseLost);
if (responseLost) {
const next = createReviewDecisionController(f.configuration);
next.activate();
assert.equal(next.getSnapshot().pending.operationId, "op-1");
await next.reconcile();
assert.equal(next.getSnapshot().pending, null);
} else assert.equal(f.state().pending, null);
assert.equal(f.values.size, 0);
});
}
test("two missing receipts can retry their original operation IDs without selecting each other forever", async () => {
const f = fixture();
for (const operationId of ["first", "second"]) {
f.storage.setItem(f.configuration.key + ":operation:" + operationId, JSON.stringify({ ...input, operationId }));
}
f.controller.activate();
const sent = [];
f.api.get = async () => {
throw new HttpError(404);
};
await f.controller.reconcile();
assert.equal(f.state().canRetry, true);
f.api.send = async (_path, payload) => sent.push(payload.operationId);
f.api.get = async (_item, operationId) => ({ status: "completed", operationId });
await f.controller.retry(() => ({}));
assert.equal(f.state().pending.operationId, "second");
await f.controller.retry(() => ({}));
assert.equal(f.state().pending, null);
assert.deepEqual(sent, ["first", "second"]);
assert.equal(f.values.size, 0);
});