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

+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);
}