Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d1bf44eca | ||
|
|
417c8c9be2 | ||
|
|
fefd57ac7f | ||
|
|
c83d4c7515 | ||
|
|
85f64f2f1c | ||
|
|
dc49c758fc | ||
|
|
ac1c51d374 | ||
|
|
ed7fe3cac8 | ||
|
|
1ab8a84901 | ||
|
|
c43ad3749e | ||
|
|
34eb8c7d0b | ||
|
|
f412ec3dcc | ||
|
|
85ec38aa2d | ||
|
|
838f497290 |
No files matched your search
@@ -15,3 +15,6 @@ ngx = { path = "../ipass-core/rust/vendor/ngx-rust" }
|
|||||||
nginx-sys = { path = "../ipass-core/rust/vendor/ngx-rust/nginx-sys" }
|
nginx-sys = { path = "../ipass-core/rust/vendor/ngx-rust/nginx-sys" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
|
||||||
|
[profile.dev]
|
||||||
|
incremental = false
|
||||||
+35
-3
@@ -110,8 +110,17 @@ fn h_admin_overview(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
|||||||
|
|
||||||
/// 新增/修改一个路由的上游。
|
/// 新增/修改一个路由的上游。
|
||||||
///
|
///
|
||||||
/// 表单字段:`route`(必填) / `base` / `key` / `name` / `desc` / `note` / `enabled`。
|
/// 表单字段:`route`(必填) / `base` / `key` / `name` / `desc` / `note` / `enabled`
|
||||||
|
/// / `sources`。
|
||||||
/// `base` 留空 = 保留原值;`key` 留空 = **清空**(语义差异见 `upstreams::upsert`)。
|
/// `base` 留空 = 保留原值;`key` 留空 = **清空**(语义差异见 `upstreams::upsert`)。
|
||||||
|
///
|
||||||
|
/// ⚠️ **`sources` 的值是一个「JSON 数组的字符串」**,不是 JSON 数组本身。
|
||||||
|
/// 原因:`ipass_core::http::params()` 解析 JSON body 时,数组/对象类型的字段
|
||||||
|
/// 会被**丢掉** ⇒ 直接传 `{"sources": [...]}` 会被**静默忽略**
|
||||||
|
/// (看起来「保存成功」但源池根本没变)。
|
||||||
|
/// 正确写法:
|
||||||
|
/// `sources=[{"id":"goproxy-cn","url":"https://goproxy.cn","key":"","note":""}]`
|
||||||
|
/// (表单编码时整个数组 URL 编码后作为值传;JSON body 时值是字符串,串里再放 JSON)。
|
||||||
fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||||
let p = http::params(r);
|
let p = http::params(r);
|
||||||
let route_raw = p.get("route").cloned().unwrap_or_default();
|
let route_raw = p.get("route").cloned().unwrap_or_default();
|
||||||
@@ -121,6 +130,25 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
|||||||
None => true,
|
None => true,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// sources:表单里的 JSON 数组字符串。
|
||||||
|
// 字段不提交(或提交空串)⇒ None ⇒ 不改现有源池;
|
||||||
|
// 提交合法空数组 `[]` ⇒ Some(vec![]) ⇒ 清空(退回单 base);
|
||||||
|
// 提交非空数组 ⇒ 覆盖。
|
||||||
|
let sources = match p.get("sources") {
|
||||||
|
Some(raw) if !util::trim(raw).is_empty() => match upstreams::parse_sources(raw) {
|
||||||
|
Ok(v) => Some(v),
|
||||||
|
Err(e) => {
|
||||||
|
util::log_err(&format!("[cache] sources 参数解析失败:{e}"));
|
||||||
|
return http::fail(
|
||||||
|
r,
|
||||||
|
HTTPStatus::BAD_REQUEST,
|
||||||
|
&format!("sources 参数非法:{e}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
// ⚠️ key 用「字段是否出现」区分「不改」与「清空」,所以这里不能把
|
// ⚠️ key 用「字段是否出现」区分「不改」与「清空」,所以这里不能把
|
||||||
// `p.get("key")` 归一成空串——前端删掉输入框内容时应提交 `key=`(空串)。
|
// `p.get("key")` 归一成空串——前端删掉输入框内容时应提交 `key=`(空串)。
|
||||||
let res = upstreams::upsert(
|
let res = upstreams::upsert(
|
||||||
@@ -131,6 +159,7 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
|||||||
p.get("desc"),
|
p.get("desc"),
|
||||||
enabled,
|
enabled,
|
||||||
p.get("note"),
|
p.get("note"),
|
||||||
|
sources.as_deref(),
|
||||||
);
|
);
|
||||||
|
|
||||||
match res {
|
match res {
|
||||||
@@ -138,8 +167,10 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
|||||||
let route = util::trim(&route_raw).to_ascii_lowercase();
|
let route = util::trim(&route_raw).to_ascii_lowercase();
|
||||||
let active = upstreams::lookup(&route).is_some();
|
let active = upstreams::lookup(&route).is_some();
|
||||||
util::log_notice(&format!(
|
util::log_notice(&format!(
|
||||||
"[cache] 保存上游 route={route} base={} enabled={} active={active}",
|
"[cache] 保存上游 route={route} base={} sources={} enabled={} active={active}",
|
||||||
item.base, item.enabled
|
item.base,
|
||||||
|
item.sources.len(),
|
||||||
|
item.enabled
|
||||||
));
|
));
|
||||||
http::ok(
|
http::ok(
|
||||||
r,
|
r,
|
||||||
@@ -147,6 +178,7 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
|||||||
"route": route,
|
"route": route,
|
||||||
"base": item.base,
|
"base": item.base,
|
||||||
"key_set": !item.key.is_empty(),
|
"key_set": !item.key.is_empty(),
|
||||||
|
"source_count": item.sources.len(),
|
||||||
"enabled": item.enabled,
|
"enabled": item.enabled,
|
||||||
"active": active,
|
"active": active,
|
||||||
"entry": upstreams::entry_base(r),
|
"entry": upstreams::entry_base(r),
|
||||||
|
|||||||
+1023
-37
File diff suppressed because it is too large.
Load diff
+18
-2
@@ -25,6 +25,17 @@ pub const KEY_CX_PREFIX: &[u8] = b"cx:";
|
|||||||
/// 与 `cx:` 分属两片键空间:前者是**配置**,后者是**读数**。
|
/// 与 `cx:` 分属两片键空间:前者是**配置**,后者是**读数**。
|
||||||
pub const KEY_CACHE_PREFIX: &str = "cache:";
|
pub const KEY_CACHE_PREFIX: &str = "cache:";
|
||||||
|
|
||||||
|
/// 源冷却的键前缀:`ch:<route>:<源下标>` → 值 `"1"`,靠 `expires_at` 自动过期。
|
||||||
|
///
|
||||||
|
/// 与 `cx:`(配置)、`cache:`(读数)分属三片键空间:这里是**运行时状态**。
|
||||||
|
pub const KEY_CH_PREFIX: &[u8] = b"ch:";
|
||||||
|
|
||||||
|
/// 失败源的冷却时长(秒)。短到能自愈,长到能挡住一次抽风窗口。
|
||||||
|
pub const COOLDOWN_SECS: i64 = 60;
|
||||||
|
|
||||||
|
/// 换源链长度:首选 + 备选 1 + 备选 2(conf 里固定三跳 ⇒ 这里固定 3)。
|
||||||
|
pub const MAX_SLOTS: usize = 3;
|
||||||
|
|
||||||
/// shm payload 内部的行分隔符(base / 上游 Key / mode)。
|
/// shm payload 内部的行分隔符(base / 上游 Key / mode)。
|
||||||
pub const PAYLOAD_SEP: char = '\n';
|
pub const PAYLOAD_SEP: char = '\n';
|
||||||
|
|
||||||
@@ -177,8 +188,13 @@ pub const CLIENT_HINTS: &[(&str, &str, &str)] = &[
|
|||||||
("go", "Go module proxy", "export GOPROXY={base}/go"),
|
("go", "Go module proxy", "export GOPROXY={base}/go"),
|
||||||
(
|
(
|
||||||
"cargo",
|
"cargo",
|
||||||
"crates.io 稀疏索引(包本体需另配 /cargo-dl/,见文档)",
|
"crates.io 稀疏索引(config.json 的 dl 已改写回本网关 ⇒ 包体也走网关)",
|
||||||
"mkdir -p ~/.cargo && printf '[registries.crates-io]\\nindex = \"sparse+{base}/cargo/\"\\n' >> ~/.cargo/config.toml",
|
// ⚠️ 必须是**源替换**:`[registries.crates-io] index = …` 会被 cargo
|
||||||
|
// **静默忽略**(继续用真正的 crates.io ⇒ 看着成功,其实没过网关)。
|
||||||
|
// 另需 `[registry] global-credential-providers`(否则 cargo 报
|
||||||
|
// "authenticated registries require a credential-provider"),
|
||||||
|
// token 放 credentials.toml。
|
||||||
|
"mkdir -p ~/.cargo && printf '[source.crates-io]\\nreplace-with = \"ipass\"\\n[source.ipass]\\nregistry = \"sparse+{base}/cargo/\"\\n[registries.ipass]\\nindex = \"sparse+{base}/cargo/\"\\n[registry]\\nglobal-credential-providers = [\"cargo:token\"]\\n' >> ~/.cargo/config.toml && printf '[registries.ipass]\\ntoken = \"sk_…\"\\n' >> ~/.cargo/credentials.toml",
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"pypi",
|
"pypi",
|
||||||
|
|||||||
+247
-12
@@ -25,23 +25,28 @@ use core::sync::atomic::{AtomicIsize, Ordering};
|
|||||||
|
|
||||||
use ngx::core::Status;
|
use ngx::core::Status;
|
||||||
use ngx::ffi::{
|
use ngx::ffi::{
|
||||||
ngx_conf_t, ngx_http_get_indexed_variable, ngx_http_get_variable_index, ngx_http_request_t,
|
ngx_conf_t, ngx_http_get_indexed_variable, ngx_http_get_variable, ngx_http_get_variable_index,
|
||||||
ngx_str_t, ngx_uint_t,
|
ngx_http_request_t, ngx_str_t, ngx_uint_t,
|
||||||
};
|
};
|
||||||
use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request};
|
use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request};
|
||||||
|
|
||||||
use ipass_core::{auth, http, plugin_registry, util};
|
use ipass_core::{auth, http, plugin_registry, util};
|
||||||
|
|
||||||
|
use crate::cache;
|
||||||
use crate::config;
|
use crate::config;
|
||||||
use crate::stats;
|
use crate::stats;
|
||||||
use crate::upstreams;
|
|
||||||
|
|
||||||
/// `$upstream_cache_status` 的变量索引(postconfig 解析一次,log 阶段复用)
|
/// `$upstream_cache_status` 的变量索引(postconfig 解析一次,log 阶段复用)
|
||||||
static CACHE_STATUS_IDX: AtomicIsize = AtomicIsize::new(-1);
|
static CACHE_STATUS_IDX: AtomicIsize = AtomicIsize::new(-1);
|
||||||
/// `$scheme` 的变量索引(管理 API 拼「下游地址」时要回显 http/https)
|
/// `$scheme` 的变量索引(管理 API 拼「下游地址」时要回显 http/https)
|
||||||
static SCHEME_IDX: AtomicIsize = AtomicIsize::new(-1);
|
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 模块的内建变量,
|
/// 为什么在 postconfig 而不是 preconfig:`$scheme` 是 core 模块的内建变量,
|
||||||
/// 本模块的 preconfig 早于变量全部注册完成,取 index 可能失败;postconfig
|
/// 本模块的 preconfig 早于变量全部注册完成,取 index 可能失败;postconfig
|
||||||
@@ -63,6 +68,36 @@ pub fn prefetch_indexes(cf: *mut ngx_conf_t) -> bool {
|
|||||||
}
|
}
|
||||||
CACHE_STATUS_IDX.store(i1 as isize, Ordering::Relaxed);
|
CACHE_STATUS_IDX.store(i1 as isize, Ordering::Relaxed);
|
||||||
SCHEME_IDX.store(i2 as isize, Ordering::Relaxed);
|
SCHEME_IDX.store(i2 as isize, Ordering::Relaxed);
|
||||||
|
|
||||||
|
// `$request_id` 是**可选**的:拿不到就退化为 URI 散列(见 cache::hash_of_request),
|
||||||
|
// 因此这里解析失败**不致命**——与上面两个不同,它们缺了会让核心功能不可用。
|
||||||
|
let mut rid = ngx_str_t {
|
||||||
|
len: "request_id".len() as usize,
|
||||||
|
data: b"request_id\0".as_ptr() as *mut u8,
|
||||||
|
};
|
||||||
|
// SAFETY: cf 由 nginx 传入且有效;ngx_str_t 指向栈上合法内存
|
||||||
|
let i3 = unsafe { ngx_http_get_variable_index(cf, &mut rid) };
|
||||||
|
REQUEST_ID_IDX.store(i3 as isize, Ordering::Relaxed);
|
||||||
|
|
||||||
|
// `$cache_pick`(本插件自己注册的变量)——运行时按**索引**读,
|
||||||
|
// 不用 ngx_http_get_variable 的名字查找(那个 API 的 key 是哈希桶号,
|
||||||
|
// 传 0 会间歇性查不中,详见 cache::read_pick_var 的注释)。
|
||||||
|
let mut cp = ngx_str_t {
|
||||||
|
len: "cache_pick".len() as usize,
|
||||||
|
data: b"cache_pick\0".as_ptr() as *mut u8,
|
||||||
|
};
|
||||||
|
// SAFETY: cf 由 nginx 传入且有效;ngx_str_t 指向栈上合法内存
|
||||||
|
let i4 = unsafe { ngx_http_get_variable_index(cf, &mut cp) };
|
||||||
|
if i4 < 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
crate::cache::set_pick_index(i4 as isize);
|
||||||
|
|
||||||
|
// 内部变量 `$cache_ctx`(请求级 memo 的载体)——同样按索引读。
|
||||||
|
if !crate::cache::prefetch_memo_index(cf) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,6 +107,12 @@ pub fn read_scheme(r: *mut ngx_http_request_t) -> String {
|
|||||||
unsafe { read_indexed(r, SCHEME_IDX.load(Ordering::Relaxed)) }
|
unsafe { read_indexed(r, SCHEME_IDX.load(Ordering::Relaxed)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 读当前请求的 `$request_id`(空串 = 拿不到,调用方自行退化)
|
||||||
|
pub fn read_request_id(r: *mut ngx_http_request_t) -> String {
|
||||||
|
// SAFETY: r 由 nginx 传入且有效;索引在 postconfig 已解析
|
||||||
|
unsafe { read_indexed(r, REQUEST_ID_IDX.load(Ordering::Relaxed)) }
|
||||||
|
}
|
||||||
|
|
||||||
/// 安全读取一个已索引变量的字符串值;拿不到返回空串。
|
/// 安全读取一个已索引变量的字符串值;拿不到返回空串。
|
||||||
unsafe fn read_indexed(r: *mut ngx_http_request_t, idx: isize) -> String {
|
unsafe fn read_indexed(r: *mut ngx_http_request_t, idx: isize) -> String {
|
||||||
if idx < 0 {
|
if idx < 0 {
|
||||||
@@ -94,10 +135,179 @@ pub fn read_cache_status(r: *mut ngx_http_request_t) -> String {
|
|||||||
unsafe { read_indexed(r, CACHE_STATUS_IDX.load(Ordering::Relaxed)) }
|
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;
|
||||||
|
}
|
||||||
|
// ⚠️ **先判 not_found,再碰 data / len**(两步走,别合成一个元组):
|
||||||
|
// nginx 的「未找到」分支(ngx_http_variables.c:998-1001)**只置 not_found**,
|
||||||
|
// **不动 data / len**;而这个值槽是 `ngx_palloc` 分配的(同文件 :725)
|
||||||
|
// ⇒ **不清零** ⇒ not_found 为真时 data / len 是**未初始化**的。
|
||||||
|
// 元组/逗号表达式会**按顺序求值全部元素** ⇒ 把 data/len 提到 not_found
|
||||||
|
// 之前读 ⇒ 未初始化读(UB)。故这里**提前 return**。
|
||||||
|
//
|
||||||
|
// ⚠️ 本函数走的是**按名查**(`ngx_http_get_variable`)⇒ 值槽是
|
||||||
|
// `ngx_palloc` 的**未清零**内存。
|
||||||
|
// 对比 `cache.rs::read_indexed_var`(按索引查):值槽在
|
||||||
|
// `r->variables[]` 里,是 `ngx_pcalloc` 的**清零**内存 ⇒ 那边没这个问题。
|
||||||
|
// SAFETY: v 非空 ⇒ 可读它的字段;nginx 保证了 not_found 已被写过
|
||||||
|
if unsafe { (*v).not_found() != 0 } {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// SAFETY: not_found 为假 ⇒ nginx 走的是 unknown_header 的**成功分支**
|
||||||
|
// (ngx_http_variables.c:1003-1011 / 1017-1029)⇒ data / len 都被写好了
|
||||||
|
let data = unsafe { (*v).data };
|
||||||
|
if data.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// SAFETY: 同上 ⇒ len 也已被 nginx 写好
|
||||||
|
let len = unsafe { (*v).len() as usize };
|
||||||
|
if len == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// SAFETY: 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 last = s.rsplit(',').next().unwrap_or(s).trim();
|
||||||
|
match last.parse::<usize>() {
|
||||||
|
Ok(v) => Some(v),
|
||||||
|
Err(_) => {
|
||||||
|
// ⚠️ **只在「有值但解析不出来」时告警**(D4):
|
||||||
|
// 之前这里是 `.ok()` ⇒ 静默吞掉 ⇒ 排障时看不到任何线索
|
||||||
|
// (换源链写坏了头 / conf 写了两次 / 上游塞了脏值,都表现为
|
||||||
|
// 「一个源都不冷却」,无从判断是「没失败」还是「解析失败」)。
|
||||||
|
// 「头不存在」走的是上面的 not_found 早退、「值为空」走 len==0
|
||||||
|
// 早退 ⇒ **都不在这里打**,避免正常请求(没失败过)在热路径上
|
||||||
|
// 无脑刷日志。
|
||||||
|
//
|
||||||
|
// ⚠️ 头值**可能来自上游**(`sent_http_` 读的是响应头全集)
|
||||||
|
// ⇒ 截断到 64 字符再打(免得灌日志);`{:?}` 会转义控制字符
|
||||||
|
// (免得伪造日志行)。
|
||||||
|
let shown: String = s.chars().take(64).collect();
|
||||||
|
util::log_warn(&format!(
|
||||||
|
"[cache] 响应头 X-Cache-Failed-Slot 的值无法解析为顺位号:{shown:?} —— 本次不冷却任何源"
|
||||||
|
));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 把失败的源打入冷却(`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)⇒ 与本次请求**实际用的源**严格一致;
|
||||||
|
/// 另查一次上游表拿到的是**此刻**的池子 ⇒ 管理员在请求中途改了池子就错位。
|
||||||
|
/// ⇒ 边界检查用的「源个数」也**从同一个请求级 memo 取**
|
||||||
|
/// (`cache::memo_source_count`,D3),不另查表、也不 clone 整份源列表:
|
||||||
|
/// 顺位下标与源个数因此处在**同一个下标空间**里,天然不会错位。
|
||||||
|
///
|
||||||
|
/// ⚠️ 调用点必须在 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;
|
||||||
|
};
|
||||||
|
// 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;
|
||||||
|
};
|
||||||
|
// 源个数(**只**用于边界检查;真相源是 $cache_pick,见上)
|
||||||
|
//
|
||||||
|
// ⚠️ **走请求级 memo**(Task 4 建的那份快照,D3):
|
||||||
|
// memo 里装的就是**本次请求选源时用的那份源列表** ⇒ 顺位下标
|
||||||
|
// (`$cache_pick`)与它是**同一个下标空间** ⇒ 边界检查天然成立。
|
||||||
|
// 这样 log 阶段**不必再查一次上游表、也不必 clone 整份源列表**
|
||||||
|
// (每次多一次 shm 读 + 逐行解码 + 一批 String 分配)。
|
||||||
|
//
|
||||||
|
// ⚠️ memo 拿不到 ⇒ 本请求**没有选过源** ⇒ `$cache_pick` 也拿不到
|
||||||
|
// (两者同源)⇒ 直接返回,不冷却任何源。
|
||||||
|
let Some(n_sources) = cache::memo_source_count(r, route) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if n_sources == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for slot in failed {
|
||||||
|
let Some(idx) = slots.get(slot) else { continue };
|
||||||
|
if *idx >= n_sources {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cache::cool_down(route, *idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ===========================================================================
|
// ===========================================================================
|
||||||
// access:统一 Key 鉴权 + 上游就绪检查
|
// access:统一 Key 鉴权 + 上游就绪检查
|
||||||
// ===========================================================================
|
// ===========================================================================
|
||||||
|
|
||||||
|
/// 401 响应:**必须带 `WWW-Authenticate`**,否则客户端不知道凭据怎么带。
|
||||||
|
///
|
||||||
|
/// core 的 `http::fail` 硬编码 `&[]`(加不了响应头)⇒ 这里自己拼。
|
||||||
|
/// cargo 不依赖这个头(它靠 config.json 里的 `auth-required` 决定是否附带 token),
|
||||||
|
/// 但 curl / npm / pip 这类客户端靠它触发「带凭据重试」。
|
||||||
|
fn fail_401(r: *mut ngx_http_request_t, msg: &str) -> Status {
|
||||||
|
let body = serde_json::json!({ "code": 401, "msg": msg }).to_string();
|
||||||
|
http::send_with(
|
||||||
|
r,
|
||||||
|
HTTPStatus::UNAUTHORIZED,
|
||||||
|
&body,
|
||||||
|
&[("WWW-Authenticate", "Bearer realm=\"ipass-cache\"")],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// 制品缓存 access handler。受管制 URI 由路由表(8 前缀)圈定;
|
/// 制品缓存 access handler。受管制 URI 由路由表(8 前缀)圈定;
|
||||||
/// R19 禁用 → fail-closed 404(数据面是鉴权后的磁盘读,放行=无鉴权读缓存盘)。
|
/// R19 禁用 → fail-closed 404(数据面是鉴权后的磁盘读,放行=无鉴权读缓存盘)。
|
||||||
pub struct CacheAccessHandler;
|
pub struct CacheAccessHandler;
|
||||||
@@ -123,7 +333,15 @@ impl HttpRequestHandler for CacheAccessHandler {
|
|||||||
// 上游未配置:**必须在这里拦**。否则变量式 proxy_pass 拿到空
|
// 上游未配置:**必须在这里拦**。否则变量式 proxy_pass 拿到空
|
||||||
// `$cache_target`,nginx 会报 500 `no host in upstream`,
|
// `$cache_target`,nginx 会报 500 `no host in upstream`,
|
||||||
// 排障时会误以为是缓存本身坏了。
|
// 排障时会误以为是缓存本身坏了。
|
||||||
if upstreams::lookup(route).is_none() {
|
//
|
||||||
|
// ⚠️ 走**请求级 memo**(`cache::upstream_configured`)而不是
|
||||||
|
// `upstreams::lookup()`:后者会**再查一次上游表** ⇒
|
||||||
|
// 一个请求查两次表(access 一次 + 变量求值一次),
|
||||||
|
// 且两次快照可能不同(中间配置被改)⇒ 判「未配置」与
|
||||||
|
// 实际选中的源对不上。
|
||||||
|
// memo 在这里**第一次**被建立(查表发生在此),
|
||||||
|
// 后面数据面变量求值时**复用同一份快照**(R-T4-2)。
|
||||||
|
if !cache::upstream_configured(r, route) {
|
||||||
util::log_warn(&format!(
|
util::log_warn(&format!(
|
||||||
"[cache] 路由 {route} 未配置上游,拒绝 {uri}(client={})",
|
"[cache] 路由 {route} 未配置上游,拒绝 {uri}(client={})",
|
||||||
http::remote_addr(r)
|
http::remote_addr(r)
|
||||||
@@ -138,10 +356,11 @@ impl HttpRequestHandler for CacheAccessHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---- 统一 Key 鉴权(与 LLM / API 代理同一把 sk_、同一份配额)----
|
// ---- 统一 Key 鉴权(与 LLM / API 代理同一把 sk_、同一份配额)----
|
||||||
let Some(key) = auth::downstream_key(r) else {
|
// 携带方式:Authorization: Bearer sk_… / Authorization: sk_…(cargo 裸 token)
|
||||||
return http::fail(
|
// / x-api-key: sk_… / api-key: sk_…
|
||||||
|
let Some(key) = crate::key::downstream_key(r) else {
|
||||||
|
return fail_401(
|
||||||
r,
|
r,
|
||||||
HTTPStatus::UNAUTHORIZED,
|
|
||||||
"缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带",
|
"缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带",
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -150,12 +369,22 @@ impl HttpRequestHandler for CacheAccessHandler {
|
|||||||
"[cache] API Key 校验失败 route={route} client={}",
|
"[cache] API Key 校验失败 route={route} client={}",
|
||||||
http::remote_addr(r)
|
http::remote_addr(r)
|
||||||
));
|
));
|
||||||
return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或已失效");
|
return fail_401(r, "API Key 无效或已失效");
|
||||||
};
|
};
|
||||||
|
|
||||||
// SAFETY: r 由 nginx 传入且有效;check_quota 只读请求头与共享内存
|
// ⚠️ 换源链的每一跳都会**重跑 ACCESS 阶段**(nginx 1.30.4 的
|
||||||
if let Some(resp) = unsafe { auth::check_quota(r, &username, rpm, daily) } {
|
// `error_page … = @<name>;` → `ngx_http_named_location()` 会把
|
||||||
return resp;
|
// `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`(命中不产生任何模块开销)
|
// 放行:数据面交给 nginx `proxy_cache`(命中不产生任何模块开销)
|
||||||
@@ -192,6 +421,12 @@ impl HttpRequestHandler for CacheLogHandler {
|
|||||||
// 生态从 URI 首段推导(直读 r->uri,不依赖任何 nginx 变量)
|
// 生态从 URI 首段推导(直读 r->uri,不依赖任何 nginx 变量)
|
||||||
let eco = config::eco_of_uri(&http::uri(r));
|
let eco = config::eco_of_uri(&http::uri(r));
|
||||||
stats::record(eco, &status, util::now());
|
stats::record(eco, &status, util::now());
|
||||||
|
// 失败源冷却(换源链失败时把那个源踢出轮转 60s)
|
||||||
|
//
|
||||||
|
// ⚠️ 必须放在上面 `status.is_empty()` 的早退**之后**(R-T5-1):
|
||||||
|
// 没过缓存层的请求(401 无效 Key / 429 超配额 / 503 未配上游)
|
||||||
|
// **没有回源** ⇒ 没有源失败 ⇒ 一个源都不该被冷却。
|
||||||
|
cool_down_failed(r);
|
||||||
Status::NGX_DECLINED
|
Status::NGX_DECLINED
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
//! 下行 Key 的**携带方式**解析(缓存插件自己的口径)。
|
||||||
|
//!
|
||||||
|
//! ## 为什么不在 core 里改
|
||||||
|
//!
|
||||||
|
//! 内核 `ipass_core::auth::downstream_key` 是**全平台共用**的口径:
|
||||||
|
//! `Authorization: Bearer <sk_…>` / `x-api-key` / `api-key`。
|
||||||
|
//! 改它会波及 ipass-all / ipass-sso 的 LLM、apix 等所有路径 ⇒ 爆炸半径太大。
|
||||||
|
//! 缓存插件**只多认一种携带方式**,且取到的值照样要过
|
||||||
|
//! `auth::identity(&key)`(比对 shm 的 `ukey:` 索引)⇒ **不构成任何授权绕过**。
|
||||||
|
//!
|
||||||
|
//! ## 多认的那一种:裸 token
|
||||||
|
//!
|
||||||
|
//! cargo 客户端发的是**裸 token**(不是 `Bearer ` 前缀):
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! Authorization: sk_xxxxxxxx
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! 源码依据(cargo 0.100.0 `src/util/auth/mod.rs`):token 以
|
||||||
|
//! `token.expose()` 取值后**直接**放进 `AUTHORIZATION` 头,
|
||||||
|
//! 中间不拼任何 scheme ⇒ core 的 `downstream_key` 认不出来 ⇒
|
||||||
|
//! cargo 全程 401,装不上任何 crate。
|
||||||
|
//!
|
||||||
|
//! ## 安全边界
|
||||||
|
//!
|
||||||
|
//! * 裸值本身**不是凭据**:仍须 `auth::identity()` 命中 shm 索引。
|
||||||
|
//! * 已排除常见认证方案前缀(Basic / Token / Digest / Negotiate),
|
||||||
|
//! 免得把别家客户端的凭据格式误当成 key(虽然最终仍会被 identity 拒掉,
|
||||||
|
//! 但错误信息会变得难以排查)。
|
||||||
|
|
||||||
|
use ipass_core::{auth, http};
|
||||||
|
use ngx::ffi::ngx_http_request_t;
|
||||||
|
|
||||||
|
/// 取下行 Key:core 的三种携带方式 + **裸 `Authorization: <token>`**。
|
||||||
|
///
|
||||||
|
/// 返回的字符串**还要**过 `auth::identity(&key)` 才能变成身份。
|
||||||
|
pub fn downstream_key(r: *mut ngx_http_request_t) -> Option<String> {
|
||||||
|
if let Some(k) = auth::downstream_key(r) {
|
||||||
|
return Some(k);
|
||||||
|
}
|
||||||
|
let raw = http::header(r, "authorization")?.trim().to_owned();
|
||||||
|
if raw.is_empty() || raw.contains(char::is_whitespace) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
const SCHEMES: [&str; 4] = ["basic", "token", "digest", "negotiate"];
|
||||||
|
let head = raw.split(':').next().unwrap_or("").to_ascii_lowercase();
|
||||||
|
if SCHEMES.contains(&head.as_str()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(raw)
|
||||||
|
}
|
||||||
+7
-2
@@ -15,8 +15,12 @@
|
|||||||
//!
|
//!
|
||||||
//! ## 装配点(gateway)
|
//! ## 装配点(gateway)
|
||||||
//!
|
//!
|
||||||
//! * `preconfig` —— 注册五个只读变量:`$cache_target` / `$cache_host` /
|
//! * `preconfig` —— 注册**十一个对外只读变量 + 一个内部变量**:
|
||||||
//! `$cache_upstream_key` / `$cache_eco` / `$cache_key`(见 [`cache`])
|
//! 对外的:`$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` 变量索引、
|
//! * `postconfig` —— 预取 `$upstream_cache_status` / `$scheme` 变量索引、
|
||||||
//! 识别 proxy_cache 容量区([`zones`],供容量面板读数与清理),
|
//! 识别 proxy_cache 容量区([`zones`],供容量面板读数与清理),
|
||||||
//! 并注册 access(鉴权)+ log(计量)两个 handler
|
//! 并注册 access(鉴权)+ log(计量)两个 handler
|
||||||
@@ -34,6 +38,7 @@ pub mod api;
|
|||||||
pub mod cache;
|
pub mod cache;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod handlers;
|
pub mod handlers;
|
||||||
|
pub mod key;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
pub mod stats;
|
pub mod stats;
|
||||||
pub mod store;
|
pub mod store;
|
||||||
|
|||||||
@@ -34,6 +34,32 @@ impl Default for CacheUpstreamStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 多源模式下的**一条上游源**。
|
||||||
|
///
|
||||||
|
/// 与 `CacheUpstream.base` 的区别:`base` 是「这条路由的上游」,
|
||||||
|
/// `sources` 是「这条路由的**镜像池**」——插件在池里轮转选源,
|
||||||
|
/// 失败的那个进冷却、下次直接跳过。
|
||||||
|
///
|
||||||
|
/// ⚠️ `url` 与 `base` 同约定:**不含**路由的协议前缀
|
||||||
|
/// (docker 的 `/v2` 由插件在 tail 侧补,见 `config::upstream_path_prefix`)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
|
pub struct CacheSource {
|
||||||
|
/// 稳定标识(小写字母/数字/`-`),管理台展示与冷却键用;
|
||||||
|
/// 留空时由 `url` 的 host(+ 路径)自动生成,同一路由内唯一。
|
||||||
|
#[serde(default)]
|
||||||
|
pub id: String,
|
||||||
|
/// 上游 URL:`scheme://host[/镜像自己的路径前缀]`,不带尾斜杠。
|
||||||
|
#[serde(default)]
|
||||||
|
pub url: String,
|
||||||
|
/// 该源自己的凭据(完整 `Authorization` 头值)。
|
||||||
|
/// 空 = 用路由级 `key`;路由级也空 = 透传客户端的 `Authorization`。
|
||||||
|
#[serde(default)]
|
||||||
|
pub key: String,
|
||||||
|
/// 备注
|
||||||
|
#[serde(default)]
|
||||||
|
pub note: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// 单个生态的上游配置。
|
/// 单个生态的上游配置。
|
||||||
///
|
///
|
||||||
/// 这里刻意**不存**「把哪个 URI 前缀映射到本生态」——那由 nginx conf 的
|
/// 这里刻意**不存**「把哪个 URI 前缀映射到本生态」——那由 nginx conf 的
|
||||||
@@ -50,6 +76,9 @@ pub struct CacheUpstream {
|
|||||||
/// Authorization,Docker Hub 的 Bearer token 走这条;但下端 `sk_` 会被剔除)。
|
/// Authorization,Docker Hub 的 Bearer token 走这条;但下端 `sk_` 会被剔除)。
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub key: String,
|
pub key: String,
|
||||||
|
/// 镜像源池(非空 = 多源模式)。空 = 退回单 `base` 模式(今天的行为)。
|
||||||
|
#[serde(default)]
|
||||||
|
pub sources: Vec<CacheSource>,
|
||||||
/// 模式(见 `config::MODE_PROXY`)
|
/// 模式(见 `config::MODE_PROXY`)
|
||||||
#[serde(default = "default_mode")]
|
#[serde(default = "default_mode")]
|
||||||
pub mode: String,
|
pub mode: String,
|
||||||
@@ -83,6 +112,7 @@ impl Default for CacheUpstream {
|
|||||||
Self {
|
Self {
|
||||||
base: String::new(),
|
base: String::new(),
|
||||||
key: String::new(),
|
key: String::new(),
|
||||||
|
sources: Vec::new(),
|
||||||
mode: default_mode(),
|
mode: default_mode(),
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
desc: String::new(),
|
desc: String::new(),
|
||||||
|
|||||||
+1005
-25
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user