fix(报告推送): 补核查影响——分拣/出库来源也入队(否则报告最多晚 24h)、僵尸任务收口告警、队列表分公司隔离 RLS + 按分公司处理
This commit is contained in:
@@ -53,7 +53,19 @@
|
||||
> `inconsistent types deduced for parameter $2` ⇒ 队列行永远不更新、`attempts` 停在 0。已改为显式定型
|
||||
> (`status = $2::varchar` / `CASE WHEN $2::text = 'done'`)。
|
||||
|
||||
## 4. 未做 / 后续
|
||||
## 4. 影响核查后的补强(2026-10-24 当天)
|
||||
|
||||
开发者要求"核查会不会影响实际使用"后,核查出 3 项并已补:
|
||||
|
||||
| # | 核查出的影响 | 补法 | 验证 |
|
||||
|---|---|---|---|
|
||||
| 1 | 报告候选的**两个来源**(分拣手选批次计划、`picking_out` / `delivery_loading_out` 出库流水)都不在入队点 ⇒ 报告会从 ≤15 分钟延迟到**每日兜底(≤24h)** | 在 **分拣保存**(`pickingService.updatePickingItemProgress`)、**分拣完成出库**(`orderWorkflowFulfillmentService`)、**发车核货出库**(`inventoryOutboundService`)三处按 `our_order_code` 入队 | 契约测试 3 条断言 + 真库队列链路(入队幂等、worker 到 done) |
|
||||
| 3 | `attempts >= 5` 的 pending 任务成为**僵尸**(永不再处理且无告警) | 新增 `failExhaustedReportPushTasks()`:置 `failed` + `console.warn` 列明细;每轮每分公司先跑一次 | 真库:造 `attempts=5` 行 → 收口 1 条,`status=failed` 保留 `last_error` |
|
||||
| 6 | 队列表在 `public` 且**无 RLS**,租户角色可读写跨分公司行 | 迁移 `20261076`:`ENABLE + FORCE ROW LEVEL SECURITY`,策略=有 `app.branch_code` 上下文时只能看/改本分公司;空上下文(调度/运维)放行;调度改 `processReportPushQueueForAllBranches()`(每分公司在 `runWithTenantDbContext` 里处理) | 真库:BR002 上下文只见 BR002;**跨分支写入被拒**(`violates row-level security policy`);无上下文可见全部 |
|
||||
|
||||
仍**未做**:`statement_timeout`/每轮总预算;退货跟随的增量水位(见下)。
|
||||
|
||||
## 5. 未做 / 后续
|
||||
|
||||
1. **`statement_timeout` 与"每轮总预算"** 尚未加(队列化后单轮已很小,但仍建议给全量兜底加 30s 超时)。
|
||||
2. 退货跟随(60 秒 × 每分公司)仍是按分公司循环;规模上来后建议按 `updated_at` 增量 + 提高并发/预算。
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
-- 报告推送队列:**分公司隔离**(2026-10-24 核查项 6)
|
||||
--
|
||||
-- 背景:`public.main_system_report_push_queue` 建表时没有 RLS,而租户角色 `canteen_app_rls`
|
||||
-- 默认拿到 INSERT/SELECT/UPDATE/DELETE ⇒ 租户连接理论上能读写**其它分公司**的队列行。
|
||||
-- 队列本身不含敏感业务数据,但按本项目"schema 级隔离"纪律应当收口。
|
||||
--
|
||||
-- 口径:
|
||||
-- · 有租户上下文(`app.branch_code` 非空)⇒ 只能看/改自己分公司的行;
|
||||
-- · 无租户上下文(调度器 / 运维 / 主系统对账)⇒ 放行(否则 worker 跨分公司处理会被拦死);
|
||||
-- · 用 FORCE 让表 owner 也受限(本项目核心表同款作风),策略里对空上下文开白。
|
||||
|
||||
ALTER TABLE public.main_system_report_push_queue ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.main_system_report_push_queue FORCE ROW LEVEL SECURITY;
|
||||
|
||||
DROP POLICY IF EXISTS report_push_queue_branch_isolation ON public.main_system_report_push_queue;
|
||||
CREATE POLICY report_push_queue_branch_isolation ON public.main_system_report_push_queue
|
||||
USING (
|
||||
COALESCE(current_setting('app.branch_code', true), '') = ''
|
||||
OR branch_code = current_setting('app.branch_code', true)
|
||||
)
|
||||
WITH CHECK (
|
||||
COALESCE(current_setting('app.branch_code', true), '') = ''
|
||||
OR branch_code = current_setting('app.branch_code', true)
|
||||
);
|
||||
@@ -1153,6 +1153,23 @@ export async function backfillDeliveryLoadingOutboundForOrder(
|
||||
|
||||
await consumeReservationsForOrder(client, code);
|
||||
await client.query('COMMIT');
|
||||
/**
|
||||
* **事件驱动报告推送**(2026-10-24 核查项 1):发车核货出库(`delivery_loading_out`)是报告候选源②,
|
||||
* 这一刻才知道实际消耗的批次 ⇒ 入队这一单,别等每日全量兜底。失败不影响出库。
|
||||
*/
|
||||
try {
|
||||
const { enqueueReportPush } = await import('./reportPushQueueService');
|
||||
if (branchCode) {
|
||||
await enqueueReportPush({
|
||||
branchCode: String(branchCode),
|
||||
kind: 'register' as const,
|
||||
ourOrderCode: code,
|
||||
reason: '发车核货出库(delivery_loading_out)',
|
||||
});
|
||||
}
|
||||
} catch (queueError) {
|
||||
console.warn('[outbound] 报告推送入队失败(忽略):', (queueError as Error)?.message || queueError);
|
||||
}
|
||||
return {
|
||||
order_code: code,
|
||||
branch_code: branchCode,
|
||||
|
||||
@@ -220,6 +220,21 @@ export async function tryAdvanceOrderToDelivery(orderCode: string): Promise<{ ad
|
||||
// 用 delivery_loading_out 会被它误加回来 ⇒ 后续发车又被幂等守卫挡住 ⇒ 净漏扣(见函数注释)
|
||||
operationType: 'picking_out',
|
||||
});
|
||||
/**
|
||||
* **事件驱动报告推送**(2026-10-24 核查项 1):分拣完成=出库=扣批次,
|
||||
* 这一刻才知道这单实际消耗哪些批次(报告候选源②)⇒ 入队这一单,别等每日全量兜底。
|
||||
*/
|
||||
try {
|
||||
const { enqueueReportPush } = await import('./reportPushQueueService');
|
||||
await enqueueReportPush({
|
||||
branchCode,
|
||||
kind: 'register',
|
||||
ourOrderCode: orderCode,
|
||||
reason: '分拣完成出库(picking_out)',
|
||||
});
|
||||
} catch (queueError) {
|
||||
console.warn('[picking-outbound] 报告推送入队失败(忽略):', (queueError as Error)?.message || queueError);
|
||||
}
|
||||
/**
|
||||
* **软扣缺口必须被看见**(2026-10-14 审计 P0-3):库存不足的行不会拦「进入待配送」,
|
||||
* 但以前连日志都不留(`softSkipped` 算了没人读)⇒ 账面虚高且无人知道。
|
||||
|
||||
@@ -917,14 +917,19 @@ export async function updatePickingItemProgress(input: {
|
||||
rows: PickingProgressRow[];
|
||||
}) {
|
||||
const client = await pool.connect();
|
||||
/** 分拣保存可能写入"实际消耗的批次计划" ⇒ 报告候选在这一刻才成立,提交后入队(2026-10-24 核查项 1) */
|
||||
let queueTarget: { branchCode: string; orderCode: string } | null = null;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const taskResult = await client.query(
|
||||
`SELECT pick_status FROM picking_tasks WHERE pick_code = $1 FOR UPDATE`,
|
||||
`SELECT pick_status, order_code, branch_code FROM picking_tasks WHERE pick_code = $1 FOR UPDATE`,
|
||||
[input.pickCode]
|
||||
);
|
||||
const task = taskResult.rows[0];
|
||||
if (!task) throw Object.assign(new Error('分拣任务不存在'), { status: 404 });
|
||||
if (task.order_code && task.branch_code) {
|
||||
queueTarget = { branchCode: String(task.branch_code), orderCode: String(task.order_code) };
|
||||
}
|
||||
if (Number(task.pick_status) >= 40) {
|
||||
throw Object.assign(new Error('该单已出库,无法继续改量'), { status: 400 });
|
||||
}
|
||||
@@ -997,6 +1002,20 @@ export async function updatePickingItemProgress(input: {
|
||||
);
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
/** 提交后入队(尽力而为,失败不影响分拣保存):本单消耗的批次可能刚被确定 ⇒ 报告候选成立了 */
|
||||
if (queueTarget) {
|
||||
try {
|
||||
const { enqueueReportPush } = await import('./reportPushQueueService');
|
||||
await enqueueReportPush({
|
||||
branchCode: queueTarget.branchCode,
|
||||
kind: 'register',
|
||||
ourOrderCode: queueTarget.orderCode,
|
||||
reason: '分拣保存/批次计划更新',
|
||||
});
|
||||
} catch (queueError) {
|
||||
console.warn('[picking] 报告推送入队失败(忽略):', (queueError as Error)?.message || queueError);
|
||||
}
|
||||
}
|
||||
return { hasDiff };
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
|
||||
@@ -124,6 +124,35 @@ export async function markReportPushTask(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* **失败任务收口**(2026-10-24 核查项 3):`claimPendingReportPushTasks` 只取 `attempts < 5`,
|
||||
* 否则任务会静默停留在 pending、永远不再被处理且没人知道。
|
||||
* 这里把"重试用尽"的任务显式转 `failed`(保留 last_error 供排查)并打告警日志。
|
||||
*/
|
||||
export async function failExhaustedReportPushTasks(input: { branchCode?: string | null } = {}): Promise<number> {
|
||||
const branchCode = trim(input.branchCode) || null;
|
||||
try {
|
||||
const res = await pool.query<{ id: string; branch_code: string; kind: string; last_error: string | null }>(
|
||||
`UPDATE public.main_system_report_push_queue
|
||||
SET status = 'failed', updated_at = NOW()
|
||||
WHERE status = 'pending' AND attempts >= 5
|
||||
AND ($1::text IS NULL OR branch_code = $1)
|
||||
RETURNING id::text, branch_code, kind, last_error`,
|
||||
[branchCode]
|
||||
);
|
||||
if (res.rowCount) {
|
||||
console.warn(
|
||||
`[report-push-queue] ⚠️ ${res.rowCount} 条任务重试已用尽(上限 5)⇒ 置 failed 待人工处理:` +
|
||||
res.rows.map((r) => `${r.branch_code}/${r.kind}#${r.id}`).join('、')
|
||||
);
|
||||
}
|
||||
return res.rowCount || 0;
|
||||
} catch (error) {
|
||||
console.warn('[report-push-queue] 失败任务收口异常(忽略):', (error as Error)?.message || error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export interface QueueProcessSummary {
|
||||
claimed: number;
|
||||
done: number;
|
||||
@@ -132,6 +161,35 @@ export interface QueueProcessSummary {
|
||||
}
|
||||
|
||||
/** worker:处理队列(按分支可选)。真正推送复用 `mainSystemReportPushService` 的既有推送函数。 */
|
||||
/**
|
||||
* **按分公司**处理队列(2026-10-24 核查项 6:队列表在 public,需要分支隔离)。
|
||||
* 每个分公司都在 `runWithTenantDbContext` 里处理 ⇒ SQL 只可能命中自己的行(配合迁移 20261076 的 RLS 策略)。
|
||||
*/
|
||||
export async function processReportPushQueueForAllBranches(limitPerBranch = 50): Promise<QueueProcessSummary> {
|
||||
const summary: QueueProcessSummary = { claimed: 0, done: 0, failed: 0, skipped: 0 };
|
||||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||||
const branches = await pool.query<{ branch_code: string }>(
|
||||
`SELECT branch_code FROM public.branches WHERE COALESCE(status, 1) = 1 ORDER BY branch_code`
|
||||
);
|
||||
for (const row of branches.rows) {
|
||||
const code = String(row.branch_code || '').trim();
|
||||
if (!code) continue;
|
||||
try {
|
||||
const part = await runWithTenantDbContext(code, async () => {
|
||||
await failExhaustedReportPushTasks({ branchCode: code });
|
||||
return processReportPushQueue({ branchCode: code, limit: limitPerBranch });
|
||||
});
|
||||
summary.claimed += part.claimed;
|
||||
summary.done += part.done;
|
||||
summary.failed += part.failed;
|
||||
summary.skipped += part.skipped;
|
||||
} catch (error) {
|
||||
console.warn(`[report-push-queue] ${code} 处理失败(继续其它分公司):`, (error as Error)?.message || error);
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
/** 进程内在途互斥:上一轮没跑完就跳过本轮(防"慢轮 + 下一 tick"叠罗汉) */
|
||||
let queueRunning = false;
|
||||
|
||||
|
||||
@@ -507,8 +507,12 @@ function chinaTodayKey(): string {
|
||||
|
||||
async function runReportPushReconcile() {
|
||||
try {
|
||||
const { processReportPushQueue } = await import('./reportPushQueueService');
|
||||
const queued = await processReportPushQueue({ limit: 200 });
|
||||
/**
|
||||
* 按分公司处理(每个分公司在租户上下文里 ⇒ 只可能命中自己的队列行;配合迁移 20261076 的 RLS)。
|
||||
* 每分公司 ≤50 条/轮,避免"几百家 × 大批量"在一轮里堆出长尾。
|
||||
*/
|
||||
const { processReportPushQueueForAllBranches } = await import('./reportPushQueueService');
|
||||
const queued = await processReportPushQueueForAllBranches(50);
|
||||
if (queued.claimed) {
|
||||
console.log(
|
||||
`[scheduler] 报告推送队列:认领 ${queued.claimed}、完成 ${queued.done}、待重试 ${queued.failed}、跳过 ${queued.skipped}`
|
||||
|
||||
@@ -15,6 +15,13 @@ const push = readFileSync(new URL('../src/services/mainSystemReportPushService.t
|
||||
const report = readFileSync(new URL('../src/services/inventoryBatchReportService.ts', import.meta.url), 'utf8');
|
||||
const scheduler = readFileSync(new URL('../src/services/scheduledJobs.ts', import.meta.url), 'utf8');
|
||||
const importer = readFileSync(new URL('../src/services/mainSystemOrderImport.ts', import.meta.url), 'utf8');
|
||||
const picking = readFileSync(new URL('../src/services/pickingService.ts', import.meta.url), 'utf8');
|
||||
const fulfillment = readFileSync(new URL('../src/services/orderWorkflowFulfillmentService.ts', import.meta.url), 'utf8');
|
||||
const outbound = readFileSync(new URL('../src/services/inventoryOutboundService.ts', import.meta.url), 'utf8');
|
||||
const isolationMigration = readFileSync(
|
||||
new URL('../../migrations/20261076_report_push_queue_branch_isolation.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const migration = readFileSync(
|
||||
new URL('../../migrations/20261075_report_push_queue_and_indexes.sql', import.meta.url),
|
||||
'utf8'
|
||||
@@ -55,7 +62,7 @@ describe('报告推送队列', () => {
|
||||
|
||||
it('调度:平时只处理队列,全量扫描降为每日一次兜底', () => {
|
||||
expect(scheduler).toContain("import('./reportPushQueueService')");
|
||||
expect(scheduler).toContain('processReportPushQueue({ limit: 200 })');
|
||||
expect(scheduler).toContain('processReportPushQueueForAllBranches(50)');
|
||||
expect(scheduler).toContain('lastReportFullSweepDay');
|
||||
});
|
||||
|
||||
@@ -63,4 +70,25 @@ describe('报告推送队列', () => {
|
||||
expect(queue).toContain("SET status = $2::varchar");
|
||||
expect(queue).toContain("CASE WHEN $2::text = 'done'");
|
||||
});
|
||||
|
||||
it('候选来源也会入队:分拣保存 / 分拣完成出库 / 发车出库(核查项 1)', () => {
|
||||
expect(picking).toContain("reason: '分拣保存/批次计划更新'");
|
||||
expect(fulfillment).toContain('分拣完成出库(picking_out)');
|
||||
expect(outbound).toContain('发车核货出库(delivery_loading_out)');
|
||||
});
|
||||
|
||||
it('僵尸任务收口:重试用尽 → failed 并告警(核查项 3)', () => {
|
||||
expect(queue).toContain('export async function failExhaustedReportPushTasks');
|
||||
expect(queue).toContain("SET status = 'failed'");
|
||||
expect(queue).toContain('重试已用尽');
|
||||
});
|
||||
|
||||
it('按分公司处理队列 + 分支隔离 RLS(核查项 6)', () => {
|
||||
expect(queue).toContain('export async function processReportPushQueueForAllBranches');
|
||||
expect(queue).toContain('runWithTenantDbContext');
|
||||
expect(scheduler).toContain('processReportPushQueueForAllBranches(50)');
|
||||
expect(isolationMigration).toContain('ENABLE ROW LEVEL SECURITY');
|
||||
expect(isolationMigration).toContain('FORCE ROW LEVEL SECURITY');
|
||||
expect(isolationMigration).toContain("current_setting('app.branch_code', true)");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user