fix(product-archive): isolate missing pictures from daily enrichment
Run ordinary archive fields without picture reads. Fill missing images in a separate daily job, retain current images under transaction locks, and query only requested SKUs with bounded transfers and separate checkpoints. (cherry picked from commit f0af16237b1844b6d2b11401c20f4ad8ca022545)
This commit is contained in:
parent
01658afe6b
commit
45ff5be452
@ -113,6 +113,15 @@
|
||||
- 首次安装生成权限为 `600` 的 `/opt/furniture-3d-system-prod/shared/product-sabc-timer.env`,默认 `PRODUCT_SABC_TIMER_MODE=APPLY`;如需先观察可临时改为 `PREVIEW`(只试算不写库、不冻结)。
|
||||
- SABC 自动任务只读取现有 `DATABASE_URL`;上游日销售同步任务继续使用 `JST_REPORT_DB_*`,凭据不写入定时器配置。安装、迁移、首次 APPLY 和生产核算都需要单独授权。
|
||||
|
||||
## 产品档案普通字段与图片同步
|
||||
|
||||
- `install-supply-chain-product-archive-sync-timer.sh` 安装两个独立任务:普通字段每天北京时间 08:10,缺图补齐每天 10:10。
|
||||
- 普通字段任务 `furniture-supply-chain-product-archive-sync.service` 不读取图片源,仍按基础档案、审批负责人、库存/价格等补充字段、产品类型顺序更新。
|
||||
- 图片任务 `furniture-supply-chain-product-archive-sync-pictures.service` 使用同一脚本的 `--pictures-only` 模式,只查询当前无图的条码;已有图的 DF 和普通条码都不进入补图目标。
|
||||
- 补图按三张平台图表各查询一次目标集合,不再向应用传输全表主键分页,也不追加 DF 全量分支。每张表完整传输最多 120 秒,成功来源独立保存;图片任务失败单独告警,不影响普通字段任务。
|
||||
- 图片写入在事务内再次核对当前图片为空,并保留字段来源及审计;图片查询期间人工上传的图片不会被补图覆盖。
|
||||
- 两个任务使用独立断点文件。新版本默认 run-key 含 `fields-v2` / `pictures-v1`,不复用旧版本不兼容的同日断点;显式复跑仍可指定新的 `--run-key`。
|
||||
|
||||
## 操作日志保留策略
|
||||
|
||||
- 清理脚本:`npm run db:cleanup-operation-logs` 默认只做 dry-run;只有显式传入 `--apply --confirm=cleanup-operation-logs` 才会删除数据。
|
||||
|
||||
@ -12,6 +12,8 @@ TIMER_FILE="/etc/systemd/system/$SERVICE_NAME.timer"
|
||||
SYNC_ON_BOOT_SEC="${SUPPLY_CHAIN_ARCHIVE_SYNC_ON_BOOT_SEC:-3min}"
|
||||
SYNC_INTERVAL="${SUPPLY_CHAIN_ARCHIVE_SYNC_INTERVAL:-15min}"
|
||||
SYNC_CALENDAR="${SUPPLY_CHAIN_ARCHIVE_SYNC_CALENDAR:-*-*-* 08:10:00 Asia/Shanghai}"
|
||||
PICTURE_SERVICE_NAME="$SERVICE_NAME-pictures"
|
||||
PICTURE_CALENDAR="${SUPPLY_CHAIN_ARCHIVE_PICTURE_CALENDAR:-*-*-* 10:10:00 Asia/Shanghai}"
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
echo "This installer must run as root." >&2
|
||||
@ -77,6 +79,40 @@ Unit=$SERVICE_NAME.service
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
|
||||
cat >"/etc/systemd/system/$PICTURE_SERVICE_NAME.service" <<EOF
|
||||
[Unit]
|
||||
Description=Fill missing product archive pictures independently of ordinary fields
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
WorkingDirectory=$APP_ROOT
|
||||
Environment=NODE_ENV=production
|
||||
Environment=PRODUCT_ARCHIVE_SYNC_FAILURE_NOTIFICATIONS=1
|
||||
EnvironmentFile=$APP_ENV
|
||||
EnvironmentFile=$SYNC_ENV
|
||||
TimeoutStartSec=10min
|
||||
ExecStart=/bin/bash -lc 'set -euo pipefail; cd "$APP_ROOT"; ./node_modules/.bin/tsx scripts/sync-supply-chain-product-archive-enrichment.ts --apply --pictures-only --confirm=sync-supply-chain-product-archive-enrichment --expected-database-identity="\${SUPPLY_CHAIN_ARCHIVE_EXPECTED_DATABASE_IDENTITY:?Set database identity in $SYNC_ENV}" --expected-source-database-identity="\${SUPPLY_CHAIN_ARCHIVE_EXPECTED_SOURCE_DATABASE_IDENTITY:?Set source identity in $SYNC_ENV}" --batch-size="\${SUPPLY_CHAIN_ARCHIVE_ENRICHMENT_BATCH_SIZE:-200}"'
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
EOF
|
||||
|
||||
cat >"/etc/systemd/system/$PICTURE_SERVICE_NAME.timer" <<EOF
|
||||
[Unit]
|
||||
Description=Fill missing product archive pictures daily at 10:10 Asia/Shanghai
|
||||
|
||||
[Timer]
|
||||
OnCalendar=$PICTURE_CALENDAR
|
||||
Persistent=true
|
||||
RandomizedDelaySec=60
|
||||
Unit=$PICTURE_SERVICE_NAME.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now "$SERVICE_NAME.timer"
|
||||
systemctl list-timers --all "$SERVICE_NAME.timer" --no-pager
|
||||
systemctl enable --now "$PICTURE_SERVICE_NAME.timer"
|
||||
systemctl list-timers --all "$SERVICE_NAME.timer" "$PICTURE_SERVICE_NAME.timer" --no-pager
|
||||
|
||||
@ -71,6 +71,8 @@ async function main() {
|
||||
throw new Error('--operator-only has been retired; js_sku_info_manage is no longer a product archive source.')
|
||||
}
|
||||
const opsDirectorOnly = process.argv.includes('--ops-director-only')
|
||||
const picturesOnly = process.argv.includes('--pictures-only')
|
||||
if (picturesOnly && (opsDirectorOnly || syncJstBase)) throw new Error('--pictures-only cannot be combined with base/owner-only sync.')
|
||||
const jstBatchSize = Number(readArgument('jst-batch-size') || '500')
|
||||
if (
|
||||
!Number.isSafeInteger(jstBatchSize) ||
|
||||
@ -94,7 +96,7 @@ async function main() {
|
||||
])
|
||||
try {
|
||||
const result = await runArchiveEnrichmentWithCheckpoint({ batchSize: batchSizeValue,
|
||||
jstBatchSize, jstConcurrency, syncJstBase, opsDirectorOnly, runKey: readArgument('run-key') || undefined })
|
||||
jstBatchSize, jstConcurrency, syncJstBase, opsDirectorOnly, picturesOnly, runKey: readArgument('run-key') || undefined })
|
||||
if ('ownerWorkflowResult' in result && result.ownerWorkflowResult) {
|
||||
console.log(JSON.stringify({ ...result, ownerWorkflowResult: {
|
||||
...result.ownerWorkflowResult, differences: undefined, unmatched: undefined,
|
||||
@ -107,7 +109,8 @@ async function main() {
|
||||
async function notifySyncFailure(error: unknown) {
|
||||
try {
|
||||
const { ARCHIVE_SYNC_FAILURE_TASKS, notifyArchiveSyncFailureSafely } = await import('../src/server/services/product-archive-sync-failure-notification.service')
|
||||
await notifyArchiveSyncFailureSafely(ARCHIVE_SYNC_FAILURE_TASKS.enrichment, error)
|
||||
await notifyArchiveSyncFailureSafely(process.argv.includes('--pictures-only')
|
||||
? ARCHIVE_SYNC_FAILURE_TASKS.pictures : ARCHIVE_SYNC_FAILURE_TASKS.enrichment, error)
|
||||
} catch {
|
||||
// 通知链路异常不影响同步任务的退出码
|
||||
}
|
||||
|
||||
@ -30,7 +30,9 @@ describe('run-scoped source queries', () => {
|
||||
})
|
||||
|
||||
it('keeps picture normalization with lossless compressed transport', () => {
|
||||
expect(pictureQuery('rpt', 'jst_skumap')).toContain('UPPER(LTRIM(RTRIM(CAST(s.sku_id AS varchar(200)))))')
|
||||
expect(pictureQuery('rpt', 'jst_skumap')).toContain('CAST(s.sku_id AS nvarchar(200))')
|
||||
expect(pictureQuery('rpt', 'jst_skumap')).toContain('NCHAR(8203)')
|
||||
expect(pictureQuery('rpt', 'jst_skumap')).not.toMatch(/UNION ALL|LIKE 'DF%'/)
|
||||
expect(pictureQuery('rpt', 'jst_skumap')).toContain('SELECT COMPRESS(')
|
||||
expect(pictureQuery('rpt', 'jst_skumap_pdd')).toContain('OPENJSON(@requested)')
|
||||
expect(pictureKeyPageQuery('rpt', true, 50000)).toContain('ORDER BY shop_id,shop_i_id,shop_sku_id')
|
||||
@ -102,8 +104,7 @@ describe('run-scoped source queries', () => {
|
||||
const previous = { ...process.env }
|
||||
Object.assign(process.env, { JST_REPORT_DB_HOST: 'test', JST_REPORT_DB_NAME: 'test', JST_REPORT_DB_USER: 'test', JST_REPORT_DB_PASSWORD: 'test' })
|
||||
const encode = (rows: unknown) => ({ recordset: [{ payload: gzipSync(Buffer.from(JSON.stringify(rows), 'utf16le')) }] })
|
||||
const query = jest.fn().mockResolvedValueOnce(encode([key(1, 'DF-1')]))
|
||||
.mockResolvedValueOnce(encode([{ skuId: 'DF-1', pic: 'main', sourceModifiedAt: '2026-10-20T12:00:00' }]))
|
||||
const query = jest.fn().mockResolvedValueOnce(encode([{ skuId: 'DF-1', pic: 'main', sourceModifiedAt: '2026-10-20T12:00:00' }]))
|
||||
.mockResolvedValueOnce(encode([{ skuId: 'DF-1', pic: 'latest', sourceModifiedAt: '2026-10-20T13:00:00' }]))
|
||||
.mockResolvedValueOnce(encode([{ skuId: 'DF-1', pic: '', sourceModifiedAt: '2026-10-20T14:00:00' }]))
|
||||
const request = { input: jest.fn().mockReturnThis(), query, cancel: jest.fn() }
|
||||
@ -113,9 +114,9 @@ describe('run-scoped source queries', () => {
|
||||
try {
|
||||
await expect(new ProductArchiveEnrichmentSourceSnapshotRepositoryClass().read('pictures', ['DF-1']))
|
||||
.resolves.toEqual([{ skuId: 'DF-1', pic: 'latest' }])
|
||||
expect(query).toHaveBeenCalledTimes(4)
|
||||
expect(query).toHaveBeenCalledTimes(3)
|
||||
expect(pool.close).toHaveBeenCalledTimes(1)
|
||||
query.mockReset().mockResolvedValueOnce(encode([key(1, 'DF-1')])).mockRejectedValueOnce(new Error('SOURCE_FAILED'))
|
||||
query.mockReset().mockResolvedValueOnce(encode([])).mockRejectedValueOnce(new Error('SOURCE_FAILED'))
|
||||
await expect(new ProductArchiveEnrichmentSourceSnapshotRepositoryClass().read('pictures', ['DF-1'])).rejects.toThrow('SOURCE_FAILED')
|
||||
expect(pool.close).toHaveBeenCalledTimes(2)
|
||||
} finally { process.env = previous; log.mockRestore() }
|
||||
@ -144,8 +145,7 @@ describe('run-scoped source queries', () => {
|
||||
const previous = { ...process.env }
|
||||
Object.assign(process.env, { JST_REPORT_DB_HOST: 'test', JST_REPORT_DB_NAME: 'test', JST_REPORT_DB_USER: 'test', JST_REPORT_DB_PASSWORD: 'test' })
|
||||
const encode = (rows: unknown) => ({ recordset: [{ payload: gzipSync(Buffer.from(JSON.stringify(rows), 'utf16le')) }] })
|
||||
const query = jest.fn().mockResolvedValueOnce(encode([key(1, 'DF-1')]))
|
||||
.mockResolvedValueOnce(encode([{ skuId: 'DF-1', pic: 'main', sourceModifiedAt: null }]))
|
||||
const query = jest.fn().mockResolvedValueOnce(encode([{ skuId: 'DF-1', pic: 'main', sourceModifiedAt: null }]))
|
||||
.mockRejectedValueOnce(new Error('PDD_FAILED')).mockResolvedValue(encode([]))
|
||||
const request = { input: jest.fn().mockReturnThis(), query, cancel: jest.fn() }
|
||||
const pool = { connect: jest.fn(), request: () => request, close: jest.fn() }
|
||||
@ -161,7 +161,7 @@ describe('run-scoped source queries', () => {
|
||||
await expect(repo.read('pictures', ['DF-1'], options)).rejects.toThrow('PDD_FAILED')
|
||||
expect([...parts.keys()]).toEqual(['pictures-main'])
|
||||
await expect(repo.read('pictures', ['DF-1'], options)).resolves.toEqual([{ skuId: 'DF-1', pic: 'main' }])
|
||||
expect(query).toHaveBeenCalledTimes(5)
|
||||
expect(query).toHaveBeenCalledTimes(4)
|
||||
expect(pool.close).toHaveBeenCalledTimes(2)
|
||||
expect(validSerializedPicture({ skuId: 'DF', pic: 'url', time: 'not-a-number' })).toBe(false)
|
||||
expect(() => restorePictures([{ skuId: 'DF', pic: 'url', time: 'bad' }])).toThrow('INVALID_PICTURE_PART')
|
||||
|
||||
@ -57,4 +57,15 @@ describe('product archive cooperative priority', () => {
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
expect(c.end).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('uses independent run locks for fields and pictures while retaining the shared batch write lock', async () => {
|
||||
const c = client(jest.fn().mockResolvedValue({ rows: [{ locked: true }] }))
|
||||
const repository = new ProductArchiveSyncTurnRepository(() => c as never)
|
||||
await repository.backgroundRun(async () => undefined)
|
||||
await repository.backgroundRun(async () => undefined, 'pictures')
|
||||
expect(c.query.mock.calls.map(([, args]) => args)).toEqual([[90710, 5], [90710, 6]])
|
||||
c.query.mockClear()
|
||||
await repository.exclusive('background', async () => undefined)
|
||||
expect(c.query.mock.calls.some(([, args]) => args?.[1] === 3)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@ -48,14 +48,15 @@ export function enrichmentSnapshotQuery(kind: EnrichmentSnapshotQuery, schema: s
|
||||
export const pictureSnapshotTables = ['jst_skumap', 'jst_skumap_pdd', 'jst_skumap_qmcust_add'] as const
|
||||
export function pictureQuery(schema: string, table: string = pictureSnapshotTables[0]) {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema) || !pictureSnapshotTables.some(name => name === table)) throw new Error('INVALID_PICTURE_SOURCE')
|
||||
// Compress the full matching rows on the source server. Latest nonempty
|
||||
// selection is performed after lossless decoding, without sorting LOBs.
|
||||
// Return requested missing-image SKUs only, including normalized dirty keys.
|
||||
// Do not append all DF rows or transfer every primary-key page to the app.
|
||||
const normalized = `UPPER(LTRIM(RTRIM(CAST(${[8203, 8204, 8205, 8288, 65279, 173].reduce(
|
||||
(value, character) => `REPLACE(${value},NCHAR(${character}),N'')`, 'CAST(s.sku_id AS nvarchar(200))')} AS varchar(200)))))`
|
||||
return `WITH requested AS(SELECT DISTINCT value FROM OPENJSON(@requested) WITH(value varchar(200) '$')),
|
||||
matched AS(SELECT ${code('s.sku_id', 200)} AS skuId,LTRIM(RTRIM(s.pic)) AS pic,s.modified AS sourceModifiedAt
|
||||
FROM [${schema}].[${table}] s INNER HASH JOIN requested r ON ${code('s.sku_id', 200)}=r.value
|
||||
UNION ALL SELECT ${code('s.sku_id', 200)} AS skuId,LTRIM(RTRIM(s.pic)) AS pic,s.modified AS sourceModifiedAt
|
||||
FROM [${schema}].[${table}] s WHERE ${code('s.sku_id', 200)} LIKE 'DF%')
|
||||
SELECT COMPRESS((SELECT * FROM matched FOR JSON PATH,INCLUDE_NULL_VALUES)) AS payload`
|
||||
matched AS(SELECT ${normalized} AS skuId,LTRIM(RTRIM(s.pic)) AS pic,s.modified AS sourceModifiedAt
|
||||
FROM [${schema}].[${table}] s INNER HASH JOIN requested r ON ${normalized}=r.value
|
||||
WHERE s.pic IS NOT NULL AND LTRIM(RTRIM(s.pic))<>N'')
|
||||
SELECT COMPRESS((SELECT * FROM matched FOR JSON PATH,INCLUDE_NULL_VALUES)) AS payload OPTION(RECOMPILE)`
|
||||
}
|
||||
|
||||
export function pictureKeyPageQuery(schema: string, after: boolean, pageSize: number) {
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
import type mssql from 'mssql'
|
||||
import { inventoryWarehouseIdsJson } from './jst-inventory-actual-quantity.query'
|
||||
import { enrichmentSnapshotQuery, pictureQuery, pictureKeyPageQuery, pictureValuesQuery, pictureSnapshotTables, type EnrichmentSnapshotQuery } from './product-archive-enrichment-source-snapshot.queries'
|
||||
import { enrichmentSnapshotQuery, pictureQuery, pictureSnapshotTables, type EnrichmentSnapshotQuery } from './product-archive-enrichment-source-snapshot.queries'
|
||||
import { decodePictureSnapshot, serializePictures, restorePictures, type DecodedPicture, type SerializedPicture } from './product-archive-enrichment-source-snapshot.codec'
|
||||
import { decodePictureKeyPage, visitPictureKeyPages, PICTURE_KEY_PAGE_SIZE } from './product-archive-picture-pages.repository'
|
||||
import type { JstSkuPriceProfile } from './jst-sku-price.repository'
|
||||
import type { JstInventoryPublicAvailableProfile } from './jst-inventory-public-available.repository'
|
||||
import type { ProductArchiveClearanceStockProfile } from './supply-chain-product-archive-clearance-stock.repository'
|
||||
@ -22,6 +21,7 @@ export type EnrichmentSnapshotRows = {
|
||||
}
|
||||
export type EnrichmentSnapshotRequest = string[] | Array<{ batchIndex: number; barcode: string; sku: string }>
|
||||
export type PictureSnapshotOptions = {
|
||||
queryTimeoutMs?: number
|
||||
readPicturePart?(name: string, read: () => Promise<SerializedPicture[]>): Promise<SerializedPicture[]>
|
||||
inventoryWarehouseIds?: readonly number[]
|
||||
}
|
||||
@ -59,7 +59,7 @@ export class ProductArchiveEnrichmentSourceSnapshotRepositoryClass implements Pr
|
||||
if (!requested.length) return []
|
||||
if (requested.length > 300_000) throw new Error('SOURCE_SNAPSHOT_TARGET_LIMIT')
|
||||
const warehouseIds = kind === 'inventory' ? inventoryWarehouseIdsJson(options.inventoryWarehouseIds ?? []) : null
|
||||
const timeout = Number(process.env.PRODUCT_ARCHIVE_SNAPSHOT_QUERY_TIMEOUT_MS || (kind === 'pictures' ? '600000' : '300000'))
|
||||
const timeout = Number(options.queryTimeoutMs ?? (process.env.PRODUCT_ARCHIVE_SNAPSHOT_QUERY_TIMEOUT_MS || (kind === 'pictures' ? '600000' : '300000')))
|
||||
if (!Number.isSafeInteger(timeout) || timeout < 1000 || timeout > 600_000) throw new Error('INVALID_SNAPSHOT_QUERY_TIMEOUT')
|
||||
const sql = (await import('mssql')).default
|
||||
// Each source attempt owns its connection. Retrying one source cannot close
|
||||
@ -74,10 +74,8 @@ export class ProductArchiveEnrichmentSourceSnapshotRepositoryClass implements Pr
|
||||
await pool.connect()
|
||||
const schema = process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt'
|
||||
if (kind === 'pictures') {
|
||||
const keys = new Set((requested as string[]).map(value => value.trim().toUpperCase()))
|
||||
const normalizeDf = (value: string) => value.replace(/[\u200B-\u200D\u2060\uFEFF\u00AD]/g, '').trim().toUpperCase()
|
||||
const dfKeys = new Set([...keys].filter(value => normalizeDf(value).startsWith('DF')).map(normalizeDf))
|
||||
const matches = (value: string) => keys.has(value) || (value.startsWith('DF') && dfKeys.has(normalizeDf(value)))
|
||||
const keys = new Set((requested as string[]).map(value => value.replace(/[\u200B-\u200D\u2060\uFEFF\u00AD]/g, '').trim().toUpperCase()))
|
||||
const matches = (value: string) => keys.has(value)
|
||||
const latest = new Map<string, DecodedPicture>()
|
||||
const accept = (rows: DecodedPicture[]) => {
|
||||
for (const row of rows) {
|
||||
@ -94,27 +92,8 @@ export class ProductArchiveEnrichmentSourceSnapshotRepositoryClass implements Pr
|
||||
const part = async (name: string, read: () => Promise<DecodedPicture[]>) => {
|
||||
accept(options.readPicturePart ? restorePictures(await options.readPicturePart(name, async () => serializePictures(await read()))) : await read())
|
||||
}
|
||||
await part('pictures-main', async () => {
|
||||
const started = performance.now()
|
||||
await visitPictureKeyPages({
|
||||
async readKeys(cursor) {
|
||||
const request = pool.request()
|
||||
if (cursor) request.input('shopId', sql.Int, cursor.shopId)
|
||||
.input('shopItemId', sql.NVarChar(100), cursor.shopItemId).input('shopSkuId', sql.NVarChar(100), cursor.shopSkuId)
|
||||
return decodePictureKeyPage(await payload(request, pictureKeyPageQuery(schema, !!cursor, PICTURE_KEY_PAGE_SIZE)))
|
||||
},
|
||||
async readValues(matched) {
|
||||
const requestedKeys = matched.map(({ shopId, shopItemId, shopSkuId }) => ({ shopId, shopItemId, shopSkuId }))
|
||||
return decodePictureSnapshot(await payload(pool.request().input('requested', sql.NVarChar(sql.MAX), JSON.stringify(requestedKeys)), pictureValuesQuery(schema)))
|
||||
}, matches, accept,
|
||||
report(progress) { console.log(JSON.stringify({ kind: 'ARCHIVE_PICTURE_PAGE', ...progress, elapsedMs: Math.round(performance.now() - started) })) },
|
||||
})
|
||||
const rows = [...latest.values()]
|
||||
latest.clear()
|
||||
return rows
|
||||
})
|
||||
for (const table of pictureSnapshotTables.slice(1)) {
|
||||
await part(table === 'jst_skumap_pdd' ? 'pictures-pdd' : 'pictures-extra', async () => {
|
||||
for (const table of pictureSnapshotTables) {
|
||||
await part(table === 'jst_skumap' ? 'pictures-main' : table === 'jst_skumap_pdd' ? 'pictures-pdd' : 'pictures-extra', async () => {
|
||||
const started = performance.now()
|
||||
const data = await payload(pool.request().input('requested', sql.NVarChar(sql.MAX), JSON.stringify([...keys])), pictureQuery(schema, table))
|
||||
const rows = decodePictureSnapshot(data)
|
||||
|
||||
@ -48,14 +48,14 @@ export class ProductArchiveSyncTurnRepository {
|
||||
}
|
||||
}
|
||||
|
||||
async backgroundRun<T>(work: (assertConnected: () => void) => Promise<T>): Promise<T | { status: 'SKIPPED_RUNNING' }> {
|
||||
async backgroundRun<T>(work: (assertConnected: () => void) => Promise<T>, lane: 'fields' | 'pictures' = 'fields'): Promise<T | { status: 'SKIPPED_RUNNING' }> {
|
||||
const client = this.connect()
|
||||
let disconnected: Error | undefined
|
||||
client.on('error', error => { disconnected = error })
|
||||
client.on('end', () => { disconnected ??= new Error('ARCHIVE_SYNC_RUN_CONNECTION_CLOSED') })
|
||||
try {
|
||||
await client.connect()
|
||||
const lock = await client.query<{ locked: boolean }>('SELECT pg_try_advisory_lock($1, $2) AS locked', [LOCK_NAMESPACE, RUN_LOCK])
|
||||
const lock = await client.query<{ locked: boolean }>('SELECT pg_try_advisory_lock($1, $2) AS locked', [LOCK_NAMESPACE, lane === 'pictures' ? RUN_LOCK + 1 : RUN_LOCK])
|
||||
if (!lock.rows[0]?.locked) return { status: 'SKIPPED_RUNNING' }
|
||||
const assertConnected = () => { if (disconnected) throw disconnected }
|
||||
assertConnected()
|
||||
|
||||
@ -179,8 +179,10 @@ class SupplyChainProductArchiveEnrichmentSyncRepositoryClass
|
||||
storedSource, incomingSourceCode: input.source.sourceCode,
|
||||
incomingSourceRecordId: input.source.sourceRecordId })) return false
|
||||
const current = (previous as unknown as Record<string, unknown>)[field]
|
||||
if (input.source.fillBlankOnly && comparable(current).trim() !== '') return false
|
||||
return !input.source.fillEmptyOnly || comparable(current) === ''
|
||||
})) as ProductArchiveEnrichmentPatch
|
||||
if (input.source.fillBlankOnly && Object.keys(patch).length === 0) return { changes: [], sourceInitialized: false }
|
||||
const changes = changedValues(previous, patch)
|
||||
const sourceRecordId = previous.barcode
|
||||
const fieldSourceRecordId = `${input.source.sourceRecordId}:${previous.barcode}`
|
||||
|
||||
@ -44,6 +44,8 @@ export type ProductArchiveEnrichmentSource = {
|
||||
sourceColumns: Partial<Record<ProductArchiveEnrichmentField, string>>
|
||||
sourceRecordedAt?: Date | null
|
||||
fillEmptyOnly?: boolean
|
||||
/** Check current field values at write time, even for an existing source. */
|
||||
fillBlankOnly?: boolean
|
||||
/** Update a changed source definition even when its numeric value is unchanged. */
|
||||
refreshSourceMetadata?: boolean
|
||||
}
|
||||
|
||||
@ -0,0 +1,59 @@
|
||||
/** @jest-environment node */
|
||||
jest.mock('@/server/repositories/product-archive-sync-turn.repository', () => ({
|
||||
productArchiveSyncTurnRepository: {
|
||||
backgroundRun: jest.fn(async work => work(() => undefined)),
|
||||
exclusive: jest.fn(async (_priority, work) => work(() => undefined)),
|
||||
},
|
||||
}))
|
||||
jest.mock('../supply-chain-product-archive-enrichment-sync.checkpoint', () => ({
|
||||
ArchiveSyncCheckpointFile: jest.fn().mockImplementation(() => ({
|
||||
load: jest.fn(), phase: jest.fn(), save: jest.fn(),
|
||||
})),
|
||||
}))
|
||||
jest.mock('../jst-sku-product-archive-full-sync.service', () => ({ jstSkuProductArchiveFullSyncService: { syncAll: jest.fn() } }))
|
||||
jest.mock('../product-archive-owner-workflow-sync.service', () => ({ productArchiveOwnerWorkflowSyncService: { syncAll: jest.fn() } }))
|
||||
jest.mock('../supply-chain-product-archive-ops-director-sync.service', () => ({ supplyChainProductArchiveOpsDirectorSyncService: { syncAll: jest.fn() } }))
|
||||
jest.mock('../supply-chain-product-archive-enrichment-sync.service', () => ({ supplyChainProductArchiveEnrichmentSyncService: { syncAll: jest.fn() } }))
|
||||
jest.mock('../supply-chain-product-archive-production-type-fill.service', () => ({ supplyChainProductArchiveProductionTypeFillService: { syncAll: jest.fn() } }))
|
||||
jest.mock('../product-archive-missing-pictures-sync.service', () => ({ productArchiveMissingPicturesSyncService: { syncAll: jest.fn() } }))
|
||||
|
||||
import { runArchiveEnrichmentWithCheckpoint } from '../supply-chain-product-archive-enrichment-sync.runner'
|
||||
import { supplyChainProductArchiveEnrichmentSyncService as fields } from '../supply-chain-product-archive-enrichment-sync.service'
|
||||
import { productArchiveMissingPicturesSyncService as pictures } from '../product-archive-missing-pictures-sync.service'
|
||||
import { supplyChainProductArchiveProductionTypeFillService as types } from '../supply-chain-product-archive-production-type-fill.service'
|
||||
import { jstSkuProductArchiveFullSyncService as base } from '../jst-sku-product-archive-full-sync.service'
|
||||
import { productArchiveSyncTurnRepository as turns } from '@/server/repositories/product-archive-sync-turn.repository'
|
||||
|
||||
const input = { batchSize: 200, jstBatchSize: 500, jstConcurrency: 8, syncJstBase: true, opsDirectorOnly: false }
|
||||
|
||||
describe('ordinary-field and missing-picture job isolation', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
jest.spyOn(console, 'log').mockImplementation(() => undefined)
|
||||
})
|
||||
afterEach(() => jest.restoreAllMocks())
|
||||
|
||||
it('finishes all ordinary phases without invoking the failed picture job', async () => {
|
||||
jest.mocked(pictures.syncAll).mockRejectedValue(new Error('SOURCE_SNAPSHOT_DEADLINE'))
|
||||
await runArchiveEnrichmentWithCheckpoint(input)
|
||||
expect(fields.syncAll).toHaveBeenCalledWith(expect.objectContaining({ skipPictures: true }))
|
||||
expect(types.syncAll).toHaveBeenCalled()
|
||||
expect(pictures.syncAll).not.toHaveBeenCalled()
|
||||
expect(turns.backgroundRun).toHaveBeenCalledWith(expect.any(Function), 'fields')
|
||||
})
|
||||
|
||||
it('reports image-only failures without running any ordinary phase, using a separate run lock', async () => {
|
||||
jest.mocked(pictures.syncAll).mockRejectedValue(new Error('SOURCE_SNAPSHOT_DEADLINE'))
|
||||
await expect(runArchiveEnrichmentWithCheckpoint({ ...input, syncJstBase: false, picturesOnly: true }))
|
||||
.rejects.toThrow('SOURCE_SNAPSHOT_DEADLINE')
|
||||
expect(base.syncAll).not.toHaveBeenCalled()
|
||||
expect(fields.syncAll).not.toHaveBeenCalled()
|
||||
expect(types.syncAll).not.toHaveBeenCalled()
|
||||
expect(turns.backgroundRun).toHaveBeenCalledWith(expect.any(Function), 'pictures')
|
||||
})
|
||||
|
||||
it('refuses contradictory modes before starting a job', async () => {
|
||||
await expect(runArchiveEnrichmentWithCheckpoint({ ...input, picturesOnly: true })).rejects.toThrow('CONFLICTING_ARCHIVE_SYNC_MODES')
|
||||
expect(turns.backgroundRun).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -59,7 +59,7 @@ describe('archive run source snapshots', () => {
|
||||
expect(f.deps.repository.listTargetsByIds).not.toHaveBeenCalled()
|
||||
const next = fixture()
|
||||
await loadArchiveEnrichmentSnapshot({ dependencies: next.dependencies, batchSize: 2, directory: dir, context: 'same' })
|
||||
expect(next.deps.snapshotRepository.read.mock.calls.map(([kind]) => kind)).not.toContain('pictures')
|
||||
expect(next.deps.snapshotRepository.read.mock.calls.map(([kind]) => kind)).not.toContain('inventory')
|
||||
expect(next.deps.snapshotRepository.read.mock.calls.map(([kind]) => kind)).toContain('prices')
|
||||
})
|
||||
|
||||
@ -71,6 +71,28 @@ describe('archive run source snapshots', () => {
|
||||
await expect(snapshot.batch(0)).rejects.toThrow('ARCHIVE_SOURCE_TARGET_CHANGED')
|
||||
})
|
||||
|
||||
it('completes ordinary sources without reading the failing picture source or rejecting an image edit', async () => {
|
||||
const f = fixture()
|
||||
f.targets[0].image = 'existing' as never
|
||||
f.deps.snapshotRepository.read.mockImplementation(async kind => {
|
||||
if (kind === 'pictures') throw new Error('SOURCE_SNAPSHOT_DEADLINE')
|
||||
return []
|
||||
})
|
||||
const snapshot = await loadArchiveEnrichmentSnapshot({ dependencies: f.dependencies, batchSize: 2, skipPictures: true })
|
||||
f.targets[0].image = null
|
||||
await expect(snapshot.batch(0)).resolves.toHaveProperty('targets')
|
||||
expect(f.deps.snapshotRepository.read.mock.calls.map(([kind]) => kind)).not.toContain('pictures')
|
||||
expect(snapshot.pictures).toEqual({ df: [], fill: [] })
|
||||
})
|
||||
|
||||
it('excludes existing DF images from the requested picture keys', async () => {
|
||||
const f = fixture()
|
||||
f.targets[0] = { ...f.targets[0], barcode: 'DF-HAS-IMAGE', image: 'existing' as never }
|
||||
f.targets[1].barcode = 'DF-MISSING'
|
||||
await loadArchiveEnrichmentSnapshot({ dependencies: f.dependencies, batchSize: 2 })
|
||||
expect(f.deps.snapshotRepository.read).toHaveBeenCalledWith('pictures', ['DF-MISSING', 'BAR-C'], expect.any(Object))
|
||||
})
|
||||
|
||||
it('rejects corrupted cached values instead of treating them as an empty source', async () => {
|
||||
const dir = await directory(), cache = new ArchiveEnrichmentSnapshotFiles(dir, 'same')
|
||||
await cache.read('prices', async () => [{ barcode: 'BAR' }], row => !!row)
|
||||
|
||||
@ -0,0 +1,95 @@
|
||||
/** @jest-environment node */
|
||||
jest.mock('../supply-chain-product-archive-change-log.service', () => ({ recordProductArchiveFieldChanges: jest.fn() }))
|
||||
|
||||
import { ProductArchiveMissingPicturesSyncService } from '../product-archive-missing-pictures-sync.service'
|
||||
import { SupplyChainProductArchiveEnrichmentSyncService } from '../supply-chain-product-archive-enrichment-sync.service'
|
||||
import { planEnrichmentBatch, enrichmentSourceKey } from '../supply-chain-product-archive-enrichment-sync.batch'
|
||||
import type { EnrichmentDependencies } from '../supply-chain-product-archive-enrichment-sync.sources'
|
||||
import type { CurrentArchive } from '@/server/repositories/supply-chain-product-archive-enrichment-targets'
|
||||
import { JST_SKUMAP_PIC_ARCHIVE_SOURCE_CODE } from '@/lib/supply-chain-product-archive-field-source'
|
||||
|
||||
function fixture() {
|
||||
const targets = ['DF-MISSING', 'BAR-MISSING', 'DF-EXISTING'].map((barcode, index) => ({
|
||||
id: String(index), barcode, spu: 'SPU', sku: 'SKU', image: index === 2 ? 'manual-original' : '',
|
||||
supplierName: '', inOutWarehouse: '', designer: '', opsHead: '', opsDirector: '', opsDeptHead: '', fieldSourceMap: {},
|
||||
}))
|
||||
const current = targets.map(row => ({ ...row }))
|
||||
const sourceKeys = new Set(targets.map(row => enrichmentSourceKey(JST_SKUMAP_PIC_ARCHIVE_SOURCE_CODE, row.barcode)))
|
||||
const plans: ReturnType<typeof planEnrichmentBatch>[] = []
|
||||
const empty = () => jest.fn().mockResolvedValue([])
|
||||
const close = jest.fn().mockResolvedValue(undefined)
|
||||
const dependencies = {
|
||||
snapshotRepository: { read: jest.fn(async kind => kind === 'pictures'
|
||||
? targets.map(row => ({ skuId: row.barcode, pic: `source-${row.barcode}` })) : []) },
|
||||
repository: {
|
||||
listAllTargets: jest.fn(async () => targets),
|
||||
listTargetsByIds: jest.fn(async (ids: string[]) => targets.filter(row => ids.includes(row.id))),
|
||||
listIntakeSpuOwners: empty(), listIntakeSpuDesigners: empty(),
|
||||
applyBatch: jest.fn(async (items, planner) => {
|
||||
const plan = planner(items, current as CurrentArchive[], sourceKeys, new Date('2026-11-23T00:00:00Z'))
|
||||
plans.push(plan)
|
||||
for (const write of plan.writes) {
|
||||
Object.assign(current.find(row => row.id === write.id)!, write.patch, { fieldSourceMap: write.fieldSourceMap })
|
||||
Object.assign(targets.find(row => row.id === write.id)!, write.patch)
|
||||
}
|
||||
return { changed: plan.changed, unchanged: plan.unchanged }
|
||||
}),
|
||||
},
|
||||
configRepository: { listActive: empty() }, ownerConfigRepository: { listOwnerHierarchy: empty() },
|
||||
skumapPicRepository: { listDfLatestSkuPics: jest.fn().mockRejectedValue(new Error('PICTURES_FAILED')),
|
||||
listLatestSkuPicsForBarcodes: jest.fn().mockRejectedValue(new Error('PICTURES_FAILED')), close },
|
||||
catalogCostRepository: { listByBarcodes: empty() },
|
||||
clearanceStockRepository: { close }, publicAvailableStockRepository: { close },
|
||||
supplierRepository: { close }, stockRepository: { close }, warehouseRepository: { close }, priceRepository: { close },
|
||||
} as unknown as EnrichmentDependencies
|
||||
return { dependencies, targets, current, plans, service: new ProductArchiveMissingPicturesSyncService(dependencies) }
|
||||
}
|
||||
|
||||
describe('independent missing-picture synchronization', () => {
|
||||
beforeEach(() => jest.spyOn(console, 'log').mockImplementation(() => undefined))
|
||||
afterEach(() => jest.restoreAllMocks())
|
||||
|
||||
it('fills missing DF and ordinary images, including previously registered sources, and preserves existing images', async () => {
|
||||
const f = fixture()
|
||||
await expect(f.service.syncAll()).resolves.toMatchObject({ changed: 2, scanned: 2, missingAtStart: 2 })
|
||||
expect(f.dependencies.snapshotRepository!.read).toHaveBeenCalledWith('pictures', ['DF-MISSING', 'BAR-MISSING'],
|
||||
expect.objectContaining({ queryTimeoutMs: 120_000 }))
|
||||
expect(f.current.map(row => row.image)).toEqual(['source-DF-MISSING', 'source-BAR-MISSING', 'manual-original'])
|
||||
expect(f.plans.flatMap(plan => plan.logs)).toHaveLength(2)
|
||||
const reads = jest.mocked(f.dependencies.snapshotRepository!.read)
|
||||
reads.mockClear()
|
||||
await expect(f.service.syncAll()).resolves.toMatchObject({ changed: 0, missingAtStart: 0 })
|
||||
expect(reads).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('preserves an image uploaded between source reading and the transaction lock', async () => {
|
||||
const f = fixture()
|
||||
f.current[0].image = 'uploaded-during-query'
|
||||
await f.service.syncAll()
|
||||
expect(f.current[0].image).toBe('uploaded-during-query')
|
||||
expect(f.plans.flatMap(plan => plan.logs).some(log => log.skuCode === 'DF-MISSING')).toBe(false)
|
||||
expect(f.plans.flatMap(plan => plan.sources).some(source => source.sourceRecordId === 'DF-MISSING')).toBe(false)
|
||||
expect(f.current[0].fieldSourceMap).toEqual({})
|
||||
})
|
||||
|
||||
it('does not write images or ordinary fields when the image source fails', async () => {
|
||||
const f = fixture()
|
||||
jest.mocked(f.dependencies.snapshotRepository!.read).mockRejectedValue(new Error('SOURCE_SNAPSHOT_DEADLINE'))
|
||||
await expect(f.service.syncAll()).rejects.toThrow('SOURCE_SNAPSHOT_DEADLINE')
|
||||
expect(f.dependencies.repository.applyBatch).not.toHaveBeenCalled()
|
||||
expect(f.current[0].image).toBe('')
|
||||
})
|
||||
|
||||
it('completes the ordinary-field service when all legacy image readers fail', async () => {
|
||||
const f = fixture()
|
||||
jest.mocked(f.dependencies.snapshotRepository!.read).mockImplementation(async kind => {
|
||||
if (kind === 'pictures') throw new Error('SOURCE_SNAPSHOT_DEADLINE')
|
||||
return []
|
||||
})
|
||||
await expect(new SupplyChainProductArchiveEnrichmentSyncService(f.dependencies).syncAll({ skipPictures: true }))
|
||||
.resolves.toMatchObject({ scanned: 3, failed: 0 })
|
||||
expect(f.dependencies.skumapPicRepository.listDfLatestSkuPics).not.toHaveBeenCalled()
|
||||
expect(f.dependencies.skumapPicRepository.listLatestSkuPicsForBarcodes).not.toHaveBeenCalled()
|
||||
expect(f.current[2].image).toBe('manual-original')
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,69 @@
|
||||
import { JST_SKUMAP_PIC_ARCHIVE_SOURCE_CODE } from '@/lib/supply-chain-product-archive-field-source'
|
||||
import { validSerializedPicture } from '@/server/repositories/product-archive-enrichment-source-snapshot.codec'
|
||||
import type { EnrichmentBatchInput } from '@/server/repositories/supply-chain-product-archive-enrichment-batch.repository'
|
||||
import { enrichmentDependencies, type EnrichmentDependencies } from './supply-chain-product-archive-enrichment-sync.sources'
|
||||
import { ArchiveEnrichmentSnapshotFiles } from './supply-chain-product-archive-enrichment-sync.snapshot-file'
|
||||
import { snapshotResumeOffset } from './supply-chain-product-archive-enrichment-sync.snapshot'
|
||||
import { normalizeIdentity } from './supply-chain-product-archive-enrichment-sync.types'
|
||||
import { planEnrichmentBatch } from './supply-chain-product-archive-enrichment-sync.batch'
|
||||
import { enrichmentProgress, type EnrichmentSyncInput } from './supply-chain-product-archive-enrichment-sync.runtime'
|
||||
|
||||
type Dependencies = Pick<EnrichmentDependencies, 'repository' | 'snapshotRepository'>
|
||||
|
||||
/** Independent from inventory/prices/owners; never overwrites an existing image. */
|
||||
export class ProductArchiveMissingPicturesSyncService {
|
||||
constructor(private readonly deps: Dependencies = enrichmentDependencies) {}
|
||||
|
||||
async syncAll(input: EnrichmentSyncInput = {}) {
|
||||
const { repository, snapshotRepository } = this.deps
|
||||
if (!repository.listAllTargets || !repository.listTargetsByIds || !repository.applyBatch || !snapshotRepository) {
|
||||
throw new Error('MISSING_PICTURE_SYNC_DEPENDENCIES')
|
||||
}
|
||||
const batchSize = Math.min(200, Math.max(1, Math.trunc(input.batchSize ?? 200)))
|
||||
const result = enrichmentProgress(input.resume)
|
||||
const cache = new ArchiveEnrichmentSnapshotFiles(input.snapshotDirectory, input.snapshotContext)
|
||||
const targets = await cache.read('picture-targets', async () =>
|
||||
(await repository.listAllTargets!()).filter(row => !row.image?.trim()),
|
||||
row => !!row && typeof row === 'object' && ['id', 'barcode'].every(key =>
|
||||
typeof (row as Record<string, unknown>)[key] === 'string'))
|
||||
if (!targets.length) return { ...result, missingAtStart: 0, matched: 0 }
|
||||
|
||||
// Each table has a bounded complete-transfer deadline. Successful tables
|
||||
// are saved independently; a failure never affects the ordinary-field job.
|
||||
const pictures = await cache.read('pictures', () => snapshotRepository.read('pictures',
|
||||
[...new Set(targets.map(row => normalizeIdentity(row.barcode)).filter(Boolean))], {
|
||||
queryTimeoutMs: 120_000,
|
||||
readPicturePart: (name, read) => cache.read(name, read, validSerializedPicture),
|
||||
}), row => !!row && typeof row === 'object' &&
|
||||
typeof (row as { skuId?: unknown }).skuId === 'string' && typeof (row as { pic?: unknown }).pic === 'string')
|
||||
const byBarcode = new Map(pictures.filter(row => row.pic.trim()).map(row => [normalizeIdentity(row.skuId), row.pic]))
|
||||
for (let offset = snapshotResumeOffset(targets, result.lastId, batchSize); offset < targets.length; offset += batchSize) {
|
||||
const original = targets.slice(offset, offset + batchSize)
|
||||
const originalById = new Map(original.map(row => [row.id, row]))
|
||||
const fresh = await repository.listTargetsByIds(original.map(row => row.id))
|
||||
if (fresh.length !== original.length || fresh.some(row => row.barcode !== originalById.get(row.id)?.barcode)) {
|
||||
throw new Error('ARCHIVE_PICTURE_TARGET_CHANGED_USE_NEW_RUN_KEY')
|
||||
}
|
||||
const items: EnrichmentBatchInput = fresh.flatMap(target => {
|
||||
const pic = byBarcode.get(normalizeIdentity(target.barcode))
|
||||
if (target.image?.trim() || !pic) return []
|
||||
return [{ target, updates: [{ patch: { image: pic }, source: {
|
||||
sourceCode: JST_SKUMAP_PIC_ARCHIVE_SOURCE_CODE, sourceSystem: '聚水潭 JSReportReplica',
|
||||
sourceSchema: 'rpt', sourceObject: 'jst_skumap|jst_skumap_pdd|jst_skumap_qmcust_add',
|
||||
sourceRecordId: target.barcode, sourceColumns: { image: 'pic' }, fillBlankOnly: true,
|
||||
} }] }]
|
||||
})
|
||||
const apply = () => repository.applyBatch!(items, planEnrichmentBatch)
|
||||
const applied = await (input.withBatch ? input.withBatch(apply) : apply())
|
||||
result.changed += applied.changed
|
||||
result.unchanged += applied.unchanged + original.length - items.length
|
||||
result.scanned += original.length
|
||||
result.batches++
|
||||
result.lastId = original[original.length - 1].id
|
||||
await input.onBatch?.({ ...result }, { sharedMs: 0, sourceMs: 0, mapMs: 0, writeMs: 0, elapsedMs: 0 })
|
||||
}
|
||||
return { ...result, missingAtStart: targets.length, matched: byBarcode.size }
|
||||
}
|
||||
}
|
||||
|
||||
export const productArchiveMissingPicturesSyncService = new ProductArchiveMissingPicturesSyncService()
|
||||
@ -6,6 +6,12 @@ const RECIPIENT = '徐霞客'
|
||||
|
||||
// 单任务每日最多一条失败告警;任务明晨仍会按计划自动执行。
|
||||
export const ARCHIVE_SYNC_FAILURE_TASKS = {
|
||||
pictures: {
|
||||
name: '档案缺图补齐',
|
||||
slug: 'archive-missing-pictures',
|
||||
schedule: '每日 10:10',
|
||||
impact: '缺图档案暂未补齐图片;已有图片保持不变,库存、价格、负责人及产品类型的每日同步独立执行。',
|
||||
},
|
||||
enrichment: {
|
||||
name: '档案 enrichment 全量',
|
||||
slug: 'archive-enrichment',
|
||||
|
||||
@ -39,6 +39,7 @@ export function planEnrichmentBatch(input: EnrichmentBatchInput, archives: Curre
|
||||
incomingSourceRecordId: source.sourceRecordId })) continue
|
||||
const previousValue = String(current[field] ?? '')
|
||||
if (source.fillEmptyOnly && previousValue !== '') continue
|
||||
if (source.fillBlankOnly && previousValue.trim() !== '') continue
|
||||
sourcePatch[field as keyof ProductArchiveEnrichmentPatch] = value
|
||||
if (previousValue === String(value ?? '')) continue
|
||||
const fieldLabel = labels.get(field)
|
||||
@ -47,6 +48,7 @@ export function planEnrichmentBatch(input: EnrichmentBatchInput, archives: Curre
|
||||
current[field] = value
|
||||
finalPatch[field as keyof ProductArchiveEnrichmentPatch] = value
|
||||
}
|
||||
if (source.fillBlankOnly && Object.keys(sourcePatch).length === 0) { unchanged++; continue }
|
||||
if (changes.length) {
|
||||
changed += changes.length
|
||||
sourceMap = { ...sourceMap, ...createProductArchiveFieldSourceMap({
|
||||
|
||||
@ -9,8 +9,9 @@ import { supplyChainProductArchiveOpsDirectorSyncService } from './supply-chain-
|
||||
import { productArchiveOwnerWorkflowSyncService } from './product-archive-owner-workflow-sync.service'
|
||||
import { jstSkuProductArchiveFullSyncService, type JstSkuProductArchiveFullSyncProgress } from './jst-sku-product-archive-full-sync.service'
|
||||
import type { EnrichmentProgress } from './supply-chain-product-archive-enrichment-sync.runtime'
|
||||
import { productArchiveMissingPicturesSyncService } from './product-archive-missing-pictures-sync.service'
|
||||
|
||||
type RunInput = { batchSize: number; jstBatchSize: number; jstConcurrency: number; syncJstBase: boolean; opsDirectorOnly: boolean; runKey?: string }
|
||||
type RunInput = { batchSize: number; jstBatchSize: number; jstConcurrency: number; syncJstBase: boolean; opsDirectorOnly: boolean; picturesOnly?: boolean; runKey?: string }
|
||||
const codeFiles = [
|
||||
'supply-chain-product-archive-enrichment-sync.service.ts', 'supply-chain-product-archive-enrichment-sync.sources.ts',
|
||||
'supply-chain-product-archive-enrichment-sync.mapper.ts', 'supply-chain-product-archive-enrichment-sync.batch.ts',
|
||||
@ -21,11 +22,13 @@ const codeFiles = [
|
||||
'supply-chain-product-archive-enrichment-sync.snapshot.ts', 'supply-chain-product-archive-enrichment-sync.snapshot-file.ts',
|
||||
'jst-sku-product-archive-full-sync.service.ts', 'product-archive-owner-workflow-sync.service.ts',
|
||||
'supply-chain-product-archive-production-type-fill.service.ts',
|
||||
'product-archive-missing-pictures-sync.service.ts',
|
||||
]
|
||||
|
||||
export async function runArchiveEnrichmentWithCheckpoint(input: RunInput) {
|
||||
const runDate = new Date(Date.now() + 8 * 3_600_000).toISOString().slice(0, 10)
|
||||
const runKey = input.runKey || runDate
|
||||
if (input.picturesOnly && (input.opsDirectorOnly || input.syncJstBase)) throw new Error('CONFLICTING_ARCHIVE_SYNC_MODES')
|
||||
const runKey = input.runKey || `${runDate}-${input.picturesOnly ? 'pictures-v1' : 'fields-v2'}`
|
||||
if (!/^[a-zA-Z0-9._-]{1,80}$/.test(runKey)) throw new Error('INVALID_ARCHIVE_RUN_KEY')
|
||||
const contextHash = createHash('sha256').update(JSON.stringify({ ...input, runKey, database: process.env.DATABASE_URL,
|
||||
source: [process.env.JST_REPORT_DB_HOST, process.env.JST_REPORT_DB_PORT, process.env.JST_REPORT_DB_NAME,
|
||||
@ -43,7 +46,7 @@ export async function runArchiveEnrichmentWithCheckpoint(input: RunInput) {
|
||||
? path.resolve(process.cwd(), '../../../shared/product-archive-sync-checkpoints')
|
||||
: path.resolve(process.cwd(), '../../.local-services/checkpoints/product-archive-sync'))
|
||||
const identity = createHash('sha256').update(process.env.DATABASE_URL || '').digest('hex').slice(0, 12)
|
||||
const checkpoint = new ArchiveSyncCheckpointFile(path.join(directory, `${runKey}-${identity}-${input.opsDirectorOnly ? 'owners' : 'full'}.json`), context)
|
||||
const checkpoint = new ArchiveSyncCheckpointFile(path.join(directory, `${runKey}-${identity}-${input.picturesOnly ? 'pictures' : input.opsDirectorOnly ? 'owners' : 'full'}.json`), context)
|
||||
return turns.backgroundRun(async assertConnected => {
|
||||
await checkpoint.load()
|
||||
const withBatch = <T>(work: () => Promise<T>) => turns.exclusive('background', async assertTurnConnected => {
|
||||
@ -65,6 +68,17 @@ export async function runArchiveEnrichmentWithCheckpoint(input: RunInput) {
|
||||
console.log(JSON.stringify({ kind: 'ARCHIVE_SYNC_PHASE', phase: name, elapsedMs: Math.round(performance.now() - startedAt) }))
|
||||
return result
|
||||
}
|
||||
if (input.picturesOnly) {
|
||||
const picturesResult = await phase('pictures', () => productArchiveMissingPicturesSyncService.syncAll({
|
||||
batchSize: input.batchSize, withBatch, resume: checkpoint.phase<EnrichmentProgress>('pictures')?.result,
|
||||
snapshotDirectory: path.join(directory, `${runKey}-${identity}-picture-sources`), snapshotContext: context,
|
||||
onBatch: async progress => {
|
||||
await checkpoint.save('pictures', progress)
|
||||
console.log(JSON.stringify({ kind: 'ARCHIVE_PICTURE_BATCH', ...progress }))
|
||||
},
|
||||
}))
|
||||
return { picturesResult }
|
||||
}
|
||||
const baseResult = input.syncJstBase ? await phase('base', () => jstSkuProductArchiveFullSyncService.syncAll({
|
||||
apply: true, batchSize: input.jstBatchSize, concurrency: input.jstConcurrency, withBatch,
|
||||
resume: checkpoint.phase<JstSkuProductArchiveFullSyncProgress>('base')?.result,
|
||||
@ -73,7 +87,7 @@ export async function runArchiveEnrichmentWithCheckpoint(input: RunInput) {
|
||||
const opsDirectorResult = input.opsDirectorOnly ? await phase('opsDirector', () => withBatch(() => supplyChainProductArchiveOpsDirectorSyncService.syncAll({ batchSize: input.batchSize }))) : null
|
||||
const ownerWorkflowResult = input.opsDirectorOnly ? null : await phase('ownerWorkflow', () => withBatch(() => productArchiveOwnerWorkflowSyncService.syncAll({ apply: true })))
|
||||
const enrichmentResult = input.opsDirectorOnly ? null : await phase('enrichment', () => supplyChainProductArchiveEnrichmentSyncService.syncAll({
|
||||
batchSize: input.batchSize, withBatch, resume: checkpoint.phase<EnrichmentProgress>('enrichment')?.result,
|
||||
batchSize: input.batchSize, skipPictures: true, withBatch, resume: checkpoint.phase<EnrichmentProgress>('enrichment')?.result,
|
||||
snapshotDirectory: path.join(directory, `${runKey}-${identity}-sources`), snapshotContext: context,
|
||||
onBatch: async (progress, timings) => {
|
||||
assertConnected()
|
||||
@ -83,5 +97,5 @@ export async function runArchiveEnrichmentWithCheckpoint(input: RunInput) {
|
||||
}))
|
||||
const productionTypeResult = input.opsDirectorOnly ? null : await phase('productionType', () => withBatch(() => supplyChainProductArchiveProductionTypeFillService.syncAll({ apply: true, batchSize: input.batchSize })))
|
||||
return { baseResult, opsDirectorResult, ownerWorkflowResult, enrichmentResult, productionTypeResult }
|
||||
})
|
||||
}, input.picturesOnly ? 'pictures' : 'fields')
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ export type EnrichmentProgress = {
|
||||
export type EnrichmentTimings = { sharedMs: number; sourceMs: number; mapMs: number; writeMs: number; elapsedMs: number }
|
||||
export type EnrichmentSyncInput = {
|
||||
batchSize?: number
|
||||
skipPictures?: boolean
|
||||
resume?: EnrichmentProgress
|
||||
snapshotDirectory?: string
|
||||
snapshotContext?: string
|
||||
|
||||
@ -28,9 +28,10 @@ export class SupplyChainProductArchiveEnrichmentSyncService {
|
||||
const snapshot = this.dependencies.snapshotRepository ? await loadArchiveEnrichmentSnapshot({
|
||||
dependencies: this.dependencies, batchSize, directory: input.snapshotDirectory,
|
||||
context: input.snapshotContext, retryRuntime: this.retryRuntime,
|
||||
skipPictures: input.skipPictures,
|
||||
}) : null
|
||||
let offset = snapshot ? snapshotResumeOffset(snapshot.targets, result.lastId, batchSize) : 0
|
||||
const shared = await sources.loadShared(snapshot?.pictures)
|
||||
const shared = await sources.loadShared(input.skipPictures ? { df: [], fill: [] } : snapshot?.pictures)
|
||||
timings.sharedMs = performance.now() - startedAt
|
||||
while (true) {
|
||||
const sourceStarted = performance.now()
|
||||
|
||||
@ -15,6 +15,7 @@ const requiredColumns: Record<EnrichmentSnapshotQuery, string[]> = {
|
||||
}
|
||||
|
||||
export async function loadArchiveEnrichmentSnapshot(input: {
|
||||
skipPictures?: boolean
|
||||
dependencies: EnrichmentDependencies; batchSize: number; directory?: string; context?: string; retryRuntime?: Partial<EnrichmentRetryRuntime>
|
||||
}) {
|
||||
const { dependencies: deps, batchSize } = input
|
||||
@ -30,14 +31,16 @@ export async function loadArchiveEnrichmentSnapshot(input: {
|
||||
const barcodes = [...new Set(targets.map(row => row.barcode.trim().toUpperCase()).filter(Boolean))]
|
||||
const requested: Record<EnrichmentSnapshotQuery, EnrichmentSnapshotRequest> = {
|
||||
prices: barcodes, inventory: barcodes, clearance: barcodes,
|
||||
pictures: targets.filter(row => normalizeIdentity(row.barcode).startsWith('DF') || !row.image).map(row => row.barcode.trim().toUpperCase()),
|
||||
pictures: targets.filter(row => !row.image?.trim()).map(row => normalizeIdentity(row.barcode)),
|
||||
stocks: targets.map((row, index) => ({ batchIndex: Math.floor(index / batchSize), barcode: row.barcode.trim(), sku: row.sku.trim() })),
|
||||
suppliers: [...new Set(targets.map(row => row.supplierName.trim()).filter(Boolean))],
|
||||
warehouses: [...new Set(targets.map(row => row.inOutWarehouse.trim()).filter(Boolean))],
|
||||
}
|
||||
const runtime = createEnrichmentRetryRuntime(input.retryRuntime)
|
||||
const rows: { [K in EnrichmentSnapshotQuery]?: EnrichmentSnapshotRows[K][] } = {}
|
||||
const queue: EnrichmentSnapshotQuery[] = ['pictures', 'inventory', 'stocks', 'prices', 'clearance', 'suppliers', 'warehouses']
|
||||
if (input.skipPictures) rows.pictures = []
|
||||
const queue: EnrichmentSnapshotQuery[] = ['inventory', 'stocks', 'prices', 'clearance', 'suppliers', 'warehouses']
|
||||
if (!input.skipPictures) queue.push('pictures')
|
||||
let next = 0, failed: unknown
|
||||
const read = async <K extends EnrichmentSnapshotQuery>(kind: K) => {
|
||||
const data = await (kind === 'inventory' ? inventoryCache : cache).read(kind, () => readEnrichmentSource({ source: `snapshot-${kind}`,
|
||||
@ -79,7 +82,7 @@ export async function loadArchiveEnrichmentSnapshot(input: {
|
||||
const batchTargets = original.map(row => {
|
||||
const fresh = byId.get(row.id)
|
||||
if (!fresh || (['barcode', 'sku', 'supplierName', 'inOutWarehouse'] as const).some(key => fresh[key] !== row[key])) throw new Error('ARCHIVE_SOURCE_TARGET_CHANGED_USE_NEW_RUN_KEY')
|
||||
if (!normalizeIdentity(row.barcode).startsWith('DF') && row.image && !fresh.image) throw new Error('ARCHIVE_SOURCE_IMAGE_CLEARED_USE_NEW_RUN_KEY')
|
||||
if (!input.skipPictures && row.image?.trim() && !fresh.image?.trim()) throw new Error('ARCHIVE_SOURCE_IMAGE_CLEARED_USE_NEW_RUN_KEY')
|
||||
return fresh
|
||||
})
|
||||
return { targets: batchTargets, lookups: { prices: rows.prices!, publicAvailableStocks: rows.inventory!, clearanceStocks,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user