feat(cache): 管理 API 支持读写源池 sources[]
保存语义:字段不提交 = 不改;提交空数组 = 清空源池(退回单 base)。 视图回显源列表(凭据只给掩码)+ source_count + base_source。 - base 自动补齐 = sources[0].url:让「base 非空」恒等于「已配置」, sync_shm / reload_shm 的判据一个字不用改(消除 base 空 + sources 非空的 503 错位)。 - 拒绝控制字符(< 0x20 与 DEL):payload 是换行分隔的,值里藏 \n 会把源列表 错位拆行且不报错 ⇒ 静默把请求打到错误的 URL 上。 - 源池变更时清掉该路由的 ch:<route>:<下标> 冷却条目:旧下标会套到别的源头上。 - 源 id 自动生成带 host + 路径,同批次内唯一。 - payload 损坏告警只报结构(行数 / 源个数),不落任何内容字节(payload 含凭据)。 Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
ed7fe3cac8
commit
ac1c51d374
3 files changed
+538
-14
No files matched your search
+59
-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`)。
|
||||
///
|
||||
/// ⚠️ **`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 {
|
||||
let p = http::params(r);
|
||||
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,
|
||||
};
|
||||
|
||||
// sources:表单里的 JSON 数组字符串。
|
||||
// 字段不提交(或提交空串)⇒ None ⇒ 不改现有源池;
|
||||
// 提交合法空数组 `[]` ⇒ Some(vec![]) ⇒ 清空(退回单 base);
|
||||
// 提交非空数组 ⇒ 覆盖。
|
||||
let sources = match p.get("sources") {
|
||||
Some(raw) if !util::trim(raw).is_empty() => match 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 用「字段是否出现」区分「不改」与「清空」,所以这里不能把
|
||||
// `p.get("key")` 归一成空串——前端删掉输入框内容时应提交 `key=`(空串)。
|
||||
let res = upstreams::upsert(
|
||||
@@ -131,6 +159,7 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
p.get("desc"),
|
||||
enabled,
|
||||
p.get("note"),
|
||||
sources.as_deref(),
|
||||
);
|
||||
|
||||
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 active = upstreams::lookup(&route).is_some();
|
||||
util::log_notice(&format!(
|
||||
"[cache] 保存上游 route={route} base={} enabled={} active={active}",
|
||||
item.base, item.enabled
|
||||
"[cache] 保存上游 route={route} base={} sources={} enabled={} active={active}",
|
||||
item.base,
|
||||
item.sources.len(),
|
||||
item.enabled
|
||||
));
|
||||
http::ok(
|
||||
r,
|
||||
@@ -147,6 +178,7 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
"route": route,
|
||||
"base": item.base,
|
||||
"key_set": !item.key.is_empty(),
|
||||
"source_count": item.sources.len(),
|
||||
"enabled": item.enabled,
|
||||
"active": active,
|
||||
"entry": upstreams::entry_base(r),
|
||||
@@ -158,6 +190,30 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析管理台提交的 `sources` 字段(JSON 数组字符串)→ 源池条目。
|
||||
///
|
||||
/// ⚠️ 解析失败**必须**返回 Err:调用方要回 400。
|
||||
/// 绝不能回退成空数组(语义 = 清空源池),那会在一次手滑提交里把源池抹掉。
|
||||
fn parse_sources(raw: &str) -> Result<Vec<upstreams::SourceInput>, String> {
|
||||
let v: Value = serde_json::from_str(raw).map_err(|e| format!("不是合法 JSON:{e}"))?;
|
||||
let arr = v
|
||||
.as_array()
|
||||
.ok_or_else(|| "必须是 JSON 数组".to_owned())?;
|
||||
let mut out = Vec::with_capacity(arr.len());
|
||||
for item in arr {
|
||||
let obj = item
|
||||
.as_object()
|
||||
.ok_or_else(|| "数组元素必须是对象".to_owned())?;
|
||||
out.push(upstreams::SourceInput {
|
||||
id: obj.get("id").and_then(Value::as_str).unwrap_or("").to_owned(),
|
||||
url: obj.get("url").and_then(Value::as_str).unwrap_or("").to_owned(),
|
||||
key: obj.get("key").and_then(Value::as_str).unwrap_or("").to_owned(),
|
||||
note: obj.get("note").and_then(Value::as_str).unwrap_or("").to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 删除一个路由的上游配置。
|
||||
fn h_admin_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
let p = http::params(r);
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ impl Default for CacheUpstreamStore {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct CacheSource {
|
||||
/// 稳定标识(小写字母/数字/`-`),管理台展示与冷却键用;
|
||||
/// 留空时由 `url` 的 host 自动生成。
|
||||
/// 留空时由 `url` 的 host(+ 路径)自动生成,同一路由内唯一。
|
||||
#[serde(default)]
|
||||
pub id: String,
|
||||
/// 上游 URL:`scheme://host[/镜像自己的路径前缀]`,不带尾斜杠。
|
||||
|
||||
+478
-10
@@ -84,6 +84,45 @@ pub struct Decoded {
|
||||
pub sources: Vec<CacheSource>,
|
||||
}
|
||||
|
||||
/// 「v2 段行数为奇数」标记(由 [`decode`] 置位,由 [`lookup_upstream`] 取走并告警)。
|
||||
///
|
||||
/// **为什么必须留证据**:payload 是**换行分隔**的
|
||||
/// (`base\nkey\nmode\nv2\n<url1>\n<key1>…`)。
|
||||
/// 若某行里含 `\n`(写入端漏拦),`decode` 会把它拆成两行 ⇒ 源列表**整体错位**
|
||||
/// (每个源的 url/key 串行),**不报错、不 panic** ⇒ 运行时把请求打到错误的 URL 上。
|
||||
///
|
||||
/// ⚠️ **`decode` 保持纯函数**(它的返回类型被 T2 的测试钉住,且它被单测直接调用)
|
||||
/// ⇒ 它只**记录**异常,**不打日志**(单测环境里没有 nginx 日志设施)。
|
||||
/// 真正的告警在**读 payload 的地方**([`lookup_upstream`])打。
|
||||
static ODD_V2_SEEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// 异常 payload 的**结构**信息(**不含任何内容字节**)。
|
||||
///
|
||||
/// ⚠️ **绝不能**把 payload 本身(或它的片段)写进日志:
|
||||
/// payload 第 2 行是**路由级凭据**(`Authorization` 头值),
|
||||
/// v2 段里每行源凭据也是敏感值 ⇒ 落盘即泄漏。
|
||||
/// ⇒ 这里只记**数量**(行数 / 源个数),够定位「哪个路由的数据坏了」。
|
||||
static ODD_V2_SHAPE: std::sync::Mutex<(usize, usize)> = std::sync::Mutex::new((0, 0));
|
||||
|
||||
/// 「已告警过」标记:每个 worker 只告警一次,避免热路径刷日志。
|
||||
static ODD_V2_WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// v2 段末尾是否**多出一行非空**(只剩 url 没有 key)⇒ 那个源会被 [`decode`]
|
||||
/// **静默丢弃**。
|
||||
///
|
||||
/// ⚠️ 判据用「剩下的那行**非空**」而不是「v2 段行数为奇数」:
|
||||
/// payload 以 `\n` 结尾时 `split` 会多出一个**空**行(= 某个源的 key 为空
|
||||
/// 或结尾符)⇒ 行数是奇数,但**并没有**真的丢源 ⇒ 不能按奇数报。
|
||||
/// 「剩下的那行非空」才精确对应「末尾有一对只剩 url 没有 key」。
|
||||
fn v2_has_dangling_tail(lines: &[&str]) -> bool {
|
||||
// v2 段从第 4 行起,每两行一个源(url + key)。
|
||||
let mut i = 4;
|
||||
while i + 1 < lines.len() {
|
||||
i += 2;
|
||||
}
|
||||
i < lines.len() && !lines[i].is_empty()
|
||||
}
|
||||
|
||||
/// 解析 payload(v1 / v2 通吃)。
|
||||
pub fn decode(payload: &str) -> Decoded {
|
||||
let lines: Vec<&str> = payload.split(config::PAYLOAD_SEP).collect();
|
||||
@@ -99,6 +138,18 @@ pub fn decode(payload: &str) -> Decoded {
|
||||
});
|
||||
i += 2;
|
||||
}
|
||||
// R-T6-3:末尾多出一行(只剩 url 没有 key)⇒ 那个源被上面 while
|
||||
// **静默丢弃** ⇒ 记异常(由读 payload 的地方告警),**不改返回类型**。
|
||||
if v2_has_dangling_tail(&lines) {
|
||||
ODD_V2_SEEN.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
// 只记**结构**(v2 段行数、解析出的源个数)⇒ **不记任何内容字节**
|
||||
// (payload 第 2 行是路由级凭据、v2 段里是源凭据 ⇒ 不能落盘)。
|
||||
if let Ok(mut g) = ODD_V2_SHAPE.lock() {
|
||||
if g.0 == 0 {
|
||||
*g = (lines.len() - 4, sources.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Decoded {
|
||||
base: lines.first().copied().unwrap_or("").to_owned(),
|
||||
@@ -174,6 +225,20 @@ pub fn reload_shm() -> usize {
|
||||
pub fn lookup_upstream(route: &str) -> Option<Decoded> {
|
||||
let payload = state::get(config::KEY_CX_PREFIX, route.as_bytes())?.0;
|
||||
let up = decode(&payload);
|
||||
// R-T6-3:v2 段末尾多出一行(只剩 url 没有 key)⇒ 那个源被**静默丢弃**。
|
||||
// 写入端已按 R-T6-2 拒掉控制字符,所以这基本只可能是**数据损坏 / 旧版本写入**。
|
||||
// ⇒ 留证据(每个 worker 只告警一次,避免热路径刷日志)。
|
||||
//
|
||||
// ⚠️ 只报**结构**(行数 / 源个数),**不报 payload 内容**:
|
||||
// payload 第 2 行是路由级凭据、v2 段里是源凭据 ⇒ 落盘即泄漏。
|
||||
if ODD_V2_SEEN.swap(false, std::sync::atomic::Ordering::Relaxed)
|
||||
&& !ODD_V2_WARNED.swap(true, std::sync::atomic::Ordering::Relaxed)
|
||||
{
|
||||
let (v2_lines, n_sources) = ODD_V2_SHAPE.lock().map(|g| *g).unwrap_or((0, 0));
|
||||
util::log_err(&format!(
|
||||
"[cache] 路由 {route} 的上游 payload v2 段行数为奇数(末尾有一对只剩 url 没有 key)⇒ 该源被静默丢弃(数据损坏?);v2 段行数={v2_lines} 解析出的源个数={n_sources}"
|
||||
));
|
||||
}
|
||||
if up.base.is_empty() && up.sources.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -247,23 +312,61 @@ pub fn validate_route(raw: &str) -> Result<String, String> {
|
||||
/// 为什么强制 scheme:nginx 的变量式 `proxy_pass $cache_target` 需要完整 URL,
|
||||
/// 而模块拼 target 时是 `base + tail`——base 缺 scheme 会直接 500。
|
||||
pub fn validate_base(raw: &str) -> Result<String, String> {
|
||||
base_checked(raw, "上游基址(base)")
|
||||
}
|
||||
|
||||
/// 基址校验的带字段名版本(源地址复用同一套规则,但错误信息要说清是哪个字段)。
|
||||
fn base_checked(raw: &str, field: &str) -> Result<String, String> {
|
||||
// ⚠️ 控制字符要在 **trim 之前**查:`util::trim` 会把首尾的 `\n`/`\r`/`\t`
|
||||
// 悄悄吃掉 ⇒ 「只 trim」等于「静默改写」,正是 R-T6-2 要避免的。
|
||||
check_control_chars(raw, field)?;
|
||||
let b = util::trim(raw).trim_end_matches('/').to_owned();
|
||||
if b.is_empty() {
|
||||
return Err("上游基址(base)不能为空".to_owned());
|
||||
return Err(format!("{field}不能为空"));
|
||||
}
|
||||
if b.len() > config::BASE_MAX_LEN {
|
||||
return Err(format!("上游基址过长(上限 {} 字节)", config::BASE_MAX_LEN));
|
||||
return Err(format!("{field}过长(上限 {} 字节)", config::BASE_MAX_LEN));
|
||||
}
|
||||
if !(b.starts_with("http://") || b.starts_with("https://")) {
|
||||
return Err("上游基址必须以 http:// 或 https:// 开头".to_owned());
|
||||
return Err(format!("{field}必须以 http:// 或 https:// 开头"));
|
||||
}
|
||||
if b.len() <= "https://".len() {
|
||||
return Err("上游基址不完整".to_owned());
|
||||
return Err(format!("{field}不完整"));
|
||||
}
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
/// 裁剪文本字段到上限(超长直接拒绝,避免悄悄丢字让人困惑)
|
||||
/// 控制字符校验:**拒绝**任何 `< 0x20` 的字符与 DEL(0x7f)。
|
||||
///
|
||||
/// ## 为什么必须拒绝(而不是只 trim)
|
||||
///
|
||||
/// shm payload 是**换行分隔**的:
|
||||
/// `base\nkey\nmode\nv2\n<url1>\n<key1>\n<url2>\n<key2>…`。
|
||||
/// 若某个 `url` / `key` 里藏一个 `\n`:
|
||||
///
|
||||
/// * `decode` 会把它**拆成两行** ⇒ 源列表整体**错位**(每个源的 url/key 串行),
|
||||
/// **不报错、不 panic** ⇒ 运行时把请求打到**错误的 URL** 上;
|
||||
/// * `\r` 同理(某些解析路径把它当行尾)。
|
||||
///
|
||||
/// ⇒ 只能**拒绝**(转义成 `\n` 字面量会让 URL 里出现反斜杠,变成另一个错的 URL)。
|
||||
///
|
||||
/// `note` / `id` 也要查:它们不进 payload,但会进管理台视图与**日志行**
|
||||
/// ⇒ 控制字符能污染日志。
|
||||
fn check_control_chars(v: &str, field: &str) -> Result<(), String> {
|
||||
if let Some(c) = v.chars().find(|c| c.is_control()) {
|
||||
return Err(format!(
|
||||
"{field}不能含控制字符(0x{:02x})",
|
||||
c as u32
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 裁剪文本字段到上限(超长直接拒绝,避免悄悄丢字让人困惑)。
|
||||
///
|
||||
/// ⚠️ 这里**不**查控制字符:路由级的 `name` / `desc` / `note` 是纯展示字段,
|
||||
/// 不进 shm payload ⇒ 不会造成「源列表错位」那种静默数据损坏。
|
||||
/// 会进 payload 的字段(base / 路由级 key / 源的 url+key+note+id)各自查。
|
||||
fn validate_text(raw: &str, max: usize, field: &str) -> Result<String, String> {
|
||||
let v = util::trim(raw).to_owned();
|
||||
if v.len() > max {
|
||||
@@ -272,6 +375,176 @@ fn validate_text(raw: &str, max: usize, field: &str) -> Result<String, String> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// 源标识(id)上限。
|
||||
pub const SOURCE_ID_MAX_LEN: usize = 32;
|
||||
|
||||
/// 把任意串转成「小写字母/数字/`-`」的 slug(连续分隔符折叠,首尾去掉)。
|
||||
fn slug(raw: &str) -> String {
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
let mut last_dash = false;
|
||||
for c in raw.chars() {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
out.push(c.to_ascii_lowercase());
|
||||
last_dash = false;
|
||||
} else if !last_dash {
|
||||
out.push('-');
|
||||
last_dash = true;
|
||||
}
|
||||
}
|
||||
out.trim_matches('-').to_owned()
|
||||
}
|
||||
|
||||
/// 截断到上限字节(按字符边界切,不切出半个 UTF-8)。
|
||||
fn truncate_chars(v: &str, max: usize) -> String {
|
||||
if v.len() <= max {
|
||||
return v.to_owned();
|
||||
}
|
||||
let mut out = String::new();
|
||||
for c in v.chars() {
|
||||
if out.len() + c.len_utf8() > max {
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 源标识自动生成:**host 主机名 +(路径非空时)路径后缀**。
|
||||
///
|
||||
/// ## 为什么带路径
|
||||
///
|
||||
/// 同一路由里可能有**同 host 不同路径**的两个源
|
||||
/// (`https://mirrors.ustc.edu.cn/a` 与 `https://mirrors.ustc.edu.cn/b`)——
|
||||
/// 只按 host 生成会撞 id(都是 `mirrors-ustc-edu-cn`)。
|
||||
/// 带路径后两者天然不同;再叠加 [`validate_sources`] 的**批次内去重**兜底。
|
||||
///
|
||||
/// 超长按字符边界截断(不报错):id 只用于展示与人工识别,
|
||||
/// 运行时认的是**下标**——不该因为镜像地址长而让整次保存失败。
|
||||
fn auto_source_id(url: &str) -> String {
|
||||
let host = crate::cache::host_of(url);
|
||||
let rest = url.split_once("://").map(|(_, r)| r).unwrap_or(url);
|
||||
let path = rest.strip_prefix(host).unwrap_or("").trim_start_matches('/');
|
||||
let mut id = slug(host);
|
||||
let p = slug(path);
|
||||
if !p.is_empty() {
|
||||
id.push('-');
|
||||
id.push_str(&p);
|
||||
}
|
||||
truncate_chars(&id, SOURCE_ID_MAX_LEN)
|
||||
}
|
||||
|
||||
/// 管理台提交的一条源(还没规范化)。
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct SourceInput {
|
||||
pub id: String,
|
||||
pub url: String,
|
||||
pub key: String,
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
/// 源校验与规范化(**单条**;批次内 id 唯一性见 [`validate_sources`])。
|
||||
///
|
||||
/// * `url` 必须与 `base` 同规则(http/https、不带尾斜杠、**不含控制字符**);
|
||||
/// * `id` 只保留小写字母/数字/`-`,空则按 url 自动生成(host + 路径);
|
||||
/// * `key` 上限沿用 `config::KEY_MAX_LEN`;
|
||||
/// * `note` / `id` 也要过控制字符检查(会进视图与日志)。
|
||||
pub fn validate_source(raw: &SourceInput) -> Result<CacheSource, String> {
|
||||
let url = base_checked(&raw.url, "源地址")?;
|
||||
check_control_chars(&raw.id, "源标识")?;
|
||||
let mut id: String = util::trim(&raw.id).to_ascii_lowercase();
|
||||
id.retain(|c| c.is_ascii_alphanumeric() || c == '-');
|
||||
if id.is_empty() {
|
||||
id = auto_source_id(&url);
|
||||
}
|
||||
if id.len() > SOURCE_ID_MAX_LEN {
|
||||
return Err(format!("源标识过长(上限 {SOURCE_ID_MAX_LEN} 字节):{id}"));
|
||||
}
|
||||
// ⚠️ 控制字符在 **trim 之前**查:`util::trim` 会吃掉首尾的 `\n`/`\r`/`\t`
|
||||
// ⇒ 「只 trim」等于「静默改写」,正是 R-T6-2 要避免的。
|
||||
check_control_chars(&raw.key, "源凭据")?;
|
||||
let key = util::trim(&raw.key).to_owned();
|
||||
if key.len() > config::KEY_MAX_LEN {
|
||||
return Err(format!("源凭据过长(上限 {} 字节)", config::KEY_MAX_LEN));
|
||||
}
|
||||
// 源备注不进 payload,但会进管理台视图与日志 ⇒ 同样拒控制字符(R-T6-2 附带条款)。
|
||||
check_control_chars(&raw.note, "源备注")?;
|
||||
let note = validate_text(&raw.note, config::NOTE_MAX_LEN, "源备注")?;
|
||||
Ok(CacheSource { id, url, key, note })
|
||||
}
|
||||
|
||||
/// 校验一批源,并保证**批次内 id 唯一**。
|
||||
///
|
||||
/// 撞 id 时加 `-2` / `-3` 后缀(**同批次即可**:id 只用于展示与人工识别,
|
||||
/// 运行时认的是**下标** ⇒ 冷却键也不受 id 影响)。
|
||||
pub fn validate_sources(list: &[SourceInput]) -> Result<Vec<CacheSource>, String> {
|
||||
let mut out: Vec<CacheSource> = Vec::with_capacity(list.len());
|
||||
for raw in list {
|
||||
let mut s = validate_source(raw)?;
|
||||
if out.iter().any(|p| p.id == s.id) {
|
||||
let base_id = s.id.clone();
|
||||
let mut n = 2usize;
|
||||
loop {
|
||||
let suffix = format!("-{n}");
|
||||
let mut cand = base_id.clone();
|
||||
let keep = SOURCE_ID_MAX_LEN.saturating_sub(suffix.len());
|
||||
cand = truncate_chars(&cand, keep);
|
||||
cand.push_str(&suffix);
|
||||
if !out.iter().any(|p| p.id == cand) {
|
||||
s.id = cand;
|
||||
break;
|
||||
}
|
||||
n += 1;
|
||||
if n > 999 {
|
||||
return Err(format!("源标识重复过多:{base_id}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(s);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 两个源列表是否「同一批」(比 url + key——运行期只认这两个)。
|
||||
fn same_sources(a: &[CacheSource], b: &[CacheSource]) -> bool {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.zip(b.iter())
|
||||
.all(|(x, y)| x.url == y.url && x.key == y.key)
|
||||
}
|
||||
|
||||
/// 决定这条路由最终落库的 `base`(**「已配置」判据的唯一落点**)。
|
||||
///
|
||||
/// ## 规则(R-T6-1)
|
||||
///
|
||||
/// * `base` 非空 ⇒ 原样保留;
|
||||
/// * `base` 空、但源池非空 ⇒ **自动补齐成 `sources[0].url`**(不报错);
|
||||
/// * `base` 与源池同时为空 ⇒ 报错(新建时必须填)。
|
||||
///
|
||||
/// ## 为什么补齐就够了(shm 判据一个字都不用改)
|
||||
///
|
||||
/// | 位置 | 判据 |
|
||||
/// | --- | --- |
|
||||
/// | `sync_shm` / `reload_shm` | `!item.enabled \|\| item.base.is_empty()` ⇒ 跳过 |
|
||||
/// | `lookup_upstream` | `base.is_empty() && sources.is_empty()` ⇒ 才算「未配置」 |
|
||||
///
|
||||
/// 补齐 base ⇒ **「base 非空」恒等于「已配置」** ⇒ 两边判据一致
|
||||
/// ⇒ 不会出现「lookup 认为已配置、但 shm 里查不到 ⇒ 503」的错位。
|
||||
///
|
||||
/// (另一条路——改 shm 判据——会让 base 空的条目进 shm ⇒ payload 首行为空
|
||||
/// ⇒ 变量式 `proxy_pass` 拿不到 host ⇒ nginx 报 500 `no host in upstream`。
|
||||
/// 所以补齐 base 是唯一同时满足「闸门准确」与「shm 判据不动」的解。)
|
||||
pub fn resolve_base(base: &str, sources: &[CacheSource]) -> Result<String, String> {
|
||||
if !base.is_empty() {
|
||||
return Ok(base.to_owned());
|
||||
}
|
||||
match sources.first() {
|
||||
Some(s) => Ok(s.url.clone()),
|
||||
None => Err(
|
||||
"该路由还没有上游基址:新建时必须填写(可点「填入官方源」一键带入)".to_owned(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 写入
|
||||
// ===========================================================================
|
||||
@@ -281,6 +554,9 @@ fn validate_text(raw: &str, max: usize, field: &str) -> Result<String, String> {
|
||||
/// `base` 传 `None` 或空串表示「保留原值」(新建时必须填);
|
||||
/// `key` 传 `None` 表示保留、`Some("")` 表示清空、`Some(v)` 表示覆盖——
|
||||
/// 两种语义的差异及理由见函数体内注释。
|
||||
///
|
||||
/// `sources` 传 `None` 表示保留原值、`Some(&[])` 表示**清空源池**(退回单 base 模式)、
|
||||
/// `Some(list)` 表示**覆盖**。
|
||||
pub fn upsert(
|
||||
route_raw: &str,
|
||||
base_raw: Option<&String>,
|
||||
@@ -289,6 +565,7 @@ pub fn upsert(
|
||||
desc: Option<&String>,
|
||||
enabled: bool,
|
||||
note: Option<&String>,
|
||||
sources: Option<&[SourceInput]>,
|
||||
) -> Result<CacheUpstream, String> {
|
||||
let route = validate_route(route_raw)?;
|
||||
|
||||
@@ -300,6 +577,11 @@ pub fn upsert(
|
||||
};
|
||||
let name_v = opt_text(name, config::NAME_MAX_LEN, "展示名")?;
|
||||
let desc_v = opt_text(desc, config::DESC_MAX_LEN, "说明")?;
|
||||
// ⚠️ 路由级备注也要拒控制字符(R-T6-2 附带条款):它不进 payload,
|
||||
// 但会进管理台视图与**日志行** ⇒ 控制字符能污染日志行。
|
||||
if let Some(n) = note {
|
||||
check_control_chars(n, "备注")?;
|
||||
}
|
||||
let note_v = opt_text(note, config::NOTE_MAX_LEN, "备注")?;
|
||||
|
||||
let base_arg = match base_raw {
|
||||
@@ -315,6 +597,9 @@ pub fn upsert(
|
||||
let key_arg = match key_raw {
|
||||
None => None,
|
||||
Some(k) => {
|
||||
// ⚠️ 路由级 key 也进 payload(第 2 行)⇒ 控制字符同样会**错位拆行**
|
||||
// ⇒ 与源凭据一样**拒绝**(不 trim、不改写)。
|
||||
check_control_chars(k, "上游凭据")?;
|
||||
let k = util::trim(k).to_owned();
|
||||
if k.len() > config::KEY_MAX_LEN {
|
||||
return Err(format!("上游凭据过长(上限 {} 字节)", config::KEY_MAX_LEN));
|
||||
@@ -323,9 +608,19 @@ pub fn upsert(
|
||||
}
|
||||
};
|
||||
|
||||
// 源池:先**校验并规范化**(纯函数,失败即报错,**不写盘**)。
|
||||
// `None` = 保留原值、`Some(&[])` = 清空、`Some(list)` = 覆盖。
|
||||
let sources_arg: Option<Vec<CacheSource>> = match sources {
|
||||
None => None,
|
||||
Some(list) => Some(validate_sources(list)?),
|
||||
};
|
||||
|
||||
let now = util::now();
|
||||
let mut saved = CacheUpstream::default();
|
||||
let mut snapshot = CacheUpstreamStore::default();
|
||||
// R-T6-4:源列表变了 ⇒ 该路由的 `ch:<route>:<下标>` 冷却条目指的是**旧池子**的下标
|
||||
// ⇒ 全部作废(否则旧冷却会「套到别的源头上」)。
|
||||
let mut cooldown_clear_len = 0usize;
|
||||
|
||||
store::update_upstreams(|st| {
|
||||
let item = st.items.entry(route.clone()).or_default();
|
||||
@@ -336,10 +631,30 @@ pub fn upsert(
|
||||
if let Some(b) = &base_arg {
|
||||
item.base = b.clone();
|
||||
}
|
||||
if item.base.is_empty() {
|
||||
return Err(
|
||||
"该路由还没有上游基址:新建时必须填写(可点「填入官方源」一键带入)".to_owned(),
|
||||
);
|
||||
// sources:`None` = 不改(表单没提交该字段);`Some(&[])` = 清空源池
|
||||
// (退回单 base 模式);`Some(&[..])` = 覆盖。
|
||||
let prev_sources = item.sources.clone();
|
||||
if let Some(v) = &sources_arg {
|
||||
item.sources = v.clone();
|
||||
}
|
||||
// R-T6-1:**base 与 sources 的「已配置」判据必须一致**。
|
||||
//
|
||||
// 规则(见 [`resolve_base`]):
|
||||
// * 管理员**显式**填了 base(`base_arg` 有值)⇒ 以管理员填的为准;
|
||||
// * 没显式填 base、但提交了**非空**源池 ⇒ base = `sources[0].url`
|
||||
// (base 本来就是「池子的头」⇒ 池子改了 base 跟着改);
|
||||
// * base 空、但源池非空 ⇒ **自动补齐**成 `sources[0].url`(**不报错**);
|
||||
// * base 与源池**同时**为空 ⇒ 报错(新建时必须填)。
|
||||
//
|
||||
// ⇒ 「base 非空」**恒等于**「已配置」⇒ `sync_shm` / `reload_shm` 的
|
||||
// `base.is_empty()` 判据一个字都不用改。
|
||||
if base_arg.is_none() && sources_arg.is_some() && !item.sources.is_empty() {
|
||||
item.base = item.sources[0].url.clone();
|
||||
}
|
||||
item.base = resolve_base(&item.base, &item.sources)?;
|
||||
// R-T6-4:源列表变了 ⇒ 清掉该路由的冷却条目(范围 = 旧/新长度的较大者)。
|
||||
if sources_arg.is_some() && !same_sources(&prev_sources, &item.sources) {
|
||||
cooldown_clear_len = prev_sources.len().max(item.sources.len());
|
||||
}
|
||||
// key:`Some("")` = 清空、`Some(v)` = 覆盖、`None` = 保留(表单没提交)。
|
||||
// 语义与 base 刻意不同,理由见上面 key_arg 的注释;管理台提交空串即清空。
|
||||
@@ -362,6 +677,17 @@ pub fn upsert(
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
// R-T6-4:源列表变了 ⇒ 旧的 `ch:<route>:<下标>` 冷却条目指的是旧池子的下标 ⇒ 全部作废。
|
||||
// 只清**本路由**(各路由独立)。
|
||||
if cooldown_clear_len > 0 {
|
||||
for i in 0..cooldown_clear_len {
|
||||
state::remove(config::KEY_CH_PREFIX, format!("{route}:{i}").as_bytes());
|
||||
}
|
||||
util::log_notice(&format!(
|
||||
"[cache] 路由 {route} 的源池已变更 ⇒ 清除 {cooldown_clear_len} 条冷却记录(ch: 前缀)"
|
||||
));
|
||||
}
|
||||
|
||||
sync_shm(&route, &snapshot);
|
||||
Ok(saved)
|
||||
}
|
||||
@@ -434,6 +760,8 @@ pub fn view(route: &str, item: Option<&CacheUpstream>, entry: &str, active: bool
|
||||
let eco = config::eco_of_route(route);
|
||||
let configured = item.is_some();
|
||||
let it = item.cloned().unwrap_or_default();
|
||||
// 首选源 = 源池的第一个(base 在多源模式下就是补齐成 sources[0].url 的)。
|
||||
let base_source = it.sources.first().map(|s| s.url.clone()).unwrap_or_default();
|
||||
json!({
|
||||
"route": route,
|
||||
"eco": eco,
|
||||
@@ -447,8 +775,23 @@ pub fn view(route: &str, item: Option<&CacheUpstream>, entry: &str, active: bool
|
||||
"note": it.note,
|
||||
"enabled": it.enabled,
|
||||
"configured": configured,
|
||||
// 是否真的在共享内存里(= 已配置 && 启用 && base 非空)
|
||||
// 是否真的在共享内存里(= 已配置 && 启用 && base 非空;
|
||||
// base 为空时由 `upsert` 自动补齐成 `sources[0].url` ⇒ 判据一致)
|
||||
"active": active,
|
||||
// 多源模式:源池(凭据只给掩码)+ 源个数 + 首选源
|
||||
"sources": it
|
||||
.sources
|
||||
.iter()
|
||||
.map(|s| json!({
|
||||
"id": s.id,
|
||||
"url": s.url,
|
||||
"key_masked": mask_key(&s.key),
|
||||
"key_set": !s.key.is_empty(),
|
||||
"note": s.note,
|
||||
}))
|
||||
.collect::<Vec<Value>>(),
|
||||
"source_count": it.sources.len(),
|
||||
"base_source": base_source,
|
||||
"default_base": config::default_base(route),
|
||||
"updated_at": it.updated_at,
|
||||
"client": client_hint(eco, entry),
|
||||
@@ -461,6 +804,8 @@ pub fn view_all(entry: &str) -> Vec<Value> {
|
||||
let mut out = Vec::with_capacity(config::ROUTES.len());
|
||||
for route in config::ROUTES {
|
||||
let item = stored.items.get(*route);
|
||||
// `active` = 已配置 && 启用 && base 非空
|
||||
// (base 为空时由 `upsert` 自动补齐成 `sources[0].url` ⇒ 判据一致)
|
||||
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));
|
||||
@@ -565,4 +910,127 @@ mod tests {
|
||||
assert_eq!(srcs[0].url, "https://goproxy.cn");
|
||||
assert_eq!(srcs[0].key, "KEY");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Task 6:源池校验(R-T6-2 控制字符 / R-T6-5 id 唯一 / R-T6-1 base 补齐)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn src(id: &str, url: &str, key: &str) -> SourceInput {
|
||||
SourceInput {
|
||||
id: id.to_owned(),
|
||||
url: url.to_owned(),
|
||||
key: key.to_owned(),
|
||||
note: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_source_rejects_newline_in_url() {
|
||||
// payload 是换行分隔的 ⇒ url 里的 `\n` 会把源列表**错位拆行**(不报错、不 panic)。
|
||||
let e = validate_source(&src("", "https://a\nb", "")).unwrap_err();
|
||||
assert!(e.contains("控制字符"), "错误信息应说清是控制字符:{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_source_rejects_carriage_return_in_key() {
|
||||
let e = validate_source(&src("", "https://a", "K\rR")).unwrap_err();
|
||||
assert!(e.contains("控制字符"), "错误信息应说清是控制字符:{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_source_rejects_tab_in_note() {
|
||||
let mut s = src("", "https://a", "");
|
||||
s.note = "a\tb".to_owned();
|
||||
let e = validate_source(&s).unwrap_err();
|
||||
assert!(e.contains("控制字符"), "错误信息应说清是控制字符:{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_source_rejects_control_char_in_id() {
|
||||
let e = validate_source(&src("a\nb", "https://a", "")).unwrap_err();
|
||||
assert!(e.contains("控制字符"), "错误信息应说清是控制字符:{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_source_generates_different_ids_for_same_host_different_path() {
|
||||
// 同 host 不同路径 ⇒ id 不能撞(否则管理台分不清哪个源)。
|
||||
let a = validate_source(&src("", "https://mirrors.ustc.edu.cn/a", "")).unwrap();
|
||||
let b = validate_source(&src("", "https://mirrors.ustc.edu.cn/b", "")).unwrap();
|
||||
assert_ne!(a.id, b.id, "同 host 不同路径应生成不同的 id:{} vs {}", a.id, b.id);
|
||||
assert!(!a.id.is_empty() && !b.id.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_sources_dedupes_ids_within_batch() {
|
||||
// 同批次内 id 必须唯一 ⇒ 重复的加 `-2` 后缀。
|
||||
let list = vec![
|
||||
src("", "https://a.example/x", ""),
|
||||
src("", "https://a.example/y", ""),
|
||||
src("", "https://b.example/z", ""),
|
||||
];
|
||||
let v = validate_sources(&list).unwrap();
|
||||
assert_eq!(v.len(), 3);
|
||||
assert_ne!(v[0].id, v[1].id);
|
||||
assert_ne!(v[0].id, v[2].id);
|
||||
assert_ne!(v[1].id, v[2].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_source_keeps_explicit_id_and_rejects_too_long() {
|
||||
let s = validate_source(&src("My-Src", "https://a", "")).unwrap();
|
||||
assert_eq!(s.id, "my-src");
|
||||
let long = "a".repeat(SOURCE_ID_MAX_LEN + 1);
|
||||
let e = validate_source(&src(&long, "https://a", "")).unwrap_err();
|
||||
assert!(e.contains("源标识过长"), "错误信息应说清是源标识:{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_source_trims_url_trailing_slash() {
|
||||
let s = validate_source(&src("", "https://a.example/", "")).unwrap();
|
||||
assert_eq!(s.url, "https://a.example");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_base_fills_from_first_source_when_base_empty() {
|
||||
// R-T6-1:base 空 + 源池非空 ⇒ base = sources[0].url(**不报错**)。
|
||||
let list = vec![
|
||||
src("", "https://a.example", ""),
|
||||
src("", "https://b.example", ""),
|
||||
];
|
||||
let v = validate_sources(&list).unwrap();
|
||||
let base = resolve_base("", &v).unwrap();
|
||||
assert_eq!(base, "https://a.example");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_base_keeps_explicit_base() {
|
||||
let list = vec![src("", "https://a.example", "")];
|
||||
let v = validate_sources(&list).unwrap();
|
||||
let base = resolve_base("https://explicit.example", &v).unwrap();
|
||||
assert_eq!(base, "https://explicit.example");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_base_errors_when_both_base_and_sources_empty() {
|
||||
// R-T6-1:base 与源池**同时**为空 ⇒ 保持今天的报错。
|
||||
let e = resolve_base("", &[]).unwrap_err();
|
||||
assert!(e.contains("上游基址"), "错误信息应说清缺什么:{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_sources_compares_url_and_key_only() {
|
||||
let mut a = CacheSource {
|
||||
id: "x".to_owned(),
|
||||
url: "https://a".to_owned(),
|
||||
key: "K".to_owned(),
|
||||
note: "n1".to_owned(),
|
||||
};
|
||||
let mut b = a.clone();
|
||||
b.note = "n2".to_owned(); // note 变了不算池子变了
|
||||
assert!(same_sources(&[a.clone()], &[b.clone()]));
|
||||
b.key = "K2".to_owned();
|
||||
assert!(!same_sources(&[a.clone()], &[b.clone()]));
|
||||
a.url = "https://c".to_owned();
|
||||
assert!(!same_sources(&[a], &[b]));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user