Files
ipass__ipass/rust/gateway/src/lib.rs
T
admin 16cf68d132 feat(stats): 运行期统计落盘/恢复 + 审计口径收口 (1.0.18)
起因:发版后管理台「用量」与「趋势」从 0 重新长起来。根因是统计类键
(ust:/ums:/utt:/utms:/ud:/udu:/uds:/uda:/uex:/uh:)只活在共享内存,
进程退出即消失;而上游/账号/域名/用户都有 data/*.json 所以不丢。

统计落盘(新 stats_persist.rs):
- 快照 data/llm-stats.json(与 users.json 同级),原子写 <path>.tmp.<pid> + rename
- 两个落盘点互补:worker 退出钩子 exit_process(发版/docker stop,零丢失)
  + 记账后按间隔节流落盘(默认 60s,覆盖 SIGKILL/OOM/断电)
- 启动 init_process 恢复,put-if-absent → 多 worker 幂等、不覆盖新数据
- 白名单 10 个统计前缀;刻意排除配置类/ukb:/内核态(各有数据文件或重启清零更安全)
- 恢复结果发布 shm spr:last(不再放进程内静态量,否则接口落到哪个 worker 报哪个数)
- 接口 GET /api/admin/stats/persist + POST /api/admin/stats/dump
- 指令 ipass_stats_persist <秒>(0=只留退出钩子);生产 conf 刻意不写

fix(audit): excerpt 双重编码
- json_quote_bytes(手工转义+两侧引号)塞进 json!() 被二次转义,落盘成
  "excerpt":"\"{\\\"model\\\"…",解码后多一层引号,消费方全解析不到
- 改为 excerpt_text():只 from_utf8_lossy,转义交给 serde

docs: 新增 docs/llm/STATS_PERSISTENCE.md(含 runbook)、docs/llm/AUDIT_LOG.md
  (两者此前被代码注释与 Dockerfile 引用但文件并不存在)

tests:
- 新增【15】统计落盘/重启恢复 13 条(间隔压 1s → 快照产出与白名单 →
  nginx -s quit → 恢复键数 == 快照键数、用量不变、再打一笔 +1、趋势仍在)
- 【13】「不再生成 body 副本」改断言本轮增量 = 0(对历史残留免疫);
  选择器改 body_bytes>400 且取最后一条匹配(目录里有首版的双重编码行)
- run.sh 复位改用 mv(rename 不算删除)——本机 safe-delete 钩子在累计删除
  超 50 个文件后会静默拦掉后续删除,rm -rf 与 python rmtree 同样被拦
- 回归 298 全绿(网关 102 + LLM 196)
2026-09-14 19:32:17 +08:00

707 lines
27 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.
//! iPass 山海关(ipass-gateway)—— nginx + Rust 动态模块
//!
//! 尚数网 统一网关(动态域名 / LLM API 路由及未来各类统一出口能力)。
//!
//! 插件化定型后(2026-09-13),本 crate 仅作"装配壳":模块入口、7 条
//! `ipass_*` 指令、`ModuleConfig` 开关、`ApiHandler` content 阶段两段式读体
//! 后按 PLUGINS 顺序分发、trend 组合端点、state_zone_init 三表装载、
//! `init_process` 播种 admin + 审计目录启动巡检。具体业务实现都在
//! `crates/ipass-core` 与三个 `plugin-*` crate 里。
//!
//! ## 三条热路径
//!
//! | 入口 | 阶段 | 开关 | 做什么 |
//! | --- | --- | --- | --- |
//! | `*.yourdomain.com/*` | access | `ipass_proxy` | 查 `sub:` 决定后端 |
//! | `llm.yourdomain.com/<slot>/*` | access | `ipass_llm` | 查 `ukey:` 鉴权 + `up:` 定上游 |
//! | `llm.yourdomain.com/apix/<slug>` | access | `ipass_apix` | 同上鉴权,查 `ax:` 定供应商资产 |
//! | `proxy-api.yourdomain.com/api/*` | content | `ipass_api` | 管理接口,读体后分发 |
//!
//! ## 关键实现约束(均为实测/查证确认,详见 CLAUDE.md)
//!
//! * `ngx_http_add_variable` 必须在 **preconfiguration** 阶段调用,
//! 否则配置里的 `proxy_pass http://$proxy_backend_addr` 无法解析。
//! * 阶段处理器在 postconfiguration 阶段注册,且**必须按 location 开关**
//! (`ipass_proxy` / `ipass_api` / `ipass_llm`),否则管理台与 API
//! 也会被转发逻辑 404 掉。
//! * 共享内存只有 `RwLock<RbTreeMap<_, _, SlabPool>, _>` 一种安全形态;
//! `SlabPool` 只能在 zone 初始化回调里取出,锁本身也必须用
//! `ngx::allocator::allocate` 放进共享内存,否则各 worker 拿到的是各自的副本。
//! * ngx crate **没有**暴露请求体读取,必须走
//! `ngx_http_read_client_request_body` 的两段式异步接口(见 `ApiHandler`)。
//! **这也是 LLM 代理不按 body 里的 `model` 字段路由的原因**——access 阶段
//! 根本拿不到请求体。
mod api;
// 内核模块桥接:业务文件里的 `crate::config::X` / `crate::state::…` 等路径
// 不用改写,直接经此解析到 ipass-core(插件化 P0 的行为等价手段,
// 各业务模块随 P2–P4 迁入插件 crate 后,这里的 re-export 会逐个撤掉)。
pub use ipass_core::{config, http, models, session, state, store, users, util};
use core::ffi::{c_char, c_void};
use core::ptr;
use ngx::core::{NGX_CONF_ERROR, NGX_CONF_OK, NgxStr, NgxString, SlabPool, Status};
use serde_json::{Value, json};
use ngx::ffi::{
NGX_CONF_TAKE1, NGX_CONF_TAKE2, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MAIN_CONF,
NGX_HTTP_MAIN_CONF_OFFSET, NGX_HTTP_MODULE,
NGX_LOG_EMERG, ngx_command_t, ngx_conf_t, ngx_cycle_t,
ngx_http_module_t,
ngx_http_request_t, ngx_int_t, ngx_module_t, ngx_parse_size,
ngx_shared_memory_add, ngx_shm_zone_t, ngx_str_t, ngx_uint_t,
};
use ngx::http::{
HTTPStatus, HttpModule, HttpModuleLocationConf, HttpPhase, HttpRequestHandler, Merge,
MergeConfigError, Request,
};
use ngx::{ngx_conf_log_error, ngx_string};
use ipass_core::loc::{self, Switch};
use ipass_core::plugin::Plugin;
// ===========================================================================
// 插件装配(PLUGINS 顺序 = 认领顺序;身份类端点将来必须排最前)
// ===========================================================================
/// 装配根:trend 组合端点由 gateway 自己认领(见 `api::h_admin_trend`)。
struct GatewayRoutes;
impl Plugin for GatewayRoutes {
fn name(&self) -> &'static str {
"gateway-routes"
}
fn dispatch_api(&self, r: *mut ngx_http_request_t) -> Option<Status> {
api::dispatch(r)
}
}
/// 插件注册表。**身份类端点(CorePlugin)排在最前**:dispatch 按顺序认领,
/// 先注册者先得。装配顺序:内核(身份)→ 域名 → LLM → API 代理 → trend。
static PLUGINS: &[&dyn Plugin] = &[
&ipass_core::api::CorePlugin,
&plugin_domain::DomainPlugin,
&plugin_llm::LlmPlugin,
&plugin_apix::ApixPlugin,
&GatewayRoutes,
];
/// 装配根的插件扩展:把身份端点需要的插件侧数据回填给内核
/// (内核不认识任何插件,见 `ipass_core::api::CoreExt`)。
struct GatewayExt;
impl ipass_core::api::CoreExt for GatewayExt {
/// 管理台账号列表:域名数 + LLM 用量摘要(一次扫表,避免逐账号查共享内存)
fn decorate_admin_users(&self, views: &mut [Value]) {
let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
for d in plugin_domain::domains::all() {
*counts.entry(d.owner).or_insert(0) += 1;
}
let now = util::now();
let usage: std::collections::HashMap<String, plugin_llm::stats::UserUsage> =
plugin_llm::stats::all_users(now)
.into_iter()
.map(|u| (u.username.clone(), u))
.collect();
for v in views {
let Some(username) = v.get("username").and_then(Value::as_str).map(str::to_owned)
else {
continue;
};
if let Value::Object(ref mut m) = v {
let mut usage_json = json!({ "today": 0, "total": 0, "last_ts": 0, "last_ts_text": "" });
if let Some(uu) = usage.get(&username) {
usage_json = uu.usage.json();
}
m.insert(
"domain_count".to_owned(),
json!(counts.get(&username).copied().unwrap_or(0)),
);
// 今日 LLM 用量:与热路径同一数据源(共享内存)——注意口径是
// **已转发**的请求,不含被限流/越权拒掉的那些
m.insert(
"llm_today".to_owned(),
json!(usage.get(&username).map(|x| x.usage.today).unwrap_or(0)),
);
m.insert("llm_usage".to_owned(), usage_json);
}
}
}
/// `/api/v1/me`:我的域名 + 用量摘要 + 策略 TTL + **能力目录**(upstreams + apix)。
///
/// 能力目录让同事拿一把 key 一个 me 拿全,不再需要分别调
/// `/api/v1/upstreams` / `/api/v1/apix` / `/api/v1/domains`。
/// 老 3 个端点保留,客户端脚本不破坏。
///
/// LLM 上游按 `allowed_models` 白名单过滤(复用 `plugin_llm::upstreams::available`),
/// apix 只列 `enabled = true` 的代理(`plugin_apix::apix::enabled`),
/// 否则列表里出现「调就 404」让人误判网关坏掉。
/// `port` 从请求 Host 头取,**不要写死**——见 `plugin_apix::call_url` 注释。
fn decorate_me(&self, user: &ipass_core::models::User, port: &str, view: &mut Value) {
let Value::Object(ref mut m) = view else {
return;
};
m.insert(
"domains".to_owned(),
json!(plugin_domain::domains::view_all(
&plugin_domain::domains::by_owner(&user.username),
)),
);
// 用量摘要(明细走 /api/v1/usage)——让客户端一个请求就能决定要不要自我节流
m.insert(
"llm_usage".to_owned(),
plugin_llm::stats::user(&user.username, util::now()).json(),
);
m.insert(
"policy".to_owned(),
json!({
"temp_grant_ttl_hours": config::TEMP_GRANT_TTL / 3600,
"temp_domain_ttl_hours": plugin_domain::config::TEMP_DOMAIN_TTL / 3600,
}),
);
// 能力目录:upstreams(按白名单过滤)+ apix(仅 enabled)。
// 这两个 view_all 都返回完整结构(slot/base_url/models 或 slug/url/params/...),
// 同事拿到后能直接配客户端,不再需要二次问「这个 slot 怎么调」。
m.insert(
"upstreams".to_owned(),
json!(plugin_llm::upstreams::view_all(
&plugin_llm::upstreams::available(&user.allowed_models),
port,
)),
);
m.insert(
"apix".to_owned(),
json!(plugin_apix::apix::view_all(
&plugin_apix::apix::enabled(),
port,
)),
);
}
/// 删除账号:连带回收该账号名下的域名,避免出现无主映射
fn reclaim_on_delete(&self, username: &str) -> usize {
plugin_domain::domains::remove_by_owner(username)
}
/// 账号「可用上游」白名单校验:slot 必须真实存在,否则白名单里会存进
/// 永远匹配不上的死名字,表现为「账号被授权了却一直 403」
fn validate_slots(&self, slots: &[String]) -> Result<(), String> {
for slot in slots {
if plugin_llm::upstreams::get(slot).is_none() {
return Err(format!("上游 {slot} 不存在"));
}
}
Ok(())
}
}
/// gateway 注入给 `loc::enabled` 的查询实现:把 Switch 翻译到 ModuleConfig。
/// 未实现的变体(Iap / Domain)**保守返回 false**,绝不误开。
fn loc_switch(request: &mut Request, s: Switch) -> bool {
let conf = Module::location_conf(request);
match s {
Switch::Api => conf.map(|c| c.api).unwrap_or(false),
Switch::Proxy => conf.map(|c| c.proxy).unwrap_or(false),
Switch::Llm => conf.map(|c| c.llm).unwrap_or(false),
Switch::Apix => conf.map(|c| c.apix).unwrap_or(false),
Switch::Iap | Switch::Domain => false,
}
}
/// 管理 API 分发:按 PLUGINS 顺序问每个插件,都不认领才统一 404。
fn dispatch_api(r: *mut ngx_http_request_t) -> Status {
for p in PLUGINS {
if let Some(s) = p.dispatch_api(r) {
return s;
}
}
let method = http::method_str(r);
let uri = http::uri(r);
http::fail(
r,
HTTPStatus::NOT_FOUND,
&format!("接口不存在:{method} {uri}"),
)
}
/// 管理 API:content 阶段先读请求体,读完后交给 `api::dispatch`。
///
/// 这是本项目唯一需要异步的地方。`ngx_http_read_client_request_body` 是
/// **两段式**接口:请求体已在缓冲区时会**同步**调用 post_handler,
/// 否则挂起等 socket 事件后回调。两条路径都必须正确,所以不能假设
/// 「回调一定晚于本次返回」。
struct ApiHandler;
impl HttpRequestHandler for ApiHandler {
const PHASE: HttpPhase = HttpPhase::Content;
type Output = Status;
fn handler(request: &mut ngx::http::Request) -> Self::Output {
if !Module::location_conf(request).map(|c| c.api).unwrap_or(false) {
return Status::NGX_DECLINED;
}
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
// SAFETY: r 有效;回调只会在请求内存池存活期间被调用
let rc = unsafe { nginx_sys::ngx_http_read_client_request_body(r, Some(api_body_ready)) };
// 读体失败(请求体超限等):把原始状态码交回 nginx,由它生成对应错误页
if rc >= nginx_sys::NGX_HTTP_SPECIAL_RESPONSE as ngx_int_t {
return Status(rc);
}
// 响应由回调发出,本阶段到此挂起
Status::NGX_DONE
}
}
/// 请求体就绪回调:执行路由分发并终结请求。
unsafe extern "C" fn api_body_ready(r: *mut ngx_http_request_t) {
let status = dispatch_api(r);
// SAFETY: r 由 nginx 传入且仍然有效;NGX_OK 表示响应已完整发出
unsafe { nginx_sys::ngx_http_finalize_request(r, status.0) };
}
// ===========================================================================
// 模块定义
// ===========================================================================
struct Module;
/// 按 location 生效的开关。
///
/// 必须存在:阶段处理器注册在 http 主配置上,若不按 location 收敛,
/// 管理台与 API 也会走转发逻辑并被 404。
#[derive(Debug, Default)]
struct ModuleConfig {
/// 该 location 走「子域名 → 后端」转发
proxy: bool,
/// 该 location 暴露管理 API(/api/admin/*、/api/v1/*)
api: bool,
/// 该 location 走 LLM 代理(`/<slot>/...` → 上游)
llm: bool,
/// 该 location 走 API 代理(`/apix/<slug>` → 外部供应商)
apix: bool,
}
unsafe impl HttpModuleLocationConf for Module {
type LocationConf = ModuleConfig;
}
impl Merge for ModuleConfig {
fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> {
if prev.proxy {
self.proxy = true;
}
if prev.api {
self.api = true;
}
if prev.llm {
self.llm = true;
}
if prev.apix {
self.apix = true;
}
Ok(())
}
}
impl HttpModule for Module {
fn module() -> &'static ngx_module_t {
// SAFETY: 模块定义是静态的,生命周期贯穿进程
unsafe { &*ptr::addr_of!(ngx_http_ipass_module) }
}
/// 必须在配置解析前注册变量,否则 `proxy_pass http://$proxy_backend_addr` 无法解析
unsafe extern "C" fn preconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t {
// 契约层:注入 location 开关查询实现(早于任何请求与 phase handler)
loc::set_switch_fn(loc_switch);
// 装配根注册插件扩展:身份端点所需的插件侧数据经它回填内核
ipass_core::api::set_ext(&GatewayExt);
// 各插件注册自己的 nginx 变量($proxy_backend_addr 归 plugin-domain、
// LLM 三件套归 plugin-llm、API 代理六件套归 plugin-apix)
for p in PLUGINS {
if !p.preconfig(cf) {
ngx_conf_log_error!(
NGX_LOG_EMERG,
unsafe { &mut *cf },
"插件 {} 变量注册失败",
p.name()
);
return Status::NGX_ERROR.into();
}
}
Status::NGX_OK.into()
}
unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t {
let cf = unsafe { &mut *cf };
// 把本模块 ctx_index 注入内核契约:插件在 r->ctx 上挂请求级状态
// (如 plugin-llm 的 usage_filter 扫描窗口)用它定位自己的槽位
ipass_core::plugin::set_ctx_index(Module::module().ctx_index as usize);
// 各插件注册自己的 phase handler(ResolveHandler 归 plugin-domain、
// LlmHandler/LlmHealthHandler/AuditHandler 归 plugin-llm、
// ApiProxyHandler 归 plugin-apix)
for p in PLUGINS {
if !p.postconfig(cf) {
return Status::NGX_ERROR.into();
}
}
if ngx::http::add_phase_handler::<ApiHandler>(cf).is_err() {
return Status::NGX_ERROR.into();
}
Status::NGX_OK.into()
}
}
static mut NGX_HTTP_IPASS_COMMANDS: [ngx_command_t; 9] = [
ngx_command_t {
name: ngx_string!("ipass_state"),
type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t,
set: Some(set_state_zone),
conf: NGX_HTTP_MAIN_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("ipass_data_dir"),
type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(set_data_dir),
conf: NGX_HTTP_MAIN_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("ipass_audit_dir"),
type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(set_audit_dir),
conf: NGX_HTTP_MAIN_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("ipass_stats_persist"),
type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(set_stats_persist),
conf: NGX_HTTP_MAIN_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("ipass_proxy"),
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(set_flag_proxy),
conf: NGX_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("ipass_api"),
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(set_flag_api),
conf: NGX_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("ipass_llm"),
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(set_flag_llm),
conf: NGX_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("ipass_apix"),
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(set_flag_apix),
conf: NGX_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t::empty(),
];
static NGX_HTTP_IPASS_MODULE_CTX: ngx_http_module_t = ngx_http_module_t {
preconfiguration: Some(Module::preconfiguration),
postconfiguration: Some(Module::postconfiguration),
create_main_conf: None,
init_main_conf: None,
create_srv_conf: None,
merge_srv_conf: None,
create_loc_conf: Some(Module::create_loc_conf),
merge_loc_conf: Some(Module::merge_loc_conf),
};
// 脱离 nginx 构建系统、单独产出 cdylib 时必须靠这个宏导出 ngx_modules 表
#[cfg(feature = "export-modules")]
ngx::ngx_modules!(ngx_http_ipass_module);
#[used]
#[allow(non_upper_case_globals)]
pub static mut ngx_http_ipass_module: ngx_module_t = ngx_module_t {
ctx: &raw const NGX_HTTP_IPASS_MODULE_CTX as _,
commands: unsafe { &raw mut NGX_HTTP_IPASS_COMMANDS[0] },
type_: NGX_HTTP_MODULE as _,
init_process: Some(init_process),
exit_process: Some(exit_process),
..ngx_module_t::default()
};
/// 每个 worker 启动后执行一次。管理员播种是**幂等**的:
/// 文件里已有任何账号就直接跳过,所以多 worker 同时跑不会重复创建。
unsafe extern "C" fn init_process(_cycle: *mut ngx_cycle_t) -> ngx_int_t {
match users::seed_admin() {
Ok(true) => util::log_warn(
"[ipass] 已创建初始管理员 admin,请首次登录后立即修改密码",
),
Ok(false) => {}
Err(e) => util::log_err(&format!("[ipass] 初始化管理员失败: {e}")),
}
// 对话审计:确保目录存在 + 容量巡检一次(此后由请求写入节流触发)
plugin_llm::llm_audit::startup();
// 运行期统计:把上一次退出时落盘的快照灌回共享内存。
// **放在每个 worker 里跑是刻意的**:恢复是「键不存在才写」(put-if-absent),
// 第一个 worker 恢复完,其余 worker 全部跳过 —— 天然幂等,不会把计数恢复成 N 倍。
// 详见 plugin_llm::stats_persist 模块注释 / docs/llm/STATS_PERSISTENCE.md。
plugin_llm::stats_persist::restore();
Status::NGX_OK.into()
}
/// worker 退出前执行一次(nginx 的 `exit_process` 钩子)。
///
/// **这是「发版不丢统计」的关键**:共享内存随进程消失,而用量/趋势只活在共享内存里,
/// 所以必须在退出前落一次盘。`docker stop` 发的是镜像声明的 `STOPSIGNAL=SIGQUIT`
/// (优雅停机),`SIGTERM` 也走同一条 worker 退出路径 —— 两者都会到这里。
/// 只有 `SIGKILL`(`rm -f` 超时兜底 / OOM / 断电)绕过它,那由周期落盘兜住
/// (见 `stats_persist::maybe_dump`,默认 60 秒一次)。
///
/// 多 worker 会各落一次:内容本就只是「同一份共享内存的近似快照」,
/// 写临时文件带 pid、`rename` 原子,谁最后赢都对。
unsafe extern "C" fn exit_process(_cycle: *mut ngx_cycle_t) {
if let Err(e) = plugin_llm::stats_persist::dump_now("worker-exit") {
util::log_err(&format!("[stats] 退出落盘失败:{e}"));
}
}
// ===========================================================================
// 指令处理
// ===========================================================================
/// 读第 2 个参数并转成 bool(on/off/1/0/yes/no)。
unsafe fn arg_flag(cf: *mut ngx_conf_t, idx: usize) -> Option<bool> {
let cf_ref = unsafe { cf.as_mut() }?;
let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() };
let raw = args.get(idx)?.as_bytes();
let s = core::str::from_utf8(raw).ok()?;
Some(matches!(s.to_ascii_lowercase().as_str(), "on" | "1" | "true" | "yes"))
}
extern "C" fn set_flag_proxy(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
let Some(flag) = (unsafe { arg_flag(cf, 1) }) else {
return NGX_CONF_ERROR;
};
// SAFETY: nginx 保证 conf 指向本模块的 loc conf 结构
unsafe { (*(conf as *mut ModuleConfig)).proxy = flag };
NGX_CONF_OK
}
extern "C" fn set_flag_api(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
let Some(flag) = (unsafe { arg_flag(cf, 1) }) else {
return NGX_CONF_ERROR;
};
// SAFETY: 同上
unsafe { (*(conf as *mut ModuleConfig)).api = flag };
NGX_CONF_OK
}
extern "C" fn set_flag_llm(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
let Some(flag) = (unsafe { arg_flag(cf, 1) }) else {
return NGX_CONF_ERROR;
};
// SAFETY: 同上
unsafe { (*(conf as *mut ModuleConfig)).llm = flag };
NGX_CONF_OK
}
extern "C" fn set_flag_apix(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
let Some(flag) = (unsafe { arg_flag(cf, 1) }) else {
return NGX_CONF_ERROR;
};
// SAFETY: 同上
unsafe { (*(conf as *mut ModuleConfig)).apix = flag };
NGX_CONF_OK
}
extern "C" fn set_state_zone(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
_conf: *mut c_void,
) -> *mut c_char {
// SAFETY: 配置回调必然拿到有效的 cf
let cf_ref = unsafe { cf.as_mut().unwrap() };
let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() };
let mut name: ngx_str_t = args[1];
let size = unsafe { ngx_parse_size(&raw mut args[2]) };
if size == -1 {
ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "ipass_state: 共享内存大小非法");
return NGX_CONF_ERROR;
}
let zone = unsafe {
ngx_shared_memory_add(
cf,
&raw mut name,
size as usize,
(&raw mut ngx_http_ipass_module).cast(),
)
};
if zone.is_null() {
return NGX_CONF_ERROR;
}
unsafe {
(*zone).init = Some(state_zone_init);
}
state::set_zone(zone);
NGX_CONF_OK
}
/// 共享内存初始化:由 nginx 在 **fork 之前**调用一次。
///
/// 在这里装载三张表,所有 worker 直接共享结果——比放在
/// `init_process`(每个 worker 各跑一遍)省掉 N-1 次文件读与 JSON 解析。
extern "C" fn state_zone_init(zone: *mut ngx_shm_zone_t, _data: *mut c_void) -> ngx_int_t {
let status = state::init_zone(zone);
if status != Status::NGX_OK {
return status.into();
}
// 插件注册「删账号要清什么」:gateway 装配了 plugin_llm 的 stats(用量账本),
// 就要在这里挂上清理钩子——内核自己不认识 ust:/utt: 这些键(P0 起钩子化)。
// on_delete 内部按函数指针去重,nginx reload 重复走到这里也安全。
users::on_delete(plugin_llm::stats::forget);
let loaded = plugin_domain::domains::reload_shm();
util::log_notice(&format!("[ipass] 共享内存已装载 {loaded} 条转发映射"));
// 账号 Key 与 LLM 上游 / API 代理必须一起进内存:各热路径未命中即
// 401 / 404,没有任何回源兜底(同 domains 的写穿语义)。
// 上游表装载归 plugin-llm、代理表装载归 plugin-apix。
let keys = users::reload_shm();
let ups = plugin_llm::upstreams::reload_shm();
let axs = plugin_apix::apix::reload_shm();
util::log_notice(&format!(
"[ipass] 已装载 {keys} 个账号 Key、{ups} 个 LLM 上游、{axs} 个 API 代理"
));
Status::NGX_OK.into()
}
extern "C" fn set_data_dir(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
_conf: *mut c_void,
) -> *mut c_char {
// SAFETY: 配置回调必然拿到有效的 cf
let cf_ref = unsafe { cf.as_mut().unwrap() };
let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() };
match core::str::from_utf8(args[1].as_bytes()) {
Ok(dir) => {
store::set_data_dir(dir);
NGX_CONF_OK
}
Err(_) => {
ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "ipass_data_dir: 路径不是合法 UTF-8");
NGX_CONF_ERROR
}
}
}
/// `ipass_audit_dir <path>`:LLM 对话审计根目录。缺省 = data 目录的兄弟目录。
extern "C" fn set_audit_dir(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
_conf: *mut c_void,
) -> *mut c_char {
// SAFETY: 配置回调必然拿到有效的 cf
let cf_ref = unsafe { cf.as_mut().unwrap() };
let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() };
match core::str::from_utf8(args[1].as_bytes()) {
Ok(dir) => {
plugin_llm::llm_audit::set_dir(dir);
NGX_CONF_OK
}
Err(_) => {
ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "ipass_audit_dir: 路径不是合法 UTF-8");
NGX_CONF_ERROR
}
}
}
/// `ipass_stats_persist <秒>`:运行期统计(用量 / 趋势 / 账号负载)的周期落盘间隔。
///
/// 缺省 60 秒;`0` = 关闭周期落盘,只保留 worker 退出钩子那一次(见 `exit_process`)。
/// 调小它只为缩短「被 SIGKILL 时最多丢多久」,正常发版走退出钩子,本来就是零丢失。
extern "C" fn set_stats_persist(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
_conf: *mut c_void,
) -> *mut c_char {
// SAFETY: 配置回调必然拿到有效的 cf
let cf_ref = unsafe { cf.as_mut().unwrap() };
let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() };
let Ok(raw) = core::str::from_utf8(args[1].as_bytes()) else {
ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "ipass_stats_persist: 不是合法 UTF-8");
return NGX_CONF_ERROR;
};
let Ok(secs) = raw.trim().parse::<i64>() else {
ngx_conf_log_error!(
NGX_LOG_EMERG,
cf_ref,
"ipass_stats_persist: 需要非负整数秒(0 = 只靠退出钩子)"
);
return NGX_CONF_ERROR;
};
if secs < 0 {
ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "ipass_stats_persist: 秒数不能为负");
return NGX_CONF_ERROR;
}
plugin_llm::stats_persist::set_interval(secs);
NGX_CONF_OK
}
/// 供测试与诊断使用:`NgxStr` 类型在模块里被多处引用,确保编译期链接到正确的符号
#[allow(dead_code)]
fn _type_witness(_: &NgxStr, _: &NgxString<SlabPool>) {}