feat(cache): 失败源进 60s 冷却

换源链在命名 location 里写下 X-Cache-Failed-Slot 响应头,
log 阶段据此把失败的源踢出轮转;最终 502/504 时全部冷却(兜底)。
This commit is contained in:
admin committed 2026-10-30 20:31:26 +08:00
1 parent 34eb8c7d0b
commit c43ad3749e
3 files changed
+257 -31

No files matched your search

+118 -3
View File
@@ -25,8 +25,8 @@ 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,
ngx_conf_t, ngx_http_get_indexed_variable, ngx_http_get_variable, ngx_http_get_variable_index,
ngx_http_request_t, ngx_str_t, ngx_uint_t,
};
use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request};
@@ -35,6 +35,7 @@ use ipass_core::{auth, http, plugin_registry, util};
use crate::cache;
use crate::config;
use crate::stats;
use crate::upstreams;
/// `$upstream_cache_status` 的变量索引(postconfig 解析一次,log 阶段复用)
static CACHE_STATUS_IDX: AtomicIsize = AtomicIsize::new(-1);
@@ -43,7 +44,10 @@ static SCHEME_IDX: AtomicIsize = AtomicIsize::new(-1);
/// `$request_id` 的变量索引(选源散列用)。**可选**:拿不到就退化为 URI 散列。
static REQUEST_ID_IDX: AtomicIsize = AtomicIsize::new(-1);
/// postconfiguration:预取三个变量索引。失败返回 false,gateway 会 EMERG 退出。
/// postconfiguration:预取**五个**变量索引。失败返回 false,gateway 会 EMERG 退出。
///
/// 五个是:`$upstream_cache_status`、`$scheme`、`$request_id`(**可选**)、
/// `$cache_pick`、以及内部变量 `$cache_ctx`。
///
/// 为什么在 postconfig 而不是 preconfig:`$scheme` 是 core 模块的内建变量,
/// 本模块的 preconfig 早于变量全部注册完成,取 index 可能失败;postconfig
@@ -132,6 +136,111 @@ pub fn read_cache_status(r: *mut ngx_http_request_t) -> String {
unsafe { read_indexed(r, CACHE_STATUS_IDX.load(Ordering::Relaxed)) }
}
// ===========================================================================
// log:把失败的源打入冷却(熔断)
// ===========================================================================
/// 读换源链写下的「失败顺位」响应头 `$sent_http_x_cache_failed_slot`。
///
/// 契约(由 nginx conf 保证):换源链的命名 location 里
/// `add_header X-Cache-Failed-Slot "<顺位>" always;`
/// ——「我这一跳是第几跳」=「上一跳(及更早)失败了」。
/// 拿不到 = 本次没有失败过(正常命中或一次成功)。
///
/// ⚠️ 这里 `ngx_http_get_variable(r, name, 0)` 的 `key = 0` **是安全的**,
/// 与 Task 4 的 `$cache_pick` 不同——因为 `sent_http_` 是 nginx 的
/// **前缀变量**(`ngx_http_variables.c:399` 注册):
/// `ngx_http_get_variable()` 先查 `variables_hash`(查不到),
/// 再落到 `cmcf->prefix_variables` 兜底(src/http/ngx_http_variables.c:727-750),
/// 这条路径**不看 `key`** ⇒ 传 0 无所谓。
/// 反过来,**普通变量**(像 `$cache_pick`)走的就是 `variables_hash`
/// 那条路,`key` 是哈希桶号 ⇒ 必须用索引读,别照抄这里的写法。
///
/// 头名映射:nginx 把响应头名小写并把 `-` 换成 `_` 后比较
/// (src/http/ngx_http_variables.c:971-984),
/// 所以 `X-Cache-Failed-Slot` ↔ `x_cache_failed_slot` ✔。
pub fn read_failed_slot(r: *mut ngx_http_request_t) -> Option<usize> {
let mut name = ngx_str_t {
len: "sent_http_x_cache_failed_slot".len(),
data: b"sent_http_x_cache_failed_slot\0".as_ptr() as *mut u8,
};
// SAFETY: r 由 nginx 传入且有效;sent_http_ 是 nginx 内建前缀变量
let v = unsafe { ngx_http_get_variable(r, &raw mut name, 0) };
if v.is_null() {
return None;
}
// SAFETY: v 非空 ⇒ 可读它的字段;not_found 为真时 data 未定义
// (nginx 只置 not_found,不清 data)⇒ 先判 not_found 再碰 data。
let (not_found, data, len) = unsafe { ((*v).not_found() != 0, (*v).data, (*v).len() as usize) };
if not_found || data.is_null() || len == 0 {
return None;
}
// SAFETY: not_found 为假且 data 非空 ⇒ data 指向 len 字节的有效内存
let s = unsafe { core::slice::from_raw_parts(data, len) };
let s = String::from_utf8_lossy(s);
let s = s.trim();
// ⚠️ nginx 对**同名**的多个响应头会用 ", " 拼接成一个值
// (ngx_http_variable_unknown_header:多个匹配头拼成 "a, b")。
// 契约是「一个整数」,但若 conf 在**同一层**写了两次该头,
// 拿到的就是 "1, 2" ⇒ 直接 parse 会失败 ⇒ **静默地一个源都不冷却**。
// ⇒ 取**最后一段**(内层/后写的那次最贴近真实失败顺位)再解析。
let s = s.rsplit(',').next().unwrap_or(s).trim();
s.parse::<usize>().ok()
}
/// 把失败的源打入冷却(`cache::cool_down`,60 秒)。
///
/// 判定「哪些源失败」用两条线索:
/// 1. **响应头 `X-Cache-Failed-Slot`**(换源链写下的顺位)——它给的是
/// **最后一跳失败的那个顺位**,而走到那一跳说明 `slots[0..=k]` 全都失败过
/// ⇒ 冷却**整段 `0..=k`**(R34 / R-T5-4);
/// 2. **最终状态码是 403/5xx** ⇒ 整条链都失败 ⇒ 全部顺位冷却
/// (兜底:conf 没写该响应头、或旧版 conf 没这个机制)。
/// 403 也在内,因为换源链把 403 当「该源拒绝我们」⇒ 走到最后仍是 403
/// 就说明整个池都在拒绝我们。404 不在列(= 确实没这个包,不是源的问题)。
///
/// 顺位 → 源下标的映射**必须**走 `$cache_pick`(R-T5-5):它是**请求内缓存**
/// 的(Task 4 的 memo)⇒ 与本次请求**实际用的源**严格一致;
/// 另查一次上游表拿到的是**此刻**的池子 ⇒ 管理员在请求中途改了池子就错位。
/// 另查的那一次**只**用来取 `sources.len()` 做**边界检查**
/// (防止池子缩小后下标越界)——这条检查必须保留。
///
/// ⚠️ 调用点必须在 log handler 的 `status.is_empty()` **早退之后**
/// (R-T5-1):没过缓存层的请求(401 无效 Key / 429 超配额 / 503 未配上游)
/// **没有回源** ⇒ 没有源失败 ⇒ 不该冷却任何源。
fn cool_down_failed(r: *mut ngx_http_request_t) {
let Some(route) = config::route_of_uri(&http::uri(r)) else {
return;
};
// 只用来取 sources.len() 做边界检查(真相源是 $cache_pick,见上)
let Some(up) = upstreams::lookup_upstream(route) else {
return;
};
let sources = upstreams::effective_sources(&up);
if sources.is_empty() {
return;
}
// SAFETY: r 由 nginx 传入且有效;只读响应状态码
let final_status = unsafe { (*r).headers_out.status as u16 };
let all_failed = matches!(final_status, 403 | 500 | 502 | 503 | 504);
let slot = if all_failed { None } else { read_failed_slot(r) };
let failed = cache::failed_slots(all_failed, slot);
if failed.is_empty() {
return;
}
let raw = cache::read_pick_var(r);
let Some(slots) = cache::parse_pick(&raw) else {
return;
};
for slot in failed {
let Some(idx) = slots.get(slot) else { continue };
if *idx >= sources.len() {
continue;
}
cache::cool_down(route, *idx);
}
}
// ===========================================================================
// access:统一 Key 鉴权 + 上游就绪检查
// ===========================================================================
@@ -238,6 +347,12 @@ impl HttpRequestHandler for CacheLogHandler {
// 生态从 URI 首段推导(直读 r->uri,不依赖任何 nginx 变量)
let eco = config::eco_of_uri(&http::uri(r));
stats::record(eco, &status, util::now());
// 失败源冷却(换源链失败时把那个源踢出轮转 60s)
//
// ⚠️ 必须放在上面 `status.is_empty()` 的早退**之后**(R-T5-1):
// 没过缓存层的请求(401 无效 Key / 429 超配额 / 503 未配上游)
// **没有回源** ⇒ 没有源失败 ⇒ 一个源都不该被冷却。
cool_down_failed(r);
Status::NGX_DECLINED
}
}