fix(cms): 后台发布/更新/删除真正让前台 ISR 失效(DEC-N5)

失效映射原先长在 /api/cms/revalidate 的路由体里,所以它只能被外部 HTTP 调用触发。
实测后果:后台四条变更链一个都不刷缓存,8 个页面注释里那句
「CMS 发布/更新时通过 /api/cms/revalidate 主动刷新」是假的 —— s-maxage=3600 下
最长 1 小时前台仍端出已删或过期内容,且没有任何门禁会红。

- 新增 src/lib/cms/revalidation.ts:modelCode→paths 推导做成纯函数
  (pathsForModel / tagsForModel / planRevalidation),副作用收在
  revalidateContent;同 §5.30「安全抽象必须可导入」。
- 路由改为消费同一份推导(响应契约与去重语义逐字保持,16 套件既有断言未动)。
- items 的 POST/PUT/DELETE、workflow 四个动作、zones 的写与删都接上失效;
  判据按 status(草稿不进前台读取路径),slug 变更时旧地址一并刷。
- revalidateContent 是尽力而为:逐条 try + [revalidation-failed] 日志 + failed 回报,
  因为数据已落库,刷缓存失败不该把成功的写入连带变成 500;
  applyRevalidation 仍严格冒泡,保持 /api/cms/revalidate 的 500 语义。

证据:新增 10 例(纯映射 12 例 + 调用点 6 例)。定向 16 套件 193 例 EXIT=0;
负对照把 workflow 的调用点改成注释 ⇒ MUTANT_EXIT=1(4 例转红),还原后 EXIT=0。
lint 定向 0 error。
This commit is contained in:
zhangxiang committed 2026-10-17 07:43:42 +08:00
1 parent 0ae765afcd
commit f3e66f7d36
9 files changed
+660 -134

No files matched your search

