refactor(posts): use precise cache invalidation in rebuild

This commit is contained in:
xfy 2026-06-17 16:37:20 +08:00
parent bb34e2c36e
commit c03093fc8b

View File

@ -34,14 +34,14 @@ pub async fn rebuild_content_html(rebuild_all: bool) -> Result<RebuildResult, Se
{
let client = get_conn().await.map_err(AppError::db_conn)?;
// 根据参数构造 WHERE 条件,限制单次处理数量
// 根据参数构造 WHERE 条件,限制单次处理数量;同时查询 slug 用于精准失效缓存
let query = if rebuild_all {
format!(
"SELECT id, content_md FROM posts WHERE deleted_at IS NULL ORDER BY id LIMIT {REBUILD_BATCH_LIMIT}"
"SELECT id, slug, content_md FROM posts WHERE deleted_at IS NULL ORDER BY id LIMIT {REBUILD_BATCH_LIMIT}"
)
} else {
format!(
"SELECT id, content_md FROM posts WHERE deleted_at IS NULL AND content_html IS NULL ORDER BY id LIMIT {REBUILD_BATCH_LIMIT}"
"SELECT id, slug, content_md FROM posts WHERE deleted_at IS NULL AND content_html IS NULL ORDER BY id LIMIT {REBUILD_BATCH_LIMIT}"
)
};
@ -50,10 +50,12 @@ pub async fn rebuild_content_html(rebuild_all: bool) -> Result<RebuildResult, Se
let mut rebuilt: u64 = 0;
let mut failed: u64 = 0;
let mut errors: Vec<String> = Vec::new();
let mut rebuilt_slugs: Vec<String> = Vec::with_capacity(rows.len());
for row in &rows {
let id: i32 = row.get(0);
let content_md: String = row.get(1);
let slug: String = row.get(1);
let content_md: String = row.get(2);
// 捕获 Markdown 渲染 panic避免单条记录导致整批失败。
let rendered = match std::panic::catch_unwind(|| {
@ -91,7 +93,10 @@ pub async fn rebuild_content_html(rebuild_all: bool) -> Result<RebuildResult, Se
)
.await
{
Ok(_) => rebuilt += 1,
Ok(_) => {
rebuilt += 1;
rebuilt_slugs.push(slug);
}
Err(_) => {
failed += 1;
if errors.len() < MAX_DISPLAY_ERRORS {
@ -101,9 +106,14 @@ pub async fn rebuild_content_html(rebuild_all: bool) -> Result<RebuildResult, Se
}
}
// 只要有文章被更新,就清空所有文章缓存。
if rebuilt > 0 || failed > 0 {
crate::cache::invalidate_all_post_caches();
// 只要有文章被更新,就按影响范围失效缓存:列表、标签云、统计,以及每篇被重建文章的 slug 缓存。
if rebuilt > 0 {
crate::cache::invalidate_post_lists();
crate::cache::invalidate_all_tags();
crate::cache::invalidate_post_stats();
for slug in &rebuilt_slugs {
crate::cache::invalidate_post_by_slug(slug).await;
}
}
Ok(RebuildResult {