修复生产PostgreSQL高CPU与15秒超时热路径(迁移187)

This commit is contained in:
yml
2026-11-28 19:50:46 +08:00
parent 2ec5ff7af5
commit f68dc7c217
12 changed files with 735 additions and 203 deletions
@@ -265,3 +265,220 @@ test(
}
},
)
test(
'迁移 187 回调 JSONB 反查、店铺名松散索引、待办通知排序与 carrier_dispatch 游标推进',
{ skip: !TEST_DATABASE_URL ? '未设置 CARRIER_DISPATCH_TEST_DATABASE_URL' : false },
async () => {
process.env.DATABASE_URL = TEST_DATABASE_URL
const { closeDb, query } = await import('../../db/client.js')
const { findAffiliateDashTaskByOrder, findKuaishouFeifeiTaskByOrder } =
await import('../../repositories/task-repo.js')
const { listWorkOrderShopNames } =
await import('../../repositories/worker-platform/work-order-query-repo.js')
const { listAdminPendingNotifications, resolveAdminNotificationEntity } =
await import('../admin/admin-notification-service.js')
const { createAdminNotification } =
await import('../../repositories/admin-notification-repo.js')
const { runCarrierDispatchJob } = await import('../scheduler/finance-pipeline-jobs.js')
const { readWatermarkItemId, touchWatermark } = await import('../watermark-store.js')
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
let orderWithWoId = 0
let orderWithoutWoId = 0
let profileId = 0
let workOrderId = 0
const createdNotifIds: number[] = []
const originalDispatchCursor = await readWatermarkItemId('carrier_dispatch')
try {
const shopWithWo = `AAA_工单店铺_${suffix}`
const shopWithoutWo = `AAA_无工单店铺_${suffix}`
const orderWithWo = await query<{ id: number }>(
`INSERT INTO orders (
provider, platform, shop_id, shop_name, platform_order_id,
order_status, pay_status, total_amount, paid_at, created_at, updated_at
) VALUES (
'integration-test', 'integration-test', $1, $2, $3,
'paid', 'paid', 1000, NOW(), NOW(), NOW()
) RETURNING id`,
[`shop-wo-${suffix}`, shopWithWo, `IT-HOTPATH-WO-${suffix}`],
)
orderWithWoId = Number(orderWithWo.rows[0]!.id)
const orderWithoutWo = await query<{ id: number }>(
`INSERT INTO orders (
provider, platform, shop_id, shop_name, platform_order_id,
order_status, pay_status, total_amount, paid_at, created_at, updated_at
) VALUES (
'integration-test', 'integration-test', $1, $2, $3,
'paid', 'paid', 1000, NOW(), NOW(), NOW()
) RETURNING id`,
[`shop-nowo-${suffix}`, shopWithoutWo, `IT-HOTPATH-NOWO-${suffix}`],
)
orderWithoutWoId = Number(orderWithoutWo.rows[0]!.id)
const item1 = await query<{ id: number }>(
`INSERT INTO order_items (
order_id, sku_code, sku_name, quantity, created_at, updated_at
) VALUES ($1, $2, $2, 1, NOW(), NOW())
RETURNING id`,
[orderWithWoId, `热路径测试商品-${suffix}`],
)
const item1Id = Number(item1.rows[0]!.id)
const profile = await query<{ id: number }>(
`INSERT INTO fulfillment_profiles (
profile_key, name, executor_key, requires_claim, auto_dispatch,
inventory_strategy, config_json, created_at, updated_at
) VALUES ($1, '热路径测试', 'affiliate_dash', TRUE, FALSE, 'static_pool', '{}'::jsonb, NOW(), NOW())
RETURNING id`,
[`it-hotpath-profile-${suffix}`],
)
profileId = Number(profile.rows[0]!.id)
await query(
`INSERT INTO fulfillment_tasks (
order_id, order_item_id, unit_index, task_no, provider, platform, shop_id, shop_name,
platform_order_id, profile_id, executor_key, task_status, context_json, created_at, updated_at
) VALUES (
$1, $2, 1, $3, 'affiliate', 'douyin', 's1', '店1', $4, $5, 'affiliate_dash', 'pending_payment',
jsonb_build_object('affiliateDash', jsonb_build_object('orderNo', $6::text, 'clientOrderNo', $7::text)),
NOW(), NOW()
)`,
[
orderWithWoId,
item1Id,
`IT-AFF-JSON-${suffix}`,
`IT-HOTPATH-WO-${suffix}`,
profileId,
`AFF-ORD-${suffix}`,
`AFF-CLI-${suffix}`,
],
)
await query(
`INSERT INTO fulfillment_tasks (
order_id, order_item_id, unit_index, task_no, provider, platform, shop_id, shop_name,
platform_order_id, profile_id, executor_key, task_status, context_json, created_at, updated_at
) VALUES (
$1, $2, 2, $3, 'kuaishou', 'kuaishou', 's2', '店2', $4, $5, 'kuaishou_feifei', 'pending_payment',
jsonb_build_object('kuaishouFeifei', jsonb_build_object('platformOrderNo', $6::text, 'orderNo', $7::text)),
NOW(), NOW()
)`,
[
orderWithWoId,
item1Id,
`IT-KS-JSON-${suffix}`,
`IT-HOTPATH-WO-${suffix}`,
profileId,
`KS-PLAT-${suffix}`,
`KS-ORD-${suffix}`,
],
)
const affByOrder = await findAffiliateDashTaskByOrder({ orderNo: `AFF-ORD-${suffix}` })
const affByClient = await findAffiliateDashTaskByOrder({ clientOrderNo: `AFF-CLI-${suffix}` })
const ksByPlatform = await findKuaishouFeifeiTaskByOrder({
platformOrderNo: `KS-PLAT-${suffix}`,
})
const ksByOrder = await findKuaishouFeifeiTaskByOrder({ orderNo: `KS-ORD-${suffix}` })
assert.equal(affByOrder?.task_no, `IT-AFF-JSON-${suffix}`)
assert.equal(affByClient?.task_no, `IT-AFF-JSON-${suffix}`)
assert.equal(ksByPlatform?.task_no, `IT-KS-JSON-${suffix}`)
assert.equal(ksByOrder?.task_no, `IT-KS-JSON-${suffix}`)
assert.equal(await findAffiliateDashTaskByOrder({ orderNo: '' }), null)
const wo = await query<{ id: number }>(
`INSERT INTO work_orders (
work_order_no, order_id, order_item_id, platform_order_id, product_name,
status, reward_amount, required_deposit_amount, created_at, updated_at
) VALUES ($1, $2, $3, $4, '热路径工单', 'open', 100, 0, NOW(), NOW())
RETURNING id`,
[`IT-WO-SHOP-${suffix}`, orderWithWoId, item1Id, `IT-HOTPATH-WO-${suffix}`],
)
workOrderId = Number(wo.rows[0]!.id)
const shops = await listWorkOrderShopNames()
assert.ok(shops.includes(shopWithWo))
assert.ok(!shops.includes(shopWithoutWo))
const normalNotif = await createAdminNotification({
notificationType: 'it_hotpath',
priority: 'normal',
entityType: 'it_hotpath_entity',
entityId: orderWithWoId,
dedupeKey: `it_hotpath_normal_${suffix}`,
title: `普通通知-${suffix}`,
body: 'body',
actionPath: '/',
now: new Date(Date.now() + 1000).toISOString(),
visible: true,
soundEnabled: false,
})
const urgentNotif = await createAdminNotification({
notificationType: 'it_hotpath',
priority: 'urgent',
entityType: 'it_hotpath_entity',
entityId: orderWithWoId,
dedupeKey: `it_hotpath_urgent_${suffix}`,
title: `紧急通知-${suffix}`,
body: 'body',
actionPath: '/',
now: new Date().toISOString(),
visible: true,
soundEnabled: false,
})
if (normalNotif) createdNotifIds.push(Number(normalNotif.id))
if (urgentNotif) createdNotifIds.push(Number(urgentNotif.id))
const pending = await listAdminPendingNotifications(50)
const urgentIdx = pending.items.findIndex(
(item) => item.notificationId === Number(urgentNotif?.id),
)
const normalIdx = pending.items.findIndex(
(item) => item.notificationId === Number(normalNotif?.id),
)
assert.ok(urgentIdx >= 0 && normalIdx >= 0 && urgentIdx < normalIdx)
await resolveAdminNotificationEntity('it_hotpath_entity', orderWithWoId, 'it_cleanup')
const afterResolve = await listAdminPendingNotifications(50)
assert.ok(!afterResolve.items.some((item) => item.notificationId === Number(urgentNotif?.id)))
// 验证 carrier_dispatch 在已分配记录全部已有异常(0 新增异常)时依然按扫描页推进游标
await query(
`UPDATE fulfillments
SET status = 'assigned', channel = 'work_order', source = 'integration_test', updated_at = NOW()
WHERE order_item_id = $1`,
[item1Id],
)
await touchWatermark('carrier_dispatch', { lastItemId: item1Id - 1 })
await runCarrierDispatchJob({ config: { limit: 1, afterId: item1Id - 1 } })
assert.ok((await readWatermarkItemId('carrier_dispatch')) >= item1Id)
} finally {
await touchWatermark('carrier_dispatch', { lastItemId: originalDispatchCursor }).catch(
() => undefined,
)
if (createdNotifIds.length > 0) {
await query('DELETE FROM admin_notifications WHERE id = ANY($1::bigint[])', [
createdNotifIds,
]).catch(() => undefined)
}
if (workOrderId > 0) {
await query('DELETE FROM work_orders WHERE id = $1', [workOrderId]).catch(() => undefined)
}
if (orderWithWoId > 0) {
await query('DELETE FROM orders WHERE id = $1', [orderWithWoId]).catch(() => undefined)
}
if (orderWithoutWoId > 0) {
await query('DELETE FROM orders WHERE id = $1', [orderWithoutWoId]).catch(() => undefined)
}
if (profileId > 0) {
await query('DELETE FROM fulfillment_profiles WHERE id = $1', [profileId]).catch(
() => undefined,
)
}
await closeDb()
}
},
)