Files
ipass__ipass/rust/crates/plugin-llm/src/handlers.rs
T
admin bfa3cf8ff8 feat(llm): 上游多账号路由 + 账号级负载统计 (1.0.14)
一个 slot 挂多把上游账号 Key,解决厂商「单账号额度/并发受限」与
「同一用户缓存命中」两个矛盾诉求。

多账号路由 (plugin-llm)
- models: Upstream.accounts[] (auth/note/resets) + 上游级
  exhaust_status/exhaust_markers;顶层 auth 保留兼容(accounts 为空时合成单账号)
- upstreams::pick_account:粘性绑定 ukb:<key> 优先 → 无绑定时
  FNV-1a(下游 Key) % 可用数 冷分散 → 绑定账号冷却则重新分散 → 全冷却取最早恢复
  * 分散避开厂商单账号 agent 并发上限;落点固定保住 prompt/token 缓存
- cool_until_until 天锚定冷却:boundary = day0 + ceil(已过/窗口)*窗口,
  封顶次日 0 点(MiniMax 5h 窗口、24=5*4+4 → 末段 20:00-24:00 只有 4h 随天重置)
- 耗尽双检测 (log 阶段):$upstream_status 命中 exhaust_status,或
  usage_filter 流式扫到 marker → $llm_acct 定位本次账号 → 写冷却 uac:
- shm: up:/upa:/uac:/ukb:/upe: 五类前缀;$llm_acct 变量 (NOCACHEABLE)

账号级负载统计(问题发现与跟踪)
- 新增 uda:<slot>:<idx>:<day>(请求/token)与 uex:(耗尽次数) 日桶,
  复用内核 usage::bump_day —— 无数据库、无新进程(项目红线)
- 计数点只在 log 阶段一次;pick_account 会被 $llm_target/$llm_auth/$llm_acct
  三个变量各触发一次,放进那里会三倍计数
- view() 投影带每账号 load 与 account_trend + trend_labels(日期由后端算)
- 管理台「上游」页密钥列:各 Key 今日请求/token/耗尽 + 负载比例条 +
  14 天迷你趋势(自绘 SVG,零第三方依赖)+ 冷却/耗尽徽标 + 上游合计

测试与验证
- 回归 279 条全绿(网关 102 + LLM 177),新增 6 条多账号/负载断言
- 假上游新增 UPSTREAM_FAIL_AUTH 模拟账号额度耗尽;靶机验证 Key 真被替换
- 前端以真实 admin.css + upstreams.js 渲染路径做无头浏览器断言:
  比例条与负载成比例(412 vs 96 → 100%/23%)、每账号 14 条块、
  悬停峰值日期与数据逐位吻合、单账号/无账号兜底正常、无横向溢出、零 JS 错误

