- 扁平化:rust/crates/plugin-cache/src → src/,单包 Cargo.toml(name ipass-plugin-cache 2.0.0),
path 依赖改 ../ipass-core(内核+vendor ngx),删除旧单体拆分残留(rust/ 层级、
deps/ipass submodule、.gitmodules、conf/、tests/、多页静态 www/、AGENTS.md)
- R19 启停对齐:access/log 热路径加 plugin_registry::plugin_enabled("cache")
门控,fail-closed 404(数据面是鉴权后磁盘读,禁用放行=无鉴权读缓存盘);
location 圈定暂用 8 前缀路由表,ipass_cache 指令待 gateway 接入轮
- 旧独立应用形态保留在 tag legacy-app-final
- 文档:CLAUDE.md(装配关系+未挂载待办+本机编译 env 姿势)、README.md、
docs/cache-usage.md 保留;docs/plugins.md(单体时代)删除
- 验证:cargo check --release 通过,cargo test 4 passed
Co-Authored-By: Claude Opus 4.8 <[email protected]>
847 lines
32 KiB
Rust
847 lines
32 KiB
Rust
//! 容量管理:把 **nginx 自己的 proxy_cache 记账** 读出来,并提供按区清理。
|
||
//!
|
||
//! ## 为什么不自己扫盘
|
||
//!
|
||
//! 「缓存占了多大、快不快满」是一件 nginx 已经知道的事:它把每个缓存区
|
||
//! (`proxy_cache_path` 的 `keys_zone`)的**条目数、已用块数、上限、水位线**
|
||
//! 全放在共享内存里,并且**淘汰逻辑用的就是这几个数**。自己扫盘算一遍至少有
|
||
//! 三个坑:① 与 nginx 的口径不一致(它按块向上取整记账,`stat` 出来的文件
|
||
//! 大小不是这个数);② 大目录扫一次几十万文件,放在请求路径里就是事故;
|
||
//! ③ 容量上限得从 conf 再抄一遍到代码里,**两处必然漂移**。
|
||
//!
|
||
//! 所以这里直读 `ngx_http_file_cache_sh_t`:读数的口径与淘汰动作**同源**,
|
||
//! 且新增/修改 zone 时本模块不用改一行代码。
|
||
//!
|
||
//! ## 怎么在共享内存里认出「哪个 zone 是 proxy_cache 的」
|
||
//!
|
||
//! 靠 nginx 自己的所有权标记:`ngx_shared_memory_add(cf, &name, size, tag)` 的
|
||
//! `tag`,而 `proxy_cache_path` 传的 tag 是 `cmd->post`,即 **`&ngx_http_proxy_module`**
|
||
//! (见 `ngx_http_file_cache.c:2691` 与 `ngx_http_proxy_module.c:436-441`)。
|
||
//! tag 相等 ⇒ 该 zone 的 `data` 必然是一个 `ngx_http_file_cache_t`,可以直接读。
|
||
//!
|
||
//! **这不是猜名字**:名字可能被改、可能被复制粘贴错,tag 是 nginx 的权威归属。
|
||
//! 反过来,如果不用 tag 而按名字找 zone,一旦名字对上一个**别的插件**的 zone,
|
||
//! `data` 就不是 file_cache,强转会读到野指针——那是崩溃,不是报错。
|
||
//!
|
||
//! 那个符号能不能引用?能。nginx 的 `auto/cc/conf:167-178` 会探测并把
|
||
//! `-Wl,-E` 放进 `MAIN_LINK`,**二进制因此导出全部全局符号**——动态模块生态
|
||
//! 本来就靠这个(否则模块连 `ngx_http_internal_redirect` 都调不到)。
|
||
//!
|
||
//! ## 单位:全部是「块」,不是字节
|
||
//!
|
||
//! `ngx_http_file_cache_init` 里有一句 `cache->max_size /= cache->bsize`
|
||
//! (新起与 reload 两条路径都有),而 `sh->size` 累加的是 `node->fs_size`
|
||
//! —— 也是块。所以**比值可以直接用来算水位**,要字节就乘回 `bsize`
|
||
//! (`ngx_fs_bsize()`,通常 4096)。
|
||
//!
|
||
//! ## 两条容量轴,缺一不可
|
||
//!
|
||
//! | 轴 | 载体 | 耗尽后果 | 这里怎么体现 |
|
||
//! | --- | --- | --- | --- |
|
||
//! | 磁盘 | `max_size` / `sh->size` | 按 LRU 淘汰旧条目(渐进,非硬配额) | `limit_bytes` / `used_bytes` / `pct` |
|
||
//! | 索引内存 | `keys_zone` 的 `shm.size`(条目元数据) | **nftc 淘汰也救不了**:新条目分不到节点,nginx 会设 `watermark` 改按**条目数**淘汰 | `keys_zone_bytes` / `entries` / `index_pressure` |
|
||
//!
|
||
//! 第二条轴很容易被漏掉,但它的信号最硬:`sh->watermark != (ngx_uint_t)-1`
|
||
//! 表示 nginx **已经**因为索引内存吃紧而开始强制回收(`set_watermark` 只在
|
||
//! 节点分配失败时调用)。看到它就该扩 `keys_zone` 了。
|
||
|
||
use core::ffi::c_void;
|
||
use std::fs;
|
||
use std::io::Read;
|
||
use std::path::{Path, PathBuf};
|
||
use std::sync::Mutex;
|
||
|
||
use nginx_sys::{
|
||
ngx_conf_t, ngx_http_file_cache_node_t, ngx_http_file_cache_t, ngx_list_part_t, ngx_module_t,
|
||
ngx_shm_zone_t, ngx_str_t,
|
||
};
|
||
|
||
use ipass_core::util;
|
||
|
||
use crate::config;
|
||
|
||
// nginx 内建的 proxy 模块对象。**只要它的地址**,不读它的字段。
|
||
//
|
||
// 见文件头「怎么认出 proxy_cache 的 zone」——它就是 `proxy_cache_path`
|
||
// 注册共享内存时用的 tag。
|
||
extern "C" {
|
||
static ngx_http_proxy_module: ngx_module_t;
|
||
}
|
||
|
||
/// 一个 proxy_cache 区的静态身份。config 阶段发现一次,之后只读。
|
||
struct ZoneRef {
|
||
/// `keys_zone` 名。本仓库约定 = 生态名(`go` / `cargo` / `pypi` / `npm` / …)
|
||
name: String,
|
||
/// 磁盘目录(`proxy_cache_path` 的第一段)
|
||
dir: PathBuf,
|
||
/// `keys_zone` 的共享内存字节数 —— 索引容量(条目元数据住在这里)
|
||
keys_zone_bytes: usize,
|
||
/// `zone->data`,即 nginx 的 `ngx_http_file_cache_t`
|
||
cache: *mut ngx_http_file_cache_t,
|
||
}
|
||
|
||
// SAFETY: 指针由 nginx 在 config 阶段填好,fork 之后各 worker 只读;
|
||
// 我们既不跨线程移动它,也不在 worker 里改 `data` 指向的对象。
|
||
unsafe impl Send for ZoneRef {}
|
||
unsafe impl Sync for ZoneRef {}
|
||
|
||
/// 发现到的全部 proxy_cache 区(`postconfig` 时填一次)。
|
||
///
|
||
/// 用 `Mutex` 而不是 `OnceLock`:reload 会走一遍新的 config 解析,
|
||
/// 那时要用新 cycle 的 zone 覆盖旧的(zone 名相同但对象是新的)。
|
||
static ZONES: Mutex<Vec<ZoneRef>> = Mutex::new(Vec::new());
|
||
|
||
/// `ngx_str_t` → `String`(拷出来,不持有配置池内存)
|
||
///
|
||
/// # Safety
|
||
/// `s.data` 若非空,必须是 `s.len` 字节的有效只读区(nginx 的配置池字符串满足)。
|
||
unsafe fn nstr(s: ngx_str_t) -> String {
|
||
if s.data.is_null() || s.len == 0 {
|
||
return String::new();
|
||
}
|
||
String::from_utf8_lossy(core::slice::from_raw_parts(s.data, s.len)).into_owned()
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 发现(postconfig 调用一次)
|
||
// ===========================================================================
|
||
|
||
/// 遍历 `cycle->shared_memory`,挑出所有 proxy_cache 区。返回发现个数。
|
||
///
|
||
/// 时机很关键:必须在 **config 阶段**(`postconfig`)调,因为
|
||
/// `zone->data` 是 `proxy_cache_path` 解析时赋的(`set_slot` 末尾),
|
||
/// 此时已可用;而 `cache->sh`(共享内存里的记账结构)要到 `ngx_init_cycle`
|
||
/// 的 init 回调才填好 —— 所以这里**只记指针,不读 `sh`**,读数全部推迟到
|
||
/// 请求期(见 [`snapshot`])。
|
||
pub fn discover(cf: *mut ngx_conf_t) -> usize {
|
||
if cf.is_null() {
|
||
return 0;
|
||
}
|
||
// 取 tag 指针(`addr_of!` 只算地址、不读该符号,故无需 unsafe 上下文)。
|
||
// 若某天 nginx 不再导出这个符号,本模块会退化成「容量面板不可用」,
|
||
// 而不是把整个模块拖死——见文件头。
|
||
let tag = core::ptr::addr_of!(ngx_http_proxy_module).cast::<c_void>() as *mut c_void;
|
||
|
||
let mut found: Vec<ZoneRef> = Vec::new();
|
||
|
||
// SAFETY: 下面只读 cycle/zone 的元数据,并在指针非空时按 nginx 的布局解引用
|
||
unsafe {
|
||
let cycle = (*cf).cycle;
|
||
if cycle.is_null() {
|
||
return 0;
|
||
}
|
||
// `cycle->shared_memory` 是 ngx_list_t(不是 array),按 part/next 链走
|
||
let mut part: *mut ngx_list_part_t = core::ptr::addr_of_mut!((*cycle).shared_memory.part);
|
||
loop {
|
||
if part.is_null() {
|
||
break;
|
||
}
|
||
let nelts = (*part).nelts;
|
||
let elts = (*part).elts as *mut ngx_shm_zone_t;
|
||
if !elts.is_null() {
|
||
for i in 0..nelts {
|
||
let z = elts.add(i);
|
||
// ★ 权威归属判定:tag 不相等就不是 proxy_cache 的区,跳过
|
||
if (*z).tag != tag {
|
||
continue;
|
||
}
|
||
let cache = (*z).data as *mut ngx_http_file_cache_t;
|
||
if cache.is_null() {
|
||
continue;
|
||
}
|
||
let path = (*cache).path;
|
||
if path.is_null() || (*path).name.data.is_null() {
|
||
continue;
|
||
}
|
||
found.push(ZoneRef {
|
||
name: nstr((*z).shm.name),
|
||
dir: PathBuf::from(nstr((*path).name)),
|
||
keys_zone_bytes: (*z).shm.size,
|
||
cache,
|
||
});
|
||
}
|
||
}
|
||
if (*part).next.is_null() {
|
||
break;
|
||
}
|
||
part = (*part).next;
|
||
}
|
||
}
|
||
|
||
let n = found.len();
|
||
// 名字先拷成 owned:下面要把 `found` 整个移进静态表,不能再有借用
|
||
let names: Vec<String> = found.iter().map(|z| z.name.clone()).collect();
|
||
{
|
||
let mut g = ZONES.lock().unwrap_or_else(|e| e.into_inner());
|
||
*g = found;
|
||
}
|
||
|
||
if n == 0 {
|
||
// 不是致命错误:读不到就只是「容量面板不可用」,其余功能照旧。
|
||
// 但必须**说清楚**,别让运维在界面上看到一个空白面板去猜。
|
||
util::log_warn(
|
||
"[cache] 未发现任何 proxy_cache 区:容量读数不可用。\
|
||
若 conf 里确有 proxy_cache_path,多半是 nginx 未导出符号 \
|
||
(见 zones.rs 文件头)或 config 阶段早于 proxy_cache_path 解析",
|
||
);
|
||
} else {
|
||
util::log_notice(&format!("[cache] 容量区已识别 {} 个:{:?}", n, names));
|
||
}
|
||
n
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 读数(请求期调用)
|
||
// ===========================================================================
|
||
|
||
/// 一个缓存区的容量快照。
|
||
pub struct ZoneView {
|
||
pub name: String,
|
||
pub eco: &'static str,
|
||
pub dir: String,
|
||
pub dir_exists: bool,
|
||
pub routes: Vec<&'static str>,
|
||
/// 磁盘上限(字节)。由 `max_size * bsize` 还原——nginx 内部按块记账
|
||
pub limit_bytes: i64,
|
||
pub used_bytes: i64,
|
||
pub pct: f64,
|
||
pub entries: u64,
|
||
/// 索引内存(keys_zone)字节数
|
||
pub keys_zone_bytes: u64,
|
||
/// 索引条目容量的**估算**(`keys_zone / sizeof(节点)`;未扣 slab 开销与元数据)
|
||
pub entries_cap_est: u64,
|
||
/// nginx 是否已因索引内存吃紧而改按条目数淘汰(watermark 已设)
|
||
pub index_pressure: bool,
|
||
pub bsize: u64,
|
||
pub inactive_secs: i64,
|
||
/// 启动后仍在从磁盘装载(此时条目数会一路上涨,属正常)
|
||
pub cold: bool,
|
||
pub loading: bool,
|
||
/// `ok` / `warn` / `crit`(判定只此一处,前端不重算)
|
||
pub level: &'static str,
|
||
/// 磁盘实测(可选,`scan=1` 时才算)。见 [`disk_usage`]
|
||
pub disk: Option<DiskUsage>,
|
||
}
|
||
|
||
/// 磁盘实测结果
|
||
pub struct DiskUsage {
|
||
pub bytes: u64,
|
||
pub files: u64,
|
||
/// 达到扫描上限而提前结束(数字是下界,不是精确值)
|
||
pub truncated: bool,
|
||
}
|
||
|
||
/// 水位的告警线。判定放在后端是为了让「界面上的红」与「运维的判断」一致;
|
||
/// 前端各自拍一个数字,同一份数据在不同页面就会显示成不同颜色。
|
||
const WARN_PCT: f64 = 80.0;
|
||
const CRIT_PCT: f64 = 95.0;
|
||
|
||
/// 读全部区的容量。`scan` = 是否同时盘点磁盘(见 [`disk_usage`])。
|
||
///
|
||
/// **只读、无锁**:这里读的 `sh->size` / `sh->count` 在 nginx 侧是加
|
||
/// `shpool->mutex` 读的,我们不加锁是为了不在管理请求里被写缓存的临界区卡住。
|
||
/// 64 位对齐读不会撕裂,最多是「差几毫秒的旧值」—— 对一个展示用的水位读数够用。
|
||
pub fn snapshot(scan: bool) -> Vec<ZoneView> {
|
||
let g = ZONES.lock().unwrap_or_else(|e| e.into_inner());
|
||
g.iter().map(|z| view_of(z, scan)).collect()
|
||
}
|
||
|
||
/// 磁盘实测:递归统计目录里的**文件**数与字节数。
|
||
///
|
||
/// ## 为什么默认不开
|
||
///
|
||
/// 大 zone 可能有上百个万小文件,完整走一遍是秒级;而管理台刷新是高频动作。
|
||
/// 所以默认只读 nginx 记账(O(1)),要核对时显式 `scan=1`。
|
||
/// 扫描有上限保护:到 `MAX_SCAN_FILES` 就停并标 `truncated`——宁可给一个
|
||
/// 标明「不完整」的下界,也不要让一个管理请求在千万级目录上挂住。
|
||
///
|
||
/// ## 它存在的理由:记账会滞后
|
||
///
|
||
/// nginx 的 `sh->size` / `sh->count` 只在**它自己删**(到期/容量淘汰)或
|
||
/// **某个 key 再次被访问**(那时才发现文件不在了)时回落。手工清空缓存文件
|
||
/// 之后节点还在 rbtree 里,于是「面板显示占 600MB、磁盘其实是空的」这种
|
||
/// 假象会持续到条目到期(默认 `inactive=7d`)。把两个数并排显示,
|
||
/// 这个差就是**可见的**,而不是等着人去猜。
|
||
pub fn disk_usage(root: &Path) -> DiskUsage {
|
||
let mut acc = DiskUsage {
|
||
bytes: 0,
|
||
files: 0,
|
||
truncated: false,
|
||
};
|
||
let _ = walk_disk(root, 0, &mut acc);
|
||
acc
|
||
}
|
||
|
||
/// 实测扫描的文件数上限(防呆;到顶即停并标 truncated)
|
||
const MAX_SCAN_FILES: u64 = 200_000;
|
||
|
||
fn walk_disk(root: &Path, depth: usize, acc: &mut DiskUsage) -> std::io::Result<()> {
|
||
const MAX_DEPTH: usize = 6;
|
||
if depth > MAX_DEPTH {
|
||
return Ok(());
|
||
}
|
||
for ent in fs::read_dir(root)? {
|
||
if acc.files >= MAX_SCAN_FILES {
|
||
acc.truncated = true;
|
||
return Ok(());
|
||
}
|
||
let ent = ent?;
|
||
let ft = ent.file_type()?;
|
||
if ft.is_dir() {
|
||
walk_disk(&ent.path(), depth + 1, acc)?;
|
||
} else if ft.is_file() {
|
||
acc.bytes += ent.metadata().map(|m| m.len()).unwrap_or(0);
|
||
acc.files += 1;
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn view_of(z: &ZoneRef, scan: bool) -> ZoneView {
|
||
let eco = eco_of_zone(&z.name);
|
||
let routes = routes_of_eco(eco);
|
||
let dir_exists = z.dir.is_dir();
|
||
|
||
// SAFETY: cache 由 discover 从 tag 校验过的 zone 里取出;`sh` 在 init 后非空
|
||
let (limit_bytes, used_bytes, entries, index_pressure, bsize, inactive, cold, loading) =
|
||
unsafe {
|
||
let c = z.cache;
|
||
if c.is_null() {
|
||
return empty_view(z, eco, routes, dir_exists, scan);
|
||
}
|
||
let bs = (*c).bsize as i64;
|
||
let sh = (*c).sh;
|
||
if sh.is_null() {
|
||
// init 尚未跑完(极早期)——不编数字,如实给 0
|
||
return empty_view(z, eco, routes, dir_exists, scan);
|
||
}
|
||
(
|
||
(*c).max_size * bs, // max_size 已是「块」
|
||
(*sh).size * bs, // 同上
|
||
(*sh).count as u64,
|
||
(*sh).watermark != usize::MAX,
|
||
bs as u64,
|
||
(*c).inactive as i64,
|
||
(*sh).cold != 0,
|
||
(*sh).loading != 0,
|
||
)
|
||
};
|
||
|
||
let pct = if limit_bytes > 0 {
|
||
(used_bytes as f64 / limit_bytes as f64) * 100.0
|
||
} else {
|
||
0.0
|
||
};
|
||
|
||
let node_size = core::mem::size_of::<ngx_http_file_cache_node_t>() as u64;
|
||
let entries_cap_est = if node_size > 0 {
|
||
z.keys_zone_bytes as u64 / node_size
|
||
} else {
|
||
0
|
||
};
|
||
|
||
// 目录缺失 = 最严重:nginx 运行期不会重建 cache/<eco>,此后**每次写缓存
|
||
// 都会 [crit] mkdir 失败并直接断开客户端**(详见 docs 的「容量与淘汰」一节)。
|
||
let level = if !dir_exists {
|
||
"crit"
|
||
} else if index_pressure || pct >= CRIT_PCT {
|
||
"crit"
|
||
} else if pct >= WARN_PCT {
|
||
"warn"
|
||
} else {
|
||
"ok"
|
||
};
|
||
|
||
ZoneView {
|
||
name: z.name.clone(),
|
||
eco,
|
||
dir: z.dir.to_string_lossy().into_owned(),
|
||
dir_exists,
|
||
routes,
|
||
limit_bytes,
|
||
used_bytes,
|
||
pct,
|
||
entries,
|
||
keys_zone_bytes: z.keys_zone_bytes as u64,
|
||
entries_cap_est,
|
||
index_pressure,
|
||
bsize,
|
||
inactive_secs: inactive,
|
||
cold,
|
||
loading,
|
||
level,
|
||
disk: if scan { Some(disk_usage(&z.dir)) } else { None },
|
||
}
|
||
}
|
||
|
||
fn empty_view(
|
||
z: &ZoneRef,
|
||
eco: &'static str,
|
||
routes: Vec<&'static str>,
|
||
dir_exists: bool,
|
||
scan: bool,
|
||
) -> ZoneView {
|
||
ZoneView {
|
||
name: z.name.clone(),
|
||
eco,
|
||
dir: z.dir.to_string_lossy().into_owned(),
|
||
dir_exists,
|
||
routes,
|
||
limit_bytes: 0,
|
||
used_bytes: 0,
|
||
pct: 0.0,
|
||
entries: 0,
|
||
keys_zone_bytes: z.keys_zone_bytes as u64,
|
||
entries_cap_est: 0,
|
||
index_pressure: false,
|
||
bsize: 0,
|
||
inactive_secs: 0,
|
||
cold: false,
|
||
loading: false,
|
||
level: if dir_exists { "ok" } else { "crit" },
|
||
disk: if scan { Some(disk_usage(&z.dir)) } else { None },
|
||
}
|
||
}
|
||
|
||
/// zone 名 → 生态名(本仓库约定二者同名)。不在生态表里返回空串(照实展示,不猜)。
|
||
fn eco_of_zone(zone: &str) -> &'static str {
|
||
config::ECOS
|
||
.iter()
|
||
.copied()
|
||
.find(|e| *e == zone && *e != config::ECO_DEFAULT)
|
||
.unwrap_or("")
|
||
}
|
||
|
||
/// 生态 → 路由列表(cargo 生态含 `cargo` 与 `cargo-dl` 两个路由,共用同一个 zone)
|
||
fn routes_of_eco(eco: &str) -> Vec<&'static str> {
|
||
if eco.is_empty() {
|
||
return Vec::new();
|
||
}
|
||
config::ROUTES
|
||
.iter()
|
||
.copied()
|
||
.filter(|r| config::eco_of_route(r) == eco)
|
||
.collect()
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 清理(管理 API 调用)
|
||
// ===========================================================================
|
||
|
||
/// 一个区的清理结果
|
||
pub struct PurgeItem {
|
||
pub zone: String,
|
||
pub dir: String,
|
||
pub files: u64,
|
||
pub bytes: u64,
|
||
pub dir_exists: bool,
|
||
}
|
||
|
||
/// 按区清理磁盘缓存。`selector` = 生态/区名,或 `all`。
|
||
///
|
||
/// ## 只删文件,**绝不删目录**
|
||
///
|
||
/// nginx 只在**启动时**创建 `cache/<eco>` 这些目录,运行期只按 `levels`
|
||
/// 建下级目录。父目录一旦被删,它不会自愈:此后每次写缓存都
|
||
/// `[crit] mkdir() failed` 并**直接断开客户端**,整条路由不可用直到 reload。
|
||
/// 本仓库在脚本里已经踩过一次(见 docs 的「容量与淘汰」),所以这里的实现
|
||
/// 是「递归删到文件为止」——目录一棵都不动,`purge` 之后目录树依然完好。
|
||
///
|
||
/// ## 与 nginx 记账的对齐
|
||
///
|
||
/// 删文件是**绕过** nginx 的(官方 purge 模块走的是商业版接口)。删掉之后:
|
||
/// ① 请求会命中 MISS 重新回源,不会返回脏数据(Tier1/Tier2 已验证);
|
||
/// ② `sh->size` 的记账要等 cache manager 下一轮发现文件不在了才回落
|
||
/// (默认亚秒级),所以**清完立刻看容量面板可能还显示旧值**,属正常。
|
||
/// 界面上的提示语就是这么写的,别让它看起来像个 bug。
|
||
pub fn purge(selector: &str) -> Result<Vec<PurgeItem>, String> {
|
||
let sel = selector.trim();
|
||
if sel.is_empty() {
|
||
return Err("缺少 zone 参数(填生态名或 all)".to_owned());
|
||
}
|
||
|
||
let targets: Vec<(String, PathBuf)> = {
|
||
let g = ZONES.lock().unwrap_or_else(|e| e.into_inner());
|
||
if g.is_empty() {
|
||
return Err("未发现任何 proxy_cache 区,无法清理(见 error_log 的 [cache] 告警)"
|
||
.to_owned());
|
||
}
|
||
if sel.eq_ignore_ascii_case("all") {
|
||
g.iter().map(|z| (z.name.clone(), z.dir.clone())).collect()
|
||
} else {
|
||
let hit: Vec<_> = g
|
||
.iter()
|
||
.filter(|z| z.name == sel || eco_of_zone(&z.name) == sel)
|
||
.map(|z| (z.name.clone(), z.dir.clone()))
|
||
.collect();
|
||
if hit.is_empty() {
|
||
let known: Vec<&str> = g.iter().map(|z| z.name.as_str()).collect();
|
||
return Err(format!("未知的缓存区 {sel}(已知:{known:?},或用 all)"));
|
||
}
|
||
hit
|
||
}
|
||
};
|
||
|
||
let mut out = Vec::with_capacity(targets.len());
|
||
for (zone, dir) in targets {
|
||
let mut acc = (0u64, 0u64);
|
||
let exists = dir.is_dir();
|
||
if exists {
|
||
// 只可能因为权限/IO 出错;不要因为一个区失败就整批中止,
|
||
// 但要如实报出来(调用方看得到哪个区没清干净)。
|
||
let _ = purge_files(&dir, 0, &mut acc);
|
||
}
|
||
out.push(PurgeItem {
|
||
zone,
|
||
dir: dir.to_string_lossy().into_owned(),
|
||
files: acc.0,
|
||
bytes: acc.1,
|
||
dir_exists: exists,
|
||
});
|
||
}
|
||
|
||
let total_f: u64 = out.iter().map(|i| i.files).sum();
|
||
let total_b: u64 = out.iter().map(|i| i.bytes).sum();
|
||
util::log_notice(&format!(
|
||
"[cache] 清理缓存 selector={sel} 删除 {} 个文件 / {} 字节(只删文件,目录保留)",
|
||
total_f, total_b
|
||
));
|
||
Ok(out)
|
||
}
|
||
|
||
/// 递归删文件。深度上限防呆(正常 `levels=1:2` 只有 3 层)。
|
||
fn purge_files(root: &Path, depth: usize, acc: &mut (u64, u64)) -> std::io::Result<()> {
|
||
const MAX_DEPTH: usize = 6;
|
||
if depth > MAX_DEPTH {
|
||
return Ok(());
|
||
}
|
||
for ent in fs::read_dir(root)? {
|
||
let ent = ent?;
|
||
let ft = ent.file_type()?;
|
||
if ft.is_dir() {
|
||
purge_files(&ent.path(), depth + 1, acc)?;
|
||
} else if ft.is_file() {
|
||
// 先取大小再删:删完 metadata 就没了
|
||
let len = ent.metadata().map(|m| m.len()).unwrap_or(0);
|
||
if fs::remove_file(ent.path()).is_ok() {
|
||
acc.0 += 1;
|
||
acc.1 += len;
|
||
}
|
||
}
|
||
// 符号链接/其他类型一律不动(file_type 是链接本身,不会跟随)
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 按制品失效(管理 API 调用)
|
||
// ===========================================================================
|
||
|
||
/// nginx 缓存文件里 KEY 行的明文前缀。
|
||
///
|
||
/// ## 为什么不解析 `ngx_http_file_cache_header_t`
|
||
///
|
||
/// 那个结构体是**版本相关**的:字段增删过好几次(`updating_time` / `error_time` /
|
||
/// `vary_len` 都是后加的),按它算偏移量去读 key,一旦 nginx 版本对不上就是**错位**——
|
||
/// 表现不是报错,而是「匹配不到任何东西」或更糟的「匹配到错误的东西然后删掉」。
|
||
///
|
||
/// 而 nginx 在写缓存文件时,把 key **以明文**写在元数据头之后:
|
||
///
|
||
/// ```text
|
||
/// <二进制元数据头>
|
||
/// KEY: npm:/npm/lodashGET*/*
|
||
/// HTTP/1.1 200 OK
|
||
/// ...
|
||
/// ```
|
||
///
|
||
/// 所以这里改成**搜标记**:不依赖任何结构体布局,跨版本稳定;找不到标记就当
|
||
/// 「不是缓存文件」跳过(比如正好撞上正在写入、还没写 key 的文件)。
|
||
const KEY_MARK: &[u8] = b"KEY: ";
|
||
|
||
/// 读文件头部的字节数。key 紧跟在二进制头后面(头部 + etag/vary 合起来通常 <1KB),
|
||
/// 8KB 有充足余量,同时保证每个文件只读一次小 `read`,不把大制品读进内存。
|
||
const HEAD_READ: usize = 8192;
|
||
|
||
/// 单次失效最多删除的文件数(防呆:把 `match` 写宽了不至于一次清空整盘)。
|
||
const MAX_DELETE: u64 = 5000;
|
||
|
||
/// 单次失效最多扫描的文件数
|
||
const MAX_INVALIDATE_SCAN: u64 = 200_000;
|
||
|
||
/// 返回给界面的命中 key 样例上限
|
||
const MAX_KEY_SAMPLES: usize = 50;
|
||
|
||
/// 一个区的「按制品失效」结果
|
||
pub struct InvalidateItem {
|
||
pub zone: String,
|
||
pub dir: String,
|
||
/// 命中的文件数(`apply=false` 时是「将要删除」的个数)
|
||
pub matched: u64,
|
||
/// 实际删除的个数(`apply=false` 时恒为 0)
|
||
pub deleted: u64,
|
||
/// 命中文件的总字节(`apply=true` 时即释放量)
|
||
pub bytes: u64,
|
||
/// 区分去重后的命中 key(样例,最多 [`MAX_KEY_SAMPLES`] 条)
|
||
pub keys: Vec<String>,
|
||
/// 命中数超过 [`MAX_DELETE`] 或扫描触顶——数字是下界,不是精确值
|
||
pub truncated: bool,
|
||
pub dir_exists: bool,
|
||
}
|
||
|
||
/// 按制品失效:在指定区(或全部区)里找出 cache key 匹配 `pattern` 的条目并删除。
|
||
///
|
||
/// ## 与 [`purge`] 的分工
|
||
///
|
||
/// `purge` 是「整区清空」——把某个生态的缓存全扔掉。它解决的是「这个生态整体脏了」,
|
||
/// 但运维更常见的事故是**局部**的:上游把 `[email protected]` 发成了坏包、某个
|
||
/// `maven-metadata.xml` 发布错了版本。这时清掉整个 npm 区意味着**几十 GB 白重拉**,
|
||
/// 而真正要扔的只有那几个文件。这个函数就是补这一档粒度。
|
||
///
|
||
/// ## `pattern` 的语义(故意做成「不用记语法」)
|
||
///
|
||
/// - 含 `*` / `?` → 按 **glob** 匹配(`*` 任意多字符、`?` 单字符)
|
||
/// - 否则 → 按**子串**匹配(`lodash` 命中 `npm:/npm/lodashGET*/*`)
|
||
///
|
||
/// 两种都**大小写敏感**:cache key 直接来自 URL,折叠大小写会扩大命中面,
|
||
/// 对「删除」这种动作宁可少删让人补一次,也不要多删。
|
||
///
|
||
/// ## `apply=false` 是**默认必须显式绕过**的预览
|
||
///
|
||
/// 调用方不传 `apply` 就只返回「会删哪些」而不动盘。破坏性动作先给一次
|
||
/// 无副作用的预览,是这个接口与 `purge` 最重要的区别(`purge` 的语义足够
|
||
/// 单一,预览价值不大;而通配匹配很容易写宽)。
|
||
///
|
||
/// ## 与 [`purge`] 相同的两条硬约束
|
||
///
|
||
/// - **只删文件,绝不删目录**(理由见 [`purge`])
|
||
/// - 删的是磁盘副本,请求会 MISS 回源重建,**不影响正确性**
|
||
pub fn invalidate(selector: &str, pattern: &str, apply: bool) -> Result<Vec<InvalidateItem>, String> {
|
||
let sel = selector.trim();
|
||
let pat = pattern.trim();
|
||
if sel.is_empty() {
|
||
return Err("缺少 zone 参数(填生态名或 all)".to_owned());
|
||
}
|
||
if pat.is_empty() {
|
||
return Err("缺少 match 参数:要失效的制品关键字(如 lodash、library/alpine,支持 * 通配)"
|
||
.to_owned());
|
||
}
|
||
|
||
let targets: Vec<(String, PathBuf)> = {
|
||
let g = ZONES.lock().unwrap_or_else(|e| e.into_inner());
|
||
if g.is_empty() {
|
||
return Err("未发现任何 proxy_cache 区,无法失效(见 error_log 的 [cache] 告警)"
|
||
.to_owned());
|
||
}
|
||
if sel.eq_ignore_ascii_case("all") {
|
||
g.iter().map(|z| (z.name.clone(), z.dir.clone())).collect()
|
||
} else {
|
||
let hit: Vec<_> = g
|
||
.iter()
|
||
.filter(|z| z.name == sel || eco_of_zone(&z.name) == sel)
|
||
.map(|z| (z.name.clone(), z.dir.clone()))
|
||
.collect();
|
||
if hit.is_empty() {
|
||
let known: Vec<&str> = g.iter().map(|z| z.name.as_str()).collect();
|
||
return Err(format!("未知的缓存区 {sel}(已知:{known:?},或用 all)"));
|
||
}
|
||
hit
|
||
}
|
||
};
|
||
|
||
let mut out = Vec::with_capacity(targets.len());
|
||
for (zone, dir) in targets {
|
||
let exists = dir.is_dir();
|
||
let mut acc = InvAcc {
|
||
pat: pat.to_owned(),
|
||
apply,
|
||
..Default::default()
|
||
};
|
||
if exists {
|
||
// 单个区出错不中止整批,但要如实报(调用方看得到哪个区没处理干净)
|
||
let _ = scan_keys(&dir, 0, &mut acc);
|
||
}
|
||
out.push(InvalidateItem {
|
||
zone,
|
||
dir: dir.to_string_lossy().into_owned(),
|
||
matched: acc.matched,
|
||
deleted: acc.deleted,
|
||
bytes: acc.bytes,
|
||
keys: acc.keys,
|
||
truncated: acc.truncated,
|
||
dir_exists: exists,
|
||
});
|
||
}
|
||
|
||
let tm: u64 = out.iter().map(|i| i.matched).sum();
|
||
let td: u64 = out.iter().map(|i| i.deleted).sum();
|
||
let tb: u64 = out.iter().map(|i| i.bytes).sum();
|
||
util::log_notice(&format!(
|
||
"[cache] {} cache selector={sel} match=\"{pat}\":命中 {tm} 个 / {} 字节,删除 {td} 个(只删文件,目录保留)",
|
||
if apply { "失效" } else { "预览" },
|
||
tb
|
||
));
|
||
Ok(out)
|
||
}
|
||
|
||
#[derive(Default)]
|
||
struct InvAcc {
|
||
pat: String,
|
||
apply: bool,
|
||
scanned: u64,
|
||
matched: u64,
|
||
deleted: u64,
|
||
bytes: u64,
|
||
keys: Vec<String>,
|
||
truncated: bool,
|
||
}
|
||
|
||
/// 遍历缓存目录,读出每个文件的明文 KEY,匹配则(可选)删除。
|
||
fn scan_keys(root: &Path, depth: usize, acc: &mut InvAcc) -> std::io::Result<()> {
|
||
const MAX_DEPTH: usize = 6;
|
||
if depth > MAX_DEPTH || acc.truncated {
|
||
return Ok(());
|
||
}
|
||
for ent in fs::read_dir(root)? {
|
||
if acc.scanned >= MAX_INVALIDATE_SCAN {
|
||
acc.truncated = true;
|
||
return Ok(());
|
||
}
|
||
let ent = ent?;
|
||
let ft = ent.file_type()?;
|
||
if ft.is_dir() {
|
||
scan_keys(&ent.path(), depth + 1, acc)?;
|
||
continue;
|
||
}
|
||
if !ft.is_file() {
|
||
continue; // 符号链接等一律不动
|
||
}
|
||
acc.scanned += 1;
|
||
let path = ent.path();
|
||
let Some(key) = cache_key_of(&path) else {
|
||
continue; // 读不到 key(正在写入 / 非缓存文件)→ 跳过,绝不猜
|
||
};
|
||
if !key_matches(&key, &acc.pat) {
|
||
continue;
|
||
}
|
||
// 命中即计数;`bytes` 必须在删除前取
|
||
let len = ent.metadata().map(|m| m.len()).unwrap_or(0);
|
||
acc.matched += 1;
|
||
acc.bytes += len;
|
||
if acc.keys.len() < MAX_KEY_SAMPLES && !acc.keys.iter().any(|k| *k == key) {
|
||
acc.keys.push(key);
|
||
}
|
||
if acc.matched > MAX_DELETE {
|
||
// 超出单次删除上限:停在这里,让调用方看到 truncated 后收窄 pattern
|
||
acc.truncated = true;
|
||
return Ok(());
|
||
}
|
||
if acc.apply && fs::remove_file(&path).is_ok() {
|
||
acc.deleted += 1;
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// 从缓存文件里取出明文 cache key。
|
||
///
|
||
/// 见 [`KEY_MARK`]:搜标记而不是解析结构体,跨 nginx 版本稳定。
|
||
fn cache_key_of(path: &Path) -> Option<String> {
|
||
let f = fs::File::open(path).ok()?;
|
||
let mut buf = Vec::with_capacity(HEAD_READ);
|
||
// take(HEAD_READ) 而不是 read():`read` 对普通文件也不保证一次读满,
|
||
// 而 key 可能落在两次 read 的边界上。
|
||
f.take(HEAD_READ as u64).read_to_end(&mut buf).ok()?;
|
||
let i = find_bytes(&buf, KEY_MARK)?;
|
||
let start = i + KEY_MARK.len();
|
||
let end = buf[start..]
|
||
.iter()
|
||
.position(|&b| b == b'\n')
|
||
.map(|p| start + p)
|
||
.unwrap_or(buf.len());
|
||
if end <= start {
|
||
return None;
|
||
}
|
||
Some(String::from_utf8_lossy(&buf[start..end]).into_owned())
|
||
}
|
||
|
||
/// 子串查找(只在这里用,不值得为此引依赖)
|
||
fn find_bytes(hay: &[u8], needle: &[u8]) -> Option<usize> {
|
||
if needle.is_empty() || hay.len() < needle.len() {
|
||
return None;
|
||
}
|
||
(0..=hay.len() - needle.len()).find(|&i| &hay[i..i + needle.len()] == needle)
|
||
}
|
||
|
||
/// key 是否命中 `pattern`。语义见 [`invalidate`] 的文档。
|
||
pub fn key_matches(key: &str, pattern: &str) -> bool {
|
||
if pattern.contains('*') || pattern.contains('?') {
|
||
glob_match(pattern, key)
|
||
} else {
|
||
key.contains(pattern)
|
||
}
|
||
}
|
||
|
||
/// 极简 glob:只支持 `*`(任意多字符)与 `?`(单字符),迭代+回溯,无递归爆栈风险。
|
||
fn glob_match(pattern: &str, s: &str) -> bool {
|
||
let p: Vec<char> = pattern.chars().collect();
|
||
let t: Vec<char> = s.chars().collect();
|
||
let (mut pi, mut ti) = (0usize, 0usize);
|
||
let mut star: Option<usize> = None; // 最近一个 `*` 在 pattern 里的位置
|
||
let mut mark = 0usize; // 该 `*` 当前吞到 s 的哪个位置
|
||
while ti < t.len() {
|
||
if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
|
||
pi += 1;
|
||
ti += 1;
|
||
} else if pi < p.len() && p[pi] == '*' {
|
||
star = Some(pi);
|
||
mark = ti;
|
||
pi += 1;
|
||
} else if let Some(sp) = star {
|
||
pi = sp + 1; // 回退到 `*` 后面,让它多吞一个字符
|
||
mark += 1;
|
||
ti = mark;
|
||
} else {
|
||
return false;
|
||
}
|
||
}
|
||
while pi < p.len() && p[pi] == '*' {
|
||
pi += 1;
|
||
}
|
||
pi == p.len()
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn substring_when_no_wildcard() {
|
||
assert!(key_matches("npm:/npm/lodashGET*/*", "lodash"));
|
||
assert!(key_matches("docker:/v2/library/alpine/manifests/latestGET*/*", "library/alpine"));
|
||
assert!(!key_matches("npm:/npm/lodashGET*/*", "underscore"));
|
||
}
|
||
|
||
#[test]
|
||
fn case_sensitive_on_purpose() {
|
||
assert!(!key_matches("npm:/npm/lodashGET*/*", "Lodash"));
|
||
}
|
||
|
||
#[test]
|
||
fn glob_star_and_question() {
|
||
assert!(key_matches("npm:/npm/lodashGET*/*", "npm:/npm/*"));
|
||
assert!(key_matches("npm:/npm/lodashGET*/*", "*lodash*"));
|
||
assert!(key_matches("go:/go/golang.org/x/text/@v/listGET*/*", "go:/go/*/@v/list*"));
|
||
assert!(!key_matches("go:/go/golang.org/x/text/@v/listGET*/*", "go:/go/*/@v/foo*"));
|
||
assert!(key_matches("ab", "a?"));
|
||
assert!(!key_matches("abc", "a?"));
|
||
assert!(key_matches("anything", "*"));
|
||
}
|
||
|
||
#[test]
|
||
fn glob_trailing_star_matches_empty() {
|
||
assert!(key_matches("npm:/npm/x", "npm:/npm/x*"));
|
||
assert!(key_matches("", "*"));
|
||
}
|
||
}
|
||
|