feat(reports): report queue lanes — two at once with a short-report lane, waiting screens show the expected wait
Every report type already queued in personal_report_jobs, one at a time per server. The worker now runs PERSONAL_REPORT_WORKER_CONCURRENCY lanes (default 2); the second takes only annual and synastry reports so they never wait behind long personal reports. claim_personal_report_job gains an optional report-type filter; personal_report_queue_view (owner-only, security definer) gives the wait, shown as a single line on the annual, personal and synastry waiting screens. Also keeps the privacy whitelist line numbers in personal-report-api.test.ts unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXozbkyFNqbu8pVEtZ7W
This commit is contained in:
@@ -20,6 +20,10 @@ PERSONAL_REPORT_ENABLED=true
|
||||
PERSONAL_REPORT_DAILY_LIMIT=5
|
||||
```
|
||||
|
||||
`PERSONAL_REPORT_DAILY_LIMIT` applies only to reports that are not billed; paid reports (annual, synastry, personal with billing) have no daily or hourly cap, and a failed report is never counted (BUG-1641).
|
||||
|
||||
`PERSONAL_REPORT_WORKER_CONCURRENCY` (optional, default `2`, at most `6`) is how many reports one server writes at once. Lane 1 takes any report, lane 2 only short ones (annual, synastry), further lanes any. `1` is the old one-at-a-time behaviour. Raise it after a server upgrade; no code change is needed. Waiting users see an estimated wait from the recent average run time per report type.
|
||||
|
||||
`PERSONAL_REPORT_ALLOWED_ORIGINS` is normally omitted because browser requests are same-origin. Add it only for an explicitly reviewed origin. `JYOTISH_SKILL_SNAPSHOT_SHA256` and `JYOTISH_SKILL_SOURCE_COMMIT` are optional deployment pins; without a valid override, the web bundle uses the statically packaged, validated source manifest and fails closed if its SHA is invalid.
|
||||
|
||||
Validate without logging values:
|
||||
|
||||
@@ -23,6 +23,7 @@ import { isSupabaseConfigurationError } from "@/lib/supabase/config";
|
||||
import { createServerSupabaseClient } from "@/lib/supabase/server";
|
||||
import { publicSynastryView, SNAPSHOT_SECTION } from "@/lib/synastry-full-run";
|
||||
import { readAnnualSnapshot } from "@/lib/annual-report-server";
|
||||
import { loadReportQueue } from "@/lib/report-queue";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
@@ -37,6 +38,15 @@ function toNextResponse(response: { status: number; body: Record<string, unknown
|
||||
return NextResponse.json(response.body, { status: response.status });
|
||||
}
|
||||
|
||||
/** The queue view answers only the job's own user (auth.uid() in the database). */
|
||||
async function queueFor(client: unknown, jobId: string, reportType: string) {
|
||||
try {
|
||||
return await loadReportQueue(client as never, jobId, reportType, process.env);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
/**
|
||||
@@ -136,7 +146,8 @@ export async function GET(request: Request, context: RouteContext) {
|
||||
const job = owned.status === "generating" && jobs
|
||||
? await jobs.getOwnedByRequestId(userId, owned.requestId).catch(() => null)
|
||||
: null;
|
||||
return NextResponse.json({ report: reportView(owned, job), annual });
|
||||
const queue = job ? await queueFor(supabase, job.id, owned.reportType) : null;
|
||||
return NextResponse.json({ report: reportView(owned, job), annual, ...(queue ? { queue } : {}) });
|
||||
}
|
||||
if (owned?.reportType === "synastry_full" && owned.status === "ready") {
|
||||
const stored = await supabase
|
||||
@@ -153,6 +164,7 @@ export async function GET(request: Request, context: RouteContext) {
|
||||
return NextResponse.json({ report: reportView(owned), synastry });
|
||||
}
|
||||
}
|
||||
const owned = userId && persistence ? await persistence.getOwnedById(userId, reportId).catch(() => null) : null;
|
||||
const response = await resolveReportRead({
|
||||
requestUrl: request.url,
|
||||
origin: request.headers.get("origin"),
|
||||
@@ -181,6 +193,12 @@ export async function GET(request: Request, context: RouteContext) {
|
||||
: { ok: false };
|
||||
},
|
||||
});
|
||||
// A waiting report also says where it is in the queue (report queue, 2026-11-05).
|
||||
if (response.status === 200 && owned?.status === "generating" && jobs && userId && supabase) {
|
||||
const job = await jobs.getOwnedByRequestId(userId, owned.requestId).catch(() => null);
|
||||
const queue = job ? await queueFor(supabase, job.id, owned.reportType) : null;
|
||||
if (queue) return toNextResponse({ ...response, body: { ...response.body, queue } });
|
||||
}
|
||||
return toNextResponse(response);
|
||||
} catch (error) {
|
||||
if (isSupabaseConfigurationError(error)) {
|
||||
|
||||
@@ -5022,6 +5022,8 @@ button.synastry-dd-add { border-radius: 0 0 var(--radius-md) var(--radius-md); }
|
||||
}
|
||||
.synastry-wait p { margin: 0; }
|
||||
.synastry-wait .sub { max-width: 36rem; color: var(--color-ink-tertiary); font-size: 14px; line-height: 1.6; }
|
||||
/* Where a waiting report is in the queue (report queue, 2026-11-05): personal, synastry and annual waits. */
|
||||
.report-queue-line { margin: 0; color: var(--color-ink-secondary); font-size: 14px; line-height: 1.6; font-variant-numeric: tabular-nums; }
|
||||
/* The app's one waiting motion since 2026-11-05 (BUG-1613); the orbit rules below are unused. */
|
||||
.synastry-wait-chart { flex: none; }
|
||||
.synastry-orbit { position: relative; width: 56px; height: 56px; min-height: 56px; flex: none; }
|
||||
|
||||
@@ -49,6 +49,8 @@ type ReportState = Readonly<{
|
||||
/** The worker's stage: queued → computing_annual → writing_report. */
|
||||
phase?: string;
|
||||
createdAt?: string;
|
||||
/** Where the report is in the queue, from the server (report queue, 2026-11-05). */
|
||||
queueLine?: string;
|
||||
}>;
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
@@ -96,11 +98,12 @@ function elapsedLabel(seconds: number): string {
|
||||
* being written, and how long it has taken. Every value comes from the job
|
||||
* stage and the saved snapshot; nothing is estimated.
|
||||
*/
|
||||
export function AnnualProgress({ phase, snapshot, createdAt, now }: Readonly<{
|
||||
export function AnnualProgress({ phase, snapshot, createdAt, now, queueLine }: Readonly<{
|
||||
phase?: string;
|
||||
snapshot: AnnualSnapshot | null;
|
||||
createdAt?: string;
|
||||
now?: number;
|
||||
queueLine?: string;
|
||||
}>) {
|
||||
const step = stepOf(phase, snapshot);
|
||||
const total = snapshot?.plan.length ?? ANNUAL_SKELETON_TITLES.length;
|
||||
@@ -114,7 +117,7 @@ export function AnnualProgress({ phase, snapshot, createdAt, now }: Readonly<{
|
||||
<section className="annual-progress" aria-label="年运写作进度">
|
||||
<div className="annual-progress-top">
|
||||
<p className="annual-progress-now" role="status" aria-live="polite">
|
||||
{current ? <>正在写「{current}」</> : PROGRESS_STEPS[step].detail}
|
||||
{current ? <>正在写「{current}」</> : step === 0 && queueLine ? queueLine : PROGRESS_STEPS[step].detail}
|
||||
</p>
|
||||
<p className="annual-progress-count">
|
||||
{step === 2 ? `${done} / ${total} 节` : ""}{seconds !== null ? `${step === 2 ? " · " : ""}已用 ${elapsedLabel(seconds)}` : ""}
|
||||
@@ -624,6 +627,7 @@ export function AnnualReportPage({ initialReportId = null }: Readonly<{ initialR
|
||||
id, status, annual: (json.annual as AnnualSnapshot | null) ?? null,
|
||||
...(typeof view.progressPhase === "string" ? { phase: view.progressPhase } : {}),
|
||||
...(typeof view.createdAt === "string" ? { createdAt: view.createdAt } : {}),
|
||||
...(typeof record(json.queue).line === "string" ? { queueLine: record(json.queue).line as string } : {}),
|
||||
});
|
||||
}, []);
|
||||
|
||||
@@ -678,7 +682,7 @@ export function AnnualReportPage({ initialReportId = null }: Readonly<{ initialR
|
||||
{overviewError ? <p className="annual-error" role="alert">{overviewError}</p> : null}
|
||||
{writing && report ? (
|
||||
<div className="annual-progress-dock">
|
||||
<AnnualProgress phase={report.phase} snapshot={report.annual} createdAt={report.createdAt} now={now} />
|
||||
<AnnualProgress phase={report.phase} snapshot={report.annual} createdAt={report.createdAt} now={now} queueLine={report.queueLine} />
|
||||
</div>
|
||||
) : null}
|
||||
{/* A failed run keeps what it already wrote (BUG-1611): the snapshot is
|
||||
|
||||
@@ -58,6 +58,8 @@ export type ReportLoadState =
|
||||
progressPercent?: number;
|
||||
progressPhase?: string;
|
||||
sections?: readonly ReportSectionProgress[];
|
||||
/** Where the report is in the queue, from the server (report queue, 2026-11-05). */
|
||||
queueLine?: string;
|
||||
}
|
||||
| { phase: "timed-out" }
|
||||
| { phase: "failed"; failureCode: string | null; failureSummary?: string | null; appendixLastErrorCode?: string | null; reportType?: string }
|
||||
@@ -185,8 +187,11 @@ export function classifyReportEnvelope(statusCode: number, json: unknown): Repor
|
||||
const progressPercent = typeof view.progressPercent === "number" ? view.progressPercent : undefined;
|
||||
const progressPhase = typeof view.progressPhase === "string" ? view.progressPhase : undefined;
|
||||
const sections = readSectionProgress(view.sections);
|
||||
const queue = isRecord(json.queue) ? json.queue : null;
|
||||
const queueLine = queue && typeof queue.line === "string" ? queue.line : undefined;
|
||||
return {
|
||||
phase: "generating",
|
||||
...(queueLine ? { queueLine } : {}),
|
||||
...(view.reportType === "synastry_full" ? { reportType: "synastry_full" as const } : {}),
|
||||
...(progressPercent === undefined ? {} : { progressPercent }),
|
||||
...(progressPhase === undefined ? {} : { progressPhase }),
|
||||
@@ -452,7 +457,7 @@ export function PersonalReportPage({
|
||||
return (
|
||||
<>
|
||||
<SecondaryHeader title="婚恋合盘" />
|
||||
<SynastryWait reportId={reportId} phase={state.progressPhase} />
|
||||
<SynastryWait reportId={reportId} phase={state.progressPhase} queueLine={state.queueLine} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -481,6 +486,7 @@ export function PersonalReportPage({
|
||||
<p role="status" className={writing ? "personal-report-progress-headline" : undefined}>
|
||||
{progress?.headline ?? PERSONAL_REPORT_GENERATING_COPY}
|
||||
</p>
|
||||
{state.queueLine ? <p className="report-queue-line">{state.queueLine}</p> : null}
|
||||
{progress && writing && <PersonalReportProgressPanel progress={progress} />}
|
||||
{generating && (
|
||||
<>
|
||||
|
||||
@@ -39,6 +39,8 @@ export function SynastryWait(props: {
|
||||
reportId?: string;
|
||||
phase?: string;
|
||||
names?: { a?: string; b?: string };
|
||||
/** Where the report is in the queue (report queue, 2026-11-05). */
|
||||
queueLine?: string;
|
||||
}) {
|
||||
const stored = useSyncExternalStore(
|
||||
() => () => {},
|
||||
@@ -64,6 +66,7 @@ export function SynastryWait(props: {
|
||||
<div className="synastry-wait" role="status">
|
||||
<Orbit />
|
||||
<p>正在写{who}合盘报告…</p>
|
||||
{props.queueLine ? <p className="report-queue-line">{props.queueLine}</p> : null}
|
||||
<ol className="synastry-steps">
|
||||
{STEPS.map((label, index) => (
|
||||
<li key={label} className={index < done ? "done" : undefined}>{label}</li>
|
||||
|
||||
@@ -92,6 +92,8 @@ export type ClaimPersonalReportJobInput = Readonly<{
|
||||
workerId: string;
|
||||
leaseSeconds?: number;
|
||||
jobId?: string | null;
|
||||
/** Only claim these report types (a queue lane); absent = any type. */
|
||||
reportTypes?: readonly string[] | null;
|
||||
}>;
|
||||
|
||||
export type HeartbeatPersonalReportJobInput = Readonly<{
|
||||
@@ -677,10 +679,12 @@ export function createPersonalReportJobService(
|
||||
const workerId = requireWorkerId(input.workerId);
|
||||
const leaseSeconds = requireInteger(input.leaseSeconds ?? 60, "leaseSeconds", 5, 3600);
|
||||
const jobId = optionalUuid(input.jobId, "jobId");
|
||||
const reportTypes = input.reportTypes && input.reportTypes.length > 0 ? [...input.reportTypes] : null;
|
||||
const { data, error } = await client.rpc("claim_personal_report_job", {
|
||||
p_worker_id: workerId,
|
||||
p_lease_seconds: leaseSeconds,
|
||||
p_job_id: jobId,
|
||||
p_report_types: reportTypes,
|
||||
});
|
||||
if (error) throw storageError(error);
|
||||
const row = firstRpcRow(data);
|
||||
|
||||
@@ -94,6 +94,8 @@ export type PersonalReportWorkerReportPort = Pick<
|
||||
|
||||
export type PersonalReportWorkerDeps = Readonly<{
|
||||
workerId: string;
|
||||
/** The queue lane: only these report types are claimed; absent = any. */
|
||||
reportTypes?: readonly string[] | null;
|
||||
jobs: PersonalReportWorkerJobPort;
|
||||
reports: PersonalReportWorkerReportPort;
|
||||
loadProfile: (userId: string, subjectId: string) => Promise<unknown | null>;
|
||||
@@ -494,7 +496,7 @@ export function createPersonalReportWorker(deps: PersonalReportWorkerDeps) {
|
||||
return {
|
||||
async tick(): Promise<PersonalReportWorkerTickResult> {
|
||||
const recovery = await deps.jobs.recoverExpiredLeases(recoveryLimit);
|
||||
const job = await deps.jobs.claimLease({ workerId: deps.workerId, leaseSeconds });
|
||||
const job = await deps.jobs.claimLease({ workerId: deps.workerId, leaseSeconds, reportTypes: deps.reportTypes ?? null });
|
||||
if (!job) {
|
||||
void deps.runIdleSynastryEnglish?.().catch((error) => {
|
||||
console.error(`[synastry-english] ${error instanceof Error ? error.name : "failed"}`);
|
||||
|
||||
@@ -34,6 +34,7 @@ import { PERSONAL_REPORT_WRITER_ENABLED } from "@/lib/personal-report-writer-fla
|
||||
import { loadReportCandidateRange } from "@/lib/report-candidate-range";
|
||||
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
|
||||
import { recordSynastryModelUsage, runIdleSynastryEnglish, runSynastryFullReport } from "@/lib/synastry-full-run";
|
||||
import { readReportWorkerConcurrency, reportWorkerLanes, type ReportLane } from "@/lib/report-queue";
|
||||
import { runAnnualReport } from "@/lib/annual-report-server";
|
||||
import { ANNUAL_FEATURE_KEY, ANNUAL_REPORT_SCHEMA } from "@/lib/annual-report-shared";
|
||||
import { completeUsage, releaseUsage } from "@/lib/consultation-billing";
|
||||
@@ -257,10 +258,11 @@ async function generateProductionReport(
|
||||
return generateLongformReport(context, candidateRange, admin);
|
||||
}
|
||||
|
||||
function createProductionWorker(workerId: string) {
|
||||
function createProductionWorker(workerId: string, lane: ReportLane, primary: boolean) {
|
||||
const admin = createAdminSupabaseClient();
|
||||
return createPersonalReportWorker({
|
||||
workerId,
|
||||
reportTypes: lane.reportTypes,
|
||||
leaseSeconds: 600,
|
||||
heartbeatIntervalMs: 20_000,
|
||||
jobs: createSupabasePersonalReportJobService(admin),
|
||||
@@ -315,7 +317,8 @@ function createProductionWorker(workerId: string) {
|
||||
reserve: async () => { throw new Error("report worker does not reserve usage"); },
|
||||
},
|
||||
loadProfile: (userId, subjectId) => loadReportWorkerProfile(admin, userId, subjectId),
|
||||
runIdleSynastryEnglish: () => runIdleSynastryEnglish(admin as never),
|
||||
// Idle chores run on the first lane only, so they never run twice at once.
|
||||
...(primary ? { runIdleSynastryEnglish: () => runIdleSynastryEnglish(admin as never) } : {}),
|
||||
finalizeSynastry: async (report, ready) => {
|
||||
const completedAt = new Date().toISOString();
|
||||
// Synastry and annual reports both persist their own snapshot section
|
||||
@@ -379,22 +382,28 @@ export function startPersonalReportWorker(): PersonalReportWorkerHandle {
|
||||
|
||||
const controller = new AbortController();
|
||||
const workerId = `personal-report:${globalThis.crypto.randomUUID()}`;
|
||||
let worker: ReturnType<typeof createProductionWorker> | null = null;
|
||||
const lazyWorker = {
|
||||
tick: async () => {
|
||||
worker ??= createProductionWorker(workerId);
|
||||
return worker.tick();
|
||||
},
|
||||
};
|
||||
const done = runPersonalReportWorkerLoop(lazyWorker, {
|
||||
signal: controller.signal,
|
||||
onError: (error) => {
|
||||
console.error(`[personal-report-worker] tick failed reason=${sanitizedErrorName(error)}`);
|
||||
},
|
||||
// A few lanes run side by side (report queue, 2026-11-05); writing is mostly
|
||||
// waiting on the model, so the server stays light. The heavy chart step is
|
||||
// still bounded by the engine's own heavy-compute gate.
|
||||
const lanes = reportWorkerLanes(readReportWorkerConcurrency(process.env));
|
||||
const loops = lanes.map((lane, index) => {
|
||||
let worker: ReturnType<typeof createProductionWorker> | null = null;
|
||||
const lazyWorker = {
|
||||
tick: async () => {
|
||||
worker ??= createProductionWorker(`${workerId}:${lane.id}`, lane, index === 0);
|
||||
return worker.tick();
|
||||
},
|
||||
};
|
||||
return runPersonalReportWorkerLoop(lazyWorker, {
|
||||
signal: controller.signal,
|
||||
onError: (error) => {
|
||||
console.error(`[personal-report-worker] tick failed lane=${lane.id} reason=${sanitizedErrorName(error)}`);
|
||||
},
|
||||
});
|
||||
});
|
||||
const handle: PersonalReportWorkerHandle = {
|
||||
workerId,
|
||||
done,
|
||||
done: Promise.all(loops).then(() => undefined),
|
||||
stop: () => controller.abort(),
|
||||
};
|
||||
state.jyotishaPersonalReportWorker = handle;
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Report queue lanes and wait estimate (product 2026-11-05: reports queue
|
||||
* when several people generate at once; the server will be upgraded later).
|
||||
*
|
||||
* Every report type goes through personal_report_jobs. The worker runs
|
||||
* `PERSONAL_REPORT_WORKER_CONCURRENCY` lanes (default 2). The second lane takes
|
||||
* only short reports (annual, synastry), so they never wait behind two long
|
||||
* personal reports; any further lane takes anything. Raising the number after
|
||||
* a server upgrade needs no code change.
|
||||
*
|
||||
* The estimate comes from the queue itself and from the recent average run
|
||||
* time per type. With no recent finished report of a type, the estimate is
|
||||
* left out rather than guessed.
|
||||
*/
|
||||
|
||||
export const SHORT_REPORT_TYPES = ["annual_full", "synastry_full"] as const;
|
||||
export const REPORT_WORKER_CONCURRENCY_ENV = "PERSONAL_REPORT_WORKER_CONCURRENCY";
|
||||
export const DEFAULT_REPORT_WORKER_CONCURRENCY = 2;
|
||||
export const MAX_REPORT_WORKER_CONCURRENCY = 6;
|
||||
|
||||
/** null = any report type. */
|
||||
export type ReportLane = Readonly<{ id: string; reportTypes: readonly string[] | null }>;
|
||||
|
||||
export function readReportWorkerConcurrency(environment: Readonly<Record<string, string | undefined>>): number {
|
||||
const raw = environment[REPORT_WORKER_CONCURRENCY_ENV]?.trim();
|
||||
const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;
|
||||
if (!Number.isFinite(parsed) || parsed < 1) return DEFAULT_REPORT_WORKER_CONCURRENCY;
|
||||
return Math.min(parsed, MAX_REPORT_WORKER_CONCURRENCY);
|
||||
}
|
||||
|
||||
/** Lane 1 takes anything; lane 2 short reports only; lanes 3+ anything. */
|
||||
export function reportWorkerLanes(concurrency: number): ReportLane[] {
|
||||
return Array.from({ length: Math.max(1, concurrency) }, (_, index) => ({
|
||||
id: `lane-${index + 1}`,
|
||||
reportTypes: index === 1 ? [...SHORT_REPORT_TYPES] : null,
|
||||
}));
|
||||
}
|
||||
|
||||
export type ReportQueueView = Readonly<{
|
||||
status: string;
|
||||
ahead: readonly string[];
|
||||
running: readonly Readonly<{ type: string; elapsedSeconds: number }>[];
|
||||
averages: Readonly<Record<string, Readonly<{ seconds: number; samples: number }>>>;
|
||||
}>;
|
||||
|
||||
export type ReportQueueEstimate = Readonly<{
|
||||
/** Reports that will start before this one. */
|
||||
ahead: number;
|
||||
/** Seconds until this report starts; null when a type has no recent run time. */
|
||||
startsInSeconds: number | null;
|
||||
}>;
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
/** Parse the database view; anything malformed becomes null (the page then shows no queue line). */
|
||||
export function parseReportQueueView(value: unknown): ReportQueueView | null {
|
||||
const row = record(value);
|
||||
if (typeof row.status !== "string") return null;
|
||||
const ahead = Array.isArray(row.ahead) ? row.ahead.filter((item): item is string => typeof item === "string") : [];
|
||||
const running = (Array.isArray(row.running) ? row.running : []).map(record)
|
||||
.filter((item) => typeof item.type === "string")
|
||||
.map((item) => ({ type: item.type as string, elapsedSeconds: typeof item.elapsedSeconds === "number" ? Math.max(0, item.elapsedSeconds) : 0 }));
|
||||
const averages: Record<string, { seconds: number; samples: number }> = {};
|
||||
for (const [type, entry] of Object.entries(record(row.averages))) {
|
||||
const item = record(entry);
|
||||
if (typeof item.seconds === "number" && item.seconds > 0) {
|
||||
averages[type] = { seconds: item.seconds, samples: typeof item.samples === "number" ? item.samples : 0 };
|
||||
}
|
||||
}
|
||||
return { status: row.status, ahead, running, averages };
|
||||
}
|
||||
|
||||
function laneTakes(lane: ReportLane, type: string): boolean {
|
||||
return lane.reportTypes === null || lane.reportTypes.includes(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* When this report starts, by playing the queue forward over the lanes: the
|
||||
* running reports finish after their average minus what they have run, each
|
||||
* report ahead takes the free lane that accepts it first. Only meaningful
|
||||
* while this report is still waiting.
|
||||
*/
|
||||
export function estimateReportQueue(view: ReportQueueView, ownType: string, lanes: readonly ReportLane[]): ReportQueueEstimate | null {
|
||||
if (view.status !== "queued" && view.status !== "retrying") return null;
|
||||
const average = (type: string) => view.averages[type]?.seconds ?? null;
|
||||
const free = lanes.map(() => 0);
|
||||
let known = true;
|
||||
// Running reports sit on lanes. Long ones can only be on a general lane, so
|
||||
// place them first; short ones then prefer the short-only lane.
|
||||
const isShort = (type: string) => (SHORT_REPORT_TYPES as readonly string[]).includes(type);
|
||||
const running = [...view.running].sort((a, b) => Number(isShort(a.type)) - Number(isShort(b.type)));
|
||||
const taken = lanes.map(() => false);
|
||||
for (const job of running) {
|
||||
const open = lanes.map((lane, index) => index).filter((index) => !taken[index] && laneTakes(lanes[index], job.type));
|
||||
const slot = open.find((index) => lanes[index].reportTypes !== null) ?? open[0];
|
||||
if (slot === undefined) continue;
|
||||
taken[slot] = true;
|
||||
const seconds = average(job.type);
|
||||
if (seconds === null) known = false;
|
||||
free[slot] = Math.max(60, (seconds ?? 0) - job.elapsedSeconds);
|
||||
}
|
||||
const startOn = (type: string) => {
|
||||
let best = -1;
|
||||
lanes.forEach((lane, index) => {
|
||||
if (laneTakes(lane, type) && (best < 0 || free[index] < free[best])) best = index;
|
||||
});
|
||||
return best;
|
||||
};
|
||||
for (const type of view.ahead) {
|
||||
const slot = startOn(type);
|
||||
if (slot < 0) continue;
|
||||
const seconds = average(type);
|
||||
if (seconds === null) known = false;
|
||||
free[slot] += seconds ?? 0;
|
||||
}
|
||||
const own = startOn(ownType);
|
||||
return {
|
||||
ahead: view.ahead.length,
|
||||
startsInSeconds: known && own >= 0 ? Math.round(free[own]) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The line under the waiting step: only the wait, never how many reports are
|
||||
* ahead (product 2026-11-05: 「不要写前面还有几份报告,就说等待时间就行」).
|
||||
*/
|
||||
export function reportQueueLine(estimate: ReportQueueEstimate | null): string | null {
|
||||
if (!estimate) return null;
|
||||
if (estimate.startsInSeconds === null) return estimate.ahead === 0 ? "马上开始。" : "正在排队。";
|
||||
if (estimate.startsInSeconds <= 60) return "马上开始。";
|
||||
return `大约等 ${Math.ceil(estimate.startsInSeconds / 60)} 分钟开始。`;
|
||||
}
|
||||
|
||||
type QueueRpcClient = Readonly<{
|
||||
rpc(name: "personal_report_queue_view", args: Readonly<{ p_job_id: string }>): PromiseLike<{ data: unknown; error: unknown }>;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* The queue line for one waiting report, read with the service role after the
|
||||
* caller has checked the report is the user's own. Any failure gives null: the
|
||||
* waiting screen then simply shows no queue line.
|
||||
*/
|
||||
export async function loadReportQueue(
|
||||
admin: QueueRpcClient,
|
||||
jobId: string,
|
||||
reportType: string,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
): Promise<{ ahead: number; startsInSeconds: number | null; line: string } | null> {
|
||||
try {
|
||||
const { data, error } = await admin.rpc("personal_report_queue_view", { p_job_id: jobId });
|
||||
if (error) return null;
|
||||
const view = parseReportQueueView(data);
|
||||
if (!view) return null;
|
||||
const estimate = estimateReportQueue(view, reportType, reportWorkerLanes(readReportWorkerConcurrency(environment)));
|
||||
const line = reportQueueLine(estimate);
|
||||
return estimate && line ? { ahead: estimate.ahead, startsInSeconds: estimate.startsInSeconds, line } : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
begin;
|
||||
|
||||
-- Report queue lanes and queue position (product 2026-11-05: 「年报和报告做成
|
||||
-- 任务队列,多用户同时使用的时候排一下队」).
|
||||
--
|
||||
-- Every report type (personal_full / personal_thematic, synastry_full,
|
||||
-- annual_full) already goes through personal_report_jobs, one job at a time
|
||||
-- per server. The worker now runs a few lanes at once; a lane may take only
|
||||
-- some report types, so a short annual or synastry report is never stuck
|
||||
-- behind long personal reports. claim_personal_report_job gains an optional
|
||||
-- p_report_types filter (null = any type, the old behaviour). The old
|
||||
-- three-argument signature is dropped so positional calls with three
|
||||
-- arguments resolve to the new function and keep working.
|
||||
--
|
||||
-- personal_report_queue_view gives one job's place in the queue: the types of
|
||||
-- the jobs that will be claimed before it, the jobs running now with how long
|
||||
-- they have run, and the recent average run time per type. Security definer so
|
||||
-- it can count other people's jobs; it answers only the job's own user
|
||||
-- (auth.uid()) and returns report types and times, never another user's
|
||||
-- identifiers. The report route calls it with the user's own client.
|
||||
|
||||
drop function if exists public.claim_personal_report_job(text, integer, uuid);
|
||||
|
||||
create or replace function public.claim_personal_report_job(
|
||||
p_worker_id text,
|
||||
p_lease_seconds integer default 60,
|
||||
p_job_id uuid default null,
|
||||
p_report_types text[] default null
|
||||
)
|
||||
returns setof public.personal_report_jobs
|
||||
language plpgsql
|
||||
set search_path = pg_catalog, public
|
||||
as $$
|
||||
declare
|
||||
v_job_id uuid;
|
||||
begin
|
||||
if p_worker_id is null or length(btrim(p_worker_id)) not between 1 and 128 then
|
||||
raise exception using errcode = '22023', message = 'personal_report_job_worker_invalid';
|
||||
end if;
|
||||
if p_lease_seconds not between 5 and 3600 then
|
||||
raise exception using errcode = '22023', message = 'personal_report_job_lease_seconds_invalid';
|
||||
end if;
|
||||
|
||||
select job.id
|
||||
into v_job_id
|
||||
from public.personal_report_jobs as job
|
||||
where (p_job_id is null or job.id = p_job_id)
|
||||
and job.status in ('queued', 'retrying')
|
||||
and (job.next_attempt_at is null or job.next_attempt_at <= clock_timestamp())
|
||||
and job.attempt_count < job.max_attempts
|
||||
and (
|
||||
p_report_types is null
|
||||
or exists (
|
||||
select 1
|
||||
from public.personal_reports as report
|
||||
where report.user_id = job.user_id
|
||||
and report.request_id = job.request_id
|
||||
and report.report_type = any(p_report_types)
|
||||
)
|
||||
)
|
||||
order by job.next_attempt_at nulls first, job.created_at, job.id
|
||||
for update skip locked
|
||||
limit 1;
|
||||
|
||||
if v_job_id is null then
|
||||
return;
|
||||
end if;
|
||||
|
||||
return query
|
||||
update public.personal_report_jobs as job
|
||||
set status = 'running',
|
||||
attempt_count = job.attempt_count + 1,
|
||||
lease_token = gen_random_uuid(),
|
||||
lease_owner = btrim(p_worker_id),
|
||||
lease_acquired_at = clock_timestamp(),
|
||||
lease_expires_at = clock_timestamp() + make_interval(secs => p_lease_seconds),
|
||||
heartbeat_at = clock_timestamp(),
|
||||
next_attempt_at = null,
|
||||
progress_phase = case
|
||||
when job.attempt_count = 0 then 'starting'
|
||||
else 'retry_starting'
|
||||
end,
|
||||
started_at = coalesce(job.started_at, clock_timestamp())
|
||||
where job.id = v_job_id
|
||||
returning job.*;
|
||||
end;
|
||||
$$;
|
||||
|
||||
revoke all on function public.claim_personal_report_job(text, integer, uuid, text[]) from public, anon, authenticated;
|
||||
grant execute on function public.claim_personal_report_job(text, integer, uuid, text[]) to service_role;
|
||||
|
||||
create or replace function public.personal_report_queue_view(p_job_id uuid)
|
||||
returns jsonb
|
||||
language plpgsql
|
||||
stable
|
||||
security definer
|
||||
set search_path = ''
|
||||
as $$
|
||||
declare
|
||||
owner uuid := (select auth.uid());
|
||||
result jsonb;
|
||||
begin
|
||||
-- Only the job's own user may ask; the answer counts other people's jobs but
|
||||
-- names only their report types and run times.
|
||||
if owner is null then
|
||||
return null;
|
||||
end if;
|
||||
if not exists (
|
||||
select 1 from public.personal_report_jobs as job
|
||||
where job.id = p_job_id and job.user_id = owner
|
||||
) then
|
||||
return null;
|
||||
end if;
|
||||
|
||||
with me as (
|
||||
select job.id, job.status, job.next_attempt_at, job.created_at
|
||||
from public.personal_report_jobs as job
|
||||
where job.id = p_job_id
|
||||
),
|
||||
typed as (
|
||||
select job.id, job.status, job.attempt_count, job.max_attempts, job.next_attempt_at,
|
||||
job.created_at, job.started_at, job.finished_at, job.lease_acquired_at, report.report_type
|
||||
from public.personal_report_jobs as job
|
||||
join public.personal_reports as report
|
||||
on report.user_id = job.user_id and report.request_id = job.request_id
|
||||
),
|
||||
ahead as (
|
||||
select typed.report_type, typed.next_attempt_at, typed.created_at, typed.id
|
||||
from typed, me
|
||||
where typed.status in ('queued', 'retrying')
|
||||
and typed.attempt_count < typed.max_attempts
|
||||
and typed.id <> me.id
|
||||
and (coalesce(typed.next_attempt_at, '-infinity'::timestamptz), typed.created_at, typed.id)
|
||||
< (coalesce(me.next_attempt_at, '-infinity'::timestamptz), me.created_at, me.id)
|
||||
),
|
||||
running as (
|
||||
select typed.report_type,
|
||||
greatest(0, extract(epoch from pg_catalog.clock_timestamp() - coalesce(typed.lease_acquired_at, typed.started_at, pg_catalog.clock_timestamp())))::integer as elapsed_seconds
|
||||
from typed
|
||||
where typed.status = 'running'
|
||||
),
|
||||
averages as (
|
||||
select typed.report_type,
|
||||
round(avg(extract(epoch from typed.finished_at - typed.started_at)))::integer as seconds,
|
||||
count(*)::integer as samples
|
||||
from typed
|
||||
where typed.status = 'ready'
|
||||
and typed.started_at is not null
|
||||
and typed.finished_at > pg_catalog.clock_timestamp() - interval '14 days'
|
||||
group by typed.report_type
|
||||
)
|
||||
select jsonb_build_object(
|
||||
'status', (select me.status from me),
|
||||
'ahead', coalesce((select jsonb_agg(ahead.report_type order by ahead.next_attempt_at nulls first, ahead.created_at, ahead.id) from ahead), '[]'::jsonb),
|
||||
'running', coalesce((select jsonb_agg(jsonb_build_object('type', running.report_type, 'elapsedSeconds', running.elapsed_seconds)) from running), '[]'::jsonb),
|
||||
'averages', coalesce((select jsonb_object_agg(averages.report_type, jsonb_build_object('seconds', averages.seconds, 'samples', averages.samples)) from averages), '{}'::jsonb)
|
||||
) into result;
|
||||
return result;
|
||||
end;
|
||||
$$;
|
||||
|
||||
revoke all on function public.personal_report_queue_view(uuid) from public, anon;
|
||||
grant execute on function public.personal_report_queue_view(uuid) to authenticated, service_role;
|
||||
|
||||
commit;
|
||||
@@ -702,12 +702,9 @@ test("core create: 409 when a generation is already in progress", async () => {
|
||||
assert.equal(response.body.code, "report_generation_in_progress");
|
||||
});
|
||||
|
||||
// 原值:所有报告到每日上限就 429;新值:付点数的报告没有每日上限,只有没接计费的部署才数
|
||||
// 原因:产品 2026-11-05「每一份用户都掏钱为什么要限制次数」(BUG-1641)
|
||||
test("core create: 429 at the daily limit only when the report is not billed", async () => {
|
||||
test("core create: 429 at the daily limit only when the report is not billed (BUG-1641)", async () => {
|
||||
const response = await resolveReportCreate(baseDeps({
|
||||
billing: undefined,
|
||||
counts: { countGenerating: async () => 0, countCreatedToday: async () => 5 },
|
||||
billing: undefined, counts: { countGenerating: async () => 0, countCreatedToday: async () => 5 },
|
||||
}));
|
||||
assert.equal(response.status, 429);
|
||||
assert.equal(response.body.code, "report_rate_limited");
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
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,
|
||||
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, ...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 } } }),
|
||||
{ status: "queued", ahead: ["annual_full"], running: [{ type: "x", elapsedSeconds: 0 }], averages: {} });
|
||||
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.p_report_types), [["annual_full", "synastry_full"], null]);
|
||||
});
|
||||
|
||||
test("migration: the claim filter, the dropped three-argument claim, and an owner-only queue view", () => {
|
||||
const sql = read("../supabase/migrations/20261105010000_personal_report_job_lanes.sql");
|
||||
assert.match(sql, /drop function if exists public\.claim_personal_report_job\(text, integer, uuid\);/);
|
||||
assert.match(sql, /p_report_types text\[\] default null/);
|
||||
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\(text, integer, uuid, text\[\]\) from public, anon, authenticated/);
|
||||
assert.match(sql, /grant execute on function public\.claim_personal_report_job\(text, integer, uuid, 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/);
|
||||
});
|
||||
Reference in New Issue
Block a user