Files
ipass/rust/crates/plugin-llm/src/api.rs
T
admin 0a9047840d feat(llm): 上游账号冷却改指数退避 + 真实请求探测闭环 (1.0.44)
天锚定重置边界计算(resets)删掉:锚点算错过两次(1.0.14 / 1.0.24),
线上表现为「厂商 15:00 已重置、网关锁到 18:00」。resets 只存不路由。

新口径:uac: = <backoff>:<next_probe>:<hard_cap>
- 到期放一个「无绑定/绑定失效」的真实请求过去探测,2xx → clear_cool 回队;
- 仍耗尽 → 退避翻倍(首轮 ipass_probe_min,默认 60s,30min 硬顶无条件回队自愈);
- 绑定流量永不被劫持当探测(保 prompt 缓存亲和)。
- pick_account 必须纯决策:四个 $llm_* 变量各求值一次,副作用只在 log 阶段记一次。

fix: 探测窗口判定改严格小于 —— 秒级时钟下 >= 会让「标记于 45.95s、next_probe=46」
的账号在 46.05s 即被当探测目标,1s 退避实际只等 0.05s,冷却形同虚设(回归暴露)。

回归 370 条全绿(网关 108 + LLM 262,新增「探测恢复闭环」剧本)。
2026-09-17 07:19:35 +08:00