文档
- 新增 docs/llm/MULTI_ACCOUNT_ROUTING.md(数据模型/路由/冷却数学/shm 布局/负载统计)
- readme §11 数据模型 + §15 上游配置 + §15 用量统计 + §12.6 tag 表 + §16 变更记录
- 修正 docs/llm/*.md 中插件化前的过时路径(rust/src/* → crates/plugin-llm/src/*)
2026-09-14 11:57:08 +08:00

333 lines
15 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 插件的 phase handler:access 转发决策、log 阶段健康标记与对话审计。
//!
//! 插件化改造点(相对 gateway 旧版行为等价):
//! * location 开关改走内核契约 `loc::enabled(r, Switch::Llm)`——插件不认识
//! gateway 私有的 `ModuleConfig`;
//! * 下行鉴权(取 Key / 查身份 / 限流配额 / OpenAI 兼容错误体)用内核
//! `ipass_core::auth`(LLM 与 apix 两条下行链路共用);
//! * `$upstream_status` 变量索引的预取从 gateway postconfiguration 迁入本插件
//! 的 postconfig(见 [`prefetch_upstream_status_index`])。
use core::sync::atomic::{AtomicIsize, Ordering};
use ngx::core::{Status, NgxStr};
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,
};
use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request};
use crate::llm;
use crate::llm_audit;
use crate::stats;
use crate::upstreams;
use crate::usage_filter;
use ipass_core::{auth, http, loc, util};
use ipass_core::loc::Switch;
// ===========================================================================
// LLM 代理热路径(access)
// ===========================================================================
/// LLM 代理热路径:鉴权 → 校验上游与白名单 → 放行。
///
/// 刻意**只做决策、不搬数据**:真正的转发交给 nginx 的 proxy 模块,
/// 于是 SSE 流式、`proxy_buffering`、上游超时全部是 nginx 原生行为,
/// 不需要自己实现 upstream——那正是「按 body 里的 model 路由」代价高昂之处。
///
/// 变量(`$llm_target` / `$llm_host` / `$llm_auth`)不在这里赋值,
/// 而由 `llm::var_get` 在 `proxy_pass` 求值时计算,与 `$proxy_backend_addr` 同构。
pub struct LlmHandler;
impl HttpRequestHandler for LlmHandler {
const PHASE: HttpPhase = HttpPhase::Access;
type Output = Status;
fn handler(request: &mut Request) -> Self::Output {
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
if !loc::enabled(r, Switch::Llm) {
return Status::NGX_DECLINED;
}
let Some(slot) = llm::slot_of(r) else {
return auth::fail(
r,
HTTPStatus::BAD_REQUEST,
"invalid_request_error",
"路径缺少上游段,正确形式:/<上游名>/v1/chat/completions",
);
};
let Some(key) = auth::downstream_key(r) else {
return auth::fail(
r,
HTTPStatus::UNAUTHORIZED,
"invalid_api_key",
"缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带",
);
};
// 只碰共享内存:这里若改成 users::find_by_key 会每请求读一次 users.json
let Some((username, allowed, rpm, daily)) = auth::identity(&key) else {
util::log_warn(&format!(
"[llm] API Key 校验失败 slot={slot} client={}",
http::remote_addr(r)
));
return auth::fail(
r,
HTTPStatus::UNAUTHORIZED,
"invalid_api_key",
"API Key 无效或已失效",
);
};
// 「列出可用模型」是网关自己的元信息接口(OpenAI 兼容形状),
// 在查上游之前就地应答——否则 `/v1/models` 会被当成 slot=v1 → 404。
if llm::is_models_probe(r) {
return llm::respond_models(r, &allowed);
}
let upstream_live = llm::upstream_live(&slot);
if !upstream_live {
return auth::fail(
r,
HTTPStatus::NOT_FOUND,
"model_not_found",
&format!("上游 {slot} 不存在或已停用"),
);
}
// 空白名单 = 不限(老账号没有该字段时的语义)
if !allowed.is_empty() && !allowed.iter().any(|s| s == &slot) {
util::log_warn(&format!("[llm] {username} 无权访问上游 {slot}"));
return auth::fail(
r,
HTTPStatus::FORBIDDEN,
"permission_denied",
&format!("当前账号无权访问上游 {slot}"),
);
}
// 限流与每日配额(先增后判,纯共享内存)。放在最后:
// 鉴权/白名单都没过的请求不该消耗对方的计数
// SAFETY: r 由 nginx 传入且有效
if let Some(resp) = unsafe { auth::check_quota(r, &username, rpm, daily) } {
return resp;
}
// 用量统计:走到这里说明请求**真的会被转发**,才计入。
// 被拒的请求(401/403/404/429)不进统计——那是给人看的数字,
// 把拒绝也算进"用量"只会误导(与配额计数 st: 的语义刻意不同)。
stats::record(&username, &slot, util::now());
Status::NGX_DECLINED
}
}
// ===========================================================================
// log 阶段:上游健康标记
// ===========================================================================
/// `$upstream_status` 的变量索引,postconfiguration 时解析一次(log 阶段复用)。
static UPSTREAM_STATUS_IDX: AtomicIsize = AtomicIsize::new(-1);
/// `$llm_acct` 的变量索引(本插件注册),log 阶段读它拿到「本次请求打到的上游账号下标」,
/// 用于额度耗尽时精确标记那一个账号进入冷却。postconfiguration 时解析一次。
static LLM_ACCT_IDX: AtomicIsize = AtomicIsize::new(-1);
/// postconfiguration:预取 `$upstream_status` 与 `$llm_acct` 变量索引。
/// 失败返回 false,gateway 会 EMERG 退出。
pub fn prefetch_upstream_status_index(cf: *mut ngx_conf_t) -> bool {
let mut status_name = ngx_str_t {
len: "upstream_status".len() as usize,
data: b"upstream_status\0".as_ptr() as *mut u8,
};
// SAFETY: cf 由 nginx 传入且有效;name 指向栈上合法 ngx_str_t
let sidx = unsafe { ngx_http_get_variable_index(cf, &mut status_name) };
if sidx == -1 {
return false;
}
UPSTREAM_STATUS_IDX.store(sidx as isize, Ordering::Relaxed);
let mut acct_name = ngx_str_t {
len: "llm_acct".len() as usize,
data: b"llm_acct\0".as_ptr() as *mut u8,
};
// SAFETY: 同上;本插件已在 preconfiguration 用 add_var 注册过 llm_acct
let aidx = unsafe { ngx_http_get_variable_index(cf, &mut acct_name) };
if aidx == -1 {
return false;
}
LLM_ACCT_IDX.store(aidx as isize, Ordering::Relaxed);
true
}
/// LLM 上游健康标记(log 阶段):把上游**真实**状态码写进 `uh:<slot>` 缓存。
///
/// 为什么在 log 阶段:转发决策在 access、响应在 proxy 模块手里,只有 log
/// 阶段能同时拿到「slot 是谁」和「上游实际回了什么」。这相当于让**真实流量
/// 自己当探针**——不需要额外的常驻探测进程(项目红线),健康状态也最真实。
/// 管理台「测试」按钮的探测请求走同一条 `proxy_pass` 链路,天然共用本逻辑。
///
/// 写下的缓存**只用于展示**(列表标红 / 模型发现附状态),转发路径不读它,
/// 误标不影响任何请求的结果。
///
/// ⚠️ 状态码从 `$upstream_status` 变量读,**不能读 `r->upstream`**——
/// `ngx_http_upstream_finalize_request` 在日志阶段之前就把 `r->upstream`
/// 置空了(实测踩过:代码编译通过、跑起来状态永远是 unknown)。
/// access log 模块同款手法:变量在 finalize 时快照,log 阶段仍有效。
pub struct LlmHealthHandler;
impl HttpRequestHandler for LlmHealthHandler {
const PHASE: HttpPhase = HttpPhase::Log;
type Output = Status;
fn handler(request: &mut Request) -> Self::Output {
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
// 两类请求要标记:
// ① LLM server 的真实转发流量(Switch::Llm 开启);
// ② 管理台探测流量——内部重定向到管理 server 的 /_upstream_test location,
// 那里**没有** ipass_llm 指令(有就会重跑 access 鉴权,探测请求只有
// 登录会话没有 API Key),所以只能按 URI 前缀认。
let uri = http::uri(r);
let is_llm = loc::enabled(r, Switch::Llm);
let is_probe = uri.starts_with("/_upstream_test");
if !is_llm && !is_probe {
return Status::NGX_DECLINED;
}
// SAFETY: r 有效;索引在 postconfiguration 已解析(见 prefetch_upstream_status_index)
let code = unsafe {
let idx = UPSTREAM_STATUS_IDX.load(Ordering::Relaxed);
if idx < 0 {
0
} else {
let v = ngx_http_get_indexed_variable(r, idx as ngx_uint_t);
if (*v).not_found() != 0 || (*v).data.is_null() {
0
} else {
let s = core::str::from_utf8(core::slice::from_raw_parts(
(*v).data,
(*v).len() as usize,
))
.unwrap_or("");
// 内部重定向会有多段(如 "502, 200"),取**最后一段** = 最近一次上游尝试
s.rsplit(',').next().unwrap_or("").trim().parse().unwrap_or(0)
}
}
};
// 没有 upstream(本地应答如 /v1/models)或没拿到状态码(客户端中途
// 断连等)→ 无从判断,不写缓存,留给下一次真实转发
if code == 0 {
return Status::NGX_DECLINED;
}
if let Some(slot) = llm::slot_of(r) {
let now = util::now();
// 上游回了头 = 它活着:2xx~4xx 都算正常(4xx 是它对我们请求的意见,
// 不是机器死了);5xx / 连接失败(502) / 等头超时(504) 才算失效
upstreams::mark_health(&slot, (200..500).contains(&code), code);
// 账号级负载:每次真实转发都记到选中的上游账号(负载分布 / 问题发现)。
// 只在这里记一次(read_llm_acct 触发一次 pick_account),绝不放在
// pick_account 里——否则 $llm_target/$llm_auth/$llm_acct 三变量各触发一次
// 会把同一请求记三遍。
if let Some(idx) = read_llm_acct(r) {
upstreams::bump_acct_load(&slot, idx, now);
// 额度耗尽检测:状态码命中 或 响应体命中标记 → 标记该账号冷却 + 耗尽计数 +1。
// 状态码来自 `$upstream_status`,标记来自 body filter 的 `take_exhausted`
// (流式也能扫到)。
let (status_list, _) = upstreams::read_upe(&slot);
let status_exhausted = status_list.iter().any(|&s| s == code);
let body_exhausted = usage_filter::take_exhausted(r);
if status_exhausted || body_exhausted {
if let Some((_, resets)) = upstreams::read_upa(&slot, idx) {
upstreams::mark_exhausted(&slot, idx, &resets, now);
}
upstreams::bump_acct_exhaust(&slot, idx, now);
}
}
}
Status::NGX_DECLINED
}
}
/// 从 `$llm_acct` 索引读本次请求选中的上游账号下标(NOCACHEABLE,读时重算,确定一致)。
///
/// 读不到(未求值/解析失败)返回 None——不标记,避免误伤。
fn read_llm_acct(r: *mut ngx_http_request_t) -> Option<usize> {
let idx = LLM_ACCT_IDX.load(Ordering::Relaxed);
if idx < 0 {
return None;
}
// SAFETY: 索引在 postconfiguration 已解析;变量为 NOCACHEABLE,读即触发 get_handler
unsafe {
let v = ngx_http_get_indexed_variable(r, idx as ngx_uint_t);
if v.is_null() || (*v).not_found() != 0 || (*v).data.is_null() {
return None;
}
let s = core::str::from_utf8(core::slice::from_raw_parts(
(*v).data,
(*v).len() as usize,
))
.ok()?;
s.trim().parse::<usize>().ok()
}
}
// ===========================================================================
// log 阶段:对话审计 + token 入账
// ===========================================================================
/// LLM 对话审计(log 阶段):把被转发请求的 body 临时文件复制进审计目录。
///
/// 捕获机制与清理策略见 `llm_audit` 模块注释与 docs/llm/AUDIT_LOG.md。
/// 关键点:只依赖 `client_body_in_file_only clean` 留下的临时文件,本阶段
/// **不读请求体、不碰内存缓冲**——热路径与 SSE 透传完全无感知。
pub struct AuditHandler;
impl HttpRequestHandler for AuditHandler {
const PHASE: HttpPhase = HttpPhase::Log;
type Output = Status;
fn handler(request: &mut Request) -> Self::Output {
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
if !loc::enabled(r, Switch::Llm) {
return Status::NGX_DECLINED;
}
// 身份在 log 阶段重新解析:ukey shm 查询是纯内存读,代价可忽略;
// 换取 access→log 之间不挂任何请求级状态(无 ctx、无生命周期问题)。
// 请求已被转发过(有临时文件)才查得到 Key——被拒请求天然不入档。
let user = auth::downstream_key(r)
.and_then(|k| auth::identity(&k))
.map(|(u, _, _, _)| u);
let slot = llm::slot_of(r).unwrap_or_default();
// token 计量:body filter 旁路抓到的 usage(见 usage_filter 模块注释)
let (tin, tout) = usage_filter::take(r);
if tin > 0 || tout > 0 {
if let Some(name) = user.as_deref() {
stats::add_tokens(name, &slot, tin, tout, util::now());
}
// 账号级 token 负载(与账号级请求数同一个日桶维度 uda:)
let now = util::now();
if let Some(idx) = read_llm_acct(r) {
upstreams::add_acct_tokens(&slot, idx, tin as i64, tout as i64, now);
}
}
// SAFETY: 同上;capture 内部任何失败只记日志,绝不 panic
unsafe { llm_audit::capture(r, user.as_deref().unwrap_or("-"), &slot, tin, tout) };
Status::NGX_DECLINED
}
}
// 类型占位:NgxStr 在本 crate 被引用但暂未直接使用,保留编译期链接检查
#[allow(dead_code)]
fn _type_witness(_: &NgxStr) {}