refactor: 改造为独立插件仓 ipass-plugin-cache(对齐兄弟仓形态)

- 扁平化: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]>
This commit is contained in:
adminandClaude Opus 4.8 committed 2026-09-24 21:15:57 +08:00
1 parent f7c70a0e19
commit 2c8fb2a1ee
128 files changed
+110 -9496

No files matched your search

+466
View File
@@ -0,0 +1,466 @@
//! 缓存插件的管理 API 与账号态 API。
//!
//! 鉴权语义与内核共用一套:`ipass_core::api::{Guard, Actor, run_guarded}`。
//! 管理员态走登录会话(管理台),账号态走统一 `sk_` Key(用户 / AI Agent)。
//!
//! | 端点 | Guard | 用途 |
//! | --- | --- | --- |
//! | `GET /api/admin/cache` | Admin | 管理台一次性拉全:上游表 + 命中计数 + 网关入口 |
//! | `POST /api/admin/cache/save` | Admin | 新增/修改某路由的上游(地址、凭据、启用) |
//! | `POST /api/admin/cache/delete` | Admin | 删除某路由的上游配置 |
//! | `POST /api/admin/cache/test` | Admin | 连通性测试(内部重定向到 `/_cache_test/<route>`,**以 GET 转发**) |
//! | `POST /api/admin/cache/purge` | Admin | 整区清理(`zone=<生态>|all`),只删文件不删目录 |
//! | `POST /api/admin/cache/invalidate` | Admin | 按制品失效(`match` 子串/glob;不传 `apply` 只预览) |
//! | `GET /api/v1/cache` | User | 账号态:可用生态 + **一键复制的接入命令** |
//! | `GET /api/v1/cache/stats` | User | 只读命中计数(给 AI Agent / 监控轮询) |
//!
//! 为什么管理员态要有一个「一次性拉全」端点:管理台渲染一张表要用到
//! 「上游 + 是否生效 + 下游地址 + 命中数」四类信息,拆成四个请求会让页面
//! 多次闪烁(且任一失败整页不可用)。合成一个原子快照更稳。
use ngx::core::{Pool, Status};
use ngx::ffi::ngx_http_request_t;
use ngx::http::HTTPStatus;
use serde_json::{Value, json};
use ipass_core::api::{Actor, Guard, run_guarded};
use ipass_core::{http, util};
use crate::cache;
use crate::config;
use crate::stats;
use crate::upstreams;
use crate::zones;
// ===========================================================================
// 路由
// ===========================================================================
type Handler = fn(*mut ngx_http_request_t, Actor) -> Status;
/// 路由表。精确匹配而非正则——路径固定,正则只会引入「锚点写错导致前缀误匹配」。
fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> {
let entry: (Guard, Handler) = match (method, uri) {
("GET", "/api/admin/cache") => (Guard::Admin, h_admin_overview),
("POST", "/api/admin/cache/save") => (Guard::Admin, h_admin_save),
("POST", "/api/admin/cache/delete") => (Guard::Admin, h_admin_delete),
("POST", "/api/admin/cache/test") => (Guard::Admin, h_admin_test),
("POST", "/api/admin/cache/purge") => (Guard::Admin, h_admin_purge),
("POST", "/api/admin/cache/invalidate") => (Guard::Admin, h_admin_invalidate),
("GET", "/api/v1/cache") => (Guard::User, h_my_cache),
("GET", "/api/v1/cache/stats") => (Guard::User, h_my_stats),
_ => return None,
};
Some(entry)
}
/// 本表分发:认领则返回响应状态,不认领返回 `None`(交给下一个插件)。
pub fn dispatch(r: *mut ngx_http_request_t) -> Option<Status> {
let method = http::method_str(r);
let uri = http::uri(r);
let Some((guard, handler)) = route(&method, &uri) else {
return None;
};
Some(run_guarded(r, guard, handler))
}
// ===========================================================================
// 管理员
// ===========================================================================
/// 管理台快照:上游表 + 命中计数 + 容量水位 + 网关入口 + 变量契约。
///
/// `?scan=1`:额外盘点每个缓存区的磁盘占用(默认关,见 [`capacity_view`])。
fn h_admin_overview(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let params = http::params(r);
let scan = util::to_bool(params.get("scan"));
let entry = upstreams::entry_base(r);
let items = upstreams::view_all(&entry);
let configured = items
.iter()
.filter(|v| {
v.get("configured")
.and_then(Value::as_bool)
.unwrap_or(false)
})
.count();
let active = items
.iter()
.filter(|v| v.get("active").and_then(Value::as_bool).unwrap_or(false))
.count();
http::ok(
r,
json!({
"entry": entry,
"items": items,
"count": items.len(),
"configured": configured,
"active": active,
"stats": stats::overview(util::now()),
"capacity": capacity_view(scan),
"variables": cache::VARIABLE_DOCS
.iter()
.map(|(n, d)| json!({ "name": n, "desc": d }))
.collect::<Vec<Value>>(),
"probe_prefix": cache::PROBE_PREFIX,
}),
"ok",
)
}
/// 新增/修改一个路由的上游。
///
/// 表单字段:`route`(必填) / `base` / `key` / `name` / `desc` / `note` / `enabled`。
/// `base` 留空 = 保留原值;`key` 留空 = **清空**(语义差异见 `upstreams::upsert`)。
fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
let route_raw = p.get("route").cloned().unwrap_or_default();
let enabled = match p.get("enabled") {
Some(v) => util::to_bool(Some(v)),
None => true,
};
// ⚠️ key 用「字段是否出现」区分「不改」与「清空」,所以这里不能把
// `p.get("key")` 归一成空串——前端删掉输入框内容时应提交 `key=`(空串)。
let res = upstreams::upsert(
&route_raw,
p.get("base"),
p.get("key"),
p.get("name"),
p.get("desc"),
enabled,
p.get("note"),
);
match res {
Ok(item) => {
let route = util::trim(&route_raw).to_ascii_lowercase();
let active = upstreams::lookup(&route).is_some();
util::log_notice(&format!(
"[cache] 保存上游 route={route} base={} enabled={} active={active}",
item.base, item.enabled
));
http::ok(
r,
json!({
"route": route,
"base": item.base,
"key_set": !item.key.is_empty(),
"enabled": item.enabled,
"active": active,
"entry": upstreams::entry_base(r),
}),
"已保存",
)
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
/// 删除一个路由的上游配置。
fn h_admin_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
let route = p.get("route").cloned().unwrap_or_default();
match upstreams::remove(&route) {
Ok(route) => {
util::log_notice(&format!("[cache] 删除上游 route={route}"));
http::ok(r, json!({ "route": route }), "已删除")
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
/// 连通性测试:内部重定向到 `/_cache_test/<route>`。
///
/// 该 internal location 复用 `$cache_target` / `$cache_host` /
/// `$cache_upstream_key` 三个变量——**与真实转发走同一套拼接与换 Key 逻辑**,
/// 所以「测试通过」等价于「真实请求能到上游并带上凭据」。
/// 上游返回什么状态码/响应体,就原样透传给管理台(便于区分 401 与 404)。
///
/// ⚠️ 转发方法**强制改成 GET**。管理台是用 `POST /api/admin/cache/test` 触发的,
/// 而 `ngx_http_internal_redirect` **保留原方法**,于是探针会以 POST 打到上游:
/// 1. POST 是写语义 —— 探测不该有在上游产生副作用的能力;
/// 2. 制品拉取全是 GET/HEAD(docker 有 HEAD),用 POST 探到的结果不代表真实流量;
/// 3. 实测后果很误导:假上游只实现 `do_GET`,探针拿到 501,
/// 管理台显示「测试失败」,而它其实**连通正常**。
/// 同时 conf 里 `/_cache_test/` 必须配 `proxy_pass_request_body off;`(不转那 2 字节
/// `{}`,也不生成 Content-Length,否则 keepalive 上会留下半截请求体)。
fn h_admin_test(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let route_raw = http::params(r).get("route").cloned().unwrap_or_default();
let route = match upstreams::validate_route(&route_raw) {
Ok(r) => r,
Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e),
};
if upstreams::lookup(&route).is_none() {
return http::fail(
r,
HTTPStatus::NOT_FOUND,
&format!("路由 {route} 尚未配置上游或已停用"),
);
}
let uri = format!("{}{route}", cache::PROBE_PREFIX);
util::log_notice(&format!("[cache] 测试上游 route={route}"));
// 与 apix / llm 上游测试同一个坑:internal_redirect 只浅拷贝 ngx_str_t,
// 必须把字节拷进请求池,否则函数返回后 r->uri 全是 NUL(实测踩过)。
// SAFETY: r 有效;请求池内存在整个请求生命周期内有效。
unsafe {
let pool = Pool::from_ngx_pool((*r).pool);
let bytes = uri.as_bytes();
let data = pool.alloc(bytes.len()) as *mut u8;
if data.is_null() {
return http::fail(r, HTTPStatus::INTERNAL_SERVER_ERROR, "内存分配失败");
}
core::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
// 见函数注释:把方法钉成 GET。method_name 指向 .rodata 里的静态字节,
// 生命周期覆盖整个请求,不会悬垂。
(*r).method = nginx_sys::NGX_HTTP_GET as _;
(*r).method_name = nginx_sys::ngx_str_t {
len: PROBE_METHOD.len(),
data: PROBE_METHOD.as_ptr() as *mut u8,
};
let mut u = nginx_sys::ngx_str_t {
len: bytes.len(),
data,
};
let mut args = nginx_sys::ngx_str_t {
len: 0,
data: core::ptr::null_mut(),
};
nginx_sys::ngx_http_internal_redirect(r, &mut u, &mut args);
}
Status::NGX_DONE
}
/// 探针转发用的方法名(静态字节,供 `method_name` 指用)。
static PROBE_METHOD: &[u8] = b"GET";
/// 容量水位快照(盘 + 索引两条轴)。
///
/// 数字全部来自 nginx 自己的共享内存记账(见 [`zones`]),**不是扫盘统计**:
/// 口径与淘汰动作同源,所以「面板显示 91%」与「nginx 正在淘汰」说的是同一件事。
/// 前端只负责画条与上色,阈值判定(ok/warn/crit)在后端算好下发——
/// 判定散到前端就会出现「同一天同一块盘,两个页面两种颜色」。
///
/// `scan` = 是否**同时**盘点磁盘(`?scan=1`)。两个数并排才有意义:
/// nginx 的记账在「手工删过缓存文件」之后是滞后的(节点要等再被访问或到期
/// 才回收),只有拿磁盘实测一比,才知道差额是真实占用还是虚账。
fn capacity_view(scan: bool) -> Value {
let list = zones::snapshot(scan);
let mut items: Vec<Value> = Vec::with_capacity(list.len());
let (mut t_limit, mut t_used, mut t_entries) = (0i64, 0i64, 0u64);
let (mut t_disk, mut scanned) = (0u64, false);
let (mut warn, mut crit) = (0u32, 0u32);
for z in &list {
t_limit += z.limit_bytes;
t_used += z.used_bytes;
t_entries += z.entries;
if let Some(d) = &z.disk {
t_disk += d.bytes;
scanned = true;
}
match z.level {
"warn" => warn += 1,
"crit" => crit += 1,
_ => {}
}
items.push(json!({
"zone": z.name,
"eco": z.eco,
"routes": z.routes,
"dir": z.dir,
"dir_exists": z.dir_exists,
"limit_bytes": z.limit_bytes,
"used_bytes": z.used_bytes,
"pct": pct1(z.used_bytes, z.limit_bytes),
"entries": z.entries,
"keys_zone_bytes": z.keys_zone_bytes,
"entries_cap_est": z.entries_cap_est,
"index_pressure": z.index_pressure,
"bsize": z.bsize,
"inactive_secs": z.inactive_secs,
"cold": z.cold,
"loading": z.loading,
"level": z.level,
// 磁盘实测(未 scan 时为 null,前端据此决定要不要显示这一栏)
"disk_bytes": z.disk.as_ref().map(|d| d.bytes),
"disk_files": z.disk.as_ref().map(|d| d.files),
"disk_truncated": z.disk.as_ref().map(|d| d.truncated),
}));
}
json!({
"available": !list.is_empty(),
"reason": if list.is_empty() {
"模块未能在启动时识别到任何 proxy_cache 区(详见 error_log 的 [cache] 告警)"
} else {
""
},
"scanned": scanned,
"zones": items,
"totals": {
"zones": list.len(),
"limit_bytes": t_limit,
"used_bytes": t_used,
"pct": pct1(t_used, t_limit),
"entries": t_entries,
"disk_bytes": if scanned { Some(t_disk) } else { None },
"warn": warn,
"crit": crit,
},
})
}
/// 百分比保留一位小数(0/0 视为 0,不给 NaN)
fn pct1(used: i64, limit: i64) -> f64 {
if limit <= 0 {
return 0.0;
}
let v = (used as f64 / limit as f64) * 1000.0;
(v.round()) / 10.0
}
/// 清理缓存区:`zone=<生态名>` 或 `zone=all`。
///
/// 为什么手动清理还要做成接口:nginx 的自动淘汰是**按容量/闲置**的,
/// 而运维常有「现在就要腾出 20G」或「某次上游发错版本、先把错的制品清掉」
/// 这类**按需**诉求。手工 `rm` 的版本已经在脚本里踩过坑(删掉 cache/<eco>
/// 目录 → 整条路由 [crit] 直到 reload),所以这一步必须由模块来做,
/// 顺便把「删了多少」记进日志当审计。
///
/// 清理**不影响正确性**:删掉的只是磁盘副本,请求会 MISS 回源重建。
fn h_admin_purge(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let sel = http::params(r).get("zone").cloned().unwrap_or_default();
match zones::purge(&sel) {
Ok(items) => {
let files: u64 = items.iter().map(|i| i.files).sum();
let bytes: u64 = items.iter().map(|i| i.bytes).sum();
let body: Vec<Value> = items
.iter()
.map(|i| {
json!({
"zone": i.zone,
"dir": i.dir,
"files": i.files,
"bytes": i.bytes,
"dir_exists": i.dir_exists,
})
})
.collect();
http::ok(
r,
json!({
"selector": sel,
"items": body,
"total": { "files": files, "bytes": bytes },
}),
&format!("已清理 {files} 个缓存文件"),
)
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
/// 按制品失效:`zone=<生态名>|all`(默认 all)+ `match=<子串|glob>` + `apply=1`。
///
/// ## 为什么默认是**预览**
///
/// `purge` 的语义足够单一(整区清空),而这里支持通配:写一个 `*` 就等于清空,
/// 写宽了就是事故。所以**不传 `apply` 一律只算不删**,把「表达式正确吗」
/// 与「真的动手」拆成两次调用,前端据此做成「预览 → 看命中的 key → 确认」两步。
///
/// 注意与 `purge` 一样只删**文件**:目录一棵都不动(见 [`zones::purge`] 的说明)。
fn h_admin_invalidate(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let params = http::params(r);
let zone = params.get("zone").cloned().unwrap_or_else(|| "all".to_owned());
let pat = params.get("match").cloned().unwrap_or_default();
let apply = util::to_bool(params.get("apply"));
match zones::invalidate(&zone, &pat, apply) {
Ok(items) => {
let matched: u64 = items.iter().map(|i| i.matched).sum();
let deleted: u64 = items.iter().map(|i| i.deleted).sum();
let bytes: u64 = items.iter().map(|i| i.bytes).sum();
let truncated = items.iter().any(|i| i.truncated);
let body: Vec<Value> = items
.iter()
.map(|i| {
json!({
"zone": i.zone,
"dir": i.dir,
"matched": i.matched,
"deleted": i.deleted,
"bytes": i.bytes,
"keys": i.keys,
"truncated": i.truncated,
"dir_exists": i.dir_exists,
})
})
.collect();
let msg = if apply {
format!("已失效 {deleted} 个条目(释放 {bytes} 字节)")
} else {
format!("预览:命中 {matched} 个条目({bytes} 字节),未删除")
};
http::ok(
r,
json!({
"selector": zone,
"match": pat,
"applied": apply,
"items": body,
"total": { "matched": matched, "deleted": deleted, "bytes": bytes },
"truncated": truncated,
}),
&msg,
)
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
// ===========================================================================
// 账号态
// ===========================================================================
/// 账号态:可用生态 + 一键复制的接入命令 + 只读计数。
///
/// 刻意**不回显上游地址与凭据**:账号态是给用户 / AI Agent 用的,
/// 他只需要知道「往哪个地址发请求」,不需要知道网关背后挂的是哪家 registry。
fn h_my_cache(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let entry = upstreams::entry_base(r);
let mut items: Vec<Value> = Vec::new();
for route in config::ROUTES {
if upstreams::lookup(route).is_none() {
continue; // 未配置 / 已停用的生态不对外暴露
}
let eco = config::eco_of_route(route);
items.push(json!({
"eco": eco,
"route": route,
"uri": config::route_uri(route),
"url": format!("{entry}{}", config::route_uri(route)),
"client": upstreams::client_hint(eco, &entry),
}));
}
http::ok(
r,
json!({
"entry": entry,
"items": items,
"count": items.len(),
"stats": stats::overview(util::now()),
}),
"ok",
)
}
/// 只读命中计数(监控 / AI Agent 轮询用;口径是全站共享缓存)
fn h_my_stats(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
http::ok(r, stats::overview(util::now()), "cache stats")
}
+297
View File
@@ -0,0 +1,297 @@
//! 缓存插件的 nginx 变量层:把「上游表 + 请求 URI」算成 `proxy_pass` 能用的值。
//!
//! 注册六个**只读**变量(求值时算,模块从不主动写):
//!
//! | 变量 | 值 | 谁用 |
//! | --- | --- | --- |
//! | `$cache_target` | `base + 上游路径前缀 + 尾部 [+ ?query]` | `proxy_pass $cache_target` |
//! | `$cache_host` | 上游 Host(含端口) | `proxy_set_header Host $cache_host` |
//! | `$cache_upstream_key` | 管理台配的上游凭据**原值**(未配置为空) | 排障/日志 |
//! | `$cache_auth` | **实际下发**的 Authorization 值(含防 `sk_` 泄漏规则) | `proxy_set_header Authorization $cache_auth` |
//! | `$cache_eco` | 生态名(`go` / `cargo` / …) | 日志与排障 |
//! | `$cache_key` | `<route>:<uri>` | `proxy_cache_key`(显式给定,不依赖 `$proxy_host`) |
//!
//! ⚠️ `$proxy_host` 在**变量式 `proxy_pass`** 下不可靠,所以 `proxy_cache_key`
//! 必须显式指定;用本变量即可(同 zone 内 URI 唯一,跨 zone 天然隔离)。
//!
//! 这就是「UI 配上游 + 动态注入」的落点:上游地址与凭据都来自共享内存
//! (`cx:<route>`),改配置立即生效,无需改 nginx conf、无需 reload。
use ngx::core::{Pool, Status};
use ngx::ffi::{
NGX_HTTP_VAR_CHANGEABLE, NGX_HTTP_VAR_NOCACHEABLE, ngx_conf_t, ngx_http_add_variable,
ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t, ngx_str_t, ngx_uint_t,
};
use ngx::ngx_string;
use ipass_core::http;
use crate::config;
use crate::upstreams;
// ===========================================================================
// 变量分派标记
// ===========================================================================
/// `$cache_target`:完整上游 URL
pub const VAR_TARGET: usize = 1;
/// `$cache_host`:上游 Host 头
pub const VAR_HOST: usize = 2;
/// `$cache_upstream_key`:上游凭据(空 = 不下发鉴权头)
pub const VAR_UPSTREAM_KEY: usize = 3;
/// `$cache_eco`:生态名
pub const VAR_ECO: usize = 4;
/// `$cache_key`:缓存键(`<route>:<uri>`)
pub const VAR_KEY: usize = 5;
/// `$cache_auth`:**实际下发给上游**的 `Authorization` 头值(含防泄漏规则)
pub const VAR_AUTH: usize = 6;
/// 注册本插件的全部变量。返回 false = 失败,gateway 会 EMERG 退出。
///
/// # Safety
/// `cf` 必须由 nginx 传入且有效。
pub unsafe fn preconfig(cf: *mut ngx_conf_t) -> bool {
let mut target = ngx_string!("cache_target");
let mut host = ngx_string!("cache_host");
let mut ukey = ngx_string!("cache_upstream_key");
let mut eco = ngx_string!("cache_eco");
let mut ckey = ngx_string!("cache_key");
let mut auth = ngx_string!("cache_auth");
unsafe {
add_var(cf, &raw mut target, VAR_TARGET)
&& add_var(cf, &raw mut host, VAR_HOST)
&& add_var(cf, &raw mut ukey, VAR_UPSTREAM_KEY)
&& add_var(cf, &raw mut eco, VAR_ECO)
&& add_var(cf, &raw mut ckey, VAR_KEY)
&& add_var(cf, &raw mut auth, VAR_AUTH)
}
}
/// 注册一个只读变量,值由 [`var_get`] 按 `slot` 分派计算。
///
/// `NOCACHEABLE`:本变量是「读时现算」,若被 nginx 缓存进 `r->variables`,
/// 同一请求多次求值(`proxy_pass` 一次、`proxy_set_header` 再读)会拿到
/// 首次结果——对上游配置**中途变更**的场景会读到旧值,故标记不可缓存。
unsafe fn add_var(cf: *mut ngx_conf_t, name: *mut ngx_str_t, slot: usize) -> bool {
// SAFETY: cf 由 nginx 传入;name 指向调用方栈上的 ngx_str_t,注册时被拷贝
let var = unsafe {
ngx_http_add_variable(
cf,
name,
(NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t,
)
};
if var.is_null() {
return false;
}
// SAFETY: var 非空且由本函数独占初始化;data 承载分派标记
unsafe {
(*var).get_handler = Some(var_get);
(*var).set_handler = None;
(*var).data = slot;
}
true
}
// ===========================================================================
// 求值
// ===========================================================================
/// 管理台「测试」用的探针前缀。conf 里对应一个 `internal` location:
///
/// ```nginx
/// location /_cache_test/ {
/// internal; # 挡住外部直连(否则可绕过鉴权触达上游)
/// proxy_pass $cache_target; # 复用同一个变量,只是 tail 变成 "/"
/// proxy_set_header Host $cache_host;
/// proxy_set_header Authorization $cache_upstream_key;
/// }
/// ```
///
/// 与 apix 的 `/_apix_probe/`、llm 的 `/_upstream_test/` 同一手法:
/// **对外出口与内部探针共用同一套「定上游 + 换凭据」逻辑**,探针才能真正
/// 代表真实转发的行为(自己另写一套探针代码必然漂移)。
pub const PROBE_PREFIX: &str = "/_cache_test/";
/// 解析请求 URI → `(route, tail)`。
///
/// * 正常路径:`/go/pkg-a` → `("go", "/pkg-a")`;`/v2/library/x` → `("docker", "/library/x")`
/// * 探针路径:`/_cache_test/go` → `("go", "/")` —— 固定打上游根,只验连通与凭据
///
/// `tail` 恒以 `/` 开头(上游拼 URL 用),空尾也归一成 `/`。
pub fn resolve_route(uri: &str) -> Option<(&'static str, String)> {
if let Some(rest) = uri.strip_prefix(PROBE_PREFIX) {
let seg = rest.trim_start_matches('/').split('/').next().unwrap_or("");
let route = config::route_of_seg(seg)?;
return Some((route, "/".to_owned()));
}
let route = config::route_of_uri(uri)?;
let seg = uri.trim_start_matches('/').split('/').next().unwrap_or("");
let tail = uri.get(1 + seg.len()..).unwrap_or("");
let tail = if tail.is_empty() { "/" } else { tail };
Some((route, tail.to_owned()))
}
/// 取 base 的 host 部分(含端口)。`https://a.b:8443/x` → `a.b:8443`
pub fn host_of(base: &str) -> &str {
let rest = base.split_once("://").map(|(_, r)| r).unwrap_or(base);
rest.split('/').next().unwrap_or(rest)
}
/// 由 `(route, tail, base)` 拼出上游完整 URL。
///
/// 再补回 [`config::upstream_path_prefix`](只有 Docker 非空)。
///
/// 变量形式的 `proxy_pass` **不会自动追加 query**(nginx 已知行为),
/// 所以这里必须自己把 `args` 拼上去——否则 `?archive=tar.gz` 这类参数会被吞掉。
pub fn build_target(route: &str, tail: &str, base: &str, args: &str) -> String {
let mut t = format!("{base}{}{tail}", config::upstream_path_prefix(route));
if !args.is_empty() {
t.push('?');
t.push_str(args);
}
t
}
/// 决定下发给上游的 `Authorization` 头值。
///
/// `configured` 是本路由在管理台配的上游凭据(原值,管理员自己写全
/// `Bearer xxx` / `Basic yyy`)。
///
/// 三种情形,按镜像型缓存的真实需求排:
///
/// 1. **管理台配了凭据** → 用配置值(管理员自己写全 `Bearer xxx` / `Basic yyy`,
/// 这样正好覆盖私有 registry 的各种鉴权方案,模块不去猜 scheme)。
/// 2. **没配凭据** → 透传客户端带来的 `Authorization`。Docker Hub 走的就是这条:
/// 客户端先向 `auth.docker.io` 换一个短期 Bearer token,再拿它来拉镜像;
/// 如果这里把 Authorization 抹成空,`/v2/` 下的镜像一律 401。
/// 3. **但客户端的值若就是本网关的下行 `sk_` Key,一律丢弃**。
///
/// 第 3 条是安全底线:`sk_` 是客户端访问**本网关**的身份(`auth::downstream_key`
/// 认 `Authorization: Bearer` / `x-api-key` 等携带位)。原样透传给上游,
/// 等于把网关自己的钥匙递给上游——对方可拿它反调本网关的其它路由刷额度。
/// ipass 的 LLM 路径在 `docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md` 记过同一个坑
/// (宽松厂商会把这个缺陷掩盖成 200,换严格厂商才暴露成 401)。
///
/// 判据是**逐字节比较**:只有客户端放在 Authorization 里的值等于本次鉴权用的
/// 那把 `sk_` 才丢弃;换任何别的值(真上游 token)都照传。
///
/// ⚠️ 第 1 条必须**先判**且不能被跳过:`auth_header` 只认客户端的头是不够的
/// ——那样「配了凭据的路由」永远下发不了凭据,而且客户端带的是 `sk_` 时会被
/// 第 3 条抹成空(实测症状:管理台配了 token,上游仍收到空 Authorization,
/// 而测试里「未配凭据 → 不下发」那条却通过,很容易误判成上游问题)。
fn auth_header(r: *mut ngx_http_request_t, configured: &str) -> String {
// 1) 管理台配了凭据 → 用配置值(配置是管理员的显式意图,优先级最高)
let configured = configured.trim();
if !configured.is_empty() {
return configured.to_owned();
}
let raw = match http::header(r, "authorization") {
Some(v) => v.trim().to_owned(),
None => return String::new(),
};
let Some(dk) = ipass_core::auth::downstream_key(r) else {
// 客户端没带网关 Key → 原样透传(如纯 x-api-key 场景)
return raw;
};
let bare = raw
.strip_prefix("Bearer ")
.or_else(|| raw.strip_prefix("bearer "))
.unwrap_or(&raw)
.trim();
if bare == dk { String::new() } else { raw }
}
/// 六个变量共用一个 get_handler,靠 `var.data`(即 `slot`)分派。
pub extern "C" fn var_get(
r: *mut ngx_http_request_t,
v: *mut ngx_http_variable_value_t,
data: usize,
) -> ngx_int_t {
// SAFETY: r/v 由 nginx 传入且有效;本函数只读请求结构、只写 v
unsafe {
let resolved = (|| -> Option<String> {
let uri = http::uri(r);
let (route, tail) = resolve_route(&uri)?;
let (base, key, _mode) = upstreams::lookup(route)?;
Some(match data {
VAR_TARGET => {
let args = http::args_raw(r);
let args = core::str::from_utf8(&args).unwrap_or("");
build_target(route, &tail, &base, args)
}
VAR_HOST => host_of(&base).to_owned(),
VAR_UPSTREAM_KEY => key,
VAR_AUTH => auth_header(r, &key),
VAR_ECO => config::eco_of_route(route).to_owned(),
// 缓存键必须含 query(完整资源身份):npm 的 `?write=true`、
// docker 的 `?ns=`、go 的 `?go-get=1`、cargo 的 `?archive=tar.gz`
// 都靠 query 区分实体。而**变量式 proxy_pass 不把 query 写进
// `$uri`**,只看 `$uri` 会让「带 query 的请求」命中「不带 query
// 的缓存」,把错的制品发出去(实测:`/go/@v/list?x=1` 命中了
// `/go/@v/list` 的缓存体,且完全没有回源)。
VAR_KEY => {
let args = http::args_raw(r);
match core::str::from_utf8(&args) {
Ok(a) if !a.is_empty() => format!("{route}:{uri}?{a}"),
_ => format!("{route}:{uri}"),
}
}
_ => return None,
})
})();
match resolved {
Some(value) => set_value(r, v, &value),
None => {
// 未配置上游 / 非受管制路由:把变量置为「未找到」。
// nginx 的变量式 proxy_pass 拿到空值会报 500(no host in upstream),
// 所以 access handler 必须先一步用 503 拦掉,别让请求走到这里。
(*v).set_not_found(1);
(*v).set_valid(0);
Status::NGX_ERROR.into()
}
}
}
}
/// 把字符串写进 nginx 变量值(数据从请求内存池分配,生命周期由请求保证)。
///
/// # Safety
/// `r` / `v` 必须由 nginx 传入且在本调用期间有效。
unsafe fn set_value(
r: *mut ngx_http_request_t,
v: *mut ngx_http_variable_value_t,
value: &str,
) -> ngx_int_t {
let pool = Pool::from_ngx_pool((*r).pool);
let bytes = value.as_bytes();
let data = pool.alloc(bytes.len()) as *mut u8;
if data.is_null() {
(*v).set_not_found(1);
return Status::NGX_ERROR.into();
}
core::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
(*v).data = data;
(*v).set_len(bytes.len() as _);
(*v).set_valid(1);
(*v).set_no_cacheable(1);
(*v).set_not_found(0);
Status::NGX_OK.into()
}
/// 头字段用的变量名清单——管理台与文档引用它,避免两处写不一致。
pub const VARIABLE_DOCS: &[(&str, &str)] = &[
("$cache_target", "上游完整 URL(proxy_pass)"),
("$cache_host", "上游 Host 头"),
("$cache_upstream_key", "管理台配的上游凭据原值(未配置为空)"),
(
"$cache_auth",
"实际下发的 Authorization:配了凭据就用它,没配就透传客户端值,但会剔除下游 sk_ 自身",
),
("$cache_eco", "生态名"),
(
"$cache_key",
"缓存键(proxy_cache_key)= <route>:<uri>[?args],含 query、不含任何下游凭据(全站共享)",
),
];
+213
View File
@@ -0,0 +1,213 @@
//! 缓存插件的策略常量、路由表、共享内存键前缀与「下游接入说明」模板。
//!
//! 与其他插件的关系:**同一把下行 `sk_` Key**(内核 `ipass_core::auth`),
//! 同一套限流配额;差别在数据面——nginx 原生 `proxy_cache` 落磁盘,
//! 本插件只负责「鉴权 + 定上游 + 注入上游凭据 + 命中计量 + 管理 API」。
//!
//! ## 为什么「上游」挂在 route 上而不是 eco 上
//!
//! 一个生态的上游**不止一个域名**:crates.io 的稀疏索引在 `index.crates.io`,
//! 而 `.crate` 包本体在 `static.crates.io`;PyPI 的索引在 `pypi.org`,
//! 包文件在 `files.pythonhosted.org`;Docker 的 `/v2/` 前缀既是路由也是协议路径。
//! 所以:
//!
//! * **route**(8 条)= nginx 里一个 `location`,各有自己的上游与凭据;
//! * **eco**(6 个)= 对外展示与计量的口径,`cargo-dl` 与 `pypi-files` 分别
//! 归到 `cargo` / `pypi`(同一门语言的流量记在一起才看得懂)。
/// shm 键前缀:`cx:<route>` → `base \n 上游Key \n mode`。
///
/// 三行塞一个键是刻意的(与 apix 的 `ax:` 同一手法):热路径查一次表就拿到
/// 转发所需的全部信息。条目数 = route 数(个位数),改一条重同步一条即可。
pub const KEY_CX_PREFIX: &[u8] = b"cx:";
/// 命中计量的键前缀(`cache:<eco>:<STATUS>`),值走内核 `usage` 原语。
/// 与 `cx:` 分属两片键空间:前者是**配置**,后者是**读数**。
pub const KEY_CACHE_PREFIX: &str = "cache:";
/// shm payload 内部的行分隔符(base / 上游 Key / mode)。
pub const PAYLOAD_SEP: char = '\n';
// ---------------------------------------------------------------------------
// 路由表(route)与生态(eco)
// ---------------------------------------------------------------------------
/// 可配置上游的路由,顺序即管理台展示顺序。
pub const ROUTES: &[&str] = &[
"go",
"cargo",
"cargo-dl",
"pypi",
"pypi-files",
"npm",
"maven",
"docker",
];
/// 计量的生态口径(顺序即展示顺序)。`global` 是跨生态汇总,不对应上游。
pub const ECOS: &[&str] = &["go", "cargo", "pypi", "npm", "maven", "docker", "global"];
/// 缓存命中状态(取值与 nginx `$upstream_cache_status` 一一对应)。
pub const STATUSES: &[&str] = &[
"HIT",
"MISS",
"BYPASS",
"EXPIRED",
"REVALIDATED",
"UPDATING",
"STALE",
];
/// URI 首段不在路由表里时的兜底生态名(只进计量,不成上游)。
pub const ECO_DEFAULT: &str = "global";
/// 上游模式。当前只有 `proxy`(普通上游镜像,凭据可选);
/// 独立成字段是为了不改数据文件就能扩展(如将来的 `p2p` / `offline`)。
pub const MODE_PROXY: &str = "proxy";
/// URI 首段 → route。**唯一**的路由判定入口(rest 里的 `/v2/` 也在这里归一)。
pub fn route_of_seg(seg: &str) -> Option<&'static str> {
Some(match seg {
"go" => "go",
"cargo" => "cargo",
"cargo-dl" => "cargo-dl",
"pypi" => "pypi",
"pypi-files" => "pypi-files",
"npm" => "npm",
"maven" => "maven",
"v2" => "docker",
_ => return None,
})
}
/// route → 计量用的生态名。包本体与索引归到同一门语言下。
pub fn eco_of_route(route: &str) -> &'static str {
match route {
"go" => "go",
"cargo" | "cargo-dl" => "cargo",
"pypi" | "pypi-files" => "pypi",
"npm" => "npm",
"maven" => "maven",
"docker" => "docker",
_ => ECO_DEFAULT,
}
}
/// route → nginx `location` 前缀(与 conf 必须逐字一致;管理台用它拼下游地址)。
pub fn route_uri(route: &str) -> &'static str {
match route {
"go" => "/go/",
"cargo" => "/cargo/",
"cargo-dl" => "/cargo-dl/",
"pypi" => "/pypi/",
"pypi-files" => "/pypi-files/",
"npm" => "/npm/",
"maven" => "/maven/",
"docker" => "/v2/",
_ => "/",
}
}
/// route → 中转时要**补回**上游路径的前缀。
///
/// 只有 Docker 需要:`registry v2` 的规范路径本身就含 `/v2`,而我们的
/// location 前缀 `/v2/` 同时承担路由与协议路径两个角色,不能像其他生态
/// 那样把它当纯路由前缀丢掉(丢了上游会收到 `/library/...` 而 404)。
pub fn upstream_path_prefix(route: &str) -> &'static str {
match route {
"docker" => "/v2",
_ => "",
}
}
/// 从请求 URI 推导 route;不在表里返回 `None`。
pub fn route_of_uri(uri: &str) -> Option<&'static str> {
let first = uri.trim_start_matches('/').split('/').next().unwrap_or("");
route_of_seg(first)
}
/// 从请求 URI 推导生态;不在表里归入 [`ECO_DEFAULT`]。
pub fn eco_of_uri(uri: &str) -> &'static str {
match route_of_uri(uri) {
Some(r) => eco_of_route(r),
None => ECO_DEFAULT,
}
}
// ---------------------------------------------------------------------------
// 长度上限(挡住往共享内存塞超长值)
// ---------------------------------------------------------------------------
/// 上游基址长度上限
pub const BASE_MAX_LEN: usize = 200;
/// 上游凭据长度上限
pub const KEY_MAX_LEN: usize = 256;
/// 展示名 / 说明 / 备注长度上限
pub const NAME_MAX_LEN: usize = 64;
pub const DESC_MAX_LEN: usize = 200;
pub const NOTE_MAX_LEN: usize = 200;
// ---------------------------------------------------------------------------
// 默认上游与下游接入说明
// ---------------------------------------------------------------------------
/// 各 route 的官方源。两个用途:
/// 1. 管理台「一键填入官方源」按钮;
/// 2. 上游未配置时,错误信息里告诉管理员该填什么。
pub const DEFAULT_BASES: &[(&str, &str)] = &[
("go", "https://proxy.golang.org"),
("cargo", "https://index.crates.io"),
("cargo-dl", "https://static.crates.io"),
("pypi", "https://pypi.org"),
("pypi-files", "https://files.pythonhosted.org"),
("npm", "https://registry.npmjs.org"),
("maven", "https://repo1.maven.org/maven2"),
("docker", "https://registry-1.docker.io"),
];
/// 各生态的客户端接入说明——**「一键复制下游地址」的数据源**。
///
/// 三元组:`(生态, 简述, 命令模板)`。模板里的 `{base}` 由管理 API 替换成
/// 当前网关入口(`http(s)://<请求的 Host>`),所以文案只此一份、不在前端硬编码:
/// UI 只负责把返回的字符串塞进剪贴板。
///
/// 为什么要放后端:接入命令与**路由前缀**强耦合(`/go/` `/v2/` …)。
/// 前缀改了而前端文案没改,用户照抄就会踩空——放在同一处改就不会漂。
pub const CLIENT_HINTS: &[(&str, &str, &str)] = &[
("go", "Go module proxy", "export GOPROXY={base}/go"),
(
"cargo",
"crates.io 稀疏索引(包本体需另配 /cargo-dl/,见文档)",
"mkdir -p ~/.cargo && printf '[registries.crates-io]\\nindex = \"sparse+{base}/cargo/\"\\n' >> ~/.cargo/config.toml",
),
(
"pypi",
"PyPI 索引(包文件需另配 /pypi-files/,见文档)",
"pip config set global.index-url {base}/pypi/simple/",
),
("npm", "npm registry", "npm config set registry {base}/npm/"),
(
"maven",
"Maven Central 镜像(settings.xml 的 mirror)",
"<mirror><id>ipass</id><url>{base}/maven</url><mirrorOf>central</mirrorOf></mirror>",
),
(
"docker",
"Docker Registry v2(需 TLS;仅 docker.io 官方镜像)",
"sudo mkdir -p /etc/docker && printf '{\"registry-mirrors\":[\"{base}\"]}' | sudo tee /etc/docker/daemon.json",
),
];
/// 某个 route 的官方源(找不到返回空串)
pub fn default_base(route: &str) -> &'static str {
DEFAULT_BASES
.iter()
.find(|(r, _)| *r == route)
.map(|(_, b)| *b)
.unwrap_or("")
}
/// route 是否是受管制路由
pub fn is_route(route: &str) -> bool {
ROUTES.contains(&route)
}
+197
View File
@@ -0,0 +1,197 @@
//! 缓存插件的两个 phase handler。
//!
//! * **access**([`CacheAccessHandler`]):统一 `sk_` Key 鉴权 → 查上游表 →
//! 配额校验 → 放行给 nginx 的 `proxy_cache` 数据面。
//! * **log**([`CacheLogHandler`]):读 `$upstream_cache_status`,按生态记账。
//!
//! ## 为什么鉴权在 access 而计量在 log
//!
//! 鉴权必须早于数据面(access 阶段),否则未授权的请求会白白拉一遍上游;
//! 而**命中与否**只有在代理模块把响应交给客户端之后才最终确定(`HIT` 是
//! 「本次没回源」,由缓存模块在响应阶段判定),access 阶段拿不到。
//! 这与 plugin-llm 的 `LlmHealthHandler` 同构——真实流量自己当探针。
//!
//! ## 缓存为什么是「共享」的
//!
//! `proxy_cache_key` 由 [`crate::cache`] 的 `$cache_key` 给出 = `<route>:<uri>`,
//! **不含用户的 `sk_`**。这是刻意的:同一份 go module / npm 包被 N 个账号拉取时,
//! 只应该回源一次——制品缓存的价值就在这里。鉴权在 access 层做(谁能读),
//! 数据在共享层复用(读什么不必各存一份)。
//!
//! 代价:任一有效 Key 都能命中别人拉过的制品。对公开 registry 无碍;
//! 若某路由指向**私有**上游,请理解这一点再启用(见 docs 的边界说明)。
use core::sync::atomic::{AtomicIsize, Ordering};
use ngx::core::Status;
use ngx::ffi::{
ngx_conf_t, ngx_http_get_indexed_variable, ngx_http_get_variable_index, ngx_http_request_t,
ngx_str_t, ngx_uint_t,
};
use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request};
use ipass_core::{auth, http, plugin_registry, util};
use crate::config;
use crate::stats;
use crate::upstreams;
/// `$upstream_cache_status` 的变量索引(postconfig 解析一次,log 阶段复用)
static CACHE_STATUS_IDX: AtomicIsize = AtomicIsize::new(-1);
/// `$scheme` 的变量索引(管理 API 拼「下游地址」时要回显 http/https)
static SCHEME_IDX: AtomicIsize = AtomicIsize::new(-1);
/// postconfiguration:预取两个变量索引。失败返回 false,gateway 会 EMERG 退出。
///
/// 为什么在 postconfig 而不是 preconfig:`$scheme` 是 core 模块的内建变量,
/// 本模块的 preconfig 早于变量全部注册完成,取 index 可能失败;postconfig
/// 时所有模块的变量都已就位(与 plugin-llm 取 `$upstream_status` 同一时机)。
pub fn prefetch_indexes(cf: *mut ngx_conf_t) -> bool {
let mut cs = ngx_str_t {
len: "upstream_cache_status".len() as usize,
data: b"upstream_cache_status\0".as_ptr() as *mut u8,
};
let mut sc = ngx_str_t {
len: "scheme".len() as usize,
data: b"scheme\0".as_ptr() as *mut u8,
};
// SAFETY: cf 由 nginx 传入且有效;两个 ngx_str_t 指向栈上合法内存
let i1 = unsafe { ngx_http_get_variable_index(cf, &mut cs) };
let i2 = unsafe { ngx_http_get_variable_index(cf, &mut sc) };
if i1 < 0 || i2 < 0 {
return false;
}
CACHE_STATUS_IDX.store(i1 as isize, Ordering::Relaxed);
SCHEME_IDX.store(i2 as isize, Ordering::Relaxed);
true
}
/// 读当前请求的 `$scheme`(拿不到返回空串,调用方回落 `http`)。
pub fn read_scheme(r: *mut ngx_http_request_t) -> String {
// SAFETY: r 由 nginx 传入且有效;索引在 postconfig 已解析
unsafe { read_indexed(r, SCHEME_IDX.load(Ordering::Relaxed)) }
}
/// 安全读取一个已索引变量的字符串值;拿不到返回空串。
unsafe fn read_indexed(r: *mut ngx_http_request_t, idx: isize) -> String {
if idx < 0 {
return String::new();
}
let v = ngx_http_get_indexed_variable(r, idx as ngx_uint_t);
if v.is_null() || (*v).not_found() != 0 || (*v).data.is_null() {
return String::new();
}
let len = (*v).len() as usize;
if len == 0 {
return String::new();
}
String::from_utf8_lossy(core::slice::from_raw_parts((*v).data, len)).into_owned()
}
/// 读当前请求的 `$upstream_cache_status`(供管理 API / 排障复用)
pub fn read_cache_status(r: *mut ngx_http_request_t) -> String {
// SAFETY: r 由 nginx 传入且有效;索引在 postconfig 已解析
unsafe { read_indexed(r, CACHE_STATUS_IDX.load(Ordering::Relaxed)) }
}
// ===========================================================================
// access:统一 Key 鉴权 + 上游就绪检查
// ===========================================================================
/// 制品缓存 access handler。受管制 URI 由路由表(8 前缀)圈定;
/// R19 禁用 → fail-closed 404(数据面是鉴权后的磁盘读,放行=无鉴权读缓存盘)。
pub struct CacheAccessHandler;
impl HttpRequestHandler for CacheAccessHandler {
const PHASE: HttpPhase = HttpPhase::Access;
type Output = Status;
fn handler(request: &mut Request) -> Self::Output {
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
// 非受管制路径(favicon、探针等)直接放行,交给 nginx 自己的 location 处理
let uri = http::uri(r);
let Some(route) = config::route_of_uri(&uri) else {
return Status::NGX_DECLINED;
};
// R19 总闸。location 级开关(`ipass_cache on` → `loc::Switch::Cache`)
// 待 gateway 接入轮随 core 补变体后一并加回,路由前缀判定保留作第二道闸。
if !plugin_registry::plugin_enabled("cache") {
return HTTPStatus::NOT_FOUND.into();
}
// 上游未配置:**必须在这里拦**。否则变量式 proxy_pass 拿到空
// `$cache_target`,nginx 会报 500 `no host in upstream`,
// 排障时会误以为是缓存本身坏了。
if upstreams::lookup(route).is_none() {
util::log_warn(&format!(
"[cache] 路由 {route} 未配置上游,拒绝 {uri}(client={})",
http::remote_addr(r)
));
return http::fail(
r,
HTTPStatus::SERVICE_UNAVAILABLE,
&format!(
"生态 {route} 的上游尚未配置,请联系管理员到「制品缓存」页填写上游地址"
),
);
}
// ---- 统一 Key 鉴权(与 LLM / API 代理同一把 sk_、同一份配额)----
let Some(key) = auth::downstream_key(r) else {
return http::fail(
r,
HTTPStatus::UNAUTHORIZED,
"缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带",
);
};
let Some((username, _allowed, rpm, daily)) = auth::identity(&key) else {
util::log_warn(&format!(
"[cache] API Key 校验失败 route={route} client={}",
http::remote_addr(r)
));
return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或已失效");
};
// SAFETY: r 由 nginx 传入且有效;check_quota 只读请求头与共享内存
if let Some(resp) = unsafe { auth::check_quota(r, &username, rpm, daily) } {
return resp;
}
// 放行:数据面交给 nginx `proxy_cache`(命中不产生任何模块开销)
Status::NGX_DECLINED
}
}
// ===========================================================================
// log:按生态记命中
// ===========================================================================
/// 缓存命中计量(log 阶段)。同样按路由表圈定(与 access 一致);禁用时不记账。
pub struct CacheLogHandler;
impl HttpRequestHandler for CacheLogHandler {
const PHASE: HttpPhase = HttpPhase::Log;
type Output = Status;
fn handler(request: &mut Request) -> Self::Output {
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
// 只计缓存路由的请求(非缓存 URI 不进命中率分母);R19 禁用时跳过。
if config::route_of_uri(&http::uri(r)).is_none()
|| !plugin_registry::plugin_enabled("cache")
{
return Status::NGX_DECLINED;
}
let status = read_cache_status(r);
if status.is_empty() {
// 没拿到状态:请求被鉴权拦下(401/503)、或上游连接失败未走缓存模块。
// 这类请求不该计入命中率分母——它们根本没进缓存层。
return Status::NGX_DECLINED;
}
// 生态从 URI 首段推导(直读 r->uri,不依赖任何 nginx 变量)
let eco = config::eco_of_uri(&http::uri(r));
stats::record(eco, &status, util::now());
Status::NGX_DECLINED
}
}
+90
View File
@@ -0,0 +1,90 @@
//! ipass-plugin-cache —— 统一制品缓存插件(go / rust / python / npm / java / docker)。
//!
//! ## 它做什么,不做什么
//!
//! | 层 | 谁干 | 在哪 |
//! | --- | --- | --- |
//! | 缓存内容(制品字节) | nginx 原生 `proxy_cache` | **本地磁盘**(`proxy_cache_path`) |
//! | 命中计数 | 本插件的 log handler | 内核共享内存(`usage` 原语) |
//! | 鉴权 | 本插件的 access handler | 内核 `auth`(统一 `sk_` Key) |
//! | 上游地址与凭据 | 本插件的 `upstreams` 表 | 共享内存 `cx:<route>` + JSON 落盘 |
//!
//! **不自己实现 upstream**:转发、Range、错误重试、连接池、磁盘淘汰全部交给
//! nginx 的 proxy 模块。本插件只在 access 阶段做一次决策(有没有资格、上游是谁)、
//! 在 log 阶段记一笔账。
//!
//! ## 装配点(gateway)
//!
//! * `preconfig` —— 注册五个只读变量:`$cache_target` / `$cache_host` /
//! `$cache_upstream_key` / `$cache_eco` / `$cache_key`(见 [`cache`])
//! * `postconfig` —— 预取 `$upstream_cache_status` / `$scheme` 变量索引、
//! 识别 proxy_cache 容量区([`zones`],供容量面板读数与清理),
//! 并注册 access(鉴权)+ log(计量)两个 handler
//! * `zone_load` —— 全量装载 `cx:` 上游表
//! * `dispatch_api` —— 认领 `/api/admin/cache*`(管理员)与 `/api/v1/cache*`(账号态)
//!
//! ## 与 apix / llm 的关系
//!
//! 同一把下行 `sk_` Key、同一份配额(内核 `auth`),差别只在数据面:
//! llm/apix 把请求转给上游 API,cache 把请求交给 nginx 的磁盘缓存。
//! 上游表的写法刻意与 `plugin-apix::apix` 同构(`<前缀>:` → 多行 payload),
//! 这样三张表的「写文件 → 写穿共享内存 → 热路径查表」读起来是一套东西。
pub mod api;
pub mod cache;
pub mod config;
pub mod handlers;
pub mod models;
pub mod stats;
pub mod store;
pub mod upstreams;
pub mod zones;
use ngx::core::Status;
use ngx::ffi::{ngx_conf_t, ngx_http_request_t};
use ipass_core::plugin::Plugin;
pub struct CachePlugin;
impl Plugin for CachePlugin {
fn name(&self) -> &'static str {
"cache"
}
fn preconfig(&self, cf: *mut ngx_conf_t) -> bool {
// SAFETY: cf 由 nginx 传入且有效
unsafe { cache::preconfig(cf) }
}
fn postconfig(&self, cf: *mut ngx_conf_t) -> bool {
// 变量索引先取(拿不到就没法记账/回显 scheme,直接让 nginx EMERG 退出,
// 好过运行期静默少记一笔账)
if !handlers::prefetch_indexes(cf) {
return false;
}
// 容量区识别:必须在 config 阶段做——`zone->data` 指向的
// ngx_http_file_cache_t 是 proxy_cache_path 解析时填的,
// 而共享内存里的记账结构要等 init 之后才可读(读数推迟到请求期)。
// 失败不致命:容量面板显示"不可用",其余功能照常。
zones::discover(cf);
// SAFETY: cf 由 nginx 传入且有效
let cf = unsafe { &mut *cf };
// 顺序无关(两个 handler 在不同阶段),但 access 在前更贴近阅读顺序
if ngx::http::add_phase_handler::<handlers::CacheAccessHandler>(cf).is_err() {
return false;
}
if ngx::http::add_phase_handler::<handlers::CacheLogHandler>(cf).is_err() {
return false;
}
true
}
fn dispatch_api(&self, r: *mut ngx_http_request_t) -> Option<Status> {
api::dispatch(r)
}
fn zone_load(&self) -> usize {
upstreams::reload_shm()
}
}
+95
View File
@@ -0,0 +1,95 @@
//! 缓存上游的持久化模型(`data/cache-upstreams.json`)。
//!
//! 与 `llm-upstreams.json` / `api-proxies.json` 同构——一个 JSON 文件就是一个
//! 小表,`store` 负责原子写与跨 worker 互斥,**没有数据库**。
//!
//! ⚠️ `key` 字段是**上游凭据**(私有 registry 的 token / Basic 串)。
//! 敏感级别等同 `users.json`:写盘按密钥处理好、管理 API 只回显掩码。
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// 上游表(`cache-upstreams.json`)。
///
/// key = **路由名**,取值必须落在 `config::ROUTES` 里(共 8 个)。
///
/// ⚠️ 「路由名 / URI 前缀 / 生态名」是三个不同的东西,只在 docker 上分开,
/// 也正是在那里最容易写错:
/// URI 前缀 `/v2/` ← 路由名 `docker` ← 生态 `docker`
/// `config::route_of_seg` 把首段 `v2` 归一成路由名 `docker`,所以本表的键
/// 是 `docker`(写成 `v2` 不会报错,只会让该路由**恒 503「上游尚未配置」**,
/// 表现像配置没保存)。同理 `cargo-dl` / `pypi-files` 是独立路由,
/// 但 `eco_of_route` 把它们归到 `cargo` / `pypi` 生态计数。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheUpstreamStore {
#[serde(default)]
pub items: BTreeMap<String, CacheUpstream>,
}
impl Default for CacheUpstreamStore {
fn default() -> Self {
Self {
items: BTreeMap::new(),
}
}
}
/// 单个生态的上游配置。
///
/// 这里刻意**不存**「把哪个 URI 前缀映射到本生态」——那由 nginx conf 的
/// `location /go/` 决定(写死在配置里、启动即固定)。两者分工:
/// conf 管「路由与缓存策略」,本表管「上游地址与凭据」,各自改各自的不冲突。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheUpstream {
/// 上游基址,如 `https://proxy.golang.org`(不带尾斜杠)。
/// 转发的目标 = `base + <location 前缀之后的 URI 尾部>`。
#[serde(default)]
pub base: String,
/// 上游凭据,存**完整的 Authorization 头值**(如 `Bearer xxx` / `Basic yyy`),
/// 由 `$cache_auth` 直接下发。留空 = 不指定上游凭据(此时透传客户端自带的
/// Authorization,Docker Hub 的 Bearer token 走这条;但下端 `sk_` 会被剔除)。
#[serde(default)]
pub key: String,
/// 模式(见 `config::MODE_PROXY`)
#[serde(default = "default_mode")]
pub mode: String,
/// 展示名(中文)
#[serde(default)]
pub name: String,
/// 一句话说明
#[serde(default)]
pub desc: String,
/// 停用 = 从共享内存删除(热路径查不到即 404),保留 JSON 便于再启用
#[serde(default = "default_true")]
pub enabled: bool,
#[serde(default)]
pub note: String,
#[serde(default)]
pub created_at: i64,
#[serde(default)]
pub updated_at: i64,
}
fn default_true() -> bool {
true
}
fn default_mode() -> String {
crate::config::MODE_PROXY.to_owned()
}
impl Default for CacheUpstream {
fn default() -> Self {
Self {
base: String::new(),
key: String::new(),
mode: default_mode(),
name: String::new(),
desc: String::new(),
enabled: true,
note: String::new(),
created_at: 0,
updated_at: 0,
}
}
}
+43
View File
@@ -0,0 +1,43 @@
//! 缓存命中计量:复用内核 `usage` 共享内存原语(与 LLM 用量同款)。
//!
//! 键形如 `cache:<eco>:<STATUS>`,值为窗口读数 `<日窗id>:<今日>:<累计>:<ts>`。
//! 命中率管理只关心**累计**(`total`),所以 overview 只读 total 字段。
//! 数据全部躺在共享内存里,没有新文件、没有新进程——守住「单容器零依赖」。
use std::collections::BTreeMap;
use serde_json::{Value, json};
use crate::config::{ECOS, KEY_CACHE_PREFIX, STATUSES};
use ipass_core::{usage, util};
/// 记一次缓存状态(按生态 + 全局两个维度)。
pub fn record(eco: &str, status: &str, now: i64) {
if eco.is_empty() || status.is_empty() {
return;
}
let day = util::day_id(now);
usage::bump(KEY_CACHE_PREFIX.as_bytes(), &format!("{eco}:{status}"), day, now);
usage::bump(KEY_CACHE_PREFIX.as_bytes(), &format!("global:{status}"), day, now);
}
/// 管理 API 读数:按生态 × 状态给出累计命中数。
///
/// 口径与 LLM 用量一致——**只统计真的走缓存层的请求**(log 阶段在代理
/// 模块把响应交给客户端之后才记账,被 `proxy_cache off` 或错误短路的请求
/// 拿不到 `$upstream_cache_status`,自然不计入)。
pub fn overview(now: i64) -> Value {
let day = util::day_id(now);
let mut by_eco: BTreeMap<String, BTreeMap<String, i64>> = BTreeMap::new();
for eco in ECOS {
let mut m = BTreeMap::new();
for st in STATUSES {
let u = usage::read(KEY_CACHE_PREFIX.as_bytes(), &format!("{eco}:{st}"), day);
m.insert((*st).to_string(), u.total);
}
by_eco.insert((*eco).to_string(), m);
}
json!({ "now": now, "by_ecosystem": by_eco })
}
+38
View File
@@ -0,0 +1,38 @@
//! 上游表的文件读写(复用内核 store 的原子写 + 全局文件写锁)。
//!
//! `data/cache-upstreams.json` 可能含上游凭据,**敏感级别等同 `users.json`**
//! (`data/` 目录已被 .gitignore 排除)。
use std::path::PathBuf;
use ipass_core::{state, store};
use crate::models::CacheUpstreamStore;
fn upstreams_path() -> PathBuf {
store::path_in_data("cache-upstreams.json")
}
pub fn read_upstreams() -> CacheUpstreamStore {
store::read_json(&upstreams_path(), CacheUpstreamStore::default())
}
pub fn write_upstreams(data: &CacheUpstreamStore) -> Result<(), String> {
store::write_json(&upstreams_path(), data)
}
/// 加锁「读-改-写」上游表。
///
/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。
/// ⚠️ 提交后**必须**调用 `upstreams::sync_shm` 把变更写穿共享内存,
/// 否则改动只落在文件里、热路径仍按旧值转发(下次重启才生效)。
pub fn update_upstreams<T, F>(f: F) -> Result<T, String>
where
F: FnOnce(&mut CacheUpstreamStore) -> Result<T, String>,
{
let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?;
let mut data = read_upstreams();
let out = f(&mut data)?;
write_upstreams(&data)?;
Ok(out)
}
+379
View File
@@ -0,0 +1,379 @@
//! 上游表:JSON 落盘 + 共享内存热表 + 入参校验 + 管理台视图。
//!
//! 生命周期与 apix 的代理表同构:
//! **写文件(原子)→ 写穿共享内存**;热路径只读共享内存,查不到即「该路由
//! 未配置上游」——不设任何回源兜底(与 `domains` / `upstreams` 同一语义)。
use serde_json::{Value, json};
use ngx::ffi::ngx_http_request_t;
use ipass_core::{http, state, util};
use crate::config;
use crate::handlers; // `$scheme` 变量索引由 handlers 统一预取(见 prefetch_indexes)
use crate::models::{CacheUpstream, CacheUpstreamStore};
use crate::store;
// ===========================================================================
// payload 编解码(shm 值)
// ===========================================================================
/// `base \n 上游Key \n mode`。三行塞一个键,热路径一次查表拿全。
fn payload_of(item: &CacheUpstream) -> String {
format!(
"{}{}{}{}{}",
item.base,
config::PAYLOAD_SEP,
item.key,
config::PAYLOAD_SEP,
item.mode
)
}
/// 拆 payload:`base \n key \n mode`(缺字段时给空串,不 panic)。
pub fn split_payload(payload: &str) -> (&str, &str, &str) {
let mut it = payload.splitn(3, config::PAYLOAD_SEP);
let base = it.next().unwrap_or("");
let key = it.next().unwrap_or("");
let mode = it.next().unwrap_or("");
(base, key, mode)
}
// ===========================================================================
// 共享内存同步
// ===========================================================================
/// 把一条路由同步进共享内存。**所有写操作之后必须调用它**。
///
/// 停用 = 删除:热路径「查不到 = 不可用」,停用即刻生效且不留残留。
pub fn sync_shm(route: &str, st: &CacheUpstreamStore) {
let Some(item) = st.items.get(route) else {
state::remove(config::KEY_CX_PREFIX, route.as_bytes());
return;
};
if !item.enabled || item.base.is_empty() {
state::remove(config::KEY_CX_PREFIX, route.as_bytes());
return;
}
let payload = payload_of(item);
if !state::put(
config::KEY_CX_PREFIX,
route.as_bytes(),
payload.as_bytes(),
0,
) {
util::log_err(&format!(
"[cache] 上游配置写共享内存失败 route={route} —— 该路由会 404(共享内存可能已满)"
));
}
}
/// 全量重载上游表(worker 启动装载 / 变更后)。返回装载条数。
pub fn reload_shm() -> usize {
state::clear_prefix(config::KEY_CX_PREFIX);
let data = store::read_upstreams();
let mut expected = 0;
let mut loaded = 0;
for (route, item) in &data.items {
if !item.enabled || item.base.is_empty() {
continue;
}
expected += 1;
let payload = payload_of(item);
if state::put(
config::KEY_CX_PREFIX,
route.as_bytes(),
payload.as_bytes(),
0,
) {
loaded += 1;
}
}
if loaded != expected {
util::log_err(&format!(
"[cache] 上游装载不全:{loaded}/{expected} —— 有路由会 404"
));
}
loaded
}
// ===========================================================================
// 查询
// ===========================================================================
/// 热路径查表:`route → (base, 上游Key, mode)`
pub fn lookup(route: &str) -> Option<(String, String, String)> {
let payload = state::get(config::KEY_CX_PREFIX, route.as_bytes())?.0;
let (base, key, mode) = split_payload(&payload);
if base.is_empty() {
return None;
}
Some((base.to_owned(), key.to_owned(), mode.to_owned()))
}
/// 从请求推出 `(route, base, 上游Key, mode)`——access handler 与变量求值共用。
///
/// 返回 `None` 表示「该 URI 不在受管制路由下」或「该路由尚未配置上游」。
/// 两者对调用方的处理不同(前者放行不管、后者要报 503 并提示去管理台配),
/// 所以外面还要用 [`config::route_of_uri`] 区分。
pub fn upstream_of_request(r: *mut ngx_http_request_t) -> Option<(String, String, String, String)> {
let route = config::route_of_uri(&http::uri(r))?;
let (base, key, mode) = lookup(route)?;
Some((route.to_owned(), base, key, mode))
}
/// 上游表全量(含未启用条目,管理台要看到)
pub fn all() -> Vec<(String, CacheUpstream)> {
store::read_upstreams().items.into_iter().collect()
}
/// 读单条(管理 API 用)
pub fn get(route: &str) -> Option<CacheUpstream> {
store::read_upstreams().items.get(route).cloned()
}
// ===========================================================================
// 校验
// ===========================================================================
/// 路由名校验:必须在 `config::ROUTES` 内(大小写归一)。
pub fn validate_route(raw: &str) -> Result<String, String> {
let r = util::trim(raw).to_ascii_lowercase();
if r.is_empty() {
return Err("缺少路由名(route)".to_owned());
}
if !config::is_route(&r) {
return Err(format!(
"未知路由 {r},可选:{}",
config::ROUTES.join(" / ")
));
}
Ok(r)
}
/// 上游基址校验:必须是 http(s) 绝对地址,且不带尾斜杠。
///
/// 为什么强制 scheme:nginx 的变量式 `proxy_pass $cache_target` 需要完整 URL,
/// 而模块拼 target 时是 `base + tail`——base 缺 scheme 会直接 500。
pub fn validate_base(raw: &str) -> Result<String, String> {
let b = util::trim(raw).trim_end_matches('/').to_owned();
if b.is_empty() {
return Err("上游基址(base)不能为空".to_owned());
}
if b.len() > config::BASE_MAX_LEN {
return Err(format!("上游基址过长(上限 {} 字节)", config::BASE_MAX_LEN));
}
if !(b.starts_with("http://") || b.starts_with("https://")) {
return Err("上游基址必须以 http:// 或 https:// 开头".to_owned());
}
if b.len() <= "https://".len() {
return Err("上游基址不完整".to_owned());
}
Ok(b)
}
/// 裁剪文本字段到上限(超长直接拒绝,避免悄悄丢字让人困惑)
fn validate_text(raw: &str, max: usize, field: &str) -> Result<String, String> {
let v = util::trim(raw).to_owned();
if v.len() > max {
return Err(format!("{field}过长(上限 {max} 字节)"));
}
Ok(v)
}
// ===========================================================================
// 写入
// ===========================================================================
/// 新增或覆盖一条上游配置。
///
/// `base` 传 `None` 或空串表示「保留原值」(新建时必须填);
/// `key` 传 `None` 表示保留、`Some("")` 表示清空、`Some(v)` 表示覆盖——
/// 两种语义的差异及理由见函数体内注释。
pub fn upsert(
route_raw: &str,
base_raw: Option<&String>,
key_raw: Option<&String>,
name: Option<&String>,
desc: Option<&String>,
enabled: bool,
note: Option<&String>,
) -> Result<CacheUpstream, String> {
let route = validate_route(route_raw)?;
let opt_text = |o: Option<&String>, max: usize, field: &str| -> Result<Option<String>, String> {
match o {
Some(v) if !util::trim(v).is_empty() => Ok(Some(validate_text(v, max, field)?)),
_ => Ok(None),
}
};
let name_v = opt_text(name, config::NAME_MAX_LEN, "展示名")?;
let desc_v = opt_text(desc, config::DESC_MAX_LEN, "说明")?;
let note_v = opt_text(note, config::NOTE_MAX_LEN, "备注")?;
let base_arg = match base_raw {
Some(b) if !util::trim(b).is_empty() => Some(validate_base(b)?),
_ => None,
};
// ⚠️ key 的语义与 base **刻意不同**:
// None = 保留原值(表单没提交该字段)
// Some("") = 清空
// Some(v) = 覆盖
// 理由:凭据在管理台只回显掩码(抄不出来),若也按「空=保留」处理,
// 就永远删不掉一个填错的凭据;而 base 是明文可抄的,「空=保留」更顺手。
let key_arg = match key_raw {
None => None,
Some(k) => {
let k = util::trim(k).to_owned();
if k.len() > config::KEY_MAX_LEN {
return Err(format!("上游凭据过长(上限 {} 字节)", config::KEY_MAX_LEN));
}
Some(k)
}
};
let now = util::now();
let mut saved = CacheUpstream::default();
let mut snapshot = CacheUpstreamStore::default();
store::update_upstreams(|st| {
let item = st.items.entry(route.clone()).or_default();
if item.created_at == 0 {
item.created_at = now;
}
// base:空 = 保留原值;新建时为空则报错(没基址无法转发)
if let Some(b) = &base_arg {
item.base = b.clone();
}
if item.base.is_empty() {
return Err(
"该路由还没有上游基址:新建时必须填写(可点「填入官方源」一键带入)".to_owned(),
);
}
// key:`Some("")` = 清空、`Some(v)` = 覆盖、`None` = 保留(表单没提交)。
// 语义与 base 刻意不同,理由见上面 key_arg 的注释;管理台提交空串即清空。
if let Some(k) = &key_arg {
item.key = k.clone();
}
if let Some(v) = name_v {
item.name = v;
}
if let Some(v) = desc_v {
item.desc = v;
}
if let Some(v) = note_v {
item.note = v;
}
item.enabled = enabled;
item.updated_at = now;
saved = item.clone();
snapshot = st.clone();
Ok(())
})?;
sync_shm(&route, &snapshot);
Ok(saved)
}
/// 删除一条上游配置(连同共享内存条目)。
pub fn remove(route_raw: &str) -> Result<String, String> {
let route = validate_route(route_raw)?;
let mut snapshot = CacheUpstreamStore::default();
store::update_upstreams(|st| {
if st.items.remove(&route).is_none() {
return Err(format!("路由 {route} 没有配置"));
}
snapshot = st.clone();
Ok(())
})?;
state::remove(config::KEY_CX_PREFIX, route.as_bytes());
Ok(route)
}
// ===========================================================================
// 视图(管理台 / 账号态)
// ===========================================================================
/// 上游凭据掩码:只留末 4 位。空串回空串(前端据此显示「未配置」)。
pub fn mask_key(k: &str) -> String {
if k.is_empty() {
return String::new();
}
let skip = k.chars().count().saturating_sub(4);
let tail: String = k.chars().skip(skip).collect();
format!("****{tail}")
}
/// 当前网关入口(`scheme://Host`)——「一键复制下游地址」的 `{base}`。
///
/// 用**请求自带的 Host** 而不是写死域名:同一份配置可能挂在 88 / 443 /
/// 内网端口后面,写死就会把用户指到一个他访问不到的地址。
pub fn entry_base(r: *mut ngx_http_request_t) -> String {
// SAFETY: r 有效;$scheme 索引在 postconfiguration 已预取(失败则回落 http)
let scheme = handlers::read_scheme(r);
let scheme = if scheme.is_empty() {
"http".to_owned()
} else {
scheme
};
match http::header(r, "Host") {
Some(h) if !util::trim(&h).is_empty() => format!("{scheme}://{}", util::trim(&h)),
_ => scheme,
}
}
/// 某生态的「一键复制」内容(来自 `config::CLIENT_HINTS`,`{base}` 已替换)
pub fn client_hint(eco: &str, entry: &str) -> Option<Value> {
config::CLIENT_HINTS
.iter()
.find(|(e, _, _)| *e == eco)
.map(|(_, label, tpl)| {
json!({
"label": label,
"command": tpl.replace("{base}", entry),
})
})
}
/// 管理台单行视图。
///
/// `item = None` 表示该路由**尚未配置**——仍然回显一行(带官方源与下游地址),
/// 这样管理员打开页面就能看到「六个生态 + 两个包本体路由」的全貌,而不是空表。
pub fn view(route: &str, item: Option<&CacheUpstream>, entry: &str, active: bool) -> Value {
let eco = config::eco_of_route(route);
let configured = item.is_some();
let it = item.cloned().unwrap_or_default();
json!({
"route": route,
"eco": eco,
"uri": config::route_uri(route),
"base": it.base,
"key_masked": mask_key(&it.key),
"key_set": !it.key.is_empty(),
"mode": it.mode,
"name": it.name,
"desc": it.desc,
"note": it.note,
"enabled": it.enabled,
"configured": configured,
// 是否真的在共享内存里(= 已配置 && 启用 && base 非空)
"active": active,
"default_base": config::default_base(route),
"updated_at": it.updated_at,
"client": client_hint(eco, entry),
})
}
/// 管理台全表视图:**按 `config::ROUTES` 顺序**输出(含未配置的行)。
pub fn view_all(entry: &str) -> Vec<Value> {
let stored = store::read_upstreams();
let mut out = Vec::with_capacity(config::ROUTES.len());
for route in config::ROUTES {
let item = stored.items.get(*route);
let active = item.map(|i| i.enabled && !i.base.is_empty()).unwrap_or(false)
&& lookup(route).is_some();
out.push(view(route, item, entry, active));
}
out
}
+846
View File
@@ -0,0 +1,846 @@
//! 容量管理:把 **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("", "*"));
}
}