feat(ov): public read api on replicas with hot sorting

P2 Task 6(ov 公开读 API + viewer 切换):
- ov 装配 PublicOvModule(仅 app-ov.module):/public/albums/{token}、
  /photos、/photos/{id} 三端点同契约读 ov 副本——translations/categories
  自 JSON 列解析(防御性过滤),banner 经 ov 侧 STORAGE_PORT_OV 预签名
  (同本地 MinIO;只读属约定,真实 OSS 只读凭证 P5),viewCount 取
  album_stats 权威累计(无行默认 0;计数端点 Task 8 接线)
- 排序:latest=发布时间 keyset(shared/cursor.ts 同 cn);hot=likeTotal
  desc + photoId desc 决胜,顺序按 `${albumId}|${category}` 短期快照
  (内存 TTL 默认 30s,HOT_SORT_TTL_MS 惰性读取)——计数逐请求现读、
  顺序冻结窗口内一致,偏移游标(base64url 整数)在快照内严格稳定;
  非法 sort 400 VALIDATION_FAILED(cn 不感知该参数)
- 契约:viewCount 放宽为 integer|null(cn null、ov 权威值);
  listPublicPhotos 增 sort 枚举(latest|hot,缺省 latest);
  PhotoPublishedPayload 增 categoryId——补上 Tasks 3/4 管线缺口
  (payloads/publish.service/sync-inbox 投影 + 关联测试随改)
- e2e(services/api/test/public-ov.e2e-spec.ts,7 用例):双入口同进程
  起 cn+ov,cn API 种子→真实发送管线投递;断言相册/列表/单图与 cn
  深等(仅签名 URL 剔除)、banner 真字节、参数矩阵 400/404、hot 排序
  TTL 内快照(计数新/顺序旧)+TTL 过期翻转+偏移翻页、隐藏/下线/紧急
  停用逐态撤下
