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:
1 parent
0ae765afcd
commit
f3e66f7d36
9 files changed
+660
-134
No files matched your search
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user