Files
ssw__ipass/rust/crates/plugin-apix/src/apix.rs
T
admin 26a0f2f4f4 feat(apix): usage_hint 字段 —— /api/v1/me 帮用户 AI 自动发现调用语法 (1.0.22)
`desc` 是中文给运维看的,`params` 只对 vendor 有意义(passthrough 是空数组)。
`/api/v1/me` 把条目下发给用户 AI 后,AI 必须能自己拼出:
- 路径尾部是什么(/ocr /ocr/base64 /ocr/url)
- 每个端点的 Content-Type(multipart 还是 json)
- 上游字段名 / Swagger 在哪

加 `usage_hint` 字段:管理员按 OpenAPI 风格填写自由格式,由 /api/v1/me
原样透传给用户 AI。AI 直接解析,无需再读人工文档。

设计要点:
- 不进 shm(热路径只查 base/key/asset_id/mode,进 shm 占带宽)
- 截断到 1KB(够写 3-5 个端点说明,长 Swagger 截断而非拒绝)
- 默认空字符串,向后兼容旧数据
- passthrough 推荐填,vendor 可选填

改动:
- models.rs: ApiProxy 加 usage_hint 字段
- apix.rs: upsert 收 usage_hint_raw + 截断;view 回显
- api.rs: save 解析 usage_hint;响应回显
- www/apix.html: 描述加 usage_hint 解释
- www/assets/apix.js: 表单加 textarea + 提交带 usage_hint
- tests/llm/e2e.sh: §11.5 加 1 条 usage_hint 写入与回显断言
- 回归 227/0 全绿(修复断言 1 条)
2026-09-15 11:30:16 +08:00

