Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
159 lines
10 KiB
TypeScript
159 lines
10 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { readFileSync } from "node:fs";
|
|
import test from "node:test";
|
|
|
|
import { createSupabasePersonalReportJobService } from "../src/lib/personal-report-job-service-core.ts";
|
|
import {
|
|
estimateReportQueue,
|
|
loadReportQueue,
|
|
parseReportQueueView,
|
|
ownReportsQueueLine,
|
|
readReportWorkerConcurrency,
|
|
reportQueueLine,
|
|
reportWorkerLanes,
|
|
SHORT_REPORT_TYPES,
|
|
type ReportQueueView,
|
|
} from "../src/lib/report-queue.ts";
|
|
|
|
const read = (path: string) => readFileSync(new URL(path, import.meta.url), "utf8");
|
|
|
|
const averages = {
|
|
personal_full: { seconds: 600, samples: 10 },
|
|
annual_full: { seconds: 120, samples: 10 },
|
|
synastry_full: { seconds: 240, samples: 10 },
|
|
};
|
|
|
|
function view(partial: Partial<ReportQueueView>): ReportQueueView {
|
|
return { status: "queued", ahead: [], running: [], averages, mineAhead: 0, ...partial };
|
|
}
|
|
|
|
test("lanes: two by default, the second takes short reports only; the env raises it after a server upgrade", () => {
|
|
assert.equal(readReportWorkerConcurrency({}), 2);
|
|
assert.equal(readReportWorkerConcurrency({ PERSONAL_REPORT_WORKER_CONCURRENCY: "4" }), 4);
|
|
assert.equal(readReportWorkerConcurrency({ PERSONAL_REPORT_WORKER_CONCURRENCY: "99" }), 6);
|
|
assert.equal(readReportWorkerConcurrency({ PERSONAL_REPORT_WORKER_CONCURRENCY: "zero" }), 2);
|
|
assert.equal(readReportWorkerConcurrency({ PERSONAL_REPORT_WORKER_CONCURRENCY: "1" }), 1);
|
|
assert.deepEqual(reportWorkerLanes(1), [{ id: "lane-1", reportTypes: null }]);
|
|
assert.deepEqual(reportWorkerLanes(3).map((lane) => lane.reportTypes), [null, [...SHORT_REPORT_TYPES], null]);
|
|
});
|
|
|
|
test("estimate: an annual report waits for the short lane, not behind long personal reports", () => {
|
|
const lanes = reportWorkerLanes(2);
|
|
// A long report runs on lane 1 (200 s in); two personal reports wait; my annual one is third.
|
|
const estimate = estimateReportQueue(view({
|
|
ahead: ["personal_full", "personal_full"],
|
|
running: [{ type: "personal_full", elapsedSeconds: 200 }],
|
|
}), "annual_full", lanes);
|
|
assert.deepEqual(estimate, { ahead: 2, startsInSeconds: 0 });
|
|
assert.equal(reportQueueLine(estimate), "马上开始。");
|
|
});
|
|
|
|
test("estimate: a personal report waits for the general lane", () => {
|
|
const lanes = reportWorkerLanes(2);
|
|
const estimate = estimateReportQueue(view({
|
|
ahead: ["annual_full", "personal_full"],
|
|
running: [{ type: "personal_full", elapsedSeconds: 300 }, { type: "annual_full", elapsedSeconds: 30 }],
|
|
}), "personal_full", lanes);
|
|
// Lane 1 frees at 300 s, takes the personal report ahead (600 s) → 900 s; the annual one ahead goes to lane 2.
|
|
assert.equal(estimate?.startsInSeconds, 900);
|
|
assert.equal(reportQueueLine(estimate), "大约等 15 分钟开始。");
|
|
});
|
|
|
|
test("estimate: no recent run time for a type → only the count, never a guessed time", () => {
|
|
const estimate = estimateReportQueue(view({ ahead: ["annual_full"], averages: {} }), "annual_full", reportWorkerLanes(2));
|
|
assert.deepEqual(estimate, { ahead: 1, startsInSeconds: null });
|
|
assert.equal(reportQueueLine(estimate), "正在排队。");
|
|
assert.equal(reportQueueLine(estimateReportQueue(view({}), "annual_full", reportWorkerLanes(2))), "马上开始。");
|
|
// Once it runs there is no queue line.
|
|
assert.equal(estimateReportQueue(view({ status: "running" }), "annual_full", reportWorkerLanes(2)), null);
|
|
});
|
|
|
|
test("the line names only the wait, never how many reports are ahead", () => {
|
|
for (const estimate of [{ ahead: 3, startsInSeconds: 600 }, { ahead: 3, startsInSeconds: null }, { ahead: 3, startsInSeconds: 30 }]) {
|
|
assert.doesNotMatch(reportQueueLine(estimate) ?? "", /份|前面|轮到/);
|
|
}
|
|
});
|
|
|
|
test("the database view is parsed defensively and a failed read shows no line", async () => {
|
|
assert.equal(parseReportQueueView(null), null);
|
|
assert.deepEqual(parseReportQueueView({ status: "queued", ahead: ["annual_full", 3], running: [{ type: "x" }], averages: { a: { seconds: -1 } } }),
|
|
// 原值:解析结果没有 mineAhead;新值:缺省为 0;原因:BUG-2418 视图新增「前面还有几份自己的报告」
|
|
{ status: "queued", ahead: ["annual_full"], running: [{ type: "x", elapsedSeconds: 0 }], averages: {}, mineAhead: 0 });
|
|
const broken = { rpc: async () => ({ data: null, error: { message: "boom" } }) };
|
|
assert.equal(await loadReportQueue(broken, "00000000-0000-4000-8000-000000000001", "annual_full", {}), null);
|
|
const ok = { rpc: async () => ({ data: { status: "queued", ahead: ["personal_full"], running: [], averages }, error: null }) };
|
|
assert.deepEqual(await loadReportQueue(ok, "00000000-0000-4000-8000-000000000001", "annual_full", {}),
|
|
{ ahead: 1, startsInSeconds: 0, line: "马上开始。" });
|
|
const busy = { rpc: async () => ({ data: { status: "queued", ahead: ["annual_full"], running: [{ type: "annual_full", elapsedSeconds: 20 }], averages }, error: null }) };
|
|
assert.deepEqual(await loadReportQueue(busy, "00000000-0000-4000-8000-000000000001", "annual_full", {}),
|
|
{ ahead: 1, startsInSeconds: 100, line: "大约等 2 分钟开始。" });
|
|
});
|
|
|
|
test("a lane claims only its report types", async () => {
|
|
const calls: Array<Record<string, unknown>> = [];
|
|
const client = {
|
|
from() { throw new Error("not used"); },
|
|
async rpc(name: string, args: Record<string, unknown>) {
|
|
calls.push({ name, ...args });
|
|
return { data: [], error: null };
|
|
},
|
|
};
|
|
const service = createSupabasePersonalReportJobService(client as never);
|
|
assert.equal(await service.claimLease({ workerId: "w:lane-2", reportTypes: ["annual_full", "synastry_full"] }), null);
|
|
assert.equal(await service.claimLease({ workerId: "w:lane-1" }), null);
|
|
assert.deepEqual(calls.map((call) => [call.name, call.p_report_types ?? null]), [
|
|
["claim_personal_report_job_for_types", ["annual_full", "synastry_full"]],
|
|
["claim_personal_report_job", null],
|
|
]);
|
|
});
|
|
|
|
test("migration: a separate typed claim (the original claim is untouched) and an owner-only queue view", () => {
|
|
const sql = read("../supabase/migrations/20261105010000_personal_report_job_lanes.sql");
|
|
// Overloading claim_personal_report_job made three-argument calls ambiguous in the staging DB gate.
|
|
assert.doesNotMatch(sql, /function public\.claim_personal_report_job\(/);
|
|
assert.match(sql, /create or replace function public\.claim_personal_report_job_for_types\(\s*p_worker_id text,\s*p_lease_seconds integer,\s*p_report_types text\[\]\s*\)/);
|
|
assert.match(sql, /report\.report_type = any\(p_report_types\)/);
|
|
assert.match(sql, /for update skip locked/);
|
|
assert.match(sql, /revoke all on function public\.claim_personal_report_job_for_types\(text, integer, text\[\]\) from public, anon, authenticated/);
|
|
assert.match(sql, /grant execute on function public\.claim_personal_report_job_for_types\(text, integer, text\[\]\) to service_role/);
|
|
// The view answers only the job's own user; it can count others' jobs (security definer).
|
|
assert.match(sql, /owner uuid := \(select auth\.uid\(\)\);/);
|
|
assert.match(sql, /where job\.id = p_job_id and job\.user_id = owner/);
|
|
assert.match(sql, /security definer\s+set search_path = ''/);
|
|
assert.match(sql, /revoke all on function public\.personal_report_queue_view\(uuid\) from public, anon;/);
|
|
assert.match(sql, /grant execute on function public\.personal_report_queue_view\(uuid\) to authenticated, service_role;/);
|
|
// The view returns types and times only, never another user's identifiers.
|
|
const viewSql = sql.slice(sql.indexOf("create or replace function public.personal_report_queue_view"));
|
|
assert.doesNotMatch(viewSql.slice(viewSql.indexOf("jsonb_build_object(")), /user_id|request_id|'id'/);
|
|
});
|
|
|
|
test("the server runs one loop per lane and the report API adds the queue line for waiting reports", () => {
|
|
const worker = read("../src/lib/personal-report-worker.ts");
|
|
assert.match(worker, /reportWorkerLanes\(readReportWorkerConcurrency\(process\.env\)\)/);
|
|
assert.match(worker, /reportTypes: lane\.reportTypes/);
|
|
assert.match(worker, /primary \? \{ runIdleSynastryEnglish/);
|
|
const route = read("../src/app/api/reports/[reportId]/route.ts");
|
|
assert.match(route, /owned\?\.status === "generating"/);
|
|
// Least privilege: the item route never uses the service role (personal-report-api test).
|
|
assert.match(route, /queueFor\(supabase, job\.id/);
|
|
assert.doesNotMatch(route, /createAdminSupabaseClient/);
|
|
});
|
|
|
|
test("BUG-2418: a report waiting behind the person's own earlier reports says how many of theirs come first", async () => {
|
|
assert.equal(parseReportQueueView({ status: "queued", ahead: [], running: [], averages: {} })?.mineAhead, 0);
|
|
assert.equal(parseReportQueueView({ status: "queued", ahead: [], running: [], averages: {}, mineAhead: 2 })?.mineAhead, 2);
|
|
assert.equal(ownReportsQueueLine(0), null);
|
|
assert.equal(ownReportsQueueLine(1), "排队中,前面还有 1 份你的报告,写完就轮到这一份。");
|
|
const client = { rpc: async () => ({ data: { status: "queued", ahead: ["personal_full"], running: [{ type: "personal_full", elapsedSeconds: 30 }], averages, mineAhead: 1 }, error: null }) };
|
|
const loaded = await loadReportQueue(client, "00000000-0000-4000-8000-000000000001", "synastry_full", {});
|
|
assert.deepEqual(loaded, { ahead: 1, startsInSeconds: null, line: "排队中,前面还有 1 份你的报告,写完就轮到这一份。" });
|
|
const migration = read("../supabase/migrations/20261126040000_report_queue_per_user.sql");
|
|
assert.match(migration, /drop index if exists public\.personal_reports_one_generating_per_user;/);
|
|
assert.match(migration, /drop index if exists public\.personal_report_jobs_one_active_per_user;/);
|
|
assert.match(migration, /create unique index if not exists personal_report_jobs_one_running_per_user\s+on public\.personal_report_jobs \(user_id\)\s+where status = 'running';/);
|
|
// Both claim functions skip a person who already has a running job, atomically.
|
|
assert.equal((migration.match(/busy\.user_id = job\.user_id and busy\.status = 'running'/g) ?? []).length, 2);
|
|
assert.equal((migration.match(/exception when unique_violation then/g) ?? []).length, 2);
|
|
assert.match(migration, /'mineAhead', \(select mine_ahead\.n from mine_ahead\)/);
|
|
});
|