修复生产PostgreSQL高CPU与15秒超时热路径(迁移187)
This commit is contained in:
@@ -45,6 +45,12 @@ export async function runAffiliateFallback(
|
||||
basis_date: string
|
||||
}>(
|
||||
`
|
||||
WITH failed_affiliate_items AS (
|
||||
SELECT DISTINCT ft_fail.order_item_id
|
||||
FROM fulfillment_tasks ft_fail
|
||||
WHERE ft_fail.executor_key = 'affiliate_dash'
|
||||
AND ft_fail.task_status = ANY($1::text[])
|
||||
)
|
||||
SELECT
|
||||
oi.id,
|
||||
oi.id AS order_item_id,
|
||||
@@ -55,18 +61,20 @@ export async function runAffiliateFallback(
|
||||
cfg.id AS config_id,
|
||||
cfg.canonical_product_id AS config_product_id,
|
||||
(COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date::text AS basis_date
|
||||
FROM v_order_item_current oi
|
||||
FROM failed_affiliate_items fai
|
||||
JOIN fulfillments f
|
||||
ON f.order_item_id = fai.order_item_id
|
||||
AND f.status = 'assigned'
|
||||
AND f.channel = 'affiliate_dash'
|
||||
AND f.locked = FALSE
|
||||
JOIN order_items oi ON oi.id = f.order_item_id
|
||||
JOIN orders o ON o.id = oi.order_id
|
||||
LEFT JOIN manual_fulfillment_configs cfg
|
||||
JOIN manual_fulfillment_configs cfg
|
||||
ON canonicalize_internal_sku(cfg.sku_key) = resolve_internal_sku(
|
||||
oi.manual_sku_key, oi.sku_name, oi.sku_code
|
||||
)
|
||||
AND cfg.enabled
|
||||
WHERE oi.fulfillment_status = 'assigned'
|
||||
AND oi.fulfillment_channel = 'affiliate_dash'
|
||||
AND oi.fulfillment_locked = FALSE
|
||||
AND cfg.id IS NOT NULL
|
||||
AND EXISTS (
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM sku_channel_routes route
|
||||
JOIN internal_skus sku ON sku.id = route.internal_sku_id
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -140,3 +140,56 @@ test('新单快速推进只处理 actionable 履约桶', () => {
|
||||
assert.ok(advance.includes('reconcilePendingCarriers'))
|
||||
assert.ok(!advance.includes('includeNonActionable'))
|
||||
})
|
||||
|
||||
test('热路径数据库优化迁移 187 与对应仓储查询守卫生效', () => {
|
||||
const migration187 = source('../../db/migrations/187_order_site_hotpath_optimization.sql')
|
||||
const taskRepo = source('../../repositories/task-repo.ts')
|
||||
const affiliateFallback = source('./affiliate-fallback-service.ts')
|
||||
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
|
||||
const manualConfig = source('../cost-center/manual-fulfillment-config-service.ts')
|
||||
const workOrderQueryRepo = source('../../repositories/worker-platform/work-order-query-repo.ts')
|
||||
const adminNotificationService = source('../admin/admin-notification-service.ts')
|
||||
const workerHallService = source('../worker-platform/worker-hall-service.ts')
|
||||
|
||||
assert.ok(migration187.includes('idx_fulfillment_tasks_affiliate_dash_order_no'))
|
||||
assert.ok(migration187.includes('idx_fulfillment_tasks_kuaishou_feifei_platform_order_no'))
|
||||
assert.ok(migration187.includes('idx_fulfillment_tasks_affiliate_failed_item'))
|
||||
assert.ok(migration187.includes('idx_fulfillments_assigned_manual_configured'))
|
||||
assert.ok(migration187.includes('idx_orders_shop_name_trimmed_id_desc'))
|
||||
assert.ok(migration187.includes('idx_admin_notifications_visible_pending_rank'))
|
||||
assert.ok(migration187.includes('idx_work_orders_leaderboard_accepted'))
|
||||
|
||||
const jsonLookup = taskRepo.slice(
|
||||
taskRepo.indexOf('async function findExecutorTaskByJsonKeys'),
|
||||
taskRepo.indexOf('export async function findKuaishouFeifeiTaskByOrder'),
|
||||
)
|
||||
assert.ok(jsonLookup.includes('UNION ALL'))
|
||||
assert.ok(!jsonLookup.includes(' OR '))
|
||||
|
||||
assert.ok(affiliateFallback.includes('WITH failed_affiliate_items AS'))
|
||||
assert.ok(!affiliateFallback.includes('FROM v_order_item_current oi'))
|
||||
|
||||
const carrierDispatchBody = financeJobs.slice(
|
||||
financeJobs.indexOf('export async function runCarrierDispatchJob'),
|
||||
financeJobs.indexOf('export async function runProductNormalizeJob'),
|
||||
)
|
||||
assert.ok(carrierDispatchBody.includes('WITH candidate_page AS'))
|
||||
assert.ok(carrierDispatchBody.includes('scanned_max_id'))
|
||||
assert.ok(!carrierDispatchBody.includes('FROM v_order_item_current oi'))
|
||||
assert.ok(
|
||||
!manualConfig
|
||||
.slice(manualConfig.indexOf('export async function rematchManualFulfillments'))
|
||||
.includes('FROM v_order_item_current oi'),
|
||||
)
|
||||
|
||||
const shopNamesBody = workOrderQueryRepo.slice(
|
||||
workOrderQueryRepo.indexOf('export async function listWorkOrderShopNames'),
|
||||
workOrderQueryRepo.indexOf('export async function countWorkOrders'),
|
||||
)
|
||||
assert.ok(shopNamesBody.includes('WITH RECURSIVE distinct_shops AS'))
|
||||
assert.ok(shopNamesBody.includes('ORDER BY BTRIM(o.shop_name) ASC, o.id DESC'))
|
||||
|
||||
assert.ok(adminNotificationService.includes('pendingNotificationsCache.getOrSet('))
|
||||
assert.ok(adminNotificationService.includes('pendingNotificationsCache.clear()'))
|
||||
assert.ok(workerHallService.includes('HALL_ALL_LEADERBOARD_CACHE_TTL_MS'))
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user