feat(sync): stat snapshot return path with version replacement
P2 Task 9 统计回传(ov→cn): - cn 迁移:albums 增 viewCountReplica/statsVersion/statsSyncedAt、 photos 增 statsVersion(like_count 已有副本位;无 VARCHAR 新列不涉校对手决) - cn 接收端 POST /v1/internal/sync/stat-snapshots(InternalSyncGuard): 整批单事务,逐快照 updateMany WHERE statsVersion < statVersion —— 仅更高 statVersion 以权威 total 整体替换副本(绝不相加),重复/乱序幂等忽略; accepted 只数实际应用条数;views 应用同时推进 statsSyncedAt(A27 展示) - ov 回传发送器 services/sync/stat-return.ts:聚合 outbox_stat_events 未发送 行按(kind, photoId|albumId)取 MAX(statVersion) 折叠突发 → HMAC 推送 → 200 后按计数器标记截至该版本全部源行 sentAt;失败留待下轮重发;main.ts 第三循环 STAT_RETURN_INTERVAL_MS(默认 60s,env 可调) - 契约 AlbumSummary + statsSyncedAt(string|null readOnly,+gen);listAlbums/ getAlbum 经 toSummaryResponse 暴露(管理 UI 列留 P4a) - e2e(services/sync stat-return.e2e-spec,7 例):逐次点赞回传替换式收敛 (2→5→10 非累加)、浏览窗口去重回传 + statsSyncedAt、重复回传 accepted=0 值不动(A27 不重复累计)、乱序高版本替换(total 可下调)+ 低版本忽略、 发送端折叠只发最高版本且被折叠行随批确认、管理列表 likeCount/statsSyncedAt 展示、新端点 401/400 守卫 Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -1,14 +1,21 @@
|
||||
// services/api/src/sync/dto.ts —— 内部同步端点请求 DTO(P2 Task 3
|
||||
// bootstrap/reconcile;Task 4 增 digest)。
|
||||
// 契约权威:openapi.yaml [internal](syncBootstrap/syncReconcile/syncDigest)。
|
||||
// 经全局 ValidationPipe(whitelist)剥离未知字段;校验失败 400 VALIDATION_FAILED。
|
||||
// bootstrap/reconcile;Task 4 增 digest;Task 9 增 stat-snapshots)。
|
||||
// 契约权威:openapi.yaml [internal](syncBootstrap/syncReconcile/syncDigest/
|
||||
// syncStatSnapshots)。经全局 ValidationPipe(whitelist)剥离未知字段;校验
|
||||
// 失败 400 VALIDATION_FAILED。
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
ArrayMinSize,
|
||||
IsDateString,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
ValidateIf,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
|
||||
/** 契约 SyncEntityType(slot-state 预留——与 openapi enum 同步)。 */
|
||||
@@ -52,3 +59,48 @@ export class DigestRequestDto {
|
||||
@IsString()
|
||||
albumId?: string;
|
||||
}
|
||||
|
||||
/** 契约 SyncStatKind(与 openapi enum 同步)。 */
|
||||
export const SYNC_STAT_KINDS = ['likes', 'views'] as const;
|
||||
|
||||
/**
|
||||
* 契约 StatSnapshot(Task 9 ov→cn 统计快照单元)。kind=likes 时 photoId 必填
|
||||
* (ValidateIf 条件校验,违反 → 400);kind=views 时 photoId 即使携带也仅作
|
||||
* 透传字段,接收端按 albumId 应用(相册级快照无照片位)。
|
||||
*/
|
||||
export class StatSnapshotDto {
|
||||
// 仅 kind=likes 时校验(条件为 true 时 undefined 也过不了 IsString → 400,
|
||||
// 即契约「likes 时 photoId 必填」);kind=views 时跳过、接收端忽略该字段。
|
||||
@ValidateIf((o: StatSnapshotDto) => o.kind === 'likes')
|
||||
@IsString()
|
||||
photoId?: string;
|
||||
|
||||
@IsString()
|
||||
albumId!: string;
|
||||
|
||||
@IsIn(SYNC_STAT_KINDS)
|
||||
kind!: (typeof SYNC_STAT_KINDS)[number];
|
||||
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
total!: number;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
statVersion!: number;
|
||||
|
||||
@IsString()
|
||||
source!: string;
|
||||
|
||||
@IsDateString()
|
||||
confirmedAt!: string;
|
||||
}
|
||||
|
||||
/** 契约 StatSnapshotRequest(Task 9):批次上限对齐 SYNC_BATCH_SIZE 量级。 */
|
||||
export class StatSnapshotRequestDto {
|
||||
@ArrayMinSize(1)
|
||||
@ArrayMaxSize(100)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => StatSnapshotDto)
|
||||
snapshots!: StatSnapshotDto[];
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// services/api/src/sync/sync.controller.ts —— cn 侧内部同步端点(P2 Task 3:
|
||||
// bootstrap/reconcile;Task 4 增 digest)。契约权威:openapi.yaml [internal]
|
||||
// (POST /internal/sync/bootstrap、POST /internal/sync/reconcile、
|
||||
// POST /internal/sync/digest)。鉴权:InternalSyncGuard(HMAC 原始请求体
|
||||
// bootstrap/reconcile;Task 4 增 digest;Task 9 增 stat-snapshots)。契约权威:
|
||||
// openapi.yaml [internal](POST /internal/sync/bootstrap、
|
||||
// POST /internal/sync/reconcile、POST /internal/sync/digest、
|
||||
// POST /internal/sync/stat-snapshots)。鉴权:InternalSyncGuard(HMAC 原始请求体
|
||||
// 签名 + 时间戳 ±300s,密钥 SYNC_INTERNAL_KEY 仅 env)。仅 cn 入口装配
|
||||
// (app-cn.module);ov 入口的 content-batches 在 sync-inbox 模块(同守卫)。
|
||||
import { Body, Controller, HttpCode, Post, UseGuards } from '@nestjs/common';
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
BootstrapRequestDto,
|
||||
DigestRequestDto,
|
||||
ReconcileRequestDto,
|
||||
StatSnapshotRequestDto,
|
||||
} from './dto';
|
||||
import { SyncService } from './sync.service';
|
||||
|
||||
@@ -38,4 +40,11 @@ export class SyncController {
|
||||
digest(@Body() dto: DigestRequestDto) {
|
||||
return this.sync.digest(dto.albumId);
|
||||
}
|
||||
|
||||
/** 统计快照回传(Task 9 ov→cn):版本替换式副本更新(见 service 设计说明)。 */
|
||||
@Post('stat-snapshots')
|
||||
@HttpCode(200)
|
||||
statSnapshots(@Body() dto: StatSnapshotRequestDto) {
|
||||
return this.sync.receiveStatSnapshots(dto.snapshots);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import { Injectable } from '@nestjs/common';
|
||||
import type { components } from '@photo/contracts';
|
||||
import type { Prisma } from '@photo/db-cn';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { StatSnapshotDto } from './dto';
|
||||
import {
|
||||
type AlbumCategoryInput,
|
||||
buildAlbumUpdatedPayload,
|
||||
@@ -41,6 +42,7 @@ import {
|
||||
export type BootstrapResponse = components['schemas']['BootstrapResponse'];
|
||||
export type ReconcileResponse = components['schemas']['ReconcileResponse'];
|
||||
export type DigestResponse = components['schemas']['DigestResponse'];
|
||||
export type StatSnapshotResponse = components['schemas']['StatSnapshotResponse'];
|
||||
export type SyncEventWire = components['schemas']['SyncEvent'];
|
||||
|
||||
/** 线格式 schema 版本(契约 SyncEvent.schemaVersion 当前为 1)。 */
|
||||
@@ -502,6 +504,58 @@ export class SyncService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计快照回传接收(P2 Task 9,ov→cn):整批单事务,逐快照做**版本替换**——
|
||||
* 仅当 cn 侧 statsVersion < snapshot.statVersion 时以权威 total 整体替换副本
|
||||
* (绝不相加),重复回传(同版本)与乱序(更低版本)均幂等忽略。这是 A27
|
||||
* 「不重复累计」的接收端锚点:total 恒为 ov 权威快照值(非增量),即使未来
|
||||
* 出现下调修正(total 变小),更高版本也照常替换——版本是唯一权威。
|
||||
*
|
||||
* 副本位:likes → photos.likeCount(比较位 photos.statsVersion);
|
||||
* views → albums.viewCountReplica(比较位 albums.statsVersion,
|
||||
* 同时推进 statsSyncedAt=本批应用时刻,A27 展示同步时间;likes 快照的
|
||||
* photoId 在 cn 必然存在(照片源于 cn),不存在/更旧版本 → 该条不计入
|
||||
* accepted,不报错——与「旧版本忽略不计」同一幂等口径)。
|
||||
* accepted 只数**实际应用**(新版本生效)的条数(契约:旧版本被忽略的不计)。
|
||||
*/
|
||||
async receiveStatSnapshots(
|
||||
snapshots: StatSnapshotDto[],
|
||||
): Promise<StatSnapshotResponse> {
|
||||
const syncedAt = new Date();
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
let accepted = 0;
|
||||
for (const snapshot of snapshots) {
|
||||
if (snapshot.kind === 'likes' && snapshot.photoId !== undefined) {
|
||||
const applied = await tx.photos.updateMany({
|
||||
where: {
|
||||
id: snapshot.photoId,
|
||||
statsVersion: { lt: snapshot.statVersion },
|
||||
},
|
||||
data: {
|
||||
likeCount: snapshot.total,
|
||||
statsVersion: snapshot.statVersion,
|
||||
},
|
||||
});
|
||||
accepted += applied.count;
|
||||
} else if (snapshot.kind === 'views') {
|
||||
const applied = await tx.albums.updateMany({
|
||||
where: {
|
||||
id: snapshot.albumId,
|
||||
statsVersion: { lt: snapshot.statVersion },
|
||||
},
|
||||
data: {
|
||||
viewCountReplica: snapshot.total,
|
||||
statsVersion: snapshot.statVersion,
|
||||
statsSyncedAt: syncedAt,
|
||||
},
|
||||
});
|
||||
accepted += applied.count;
|
||||
}
|
||||
}
|
||||
return { accepted };
|
||||
});
|
||||
}
|
||||
|
||||
/** 相册 id 集合 → 分类快照输入(分类行 + 翻译行配对;升序确定性由构建器排)。 */
|
||||
private async categoryInputsByAlbumIds(
|
||||
albumIds: string[],
|
||||
|
||||
Reference in New Issue
Block a user