feat(cache): 失败源进 60s 冷却
换源链在命名 location 里写下 X-Cache-Failed-Slot 响应头, log 阶段据此把失败的源踢出轮转;最终 502/504 时全部冷却(兜底)。
This commit is contained in:
1 parent
34eb8c7d0b
commit
c43ad3749e
3 files changed
+257
-31
No files matched your search
+133
-26
@@ -327,6 +327,14 @@ pub fn parse_pick(raw: &str) -> Option<[usize; config::MAX_SLOTS]> {
|
||||
}
|
||||
|
||||
/// 该源实际使用的上游凭据:源自己的优先,空则回落路由级 `key`。
|
||||
///
|
||||
/// ⚠️ **多源路由不应配路由级 `key`**(由 **Task 6** 落实强制)。
|
||||
/// 本函数把路由级 `key` **复制给每一个没配自己凭据的源** ⇒ 池里
|
||||
/// **任意一个**第三方镜像站都会收到这份路由级凭据 —— 等价于把一份凭据
|
||||
/// 发给 N 个互不信任的第三方。
|
||||
/// 多源路由的正确做法是**逐源配凭据**(每个源用各自的 `key`)。
|
||||
/// 今天保留「空则回落路由级」的语义(单源路由依赖它),
|
||||
/// 本条只是把约束**写死在注释里**,真正的强制在 Task 6。
|
||||
pub fn effective_key(up: &upstreams::Decoded, src: &CacheSource) -> String {
|
||||
if !src.key.is_empty() {
|
||||
return src.key.clone();
|
||||
@@ -369,6 +377,9 @@ pub fn allow_client_auth(route: &str, source_count: usize) -> bool {
|
||||
/// 该路由各源是否处于冷却中。
|
||||
///
|
||||
/// 冷却项用 `expires_at` 自动过期 ⇒ 这里只需查「还活着没有」。
|
||||
///
|
||||
/// ⚠️ **键是「源下标」不是「源 id」**(R-T5-3)⇒ 池子变了必须清
|
||||
/// 该路由的 `ch:` 条目(见 [`cool_down`] 的注释 / Task 6)。
|
||||
pub fn cooled_flags(route: &str, n: usize) -> Vec<bool> {
|
||||
let now = util::now();
|
||||
(0..n)
|
||||
@@ -380,6 +391,12 @@ pub fn cooled_flags(route: &str, n: usize) -> Vec<bool> {
|
||||
}
|
||||
|
||||
/// 把某个源打入冷却(`config::COOLDOWN_SECS` 秒后自动恢复)。
|
||||
///
|
||||
/// ⚠️ **键是「源下标」不是「源 id」**(R-T5-3):`ch:<route>:<下标>`。
|
||||
/// ⇒ 管理员在管理台**重排 / 增删源**之后,旧的 `ch:` 条目会**套到别的源头上**。
|
||||
/// ⇒ **改池子时必须清掉该路由的 `ch:` 条目**(由 **Task 6** 落实)。
|
||||
/// (好消息:共享内存是匿名的 ⇒ **Pod 重启即清空全部 `ch:`**;
|
||||
/// 只有「不重启就改池子」才会踩到。)
|
||||
pub fn cool_down(route: &str, idx: usize) {
|
||||
let name = format!("{route}:{idx}");
|
||||
let until = util::now() + config::COOLDOWN_SECS;
|
||||
@@ -390,6 +407,36 @@ pub fn cool_down(route: &str, idx: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 哪些**顺位**失败了(纯函数,可单测)。
|
||||
///
|
||||
/// * `all_failed` = 最终状态是 403/5xx ⇒ 整条换源链都失败 ⇒ 全部顺位都冷却;
|
||||
/// * `slot` = 换源链写下的**失败顺位**(响应头 `X-Cache-Failed-Slot`)。
|
||||
///
|
||||
/// ⚠️ `Some(k)` ⇒ 冷却 **`0..=k`(整段)**,**不是**只冷却第 k 跳:
|
||||
/// 走到第 k 跳说明 `slots[0..=k]` **全都失败过**(前面几跳正是因为失败
|
||||
/// 才换到这里的)。
|
||||
/// 只冷却最后一跳 ⇒ **首选源永远不会被踢出轮转** ⇒ 每次请求都要先撞一次
|
||||
/// 死源才换源 ⇒ **熔断形同虚设**。
|
||||
/// (2026-10-30 pre-flight 扫描 R34 / 裁决 R-T5-4)
|
||||
///
|
||||
/// `None` + 非 `all_failed` ⇒ **没换过源** ⇒ 不冷却任何源。
|
||||
///
|
||||
/// ⚠️ 上界裁剪:返回的顺位**不会超过 `config::MAX_SLOTS - 1`**。
|
||||
/// 换源链只有 `MAX_SLOTS` 跳 ⇒ 更大的顺位不可能出现;
|
||||
/// 但 `slot` 来自**响应头**(外部可控的字符串)⇒ 必须裁剪,
|
||||
/// 否则一个 `X-Cache-Failed-Slot: 18446744073709551615` 就能让本函数
|
||||
/// 分配一个天文大小的 `Vec`(OOM)。
|
||||
pub fn failed_slots(all_failed: bool, slot: Option<usize>) -> Vec<usize> {
|
||||
if all_failed {
|
||||
return (0..config::MAX_SLOTS).collect();
|
||||
}
|
||||
let Some(k) = slot else {
|
||||
return Vec::new();
|
||||
};
|
||||
let last = k.min(config::MAX_SLOTS - 1);
|
||||
(0..=last).collect()
|
||||
}
|
||||
|
||||
/// 本次请求的散列种子:优先用 `$request_id`(每请求唯一 ⇒ 冷请求天然分散),
|
||||
/// 拿不到时退化为 URI+args 的散列。
|
||||
pub fn hash_of_request(r: *mut ngx_http_request_t) -> u64 {
|
||||
@@ -450,7 +497,7 @@ pub fn build_target(route: &str, tail: &str, base: &str, args: &str) -> String {
|
||||
/// 判据是**逐字节比较**:只有客户端放在 Authorization 里的值等于本次鉴权用的
|
||||
/// 那把 `sk_` 才丢弃;换任何别的值(真上游 token)都照传。
|
||||
///
|
||||
/// ⚠️ 第 1 条必须**先判**且不能被跳过:`auth_header` 只认客户端的头是不够的
|
||||
/// ⚠️ 第 1 条必须**先判**且不能被跳过:本函数只认客户端的头是不够的
|
||||
/// ——那样「配了凭据的路由」永远下发不了凭据,而且客户端带的是 `sk_` 时会被
|
||||
/// 第 3 条抹成空(实测症状:管理台配了 token,上游仍收到空 Authorization,
|
||||
/// 而测试里「未配凭据 → 不下发」那条却通过,很容易误判成上游问题)。
|
||||
@@ -480,13 +527,6 @@ fn auth_header_for(r: *mut ngx_http_request_t, configured: &str, allow_client: b
|
||||
if bare == dk { String::new() } else { raw }
|
||||
}
|
||||
|
||||
/// 兼容旧调用点(单源语义:允许转发客户端凭据)。
|
||||
///
|
||||
/// 保留它是为了**语义不变**:单源路由今天的透传行为一字不改。
|
||||
pub fn auth_header(r: *mut ngx_http_request_t, configured: &str) -> String {
|
||||
auth_header_for(r, configured, true)
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 请求级 memo(一个请求只查一次上游表)
|
||||
// ===========================================================================
|
||||
@@ -496,6 +536,24 @@ pub fn auth_header(r: *mut ngx_http_request_t, configured: &str) -> String {
|
||||
/// ⚠️ 本体由 **nginx 请求池**分配(`Pool::allocate` 会注册池 cleanup,
|
||||
/// 负责 drop 内部的 `Vec`/`String`)⇒ 请求结束随池回收,
|
||||
/// 不跨请求、不泄漏。**不要**改成 `Box`(那会绕过请求池生命周期)。
|
||||
///
|
||||
/// ## 取舍:同时持 `up` 与 `sources`(源列表双份常驻)
|
||||
///
|
||||
/// `up`(路由级配置)与 `sources`(该路由的有效源列表)在多源下**内容重叠**
|
||||
/// ——`sources` 就是从 `up` 派生的(`upstreams::effective_sources`),
|
||||
/// 于是同一个请求里源信息**存了两份**。
|
||||
///
|
||||
/// 之所以仍然两份,是为了让「取源」(`picked_source(sources, …)`)与
|
||||
/// 「取路由级凭据」(`effective_key(up, src)`)都只做**借用**、不重算:
|
||||
/// 若只留 `sources`,路由级 `key` 就得另找地方存(要么再加一个字段,
|
||||
/// 要么把 `effective_key` 改成在 `sources` 里翻找——后者会把
|
||||
/// 「源自己的 key 优先、路由级兜底」的语义藏进数据里,更难读)。
|
||||
///
|
||||
/// 代价是每请求多一份 `Vec<CacheSource>` 的常驻内存(源数 × 每源一串
|
||||
/// URL/key/note,通常几百字节 ⇒ 每请求几百字节)——相对于 nginx 自己
|
||||
/// 每请求几十次分配,这个量级可接受;换来的是**零重算、零重复查表**。
|
||||
/// 若将来源数涨到几十个、这份开销变成问题,再考虑让 `sources` 借用
|
||||
/// `up` 的存储。
|
||||
struct Memo {
|
||||
/// 本次请求的路由(自检用:memo 与调用方的路由必须一致)。
|
||||
route: &'static str,
|
||||
@@ -550,6 +608,12 @@ unsafe fn memo_of(r: *mut ngx_http_request_t) -> Option<*const Memo> {
|
||||
if v.is_null() || (*v).not_found() != 0 || (*v).data.is_null() {
|
||||
return None;
|
||||
}
|
||||
// ⚠️ 取巧护栏(F6):值槽里存的是**指针**(不是字符串)⇒ `len` 必须恒为 0。
|
||||
// 若哪天有人给 `$cache_ctx` 加了 `NOCACHEABLE`、或改了 `memo_get` 里的
|
||||
// `set_len`,nginx 会把值槽当**字符串**处理 ⇒ 指针被当字符串读/拷
|
||||
// ⇒ **静默**出错(不报错、只是拿到垃圾)。
|
||||
// `debug_assert!` 在 release 构建里被消掉 ⇒ 运行时零开销。
|
||||
debug_assert_eq!((*v).len(), 0, "$cache_ctx 的值槽只存指针,len 必须恒为 0");
|
||||
// 值槽里存的是 `Memo` 的指针(不是字符串)
|
||||
Some((*v).data as *const Memo)
|
||||
}
|
||||
@@ -616,7 +680,11 @@ pub fn upstream_configured(r: *mut ngx_http_request_t, route: &str) -> bool {
|
||||
///
|
||||
/// 正确做法(与 `handlers.rs` 读 `$upstream_cache_status` 同一套):
|
||||
/// postconfig 取一次索引,运行时用 `ngx_http_get_indexed_variable()` 读。
|
||||
pub fn read_pick_var(r: *mut ngx_http_request_t) -> String {
|
||||
///
|
||||
/// `pub(crate)`:Task 5 的 `handlers::cool_down_failed` 要用它把
|
||||
/// 「失败顺位」映射回**本次请求实际用的源下标**(R-T5-5:以 `$cache_pick`
|
||||
/// 为真相源,不另查上游表)。
|
||||
pub(crate) fn read_pick_var(r: *mut ngx_http_request_t) -> String {
|
||||
let idx = CACHE_PICK_IDX.load(Ordering::Relaxed);
|
||||
if idx < 0 {
|
||||
return String::new();
|
||||
@@ -661,23 +729,6 @@ fn compute_pick(
|
||||
Some(select(sources.len(), hash_of_request(r), &cooled))
|
||||
}
|
||||
|
||||
/// 取本次请求的选源结果(**请求级 memo**)。
|
||||
///
|
||||
/// 首选 memo(与 target/auth/host 同源同槽位);memo 不可用时读**已缓存**的
|
||||
/// `$cache_pick`(同一请求内 nginx 只算一次)——**不再自己查上游表**。
|
||||
pub fn pick_of(r: *mut ngx_http_request_t, route: &str) -> Option<[usize; config::MAX_SLOTS]> {
|
||||
// 首选:请求级 memo(与 target/auth/host 同源同槽位)
|
||||
// SAFETY: r 有效;memo 的路由必须与本路由一致(不一致 ⇒ fail-closed)
|
||||
if let Some(memo) = unsafe { memo_for(r, route) } {
|
||||
// SAFETY: 指针指向请求池里的 Memo,请求存活期间有效
|
||||
let m = unsafe { &*memo };
|
||||
return Some(m.slots);
|
||||
}
|
||||
// 兜底:memo 不可用(索引未解析 / 上游未配置)⇒ 读已缓存的 $cache_pick
|
||||
let raw = read_pick_var(r);
|
||||
parse_pick(&raw)
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 变量求值
|
||||
// ===========================================================================
|
||||
@@ -805,6 +856,13 @@ unsafe fn memo_get(r: *mut ngx_http_request_t, v: *mut ngx_http_variable_value_t
|
||||
if p.is_null() {
|
||||
return memo_not_found(v);
|
||||
}
|
||||
// ⚠️ 取巧护栏(F6):请求池分配 ⇒ 指针必须对齐到 `Memo`。
|
||||
// 不对齐 ⇒ `&*memo` 就是未定义行为(且多半不崩 ⇒ 更难查)。
|
||||
debug_assert_eq!(
|
||||
p as usize % core::mem::align_of::<Memo>(),
|
||||
0,
|
||||
"请求池分配的 Memo 指针必须对齐"
|
||||
);
|
||||
(*v).data = p as *mut u8;
|
||||
(*v).set_len(0);
|
||||
(*v).set_valid(1);
|
||||
@@ -954,6 +1012,55 @@ mod tests {
|
||||
assert_eq!(effective_key(&up, &srcs[0]), "ROUTEKEY");
|
||||
}
|
||||
|
||||
// F1:路由级 key 会被**复制给每一个没配自己凭据的源** —— 多源路由
|
||||
// 不应配路由级 key(由 Task 6 强制)。这里把**当前语义**钉住,
|
||||
// 免得 Task 6 改语义时无声漂移。
|
||||
#[test]
|
||||
fn route_level_key_is_copied_to_every_source_in_a_multi_source_route() {
|
||||
let up = crate::upstreams::decode("https://a\nROUTEKEY\nproxy\nv2\nhttps://b\n\nhttps://c\n");
|
||||
let srcs = crate::upstreams::effective_sources(&up);
|
||||
assert_eq!(srcs.len(), 2); // 多源路由
|
||||
// 两个源都没配自己的凭据 ⇒ **都**拿到路由级 key
|
||||
assert_eq!(effective_key(&up, &srcs[0]), "ROUTEKEY");
|
||||
assert_eq!(effective_key(&up, &srcs[1]), "ROUTEKEY");
|
||||
// 源自己配了凭据 ⇒ 用自己的,不受路由级影响
|
||||
let up2 = crate::upstreams::decode("https://a\nROUTEKEY\nproxy\nv2\nhttps://b\nSRCKEY\n");
|
||||
let srcs2 = crate::upstreams::effective_sources(&up2);
|
||||
assert_eq!(effective_key(&up2, &srcs2[0]), "SRCKEY");
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// 失败顺位 → 该冷却哪些顺位(R-T5-4)
|
||||
// -----------------------------------------------------------------
|
||||
#[test]
|
||||
fn failed_slots_all_failed_cools_every_slot() {
|
||||
assert_eq!(failed_slots(true, None), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_slots_some_zero_cools_only_first_slot() {
|
||||
assert_eq!(failed_slots(false, Some(0)), vec![0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_slots_some_one_cools_the_whole_prefix() {
|
||||
// ⚠️ 整段 0..=k(不是只冷却第 k 跳):走到第 1 跳说明第 0 跳也失败过
|
||||
assert_eq!(failed_slots(false, Some(1)), vec![0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_slots_none_cools_nothing() {
|
||||
assert_eq!(failed_slots(false, None), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_slots_clamps_out_of_range_slot() {
|
||||
// 响应头是外部可控的 ⇒ 越界顺位必须被裁到 MAX_SLOTS-1
|
||||
// (否则一个恶意头就能让本函数分配天文大小的 Vec)
|
||||
assert_eq!(failed_slots(false, Some(99)), vec![0, 1, 2]);
|
||||
assert_eq!(failed_slots(false, Some(usize::MAX)), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_auth_not_forwarded_on_multi_source_routes_except_docker() {
|
||||
// 多源 + 没有任何配置凭据 ⇒ 不下发客户端凭据(R21/R33)
|
||||
|
||||
+118
-3
@@ -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
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -15,8 +15,12 @@
|
||||
//!
|
||||
//! ## 装配点(gateway)
|
||||
//!
|
||||
//! * `preconfig` —— 注册五个只读变量:`$cache_target` / `$cache_host` /
|
||||
//! `$cache_upstream_key` / `$cache_eco` / `$cache_key`(见 [`cache`])
|
||||
//! * `preconfig` —— 注册**十一个对外只读变量 + 一个内部变量**:
|
||||
//! 对外的:`$cache_target` / `$cache_host` / `$cache_upstream_key` /
|
||||
//! `$cache_eco` / `$cache_key` / `$cache_auth` / `$cache_target_alt` /
|
||||
//! `$cache_target_alt2` / `$cache_auth_alt` / `$cache_auth_alt2` /
|
||||
//! `$cache_pick`;内部的:`$cache_ctx`(请求级 memo 的载体,
|
||||
//! 值槽里存指针,不是字符串)(见 [`cache`])
|
||||
//! * `postconfig` —— 预取 `$upstream_cache_status` / `$scheme` 变量索引、
|
||||
//! 识别 proxy_cache 容量区([`zones`],供容量面板读数与清理),
|
||||
//! 并注册 access(鉴权)+ log(计量)两个 handler
|
||||
|
||||
Reference in new issue
Block a user