From 85ea0a1531963b06e3731c4f79dd9099b375a0ed Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 13 Sep 2026 12:16:47 +0800 Subject: [PATCH] =?UTF-8?q?refactor(plugin):=20P4=20=E6=8B=86=20plugin-api?= =?UTF-8?q?x=20=E2=80=94=E2=80=94=20API=20=E4=BB=A3=E7=90=86=E8=BF=81?= =?UTF-8?q?=E5=85=A5=E7=8B=AC=E7=AB=8B=E6=8F=92=E4=BB=B6=EF=BC=8C=E8=BF=87?= =?UTF-8?q?=E6=B8=A1=E6=9C=9F=E8=B7=AF=E7=94=B1=E6=B8=85=E7=A9=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - plugin-apix 新 crate:apix/handlers/api/config/models/store - ApiProxy/ApiProxyStore、api-proxies.json 读写、ax: 键空间与 APIX_* 常量自内核迁入 - ApiProxyHandler 与 $apix_* 六变量注册归 ApixPlugin;用量记账仍走 plugin_llm::stats(同一片键空间、单一写入口) - gateway 路由表只剩 trend 组合端点(需 users+upstreams+apix 三方名册) - 行为等价:262 项回归全绿(gateway 102 + llm 160) --- rust/Cargo.lock | 13 ++ rust/Cargo.toml | 3 +- rust/crates/ipass-core/src/config.rs | 45 ----- rust/crates/ipass-core/src/models.rs | 60 ------ rust/crates/ipass-core/src/store.rs | 34 +--- rust/crates/plugin-apix/Cargo.toml | 20 ++ rust/crates/plugin-apix/src/api.rs | 179 ++++++++++++++++++ .../plugin-apix}/src/apix.rs | 83 ++++++-- rust/crates/plugin-apix/src/config.rs | 44 +++++ rust/crates/plugin-apix/src/handlers.rs | 91 +++++++++ rust/crates/plugin-apix/src/lib.rs | 56 ++++++ rust/crates/plugin-apix/src/models.rs | 66 +++++++ rust/crates/plugin-apix/src/store.rs | 35 ++++ rust/gateway/Cargo.toml | 1 + rust/gateway/src/api.rs | 161 ++-------------- rust/gateway/src/lib.rs | 150 ++------------- 16 files changed, 606 insertions(+), 435 deletions(-) create mode 100644 rust/crates/plugin-apix/Cargo.toml create mode 100644 rust/crates/plugin-apix/src/api.rs rename rust/{gateway => crates/plugin-apix}/src/apix.rs (87%) create mode 100644 rust/crates/plugin-apix/src/config.rs create mode 100644 rust/crates/plugin-apix/src/handlers.rs create mode 100644 rust/crates/plugin-apix/src/lib.rs create mode 100644 rust/crates/plugin-apix/src/models.rs create mode 100644 rust/crates/plugin-apix/src/store.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 46a5224..bd8a2c1 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -194,6 +194,7 @@ dependencies = [ "libc", "nginx-sys", "ngx", + "plugin-apix", "plugin-domain", "plugin-llm", "serde", @@ -290,6 +291,18 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "plugin-apix" +version = "2.0.0" +dependencies = [ + "ipass-core", + "nginx-sys", + "ngx", + "plugin-llm", + "serde", + "serde_json", +] + [[package]] name = "plugin-domain" version = "2.0.0" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 86d4a98..4ca9b5d 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -5,7 +5,7 @@ # panic="abort" 丢了就意味着 panic 可能跨 FFI 边界展开进 nginx。 [workspace] resolver = "2" -members = ["crates/ipass-core", "crates/plugin-domain", "crates/plugin-llm", "gateway"] +members = ["crates/ipass-core", "crates/plugin-domain", "crates/plugin-llm", "crates/plugin-apix", "gateway"] # 独立 workspace:vendored 的 ngx-rust 本身是 workspace 根,需显式排除以免歧义 exclude = ["vendor/ngx-rust"] @@ -41,6 +41,7 @@ libc = "0.2" # 仅用于 localtime_r / time(旧版由 os.date / ngx ipass-core = { path = "crates/ipass-core" } plugin-domain = { path = "crates/plugin-domain" } plugin-llm = { path = "crates/plugin-llm" } +plugin-apix = { path = "crates/plugin-apix" } [profile.release] opt-level = 3 diff --git a/rust/crates/ipass-core/src/config.rs b/rust/crates/ipass-core/src/config.rs index 9e05c59..241bad3 100644 --- a/rust/crates/ipass-core/src/config.rs +++ b/rust/crates/ipass-core/src/config.rs @@ -86,48 +86,3 @@ pub const KEY_BUF_LEN: usize = 128; /// LLM 代理对外域名,用于账号态 API 回显 `base_url`(apix 的「复制地址」也用它)。 /// 改域名只改这里(`conf/nginx.conf` 的 LLM server_name 要同步改)。 pub const LLM_PUBLIC_HOST: &str = "lm.mayishangshu.cn"; - -// =========================================================================== -// API 代理(apix):把外部供应商的 API 资产挂到网关下(P4 迁入 plugin-apix) -// =========================================================================== -// -// 与 LLM 代理的关系:同一把 `sk_` 下行 Key、同一套限流与统计, -// 但每条 apix 记录自带「基址 + 供应商 Key + 资产 id」——不同供应商互不影响 -// (见 `models::ApiProxyStore`),所以 slug 只映射到 `asset_id`。 - -/// shm 键前缀:slug → `base \n 供应商Key \n asset_id`。 -/// -/// 三行塞一个键是刻意的:热路径只查一次表就拿到转发所需全部信息。 -/// 代价是改某条凭据要重新同步该条目(条目数是个位数,无所谓)。 -pub const KEY_AX_PREFIX: &[u8] = b"ax:"; - -/// 供应商「调用资产」路径(`POST {base}{path}`,body = `{"asset_id":..,"call_data":{..}}`)。 -/// 每条 apix 记录都按这个路径转发——它定义了该供应商接口所遵循的协议。 -pub const APIX_REQUEST_PATH: &str = "/api/v1/ai/request"; -/// 供应商「费用预估」路径。**免费**,且响应里带余额——管理台的 -/// 「测试」按钮走它:既能验 Key 通不通,又能看到还剩多少余额,不花一分钱。 -pub const APIX_ESTIMATE_PATH: &str = "/api/v1/ai/estimate"; - -/// slug 长度上限 -pub const APIX_SLUG_MAX_LEN: usize = 32; -/// 供应商基址长度上限 -pub const APIX_URL_MAX_LEN: usize = 200; -/// 展示名 / 说明长度上限 -pub const APIX_NAME_MAX_LEN: usize = 64; -pub const APIX_DESC_MAX_LEN: usize = 200; -/// asset_id 长度上限 -pub const APIX_ASSET_MAX_LEN: usize = 64; -/// 单条目声明的参数个数上限 -pub const APIX_PARAM_MAX: usize = 16; -/// 单次调用允许的 query 参数个数上限(挡住拼超长 URL 刷共享内存) -pub const APIX_ARG_MAX: usize = 32; -/// 单个参数值长度上限(bytes) -pub const APIX_VAL_MAX: usize = 4096; -/// 供应商 Key 长度上限 -pub const APIX_KEY_MAX_LEN: usize = 128; -/// 用量统计里 API 代理的 slot 前缀。 -/// -/// 与 LLM 的 slot 刻意区分开:`uds::<日窗>` 是**同一片键空间**, -/// 而 LLM slot 的字符集不含 `/`(见 `upstreams::validate_slot`), -/// 所以 `api/` 绝不会和 LLM 上游撞车,用量页能自然分成两组。 -pub const APIX_STATS_PREFIX: &str = "api/"; diff --git a/rust/crates/ipass-core/src/models.rs b/rust/crates/ipass-core/src/models.rs index 0071cec..128fb09 100644 --- a/rust/crates/ipass-core/src/models.rs +++ b/rust/crates/ipass-core/src/models.rs @@ -61,10 +61,6 @@ impl User { } -fn default_true() -> bool { - true -} - fn default_llm_rpm() -> i64 { crate::config::LLM_RPM_DEFAULT } @@ -72,59 +68,3 @@ fn default_llm_rpm() -> i64 { fn default_llm_daily() -> i64 { crate::config::LLM_DAILY_DEFAULT } - -/// API 代理表(`api-proxies.json`)。 -/// -/// 与 `llm-upstreams.json` 同构:每条记录 = 一个供应商(自带基址与密钥), -/// 由 `slug` 区分。调用方访问 `/apix/?参数=值`,网关用本记录里的密钥 -/// 转发到供应商、并把响应原样返回。不同供应商彼此独立、互不耦合。 -/// -/// `key` 是供应商真 Key,**敏感级别等同 `users.json`**(data/ 已 gitignore)。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ApiProxyStore { - /// slug → 代理映射 - #[serde(default)] - pub items: BTreeMap, -} - -impl Default for ApiProxyStore { - fn default() -> Self { - Self { items: BTreeMap::new() } - } -} - -/// 单个 API 代理条目:指向某一家供应商的一个可调用的资产。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ApiProxy { - /// 供应商侧的资产 id(如 `searxng-search`),决定具体调用哪个资产 - pub asset_id: String, - /// 供应商名称(仅展示用,管理员自填,例如 `provider-x` / 客户自定) - #[serde(default)] - pub supplier: String, - /// 供应商基址,如 `https://api.example.com` - #[serde(default)] - pub base: String, - /// 供应商 API Key(`ak_...`)。留空 = 未配置,热路径直接 503。 - /// **敏感**:写盘与回显都按密钥处理,管理台只回显掩码。 - #[serde(default)] - pub key: String, - /// 展示名(中文) - #[serde(default)] - pub name: String, - /// 一句话说明 - #[serde(default)] - pub desc: String, - /// **声明式参数清单**(如 `["q"]`)。 - /// - /// 只用于给调用方看的文档(管理台把 `?q=关键词` 拼出来、账号态接口回显), - /// 转发时**不按它过滤**——过滤要靠读请求体,而 access 阶段读不到。 - /// 供应商侧自己会拒绝不认识的参数,拦在网关意义不大。 - #[serde(default)] - pub params: Vec, - #[serde(default = "default_true")] - pub enabled: bool, - #[serde(default)] - pub note: String, - #[serde(default)] - pub created_at: i64, -} diff --git a/rust/crates/ipass-core/src/store.rs b/rust/crates/ipass-core/src/store.rs index 6fb1d97..ae75713 100644 --- a/rust/crates/ipass-core/src/store.rs +++ b/rust/crates/ipass-core/src/store.rs @@ -12,7 +12,7 @@ //! //! 闭包返回 `Err` 表示业务校验失败,此时**不落盘**(与旧版 `fn` 返回 nil 一致)。 //! -//! ## 三个表的分工 +//! ## 表的分工 //! //! | 文件 | 内容 | 是否进共享内存 | //! | --- | --- | --- | @@ -21,14 +21,16 @@ //! | `llm-upstreams.json` | LLM 上游基址与密钥 | `up:` 进(LLM 转发热路径) | //! | `api-proxies.json` | API 代理清单(每条含各自供应商凭据) | `ax:` 进(API 代理热路径) | //! -//! 四个文件都在 `data/` 下,都已 `.gitignore`。**LLM 上游表含上游真 Key, -//! 敏感级别与 `users.json` 相同**,不要再往别处复制。 +//! 内核只直接管 `users.json`;其余数据文件由各插件经 `path_in_data` + +//! 通用读写原语自管(plugin-domain / plugin-llm / plugin-apix)。四个文件 +//! 都在 `data/` 下,都已 `.gitignore`。**LLM 上游表与 API 代理表含真实 +//! 供应商 Key,敏感级别与 `users.json` 相同**,不要再往别处复制。 use std::path::PathBuf; use std::sync::Mutex; use crate::config::DEFAULT_DATA_DIR; -use crate::models::{ApiProxyStore, UserTable}; +use crate::models::UserTable; use crate::state; /// 状态目录。配置阶段由 `ipass_data_dir` 指令设置一次,之后只读。 @@ -56,10 +58,6 @@ pub fn users_path() -> PathBuf { path_of("users.json") } -pub fn api_proxies_path() -> PathBuf { - path_of("api-proxies.json") -} - /// data 目录下任意文件的路径(插件用它管理自己的数据文件, /// 如 plugin-domain 的 `domains.json`) pub fn path_in_data(name: &str) -> PathBuf { @@ -115,18 +113,10 @@ pub fn read_users() -> UserTable { read_json(&users_path(), UserTable::new()) } -pub fn read_api_proxies() -> ApiProxyStore { - read_json(&api_proxies_path(), ApiProxyStore::default()) -} - pub fn write_users(data: &UserTable) -> Result<(), String> { write_json(&users_path(), data) } -pub fn write_api_proxies(data: &ApiProxyStore) -> Result<(), String> { - write_json(&api_proxies_path(), data) -} - /// 加锁「读-改-写」账号表。 /// /// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。 @@ -140,15 +130,3 @@ where write_users(&data)?; Ok(out) } - -/// 加锁「读-改-写」API 代理表 -pub fn update_api_proxies(f: F) -> Result -where - F: FnOnce(&mut ApiProxyStore) -> Result, -{ - let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?; - let mut data = read_api_proxies(); - let out = f(&mut data)?; - write_api_proxies(&data)?; - Ok(out) -} diff --git a/rust/crates/plugin-apix/Cargo.toml b/rust/crates/plugin-apix/Cargo.toml new file mode 100644 index 0000000..bd33984 --- /dev/null +++ b/rust/crates/plugin-apix/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "plugin-apix" +version = "2.0.0" +edition.workspace = true +publish = false +description = "iPass 插件:API 代理(外部供应商资产挂网关,复用 LLM 下行契约)" + +[lib] +# 只有 gateway 是 cdylib;插件一律 rlib(跨 .so 传 Rust 类型会双重 free) +crate-type = ["rlib"] + +[dependencies] +ngx.workspace = true +nginx-sys.workspace = true +serde.workspace = true +serde_json.workspace = true +ipass-core.workspace = true +# 用量记账:apix 与 LLM 共用同一片 ust:/ums:/ud: 键空间(slot 带 api/ 前缀归组), +# 记账入口只有一个(plugin_llm::stats),避免两份写入口漂移 +plugin-llm.workspace = true diff --git a/rust/crates/plugin-apix/src/api.rs b/rust/crates/plugin-apix/src/api.rs new file mode 100644 index 0000000..9df6145 --- /dev/null +++ b/rust/crates/plugin-apix/src/api.rs @@ -0,0 +1,179 @@ +//! API 代理(apix)插件的管理 API 端点。 +//! +//! 鉴权语义与内核共用一套:`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}; +use ipass_core::{http, util}; + +use crate::apix; + +// =========================================================================== +// 路由 +// =========================================================================== + +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/apix") => (Guard::Admin, h_admin_apix), + ("POST", "/api/admin/apix/save") => (Guard::Admin, h_admin_apix_save), + ("POST", "/api/admin/apix/delete") => (Guard::Admin, h_admin_apix_delete), + ("POST", "/api/admin/apix/test") => (Guard::Admin, h_admin_apix_test), + ("GET", "/api/v1/apix") => (Guard::User, h_my_apix), + _ => return None, + }; + Some(entry) +} + +/// 本表分发:认领则返回响应状态,不认领返回 `None`(交给下一个插件)。 +pub fn dispatch(r: *mut ngx_http_request_t) -> Option { + 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)) +} + +// =========================================================================== +// 管理员 +// =========================================================================== + +/// 管理员:API 代理清单 +fn h_admin_apix(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let port = http::host_port(r); + let list = apix::all(); + http::ok( + r, + json!({ + "items": apix::view_all(&list, &port), + "count": list.len(), + }), + "ok", + ) +} + +/// 管理员:新增/修改一个 API 代理条目 +fn h_admin_apix_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let slug = p.get("slug").cloned().unwrap_or_default(); + let asset = p.get("asset_id").cloned().unwrap_or_default(); + + // 参数清单允许两种写法:逗号分隔(`q,format`)或 JSON 数组(`["q"]`) + let params = p.get("params").and_then(|v| { + let v = util::trim(v); + if v.is_empty() { + return None; + } + Some(if let Ok(Value::Array(arr)) = serde_json::from_str::(v) { + arr.into_iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect::>() + } else { + v.split(',').map(str::to_owned).collect::>() + }) + }); + + // 不带 enabled 视为「启用」:新建表单里漏勾是常见手滑,默认值取更安全的一侧 + let enabled = match p.get("enabled") { + Some(v) => util::to_bool(Some(v)), + None => true, + }; + + match apix::upsert( + &slug, + &asset, + p.get("base"), + p.get("key"), + p.get("supplier"), + p.get("name"), + p.get("desc"), + params, + enabled, + p.get("note"), + ) { + Ok(item) => { + util::log_notice(&format!("[api] 保存 API 代理 {slug} → {asset}")); + http::ok(r, json!({ "slug": slug, "asset_id": item.asset_id }), "已保存") + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +/// 管理员:删除一个 API 代理条目 +fn h_admin_apix_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + match apix::remove(p.get("slug").map(String::as_str).unwrap_or("")) { + Ok(slug) => { + util::log_notice(&format!("[api] 删除 API 代理 {slug}")); + http::ok(r, json!({ "slug": slug }), "已删除") + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +/// 管理员:探测供应商 Key 是否可用(管理台「测试」按钮)。 +/// +/// 走供应商的**免费预估**接口(`/api/v1/ai/estimate`):它不执行资产、不扣费, +/// 响应里还带 `current_balance_usd` —— 一次调用同时拿到「Key 通不通」和 +/// 「还剩多少钱」。实现上内部重定向到管理 server 的 `/_apix_probe/`, +/// 复用 `$apix_probe_*` 变量(拼体、换 Key 与真实转发同一套逻辑)。 +fn h_admin_apix_test(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let slug_raw = http::params(r).get("slug").cloned().unwrap_or_default(); + let slug = match apix::validate_slug(&slug_raw) { + Ok(s) => s, + Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e), + }; + if apix::lookup(&slug).is_none() { + return http::fail(r, HTTPStatus::NOT_FOUND, &format!("代理 {slug} 不存在或已停用")); + } + + let uri = format!("{}{}", apix::PROBE_URI_PREFIX, slug); + util::log_notice(&format!("[api] 测试 API 代理 {slug}")); + + // ⚠️ 与 LLM 上游测试同一个坑:internal_redirect 只浅拷贝 ngx_str_t, + // 必须把字节拷进请求池,否则函数返回后 r->uri 全是 NUL(实测踩过)。 + // 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: core::ptr::null_mut(), + }; + nginx_sys::ngx_http_internal_redirect(r, &mut u, &mut args); + } + + Status::NGX_DONE +} + +// =========================================================================== +// 账号态 +// =========================================================================== + +/// 账号态:列出当前可用的 API 代理及调用地址 +fn h_my_apix(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let port = http::host_port(r); + let items: Vec = apix::all() + .into_iter() + .filter(|(_, it)| it.enabled) + .map(|(slug, it)| apix::view(&slug, &it, &port)) + .collect(); + http::ok(r, json!({ "items": items, "count": items.len() }), "ok") +} diff --git a/rust/gateway/src/apix.rs b/rust/crates/plugin-apix/src/apix.rs similarity index 87% rename from rust/gateway/src/apix.rs rename to rust/crates/plugin-apix/src/apix.rs index fe8b674..cdec8c3 100644 --- a/rust/gateway/src/apix.rs +++ b/rust/crates/plugin-apix/src/apix.rs @@ -1,7 +1,7 @@ //! API 代理:把外部供应商的 API 资产挂到网关下。 //! -//! 与 LLM 代理(`llm.rs`)是**同一套下行契约**——都认 `sk_` 那把 Key、都吃 -//! 同一份限流配额、都进同一套用量统计——差别只在上游形态: +//! 与 LLM 代理(`plugin_llm`)是**同一套下行契约**——都认 `sk_` 那把 Key、 +//! 都吃同一份限流配额、都进同一套用量统计——差别只在上游形态: //! //! | | LLM 代理 | API 代理 | //! | --- | --- | --- | @@ -18,22 +18,78 @@ //! 调用方只能决定参数。 //! //! 反过来,参数只能走 **query string**:转发决策在 access 阶段,而请求体 -//! 要到 content 阶段才读得到(见 `llm.rs` 模块头注释)。nginx 侧靠 +//! 要到 content 阶段才读得到(见 `plugin_llm::llm` 模块头注释)。nginx 侧靠 //! `proxy_method POST` + `proxy_set_body $apix_body` 把 GET 变成 //! 带体的 POST,网关不需要自己实现 upstream。 //! //! `data/api-proxies.json` 含供应商真 Key,**敏感级别等同 `users.json`**。 -use ngx::core::Status; -use ngx::ffi::{ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t}; +use ngx::core::{Pool, Status}; +use ngx::ffi::{ + NGX_HTTP_VAR_CHANGEABLE, NGX_HTTP_VAR_NOCACHEABLE, ngx_conf_t, ngx_http_add_variable, + ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t, ngx_str_t, ngx_uint_t, +}; +use ngx::ngx_string; use serde_json::{Value, json}; use crate::config; -use crate::http; use crate::models::{ApiProxy, ApiProxyStore}; -use crate::state; use crate::store; -use crate::util; +use ipass_core::config::LLM_PUBLIC_HOST; +use ipass_core::{http, state, util}; + +// =========================================================================== +// preconfiguration:注册变量 +// =========================================================================== + +/// 注册 API 代理六件套只读变量(gateway preconfiguration 经插件循环调用)。 +/// +/// 前缀 `apix_` 与 `llm_` 同理:nginx 变量名全局唯一,将来接入别的模块时 +/// 才不会撞名。 +/// +/// # Safety +/// `cf` 由 nginx 传入且有效。 +pub unsafe fn preconfig(cf: *mut ngx_conf_t) -> bool { + let mut ax_target = ngx_string!("apix_target"); + let mut ax_host = ngx_string!("apix_host"); + let mut ax_key = ngx_string!("apix_key"); + let mut ax_body = ngx_string!("apix_body"); + let mut ax_ptarget = ngx_string!("apix_probe_target"); + let mut ax_pbody = ngx_string!("apix_probe_body"); + unsafe { + add_var(cf, &raw mut ax_target, VAR_TARGET) + && add_var(cf, &raw mut ax_host, VAR_HOST) + && add_var(cf, &raw mut ax_key, VAR_KEY) + && add_var(cf, &raw mut ax_body, VAR_BODY) + && add_var(cf, &raw mut ax_ptarget, VAR_PROBE_TARGET) + && add_var(cf, &raw mut ax_pbody, VAR_PROBE_BODY) + } +} + +/// 注册一个只读变量,值由 [`var_get`] 按 `slot` 分派计算。 +/// +/// 与 `$proxy_backend_addr` 不同,这六个变量是纯只读的,模块从不主动写, +/// 只有 `proxy_pass` / `proxy_set_body` 求值时触发 get_handler。 +unsafe fn add_var(cf: *mut ngx_conf_t, name: *mut ngx_str_t, slot: usize) -> bool { + // SAFETY: cf 由 nginx 传入;name 指向本函数调用方栈上的 ngx_str_t,注册时被拷贝 + let var = unsafe { + ngx_http_add_variable( + cf, + name, + (NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t, + ) + }; + if var.is_null() { + return false; + } + // SAFETY: var 非空且由本函数独占初始化;data 承载分派标记 + unsafe { + (*var).get_handler = Some(var_get); + (*var).set_handler = None; + (*var).data = slot; + } + true +} // =========================================================================== // 变量分派标记 @@ -66,8 +122,9 @@ const PUB_PREFIX: &str = "/apix/"; // 校验 // =========================================================================== -/// slug:小写字母/数字开头,其后可含短横线、下划线。与 `upstreams::validate_slot` -/// 同一套规则(保持一致,管理员不用记两套),只把错误文案换成「slug」。 +/// slug:小写字母/数字开头,其后可含短横线、下划线。与 +/// `plugin_llm::upstreams::validate_slot` 同一套规则(保持一致,管理员不用记两套), +/// 只把错误文案换成「slug」。 pub fn validate_slug(raw: &str) -> Result { let s = util::trim(raw).to_ascii_lowercase(); if s.is_empty() { @@ -230,7 +287,7 @@ pub fn lookup(slug: &str) -> Option<(String, String, String)> { /// 两个前缀都认:对外出口与内部探测共用同一套「取 slug → 拼体 → 换 Key」逻辑, /// 与 `llm::slot_of` 对 `/_upstream_test` 的处理是同一个手法。 pub fn slug_of(r: *mut ngx_http_request_t) -> Option { - let uri = crate::http::uri(r); + let uri = http::uri(r); let rest = uri .strip_prefix(PROBE_PREFIX) .or_else(|| uri.strip_prefix(PUB_PREFIX))?; @@ -351,7 +408,7 @@ unsafe fn set_value( v: *mut ngx_http_variable_value_t, value: &str, ) -> ngx_int_t { - let pool = ngx::core::Pool::from_ngx_pool((*r).pool); + let pool = Pool::from_ngx_pool((*r).pool); let bytes = value.as_bytes(); let data = pool.alloc(bytes.len()) as *mut u8; if data.is_null() { @@ -419,7 +476,7 @@ pub fn all() -> Vec<(String, ApiProxy)> { /// **不要写死**(部署在 88 时要带 `:88`,放在 443 反代后面时不能带)。 /// query 参数由前端按 `params` 拼一次(避免后端与前端各拼一次导致 `?q=?q=`)。 pub fn call_url(slug: &str, port: &str) -> String { - format!("https://{}{port}{PUB_PREFIX}{slug}", config::LLM_PUBLIC_HOST) + format!("https://{LLM_PUBLIC_HOST}{port}{PUB_PREFIX}{slug}") } /// 新增或覆盖一个代理条目。 diff --git a/rust/crates/plugin-apix/src/config.rs b/rust/crates/plugin-apix/src/config.rs new file mode 100644 index 0000000..affb8a9 --- /dev/null +++ b/rust/crates/plugin-apix/src/config.rs @@ -0,0 +1,44 @@ +//! API 代理(apix)策略常量与 shm 键前缀(自内核 config.rs 迁入;改策略只改这里)。 +//! +//! 与 LLM 代理的关系:同一把 `sk_` 下行 Key、同一套限流与统计(内核 +//! `ipass_core::auth` + `plugin_llm::stats`),但每条 apix 记录自带 +//! 「基址 + 供应商 Key + 资产 id」——不同供应商互不影响,slug 只映射到 +//! `asset_id`。 + +/// shm 键前缀:slug → `base \n 供应商Key \n asset_id`。 +/// +/// 三行塞一个键是刻意的:热路径只查一次表就拿到转发所需全部信息。 +/// 代价是改某条凭据要重新同步该条目(条目数是个位数,无所谓)。 +pub const KEY_AX_PREFIX: &[u8] = b"ax:"; + +/// 供应商「调用资产」路径(`POST {base}{path}`,body = `{"asset_id":..,"call_data":{..}}`)。 +/// 每条 apix 记录都按这个路径转发——它定义了该供应商接口所遵循的协议。 +pub const APIX_REQUEST_PATH: &str = "/api/v1/ai/request"; +/// 供应商「费用预估」路径。**免费**,且响应里带余额——管理台的 +/// 「测试」按钮走它:既能验 Key 通不通,又能看到还剩多少余额,不花一分钱。 +pub const APIX_ESTIMATE_PATH: &str = "/api/v1/ai/estimate"; + +/// slug 长度上限 +pub const APIX_SLUG_MAX_LEN: usize = 32; +/// 供应商基址长度上限 +pub const APIX_URL_MAX_LEN: usize = 200; +/// 展示名 / 说明长度上限 +pub const APIX_NAME_MAX_LEN: usize = 64; +pub const APIX_DESC_MAX_LEN: usize = 200; +/// asset_id 长度上限 +pub const APIX_ASSET_MAX_LEN: usize = 64; +/// 单条目声明的参数个数上限 +pub const APIX_PARAM_MAX: usize = 16; +/// 单次调用允许的 query 参数个数上限(挡住拼超长 URL 刷共享内存) +pub const APIX_ARG_MAX: usize = 32; +/// 单个参数值长度上限(bytes) +pub const APIX_VAL_MAX: usize = 4096; +/// 供应商 Key 长度上限 +pub const APIX_KEY_MAX_LEN: usize = 128; + +/// 用量统计里 API 代理的 slot 前缀。 +/// +/// 与 LLM 的 slot 刻意区分开:`uds::<日窗>` 是**同一片键空间**, +/// 而 LLM slot 的字符集不含 `/`(见 `plugin_llm::upstreams::validate_slot`), +/// 所以 `api/` 绝不会和 LLM 上游撞车,用量页能自然分成两组。 +pub const APIX_STATS_PREFIX: &str = "api/"; diff --git a/rust/crates/plugin-apix/src/handlers.rs b/rust/crates/plugin-apix/src/handlers.rs new file mode 100644 index 0000000..bd4ca1b --- /dev/null +++ b/rust/crates/plugin-apix/src/handlers.rs @@ -0,0 +1,91 @@ +//! API 代理热路径(access 阶段):鉴权 → 查代理 → 放行。 +//! +//! 与 plugin-llm 的 `LlmHandler` 是同一套下行契约(同一把 `sk_` Key、 +//! 同一份限流配额——都在内核 `ipass_core::auth`),差别只在查哪张表、 +//! 以及**请求体由网关拼**(`apix::build_body`)——资产选择权必须留在服务端, +/// 否则客户端能自己挑最贵的模型刷。 + +use ngx::core::Status; +use ngx::ffi::ngx_http_request_t; +use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request}; + +use crate::apix; +use crate::config; +use ipass_core::{auth, http, loc, util}; +use ipass_core::loc::Switch; + +/// API 代理 access handler。location 开关:`ipass_apix on`(Switch::Apix)。 +pub struct ApiProxyHandler; + +impl HttpRequestHandler for ApiProxyHandler { + 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::Apix) { + return Status::NGX_DECLINED; + } + + let Some(slug) = apix::slug_of(r) else { + return http::fail( + r, + HTTPStatus::BAD_REQUEST, + "路径缺少代理名,正确形式:/apix/<代理名>?<参数>", + ); + }; + + let Some(key) = auth::downstream_key(r) else { + return http::fail( + r, + HTTPStatus::UNAUTHORIZED, + "缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带", + ); + }; + + let Some((username, _allowed, rpm, daily)) = auth::identity(&key) else { + util::log_warn(&format!( + "[apix] API Key 校验失败 slug={slug} client={}", + http::remote_addr(r) + )); + return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或已失效"); + }; + + // 代理的**可见性**由管理员的启用/停用决定,不再叠一层账号白名单: + // 白名单是给「一家厂商一个 slot」设计的,这里再套一层会让 + // 「管理员明明启用了、某账号却 403」变得难以解释。 + let Some((_base, supplier_key, _asset)) = apix::lookup(&slug) else { + return http::fail( + r, + HTTPStatus::NOT_FOUND, + &format!("代理 {slug} 不存在或已停用"), + ); + }; + + if supplier_key.is_empty() { + util::log_err(&format!( + "[apix] 供应商 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写" + )); + return http::fail( + r, + HTTPStatus::SERVICE_UNAVAILABLE, + "供应商 API Key 未配置,请联系管理员", + ); + } + + // SAFETY: r 由 nginx 传入且有效 + if let Some(resp) = unsafe { auth::check_quota(r, &username, rpm, daily) } { + return resp; + } + + // 用量统计。slot 带 `api/` 前缀,与 LLM 上游在同一片键空间里天然分组 + // (键空间归 plugin-llm 的 stats,记账原语在内核 usage——apix 只是租户) + plugin_llm::stats::record( + &username, + &format!("{}{}", config::APIX_STATS_PREFIX, slug), + util::now(), + ); + + Status::NGX_DECLINED + } +} diff --git a/rust/crates/plugin-apix/src/lib.rs b/rust/crates/plugin-apix/src/lib.rs new file mode 100644 index 0000000..942251c --- /dev/null +++ b/rust/crates/plugin-apix/src/lib.rs @@ -0,0 +1,56 @@ +//! plugin-apix —— API 代理插件。 +//! +//! 把外部 **API 供应商**的资产挂到网关下,复用 LLM 的 `sk_` 鉴权 + 配额 + +//! 用量统计(slot 带 `api/` 前缀,天然归组)。数据文件 +//! `data/api-proxies.json`(含供应商真 Key,敏感级别等同 users.json)。 +//! +//! ## 装配点(gateway) +//! +//! * `preconfig` —— 注册 `$apix_target` / `$apix_host` / `$apix_key` / +//! `$apix_body` / `$apix_probe_target` / `$apix_probe_body` 六件套 +//! * `postconfig` —— 注册 ApiProxyHandler(access 阶段) +//! * `zone_load` —— 全量装载 `ax:` 代理表 +//! * `dispatch_api` —— 认领 apix 管理端点与账号态端点 +//! +//! ## 依赖说明 +//! +//! 下行鉴权 / 配额在内核 `ipass_core::auth`;用量记账入口在 +//! `plugin_llm::stats`(apix 与 LLM 共用同一片键空间,单一写入口防漂移)。 + +pub mod api; +pub mod apix; +pub mod config; +pub mod handlers; +pub mod models; +pub mod store; + +use ngx::core::Status; +use ngx::ffi::{ngx_conf_t, ngx_http_request_t}; + +use ipass_core::plugin::Plugin; + +pub struct ApixPlugin; + +impl Plugin for ApixPlugin { + fn name(&self) -> &'static str { + "apix" + } + + fn preconfig(&self, cf: *mut ngx_conf_t) -> bool { + // SAFETY: cf 由 nginx 传入且有效 + unsafe { apix::preconfig(cf) } + } + + fn postconfig(&self, cf: *mut ngx_conf_t) -> bool { + // SAFETY: cf 由 nginx 传入且有效 + ngx::http::add_phase_handler::(unsafe { &mut *cf }).is_ok() + } + + fn dispatch_api(&self, r: *mut ngx_http_request_t) -> Option { + api::dispatch(r) + } + + fn zone_load(&self) -> usize { + apix::reload_shm() + } +} diff --git a/rust/crates/plugin-apix/src/models.rs b/rust/crates/plugin-apix/src/models.rs new file mode 100644 index 0000000..49399a9 --- /dev/null +++ b/rust/crates/plugin-apix/src/models.rs @@ -0,0 +1,66 @@ +//! API 代理持久化模型(`api-proxies.json`:以 slug 为 key)。 +//! +//! 字段名与旧版 `data/api-proxies.json` **逐字对应**,以便新版直接接管旧数据文件。 + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// API 代理表(`api-proxies.json`)。 +/// +/// 与 `llm-upstreams.json` 同构:每条记录 = 一个供应商(自带基址与密钥), +/// 由 `slug` 区分。调用方访问 `/apix/?参数=值`,网关用本记录里的密钥 +/// 转发到供应商、并把响应原样返回。不同供应商彼此独立、互不耦合。 +/// +/// `key` 是供应商真 Key,**敏感级别等同 `users.json`**(data/ 已 gitignore)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ApiProxyStore { + /// slug → 代理映射 + #[serde(default)] + pub items: BTreeMap, +} + +impl Default for ApiProxyStore { + fn default() -> Self { + Self { items: BTreeMap::new() } + } +} + +/// 单个 API 代理条目:指向某一家供应商的一个可调用的资产。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ApiProxy { + /// 供应商侧的资产 id(如 `searxng-search`),决定具体调用哪个资产 + pub asset_id: String, + /// 供应商名称(仅展示用,管理员自填,例如 `provider-x` / 客户自定) + #[serde(default)] + pub supplier: String, + /// 供应商基址,如 `https://api.example.com` + #[serde(default)] + pub base: String, + /// 供应商 API Key(`ak_...`)。留空 = 未配置,热路径直接 503。 + /// **敏感**:写盘与回显都按密钥处理,管理台只回显掩码。 + #[serde(default)] + pub key: String, + /// 展示名(中文) + #[serde(default)] + pub name: String, + /// 一句话说明 + #[serde(default)] + pub desc: String, + /// **声明式参数清单**(如 `["q"]`)。 + /// + /// 只用于给调用方看的文档(管理台把 `?q=关键词` 拼出来、账号态接口回显), + /// 转发时**不按它过滤**——过滤要靠读请求体,而 access 阶段读不到。 + /// 供应商侧自己会拒绝不认识的参数,拦在网关意义不大。 + #[serde(default)] + pub params: Vec, + #[serde(default = "default_true")] + pub enabled: bool, + #[serde(default)] + pub note: String, + #[serde(default)] + pub created_at: i64, +} + +fn default_true() -> bool { + true +} diff --git a/rust/crates/plugin-apix/src/store.rs b/rust/crates/plugin-apix/src/store.rs new file mode 100644 index 0000000..78dddd4 --- /dev/null +++ b/rust/crates/plugin-apix/src/store.rs @@ -0,0 +1,35 @@ +//! 代理表的文件读写(复用内核 store 的原子写 + 全局文件写锁)。 +//! +//! `data/api-proxies.json` 含供应商真 Key,**敏感级别等同 `users.json`**。 + +use std::path::PathBuf; + +use ipass_core::{state, store}; + +use crate::models::ApiProxyStore; + +fn api_proxies_path() -> PathBuf { + store::path_in_data("api-proxies.json") +} + +pub fn read_api_proxies() -> ApiProxyStore { + store::read_json(&api_proxies_path(), ApiProxyStore::default()) +} + +pub fn write_api_proxies(data: &ApiProxyStore) -> Result<(), String> { + store::write_json(&api_proxies_path(), data) +} + +/// 加锁「读-改-写」代理表。 +/// +/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。 +pub fn update_api_proxies(f: F) -> Result +where + F: FnOnce(&mut ApiProxyStore) -> Result, +{ + let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?; + let mut data = read_api_proxies(); + let out = f(&mut data)?; + write_api_proxies(&data)?; + Ok(out) +} diff --git a/rust/gateway/Cargo.toml b/rust/gateway/Cargo.toml index 9518632..0b870ac 100644 --- a/rust/gateway/Cargo.toml +++ b/rust/gateway/Cargo.toml @@ -21,6 +21,7 @@ nginx-sys.workspace = true ipass-core.workspace = true plugin-domain.workspace = true plugin-llm.workspace = true +plugin-apix.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/rust/gateway/src/api.rs b/rust/gateway/src/api.rs index d436845..690e62a 100644 --- a/rust/gateway/src/api.rs +++ b/rust/gateway/src/api.rs @@ -1,28 +1,22 @@ -//! 插件路由表(过渡期):API 代理(apix)端点 + 用量趋势(组合根)。 +//! 插件路由表(最终形态):仅剩用量趋势组合端点。 //! -//! 身份类端点已下沉 `ipass-core::api`(CorePlugin),域名类端点已下沉 -//! `plugin-domain::api`(DomainPlugin),LLM 上游 / 用量端点已下沉 -//! `plugin-llm::api`(LlmPlugin)。本表只剩两类: +//! 身份类端点在 `ipass-core::api`(CorePlugin),域名类在 +//! `plugin-domain::api`,LLM 上游 / 用量端点在 `plugin-llm::api`, +//! API 代理端点在 `plugin-apix::api`。本表只剩 //! -//! * **apix 端点** —— P4 将迁 plugin-apix; //! * **`/api/admin/trend`** —— **刻意留在 gateway**(对方案的有意偏离): //! 日桶键带日窗 id、按前缀扫不出来,趋势接口需要 users + upstreams + //! apix 三方名册,这是跨插件组合逻辑,属于装配根职责。 //! //! 鉴权语义与内核共用一套:`ipass_core::api::{Guard, Actor, run_guarded}`。 -use ngx::core::{Pool, Status}; +use ngx::core::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}; +use ipass_core::{http, util}; -use crate::apix; -use crate::config; -use crate::http; use crate::users; -use crate::util; // =========================================================================== // 路由 @@ -33,11 +27,6 @@ use crate::util; fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> { let entry: (Guard, Handler) = match (method, uri) { ("GET", "/api/admin/trend") => (Guard::Admin, h_admin_trend), - ("GET", "/api/admin/apix") => (Guard::Admin, h_admin_apix), - ("POST", "/api/admin/apix/save") => (Guard::Admin, h_admin_apix_save), - ("POST", "/api/admin/apix/delete") => (Guard::Admin, h_admin_apix_delete), - ("POST", "/api/admin/apix/test") => (Guard::Admin, h_admin_apix_test), - ("GET", "/api/v1/apix") => (Guard::User, h_my_apix), _ => return None, }; Some(entry) @@ -76,14 +65,16 @@ fn h_admin_trend(r: *mut ngx_http_request_t, _actor: Actor) -> Status { let usernames: Vec = users::all().into_iter().map(|u| u.username).collect(); // API 代理与 LLM 上游共用同一片用量键空间,只是 slot 带 `api/` 前缀 - // (见 `config::APIX_STATS_PREFIX`)——这里一起列出,趋势图才会出现它们 + // (见 `plugin_apix::config::APIX_STATS_PREFIX`)——这里一起列出,趋势图才会出现它们 let slots: Vec = plugin_llm::upstreams::all() .into_iter() .map(|(slot, _)| slot) .chain( - apix::all() + plugin_apix::apix::all() .into_iter() - .map(|(slug, _)| format!("{}{}", config::APIX_STATS_PREFIX, slug)), + .map(|(slug, _)| { + format!("{}{}", plugin_apix::config::APIX_STATS_PREFIX, slug) + }), ) .collect(); @@ -93,133 +84,3 @@ fn h_admin_trend(r: *mut ngx_http_request_t, _actor: Actor) -> Status { "ok", ) } - -// =========================================================================== -// API 代理管理 -// =========================================================================== - -/// 管理员:API 代理清单 -fn h_admin_apix(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let port = http::host_port(r); - let list = apix::all(); - http::ok( - r, - json!({ - "items": apix::view_all(&list, &port), - "count": list.len(), - }), - "ok", - ) -} - -/// 管理员:新增/修改一个 API 代理条目 -fn h_admin_apix_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let slug = p.get("slug").cloned().unwrap_or_default(); - let asset = p.get("asset_id").cloned().unwrap_or_default(); - - // 参数清单允许两种写法:逗号分隔(`q,format`)或 JSON 数组(`["q"]`) - let params = p.get("params").and_then(|v| { - let v = util::trim(v); - if v.is_empty() { - return None; - } - Some(if let Ok(Value::Array(arr)) = serde_json::from_str::(v) { - arr.into_iter() - .filter_map(|x| x.as_str().map(str::to_owned)) - .collect::>() - } else { - v.split(',').map(str::to_owned).collect::>() - }) - }); - - // 不带 enabled 视为「启用」:新建表单里漏勾是常见手滑,默认值取更安全的一侧 - let enabled = match p.get("enabled") { - Some(v) => util::to_bool(Some(v)), - None => true, - }; - - match apix::upsert( - &slug, - &asset, - p.get("base"), - p.get("key"), - p.get("supplier"), - p.get("name"), - p.get("desc"), - params, - enabled, - p.get("note"), - ) { - Ok(item) => { - util::log_notice(&format!("[api] 保存 API 代理 {slug} → {asset}")); - http::ok(r, json!({ "slug": slug, "asset_id": item.asset_id }), "已保存") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 管理员:删除一个 API 代理条目 -fn h_admin_apix_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - match apix::remove(p.get("slug").map(String::as_str).unwrap_or("")) { - Ok(slug) => { - util::log_notice(&format!("[api] 删除 API 代理 {slug}")); - http::ok(r, json!({ "slug": slug }), "已删除") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 管理员:探测供应商 Key 是否可用(管理台「测试」按钮)。 -/// -/// 走供应商的**免费预估**接口(`/api/v1/ai/estimate`):它不执行资产、不扣费, -/// 响应里还带 `current_balance_usd` —— 一次调用同时拿到「Key 通不通」和 -/// 「还剩多少钱」。实现上内部重定向到管理 server 的 `/_apix_probe/`, -/// 复用 `$apix_probe_*` 变量(拼体、换 Key 与真实转发同一套逻辑)。 -fn h_admin_apix_test(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let slug_raw = http::params(r).get("slug").cloned().unwrap_or_default(); - let slug = match apix::validate_slug(&slug_raw) { - Ok(s) => s, - Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e), - }; - if apix::lookup(&slug).is_none() { - return http::fail(r, HTTPStatus::NOT_FOUND, &format!("代理 {slug} 不存在或已停用")); - } - - let uri = format!("{}{}", apix::PROBE_URI_PREFIX, slug); - util::log_notice(&format!("[api] 测试 API 代理 {slug}")); - - // ⚠️ 与 h_admin_upstream_test 同一个坑:internal_redirect 只浅拷贝 ngx_str_t, - // 必须把字节拷进请求池,否则函数返回后 r->uri 全是 NUL。 - // 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: core::ptr::null_mut(), - }; - nginx_sys::ngx_http_internal_redirect(r, &mut u, &mut args); - } - - Status::NGX_DONE -} - -/// 账号态:列出当前可用的 API 代理及调用地址 -fn h_my_apix(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let port = http::host_port(r); - let items: Vec = apix::all() - .into_iter() - .filter(|(_, it)| it.enabled) - .map(|(slug, it)| apix::view(&slug, &it, &port)) - .collect(); - http::ok(r, json!({ "items": items, "count": items.len() }), "ok") -} diff --git a/rust/gateway/src/lib.rs b/rust/gateway/src/lib.rs index d1ea4ae..3e202a1 100644 --- a/rust/gateway/src/lib.rs +++ b/rust/gateway/src/lib.rs @@ -39,7 +39,6 @@ //! 根本拿不到请求体。 mod api; -mod apix; // 内核模块桥接:业务文件里的 `crate::config::X` / `crate::state::…` 等路径 // 不用改写,直接经此解析到 ipass-core(插件化 P0 的行为等价手段, @@ -53,8 +52,8 @@ 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_HTTP_VAR_CHANGEABLE, NGX_HTTP_VAR_NOCACHEABLE, - NGX_LOG_EMERG, ngx_command_t, ngx_conf_t, ngx_cycle_t, ngx_http_add_variable, + 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, @@ -72,9 +71,7 @@ use ipass_core::plugin::Plugin; // 插件装配(PLUGINS 顺序 = 认领顺序;身份类端点将来必须排最前) // =========================================================================== -/// 过渡期路由插件:api.rs 里暂留的端点由 gateway 自己认领。 -/// P3 起 llm 路由已迁 plugin-llm;P4 迁 plugin-apix 后 -/// 本插件消失(或只剩 trend 的路由部分并入 ApixPlugin)。 +/// 装配根:trend 组合端点由 gateway 自己认领(见 `api::h_admin_trend`)。 struct GatewayRoutes; impl Plugin for GatewayRoutes { @@ -88,11 +85,12 @@ impl Plugin for GatewayRoutes { } /// 插件注册表。**身份类端点(CorePlugin)排在最前**:dispatch 按顺序认领, -/// 先注册者先得。装配顺序:内核(身份)→ 域名 → LLM → 过渡期路由(apix/trend)。 +/// 先注册者先得。装配顺序:内核(身份)→ 域名 → LLM → API 代理 → trend。 static PLUGINS: &[&dyn Plugin] = &[ &ipass_core::api::CorePlugin, &plugin_domain::DomainPlugin, &plugin_llm::LlmPlugin, + &plugin_apix::ApixPlugin, &GatewayRoutes, ]; @@ -205,87 +203,6 @@ fn dispatch_api(r: *mut ngx_http_request_t) -> Status { &format!("接口不存在:{method} {uri}"), ) } -/// API 代理热路径(`/apix/?<参数>`):鉴权 → 查代理 → 放行。 -/// -/// 与 plugin-llm 的 `LlmHandler` 是同一套下行契约(同一把 `sk_` Key、 -/// 同一份限流配额——都在内核 `ipass_core::auth`),差别只在查哪张表、 -/// 以及**请求体由网关拼**(`apix::build_body`)——资产选择权必须留在服务端, -/// 否则客户端能自己挑最贵的模型刷。P4 将随 apix 端点一起迁 plugin-apix。 -struct ApiProxyHandler; - -impl HttpRequestHandler for ApiProxyHandler { - const PHASE: HttpPhase = HttpPhase::Access; - type Output = Status; - - fn handler(request: &mut ngx::http::Request) -> Self::Output { - if !Module::location_conf(request).map(|c| c.apix).unwrap_or(false) { - return Status::NGX_DECLINED; - } - - let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t; - - let Some(slug) = apix::slug_of(r) else { - return http::fail( - r, - HTTPStatus::BAD_REQUEST, - "路径缺少代理名,正确形式:/apix/<代理名>?<参数>", - ); - }; - - let Some(key) = ipass_core::auth::downstream_key(r) else { - return http::fail( - r, - HTTPStatus::UNAUTHORIZED, - "缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带", - ); - }; - - let Some((username, _allowed, rpm, daily)) = ipass_core::auth::identity(&key) else { - util::log_warn(&format!( - "[apix] API Key 校验失败 slug={slug} client={}", - http::remote_addr(r) - )); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或已失效"); - }; - - // 代理的**可见性**由管理员的启用/停用决定,不再叠一层账号白名单: - // 白名单是给「一家厂商一个 slot」设计的,这里再套一层会让 - // 「管理员明明启用了、某账号却 403」变得难以解释。 - let Some((_base, supplier_key, _asset)) = apix::lookup(&slug) else { - return http::fail( - r, - HTTPStatus::NOT_FOUND, - &format!("代理 {slug} 不存在或已停用"), - ); - }; - - if supplier_key.is_empty() { - util::log_err(&format!( - "[apix] 供应商 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写" - )); - return http::fail( - r, - HTTPStatus::SERVICE_UNAVAILABLE, - "供应商 API Key 未配置,请联系管理员", - ); - } - - // SAFETY: r 由 nginx 传入且有效 - if let Some(resp) = unsafe { ipass_core::auth::check_quota(r, &username, rpm, daily) } { - return resp; - } - - // 用量统计。slot 带 `api/` 前缀,与 LLM 上游在同一片键空间里天然分组 - plugin_llm::stats::record( - &username, - &format!("{}{}", config::APIX_STATS_PREFIX, slug), - util::now(), - ); - - Status::NGX_DECLINED - } -} - /// 管理 API:content 阶段先读请求体,读完后交给 `api::dispatch`。 /// /// 这是本项目唯一需要异步的地方。`ngx_http_read_client_request_body` 是 @@ -369,28 +286,6 @@ impl Merge for ModuleConfig { } } -/// 注册一个由 `apix::var_get` 计算的只读变量 -unsafe fn add_apix_var(cf: *mut ngx_conf_t, name: *mut ngx_str_t, slot: usize) -> bool { - // SAFETY: cf 由 nginx 传入;name 指向本函数调用方栈上的 ngx_str_t,注册时被拷贝 - let var = unsafe { - ngx_http_add_variable( - cf, - name, - (NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t, - ) - }; - if var.is_null() { - return false; - } - // SAFETY: var 非空且由本函数独占初始化;data 承载分派标记 - unsafe { - (*var).get_handler = Some(apix::var_get); - (*var).set_handler = None; - (*var).data = slot; - } - true -} - impl HttpModule for Module { fn module() -> &'static ngx_module_t { // SAFETY: 模块定义是静态的,生命周期贯穿进程 @@ -405,7 +300,7 @@ impl HttpModule for Module { ipass_core::api::set_ext(&GatewayExt); // 各插件注册自己的 nginx 变量($proxy_backend_addr 归 plugin-domain、 - // LLM 三件套归 plugin-llm) + // LLM 三件套归 plugin-llm、API 代理六件套归 plugin-apix) for p in PLUGINS { if !p.preconfig(cf) { ngx_conf_log_error!( @@ -418,26 +313,6 @@ impl HttpModule for Module { } } - // API 代理六件套。前缀 `apix_` 与 `llm_` 同理:nginx 变量名全局唯一。 - let mut ax_target = ngx_string!("apix_target"); - let mut ax_host = ngx_string!("apix_host"); - let mut ax_key = ngx_string!("apix_key"); - let mut ax_body = ngx_string!("apix_body"); - let mut ax_ptarget = ngx_string!("apix_probe_target"); - let mut ax_pbody = ngx_string!("apix_probe_body"); - let apix_ok = unsafe { - add_apix_var(cf, &raw mut ax_target, apix::VAR_TARGET) - && add_apix_var(cf, &raw mut ax_host, apix::VAR_HOST) - && add_apix_var(cf, &raw mut ax_key, apix::VAR_KEY) - && add_apix_var(cf, &raw mut ax_body, apix::VAR_BODY) - && add_apix_var(cf, &raw mut ax_ptarget, apix::VAR_PROBE_TARGET) - && add_apix_var(cf, &raw mut ax_pbody, apix::VAR_PROBE_BODY) - }; - if !apix_ok { - ngx_conf_log_error!(NGX_LOG_EMERG, unsafe { &mut *cf }, "注册 API 代理变量失败"); - return Status::NGX_ERROR.into(); - } - Status::NGX_OK.into() } @@ -449,16 +324,14 @@ impl HttpModule for Module { ipass_core::plugin::set_ctx_index(Module::module().ctx_index as usize); // 各插件注册自己的 phase handler(ResolveHandler 归 plugin-domain、 - // LlmHandler/LlmHealthHandler/AuditHandler 归 plugin-llm) + // 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::(cf).is_err() { - return Status::NGX_ERROR.into(); - } if ngx::http::add_phase_handler::(cf).is_err() { return Status::NGX_ERROR.into(); } @@ -684,11 +557,12 @@ extern "C" fn state_zone_init(zone: *mut ngx_shm_zone_t, _data: *mut c_void) -> let loaded = plugin_domain::domains::reload_shm(); util::log_notice(&format!("[ipass] 共享内存已装载 {loaded} 条转发映射")); - // 账号 Key 与 LLM 上游必须一起进内存:LLM 热路径未命中即 401 / 404, - // 没有任何回源兜底(同 domains 的写穿语义)。上游表装载归 plugin-llm。 + // 账号 Key 与 LLM 上游 / API 代理必须一起进内存:各热路径未命中即 + // 401 / 404,没有任何回源兜底(同 domains 的写穿语义)。 + // 上游表装载归 plugin-llm、代理表装载归 plugin-apix。 let keys = users::reload_shm(); let ups = plugin_llm::upstreams::reload_shm(); - let axs = apix::reload_shm(); + let axs = plugin_apix::apix::reload_shm(); util::log_notice(&format!( "[ipass] 已装载 {keys} 个账号 Key、{ups} 个 LLM 上游、{axs} 个 API 代理" ));