445 lines
18 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! LLM 插件的管理 API:上游 CRUD / 连通性测试 / 用量查询。
//!
//! 趋势接口 `/api/admin/trend` **不在本表**——它需要 users + upstreams +
//! apix 三方名册(日桶键带日窗 id,按前缀扫不出来),属于组合逻辑,
//! 由 gateway 作为装配根实现(对方案的有意偏离,见 PLUGINIZATION_PLAN)。
//!
//! 鉴权语义与内核共用一套:`ipass_core::api::{Guard, Actor, run_guarded}`。
use ngx::core::{Pool, Status};
use ngx::ffi::ngx_http_request_t;
use ngx::http::HTTPStatus;
use serde_json::{Value, json};
use ipass_core::api::{Actor, Guard, run_guarded, user_or_401};
use ipass_core::{http, util};
use crate::llm;
use crate::llm_audit;
use crate::stats;
use crate::stats_persist;
use crate::upstreams;
// ===========================================================================
// 路由
// ===========================================================================
type Handler = fn(*mut ngx_http_request_t, Actor) -> Status;
/// 路由表。刻意用精确匹配而非正则——接口路径是固定的,
/// 正则只会引入「写错锚点导致前缀误匹配」的风险。
fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> {
let entry: (Guard, Handler) = match (method, uri) {
("GET", "/api/admin/upstreams") => (Guard::Admin, h_admin_upstreams),
("POST", "/api/admin/upstreams/save") => (Guard::Admin, h_admin_upstream_save),
("POST", "/api/admin/upstreams/test") => (Guard::Admin, h_admin_upstream_test),
("POST", "/api/admin/upstreams/delete") => (Guard::Admin, h_admin_upstream_delete),
("GET", "/api/admin/usage") => (Guard::Admin, h_admin_usage),
("GET", "/api/admin/stats/persist") => (Guard::Admin, h_admin_stats_persist),
("POST", "/api/admin/stats/dump") => (Guard::Admin, h_admin_stats_dump),
("GET", "/api/admin/audit/days") => (Guard::Admin, h_admin_audit_days),
("GET", "/api/admin/audit/day") => (Guard::Admin, h_admin_audit_day),
("GET", "/api/v1/models") => (Guard::User, h_my_models),
("GET", "/api/v1/usage") => (Guard::User, h_my_usage),
("GET", "/api/v1/upstreams") => (Guard::User, h_my_upstreams),
_ => return None,
};
Some(entry)
}
/// 本表分发:认领则返回响应状态,不认领返回 `None`(交给下一个插件)。
pub fn dispatch(r: *mut ngx_http_request_t) -> Option<Status> {
let method = http::method_str(r);
let uri = http::uri(r);
let Some((guard, handler)) = route(&method, &uri) else {
return None;
};
Some(run_guarded(r, guard, handler))
}
// ===========================================================================
// 管理员:LLM 上游
// ===========================================================================
fn h_admin_upstreams(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
http::ok(
r,
json!({ "items": upstreams::view_all(&upstreams::all(), &http::host_port(r)) }),
"ok",
)
}
fn h_admin_upstream_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
// 表单没提交 enabled 字段时视为「启用」——否则改个备注就会把上游改停,
// 这种误伤在管理台上极难自查
let enabled = match p.get("enabled") {
None => true,
Some(v) => util::to_bool(Some(v)),
};
// models 缺省 = 保持原清单;显式传(哪怕是空串)= 覆盖。
// 分隔符同时接受换行/逗号/顿号/分号——粘一份厂商文档里的模型列表是常见操作。
let models = p.get("models").map(|raw| parse_model_list(raw));
// 多账号:前端把 `accounts` 作为 JSON 数组串传上来(每个 {auth, note, resets})。
// 缺省/空 = 沿用旧逻辑(用 `auth` 维护单账号)。
let accounts = p
.get("accounts")
.and_then(|s| {
let s = s.trim();
if s.is_empty() {
None
} else {
serde_json::from_str::<Vec<crate::models::UpstreamAccount>>(s).ok()
}
});
// 上游级「额度耗尽」探测配置(JSON 数组;也兼容逗号串)
let exhaust_status = parse_int_list(p.get("exhaust_status"));
let exhaust_markers = p
.get("exhaust_markers")
.and_then(|s| {
let s = s.trim();
if s.is_empty() {
None
} else {
serde_json::from_str::<Vec<String>>(s).ok()
}
});
let slot_raw = p.get("slot").map(String::as_str).unwrap_or("");
match upstreams::upsert(
slot_raw,
p.get("base"),
p.get("base_anthropic"),
models,
p.get("auth"),
accounts,
exhaust_status,
exhaust_markers,
enabled,
p.get("note"),
) {
Ok(up) => {
// 用校验后的 slot 回显;直接拿原始入参会把大小写差异带进响应
let slot = upstreams::validate_slot(slot_raw).unwrap_or_default();
util::log_notice(&format!(
"[api] 保存 LLM 上游 {slot} enabled={enabled} accounts={} models={}",
up.effective_accounts().len(),
up.models.len()
));
// base_url 带「调用方正在用的端口」:见 upstreams::base_url 的说明
http::ok(r, upstreams::view(&slot, &up, &http::host_port(r)), "已保存")
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
/// 解析整数列表:优先 JSON 数组,回退逗号分隔串。
fn parse_int_list(raw: Option<&String>) -> Option<Vec<i64>> {
let s = raw?;
let s = s.trim();
if s.is_empty() {
return None;
}
if let Ok(v) = serde_json::from_str::<Vec<i64>>(s) {
return Some(v);
}
Some(
s.split(',')
.filter_map(|x| x.trim().parse::<i64>().ok())
.collect(),
)
}
/// 把管理台/接口传入的模型列表串拆成模型名数组。
///
/// 允许的写法(混用也认):`a,b` / `a、b` / `a;b` / 一行一个。
pub fn parse_model_list(raw: &str) -> Vec<String> {
raw.split(|c: char| c == ',' || c == '、' || c == ';' || c == '\n' || c == '\r' || c == '\t')
.map(|s| util::trim(s).to_owned())
.filter(|s| !s.is_empty())
.collect()
}
fn h_admin_upstream_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
match upstreams::remove(p.get("slot").map(String::as_str).unwrap_or("")) {
Ok(slot) => {
util::log_notice(&format!("[api] 删除 LLM 上游 {slot}"));
http::ok(r, json!({ "slot": slot }), "已删除")
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
/// 管理员:上游连通性测试(管理台「测试」按钮)。
///
/// 面板把 slot 放在 query(`?slot=x`),把**要发给上游的探测 JSON**(真实
/// chat/completions 请求,max_tokens=1)放在请求体——模块对体零改写。
/// 实现上校验 slot 存在后 `ngx_http_internal_redirect` 到管理 server 的
/// 内部 location `/_upstream_test/<slot>/v1/chat/completions`:
///
/// * `proxy_pass $llm_target` 原样复用 LLM 链路的取 slot / 拼路径 / 换真 Key
/// 逻辑(见 `llm::slot_of` 对 `/_upstream_test` 前缀的识别);
/// * 请求体在 API 两段式读取里已经进 `r->request_body`,内部重定向后由
/// proxy 原样转发;
/// * 上游的真实状态码与响应体直接透传给面板——通不通、错在哪个厂商,
/// 面板看到的就是厂商原话。
///
/// 为什么不能在浏览器里直测:上游真 Key 只存在服务端(面板只有掩码),
/// 且 lm 域名与 mdm 不同源,fetch 会被 CORS 拦住——测试必须在服务端发起。
fn h_admin_upstream_test(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let slot_raw = http::params(r).get("slot").cloned().unwrap_or_default();
let slot = match upstreams::validate_slot(&slot_raw) {
Ok(s) => s,
Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e),
};
if !llm::upstream_live(&slot) {
return http::fail(r, HTTPStatus::NOT_FOUND, &format!("上游 {slot} 不存在"));
}
// 与真实 OpenAI SDK 同形(必带 /v1)。1.0.42 曾改成裸 /chat/completions 绕智谱
// NPE——那是 join_target 剥冗余 /v1 落地(1.0.41)之前的坑位,且把**无路径 base**
// 的 openai/deepseek 探测打去了 /chat/completions(真端点 404,回归组11 抓到)。
// 1.0.43 用最小 dummy 体解决 NPE 后,这里恢复 /v1:base 带路径的厂商由
// join_target 剥除(llm.rs 单测钉死),不带路径的原样保留。
let uri = format!("/_upstream_test/{slot}/v1/chat/completions");
util::log_notice(&format!("[api] 测试 LLM 上游 {slot}"));
// ⚠️ nginx 的 internal_redirect 只**浅拷贝 ngx_str_t 结构体**(data 指针 + len),
// 不拷贝字节内容。若把栈上 String 的指针直接递过去,函数一返回堆内存就被回收,
// 之后 log 阶段读 r->uri 全是 NUL——健康标记、slot 解析全部静默失效(实测踩过)。
// 必须把 URI 字节拷进**请求池**,让它活到请求结束。
//
// SAFETY: r 有效;池内存在整个请求生命周期内有效。
unsafe {
let pool = Pool::from_ngx_pool((*r).pool);
let bytes = uri.as_bytes();
let data = pool.alloc(bytes.len()) as *mut u8;
if data.is_null() {
return http::fail(r, HTTPStatus::INTERNAL_SERVER_ERROR, "内存分配失败");
}
core::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
let mut u = nginx_sys::ngx_str_t {
len: bytes.len(),
data,
};
let mut args = nginx_sys::ngx_str_t {
len: 0,
data: std::ptr::null_mut(),
};
nginx_sys::ngx_http_internal_redirect(r, &mut u, &mut args);
}
Status::NGX_DONE
}
/// 管理员:LLM 用量总览(每人 / 每上游 / 合计)。
///
/// 口径是**请求数**,且只统计真正转发出去的请求(见 `stats` 模块头注释)。
///
/// **1.0.32**:在 `data.tokens` 下追加 `all_time` 块(自服务上线以来累计)——
/// 来自 audit meta.jsonl 真源聚合,**不受 stats 落盘/恢复影响**(audit 是
/// append-only,stats 会被 reset)。前端 `overview.html` 用此字段把"累计
/// token"从模糊的"自上次 stats 恢复以来"换成清晰的"自上线以来"。
fn h_admin_usage(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let now = util::now();
let mut view = stats::overview(now);
if let Some(tok) = view.get_mut("tokens").and_then(|v| v.as_object_mut()) {
tok.insert("all_time".to_owned(), llm_audit::all_time_total());
}
http::ok(r, view, "ok")
}
// ===========================================================================
// 账号态
// ===========================================================================
/// 账号态:看看自己能用哪些上游。
///
/// 刻意只回显 slot / base_url / **模型清单**——**不回显任何密钥**(连脱敏都不给,
/// 上游密钥与调用方无关,没有知道的必要)。
fn h_my_upstreams(r: *mut ngx_http_request_t, actor: Actor) -> Status {
// 回显的 base_url 必须带「调用方正在用的端口」,否则客户端照着拼会打不通
let port = http::host_port(r);
let user = match user_or_401(r, actor) {
Ok(u) => u,
Err(e) => return e,
};
let items: Vec<Value> = upstreams::available(&user.allowed_models)
.into_iter()
.map(|(slot, up)| {
let (status, code, checked_at) = match upstreams::health(&slot) {
Some((ok, c, ts)) => (if ok { "ok" } else { "failed" }, c, ts),
None => ("unknown", 0, 0),
};
json!({
"slot": slot,
"base_url": upstreams::base_url(&slot, &up, &port),
"anthropic_base_url": upstreams::anthropic_base_url(&slot, &up, &port),
"models": up.models,
"note": up.note,
"status": status,
"status_code": if code > 0 { json!(code) } else { Value::Null },
"checked_at": checked_at,
})
})
.collect();
http::ok(r, json!({ "items": items }), "ok")
}
/// 账号态:列出自己**可用的模型**(上游登记的模型清单,按白名单过滤)。
///
/// 与 LLM 域名下的 `GET /v1/models` 是同一份数据:那边给 OpenAI SDK 用
/// (形状 `{object:"list",data:[{id,...}]}`),这边给管理/自研客户端用
/// (形状 `{code,msg,data}`,带 base_url 便于直接拼请求)。
fn h_my_models(r: *mut ngx_http_request_t, actor: Actor) -> Status {
// 同 h_my_upstreams:base_url 跟随调用方所用的端口
let port = http::host_port(r);
let user = match user_or_401(r, actor) {
Ok(u) => u,
Err(e) => return e,
};
let available = upstreams::available(&user.allowed_models);
let mut items: Vec<Value> = Vec::new();
for (slot, up) in &available {
for model in &up.models {
items.push(json!({
"model": model,
"slot": slot,
"base_url": upstreams::base_url(slot, up, &port),
"note": up.note,
}));
}
}
http::ok(
r,
json!({
"items": items,
"upstreams": available
.iter()
.map(|(slot, up)| {
let (status, code, checked_at) = match upstreams::health(slot) {
Some((ok, c, ts)) => (if ok { "ok" } else { "failed" }, c, ts),
None => ("unknown", 0, 0),
};
json!({
"slot": slot,
"base_url": upstreams::base_url(slot, up, &port),
"anthropic_base_url": upstreams::anthropic_base_url(slot, up, &port),
"models": up.models,
"status": status,
"status_code": if code > 0 { json!(code) } else { Value::Null },
"checked_at": checked_at,
})
})
.collect::<Vec<_>>(),
}),
"ok",
)
}
/// 账号态:查自己的 LLM 用量(今日 / 累计 / 最近调用 + 分上游明细)。
fn h_my_usage(r: *mut ngx_http_request_t, actor: Actor) -> Status {
let user = match user_or_401(r, actor) {
Ok(u) => u,
Err(e) => return e,
};
let now = util::now();
let usage = stats::user(&user.username, now);
// token 计量(body filter 从上游 usage 抓的;抓不到 = 0,不补估)
let tin = stats::tokens_user(&user.username, now);
let models: Vec<Value> = stats::user_models(&user.username, now)
.into_iter()
.map(|(slot, u)| {
json!({
"slot": slot,
"today": u.today,
"total": u.total,
"last_ts": u.last_ts,
"last_ts_text": if u.last_ts > 0 { util::fmt_time(u.last_ts) } else { String::new() },
})
})
.collect();
http::ok(
r,
json!({
"username": user.username,
"display_name": user.display_name,
"today": usage.today,
"total": usage.total,
"last_ts": usage.last_ts,
"last_ts_text": if usage.last_ts > 0 { util::fmt_time(usage.last_ts) } else { String::new() },
"tokens": tin.json(),
"models": models,
// 限额一起回显:客户端可据此自我节流,不必等 429
"limits": { "rpm": user.llm_rpm, "daily": user.llm_daily },
}),
"ok",
)
}
// ===========================================================================
// 管理员:统计落盘
// ===========================================================================
//
// 用量/趋势只活在共享内存里,进程退出即清零。落盘/恢复见
// `crate::stats_persist` 模块注释与 docs/llm/STATS_PERSISTENCE.md。
// 这两个端点不参与任何转发逻辑,纯粹是「让运维看得见 + 手动兜一次」。
/// `GET /api/admin/stats/persist`:快照文件状态 + 当前共享内存键数。
///
/// 排障用法:发版后立刻查一次,`restored_keys` 应当等于 `file_keys`;
/// 若 `live_keys` 长期远大于 `file_keys`(且 `saved_at` 很旧),说明周期落盘没跑。
fn h_admin_stats_persist(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
http::ok(r, stats_persist::status(), "ok")
}
/// `POST /api/admin/stats/dump`:立刻落盘一次(不看间隔)。
///
/// 计划内维护前手动兜一次用;正常情况下不需要 —— 发版走 `exit_process` 钩子
/// 已经是零丢失,这个端点只是给个「我说了算」的把手。
fn h_admin_stats_dump(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
match stats_persist::dump_now("admin") {
Ok(n) => http::ok(r, json!({ "keys": n }), "已落盘"),
Err(e) => http::fail(r, HTTPStatus::INTERNAL_SERVER_ERROR, &e),
}
}
/// 列出审计目录所有有 `meta.jsonl` 的日期(按新→旧排序)
fn h_admin_audit_days(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let days = llm_audit::list_days();
http::ok(r, json!({ "days": days, "count": days.len() }), "ok")
}
/// 读某天 meta.jsonl 的所有行(剔除 excerpt / body_hash,**仅供管理台聚合**)。
///
/// 1.0.27 起管理台「小时级趋势」直接读这个端点 → 前端按 `ts / 3600` 分组聚合。
/// 不在网关做 hour-bucket 持久化:避免给热路径加写、避免新增 shm 键空间。
fn h_admin_audit_day(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let day = match http::params(r).get("day") {
Some(d) => d.trim().to_owned(),
None => return http::fail(r, HTTPStatus::BAD_REQUEST, "缺少 day 参数(YYYY-MM-DD)"),
};
match llm_audit::read_day(&day) {
Ok(rows) => {
let n = rows.len();
http::ok(r, json!({ "day": day, "rows": rows, "count": n }), "ok")
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}