// services/sync/src/sender.ts —— cn→ov outbox 发送器(P2 Task 3)。 // 单次推送 runOnce():从 cn 库 outbox_events 取 deliveredAt 为空的事件一批, // 转内部同步线格式(openapi SyncEvent)后 HMAC 签名推送 ov 入口 // POST /v1/internal/sync/content-batches;响应 acceptedEventIds 即「受理」锚点 // (含幂等重复),据此回写 deliveredAt。 // // 高优先级排序:**显式两段取数**(先 high 后其余,段内 occurredAt 升序)而非 // ORDER BY priority DESC——'high' < 'normal'(字典序 h { const sender = new OutboxSender(options); for (let round = 0; round < DELIVER_MAX_ROUNDS; round++) { const stats = await sender.runOnce(); if (stats.picked === 0) { return; } } throw new Error( `deliverPendingOnce 超时:${DELIVER_MAX_ROUNDS} 轮后 outbox 仍有未投递事件`, ); } export class OutboxSender { private readonly batchSize: number; private readonly timeoutMs: number; private readonly endpoint: string; constructor(private readonly options: OutboxSenderOptions) { this.batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE; this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; // 基址容错:吞并尾斜杠再拼路径,端点只此一处。 this.endpoint = `${options.ovApiUrl.replace(/\/+$/, '')}${CONTENT_BATCHES_PATH}`; } /** 单轮推送:取批 → 线格式 → 签名推送 → 按受理回写 deliveredAt。 */ async runOnce(): Promise { const rows = await this.pickBatch(); if (rows.length === 0) { return { picked: 0, acceptedEventIds: [], applied: 0 }; } const events = rows.map((row) => this.toWireEvent(row)); const response = await this.push(events); // 只标记 ov 明确受理的 eventId(且仍为未投递),幂等可重入。 if (response.acceptedEventIds.length > 0) { await this.options.prisma.outbox_events.updateMany({ where: { id: { in: response.acceptedEventIds }, deliveredAt: null, }, data: { deliveredAt: new Date() }, }); } this.options.logger?.debug( { picked: rows.length, accepted: response.acceptedEventIds.length, applied: response.applied, }, 'outbox batch pushed', ); return { picked: rows.length, acceptedEventIds: response.acceptedEventIds, applied: response.applied, }; } /** * 两段取数(见文件头排序说明):high 段占满批则不发第二查;两查之间存在 * 微小时序窗口(新事件落入两查之间)——对轮询器无害,下一轮补上。 */ private async pickBatch(): Promise { const prisma = this.options.prisma; const high = await prisma.outbox_events.findMany({ where: { deliveredAt: null, priority: 'high' }, orderBy: [{ occurredAt: 'asc' }, { id: 'asc' }], take: this.batchSize, // 只取发送器关心的列(payload JsonValue 原样透传)。 select: { id: true, type: true, albumId: true, photoId: true, entityVersion: true, priority: true, payload: true, occurredAt: true, }, }); if (high.length >= this.batchSize) { return high; } const rest = await prisma.outbox_events.findMany({ where: { deliveredAt: null, priority: { not: 'high' } }, orderBy: [{ occurredAt: 'asc' }, { id: 'asc' }], take: this.batchSize - high.length, select: { id: true, type: true, albumId: true, photoId: true, entityVersion: true, priority: true, payload: true, occurredAt: true, }, }); return [...high, ...rest]; } /** * outbox 行 → SyncEvent 线格式。entityId 按实体类型取自不同位置: * album → albumId 列;photo → photoId 列;category/asset/slot-state/ad → * 载荷内的 categoryId/assetId/slotId/adId(outbox 表无此四列)。映射缺料 * 抛错(fail-fast:本轮不推、不标记,错误日志暴露;cn 侧发射器按构造保证 * 不缺料)。 */ private toWireEvent(row: OutboxRow): SyncEventWire { const type = row.type as OutboxEvent['type']; const entityType = syncEntityTypeOfOutboxType(type); const payload = (row.payload ?? {}) as Record; let entityId: string; if (entityType === 'album') { entityId = row.albumId; } else if (entityType === 'photo') { if (row.photoId === null) { throw new Error(`outbox 事件 ${row.id}(${type})缺 photoId,无法推导 entityId`); } entityId = row.photoId; } else if (entityType === 'slot-state') { if (typeof payload.slotId !== 'string') { throw new Error(`outbox 事件 ${row.id}(${type})载荷缺 slotId,无法推导 entityId`); } entityId = payload.slotId; } else if (entityType === 'ad') { if (typeof payload.adId !== 'string') { throw new Error(`outbox 事件 ${row.id}(${type})载荷缺 adId,无法推导 entityId`); } entityId = payload.adId; } else if (typeof payload.categoryId === 'string') { entityId = payload.categoryId; } else if (typeof payload.assetId === 'string') { entityId = payload.assetId; } else { throw new Error(`outbox 事件 ${row.id}(${type})载荷缺实体 ID,无法推导 entityId`); } const tombstone = isTombstoneOutboxType(type); return { eventId: row.id, schemaVersion: 1, entityType, entityId, albumId: row.albumId, entityVersion: row.entityVersion, // 线格式 tombstone 显式携带(生成类型必填:openapi-typescript 把带 // default 的属性渲染为非可选)。 tombstone, priority: row.priority === 'high' ? 'high' : 'normal', payload: payload as SyncEventWire['payload'], }; } /** * 签名推送:同一 JSON.stringify 产物既作签名输入也作请求体(原始字节一致, * 接收端 rawBody 验签才能通过——见 contracts/internal-sync.ts 头注)。 * 非 2xx / 响应形状异常均抛错(调用方整批重试)。 */ private async push(events: SyncEventWire[]): Promise { const rawBody = JSON.stringify({ batch: events }); const timestamp = Math.floor(Date.now() / 1000).toString(); let response: Response; try { response = await fetch(this.endpoint, { method: 'POST', headers: { 'content-type': 'application/json', [SYNC_TIMESTAMP_HEADER]: timestamp, [SYNC_SIGNATURE_HEADER]: signSyncBody(this.options.internalKey, rawBody), }, body: rawBody, signal: AbortSignal.timeout(this.timeoutMs), }); } catch (err) { throw new Error( `content-batches 请求失败(${this.endpoint}):${err instanceof Error ? err.message : String(err)}`, ); } if (!response.ok) { const body = await response.text().catch(() => ''); throw new Error( `content-batches 非 2xx(${this.endpoint}):status=${response.status} body=${body.slice(0, 500)}`, ); } const data: unknown = await response.json(); if ( typeof data !== 'object' || data === null || !Array.isArray((data as ContentBatchResponse).acceptedEventIds) || !((data as ContentBatchResponse).acceptedEventIds as unknown[]).every( (id) => typeof id === 'string', ) || typeof (data as ContentBatchResponse).applied !== 'number' ) { throw new Error('content-batches 响应形状异常(acceptedEventIds/applied 缺失)'); } return data as ContentBatchResponse; } }