1. LLM 上游 / API 代理的「新建 / 编辑」改为弹出卡片(IP.modal), 列表页只留复制地址 / 测试 / 编辑 / 启停 / 删除,体验更轻。 2. API 代理彻底去「API 市场 / 平台级凭据」概念:souyi 仅作供应商之一, 每条代理自带 base / 供应商 Key / asset_id(后端 platform 概念已移除), 源码与文档均不再出现 souyi / AIMALL 品牌与目录直拉。 3. 修 apix.js 示例地址拼接 bug:之前末尾出现 `?q=?q=`, 现 url 只拼一次 `?q=`、示例给出 `?q=关键词`(base 由后端返回纯基址)。 Co-Authored-By: 小K <[email protected]>
197 lines
6.2 KiB
Rust
197 lines
6.2 KiB
Rust
//! JSON 文件存储层:原子写 + 跨 worker 互斥。
|
||
//!
|
||
//! 与旧版 `lua/store.lua` 语义一致——**状态就是几个 JSON 文件**,不引入数据库。
|
||
//! 差别只有一处:互斥锁从 `resty.lock`(基于 lua_shared_dict)换成共享内存里的
|
||
//! `RwLock`,因为新版已经有一块共享内存了,不必再造一个字典。
|
||
//!
|
||
//! 所有写操作统一走 `update_*`,流程固定为:
|
||
//!
|
||
//! ```text
|
||
//! 取全局文件写锁 → 读文件 → 闭包修改 → 原子写回 → 放锁
|
||
//! ```
|
||
//!
|
||
//! 闭包返回 `Err` 表示业务校验失败,此时**不落盘**(与旧版 `fn` 返回 nil 一致)。
|
||
//!
|
||
//! ## 三个表的分工
|
||
//!
|
||
//! | 文件 | 内容 | 是否进共享内存 |
|
||
//! | --- | --- | --- |
|
||
//! | `users.json` | 账号、口令哈希、API Key | `ukey:` 索引进(热路径要它) |
|
||
//! | `domains.json` | 子域名 → 后端映射 | `sub:` 进(转发热路径) |
|
||
//! | `llm-upstreams.json` | LLM 上游基址与密钥 | `up:` 进(LLM 转发热路径) |
|
||
//! | `api-proxies.json` | API 代理清单(每条含各自供应商凭据) | `ax:` 进(API 代理热路径) |
|
||
//!
|
||
//! 四个文件都在 `data/` 下,都已 `.gitignore`。**LLM 上游表含上游真 Key,
|
||
//! 敏感级别与 `users.json` 相同**,不要再往别处复制。
|
||
|
||
use std::path::PathBuf;
|
||
use std::sync::Mutex;
|
||
|
||
use crate::config::DEFAULT_DATA_DIR;
|
||
use crate::models::{ApiProxyStore, DomainEntry, UpstreamTable, UserTable};
|
||
use crate::state;
|
||
|
||
/// 状态目录。配置阶段由 `ipass_data_dir` 指令设置一次,之后只读。
|
||
static DATA_DIR: Mutex<Option<String>> = Mutex::new(None);
|
||
|
||
pub fn set_data_dir(dir: &str) {
|
||
if let Ok(mut slot) = DATA_DIR.lock() {
|
||
*slot = Some(dir.to_owned());
|
||
}
|
||
}
|
||
|
||
pub fn data_dir() -> String {
|
||
DATA_DIR
|
||
.lock()
|
||
.ok()
|
||
.and_then(|s| s.clone())
|
||
.unwrap_or_else(|| DEFAULT_DATA_DIR.to_owned())
|
||
}
|
||
|
||
fn path_of(name: &str) -> PathBuf {
|
||
PathBuf::from(data_dir()).join(name)
|
||
}
|
||
|
||
pub fn users_path() -> PathBuf {
|
||
path_of("users.json")
|
||
}
|
||
|
||
pub fn domains_path() -> PathBuf {
|
||
path_of("domains.json")
|
||
}
|
||
|
||
pub fn upstreams_path() -> PathBuf {
|
||
path_of("llm-upstreams.json")
|
||
}
|
||
|
||
pub fn api_proxies_path() -> PathBuf {
|
||
path_of("api-proxies.json")
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 读写
|
||
// ===========================================================================
|
||
|
||
/// 读取并反序列化;文件缺失或损坏时回退 `default`(不抛错,保证转发侧可用)
|
||
fn read_json<T: serde::de::DeserializeOwned>(path: &PathBuf, default: T) -> T {
|
||
let Ok(text) = std::fs::read_to_string(path) else {
|
||
return default;
|
||
};
|
||
if text.trim().is_empty() {
|
||
return default;
|
||
}
|
||
match serde_json::from_str(&text) {
|
||
Ok(v) => v,
|
||
Err(e) => {
|
||
// 解析失败必须留痕:静默回退会让「数据看起来还在、实际全空」极难排查
|
||
crate::util::log_err(&format!(
|
||
"[store] 解析失败,回退默认值:{} ({e})",
|
||
path.display()
|
||
));
|
||
default
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 原子写:先写 `<path>.tmp` 再 rename,避免读到写了一半的内容
|
||
fn write_json<T: serde::Serialize>(path: &PathBuf, value: &T) -> Result<(), String> {
|
||
let text = serde_json::to_string(value).map_err(|e| format!("序列化失败:{e}"))?;
|
||
let tmp = PathBuf::from(format!("{}.tmp", path.display()));
|
||
|
||
std::fs::write(&tmp, text.as_bytes()).map_err(|e| {
|
||
let _ = std::fs::remove_file(&tmp);
|
||
format!("写入临时文件失败:{e}")
|
||
})?;
|
||
|
||
std::fs::rename(&tmp, path).map_err(|e| {
|
||
let _ = std::fs::remove_file(&tmp);
|
||
format!("重命名失败:{e}")
|
||
})
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 对外接口
|
||
// ===========================================================================
|
||
|
||
pub fn read_users() -> UserTable {
|
||
read_json(&users_path(), UserTable::new())
|
||
}
|
||
|
||
pub fn read_domains() -> Vec<DomainEntry> {
|
||
read_json(&domains_path(), Vec::new())
|
||
}
|
||
|
||
pub fn read_upstreams() -> UpstreamTable {
|
||
read_json(&upstreams_path(), UpstreamTable::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_domains(data: &[DomainEntry]) -> Result<(), String> {
|
||
write_json(&domains_path(), &data.to_vec())
|
||
}
|
||
|
||
pub fn write_upstreams(data: &UpstreamTable) -> Result<(), String> {
|
||
write_json(&upstreams_path(), data)
|
||
}
|
||
|
||
pub fn write_api_proxies(data: &ApiProxyStore) -> Result<(), String> {
|
||
write_json(&api_proxies_path(), data)
|
||
}
|
||
|
||
/// 加锁「读-改-写」账号表。
|
||
///
|
||
/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。
|
||
pub fn update_users<T, F>(f: F) -> Result<T, String>
|
||
where
|
||
F: FnOnce(&mut UserTable) -> Result<T, String>,
|
||
{
|
||
let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?;
|
||
let mut data = read_users();
|
||
let out = f(&mut data)?;
|
||
write_users(&data)?;
|
||
Ok(out)
|
||
}
|
||
|
||
/// 加锁「读-改-写」域名表
|
||
pub fn update_domains<T, F>(f: F) -> Result<T, String>
|
||
where
|
||
F: FnOnce(&mut Vec<DomainEntry>) -> Result<T, String>,
|
||
{
|
||
let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?;
|
||
let mut data = read_domains();
|
||
let out = f(&mut data)?;
|
||
write_domains(&data)?;
|
||
Ok(out)
|
||
}
|
||
|
||
/// 加锁「读-改-写」LLM 上游表
|
||
pub fn update_upstreams<T, F>(f: F) -> Result<T, String>
|
||
where
|
||
F: FnOnce(&mut UpstreamTable) -> Result<T, String>,
|
||
{
|
||
let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?;
|
||
let mut data = read_upstreams();
|
||
let out = f(&mut data)?;
|
||
write_upstreams(&data)?;
|
||
Ok(out)
|
||
}
|
||
|
||
/// 加锁「读-改-写」API 代理表
|
||
pub fn update_api_proxies<T, F>(f: F) -> Result<T, String>
|
||
where
|
||
F: FnOnce(&mut ApiProxyStore) -> Result<T, String>,
|
||
{
|
||
let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?;
|
||
let mut data = read_api_proxies();
|
||
let out = f(&mut data)?;
|
||
write_api_proxies(&data)?;
|
||
Ok(out)
|
||
}
|