fix(cache): 换源链重跑 ACCESS 阶段不该重复扣配额
- nginx 的 error_page → 命名 location 会把 phase_handler 重置到 REWRITE 起点 ⇒ 每一跳都重跑本插件的 access handler ⇒ 一个客户端请求走完 3 跳 被扣 3 次配额(平时 1 次)⇒ 上游一挂轮转配额只剩 1/3,客户端提前吃 429。 - Memo 加 ChargeGate(Cell<bool> 内部可变性 ⇒ *const Memo 的取法一个字不用改): claim() 首次 true、之后 false;claim_quota_charge() 拿不到 memo 时 fail-closed 照常计费(宁可多扣,不白送配额)。 - access handler 改成只在 claim 成功时才调 auth::check_quota。 - 前提:$cache_ctx 不带 NOCACHEABLE ⇒ 同一请求拿到同一份 memo ⇒ 闸门在换源链上有效。 Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
85f64f2f1c
commit
c83d4c7515
2 files changed
+112
-3
No files matched your search
@@ -37,6 +37,7 @@
|
||||
//! 不跨请求、不泄漏。
|
||||
|
||||
use core::sync::atomic::{AtomicIsize, Ordering};
|
||||
use std::cell::Cell;
|
||||
|
||||
use ngx::core::{Pool, Status};
|
||||
use ngx::ffi::{
|
||||
@@ -549,6 +550,52 @@ fn auth_header_for(r: *mut ngx_http_request_t, configured: &str, allow_client: b
|
||||
// 请求级 memo(一个请求只查一次上游表)
|
||||
// ===========================================================================
|
||||
|
||||
/// 本请求的**计费闸**:配额只能扣**一次**。
|
||||
///
|
||||
/// ## 为什么需要它
|
||||
///
|
||||
/// nginx 的 `error_page 502 504 403 = @<name>;` 会调 `ngx_http_named_location()`
|
||||
/// (nginx 1.30.4 `src/http/ngx_http_core_module.c:2602`):
|
||||
/// 它把 `r->phase_handler` 重置到 `location_rewrite_index`
|
||||
/// (`src/http/ngx_http.c:510-511`)⇒ **REWRITE → … → ACCESS → … 全部再跑一遍**。
|
||||
///
|
||||
/// ⇒ **换源链的每一跳都会重跑本插件的 ACCESS handler**
|
||||
/// ⇒ 若 ACCESS 阶段每次都调 `auth::check_quota`,一个客户端请求走完 3 跳
|
||||
/// 就被**扣 3 次配额**(正常不换源时是 1 次)⇒ 上游一挂,轮转配额消耗
|
||||
/// 速度就是平时的 1/3 ⇒ 客户端提前吃 429。
|
||||
///
|
||||
/// ## 闸门挂在哪
|
||||
///
|
||||
/// 挂在**请求级 memo**([`Memo`])上 ⇒ 同一请求内无论 ACCESS 阶段跑几次,
|
||||
/// 拿到的都是**同一份** memo ⇒ 闸门状态自然共享。
|
||||
///
|
||||
/// ⚠️ 前提:`$cache_ctx` 注册时**不带** `NOCACHEABLE`
|
||||
/// ⇒ nginx 把值缓存在 `r->variables[index]` ⇒ 内部重定向**不会**清
|
||||
/// `r->variables` ⇒ 同一请求拿到同一份 memo。
|
||||
/// **不要**给 `$cache_ctx` 加 `NOCACHEABLE`(那会破坏 R-T4-2 的整个前提)。
|
||||
///
|
||||
/// 用**内部可变性**(`Cell<bool>`)⇒ memo 仍可用 `*const Memo` 取
|
||||
/// ([`memo_of`] / [`memo_for`] 一个字都不用改),不需要 `&mut`。
|
||||
#[derive(Default)]
|
||||
pub struct ChargeGate {
|
||||
/// 本请求是否**已经**扣过配额。
|
||||
charged: Cell<bool>,
|
||||
}
|
||||
|
||||
impl ChargeGate {
|
||||
/// 认领本次计费:首次 ⇒ `true`(该扣);已扣过 ⇒ `false`(别再扣)。
|
||||
///
|
||||
/// 单调、幂等:多次调用只有第一次返回 `true`。
|
||||
pub fn claim(&self) -> bool {
|
||||
if self.charged.get() {
|
||||
false
|
||||
} else {
|
||||
self.charged.set(true);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一个请求内的选源结果 + 源列表。
|
||||
///
|
||||
/// ⚠️ 本体由 **nginx 请求池**分配(`Pool::allocate` 会注册池 cleanup,
|
||||
@@ -581,6 +628,8 @@ struct Memo {
|
||||
sources: Vec<CacheSource>,
|
||||
/// 路由级上游配置(`effective_key` 的回落来源)。
|
||||
up: upstreams::Decoded,
|
||||
/// 本请求的计费闸(换源链重跑 ACCESS 阶段 ⇒ 配额只扣一次)。
|
||||
charge: ChargeGate,
|
||||
}
|
||||
|
||||
impl Memo {
|
||||
@@ -600,6 +649,7 @@ impl Memo {
|
||||
slots,
|
||||
sources,
|
||||
up,
|
||||
charge: ChargeGate::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -685,6 +735,33 @@ pub fn upstream_configured(r: *mut ngx_http_request_t, route: &str) -> bool {
|
||||
unsafe { memo_for(r, route) }.is_some()
|
||||
}
|
||||
|
||||
/// 认领本请求的**配额扣减**(换源链的每一跳都会重跑 ACCESS 阶段 ⇒ 只扣一次)。
|
||||
///
|
||||
/// - 返回 `true` ⇒ **该扣**配额(本次请求的首次 ACCESS);
|
||||
/// - 返回 `false` ⇒ 本请求已扣过,**别再扣**(否则一个请求走完 3 跳扣 3 次)。
|
||||
///
|
||||
/// ⚠️ **fail-closed**:拿不到本请求的 memo ⇒ 返回 `true`(照常计费)。
|
||||
/// 计费闸失灵时**宁可多扣,也不能白送配额**。
|
||||
///
|
||||
/// ⚠️ 必须在 [`upstream_configured`](建 memo)**之后**调用 ⇒ memo 一定存在;
|
||||
/// 挪到它之前会让闸门恒为「未扣过」⇒ 退化成「每跳都扣」。
|
||||
///
|
||||
/// ⚠️ 前提:`$cache_ctx` **不带** `NOCACHEABLE` ⇒ nginx 把值缓存在
|
||||
/// `r->variables[index]`,内部重定向**不清** `r->variables`
|
||||
/// ⇒ 同一请求拿到**同一份** memo ⇒ 闸门在换源链上有效。
|
||||
///
|
||||
/// `r` 必须是 nginx 传入的有效请求指针。
|
||||
pub(crate) fn claim_quota_charge(r: *mut ngx_http_request_t, route: &str) -> bool {
|
||||
// SAFETY: r 有效;memo 的路由必须与本路由一致
|
||||
let Some(m) = (unsafe { memo_for(r, route) }) else {
|
||||
// 拿不到 memo ⇒ fail-closed:照常计费
|
||||
return true;
|
||||
};
|
||||
// SAFETY: 指针指向请求池里的 Memo,请求存活期间有效;
|
||||
// ChargeGate 用内部可变性(Cell)⇒ 只需共享引用
|
||||
unsafe { (*m).charge.claim() }
|
||||
}
|
||||
|
||||
/// 取本请求 memo 里的**有效源个数**(log 阶段用)。
|
||||
///
|
||||
/// `pub(crate)`:Task 5 的 `handlers::cool_down_failed` 要用它做
|
||||
@@ -994,6 +1071,28 @@ mod tests {
|
||||
assert_ne!(fnv1a(b"abc"), fnv1a(b"abd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn charge_gate_claims_only_once() {
|
||||
// ⭐ 换源链的每一跳都会重跑 ACCESS 阶段 ⇒ 配额只能扣一次。
|
||||
let gate = ChargeGate::default();
|
||||
// 首次 ⇒ 该扣
|
||||
assert!(gate.claim());
|
||||
// 再来两次 ⇒ 都不该扣
|
||||
assert!(!gate.claim());
|
||||
assert!(!gate.claim());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn charge_gate_is_per_instance() {
|
||||
// 两个请求 = 两份 memo = 两个独立的闸门 ⇒ 各自都能扣一次
|
||||
let a = ChargeGate::default();
|
||||
let b = ChargeGate::default();
|
||||
assert!(a.claim());
|
||||
assert!(b.claim());
|
||||
assert!(!a.claim());
|
||||
assert!(!b.claim());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_starts_at_hash_position() {
|
||||
// 4 个源全部健康:起点 = hash % 4 = 2
|
||||
|
||||
+13
-3
@@ -356,9 +356,19 @@ impl HttpRequestHandler for CacheAccessHandler {
|
||||
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;
|
||||
// ⚠️ 换源链的每一跳都会**重跑 ACCESS 阶段**(nginx 1.30.4 的
|
||||
// `error_page … = @<name>;` → `ngx_http_named_location()` 会把
|
||||
// `r->phase_handler` 重置到 REWRITE 起点 ⇒ 阶段全部再跑一遍)
|
||||
// ⇒ 这里会被执行多次 ⇒ **配额只能扣一次**。
|
||||
// 计费闸挂在**请求级 memo** 上(`$cache_ctx` 不带 NOCACHEABLE
|
||||
// ⇒ nginx 把值缓存在 `r->variables[index]`,内部重定向不清
|
||||
// `r->variables` ⇒ 同一请求拿到同一份 memo)。
|
||||
// ⚠️ 必须在上面的 `upstream_configured`(建 memo)**之后**。
|
||||
if cache::claim_quota_charge(r, route) {
|
||||
// SAFETY: r 由 nginx 传入且有效;check_quota 只读请求头与共享内存
|
||||
if let Some(resp) = unsafe { auth::check_quota(r, &username, rpm, daily) } {
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
|
||||
// 放行:数据面交给 nginx `proxy_cache`(命中不产生任何模块开销)
|
||||
|
||||
Reference in new issue
Block a user