787 lines
31 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.
//! API 代理:把外部供应商的 API 资产挂到网关下。
//!
//! 与 LLM 代理(`plugin_llm`)是**同一套下行契约**——都认 `sk_` 那把 Key、
//! 都吃同一份限流配额、都进同一套用量统计——差别只在上游形态:
//!
//! | | LLM 代理 | API 代理 |
//! | --- | --- | --- |
//! | 上游 | N 家厂商,各有基址与密钥 | 每条记录自带基址与供应商 Key |
//! | URL 第一段 | `slot` → `up:` 里的 `base \n auth` | `slug` → `ax:` 里的 `base \n key \n asset_id` |
//! | 请求体 | 客户端原样带过来 | **由网关从 query 拼**(见下) |
//!
//! ## 为什么请求体必须由网关拼
//!
//! 供应商侧只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的
//! `asset_id`** 区分。如果让客户端自己带 `asset_id`,管理员就失去了
//! 「只暴露免费资产」的控制力——任何人都能拿网关的 Key 去刷最贵的那个模型。
//! 所以资产选择权留在服务端:`slug → asset_id` 由管理员配置,
//! 调用方只能决定参数。
//!
//! 反过来,参数只能走 **query string**:转发决策在 access 阶段,而请求体
//! 要到 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::{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::models::{ApiProxy, ApiProxyStore};
use crate::store;
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");
let mut axp_target = ngx_string!("apixp_target");
let mut axp_host = ngx_string!("apixp_host");
let mut axp_key = ngx_string!("apixp_key");
let mut axp_probe = ngx_string!("apixp_probe_target");
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)
&& add_var(cf, &raw mut axp_target, VAR_PT_TARGET)
&& add_var(cf, &raw mut axp_host, VAR_PT_HOST)
&& add_var(cf, &raw mut axp_key, VAR_PT_KEY)
&& add_var(cf, &raw mut axp_probe, VAR_PT_PROBE)
}
}
/// 注册一个只读变量,值由 [`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
}
// ===========================================================================
// 变量分派标记
// ===========================================================================
/// `$apix_target`:完整上游 URL(`base + /api/v1/ai/request`)
pub const VAR_TARGET: usize = 1;
/// `$apix_host`:上游 Host 头
pub const VAR_HOST: usize = 2;
/// `$apix_key`:供应商 API Key(下行那把 `sk_` 到此为止,不往上游传)
pub const VAR_KEY: usize = 3;
/// `$apix_body`:由 query 拼出的调用体
pub const VAR_BODY: usize = 4;
/// `$apix_probe_target` / `$apix_probe_body`:管理台「测试」用的**免费**预估调用
pub const VAR_PROBE_TARGET: usize = 5;
pub const VAR_PROBE_BODY: usize = 6;
/// `$apixp_target`:透传模式完整上游 URL(`base + /apixp/<slug> 之后的 URI 尾部`)
pub const VAR_PT_TARGET: usize = 7;
/// `$apixp_host`:透传模式上游 Host 头
pub const VAR_PT_HOST: usize = 8;
/// `$apixp_key`:透传模式供应商 Key(内部服务无 Key 时下发空,nginx 侧不下发鉴权头)
pub const VAR_PT_KEY: usize = 9;
/// `$apixp_probe_target`:透传模式「测试」用的连通性探针(GET 打上游根地址)
pub const VAR_PT_PROBE: usize = 10;
/// shm payload 内部分隔符:base / 供应商 Key / asset_id 之间。
///
/// base 是 URL、key 与 asset_id 都是 token 类字符串,都不可能含换行。
pub const PAYLOAD_SEP: char = '\n';
/// 内部探测前缀(管理台「测试」按钮经内部重定向落到 `/_apix_probe/<slug>`)
pub const PROBE_URI_PREFIX: &str = "/_apix_probe/";
const PROBE_PREFIX: &str = PROBE_URI_PREFIX;
/// 对外的 API 代理前缀
const PUB_PREFIX: &str = "/apix/";
/// 透传模式(passthrough)对外的 API 代理前缀:`/apixp/<slug>/<tail>`。
///
/// 与 vendor 的 `/apix/` 拆成**两个独立 location**,根本原因是 vendor 的
/// `/apix/` location 在 nginx 层强制了 `proxy_method POST` + `proxy_set_body`
/// + `Content-Type: application/json` + `proxy_pass_request_headers off`——
/// 这些 location 级指令无法按请求级 shm 的 mode 动态切换。透传必须原样转发
/// 客户端的方法/请求体/Content-Type(OCR 的 `/ocr` 就是 `multipart/form-data`),
/// 所以只能另起一个不施加上述约束的 `/apixp/` location,零风险保留 `/apix/` 行为。
pub const PUB_PT_PREFIX: &str = "/apixp/";
/// 透传模式内部探测前缀(管理台「测试」走 GET 打上游根地址验连通性)。
pub const PROBE_PT_PREFIX: &str = "/_apixp_probe/";
// ===========================================================================
// 校验
// ===========================================================================
/// slug:小写字母/数字开头,其后可含短横线、下划线。与
/// `plugin_llm::upstreams::validate_slot` 同一套规则(保持一致,管理员不用记两套),
/// 只把错误文案换成「slug」。
pub fn validate_slug(raw: &str) -> Result<String, String> {
let s = util::trim(raw).to_ascii_lowercase();
if s.is_empty() {
return Err("缺少 slug 参数".to_owned());
}
if s.len() > config::APIX_SLUG_MAX_LEN {
return Err(format!("slug 长度不能超过 {} 个字符", config::APIX_SLUG_MAX_LEN));
}
let bytes = s.as_bytes();
let head_ok = matches!(bytes[0], b'a'..=b'z' | b'0'..=b'9');
let tail_ok = bytes[1..].iter().all(|&b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_'));
if !head_ok || !tail_ok {
return Err("slug 只能是小写字母、数字、短横线或下划线,且不能以符号开头".to_owned());
}
Ok(s)
}
/// 供应商基址:`http(s)://host`,允许尾随路径(供应商挂在子路径下的情况)。
pub fn validate_base(raw: &str) -> Result<String, String> {
let s = util::trim(raw).trim_end_matches('/').to_owned();
if s.is_empty() {
return Err("缺少 base 参数".to_owned());
}
if s.len() > config::APIX_URL_MAX_LEN {
return Err(format!("base 长度不能超过 {} 个字符", config::APIX_URL_MAX_LEN));
}
let rest = if let Some(r) = s.strip_prefix("https://") {
r
} else if let Some(r) = s.strip_prefix("http://") {
r
} else {
return Err("base 必须以 http:// 或 https:// 开头,例如 https://api.example.com".to_owned());
};
if rest.is_empty() || rest.split('/').next().unwrap_or("").is_empty() {
return Err("base 缺少主机名".to_owned());
}
if rest.chars().any(char::is_whitespace) || rest.contains('@') {
return Err("base 不允许包含空格或用户信息(user@host)".to_owned());
}
Ok(s)
}
/// asset_id:供应商那边的资产标识。宽进——各供应商的命名规则不同,
/// 这里只挡空白与控制字符(它要出现在 JSON 与 HTML 里)。
fn validate_asset(raw: &str) -> Result<String, String> {
let s = util::trim(raw).to_owned();
if s.is_empty() {
return Err("缺少 asset_id 参数".to_owned());
}
if s.chars().count() > config::APIX_ASSET_MAX_LEN {
return Err(format!("asset_id 超过 {} 个字符", config::APIX_ASSET_MAX_LEN));
}
if s.chars().any(char::is_whitespace) || s.chars().any(char::is_control) {
return Err("asset_id 不能包含空格或控制字符".to_owned());
}
Ok(s)
}
fn check_params(raw: &[String]) -> Result<Vec<String>, String> {
if raw.len() > config::APIX_PARAM_MAX {
return Err(format!("单个代理最多声明 {} 个参数", config::APIX_PARAM_MAX));
}
let mut out: Vec<String> = Vec::new();
for item in raw {
let p = util::trim(item);
if p.is_empty() {
continue;
}
if p.chars().count() > config::APIX_NAME_MAX_LEN {
return Err(format!("参数名「{p}」超过 {} 个字符", config::APIX_NAME_MAX_LEN));
}
if p.chars().any(char::is_whitespace) || p.chars().any(char::is_control) {
return Err(format!("参数名「{p}」不能包含空格或控制字符"));
}
if !out.iter().any(|x| x == p) {
out.push(p.to_owned());
}
}
Ok(out)
}
// ===========================================================================
// 共享内存同步(写穿 / 装载)
// ===========================================================================
fn payload_of(item: &ApiProxy) -> String {
format!(
"{}{PAYLOAD_SEP}{}{PAYLOAD_SEP}{}{PAYLOAD_SEP}{}",
item.base, item.key, item.asset_id, item.mode
)
}
/// 拆 payload:`base \n key \n asset_id \n mode`
pub fn split_payload(payload: &str) -> (&str, &str, &str, &str) {
let mut it = payload.splitn(4, PAYLOAD_SEP);
let base = it.next().unwrap_or("");
let key = it.next().unwrap_or("");
let asset = it.next().unwrap_or("");
let mode = it.next().unwrap_or("");
(base, key, asset, mode)
}
/// 把一条代理同步进共享内存。**所有写操作之后必须调用它**。
///
/// 停用 = 删除(与 `upstreams::sync_shm` 同一手法):热路径「查不到 = 不可用」,
/// 这样停用即刻生效且不留残留。
pub fn sync_shm(slug: &str, store: &ApiProxyStore) {
let Some(item) = store.items.get(slug) else {
state::remove(config::KEY_AX_PREFIX, slug.as_bytes());
return;
};
if !item.enabled {
state::remove(config::KEY_AX_PREFIX, slug.as_bytes());
return;
}
let payload = payload_of(item);
if !state::put(config::KEY_AX_PREFIX, slug.as_bytes(), payload.as_bytes(), 0) {
util::log_err(&format!(
"[apix] 代理配置写共享内存失败 slug={slug} —— 该代理会 404(共享内存可能已满)"
));
}
}
/// 全量重载代理表(启动装载 / 供应商凭据变更后)。返回装载条数。
pub fn reload_shm() -> usize {
state::clear_prefix(config::KEY_AX_PREFIX);
let data = store::read_api_proxies();
let mut expected = 0;
let mut loaded = 0;
for (slug, item) in &data.items {
if !item.enabled {
continue;
}
expected += 1;
let payload = payload_of(item);
if state::put(config::KEY_AX_PREFIX, slug.as_bytes(), payload.as_bytes(), 0) {
loaded += 1;
}
}
if loaded != expected {
util::log_err(&format!(
"[apix] 代理装载不全:{loaded}/{expected} —— 有代理会 404"
));
}
loaded
}
/// 热路径查表:`slug → (base, 供应商Key, asset_id, mode)`
///
/// vendor 模式要求 `asset_id` 非空——它是拼调用体的依据;passthrough 模式
/// `asset_id` 留空也合法,上游路径由 URL 尾部(见 [`slug_of`] 的 `tail`)决定。
pub fn lookup(slug: &str) -> Option<(String, String, String, String)> {
let payload = state::get(config::KEY_AX_PREFIX, slug.as_bytes())?.0;
let (base, key, asset, mode) = split_payload(&payload);
if mode != config::APIX_MODE_PASSTHRU && asset.is_empty() {
return None;
}
Some((
base.to_owned(),
key.to_owned(),
asset.to_owned(),
mode.to_owned(),
))
}
// ===========================================================================
// 请求解析
// ===========================================================================
/// 取 URL 里的 slug,并返回 URI 尾部与「是否落在透传前缀下」。
///
/// 四个前缀都认:vendor 对外 `/apix/` 与内部探针 `/_apix_probe/`、
/// passthrough 对外 `/apixp/` 与内部探针 `/_apixp_probe/`。
/// 返回三元组 `(slug, tail, is_passthru_path)`:
/// - `tail`:slug 之后的 URI 片段(含前导 `/`,可能为空)。vendor 模式恒为空
/// (路径写死 `/api/v1/ai/request`);passthrough 模式 = 真正转发到上游的
/// 路径尾部(如 `/ocr`、`/ocr/url`、`/ocr/base64`)。
/// - `is_passthru_path`:当前请求是否落在透传前缀下,供 handler 校验
/// 「路径前缀」与「条目 mode」一致(vendor slug 不能走 `/apixp/`,反之亦然)。
///
/// 与 `llm::slot_of` 对 `/_upstream_test` 的处理是同一个手法:对外出口与内部
/// 探测共用同一套「取 slug → 拼目标 → 换 Key」逻辑。
pub fn slug_of(r: *mut ngx_http_request_t) -> Option<(String, String, bool)> {
let uri = http::uri(r);
let (rest, is_pt) = if let Some(rest) = uri.strip_prefix(PUB_PT_PREFIX) {
(rest, true)
} else if let Some(rest) = uri.strip_prefix(PROBE_PT_PREFIX) {
(rest, true)
} else if let Some(rest) = uri.strip_prefix(PUB_PREFIX) {
(rest, false)
} else if let Some(rest) = uri.strip_prefix(PROBE_PREFIX) {
(rest, false)
} else {
return None;
};
let slug = rest.split('/').next().unwrap_or("");
if slug.is_empty() {
return None;
}
let slug = slug.to_ascii_lowercase();
// tail = slug 之后的全部内容(含前导 '/',可能为空)
let tail = rest[slug.len()..].to_owned();
Some((slug, tail, is_pt))
}
/// 从 `https://api.example.com:443` 取出 `api.example.com:443`
fn host_of(base: &str) -> &str {
let rest = match base.find("://") {
Some(i) => &base[i + 3..],
None => base,
};
match rest.find('/') {
Some(i) => &rest[..i],
None => rest,
}
}
/// JSON 字符串字面量(含两侧引号)。
///
/// 自己拼而不走 `serde_json` 是因为输入来自 query string,中文与特殊字符
/// 都会被 percent-encode 过一遍,这里必须按 JSON 规则重新转义——
/// 直接 `format!("\"{v}\"")` 遇到 `"` 或 `\` 就拼出非法 JSON,
/// 上游报 400 而从网关日志完全看不出是拼体的问题。
fn json_quote(v: &str) -> String {
let mut out = String::with_capacity(v.len() + 2);
out.push('"');
for c in v.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
/// 单个参数值截断(bytes 级,避免把几 MB 的垃圾塞进调用体)
fn clip(v: &str) -> &str {
if v.len() <= config::APIX_VAL_MAX {
return v;
}
// 截断到字符边界,否则 `\u{fffd}` 会污染整个 JSON
let mut end = config::APIX_VAL_MAX;
while end > 0 && !v.is_char_boundary(end) {
end -= 1;
}
&v[..end]
}
/// 由 query 拼出供应商的调用体。
///
/// ```text
/// ?q=nginx&format=json → {"asset_id":"searxng-search","call_data":{"q":"nginx","format":"json"}}
/// ?prompt=你好 → {"asset_id":"minimax-m3","prompt":"你好","call_data":{}}
/// ```
///
/// `prompt` 单独提到顶层:供应商的 model 类资产(MiniMax-M3 等)把它当必填字段,
/// 塞进 `call_data` 会被当成未知参数。其余参数一律进 `call_data`。
pub fn build_body(asset_id: &str, args: &[(String, String)]) -> String {
let mut call = String::new();
let mut prompt: Option<&str> = None;
let mut n = 0;
for (k, v) in args {
if k.is_empty() || n >= config::APIX_ARG_MAX {
continue;
}
if k == "prompt" {
prompt = Some(v);
continue;
}
if !call.is_empty() {
call.push(',');
}
call.push_str(&json_quote(k));
call.push(':');
call.push_str(&json_quote(clip(v)));
n += 1;
}
let mut body = String::with_capacity(128 + call.len());
body.push_str("{\"asset_id\":");
body.push_str(&json_quote(asset_id));
if let Some(p) = prompt {
body.push_str(",\"prompt\":");
body.push_str(&json_quote(clip(p)));
}
body.push_str(",\"call_data\":{");
body.push_str(&call);
body.push_str("}}");
body
}
fn build_body_from_request(r: *mut ngx_http_request_t, asset_id: &str) -> String {
let args = util::parse_kv(&http::args_raw(r));
build_body(asset_id, &args)
}
// ===========================================================================
// 变量 get_handler
// ===========================================================================
/// 在请求内存池里分配字符串并写进变量槽。
///
/// # Safety
/// `r` / `v` 必须由 nginx 传入且在本调用期间有效。
unsafe fn set_value(
r: *mut ngx_http_request_t,
v: *mut ngx_http_variable_value_t,
value: &str,
) -> ngx_int_t {
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() {
(*v).set_not_found(1);
return Status::NGX_ERROR.into();
}
core::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
(*v).data = data;
(*v).set_len(bytes.len() as _);
(*v).set_valid(1);
(*v).set_no_cacheable(1);
(*v).set_not_found(0);
Status::NGX_OK.into()
}
/// 六个 API 代理变量共用一个 get_handler,靠 `var.data` 分派。
pub extern "C" fn var_get(
r: *mut ngx_http_request_t,
v: *mut ngx_http_variable_value_t,
data: usize,
) -> ngx_int_t {
// SAFETY: r/v 由 nginx 传入且有效;slug_of 只读请求结构
unsafe {
let resolved = (|| -> Option<String> {
let (slug, tail, _is_pt) = slug_of(r)?;
let (base, key, asset, mode) = lookup(&slug)?;
Some(match data {
VAR_TARGET => format!("{base}{}", config::APIX_REQUEST_PATH),
VAR_PROBE_TARGET => format!("{base}{}", config::APIX_ESTIMATE_PATH),
VAR_HOST => host_of(&base).to_owned(),
VAR_KEY => key,
VAR_BODY => build_body_from_request(r, &asset),
VAR_PROBE_BODY => {
// 预估是**免费**的,且不真正执行资产——用它当连通性探针,
// 响应里的 current_balance_usd 顺带把供应商余额带回来
format!("{{\"asset_id\":{},\"max_tokens\":1}}", json_quote(&asset))
}
// —— 透传模式变量:仅当条目本身是 passthrough 才有效 ——
VAR_PT_TARGET if mode == config::APIX_MODE_PASSTHRU => {
// 原样转发:上游 URL = base + URL 尾部(如 base + /ocr)。
// 变量形式 proxy_pass 不自动追加 query(与 LLM 同约束),
// 所以通用 REST 出口必须把 query 也拼进去。
let args = http::args_raw(r);
let args = std::str::from_utf8(&args).unwrap_or("");
if args.is_empty() {
format!("{base}{tail}")
} else {
format!("{base}{tail}?{args}")
}
}
VAR_PT_HOST if mode == config::APIX_MODE_PASSTHRU => host_of(&base).to_owned(),
VAR_PT_KEY if mode == config::APIX_MODE_PASSTHRU => key,
VAR_PT_PROBE if mode == config::APIX_MODE_PASSTHRU => {
// 透传探针:GET 打上游根地址,验证连通性(不真正执行任何资产)
format!("{base}/")
}
_ => return None,
})
})();
match resolved {
Some(value) => set_value(r, v, &value),
None => {
(*v).set_not_found(1);
(*v).set_valid(0);
Status::NGX_ERROR.into()
}
}
}
}
// ===========================================================================
// 查询 / 写入
// ===========================================================================
pub fn all() -> Vec<(String, ApiProxy)> {
store::read_api_proxies()
.items
.into_iter()
.collect()
}
/// 仅启用(`enabled = true`)的代理条目。
///
/// `plugin-apix::api::h_list` 与 gateway 的 `decorate_me` 都走这个:
/// 给同事/自己看的清单只该含「现在能调」的代理,停用的不该暴露,
/// 否则列表里出现一行「调就 404」会让人误以为是网关坏掉。
pub fn enabled() -> Vec<(String, ApiProxy)> {
all().into_iter().filter(|(_, it)| it.enabled).collect()
}
/// 客户端应当使用的调用地址(base,不带 query)。端口由调用方从请求 Host 头取,
/// **不要写死**(部署在 88 时要带 `:88`,放在 443 反代后面时不能带)。
/// query 参数由前端按 `params` 拼一次(避免后端与前端各拼一次导致 `?q=?q=`)。
///
/// `mode` 决定前缀:vendor → `/apix/<slug>`,passthrough → `/apixp/<slug>`
/// (passthrough 后续还能再追路径尾部,如 `/apixp/ocr/ocr`)。
pub fn call_url(slug: &str, port: &str, mode: &str) -> String {
let prefix = if mode == config::APIX_MODE_PASSTHRU {
PUB_PT_PREFIX
} else {
PUB_PREFIX
};
format!("https://{LLM_PUBLIC_HOST}{port}{prefix}{slug}")
}
/// 新增或覆盖一个代理条目。
///
/// `params = None` 表示保持原值(只改名字时不必回填参数清单)。
/// `base` / `key` / `supplier` 同理:`None` 或空串都表示「保留原值」——
/// 这样编辑时不必把密钥再抄一遍。新建时若填了空串仍为空,则报错
/// (没有基址与密钥无法转发)。
pub fn upsert(
slug_raw: &str,
asset_raw: &str,
mode_raw: Option<&String>,
base_raw: Option<&String>,
key_raw: Option<&String>,
supplier_raw: Option<&String>,
name: Option<&String>,
desc: Option<&String>,
params: Option<Vec<String>>,
enabled: bool,
note: Option<&String>,
usage_hint_raw: Option<&String>,
) -> Result<ApiProxy, String> {
let slug = validate_slug(slug_raw)?;
// 代理模式:vendor(默认)/ passthrough,其余值一律拒绝
let mode = match mode_raw {
Some(m) => {
let m = util::trim(m).to_ascii_lowercase();
if m.is_empty() {
config::APIX_MODE_VENDOR.to_owned()
} else if m == config::APIX_MODE_VENDOR || m == config::APIX_MODE_PASSTHRU {
m
} else {
return Err(format!(
"不支持的代理模式:{m}(仅支持 vendor / passthrough)"
));
}
}
None => config::APIX_MODE_VENDOR.to_owned(),
};
// vendor 模式 asset_id 必填(拼体依据);passthrough 模式可留空
// (上游路径由 URL 尾部决定),仅做与 vendor 同样的卫生检查。
let asset_id = if mode == config::APIX_MODE_PASSTHRU {
let s = util::trim(asset_raw);
if s.chars().any(char::is_whitespace) || s.chars().any(char::is_control) {
return Err("asset_id 不能包含空格或控制字符".to_owned());
}
if s.chars().count() > config::APIX_ASSET_MAX_LEN {
return Err(format!("asset_id 超过 {} 个字符", config::APIX_ASSET_MAX_LEN));
}
s.to_owned()
} else {
validate_asset(asset_raw)?
};
let params = match params {
Some(list) => Some(check_params(&list)?),
None => None,
};
// base / key:空串视为「保留原值」,交给下方闭包按 existing 决定
let new_base = match base_raw {
Some(b) => {
let b = util::trim(b);
if b.is_empty() { None } else { Some(validate_base(&b)?) }
}
None => None,
};
let new_key = match key_raw {
Some(k) => {
let k = util::trim(k).to_owned();
if k.is_empty() {
None
} else {
if k.chars().count() > config::APIX_KEY_MAX_LEN {
return Err(format!("供应商 Key 超过 {} 个字符", config::APIX_KEY_MAX_LEN));
}
Some(k)
}
}
None => None,
};
let key = slug.clone();
let (item, snapshot) = store::update_api_proxies(move |data| {
let existing = data.items.get(&key).cloned();
let base = new_base
.or_else(|| existing.as_ref().map(|e| e.base.clone()))
.unwrap_or_default();
let key_val = new_key
.or_else(|| existing.as_ref().map(|e| e.key.clone()))
.unwrap_or_default();
// 新建必填校验:vendor 必须 base + key 都填;passthrough 仅 base 必填,
// key 可空(内部服务免鉴权,下发时 nginx 空串语义 = 不发该头)。
// 这是 1.0.20 现场踩到的坑:原校验统一要求「基址与密钥」,导致管理台
// 提交 passthrough + 空 Key 直接 400,handler 实际是放行的。
if existing.is_none() {
if base.is_empty() {
return Err("新建代理必须提供供应商基址".to_owned());
}
if key_val.is_empty() && mode == config::APIX_MODE_VENDOR {
return Err("vendor 模式必须提供供应商 Key(passthrough 可留空)".to_owned());
}
}
let supplier = match supplier_raw {
Some(s) => util::trim(s).chars().take(config::APIX_NAME_MAX_LEN).collect(),
None => existing.as_ref().map(|e| e.supplier.clone()).unwrap_or_default(),
};
let name = match name {
Some(n) => util::trim(n).chars().take(config::APIX_NAME_MAX_LEN).collect(),
None => existing.as_ref().map(|e| e.name.clone()).unwrap_or_default(),
};
let desc = match desc {
Some(d) => util::trim(d).chars().take(config::APIX_DESC_MAX_LEN).collect(),
None => existing.as_ref().map(|e| e.desc.clone()).unwrap_or_default(),
};
let note = match note {
Some(n) => util::trim(n).to_owned(),
None => existing.as_ref().map(|e| e.note.clone()).unwrap_or_default(),
};
let usage_hint = match usage_hint_raw {
Some(h) => {
let h = util::trim(h);
if h.is_empty() {
String::new()
} else {
// 截断到 1KB(够写 3-5 个端点说明)。机器可读文本通常几十到几百字节,
// 给 4 倍冗余。过长截断而非拒绝——管理员可以粘贴 Swagger 长片段。
h.chars().take(1024).collect()
}
}
None => existing.as_ref().map(|e| e.usage_hint.clone()).unwrap_or_default(),
};
let params = match params {
Some(p) => p,
None => existing.as_ref().map(|e| e.params.clone()).unwrap_or_default(),
};
let created_at = existing
.as_ref()
.map(|e| e.created_at)
.filter(|&t| t > 0)
.unwrap_or_else(util::now);
let item = ApiProxy {
asset_id,
supplier,
base,
key: key_val,
mode,
name,
desc,
params,
enabled,
note,
usage_hint,
created_at,
};
data.items.insert(key.clone(), item.clone());
Ok((item, data.clone()))
})?;
sync_shm(&slug, &snapshot);
Ok(item)
}
pub fn remove(slug_raw: &str) -> Result<String, String> {
let slug = validate_slug(slug_raw)?;
let key = slug.clone();
store::update_api_proxies(move |data| {
if data.items.remove(&key).is_none() {
return Err(format!("代理 {key} 不存在"));
}
Ok(())
})?;
state::remove(config::KEY_AX_PREFIX, slug.as_bytes());
Ok(slug)
}
// ===========================================================================
// 对外投影
// ===========================================================================
/// 转成管理台可见的字段。
///
/// **绝不回显完整供应商 Key**——与 `upstreams::view` 同一理由:管理台页面会被
/// 截图、被浏览器插件读取,回显真 Key 等于把供应商余额摆在一个 HTML 里。
/// `url` 只给 base 路径,query 参数由前端按 `params` 拼一次。
pub fn view(slug: &str, item: &ApiProxy, port: &str) -> Value {
json!({
"slug": slug,
"asset_id": item.asset_id,
"mode": item.mode,
"supplier": item.supplier,
"base": item.base,
"name": item.name,
"desc": item.desc,
"params": item.params,
"enabled": item.enabled,
"key_set": !item.key.is_empty(),
"key_mask": if item.key.is_empty() { "-".to_owned() } else { util::mask_key(&item.key) },
"note": item.note,
"usage_hint": item.usage_hint,
"created_at": item.created_at,
"created_at_text": util::fmt_time(item.created_at),
"url": call_url(slug, port, &item.mode),
})
}
pub fn view_all(list: &[(String, ApiProxy)], port: &str) -> Vec<Value> {
list.iter().map(|(slug, it)| view(slug, it, port)).collect()
}