@@ -5,6 +5,13 @@ import { NextRequest } from 'next/server';
const mockContentItemFindUnique = jest.fn<(args: unknown) => Promise<unknown | null>>();
const mockContentItemFindUniqueOrThrow = jest.fn<(args: unknown) => Promise<unknown>>();
// 同 api/cms/revalidate/route.test.ts:next/cache 由运行时提供,jest 里真调会抛
// `Invariant: static generation store missing`。DEC-N5 后发布链会触发失效,故桩掉。
jest.mock('next/cache', () => ({
revalidatePath: jest.fn(),
revalidateTag: jest.fn(),
}));
jest.mock('@/lib/db', () => ({
prisma: {
contentItem: {
@@ -19,6 +19,7 @@ import {
} from '@/lib/api-response';
import { withCrypto } from '@/lib/api-crypto';
import { parseCmsData } from '@/lib/cms/validate-content-data';
import { revalidateContent } from '@/lib/cms/revalidation';
// 与 items/route.ts 同源:脏 data 列不得让这个已成功的审批动作在返回阶段变成 500(B-4)。
function parseItem(item: { data: string; [key: string]: unknown }) {
@@ -82,7 +83,13 @@ export const POST = withCrypto(async (
break;
}
return success(parseItem(await prisma.contentItem.findUniqueOrThrow({ where: { id } })));
// DEC-N5:发布链以前什么都不刷 ——「后台发布后前台最长 1 小时不可见」就是这条缺口。
// approve 让内容首次出现,reject/archive 让它消失,submit 不改可见性但也一并失效:
// 多余的一次 revalidatePath 是幂等的,漏一次则是用户可见的旧内容,代价不对称。
const updated = await prisma.contentItem.findUniqueOrThrow({ where: { id } });
revalidateContent(existing.modelCode, updated.slug);
return success(parseItem(updated));
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('内容不存在')) {
@@ -0,0 +1,202 @@
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
import { NextRequest } from 'next/server';
/**
* DEC-N5 的回归守卫:后台四条变更链必须让前台 ISR 快照失效。
*
* 为什么单独成文件、且断言的是「调用了吗」而不是「返回值对不对」:
* 本仓原先的缺口不在映射算错,而在**没有任何生产调用方** ——
* 映射长在 /api/cms/revalidate 的路由体里,只有外部 HTTP 调用才触发它,
* 于是后台发布/更新/删除全都静默不刷缓存,最长 1 小时前台仍是旧内容,
* 而没有任何门禁会红。所以这道守卫的对象就是「调用点存在」本身。
*
* 敏感性自证(负对照):把 route.ts 里任一 `revalidateContent(...)` 调用删掉,
* 本文件对应用例必须转红(`Expected "revalidateContent" to have been called ... Received number of calls: 0`)。
*/
const mockRevalidateContent = jest.fn<(modelCode: string, slug?: string | null) => unknown>();
jest.mock('@/lib/cms/revalidation', () => ({
revalidateContent: mockRevalidateContent,
}));
// next/cache 在测试运行时不可用;本文件不触达真实实现(已被上面的 mock 挡住),
// 但仍显式桩掉,避免任何间接 import 把真实模块拉进来。
jest.mock('next/cache', () => ({
revalidatePath: jest.fn(),
revalidateTag: jest.fn(),
}));
const mockContentItemFindUnique = jest.fn<(args: unknown) => Promise<unknown>>();
const mockContentItemFindUniqueOrThrow = jest.fn<(args: unknown) => Promise<unknown>>();
const mockContentItemFindFirst = jest.fn<(args: unknown) => Promise<unknown>>();
const mockContentItemUpdate = jest.fn<(args: unknown) => Promise<unknown>>();
const mockContentItemDelete = jest.fn<(args: unknown) => Promise<unknown>>();
const mockContentItemCreate = jest.fn<(args: unknown) => Promise<unknown>>();
const mockContentModelFindUnique = jest.fn<(args: unknown) => Promise<unknown>>();
const mockAuditLogCreate = jest.fn<(args: unknown) => Promise<unknown>>();
jest.mock('@/lib/db', () => ({
prisma: {
contentItem: {
findUnique: mockContentItemFindUnique,
findUniqueOrThrow: mockContentItemFindUniqueOrThrow,
findFirst: mockContentItemFindFirst,
update: mockContentItemUpdate,
delete: mockContentItemDelete,
create: mockContentItemCreate,
},
contentModel: { findUnique: mockContentModelFindUnique },
auditLog: { create: mockAuditLogCreate },
},
}));
const mockRequirePermission = jest.fn<(r: NextRequest, m: string, a: string) => Promise<unknown>>();
jest.mock('@/lib/permissions', () => ({ requirePermission: mockRequirePermission }));
const mockAuthenticateRequest = jest.fn<(r: NextRequest) => unknown>();
jest.mock('@/lib/auth', () => ({ authenticateRequest: mockAuthenticateRequest }));
const mockSubmitForReview = jest.fn<(id: string, u: unknown) => Promise<unknown>>();
const mockApprove = jest.fn<(id: string, u: unknown) => Promise<unknown>>();
const mockReject = jest.fn<(id: string, u: unknown, reason?: string) => Promise<unknown>>();
const mockArchive = jest.fn<(id: string, u: unknown) => Promise<unknown>>();
jest.mock('@/lib/cms/workflow', () => ({
submitForReview: mockSubmitForReview,
approve: mockApprove,
reject: mockReject,
archive: mockArchive,
}));
jest.unmock('@/app/api/admin/items/route');
import { POST as PUT_ITEMS_POST, PUT, DELETE } from '@/app/api/admin/items/route';
import { POST as WORKFLOW_POST } from '@/app/api/admin/items/[id]/workflow/route';
function req(url: string, body: Record<string, unknown>): NextRequest {
return {
url,
nextUrl: new URL(url),
headers: new Headers(),
json: async () => body,
} as unknown as NextRequest;
}
const NEWS_MODEL_FIELDS = JSON.stringify([]);
beforeEach(() => {
jest.clearAllMocks();
mockRequirePermission.mockResolvedValue({ user: { userId: 'u1', username: 'admin' } });
mockAuthenticateRequest.mockReturnValue({ userId: 'u1', username: 'admin' });
mockContentModelFindUnique.mockResolvedValue({ id: 'm1', code: 'news', fields: NEWS_MODEL_FIELDS });
mockContentItemFindFirst.mockResolvedValue(null);
mockAuditLogCreate.mockResolvedValue({});
mockSubmitForReview.mockResolvedValue(undefined);
mockApprove.mockResolvedValue(undefined);
mockReject.mockResolvedValue(undefined);
mockArchive.mockResolvedValue(undefined);
});
function newsRow(status: string, slug = 'hello-world') {
return {
id: 'item-1',
modelCode: 'news',
slug,
status,
title: 'T',
data: JSON.stringify({}),
};
}
describe('PUT /api/admin/items —— 更新已发布内容必须失效前台快照', () => {
it('已发布行被编辑 ⇒ 按 modelCode + 新 slug 失效', async () => {
mockContentItemFindUnique.mockResolvedValue(newsRow('published'));
mockContentItemUpdate.mockResolvedValue(newsRow('published', 'hello-world'));
const res = await PUT(req('http://x/api/admin/items?id=item-1', { title: '改名' }));
expect(res.status).toBe(200);
expect(mockRevalidateContent).toHaveBeenCalledTimes(1);
expect(mockRevalidateContent).toHaveBeenCalledWith('news', 'hello-world');
});
it('草稿不进前台 ⇒ 不该失效(判据按状态、不是无条件刷)', async () => {
mockContentItemFindUnique.mockResolvedValue(newsRow('draft'));
mockContentItemUpdate.mockResolvedValue(newsRow('draft'));
const res = await PUT(req('http://x/api/admin/items?id=item-1', { title: '改名' }));
expect(res.status).toBe(200);
expect(mockRevalidateContent).not.toHaveBeenCalled();
});
it('slug 变更 ⇒ 新地址与**旧地址**都要失效,否则旧 URL 继续端出旧内容', async () => {
mockContentItemFindUnique.mockResolvedValue(newsRow('published', 'old-slug'));
mockContentItemUpdate.mockResolvedValue(newsRow('published', 'new-slug'));
const res = await PUT(req('http://x/api/admin/items?id=item-1', { slug: 'new-slug' }));
expect(res.status).toBe(200);
expect(mockRevalidateContent).toHaveBeenCalledTimes(2);
const slugs = mockRevalidateContent.mock.calls.map((c) => c[1]);
expect(slugs).toEqual(expect.arrayContaining(['new-slug', 'old-slug']));
});
});
describe('DELETE /api/admin/items —— 删除已发布内容必须失效前台快照', () => {
it('删除已发布行 ⇒ 失效(§11.5 那 8 条 /news 计数红的产品层根因)', async () => {
mockContentItemFindUnique.mockResolvedValue(newsRow('published'));
mockContentItemDelete.mockResolvedValue(newsRow('published'));
const res = await DELETE(req('http://x/api/admin/items?id=item-1'));
expect(res.status).toBe(200);
expect(mockRevalidateContent).toHaveBeenCalledWith('news', 'hello-world');
});
it('删除草稿 ⇒ 不失效', async () => {
mockContentItemFindUnique.mockResolvedValue(newsRow('draft'));
mockContentItemDelete.mockResolvedValue(newsRow('draft'));
const res = await DELETE(req('http://x/api/admin/items?id=item-1'));
expect(res.status).toBe(200);
expect(mockRevalidateContent).not.toHaveBeenCalled();
});
});
describe('POST /api/admin/items —— 创建', () => {
it('强制草稿(B-1)⇒ 不失效;但判据跟着 status 走,放开直接发布时会自动跟上', async () => {
mockContentItemCreate.mockResolvedValue({ ...newsRow('draft'), id: 'new-1' });
const res = await PUT_ITEMS_POST(
req('http://x/api/admin/items', { modelId: 'm1', modelCode: 'news', title: '新稿' })
);
expect(res.status).toBe(201);
expect(mockRevalidateContent).not.toHaveBeenCalled();
});
});
describe('POST /api/admin/items/[id]/workflow —— 发布链', () => {
it('approve ⇒ 发布后立刻失效(这条以前完全不刷,是 DEC-N5 的主体)', async () => {
mockContentItemFindUnique.mockResolvedValue(newsRow('pending_review'));
mockContentItemFindUniqueOrThrow.mockResolvedValue({ ...newsRow('published'), id: 'item-1' });
const res = await WORKFLOW_POST(
req('http://x/api/admin/items/workflow?id=item-1', { action: 'approve' }),
{ params: Promise.resolve({ id: 'item-1' }) } as never
);
expect(res.status).toBe(200);
expect(mockApprove).toHaveBeenCalledWith('item-1', { userId: 'u1', username: 'admin' });
expect(mockRevalidateContent).toHaveBeenCalledTimes(1);
expect(mockRevalidateContent).toHaveBeenCalledWith('news', 'hello-world');
});
it.each(['submit', 'reject', 'archive'] as const)(
'%s 也失效:多余一次是幂等,漏一次是用户可见的旧内容',
async (action) => {
mockContentItemFindUnique.mockResolvedValue(newsRow('published'));
mockContentItemFindUniqueOrThrow.mockResolvedValue(newsRow('published'));
const res = await WORKFLOW_POST(req('http://x/api/admin/items/workflow?id=item-1', { action } as never), {
params: Promise.resolve({ id: 'item-1' }),
} as never);
expect(res.status).toBe(200);
expect(mockRevalidateContent).toHaveBeenCalledTimes(1);
}
);
});
+21
View File
@@ -17,6 +17,7 @@ import {
type ContentFieldError,
} from '@/lib/cms/validate-content-data';
import type { FieldDefinition } from '@/lib/cms/types';
import { revalidateContent } from '@/lib/cms/revalidation';
function parseItem(item: { data: string; [key: string]: unknown }) {
return { ...item, data: parseCmsData(item.data) };
@@ -191,6 +192,11 @@ export const POST = withCrypto(async (request: NextRequest) => {
},
});
// DEC-N5:只有已发布的行会出现在前台读取路径上,草稿不需要刷 ISR。
// 判据写成「item.status === 'published'」而不是「不刷」:本接口现在强制 draft
// (B-1),一旦将来放开直接发布,失效会跟着状态自动发生,而不是留一处静默漏刷。
if (item.status === 'published') revalidateContent(item.modelCode, item.slug);
return success(parseItem(item), 201);
} catch (error) {
console.error('Create item error:', error);
@@ -271,6 +277,16 @@ export const PUT = withCrypto(async (request: NextRequest) => {
},
});
// DEC-N5:内容一旦落库,前台那份 ISR 快照就过期了。原先这里什么都不做,
// 于是「已发布的行被改成新文案」最长 1 小时(s-maxage=3600)仍按旧快照对外。
// 失效面由 revalidation 从 modelCode(含 slug)推导,与 /api/cms/revalidate 同源。
// 放在审计之后:刷缓存是**尽力而为**的下游动作,不该把已成功的写入连带回滚成 500。
if (existing.status === 'published') {
revalidateContent(existing.modelCode, item.slug);
// slug 变更时**旧**详情页的快照也得刷,否则旧地址继续端出旧内容 1 小时。
if (item.slug !== existing.slug) revalidateContent(existing.modelCode, existing.slug);
}
return success(parseItem(item));
} catch (error) {
console.error('Update item error:', error);
@@ -306,6 +322,11 @@ export const DELETE = withCrypto(async (request: NextRequest) => {
},
});
// DEC-N5:删除已发布的行同样要让前台立刻知道(本条就是 qa-tracker §11.5
// 里那 8 条「/news 筛选计数 2≠1」红因的产品层根因:uj03 删了行但没人刷缓存,
// 于是删除被冻进 ISR 产物)。
if (existing.status === 'published') revalidateContent(existing.modelCode, existing.slug);
return success({ message: '删除成功' });
} catch (error) {
console.error('Delete item error:', error);
+7
View File
@@ -9,6 +9,13 @@ const mockContentZoneUpdate = jest.fn<(args: unknown) => Promise<unknown>>();
const mockContentZoneDelete = jest.fn<(args: unknown) => Promise<unknown>>();
const mockAuditLogCreate = jest.fn<(args: unknown) => Promise<unknown>>();
// next/cache 是运行时提供的模块,jest 里真跑会抛 `Invariant: static generation store missing`。
// DEC-N5 之后 zones 路由会触发失效,所以按本仓既有做法(见 api/cms/revalidate/route.test.ts)桩掉。
jest.mock('next/cache', () => ({
revalidatePath: jest.fn(),
revalidateTag: jest.fn(),
}));
jest.mock('@/lib/db', () => ({
prisma: {
contentZone: {
+6
View File
@@ -8,6 +8,7 @@ import {
internalError,
} from '@/lib/api-response';
import { withCrypto } from '@/lib/api-crypto';
import { revalidateContent } from '@/lib/cms/revalidation';
// GET /api/admin/zones - 获取所有内容区域
export const GET = withCrypto(async (request: NextRequest) => {
@@ -86,6 +87,10 @@ export const POST = withCrypto(async (request: NextRequest) => {
});
}
// DEC-N5:ContentZone 是首页各段的数据源,改完必须让 / 的快照失效。
// 口径与 /api/cms/revalidate 里 'content-zone' → '/' 那条同源(见 lib/cms/revalidation)。
revalidateContent('content-zone');
return success({
...zone,
allowedModels: JSON.parse(zone.allowedModels),
@@ -117,6 +122,7 @@ export const DELETE = withCrypto(async (request: NextRequest) => {
if (!existing) return notFound('区域不存在');
await prisma.contentZone.delete({ where: { id } });
revalidateContent('content-zone');
await prisma.auditLog.create({
data: {
+11 -133
View File
@@ -1,30 +1,10 @@
import { NextRequest, NextResponse } from 'next/server';
import { revalidatePath, revalidateTag } from 'next/cache';
import { CONTENT_TYPE_CONFIGS } from '@/lib/cms/content-types';
import { planRevalidation, applyRevalidation } from '@/lib/cms/revalidation';
function getContentTypeConfig(code: string) {
return CONTENT_TYPE_CONFIGS[code as keyof typeof CONTENT_TYPE_CONFIGS] ?? null;
}
function getAllContentTypeConfigs() {
return Object.values(CONTENT_TYPE_CONFIGS);
}
// 首页受影响的模型:更新后需要同时刷新 /
const HOME_AFFECTED_MODELS = new Set([
'hero-banner',
'stat-item',
'service',
'case-study',
'solution',
'news',
]);
// 洞察枢纽 /insights 的数据来自三路真源:news(技术与观点)、case-study(客户成果,当前 0 行)、
// methodology(方法论)。它**不在** CONTENT_TYPE_CONFIGS 的任何 listPage 里 ——
// 通用推导只会刷 /news、/methodology,于是后台发了新内容而 /insights 仍端出旧 ISR 快照,
// 最长 1 小时不可见,且没有任何门禁会红。新路由必须显式登记失效映射。
const INSIGHTS_AFFECTED_MODELS = new Set(['news', 'case-study', 'methodology']);
// 失效映射与执行都来自 @/lib/cms/revalidation(DEC-N5):后台的创建/更新/删除/发布
// 四条变更链现在与这个 HTTP 入口共用**同一份** modelCode → paths 推导。
// 原先映射长在下面的路由体里,所以它只能被外部调用触发,
// 「CMS 发布/更新时主动刷新」那句话在没有任何生产调用方的日子里是假的。
interface RevalidateRequestBody {
event?: string;
@@ -57,119 +37,17 @@ export async function POST(request: NextRequest) {
);
}
const revalidatedPaths: string[] = [];
const revalidatedTags: string[] = [];
if (body.paths && body.paths.length > 0) {
for (const path of body.paths) {
revalidatePath(path);
revalidatedPaths.push(path);
}
}
if (body.tags && body.tags.length > 0) {
for (const tag of body.tags) {
revalidateTag(tag, {});
revalidatedTags.push(tag);
}
}
if (body.modelCode) {
const config = getContentTypeConfig(body.modelCode);
if (config) {
if (config.listPage?.route) {
revalidatePath(config.listPage.route);
revalidatedPaths.push(config.listPage.route);
}
if (config.detailPage?.routePattern && body.slug) {
const detailPath = config.detailPage.routePattern.replace('{slug}', body.slug);
revalidatePath(detailPath);
revalidatedPaths.push(detailPath);
}
const tag = `cms:${body.modelCode}`;
revalidateTag(tag, {});
revalidatedTags.push(tag);
}
// legal-page 为特殊页面类型,固定映射到 /privacy 和 /terms
if (body.modelCode === 'legal-page') {
const legalPaths = body.slug
? [body.slug === 'terms' ? '/terms' : '/privacy']
: ['/privacy', '/terms'];
for (const path of legalPaths) {
if (!revalidatedPaths.includes(path)) {
revalidatePath(path);
revalidatedPaths.push(path);
}
}
}
// team-page 为单页模型,固定映射到 /team
if (body.modelCode === 'team-page' && !revalidatedPaths.includes('/team')) {
revalidatePath('/team');
revalidatedPaths.push('/team');
}
// about-page / contact-page 为无 listPage 配置的单页模型,固定映射(S-3)
if (body.modelCode === 'about-page' && !revalidatedPaths.includes('/about')) {
revalidatePath('/about');
revalidatedPaths.push('/about');
}
if (body.modelCode === 'contact-page' && !revalidatedPaths.includes('/contact')) {
revalidatePath('/contact');
revalidatedPaths.push('/contact');
}
// /products/erp-upgrade 是硬编码页面,但数据来自 product 模型(slug=erp)(S-3)
if (body.modelCode === 'product' && !revalidatedPaths.includes('/products/erp-upgrade')) {
revalidatePath('/products/erp-upgrade');
revalidatedPaths.push('/products/erp-upgrade');
}
// 洞察枢纽:三个上游模型任一变更都要刷 /insights
if (
INSIGHTS_AFFECTED_MODELS.has(body.modelCode) &&
!revalidatedPaths.includes('/insights')
) {
revalidatePath('/insights');
revalidatedPaths.push('/insights');
}
// 首页相关模型变更时同步刷新 /
if (HOME_AFFECTED_MODELS.has(body.modelCode) && !revalidatedPaths.includes('/')) {
revalidatePath('/');
revalidatedPaths.push('/');
}
// ContentZone 变更时刷新关联页面
if (body.modelCode === 'content-zone' && !revalidatedPaths.includes('/')) {
revalidatePath('/');
revalidatedPaths.push('/');
}
}
if (body.event === 'content.published' || body.event === 'content.updated') {
const allConfigs = getAllContentTypeConfigs();
for (const config of allConfigs) {
if (config.listPage?.route) {
revalidatePath(config.listPage.route);
if (!revalidatedPaths.includes(config.listPage.route)) {
revalidatedPaths.push(config.listPage.route);
}
}
}
revalidateTag('cms:all', {});
revalidatedTags.push('cms:all');
}
// modelCode 无对应 content-type 配置时,paths/tags 都会是空数组 ——
// 这与重构前一致(不静默刷全站),并交由调用方看到空回执。
const plan = planRevalidation(body);
const applied = applyRevalidation(plan);
return NextResponse.json({
code: 0,
message: 'success',
data: {
revalidatedPaths,
revalidatedTags,
revalidatedPaths: applied.paths,
revalidatedTags: applied.tags,
timestamp: new Date().toISOString(),
},
});
+167
View File
@@ -0,0 +1,167 @@
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
/**
* DEC-N5 的纯推导层守卫。
*
* 这里刻意不 mock `@/lib/cms/content-types` —— 映射的正确性必须相对**真实配置**断言,
* 否则它只是在给自己打气(把期望写死成实现的样子)。
* 但也不许把 listPage 的字面路径抄进测试当唯一真源:抄本会随配置漂移而静默过期,
* 所以每条列表页断言都同时用「配置里的 route」与「推导结果」对账。
*/
const mockRevalidatePath = jest.fn<(p: string) => void>();
const mockRevalidateTag = jest.fn<(t: string, opts?: unknown) => void>();
jest.mock('next/cache', () => ({
revalidatePath: mockRevalidatePath,
revalidateTag: mockRevalidateTag,
}));
import {
pathsForModel,
tagsForModel,
planRevalidation,
applyRevalidation,
revalidateContent,
allListPagePaths,
HOME_AFFECTED_MODELS,
INSIGHTS_AFFECTED_MODELS,
} from '@/lib/cms/revalidation';
import { CONTENT_TYPE_CONFIGS } from '@/lib/cms/content-types';
beforeEach(() => {
jest.clearAllMocks();
});
describe('pathsForModel —— 通用推导', () => {
it('news 带 slug ⇒ 列表页 + 详情页 + /insights + /(首页受影响的模型)', () => {
const listRoute = CONTENT_TYPE_CONFIGS['news'].listPage?.route as string;
expect(listRoute).toBeTruthy();
const paths = pathsForModel('news', 'hello-world');
expect(paths).toEqual(expect.arrayContaining([listRoute, '/news/hello-world', '/insights', '/']));
expect(HOME_AFFECTED_MODELS.has('news')).toBe(true);
expect(INSIGHTS_AFFECTED_MODELS.has('news')).toBe(true);
});
it('不带 slug ⇒ 不该凭空造出详情页路径', () => {
const paths = pathsForModel('news');
expect(paths.some((p) => p.includes('{slug}'))).toBe(false);
});
it('结果不得有重复(同一 modelCode 的多条规则可命中同一路径)', () => {
for (const code of Object.keys(CONTENT_TYPE_CONFIGS)) {
const paths = pathsForModel(code, 'demo-slug');
expect(new Set(paths).size).toBe(paths.length);
}
});
it('未知模型 ⇒ 空数组(不静默刷全站)', () => {
expect(pathsForModel('不存在的模型')).toEqual([]);
expect(tagsForModel('不存在的模型')).toEqual([]);
});
});
describe('固定映射(单页 / 硬编码例外 / legal-page)', () => {
it('单页模型各有固定路径', () => {
expect(pathsForModel('team-page')).toEqual(expect.arrayContaining(['/team']));
expect(pathsForModel('about-page')).toEqual(expect.arrayContaining(['/about']));
expect(pathsForModel('contact-page')).toEqual(expect.arrayContaining(['/contact']));
});
it('product 变更要连硬编码的 /products/erp-upgrade 一起刷', () => {
expect(pathsForModel('product', 'erp')).toContain('/products/erp-upgrade');
});
it('legal-page 按 slug 分流;无 slug 时两页都刷', () => {
expect(pathsForModel('legal-page', 'terms')).toEqual(['/terms']);
expect(pathsForModel('legal-page', 'privacy')).toEqual(['/privacy']);
expect(pathsForModel('legal-page')).toEqual(['/privacy', '/terms']);
});
it('case-study 与 methodology 都要刷 /insights(三路真源)', () => {
expect(pathsForModel('case-study')).toContain('/insights');
expect(pathsForModel('methodology')).toContain('/insights');
});
it('content-zone 刷首页', () => {
expect(pathsForModel('content-zone')).toContain('/');
});
});
describe('planRevalidation —— 合成与去重', () => {
it('显式 paths 原样执行(不去重、不解释)', () => {
const plan = planRevalidation({ paths: ['/a', '/a', '/b'] });
expect(plan.paths).toEqual(['/a', '/a', '/b']);
});
it('显式 paths 已含某推导路径时不重复追加', () => {
const listRoute = CONTENT_TYPE_CONFIGS['news'].listPage?.route as string;
const plan = planRevalidation({ paths: [listRoute], modelCode: 'news', slug: 'x' });
expect(plan.paths.filter((p) => p === listRoute)).toHaveLength(1);
});
it('modelCode ⇒ 带 cms:<model> 标签', () => {
expect(planRevalidation({ modelCode: 'news' }).tags).toEqual(['cms:news']);
});
it('content.published 事件 ⇒ 所有已声明列表页 + cms:all', () => {
const plan = planRevalidation({ event: 'content.published' });
expect(plan.tags).toEqual(['cms:all']);
for (const p of allListPagePaths()) expect(plan.paths).toContain(p);
});
it('未知事件不额外扩大失效面', () => {
expect(planRevalidation({ event: 'content.draft_saved' })).toEqual({ paths: [], tags: [] });
});
});
describe('applyRevalidation / revalidateContent —— 副作用出口', () => {
it('逐项调 next/cache 并回报实际应用集', () => {
const applied = applyRevalidation({ paths: ['/news', '/'], tags: ['cms:news'] });
expect(mockRevalidatePath).toHaveBeenCalledWith('/news');
expect(mockRevalidatePath).toHaveBeenCalledWith('/');
expect(mockRevalidateTag).toHaveBeenCalledWith('cms:news', {});
expect(applied).toEqual({ paths: ['/news', '/'], tags: ['cms:news'] });
});
it('revalidateContent 是后台变更链唯一入口:推导 + 执行一次完成', () => {
const applied = revalidateContent('news', 'hello-world');
expect(applied.paths).toEqual(expect.arrayContaining(['/news/hello-world', '/insights', '/']));
expect(mockRevalidatePath.mock.calls.length).toBe(applied.paths.length);
});
it('未知模型 ⇒ 什么都不刷(防止把「推导失败」读成「刷全站」)', () => {
const applied = revalidateContent('不存在的模型');
expect(applied).toEqual({ paths: [], tags: [], failed: [] });
expect(mockRevalidatePath).not.toHaveBeenCalled();
});
/**
* 后台变更链用的是尽力而为版本:数据已落库,刷缓存失败不该把请求变成 500
* (那会让操作者以为「保存失败」而内容其实已经改了)。
* 但也不能静默 —— 失败面必须回报,所以断言的是「不抛 + failed 有条目 + 打了可 grep 的日志」。
*/
it('revalidatePath 抛错时不冒泡,逐条记账并保留其余路径', () => {
const err = new Error('Invariant: static generation store missing');
mockRevalidatePath.mockImplementationOnce(() => {
throw err;
});
const spy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
const applied = revalidateContent('news', 'hello-world');
expect(applied.failed.length).toBe(1);
expect(applied.failed[0]).toMatchObject({ kind: 'path', message: err.message });
// 第一条失败不连累其余
expect(applied.paths.length).toBeGreaterThanOrEqual(1);
expect(spy).toHaveBeenCalledWith(expect.stringContaining('[revalidation-failed]'), err.message);
spy.mockRestore();
});
it('严格的 applyRevalidation 仍会冒泡(/api/cms/revalidate 需要真实 500 语义)', () => {
mockRevalidatePath.mockImplementationOnce(() => {
throw new Error('boom');
});
expect(() => applyRevalidation({ paths: ['/news', '/'], tags: [] })).toThrow('boom');
});
});
+231
View File
@@ -0,0 +1,231 @@
/**
* CMS 缓存失效的单一真源(DEC-N5)。
*
* 为什么要抽出来:`modelCode → 受影响路径` 的推导原先长在 `/api/cms/revalidate` 的路由体里,
* 于是它只能被「外部 HTTP 调用」触发。实测后果是后台的四条变更链
* (创建 / 更新 / 删除 / 工作流发布)**没有任何生产调用方**,而 8 个页面的注释都写着
* 「CMS 发布/更新时通过 /api/cms/revalidate 主动刷新」—— 那句话当时是假的:
* `s-maxage=3600` 下最长 1 小时前台仍端出已删或过期的内容,且没有任何门禁会红。
*
* 本模块把推导变成**纯函数**(`planRevalidation` / `pathsForModel`),把副作用收在
* 一个可导入的出口(`revalidateContent`),让路由与后台变更链共用同一份映射。
* 依据同 `docs/lessons-learned.md` §5.30:安全抽象必须可导入,否则它只在被调用时才存在。
*
* 纯函数不 import `next/cache` ⇒ 单测无需 mock 就能断言映射本身;
* 副作用只在 `applyRevalidation` / `revalidateContent` 里发生。
*/
import { revalidatePath, revalidateTag } from 'next/cache';
import { CONTENT_TYPE_CONFIGS } from '@/lib/cms/content-types';
/** 首页受影响的模型:更新后需要同时刷新 `/`。 */
export const HOME_AFFECTED_MODELS = new Set([
'hero-banner',
'stat-item',
'service',
'case-study',
'solution',
'news',
]);
/**
* 洞察枢纽 /insights 的数据来自三路真源:news(技术与观点)、case-study(客户成果,当前 0 行)、
* methodology(方法论)。它**不在** CONTENT_TYPE_CONFIGS 的任何 listPage 里 ——
* 通用推导只会刷 /news、/methodology,于是后台发了新内容而 /insights 仍端出旧 ISR 快照,
* 最长 1 小时不可见,且没有任何门禁会红。新路由必须显式登记失效映射。
*/
export const INSIGHTS_AFFECTED_MODELS = new Set(['news', 'case-study', 'methodology']);
/**
* 没有 listPage 配置的单页模型:固定映射(S-3)。
* 登记在这里而不是散落在路由体里,是为了让「新增模型必须登记失效面」这件事只有一处可查。
*/
const SINGLE_PAGE_PATHS: Record<string, string> = {
'team-page': '/team',
'about-page': '/about',
'contact-page': '/contact',
};
/**
* 数据来自某模型、但页面路径是硬编码的例外(S-3)。
* `/products/erp-upgrade` 不由 CONTENT_TYPE_CONFIGS 的 routePattern 生成,
* 通用推导刷不到它 ⇒ 后台改 product(slug=erp)时该页会留旧快照。
*/
const HARDCODED_PAGE_PATHS: Record<string, string[]> = {
product: ['/products/erp-upgrade'],
};
export interface RevalidationPlan {
paths: string[];
tags: string[];
}
export interface RevalidationResult {
paths: string[];
tags: string[];
/** 刷失败的面(path/tag 各自独立 try,见 revalidateContent 的注释)。 */
failed: { kind: 'path' | 'tag'; value: string; message: string }[];
}
export interface RevalidationInput {
event?: string;
modelCode?: string;
slug?: string;
paths?: string[];
tags?: string[];
}
function getContentTypeConfig(code: string) {
return CONTENT_TYPE_CONFIGS[code as keyof typeof CONTENT_TYPE_CONFIGS] ?? null;
}
function getAllContentTypeConfigs() {
return Object.values(CONTENT_TYPE_CONFIGS);
}
/**
* 纯推导:给定模型(与可选 slug),前台有哪些路径会因它变更而失效。
* 覆盖:listPage 列表页、detailPage 详情页(需 slug)、legal-page 的固定两页、
* 单页模型、硬编码页面例外、/insights 三路真源、首页、content-zone。
*/
export function pathsForModel(modelCode: string, slug?: string | null): string[] {
const paths: string[] = [];
const push = (p: string) => {
if (!paths.includes(p)) paths.push(p);
};
const config = getContentTypeConfig(modelCode);
if (config) {
if (config.listPage?.route) push(config.listPage.route);
if (config.detailPage?.routePattern && slug) {
push(config.detailPage.routePattern.replace('{slug}', slug));
}
}
// legal-page 为特殊页面类型,固定映射到 /privacy 和 /terms
if (modelCode === 'legal-page') {
if (slug) push(slug === 'terms' ? '/terms' : '/privacy');
else {
push('/privacy');
push('/terms');
}
}
const single = SINGLE_PAGE_PATHS[modelCode];
if (single) push(single);
for (const p of HARDCODED_PAGE_PATHS[modelCode] ?? []) push(p);
// 洞察枢纽:三个上游模型任一变更都要刷 /insights
if (INSIGHTS_AFFECTED_MODELS.has(modelCode)) push('/insights');
// 首页相关模型、以及 ContentZone 变更时同步刷新 /
if (HOME_AFFECTED_MODELS.has(modelCode) || modelCode === 'content-zone') push('/');
return paths;
}
/** 只有存在 content-type 配置时才打标签(与重构前的路由行为逐字一致)。 */
export function tagsForModel(modelCode: string): string[] {
return getContentTypeConfig(modelCode) ? [`cms:${modelCode}`] : [];
}
/** 所有已声明的列表页 —— 用于 `content.published` / `content.updated` 这种不带 modelCode 的事件。 */
export function allListPagePaths(): string[] {
const paths: string[] = [];
for (const config of getAllContentTypeConfigs()) {
const route = config.listPage?.route;
if (route && !paths.includes(route)) paths.push(route);
}
return paths;
}
/**
* 把显式传入的 paths/tags 与由 modelCode 推导的结果合成一份执行计划。
* 语义与重构前的路由体逐字对齐(显式列表不去重、推导段按 includes 去重),
* 这样 `/api/cms/revalidate` 的既有契约与既有测试不会因为「顺手改成全局去重」而漂移。
*/
export function planRevalidation(input: RevalidationInput): RevalidationPlan {
const paths: string[] = [];
const tags: string[] = [];
const pushUnique = (list: string[], value: string) => {
if (!list.includes(value)) list.push(value);
};
if (input.paths && input.paths.length > 0) {
for (const p of input.paths) paths.push(p);
}
if (input.tags && input.tags.length > 0) {
for (const t of input.tags) tags.push(t);
}
if (input.modelCode) {
for (const p of pathsForModel(input.modelCode, input.slug ?? null)) pushUnique(paths, p);
for (const t of tagsForModel(input.modelCode)) pushUnique(tags, t);
}
if (input.event === 'content.published' || input.event === 'content.updated') {
for (const p of allListPagePaths()) pushUnique(paths, p);
pushUnique(tags, 'cms:all');
}
return { paths, tags };
}
/** 执行一份计划:真正的 next/cache 副作用只发生在这里。 */
export function applyRevalidation(plan: RevalidationPlan): RevalidationPlan {
const applied: RevalidationPlan = { paths: [], tags: [] };
for (const path of plan.paths) {
revalidatePath(path);
applied.paths.push(path);
}
for (const tag of plan.tags) {
revalidateTag(tag, {});
applied.tags.push(tag);
}
return applied;
}
/**
* 后台变更链的唯一出口:按模型(与 slug)推导失效面并执行。
*
* 与 `applyRevalidation` 的分工是刻意的:
* - 路由 `/api/cms/revalidate` 用严格的 `applyRevalidation` —— 它失败就该回 500,调用方需要知道。
* - 后台变更链用这个**尽力而为**版本:数据已落库,此刻再因为「刷缓存失败」把请求变成 500,
* 等于告诉操作者「保存失败」而内容其实已经改了(比旧快照更糟)。
* 所以逐条 try:一条路径刷失败不连累其余,失败面以 `[revalidation-failed]` 打日志(可 grep),
* 并通过 `failed` 字段回报给调用方。
*
* 时序:调用点必须在**数据与审计都落库之后**,否则刷新会重新读到旧内容(ISR 的时序坑)。
*/
export function revalidateContent(
modelCode: string,
slug?: string | null
): RevalidationResult {
const plan = planRevalidation({ modelCode, slug: slug ?? undefined });
const applied: RevalidationResult = { paths: [], tags: [], failed: [] };
for (const path of plan.paths) {
try {
revalidatePath(path);
applied.paths.push(path);
} catch (error) {
applied.failed.push({ kind: 'path', value: path, message: messageOf(error) });
console.error(`[revalidation-failed] path=${path} model=${modelCode}:`, messageOf(error));
}
}
for (const tag of plan.tags) {
try {
revalidateTag(tag, {});
applied.tags.push(tag);
} catch (error) {
applied.failed.push({ kind: 'tag', value: tag, message: messageOf(error) });
console.error(`[revalidation-failed] tag=${tag} model=${modelCode}:`, messageOf(error));
}
}
return applied;
}
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}