- viewer 切 ov:API 基址 VITE_API_BASE(缺省 http://127.0.0.1:8081,
  空串=同源网关;Vite 只读 apps/viewer/.env*,根 .env 对前端无效),
  移除 /v1 dev 代理(CORS_ORIGINS 增 127.0.0.1:5175 直连两形);
  playwright webServer 增 dev:ov;e2e 夹具 flushSync(albumId)=cn
  bootstrap 快照 + deliverPendingOnce(sender 新导出)经真实管线投影
  种子,deleteSeededPhoto 改软删让墓碑可同步;14 个 Playwright 全绿
  (journey 管理/staffB 腿仍走 cn 8080)

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
浅念
2026-09-18 17:05:56 +08:00
parent eac8da6d6c
commit 0fcf18cc5c
26 changed files with 1355 additions and 40 deletions
+6 -2
View File
@@ -3,8 +3,9 @@
// request-id + 全局异常过滤器 + 全局校验管道 + /v1/health),但**显式挑选**
// ov 角色模块:cn 专属域(auth/albums/uploads/photos/admin——写路径与 MinIO
// 上传)不装配;P2 Task 3 加入 sync-inbox(内容事件接收 + 副本投影);Task 5
// 加入 emergency(海外紧急停用通道,独立于同步);公开读、likes/visits、
// WS 网关自 Task 6+ 起逐个加入。cn 模块保持原样,两入口互不影响。
// 加入 emergency(海外紧急停用通道,独立于同步);公开读自 Task 6 起装配
// (public-ov:读 photos_ov 副本的同形契约端点 + hot 排序);likes/visits、
// WS 网关自 Task 7+ 起逐个加入。cn 模块保持原样,两入口互不影响。
import {
type MiddlewareConsumer,
Module,
@@ -16,6 +17,7 @@ import { LoggerModule } from 'nestjs-pino';
import { AllExceptionsFilter } from './all-exceptions.filter';
import { EmergencyModule } from './emergency/emergency.module';
import { HealthController } from './health.controller';
import { PublicOvModule } from './public-ov/public-ov.module';
import { RequestIdMiddleware } from './request-id.middleware';
import { createLoggerOptions } from './shared/logger-options';
import { SyncInboxModule } from './sync-inbox/sync-inbox.module';
@@ -27,6 +29,8 @@ import { SyncInboxModule } from './sync-inbox/sync-inbox.module';
SyncInboxModule,
// 海外紧急停用通道(P2 Task 5):POST /v1/internal/emergency/disable|enable。
EmergencyModule,
// ov 公开读(P2 Task 6):/public/albums/* 读 ov 副本(含 sort=hot 快照)。
PublicOvModule,
],
controllers: [HealthController],
providers: [
@@ -0,0 +1,82 @@
// services/api/src/public-ov/public-ov.controller.ts —— ov 公开端点
// (P2 Task 6)。路由/方法名与 cn public.controller 一一对应(契约同形:
// 路径前缀不变、部署域名区分),差异仅两处:
// · 新增 sort 查询参数(latest|hot;hot 仅 ov 实现——cn 不感知,见契约
// listPublicPhotos sort 描述)。非法取值 400 VALIDATION_FAILED(与
// limit/cursor 同口径;locale 仍保持「非法值静默回退」的 Task 5 决策);
// · 服务层读 ov 副本(PublicOvService)。
// limit/cursor 规整直接复用 cn public.controller 的解析函数(缺省 30、1..60、
// cursor 长度上限)——两入口共享同一套校验源,杜绝漂移。匿名访问(无
// SessionGuard;认证由持有 publicToken 取代)。
import { Controller, Get, Param, Query } from '@nestjs/common';
// limit 规整复用 cn public.controller 的导出(同一校验源,杜绝两入口漂移)。
import { parsePublicPhotoLimit } from '../public/public.controller';
import { parseCursor } from '../shared/pagination';
import { validationFailed } from '../albums/support';
import {
type PublicAlbumResponse,
type PublicPhotoDetailResponse,
type PublicPhotoListResponse,
PublicOvService,
} from './public-ov.service';
/** sort 查询参数解析:缺省 latest;非法 → 400(见文件头口径说明)。 */
export function parsePublicPhotoSort(
raw: string | undefined,
): 'latest' | 'hot' {
if (raw === undefined || raw === '') {
return 'latest';
}
if (raw === 'latest' || raw === 'hot') {
return raw;
}
throw validationFailed('sort 必须是 latest 或 hot');
}
@Controller('public/albums')
export class PublicOvController {
constructor(private readonly publicService: PublicOvService) {}
/** 公开相册信息:locale 缺省/非法/无条目均按 defaultLocale 回退(200)。 */
@Get(':token')
getPublicAlbum(
@Param('token') token: string,
@Query('locale') locale: string | undefined,
): Promise<PublicAlbumResponse> {
return this.publicService.getPublicAlbum(token, locale);
}
/**
* 公开照片列表:latest=(publishedAt,photoId) 键集游标(缺省);hot=点赞
* 快照 offset 游标(30s 缓冲,服务层语义)。category 限本册分类。
*/
@Get(':token/photos')
listPublicPhotos(
@Param('token') token: string,
@Query('category') category: string | undefined,
@Query('locale') locale: string | undefined,
@Query('cursor') cursor: string | undefined,
@Query('limit') limit: string | undefined,
@Query('sort') sort: string | undefined,
): Promise<PublicPhotoListResponse> {
return this.publicService.listPublicPhotos(token, {
category,
// locale 仅保证「不因非法值报 400」,列表无语言敏感字段,不向下传。
cursor: parseCursor(cursor),
limit: parsePublicPhotoLimit(limit),
sort: parsePublicPhotoSort(sort),
});
}
/**
* 公开单图:深链定位;隐藏/删除/换册后的旧链接 404 PHOTO_NOT_PUBLIC。
* 每次调用现签 thumb/browse(契约规定的过期刷新入口)。
*/
@Get(':token/photos/:photoId')
getPublicPhoto(
@Param('token') token: string,
@Param('photoId') photoId: string,
): Promise<PublicPhotoDetailResponse> {
return this.publicService.getPublicPhoto(token, photoId);
}
}
@@ -0,0 +1,17 @@
// services/api/src/public-ov/public-ov.module.ts —— ov 公开(观众端)读模块
// (P2 Task 6)。仅 ov 入口装配(app-ov.module 显式挑选;cn 的 PublicModule
// 互不影响)。装配:PublicOvController/PublicOvService + OvPrismaModule
// (非 @Global,显式 import)+ STORAGE_PORT_OV(ov 只读存储约定,见
// storage-ov.provider 头注)。无认证语义(公开端点匿名)。
import { Module } from '@nestjs/common';
import { OvPrismaModule } from '../prisma-ov/ov-prisma.module';
import { PublicOvController } from './public-ov.controller';
import { PublicOvService } from './public-ov.service';
import { storageOvProvider } from './storage-ov.provider';
@Module({
imports: [OvPrismaModule],
controllers: [PublicOvController],
providers: [PublicOvService, storageOvProvider],
})
export class PublicOvModule {}
@@ -0,0 +1,459 @@
// services/api/src/public-ov/public-ov.service.ts —— ov(海外观众)公开读逻辑
// (P2 Task 6)。契约权威与 cn public.service 同一来源(openapi tags [public],
// 路径不变、部署域名区分)——**契约同形**是本域的验收口径:响应形状一律取
// @photo/contracts 生成类型,与 cn 逐字段对齐(e2e deep-eval 见
// test/public-ov.e2e-spec.ts)。与 cn 实现的本质差异:
// · 数据源是副本表(albums_ov/photos_ov,translations/categories 反规范化
// JSON,三对象键内联 photos_ov——无变体表),无关联行二次查询;
// · 相册可见性叠加 ov 本地紧急停用位(isAlbumVisibleOv,Task 5 单一实现,
// 与 cn findPublicAlbum 同形:任一不满足统一 404 ALBUM_NOT_PUBLIC);
// · viewCount 是真实值:album_stats 权威累计(无行默认 0;计数端点 Task 8
// 接线,此处只读列)——cn 侧仍是占位 null(Task 9 副本回填);
// · banner 是单键(albums_ov.bannerAssetKey,asset.updated 事件投影的「最新
// 生效 banner」):cn 侧语言偏好解析(locale 行 → 全局行)在 ov 副本上
// 退化为最新键——多语言 banner 的 ov 侧精确解析登记为 P5 展示 refinement
// (本地仿真 e2e 用单全局 banner 验证同形);
// · 列表新增 sort=hot(plan Task 6 / 技术方案 §7):likeTotal 倒序 + photoId
// 倒序决胜,**短期快照语义**——每相册内存缓存排好序的 photoId 清单
// (TTL 缺省 30s,env HOT_SORT_TTL_MS 可调,惰性读取),窗口内翻页对同一
// 快照切片(offset 游标在冻结清单上严格稳定),不做失效广播:30s 窗口
// 外自然过期重算(点赞计数仍逐条现读,仅顺序是快照)。
// 防御语义与 cn 对齐:发布副本缺宽高 → 列表跳过 / 单图 404(公开页不因单张
// 脏数据整页失败);defaultLocale 翻译条目缺失属装配异常 → 5xx 兜底。
import { HttpStatus, Inject, Injectable } from '@nestjs/common';
import type { components } from '@photo/contracts';
import { ErrorCodes } from '@photo/contracts';
import { ApiException } from '../api-exception';
import { ALBUM_LOCALES, type AlbumLocale } from '../albums/dto';
import { validationFailed } from '../albums/support';
import { isAlbumVisibleOv } from '../shared/album-visibility';
import {
decodeKeysetCursor,
encodeKeysetCursor,
keysetWhereDesc,
} from '../shared/cursor';
import { OvPrismaService } from '../prisma-ov/ov-prisma.module';
import { signedUrlTtlSeconds } from '../uploads/support';
import { albumNotPublic, photoNotPublic } from '../public/support';
import { STORAGE_PORT_OV } from './storage-ov.provider';
import type { StoragePort } from '@photo/storage';
export type PublicAlbumResponse = components['schemas']['PublicAlbum'];
export type PublicPhotoListResponse =
components['schemas']['PublicPhotoList'];
export type PublicPhotoDetailResponse =
components['schemas']['PublicPhotoDetail'];
type SignedUrlResponse = components['schemas']['SignedUrl'];
/** 与 cn public.service 同值(契约 listPublicPhotos limit bounds)。 */
export const DEFAULT_PUBLIC_PHOTO_PAGE_SIZE = 30;
export const MAX_PUBLIC_PHOTO_PAGE_SIZE = 60;
/** HOT_SORT_TTL_MS 缺省 30s(技术方案 §7 快照缓冲;与 .env.example 同步)。 */
export const DEFAULT_HOT_SORT_TTL_MS = 30_000;
/** 逐请求惰性读取快照 TTL(同 signedUrlTtlSeconds 模式:测试可进程内调 env)。 */
export function hotSortTtlMs(): number {
const parsed = Number.parseInt(process.env.HOT_SORT_TTL_MS ?? '', 10);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_HOT_SORT_TTL_MS;
}
/** albums_ov.translations JSON 元素形状(sync payload 原文,cn 行可空字段保留)。 */
interface TranslationEntry {
locale: string;
title: string;
description: string | null;
venue: string | null;
address: string | null;
}
/** albums_ov.categories JSON 元素形状(sync-inbox 投影结构)。 */
interface CategoryEntry {
id: string;
sortOrder: number;
translations: Array<{ locale: string; name: string }>;
}
/** 热门排序快照:冻结的 photoId 有序清单 + 过期时刻(见文件头快照说明)。 */
interface HotSnapshot {
ids: readonly string[];
expiresAt: number;
}
/**
* 热门快照 offset 游标:base64url JSON 数字(快照内下一页起始下标)。快照在
* TTL 内冻结,下标分页严格稳定(无并发漂移);解码失败 → null(调用方 400,
* 与 latest 游标同语义)。两种模式的游标互不通用(opaque,各解码各的)。
*/
export function encodeHotCursor(offset: number): string {
return Buffer.from(JSON.stringify(offset), 'utf8').toString('base64url');
}
export function decodeHotCursor(raw: string): number | null {
if (raw === '') {
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
} catch {
return null;
}
return typeof parsed === 'number' && Number.isInteger(parsed) && parsed >= 0
? parsed
: null;
}
@Injectable()
export class PublicOvService {
/** 每相册热门快照(进程内单例状态;TTL 过期懒重算,无失效广播)。 */
private readonly hotSnapshots = new Map<string, HotSnapshot>();
constructor(
private readonly prisma: OvPrismaService,
@Inject(STORAGE_PORT_OV) private readonly storage: StoragePort,
) {}
/**
* 公开相册信息:publicToken → albums_ov 副本 → isAlbumVisibleOv → 翻译回退
* 解析(translations JSON)→ 分类(categories JSON,sortOrder 升序 + id 决胜
* —— cn 侧由 ORDER BY 保证,副本在内存排序)→ banner 现签 → viewCount
* (album_stats 真实值,无行默认 0)。
*/
async getPublicAlbum(
token: string,
localeRaw: string | undefined,
): Promise<PublicAlbumResponse> {
const album = await this.findPublicAlbumOv(token);
const translations = this.translationEntries(album.translations);
const resolved = this.resolveTranslation(
album.defaultLocale,
translations,
localeRaw,
);
const categories = this.categoryEntries(album.categories)
.slice()
.sort((a, b) => a.sortOrder - b.sortOrder || (a.id < b.id ? -1 : 1));
const banner =
album.bannerAssetKey === null
? null
: await this.presign(album.bannerAssetKey);
const stats = await this.prisma.album_stats.findUnique({
where: { albumId: album.albumId },
select: { viewCount: true },
});
return {
publicToken: album.publicToken,
resolvedLocale: resolved.locale,
defaultLocale: album.defaultLocale as AlbumLocale,
timezone: album.timezone,
startAt: (album.startAt ?? new Date(0)).toISOString(),
endAt:
album.endAt === null ? null : album.endAt.toISOString(),
translation: {
locale: resolved.locale,
title: resolved.row.title,
description: resolved.row.description,
venue: resolved.row.venue,
address: resolved.row.address,
},
categories: categories.map((c) => ({
id: c.id,
name: this.resolveCategoryName(
c.translations,
resolved.locale,
album.defaultLocale,
),
sortOrder: c.sortOrder,
})),
banner,
// 真实值(Task 8 的 /visits 端点维护计数;此处只读列,无行 = 0)。
viewCount: stats?.viewCount ?? 0,
};
}
/**
* 公开照片列表。latest(缺省):(publishedAt, photoId) 双列稳定倒序键集游标
* (shared/cursor,与 cn 同一实现——游标编码逐字节同形)。hot:快照清单
* offset 切片(见文件头)。category 过滤校验同 cn:须出现在本相册 categories
* JSON(幽灵/跨册同码 400,防探测)。签名 URL 逐条现签(ov 只读凭证)。
*/
async listPublicPhotos(
token: string,
query: {
category?: string;
cursor?: string;
limit: number;
sort: 'latest' | 'hot';
},
): Promise<PublicPhotoListResponse> {
const album = await this.findPublicAlbumOv(token);
const categoryIds = new Set(
this.categoryEntries(album.categories).map((c) => c.id),
);
if (query.category !== undefined && query.category !== '') {
if (!categoryIds.has(query.category)) {
throw validationFailed('category 不属于该相册');
}
}
const categoryFilter =
query.category !== undefined && query.category !== ''
? { categoryId: query.category }
: {};
if (query.sort === 'hot') {
return this.listHot(album.albumId, categoryFilter, query);
}
let decoded: ReturnType<typeof decodeKeysetCursor> = null;
if (query.cursor !== undefined && query.cursor !== '') {
decoded = decodeKeysetCursor(query.cursor);
if (decoded === null) {
throw validationFailed('cursor 不合法');
}
}
const where = {
albumId: album.albumId,
visibility: 'published',
...categoryFilter,
...(decoded !== null
? keysetWhereDesc('publishedAt', 'photoId', decoded)
: {}),
};
const rows = await this.prisma.photos_ov.findMany({
where,
orderBy: [{ publishedAt: 'desc' }, { photoId: 'desc' }],
take: query.limit + 1, // 多取一条探测 hasMore(同 cn 相册列表)
});
const hasMore = rows.length > query.limit;
const page = hasMore ? rows.slice(0, query.limit) : rows;
const items = await this.toItems(page);
// 游标取自「DB 页末行」(同 cn:被跳过的行不进下一页重扫)。
const last = page.at(-1);
const nextCursor =
hasMore && last !== undefined
? encodeKeysetCursor({
sort: (last.publishedAt ?? new Date(0)).toISOString(),
id: last.photoId,
})
: null;
return { items, nextCursor, hasMore: nextCursor !== null };
}
/**
* 公开单图(深链定位 + 签名刷新入口,每次现签)。校验同 cn:照片不存在 /
* 不属于该相册 / 非 published 统一 404 PHOTO_NOT_PUBLIC;副本缺宽高同 cn
* 防御语义(不可展示 → 404)。
*/
async getPublicPhoto(
token: string,
photoId: string,
): Promise<PublicPhotoDetailResponse> {
const album = await this.findPublicAlbumOv(token);
const photo = await this.prisma.photos_ov.findUnique({
where: { photoId },
});
if (
photo === null ||
photo.albumId !== album.albumId ||
photo.visibility !== 'published' ||
photo.width === null ||
photo.height === null
) {
throw photoNotPublic();
}
return {
photoId: photo.photoId,
width: photo.width,
height: photo.height,
thumb: await this.presign(photo.thumbObjectKey),
browse: await this.presign(photo.browseObjectKey),
likeCount: photo.likeTotal,
publishedAt: (photo.publishedAt ?? new Date(0)).toISOString(),
categoryId: photo.categoryId,
};
}
/** hot 排序页:快照清单(TTL 缓存)offset 切片 → 现取行(跳过中途被撤下的)。 */
private async listHot(
albumId: string,
categoryFilter: { categoryId?: string },
query: { cursor?: string; limit: number },
): Promise<PublicPhotoListResponse> {
let offset = 0;
if (query.cursor !== undefined && query.cursor !== '') {
offset = decodeHotCursor(query.cursor) ?? -1;
if (offset < 0) {
throw validationFailed('cursor 不合法');
}
}
const snapshot = await this.hotSnapshot(albumId, categoryFilter);
const pageIds = snapshot.slice(offset, offset + query.limit);
const hasMore = offset + query.limit < snapshot.length;
if (pageIds.length === 0) {
return { items: [], nextCursor: null, hasMore: false };
}
// 行现取:快照只冻结顺序;可见性/计数逐条现读(中途撤下的照片跳过——
// 页短于 limit 不影响游标推进,同 cn「游标取自 DB 页末行」的越过语义)。
const rows = await this.prisma.photos_ov.findMany({
where: { photoId: { in: pageIds }, visibility: 'published' },
});
const byId = new Map(rows.map((row) => [row.photoId, row]));
const ordered = pageIds
.map((id) => byId.get(id))
.filter((row) => row !== undefined);
const items = await this.toItems(ordered);
const nextCursor = hasMore ? encodeHotCursor(offset + query.limit) : null;
return { items, nextCursor, hasMore: nextCursor !== null };
}
/**
* 热门快照:likeTotal DESC, photoId DESC 的 published photoId 清单,TTL 内
* 复用(category 过滤参与缓存键——不同过滤各自快照,语义独立且互不污染)。
*/
private async hotSnapshot(
albumId: string,
categoryFilter: { categoryId?: string },
): Promise<readonly string[]> {
const key = `${albumId}|${categoryFilter.categoryId ?? ''}`;
const cached = this.hotSnapshots.get(key);
if (cached !== undefined && Date.now() < cached.expiresAt) {
return cached.ids;
}
const rows = await this.prisma.photos_ov.findMany({
where: { albumId, visibility: 'published', ...categoryFilter },
orderBy: [{ likeTotal: 'desc' }, { photoId: 'desc' }],
select: { photoId: true },
});
const ids = rows.map((row) => row.photoId);
this.hotSnapshots.set(key, {
ids,
expiresAt: Date.now() + hotSortTtlMs(),
});
return ids;
}
/** 副本行 → 契约条目(宽高缺失跳过,同 cn 防御语义;键为发布载荷内联键)。 */
private async toItems(
page: Array<{
photoId: string;
width: number | null;
height: number | null;
thumbObjectKey: string;
browseObjectKey: string;
likeTotal: number;
publishedAt: Date | null;
}>,
): Promise<PublicPhotoListResponse['items']> {
const items: PublicPhotoListResponse['items'] = [];
for (const photo of page) {
if (photo.width === null || photo.height === null) {
continue;
}
items.push({
photoId: photo.photoId,
width: photo.width,
height: photo.height,
thumb: await this.presign(photo.thumbObjectKey),
browse: await this.presign(photo.browseObjectKey),
likeCount: photo.likeTotal,
publishedAt: (photo.publishedAt ?? new Date(0)).toISOString(),
});
}
return items;
}
/** publicToken → albums_ov 副本;不存在 / 不可见(含紧急停用)统一 404。 */
private async findPublicAlbumOv(token: string) {
const album = await this.prisma.albums_ov.findUnique({
where: { publicToken: token },
});
if (album === null || !isAlbumVisibleOv(album)) {
throw albumNotPublic();
}
return album;
}
/** translations JSON → 类型化条目(非数组属投影异常,按空集走 5xx 兜底)。 */
private translationEntries(value: unknown): TranslationEntry[] {
return Array.isArray(value)
? (value as TranslationEntry[]).filter(
(t) =>
typeof t?.locale === 'string' && typeof t?.title === 'string',
)
: [];
}
/** categories JSON → 类型化条目(防御同上)。 */
private categoryEntries(value: unknown): CategoryEntry[] {
return Array.isArray(value)
? (value as CategoryEntry[]).filter(
(c) => typeof c?.id === 'string' && Array.isArray(c.translations),
)
: [];
}
/**
* 语言回退解析(需求 4.7,与 cn 同形):请求 locale 合法(契约枚举)且副本
* 有条目 → 用之;否则 defaultLocale。defaultLocale 条目由 cn 创建/更新路径
* 保证必在(同步载荷原样携带),缺行属装配异常 → 5xx(公开端点不得以半
* 翻译状态 200)。
*/
private resolveTranslation(
defaultLocale: string,
entries: TranslationEntry[],
requested: string | undefined,
): { locale: AlbumLocale; row: TranslationEntry } {
const byLocale = new Map(entries.map((row) => [row.locale, row]));
const defaultRow = byLocale.get(defaultLocale);
if (defaultRow === undefined) {
throw new ApiException(
ErrorCodes.INTERNAL_ERROR,
'Internal server error',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
if (
requested !== undefined &&
(ALBUM_LOCALES as readonly string[]).includes(requested)
) {
const row = byLocale.get(requested);
if (row !== undefined) {
return { locale: requested as AlbumLocale, row };
}
}
return { locale: defaultLocale as AlbumLocale, row: defaultRow };
}
/**
* 分类名称解析:resolved locale → defaultLocale → 任一既有条目(locale 升序
* 首,确定性)——与 cn resolveCategoryName 同形;真缺行回退空串保持 200
* (名称为契约必返 string,公开页不因单分类脏数据整页 5xx)。
*/
private resolveCategoryName(
translations: Array<{ locale: string; name: string }>,
resolvedLocale: AlbumLocale,
defaultLocale: string,
): string {
if (translations.length === 0) {
return '';
}
const byLocale = new Map(translations.map((t) => [t.locale, t.name]));
return (
byLocale.get(resolvedLocale) ??
byLocale.get(defaultLocale) ??
([...translations]
.sort((a, b) => (a.locale < b.locale ? -1 : 1))[0]?.name ?? '')
);
}
/** 现签短期 GET 凭证(TTL 惰性读取;同 cn:SigV4 本地计算无网络副作用)。 */
private async presign(objectKey: string): Promise<SignedUrlResponse> {
const ttl = signedUrlTtlSeconds();
const url = await this.storage.presignGet(objectKey, ttl);
return { url, expiresAt: new Date(Date.now() + ttl * 1000).toISOString() };
}
}
@@ -0,0 +1,19 @@
// services/api/src/public-ov/storage-ov.provider.ts —— ov 侧 StoragePort 的 DI
// 装配(P2 Task 6)。与 cn 侧 uploads/storage.provider 同一构造
// (createStorageFromEnv → MinioStorageAdapter),但**只读约定**:
// · ov 公开读域只调用 presignGet(thumb/browse/banner 现签短期 GET 凭证);
// cn 副本对象键与 ov 共用同一本地 MinIO(生产为同桶只读凭证/CDN,P5)。
// · 「只读」是约定而非凭证约束:本地仿真沿用同一对 access key,真实 OSS
// 侧应发放只读凭证(presignGet/head)——登记为 P5 部署事项(计划 Task 6
// 执行注意:真实 OSS 只读凭证随 G1/P5)。
// 独立 DI token(STORAGE_PORT_OV)而非复用 STORAGE_PORT:uploads 模块属 cn
// 角色装配(Redis 队列等),ov 入口不 import UploadsModule,token 不共享实例。
import { createStorageFromEnv, type StoragePort } from '@photo/storage';
/** ov 侧只读存储端口 DI token(public-ov Task 6;likes/visits 后续按需复用)。 */
export const STORAGE_PORT_OV = Symbol('STORAGE_PORT_OV');
export const storageOvProvider = {
provide: STORAGE_PORT_OV,
useFactory: (): StoragePort => createStorageFromEnv(),
};
@@ -17,7 +17,8 @@
// Task 5;categories 仅当载荷携带全量清单(bootstrap/reconcile 快照事件)
// 时整体替换——错过的 category 墓碑由此收敛,增量事件不携带则不动);
// category → albums_ov.categories JSON 元素 upsert/移除;photo.published →
// photos_ov upsert(保留 likeTotal/countVersion 权威计数);photo.hidden/
// photos_ov upsert(含 categoryId——Task 6 公开列表分类过滤/单图同形所需;
// 保留 likeTotal/countVersion 权威计数);photo.hidden/
// deleted → photos_ov.visibility 置位(行不存在 = 从未复制即不可见,缺席
// 即撤下语义);asset → banner 投影 albums_ov.bannerAssetKey(cover/logo
// 仅推进版本,ov schema 无位);
@@ -299,6 +300,7 @@ export class SyncInboxService {
data: {
photoId: event.entityId,
albumId: event.albumId,
categoryId: p.categoryId ?? null,
originalObjectKey: p.objectKey,
thumbObjectKey: p.thumbKey,
browseObjectKey: p.browseKey,
@@ -318,6 +320,7 @@ export class SyncInboxService {
};
if (visibility === 'published') {
const p = payload as PhotoPublishedPayload;
data.categoryId = p.categoryId ?? null;
data.originalObjectKey = p.objectKey;
data.thumbObjectKey = p.thumbKey;
data.browseObjectKey = p.browseKey;
+1
View File
@@ -177,6 +177,7 @@ export function buildPhotoPublishedPayload(
return {
photoId: photo.id,
albumId: photo.albumId,
categoryId: photo.categoryId,
objectKey: photo.objectKey,
thumbKey: thumb.objectKey,
browseKey: browse.objectKey,
+1
View File
@@ -542,6 +542,7 @@ describe('photos visibility (e2e)', () => {
expect(events[1].payload).toEqual({
photoId: lifecycleId,
albumId,
categoryId: null, // 本 spec 种子未分类(P2 Task 6:categoryId 随载荷同步 ov)
objectKey: `${KEY_ROOT}/albums/${albumId}/originals/${lifecycleId}.jpg`,
thumbKey: variantKey(albumId, lifecycleId, 'thumb'),
browseKey: variantKey(albumId, lifecycleId, 'browse'),
+508
View File
@@ -0,0 +1,508 @@
// services/api/test/public-ov.e2e-spec.ts —— P2 Task 6 ov 公开读端点 e2e。
// ONE spec 串「cn 种 → 同步 → ov 读」全链路:进程内起两个真实入口(cn + ov,
// 同 sync.e2e-spec 模式),业务动作全走 cn API(建相册/分类/banner 资产/上传
// complete + 直驱 worker 发布事务),发送器为生产 OutboxSender(指向 ov 入口
// 真实 URL)——ov 读到的数据与生产链路逐字节同源。
//
// 覆盖(任务验收):
// ① 契约同形(本 spec 的核心证明):ov getPublicAlbum/listPublicPhotos/
// getPublicPhoto 与 cn 同端点响应 deep-equal(剥离现签 URL 后逐字段相等;
// album 另差 viewCount——cn 占位 null / ov 真实值);游标字符串相等
// (同一 shared/cursor 编码);分类过滤/单图 categoryId 同形;
// banner 签名 URL 可取回真实字节;locale 回退(en/zh)同形;
// ② viewCount 真实读:无 album_stats 行 → 0;有行 → 行值(计数端点 Task 8);
// ③ 参数校验同形:sort 非法 → 400(ov 新增参数);cursor 非法 → 400;
// category 幽灵 → 400(与 cn 同码同因);幽灵 token 三端点 → 404
// ALBUM_NOT_PUBLIC;
// ④ hot 排序快照:likeTotal 全 0 → photoId 倒序决胜;TTL 窗口内顺序冻结
// (DB 改 likeTotal 后响应顺序不变,计数现读);翻页对同一快照切片;
// TTL 过期后重算 → 顺序翻转;
// ⑤ 隐藏照片:cn 隐藏 → 高优先级同步 → ov 列表剔除 + 单图 404
// PHOTO_NOT_PUBLIC;
// ⑥ 相册下线:cn publicEnabled=false → ov 404(与 cn 同码);
// ⑦ 紧急停用(Task 5 通道 × 公开读):ov disable → ov 404 而 cn 仍 200
// (ov 本地独立位);enable → 恢复。
// 真实 MySQL×2 + MinIO(banner/变体真实 JPEG)+ HMAC 同步链路字节一致。
import { NestFactory } from '@nestjs/core';
import { type NestExpressApplication } from '@nestjs/platform-express';
import request from 'supertest';
import sharp from 'sharp';
import { PrismaClient } from '@photo/db-cn';
import { PrismaClient as OvPrismaClient } from '@photo/db-ov';
import { ErrorCodes, signSyncBody } from '@photo/contracts';
import {
createStorageFromEnv,
type MinioStorageAdapter,
} from '@photo/storage';
import { AppCnModule } from '../src/app-cn.module';
import { AppOvModule } from '../src/app-ov.module';
import { seedAdmin } from '../src/scripts/seed-admin';
import { configureApp } from '../src/shared/configure-app';
import { PublishService } from '../../worker/src/publish.service';
import { resetDb } from './reset';
import { resetOvDb } from './reset-ov';
import { OutboxSender } from '../../sync/src/sender';
jest.setTimeout(180_000);
const ADMIN_ACCOUNT = process.env.ADMIN_ACCOUNT ?? 'admin';
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD ?? 'admin-secret-change-me';
const SYNC_KEY = process.env.SYNC_INTERNAL_KEY ?? 'dev-sync-secret-change-me';
/** hot 快照 TTL(默认 30s 对 e2e 太长:缩短到 2s,「窗口内冻结」断言留足余量)。 */
const HOT_TTL_TEST_MS = 2000;
/** 测试内生成真实 JPEG(同 sync.e2e-spec;无二进制入库)。 */
async function makeJpeg(
width: number,
height: number,
rgb: { r: number; g: number; b: number },
): Promise<Buffer> {
return sharp({ create: { width, height, channels: 3, background: rgb } })
.jpeg({ quality: 85 })
.toBuffer();
}
/** 签名 POST(emergency 内部端点)。 */
async function signedPost(
base: string,
path: string,
body: unknown,
): Promise<Response> {
const raw = JSON.stringify(body);
return fetch(`${base}${path}`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-sync-timestamp': String(Math.floor(Date.now() / 1000)),
'x-sync-signature': signSyncBody(SYNC_KEY, raw),
},
body: raw,
});
}
/** SignedUrl 字段剥离(现签 URL 必然不同:两端各自签名;形状仍断言)。 */
interface ItemNoUrl {
photoId: string;
width: number;
height: number;
likeCount: number;
publishedAt: string;
}
function stripItem(item: {
photoId: string;
width: number;
height: number;
thumb: unknown;
browse: unknown;
likeCount: number;
publishedAt: string;
}): ItemNoUrl {
const { thumb: _thumb, browse: _browse, ...rest } = item;
void _thumb;
void _browse;
return rest;
}
describe('public-ov (e2e)', () => {
let cnApp: NestExpressApplication;
let ovApp: NestExpressApplication;
let cnBase: string;
let ovBase: string;
let prismaCn: PrismaClient;
let prismaOv: OvPrismaClient;
let storage: MinioStorageAdapter;
let sender: OutboxSender;
let adminToken: string;
let albumId: string;
let publicToken: string;
let categoryId: string;
/** 按上传顺序(publishedAt 升序)的三张照片。 */
let photoIds: string[];
/** 排空发送器:循环 runOnce 直至无未投递事件。 */
async function drainSender(): Promise<void> {
for (let round = 0; round < 20; round++) {
const stats = await sender.runOnce();
if (stats.picked === 0) {
return;
}
}
throw new Error('drainSender 超时:20 轮后 outbox 仍有未投递事件');
}
/** 上传全链路:init → presign PUT 实写 MinIO → complete → 直驱发布事务。 */
async function uploadAndPublish(
clientTaskId: string,
jpeg: Buffer,
withCategory: boolean,
): Promise<string> {
const init = await request(cnBase)
.post('/v1/uploads')
.set('Authorization', `Bearer ${adminToken}`)
.send({
albumId,
clientTaskId,
filename: 'pub-ov.jpg',
bytes: jpeg.length,
contentType: 'image/jpeg',
...(withCategory ? { categoryId } : {}),
});
expect(init.status).toBe(201);
const { uploadId, photoId, credential } = init.body as {
uploadId: string;
photoId: string;
credential: { url: string; method: string; headers: Record<string, string> };
};
const put = await fetch(credential.url, {
method: credential.method,
headers: credential.headers,
body: new Uint8Array(jpeg),
});
expect(put.ok).toBe(true);
const done = await request(cnBase)
.post(`/v1/uploads/${uploadId}/complete`)
.set('Authorization', `Bearer ${adminToken}`);
expect(done.status).toBe(200);
expect(await new PublishService(prismaCn, storage).processPhoto(photoId)).toBe(
'published',
);
return photoId;
}
/** GET(匿名公开端点;supertest Response.body 已是宽松 JSON 类型)。 */
async function getJson(base: string, path: string): Promise<request.Response> {
return request(base).get(path).set('accept', 'application/json');
}
beforeAll(async () => {
expect(SYNC_KEY).not.toBe('');
await resetDb();
await resetOvDb();
// hot 快照 TTL 缩短(服务端逐请求惰性读 env,见 public-ov.service)。
process.env.HOT_SORT_TTL_MS = String(HOT_TTL_TEST_MS);
cnApp = await NestFactory.create<NestExpressApplication>(AppCnModule, {
rawBody: true,
});
configureApp(cnApp);
await cnApp.listen(0);
cnBase = await cnApp.getUrl();
ovApp = await NestFactory.create<NestExpressApplication>(AppOvModule, {
rawBody: true,
});
configureApp(ovApp);
await ovApp.listen(0);
ovBase = await ovApp.getUrl();
prismaCn = new PrismaClient();
prismaOv = new OvPrismaClient();
storage = createStorageFromEnv();
sender = new OutboxSender({
prisma: prismaCn,
ovApiUrl: ovBase,
internalKey: SYNC_KEY,
});
await seedAdmin(prismaCn, ADMIN_ACCOUNT, ADMIN_PASSWORD);
const login = await request(cnBase).post('/v1/auth/password').send({
account: ADMIN_ACCOUNT,
password: ADMIN_PASSWORD,
});
expect(login.status).toBe(200);
adminToken = login.body.sessionToken as string;
});
afterAll(async () => {
delete process.env.HOT_SORT_TTL_MS;
await cnApp.close();
await ovApp.close();
await prismaCn.$disconnect();
await prismaOv.$disconnect();
});
it('① ov 三端点与 cn 契约同形(deep-equal 剥离现签 URL;游标逐字节相等)', async () => {
// —— cn 侧种全套:相册(zh+en)+ 分类 + banner(全局)+ 3 张发布照片 ——
const album = await request(cnBase)
.post('/v1/albums')
.set('Authorization', `Bearer ${adminToken}`)
.send({
translations: [
{ locale: 'zh-CN', title: '海外晚会', description: 'ov 公开读验收', venue: '主会场' },
{ locale: 'en', title: 'Overseas Gala' },
],
defaultLocale: 'zh-CN',
startAt: '2026-10-01T10:00:00.000Z',
});
expect(album.status).toBe(201);
albumId = album.body.id as string;
publicToken = album.body.publicToken as string;
const category = await request(cnBase)
.post(`/v1/albums/${albumId}/categories`)
.set('Authorization', `Bearer ${adminToken}`)
.send({
sortOrder: 0,
translations: [
{ locale: 'zh-CN', name: '红毯' },
{ locale: 'en', name: 'Red Carpet' },
],
});
expect(category.status).toBe(201);
categoryId = category.body.id as string;
// banner:资产 API 全链路(init → PUT → complete → asset.updated 事件)。
const bannerJpeg = await makeJpeg(1200, 300, { r: 150, g: 100, b: 60 });
const bannerInit = await request(cnBase)
.post(`/v1/albums/${albumId}/assets`)
.set('Authorization', `Bearer ${adminToken}`)
.send({
kind: 'banner',
filename: 'banner.jpg',
bytes: bannerJpeg.length,
contentType: 'image/jpeg',
});
expect(bannerInit.status).toBe(201);
const bannerCredential = bannerInit.body.credential as {
url: string;
method: string;
headers: Record<string, string>;
};
expect(
await fetch(bannerCredential.url, {
method: bannerCredential.method,
headers: bannerCredential.headers,
body: new Uint8Array(bannerJpeg),
}).then((r) => r.ok),
).toBe(true);
const bannerDone = await request(cnBase)
.post(`/v1/albums/${albumId}/assets/${bannerInit.body.assetId as string}/complete`)
.set('Authorization', `Bearer ${adminToken}`);
expect(bannerDone.status).toBe(200);
photoIds = [];
const shapes = [
{ w: 900, h: 600, rgb: { r: 180, g: 120, b: 60 }, withCategory: true },
{ w: 800, h: 500, rgb: { r: 60, g: 130, b: 180 }, withCategory: false },
{ w: 700, h: 450, rgb: { r: 120, g: 180, b: 90 }, withCategory: false },
] as const;
for (let i = 0; i < shapes.length; i++) {
const s = shapes[i]!;
photoIds.push(
await uploadAndPublish(
`pub-ov-${i}`,
await makeJpeg(s.w, s.h, s.rgb),
s.withCategory,
),
);
}
await drainSender();
// —— getPublicAlbum 同形(zh 缺省 + en 显式两个 locale)——
for (const localeQuery of ['', '?locale=en']) {
const cn = await getJson(cnBase, `/v1/public/albums/${publicToken}${localeQuery}`);
const ov = await getJson(ovBase, `/v1/public/albums/${publicToken}${localeQuery}`);
expect(ov.status).toBe(200);
// 剥离 banner(现签 URL 必不同)与 viewCount(cn 占位 null / ov 真实 0)
// 后逐字段相等——契约同形的直接证明。
const { banner: _cb, viewCount: _cv, ...cnRest } = cn.body;
const { banner: ovBanner, viewCount: ovViewCount, ...ovRest } = ov.body;
void _cb;
void _cv;
expect(ovRest).toEqual(cnRest);
expect(ovViewCount).toBe(0); // 无 album_stats 行 → 默认 0(真实值语义)
// banner:两端都有、形状合法、ov URL 取回真实字节(签名对副本键有效)。
expect(ovBanner).not.toBeNull();
expect(typeof ovBanner.url).toBe('string');
expect(Date.parse(ovBanner.expiresAt)).toBeGreaterThan(Date.now());
const fetched = await fetch(ovBanner.url as string);
expect(fetched.ok).toBe(true);
expect((await fetched.arrayBuffer()).byteLength).toBe(bannerJpeg.length);
}
// —— listPublicPhotos 同形:默认页 / limit=2(hasMore+游标值)/ 分类过滤 ——
const listCases = [
'',
'?limit=2',
`?limit=2&category=${categoryId}`,
'?sort=latest',
];
for (const query of listCases) {
const cn = await getJson(cnBase, `/v1/public/albums/${publicToken}/photos${query}`);
const ov = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos${query}`);
expect(ov.status).toBe(200);
expect(ov.body.items.map(stripItem)).toEqual(cn.body.items.map(stripItem));
expect(ov.body.nextCursor).toBe(cn.body.nextCursor); // 同一 shared/cursor 编码 → 逐字节相等
expect(ov.body.hasMore).toBe(cn.body.hasMore);
// 现签 URL 形状仍校验(每条可取回真实字节)。
for (const item of ov.body.items) {
expect(Date.parse(item.thumb.expiresAt)).toBeGreaterThan(Date.now());
expect(await fetch(item.thumb.url).then((r) => r.ok)).toBe(true);
}
}
// limit=2 分页确实产生了 hasMore(上面游标相等性才有意义)。
const firstPage = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos?limit=2`);
expect(firstPage.body.hasMore).toBe(true);
expect(firstPage.body.items).toHaveLength(2);
// —— getPublicPhoto 同形(含 categoryId;刷新入口语义=每次现签)——
for (const photoId of photoIds) {
const cn = await getJson(cnBase, `/v1/public/albums/${publicToken}/photos/${photoId}`);
const ov = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos/${photoId}`);
expect(ov.status).toBe(200);
expect(stripItem(ov.body)).toEqual(stripItem(cn.body));
expect(ov.body.categoryId).toBe(cn.body.categoryId);
}
});
it('② viewCount 真实读:album_stats 行值(计数端点 Task 8 接线)', async () => {
const before = await getJson(ovBase, `/v1/public/albums/${publicToken}`);
expect(before.body.viewCount).toBe(0);
await prismaOv.album_stats.create({
data: { albumId, viewCount: 5, statVersion: 3 },
});
const after = await getJson(ovBase, `/v1/public/albums/${publicToken}`);
expect(after.body.viewCount).toBe(5);
});
it('③ 参数校验同形:sort/cursor/category 400;幽灵 token 三端点 404', async () => {
const badSort = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos?sort=bogus`);
expect(badSort.status).toBe(400);
expect(badSort.body.code).toBe(ErrorCodes.VALIDATION_FAILED);
const badCursor = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos?cursor=zzz`);
expect(badCursor.status).toBe(400);
expect(badCursor.body.code).toBe(ErrorCodes.VALIDATION_FAILED);
// 幽灵分类:与 cn 同码同因(防探测,不区分不存在/跨册)。
for (const base of [cnBase, ovBase]) {
const ghostCategory = await getJson(base, `/v1/public/albums/${publicToken}/photos?category=cat-ghost`);
expect(ghostCategory.status).toBe(400);
expect(ghostCategory.body.code).toBe(ErrorCodes.VALIDATION_FAILED);
}
const ghostToken = 'g' + '0'.repeat(23);
for (const path of [
`/v1/public/albums/${ghostToken}`,
`/v1/public/albums/${ghostToken}/photos`,
`/v1/public/albums/${ghostToken}/photos/p-x`,
]) {
const res = await getJson(ovBase, path);
expect(res.status).toBe(404);
expect(res.body.code).toBe(ErrorCodes.ALBUM_NOT_PUBLIC);
}
});
it('④ hot 排序:photoId 决胜 → TTL 窗口冻结(计数现读)→ 过期翻转', async () => {
// likeTotal 全 0:hot = likeTotal DESC, photoId DESC(id 决胜)。
const idDesc = [...photoIds].sort((a, b) => (a < b ? 1 : -1));
const first = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos?sort=hot&limit=2`);
expect(first.status).toBe(200);
expect(first.body.items.map((i: ItemNoUrl) => i.photoId)).toEqual(idDesc.slice(0, 2));
expect(first.body.hasMore).toBe(true);
// 快照语义:DB 改 likeTotal 后,TTL 窗口内顺序冻结(仍 id 序)——但条目
// 计数现读(尾张已带新值)。
const tail = idDesc[2]!;
await prismaOv.photos_ov.update({
where: { photoId: tail },
data: { likeTotal: 10 },
});
const stale = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos?sort=hot`);
expect(stale.body.items.map((i: ItemNoUrl) => i.photoId)).toEqual(idDesc);
expect(stale.body.items.find((i: ItemNoUrl) => i.photoId === tail).likeCount).toBe(10);
// 翻页对同一快照切片:第 2 页从冻结清单 offset 2 取——尾张仍在末位。
const page2 = await getJson(
ovBase,
`/v1/public/albums/${publicToken}/photos?sort=hot&limit=2&cursor=${first.body.nextCursor as string}`,
);
expect(page2.status).toBe(200);
expect(page2.body.items.map((i: ItemNoUrl) => i.photoId)).toEqual([tail]);
expect(page2.body.hasMore).toBe(false);
// TTL 过期 → 快照重算 → 顺序翻转(尾张 +10 居首)。
await new Promise((resolve) => setTimeout(resolve, HOT_TTL_TEST_MS + 200));
const flipped = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos?sort=hot`);
expect(flipped.body.items.map((i: ItemNoUrl) => i.photoId)).toEqual([
tail,
...idDesc.slice(0, 2),
]);
});
it('⑤ 隐藏照片:cn 隐藏 → 同步 → ov 列表剔除 + 单图 404 PHOTO_NOT_PUBLIC', async () => {
const hidden = photoIds[1]!;
const hide = await request(cnBase)
.patch(`/v1/photos/${hidden}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ visibility: 'hidden' });
expect(hide.status).toBe(200);
await drainSender();
const cnList = await getJson(cnBase, `/v1/public/albums/${publicToken}/photos`);
const ovList = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos`);
expect(ovList.body.items.map((i: ItemNoUrl) => i.photoId)).toEqual(
cnList.body.items.map((i: ItemNoUrl) => i.photoId),
);
expect(ovList.body.items.map((i: ItemNoUrl) => i.photoId)).not.toContain(hidden);
const single = await getJson(ovBase, `/v1/public/albums/${publicToken}/photos/${hidden}`);
expect(single.status).toBe(404);
expect(single.body.code).toBe(ErrorCodes.PHOTO_NOT_PUBLIC);
});
it('⑥ 相册下线:cn publicEnabled=false → ov 与 cn 同码 404', async () => {
const offline = await request(cnBase)
.patch(`/v1/albums/${albumId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ publicEnabled: false });
expect(offline.status).toBe(200);
await drainSender();
for (const base of [cnBase, ovBase]) {
const album = await getJson(base, `/v1/public/albums/${publicToken}`);
expect(album.status).toBe(404);
expect(album.body.code).toBe(ErrorCodes.ALBUM_NOT_PUBLIC);
const list = await getJson(base, `/v1/public/albums/${publicToken}/photos`);
expect(list.status).toBe(404);
}
});
it('⑦ 紧急停用:ov disable → ov 404 而 cn 无感;enable 恢复', async () => {
// 独立相册(不影响前序场景):cn 建 + 同步 → ov 可读。
const album = await request(cnBase)
.post('/v1/albums')
.set('Authorization', `Bearer ${adminToken}`)
.send({
translations: [{ locale: 'zh-CN', title: '紧急停用验证' }],
defaultLocale: 'zh-CN',
startAt: '2026-10-01T10:00:00.000Z',
});
expect(album.status).toBe(201);
const token = album.body.publicToken as string;
await drainSender();
expect((await getJson(ovBase, `/v1/public/albums/${token}`)).status).toBe(200);
// ov 本地停用(独立于同步版本链)。
const disable = await signedPost(ovBase, '/v1/internal/emergency/disable', {
albumToken: token,
reason: 'e2e: public-ov visibility',
});
expect(disable.status).toBe(200);
const ovRes = await getJson(ovBase, `/v1/public/albums/${token}`);
expect(ovRes.status).toBe(404);
expect(ovRes.body.code).toBe(ErrorCodes.ALBUM_NOT_PUBLIC);
// cn 无感:仍 200(紧急停用是 ov 观众域动作,cn 权威数据不变)。
expect((await getJson(cnBase, `/v1/public/albums/${token}`)).status).toBe(200);
// 显式 enable → 恢复。
const enable = await signedPost(ovBase, '/v1/internal/emergency/enable', {
albumToken: token,
});
expect(enable.status).toBe(200);
expect((await getJson(ovBase, `/v1/public/albums/${token}`)).status).toBe(200);
});
});
+24
View File
@@ -74,6 +74,30 @@ const DEFAULT_TIMEOUT_MS = 30_000;
/** ov 侧 content-batches 端点路径(全局前缀 v1 + InternalSyncGuard 域)。 */
const CONTENT_BATCHES_PATH = '/v1/internal/sync/content-batches';
/** deliverPendingOnce 的排空轮数上限(每轮一批 ≤ batchSize;防御性熔断)。 */
const DELIVER_MAX_ROUNDS = 100;
/**
* 一次性排空 outbox(P2 Task 6):循环 runOnce 直至无未投递事件。
* 消费方:viewer e2e 夹具(flushSync,种子后经真实管线同步到 ov)与运维手工
* 触发——与常驻 main 循环同一 OutboxSender,无旁路语义;与常驻发送器并发
* 亦安全(eventId 幂等 + deliveredAt 条件回写,两侧竞争不双发不丢发)。
*/
export async function deliverPendingOnce(
options: OutboxSenderOptions,
): Promise<void> {
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;
+7 -1
View File
@@ -55,7 +55,12 @@ export class PublishService {
async processPhoto(photoId: string): Promise<ProcessOutcome> {
const photo = await this.prisma.photos.findUnique({
where: { id: photoId },
select: { albumId: true, objectKey: true, processingState: true },
select: {
albumId: true,
categoryId: true,
objectKey: true,
processingState: true,
},
});
if (photo === null) {
this.logger?.warn({ photoId }, '照片不存在,跳过处理');
@@ -144,6 +149,7 @@ export class PublishService {
const payload: PhotoPublishedPayload = {
photoId,
albumId: photo.albumId,
categoryId: photo.categoryId,
objectKey: photo.objectKey,
thumbKey,
browseKey,
+1
View File
@@ -222,6 +222,7 @@ describe('publish (e2e)', () => {
const expectedPayload: PhotoPublishedPayload = {
photoId,
albumId,
categoryId: null, // 本 spec 种子未分类(categoryId 随载荷同步到 ov 副本)
objectKey,
thumbKey: variantKey(albumId, photoId, 'thumb'),
browseKey: variantKey(albumId, photoId, 'browse'),