Files
Jyotisha/frontend/src/lib/report-queue.ts
T
ClaudeandClaude Opus 5.5 efceab8a2a
Independent Staging Quality Gate / validate-frontend (push) Failing after 4m38s
Independent Staging Quality Gate / validate-python (push) Successful in 6m35s
Independent Staging Quality Gate / publish (push) Skipped
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
2026-11-05 23:41:31 +08:00

163 lines
7.2 KiB
TypeScript

/**
* 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;
}
}