From 2c8fb2a1eed7c37b8e051b6efb1c6462d3e539e0 Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 24 Sep 2026 21:15:57 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=94=B9=E9=80=A0=E4=B8=BA?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E6=8F=92=E4=BB=B6=E4=BB=93=20ipass-plugin-ca?= =?UTF-8?q?che(=E5=AF=B9=E9=BD=90=E5=85=84=E5=BC=9F=E4=BB=93=E5=BD=A2?= =?UTF-8?q?=E6=80=81)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 扁平化:rust/crates/plugin-cache/src → src/,单包 Cargo.toml(name ipass-plugin-cache 2.0.0), path 依赖改 ../ipass-core(内核+vendor ngx),删除旧单体拆分残留(rust/ 层级、 deps/ipass submodule、.gitmodules、conf/、tests/、多页静态 www/、AGENTS.md) - R19 启停对齐:access/log 热路径加 plugin_registry::plugin_enabled("cache") 门控,fail-closed 404(数据面是鉴权后磁盘读,禁用放行=无鉴权读缓存盘); location 圈定暂用 8 前缀路由表,ipass_cache 指令待 gateway 接入轮 - 旧独立应用形态保留在 tag legacy-app-final - 文档:CLAUDE.md(装配关系+未挂载待办+本机编译 env 姿势)、README.md、 docs/cache-usage.md 保留;docs/plugins.md(单体时代)删除 - 验证:cargo check --release 通过,cargo test 4 passed Co-Authored-By: Claude Opus 4.8 --- .gitignore | 14 +- .gitmodules | 3 - AGENTS.md | 67 --- CLAUDE.md | 49 ++ rust/Cargo.lock => Cargo.lock | 75 +-- Cargo.toml | 17 + README.md | 13 + conf/cache-common.conf | 131 ----- conf/cache-routes.conf | 177 ------ conf/nginx.cache.conf | 87 --- conf/server.cache.conf | 30 - conf/tls/README.md | 42 -- conf/tls/cache.conf.example | 42 -- deps/ipass | 1 - docs/plugins.md | 79 --- rust/Cargo.toml | 57 -- rust/crates/plugin-cache/Cargo.toml | 17 - {rust/crates/plugin-cache/src => src}/api.rs | 0 .../crates/plugin-cache/src => src}/cache.rs | 0 .../crates/plugin-cache/src => src}/config.rs | 0 .../plugin-cache/src => src}/handlers.rs | 23 +- {rust/crates/plugin-cache/src => src}/lib.rs | 2 +- .../crates/plugin-cache/src => src}/models.rs | 0 .../crates/plugin-cache/src => src}/stats.rs | 0 .../crates/plugin-cache/src => src}/store.rs | 0 .../plugin-cache/src => src}/upstreams.rs | 0 .../crates/plugin-cache/src => src}/zones.rs | 0 .../1/fb/052807f7dcf903b482f647fb0035afb1 | Bin 1612 -> 0 bytes .../npm/0/6b/7c08263957217762708264c0587196b0 | Bin 205386 -> 0 bytes .../npm/1/b6/f4b23ecc52cf5b24fbe08fcc49a80b61 | Bin 205387 -> 0 bytes .../npm/3/d8/819209f49ca3661d21dbcc7cff467d83 | Bin 205387 -> 0 bytes .../npm/6/20/133297d4a6a307d27f01825f9fc2e206 | Bin 205387 -> 0 bytes .../npm/8/70/53b42c650712625207fc721e28295708 | Bin 205387 -> 0 bytes tests/cache/.run-evict/conf/cache-common.conf | 131 ----- tests/cache/.run-evict/conf/cache-routes.conf | 177 ------ tests/cache/.run-evict/conf/mime.types | 99 ---- tests/cache/.run-evict/conf/nginx.cache.conf | 87 --- tests/cache/.run-evict/conf/server.cache.conf | 30 - tests/cache/.run-evict/data/api-proxies.json | 26 - .../.run-evict/data/cache-upstreams.json | 10 - tests/cache/.run-evict/data/domains.json | 1 - tests/cache/.run-evict/data/llm-stats.json | 1 - .../cache/.run-evict/data/llm-upstreams.json | 34 -- tests/cache/.run-evict/data/users.json | 1 - tests/cache/.run-evict/logs/cache.log | 66 --- tests/cache/.run-evict/logs/error.log | 224 -------- tests/cache/.run-evict/logs/upstream.out | 32 -- tests/cache/.run-evict/upstream.log | 20 - tests/cache/.run-evict/upstream.pid | 1 - tests/cache/.run-evict/www | 1 - .../7/b6/fa85c45018774ee40eed4e14f27e5b67 | Bin 584 -> 0 bytes .../6/2b/006332a6c46dd553c5b07fbe163dd2b6 | Bin 585 -> 0 bytes .../go/a/1d/3628fdf82489b1d8471bcfb362cee1da | Bin 578 -> 0 bytes .../5/57/018b43239012a992b6a642253ec85575 | Bin 584 -> 0 bytes .../npm/c/11/531eb8fade2b128eb9584b2f4e7e011c | Bin 580 -> 0 bytes .../5/02/0351062533e47711f552e75f9bdd9025 | Bin 582 -> 0 bytes tests/cache/.run-ipass/conf/cache-common.conf | 131 ----- tests/cache/.run-ipass/conf/cache-routes.conf | 177 ------ tests/cache/.run-ipass/conf/mime.types | 99 ---- tests/cache/.run-ipass/conf/nginx.cache.conf | 87 --- tests/cache/.run-ipass/conf/server.cache.conf | 30 - .../.run-ipass/data/cache-upstreams.json | 28 - tests/cache/.run-ipass/data/llm-stats.json | 1 - tests/cache/.run-ipass/data/users.json | 1 - tests/cache/.run-ipass/logs/cache.log | 252 --------- tests/cache/.run-ipass/logs/error.log | 72 --- tests/cache/.run-ipass/logs/upstream.out | 1 - tests/cache/.run-ipass/upstream.log | 6 - tests/cache/.run-ipass/www | 1 - tests/cache/.run-prod/conf/cache-common.conf | 131 ----- tests/cache/.run-prod/conf/cache-routes.conf | 177 ------ tests/cache/.run-prod/conf/mime.types | 99 ---- tests/cache/.run-prod/conf/nginx.cache.conf | 87 --- tests/cache/.run-prod/conf/server.cache.conf | 30 - tests/cache/.run-prod/logs/cache.log | 0 tests/cache/.run-prod/logs/error.log | 3 - tests/cache/.run-prod/logs/nginx.pid | 0 tests/cache/.run-prod/www | 1 - .../8/92/96bbd6bf360b9648e9afd5d07aafd928 | Bin 580 -> 0 bytes .../2/bd/15d75620ad41340b2459f5d02b9e6bd2 | Bin 581 -> 0 bytes .../go/0/6b/decf43777bf2ea024deb844b8dd546b0 | Bin 577 -> 0 bytes .../e/16/288a53c6200b2faf2e49cb2b4bf4716e | Bin 580 -> 0 bytes .../npm/d/50/3c799f495786fbc96054087c25adb50d | Bin 578 -> 0 bytes .../a/3f/1b29e40ff5e9bd7150ad962d7181b3fa | Bin 579 -> 0 bytes tests/cache/.run/logs/error.log | 4 - tests/cache/.run/logs/upstream.out | 1 - tests/cache/.run/nginx.conf | 105 ---- tests/cache/.run/upstream.log | 8 - tests/cache/dev-server.sh | 282 --------- tests/cache/e2e-auth.sh | 279 --------- tests/cache/fixtures/api-proxies.json | 26 - tests/cache/fixtures/domains.json | 1 - tests/cache/fixtures/llm-upstreams.json | 34 -- tests/cache/fixtures/users.json | 59 -- tests/cache/lib-render.sh | 119 ---- tests/cache/mock_upstream.py | 88 --- tests/cache/nginx.cache.local.conf | 105 ---- tests/cache/run.sh | 77 --- tests/cache/test-cache-capacity.sh | 535 ------------------ tests/cache/test-cache.sh | 127 ----- tests/cache/test-ipass-cache.sh | 180 ------ tests/cache/test-real-registries.sh | 197 ------- tests/cache/validate-prod-conf.sh | 82 --- tests/cache/verify-cache-eviction.sh | 215 ------- www/apix.html | 51 -- www/assets/admin.css | 238 -------- www/assets/apix.js | 223 -------- www/assets/cache.js | 488 ---------------- www/assets/chart.js | 141 ----- www/assets/core.js | 316 ----------- www/assets/domains.js | 129 ----- www/assets/hourly.js | 363 ------------ www/assets/me.js | 270 --------- www/assets/overview.js | 95 ---- www/assets/review.js | 57 -- www/assets/upstreams.js | 337 ----------- www/assets/usage.js | 185 ------ www/assets/users.js | 150 ----- www/cache.html | 123 ---- www/domains.html | 58 -- www/hourly.html | 85 --- www/login.html | 66 --- www/me.html | 119 ---- www/overview.html | 81 --- www/review.html | 34 -- www/upstreams.html | 36 -- www/usage.html | 106 ---- www/users.html | 50 -- 128 files changed, 110 insertions(+), 9496 deletions(-) delete mode 100644 .gitmodules delete mode 100644 AGENTS.md create mode 100644 CLAUDE.md rename rust/Cargo.lock => Cargo.lock (91%) create mode 100644 Cargo.toml create mode 100644 README.md delete mode 100644 conf/cache-common.conf delete mode 100644 conf/cache-routes.conf delete mode 100644 conf/nginx.cache.conf delete mode 100644 conf/server.cache.conf delete mode 100644 conf/tls/README.md delete mode 100644 conf/tls/cache.conf.example delete mode 160000 deps/ipass delete mode 100644 docs/plugins.md delete mode 100644 rust/Cargo.toml delete mode 100644 rust/crates/plugin-cache/Cargo.toml rename {rust/crates/plugin-cache/src => src}/api.rs (100%) rename {rust/crates/plugin-cache/src => src}/cache.rs (100%) rename {rust/crates/plugin-cache/src => src}/config.rs (100%) rename {rust/crates/plugin-cache/src => src}/handlers.rs (89%) rename {rust/crates/plugin-cache/src => src}/lib.rs (97%) rename {rust/crates/plugin-cache/src => src}/models.rs (100%) rename {rust/crates/plugin-cache/src => src}/stats.rs (100%) rename {rust/crates/plugin-cache/src => src}/store.rs (100%) rename {rust/crates/plugin-cache/src => src}/upstreams.rs (100%) rename {rust/crates/plugin-cache/src => src}/zones.rs (100%) delete mode 100644 tests/cache/.run-evict/cache/maven/1/fb/052807f7dcf903b482f647fb0035afb1 delete mode 100644 tests/cache/.run-evict/cache/npm/0/6b/7c08263957217762708264c0587196b0 delete mode 100644 tests/cache/.run-evict/cache/npm/1/b6/f4b23ecc52cf5b24fbe08fcc49a80b61 delete mode 100644 tests/cache/.run-evict/cache/npm/3/d8/819209f49ca3661d21dbcc7cff467d83 delete mode 100644 tests/cache/.run-evict/cache/npm/6/20/133297d4a6a307d27f01825f9fc2e206 delete mode 100644 tests/cache/.run-evict/cache/npm/8/70/53b42c650712625207fc721e28295708 delete mode 100644 tests/cache/.run-evict/conf/cache-common.conf delete mode 100644 tests/cache/.run-evict/conf/cache-routes.conf delete mode 100644 tests/cache/.run-evict/conf/mime.types delete mode 100644 tests/cache/.run-evict/conf/nginx.cache.conf delete mode 100644 tests/cache/.run-evict/conf/server.cache.conf delete mode 100644 tests/cache/.run-evict/data/api-proxies.json delete mode 100644 tests/cache/.run-evict/data/cache-upstreams.json delete mode 100644 tests/cache/.run-evict/data/domains.json delete mode 100644 tests/cache/.run-evict/data/llm-stats.json delete mode 100644 tests/cache/.run-evict/data/llm-upstreams.json delete mode 100644 tests/cache/.run-evict/data/users.json delete mode 100644 tests/cache/.run-evict/logs/cache.log delete mode 100644 tests/cache/.run-evict/logs/error.log delete mode 100644 tests/cache/.run-evict/logs/upstream.out delete mode 100644 tests/cache/.run-evict/upstream.log delete mode 100644 tests/cache/.run-evict/upstream.pid delete mode 120000 tests/cache/.run-evict/www delete mode 100644 tests/cache/.run-ipass/cache/cargo/7/b6/fa85c45018774ee40eed4e14f27e5b67 delete mode 100644 tests/cache/.run-ipass/cache/docker/6/2b/006332a6c46dd553c5b07fbe163dd2b6 delete mode 100644 tests/cache/.run-ipass/cache/go/a/1d/3628fdf82489b1d8471bcfb362cee1da delete mode 100644 tests/cache/.run-ipass/cache/maven/5/57/018b43239012a992b6a642253ec85575 delete mode 100644 tests/cache/.run-ipass/cache/npm/c/11/531eb8fade2b128eb9584b2f4e7e011c delete mode 100644 tests/cache/.run-ipass/cache/pypi/5/02/0351062533e47711f552e75f9bdd9025 delete mode 100644 tests/cache/.run-ipass/conf/cache-common.conf delete mode 100644 tests/cache/.run-ipass/conf/cache-routes.conf delete mode 100644 tests/cache/.run-ipass/conf/mime.types delete mode 100644 tests/cache/.run-ipass/conf/nginx.cache.conf delete mode 100644 tests/cache/.run-ipass/conf/server.cache.conf delete mode 100644 tests/cache/.run-ipass/data/cache-upstreams.json delete mode 100644 tests/cache/.run-ipass/data/llm-stats.json delete mode 100644 tests/cache/.run-ipass/data/users.json delete mode 100644 tests/cache/.run-ipass/logs/cache.log delete mode 100644 tests/cache/.run-ipass/logs/error.log delete mode 100644 tests/cache/.run-ipass/logs/upstream.out delete mode 100644 tests/cache/.run-ipass/upstream.log delete mode 120000 tests/cache/.run-ipass/www delete mode 100644 tests/cache/.run-prod/conf/cache-common.conf delete mode 100644 tests/cache/.run-prod/conf/cache-routes.conf delete mode 100644 tests/cache/.run-prod/conf/mime.types delete mode 100644 tests/cache/.run-prod/conf/nginx.cache.conf delete mode 100644 tests/cache/.run-prod/conf/server.cache.conf delete mode 100644 tests/cache/.run-prod/logs/cache.log delete mode 100644 tests/cache/.run-prod/logs/error.log delete mode 100644 tests/cache/.run-prod/logs/nginx.pid delete mode 120000 tests/cache/.run-prod/www delete mode 100644 tests/cache/.run/cache/cargo/8/92/96bbd6bf360b9648e9afd5d07aafd928 delete mode 100644 tests/cache/.run/cache/docker/2/bd/15d75620ad41340b2459f5d02b9e6bd2 delete mode 100644 tests/cache/.run/cache/go/0/6b/decf43777bf2ea024deb844b8dd546b0 delete mode 100644 tests/cache/.run/cache/maven/e/16/288a53c6200b2faf2e49cb2b4bf4716e delete mode 100644 tests/cache/.run/cache/npm/d/50/3c799f495786fbc96054087c25adb50d delete mode 100644 tests/cache/.run/cache/pypi/a/3f/1b29e40ff5e9bd7150ad962d7181b3fa delete mode 100644 tests/cache/.run/logs/error.log delete mode 100644 tests/cache/.run/logs/upstream.out delete mode 100644 tests/cache/.run/nginx.conf delete mode 100644 tests/cache/.run/upstream.log delete mode 100755 tests/cache/dev-server.sh delete mode 100644 tests/cache/e2e-auth.sh delete mode 100644 tests/cache/fixtures/api-proxies.json delete mode 100644 tests/cache/fixtures/domains.json delete mode 100644 tests/cache/fixtures/llm-upstreams.json delete mode 100644 tests/cache/fixtures/users.json delete mode 100644 tests/cache/lib-render.sh delete mode 100755 tests/cache/mock_upstream.py delete mode 100644 tests/cache/nginx.cache.local.conf delete mode 100755 tests/cache/run.sh delete mode 100644 tests/cache/test-cache-capacity.sh delete mode 100755 tests/cache/test-cache.sh delete mode 100755 tests/cache/test-ipass-cache.sh delete mode 100644 tests/cache/test-real-registries.sh delete mode 100755 tests/cache/validate-prod-conf.sh delete mode 100644 tests/cache/verify-cache-eviction.sh delete mode 100644 www/apix.html delete mode 100644 www/assets/admin.css delete mode 100644 www/assets/apix.js delete mode 100644 www/assets/cache.js delete mode 100644 www/assets/chart.js delete mode 100644 www/assets/core.js delete mode 100644 www/assets/domains.js delete mode 100644 www/assets/hourly.js delete mode 100644 www/assets/me.js delete mode 100644 www/assets/overview.js delete mode 100644 www/assets/review.js delete mode 100644 www/assets/upstreams.js delete mode 100644 www/assets/usage.js delete mode 100644 www/assets/users.js delete mode 100644 www/cache.html delete mode 100644 www/domains.html delete mode 100644 www/hourly.html delete mode 100644 www/login.html delete mode 100644 www/me.html delete mode 100644 www/overview.html delete mode 100644 www/review.html delete mode 100644 www/upstreams.html delete mode 100644 www/usage.html delete mode 100644 www/users.html diff --git a/.gitignore b/.gitignore index d5a327d..5a90822 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,18 @@ # ===== 构建产物(绝不入库)===== -rust/target/ +/target/ build/ -target/ **/*.rlib **/*.so **/*.dylib **/*.o -# ===== 测试运行态实例(缓存文件 / nginx 进程 / 日志 / 临时实例)===== -# 所有 .run-* 运行时目录(.run-dev / .run-auth / .run-cap ...)一律不入库 -tests/**/.run-*/ -.run-*/ +# ===== 前端(UMD 面板改造后)===== +www/node_modules/ +www/dist/ # ===== 工作区数据(非项目源码)===== .workbuddy/ -# ===== 临时 / 被取代的目录 ===== -.pre113-mypatch/ -_superseded-docker/ - # ===== OS / 编辑器 ===== .DS_Store *.swp diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 1ed6f50..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "deps/ipass"] - path = deps/ipass - url = http://ssw:sswsswssw@192.168.1.18:13300/ipass/ipass.git diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index bfa397e..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,67 +0,0 @@ -# AGENTS.md — iPass cache 网关(插件仓) - -面向 AI agent 的项目上手与改造约束。先读这份,再碰代码。 - -## 这是什么 -iPass 统一制品缓存网关的**插件仓**(内网 Gitea:`ipass/cache`)。 -一个 nginx 入口 + 一把统一 `sk_` Key + 8 个路由(go / cargo / cargo-dl / pypi / pypi-files / npm / maven / docker v2),数据面用 nginx 原生 `proxy_cache`(本地磁盘),鉴权 / 计量 / 上游表由 Rust 模块管。 - -**本仓只含 cache 插件本身的源码**(见下「仓库边界」)。内核 `ipass-core`、模块壳 `gateway`、vendored `ngx-rust`、以及 domain/llm/apix 等其他子系统,**不在本仓**——它们属于主项目 `ipass/ipass`,本仓通过 git submodule(`deps/ipass`)引用,仅用于编译 cache 插件时解析依赖。 - -## 仓库边界(改前必看) -- ✅ 入库(本仓库职责):`rust/crates/plugin-cache`(cache 插件源码)、`conf`(cache 网关 nginx 模板)、`www`(cache 管理台前端)、`tests/cache`(cache 端到端)、`docs`、`AGENTS.md`、`docs/plugins.md`。 -- 🔗 以 submodule 引入(**非本仓源码**,来自 `ipass/ipass`,不要在本仓改):`deps/ipass/`(`ipass-core` / `gateway` / `vendor/ngx-rust` / `plugin-domain` / `plugin-llm` / `plugin-apix`)。 -- ❌ 不入库(见 `.gitignore`):`rust/target/`、`build/`、`*.dylib/*.so`、`tests/cache/.run-*/`(所有测试运行时目录)、`.workbuddy/`。 -- 远程:`origin = http://ssw:sswsswssw@192.168.1.18:13300/ipass/cache.git`,分支 `main`。 - -> ⚠️ **避免相互干扰**:本仓与主项目 `ipass/ipass` 代码分离。cache 插件的全部修改只落在本仓;`ipass-core` 等内核/框架的修改回到 `ipass/ipass`。改内核共享内存 schema 前务必评估对所有插件的影响。 - -## 代码布局 -本仓是一个**单成员 cargo workspace**,只编 `plugin-cache`: - -| 组件 | 位置 | 版本 | 职责 | 归属 | -|------|------|------|------|------| -| `plugin-cache` | `rust/crates/plugin-cache` | 0.1.0 | 统一制品缓存:8 路由代理、命中计量、上游动态注入、管理 API、容量管理 | ★ 本仓库 | -| `ipass-core` | `deps/ipass/rust/crates/ipass-core`(submodule) | 2.0.0 | 内核:共享内存 / 账号 / 会话 / 认证 / 存储 / 通用原语 | 主项目 `ipass/ipass` | -| `gateway` | `deps/ipass/rust/gateway`(submodule) | 2.0.0 | 唯一 cdylib:聚合插件 `ngx_module_t`、FFI 边界 | 主项目 | -| `vendor/ngx-rust` | `deps/ipass/rust/vendor/ngx-rust`(submodule) | — | vendored `ngx` + `nginx-sys`(离线编译) | 主项目(vendored) | -| `plugin-domain` / `plugin-llm` / `plugin-apix` | `deps/ipass/rust/crates/*`(submodule) | 2.0.0 | 其他子系统 | 主项目各子系统 | - -`plugin-cache` 的依赖(`ipass-core` / `ngx` / `nginx-sys`)在 `rust/Cargo.toml` 中通过 `../deps/ipass/rust/...` 指向 submodule。依赖方向单向:`plugin-cache` → `ipass-core` → `vendor/ngx-rust` → nginx C 进程;跨 `.so` 不传 Rust 类型(否则双重 free),所以只有 `gateway` 是 cdylib,其余全是 rlib。 - -## 构建 -前置:本仓需要主项目代码来解析依赖。 -```bash -git submodule update --init deps/ipass # 拉取 ipass-core / gateway / ngx-rust ... -``` -- **仅类型检查 / 编译插件(rlib)**:`cd rust && cargo build -p plugin-cache`。 - 这会顺着 `../deps/ipass` 把 `ipass-core` 与 `nginx-sys` 一起编出来(nginx-sys 需要 `NGINX_SOURCE_DIR` / `NGINX_BUILD_DIR` 指向一份 nginx 源码,见技能 `nginx-rs-module-local-verify`)。 -- **产出可加载模块(cdylib)并跑端到端**:本仓没有 `gateway`(cdylib 在 submodule 里)。要在本机得到 `libipass_gateway.dylib` 并运行 `tests/cache/*.sh`,请在主项目 `ipass/ipass` 中装配 cache 插件: - 1. 把本仓的 `rust/crates/plugin-cache` 放到 `ipass/ipass/rust/crates/plugin-cache`(或让主项目以 submodule/override 消费本仓); - 2. 在 `ipass/ipass/rust/Cargo.toml` 的 `members` 加 `"crates/plugin-cache"`,在 `ipass/ipass/rust/gateway/Cargo.toml` 的 `[dependencies]` 加 `plugin-cache.workspace = true`; - 3. 按技能 `nginx-rs-module-local-verify` 编译 `gateway` 得到 `.dylib`,再以 `tests/cache/dev-server.sh` / `test-cache*.sh` 验证。 - > 主项目 `ipass/ipass` 当前的 `gateway` 只装配 domain/llm/apix(不含 cache),所以上面第 2 步是接 cache 的唯一接线点。 -- macOS 编译 nginx 必须 `-DNGX_HAVE_SCHED_SETAFFINITY=0`;`[profile.release]` 只能放 workspace 根(`panic="abort"`,丢了意味着 panic 跨 FFI 边界展开进 nginx)。 - -## 端到端验证(基线,连跑两轮一致) -cache 测试都在 `tests/cache/`: -- `tests/cache/test-cache.sh` 23/23、`tests/cache/test-ipass-cache.sh` 24/24、`tests/cache/validate-prod-conf.sh` ✅、`tests/cache/e2e-auth.sh` 29/29。 -- 容量管理:`tests/cache/test-cache-capacity.sh` 48/48。 -- 跑法见 `tests/cache/run.sh`(或单独 `bash tests/cache/<脚本>`);任何「读上游日志做断言」的步骤先断言本次 MISS,且测试开头清 `$RUN/cache`。 - -## 不可动摇的架构约定(改前要懂) -1. 上游地址 / 凭据只存共享内存 `cx:`(管理台写穿,落盘 `data/cache-upstreams.json`);conf 只出现变量名 `$cache_target` / `$cache_host` / `$cache_auth`。改上游不改 conf、不 reload。 -2. `$cache_key` 必须含 query(`:[?args]`);`proxy_cache_key = $cache_key$request_method$http_accept`(不含 `sk_`)。 -3. `sk_` 绝不外传上游:出站 `Authorization` 三段式(本路由凭据 → 透传客户端值 → 丢弃网关 `sk_`);同时抹掉 `x-api-key` / `api-key`。 -4. 未配上游的路由 → 503(不是 500)。 -5. **唯一 conf 渲染器**:`tests/cache/lib-render.sh`(`cache_render_prod_conf` / `cache_write_upstreams`)。禁止手抄第二份「生产 conf → 测试前缀」替换逻辑。 -6. 清理缓存**只删文件,绝不删 `cache/` 目录本身**(否则 `[crit] mkdir failed` + 客户端断开);批量清理用 `find <子树> -type f -delete` + 残留自检。 -7. 生成 / 改写 conf 一律用 python,不用 BSD `sed`;脚本里 `curl` 统一 `--noproxy '*'`(本机代理会吞 localhost)。 - -## 提交规范 -- 只提交源码(`.gitignore` 已排除产物);push 到 `ipass/cache` 的 `main`。 -- **改动范围**:只动本仓的 `plugin-cache` / `conf` / `www` / `tests/cache` / `docs`。若要升级 `ipass-core` 等,请到 `ipass/ipass` 改,或在本仓 `git submodule update` 拉新提交后 `git add deps/ipass`。**禁止在 `deps/ipass/` 里直接改代码**(那是主项目源码)。 -- 大 push 设 `http.postBuffer=524288000`;若报 `unable to get credential storage lock`,先 `rm -f ~/.git-credentials.lock`(无 git 进程时)。 - -## 插件边界 -见 [`docs/plugins.md`](docs/plugins.md)。 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..fb16433 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,49 @@ +# CLAUDE.md + +## 入口(规划中,gateway 接入后生效) + +| URL | 目标 | +|-----|------| +| `http://nginx/go/ /cargo/ /cargo-dl/ /pypi/ /pypi-files/ /npm/ /maven/ /v2/` | 数据面(nginx 原生 `proxy_cache`;本插件 access 鉴权 + log 计量) | +| `http://nginx/api/admin/cache*` | 本插件认领的管理 API(Admin) | +| `http://nginx/api/v1/cache*` | 账号态接入说明 / 命中统计(User) | + +## 装配关系 + +本仓库是 **ipass-core 内核**的一个 *crate 级* 插件(不是 nginx 动态模块)。 +nginx 动态模块没有稳定 ABI,所有插件在 gateway 装配层以 `ipass_plugin_xxx` +extern "C" 入口函数形式注册到单个 cdylib `.so` 内。 + +**当前状态:尚未挂载到任何 gateway**(2026-09-24 由旧独立应用仓 +`ipass/cache` 改造为插件仓;旧形态完整保留在 tag `legacy-app-final`)。 +接入时需要做的配套改动: + +1. 宿主 gateway 的 `PLUGINS` 数组加 `&ipass_plugin_cache::CachePlugin` +2. 宿主 conf 加 `proxy_cache_path` 与各生态 location;location 级开关 + `ipass_cache` 需给 core `loc::Switch` 补 `Cache` 变体,并同步三个 + gateway 的穷尽 match(保守 false)——接入轮一并处理 +3. ipass-core `plugin_registry::KNOWN_PLUGINS` 加 `"cache"`、 + `plugin-config.example.json` 补条目 +4. `www/` 重写为 UMD 面板(`plugin-cache-admin.umd.js`,对齐兄弟仓) + +## 启停 + +与其他插件一致走 R19 注册表:配置键 = `cache`(`Plugin::name()` 短名)。 +禁用语义与 waf/sso 的「放行」**不同**,是 fail-closed → 404——数据面是 +鉴权后的磁盘读,禁用时放行等于无鉴权读缓存(见 `src/handlers.rs`)。 +详见 `../ipass-core/docs/toggle.md`。 + +## 构建/开发 + +本机不启用 `nginx-sys/vendored`,沿用兄弟仓姿势:env 指向一份已 configure 的 +nginx 源码树(bindgen 从其 `objs/Makefile` 抽 `-I`;路径不可 `mv`, +详见 `../ipass-waf/rust/BUILD.md` 同款说明)。 + +```bash +export LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib +export NGINX_SOURCE_DIR=/Users/xs/Desktop/workspace/ipass/ipass-ssw/build/ngxbuild/nginx-1.30.4 +export NGINX_BUILD_DIR=$NGINX_SOURCE_DIR/objs +cargo check --release && cargo test --release +``` + +兄弟仓库:`../ipass-core/`、`../ipass-plugin-{domain,llm,apix,sso,waf}/`。 diff --git a/rust/Cargo.lock b/Cargo.lock similarity index 91% rename from rust/Cargo.lock rename to Cargo.lock index c3b3ddd..8eb777b 100644 --- a/rust/Cargo.lock +++ b/Cargo.lock @@ -54,9 +54,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.4.5" +version = "1.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" dependencies = [ "find-msvc-tools", "shlex 2.0.1", @@ -73,9 +73,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "clang-sys" @@ -141,9 +141,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" [[package]] name = "generic-array" @@ -186,21 +186,14 @@ dependencies = [ ] [[package]] -name = "ipass-gateway" +name = "ipass-plugin-cache" version = "2.0.0" dependencies = [ - "getrandom", "ipass-core", - "libc", "nginx-sys", "ngx", - "plugin-apix", - "plugin-cache", - "plugin-domain", - "plugin-llm", "serde", "serde_json", - "sha2", ] [[package]] @@ -292,50 +285,6 @@ 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-cache" -version = "0.1.0" -dependencies = [ - "ipass-core", - "nginx-sys", - "ngx", - "serde", - "serde_json", -] - -[[package]] -name = "plugin-domain" -version = "2.0.0" -dependencies = [ - "ipass-core", - "ngx", - "serde", - "serde_json", -] - -[[package]] -name = "plugin-llm" -version = "2.0.0" -dependencies = [ - "ipass-core", - "nginx-sys", - "ngx", - "serde", - "serde_json", -] - [[package]] name = "prettyplease" version = "0.2.37" @@ -432,7 +381,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] [[package]] @@ -484,9 +433,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.5" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" dependencies = [ "proc-macro2", "quote", @@ -501,9 +450,9 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" [[package]] name = "version_check" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..3b01661 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "ipass-plugin-cache" +version = "2.0.0" +edition = "2021" +publish = false +description = "iPass cache plugin: 统一制品缓存(go/rust/python/npm/java/docker)鉴权 / 命中计量 / 管理 API" + +[lib] +# 只有 gateway 是 cdylib;插件一律 rlib(跨 .so 传 Rust 类型会双重 free) +crate-type = ["rlib"] + +[dependencies] +ipass-core = { path = "../ipass-core/rust/crates/ipass-core" } +ngx = { path = "../ipass-core/rust/vendor/ngx-rust" } +nginx-sys = { path = "../ipass-core/rust/vendor/ngx-rust/nginx-sys" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/README.md b/README.md new file mode 100644 index 0000000..82c90b6 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# ipass-plugin-cache + +iPass 统一制品缓存插件(go / cargo / pypi / npm / maven / docker)。 + +- **缓存内容**:nginx 原生 `proxy_cache` 落本地磁盘,插件不碰制品字节 + (转发、Range、重试、连接池、磁盘淘汰全交回 nginx) +- **鉴权 / 计量 / 管理 API**:本插件 access handler(统一 `sk_` Key,与 + LLM/apix 同一份配额)+ log handler(按生态记 `HIT/MISS/...`,共享内存) +- **上游表**:`cx:` → 共享内存 + JSON 落盘,写法与 `plugin-apix` + 的 `ax:` 同构 + +用法与容量运维细节见 [docs/cache-usage.md](docs/cache-usage.md)。 +插件仓约定、接入待办、启停语义见 [CLAUDE.md](CLAUDE.md)。 diff --git a/conf/cache-common.conf b/conf/cache-common.conf deleted file mode 100644 index 3852e97..0000000 --- a/conf/cache-common.conf +++ /dev/null @@ -1,131 +0,0 @@ -# ============================================================================ -# cache-common.conf —— 各生态 cache location 共用的缓存/代理指令 -# -# 由 conf/cache-routes.conf 在每个 location 内 `include`。 -# **每个 location 自己指定** `proxy_cache `(各生态分库),本文件只放公共项。 -# -# --------------------------------------------------------------------------- -# 与「静态上游版」相比的三处关键变化(配合 plugin-cache 的变量层) -# --------------------------------------------------------------------------- -# -# 1. `proxy_pass` 由字面量改为变量 `$cache_target`。上游地址与凭据因此来自 -# 共享内存(`cx:`,由管理台写),**改上游不用改 conf、不用 reload**。 -# 代价:变量式 proxy_pass 不推导 Host、不追加 query —— 两者都由模块算好, -# 所以这里必须显式 `proxy_set_header Host $cache_host`。 -# -# 2. `proxy_cache_key` 不再用 `$scheme$proxy_host$request_uri`(变量式下 -# `$proxy_host` 不可靠),改用模块给的 `$cache_key`,并**并入方法 + -# Accept**(下面的注释详述为什么这是正确性问题,不是调优)。 -# -# 3. 出站鉴权头改成三段式(`proxy_pass_request_headers on` + 抹掉三个 -# 网关 Key 携带位 + 用 `$cache_auth` 下发)——见文件下半部分。 -# -# ⚠️ 本文件**不得**使用 rewrite 模块的 `set` / `if`;生态判定由 plugin-cache -# 直读 `r->uri` 首段完成,不需要 `set $cache_ecosystem`。 -# (`return` / `rewrite` 本身可用:本机构建与 ipass 生产都带 --with-pcre, -# rewrite 模块在编。它们只在 cache-routes.conf 里用。) -# ============================================================================ - -# --------------------------------------------------------------------------- -# 缓存键 -# --------------------------------------------------------------------------- -# -# `$cache_key` = `:<完整 URI + query>`,**不含任何下游凭据** —— 缓存因此是 -# 「全站共享」的:同一个 go module / npm 包被 N 个账号拉,只回源一次。 -# 这正是制品缓存的价值所在;鉴权在 access 层(谁能读),数据在共享层复用。 -# 代价:任一有效 Key 都能命中别人拉过的制品 —— 对公开 registry 无碍, -# 若某路由指向**私有**上游,请理解这一点再启用。 -# -# ★ query 必须进键(由模块的 `$cache_key` 负责,本行不要再自己拼 `$args`): -# npm 的 `?write=true`、docker 的 `?ns=`、go 的 `?go-get=1`、cargo 的 -# `?archive=tar.gz` 都靠 query 区分实体。变量式 `proxy_pass` 下 `$uri` -# **不含** query,只按 `$uri` 做键会把 `/x?a` 与 `/x?b` 当成同一个资源, -# 把错的制品发给客户端(且第二次完全不回源,很难察觉)。 -# -# ★ 为什么要并入 `$request_method` 与 `$http_accept`(这是正确性,不是调优): -# -# · `$request_method`:Docker 客户端对同一 URL 先 `HEAD` 看清单存不存在、 -# 再 `GET` 取清单(registry 协议如此)。若两者共用一个键,一次 HEAD 的 -# **空体**响应会被缓存下来并回给随后的 GET,客户端拿到 0 字节清单直接失败。 -# -# · `$http_accept`:nginx 的 proxy_cache **不实现 Vary**(只能靠 -# proxy_ignore_headers 把 Vary 忽略掉,无法参与分档)。而上游同一 URL -# 会因为 Accept 返回**不同实体**: -# - npm:`application/vnd.npm.install-v1+json` → 精简元数据, -# 缺省 → 完整元数据; -# - PyPI simple:`application/vnd.pypi.simple.v1+json` → JSON, -# `text/html` → HTML; -# - Docker:清单 v2 / OCI / v1 的 mediaType 由 Accept 偏好决定。 -# 不并入 Accept 就会出现「发给 A 的实体被回给 B」的串档。代价是每个 -# Accept 变体一个桶(现代客户端取值收敛,实际只多一个桶)。 -# -# 注:刻意**不**再带 `$scheme`/`$proxy_host`:同一份制品无论客户端走 http -# 还是 https、走哪个域名进来,上游都是同一个,共享一份缓存更省盘也更省带宽。 -proxy_cache_key $cache_key$request_method$http_accept; - -# 只缓存完整 GET/HEAD(200/301/308);404 短缓存;206(range)/401 等不缓存,避免错片 -proxy_cache_methods GET HEAD; -proxy_cache_valid 200 301 308 1d; -proxy_cache_valid 404 1m; - -# 上游抖动时用陈旧副本兜底;并发同键只回源一次(防击穿) -proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; -proxy_cache_lock on; -proxy_cache_lock_age 10s; -proxy_cache_lock_timeout 30s; - -# 带 If-None-Match / If-Modified-Since 回源校验,省带宽 -proxy_cache_revalidate on; - -# 加速缓存:不被上游 no-cache/Set-Cookie/Vary 拦下(镜像型缓存的标准取舍) -# ⚠️ Vary 被忽略是**必须**的——见上面缓存键的说明,我们已用 Accept 显式分档; -# 留着 Vary 反而会让 nginx 拒绝缓存这些响应。 -proxy_ignore_headers Cache-Control Expires Set-Cookie Vary; - -proxy_http_version 1.1; - -# --------------------------------------------------------------------------- -# 出站请求头(镜像型:默认透传,但抹掉「本网关自己的 Key」) -# --------------------------------------------------------------------------- -# -# 与 LLM/API 代理的 allowlist 策略**刻意不同**:那些是无状态 API,客户端 -# 头没有语义;而镜像必须原样带上客户端的 `Accept` / `Range` / -# `If-None-Match` / `User-Agent`,否则 docker 的 mediaType 协商、range 取 -# 大 blob、条件请求全部失效。所以这里保持 `on`(nginx 默认),只在三个 -# 「网关 Key 的携带位」上显式抹空。 -# -# 为什么必须抹:`sk_` 是客户端访问**本网关**的身份(auth::downstream_key 认 -# Authorization / x-api-key / api-key 三处)。原样透传给上游 = 把网关钥匙 -# 递给上游厂商,对方可拿它反调本网关的其它路由刷额度。ipass 的 LLM 路径 -# 记过同一个坑(宽松厂商把这缺陷掩盖成 200,换严格厂商才暴露成 401)。 -proxy_pass_request_headers on; -proxy_set_header x-api-key ""; -proxy_set_header api-key ""; - -# 变量形式 proxy_pass 不会推导 Host,必须显式设(上游多为 Cloudflare 前端, -# Host 不符会被直接拒) -proxy_set_header Host $cache_host; - -# Authorization 三段式(由模块里的 `$cache_auth` 实现,语义见其文档): -# 配了上游凭据 → 下发配置值(管理员写全 `Bearer xxx` / `Basic yyy`) -# 没配 → 透传客户端值(Docker Hub 的短期 Bearer token 走这条) -# 客户端那把恰好是下行 sk_ → 丢弃 -proxy_set_header Authorization $cache_auth; - -proxy_set_header X-Real-IP $remote_addr; -proxy_set_header X-Forwarded-For $remote_addr; -proxy_set_header X-Forwarded-Proto $scheme; - -# registry 大 blob / 慢索引:放宽超时 -proxy_read_timeout 300s; -proxy_send_timeout 300s; - -# 变量式/直连上游为 HTTPS 时开 SNI;证书校验此阶段关闭(镜像多为公开源, -# 且目标主机来自管理台配置而非请求。要严格校验需另配 proxy_ssl_trusted_certificate) -proxy_ssl_server_name on; -proxy_ssl_protocols TLSv1.2 TLSv1.3; -proxy_ssl_verify off; - -# 观测:每次响应带回缓存命中状态(ipass plugin-cache 亦从同一变量记账) -add_header X-Cache-Status $upstream_cache_status always; -add_header X-Cache-Eco $cache_eco always; diff --git a/conf/cache-routes.conf b/conf/cache-routes.conf deleted file mode 100644 index 4c50106..0000000 --- a/conf/cache-routes.conf +++ /dev/null @@ -1,177 +0,0 @@ -# ============================================================================ -# cache-routes.conf —— 制品缓存网关的「server 内容」(在 server { } 里 include) -# -# 为什么单独成一个文件:这份路由要**两处复用**—— -# * 明文入口 conf/server.cache.conf(本机 e2e / 内网直连) -# * TLS 入口 conf/tls/*.conf(对外,Docker 镜像加速必须走 https) -# 路由、鉴权开关、探针、管理台只写一份,两个入口不会漂。 -# -# 路由约定:/<前缀>/ => <该 route 配置的上游>/ -# /go/ Go module proxy → 默认 proxy.golang.org -# /cargo/ crates.io 稀疏索引 → 默认 index.crates.io -# /cargo-dl/ .crate 包本体 → 默认 static.crates.io -# /pypi/ PyPI 简单索引/JSON → 默认 pypi.org -# /pypi-files/ wheel/sdist 包文件 → 默认 files.pythonhosted.org -# /npm/ npm registry → 默认 registry.npmjs.org -# /maven/ Maven Central → 默认 repo1.maven.org/maven2 -# /v2/ Docker Registry v2 → 默认 registry-1.docker.io -# -# ⚠️ 上游地址**不写在本文件里**:全部来自 plugin-cache 的上游表(管理台 -# 「制品缓存」页,落盘 data/cache-upstreams.json + 写穿共享内存)。 -# 本文件只出现变量名。改上游 = 改管理台,不需要动 conf、不需要 reload。 -# -# ⚠️ 每个带 `ipass_cache on` 的 location 都会在 access 阶段做闸门: -# 1) 该路由没配上游 → 503(不会让请求走到空 $cache_target 变成 500) -# 2) 统一 sk_ Key 鉴权(与 LLM / API 代理同一把)→ 401 -# 3) 每分钟/每日配额 → 429 -# 然后数据面才交给 nginx 原生 proxy_cache。 -# ============================================================================ - - # ---------------- 管理台(多页静态资源,挂在 /admin/ 下)---------------- - # 每页 head 里有 ,所以资源与 /api/ 都是绝对路径。 - # - # **不发版不重启也能修好页面**:所有 HTML / CSS / JS 都加 - # `Cache-Control: no-store`(expires -1 + add_header)。否则用户浏览器会 - # 一直用发版前的旧 JS —— 典型表现是「后端加了字段,页面上看不到」。 - # - # ⚠️ alias 刻意写**相对**路径 `www/`:nginx 把 root/alias 的相对路径解析到 - # **prefix** 而不是 conf/,所以生产(prefix=/usr/local/nginx)得到 - # /usr/local/nginx/www/,本地回归(prefix=tests/.../.run-prod)得到 - # 测试自己的 www/。写死绝对路径则本机必 404。 - location = / { - return 302 /admin; - } - location = /admin { - default_type text/html; - alias www/cache.html; - expires -1; - add_header Cache-Control "no-store" always; - } - # `/admin/`(末尾斜杠、后面无字符)不能直接 alias 到目录:nginx 会把 - # index 拼成 `cache.htmlindex.html` 而 500。内部重定向到具体文件最干净。 - location = /admin/ { - rewrite ^ /admin/cache.html last; - } - location /admin/ { - alias www/; - expires -1; - add_header Cache-Control "no-store" always; - } - - # ---------------- API:管理态(登录会话)+ 账号态(sk_)---------------- - # 由 plugin-cache 认领 /api/admin/cache* 与 /api/v1/cache*; - # 其余 /api/* 交给同一 gateway 里的其它插件(llm/apix/domain),互不干扰。 - location /api/ { - ipass_api on; - } - - # ---------------- 上游连通性探针(管理台「测试」按钮)---------------- - # /api/admin/cache/test 校验 route 后由模块内部重定向到这里。 - # 刻意**复用** $cache_target / $cache_host / $cache_auth —— 与真实转发 - # 走同一套「拼上游 URL + 换凭据」逻辑,所以「测试通过」才等价于 - # 「真实请求能到上游并带上凭据」;另写一套探针代码必然漂移。 - # - # 为什么这里不写 `ipass_cache on`:内部重定向会重跑 access 阶段,而管理台 - # 带的是**登录 Cookie、不是 sk_**,再鉴一次会把自己 401 掉。鉴权已在 - # /api/admin/cache/test 那一跳用 Admin 守卫做过,这里是 internal,外部进不来。 - # - # proxy_cache off:探针是「验连通」,不该用一次探测污染 1d 的制品缓存。 - location /_cache_test/ { - internal; - proxy_cache off; - proxy_pass $cache_target; - proxy_http_version 1.1; - # 探针只验「拼目标 + 换凭据 + 到达上游」,请求头与请求体都不需要转发: - # * 方法由模块钉成 GET(见 plugin-cache api.rs 的 h_admin_test); - # * body 必须 off —— 管理台是用 POST 触发的,不 off 的话那 2 字节 `{}` - # 会连 Content-Length 一起发出去,上游等一个 GET 的 body、 - # 或 keepalive 上残留半截请求体,表现为「测试时好时坏」。 - proxy_pass_request_headers off; - proxy_pass_request_body off; - proxy_set_header Host $cache_host; - proxy_set_header Authorization $cache_auth; - proxy_set_header User-Agent $http_user_agent; - proxy_ssl_server_name on; - proxy_connect_timeout 5s; - proxy_send_timeout 15s; - proxy_read_timeout 15s; - } - - # ---------------- Go module proxy ---------------- - location /go/ { - ipass_cache on; - proxy_cache go; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- crates.io 稀疏索引 ---------------- - location /cargo/ { - ipass_cache on; - proxy_cache cargo; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- .crate 包本体 ---------------- - # ⚠️ crates.io 的 config.json 里 `dl` 字段给的是**绝对 URL** - # (https://static.crates.io/crates/...),cargo 默认直连上游域名、绕过本网关, - # 所以这个 location 只是**落点就绪**。要真正命中需二选一: - # (a) nginx 开 http_sub_module,用 sub_filter 把索引/`config.json` 里的 - # 绝对 URL 改写成 https://<本网关>/cargo-dl;或 - # (b) 网络层把 static.crates.io 指到本网关(内网 DNS + 证书)。 - # 两者都归到 cargo 生态计数(plugin-cache 的 eco_of_route 已做映射)。 - location /cargo-dl/ { - ipass_cache on; - proxy_cache cargo; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- PyPI 简单索引 / JSON ---------------- - location /pypi/ { - ipass_cache on; - proxy_cache pypi; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- wheel/sdist 包文件 ---------------- - # ⚠️ 与 /cargo-dl/ 同理:PyPI simple 页里的 href 是绝对 URL - # (https://files.pythonhosted.org/...),pip 默认直连,需 sub_filter 重写 - # 或 DNS 指向才能命中本 location。归到 pypi 生态计数。 - location /pypi-files/ { - ipass_cache on; - proxy_cache pypi; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- npm registry ---------------- - location /npm/ { - ipass_cache on; - proxy_cache npm; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- Maven Central ---------------- - location /maven/ { - ipass_cache on; - proxy_cache maven; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- Docker Registry v2 ---------------- - # registry-mirrors 要求 https(见 conf/tls/),且**只适合公开镜像**: - # 缓存键不含用户身份,私有镜像会被串档(见 cache-common.conf 的说明)。 - # 客户端先向 auth.docker.io 换短期 Bearer token 再带 Authorization 来拉, - # 该 token 由 cache-common.conf 的 $cache_auth 透传给上游(但网关自己的 - # sk_ 会被剔除)。上游路径的 `/v2` 前缀由模块的 upstream_path_prefix 补回。 - location /v2/ { - ipass_cache on; - proxy_cache docker; - proxy_pass $cache_target; - include cache-common.conf; - } diff --git a/conf/nginx.cache.conf b/conf/nginx.cache.conf deleted file mode 100644 index b9941d6..0000000 --- a/conf/nginx.cache.conf +++ /dev/null @@ -1,87 +0,0 @@ -# ============================================================================ -# nginx.cache.conf —— 统一制品缓存网关 · 顶层配置 -# -# vanilla nginx + ipass Rust 动态模块(plugin-cache) -# -# 本机回归:bash tests/cache/run.sh -# 生产部署:把本文件放到 nginx prefix 的 conf/ 下,同目录放 -# server.cache.conf / cache-routes.conf / cache-common.conf / -# mime.types,启动即可;要对外 https 再加 conf/tls/*.conf。 -# -# 数据面 = nginx 原生 proxy_cache(六生态各一个 zone,落本地盘); -# 管理面 = ipass plugin-cache(access 鉴权 + log 按生态记账 + 管理 API)。 -# -# ⚠️ 上游地址/凭据**不在 conf 里**:全在 plugin-cache 的上游表 -# (管理台「制品缓存」页 → data/cache-upstreams.json → 写穿共享内存)。 -# conf 只出现 `$cache_*` 变量名,所以改上游不需要动 conf、不需要 reload。 -# -# ⚠️ 因为 proxy_pass 是变量形式,`resolver` 是**必需**的:nginx 无法在配置 -# 解析期把变量里的主机名解析成 IP,只能运行期查 DNS。缺 resolver 的表现是 -# `/go/...` 一律 500(no resolver defined to resolve ...)。 -# -# 本构建(build/build-nginx-ssl.sh)对齐 ipass 生产的 Dockerfile 参数: -# --with-pcre --with-http_ssl_module --with-http_realip_module -# 即 rewrite 模块与 SSL 都在编,所以本文件与 server.cache.conf / -# cache-routes.conf 里可以用 `return` / `rewrite` / `ssl_certificate`。 -# ============================================================================ - -load_module /usr/local/nginx/modules/libipass_gateway.so; - -worker_processes auto; -error_log /usr/local/nginx/logs/error.log info; -pid /usr/local/nginx/logs/nginx.pid; - -# 初始管理员口令(不声明则会被 nginx 从环境中剥离) -env ADMIN_INIT_PASSWORD; - -events { - worker_connections 4096; -} - -http { - include mime.types; - default_type application/octet-stream; # 缺 Content-Type 时的兜底; - # API 响应由模块显式设 application/json - - sendfile on; - keepalive_timeout 65; - - # ========== 变量式上游的必需项 ========== - # proxy_pass $cache_target 里的主机名只能运行期解析(见文件头注释)。 - # 两个国内解析器,30s 缓存;ipv6=off 避免拿到不可达的 AAAA 卡住连接。 - resolver 223.5.5.5 119.29.29.29 valid=30s ipv6=off; - resolver_timeout 5s; - - # ========== 可选 TLS(HTTPS)========== - # conf/tls/ 下放任意 *.conf(完整的 443/18098 server 块)即启用对应域名的 - # HTTPS;目录为空或不存在时 include 空匹配,不影响启动。 - # 模板见 conf/tls/cache.conf.example,说明见 conf/tls/README.md - include /usr/local/nginx/conf/tls/*.conf; - - # ========== ipass 内核:共享内存 + 数据目录 ========== - # 一张共享内存表承载:上游表(cx:)/ 命中计数(cache:)/ 管理会话 / 限流窗口。 - # 上游表条目数 = 路由数(个位数),10m 绰绰有余。 - ipass_state state 10m; - ipass_data_dir /usr/local/nginx/data; - ipass_audit_dir /usr/local/nginx/audit; - - # ========== 六类生态缓存区(本地盘热层)========== - # 各生态独立 zone,互不串档、独立上限;use_temp_path=off 省一次改名。 - # ⚠️ cargo / pypi 各有两个 route 共用同一个 zone(索引 + 包本体): - # 这是刻意的——同一门语言的流量记在一起才看得懂,而 zone 内靠 - # $cache_key 的 route 前缀天然分档,不会串。 - proxy_cache_path /var/cache/ipass-cache/go levels=1:2 keys_zone=go:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /var/cache/ipass-cache/cargo levels=1:2 keys_zone=cargo:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /var/cache/ipass-cache/pypi levels=1:2 keys_zone=pypi:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /var/cache/ipass-cache/npm levels=1:2 keys_zone=npm:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /var/cache/ipass-cache/maven levels=1:2 keys_zone=maven:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /var/cache/ipass-cache/docker levels=1:2 keys_zone=docker:200m max_size=200g inactive=7d use_temp_path=off; - - # 命中率日志(排障用;真实指标由 plugin-cache 的共享内存计数器提供) - log_format cache '$remote_addr [$time_local] "$request" $status ' - '$body_bytes_sent cache=$upstream_cache_status eco=$cache_eco ' - 'uri=$uri rt=$request_time'; - access_log /usr/local/nginx/logs/cache.log cache; - - include server.cache.conf; -} diff --git a/conf/server.cache.conf b/conf/server.cache.conf deleted file mode 100644 index c01642b..0000000 --- a/conf/server.cache.conf +++ /dev/null @@ -1,30 +0,0 @@ -# ============================================================================ -# server.cache.conf —— 统一制品缓存 server(明文入口) -# -# 这是**内网 / 本机 e2e** 用的明文入口。对外的 https 入口在 conf/tls/*.conf -# (模板见 conf/tls/cache.conf.example)——两者 include 同一份 cache-routes.conf, -# 所以路由只此一份、不会漂。 -# -# 为什么要拆两个入口:Docker 的 `registry-mirrors` 只接受 https(明文地址会 -# 被 daemon 当成 insecure registry 拒绝),而本机自测/内网互调又不想折腾证书。 -# -# 为什么本 server 不写 listen ... ssl:证书与域名属于部署环境(见 conf/tls/), -# 写死在这里会让「同一份 conf 换域名」变成改代码。 -# ============================================================================ - -server { - listen 8080; - server_name _; - - # registry 大 blob 直通,不设体积上限(0 = 不限制) - client_max_body_size 0; - # 请求体都是小 JSON / 空体,调大缓冲区让它留在内存里,避免刷临时文件 - client_body_buffer_size 1m; - - # 管理台 `location = /` 会 302 到 /admin。不关掉的话 nginx 默认写 - # 绝对 URL + 实际 listen 端口,反代/端口映射后会把浏览器踢出链路。 - absolute_redirect off; - port_in_redirect off; - - include cache-routes.conf; -} diff --git a/conf/tls/README.md b/conf/tls/README.md deleted file mode 100644 index a9e5325..0000000 --- a/conf/tls/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# conf/tls/ —— TLS 入口 - -`conf/nginx.cache.conf` 的 `http` 块里有: - -```nginx -include /usr/local/nginx/conf/tls/*.conf; -``` - -目录为空时 include 无匹配,nginx 照常启动。往里放任意 `*.conf`(每个文件是 -一个完整的 `server { ... }` 块)即启用该域名的 HTTPS。 - -| 文件 | 作用 | -| --- | --- | -| `cache.conf.example` | TLS 入口模板。`cp` 成 `cache.conf` 后改域名/证书路径即生效 | - -## 为什么制品缓存必须有 TLS 入口 - -* **Docker**:`registry-mirrors` 只接受 https。明文地址会被 daemon 拒绝 - (除非把主机加进 `insecure-registries`,那等于放弃传输安全)。 -* **`pip` / `npm` / `cargo`**:都支持 `https://user:pass@host/` 或 token 形式, - 但明文 http 会让凭据裸奔——网关的下行 `sk_` 是长期凭据,不该走明文。 - -## 证书放哪 - -按域名建目录(可以带字面 `*`,ipass 生产就是这么存无级别泛域名证书的): - -``` -conf/tls/cache.example.com/ -├── fullchain.cer -├── cache.example.com.key -└── ca.cer -``` - -## 注意 - -* `*.example` 后缀不会被 `include *.conf;` 匹配到,所以模板文件放在这里**不会** - 被误加载。 -* 本项目的 nginx 必须带 `--with-http_ssl_module`(`build/build-nginx-ssl.sh` - 已包含)。用早前那个 `--without-http_rewrite_module` 的裁剪版会直接 - 报 `unknown directive "ssl_certificate"`。 -* `conf/tls/*.conf` 与 `server.cache.conf` 里的明文入口**共用**同一份 - `cache-routes.conf`,因此路由、鉴权、探针、管理台只维护一份。 diff --git a/conf/tls/cache.conf.example b/conf/tls/cache.conf.example deleted file mode 100644 index ea036f5..0000000 --- a/conf/tls/cache.conf.example +++ /dev/null @@ -1,42 +0,0 @@ -# ============================================================================ -# cache.conf.example —— 制品缓存网关的 TLS 入口(模板) -# -# 用法: -# 1. 复制成 conf/tls/cache.conf(http 块里 include 的是 *.conf,*.example 不生效) -# 2. 改 server_name / 三处证书路径 / listen 端口 -# 3. nginx -t && nginx -s reload -# -# 为什么必须有这个入口:Docker 的 `registry-mirrors` **只接受 https**。 -# 给 daemon 配一个明文 http 地址会直接被拒(除非改 insecure-registries, -# 那等于放弃了这一层的传输安全)。所以 /v2/ 想真正被 docker 用起来, -# 就必然要一个带证书的 server。 -# -# 与明文入口的关系:两者 include 同一份 cache-routes.conf(路由、鉴权、 -# 探针、管理台),**只差 TLS 与监听**。改路由不用改两处。 -# -# ⚠️ 本机构建(build/build-nginx-ssl.sh)已带 --with-http_ssl_module, -# 所以 ssl_certificate 能被真正校验;不带 ssl 的裁剪版会直接报 -# `unknown directive "ssl_certificate"`。 -# ============================================================================ - -server { - # 18098 沿用 ipass 的约定(路由器再把它映射到 88/443)。 - # docker daemon 允许在 registry-mirrors 里写端口:https://cache.example.com:18098 - listen 18098 ssl; - server_name cache.example.com; - - # —— 证书:三个文件都是**绝对路径**,随部署环境而异 —— - ssl_certificate /usr/local/nginx/conf/tls/cache.example.com/fullchain.cer; - ssl_certificate_key /usr/local/nginx/conf/tls/cache.example.com/cache.example.com.key; - ssl_trusted_certificate /usr/local/nginx/conf/tls/cache.example.com/ca.cer; - ssl_protocols TLSv1.2 TLSv1.3; - - absolute_redirect off; - port_in_redirect off; - - # registry 大 blob 直通,不设体积上限 - client_max_body_size 0; - client_body_buffer_size 1m; - - include cache-routes.conf; -} diff --git a/deps/ipass b/deps/ipass deleted file mode 160000 index 51f322e..0000000 --- a/deps/ipass +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 51f322e983f685d4b1fd9bbf39484273beffc0c8 diff --git a/docs/plugins.md b/docs/plugins.md deleted file mode 100644 index fbf4830..0000000 --- a/docs/plugins.md +++ /dev/null @@ -1,79 +0,0 @@ -# 插件边界说明:本仓库(cache) vs 主项目(ipass/ipass) - -## 仓库拆分原则 -为避免 cache 插件与 iPass 主框架相互干扰,本仓 `ipass/cache` **只保留 cache 插件本身的源码**;内核 `ipass-core`、模块壳 `gateway`、vendored `ngx-rust`、以及 domain/llm/apix 等其他子系统,**全部留在主项目 `ipass/ipass`**,本仓以 git submodule 形式引用: - -``` -本仓 ipass/cache -├── rust/crates/plugin-cache ← 本仓唯一源码成员(cache 插件) -├── conf/ www/ tests/cache/ docs/ ← cache 专属资产 -└── deps/ipass/ (submodule → http://192.168.1.18:13300/ipass/ipass) - ├── rust/crates/ipass-core ← 内核(主项目维护) - ├── rust/gateway ← 唯一 cdylib(主项目) - ├── rust/vendor/ngx-rust ← vendored 绑定(主项目 pin) - └── rust/crates/plugin-domain|llm|apix ← 其他子系统(主项目) -``` - -本仓 `rust/Cargo.toml` 的 workspace 仅含 `crates/plugin-cache`,其依赖通过 `../deps/ipass/rust/...` 解析到 submodule。 - -## 依赖方向(单向) -``` -plugin-cache(本仓) - │ 依赖 - ▼ - ipass-core(submodule)──▶ vendor/ngx-rust(submodule)──▶ nginx C 进程 - ▲ - gateway(submodule,唯一 cdylib,聚合 plugin 的 ngx_module_t) -``` -只有 `gateway` 是 cdylib,其余全是 rlib(跨 `.so` 传 Rust 类型会双重 free)。 - -## 本仓库负责(cache) -### `plugin-cache`(rust/crates/plugin-cache,v0.1.0)★ 本仓唯一源码 -统一制品缓存插件,本仓库的核心交付: -- 8 路由制品代理:go / cargo / cargo-dl / pypi / pypi-files / npm / maven / docker v2 -- 命中计量(`stats.rs`)、上游动态注入(`upstreams.rs` + `cx:` 共享内存写穿) -- 管理 API(`api.rs` / `handlers.rs`):`GET /api/admin/cache` 容量、`POST /api/admin/cache/purge` 整区清理、`POST /api/admin/cache/invalidate` 按制品精准失效 -- 容量管理(`zones.rs`:直读 nginx `file_cache` 共享内存记账,双轴磁盘 + keys_zone 索引内存) -- 配套前端:`www/cache.html` + `www/assets/cache.js`(容量面板 + 按制品失效工具条) -- 测试:`tests/cache/test-cache-capacity.sh`(48/48)、`test-real-registries.sh`、`verify-cache-eviction.sh` -- 文档:`docs/cache-usage.md` - -> 改 cache 的路由行为、容量、purge / invalidate,只动本仓的 `plugin-cache` 与 `www/assets/cache.js`。 - -## 主项目维护(ipass/ipass,经 submodule 引入) -### `ipass-core`(deps/ipass/rust/crates/ipass-core,v2.0.0)— 内核 -共享内存原语(`cx:` / `ust:` / `ums:` / `ud:` 键空间)、账号 / 会话 / 认证(`auth::downstream_key`,`sk_` 三种携带位统一)、存储、通用 HTTP/api 框架、`config` / `state` / `usage` 记账原语。所有 plugin 依赖它,**方向只能是 plugin → core**。共享内存 schema 变更会影响全部 plugin,改前务必评估。 - -### `gateway`(deps/ipass/rust/gateway)— 唯一 cdylib -nginx 模块入口;聚合所有 plugin 的 `ngx_module_t`;FFI 边界(`panic="abort"`,跨 `.so` 不传 Rust 类型);模块加载顺序。**注意**:主项目 `gateway` 当前只装配 domain/llm/apix(不含 cache),要把 cache 编进可加载模块,需在主项目把 `plugin-cache` 加进 `members` 与 `gateway` 依赖(见 AGENTS.md「构建」)。 - -### `plugin-domain` / `plugin-llm` / `plugin-apix`(deps/ipass/rust/crates/*)— 其他子系统 -- `plugin-domain`:动态域名(子域名映射 / 申请审批 / 转发决策) -- `plugin-llm`:LLM 路由 / 上游管理 / 配额计费 / 对话审计 / 用量趋势 -- `plugin-apix`:API 代理(外部供应商资产挂网关) -由对应子系统团队在 `ipass/ipass` 维护;本仓不持有其源码,也不在其职责内。 - -### `vendor/ngx-rust`(deps/ipass/rust/vendor/ngx-rust)— 上游 vendored -`ngx` + `nginx-sys`(Rust 的 nginx C 绑定 fork)。主项目 pin 版本、vendored 以离线编译;上游是 ngx-rust 项目,iPass 维护其 vendoring 与 `panic="abort"` 配置。升级需重 pin + 全量重编译。 - -### nginx / 构建链(build/)— 外部依赖 -`build/nginx-1.30.4`、OpenSSL、PCRE2 源码与构建脚本;生产带 SSL 的完整 nginx 由 iPass 运维维护。本仓 `build/` 不入库。 - -## 责任边界速查 -| 组件 | 物理位置 | 归属 | 改前注意 | -|------|----------|------|----------| -| `plugin-cache` | 本仓 `rust/crates/plugin-cache` | 本仓库(cache) | 容量 / purge / invalidate 逻辑在此 | -| `ipass-core` | submodule `deps/ipass/...` | 主项目 `ipass/ipass` | 共享内存 schema 变更影响所有 plugin | -| `gateway` | submodule `deps/ipass/...` | 主项目 | 模块加载 / FFI 边界;当前不含 cache | -| `plugin-domain` / `plugin-llm` / `plugin-apix` | submodule `deps/ipass/...` | 主项目各子系统 | 不在本仓库职责内 | -| `vendor/ngx-rust` | submodule `deps/ipass/...` | 上游(vendored, 主项目 pin) | 升级需重 pin + 重编译 | -| nginx / 构建链 | 外部 | 外部 | 生产 SSL conf 在主项目运维 | - -## 如何更新内核 / 框架版本 -本仓记录的 submodule 提交钉在 `.gitmodules` / gitlink。要跟进主项目的新内核: -```bash -cd deps/ipass && git fetch && git checkout <新commit-or-main> && cd - -git add deps/ipass # 更新 gitlink -git commit -m "bump ipass-core via submodule" -``` -**不要在 `deps/ipass/` 里直接改代码**——那是主项目的源码,改了也不会被本仓提交,且会与上游冲突。 diff --git a/rust/Cargo.toml b/rust/Cargo.toml deleted file mode 100644 index 643a697..0000000 --- a/rust/Cargo.toml +++ /dev/null @@ -1,57 +0,0 @@ -# iPass workspace:内核(crates/ipass-core)+ 唯一 cdylib(gateway)。 -# 插件(plugin-domain / plugin-llm / plugin-apix)按 docs/plugin/PLUGINIZATION_PLAN.md 逐步迁入。 -# -# ⚠️ [profile.release] 只能放 workspace 根:member 里写会被 cargo 静默忽略, -# panic="abort" 丢了就意味着 panic 可能跨 FFI 边界展开进 nginx。 -[workspace] -resolver = "2" -members = ["crates/plugin-cache"] -# 独立 workspace:主项目 ipass/ipass 经 submodule 引入到仓库根的 deps/ipass, -# 需显式排除(路径相对本 Cargo.toml 所在目录 rust/,故是 ../deps/ipass), -# 以免与主项目自身的 workspace 冲突;target 也排除。 -exclude = ["../deps/ipass", "target"] - -[workspace.package] -edition = "2021" -publish = false -# vendored nginx-sys 的 build 脚本要读 CARGO_PKG_RUST_VERSION,而 cargo 只在 -# 声明了 rust-version 时才注入该环境变量 —— 缺了会在构建期直接 panic。 -rust-version = "1.81.0" - -[workspace.dependencies] -# ⚠️ 依赖必须用 vendored 源码,不能走 crates.io,也不能走 git: -# -# 1) `ngx = "0.5"`(crates.io 0.5.1)只发布了配置阶段接口(HttpModule), -# 请求阶段 API(add_phase_handler / HttpPhase / HttpRequestHandler)尚未发版, -# 实测直接编译失败:unresolved imports `ngx::http::HttpPhase` -# -# 2) git 依赖会永久挂起:ngx-rust 挂了一个指向完整 nginx 仓库的 submodule -# [submodule "nginx-src/nginx"] url = https://github.com/nginx/nginx.git -# cargo 解析 git 依赖时会 update_submodules,去克隆几十 MB 的 nginx 仓库, -# 国内网络下卡死(实测 cargo 5 分钟 0% CPU,调用栈停在 -# GitCheckout::update_submodules -> fetch -> wait4)。 -# -# 因此 vendor 到 vendor/ngx-rust/,用 path 依赖:离线可编译、无子模块、版本锁定。 -# 本仓只含 cache 插件,ipass-core / gateway / ngx-rust 全部从主项目 ipass/ipass -# (http://192.168.1.18:13300/ipass/ipass)经 submodule deps/ipass 引入。 -ngx = { path = "../deps/ipass/rust/vendor/ngx-rust" } -nginx-sys = { path = "../deps/ipass/rust/vendor/ngx-rust/nginx-sys" } - -# 业务层依赖:全部是纯 Rust 实现,不引入任何系统库或常驻依赖 -serde = { version = "1", features = ["derive"] } -serde_json = "1" # 序列化为紧凑 JSON;空 Vec/Vec 自动产出 [] / {} -sha2 = "0.10" # 迭代加盐 SHA-256;hash_password 算法已用独立 Python 实现逐位核对过 -getrandom = "0.2" # 不可退化成可预测伪随机(API Key / salt 由它生成) -libc = "0.2" # 仅用于 localtime_r(取本地时区) - -# 内核 crate:从主项目 ipass/ipass 经 submodule deps/ipass 引入;方向只能是 plugin → core -ipass-core = { path = "../deps/ipass/rust/crates/ipass-core" } -plugin-cache = { path = "crates/plugin-cache" } - -[profile.release] -opt-level = 3 -lto = true -codegen-units = 1 -# 模块被加载进 nginx 这个 C 进程,panic 绝不能跨 FFI 边界展开 -panic = "abort" -strip = true diff --git a/rust/crates/plugin-cache/Cargo.toml b/rust/crates/plugin-cache/Cargo.toml deleted file mode 100644 index 080a7f3..0000000 --- a/rust/crates/plugin-cache/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "plugin-cache" -version = "0.1.0" -edition.workspace = true -publish = false -description = "iPass 插件:统一制品缓存(go/rust/python/npm/java/docker)的命中计量与管理 API" - -[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 diff --git a/rust/crates/plugin-cache/src/api.rs b/src/api.rs similarity index 100% rename from rust/crates/plugin-cache/src/api.rs rename to src/api.rs diff --git a/rust/crates/plugin-cache/src/cache.rs b/src/cache.rs similarity index 100% rename from rust/crates/plugin-cache/src/cache.rs rename to src/cache.rs diff --git a/rust/crates/plugin-cache/src/config.rs b/src/config.rs similarity index 100% rename from rust/crates/plugin-cache/src/config.rs rename to src/config.rs diff --git a/rust/crates/plugin-cache/src/handlers.rs b/src/handlers.rs similarity index 89% rename from rust/crates/plugin-cache/src/handlers.rs rename to src/handlers.rs index 8be51f9..aa2e3dc 100644 --- a/rust/crates/plugin-cache/src/handlers.rs +++ b/src/handlers.rs @@ -30,8 +30,7 @@ use ngx::ffi::{ }; use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request}; -use ipass_core::loc::Switch; -use ipass_core::{auth, http, loc, util}; +use ipass_core::{auth, http, plugin_registry, util}; use crate::config; use crate::stats; @@ -99,7 +98,8 @@ pub fn read_cache_status(r: *mut ngx_http_request_t) -> String { // access:统一 Key 鉴权 + 上游就绪检查 // =========================================================================== -/// 制品缓存 access handler。location 开关:`ipass_cache on`(`Switch::Cache`)。 +/// 制品缓存 access handler。受管制 URI 由路由表(8 前缀)圈定; +/// R19 禁用 → fail-closed 404(数据面是鉴权后的磁盘读,放行=无鉴权读缓存盘)。 pub struct CacheAccessHandler; impl HttpRequestHandler for CacheAccessHandler { @@ -108,16 +108,18 @@ impl HttpRequestHandler for CacheAccessHandler { 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::Cache) { - return Status::NGX_DECLINED; - } - // 非受管制路径(favicon、探针等)直接放行,交给 nginx 自己的 location 处理 let uri = http::uri(r); let Some(route) = config::route_of_uri(&uri) else { return Status::NGX_DECLINED; }; + // R19 总闸。location 级开关(`ipass_cache on` → `loc::Switch::Cache`) + // 待 gateway 接入轮随 core 补变体后一并加回,路由前缀判定保留作第二道闸。 + if !plugin_registry::plugin_enabled("cache") { + return HTTPStatus::NOT_FOUND.into(); + } + // 上游未配置:**必须在这里拦**。否则变量式 proxy_pass 拿到空 // `$cache_target`,nginx 会报 500 `no host in upstream`, // 排障时会误以为是缓存本身坏了。 @@ -165,7 +167,7 @@ impl HttpRequestHandler for CacheAccessHandler { // log:按生态记命中 // =========================================================================== -/// 缓存命中计量(log 阶段)。location 开关同样看 `ipass_cache on`。 +/// 缓存命中计量(log 阶段)。同样按路由表圈定(与 access 一致);禁用时不记账。 pub struct CacheLogHandler; impl HttpRequestHandler for CacheLogHandler { @@ -174,7 +176,10 @@ impl HttpRequestHandler for CacheLogHandler { 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::Cache) { + // 只计缓存路由的请求(非缓存 URI 不进命中率分母);R19 禁用时跳过。 + if config::route_of_uri(&http::uri(r)).is_none() + || !plugin_registry::plugin_enabled("cache") + { return Status::NGX_DECLINED; } diff --git a/rust/crates/plugin-cache/src/lib.rs b/src/lib.rs similarity index 97% rename from rust/crates/plugin-cache/src/lib.rs rename to src/lib.rs index 8a7b1b3..bf228e5 100644 --- a/rust/crates/plugin-cache/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -//! plugin-cache —— 统一制品缓存插件(go / rust / python / npm / java / docker)。 +//! ipass-plugin-cache —— 统一制品缓存插件(go / rust / python / npm / java / docker)。 //! //! ## 它做什么,不做什么 //! diff --git a/rust/crates/plugin-cache/src/models.rs b/src/models.rs similarity index 100% rename from rust/crates/plugin-cache/src/models.rs rename to src/models.rs diff --git a/rust/crates/plugin-cache/src/stats.rs b/src/stats.rs similarity index 100% rename from rust/crates/plugin-cache/src/stats.rs rename to src/stats.rs diff --git a/rust/crates/plugin-cache/src/store.rs b/src/store.rs similarity index 100% rename from rust/crates/plugin-cache/src/store.rs rename to src/store.rs diff --git a/rust/crates/plugin-cache/src/upstreams.rs b/src/upstreams.rs similarity index 100% rename from rust/crates/plugin-cache/src/upstreams.rs rename to src/upstreams.rs diff --git a/rust/crates/plugin-cache/src/zones.rs b/src/zones.rs similarity index 100% rename from rust/crates/plugin-cache/src/zones.rs rename to src/zones.rs diff --git a/tests/cache/.run-evict/cache/maven/1/fb/052807f7dcf903b482f647fb0035afb1 b/tests/cache/.run-evict/cache/maven/1/fb/052807f7dcf903b482f647fb0035afb1 deleted file mode 100644 index ce4976403ad441c2be67479d9b2c4a81045fe03e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1612 zcmeHG(MrQG6s>|j1p4UvWshTR({3vo7=m-Gu*nAPi;r2kwAC&xZC31yzvGkWxA_5T z+6{Ez7f3IGljP)_aBptTw0(ShzCRqMNAPus;`OcNUoN~v)1FV3r{_JJI-}mv>25(5 zvwH?xUZG%C3)UlI&eNpA>rE}OoHS*d&w{?yCteV&E!(8vPztMsPJApXEEwGI5?hj* zF05-AXTlnqwi=F3Zn;DT{!R>(4t&fNI4;mDHXgC@CCu*volG+!QAlHnB9bwK=GLFx zpw5*A&+{}1xlELM7D|*xDGTIVoy-CrG1$MbQt>cGqj4;EWipy? diff --git a/tests/cache/.run-evict/cache/npm/0/6b/7c08263957217762708264c0587196b0 b/tests/cache/.run-evict/cache/npm/0/6b/7c08263957217762708264c0587196b0 deleted file mode 100644 index 838dc652a02c984088f4a3508cff52660397b9fc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 205386 zcmeI*&2AD=7zSW8F)<|EfUA=(n*swxQYUFltOQ~;Z2}v24rBtD@)MYvazou2y(F*0 zg*yCbrMhzK(->Q&kQB<9_x&E2^Qf@>`10-Z``wp&pT6%t-hKSEx%|oP*ONlw=E19n zj}Pim<0Og>_P+mr|3~q>^)?RE`6RC9e^vYAVYT+Wzsl0(>Gtkww|a-w!(yk`yR6nK zQK&~zxHvBryXoRXx`@MzWSMR*j4I7=xynYfY4x~L%m36%#g|Ez#-V#XJ<6{ay6HUs zRBwjpS^TsSH=@vf(<>FvX45R4X64uEbeN6e{9D!!)7}5~R`dKulKK2%}e*3dQ zmS*K;wn&pnso3fz!#MnWbo1*agHc*u-|Av^6^HqCKfmHpm?SslWSE{FH`h0wU+t`O z5$8W$_{$IN!u%0%C%6-~&qcopeiQsA{5m9hI(RyGI(Rz#9+RyJ)&y&UHNl#2Z+>85 zv@lv2EsPdM3*(>DWk&}`2S*1-2S*1-2S*1M31q1>cwWE$K{9qHNXC+}WGop=#*(pQ zEEx-hlJV|k+3JCMpdP3P>VbNo9;gTEfqI}Gs0Zr7-CI|6Bppdd(vfr|9Z5&hk#r;- zNk`I=bR->V?;J;pqN1oMDvFAtqNpe;ii)D5s3yDr9FR+e4u$hO=JZ$D+GY^}2*v!Lb9?skB6n)Od;*Gc7W8vj= z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl z0fsIVGp$l$?@Na!O9gDLEyl w0fsIVGp$^q=JP2Li*V!;Vj1HUUX?huTJ8|g6akv<@ zn&W)^K3^x{Wwyz02jk8lTyCrRs)&v|-TLUYny<1dPr~@7II82qI4|q2Hwf|b4X(pK|yRaALVwO{AOtePkFE4zLA^*r5{b&{+suNTv-TGaVh(<-mpn`)hB%T{xk zX0s&x+}=7ao6ht0F6(-AorLmcQU@M|W%i++&GM7u!7h0nc6xr1)UykJo3+v3zX7XZ zHB`#pCAFXy)Ph?0^G}HkWFP|>$Us68l8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*( z2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUF zBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Ex zl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e& zNJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8 zAqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dY zgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo z5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjT zNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TX zBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{l zkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!H zLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*( z2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUF zBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Ex zl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e& zNJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8 zAqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dY zgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo z5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjT zNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TX zBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{l Kkc9t~gg*cQ1pr_G diff --git a/tests/cache/.run-evict/cache/npm/3/d8/819209f49ca3661d21dbcc7cff467d83 b/tests/cache/.run-evict/cache/npm/3/d8/819209f49ca3661d21dbcc7cff467d83 deleted file mode 100644 index 073d19a28a9e2774dcead586e8ded010c4c5f012..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 205387 zcmeI!(Q4CB7y#fY2omT!9CqQwSevw+bq0puEE`nWptV?ZqHC-;^ZmV4%oksK~uZlDbuNQ}PTo@K*-F12)d6_;x zN;@yY*}JR}oh}zuv8bAFi^Zgxru8e^efsr0+mv;ZyezL~F6UWc8YU!?Wy!rx|X^!IPT zYFG`GvU5o-s0Fp47XJKGA_E!7Kn609kc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjT zNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TX zBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{l zkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!H zLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*( z2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUF zBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Ex zl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e& zNJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8 zAqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dY zgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo z5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjT zNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TX zBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{l zkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!H zLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*( z2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUF zBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Ex zl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e& zNJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8 zAqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dY Lgd`;4KPBN0k3Z%8 diff --git a/tests/cache/.run-evict/cache/npm/6/20/133297d4a6a307d27f01825f9fc2e206 b/tests/cache/.run-evict/cache/npm/6/20/133297d4a6a307d27f01825f9fc2e206 deleted file mode 100644 index 07b34976ce9e292c99e5fd9d4ad623f9c610526c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 205387 zcmeI!(Q4CB7y#fZ3?$HZIP7w)P1B({0 ze;O{{WbNo|S=L2acU~9ew4SBSE8Bhg^*q~DO_IE-ZswD`o;UfIle(xo>v~n>i*|IL z<$Us68l8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*( z2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUF zBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Ex zl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e& zNJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8 zAqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dY zgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo z5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjT zNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TX zBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{l zkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!H zLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*( z2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUF zBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Ex zl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e& zNJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8 zAqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dY zgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo z5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjT zNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TX zBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{l Kkc9t~gg*eg{u)&P diff --git a/tests/cache/.run-evict/cache/npm/8/70/53b42c650712625207fc721e28295708 b/tests/cache/.run-evict/cache/npm/8/70/53b42c650712625207fc721e28295708 deleted file mode 100644 index 9413281a32e46e14bec6f8a019c081b45506721e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 205387 zcmeI!(Q4CB7y#fZ2vX=f9CkU@HqB<$z!05fgDM-eH(q#=mP1=v)6!;QA8IK03ci8w zqo(UbhdzMdcL+I2PW~UxIr%^GptfsYzkPaldwHk(e%l7uA8*D#e|i44R@>a`-+#E5 zCPz<_Wbe-V|NBk7-+PmVVmZ&+)u}z2P1>FG*=SS7_3>`KPJ6@s_I~|rIJ{_gT1iNg zB%Jpf^+8;{kE<-a$k*{^Fllwe#ipDtiuPfvQypoe{xUCP76w|(1 zH|o7%KFPw*?XBYS@iaEKSyzk8EG(}^Rp3FG=O3E+Bpx4jx5=xple6=znqBzYtd0Ku z4Ok7Up;C4(sRgy57SzI@e@bK^0~yFb1`?8xgd`*(2}wvo5|WUFBqSjTNk~Exl8}TX zBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{l zkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!H zLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*( z2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUF zBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Ex zl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e& zNJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8 zAqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dY zgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo z5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjT zNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TX zBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{l zkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!H zLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*( z2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUF zBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Ex zl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e& zNJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8 zAqh!HLK2dYgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dY zgd`*(2}wvo5|WUFBqSjTNk~Exl8}TXBq0e&NJ0{lkc1>8Aqh!HLK2dYgd`*(2}wvo N5|WUFB>bl&`~fCa%M<_r diff --git a/tests/cache/.run-evict/conf/cache-common.conf b/tests/cache/.run-evict/conf/cache-common.conf deleted file mode 100644 index 3852e97..0000000 --- a/tests/cache/.run-evict/conf/cache-common.conf +++ /dev/null @@ -1,131 +0,0 @@ -# ============================================================================ -# cache-common.conf —— 各生态 cache location 共用的缓存/代理指令 -# -# 由 conf/cache-routes.conf 在每个 location 内 `include`。 -# **每个 location 自己指定** `proxy_cache `(各生态分库),本文件只放公共项。 -# -# --------------------------------------------------------------------------- -# 与「静态上游版」相比的三处关键变化(配合 plugin-cache 的变量层) -# --------------------------------------------------------------------------- -# -# 1. `proxy_pass` 由字面量改为变量 `$cache_target`。上游地址与凭据因此来自 -# 共享内存(`cx:`,由管理台写),**改上游不用改 conf、不用 reload**。 -# 代价:变量式 proxy_pass 不推导 Host、不追加 query —— 两者都由模块算好, -# 所以这里必须显式 `proxy_set_header Host $cache_host`。 -# -# 2. `proxy_cache_key` 不再用 `$scheme$proxy_host$request_uri`(变量式下 -# `$proxy_host` 不可靠),改用模块给的 `$cache_key`,并**并入方法 + -# Accept**(下面的注释详述为什么这是正确性问题,不是调优)。 -# -# 3. 出站鉴权头改成三段式(`proxy_pass_request_headers on` + 抹掉三个 -# 网关 Key 携带位 + 用 `$cache_auth` 下发)——见文件下半部分。 -# -# ⚠️ 本文件**不得**使用 rewrite 模块的 `set` / `if`;生态判定由 plugin-cache -# 直读 `r->uri` 首段完成,不需要 `set $cache_ecosystem`。 -# (`return` / `rewrite` 本身可用:本机构建与 ipass 生产都带 --with-pcre, -# rewrite 模块在编。它们只在 cache-routes.conf 里用。) -# ============================================================================ - -# --------------------------------------------------------------------------- -# 缓存键 -# --------------------------------------------------------------------------- -# -# `$cache_key` = `:<完整 URI + query>`,**不含任何下游凭据** —— 缓存因此是 -# 「全站共享」的:同一个 go module / npm 包被 N 个账号拉,只回源一次。 -# 这正是制品缓存的价值所在;鉴权在 access 层(谁能读),数据在共享层复用。 -# 代价:任一有效 Key 都能命中别人拉过的制品 —— 对公开 registry 无碍, -# 若某路由指向**私有**上游,请理解这一点再启用。 -# -# ★ query 必须进键(由模块的 `$cache_key` 负责,本行不要再自己拼 `$args`): -# npm 的 `?write=true`、docker 的 `?ns=`、go 的 `?go-get=1`、cargo 的 -# `?archive=tar.gz` 都靠 query 区分实体。变量式 `proxy_pass` 下 `$uri` -# **不含** query,只按 `$uri` 做键会把 `/x?a` 与 `/x?b` 当成同一个资源, -# 把错的制品发给客户端(且第二次完全不回源,很难察觉)。 -# -# ★ 为什么要并入 `$request_method` 与 `$http_accept`(这是正确性,不是调优): -# -# · `$request_method`:Docker 客户端对同一 URL 先 `HEAD` 看清单存不存在、 -# 再 `GET` 取清单(registry 协议如此)。若两者共用一个键,一次 HEAD 的 -# **空体**响应会被缓存下来并回给随后的 GET,客户端拿到 0 字节清单直接失败。 -# -# · `$http_accept`:nginx 的 proxy_cache **不实现 Vary**(只能靠 -# proxy_ignore_headers 把 Vary 忽略掉,无法参与分档)。而上游同一 URL -# 会因为 Accept 返回**不同实体**: -# - npm:`application/vnd.npm.install-v1+json` → 精简元数据, -# 缺省 → 完整元数据; -# - PyPI simple:`application/vnd.pypi.simple.v1+json` → JSON, -# `text/html` → HTML; -# - Docker:清单 v2 / OCI / v1 的 mediaType 由 Accept 偏好决定。 -# 不并入 Accept 就会出现「发给 A 的实体被回给 B」的串档。代价是每个 -# Accept 变体一个桶(现代客户端取值收敛,实际只多一个桶)。 -# -# 注:刻意**不**再带 `$scheme`/`$proxy_host`:同一份制品无论客户端走 http -# 还是 https、走哪个域名进来,上游都是同一个,共享一份缓存更省盘也更省带宽。 -proxy_cache_key $cache_key$request_method$http_accept; - -# 只缓存完整 GET/HEAD(200/301/308);404 短缓存;206(range)/401 等不缓存,避免错片 -proxy_cache_methods GET HEAD; -proxy_cache_valid 200 301 308 1d; -proxy_cache_valid 404 1m; - -# 上游抖动时用陈旧副本兜底;并发同键只回源一次(防击穿) -proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; -proxy_cache_lock on; -proxy_cache_lock_age 10s; -proxy_cache_lock_timeout 30s; - -# 带 If-None-Match / If-Modified-Since 回源校验,省带宽 -proxy_cache_revalidate on; - -# 加速缓存:不被上游 no-cache/Set-Cookie/Vary 拦下(镜像型缓存的标准取舍) -# ⚠️ Vary 被忽略是**必须**的——见上面缓存键的说明,我们已用 Accept 显式分档; -# 留着 Vary 反而会让 nginx 拒绝缓存这些响应。 -proxy_ignore_headers Cache-Control Expires Set-Cookie Vary; - -proxy_http_version 1.1; - -# --------------------------------------------------------------------------- -# 出站请求头(镜像型:默认透传,但抹掉「本网关自己的 Key」) -# --------------------------------------------------------------------------- -# -# 与 LLM/API 代理的 allowlist 策略**刻意不同**:那些是无状态 API,客户端 -# 头没有语义;而镜像必须原样带上客户端的 `Accept` / `Range` / -# `If-None-Match` / `User-Agent`,否则 docker 的 mediaType 协商、range 取 -# 大 blob、条件请求全部失效。所以这里保持 `on`(nginx 默认),只在三个 -# 「网关 Key 的携带位」上显式抹空。 -# -# 为什么必须抹:`sk_` 是客户端访问**本网关**的身份(auth::downstream_key 认 -# Authorization / x-api-key / api-key 三处)。原样透传给上游 = 把网关钥匙 -# 递给上游厂商,对方可拿它反调本网关的其它路由刷额度。ipass 的 LLM 路径 -# 记过同一个坑(宽松厂商把这缺陷掩盖成 200,换严格厂商才暴露成 401)。 -proxy_pass_request_headers on; -proxy_set_header x-api-key ""; -proxy_set_header api-key ""; - -# 变量形式 proxy_pass 不会推导 Host,必须显式设(上游多为 Cloudflare 前端, -# Host 不符会被直接拒) -proxy_set_header Host $cache_host; - -# Authorization 三段式(由模块里的 `$cache_auth` 实现,语义见其文档): -# 配了上游凭据 → 下发配置值(管理员写全 `Bearer xxx` / `Basic yyy`) -# 没配 → 透传客户端值(Docker Hub 的短期 Bearer token 走这条) -# 客户端那把恰好是下行 sk_ → 丢弃 -proxy_set_header Authorization $cache_auth; - -proxy_set_header X-Real-IP $remote_addr; -proxy_set_header X-Forwarded-For $remote_addr; -proxy_set_header X-Forwarded-Proto $scheme; - -# registry 大 blob / 慢索引:放宽超时 -proxy_read_timeout 300s; -proxy_send_timeout 300s; - -# 变量式/直连上游为 HTTPS 时开 SNI;证书校验此阶段关闭(镜像多为公开源, -# 且目标主机来自管理台配置而非请求。要严格校验需另配 proxy_ssl_trusted_certificate) -proxy_ssl_server_name on; -proxy_ssl_protocols TLSv1.2 TLSv1.3; -proxy_ssl_verify off; - -# 观测:每次响应带回缓存命中状态(ipass plugin-cache 亦从同一变量记账) -add_header X-Cache-Status $upstream_cache_status always; -add_header X-Cache-Eco $cache_eco always; diff --git a/tests/cache/.run-evict/conf/cache-routes.conf b/tests/cache/.run-evict/conf/cache-routes.conf deleted file mode 100644 index 4c50106..0000000 --- a/tests/cache/.run-evict/conf/cache-routes.conf +++ /dev/null @@ -1,177 +0,0 @@ -# ============================================================================ -# cache-routes.conf —— 制品缓存网关的「server 内容」(在 server { } 里 include) -# -# 为什么单独成一个文件:这份路由要**两处复用**—— -# * 明文入口 conf/server.cache.conf(本机 e2e / 内网直连) -# * TLS 入口 conf/tls/*.conf(对外,Docker 镜像加速必须走 https) -# 路由、鉴权开关、探针、管理台只写一份,两个入口不会漂。 -# -# 路由约定:/<前缀>/ => <该 route 配置的上游>/ -# /go/ Go module proxy → 默认 proxy.golang.org -# /cargo/ crates.io 稀疏索引 → 默认 index.crates.io -# /cargo-dl/ .crate 包本体 → 默认 static.crates.io -# /pypi/ PyPI 简单索引/JSON → 默认 pypi.org -# /pypi-files/ wheel/sdist 包文件 → 默认 files.pythonhosted.org -# /npm/ npm registry → 默认 registry.npmjs.org -# /maven/ Maven Central → 默认 repo1.maven.org/maven2 -# /v2/ Docker Registry v2 → 默认 registry-1.docker.io -# -# ⚠️ 上游地址**不写在本文件里**:全部来自 plugin-cache 的上游表(管理台 -# 「制品缓存」页,落盘 data/cache-upstreams.json + 写穿共享内存)。 -# 本文件只出现变量名。改上游 = 改管理台,不需要动 conf、不需要 reload。 -# -# ⚠️ 每个带 `ipass_cache on` 的 location 都会在 access 阶段做闸门: -# 1) 该路由没配上游 → 503(不会让请求走到空 $cache_target 变成 500) -# 2) 统一 sk_ Key 鉴权(与 LLM / API 代理同一把)→ 401 -# 3) 每分钟/每日配额 → 429 -# 然后数据面才交给 nginx 原生 proxy_cache。 -# ============================================================================ - - # ---------------- 管理台(多页静态资源,挂在 /admin/ 下)---------------- - # 每页 head 里有 ,所以资源与 /api/ 都是绝对路径。 - # - # **不发版不重启也能修好页面**:所有 HTML / CSS / JS 都加 - # `Cache-Control: no-store`(expires -1 + add_header)。否则用户浏览器会 - # 一直用发版前的旧 JS —— 典型表现是「后端加了字段,页面上看不到」。 - # - # ⚠️ alias 刻意写**相对**路径 `www/`:nginx 把 root/alias 的相对路径解析到 - # **prefix** 而不是 conf/,所以生产(prefix=/usr/local/nginx)得到 - # /usr/local/nginx/www/,本地回归(prefix=tests/.../.run-prod)得到 - # 测试自己的 www/。写死绝对路径则本机必 404。 - location = / { - return 302 /admin; - } - location = /admin { - default_type text/html; - alias www/cache.html; - expires -1; - add_header Cache-Control "no-store" always; - } - # `/admin/`(末尾斜杠、后面无字符)不能直接 alias 到目录:nginx 会把 - # index 拼成 `cache.htmlindex.html` 而 500。内部重定向到具体文件最干净。 - location = /admin/ { - rewrite ^ /admin/cache.html last; - } - location /admin/ { - alias www/; - expires -1; - add_header Cache-Control "no-store" always; - } - - # ---------------- API:管理态(登录会话)+ 账号态(sk_)---------------- - # 由 plugin-cache 认领 /api/admin/cache* 与 /api/v1/cache*; - # 其余 /api/* 交给同一 gateway 里的其它插件(llm/apix/domain),互不干扰。 - location /api/ { - ipass_api on; - } - - # ---------------- 上游连通性探针(管理台「测试」按钮)---------------- - # /api/admin/cache/test 校验 route 后由模块内部重定向到这里。 - # 刻意**复用** $cache_target / $cache_host / $cache_auth —— 与真实转发 - # 走同一套「拼上游 URL + 换凭据」逻辑,所以「测试通过」才等价于 - # 「真实请求能到上游并带上凭据」;另写一套探针代码必然漂移。 - # - # 为什么这里不写 `ipass_cache on`:内部重定向会重跑 access 阶段,而管理台 - # 带的是**登录 Cookie、不是 sk_**,再鉴一次会把自己 401 掉。鉴权已在 - # /api/admin/cache/test 那一跳用 Admin 守卫做过,这里是 internal,外部进不来。 - # - # proxy_cache off:探针是「验连通」,不该用一次探测污染 1d 的制品缓存。 - location /_cache_test/ { - internal; - proxy_cache off; - proxy_pass $cache_target; - proxy_http_version 1.1; - # 探针只验「拼目标 + 换凭据 + 到达上游」,请求头与请求体都不需要转发: - # * 方法由模块钉成 GET(见 plugin-cache api.rs 的 h_admin_test); - # * body 必须 off —— 管理台是用 POST 触发的,不 off 的话那 2 字节 `{}` - # 会连 Content-Length 一起发出去,上游等一个 GET 的 body、 - # 或 keepalive 上残留半截请求体,表现为「测试时好时坏」。 - proxy_pass_request_headers off; - proxy_pass_request_body off; - proxy_set_header Host $cache_host; - proxy_set_header Authorization $cache_auth; - proxy_set_header User-Agent $http_user_agent; - proxy_ssl_server_name on; - proxy_connect_timeout 5s; - proxy_send_timeout 15s; - proxy_read_timeout 15s; - } - - # ---------------- Go module proxy ---------------- - location /go/ { - ipass_cache on; - proxy_cache go; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- crates.io 稀疏索引 ---------------- - location /cargo/ { - ipass_cache on; - proxy_cache cargo; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- .crate 包本体 ---------------- - # ⚠️ crates.io 的 config.json 里 `dl` 字段给的是**绝对 URL** - # (https://static.crates.io/crates/...),cargo 默认直连上游域名、绕过本网关, - # 所以这个 location 只是**落点就绪**。要真正命中需二选一: - # (a) nginx 开 http_sub_module,用 sub_filter 把索引/`config.json` 里的 - # 绝对 URL 改写成 https://<本网关>/cargo-dl;或 - # (b) 网络层把 static.crates.io 指到本网关(内网 DNS + 证书)。 - # 两者都归到 cargo 生态计数(plugin-cache 的 eco_of_route 已做映射)。 - location /cargo-dl/ { - ipass_cache on; - proxy_cache cargo; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- PyPI 简单索引 / JSON ---------------- - location /pypi/ { - ipass_cache on; - proxy_cache pypi; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- wheel/sdist 包文件 ---------------- - # ⚠️ 与 /cargo-dl/ 同理:PyPI simple 页里的 href 是绝对 URL - # (https://files.pythonhosted.org/...),pip 默认直连,需 sub_filter 重写 - # 或 DNS 指向才能命中本 location。归到 pypi 生态计数。 - location /pypi-files/ { - ipass_cache on; - proxy_cache pypi; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- npm registry ---------------- - location /npm/ { - ipass_cache on; - proxy_cache npm; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- Maven Central ---------------- - location /maven/ { - ipass_cache on; - proxy_cache maven; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- Docker Registry v2 ---------------- - # registry-mirrors 要求 https(见 conf/tls/),且**只适合公开镜像**: - # 缓存键不含用户身份,私有镜像会被串档(见 cache-common.conf 的说明)。 - # 客户端先向 auth.docker.io 换短期 Bearer token 再带 Authorization 来拉, - # 该 token 由 cache-common.conf 的 $cache_auth 透传给上游(但网关自己的 - # sk_ 会被剔除)。上游路径的 `/v2` 前缀由模块的 upstream_path_prefix 补回。 - location /v2/ { - ipass_cache on; - proxy_cache docker; - proxy_pass $cache_target; - include cache-common.conf; - } diff --git a/tests/cache/.run-evict/conf/mime.types b/tests/cache/.run-evict/conf/mime.types deleted file mode 100644 index 1c00d70..0000000 --- a/tests/cache/.run-evict/conf/mime.types +++ /dev/null @@ -1,99 +0,0 @@ - -types { - text/html html htm shtml; - text/css css; - text/xml xml; - image/gif gif; - image/jpeg jpeg jpg; - application/javascript js; - application/atom+xml atom; - application/rss+xml rss; - - text/mathml mml; - text/plain txt; - text/vnd.sun.j2me.app-descriptor jad; - text/vnd.wap.wml wml; - text/x-component htc; - - image/avif avif; - image/png png; - image/svg+xml svg svgz; - image/tiff tif tiff; - image/vnd.wap.wbmp wbmp; - image/webp webp; - image/x-icon ico; - image/x-jng jng; - image/x-ms-bmp bmp; - - font/woff woff; - font/woff2 woff2; - - application/java-archive jar war ear; - application/json json; - application/mac-binhex40 hqx; - application/msword doc; - application/pdf pdf; - application/postscript ps eps ai; - application/rtf rtf; - application/vnd.apple.mpegurl m3u8; - application/vnd.google-earth.kml+xml kml; - application/vnd.google-earth.kmz kmz; - application/vnd.ms-excel xls; - application/vnd.ms-fontobject eot; - application/vnd.ms-powerpoint ppt; - application/vnd.oasis.opendocument.graphics odg; - application/vnd.oasis.opendocument.presentation odp; - application/vnd.oasis.opendocument.spreadsheet ods; - application/vnd.oasis.opendocument.text odt; - application/vnd.openxmlformats-officedocument.presentationml.presentation - pptx; - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - xlsx; - application/vnd.openxmlformats-officedocument.wordprocessingml.document - docx; - application/vnd.wap.wmlc wmlc; - application/wasm wasm; - application/x-7z-compressed 7z; - application/x-cocoa cco; - application/x-java-archive-diff jardiff; - application/x-java-jnlp-file jnlp; - application/x-makeself run; - application/x-perl pl pm; - application/x-pilot prc pdb; - application/x-rar-compressed rar; - application/x-redhat-package-manager rpm; - application/x-sea sea; - application/x-shockwave-flash swf; - application/x-stuffit sit; - application/x-tcl tcl tk; - application/x-x509-ca-cert der pem crt; - application/x-xpinstall xpi; - application/xhtml+xml xhtml; - application/xspf+xml xspf; - application/zip zip; - - application/octet-stream bin exe dll; - application/octet-stream deb; - application/octet-stream dmg; - application/octet-stream iso img; - application/octet-stream msi msp msm; - - audio/midi mid midi kar; - audio/mpeg mp3; - audio/ogg ogg; - audio/x-m4a m4a; - audio/x-realaudio ra; - - video/3gpp 3gpp 3gp; - video/mp2t ts; - video/mp4 mp4; - video/mpeg mpeg mpg; - video/quicktime mov; - video/webm webm; - video/x-flv flv; - video/x-m4v m4v; - video/x-mng mng; - video/x-ms-asf asx asf; - video/x-ms-wmv wmv; - video/x-msvideo avi; -} diff --git a/tests/cache/.run-evict/conf/nginx.cache.conf b/tests/cache/.run-evict/conf/nginx.cache.conf deleted file mode 100644 index 3a2dca0..0000000 --- a/tests/cache/.run-evict/conf/nginx.cache.conf +++ /dev/null @@ -1,87 +0,0 @@ -# ============================================================================ -# nginx.cache.conf —— 统一制品缓存网关 · 顶层配置 -# -# vanilla nginx + ipass Rust 动态模块(plugin-cache) -# -# 本机回归:bash tests/cache/run.sh -# 生产部署:把本文件放到 nginx prefix 的 conf/ 下,同目录放 -# server.cache.conf / cache-routes.conf / cache-common.conf / -# mime.types,启动即可;要对外 https 再加 conf/tls/*.conf。 -# -# 数据面 = nginx 原生 proxy_cache(六生态各一个 zone,落本地盘); -# 管理面 = ipass plugin-cache(access 鉴权 + log 按生态记账 + 管理 API)。 -# -# ⚠️ 上游地址/凭据**不在 conf 里**:全在 plugin-cache 的上游表 -# (管理台「制品缓存」页 → data/cache-upstreams.json → 写穿共享内存)。 -# conf 只出现 `$cache_*` 变量名,所以改上游不需要动 conf、不需要 reload。 -# -# ⚠️ 因为 proxy_pass 是变量形式,`resolver` 是**必需**的:nginx 无法在配置 -# 解析期把变量里的主机名解析成 IP,只能运行期查 DNS。缺 resolver 的表现是 -# `/go/...` 一律 500(no resolver defined to resolve ...)。 -# -# 本构建(build/build-nginx-ssl.sh)对齐 ipass 生产的 Dockerfile 参数: -# --with-pcre --with-http_ssl_module --with-http_realip_module -# 即 rewrite 模块与 SSL 都在编,所以本文件与 server.cache.conf / -# cache-routes.conf 里可以用 `return` / `rewrite` / `ssl_certificate`。 -# ============================================================================ - -load_module /Users/rong/Desktop/cache/rust/target/debug/libipass_gateway.dylib; - -worker_processes 1; - error_log /Users/rong/Desktop/cache/tests/cache/.run-evict/logs/error.log info; - pid /Users/rong/Desktop/cache/tests/cache/.run-evict/logs/nginx.pid; - -# 初始管理员口令(不声明则会被 nginx 从环境中剥离) -env ADMIN_INIT_PASSWORD; - -events { - worker_connections 4096; -} - -http { - include mime.types; - default_type application/octet-stream; # 缺 Content-Type 时的兜底; - # API 响应由模块显式设 application/json - - sendfile on; - keepalive_timeout 65; - - # ========== 变量式上游的必需项 ========== - # proxy_pass $cache_target 里的主机名只能运行期解析(见文件头注释)。 - # 两个国内解析器,30s 缓存;ipv6=off 避免拿到不可达的 AAAA 卡住连接。 - resolver 223.5.5.5 119.29.29.29 valid=30s ipv6=off; - resolver_timeout 5s; - - # ========== 可选 TLS(HTTPS)========== - # conf/tls/ 下放任意 *.conf(完整的 443/18098 server 块)即启用对应域名的 - # HTTPS;目录为空或不存在时 include 空匹配,不影响启动。 - # 模板见 conf/tls/cache.conf.example,说明见 conf/tls/README.md - include /Users/rong/Desktop/cache/tests/cache/.run-evict/conf/tls/*.conf; - - # ========== ipass 内核:共享内存 + 数据目录 ========== - # 一张共享内存表承载:上游表(cx:)/ 命中计数(cache:)/ 管理会话 / 限流窗口。 - # 上游表条目数 = 路由数(个位数),10m 绰绰有余。 - ipass_state state 10m; - ipass_data_dir /Users/rong/Desktop/cache/tests/cache/.run-evict/data; - ipass_audit_dir /Users/rong/Desktop/cache/tests/cache/.run-evict/audit; - - # ========== 六类生态缓存区(本地盘热层)========== - # 各生态独立 zone,互不串档、独立上限;use_temp_path=off 省一次改名。 - # ⚠️ cargo / pypi 各有两个 route 共用同一个 zone(索引 + 包本体): - # 这是刻意的——同一门语言的流量记在一起才看得懂,而 zone 内靠 - # $cache_key 的 route 前缀天然分档,不会串。 - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-evict/cache/go levels=1:2 keys_zone=go:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-evict/cache/cargo levels=1:2 keys_zone=cargo:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-evict/cache/pypi levels=1:2 keys_zone=pypi:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-evict/cache/npm levels=1:2 keys_zone=npm:100m max_size=1m inactive=1h use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-evict/cache/maven levels=1:2 keys_zone=maven:100m max_size=1g inactive=10s use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-evict/cache/docker levels=1:2 keys_zone=docker:200m max_size=200g inactive=7d use_temp_path=off; - - # 命中率日志(排障用;真实指标由 plugin-cache 的共享内存计数器提供) - log_format cache '$remote_addr [$time_local] "$request" $status ' - '$body_bytes_sent cache=$upstream_cache_status eco=$cache_eco ' - 'uri=$uri rt=$request_time'; - access_log /Users/rong/Desktop/cache/tests/cache/.run-evict/logs/cache.log cache; - - include server.cache.conf; -} diff --git a/tests/cache/.run-evict/conf/server.cache.conf b/tests/cache/.run-evict/conf/server.cache.conf deleted file mode 100644 index 53cf2ec..0000000 --- a/tests/cache/.run-evict/conf/server.cache.conf +++ /dev/null @@ -1,30 +0,0 @@ -# ============================================================================ -# server.cache.conf —— 统一制品缓存 server(明文入口) -# -# 这是**内网 / 本机 e2e** 用的明文入口。对外的 https 入口在 conf/tls/*.conf -# (模板见 conf/tls/cache.conf.example)——两者 include 同一份 cache-routes.conf, -# 所以路由只此一份、不会漂。 -# -# 为什么要拆两个入口:Docker 的 `registry-mirrors` 只接受 https(明文地址会 -# 被 daemon 当成 insecure registry 拒绝),而本机自测/内网互调又不想折腾证书。 -# -# 为什么本 server 不写 listen ... ssl:证书与域名属于部署环境(见 conf/tls/), -# 写死在这里会让「同一份 conf 换域名」变成改代码。 -# ============================================================================ - -server { - listen 18086; - server_name _; - - # registry 大 blob 直通,不设体积上限(0 = 不限制) - client_max_body_size 0; - # 请求体都是小 JSON / 空体,调大缓冲区让它留在内存里,避免刷临时文件 - client_body_buffer_size 1m; - - # 管理台 `location = /` 会 302 到 /admin。不关掉的话 nginx 默认写 - # 绝对 URL + 实际 listen 端口,反代/端口映射后会把浏览器踢出链路。 - absolute_redirect off; - port_in_redirect off; - - include cache-routes.conf; -} diff --git a/tests/cache/.run-evict/data/api-proxies.json b/tests/cache/.run-evict/data/api-proxies.json deleted file mode 100644 index 59c3871..0000000 --- a/tests/cache/.run-evict/data/api-proxies.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "items": { - "search": { - "supplier": "vendor-a", - "asset_id": "searxng-search", - "base": "http://127.0.0.1:18999", - "key": "ak_test_supplier_key", - "name": "SearXNG 免费搜索", - "desc": "服务端聚合 Google / Brave / Bing", - "params": ["q"], - "enabled": true, - "created_at": 1750000000 - }, - "offline": { - "supplier": "vendor-a", - "asset_id": "disabled-asset", - "base": "http://127.0.0.1:18999", - "key": "ak_test_supplier_key", - "name": "已停用的代理", - "desc": "enabled=false,热路径必须查不到", - "params": [], - "enabled": false, - "created_at": 1750000000 - } - } -} diff --git a/tests/cache/.run-evict/data/cache-upstreams.json b/tests/cache/.run-evict/data/cache-upstreams.json deleted file mode 100644 index c1dd3f9..0000000 --- a/tests/cache/.run-evict/data/cache-upstreams.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "items": { - "npm": { "base": "http://127.0.0.1:18997", "key": "", - "mode": "proxy", "name": "测试上游 npm", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 }, - "maven": { "base": "http://127.0.0.1:18997", "key": "", - "mode": "proxy", "name": "测试上游 maven", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 } - } -} diff --git a/tests/cache/.run-evict/data/domains.json b/tests/cache/.run-evict/data/domains.json deleted file mode 100644 index fe51488..0000000 --- a/tests/cache/.run-evict/data/domains.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/tests/cache/.run-evict/data/llm-stats.json b/tests/cache/.run-evict/data/llm-stats.json deleted file mode 100644 index 7bc1b85..0000000 --- a/tests/cache/.run-evict/data/llm-stats.json +++ /dev/null @@ -1 +0,0 @@ -{"version":1,"saved_at":1789898099,"saved_at_text":"2026-09-20 17:54:59","keys":{}} \ No newline at end of file diff --git a/tests/cache/.run-evict/data/llm-upstreams.json b/tests/cache/.run-evict/data/llm-upstreams.json deleted file mode 100644 index 13aa3bd..0000000 --- a/tests/cache/.run-evict/data/llm-upstreams.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "openai": { - "base": "http://127.0.0.1:18999", - "models": ["gpt-4o", "gpt-4o-mini"], - "auth": "Bearer sk-UPSTREAM-REAL-SECRET", - "enabled": true, - "note": "本地靶机;auth 是占位值,不是真密钥", - "created_at": 1757500000 - }, - "other": { - "base": "http://127.0.0.1:18999/llm", - "models": ["claude-3-5-sonnet"], - "auth": "Bearer sk-OTHER-UPSTREAM", - "enabled": true, - "note": "不在 alice 白名单内;base 带路径,用于验证路径拼接与模型发现过滤", - "created_at": 1757500000 - }, - "downstream": { - "base": "http://127.0.0.1:18999", - "models": ["should-not-appear"], - "auth": "", - "enabled": false, - "note": "已停用,用于验证「停用即从共享内存摘除」→ 404,且其模型不应出现在模型发现里", - "created_at": 1757500000 - }, - "deepseeklike": { - "base": "http://127.0.0.1:18999/v1", - "models": ["ds-chat"], - "auth": "Bearer sk-DS-REAL", - "enabled": true, - "note": "base 自带 /v1(厂商文档的常见写法),用于验证版本段不重复拼接", - "created_at": 1757500000 - } -} diff --git a/tests/cache/.run-evict/data/users.json b/tests/cache/.run-evict/data/users.json deleted file mode 100644 index 1c50523..0000000 --- a/tests/cache/.run-evict/data/users.json +++ /dev/null @@ -1 +0,0 @@ -{"admin":{"username":"admin","display_name":"","role":"admin","salt":"5a1b2c3d4e5f60718293a4b5c6d7e8f9","pwd_hash":"062b45d8f3cbef3d30464859355401bb37193868dc42eb941de86855416ab5e8","api_key":"sk_admin_0000000000000000000000000000000000000000000000ab","allowed_models":[],"llm_rpm":60,"llm_daily":0,"temp_grant_until":0,"created_at":1757500000},"alice":{"username":"alice","display_name":"爱丽丝","role":"user","salt":"00112233445566778899aabbccddeeff","pwd_hash":"00","api_key":"sk_alice_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","allowed_models":["openai"],"llm_rpm":60,"llm_daily":0,"temp_grant_until":0,"created_at":1757500000},"bob":{"username":"bob","display_name":"","role":"user","salt":"ffeeddccbbaa99887766554433221100","pwd_hash":"00","api_key":"sk_bob_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","allowed_models":[],"llm_rpm":60,"llm_daily":0,"temp_grant_until":0,"created_at":1757500000},"carol":{"username":"carol","display_name":"","role":"user","salt":"112233445566778899aabbccddeeff00","pwd_hash":"00","api_key":"sk_carol_cccccccccccccccccccccccccccccccccccccccccccccc","allowed_models":[],"llm_rpm":2,"llm_daily":0,"temp_grant_until":0,"created_at":1757500000},"dave":{"username":"dave","display_name":"","role":"user","salt":"aabbccddeeff00112233445566778899","pwd_hash":"00","api_key":"sk_dave_dddddddddddddddddddddddddddddddddddddddddddddddd","allowed_models":[],"llm_rpm":0,"llm_daily":2,"temp_grant_until":0,"created_at":1757500000}} \ No newline at end of file diff --git a/tests/cache/.run-evict/logs/cache.log b/tests/cache/.run-evict/logs/cache.log deleted file mode 100644 index 9e5c256..0000000 --- a/tests/cache/.run-evict/logs/cache.log +++ /dev/null @@ -1,66 +0,0 @@ -127.0.0.1 [20/Sep/2026:17:51:22 +0800] "GET / HTTP/1.1" 302 145 cache=- eco=- uri=/ rt=0.000 -127.0.0.1 [20/Sep/2026:17:51:22 +0800] "GET /npm/big/1?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/1 rt=0.021 -127.0.0.1 [20/Sep/2026:17:51:22 +0800] "GET /npm/big/2?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/2 rt=0.019 -127.0.0.1 [20/Sep/2026:17:51:22 +0800] "GET /npm/big/3?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/3 rt=0.020 -127.0.0.1 [20/Sep/2026:17:51:22 +0800] "GET /npm/big/4?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/4 rt=0.013 -127.0.0.1 [20/Sep/2026:17:51:24 +0800] "GET /npm/big/5?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/5 rt=1.495 -127.0.0.1 [20/Sep/2026:17:51:24 +0800] "GET /npm/big/6?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/6 rt=1.443 -127.0.0.1 [20/Sep/2026:17:51:24 +0800] "GET /npm/big/7?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/7 rt=1.438 -127.0.0.1 [20/Sep/2026:17:51:24 +0800] "GET /npm/big/8?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/8 rt=1.436 -127.0.0.1 [20/Sep/2026:17:51:24 +0800] "GET /npm/big/9?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/9 rt=1.434 -127.0.0.1 [20/Sep/2026:17:51:25 +0800] "GET /npm/big/10?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/10 rt=1.927 -127.0.0.1 [20/Sep/2026:17:51:25 +0800] "GET /npm/big/11?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/11 rt=1.934 -127.0.0.1 [20/Sep/2026:17:51:25 +0800] "GET /npm/big/12?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/12 rt=1.930 -127.0.0.1 [20/Sep/2026:17:51:25 +0800] "GET /npm/big/13?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/13 rt=1.925 -127.0.0.1 [20/Sep/2026:17:51:25 +0800] "GET /npm/big/14?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/14 rt=1.921 -127.0.0.1 [20/Sep/2026:17:51:25 +0800] "GET /npm/big/15?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/15 rt=1.928 -127.0.0.1 [20/Sep/2026:17:51:27 +0800] "GET /npm/big/1?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/1 rt=0.041 -127.0.0.1 [20/Sep/2026:17:51:28 +0800] "GET /npm/big/15?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/15 rt=0.025 -127.0.0.1 [20/Sep/2026:17:51:28 +0800] "GET /npm/big/15?bytes=204800 HTTP/1.1" 200 47 cache=MISS eco=npm uri=/npm/big/15 rt=0.021 -127.0.0.1 [20/Sep/2026:17:51:28 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 47 cache=MISS eco=maven uri=/maven/keepalive rt=0.049 -127.0.0.1 [20/Sep/2026:17:51:28 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 47 cache=MISS eco=maven uri=/maven/keepalive rt=0.035 -127.0.0.1 [20/Sep/2026:17:51:44 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 47 cache=MISS eco=maven uri=/maven/keepalive rt=0.017 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET / HTTP/1.1" 302 145 cache=- eco=- uri=/ rt=0.000 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/probe?bytes=1024 HTTP/1.1" 200 1024 cache=MISS eco=npm uri=/npm/probe rt=0.017 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/big/1?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/1 rt=0.019 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/big/2?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/2 rt=0.019 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/big/3?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/3 rt=0.023 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/big/4?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/4 rt=0.023 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/big/5?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/5 rt=0.018 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/big/6?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/6 rt=0.018 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/big/7?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/7 rt=0.030 -127.0.0.1 [20/Sep/2026:17:52:38 +0800] "GET /npm/big/8?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/8 rt=0.018 -127.0.0.1 [20/Sep/2026:17:52:39 +0800] "GET /npm/big/9?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/9 rt=0.020 -127.0.0.1 [20/Sep/2026:17:52:39 +0800] "GET /npm/big/10?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/10 rt=0.020 -127.0.0.1 [20/Sep/2026:17:52:39 +0800] "GET /npm/big/11?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/11 rt=0.018 -127.0.0.1 [20/Sep/2026:17:52:39 +0800] "GET /npm/big/12?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/12 rt=0.018 -127.0.0.1 [20/Sep/2026:17:52:39 +0800] "GET /npm/big/13?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/13 rt=0.017 -127.0.0.1 [20/Sep/2026:17:52:39 +0800] "GET /npm/big/14?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/14 rt=0.018 -127.0.0.1 [20/Sep/2026:17:52:39 +0800] "GET /npm/big/15?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/15 rt=0.017 -127.0.0.1 [20/Sep/2026:17:52:48 +0800] "GET /npm/big/1?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/1 rt=0.013 -127.0.0.1 [20/Sep/2026:17:52:48 +0800] "GET /npm/big/15?bytes=204800 HTTP/1.1" 200 204800 cache=HIT eco=npm uri=/npm/big/15 rt=0.000 -127.0.0.1 [20/Sep/2026:17:52:49 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 1024 cache=MISS eco=maven uri=/maven/keepalive rt=0.027 -127.0.0.1 [20/Sep/2026:17:52:49 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 1024 cache=HIT eco=maven uri=/maven/keepalive rt=0.000 -127.0.0.1 [20/Sep/2026:17:53:07 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 1024 cache=MISS eco=maven uri=/maven/keepalive rt=0.021 -127.0.0.1 [20/Sep/2026:17:54:26 +0800] "GET / HTTP/1.1" 302 145 cache=- eco=- uri=/ rt=0.000 -127.0.0.1 [20/Sep/2026:17:54:26 +0800] "GET /npm/probe?bytes=1024 HTTP/1.1" 200 1024 cache=MISS eco=npm uri=/npm/probe rt=0.011 -127.0.0.1 [20/Sep/2026:17:54:26 +0800] "GET /npm/big/1?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/1 rt=0.011 -127.0.0.1 [20/Sep/2026:17:54:26 +0800] "GET /npm/big/2?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/2 rt=0.012 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/3?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/3 rt=0.013 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/4?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/4 rt=0.011 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/5?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/5 rt=0.013 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/6?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/6 rt=0.012 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/7?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/7 rt=0.026 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/8?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/8 rt=0.024 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/9?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/9 rt=0.049 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/10?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/10 rt=0.021 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/11?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/11 rt=0.017 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/12?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/12 rt=0.019 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/13?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/13 rt=0.017 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/14?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/14 rt=0.017 -127.0.0.1 [20/Sep/2026:17:54:27 +0800] "GET /npm/big/15?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/15 rt=0.017 -127.0.0.1 [20/Sep/2026:17:54:40 +0800] "GET /npm/big/1?bytes=204800 HTTP/1.1" 200 204800 cache=MISS eco=npm uri=/npm/big/1 rt=0.032 -127.0.0.1 [20/Sep/2026:17:54:41 +0800] "GET /npm/big/15?bytes=204800 HTTP/1.1" 200 204800 cache=HIT eco=npm uri=/npm/big/15 rt=0.000 -127.0.0.1 [20/Sep/2026:17:54:41 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 1024 cache=MISS eco=maven uri=/maven/keepalive rt=0.029 -127.0.0.1 [20/Sep/2026:17:54:41 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 1024 cache=HIT eco=maven uri=/maven/keepalive rt=0.000 -127.0.0.1 [20/Sep/2026:17:54:58 +0800] "GET /maven/keepalive?bytes=1024 HTTP/1.1" 200 1024 cache=MISS eco=maven uri=/maven/keepalive rt=0.012 diff --git a/tests/cache/.run-evict/logs/error.log b/tests/cache/.run-evict/logs/error.log deleted file mode 100644 index 64b6643..0000000 --- a/tests/cache/.run-evict/logs/error.log +++ /dev/null @@ -1,224 +0,0 @@ -nginx: the configuration file /Users/rong/Desktop/cache/tests/cache/.run-evict/conf/nginx.cache.conf syntax is ok -2026/09/20 17:51:22 [notice] 48753#0: [ipass] 共享内存已装载 0 条转发映射 -2026/09/20 17:51:22 [notice] 48753#0: [ipass] 已装载 0 个账号 Key、0 个 LLM 上游、0 个 API 代理、2 个缓存上游 -nginx: configuration file /Users/rong/Desktop/cache/tests/cache/.run-evict/conf/nginx.cache.conf test is successful -2026/09/20 17:51:22 [notice] 48755#0: [ipass] 共享内存已装载 0 条转发映射 -2026/09/20 17:51:22 [notice] 48755#0: [ipass] 已装载 0 个账号 Key、0 个 LLM 上游、0 个 API 代理、2 个缓存上游 -2026/09/20 17:51:22 [notice] 48755#0: using the "kqueue" event method -2026/09/20 17:51:22 [notice] 48755#0: nginx/1.30.4 -2026/09/20 17:51:22 [notice] 48755#0: built by clang 14.0.0 (clang-1400.0.29.202) -2026/09/20 17:51:22 [notice] 48755#0: OS: Darwin 21.6.0 -2026/09/20 17:51:22 [notice] 48755#0: hw.ncpu: 4 -2026/09/20 17:51:22 [notice] 48755#0: net.inet.tcp.sendspace: 131072 -2026/09/20 17:51:22 [notice] 48755#0: kern.ipc.somaxconn: 128 -2026/09/20 17:51:22 [notice] 48755#0: hw.cachelinesize: 64 -2026/09/20 17:51:22 [notice] 48755#0: getrlimit(RLIMIT_NOFILE): 1048575:9223372036854775807 -2026/09/20 17:51:22 [notice] 48756#0: start worker processes -2026/09/20 17:51:22 [notice] 48756#0: start worker process 48757 -2026/09/20 17:51:22 [notice] 48756#0: start cache manager process 48759 -2026/09/20 17:51:22 [notice] 48756#0: start cache loader process 48760 -2026/09/20 17:51:22 [warn] 48759#0: [ipass] 已创建初始管理员 admin,请首次登录后立即修改密码 -2026/09/20 17:51:22 [notice] 48756#0: signal 23 (SIGIO) received from 48759 -2026/09/20 17:51:22 [notice] 48756#0: signal 23 (SIGIO) received from 48757 -2026/09/20 17:51:22 [info] 48757#0: *1 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:51:22 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:22 [info] 48757#0: *2 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/1?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/1?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:22 [alert] 48757#0: *2 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/1?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/1?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:22 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:22 [info] 48757#0: *4 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/2?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/2?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:22 [alert] 48757#0: *4 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/2?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/2?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:22 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:22 [info] 48757#0: *6 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/3?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/3?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:22 [alert] 48757#0: *6 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/3?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/3?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:22 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:22 [info] 48757#0: *8 kevent() reported that client prematurely closed connection while sending request to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/4?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/4?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:22 [alert] 48757#0: *8 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/4?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/4?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:22 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:22 [info] 48757#0: *10 kevent() reported that client prematurely closed connection while sending request to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/5?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/5?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *12 kevent() reported that client prematurely closed connection while sending request to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/6?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/6?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *14 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/7?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/7?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *16 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/8?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/8?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *18 kevent() reported that client prematurely closed connection while sending request to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/9?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/9?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *20 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/10?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/10?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *22 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/11?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/11?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *24 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/12?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/12?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *26 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/13?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/13?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *28 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/14?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/14?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:23 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:23 [info] 48757#0: *30 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/15?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/15?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:24 [alert] 48757#0: *10 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/5?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/5?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:24 [alert] 48757#0: *12 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/6?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/6?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:24 [alert] 48757#0: *14 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/7?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/7?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:24 [alert] 48757#0: *16 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/8?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/8?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:24 [alert] 48757#0: *18 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/9?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/9?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:25 [alert] 48757#0: *20 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/10?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/10?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:25 [alert] 48757#0: *22 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/11?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/11?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:25 [alert] 48757#0: *24 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/12?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/12?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:25 [alert] 48757#0: *26 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/13?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/13?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:25 [alert] 48757#0: *28 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/14?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/14?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:25 [alert] 48757#0: *30 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/15?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/15?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:27 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:27 [info] 48757#0: *32 kevent() reported that client prematurely closed connection while sending request to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/1?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/1?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:27 [alert] 48757#0: *32 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/1?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/1?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:27 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:27 [info] 48757#0: *34 kevent() reported that client prematurely closed connection while sending request to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/15?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/15?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:28 [alert] 48757#0: *34 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/15?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/15?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:28 [warn] 48757#0: [cache] API Key 校验失败 route=npm client=127.0.0.1 -2026/09/20 17:51:28 [info] 48757#0: *36 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/15?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/15?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:28 [alert] 48757#0: *36 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /npm/big/15?bytes=204800 HTTP/1.1", upstream: "http://127.0.0.1:18997/big/15?bytes=204800", host: "127.0.0.1:18086" -2026/09/20 17:51:28 [warn] 48757#0: [cache] API Key 校验失败 route=maven client=127.0.0.1 -2026/09/20 17:51:28 [info] 48757#0: *38 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /maven/keepalive?bytes=1024 HTTP/1.1", upstream: "http://127.0.0.1:18997/keepalive?bytes=1024", host: "127.0.0.1:18086" -2026/09/20 17:51:28 [alert] 48757#0: *38 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /maven/keepalive?bytes=1024 HTTP/1.1", upstream: "http://127.0.0.1:18997/keepalive?bytes=1024", host: "127.0.0.1:18086" -2026/09/20 17:51:28 [warn] 48757#0: [cache] API Key 校验失败 route=maven client=127.0.0.1 -2026/09/20 17:51:28 [info] 48757#0: *40 kevent() reported that client prematurely closed connection while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /maven/keepalive?bytes=1024 HTTP/1.1", upstream: "http://127.0.0.1:18997/keepalive?bytes=1024", host: "127.0.0.1:18086" -2026/09/20 17:51:28 [alert] 48757#0: *40 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /maven/keepalive?bytes=1024 HTTP/1.1", upstream: "http://127.0.0.1:18997/keepalive?bytes=1024", host: "127.0.0.1:18086" -2026/09/20 17:51:44 [warn] 48757#0: [cache] API Key 校验失败 route=maven client=127.0.0.1 -2026/09/20 17:51:44 [info] 48757#0: *42 kevent() reported that client prematurely closed connection while sending request to upstream, client: 127.0.0.1, server: _, request: "GET /maven/keepalive?bytes=1024 HTTP/1.1", upstream: "http://127.0.0.1:18997/keepalive?bytes=1024", host: "127.0.0.1:18086" -2026/09/20 17:51:44 [alert] 48757#0: *42 header already sent while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /maven/keepalive?bytes=1024 HTTP/1.1", upstream: "http://127.0.0.1:18997/keepalive?bytes=1024", host: "127.0.0.1:18086" -2026/09/20 17:51:45 [notice] 48756#0: signal 15 (SIGTERM) received from 48595, exiting -2026/09/20 17:51:45 [notice] 48759#0: exiting -2026/09/20 17:51:45 [notice] 48757#0: exiting -2026/09/20 17:51:45 [info] 48757#0: [stats] 落盘 0 键(83 B,worker-exit)-> /Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json -2026/09/20 17:51:45 [notice] 48757#0: exit -2026/09/20 17:51:45 [notice] 48760#0: exiting -2026/09/20 17:51:45 [notice] 48756#0: signal 23 (SIGIO) received -2026/09/20 17:51:45 [notice] 48756#0: signal 20 (SIGCHLD) received from 48760 -2026/09/20 17:51:45 [notice] 48756#0: cache manager process 48759 exited with code 0 -2026/09/20 17:51:45 [notice] 48756#0: signal 23 (SIGIO) received -2026/09/20 17:51:45 [notice] 48756#0: signal 23 (SIGIO) received from 48757 -2026/09/20 17:51:45 [notice] 48756#0: signal 20 (SIGCHLD) received from 48760 -2026/09/20 17:51:45 [notice] 48756#0: cache loader process 48760 exited with code 0 -2026/09/20 17:51:45 [notice] 48756#0: worker process 48757 exited with code 0 -2026/09/20 17:51:45 [notice] 48756#0: exit -nginx: the configuration file /Users/rong/Desktop/cache/tests/cache/.run-evict/conf/nginx.cache.conf syntax is ok -2026/09/20 17:52:38 [notice] 49147#0: [ipass] 共享内存已装载 0 条转发映射 -2026/09/20 17:52:38 [notice] 49147#0: [ipass] 已装载 5 个账号 Key、3 个 LLM 上游、1 个 API 代理、2 个缓存上游 -nginx: configuration file /Users/rong/Desktop/cache/tests/cache/.run-evict/conf/nginx.cache.conf test is successful -2026/09/20 17:52:38 [notice] 49148#0: [ipass] 共享内存已装载 0 条转发映射 -2026/09/20 17:52:38 [notice] 49148#0: [ipass] 已装载 5 个账号 Key、3 个 LLM 上游、1 个 API 代理、2 个缓存上游 -2026/09/20 17:52:38 [notice] 49148#0: using the "kqueue" event method -2026/09/20 17:52:38 [notice] 49148#0: nginx/1.30.4 -2026/09/20 17:52:38 [notice] 49148#0: built by clang 14.0.0 (clang-1400.0.29.202) -2026/09/20 17:52:38 [notice] 49148#0: OS: Darwin 21.6.0 -2026/09/20 17:52:38 [notice] 49148#0: hw.ncpu: 4 -2026/09/20 17:52:38 [notice] 49148#0: net.inet.tcp.sendspace: 131072 -2026/09/20 17:52:38 [notice] 49148#0: kern.ipc.somaxconn: 128 -2026/09/20 17:52:38 [notice] 49148#0: hw.cachelinesize: 64 -2026/09/20 17:52:38 [notice] 49148#0: getrlimit(RLIMIT_NOFILE): 1048575:9223372036854775807 -2026/09/20 17:52:38 [notice] 49149#0: start worker processes -2026/09/20 17:52:38 [notice] 49149#0: start worker process 49150 -2026/09/20 17:52:38 [notice] 49149#0: start cache manager process 49151 -2026/09/20 17:52:38 [notice] 49149#0: start cache loader process 49152 -2026/09/20 17:52:38 [notice] 49151#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json) -2026/09/20 17:52:38 [notice] 49149#0: signal 23 (SIGIO) received from 49151 -2026/09/20 17:52:38 [notice] 49150#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json) -2026/09/20 17:52:38 [notice] 49149#0: signal 23 (SIGIO) received from 49150 -2026/09/20 17:52:38 [notice] 49152#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json) -2026/09/20 17:52:38 [info] 49150#0: *1 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *2 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *4 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *6 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *8 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *10 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *12 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *14 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *16 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:38 [info] 49150#0: *18 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:39 [info] 49150#0: *20 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:39 [info] 49150#0: *22 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:39 [info] 49150#0: *24 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:39 [info] 49150#0: *26 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:39 [info] 49150#0: *28 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:39 [info] 49150#0: *30 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:39 [info] 49150#0: *32 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:48 [info] 49150#0: *34 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:48 [info] 49150#0: *36 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:49 [info] 49150#0: *37 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:52:49 [info] 49150#0: *39 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:53:07 [info] 49150#0: *40 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:53:08 [notice] 49149#0: signal 15 (SIGTERM) received from 48992, exiting -2026/09/20 17:53:08 [notice] 49150#0: exiting -2026/09/20 17:53:08 [notice] 49151#0: exiting -2026/09/20 17:53:08 [notice] 49152#0: exiting -2026/09/20 17:53:08 [notice] 49149#0: signal 23 (SIGIO) received from 49152 -2026/09/20 17:53:08 [info] 49150#0: [stats] 落盘 0 键(83 B,worker-exit)-> /Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json -2026/09/20 17:53:08 [notice] 49150#0: exit -2026/09/20 17:53:08 [notice] 49149#0: signal 20 (SIGCHLD) received from 49151 -2026/09/20 17:53:08 [notice] 49149#0: cache loader process 49152 exited with code 0 -2026/09/20 17:53:08 [notice] 49149#0: cache manager process 49151 exited with code 0 -2026/09/20 17:53:08 [notice] 49149#0: signal 23 (SIGIO) received -2026/09/20 17:53:08 [notice] 49149#0: signal 23 (SIGIO) received from 49150 -2026/09/20 17:53:08 [notice] 49149#0: signal 20 (SIGCHLD) received from 49150 -2026/09/20 17:53:08 [notice] 49149#0: worker process 49150 exited with code 0 -2026/09/20 17:53:08 [notice] 49149#0: exit -nginx: the configuration file /Users/rong/Desktop/cache/tests/cache/.run-evict/conf/nginx.cache.conf syntax is ok -2026/09/20 17:54:26 [notice] 49507#0: [ipass] 共享内存已装载 0 条转发映射 -2026/09/20 17:54:26 [notice] 49507#0: [ipass] 已装载 5 个账号 Key、3 个 LLM 上游、1 个 API 代理、2 个缓存上游 -nginx: configuration file /Users/rong/Desktop/cache/tests/cache/.run-evict/conf/nginx.cache.conf test is successful -2026/09/20 17:54:26 [notice] 49508#0: [ipass] 共享内存已装载 0 条转发映射 -2026/09/20 17:54:26 [notice] 49508#0: [ipass] 已装载 5 个账号 Key、3 个 LLM 上游、1 个 API 代理、2 个缓存上游 -2026/09/20 17:54:26 [notice] 49508#0: using the "kqueue" event method -2026/09/20 17:54:26 [notice] 49508#0: nginx/1.30.4 -2026/09/20 17:54:26 [notice] 49508#0: built by clang 14.0.0 (clang-1400.0.29.202) -2026/09/20 17:54:26 [notice] 49508#0: OS: Darwin 21.6.0 -2026/09/20 17:54:26 [notice] 49508#0: hw.ncpu: 4 -2026/09/20 17:54:26 [notice] 49508#0: net.inet.tcp.sendspace: 131072 -2026/09/20 17:54:26 [notice] 49508#0: kern.ipc.somaxconn: 128 -2026/09/20 17:54:26 [notice] 49508#0: hw.cachelinesize: 64 -2026/09/20 17:54:26 [notice] 49508#0: getrlimit(RLIMIT_NOFILE): 1048575:9223372036854775807 -2026/09/20 17:54:26 [notice] 49509#0: start worker processes -2026/09/20 17:54:26 [notice] 49509#0: start worker process 49510 -2026/09/20 17:54:26 [notice] 49509#0: start cache manager process 49511 -2026/09/20 17:54:26 [notice] 49509#0: start cache loader process 49512 -2026/09/20 17:54:26 [notice] 49510#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json) -2026/09/20 17:54:26 [notice] 49509#0: signal 23 (SIGIO) received from 49510 -2026/09/20 17:54:26 [notice] 49512#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json) -2026/09/20 17:54:26 [notice] 49511#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json) -2026/09/20 17:54:26 [notice] 49509#0: signal 23 (SIGIO) received from 49511 -2026/09/20 17:54:26 [info] 49510#0: *1 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:26 [info] 49510#0: *2 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:26 [info] 49510#0: *4 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:26 [info] 49510#0: *6 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *8 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *10 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *12 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *14 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *16 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *18 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *20 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *22 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *24 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *26 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *28 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *30 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:27 [info] 49510#0: *32 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:40 [info] 49510#0: *34 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:41 [info] 49510#0: *36 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:41 [info] 49510#0: *37 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:41 [info] 49510#0: *39 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:58 [info] 49510#0: *40 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 17:54:59 [notice] 49509#0: signal 15 (SIGTERM) received from 49353, exiting -2026/09/20 17:54:59 [notice] 49510#0: exiting -2026/09/20 17:54:59 [notice] 49509#0: signal 23 (SIGIO) received from 49511 -2026/09/20 17:54:59 [notice] 49511#0: exiting -2026/09/20 17:54:59 [notice] 49512#0: exiting -2026/09/20 17:54:59 [notice] 49509#0: signal 23 (SIGIO) received from 49512 -2026/09/20 17:54:59 [info] 49510#0: [stats] 落盘 0 键(83 B,worker-exit)-> /Users/rong/Desktop/cache/tests/cache/.run-evict/data/llm-stats.json -2026/09/20 17:54:59 [notice] 49510#0: exit -2026/09/20 17:54:59 [notice] 49509#0: signal 20 (SIGCHLD) received from 49512 -2026/09/20 17:54:59 [notice] 49509#0: cache loader process 49512 exited with code 0 -2026/09/20 17:54:59 [notice] 49509#0: cache manager process 49511 exited with code 0 -2026/09/20 17:54:59 [notice] 49509#0: signal 23 (SIGIO) received -2026/09/20 17:54:59 [notice] 49509#0: signal 23 (SIGIO) received -2026/09/20 17:54:59 [notice] 49509#0: signal 20 (SIGCHLD) received from 49510 -2026/09/20 17:54:59 [notice] 49509#0: worker process 49510 exited with code 0 -2026/09/20 17:54:59 [notice] 49509#0: exit diff --git a/tests/cache/.run-evict/logs/upstream.out b/tests/cache/.run-evict/logs/upstream.out deleted file mode 100644 index 348ad6e..0000000 --- a/tests/cache/.run-evict/logs/upstream.out +++ /dev/null @@ -1,32 +0,0 @@ -mock upstream on 18997 ----------------------------------------- -Exception occurred during processing of request from ('127.0.0.1', 65474) -Traceback (most recent call last): - File "/Users/rong/.workbuddy/binaries/python/versions/3.13.12/lib/python3.13/socketserver.py", line 318, in _handle_request_noblock - self.process_request(request, client_address) - ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/rong/.workbuddy/binaries/python/versions/3.13.12/lib/python3.13/socketserver.py", line 349, in process_request - self.finish_request(request, client_address) - ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/rong/.workbuddy/binaries/python/versions/3.13.12/lib/python3.13/socketserver.py", line 362, in finish_request - self.RequestHandlerClass(request, client_address, self) - ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/rong/.workbuddy/binaries/python/versions/3.13.12/lib/python3.13/socketserver.py", line 766, in __init__ - self.handle() - ~~~~~~~~~~~^^ - File "/Users/rong/.workbuddy/binaries/python/versions/3.13.12/lib/python3.13/http/server.py", line 447, in handle - self.handle_one_request() - ~~~~~~~~~~~~~~~~~~~~~~~^^ - File "/Users/rong/.workbuddy/binaries/python/versions/3.13.12/lib/python3.13/http/server.py", line 435, in handle_one_request - method() - ~~~~~~^^ - File "/Users/rong/Desktop/cache/tests/cache/mock_upstream.py", line 78, in do_GET - self.wfile.write(full) - ~~~~~~~~~~~~~~~~^^^^^^ - File "/Users/rong/.workbuddy/binaries/python/versions/3.13.12/lib/python3.13/socketserver.py", line 845, in write - self._sock.sendall(b) - ~~~~~~~~~~~~~~~~~~^^^ -ConnectionResetError: [Errno 54] Connection reset by peer ----------------------------------------- -mock upstream on 18997 -mock upstream on 18997 diff --git a/tests/cache/.run-evict/upstream.log b/tests/cache/.run-evict/upstream.log deleted file mode 100644 index 6d15288..0000000 --- a/tests/cache/.run-evict/upstream.log +++ /dev/null @@ -1,20 +0,0 @@ -GET / auth=- -GET /probe?bytes=1024 auth=- -GET /big/1?bytes=204800 auth=- -GET /big/2?bytes=204800 auth=- -GET /big/3?bytes=204800 auth=- -GET /big/4?bytes=204800 auth=- -GET /big/5?bytes=204800 auth=- -GET /big/6?bytes=204800 auth=- -GET /big/7?bytes=204800 auth=- -GET /big/8?bytes=204800 auth=- -GET /big/9?bytes=204800 auth=- -GET /big/10?bytes=204800 auth=- -GET /big/11?bytes=204800 auth=- -GET /big/12?bytes=204800 auth=- -GET /big/13?bytes=204800 auth=- -GET /big/14?bytes=204800 auth=- -GET /big/15?bytes=204800 auth=- -GET /big/1?bytes=204800 auth=- -GET /keepalive?bytes=1024 auth=- -GET /keepalive?bytes=1024 auth=- diff --git a/tests/cache/.run-evict/upstream.pid b/tests/cache/.run-evict/upstream.pid deleted file mode 100644 index 7df0eee..0000000 --- a/tests/cache/.run-evict/upstream.pid +++ /dev/null @@ -1 +0,0 @@ -49501 \ No newline at end of file diff --git a/tests/cache/.run-evict/www b/tests/cache/.run-evict/www deleted file mode 120000 index 898e1cb..0000000 --- a/tests/cache/.run-evict/www +++ /dev/null @@ -1 +0,0 @@ -/Users/rong/Desktop/cache/www \ No newline at end of file diff --git a/tests/cache/.run-ipass/cache/cargo/7/b6/fa85c45018774ee40eed4e14f27e5b67 b/tests/cache/.run-ipass/cache/cargo/7/b6/fa85c45018774ee40eed4e14f27e5b67 deleted file mode 100644 index 77fad5800e035c91739d4420f716d593fa9b7de2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 584 zcmeHE%}T>S5RRgkg}lSiV`!4yga*3c#Tr_u(n9tkp2jdF)i%4NTd@x%;^Ro4z@tx~ z+q58k2Zw=g{=N@B=F&UFF8FvlmM8FYjEB$nZvXw3etDig8=hbE#GrR_``>sTo96ct zN^C1F;|^l;T!lE!RS*YkqSQPV5r>3xm`#0FQ2Royglk+=x8zX<^R2CQ6Q_}InfUAm zElDUgP2cgLAmbp(K%|lS|eIIzT% zmM(3Js`g1HRViTqPRCJ2g>V*KadUm8P)as3@5^s`}F`qcfU^EfV75rNK2G{{t AN&o-= diff --git a/tests/cache/.run-ipass/cache/go/a/1d/3628fdf82489b1d8471bcfb362cee1da b/tests/cache/.run-ipass/cache/go/a/1d/3628fdf82489b1d8471bcfb362cee1da deleted file mode 100644 index 2fee58d576b614b5f78a4440eba52a714eaa6f72..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 578 zcmeHE+e*Vg5RIZQ3;BnkkD*C+voy#;5v-wwDlKGR^lc5pCfa6~bSw7FKN3Gje@3?# zDE)^H17~K=oCCvL2mAPqzF!aJ3H%-6`R8lL-}2945HuJ3@~X!My_4N@69i;hJPFW7 zq}rtRO~-0n$S94-M9O)}5(*imFq?*?#O@tC0e5PJJCY_j%r~w!ZORkoGYiSRawwo& zw|%dJ60L_U2gU`>1iOLpqYTN&v<_PrKVYj}Er1Pj~76R=0#f$o|R3EX@IOI8{A@P#YWG4Jou)psgnxIrS diff --git a/tests/cache/.run-ipass/cache/maven/5/57/018b43239012a992b6a642253ec85575 b/tests/cache/.run-ipass/cache/maven/5/57/018b43239012a992b6a642253ec85575 deleted file mode 100644 index ebc7ab03bfdee39529381bc692dc45b57fc8b0f8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 584 zcmeHEO-jQ+6po^sf!yKIWoR;!2@N>l#u{3v(n4nAO2+U=s_o2>PK!NGPaq!0m3wdC zN~dW-dIuj5zW4Wi@bNB#LwrW>&&Toveva|@@z(9XzjnJIFlSfi7rk`QJGuRDf`Ckl z2LVg9K`m$p)V|cQ8Wl345gAK4qiMo`GX~R1NJ?xs*b2B&E9{mm$zis2jnOnqQlC5| zx5}Y_a;^KG2PIk$Jcl$Bj0>K@=w60oXtYD^;ycu}YXqc&znR=xFQBYl%q!*QUfWa- zUA%HFs%1zDscHfHhkA~x8jSa9tyu`L>nBg@drPmes_{C@84HQ0498R9UBSWMFPRNk A!2kdN diff --git a/tests/cache/.run-ipass/cache/npm/c/11/531eb8fade2b128eb9584b2f4e7e011c b/tests/cache/.run-ipass/cache/npm/c/11/531eb8fade2b128eb9584b2f4e7e011c deleted file mode 100644 index 61c87bb3b201249cf52081ccbe01727aecd7b258..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 580 zcmeHE%}T>S5RRgkg*<{V^cb3CcSCYm@nQ`v)Y3xs;zd})kkmGtCEbdBD)AY-^cB4L zDt7w=(syte=I@*DgJG_{qx}S*ucz`X{hsXk`{RIrZEtQpZ*h@cUiDboJKOzlJdcd? zCjr_tB6cA*iz-yZTn2GKMpDjV7E$1o!gTDD0=qZt1l+3?9zYspFx%L=)o~Ir=iDa` z%A$Z`t^1A#1sa!l1}qVj3(jFUkv4MBkIc50$BPtlN;j%lrhVBsqEZox1~iJ zu55>@@kuUKC1C$d$5CaC;a;t4mjcZC#gY2ZsP|A+c$Z|9`ovKNqp5IL!STKwAnaA# diff --git a/tests/cache/.run-ipass/cache/pypi/5/02/0351062533e47711f552e75f9bdd9025 b/tests/cache/.run-ipass/cache/pypi/5/02/0351062533e47711f552e75f9bdd9025 deleted file mode 100644 index 50d9cf104e0282435b153beb18bf049d52605597..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 582 zcmeHEO-jQ+6po^sfm}fzbr(9xOhO|JxUq&7sVxNtFsM-pw4A)SgjgC}uSJdO*` z(oWif^bS5A@BjPY<6Sxj`}MwGkL5|)9_{&Ov)^BTeO@_Eb#`-pG2o-Y$?bpRIAoSQ z3DBJ`MbO7UzvWa-66pmVnM%0`xX&PD4CXVJq}aY=E8tG8aKB`J42#YbO&vr&w;sCW zUKtdSuIr)2L5kX@Fa{n87K)I=K06tw- AT>t<8 diff --git a/tests/cache/.run-ipass/conf/cache-common.conf b/tests/cache/.run-ipass/conf/cache-common.conf deleted file mode 100644 index 3852e97..0000000 --- a/tests/cache/.run-ipass/conf/cache-common.conf +++ /dev/null @@ -1,131 +0,0 @@ -# ============================================================================ -# cache-common.conf —— 各生态 cache location 共用的缓存/代理指令 -# -# 由 conf/cache-routes.conf 在每个 location 内 `include`。 -# **每个 location 自己指定** `proxy_cache `(各生态分库),本文件只放公共项。 -# -# --------------------------------------------------------------------------- -# 与「静态上游版」相比的三处关键变化(配合 plugin-cache 的变量层) -# --------------------------------------------------------------------------- -# -# 1. `proxy_pass` 由字面量改为变量 `$cache_target`。上游地址与凭据因此来自 -# 共享内存(`cx:`,由管理台写),**改上游不用改 conf、不用 reload**。 -# 代价:变量式 proxy_pass 不推导 Host、不追加 query —— 两者都由模块算好, -# 所以这里必须显式 `proxy_set_header Host $cache_host`。 -# -# 2. `proxy_cache_key` 不再用 `$scheme$proxy_host$request_uri`(变量式下 -# `$proxy_host` 不可靠),改用模块给的 `$cache_key`,并**并入方法 + -# Accept**(下面的注释详述为什么这是正确性问题,不是调优)。 -# -# 3. 出站鉴权头改成三段式(`proxy_pass_request_headers on` + 抹掉三个 -# 网关 Key 携带位 + 用 `$cache_auth` 下发)——见文件下半部分。 -# -# ⚠️ 本文件**不得**使用 rewrite 模块的 `set` / `if`;生态判定由 plugin-cache -# 直读 `r->uri` 首段完成,不需要 `set $cache_ecosystem`。 -# (`return` / `rewrite` 本身可用:本机构建与 ipass 生产都带 --with-pcre, -# rewrite 模块在编。它们只在 cache-routes.conf 里用。) -# ============================================================================ - -# --------------------------------------------------------------------------- -# 缓存键 -# --------------------------------------------------------------------------- -# -# `$cache_key` = `:<完整 URI + query>`,**不含任何下游凭据** —— 缓存因此是 -# 「全站共享」的:同一个 go module / npm 包被 N 个账号拉,只回源一次。 -# 这正是制品缓存的价值所在;鉴权在 access 层(谁能读),数据在共享层复用。 -# 代价:任一有效 Key 都能命中别人拉过的制品 —— 对公开 registry 无碍, -# 若某路由指向**私有**上游,请理解这一点再启用。 -# -# ★ query 必须进键(由模块的 `$cache_key` 负责,本行不要再自己拼 `$args`): -# npm 的 `?write=true`、docker 的 `?ns=`、go 的 `?go-get=1`、cargo 的 -# `?archive=tar.gz` 都靠 query 区分实体。变量式 `proxy_pass` 下 `$uri` -# **不含** query,只按 `$uri` 做键会把 `/x?a` 与 `/x?b` 当成同一个资源, -# 把错的制品发给客户端(且第二次完全不回源,很难察觉)。 -# -# ★ 为什么要并入 `$request_method` 与 `$http_accept`(这是正确性,不是调优): -# -# · `$request_method`:Docker 客户端对同一 URL 先 `HEAD` 看清单存不存在、 -# 再 `GET` 取清单(registry 协议如此)。若两者共用一个键,一次 HEAD 的 -# **空体**响应会被缓存下来并回给随后的 GET,客户端拿到 0 字节清单直接失败。 -# -# · `$http_accept`:nginx 的 proxy_cache **不实现 Vary**(只能靠 -# proxy_ignore_headers 把 Vary 忽略掉,无法参与分档)。而上游同一 URL -# 会因为 Accept 返回**不同实体**: -# - npm:`application/vnd.npm.install-v1+json` → 精简元数据, -# 缺省 → 完整元数据; -# - PyPI simple:`application/vnd.pypi.simple.v1+json` → JSON, -# `text/html` → HTML; -# - Docker:清单 v2 / OCI / v1 的 mediaType 由 Accept 偏好决定。 -# 不并入 Accept 就会出现「发给 A 的实体被回给 B」的串档。代价是每个 -# Accept 变体一个桶(现代客户端取值收敛,实际只多一个桶)。 -# -# 注:刻意**不**再带 `$scheme`/`$proxy_host`:同一份制品无论客户端走 http -# 还是 https、走哪个域名进来,上游都是同一个,共享一份缓存更省盘也更省带宽。 -proxy_cache_key $cache_key$request_method$http_accept; - -# 只缓存完整 GET/HEAD(200/301/308);404 短缓存;206(range)/401 等不缓存,避免错片 -proxy_cache_methods GET HEAD; -proxy_cache_valid 200 301 308 1d; -proxy_cache_valid 404 1m; - -# 上游抖动时用陈旧副本兜底;并发同键只回源一次(防击穿) -proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; -proxy_cache_lock on; -proxy_cache_lock_age 10s; -proxy_cache_lock_timeout 30s; - -# 带 If-None-Match / If-Modified-Since 回源校验,省带宽 -proxy_cache_revalidate on; - -# 加速缓存:不被上游 no-cache/Set-Cookie/Vary 拦下(镜像型缓存的标准取舍) -# ⚠️ Vary 被忽略是**必须**的——见上面缓存键的说明,我们已用 Accept 显式分档; -# 留着 Vary 反而会让 nginx 拒绝缓存这些响应。 -proxy_ignore_headers Cache-Control Expires Set-Cookie Vary; - -proxy_http_version 1.1; - -# --------------------------------------------------------------------------- -# 出站请求头(镜像型:默认透传,但抹掉「本网关自己的 Key」) -# --------------------------------------------------------------------------- -# -# 与 LLM/API 代理的 allowlist 策略**刻意不同**:那些是无状态 API,客户端 -# 头没有语义;而镜像必须原样带上客户端的 `Accept` / `Range` / -# `If-None-Match` / `User-Agent`,否则 docker 的 mediaType 协商、range 取 -# 大 blob、条件请求全部失效。所以这里保持 `on`(nginx 默认),只在三个 -# 「网关 Key 的携带位」上显式抹空。 -# -# 为什么必须抹:`sk_` 是客户端访问**本网关**的身份(auth::downstream_key 认 -# Authorization / x-api-key / api-key 三处)。原样透传给上游 = 把网关钥匙 -# 递给上游厂商,对方可拿它反调本网关的其它路由刷额度。ipass 的 LLM 路径 -# 记过同一个坑(宽松厂商把这缺陷掩盖成 200,换严格厂商才暴露成 401)。 -proxy_pass_request_headers on; -proxy_set_header x-api-key ""; -proxy_set_header api-key ""; - -# 变量形式 proxy_pass 不会推导 Host,必须显式设(上游多为 Cloudflare 前端, -# Host 不符会被直接拒) -proxy_set_header Host $cache_host; - -# Authorization 三段式(由模块里的 `$cache_auth` 实现,语义见其文档): -# 配了上游凭据 → 下发配置值(管理员写全 `Bearer xxx` / `Basic yyy`) -# 没配 → 透传客户端值(Docker Hub 的短期 Bearer token 走这条) -# 客户端那把恰好是下行 sk_ → 丢弃 -proxy_set_header Authorization $cache_auth; - -proxy_set_header X-Real-IP $remote_addr; -proxy_set_header X-Forwarded-For $remote_addr; -proxy_set_header X-Forwarded-Proto $scheme; - -# registry 大 blob / 慢索引:放宽超时 -proxy_read_timeout 300s; -proxy_send_timeout 300s; - -# 变量式/直连上游为 HTTPS 时开 SNI;证书校验此阶段关闭(镜像多为公开源, -# 且目标主机来自管理台配置而非请求。要严格校验需另配 proxy_ssl_trusted_certificate) -proxy_ssl_server_name on; -proxy_ssl_protocols TLSv1.2 TLSv1.3; -proxy_ssl_verify off; - -# 观测:每次响应带回缓存命中状态(ipass plugin-cache 亦从同一变量记账) -add_header X-Cache-Status $upstream_cache_status always; -add_header X-Cache-Eco $cache_eco always; diff --git a/tests/cache/.run-ipass/conf/cache-routes.conf b/tests/cache/.run-ipass/conf/cache-routes.conf deleted file mode 100644 index 4c50106..0000000 --- a/tests/cache/.run-ipass/conf/cache-routes.conf +++ /dev/null @@ -1,177 +0,0 @@ -# ============================================================================ -# cache-routes.conf —— 制品缓存网关的「server 内容」(在 server { } 里 include) -# -# 为什么单独成一个文件:这份路由要**两处复用**—— -# * 明文入口 conf/server.cache.conf(本机 e2e / 内网直连) -# * TLS 入口 conf/tls/*.conf(对外,Docker 镜像加速必须走 https) -# 路由、鉴权开关、探针、管理台只写一份,两个入口不会漂。 -# -# 路由约定:/<前缀>/ => <该 route 配置的上游>/ -# /go/ Go module proxy → 默认 proxy.golang.org -# /cargo/ crates.io 稀疏索引 → 默认 index.crates.io -# /cargo-dl/ .crate 包本体 → 默认 static.crates.io -# /pypi/ PyPI 简单索引/JSON → 默认 pypi.org -# /pypi-files/ wheel/sdist 包文件 → 默认 files.pythonhosted.org -# /npm/ npm registry → 默认 registry.npmjs.org -# /maven/ Maven Central → 默认 repo1.maven.org/maven2 -# /v2/ Docker Registry v2 → 默认 registry-1.docker.io -# -# ⚠️ 上游地址**不写在本文件里**:全部来自 plugin-cache 的上游表(管理台 -# 「制品缓存」页,落盘 data/cache-upstreams.json + 写穿共享内存)。 -# 本文件只出现变量名。改上游 = 改管理台,不需要动 conf、不需要 reload。 -# -# ⚠️ 每个带 `ipass_cache on` 的 location 都会在 access 阶段做闸门: -# 1) 该路由没配上游 → 503(不会让请求走到空 $cache_target 变成 500) -# 2) 统一 sk_ Key 鉴权(与 LLM / API 代理同一把)→ 401 -# 3) 每分钟/每日配额 → 429 -# 然后数据面才交给 nginx 原生 proxy_cache。 -# ============================================================================ - - # ---------------- 管理台(多页静态资源,挂在 /admin/ 下)---------------- - # 每页 head 里有 ,所以资源与 /api/ 都是绝对路径。 - # - # **不发版不重启也能修好页面**:所有 HTML / CSS / JS 都加 - # `Cache-Control: no-store`(expires -1 + add_header)。否则用户浏览器会 - # 一直用发版前的旧 JS —— 典型表现是「后端加了字段,页面上看不到」。 - # - # ⚠️ alias 刻意写**相对**路径 `www/`:nginx 把 root/alias 的相对路径解析到 - # **prefix** 而不是 conf/,所以生产(prefix=/usr/local/nginx)得到 - # /usr/local/nginx/www/,本地回归(prefix=tests/.../.run-prod)得到 - # 测试自己的 www/。写死绝对路径则本机必 404。 - location = / { - return 302 /admin; - } - location = /admin { - default_type text/html; - alias www/cache.html; - expires -1; - add_header Cache-Control "no-store" always; - } - # `/admin/`(末尾斜杠、后面无字符)不能直接 alias 到目录:nginx 会把 - # index 拼成 `cache.htmlindex.html` 而 500。内部重定向到具体文件最干净。 - location = /admin/ { - rewrite ^ /admin/cache.html last; - } - location /admin/ { - alias www/; - expires -1; - add_header Cache-Control "no-store" always; - } - - # ---------------- API:管理态(登录会话)+ 账号态(sk_)---------------- - # 由 plugin-cache 认领 /api/admin/cache* 与 /api/v1/cache*; - # 其余 /api/* 交给同一 gateway 里的其它插件(llm/apix/domain),互不干扰。 - location /api/ { - ipass_api on; - } - - # ---------------- 上游连通性探针(管理台「测试」按钮)---------------- - # /api/admin/cache/test 校验 route 后由模块内部重定向到这里。 - # 刻意**复用** $cache_target / $cache_host / $cache_auth —— 与真实转发 - # 走同一套「拼上游 URL + 换凭据」逻辑,所以「测试通过」才等价于 - # 「真实请求能到上游并带上凭据」;另写一套探针代码必然漂移。 - # - # 为什么这里不写 `ipass_cache on`:内部重定向会重跑 access 阶段,而管理台 - # 带的是**登录 Cookie、不是 sk_**,再鉴一次会把自己 401 掉。鉴权已在 - # /api/admin/cache/test 那一跳用 Admin 守卫做过,这里是 internal,外部进不来。 - # - # proxy_cache off:探针是「验连通」,不该用一次探测污染 1d 的制品缓存。 - location /_cache_test/ { - internal; - proxy_cache off; - proxy_pass $cache_target; - proxy_http_version 1.1; - # 探针只验「拼目标 + 换凭据 + 到达上游」,请求头与请求体都不需要转发: - # * 方法由模块钉成 GET(见 plugin-cache api.rs 的 h_admin_test); - # * body 必须 off —— 管理台是用 POST 触发的,不 off 的话那 2 字节 `{}` - # 会连 Content-Length 一起发出去,上游等一个 GET 的 body、 - # 或 keepalive 上残留半截请求体,表现为「测试时好时坏」。 - proxy_pass_request_headers off; - proxy_pass_request_body off; - proxy_set_header Host $cache_host; - proxy_set_header Authorization $cache_auth; - proxy_set_header User-Agent $http_user_agent; - proxy_ssl_server_name on; - proxy_connect_timeout 5s; - proxy_send_timeout 15s; - proxy_read_timeout 15s; - } - - # ---------------- Go module proxy ---------------- - location /go/ { - ipass_cache on; - proxy_cache go; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- crates.io 稀疏索引 ---------------- - location /cargo/ { - ipass_cache on; - proxy_cache cargo; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- .crate 包本体 ---------------- - # ⚠️ crates.io 的 config.json 里 `dl` 字段给的是**绝对 URL** - # (https://static.crates.io/crates/...),cargo 默认直连上游域名、绕过本网关, - # 所以这个 location 只是**落点就绪**。要真正命中需二选一: - # (a) nginx 开 http_sub_module,用 sub_filter 把索引/`config.json` 里的 - # 绝对 URL 改写成 https://<本网关>/cargo-dl;或 - # (b) 网络层把 static.crates.io 指到本网关(内网 DNS + 证书)。 - # 两者都归到 cargo 生态计数(plugin-cache 的 eco_of_route 已做映射)。 - location /cargo-dl/ { - ipass_cache on; - proxy_cache cargo; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- PyPI 简单索引 / JSON ---------------- - location /pypi/ { - ipass_cache on; - proxy_cache pypi; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- wheel/sdist 包文件 ---------------- - # ⚠️ 与 /cargo-dl/ 同理:PyPI simple 页里的 href 是绝对 URL - # (https://files.pythonhosted.org/...),pip 默认直连,需 sub_filter 重写 - # 或 DNS 指向才能命中本 location。归到 pypi 生态计数。 - location /pypi-files/ { - ipass_cache on; - proxy_cache pypi; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- npm registry ---------------- - location /npm/ { - ipass_cache on; - proxy_cache npm; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- Maven Central ---------------- - location /maven/ { - ipass_cache on; - proxy_cache maven; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- Docker Registry v2 ---------------- - # registry-mirrors 要求 https(见 conf/tls/),且**只适合公开镜像**: - # 缓存键不含用户身份,私有镜像会被串档(见 cache-common.conf 的说明)。 - # 客户端先向 auth.docker.io 换短期 Bearer token 再带 Authorization 来拉, - # 该 token 由 cache-common.conf 的 $cache_auth 透传给上游(但网关自己的 - # sk_ 会被剔除)。上游路径的 `/v2` 前缀由模块的 upstream_path_prefix 补回。 - location /v2/ { - ipass_cache on; - proxy_cache docker; - proxy_pass $cache_target; - include cache-common.conf; - } diff --git a/tests/cache/.run-ipass/conf/mime.types b/tests/cache/.run-ipass/conf/mime.types deleted file mode 100644 index 1c00d70..0000000 --- a/tests/cache/.run-ipass/conf/mime.types +++ /dev/null @@ -1,99 +0,0 @@ - -types { - text/html html htm shtml; - text/css css; - text/xml xml; - image/gif gif; - image/jpeg jpeg jpg; - application/javascript js; - application/atom+xml atom; - application/rss+xml rss; - - text/mathml mml; - text/plain txt; - text/vnd.sun.j2me.app-descriptor jad; - text/vnd.wap.wml wml; - text/x-component htc; - - image/avif avif; - image/png png; - image/svg+xml svg svgz; - image/tiff tif tiff; - image/vnd.wap.wbmp wbmp; - image/webp webp; - image/x-icon ico; - image/x-jng jng; - image/x-ms-bmp bmp; - - font/woff woff; - font/woff2 woff2; - - application/java-archive jar war ear; - application/json json; - application/mac-binhex40 hqx; - application/msword doc; - application/pdf pdf; - application/postscript ps eps ai; - application/rtf rtf; - application/vnd.apple.mpegurl m3u8; - application/vnd.google-earth.kml+xml kml; - application/vnd.google-earth.kmz kmz; - application/vnd.ms-excel xls; - application/vnd.ms-fontobject eot; - application/vnd.ms-powerpoint ppt; - application/vnd.oasis.opendocument.graphics odg; - application/vnd.oasis.opendocument.presentation odp; - application/vnd.oasis.opendocument.spreadsheet ods; - application/vnd.oasis.opendocument.text odt; - application/vnd.openxmlformats-officedocument.presentationml.presentation - pptx; - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - xlsx; - application/vnd.openxmlformats-officedocument.wordprocessingml.document - docx; - application/vnd.wap.wmlc wmlc; - application/wasm wasm; - application/x-7z-compressed 7z; - application/x-cocoa cco; - application/x-java-archive-diff jardiff; - application/x-java-jnlp-file jnlp; - application/x-makeself run; - application/x-perl pl pm; - application/x-pilot prc pdb; - application/x-rar-compressed rar; - application/x-redhat-package-manager rpm; - application/x-sea sea; - application/x-shockwave-flash swf; - application/x-stuffit sit; - application/x-tcl tcl tk; - application/x-x509-ca-cert der pem crt; - application/x-xpinstall xpi; - application/xhtml+xml xhtml; - application/xspf+xml xspf; - application/zip zip; - - application/octet-stream bin exe dll; - application/octet-stream deb; - application/octet-stream dmg; - application/octet-stream iso img; - application/octet-stream msi msp msm; - - audio/midi mid midi kar; - audio/mpeg mp3; - audio/ogg ogg; - audio/x-m4a m4a; - audio/x-realaudio ra; - - video/3gpp 3gpp 3gp; - video/mp2t ts; - video/mp4 mp4; - video/mpeg mpeg mpg; - video/quicktime mov; - video/webm webm; - video/x-flv flv; - video/x-m4v m4v; - video/x-mng mng; - video/x-ms-asf asx asf; - video/x-ms-wmv wmv; - video/x-msvideo avi; -} diff --git a/tests/cache/.run-ipass/conf/nginx.cache.conf b/tests/cache/.run-ipass/conf/nginx.cache.conf deleted file mode 100644 index 1842ebd..0000000 --- a/tests/cache/.run-ipass/conf/nginx.cache.conf +++ /dev/null @@ -1,87 +0,0 @@ -# ============================================================================ -# nginx.cache.conf —— 统一制品缓存网关 · 顶层配置 -# -# vanilla nginx + ipass Rust 动态模块(plugin-cache) -# -# 本机回归:bash tests/cache/run.sh -# 生产部署:把本文件放到 nginx prefix 的 conf/ 下,同目录放 -# server.cache.conf / cache-routes.conf / cache-common.conf / -# mime.types,启动即可;要对外 https 再加 conf/tls/*.conf。 -# -# 数据面 = nginx 原生 proxy_cache(六生态各一个 zone,落本地盘); -# 管理面 = ipass plugin-cache(access 鉴权 + log 按生态记账 + 管理 API)。 -# -# ⚠️ 上游地址/凭据**不在 conf 里**:全在 plugin-cache 的上游表 -# (管理台「制品缓存」页 → data/cache-upstreams.json → 写穿共享内存)。 -# conf 只出现 `$cache_*` 变量名,所以改上游不需要动 conf、不需要 reload。 -# -# ⚠️ 因为 proxy_pass 是变量形式,`resolver` 是**必需**的:nginx 无法在配置 -# 解析期把变量里的主机名解析成 IP,只能运行期查 DNS。缺 resolver 的表现是 -# `/go/...` 一律 500(no resolver defined to resolve ...)。 -# -# 本构建(build/build-nginx-ssl.sh)对齐 ipass 生产的 Dockerfile 参数: -# --with-pcre --with-http_ssl_module --with-http_realip_module -# 即 rewrite 模块与 SSL 都在编,所以本文件与 server.cache.conf / -# cache-routes.conf 里可以用 `return` / `rewrite` / `ssl_certificate`。 -# ============================================================================ - -load_module /Users/rong/Desktop/cache/rust/target/debug/libipass_gateway.dylib; - -worker_processes 1; - error_log /Users/rong/Desktop/cache/tests/cache/.run-ipass/logs/error.log info; - pid /Users/rong/Desktop/cache/tests/cache/.run-ipass/logs/nginx.pid; - -# 初始管理员口令(不声明则会被 nginx 从环境中剥离) -env ADMIN_INIT_PASSWORD; - -events { - worker_connections 4096; -} - -http { - include mime.types; - default_type application/octet-stream; # 缺 Content-Type 时的兜底; - # API 响应由模块显式设 application/json - - sendfile on; - keepalive_timeout 65; - - # ========== 变量式上游的必需项 ========== - # proxy_pass $cache_target 里的主机名只能运行期解析(见文件头注释)。 - # 两个国内解析器,30s 缓存;ipv6=off 避免拿到不可达的 AAAA 卡住连接。 - resolver 223.5.5.5 119.29.29.29 valid=30s ipv6=off; - resolver_timeout 5s; - - # ========== 可选 TLS(HTTPS)========== - # conf/tls/ 下放任意 *.conf(完整的 443/18098 server 块)即启用对应域名的 - # HTTPS;目录为空或不存在时 include 空匹配,不影响启动。 - # 模板见 conf/tls/cache.conf.example,说明见 conf/tls/README.md - include /Users/rong/Desktop/cache/tests/cache/.run-ipass/conf/tls/*.conf; - - # ========== ipass 内核:共享内存 + 数据目录 ========== - # 一张共享内存表承载:上游表(cx:)/ 命中计数(cache:)/ 管理会话 / 限流窗口。 - # 上游表条目数 = 路由数(个位数),10m 绰绰有余。 - ipass_state state 10m; - ipass_data_dir /Users/rong/Desktop/cache/tests/cache/.run-ipass/data; - ipass_audit_dir /Users/rong/Desktop/cache/tests/cache/.run-ipass/audit; - - # ========== 六类生态缓存区(本地盘热层)========== - # 各生态独立 zone,互不串档、独立上限;use_temp_path=off 省一次改名。 - # ⚠️ cargo / pypi 各有两个 route 共用同一个 zone(索引 + 包本体): - # 这是刻意的——同一门语言的流量记在一起才看得懂,而 zone 内靠 - # $cache_key 的 route 前缀天然分档,不会串。 - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-ipass/cache/go levels=1:2 keys_zone=go:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-ipass/cache/cargo levels=1:2 keys_zone=cargo:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-ipass/cache/pypi levels=1:2 keys_zone=pypi:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-ipass/cache/npm levels=1:2 keys_zone=npm:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-ipass/cache/maven levels=1:2 keys_zone=maven:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-ipass/cache/docker levels=1:2 keys_zone=docker:200m max_size=200g inactive=7d use_temp_path=off; - - # 命中率日志(排障用;真实指标由 plugin-cache 的共享内存计数器提供) - log_format cache '$remote_addr [$time_local] "$request" $status ' - '$body_bytes_sent cache=$upstream_cache_status eco=$cache_eco ' - 'uri=$uri rt=$request_time'; - access_log /Users/rong/Desktop/cache/tests/cache/.run-ipass/logs/cache.log cache; - - include server.cache.conf; -} diff --git a/tests/cache/.run-ipass/conf/server.cache.conf b/tests/cache/.run-ipass/conf/server.cache.conf deleted file mode 100644 index ba00b78..0000000 --- a/tests/cache/.run-ipass/conf/server.cache.conf +++ /dev/null @@ -1,30 +0,0 @@ -# ============================================================================ -# server.cache.conf —— 统一制品缓存 server(明文入口) -# -# 这是**内网 / 本机 e2e** 用的明文入口。对外的 https 入口在 conf/tls/*.conf -# (模板见 conf/tls/cache.conf.example)——两者 include 同一份 cache-routes.conf, -# 所以路由只此一份、不会漂。 -# -# 为什么要拆两个入口:Docker 的 `registry-mirrors` 只接受 https(明文地址会 -# 被 daemon 当成 insecure registry 拒绝),而本机自测/内网互调又不想折腾证书。 -# -# 为什么本 server 不写 listen ... ssl:证书与域名属于部署环境(见 conf/tls/), -# 写死在这里会让「同一份 conf 换域名」变成改代码。 -# ============================================================================ - -server { - listen 18084; - server_name _; - - # registry 大 blob 直通,不设体积上限(0 = 不限制) - client_max_body_size 0; - # 请求体都是小 JSON / 空体,调大缓冲区让它留在内存里,避免刷临时文件 - client_body_buffer_size 1m; - - # 管理台 `location = /` 会 302 到 /admin。不关掉的话 nginx 默认写 - # 绝对 URL + 实际 listen 端口,反代/端口映射后会把浏览器踢出链路。 - absolute_redirect off; - port_in_redirect off; - - include cache-routes.conf; -} diff --git a/tests/cache/.run-ipass/data/cache-upstreams.json b/tests/cache/.run-ipass/data/cache-upstreams.json deleted file mode 100644 index 31bba8b..0000000 --- a/tests/cache/.run-ipass/data/cache-upstreams.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "items": { - "go": { "base": "http://127.0.0.1:18999", "key": "", - "mode": "proxy", "name": "测试上游 go", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 }, - "cargo": { "base": "http://127.0.0.1:18999", "key": "", - "mode": "proxy", "name": "测试上游 cargo", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 }, - "cargo-dl": { "base": "http://127.0.0.1:18999", "key": "", - "mode": "proxy", "name": "测试上游 cargo-dl", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 }, - "pypi": { "base": "http://127.0.0.1:18999", "key": "", - "mode": "proxy", "name": "测试上游 pypi", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 }, - "pypi-files": { "base": "http://127.0.0.1:18999", "key": "", - "mode": "proxy", "name": "测试上游 pypi-files", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 }, - "npm": { "base": "http://127.0.0.1:18999", "key": "", - "mode": "proxy", "name": "测试上游 npm", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 }, - "maven": { "base": "http://127.0.0.1:18999", "key": "", - "mode": "proxy", "name": "测试上游 maven", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 }, - "docker": { "base": "http://127.0.0.1:18999", "key": "", - "mode": "proxy", "name": "测试上游 docker", "desc": "假上游", - "enabled": true, "note": "", "created_at": 1757500000, "updated_at": 1757500000 } - } -} diff --git a/tests/cache/.run-ipass/data/llm-stats.json b/tests/cache/.run-ipass/data/llm-stats.json deleted file mode 100644 index d69e84d..0000000 --- a/tests/cache/.run-ipass/data/llm-stats.json +++ /dev/null @@ -1 +0,0 @@ -{"version":1,"saved_at":1789909348,"saved_at_text":"2026-09-20 21:02:28","keys":{}} \ No newline at end of file diff --git a/tests/cache/.run-ipass/data/users.json b/tests/cache/.run-ipass/data/users.json deleted file mode 100644 index 1c50523..0000000 --- a/tests/cache/.run-ipass/data/users.json +++ /dev/null @@ -1 +0,0 @@ -{"admin":{"username":"admin","display_name":"","role":"admin","salt":"5a1b2c3d4e5f60718293a4b5c6d7e8f9","pwd_hash":"062b45d8f3cbef3d30464859355401bb37193868dc42eb941de86855416ab5e8","api_key":"sk_admin_0000000000000000000000000000000000000000000000ab","allowed_models":[],"llm_rpm":60,"llm_daily":0,"temp_grant_until":0,"created_at":1757500000},"alice":{"username":"alice","display_name":"爱丽丝","role":"user","salt":"00112233445566778899aabbccddeeff","pwd_hash":"00","api_key":"sk_alice_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","allowed_models":["openai"],"llm_rpm":60,"llm_daily":0,"temp_grant_until":0,"created_at":1757500000},"bob":{"username":"bob","display_name":"","role":"user","salt":"ffeeddccbbaa99887766554433221100","pwd_hash":"00","api_key":"sk_bob_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","allowed_models":[],"llm_rpm":60,"llm_daily":0,"temp_grant_until":0,"created_at":1757500000},"carol":{"username":"carol","display_name":"","role":"user","salt":"112233445566778899aabbccddeeff00","pwd_hash":"00","api_key":"sk_carol_cccccccccccccccccccccccccccccccccccccccccccccc","allowed_models":[],"llm_rpm":2,"llm_daily":0,"temp_grant_until":0,"created_at":1757500000},"dave":{"username":"dave","display_name":"","role":"user","salt":"aabbccddeeff00112233445566778899","pwd_hash":"00","api_key":"sk_dave_dddddddddddddddddddddddddddddddddddddddddddddddd","allowed_models":[],"llm_rpm":0,"llm_daily":2,"temp_grant_until":0,"created_at":1757500000}} \ No newline at end of file diff --git a/tests/cache/.run-ipass/logs/cache.log b/tests/cache/.run-ipass/logs/cache.log deleted file mode 100644 index 5a807e1..0000000 --- a/tests/cache/.run-ipass/logs/cache.log +++ /dev/null @@ -1,252 +0,0 @@ -127.0.0.1 [20/Sep/2026:16:43:43 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:43 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.020 -127.0.0.1 [20/Sep/2026:16:43:43 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:44 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.017 -127.0.0.1 [20/Sep/2026:16:43:45 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:45 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.017 -127.0.0.1 [20/Sep/2026:16:43:46 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:46 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.016 -127.0.0.1 [20/Sep/2026:16:43:47 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:48 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.015 -127.0.0.1 [20/Sep/2026:16:43:48 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:49 +0800] "GET /v2/pkg-a HTTP/1.1" 500 119 cache=- eco=- uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:49 +0800] "GET /v2/pkg-a HTTP/1.1" 500 119 cache=- eco=- uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:51 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:51 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:51 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:51 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:51 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:51 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:52 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:43:52 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:46:21 +0800] "GET /v2/pkg-a HTTP/1.1" 500 119 cache=- eco=- uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:46:21 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:00 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:00 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:01 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:01 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:02 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:03 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:03 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:04 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:04 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:05 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:06 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:06 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.017 -127.0.0.1 [20/Sep/2026:16:50:07 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:07 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:07 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 695 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:07 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 695 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:08 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 695 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:08 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:08 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:08 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 695 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:08 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 695 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:08 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 695 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:08 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 695 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:09 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:50:09 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:41 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:41 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.021 -127.0.0.1 [20/Sep/2026:16:51:41 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:42 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.020 -127.0.0.1 [20/Sep/2026:16:51:43 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:43 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.018 -127.0.0.1 [20/Sep/2026:16:51:44 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:45 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.019 -127.0.0.1 [20/Sep/2026:16:51:46 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:46 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.019 -127.0.0.1 [20/Sep/2026:16:51:47 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:48 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.021 -127.0.0.1 [20/Sep/2026:16:51:49 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:49 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:49 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:49 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:50 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:50 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:50 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:51 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:51:51 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:50 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:50 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.016 -127.0.0.1 [20/Sep/2026:16:56:51 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:51 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.016 -127.0.0.1 [20/Sep/2026:16:56:52 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:52 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.017 -127.0.0.1 [20/Sep/2026:16:56:53 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:54 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.018 -127.0.0.1 [20/Sep/2026:16:56:54 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:55 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.017 -127.0.0.1 [20/Sep/2026:16:56:55 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:56 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.017 -127.0.0.1 [20/Sep/2026:16:56:57 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:57 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:57 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:57 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:57 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:58 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:58 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:58 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:58 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:58 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:58 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:59 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:16:56:59 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:14 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:14 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.030 -127.0.0.1 [20/Sep/2026:17:00:15 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:16 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.020 -127.0.0.1 [20/Sep/2026:17:00:16 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:17 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.020 -127.0.0.1 [20/Sep/2026:17:00:18 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:19 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.025 -127.0.0.1 [20/Sep/2026:17:00:19 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:20 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.018 -127.0.0.1 [20/Sep/2026:17:00:21 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:21 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.017 -127.0.0.1 [20/Sep/2026:17:00:22 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:22 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:22 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:22 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:23 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:23 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:23 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:23 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:23 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:23 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:23 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:24 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:00:24 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:01 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:01 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.047 -127.0.0.1 [20/Sep/2026:17:03:02 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:03 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.018 -127.0.0.1 [20/Sep/2026:17:03:04 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:05 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.016 -127.0.0.1 [20/Sep/2026:17:03:06 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:07 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.039 -127.0.0.1 [20/Sep/2026:17:03:08 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:09 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.044 -127.0.0.1 [20/Sep/2026:17:03:10 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:11 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.026 -127.0.0.1 [20/Sep/2026:17:03:11 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:12 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:12 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:12 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:12 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:13 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:13 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:13 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:13 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:13 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:13 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:14 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:03:14 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:34 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:34 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.026 -127.0.0.1 [20/Sep/2026:17:04:35 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:36 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.027 -127.0.0.1 [20/Sep/2026:17:04:36 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:37 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.020 -127.0.0.1 [20/Sep/2026:17:04:38 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:38 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.032 -127.0.0.1 [20/Sep/2026:17:04:39 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:40 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.026 -127.0.0.1 [20/Sep/2026:17:04:41 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:41 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.020 -127.0.0.1 [20/Sep/2026:17:04:42 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:43 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:43 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:43 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:43 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:44 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:44 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:44 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:44 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:44 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:44 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:45 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:04:45 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:40 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:40 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.015 -127.0.0.1 [20/Sep/2026:17:57:41 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:41 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.013 -127.0.0.1 [20/Sep/2026:17:57:42 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:42 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.012 -127.0.0.1 [20/Sep/2026:17:57:43 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:43 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.013 -127.0.0.1 [20/Sep/2026:17:57:44 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:44 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.012 -127.0.0.1 [20/Sep/2026:17:57:45 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:45 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.014 -127.0.0.1 [20/Sep/2026:17:57:45 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:46 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:46 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:46 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:46 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:46 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:46 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:46 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:46 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:47 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:47 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:47 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:17:57:47 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:27 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:27 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.013 -127.0.0.1 [20/Sep/2026:18:28:27 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:28 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.009 -127.0.0.1 [20/Sep/2026:18:28:28 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:28 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.009 -127.0.0.1 [20/Sep/2026:18:28:29 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:29 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.009 -127.0.0.1 [20/Sep/2026:18:28:30 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:30 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.009 -127.0.0.1 [20/Sep/2026:18:28:30 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:31 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.009 -127.0.0.1 [20/Sep/2026:18:28:31 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:31 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:31 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:31 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:31 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:32 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:32 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:32 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:32 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:32 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:32 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:32 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:18:28:32 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:18 +0800] "HEAD /admin HTTP/1.1" 200 0 cache=- eco=- uri=/admin rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:18 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=MISS eco=go uri=/go/pkg-a rt=0.020 -127.0.0.1 [20/Sep/2026:21:02:19 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:19 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=MISS eco=cargo uri=/cargo/pkg-a rt=0.023 -127.0.0.1 [20/Sep/2026:21:02:20 +0800] "GET /cargo/pkg-a HTTP/1.1" 200 15 cache=HIT eco=cargo uri=/cargo/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:21 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=MISS eco=pypi uri=/pypi/pkg-a rt=0.014 -127.0.0.1 [20/Sep/2026:21:02:21 +0800] "GET /pypi/pkg-a HTTP/1.1" 200 15 cache=HIT eco=pypi uri=/pypi/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:22 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=MISS eco=npm uri=/npm/pkg-a rt=0.014 -127.0.0.1 [20/Sep/2026:21:02:23 +0800] "GET /npm/pkg-a HTTP/1.1" 200 15 cache=HIT eco=npm uri=/npm/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:23 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=MISS eco=maven uri=/maven/pkg-a rt=0.022 -127.0.0.1 [20/Sep/2026:21:02:24 +0800] "GET /maven/pkg-a HTTP/1.1" 200 15 cache=HIT eco=maven uri=/maven/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:24 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=MISS eco=docker uri=/v2/pkg-a rt=0.012 -127.0.0.1 [20/Sep/2026:21:02:25 +0800] "GET /v2/pkg-a HTTP/1.1" 200 18 cache=HIT eco=docker uri=/v2/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:26 +0800] "GET /api/v1/cache/stats HTTP/1.1" 401 99 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:26 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:26 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:26 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:26 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:26 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:26 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:26 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:27 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:27 +0800] "GET /api/v1/cache/stats HTTP/1.1" 200 694 cache=- eco=- uri=/api/v1/cache/stats rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:27 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 -127.0.0.1 [20/Sep/2026:21:02:28 +0800] "GET /go/pkg-a HTTP/1.1" 200 15 cache=HIT eco=go uri=/go/pkg-a rt=0.000 diff --git a/tests/cache/.run-ipass/logs/error.log b/tests/cache/.run-ipass/logs/error.log deleted file mode 100644 index d295395..0000000 --- a/tests/cache/.run-ipass/logs/error.log +++ /dev/null @@ -1,72 +0,0 @@ -2026/09/20 21:02:16 [notice] 64386#0: [cache] 容量区已识别 6 个:["go", "cargo", "pypi", "npm", "maven", "docker"] -nginx: the configuration file /Users/rong/Desktop/cache/tests/cache/.run-ipass/conf/nginx.cache.conf syntax is ok -2026/09/20 21:02:16 [notice] 64386#0: [ipass] 共享内存已装载 0 条转发映射 -2026/09/20 21:02:16 [notice] 64386#0: [ipass] 已装载 5 个账号 Key、0 个 LLM 上游、0 个 API 代理、8 个缓存上游 -nginx: configuration file /Users/rong/Desktop/cache/tests/cache/.run-ipass/conf/nginx.cache.conf test is successful -2026/09/20 21:02:17 [notice] 64387#0: [cache] 容量区已识别 6 个:["go", "cargo", "pypi", "npm", "maven", "docker"] -2026/09/20 21:02:17 [notice] 64387#0: [ipass] 共享内存已装载 0 条转发映射 -2026/09/20 21:02:17 [notice] 64387#0: [ipass] 已装载 5 个账号 Key、0 个 LLM 上游、0 个 API 代理、8 个缓存上游 -2026/09/20 21:02:17 [notice] 64387#0: using the "kqueue" event method -2026/09/20 21:02:17 [notice] 64387#0: nginx/1.30.4 -2026/09/20 21:02:17 [notice] 64387#0: built by clang 14.0.0 (clang-1400.0.29.202) -2026/09/20 21:02:17 [notice] 64387#0: OS: Darwin 21.6.0 -2026/09/20 21:02:17 [notice] 64387#0: hw.ncpu: 4 -2026/09/20 21:02:17 [notice] 64387#0: net.inet.tcp.sendspace: 131072 -2026/09/20 21:02:17 [notice] 64387#0: kern.ipc.somaxconn: 128 -2026/09/20 21:02:17 [notice] 64387#0: hw.cachelinesize: 64 -2026/09/20 21:02:17 [notice] 64387#0: getrlimit(RLIMIT_NOFILE): 1048575:9223372036854775807 -2026/09/20 21:02:17 [notice] 64388#0: start worker processes -2026/09/20 21:02:17 [notice] 64388#0: start worker process 64389 -2026/09/20 21:02:17 [notice] 64388#0: start cache manager process 64390 -2026/09/20 21:02:17 [notice] 64388#0: start cache loader process 64391 -2026/09/20 21:02:17 [notice] 64390#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-ipass/data/llm-stats.json) -2026/09/20 21:02:17 [notice] 64391#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-ipass/data/llm-stats.json) -2026/09/20 21:02:17 [notice] 64388#0: signal 23 (SIGIO) received from 64390 -2026/09/20 21:02:17 [notice] 64389#0: [stats] 已从快照恢复 0/0 键(/Users/rong/Desktop/cache/tests/cache/.run-ipass/data/llm-stats.json) -2026/09/20 21:02:17 [notice] 64388#0: signal 23 (SIGIO) received from 64389 -2026/09/20 21:02:17 [notice] 64388#0: signal 23 (SIGIO) received -2026/09/20 21:02:18 [info] 64389#0: *1 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:18 [info] 64389#0: *2 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:19 [info] 64389#0: *4 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:19 [info] 64389#0: *5 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:20 [info] 64389#0: *7 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:21 [info] 64389#0: *8 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:21 [info] 64389#0: *10 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:22 [info] 64389#0: *11 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:23 [info] 64389#0: *13 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:23 [info] 64389#0: *14 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:24 [info] 64389#0: *16 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:24 [info] 64389#0: *17 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:25 [info] 64389#0: *19 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:26 [info] 64389#0: *20 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:26 [info] 64389#0: *21 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:26 [info] 64389#0: *22 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:26 [info] 64389#0: *23 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:26 [info] 64389#0: *24 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:26 [info] 64389#0: *25 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:26 [info] 64389#0: *26 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:26 [info] 64389#0: *27 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:27 [info] 64389#0: *28 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:27 [info] 64389#0: *29 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:27 [info] 64389#0: *30 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:28 [info] 64389#0: *31 kevent() reported that client 127.0.0.1 closed keepalive connection -2026/09/20 21:02:28 [notice] 64596#0: [cache] 容量区已识别 6 个:["go", "cargo", "pypi", "npm", "maven", "docker"] -2026/09/20 21:02:28 [notice] 64596#0: signal process started -2026/09/20 21:02:28 [notice] 64388#0: signal 3 (SIGQUIT) received from 64596, shutting down -2026/09/20 21:02:28 [notice] 64388#0: signal 23 (SIGIO) received -2026/09/20 21:02:28 [notice] 64389#0: gracefully shutting down -2026/09/20 21:02:28 [notice] 64389#0: exiting -2026/09/20 21:02:28 [notice] 64388#0: signal 23 (SIGIO) received from 64390 -2026/09/20 21:02:28 [notice] 64391#0: exiting -2026/09/20 21:02:28 [notice] 64390#0: exiting -2026/09/20 21:02:28 [notice] 64388#0: signal 23 (SIGIO) received -2026/09/20 21:02:28 [info] 64389#0: [stats] 落盘 0 键(83 B,worker-exit)-> /Users/rong/Desktop/cache/tests/cache/.run-ipass/data/llm-stats.json -2026/09/20 21:02:28 [notice] 64389#0: exit -2026/09/20 21:02:28 [notice] 64388#0: signal 20 (SIGCHLD) received from 64391 -2026/09/20 21:02:28 [notice] 64388#0: cache loader process 64391 exited with code 0 -2026/09/20 21:02:28 [notice] 64388#0: cache manager process 64390 exited with code 0 -2026/09/20 21:02:28 [notice] 64388#0: signal 23 (SIGIO) received -2026/09/20 21:02:28 [notice] 64388#0: signal 23 (SIGIO) received from 64389 -2026/09/20 21:02:28 [notice] 64388#0: signal 20 (SIGCHLD) received from 64389 -2026/09/20 21:02:28 [notice] 64388#0: worker process 64389 exited with code 0 -2026/09/20 21:02:28 [notice] 64388#0: exit diff --git a/tests/cache/.run-ipass/logs/upstream.out b/tests/cache/.run-ipass/logs/upstream.out deleted file mode 100644 index d57909a..0000000 --- a/tests/cache/.run-ipass/logs/upstream.out +++ /dev/null @@ -1 +0,0 @@ -mock upstream on 18999 diff --git a/tests/cache/.run-ipass/upstream.log b/tests/cache/.run-ipass/upstream.log deleted file mode 100644 index 9d32ddf..0000000 --- a/tests/cache/.run-ipass/upstream.log +++ /dev/null @@ -1,6 +0,0 @@ -GET /pkg-a auth=- -GET /pkg-a auth=- -GET /pkg-a auth=- -GET /pkg-a auth=- -GET /pkg-a auth=- -GET /v2/pkg-a auth=- diff --git a/tests/cache/.run-ipass/www b/tests/cache/.run-ipass/www deleted file mode 120000 index 898e1cb..0000000 --- a/tests/cache/.run-ipass/www +++ /dev/null @@ -1 +0,0 @@ -/Users/rong/Desktop/cache/www \ No newline at end of file diff --git a/tests/cache/.run-prod/conf/cache-common.conf b/tests/cache/.run-prod/conf/cache-common.conf deleted file mode 100644 index 3852e97..0000000 --- a/tests/cache/.run-prod/conf/cache-common.conf +++ /dev/null @@ -1,131 +0,0 @@ -# ============================================================================ -# cache-common.conf —— 各生态 cache location 共用的缓存/代理指令 -# -# 由 conf/cache-routes.conf 在每个 location 内 `include`。 -# **每个 location 自己指定** `proxy_cache `(各生态分库),本文件只放公共项。 -# -# --------------------------------------------------------------------------- -# 与「静态上游版」相比的三处关键变化(配合 plugin-cache 的变量层) -# --------------------------------------------------------------------------- -# -# 1. `proxy_pass` 由字面量改为变量 `$cache_target`。上游地址与凭据因此来自 -# 共享内存(`cx:`,由管理台写),**改上游不用改 conf、不用 reload**。 -# 代价:变量式 proxy_pass 不推导 Host、不追加 query —— 两者都由模块算好, -# 所以这里必须显式 `proxy_set_header Host $cache_host`。 -# -# 2. `proxy_cache_key` 不再用 `$scheme$proxy_host$request_uri`(变量式下 -# `$proxy_host` 不可靠),改用模块给的 `$cache_key`,并**并入方法 + -# Accept**(下面的注释详述为什么这是正确性问题,不是调优)。 -# -# 3. 出站鉴权头改成三段式(`proxy_pass_request_headers on` + 抹掉三个 -# 网关 Key 携带位 + 用 `$cache_auth` 下发)——见文件下半部分。 -# -# ⚠️ 本文件**不得**使用 rewrite 模块的 `set` / `if`;生态判定由 plugin-cache -# 直读 `r->uri` 首段完成,不需要 `set $cache_ecosystem`。 -# (`return` / `rewrite` 本身可用:本机构建与 ipass 生产都带 --with-pcre, -# rewrite 模块在编。它们只在 cache-routes.conf 里用。) -# ============================================================================ - -# --------------------------------------------------------------------------- -# 缓存键 -# --------------------------------------------------------------------------- -# -# `$cache_key` = `:<完整 URI + query>`,**不含任何下游凭据** —— 缓存因此是 -# 「全站共享」的:同一个 go module / npm 包被 N 个账号拉,只回源一次。 -# 这正是制品缓存的价值所在;鉴权在 access 层(谁能读),数据在共享层复用。 -# 代价:任一有效 Key 都能命中别人拉过的制品 —— 对公开 registry 无碍, -# 若某路由指向**私有**上游,请理解这一点再启用。 -# -# ★ query 必须进键(由模块的 `$cache_key` 负责,本行不要再自己拼 `$args`): -# npm 的 `?write=true`、docker 的 `?ns=`、go 的 `?go-get=1`、cargo 的 -# `?archive=tar.gz` 都靠 query 区分实体。变量式 `proxy_pass` 下 `$uri` -# **不含** query,只按 `$uri` 做键会把 `/x?a` 与 `/x?b` 当成同一个资源, -# 把错的制品发给客户端(且第二次完全不回源,很难察觉)。 -# -# ★ 为什么要并入 `$request_method` 与 `$http_accept`(这是正确性,不是调优): -# -# · `$request_method`:Docker 客户端对同一 URL 先 `HEAD` 看清单存不存在、 -# 再 `GET` 取清单(registry 协议如此)。若两者共用一个键,一次 HEAD 的 -# **空体**响应会被缓存下来并回给随后的 GET,客户端拿到 0 字节清单直接失败。 -# -# · `$http_accept`:nginx 的 proxy_cache **不实现 Vary**(只能靠 -# proxy_ignore_headers 把 Vary 忽略掉,无法参与分档)。而上游同一 URL -# 会因为 Accept 返回**不同实体**: -# - npm:`application/vnd.npm.install-v1+json` → 精简元数据, -# 缺省 → 完整元数据; -# - PyPI simple:`application/vnd.pypi.simple.v1+json` → JSON, -# `text/html` → HTML; -# - Docker:清单 v2 / OCI / v1 的 mediaType 由 Accept 偏好决定。 -# 不并入 Accept 就会出现「发给 A 的实体被回给 B」的串档。代价是每个 -# Accept 变体一个桶(现代客户端取值收敛,实际只多一个桶)。 -# -# 注:刻意**不**再带 `$scheme`/`$proxy_host`:同一份制品无论客户端走 http -# 还是 https、走哪个域名进来,上游都是同一个,共享一份缓存更省盘也更省带宽。 -proxy_cache_key $cache_key$request_method$http_accept; - -# 只缓存完整 GET/HEAD(200/301/308);404 短缓存;206(range)/401 等不缓存,避免错片 -proxy_cache_methods GET HEAD; -proxy_cache_valid 200 301 308 1d; -proxy_cache_valid 404 1m; - -# 上游抖动时用陈旧副本兜底;并发同键只回源一次(防击穿) -proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; -proxy_cache_lock on; -proxy_cache_lock_age 10s; -proxy_cache_lock_timeout 30s; - -# 带 If-None-Match / If-Modified-Since 回源校验,省带宽 -proxy_cache_revalidate on; - -# 加速缓存:不被上游 no-cache/Set-Cookie/Vary 拦下(镜像型缓存的标准取舍) -# ⚠️ Vary 被忽略是**必须**的——见上面缓存键的说明,我们已用 Accept 显式分档; -# 留着 Vary 反而会让 nginx 拒绝缓存这些响应。 -proxy_ignore_headers Cache-Control Expires Set-Cookie Vary; - -proxy_http_version 1.1; - -# --------------------------------------------------------------------------- -# 出站请求头(镜像型:默认透传,但抹掉「本网关自己的 Key」) -# --------------------------------------------------------------------------- -# -# 与 LLM/API 代理的 allowlist 策略**刻意不同**:那些是无状态 API,客户端 -# 头没有语义;而镜像必须原样带上客户端的 `Accept` / `Range` / -# `If-None-Match` / `User-Agent`,否则 docker 的 mediaType 协商、range 取 -# 大 blob、条件请求全部失效。所以这里保持 `on`(nginx 默认),只在三个 -# 「网关 Key 的携带位」上显式抹空。 -# -# 为什么必须抹:`sk_` 是客户端访问**本网关**的身份(auth::downstream_key 认 -# Authorization / x-api-key / api-key 三处)。原样透传给上游 = 把网关钥匙 -# 递给上游厂商,对方可拿它反调本网关的其它路由刷额度。ipass 的 LLM 路径 -# 记过同一个坑(宽松厂商把这缺陷掩盖成 200,换严格厂商才暴露成 401)。 -proxy_pass_request_headers on; -proxy_set_header x-api-key ""; -proxy_set_header api-key ""; - -# 变量形式 proxy_pass 不会推导 Host,必须显式设(上游多为 Cloudflare 前端, -# Host 不符会被直接拒) -proxy_set_header Host $cache_host; - -# Authorization 三段式(由模块里的 `$cache_auth` 实现,语义见其文档): -# 配了上游凭据 → 下发配置值(管理员写全 `Bearer xxx` / `Basic yyy`) -# 没配 → 透传客户端值(Docker Hub 的短期 Bearer token 走这条) -# 客户端那把恰好是下行 sk_ → 丢弃 -proxy_set_header Authorization $cache_auth; - -proxy_set_header X-Real-IP $remote_addr; -proxy_set_header X-Forwarded-For $remote_addr; -proxy_set_header X-Forwarded-Proto $scheme; - -# registry 大 blob / 慢索引:放宽超时 -proxy_read_timeout 300s; -proxy_send_timeout 300s; - -# 变量式/直连上游为 HTTPS 时开 SNI;证书校验此阶段关闭(镜像多为公开源, -# 且目标主机来自管理台配置而非请求。要严格校验需另配 proxy_ssl_trusted_certificate) -proxy_ssl_server_name on; -proxy_ssl_protocols TLSv1.2 TLSv1.3; -proxy_ssl_verify off; - -# 观测:每次响应带回缓存命中状态(ipass plugin-cache 亦从同一变量记账) -add_header X-Cache-Status $upstream_cache_status always; -add_header X-Cache-Eco $cache_eco always; diff --git a/tests/cache/.run-prod/conf/cache-routes.conf b/tests/cache/.run-prod/conf/cache-routes.conf deleted file mode 100644 index 4c50106..0000000 --- a/tests/cache/.run-prod/conf/cache-routes.conf +++ /dev/null @@ -1,177 +0,0 @@ -# ============================================================================ -# cache-routes.conf —— 制品缓存网关的「server 内容」(在 server { } 里 include) -# -# 为什么单独成一个文件:这份路由要**两处复用**—— -# * 明文入口 conf/server.cache.conf(本机 e2e / 内网直连) -# * TLS 入口 conf/tls/*.conf(对外,Docker 镜像加速必须走 https) -# 路由、鉴权开关、探针、管理台只写一份,两个入口不会漂。 -# -# 路由约定:/<前缀>/ => <该 route 配置的上游>/ -# /go/ Go module proxy → 默认 proxy.golang.org -# /cargo/ crates.io 稀疏索引 → 默认 index.crates.io -# /cargo-dl/ .crate 包本体 → 默认 static.crates.io -# /pypi/ PyPI 简单索引/JSON → 默认 pypi.org -# /pypi-files/ wheel/sdist 包文件 → 默认 files.pythonhosted.org -# /npm/ npm registry → 默认 registry.npmjs.org -# /maven/ Maven Central → 默认 repo1.maven.org/maven2 -# /v2/ Docker Registry v2 → 默认 registry-1.docker.io -# -# ⚠️ 上游地址**不写在本文件里**:全部来自 plugin-cache 的上游表(管理台 -# 「制品缓存」页,落盘 data/cache-upstreams.json + 写穿共享内存)。 -# 本文件只出现变量名。改上游 = 改管理台,不需要动 conf、不需要 reload。 -# -# ⚠️ 每个带 `ipass_cache on` 的 location 都会在 access 阶段做闸门: -# 1) 该路由没配上游 → 503(不会让请求走到空 $cache_target 变成 500) -# 2) 统一 sk_ Key 鉴权(与 LLM / API 代理同一把)→ 401 -# 3) 每分钟/每日配额 → 429 -# 然后数据面才交给 nginx 原生 proxy_cache。 -# ============================================================================ - - # ---------------- 管理台(多页静态资源,挂在 /admin/ 下)---------------- - # 每页 head 里有 ,所以资源与 /api/ 都是绝对路径。 - # - # **不发版不重启也能修好页面**:所有 HTML / CSS / JS 都加 - # `Cache-Control: no-store`(expires -1 + add_header)。否则用户浏览器会 - # 一直用发版前的旧 JS —— 典型表现是「后端加了字段,页面上看不到」。 - # - # ⚠️ alias 刻意写**相对**路径 `www/`:nginx 把 root/alias 的相对路径解析到 - # **prefix** 而不是 conf/,所以生产(prefix=/usr/local/nginx)得到 - # /usr/local/nginx/www/,本地回归(prefix=tests/.../.run-prod)得到 - # 测试自己的 www/。写死绝对路径则本机必 404。 - location = / { - return 302 /admin; - } - location = /admin { - default_type text/html; - alias www/cache.html; - expires -1; - add_header Cache-Control "no-store" always; - } - # `/admin/`(末尾斜杠、后面无字符)不能直接 alias 到目录:nginx 会把 - # index 拼成 `cache.htmlindex.html` 而 500。内部重定向到具体文件最干净。 - location = /admin/ { - rewrite ^ /admin/cache.html last; - } - location /admin/ { - alias www/; - expires -1; - add_header Cache-Control "no-store" always; - } - - # ---------------- API:管理态(登录会话)+ 账号态(sk_)---------------- - # 由 plugin-cache 认领 /api/admin/cache* 与 /api/v1/cache*; - # 其余 /api/* 交给同一 gateway 里的其它插件(llm/apix/domain),互不干扰。 - location /api/ { - ipass_api on; - } - - # ---------------- 上游连通性探针(管理台「测试」按钮)---------------- - # /api/admin/cache/test 校验 route 后由模块内部重定向到这里。 - # 刻意**复用** $cache_target / $cache_host / $cache_auth —— 与真实转发 - # 走同一套「拼上游 URL + 换凭据」逻辑,所以「测试通过」才等价于 - # 「真实请求能到上游并带上凭据」;另写一套探针代码必然漂移。 - # - # 为什么这里不写 `ipass_cache on`:内部重定向会重跑 access 阶段,而管理台 - # 带的是**登录 Cookie、不是 sk_**,再鉴一次会把自己 401 掉。鉴权已在 - # /api/admin/cache/test 那一跳用 Admin 守卫做过,这里是 internal,外部进不来。 - # - # proxy_cache off:探针是「验连通」,不该用一次探测污染 1d 的制品缓存。 - location /_cache_test/ { - internal; - proxy_cache off; - proxy_pass $cache_target; - proxy_http_version 1.1; - # 探针只验「拼目标 + 换凭据 + 到达上游」,请求头与请求体都不需要转发: - # * 方法由模块钉成 GET(见 plugin-cache api.rs 的 h_admin_test); - # * body 必须 off —— 管理台是用 POST 触发的,不 off 的话那 2 字节 `{}` - # 会连 Content-Length 一起发出去,上游等一个 GET 的 body、 - # 或 keepalive 上残留半截请求体,表现为「测试时好时坏」。 - proxy_pass_request_headers off; - proxy_pass_request_body off; - proxy_set_header Host $cache_host; - proxy_set_header Authorization $cache_auth; - proxy_set_header User-Agent $http_user_agent; - proxy_ssl_server_name on; - proxy_connect_timeout 5s; - proxy_send_timeout 15s; - proxy_read_timeout 15s; - } - - # ---------------- Go module proxy ---------------- - location /go/ { - ipass_cache on; - proxy_cache go; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- crates.io 稀疏索引 ---------------- - location /cargo/ { - ipass_cache on; - proxy_cache cargo; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- .crate 包本体 ---------------- - # ⚠️ crates.io 的 config.json 里 `dl` 字段给的是**绝对 URL** - # (https://static.crates.io/crates/...),cargo 默认直连上游域名、绕过本网关, - # 所以这个 location 只是**落点就绪**。要真正命中需二选一: - # (a) nginx 开 http_sub_module,用 sub_filter 把索引/`config.json` 里的 - # 绝对 URL 改写成 https://<本网关>/cargo-dl;或 - # (b) 网络层把 static.crates.io 指到本网关(内网 DNS + 证书)。 - # 两者都归到 cargo 生态计数(plugin-cache 的 eco_of_route 已做映射)。 - location /cargo-dl/ { - ipass_cache on; - proxy_cache cargo; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- PyPI 简单索引 / JSON ---------------- - location /pypi/ { - ipass_cache on; - proxy_cache pypi; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- wheel/sdist 包文件 ---------------- - # ⚠️ 与 /cargo-dl/ 同理:PyPI simple 页里的 href 是绝对 URL - # (https://files.pythonhosted.org/...),pip 默认直连,需 sub_filter 重写 - # 或 DNS 指向才能命中本 location。归到 pypi 生态计数。 - location /pypi-files/ { - ipass_cache on; - proxy_cache pypi; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- npm registry ---------------- - location /npm/ { - ipass_cache on; - proxy_cache npm; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- Maven Central ---------------- - location /maven/ { - ipass_cache on; - proxy_cache maven; - proxy_pass $cache_target; - include cache-common.conf; - } - - # ---------------- Docker Registry v2 ---------------- - # registry-mirrors 要求 https(见 conf/tls/),且**只适合公开镜像**: - # 缓存键不含用户身份,私有镜像会被串档(见 cache-common.conf 的说明)。 - # 客户端先向 auth.docker.io 换短期 Bearer token 再带 Authorization 来拉, - # 该 token 由 cache-common.conf 的 $cache_auth 透传给上游(但网关自己的 - # sk_ 会被剔除)。上游路径的 `/v2` 前缀由模块的 upstream_path_prefix 补回。 - location /v2/ { - ipass_cache on; - proxy_cache docker; - proxy_pass $cache_target; - include cache-common.conf; - } diff --git a/tests/cache/.run-prod/conf/mime.types b/tests/cache/.run-prod/conf/mime.types deleted file mode 100644 index 1c00d70..0000000 --- a/tests/cache/.run-prod/conf/mime.types +++ /dev/null @@ -1,99 +0,0 @@ - -types { - text/html html htm shtml; - text/css css; - text/xml xml; - image/gif gif; - image/jpeg jpeg jpg; - application/javascript js; - application/atom+xml atom; - application/rss+xml rss; - - text/mathml mml; - text/plain txt; - text/vnd.sun.j2me.app-descriptor jad; - text/vnd.wap.wml wml; - text/x-component htc; - - image/avif avif; - image/png png; - image/svg+xml svg svgz; - image/tiff tif tiff; - image/vnd.wap.wbmp wbmp; - image/webp webp; - image/x-icon ico; - image/x-jng jng; - image/x-ms-bmp bmp; - - font/woff woff; - font/woff2 woff2; - - application/java-archive jar war ear; - application/json json; - application/mac-binhex40 hqx; - application/msword doc; - application/pdf pdf; - application/postscript ps eps ai; - application/rtf rtf; - application/vnd.apple.mpegurl m3u8; - application/vnd.google-earth.kml+xml kml; - application/vnd.google-earth.kmz kmz; - application/vnd.ms-excel xls; - application/vnd.ms-fontobject eot; - application/vnd.ms-powerpoint ppt; - application/vnd.oasis.opendocument.graphics odg; - application/vnd.oasis.opendocument.presentation odp; - application/vnd.oasis.opendocument.spreadsheet ods; - application/vnd.oasis.opendocument.text odt; - application/vnd.openxmlformats-officedocument.presentationml.presentation - pptx; - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - xlsx; - application/vnd.openxmlformats-officedocument.wordprocessingml.document - docx; - application/vnd.wap.wmlc wmlc; - application/wasm wasm; - application/x-7z-compressed 7z; - application/x-cocoa cco; - application/x-java-archive-diff jardiff; - application/x-java-jnlp-file jnlp; - application/x-makeself run; - application/x-perl pl pm; - application/x-pilot prc pdb; - application/x-rar-compressed rar; - application/x-redhat-package-manager rpm; - application/x-sea sea; - application/x-shockwave-flash swf; - application/x-stuffit sit; - application/x-tcl tcl tk; - application/x-x509-ca-cert der pem crt; - application/x-xpinstall xpi; - application/xhtml+xml xhtml; - application/xspf+xml xspf; - application/zip zip; - - application/octet-stream bin exe dll; - application/octet-stream deb; - application/octet-stream dmg; - application/octet-stream iso img; - application/octet-stream msi msp msm; - - audio/midi mid midi kar; - audio/mpeg mp3; - audio/ogg ogg; - audio/x-m4a m4a; - audio/x-realaudio ra; - - video/3gpp 3gpp 3gp; - video/mp2t ts; - video/mp4 mp4; - video/mpeg mpeg mpg; - video/quicktime mov; - video/webm webm; - video/x-flv flv; - video/x-m4v m4v; - video/x-mng mng; - video/x-ms-asf asx asf; - video/x-ms-wmv wmv; - video/x-msvideo avi; -} diff --git a/tests/cache/.run-prod/conf/nginx.cache.conf b/tests/cache/.run-prod/conf/nginx.cache.conf deleted file mode 100644 index a0cc915..0000000 --- a/tests/cache/.run-prod/conf/nginx.cache.conf +++ /dev/null @@ -1,87 +0,0 @@ -# ============================================================================ -# nginx.cache.conf —— 统一制品缓存网关 · 顶层配置 -# -# vanilla nginx + ipass Rust 动态模块(plugin-cache) -# -# 本机回归:bash tests/cache/run.sh -# 生产部署:把本文件放到 nginx prefix 的 conf/ 下,同目录放 -# server.cache.conf / cache-routes.conf / cache-common.conf / -# mime.types,启动即可;要对外 https 再加 conf/tls/*.conf。 -# -# 数据面 = nginx 原生 proxy_cache(六生态各一个 zone,落本地盘); -# 管理面 = ipass plugin-cache(access 鉴权 + log 按生态记账 + 管理 API)。 -# -# ⚠️ 上游地址/凭据**不在 conf 里**:全在 plugin-cache 的上游表 -# (管理台「制品缓存」页 → data/cache-upstreams.json → 写穿共享内存)。 -# conf 只出现 `$cache_*` 变量名,所以改上游不需要动 conf、不需要 reload。 -# -# ⚠️ 因为 proxy_pass 是变量形式,`resolver` 是**必需**的:nginx 无法在配置 -# 解析期把变量里的主机名解析成 IP,只能运行期查 DNS。缺 resolver 的表现是 -# `/go/...` 一律 500(no resolver defined to resolve ...)。 -# -# 本构建(build/build-nginx-ssl.sh)对齐 ipass 生产的 Dockerfile 参数: -# --with-pcre --with-http_ssl_module --with-http_realip_module -# 即 rewrite 模块与 SSL 都在编,所以本文件与 server.cache.conf / -# cache-routes.conf 里可以用 `return` / `rewrite` / `ssl_certificate`。 -# ============================================================================ - -load_module /Users/rong/Desktop/cache/rust/target/debug/libipass_gateway.dylib; - -worker_processes 1; - error_log /Users/rong/Desktop/cache/tests/cache/.run-prod/logs/error.log info; - pid /Users/rong/Desktop/cache/tests/cache/.run-prod/logs/nginx.pid; - -# 初始管理员口令(不声明则会被 nginx 从环境中剥离) -env ADMIN_INIT_PASSWORD; - -events { - worker_connections 4096; -} - -http { - include mime.types; - default_type application/octet-stream; # 缺 Content-Type 时的兜底; - # API 响应由模块显式设 application/json - - sendfile on; - keepalive_timeout 65; - - # ========== 变量式上游的必需项 ========== - # proxy_pass $cache_target 里的主机名只能运行期解析(见文件头注释)。 - # 两个国内解析器,30s 缓存;ipv6=off 避免拿到不可达的 AAAA 卡住连接。 - resolver 223.5.5.5 119.29.29.29 valid=30s ipv6=off; - resolver_timeout 5s; - - # ========== 可选 TLS(HTTPS)========== - # conf/tls/ 下放任意 *.conf(完整的 443/18098 server 块)即启用对应域名的 - # HTTPS;目录为空或不存在时 include 空匹配,不影响启动。 - # 模板见 conf/tls/cache.conf.example,说明见 conf/tls/README.md - include /Users/rong/Desktop/cache/tests/cache/.run-prod/conf/tls/*.conf; - - # ========== ipass 内核:共享内存 + 数据目录 ========== - # 一张共享内存表承载:上游表(cx:)/ 命中计数(cache:)/ 管理会话 / 限流窗口。 - # 上游表条目数 = 路由数(个位数),10m 绰绰有余。 - ipass_state state 10m; - ipass_data_dir /Users/rong/Desktop/cache/tests/cache/.run-prod/data; - ipass_audit_dir /Users/rong/Desktop/cache/tests/cache/.run-prod/audit; - - # ========== 六类生态缓存区(本地盘热层)========== - # 各生态独立 zone,互不串档、独立上限;use_temp_path=off 省一次改名。 - # ⚠️ cargo / pypi 各有两个 route 共用同一个 zone(索引 + 包本体): - # 这是刻意的——同一门语言的流量记在一起才看得懂,而 zone 内靠 - # $cache_key 的 route 前缀天然分档,不会串。 - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-prod/cache/go levels=1:2 keys_zone=go:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-prod/cache/cargo levels=1:2 keys_zone=cargo:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-prod/cache/pypi levels=1:2 keys_zone=pypi:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-prod/cache/npm levels=1:2 keys_zone=npm:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-prod/cache/maven levels=1:2 keys_zone=maven:100m max_size=50g inactive=7d use_temp_path=off; - proxy_cache_path /Users/rong/Desktop/cache/tests/cache/.run-prod/cache/docker levels=1:2 keys_zone=docker:200m max_size=200g inactive=7d use_temp_path=off; - - # 命中率日志(排障用;真实指标由 plugin-cache 的共享内存计数器提供) - log_format cache '$remote_addr [$time_local] "$request" $status ' - '$body_bytes_sent cache=$upstream_cache_status eco=$cache_eco ' - 'uri=$uri rt=$request_time'; - access_log /Users/rong/Desktop/cache/tests/cache/.run-prod/logs/cache.log cache; - - include server.cache.conf; -} diff --git a/tests/cache/.run-prod/conf/server.cache.conf b/tests/cache/.run-prod/conf/server.cache.conf deleted file mode 100644 index 53cf2ec..0000000 --- a/tests/cache/.run-prod/conf/server.cache.conf +++ /dev/null @@ -1,30 +0,0 @@ -# ============================================================================ -# server.cache.conf —— 统一制品缓存 server(明文入口) -# -# 这是**内网 / 本机 e2e** 用的明文入口。对外的 https 入口在 conf/tls/*.conf -# (模板见 conf/tls/cache.conf.example)——两者 include 同一份 cache-routes.conf, -# 所以路由只此一份、不会漂。 -# -# 为什么要拆两个入口:Docker 的 `registry-mirrors` 只接受 https(明文地址会 -# 被 daemon 当成 insecure registry 拒绝),而本机自测/内网互调又不想折腾证书。 -# -# 为什么本 server 不写 listen ... ssl:证书与域名属于部署环境(见 conf/tls/), -# 写死在这里会让「同一份 conf 换域名」变成改代码。 -# ============================================================================ - -server { - listen 18086; - server_name _; - - # registry 大 blob 直通,不设体积上限(0 = 不限制) - client_max_body_size 0; - # 请求体都是小 JSON / 空体,调大缓冲区让它留在内存里,避免刷临时文件 - client_body_buffer_size 1m; - - # 管理台 `location = /` 会 302 到 /admin。不关掉的话 nginx 默认写 - # 绝对 URL + 实际 listen 端口,反代/端口映射后会把浏览器踢出链路。 - absolute_redirect off; - port_in_redirect off; - - include cache-routes.conf; -} diff --git a/tests/cache/.run-prod/logs/cache.log b/tests/cache/.run-prod/logs/cache.log deleted file mode 100644 index e69de29..0000000 diff --git a/tests/cache/.run-prod/logs/error.log b/tests/cache/.run-prod/logs/error.log deleted file mode 100644 index fe11278..0000000 --- a/tests/cache/.run-prod/logs/error.log +++ /dev/null @@ -1,3 +0,0 @@ -nginx: the configuration file /Users/rong/Desktop/cache/tests/cache/.run-prod/conf/nginx.cache.conf syntax is ok -nginx: configuration file /Users/rong/Desktop/cache/tests/cache/.run-prod/conf/nginx.cache.conf test is successful - [notice] 64738#0: [ipass] 已装载 0 个账号 Key、0 个 LLM 上游、0 个 API 代理、0 个缓存上游 diff --git a/tests/cache/.run-prod/logs/nginx.pid b/tests/cache/.run-prod/logs/nginx.pid deleted file mode 100644 index e69de29..0000000 diff --git a/tests/cache/.run-prod/www b/tests/cache/.run-prod/www deleted file mode 120000 index 898e1cb..0000000 --- a/tests/cache/.run-prod/www +++ /dev/null @@ -1 +0,0 @@ -/Users/rong/Desktop/cache/www \ No newline at end of file diff --git a/tests/cache/.run/cache/cargo/8/92/96bbd6bf360b9648e9afd5d07aafd928 b/tests/cache/.run/cache/cargo/8/92/96bbd6bf360b9648e9afd5d07aafd928 deleted file mode 100644 index b723b69dcadd1f241c3eaf19f89873a0860717e5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 580 zcmeHE%}T>S5RRgkg}lSibCc{QB*=o7*3d%L7P1$QV_1@!CcC6lu}|fbc-IFIA49jM zAbkfv2Il9R?}K43y#bT2*QaB7lD?0KKL-Bo{{7SQnzQu$VkFYh$?kvSd2EqCNT`Wy zYsw}nv9C;In<_vyS85fBkVDKlEEhg2bpNb-2@~AvUy_FztoBr!E=oe-BKFx0l9o{H zy0Ozip{+}C1|pGM$m9xUcgkl|(~<5dxYb=nwFHs=&D7pH1GILtE|J#G+mxg!*ix^t v^;xd4l5lvY(_mTa;NaGqjRd=UbfPh|_!3~Huak^(pE=2NzLc|E!Eo6RBVJey diff --git a/tests/cache/.run/cache/docker/2/bd/15d75620ad41340b2459f5d02b9e6bd2 b/tests/cache/.run/cache/docker/2/bd/15d75620ad41340b2459f5d02b9e6bd2 deleted file mode 100644 index 9b503d772696319eac546ec493a03e1c87c2ff24..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 581 zcmeHE%}T>S5MD(ui+P8k=O)=rYz~WFtf9p!Eo4DFu5n0e^RuK=u}|gm^yOP>^!M7D18 zRrulpcA;GrzTs1?7oiLUL_)xP=J5=>H|!MLm^J=_B1mAdrLt|pIFQaGkKY9v`<2VMG2sHU*Um_TO|Ilb7i4)w;G)U^mZ>G=$o``=-F_I1$3*jxwIk)g;x>U-kp}Lsv5Z diff --git a/tests/cache/.run/cache/go/0/6b/decf43777bf2ea024deb844b8dd546b0 b/tests/cache/.run/cache/go/0/6b/decf43777bf2ea024deb844b8dd546b0 deleted file mode 100644 index c498e92be5daed5d6066989a462f56e538767c12..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 577 zcmeHE%}T>S5RRgkg}lSibCc{QB!>kNtf7S}DP%7m*DxftO?F8qV&B0B@#ft(@dq?41~|Hkv!GJlZJ z5ZTsLo2WLC-PD0*3#C?(2sy-@L$UN(iTyM75^nSke@Px@u-a2&x+n>Si`ZwknovSH zbW^8;60J*d1|pGM$W*}mUioZhI>L^EJM3y|B#88HruNnuXlu9YO4HhTn~IQv9rdVN vpXEx|5)Pkq8eKIQ9Nc=dm0*WQCz?X5Ujkj@Rg!V;GbfoX3OUaejF{zF0#8Ra(ft__&54scCkXbX)AHJdY>v7`inD z=^gwSn4fRH4~Dt*1{7Z(Z|CwNeV;M=9Qe`fZsd9GReF6hX6g81_rLKxvdmvNG}f9< zS8deE1FFchbs$M0#5!Ujg_u%UEqzjAf54u@gWTaSNy7}*N84x>B_VSW`{YqtL1sA}7AVCmmX9E~%O#%wp0v>WHGD~mSR*&b!* ulU&G}!|9n$BdZ33lUuL19L)aJi6+p=_dwQopJbH!#7XAGiZ5~j!(~4(iB+ut diff --git a/tests/cache/.run/cache/npm/d/50/3c799f495786fbc96054087c25adb50d b/tests/cache/.run/cache/npm/d/50/3c799f495786fbc96054087c25adb50d deleted file mode 100644 index ef6b1877d09426f3cfb3f7155f82ff050c168568..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 578 zcmeHE%}T>S5RRgkg}lSibCc{QHirc-*4RQVEo3hq*Dxe8&1Oj_#XgnK;}iH8x-|vq zJNPj$Ki_;G40G#^c>4NyJC_&f`;7E+yNb*EbU}n_TSvH=f5<*^7jV$hKY4 zM8>v}ZOTBirBd5SgdAedVYBjCj{O092@iUYza$S+*dD3sOq7JeMeMUjO(-EB%+%>1 zN9$6Yf=DD6@-BwOTKR0=8A3zBGn$er31ap)Q%CCzw6(js&{R9`t{|jfPd)0^XPMHa rgwrdXMi&(ZC%3-aNwCAK6HTGj?}0AyK1n(EnUlS5RRgkg}lSibCc{QX$}isY(ooGTF72Ju3<>hHp!As#XNv_-^9o88N3TV zhHgzk`VM{!%+EL92g6)D17=@un^Sp~zE6lh2LAQ^^TlyC7xCrQNK8g&yZ?>jux0un zp(HYOn{NZtn<_Bd!qaS_)H)D8hmdnvEnSvj_k^8<}klkE}OOuVME>>HU*Uu#N=/dev/null; } - -# 端口探活:直到能建立连接再往下走(HEAD 探活,不会写进上游请求日志)。 -wait_up() { # $1=port $2=最大尝试次数(默认 80,步长 0.1s) - local port="$1" n="${2:-80}" i=0 - until curl -s -o /dev/null -I --max-time 1 "http://127.0.0.1:$port/" 2>/dev/null; do - i=$((i+1)); [ "$i" -ge "$n" ] && return 1; sleep 0.1 - done - return 0 -} - -build_if_needed() { - [ -f "$MODULE" ] && [ "${FORCE_BUILD:-0}" != "1" ] && return 0 - echo "── 编译 ipass 模块(首次/强制)──" - [ -x "$CARGO" ] || { echo "错误:找不到 cargo(用 CARGO= 指定)" >&2; exit 1; } - [ -z "${LIBCLANG_PATH:-}" ] && [ -d /Library/Developer/CommandLineTools/usr/lib ] \ - && export LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib - ( cd "$REPO/rust" \ - && NGINX_SOURCE_DIR="$NGX_SRC" NGINX_BUILD_DIR="$NGX_SRC/objs" \ - LIBCLANG_PATH="${LIBCLANG_PATH:-}" "$CARGO" build ) || return 1 - echo " ✅ $MODULE" -} - -start() { - build_if_needed || { echo "❌ 模块编译失败" >&2; exit 1; } - [ -x "$NGINX_BIN" ] || { echo "错误:nginx 不存在 $NGINX_BIN" >&2; exit 1; } - stop_quiet - - mkdir -p "$RUN/logs" "$RUN/data" "$RUN/audit" "$RUN/cache" - cp "$HERE"/fixtures/*.json "$RUN/data/" 2>/dev/null - : > "$RUN/upstream.log" - - # 上游表:六生态的 route 全指向假上游(route 名:docker 是 v2)。 - # 不配 = 该路由 503(这是 access 层的闸门,不是 bug)。 - cache_write_upstreams "$RUN" "http://127.0.0.1:${UP_PORT}" \ - go cargo cargo-dl pypi pypi-files npm maven docker || exit 1 - # 渲染生产 conf(端口错开自动回归,避免互相踩) - cache_render_prod_conf "$RUN" "$PORT" "$MODULE" - - # ⚠️ 假上游必须**脱离本进程组**(start_new_session ≈ setsid)。 - # 本脚本常被「起一次就返回」的外壳调用(CI、编辑器里的命令执行器)。这类外壳在 - # 命令返回后会清理自己进程组里的后台任务——普通 `cmd &` 会连坐被杀,于是 - # nginx(daemon 化,已脱离)活着、所有路由 502「Connection refused」、 - # upstream.log 是 0 行,看着像缓存/网关坏了,其实只是上游没了。实测踩过。 - UPSTREAM_LOG="$RUN/upstream.log" UPSTREAM_PORT="$UP_PORT" \ - "$PY" - "$PY" "$HERE/mock_upstream.py" "$RUN/logs/upstream.out" "$RUN/upstream.pid" <<'P' -import os, subprocess, sys -py, script, out, pidf = sys.argv[1:5] -with open(out, "ab") as f: - p = subprocess.Popen([py, script], stdout=f, stderr=f, - env=dict(os.environ), start_new_session=True) -open(pidf, "w").write(str(p.pid)) -P - wait_up "$UP_PORT" || { echo "❌ 假上游端口 $UP_PORT 未就绪"; exit 1; } - - # 出厂管理员口令只在 users 表**为空**时播种。本脚本先拷了夹具 users.json(里面已有 - # admin),所以下面这个默认值对本地试跑**不生效**——登录用的是夹具里那把口令, - # 别把它当成登录密码去找(`admin` 子命令会说明)。 - export ADMIN_INIT_PASSWORD="${ADMIN_INIT_PASSWORD:-dev_admin_pw}" - if ! "$NGINX_BIN" -p "$RUN" -c conf/nginx.cache.conf -t 2>>"$RUN/logs/error.log"; then - echo "❌ nginx -t 失败:"; tail -15 "$RUN/logs/error.log"; exit 1 - fi - "$NGINX_BIN" -p "$RUN" -c conf/nginx.cache.conf - wait_up "$PORT" || { echo "❌ nginx 端口 $PORT 未就绪"; tail -15 "$RUN/logs/error.log"; exit 1; } - - echo "✅ 已启动" - echo " 管理台 $BASE/admin (在页面上配上游 / 一键复制下游地址)" - echo " 入口 $BASE" - echo " 制品 $BASE// 例如 $BASE/go/@v/list $BASE/v2/library/alpine/manifests/latest" - echo " (要带 Key: -H \"$AUTH\")" - echo " 读数 $BASE/api/v1/cache/stats (账号态,同样要带 Key)" - echo " 缓存盘 $RUN/cache//(真实文件)" - echo " 假上游 $(pid_of "$RUN/upstream.pid") nginx $(pid_of "$RUN/logs/nginx.pid")" - echo " 试一下: bash tests/cache/dev-server.sh demo" -} - -stop_quiet() { - [ -f "$RUN/logs/nginx.pid" ] && kill "$(pid_of "$RUN/logs/nginx.pid")" 2>/dev/null - [ -f "$RUN/upstream.pid" ] && kill "$(pid_of "$RUN/upstream.pid")" 2>/dev/null - sleep 0.4 -} - -stop() { - stop_quiet - rm -f "$RUN/logs/nginx.pid" "$RUN/upstream.pid" - echo "✅ 已停止(缓存文件保留在 $RUN/cache)" -} - -status() { - local np up - np=$(pid_of "$RUN/logs/nginx.pid"); up=$(pid_of "$RUN/upstream.pid") - if [ -n "$np" ] && kill -0 "$np" 2>/dev/null; then echo "nginx : 运行中 pid=$np"; else echo "nginx : 未运行"; fi - if [ -n "$up" ] && kill -0 "$up" 2>/dev/null; then echo "假上游 : 运行中 pid=$up"; else echo "假上游 : 未运行"; fi - curl -s -o /dev/null -w "探活 : HTTP %{http_code}\n" "$BASE/admin" 2>/dev/null || echo "探活 : 不可达" -} - -demo() { - echo "── 六生态各请求两次(第一次 MISS 回源,第二次 HIT 走盘)──" - echo " (route 前缀 ≠ 生态名:docker 生态走 /v2/)" - printf "%-8s %-10s %-10s %s\n" 生态 首请求 二次 内容一致 - for pair in $ROUTE_PAIRS; do - e=${pair%%:*}; pre=${pair#*:} - h1="$RUN/.h1"; b1="$RUN/.b1"; h2="$RUN/.h2"; b2="$RUN/.b2" - curl -s -D "$h1" -o "$b1" -H "$AUTH" "$BASE${pre}/pkg-a" - s1=$(grep -i '^X-Cache-Status:' "$h1" | tr -d '\r' | awk '{print $2}') - curl -s -D "$h2" -o "$b2" -H "$AUTH" "$BASE${pre}/pkg-a" - s2=$(grep -i '^X-Cache-Status:' "$h2" | tr -d '\r' | awk '{print $2}') - same=$([ "$(cat "$b1")" = "$(cat "$b2")" ] && echo yes || echo NO) - printf "%-8s %-10s %-10s %s\n" "$e" "${s1:-?}" "${s2:-?}" "$same" - done - rm -f "$RUN"/.h1 "$RUN"/.b1 "$RUN"/.h2 "$RUN"/.b2 - echo - echo "本轮回源次数(空缓存时首轮应为 6;全 HIT 则为 0): $(wc -l < "$RUN/upstream.log" | tr -d ' ')" - echo "(首轮想看到 6→0 的对比:先 purge 再 demo)" -} - -show_stats() { - local raw - raw=$(curl -s -H "$AUTH" "$BASE/api/v1/cache/stats") - [ -z "$raw" ] && { echo "拿不到响应,先 start"; return 1; } - echo "$raw" | grep -q '"code":401' && { - echo "❌ 账号态 stats 需要 Key;本机夹具里 alice 的 Key 应可用。原始响应:$raw"; return 1; } - # 注:用 % 格式化而非 f-string——shell 单引号内嵌双引号在旧版 python 会炸 - STATS="$raw" "$PY" -c ' -import json, os -d = json.loads(os.environ["STATS"]) -data = d.get("data", d) -be = data.get("by_ecosystem", {}) -print("%-9s%6s%6s%7s" % ("生态", "HIT", "MISS", "其他")) -for eco in ["go", "cargo", "pypi", "npm", "maven", "docker", "global"]: - m = be.get(eco, {}) - other = sum(v for k, v in m.items() if k not in ("HIT", "MISS")) - print("%-9s%6d%6d%7d" % (eco, m.get("HIT", 0), m.get("MISS", 0), other)) -' 2>/dev/null || echo "原始响应:$raw" -} - -show_files() { - echo "── 缓存盘真实文件($RUN/cache,levels=1:2 两级散列)──" - for e in go cargo pypi npm maven docker; do - n=$(find "$RUN/cache/$e" -type f 2>/dev/null | wc -l | tr -d ' ') - sz=$(du -sh "$RUN/cache/$e" 2>/dev/null | awk '{print $1}') - printf " %-8s %3s 个文件 %s\n" "$e" "$n" "${sz:-0B}" - done - echo - echo " 样例(最深 3 条):" - find "$RUN/cache" -type f 2>/dev/null | head -3 | sed 's|^| |' - echo " 说明:文件名是 proxy_cache_key 的 md5,内容即上游响应体;" - echo " 计量计数**不在**这里,而在 ipass 共享内存(所以重启 nginx 会清零读数,缓存文件仍在)。" -} - -purge() { - echo "── 清空缓存(开源 nginx 无 proxy_cache_purge,直接删目录;文件没了下次自动 MISS 回源)──" - for e in go cargo pypi npm maven docker; do - rm -rf "$RUN/cache/$e"; mkdir -p "$RUN/cache/$e" - done - echo "✅ 已清空 $RUN/cache/*(共享内存计数未清零,需 restart nginx)" -} - -urls() { - cat < -Maven mirror settings.xml http://HOST/maven # POM/JAR 同源 ✅ -Docker /etc/docker/daemon.json registry-mirrors: ["https://HOST"] - ⚠️ 上游 route 是 /v2/(registry v2 协议),且 registry-mirrors 只对 - docker.io 官方镜像生效;docker 客户端会先向 auth.docker.io 换 - 短期 Bearer token,网关按 $cache_auth 透传给上游(自己的 sk_ 不外传) -cargo 稀疏索引 [registries.crates-io] index = "sparse+http://HOST/cargo/" - ⚠️ 索引里 config.json 的 dl 是绝对地址 static.crates.io, - .crate 包本体不会自动走缓存(见 docs/cache-usage.md 的边界说明) -pip 索引 pip install -i http://HOST/pypi/simple/ - ⚠️ 包本体在 files.pythonhosted.org(绝对地址),同上属边界 -EOF -} - -logs() { tail -n "${1:-30}" "$RUN/logs/error.log"; } - -admin() { - cat <,与真实转发共用「拼目标 + 换凭据」逻辑, - 所以这里通 = 真实请求能到上游 - · 命中计数 共享内存读数(HIT/MISS/…)。**重启 nginx 归零**,但磁盘缓存文件还在, - 所以「计数清零」不等于「缓存没了」 - 对照命令行 - 制品请求 curl -H "$AUTH" $BASE/go/@v/list - 该请求读数 $BASE/api/v1/cache/stats (账号态,同样要带 Key) - 磁盘缓存 $RUN/cache//(真实文件,文件名 = proxy_cache_key 的 md5) -EOF -} - -case "${1:-help}" in - start) start ;; - stop) stop ;; - status) status ;; - demo) demo ;; - stats) show_stats ;; - files) show_files ;; - urls) urls ;; - admin) admin ;; - purge) purge ;; - logs) logs "${2:-30}" ;; - clean) stop; rm -rf "$RUN"; echo "✅ 已删除 $RUN" ;; - help|"") sed -n '3,24p' "$0" | sed 's/^# \{0,1\}//' ;; - *) echo "用法: bash tests/cache/dev-server.sh {start|stop|status|demo|stats|files|urls|admin|purge|logs|clean}" >&2; exit 2 ;; -esac diff --git a/tests/cache/e2e-auth.sh b/tests/cache/e2e-auth.sh deleted file mode 100644 index 5151137..0000000 --- a/tests/cache/e2e-auth.sh +++ /dev/null @@ -1,279 +0,0 @@ -#!/bin/bash -# ============================================================================ -# e2e-auth.sh —— 统一缓存网关的「统一 Key + 动态上游 + 磁盘缓存」端到端回归 -# -# 与既有 run.sh / test-cache.sh 的区别:那两个跑的是**静态上游版** conf -# (proxy_pass 写死 https://上游)。本脚本跑的是**变量上游版** -# (proxy_pass $cache_target + 上游表来自共享内存),也就是「UI 配上游 + -# 动态注入」这条链路,覆盖: -# -# [1] conf 能起(变量式 proxy_pass + resolver + ssl 模块在编 + alias www/) -# [2] 未配上游的路由 → 503(而不是空 $cache_target 导致的 500) -# [3] 缺 Key → 401;错的 Key → 401 -# [4] 对的路由 + 对的下行 sk_ → 200,且**路径前缀被正确剥掉**转发给上游 -# [5] 同一个 URL 第二次 → HIT 且**不再回源**(读假上游请求日志断言) -# [6] 上游收到的是配置里的 Authorization,**不是**网关自己的 sk_ -# [7] 配额与 LLM/apix 共用一把(carol 的 llm_rpm=2 → 第 3 次 429) -# [8] 管理台页面可达;管理 API 无会话 → 401;账号态 API 带 sk_ → 200 -# [9] 管理台**运行时**配上游(POST /api/admin/cache/save)→ 下一个请求 -# 立即生效、不需 reload/重启(「动态注入」的验收点) -# -# 用法:bash tests/cache/e2e-auth.sh -# 只动 tests/cache/.run-auth 与两个临时端口,可重复跑。 -# -# ⚠️ 两个移植性坑(本脚本已规避,改脚本时别踩回去): -# 1. 不要用 `sed -i ''` 做批量替换:本机虽有 BSD sed,但 PATH 上可能被 -# 注入 shim,`-i ''` 的语义会变(报 `sed: : No such file or directory`)。 -# 这里一律用 python 读写文件。 -# 2. macOS 自带 bash 3.2 会把紧跟 `$var` 之后的多字节字符算进变量名 -# (`echo "${c2})"` → `c2?: unbound variable`)。变量后紧跟中文时必须写 -# `${c2}`。 -# ============================================================================ -set -uo pipefail - -# ⚠️ 本机环境里设了 HTTP_PROXY / HTTPS_PROXY(指向 127.0.0.1:57869 的本地代理)。 -# curl 会把 `http://127.0.0.1:<随机端口>` 这种地址也丢给代理,代理连不上就回 -# 502 —— 表现为「网关全是 502」的假失败,与网关本身无关。统一强制不走代理, -# 同时 JSON 体里那个 "upstream connect failed..." 也是代理的错误页而不是网关的。 -curl() { command curl --noproxy '*' "$@"; } - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -REPO=$(cd "$HERE/../.." && pwd) -RUN="$HERE/.run-auth" -NGX="$REPO/build/nginx-1.30.4/objs/nginx" -MOD="$REPO/rust/target/debug/libipass_gateway.dylib" - -# 受管 python(隔离目录);退回系统 python3 -PY=/Users/rong/.workbuddy/binaries/python/versions/3.13.12/bin/python3 -[ -x "$PY" ] || PY=$(command -v python3) - -pick_port() { "$PY" <<'P' -import socket -s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close() -P -} -PORT=${CACHE_TEST_PORT:-$(pick_port)} -UP_PORT=${UPSTREAM_PORT:-$(pick_port)} -ADMIN_PW=${ADMIN_INIT_PASSWORD:-Auth-e2e-2026} - -ALICE=sk_alice_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -CAROL=sk_carol_cccccccccccccccccccccccccccccccccccccccccccccc - -pass=0; fail=0 -ok() { echo " ✅ $1"; pass=$((pass+1)); } -bad() { echo " ❌ $1"; fail=$((fail+1)); } -check(){ if [ "$2" = "$3" ]; then ok "$1(${2})"; else bad "$1:期望 ${3},实际 ${2}"; fi } - -echo "== 0. 准备独立前缀(端口 nginx=${PORT} 上游=${UP_PORT})==" -[ -x "$NGX" ] || { echo "缺少 nginx:${NGX}(先跑 build/build-nginx-ssl.sh)"; exit 1; } -[ -f "$MOD" ] || { echo "缺少模块:${MOD}(先 cargo build)"; exit 1; } -[ -x "$PY" ] || { echo "缺少 python3"; exit 1; } -mkdir -p "$RUN"/{conf,data,logs,audit} "$RUN"/cache/{go,cargo,pypi,npm,maven,docker} -# ⚠️ 必须清掉上一次运行留下的磁盘缓存。缓存目录在 .run-auth 下跨次留存, -# 不清的话「断言上游收到了什么请求」会静默失效——请求直接命中上次的副本、 -# 根本不回源,UP_LOG 是空的,于是 grep 恒不匹配,报出来的却是「上游没收/ -# 下发了头」这类假故障(实测:第二次跑必挂在 step 9)。 -# find -delete 只作用于本次测试自己的 cache/ 子树。 -# ⚠️ 别改成 `rm -rf "$RUN"`:本机批量删除护栏超阈值会**拒绝整个删除且不报错**, -# 于是上一轮副本存活 → 首次请求全是 HIT 的假失败。 -find "$RUN/cache" -type f -delete >/dev/null -# 自检:清完必须为空。否则「本次是 MISS」的断言会静默失真(读不到上游日志)。 -if [ -n "$(find "$RUN/cache" -type f -print -quit 2>/dev/null)" ]; then - echo "❌ 缓存目录没清干净($RUN/cache)——上游日志类断言不可信" >&2; exit 1 -fi -cp "$HERE/fixtures/users.json" "$RUN/data/users.json" - -# conf 渲染:借 lib-render.sh(与 Tier2 / dev-server 同一套渲染器)。 -# ★ 这里**刻意不再自己写一份**:曾因为两个脚本各抄一份,生产 conf 换成变量 -# 上游后 Tier2 仍在按静态上游渲染、整层挂掉。要改渲染规则就改 lib-render.sh。 -CACHE_PY="$PY"; export CACHE_PY -# shellcheck source=tests/cache/lib-render.sh -source "$HERE/lib-render.sh" -cache_render_prod_conf "$RUN" "$PORT" "$MOD" - -# 上游表:直接写文件(等价于管理台「保存」的结果——模块 zone_load 会装载它)。 -# 只配 go / cargo 两条,**故意留 npm 不配**,用于验证「未配 = 503」。 -cat > "$RUN/data/cache-upstreams.json" < "$UP_LOG" -UPSTREAM_LOG="$UP_LOG" UPSTREAM_PORT="$UP_PORT" \ - "$PY" "$HERE/mock_upstream.py" > "$RUN/logs/upstream.out" 2>&1 & -UP_PID=$! -for _ in 1 2 3 4 5 6 7 8 9 10; do - curl -s -o /dev/null "http://127.0.0.1:${UP_PORT}/__ready" && break - sleep 0.3 -done -kill -0 "$UP_PID" 2>/dev/null && ok "假上游已起(pid ${UP_PID})" || bad "假上游没起来" - -cleanup() { - "$NGX" -p "$RUN" -c conf/nginx.cache.conf -s quit >/dev/null 2>&1 - kill "$UP_PID" >/dev/null 2>&1 -} -trap cleanup EXIT - -echo "== 2. nginx -t(变量上游版 conf)==" -"$NGX" -p "$RUN" -c conf/nginx.cache.conf -t 2>&1 | sed 's/^/ /' -"$NGX" -p "$RUN" -c conf/nginx.cache.conf -t >/dev/null 2>&1 && ok "配置语法通过" || bad "配置语法失败" - -echo "== 3. 启动 ==" -ADMIN_INIT_PASSWORD="$ADMIN_PW" "$NGX" -p "$RUN" -c conf/nginx.cache.conf -sleep 1 -B="http://127.0.0.1:${PORT}" -code() { curl -s -o /dev/null -w '%{http_code}' "$@"; } - -echo "== 4. 管理台与 API ==" -check "GET /admin 页面可达" "$(code "$B/admin")" "200" -curl -s "$B/admin" | grep -q "制品缓存" && ok "页面含「制品缓存」(www alias 生效)" || bad "页面内容不对(alias www/ 解析错?)" -check "GET / 302 到 /admin" "$(code "$B/")" "302" -check "管理 API 无会话 → 401" "$(code "$B/api/admin/cache")" "401" -check "账号态 stats 无 Key → 401" "$(code "$B/api/v1/cache/stats")" "401" -check "账号态 stats 带 sk_ → 200" "$(code -H "X-API-Key: ${ALICE}" "$B/api/v1/cache/stats")" "200" - -echo "== 5. 未配上游的路由 → 503(不是 500)==" -check "GET /npm/ 未配上游" "$(code -H "Authorization: Bearer ${ALICE}" "$B/npm/foo")" "503" - -echo "== 6. 鉴权:缺 Key / 错 Key ==" -check "GET /go/ 无 Key" "$(code "$B/go/@v/list")" "401" -check "GET /go/ 错 Key" "$(code -H 'Authorization: Bearer sk_nope' "$B/go/@v/list")" "401" -check "GET /go/ x-api-key 携带位可用" "$(code -H "x-api-key: ${ALICE}" "$B/go/@v/list")" "200" - -echo "== 7. 动态上游注入:路径前缀剥离 + query 进键 + 上游 Host ==" -: > "$UP_LOG" -# ⚠️ 必须断言这次是 MISS。step 6 已经拉过 `/go/@v/list`(无 query),如果 -# query 没进缓存键,这次带 `?x=1` 的请求会**直接命中上一步的缓存**: -# 既不回源(UP_LOG 是空的),返回体也是没 query 那条 —— 于是下面两条 -# 「路径不对 / 没收到 Authorization」会一起报错,看起来像转发坏了, -# 实际上是缓存键不完整。用 MISS 把这两类故障分开定位。 -curl -s -o "$RUN/logs/h7.body" -D "$RUN/logs/h7.head" \ - -H "Authorization: Bearer ${ALICE}" "$B/go/@v/list?x=1" -body=$(cat "$RUN/logs/h7.body") -st7=$(tr -d '\r' < "$RUN/logs/h7.head" | awk 'tolower($1)=="x-cache-status:"{print $2}') -echo " 上游返回体: ${body}" -check "带 query 的首次请求是 MISS(query 参与缓存键)" "$st7" "MISS" -case "$body" in - "ECHO:GET /@v/list?x=1") ok "上游收到的是剥掉 /go 之后的路径,且 query 未被吞" ;; - *) bad "上游收到的路径不对(期望 ECHO:GET /@v/list?x=1)" ;; -esac -if grep -q "auth=Bearer upstream-secret-token" "$UP_LOG"; then - ok "上游收到配置里的 Authorization" -else - bad "上游没收到配置的 Authorization(实际:$(cat "$UP_LOG"))" -fi -if grep -q "$ALICE" "$UP_LOG"; then - bad "❌ 网关把自己的下行 sk_ 透传给了上游!" -else - ok "网关自己的 sk_ 没有泄漏给上游" -fi - -echo "== 8. 磁盘缓存:第二次必须 HIT 且不再回源 ==" -n1=$(wc -l < "$UP_LOG" | tr -d ' ') -st=$(curl -s -o /dev/null -D - -H "Authorization: Bearer ${ALICE}" "$B/go/@v/list?x=1" | tr -d '\r' | awk 'tolower($1)=="x-cache-status:"{print $2}') -n2=$(wc -l < "$UP_LOG" | tr -d ' ') -check "第二次 X-Cache-Status" "$st" "HIT" -check "上游请求数没有增加" "$n2" "$n1" - -echo "== 9. 无凭据路由(cargo):不下发 Authorization ==" -: > "$UP_LOG" -curl -s -o /dev/null -D "$RUN/logs/h9.head" -H "Authorization: Bearer ${ALICE}" "$B/cargo/config.json" -st9=$(tr -d '\r' < "$RUN/logs/h9.head" | awk 'tolower($1)=="x-cache-status:"{print $2}') -check "无凭据路由首次是 MISS(否则断言读不到上游日志)" "$st9" "MISS" -if grep -q "auth=-" "$UP_LOG"; then - ok "未配凭据的路由:上游收到的 Authorization 为空" -else - bad "未配凭据却下发了 Authorization(实际:$(cat "$UP_LOG"))" -fi - -echo "== 10. 配额与 LLM/apix 共用一把(carol llm_rpm=2)==" -c1=$(code -H "Authorization: Bearer ${CAROL}" "$B/go/@v/list") -c2=$(code -H "Authorization: Bearer ${CAROL}" "$B/go/@v/list") -c3=$(code -H "Authorization: Bearer ${CAROL}" "$B/go/@v/list") -check "carol 第 3 次触发每分钟限流" "$c3" "429" -echo " (carol 前两次:${c1} / ${c2})" - -echo "== 11. 管理台运行时配上游:不 reload 立即生效(UI 的「配上游」按钮走这条)==" -CJ="$RUN/logs/cookie.jar" -lg=$(curl -s -o "$RUN/logs/login.body" -w '%{http_code}' -c "$CJ" \ - -X POST -d "username=admin&password=123456" "$B/api/admin/login") -check "管理员登录(夹具口令 123456)" "$lg" "200" -ov=$(curl -s -b "$CJ" "$B/api/admin/cache") -check "登录后 GET /api/admin/cache" "$(code -b "$CJ" "$B/api/admin/cache")" "200" -echo "$ov" | grep -q '"entry"' \ - && ok "快照含网关入口 entry(UI「一键复制下游地址」的基址)" \ - || bad "快照缺 entry,管理台拼不出下游地址" -check "快照路由条数(8 个生态各一行)" \ - "$(echo "$ov" | grep -o '"route"' | wc -l | tr -d ' ')" "8" -# npm 在第 5 步验证过「未配 = 503」;现在用管理 API 从运行时配上它。 -# 这一步是「动态注入」的验收点:**不 reload、不重启**,下一个请求就该通。 -check "配置前 /npm/ 仍是 503" "$(code -H "Authorization: Bearer ${ALICE}" "$B/npm/foo")" "503" -# 请求体刻意用 **JSON**:与 www/assets/cache.js 的编辑弹窗完全一致 -# (IP.api 发 JSON;不带 key 字段 = 保留原值)。用表单编码测就漏掉了 UI 那条路。 -sv=$(curl -s -b "$CJ" -X POST -H 'Content-Type: application/json' \ - -d "{\"route\":\"npm\",\"base\":\"http://127.0.0.1:${UP_PORT}\",\"name\":\"e2e-runtime\",\"enabled\":true}" \ - "$B/api/admin/cache/save") -echo " save 返回: ${sv}" -echo "$sv" | grep -q '"active":true' \ - && ok "保存返回 active=true(共享内存已写穿)" \ - || bad "保存后未生效(active 非 true):${sv}" -check "配置后 /npm/ 立刻 200(免 reload)" "$(code -H "Authorization: Bearer ${ALICE}" "$B/npm/foo")" "200" -my=$(curl -s -H "X-API-Key: ${ALICE}" "$B/api/v1/cache") -echo "$my" | grep -q '"route":"npm"' \ - && ok "账号态列表出现 npm(带可复制的下游 URL)" \ - || bad "账号态列表没出现 npm:${my}" - -echo "== 12. 连通性探针(管理台「测试」按钮):以 GET 转发 + 带上游表凭据 ==" -# 管理台点「测试」= POST /api/admin/cache/test,模块用 internal_redirect 转到 -# /_cache_test/。而 internal_redirect **保留原方法**——不改方法的话探针会以 -# POST 打到上游:① 是写语义,探测不该有副作用;② 制品拉取全是 GET/HEAD,探针结果 -# 不代表真实流量;③ 实测后果最误导:假上游只实现 do_GET,探针拿到 501,管理台显示 -# 「测试失败」,而它其实连通正常。所以这里把「方法必须是 GET」钉成一条断言。 -# 顺带验探针带的是**上游表里的**凭据(go 路由配了 Bearer upstream-secret-token), -# 即探针与真实转发共用同一套换 Key 逻辑。 -: > "$UP_LOG" -pr=$(curl -s -o "$RUN/logs/probe.body" -w '%{http_code}' -b "$CJ" \ - -X POST -H 'Content-Type: application/json' -d '{}' \ - "$B/api/admin/cache/test?route=go") -check "上游状态原样透传(假上游 GET / → 200)" "$pr" "200" -echo " 上游返回体: $(cat "$RUN/logs/probe.body")" -if grep -q "^GET / " "$UP_LOG"; then - ok "上游收到 GET /(方法被钉成 GET,不是 POST)" -else - bad "探针未以 GET 到达上游(实际:$(cat "$UP_LOG"))" -fi -if grep -q "auth=Bearer upstream-secret-token" "$UP_LOG"; then - ok "探针带上的是上游表里的凭据" -else - bad "探针没带配置凭据(实际:$(cat "$UP_LOG"))" -fi - -echo -echo "==== 结果:通过 ${pass},失败 ${fail} ====" -[ "$fail" -eq 0 ] || exit 1 diff --git a/tests/cache/fixtures/api-proxies.json b/tests/cache/fixtures/api-proxies.json deleted file mode 100644 index 59c3871..0000000 --- a/tests/cache/fixtures/api-proxies.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "items": { - "search": { - "supplier": "vendor-a", - "asset_id": "searxng-search", - "base": "http://127.0.0.1:18999", - "key": "ak_test_supplier_key", - "name": "SearXNG 免费搜索", - "desc": "服务端聚合 Google / Brave / Bing", - "params": ["q"], - "enabled": true, - "created_at": 1750000000 - }, - "offline": { - "supplier": "vendor-a", - "asset_id": "disabled-asset", - "base": "http://127.0.0.1:18999", - "key": "ak_test_supplier_key", - "name": "已停用的代理", - "desc": "enabled=false,热路径必须查不到", - "params": [], - "enabled": false, - "created_at": 1750000000 - } - } -} diff --git a/tests/cache/fixtures/domains.json b/tests/cache/fixtures/domains.json deleted file mode 100644 index fe51488..0000000 --- a/tests/cache/fixtures/domains.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/tests/cache/fixtures/llm-upstreams.json b/tests/cache/fixtures/llm-upstreams.json deleted file mode 100644 index 13aa3bd..0000000 --- a/tests/cache/fixtures/llm-upstreams.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "openai": { - "base": "http://127.0.0.1:18999", - "models": ["gpt-4o", "gpt-4o-mini"], - "auth": "Bearer sk-UPSTREAM-REAL-SECRET", - "enabled": true, - "note": "本地靶机;auth 是占位值,不是真密钥", - "created_at": 1757500000 - }, - "other": { - "base": "http://127.0.0.1:18999/llm", - "models": ["claude-3-5-sonnet"], - "auth": "Bearer sk-OTHER-UPSTREAM", - "enabled": true, - "note": "不在 alice 白名单内;base 带路径,用于验证路径拼接与模型发现过滤", - "created_at": 1757500000 - }, - "downstream": { - "base": "http://127.0.0.1:18999", - "models": ["should-not-appear"], - "auth": "", - "enabled": false, - "note": "已停用,用于验证「停用即从共享内存摘除」→ 404,且其模型不应出现在模型发现里", - "created_at": 1757500000 - }, - "deepseeklike": { - "base": "http://127.0.0.1:18999/v1", - "models": ["ds-chat"], - "auth": "Bearer sk-DS-REAL", - "enabled": true, - "note": "base 自带 /v1(厂商文档的常见写法),用于验证版本段不重复拼接", - "created_at": 1757500000 - } -} diff --git a/tests/cache/fixtures/users.json b/tests/cache/fixtures/users.json deleted file mode 100644 index 303aa4f..0000000 --- a/tests/cache/fixtures/users.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "admin": { - "username": "admin", - "role": "admin", - "salt": "5a1b2c3d4e5f60718293a4b5c6d7e8f9", - "pwd_hash": "062b45d8f3cbef3d30464859355401bb37193868dc42eb941de86855416ab5e8", - "api_key": "sk_admin_0000000000000000000000000000000000000000000000ab", - "allowed_models": [], - "temp_grant_until": 0, - "created_at": 1757500000 - }, - "alice": { - "username": "alice", - "display_name": "爱丽丝", - "role": "user", - "salt": "00112233445566778899aabbccddeeff", - "pwd_hash": "00", - "api_key": "sk_alice_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "allowed_models": [ - "openai" - ], - "temp_grant_until": 0, - "created_at": 1757500000 - }, - "bob": { - "username": "bob", - "role": "user", - "salt": "ffeeddccbbaa99887766554433221100", - "pwd_hash": "00", - "api_key": "sk_bob_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "allowed_models": [], - "temp_grant_until": 0, - "created_at": 1757500000 - }, - "carol": { - "username": "carol", - "role": "user", - "salt": "112233445566778899aabbccddeeff00", - "pwd_hash": "00", - "api_key": "sk_carol_cccccccccccccccccccccccccccccccccccccccccccccc", - "allowed_models": [], - "llm_rpm": 2, - "llm_daily": 0, - "temp_grant_until": 0, - "created_at": 1757500000 - }, - "dave": { - "username": "dave", - "role": "user", - "salt": "aabbccddeeff00112233445566778899", - "pwd_hash": "00", - "api_key": "sk_dave_dddddddddddddddddddddddddddddddddddddddddddddddd", - "allowed_models": [], - "llm_rpm": 0, - "llm_daily": 2, - "temp_grant_until": 0, - "created_at": 1757500000 - } -} diff --git a/tests/cache/lib-render.sh b/tests/cache/lib-render.sh deleted file mode 100644 index 1a97c2e..0000000 --- a/tests/cache/lib-render.sh +++ /dev/null @@ -1,119 +0,0 @@ -#!/bin/bash -# ============================================================================ -# lib-render.sh —— 把**生产 conf**(conf/*.conf)渲染进一个测试前缀(被 source) -# -# 为什么必须有这个文件:测试里出现的 conf 有两类—— -# * **生产 conf 的副本**(conf/nginx.cache.conf 等,改端口/路径后跑); -# * **测试自己的 conf**(tests/cache/nginx.cache.local.conf,纯数据面)。 -# 前者曾一度被两个脚本各抄一份渲染逻辑,结果是「生产 conf 换成变量上游了, -# 某一个脚本还在按静态上游渲染」——同一份配置在两个地方漂移(实测: -# Tier2 因此整层挂掉,表现像模块坏了,其实是它在验一个已作废的形态)。 -# 所以:**任何要用生产 conf 的测试,都 from 这里借渲染**,别再手抄。 -# -# 用法: -# CACHE_PY= # 可选,默认 python3 -# source "$(dirname "$0")/lib-render.sh" -# cache_render_prod_conf "$RUN" "$PORT" "$MODULE" -# -# 只定义函数,不产生副作用(不建目录以外的动作、不启动任何东西)。 -# ============================================================================ - -# 仓库根:按本文件自身位置解析,调用方无需传 -CACHE_REPO=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) - -# 渲染生产 conf 到 $1(RUN),对外端口 $2(PORT),模块路径 $3(MODULE)。 -# -# 改动的只有「机器相关」的东西:模块路径、日志/pid/data/audit/缓存目录、 -# 监听端口、worker 数。 -# **不改任何业务指令**——所以本渲染跑通 = 生产 conf 跑通。 -cache_render_prod_conf() { - local run="$1" port="$2" mod="$3" - local py="${CACHE_PY:-python3}" - - mkdir -p "$run"/{conf,data,logs,audit} "$run"/cache/{go,cargo,pypi,npm,maven,docker} - mkdir -p "$run/conf/tls" - - cp "$CACHE_REPO/conf/nginx.cache.conf" "$run/conf/" - cp "$CACHE_REPO/conf/server.cache.conf" "$run/conf/" - cp "$CACHE_REPO/conf/cache-routes.conf" "$run/conf/" - cp "$CACHE_REPO/conf/cache-common.conf" "$run/conf/" - cp "$CACHE_REPO/build/nginx-1.30.4/conf/mime.types" "$run/conf/" 2>/dev/null - - # 管理台静态资源:cache-routes.conf 的 alias 写的是**相对 prefix** 的 www/, - # 所以测试前缀下要有个 www 能解析到仓库的 www/。 - [ -e "$run/www" ] || ln -s "$CACHE_REPO/www" "$run/www" - - # ⚠️ 用 python 而非 BSD sed:本机 PATH 上可能有 sed shim,`sed -i ''` 语义会变。 - "$py" - "$run" "$mod" "$port" <<'P' -import re, sys, pathlib -run, mod, port = sys.argv[1], sys.argv[2], sys.argv[3] -c = pathlib.Path(run, "conf") - -p = c / "nginx.cache.conf" -s = p.read_text() -s = re.sub(r"^load_module .*$", "load_module %s;" % mod, s, flags=re.M) -s = re.sub(r"^\s*error_log .*$", " error_log %s/logs/error.log info;" % run, s, flags=re.M) -s = re.sub(r"^\s*pid .*$", " pid %s/logs/nginx.pid;" % run, s, flags=re.M) -s = re.sub(r"^\s*access_log .*$", " access_log %s/logs/cache.log cache;" % run, s, flags=re.M) -s = re.sub(r"ipass_data_dir .*", "ipass_data_dir %s/data;" % run, s) -s = re.sub(r"ipass_audit_dir .*", "ipass_audit_dir %s/audit;" % run, s) -s = s.replace("/var/cache/ipass-cache", "%s/cache" % run) -s = s.replace("worker_processes auto;", "worker_processes 1;") -s = re.sub(r"^(\s*include )/usr/local/nginx/conf/tls/\*\.conf;", - r"\1%s/conf/tls/*.conf;" % run, s, flags=re.M) -p.write_text(s) - -p = c / "server.cache.conf" -s = p.read_text().replace("listen 8080;", "listen %s;" % port) -p.write_text(s) -print(" rendered: nginx.cache.conf / server.cache.conf -> %s (port %s)" % (run, port)) -P -} - -# 合法**路由名**(= plugin-cache config::ROUTES 的那 8 个)。 -# ⚠️ 路由名 ≠ URI 前缀,也 ≠ 生态名,三者在 docker 上最容易混: -# URI 前缀 /v2/ ← 路由名 docker ← 生态 docker -# `route_of_seg` 把首段 `v2` 映射成路由名 `docker`,所以上游表的键是 -# **docker**。写成 `v2` 不报错、不告警,只会让该路由恒 503(「上游尚未配置」), -# 看起来像配置没保存。实测踩过,故在此硬校验。 -CACHE_ROUTES="go cargo cargo-dl pypi pypi-files npm maven docker" - -# 写上游表(等价于管理台「保存」的结果;模块 zone_load 会装载它)。 -# $1 = RUN 目录 -# $2 = 上游基址,如 http://127.0.0.1:18999 -# $3.. = 要配的**路由名**(见上;docker 是 `docker` 不是 `v2`) -# 留空则写空表(所有路由 → 503)。 -cache_write_upstreams() { - local run="$1" base="$2"; shift 2 - local route out="" sep="" bad="" - for route in "$@"; do - case " $CACHE_ROUTES " in - *" $route "*) ;; - *) bad="$bad $route" ;; - esac - done - if [ -n "$bad" ]; then - echo "❌ 非法路由名:${bad}(合法值:${CACHE_ROUTES};注意 docker 的路由名是 docker,不是 v2)" >&2 - return 1 - fi - for route in "$@"; do - out="${out}${sep} \"${route}\": { \"base\": \"${base}\", \"key\": \"\", - \"mode\": \"proxy\", \"name\": \"测试上游 ${route}\", \"desc\": \"假上游\", - \"enabled\": true, \"note\": \"\", \"created_at\": 1757500000, \"updated_at\": 1757500000 }" - sep=", -" - done - mkdir -p "$run/data" - { - echo '{' - echo ' "items": {' - printf '%s\n' "$out" - echo ' }' - echo '}' - } > "$run/data/cache-upstreams.json" - # 立刻自检:这个文件是「静默失效」的重灾区——写坏了模块不会报错, - # 只会让所有路由 503(看起来像网关坏了)。 - "${CACHE_PY:-python3}" -c 'import json,sys; json.load(open(sys.argv[1]))' \ - "$run/data/cache-upstreams.json" 2>/dev/null \ - || { echo "❌ 上游表 JSON 非法:$run/data/cache-upstreams.json" >&2; return 1; } -} diff --git a/tests/cache/mock_upstream.py b/tests/cache/mock_upstream.py deleted file mode 100755 index 9f68aff..0000000 --- a/tests/cache/mock_upstream.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python3 -# ============================================================================ -# 确定性假上游:统一缓存自测用。 -# -# - 任何 GET 返回 200,body = "ECHO: ?#", -# 长度固定且随 path 变化,便于校验「不同生态/路径各存各的」。 -# - 支持 Range:返回 206 + Content-Range,验证大层/分片缓存。 -# - 记录每个请求到 UPSTREAM_LOG(method path),用于断言「HIT 不再回源」。 -# - 不带任何 registry 协议细节(Docker token 舞、cargo 稀疏索引等), -# 那些是生产 conf 的关注点;本靶机只验证「代理缓存」这一层本身。 -# ============================================================================ -import os -import sys -import urllib.parse -from http.server import BaseHTTPRequestHandler, HTTPServer - -PORT = int(os.environ.get("UPSTREAM_PORT", "18999")) -LOG = os.environ.get("UPSTREAM_LOG", "") - - -def log_line(s: str): - if LOG: - with open(LOG, "a") as f: - f.write(s + "\n") - - -class H(BaseHTTPRequestHandler): - def _body(self): - # 默认用完整请求行生成确定性内容;长度随 path 变化。 - # `?bytes=N` 时返回**恰好 N 字节**(可复现的填充内容,内容随 path 变化), - # 用于验证缓存容量淘汰(max_size 触发 LRU)——没有这个大响应能力, - # 「超容后会不会被淘汰」就没法在本地证明。 - path = self.path - n = 0 - if "?" in path: - qs = urllib.parse.parse_qs(urllib.parse.urlparse(path).query) - try: - n = int(qs.get("bytes", ["0"])[0]) - except ValueError: - n = 0 - if n > 0: - seed = f"ECHO:{self.command} {path}\n".encode("utf-8") - return (seed * (n // len(seed) + 1))[:n] - return f"ECHO:{self.command} {path}".encode("utf-8") - - def do_GET(self): - # 行首仍是 `GET `(既有断言依赖这个前缀),末尾补一个 auth= 字段: - # 用来证伪「网关把自己的下行 sk_ 透传给了上游」——这是镜像型缓存最要命的 - # 一类泄漏,必须在靶机上有一根静态钉子。 - log_line(f"GET {self.path} auth={self.headers.get('Authorization', '-')}") - full = self._body() - rng = self.headers.get("Range") - if rng and rng.startswith("bytes="): - # 简单支持单段 range:bytes=start-end - spec = rng[len("bytes="):] - try: - start_s, end_s = spec.split("-") - start = int(start_s) if start_s else 0 - end = int(end_s) if end_s else len(full) - 1 - end = min(end, len(full) - 1) - chunk = full[start:end + 1] - self.send_response(206) - self.send_header("Content-Range", f"bytes {start}-{end}/{len(full)}") - self.send_header("Content-Length", str(len(chunk))) - self.send_header("Content-Type", "application/octet-stream") - self.send_header("ETag", f'"{len(full)}"') - self.end_headers() - self.wfile.write(chunk) - return - except Exception: - pass - self.send_response(200) - self.send_header("Content-Length", str(len(full))) - self.send_header("Content-Type", "application/octet-stream") - self.send_header("ETag", f'"{len(full)}"') - self.send_header("Cache-Control", "public, max-age=3600") - self.end_headers() - self.wfile.write(full) - - # 静默日志,避免刷屏 - def log_message(self, *args): - pass - - -if __name__ == "__main__": - srv = HTTPServer(("127.0.0.1", PORT), H) - print(f"mock upstream on {PORT}", flush=True) - srv.serve_forever() diff --git a/tests/cache/nginx.cache.local.conf b/tests/cache/nginx.cache.local.conf deleted file mode 100644 index f8f6276..0000000 --- a/tests/cache/nginx.cache.local.conf +++ /dev/null @@ -1,105 +0,0 @@ -# ============================================================================ -# 统一制品缓存 · 本机自测配置(不加载 ipass 模块,纯 nginx proxy_cache) -# -# 验证对象:六类生态的「代理缓存」这一层本身(MISS→HIT / Range / PURGE / -# X-Cache-Status)。生产环境由 server.cache.conf 在每 location 加 `ipass_cache on` -# 接入 ipass 的身份/配额/命中计量,缓存引擎完全一致。 -# -# 上游统一指向本机 mock_upstream.py(18999);按生态分 zone 与缓存键前缀, -# 各生态互不串档。PURGE 用 map 限制仅 127.0.0.1(无需 rewrite 模块)。 -# ============================================================================ - -worker_processes 1; -error_log @RUN@/logs/error.log warn; - -events { - worker_connections 1024; -} - -http { - default_type application/octet-stream; - access_log off; - - - # 六类生态各自的缓存区(热层=本地盘;S3 冷层预留见生产 conf) - proxy_cache_path @RUN@/cache/go levels=1:2 keys_zone=go:10m max_size=1g inactive=7d; - proxy_cache_path @RUN@/cache/cargo levels=1:2 keys_zone=cargo:10m max_size=1g inactive=7d; - proxy_cache_path @RUN@/cache/pypi levels=1:2 keys_zone=pypi:10m max_size=1g inactive=7d; - proxy_cache_path @RUN@/cache/npm levels=1:2 keys_zone=npm:10m max_size=1g inactive=7d; - proxy_cache_path @RUN@/cache/maven levels=1:2 keys_zone=maven:10m max_size=1g inactive=7d; - proxy_cache_path @RUN@/cache/docker levels=1:2 keys_zone=docker:10m max_size=5g inactive=7d; - - # 假上游(确定性,支持 Range) - upstream mock { server 127.0.0.1:18999; } - - server { - listen 127.0.0.1:18083; - server_name _; - - # ---------- go (Go modules proxy) ---------- - location /go/ { - proxy_pass http://mock/; - proxy_cache go; - proxy_cache_key $scheme$proxy_host$request_uri; - proxy_cache_valid 200 302 1h; - proxy_ignore_headers Cache-Control Expires Set-Cookie; - proxy_force_ranges on; - add_header X-Cache-Status $upstream_cache_status; - } - - # ---------- cargo (Rust crates) ---------- - location /cargo/ { - proxy_pass http://mock/; - proxy_cache cargo; - proxy_cache_key $scheme$proxy_host$request_uri; - proxy_cache_valid 200 302 1h; - proxy_ignore_headers Cache-Control Expires Set-Cookie; - proxy_force_ranges on; - add_header X-Cache-Status $upstream_cache_status; - } - - # ---------- pypi (Python) ---------- - location /pypi/ { - proxy_pass http://mock/; - proxy_cache pypi; - proxy_cache_key $scheme$proxy_host$request_uri; - proxy_cache_valid 200 302 1h; - proxy_ignore_headers Cache-Control Expires Set-Cookie; - proxy_force_ranges on; - add_header X-Cache-Status $upstream_cache_status; - } - - # ---------- npm (Node) ---------- - location /npm/ { - proxy_pass http://mock/; - proxy_cache npm; - proxy_cache_key $scheme$proxy_host$request_uri; - proxy_cache_valid 200 302 1h; - proxy_ignore_headers Cache-Control Expires Set-Cookie; - proxy_force_ranges on; - add_header X-Cache-Status $upstream_cache_status; - } - - # ---------- maven (Java) ---------- - location /maven/ { - proxy_pass http://mock/; - proxy_cache maven; - proxy_cache_key $scheme$proxy_host$request_uri; - proxy_cache_valid 200 302 1h; - proxy_ignore_headers Cache-Control Expires Set-Cookie; - proxy_force_ranges on; - add_header X-Cache-Status $upstream_cache_status; - } - - # ---------- docker (OCI registry;生产含 token 透传,自测仅 GET 缓存) ---------- - location /docker/ { - proxy_pass http://mock/; - proxy_cache docker; - proxy_cache_key $scheme$proxy_host$request_uri; - proxy_cache_valid 200 302 1h; - proxy_ignore_headers Cache-Control Expires Set-Cookie; - proxy_force_ranges on; - add_header X-Cache-Status $upstream_cache_status; - } - } -} diff --git a/tests/cache/run.sh b/tests/cache/run.sh deleted file mode 100755 index b3b5d69..0000000 --- a/tests/cache/run.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/bin/bash -# ============================================================================ -# 统一制品缓存 · 本机回归统一入口 -# -# bash tests/cache/run.sh # 跑全部(Tier1 + Tier2 + 生产配置校验) -# bash tests/cache/run.sh tier1 # 只跑 Tier1(不加载模块,纯 proxy_cache) -# bash tests/cache/run.sh tier2 # 只跑 Tier2(加载 ipass 模块 + 管理 API) -# bash tests/cache/run.sh prod # 只跑生产配置语法校验(conf/nginx.cache.conf) -# -# 想**手动**玩(保留实例、自己 curl、翻缓存文件)请用 dev-server.sh: -# bash tests/cache/dev-server.sh start|demo|stats|files|purge|stop -# -# 自动完成:cargo build(带 nginx-sys 所需环境变量)→ 依次跑两层 → 汇总。 -# 可覆盖:NGINX_BIN / MODULE / CARGO / PY -# ============================================================================ -set -uo pipefail - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -REPO=$(cd "$HERE/../.." && pwd) - -NGX_SRC="$REPO/build/nginx-1.30.4" -NGX_OBJS="$NGX_SRC/objs" -NGINX_BIN=${NGINX_BIN:-$NGX_OBJS/nginx} -MODULE=${MODULE:-$REPO/rust/target/debug/libipass_gateway.dylib} - -CARGO=${CARGO:-} -if [ -z "$CARGO" ]; then - for c in cargo "$HOME/.cargo/bin/cargo"; do - command -v "$c" >/dev/null 2>&1 && { CARGO=$c; break; } - done -fi -[ -n "$CARGO" ] || { echo "错误:找不到 cargo" >&2; exit 1; } - -# bindgen 需要 libclang;macOS CommandLineTools 自带 -if [ -z "${LIBCLANG_PATH:-}" ] && [ -d /Library/Developer/CommandLineTools/usr/lib ]; then - export LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib -fi - -PY=${PY:-python3} - -build() { - echo "── 编译 ipass Rust 模块(含 plugin-cache)──" - ( cd "$REPO/rust" \ - && NGINX_SOURCE_DIR="$NGX_SRC" \ - NGINX_BUILD_DIR="$NGX_OBJS" \ - LIBCLANG_PATH="${LIBCLANG_PATH:-}" \ - "$CARGO" build ) || return 1 - [ -f "$MODULE" ] || { echo "错误:模块未产出 $MODULE" >&2; return 1; } - echo " ✅ 模块就绪:$MODULE" -} - -run_tier1() { echo; echo "══════ Tier 1 · 纯 nginx proxy_cache ══════"; \ - NGINX_BIN="$NGINX_BIN" PY="$PY" bash "$HERE/test-cache.sh"; } -run_tier2() { echo; echo "══════ Tier 2 · ipass 托管可观测 ══════"; \ - NGINX_BIN="$NGINX_BIN" MODULE="$MODULE" PY="$PY" bash "$HERE/test-ipass-cache.sh"; } -run_prod() { echo; echo "══════ 生产配置语法校验 ══════"; \ - NGINX_BIN="$NGINX_BIN" MODULE="$MODULE" bash "$HERE/validate-prod-conf.sh"; } - -WHICH=${1:-all} -rc=0 - -case "$WHICH" in - tier1) run_tier1; rc=$? ;; - tier2) build && { run_tier2; rc=$?; } ;; - prod) build && { run_prod; rc=$?; } ;; - all|"") - build || { echo "编译失败,先修 Rust" >&2; exit 1; } - run_tier1; rc=$? - run_tier2; rc2=$?; [ "$rc2" -ne 0 ] && rc=$rc2 - run_prod; rc3=$?; [ "$rc3" -ne 0 ] && rc=$rc3 - ;; - *) echo "用法: bash tests/cache/run.sh [tier1|tier2|prod|all]" >&2; exit 2 ;; -esac - -echo -[ "$rc" -eq 0 ] && echo "✅ 统一制品缓存:全部通过" || echo "❌ 有断言失败(退出码 ${rc:-0})" -exit $rc diff --git a/tests/cache/test-cache-capacity.sh b/tests/cache/test-cache-capacity.sh deleted file mode 100644 index 96c30c3..0000000 --- a/tests/cache/test-cache-capacity.sh +++ /dev/null @@ -1,535 +0,0 @@ -#!/bin/bash -# ============================================================================ -# test-cache-capacity.sh —— 验证「容量管理」这条链路 -# -# 回答的问题:缓存占了多大?快不快满?满了谁负责清?能不能现在就腾空间? -# -# 与前两个脚本的分工: -# verify-cache-eviction.sh —— nginx 会不会**自动**淘汰(LRU / inactive) -# 本脚本 —— 网关能不能**看见**容量、能不能**手动**清 -# -# 本脚本断言的事(都直连真实实例,走管理 API): -# [1] 容量面板能识别出全部 proxy_cache 区,且**上限来自 conf**(本测把 npm -# 改成 max_size=1m,接口必须如实报 1m —— 证明读数来自 nginx 而非硬编码) -# [2] 空缓存基线:占用 0 / 条目 0 / 水位 0% / 级别 ok -# [3] 写入 3×200KB 后:占用与条目上涨,且**nginx 记账与磁盘实测量级一致** -# [4] `?scan=1` 的磁盘实测 ≈ `du` 实测(±5%) -# [5] 手动清理:删除的是**文件**,`cache/` 目录必须还在(这是踩过的坑: -# 目录被删后 nginx 不会自愈,此后每次写缓存都 [crit] 并断开客户端) -# [6] 清理后 nginx 记账**滞后**——如实断言它还没归零(把已知行为固化成契约, -# 将来 nginx 行为变了,这条会先亮) -# [7] 清理后同一 URL 再请求:MISS → 200,且 error.log 里没有 crit/mkdir 失败 -# [8] 越权与参数校验:账号态(sk_)与未登录都进不来;zone 写错报 400 -# -# bash tests/cache/test-cache-capacity.sh -# -# ⚠️ 自起自停一个独立实例(端口 18087 / 假上游 18996),不碰 dev-server; -# 只杀自己记下的 pid,不用 pkill(会误伤别人正在看的实例)。 -# ============================================================================ -set -uo pipefail - -curl() { command curl -s --noproxy '*' "$@"; } - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -REPO=$(cd "$HERE/../.." && pwd) -RUN="$HERE/.run-cap" -PORT=18087 -UP_PORT=18996 -NGX="$REPO/build/nginx-1.30.4/objs/nginx" -MOD="$REPO/rust/target/debug/libipass_gateway.dylib" -PY=${PY:-python3} -CACHE_PY="$PY"; export CACHE_PY -# shellcheck source=tests/cache/lib-render.sh -source "$HERE/lib-render.sh" - -SK=sk_alice_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -AUTH="Authorization: Bearer $SK" -ADMIN_PW=123456 -BODY_SZ=204800 # 每个对象的字节数(200KB) -N=3 # 灌几个对象 - -pass=0; fail=0 -ok() { echo " ✅ $*"; pass=$((pass+1)); } -bad() { echo " ❌ $*"; fail=$((fail+1)); } - -cleanup() { - [ -f "$RUN/logs/nginx.pid" ] && kill "$(cat "$RUN/logs/nginx.pid")" 2>/dev/null - [ -f "$RUN/upstream.pid" ] && kill "$(cat "$RUN/upstream.pid")" 2>/dev/null - sleep 0.3 -} -trap cleanup EXIT - -echo "==== 容量管理验证(独立实例 :${PORT})====" - -# ---------- 1. 渲染生产 conf,把 npm 的上限改小到可断言 ---------- -cache_write_upstreams "$RUN" "http://127.0.0.1:${UP_PORT}" npm maven || exit 1 -cache_render_prod_conf "$RUN" "$PORT" "$MOD" >/dev/null -# ⚠️ 必须拷夹具账号:否则用户表为空 → alice 的 sk_ 不被认 → 全部 401, -# 而 401 在 access 阶段返回、压根不进代理层(症状是「缓存目录 0 文件」)。 -cp "$HERE"/fixtures/*.json "$RUN/data/" 2>/dev/null - -"$PY" - "$RUN" <<'P' -import re, sys, pathlib -p = pathlib.Path(sys.argv[1], "conf", "nginx.cache.conf") -out = [] -for line in p.read_text().splitlines(True): - if "keys_zone=npm:" in line: - line = re.sub(r"max_size=\S+", "max_size=1m", line) - line = re.sub(r"inactive=\S+", "inactive=1h", line) - out.append(line) -p.write_text("".join(out)) -print(" [conf] npm: max_size=1m(用于断言「上限读数来自 conf」)") -P -find "$RUN/cache" -type f -delete >/dev/null 2>&1 - -# ---------- 2. 起假上游(脱离进程组)与 nginx ---------- -mkdir -p "$RUN/logs" -: > "$RUN/upstream.log" -UPSTREAM_LOG="$RUN/upstream.log" UPSTREAM_PORT="$UP_PORT" \ -"$PY" - "$PY" "$HERE/mock_upstream.py" "$RUN/logs/upstream.out" "$RUN/upstream.pid" <<'P' -import os, subprocess, sys -py, script, out, pidf = sys.argv[1:5] -with open(out, "ab") as f: - p = subprocess.Popen([py, script], stdout=f, stderr=f, - env=dict(os.environ), start_new_session=True) -open(pidf, "w").write(str(p.pid)) -P -wait_up() { local p=$1 i=0; until curl -s -o /dev/null --max-time 1 "http://127.0.0.1:$p/$2" 2>/dev/null; do i=$((i+1)); [ $i -ge 80 ] && return 1; sleep 0.1; done; } -wait_up "$UP_PORT" "" || { echo "❌ 假上游未就绪"; exit 1; } - -ADMIN_INIT_PASSWORD=x "$NGX" -p "$RUN" -c conf/nginx.cache.conf -t 2>>"$RUN/logs/error.log" \ - || { echo "❌ nginx -t 失败"; tail -10 "$RUN/logs/error.log"; exit 1; } -ADMIN_INIT_PASSWORD=x "$NGX" -p "$RUN" -c conf/nginx.cache.conf -wait_up "$PORT" "" || { echo "❌ nginx 未就绪"; tail -10 "$RUN/logs/error.log"; exit 1; } -echo " 实例就绪(假上游 ${UP_PORT})" - -B="http://127.0.0.1:$PORT" -CJ="$RUN/.cookies" -xc() { tr -d '\r' | awk 'tolower($1)=="x-cache-status:"{print $2}'; } -: > "$RUN/logs/error.log.mark"; wc -l < "$RUN/logs/error.log" > "$RUN/logs/error.log.mark" - -# 管理会话 -curl -c "$CJ" -X POST -H 'Content-Type: application/json' \ - -d "{\"username\":\"admin\",\"password\":\"$ADMIN_PW\"}" "$B/api/admin/login" >/dev/null -# 快照 → 写进文件,后续用 jq 式的 python 取值(本机无 jq 也稳) -snap() { # snap [scan] → $RUN/.snap.json - if [ "${1:-}" = "scan" ]; then - curl -b "$CJ" -o "$RUN/.snap.json" "$B/api/admin/cache?scan=1" - else - curl -b "$CJ" -o "$RUN/.snap.json" "$B/api/admin/cache" - fi -} -# 从快照里取一个 zone 的字段:jz -jz() { - "$PY" - "$RUN/.snap.json" "$1" "$2" <<'P' -import json, sys -d = json.load(open(sys.argv[1])) -cap = d.get("data", d).get("capacity", {}) -for z in cap.get("zones", []): - if z.get("zone") == sys.argv[2]: - v = z.get(sys.argv[3]) - print("null" if v is None else v) - sys.exit(0) -print("MISSING") -P -} -jtot() { "$PY" -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["data"]["capacity"]["totals"].get(sys.argv[2],""))' "$RUN/.snap.json" "$1"; } - -# =========================================================================== -echo -echo "== 1. 容量区识别与上限来源 ==" -snap -"$PY" - "$RUN/.snap.json" <<'P' -import json, sys -d = json.load(open(sys.argv[1])) -cap = d.get("data", d).get("capacity", {}) -zones = cap.get("zones", []) -print(" available=%s scanned=%s zones=%d" % (cap.get("available"), cap.get("scanned"), len(zones))) -for z in zones: - print(" %-8s limit=%-10s used=%-8s entries=%-4s idx=%-9s level=%s dir=%s" % ( - z["zone"], z["limit_bytes"], z["used_bytes"], z["entries"], - z["keys_zone_bytes"], z["level"], z["dir"])) -P - -nzones=$(jtot zones) -if [ "${nzones:-0}" = "6" ]; then - ok "识别出 6 个 proxy_cache 区(go/cargo/pypi/npm/maven/docker)" -else - bad "识别的区数量不是 6(实际 ${nzones:-?})—— 容量读数会缺" -fi - -npm_limit=$(jz npm limit_bytes) -if [ "${npm_limit:-0}" = "1048576" ]; then - ok "npm 上限 = 1048576 字节(= conf 里的 max_size=1m)—— 读数确实来自 nginx 配置" -else - bad "npm 上限读数不对(实际 ${npm_limit:-?},期望 1048576)" -fi - -npm_dir=$(jz npm dir) -if [ "$npm_dir" = "$RUN/cache/npm" ]; then - ok "npm 的磁盘目录读数正确(${npm_dir})" -else - bad "npm 目录读数不对(实际 ${npm_dir:-?},期望 $RUN/cache/npm)" -fi - -npm_routes=$("$PY" - "$RUN/.snap.json" <<'P' -import json, sys -d = json.load(open(sys.argv[1])) -for z in d["data"]["capacity"]["zones"]: - if z["zone"] == "cargo": - print(",".join(z["routes"])) -P -) -if [ "$npm_routes" = "cargo,cargo-dl" ]; then - ok "共享 zone 的路由列全(cargo 区 → cargo,cargo-dl)" -else - bad "cargo 区的路由列表不对(实际 ${npm_routes:-?})" -fi - -# =========================================================================== -echo -echo "== 2. 空缓存基线 ==" -snap -used0=$(jz npm used_bytes); ent0=$(jz npm entries); pct0=$(jz npm pct); lv0=$(jz npm level) -if [ "${used0:-x}" = "0" ] && [ "${ent0:-x}" = "0" ] && [ "${pct0:-x}" = "0.0" ] && [ "${lv0:-x}" = "ok" ]; then - ok "空缓存:占用 0 / 条目 0 / 水位 0.0% / 级别 ok" -else - bad "空缓存基线不对(used=${used0:-?} entries=${ent0:-?} pct=${pct0:-?} level=${lv0:-?})" -fi - -# =========================================================================== -echo -echo "== 3. 写入后(${N} × ${BODY_SZ}B = $((N*BODY_SZ/1024))KB)==" -sample=$(curl -s -o /dev/null -w '%{http_code}' -H "$AUTH" "$B/npm/probe?bytes=1024") -echo " 样本请求 HTTP ${sample}(期望 200;401=Key 不被认,503=上游未配)" -[ "$sample" = "200" ] || { echo "❌ 前置检查失败,后面的容量断言没有意义"; exit 1; } - -for i in $(seq 1 $N); do - curl -s -o /dev/null -H "$AUTH" "$B/npm/cap/$i?bytes=$BODY_SZ" -done -sleep 1 -snap -used1=$(jz npm used_bytes); ent1=$(jz npm entries); pct1v=$(jz npm pct) -du1=$(du -sk "$RUN/cache/npm" 2>/dev/null | awk '{print $1}') -echo " nginx 记账:${used1} 字节 / ${ent1} 条目 / ${pct1v}% · du 实测:${du1}KB" - -if [ "${used1:-0}" -gt 0 ] && [ "${ent1:-0}" -ge "$N" ]; then - ok "占用与条目都涨上来了(${used1}B / ${ent1} 条)" -else - bad "写入后读数没涨(used=${used1:-?} entries=${ent1:-?})" -fi -# 记账 vs 磁盘:两边口径不同,不能要求逐字节相等—— -# * nginx 按**块(bsize=4K)向上取整**记账,且只算**文件**; -# * `du` 还包含目录项(levels=1:2 会多出几层目录,每个 4K)。 -# 所以判据取一个宽松窗口:「在同一量级」,跨出去才说明两套口径有一个是错的。 -du_bytes=$((du1 * 1024)) -win=$(( (N + 16) * 4096 )) -lo=$(( du_bytes - win )); [ "$lo" -lt 0 ] && lo=0 -hi=$(( du_bytes + win )) -if [ "${used1:-0}" -ge "$lo" ] && [ "${used1:-0}" -le "$hi" ]; then - ok "记账与磁盘同量级(记账 ${used1}B ∈ [${lo}, ${hi}],du=${du_bytes}B)" -else - bad "记账与磁盘量级不符(记账 ${used1}B 不在 [${lo}, ${hi}])" -fi - -# =========================================================================== -echo -echo "== 4. 磁盘实测(?scan=1)==" -snap scan -disk1=$(jz npm disk_bytes); dfiles=$(jz npm disk_files) -# 期望文件数 = N + 1:前面那发探针(/npm/probe)也是 200,同样被缓存 -EXPECT_FILES=$((N + 1)) -echo " disk_bytes=${disk1} disk_files=${dfiles}(期望 ${EXPECT_FILES})du=${du1}KB" -if [ "${dfiles:-0}" -eq "$EXPECT_FILES" ]; then - ok "磁盘实测文件数 = ${dfiles}(探针 1 + 灌入 ${N})" -else - bad "磁盘实测文件数不对(${dfiles:-?},期望 ${EXPECT_FILES})" -fi -lo=$(( du_bytes * 95 / 100 )); hi=$(( du_bytes * 105 / 100 + 4096 )) -if [ "${disk1:-0}" -ge "$lo" ] && [ "${disk1:-0}" -le "$hi" ]; then - ok "磁盘实测 ≈ du(${disk1}B vs ${du_bytes}B,±5%)" -else - bad "磁盘实测与 du 差太多(${disk1:-?} vs ${du_bytes})" -fi -# 总量里也要有磁盘数(证明 totals 汇总没漏) -tdisk=$(jtot disk_bytes) -if [ -n "${tdisk:-}" ] && [ "$tdisk" != "None" ]; then - ok "totals 里带了磁盘实测汇总(${tdisk}B)" -else - bad "totals 缺磁盘实测汇总" -fi - -# =========================================================================== -echo -echo "== 5. 越权与参数校验 ==" -c1=$(curl -s -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \ - -d '{"zone":"npm"}' "$B/api/admin/cache/purge") -c2=$(curl -s -o /dev/null -w '%{http_code}' -X POST -H "Authorization: Bearer $SK" \ - -H 'Content-Type: application/json' -d '{"zone":"npm"}' "$B/api/admin/cache/purge") -[ "$c1" = "401" ] && ok "未登录调 purge → 401" || bad "未登录调 purge 得到 ${c1}(期望 401)" -[ "$c2" = "401" ] && ok "账号态 sk_ 调 purge → 401(管理动作不给普通 Key)" \ - || bad "账号态调 purge 得到 ${c2}(期望 401)—— 这是个安全口子" - -r=$(curl -s -b "$CJ" -X POST -H 'Content-Type: application/json' -d '{"zone":"nope"}' \ - "$B/api/admin/cache/purge") -echo " zone=nope → $r" -case "$r" in - *未知*|*unknown*|*已知*) ok "未知 zone 被拒(400 且说清了已知值)" ;; - *) bad "未知 zone 没被拒:$r" ;; -esac -r=$(curl -s -b "$CJ" -X POST -H 'Content-Type: application/json' -d '{}' "$B/api/admin/cache/purge") -case "$r" in - *缺少*) ok "缺 zone 参数被拒" ;; - *) bad "缺 zone 参数没被拒:$r" ;; -esac - -# =========================================================================== -echo -echo "== 6. 手动清空 npm 区(只删文件,目录必须留下)==" -r=$(curl -s -b "$CJ" -X POST -H 'Content-Type: application/json' -d '{"zone":"npm"}' \ - "$B/api/admin/cache/purge") -echo " $r" -fdel=$("$PY" -c 'import json,sys; print(json.loads(sys.argv[1])["data"]["total"]["files"])' "$r" 2>/dev/null) -bdel=$("$PY" -c 'import json,sys; print(json.loads(sys.argv[1])["data"]["total"]["bytes"])' "$r" 2>/dev/null) -left=$(find "$RUN/cache/npm" -type f 2>/dev/null | wc -l | tr -d ' ') -[ "${fdel:-0}" -ge "$N" ] && ok "接口报告删除了 ${fdel} 个文件 / ${bdel} 字节" \ - || bad "接口报告的删除数不对(${fdel:-?})" -[ "${left:-9}" = "0" ] && ok "磁盘上文件已清零" || bad "磁盘还有 ${left} 个文件没删掉" -if [ -d "$RUN/cache/npm" ]; then - ok "★ cache/npm 目录仍在(删目录会让该路由 [crit] 直到 restart,这里必须保留)" -else - bad "★★ cache/npm 目录被删了 —— 这条路由接下来每次写缓存都会失败" -fi -snap scan -disk2=$(jz npm disk_bytes) -oneeds=$(jz npm entries) -[ "${disk2:-x}" = "0" ] && ok "磁盘实测归零(disk_bytes=0)" || bad "磁盘实测没归零(${disk2:-?})" -# ★ 已知行为:nginx 的记账**不会**因文件被外部删除而立刻回落。 -# 节点要等「该 key 再被访问(发现文件不在)」或「条目到期」才回收。 -# 这里把它固化成契约:如果哪天 nginx 改了这行为,这条会先亮,提示我们更新文档。 -if [ "${oneeds:-0}" -gt 0 ]; then - ok "nginx 记账仍滞后(entries=${oneeds},磁盘已 0)—— 与文档一致:面板不会假装账已平" -else - echo " ⚠️ nginx 记账已同步归零(entries=0):行为与预期不同,请更新 docs/§容量与淘汰" -fi - -# 清空后**再访问**:必须 MISS→200(正确性:不会返回脏数据、不会 500) -echo " -- 清空后重新拉一次(应 MISS 回源重建)--" -st=$(curl -s -D - -o /dev/null -H "$AUTH" "$B/npm/cap/1?bytes=$BODY_SZ" | xc) -code=$(curl -s -o /dev/null -w '%{http_code}' -H "$AUTH" "$B/npm/cap/1?bytes=$BODY_SZ") -[ "$st" = "MISS" ] && ok "清空后再请求 = MISS(不会返回脏数据)" || bad "清空后再请求是 ${st}(期望 MISS)" -[ "$code" = "200" ] && ok "清空后再请求 200(缓存重建正常)" || bad "清空后再请求 HTTP ${code}" -# 关键:清理动作绝不能把目录搞坏 —— 检查 nginx 有没有报 crit / mkdir 失败 -ncrit=$(tail -n +"$(cat "$RUN/logs/error.log.mark")" "$RUN/logs/error.log" 2>/dev/null | grep -c "crit\|mkdir() failed") -if [ "${ncrit:-1}" = "0" ]; then - ok "error.log 无 crit / mkdir 失败(目录结构完好)" -else - bad "error.log 出现 ${ncrit} 条 crit/mkdir 失败 —— 目录被破坏了" - tail -5 "$RUN/logs/error.log" -fi - -# =========================================================================== -echo -echo "== 7. zone=all 全清 ==" -r=$(curl -s -b "$CJ" -X POST -H 'Content-Type: application/json' -d '{"zone":"all"}' \ - "$B/api/admin/cache/purge") -fdel=$("$PY" -c 'import json,sys; print(json.loads(sys.argv[1])["data"]["total"]["files"])' "$r" 2>/dev/null) -leftall=$(find "$RUN/cache" -type f 2>/dev/null | wc -l | tr -d ' ') -dirs=$(ls "$RUN/cache" | tr '\n' ' ') -[ "${leftall:-9}" = "0" ] && ok "全部区已清空(含 maven 等)" || bad "仍有 ${leftall} 个文件" -[ "$dirs" = "cargo docker go maven npm pypi " ] \ - && ok "六个缓存目录都还在(${dirs})" \ - || bad "目录结构异常:$dirs" -echo " (all 删除 ${fdel} 个文件)" - -echo - -# =========================================================================== -# 按制品失效(purge 的细一档粒度) -# 「上游把某个版本发坏了」时真正要扔的只有几个文件,清掉整个生态 = 几十 GB 白重拉。 -# =========================================================================== -echo "== 8. 按制品失效(先预览、再确认;只删文件不删目录)==" - -IV="$B/api/admin/cache/invalidate" -nfiles() { find "$RUN/cache" -type f 2>/dev/null | wc -l | tr -d ' '; } -# inv [curl 额外参数...] → 打 HTTP 码到 stdout,响应落到 $RUN/.inv.json -inv() { - local body=$1; shift - curl -s -o "$RUN/.inv.json" -w '%{http_code}' -X POST -H 'Content-Type: application/json' \ - -d "$body" "$@" "$IV" -} -iv() { "$PY" -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["data"]["total"][sys.argv[2]])' "$RUN/.inv.json" "$1"; } - -# 造四个可区分的条目:两个 npm、一个 maven,外加一个「不该被误伤」的对照 -curl -s -o /dev/null -H "$AUTH" "$B/npm/keep-a/1?bytes=$BODY_SZ" -curl -s -o /dev/null -H "$AUTH" "$B/npm/dropme/1?bytes=$BODY_SZ" -curl -s -o /dev/null -H "$AUTH" "$B/maven/keep-m/1?bytes=$BODY_SZ" -sleep 0.3 -n0=$(nfiles) -echo " (起始 ${n0} 个缓存文件)" - -# --- 8.1 预览:必须只算不删 --- -code=$(inv '{"match":"dropme"}' -b "$CJ") -[ "$code" = "200" ] && ok "预览返回 200" || bad "预览返回 ${code}" -[ "$(iv matched)" = "1" ] && ok "预览命中 1 个(dropme)" || bad "预览命中数不对($(iv matched))" -[ "$(iv deleted)" = "0" ] && ok "★ 预览 deleted=0(未传 apply 时绝不删)" || bad "预览竟然删了 $(iv deleted) 个" -[ "$(nfiles)" = "$n0" ] && ok "★ 预览后磁盘文件数不变(${n0})" || bad "预览动了盘:$n0 → $(nfiles)" - -# 命中的 key 要回显出来 —— 否则用户没法确认表达式对不对 -if "$PY" - "$RUN/.inv.json" <<'P' -import json, sys -d = json.load(open(sys.argv[1]))["data"] -if "keys" not in json.dumps(d): - print(" ❌ 响应里没有 keys 字段(用户看不到命中什么,等于没法确认表达式)") - sys.exit(1) -keys = [k for it in d["items"] for k in it["keys"]] -good = any("dropme" in k for k in keys) -print((" ✅ " if good else " ❌ ") + "预览回显命中的 cache key:" + (keys[0] if keys else "(空)")) -sys.exit(0 if good else 1) -P -then pass=$((pass+1)); else fail=$((fail+1)); fi - -# --- 8.2 真删:只删命中项,对照项必须留下 --- -code=$(inv '{"match":"dropme","apply":1}' -b "$CJ") -[ "$code" = "200" ] && ok "失效返回 200" || bad "失效返回 ${code}" -[ "$(iv deleted)" = "1" ] && ok "应用后删除 1 个" || bad "删除数不对($(iv deleted))" -[ "$(nfiles)" = "$((n0-1))" ] && ok "磁盘文件数 $n0 → $((n0-1))(只少了命中的那个)" \ - || bad "文件数异常:$n0 → $(nfiles)" -if [ -d "$RUN/cache/npm" ]; then - ok "★ cache/npm 目录仍在(与 purge 同一条硬约束)" -else - bad "★★ cache/npm 目录被删了 —— 该路由接下来会持续 [crit]" -fi -# 对照项没被误伤:keep-a 仍在盘上(按 key 找) -if "$PY" - "$RUN/cache" <<'P' -import glob, os, sys -root = sys.argv[1] -found = [] -for p in glob.glob(os.path.join(root, "**", "*"), recursive=True): - if os.path.isfile(p): - with open(p, "rb") as f: - h = f.read(4096) - i = h.find(b"KEY: ") - if i >= 0: - found.append(h[i + 5:h.find(b"\n", i)].decode("utf-8", "replace")) -hit = [k for k in found if "keep-a" in k] -print((" ✅ " if hit else " ❌ ") + "对照项 keep-a 未被误伤(现存 " + str(len(found)) + " 个 key)") -sys.exit(0 if hit else 1) -P -then pass=$((pass+1)); else fail=$((fail+1)); fi - -# --- 8.3 删后重新拉:MISS → 200,缓存重建(正确性不受影响)--- -st=$(curl -s -D - -o /dev/null -H "$AUTH" "$B/npm/dropme/1?bytes=$BODY_SZ" | xc) -code=$(curl -s -o /dev/null -w '%{http_code}' -H "$AUTH" "$B/npm/dropme/1?bytes=$BODY_SZ") -[ "$st" = "MISS" ] && ok "失效后再请求 = MISS(不会返回脏数据)" || bad "失效后再请求是 ${st}(期望 MISS)" -[ "$code" = "200" ] && ok "失效后再请求 200(缓存重建正常)" || bad "失效后再请求 HTTP ${code}" - -# --- 8.4 glob 匹配 --- -code=$(inv '{"match":"npm:/npm/keep*"}' -b "$CJ") -[ "$code" = "200" ] && [ "$(iv matched)" = "1" ] \ - && ok "glob 'npm:/npm/keep*' 命中 1 个" || bad "glob 匹配异常(matched=$(iv matched))" -code=$(inv '{"match":"*keep*"}' -b "$CJ") -[ "$(iv matched)" = "2" ] && ok "glob '*keep*' 跨生态命中 2 个(npm keep-a + maven keep-m)" \ - || bad "跨生态 glob 命中数不对($(iv matched))" - -# --- 8.5 zone 限定:只在指定区里搜 --- -code=$(inv '{"zone":"npm","match":"keep-m"}' -b "$CJ") -[ "$(iv matched)" = "0" ] && ok "zone=npm + match=keep-m → 0(不会跨区误伤)" \ - || bad "zone 限定失效($(iv matched))" - -# --- 8.6 无命中:200 且不报错(最常见的原因是关键字写错)--- -code=$(inv '{"match":"nosuchartifact"}' -b "$CJ") -[ "$code" = "200" ] && [ "$(iv matched)" = "0" ] \ - && ok "无命中时返回 200 / matched=0(不当作错误)" || bad "无命中返回 ${code}/$(iv matched)" - -# --- 8.7 参数与越权 --- -code=$(inv '{}' -b "$CJ") -[ "$code" = "400" ] && ok "缺 match → 400" || bad "缺 match 返回 ${code}" -code=$(inv '{"zone":"nope","match":"x"}' -b "$CJ") -[ "$code" = "400" ] && ok "未知 zone → 400" || bad "未知 zone 返回 ${code}" -code=$(inv '{"match":"x"}') -[ "$code" = "401" ] && ok "未登录 → 401" || bad "未登录返回 ${code}" -code=$(inv '{"match":"x","apply":1}' -H "$AUTH") -[ "$code" = "401" ] && ok "账号态 sk_ 调失效 → 401(破坏性动作不给普通 Key)" || bad "sk_ 返回 ${code}" - -# --- 8.8 清理动作不能把目录搞坏 --- -ncrit=$(tail -n +"$(cat "$RUN/logs/error.log.mark")" "$RUN/logs/error.log" 2>/dev/null | grep -c "crit\|mkdir() failed") -if [ "${ncrit:-1}" = "0" ]; then - ok "error.log 无 crit / mkdir 失败(目录结构完好)" -else - bad "error.log 出现 ${ncrit} 条 crit/mkdir 失败" - tail -5 "$RUN/logs/error.log" -fi - -echo - -# =========================================================================== -# 前端静态契约:API 全绿 ≠ 面板看得见。 -# 曾经踩过:renderCapacity() 写好了、锚点也都在,但 render() 里漏了那一行调用 -# → 接口返回 100% 正确、后端断言全绿,而面板是**空的**。 -# 这条断言专治「定义了却没人调用」。 -echo "== 9. 前端静态契约(面板锚点齐 + 渲染函数真的被调用)==" -out=$("$PY" - "$REPO/www/cache.html" "$REPO/www/assets/cache.js" <<'PYCODE' -import re, sys -html = open(sys.argv[1], encoding="utf-8").read() -js = open(sys.argv[2], encoding="utf-8").read() -ok_, bad_ = [], [] - -need = ["capBody", "capSummary", "capRefresh", "capScan", "capPurgeAll", - "capMatch", "capZone", "capPreview", "capApply", - "capInvalResult", "capInvalKeys"] -missing = [a for a in need if ('id="%s"' % a) not in html] -if missing: - bad_.append("cache.html 缺锚点:" + " ".join(missing)) -else: - ok_.append("cache.html 含全部容量面板锚点(%d 个)" % len(need)) - -# 每个 `function NAME(` 定义,名字在全文至少要出现 2 次(定义 + 至少一处调用/引用) -defs = re.findall(r"\bfunction\s+([A-Za-z_$][\w$]*)\s*\(", js) -dead = sorted({n for n in defs if len(re.findall(r"\b%s\b" % re.escape(n), js)) < 2}) -if dead: - bad_.append("定义了但从未被引用的函数:" + " ".join(dead)) -else: - ok_.append("cache.js 无「定义了却没人调用」的函数(共 %d 个定义)" % len(defs)) - -# 容量渲染必须由 render() 以语句形式调用(只被别处引用不算「面板会渲染」) -for n in ["renderCapacity"]: - if not re.search(r"^\s*%s\(\);" % re.escape(n), js, re.M): - bad_.append("%s() 没有任何一处以语句形式调用(render() 里漏了?)" % n) - else: - ok_.append("%s() 已在 render() 的语句位置被调用" % n) - -for s in ok_: - print("OK " + s) -for s in bad_: - print("BAD " + s) -if len(ok_) + len(bad_) < 3: - # 走到这里说明这段断言自己没跑完(如被编辑弄出语法错)—— - # 必须显式失败:否则「断言静默消失」会伪装成全绿(踩过:3 条变成 0 条,fail 仍是 0) - print("BAD 静态契约断言未完整执行(只产出 %d 条)" % (len(ok_) + len(bad_))) -PYCODE -) -pyrc=$? -while IFS= read -r line; do - case "$line" in - OK\ *) echo " ✅ ${line#OK }"; pass=$((pass+1)) ;; - BAD\ *) echo " ❌ ${line#BAD }"; fail=$((fail+1)) ;; - esac -done <<< "$out" -if [ "$pyrc" -ne 0 ]; then - echo " ❌ 静态契约检查脚本自身出错(python 退出码 $pyrc)—— 上面没有 ✅ 不代表通过" - fail=$((fail+1)) -fi - -echo -# 防「断言静默消失」:本脚本的断言条数**本身是契约**。曾经因为一次编辑把 python -# 块的换行吞掉,3 条前端断言直接没跑,而 fail=0、结果看着是全绿。 -# 所以这里钉一个下限:新增/删除断言时同步改这个数(改它比漏掉断言安全)。 -EXPECT_MIN=48 -if [ "${pass}" -lt "$EXPECT_MIN" ]; then - echo " ❌ 通过数 ${pass} < 预期下限 ${EXPECT_MIN}:有断言没跑到(被改坏或被静默跳过)" - fail=$((fail+1)) -fi -echo "==== 结果:通过 ${pass},失败 ${fail}(期望下限 ${EXPECT_MIN})====" -echo "要删净临时目录: rm -rf $RUN" -[ "$fail" -eq 0 ] || exit 1 diff --git a/tests/cache/test-cache.sh b/tests/cache/test-cache.sh deleted file mode 100755 index 3492794..0000000 --- a/tests/cache/test-cache.sh +++ /dev/null @@ -1,127 +0,0 @@ -#!/bin/bash -# ============================================================================ -# 统一制品缓存 · 本机自测 -# 验证:六类生态 MISS→HIT、Range(206)、PURGE、X-Cache-Status 头 -# 前置:本机 nginx 已编译(NGINX_BIN),mock_upstream.py 由本脚本拉起 -# ============================================================================ -set -uo pipefail - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -REPO=$(cd "$HERE/../.." && pwd) -RUN="$HERE/.run" -NGINX_BIN=${NGINX_BIN:-/Users/rong/Desktop/cache/build/nginx-1.30.4/objs/nginx} -PORT=18083 -UP_PORT=18999 - -PY=${PY:-python3} -[ -x "$NGINX_BIN" ] || { echo "错误:nginx 不存在 $NGINX_BIN" >&2; exit 1; } - -mkdir -p "$RUN/cache" "$RUN/logs" -# 每次跑起点一致:清空上一轮残留的缓存文件(否则「首次」会命中旧档) -# -# ⚠️ 用 `find … -delete` 而**不是** `rm -rf "$RUN/cache"`:本机有批量删除护栏, -# 待删文件数超过阈值时整个删除会被**拒绝且不返回非零退出**,脚本(无 `set -e`) -# 静默继续 → 上一轮副本存活 → 「首次 MISS」与「PURGE 后变 MISS」双双报 HIT。 -# 这种假失败看起来像 nginx 缓存坏了,实际是本轮没打扫干净。实测踩过。 -mkdir -p "$RUN/cache/go" "$RUN/cache/cargo" "$RUN/cache/pypi" \ - "$RUN/cache/npm" "$RUN/cache/maven" "$RUN/cache/docker" -find "$RUN/cache" -type f -delete >/dev/null 2>&1 -# 自检:清完必须为空,否则后面的 MISS 断言全部不可信 -if [ -n "$(find "$RUN/cache" -type f -print -quit 2>/dev/null)" ]; then - echo "❌ 缓存目录没清干净($RUN/cache)——MISS/HIT 断言不可信,先修环境" >&2; exit 1 -fi -: > "$RUN/logs/error.log" -: > "$RUN/upstream.log" - -render() { sed -e "s|@RUN@|$RUN|g" "$1" > "$2"; } - -# 端口探活:直到能建立连接再往下走(用 HEAD,不会写进上游请求日志)。 -# 固定 sleep 在「刚 pkill 完又要立刻起」时不可靠,会偶发 502 → 断言误判。 -wait_up() { # $1=port $2=最大尝试次数(默认 80,步长 0.1s) - local port="$1" n="${2:-80}" i=0 - until curl -s -o /dev/null -I --max-time 1 "http://127.0.0.1:$port/" 2>/dev/null; do - i=$((i+1)); [ "$i" -ge "$n" ] && return 1; sleep 0.1 - done - return 0 -} - -# ---- 起假上游 ---- -pkill -f "tests/cache/mock_upstream.py" 2>/dev/null; sleep 0.3 -UPSTREAM_LOG="$RUN/upstream.log" UPSTREAM_PORT=$UP_PORT "$PY" "$HERE/mock_upstream.py" >"$RUN/logs/upstream.out" 2>&1 & -UP_PID=$! -kill -0 "$UP_PID" 2>/dev/null || { echo "假上游启动失败,见 $RUN/logs/upstream.out" >&2; exit 1; } -wait_up "$UP_PORT" || { echo "假上游端口 $UP_PORT 未就绪" >&2; kill "$UP_PID" 2>/dev/null; exit 1; } - -# ---- 起 nginx ---- -render "$HERE/nginx.cache.local.conf" "$RUN/nginx.conf" -"$NGINX_BIN" -p "$RUN" -c "$RUN/nginx.conf" -t 2>>"$RUN/logs/error.log" || { echo "nginx 配置测试失败" >&2; cat "$RUN/logs/error.log"; kill "$UP_PID"; exit 1; } -"$NGINX_BIN" -p "$RUN" -c "$RUN/nginx.conf" -wait_up "$PORT" || { echo "nginx 端口 $PORT 未就绪" >&2; cat "$RUN/logs/error.log"; kill "$UP_PID" 2>/dev/null; exit 1; } - -PASS=0; FAIL=0 -chk() { # chk <期望子串> <实际> - if [ "$3" = "$2" ]; then echo " ✅ $1"; PASS=$((PASS+1)); else echo " ❌ $1 期望[$2] 实际[$3]"; FAIL=$((FAIL+1)); fi -} -req() { # req [extra headers] -> 输出 "STATUS|XCACHE|BODY" - local m="$1" p="$2"; shift 2 - local out - out=$(curl -s -o /tmp/cache_body -w "%{http_code}" -X "$m" "http://127.0.0.1:$PORT$p" "$@" -H "X-Test: 1" 2>/dev/null) - local xc=$(curl -s -I -X "$m" "http://127.0.0.1:$PORT$p" "$@" 2>/dev/null | grep -i '^X-Cache-Status:' | tr -d '\r' | awk '{print $2}') - # 重新取 body(上面 -I 不带 body);用首请求拿到的 body - echo "$out|$xc|$(cat /tmp/cache_body)" -} - -echo "── 六类生态 MISS→HIT ──" -for eco in go cargo pypi npm maven docker; do - # 首次请求:同一次抓取头+体(避免额外请求污染 MISS 判定) - curl -s -D /tmp/h1 -o /tmp/b1 -w "%{http_code}" "http://127.0.0.1:$PORT/$eco/pkg-a" >/dev/null - xc1=$(grep -i '^X-Cache-Status:' /tmp/h1 | tr -d '\r' | awk '{print $2}') - b1=$(cat /tmp/b1) - # 二次请求:HIT - curl -s -D /tmp/h2 -o /tmp/b2 -w "%{http_code}" "http://127.0.0.1:$PORT/$eco/pkg-a" >/dev/null - xc2=$(grep -i '^X-Cache-Status:' /tmp/h2 | tr -d '\r' | awk '{print $2}') - b2=$(cat /tmp/b2) - chk "$eco 首次 MISS" "MISS" "$xc1" - chk "$eco 二次 HIT" "HIT" "$xc2" - chk "$eco 内容一致" "$b1" "$b2" -done - -echo "── Range(206 + 命中)──" -# 首段 range 请求(未预热,应 MISS 并回填缓存;nginx 缓存完整对象后可按 range 服务) -curl -s -D /tmp/hr1 -o /tmp/rr1 -w "%{http_code}" -r 0-15 "http://127.0.0.1:$PORT/go/biglayer" > /tmp/code_r -code_r=$(cat /tmp/code_r) -xc_r1=$(grep -i '^X-Cache-Status:' /tmp/hr1 | tr -d '\r' | awk '{print $2}') -# 二次 range:命中缓存 -curl -s -D /tmp/hr2 -o /dev/null -r 0-15 "http://127.0.0.1:$PORT/go/biglayer" >/dev/null -xc_r2=$(grep -i '^X-Cache-Status:' /tmp/hr2 | tr -d '\r' | awk '{print $2}') -chk "range 首请求 206" "206" "$code_r" -chk "range 首请求 MISS" "MISS" "$xc_r1" -chk "range 二次 HIT(缓存)" "HIT" "$xc_r2" - -echo "── PURGE(ipass 原生:删缓存文件,对应 POST /api/v1/cache/purge)──" -# 开源 vanilla nginx 无 proxy_cache_purge 指令;ipass 的 purge 由管理 API -# 删除缓存目录文件实现(无需第三方模块)。这里模拟同一动作。 -# ⚠️ 同样用 find -delete 而非 `rm -rf "$RUN/cache/go"/*`:护栏会静默拦下 -# 批量删除,届时文件还在、下一句仍读 HIT,「PURGE 失效」是假故障。 -find "$RUN/cache/go" -type f -delete >/dev/null 2>&1 -if [ -n "$(find "$RUN/cache/go" -type f -print -quit 2>/dev/null)" ]; then - echo "❌ PURGE 没删掉文件($RUN/cache/go)——断言不可信" >&2; exit 1 -fi -xc_after=$(curl -s -D - -o /dev/null "http://127.0.0.1:$PORT/go/pkg-a" | grep -i '^X-Cache-Status:' | tr -d '\r' | awk '{print $2}') -chk "PURGE(删文件)后变 MISS" "MISS" "$xc_after" - -echo "── 回源计数(HIT 不回源)──" -before=$(grep -c "GET /go/pkg-a" "$RUN/upstream.log" 2>/dev/null || echo 0) -# 再打两次,应全 HIT,不新增回源 -curl -s -o /dev/null "http://127.0.0.1:$PORT/go/pkg-a" -curl -s -o /dev/null "http://127.0.0.1:$PORT/go/pkg-a" -after=$(grep -c "GET /go/pkg-a" "$RUN/upstream.log" 2>/dev/null || echo 0) -chk "HIT 不回源(上游无新增)" "$before" "$after" - -# ---- 收尾 ---- -"$NGINX_BIN" -p "$RUN" -c "$RUN/nginx.conf" -s stop >/dev/null 2>&1 -kill "$UP_PID" 2>/dev/null - -echo -echo "通过 $PASS / 失败 $FAIL" -[ "$FAIL" -eq 0 ] && exit 0 || exit 1 diff --git a/tests/cache/test-ipass-cache.sh b/tests/cache/test-ipass-cache.sh deleted file mode 100755 index 4d2ffbd..0000000 --- a/tests/cache/test-ipass-cache.sh +++ /dev/null @@ -1,180 +0,0 @@ -#!/bin/bash -# ============================================================================ -# test-ipass-cache.sh —— Tier 2:ipass 托管下的**按生态记账**正确性 -# -# 跑的是**生产 conf 的渲染副本**(借 lib-render.sh;与 e2e-auth.sh 同一份, -# 不允许再各自维护一份 —— 曾因为抄了两份,生产 conf 换成变量上游后本层 -# 仍按静态上游渲染,整层挂掉且症状像模块坏了)。 -# -# 本层要证明的东西(与 e2e-auth.sh 不重叠): -# [1] 六类生态在**变量式 proxy_pass + 共享内存上游表**下 MISS→HIT(数据面) -# [2] 每个生态的命中/回源都被**记到自己的账上**(不是全记到 global) -# [3] 记账**精确**:再打 2 次 HIT,global.HIT 恰好 +2 -# [4] 非缓存 location(/api 自身)不产生缓存记账噪声 -# [5] HIT 真的不回源(读假上游请求日志) -# [6] 账号态 stats **必须带 sk_**:无 Key 401、带 Key 200 -# (这条以前是「免鉴权」——docs 把它列为已知风险 #4;现已关闭, -# 所以本层从「匿名调用」改成「必须有 Key」,别改回去。) -# -# 前置:nginx 已编译(NGINX_BIN);libipass_gateway.dylib 已构建(MODULE) -# ============================================================================ -set -uo pipefail - -# 本机 HTTP_PROXY/HTTPS_PROXY 会把 127.0.0.1 的请求丢给代理 → 假 502 -curl() { command curl --noproxy '*' "$@"; } - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -RUN="$HERE/.run-ipass" -REPO=$(cd "$HERE/../.." && pwd) -NGINX_BIN=${NGINX_BIN:-$REPO/build/nginx-1.30.4/objs/nginx} -MODULE=${MODULE:-$REPO/rust/target/debug/libipass_gateway.dylib} -PORT=18084 -UP_PORT=18999 -PY=${PY:-python3} -CACHE_PY="$PY" -export CACHE_PY -# shellcheck source=tests/cache/lib-render.sh -source "$HERE/lib-render.sh" - -ALICE=sk_alice_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - -[ -x "$NGINX_BIN" ] || { echo "错误:nginx 不存在 $NGINX_BIN" >&2; exit 1; } -[ -f "$MODULE" ] || { echo "错误:模块不存在 ${MODULE}(先 cargo build)" >&2; exit 1; } - -# 起点一致:清空上一轮缓存与数据(否则首次请求会 HIT 上一轮的副本 → -# 「首次 MISS」全红,而这不是缓存坏了,是本轮没打扫干净)。 -# -# ⚠️ 不要图省事写 `rm -rf "$RUN"`:本机有批量删除护栏,超过阈值时**整个删除 -# 被拒绝且不返回非零退出**(脚本 `set -uo pipefail` 没有 -e,于是静默继续)。 -# 表现就是「第一次请求全是 HIT」这种极难归因的假失败。实测踩过。 -# `find <子树> -delete` 不受该护栏影响(e2e-auth.sh 同样用法)。 -mkdir -p "$RUN/logs" "$RUN/data" "$RUN/audit" "$RUN/cache" -for e in go cargo pypi npm maven docker; do mkdir -p "$RUN/cache/$e"; done -find "$RUN/cache" -type f -delete >/dev/null 2>&1 -# 自检:清完必须为空。否则「首次 MISS」会全部报 HIT,且看起来像缓存坏了。 -if [ -n "$(find "$RUN/cache" -type f -print -quit 2>/dev/null)" ]; then - echo "❌ 缓存目录没清干净($RUN/cache)——MISS/HIT 断言不可信" >&2; exit 1 -fi -: > "$RUN/logs/error.log" -: > "$RUN/upstream.log" -# 上游表:六生态的 route 全配上,**键是路由名**(docker 的路由名就是 docker, -# 即使它的 URI 前缀是 /v2/;写成 v2 不报错但该路由恒 503) -cache_write_upstreams "$RUN" "http://127.0.0.1:${UP_PORT}" \ - go cargo cargo-dl pypi pypi-files npm maven docker || exit 1 -cp "$HERE"/fixtures/users.json "$RUN/data/users.json" -: > "$RUN/logs/error.log" -: > "$RUN/upstream.log" - -cache_render_prod_conf "$RUN" "$PORT" "$MODULE" - -# 端口探活:用 HEAD,不写假上游请求日志(HIT 不回源的断言靠行数比对) -wait_up() { # $1=url $2=最大尝试次数 - local url="$1" n="${2:-80}" i=0 - until curl -s -o /dev/null -I --max-time 1 "$url" 2>/dev/null; do - i=$((i+1)); [ "$i" -ge "$n" ] && return 1; sleep 0.1 - done - return 0 -} - -# ---- 起假上游 ---- -pkill -f "tests/cache/mock_upstream.py" 2>/dev/null; sleep 0.3 -UPSTREAM_LOG="$RUN/upstream.log" UPSTREAM_PORT=$UP_PORT \ - "$PY" "$HERE/mock_upstream.py" >"$RUN/logs/upstream.out" 2>&1 & -UP_PID=$! -kill -0 "$UP_PID" 2>/dev/null || { echo "假上游启动失败,见 $RUN/logs/upstream.out" >&2; exit 1; } -wait_up "http://127.0.0.1:${UP_PORT}/__ready" || { - echo "假上游端口 $UP_PORT 未就绪" >&2; kill "$UP_PID" 2>/dev/null; exit 1; } - -# ---- 起 nginx(加载 ipass 模块,跑生产 conf 副本)---- -export ADMIN_INIT_PASSWORD="test_admin_pw_123" -if ! "$NGINX_BIN" -p "$RUN" -c conf/nginx.cache.conf -t 2>>"$RUN/logs/error.log"; then - echo "❌ nginx 配置测试失败(模块加载 / 指令解析)" >&2 - tail -20 "$RUN/logs/error.log" >&2 - kill "$UP_PID" 2>/dev/null; exit 1 -fi -"$NGINX_BIN" -p "$RUN" -c conf/nginx.cache.conf -kill -0 "$(cat "$RUN/logs/nginx.pid" 2>/dev/null)" 2>/dev/null || { - echo "❌ nginx 启动失败" >&2; tail -20 "$RUN/logs/error.log" >&2 - kill "$UP_PID" 2>/dev/null; exit 1 -} -B="http://127.0.0.1:${PORT}" -wait_up "$B/admin" || { - echo "❌ nginx 端口 $PORT 未就绪" >&2; kill "$UP_PID" 2>/dev/null; exit 1; } - -cleanup() { - "$NGINX_BIN" -p "$RUN" -c conf/nginx.cache.conf -s quit >/dev/null 2>&1 - kill "$UP_PID" 2>/dev/null -} -trap cleanup EXIT - -PASS=0; FAIL=0 -chk() { if [ "$3" = "$2" ]; then echo " ✅ $1"; PASS=$((PASS+1)); else echo " ❌ $1 期望[$2] 实际[$3]"; FAIL=$((FAIL+1)); fi } -code() { curl -s -o /dev/null -w '%{http_code}' "$@"; } -xcache(){ tr -d '\r' | awk 'tolower($1)=="x-cache-status:"{print $2}'; } -stats() { curl -s -H "X-API-Key: ${ALICE}" "$B/api/v1/cache/stats"; } - -echo "── 六类生态 MISS→HIT(数据面:route 前缀 → 生态)──" -# URL 前缀 ≠ 路由名 ≠ 生态名,三者只在 docker 上分开:前缀 /v2/ 对应路由名 docker。 -# 上游表按键是**路由名**(docker),URI 走 /v2/。写混了就是恒 503,故此处显式列出。 -for pair in "go:/go" "cargo:/cargo" "pypi:/pypi" "npm:/npm" "maven:/maven" "docker:/v2"; do - eco=${pair%%:*}; pre=${pair#*:} - curl -s -D /tmp/ih1 -o /tmp/ib1 -H "Authorization: Bearer ${ALICE}" "$B${pre}/pkg-a" - xc1=$(xcache < /tmp/ih1); b1=$(cat /tmp/ib1) - curl -s -D /tmp/ih2 -o /tmp/ib2 -H "Authorization: Bearer ${ALICE}" "$B${pre}/pkg-a" - xc2=$(xcache < /tmp/ih2); b2=$(cat /tmp/ib2) - chk "${eco} 首次 MISS(${pre}/)" "MISS" "$xc1" - chk "${eco} 二次 HIT" "HIT" "$xc2" - chk "${eco} 内容一致" "$b1" "$b2" -done - -echo "── 账号态 stats 的鉴权(docs 旧「免鉴权」风险 #4 已关闭)──" -chk "无 Key → 401" "401" "$(code "$B/api/v1/cache/stats")" -chk "带 sk_ → 200" "200" "$(code -H "X-API-Key: ${ALICE}" "$B/api/v1/cache/stats")" - -echo "── 记账:六生态各自 MISS/HIT 均已入账(不是全记到 global)──" -STATS=$(stats) -STATS="$STATS" "$PY" -c ' -import json, os -try: - d = json.loads(os.environ["STATS"]) -except Exception as e: - print("0 非 JSON:", e); raise SystemExit -be = d.get("data", {}).get("by_ecosystem", {}) -probs = [] -for eco in ["go","cargo","pypi","npm","maven","docker"]: - m = be.get(eco, {}) - if m.get("MISS", 0) < 1: probs.append("%s.MISS=%s" % (eco, m.get("MISS"))) - if m.get("HIT", 0) < 1: probs.append("%s.HIT=%s" % (eco, m.get("HIT"))) -g = be.get("global", {}) -if g.get("HIT", 0) < 6: probs.append("global.HIT=%s" % g.get("HIT")) -if g.get("MISS", 0) < 6: probs.append("global.MISS=%s" % g.get("MISS")) -print("1 OK" if not probs else "0 " + "; ".join(probs)) -' > /tmp/ipass_stats_check 2>&1 -ok=$(awk 'NR==1{print $1}' /tmp/ipass_stats_check) -detail=$(awk 'NR==1{$1="";sub(/^ +/,"");print}' /tmp/ipass_stats_check) -chk "六生态 MISS/HIT 均已记账" "1" "$ok" -[ "$ok" = "0" ] && echo " 明细:$detail" - -echo "── 记账精确性:新增 2 次 HIT 后 global.HIT 恰好 +2 ──" -G_BEFORE=$(stats | "$PY" -c 'import json,sys;print(json.load(sys.stdin)["data"]["by_ecosystem"]["global"]["HIT"])') -curl -s -o /dev/null -H "Authorization: Bearer ${ALICE}" "$B/go/pkg-a" -curl -s -o /dev/null -H "Authorization: Bearer ${ALICE}" "$B/go/pkg-a" -G_AFTER=$(stats | "$PY" -c 'import json,sys;print(json.load(sys.stdin)["data"]["by_ecosystem"]["global"]["HIT"])') -chk "global.HIT 增加 2" "$((G_BEFORE+2))" "$G_AFTER" - -echo "── 非缓存 location 不产生缓存记账噪声(/api 自身)──" -G2_BEFORE=$(stats | "$PY" -c 'import json,sys;print(json.load(sys.stdin)["data"]["by_ecosystem"]["global"].get("MISS",0))') -curl -s -o /dev/null -H "X-API-Key: ${ALICE}" "$B/api/v1/cache/stats" -G2_AFTER=$(stats | "$PY" -c 'import json,sys;print(json.load(sys.stdin)["data"]["by_ecosystem"]["global"].get("MISS",0))') -chk "/api 请求不计入缓存 MISS" "$G2_BEFORE" "$G2_AFTER" - -echo "── HIT 不回源(读假上游请求日志)──" -before=$(grep -c "GET /pkg-a" "$RUN/upstream.log" 2>/dev/null || echo 0) -curl -s -o /dev/null -H "Authorization: Bearer ${ALICE}" "$B/go/pkg-a" -curl -s -o /dev/null -H "Authorization: Bearer ${ALICE}" "$B/go/pkg-a" -after=$(grep -c "GET /pkg-a" "$RUN/upstream.log" 2>/dev/null || echo 0) -chk "HIT 不回源(上游无新增)" "$before" "$after" - -echo -echo "通过 $PASS / 失败 $FAIL" -[ "$FAIL" -eq 0 ] && exit 0 || exit 1 diff --git a/tests/cache/test-real-registries.sh b/tests/cache/test-real-registries.sh deleted file mode 100644 index 70f2c40..0000000 --- a/tests/cache/test-real-registries.sh +++ /dev/null @@ -1,197 +0,0 @@ -#!/bin/bash -# ============================================================================ -# test-real-registries.sh —— 对**真实 registry** 按业务类型做一次贯通验证 -# -# 与另外三个测试脚本的分工: -# test-cache.sh Tier1:纯 nginx proxy_cache(本地假上游) -# test-ipass-cache.sh Tier2:模块加载 + 记账 + 管理 API(本地假上游) -# e2e-auth.sh 鉴权/动态注入/配额(本地假上游) -# → 它们证明的是「缓存与鉴权这一层」正确。 -# 本脚本把上游换成**真实公网 registry**,证明「各生态的真实协议路径确实能 -# 穿过网关、拿到真制品、落盘、二次命中」——这是假上游永远证明不了的部分 -# (假上游只回 `ECHO: `,任何真实协议的坑都不会暴露)。 -# -# 用法(需先有一个跑着的实例,通常是 `dev-server.sh start`): -# bash tests/cache/test-real-registries.sh -# BASE=http://127.0.0.1:18085 SK=sk_xxx bash tests/cache/test-real-registries.sh -# -# 可覆盖的环境变量: -# BASE 实例入口(默认 http://127.0.0.1:18085) -# SK 下游账号 Key(默认取夹具里的 alice) -# ADMIN_USER / ADMIN_PASSWORD 管理台账号(默认夹具 admin) -# ONLY 只跑指定路由,逗号分隔(如 ONLY=go,npm) -# GO_UP / NPM_UP / PIP_UP / MAVEN_UP / CARGO_UP / CARGO_DL_UP / DOCKER_UP -# 覆盖各路由的上游基址 -# -# ⚠️ 本脚本**不**起停实例、也**不** pkill —— 它常跑在「给人看」的实例上, -# 按进程名 pkill 会把正在浏览的实例一起打断(见 skill 的说明)。 -# ⚠️ 本机有 HTTP_PROXY/HTTPS_PROXY,curl 打 localhost 会被丢给代理 → 假 502, -# 所以脚本内 curl 一律 `--noproxy '*'`。 -# ⚠️ 清缓存用 `find -delete` 而非 `rm -rf`:本机批量删除护栏会**静默拒绝**大目录的 -# `rm -rf`(不报错、不返回非零),于是「首次请求」会命中上一轮副本。 -# ============================================================================ -set -uo pipefail - -BASE=${BASE:-http://127.0.0.1:18085} -SK=${SK:-sk_alice_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} -ADMIN_USER=${ADMIN_USER:-admin} -ADMIN_PASSWORD=${ADMIN_PASSWORD:-123456} # 夹具 tests/cache/fixtures/users.json 的 admin 口令 -ONLY=${ONLY:-} -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) - -# 默认上游:官方源在国内不通的两个(go / docker)换成可用镜像。 -# 之所以写进默认值而不是让用户配:这两个不通是本机网络环境的常态, -# 不换的话「真实测试」会以超时收场,看不出任何结论。 -GO_UP=${GO_UP:-https://goproxy.cn} -NPM_UP=${NPM_UP:-https://registry.npmjs.org} -MAVEN_UP=${MAVEN_UP:-https://repo1.maven.org/maven2} -PIP_UP=${PIP_UP:-https://pypi.org} -CARGO_UP=${CARGO_UP:-https://index.crates.io} -CARGO_DL_UP=${CARGO_DL_UP:-https://static.crates.io} -DOCKER_UP=${DOCKER_UP:-https://docker.m.daocloud.io} - -curl() { command curl -s --noproxy '*' "$@"; } - -# ---- 业务类型:路由 | 上游基址 | 探测路径 | 说明 | 备注 ---- -# 探测路径是**该生态真实客户端会打的协议路径**,不是随便一个能返回 200 的路径: -# go : 模块列表(`go list -m -versions` 走这条) -# npm : packument(含全部版本与 tarball 地址,最大的响应之一) -# maven : maven-metadata.xml(版本列表) -# pypi : simple 索引页(HTML,列出所有 wheel/sdist 的**绝对** URL) -# cargo : 稀疏索引的 config.json(cargo 启动第一件事) -# cargo-dl: .crate 包本体(固定老版本,不会被 yank 掉) -# docker : manifest(v2 协议;裸请求 401 = 要求先向 auth.docker.io 换 token,属预期) -CASES=$(cat < %-34s active=%s\n" "$route" "$base" "${act:-?}" -done -echo - -# ---------- 3. 清空磁盘缓存,保证「首请求」真是 MISS ---------- -# 默认按本仓库的交互实例目录推导;换实例时用 CACHE_DIR 覆盖。 -CACHE_DIR=${CACHE_DIR:-} -if [ -z "$CACHE_DIR" ] && [ -d "$HERE/.run-dev/cache" ]; then - CACHE_DIR="$HERE/.run-dev/cache" -fi -if [ -n "$CACHE_DIR" ] && [ -d "$CACHE_DIR" ]; then - # ★★ 只能删**文件**,绝不能删 `cache//` 这些父目录。★★ - # nginx 只在**启动时**创建 `cache/`,运行期再按 levels=1:2 建下级目录 - # (`cache//<末1位>/<末2-3位>/`)。父目录被删掉后它**不会自愈**: - # 此后每次写缓存都是 - # [crit] mkdir() ".../cache/go/0" failed (2: No such file or directory) - # nginx 随即**直接断开客户端连接**(curl 报 exit 52 Empty reply / code 000), - # 于是**所有制品路由 100% 不可用**,直到 reload/重启 nginx。实测踩过: - # 首轮真实测试整片 000 就是这个原因,看着像"网关坏了"。 - # 注意时机差异:脚本里「先清缓存、再起 nginx」是安全的(启动时会重建目录), - # 而**在已运行的实例上清缓存**才危险——本脚本属于后者。 - find "$CACHE_DIR" -type f -delete >/dev/null 2>&1 - left=$(find "$CACHE_DIR" -type f 2>/dev/null | wc -l | tr -d ' ') - if [ "$left" != "0" ]; then - echo "❌ 缓存文件没清干净(残留 $left 个):$CACHE_DIR"; exit 1 - fi - # 自检:各生态目录必须还在(缺了就会触发上面那条 crit) - missing="" - for e in go cargo pypi npm maven docker; do - [ -d "$CACHE_DIR/$e" ] || missing="$missing $e" - done - if [ -n "$missing" ]; then - echo "❌ 缓存目录结构缺失(nginx 不会自愈,会 100% crit 断连):${missing}" - echo " 修复:重启实例,或 mkdir -p $(printf '%s ' "$CACHE_DIR"/$missing)" - exit 1 - fi - echo "-- 已清空缓存文件(保留目录结构):$CACHE_DIR --" -else - echo "-- 未清磁盘缓存(未找到目录,给 CACHE_DIR 指定):若首请求不是 MISS,多半是上一轮的副本 --" -fi -echo - -# ---------- 4. 逐生态真实拉取两次 ---------- -printf "%-9s %-13s %-13s %-8s %-8s %-5s %s\n" 路由 首请求 二次 首字节 次字节 一致 说明 -echo "$CASES" | while IFS='|' read -r route base probe desc; do - [ -z "$route" ] && continue - want "$route" || continue - - H1="/tmp/realreg.$route.h1"; B1="/tmp/realreg.$route.b1" - H2="/tmp/realreg.$route.h2"; B2="/tmp/realreg.$route.b2" - - c1=$(curl -s -D "$H1" -o "$B1" -w '%{http_code}' --max-time 90 \ - -H "Authorization: Bearer $SK" "$BASE$probe") - s1=$(tr -d '\r' < "$H1" | awk 'tolower($1)=="x-cache-status:"{print $2}') - z1=$(wc -c < "$B1" | tr -d ' ') - - c2=$(curl -s -D "$H2" -o "$B2" -w '%{http_code}' --max-time 90 \ - -H "Authorization: Bearer $SK" "$BASE$probe") - s2=$(tr -d '\r' < "$H2" | awk 'tolower($1)=="x-cache-status:"{print $2}') - z2=$(wc -c < "$B2" | tr -d ' ') - - same=$([ "$z1" = "$z2" ] && cmp -s "$B1" "$B2" && echo yes || echo NO) - - printf "%-9s %-13s %-13s %-8s %-8s %-5s %s\n" \ - "$route" "${c1}/${s1:-?}" "${c2}/${s2:-?}" "${z1}B" "${z2}B" "$same" "$desc" - - # 判定,按「谁的问题」分层,别把上游/协议的事记到缓存头上: - # 401 → v2 协议要求先换 token,裸 curl 拿不到,且 401 不在 proxy_cache_valid - # 里(nginx 默认只缓存 200/301/302),所以它必然不 HIT。这是预期,不是缺陷。 - # 其余 → 二次必须 HIT(缓存层硬指标),且两次响应体必须一致。 - if [ "$c1" = "401" ]; then - echo " ⚠️ 上游 401:v2/manifest 需先向 auth 端点换 token(真实客户端会做)," - echo " 裸 curl 401 属预期;401 不在 proxy_cache_valid 里,故也不缓存。" - elif [ "${s2:-}" != "HIT" ]; then - echo " ❌ 第二次不是 HIT(实际 ${s2:-无})—— 缓存没生效或缓存键不稳定" - elif [ "$same" != "yes" ]; then - echo " ❌ 两次响应体不一致 —— 缓存返回了别的东西" - elif [ "$c1" != "200" ]; then - echo " ⚠️ 上游 HTTP $c1 —— 探测路径可能已变,需人工确认(非网关问题)" - else - echo " ✅ MISS→HIT,$z1 字节真制品已落盘" - fi - rm -f "$H1" "$B1" "$H2" "$B2" -done - -echo -echo "==== 完成。逐行 ✅ 即「真实业务类型贯通」 ====" -echo "提示:浏览器打开 $BASE/admin 可看到刚配上的上游与命中计数。" -rm -f "$CJ" diff --git a/tests/cache/validate-prod-conf.sh b/tests/cache/validate-prod-conf.sh deleted file mode 100755 index 1a9c6c1..0000000 --- a/tests/cache/validate-prod-conf.sh +++ /dev/null @@ -1,82 +0,0 @@ -#!/bin/bash -# ============================================================================ -# 生产配置语法校验:把 conf/ 下的生产配置渲染到沙箱,跑 `nginx -t`。 -# -# 验证点(不做真实回源): -# * load_module 能加载 ipass 模块(含 plugin-cache) -# * ipass_state / ipass_data_dir / ipass_audit_dir / ipass_cache / ipass_api 指令被接受 -# * 变量式 `proxy_pass $cache_target` 被接受,且 `resolver` 已声明 -# (变量上游没 resolver 会在运行期 500,配置期看不出,所以这里也断言 resolver 在) -# * **SSL 在本构建里真的可用**:conf/server.cache.conf / cache-routes.conf / -# cache-common.conf 都用了 `proxy_ssl_server_name`(上游 https 必需), -# 若拿无 SSL 的 nginx 来校验会报 unknown directive —— 这正是要拦的情况 -# * 六生态 proxy_cache_path 目录可创建 -# * include conf/server.cache.conf / cache-routes.conf / cache-common.conf -# 与 tls/*.conf 空匹配都解析正确 -# -# ⚠️ 与旧版(静态上游版)的区别:上游地址与凭据**已不在 conf 里**,全在 -# plugin-cache 的上游表(data/cache-upstreams.json → 写穿共享内存)。 -# 所以这里**不再需要**把 https:// 降级成 http:// —— 配置里根本没有字面量上游。 -# 同理也不再剔除 proxy_ssl_*:那会让「SSL 构建可用」这个验证点凭空消失。 -# ============================================================================ -set -uo pipefail - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -REPO=$(cd "$HERE/../.." && pwd) -RUN="$HERE/.run-prod" -NGINX_BIN=${NGINX_BIN:-$REPO/build/nginx-1.30.4/objs/nginx} -MODULE=${MODULE:-$REPO/rust/target/debug/libipass_gateway.dylib} - -[ -x "$NGINX_BIN" ] || { echo "错误:nginx 不存在 $NGINX_BIN" >&2; exit 1; } -[ -f "$MODULE" ] || { echo "错误:模块不存在 ${MODULE}(先 cargo build)" >&2; exit 1; } - -# 前置闸门:本校验依赖 SSL 模块在编(conf 里有 proxy_ssl_server_name)。 -# 先自检,避免用错二进制时得到一串难懂的 unknown directive。 -if ! "$NGINX_BIN" -V 2>&1 | grep -q -- '--with-http_ssl_module'; then - echo "❌ 该 nginx 未编译 http_ssl_module,无法校验生产配置:" >&2 - echo " $NGINX_BIN" >&2 - echo " 生产 conf 用了 proxy_ssl_server_name(上游 https 必需)。" >&2 - echo " 请先:bash build/build-nginx-ssl.sh(产物 build/nginx-1.30.4/objs/nginx)" >&2 - exit 1 -fi - -# 清掉上一次的 conf 副本(其余子树不必清:渲染会覆盖同名文件)。 -# ⚠️ 不要写 `rm -rf "$RUN"`:本机批量删除护栏超过阈值会**拒绝整个删除且不报错**, -# 于是上一轮残留的 conf 会被当成"本次校验通过"(静默假绿)。实测见 .run-prod。 -mkdir -p "$RUN/conf/tls" "$RUN/logs" "$RUN/data" "$RUN/audit" \ - "$RUN/cache/go" "$RUN/cache/cargo" "$RUN/cache/pypi" \ - "$RUN/cache/npm" "$RUN/cache/maven" "$RUN/cache/docker" -find "$RUN/conf" -maxdepth 1 -type f -delete >/dev/null 2>&1 - -# 渲染:**借 e2e/Tier2 同一套** lib-render.sh,别在这里自己再写一份 sed 替换。 -# 自己写的那份会漏掉 renderer 后续新增的项(端口、worker、tls include…), -# 结果就是"校验的 conf" 与 "实跑的 conf" 悄悄分叉 —— 正是 Tier2 挂掉的那类根因。 -# 端口用 18086(`-t` 不绑定端口,取个不与 run.sh 其它实例重的值只为可读)。 -CACHE_PY="${PY:-python3}"; export CACHE_PY -# shellcheck source=tests/cache/lib-render.sh -source "$HERE/lib-render.sh" -cache_render_prod_conf "$RUN" 18086 "$MODULE" -echo " (沙箱校验:借 lib-render.sh 渲染,未做任何指令降级——SSL 在编,如实校验)" - -export ADMIN_INIT_PASSWORD="validate_only_pw" - -echo "── nginx -t(生产配置:conf/nginx.cache.conf)──" -if "$NGINX_BIN" -p "$RUN" -c conf/nginx.cache.conf -t 2>"$RUN/logs/error.log"; then - # 反向断言:变量式 proxy_pass 必须配 resolver,否则运行期一律 500 - if grep -qE '^[[:space:]]*resolver[[:space:]]' "$RUN/conf/nginx.cache.conf"; then - echo "✅ resolver 已声明(变量上游运行期解析的必需项)" - else - echo "❌ 缺 resolver:变量式 proxy_pass 会在运行期报 no resolver defined" >&2 - exit 1 - fi - echo "✅ 生产配置语法与模块加载校验通过" - rc=0 -else - echo "❌ 生产配置校验失败:" >&2 - cat "$RUN/logs/error.log" >&2 - rc=1 -fi - -echo -echo " 渲染后的配置:$RUN/conf/nginx.cache.conf" -exit $rc diff --git a/tests/cache/verify-cache-eviction.sh b/tests/cache/verify-cache-eviction.sh deleted file mode 100644 index e14a278..0000000 --- a/tests/cache/verify-cache-eviction.sh +++ /dev/null @@ -1,215 +0,0 @@ -#!/bin/bash -# ============================================================================ -# verify-cache-eviction.sh —— 验证「缓存超额/闲置后被自动淘汰」 -# -# 回答的问题:磁盘缓存有没有上限?写满了谁来清? -# -# 机制(nginx 自带,无需外部脚本): -# * max_size=S zone 容量上限。cache manager 进程持续比对,超了就按 -# **LRU(最久未访问)**删到 S 以下 —— 这就是「超额自动清理」。 -# * inactive=T 条目 T 时间内没被访问过就删(与容量无关的「闲置淘汰」)。 -# 两者都在 `proxy_cache_path` 上按 **zone** 独立配置,互不干扰。 -# -# 本脚本用一个临时实例把参数改小到可观测,然后: -# A 段(容量):npm zone 配 max_size=1m,灌 ~3MB → 断言磁盘被压回 ≤1m, -# 且**最早的条目被淘汰(再请求变 MISS)、最新的还在(HIT)**。 -# B 段(闲置):maven zone 配 inactive=10s,灌 1 个小对象 → 立刻 HIT, -# 闲置 15s 后断言变 MISS。 -# -# bash tests/cache/verify-cache-eviction.sh -# -# ⚠️ 自起自停一个**独立实例**(端口 18086 / 假上游 18997),不碰 dev-server。 -# ⚠️ 本脚本**不** pkill —— 只杀自己记下的 pid(pkill 会误伤别人正在看的实例)。 -# ============================================================================ -set -uo pipefail - -curl() { command curl -s --noproxy '*' "$@"; } - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -REPO=$(cd "$HERE/../.." && pwd) -RUN="$HERE/.run-evict" -PORT=18086 -UP_PORT=18997 -NGX="$REPO/build/nginx-1.30.4/objs/nginx" -MOD="$REPO/rust/target/debug/libipass_gateway.dylib" -PY=${PY:-python3} -CACHE_PY="$PY"; export CACHE_PY -# shellcheck source=tests/cache/lib-render.sh -source "$HERE/lib-render.sh" - -SK=sk_alice_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -AUTH="Authorization: Bearer $SK" -UP_LOG="$RUN/upstream.log" - -pass=0; fail=0 -ok() { echo " ✅ $*"; pass=$((pass+1)); } -bad() { echo " ❌ $*"; fail=$((fail+1)); } - -cleanup() { - [ -f "$RUN/logs/nginx.pid" ] && kill "$(cat "$RUN/logs/nginx.pid")" 2>/dev/null - [ -f "$RUN/upstream.pid" ] && kill "$(cat "$RUN/upstream.pid")" 2>/dev/null - sleep 0.3 -} -trap cleanup EXIT - -echo "==== 缓存淘汰验证(独立实例 :${PORT})====" - -# ---------- 1. 渲染 conf 并把两个 zone 的参数改小到可观测 ---------- -cache_write_upstreams "$RUN" "http://127.0.0.1:${UP_PORT}" \ - npm maven || exit 1 -cache_render_prod_conf "$RUN" "$PORT" "$MOD" >/dev/null -# ⚠️ 必须拷夹具账号:否则用户表为空 → alice 的 sk_ 不被认 → **所有请求 401**, -# 而 401 在 access 阶段就被模块返回,压根不进代理层 —— 症状是 -# 「缓存目录 0 文件、响应头里没有 X-Cache-Status」,看着像缓存没生效。 -# dev-server.sh 也是这个顺序(先拷 fixtures 再起 nginx)。 -cp "$HERE"/fixtures/*.json "$RUN/data/" 2>/dev/null - -"$PY" - "$RUN" <<'P' -import re, sys, pathlib -run = sys.argv[1] -p = pathlib.Path(run, "conf", "nginx.cache.conf") -s = p.read_text() -out = [] -for line in s.splitlines(True): - # npm → 容量淘汰:1m 上限,闲置窗口放长(避免两段互相干扰) - if "keys_zone=npm:" in line: - line = re.sub(r"max_size=\S+", "max_size=1m", line) - line = re.sub(r"inactive=\S+", "inactive=1h", line) - # maven → 闲置淘汰:窗口 10s,容量放大 - if "keys_zone=maven:" in line: - line = re.sub(r"max_size=\S+", "max_size=1g", line) - line = re.sub(r"inactive=\S+", "inactive=10s", line) - out.append(line) -p.write_text("".join(out)) -print(" [conf] npm: max_size=1m/inactive=1h maven: max_size=1g/inactive=10s") -P - -# 目录结构由 cache_render_prod_conf 建好;这里只删文件(见 test-real-registries.sh 的警告: -# 运行中删掉 cache/ 父目录会让 nginx 永久 crit 断连)。 -find "$RUN/cache" -type f -delete >/dev/null 2>&1 - -# ---------- 2. 起假上游(脱离进程组)与 nginx ---------- -mkdir -p "$RUN/logs" -: > "$UP_LOG" -UPSTREAM_LOG="$UP_LOG" UPSTREAM_PORT="$UP_PORT" \ -"$PY" - "$PY" "$HERE/mock_upstream.py" "$RUN/logs/upstream.out" "$RUN/upstream.pid" <<'P' -import os, subprocess, sys -py, script, out, pidf = sys.argv[1:5] -with open(out, "ab") as f: - p = subprocess.Popen([py, script], stdout=f, stderr=f, - env=dict(os.environ), start_new_session=True) -open(pidf, "w").write(str(p.pid)) -P -wait_up() { local p=$1 i=0; until curl -s -o /dev/null --max-time 1 "http://127.0.0.1:$p/$2" 2>/dev/null; do i=$((i+1)); [ $i -ge 80 ] && return 1; sleep 0.1; done; } -wait_up "$UP_PORT" "" || { echo "❌ 假上游未就绪"; exit 1; } - -ADMIN_INIT_PASSWORD=x "$NGX" -p "$RUN" -c conf/nginx.cache.conf -t 2>>"$RUN/logs/error.log" \ - || { echo "❌ nginx -t 失败"; tail -10 "$RUN/logs/error.log"; exit 1; } -ADMIN_INIT_PASSWORD=x "$NGX" -p "$RUN" -c conf/nginx.cache.conf -wait_up "$PORT" "" || { echo "❌ nginx 未就绪"; tail -10 "$RUN/logs/error.log"; exit 1; } -echo " 实例就绪(假上游 ${UP_PORT})" - -B="http://127.0.0.1:$PORT" -xc() { tr -d '\r' | awk 'tolower($1)=="x-cache-status:"{print $2}'; } -code() { curl -s -o /dev/null -w '%{http_code}' --max-time 60 -H "$AUTH" "$1"; } - -# =========================================================================== -# A 段:容量淘汰(max_size) -# =========================================================================== -echo -echo "== A. 容量淘汰:npm zone max_size=1m,灌入 15 × 200KB = 3MB ==" -# 先探一发,把「Key 不被认(401)/上游未配(503)/代理写盘失败」这类故障在灌数据前就暴露, -# 否则后面只会看到一堆空的 X-Cache-Status,分不清是缓存没生效还是请求没进来。 -sample=$(curl -s -o /dev/null -w '%{http_code}' -H "$AUTH" "$B/npm/probe?bytes=1024") -echo " 样本请求 HTTP ${sample}(期望 200;401=Key 不被认,503=上游未配)" -[ "$sample" = "200" ] || { echo "❌ 前置检查失败,后面的淘汰断言没有意义"; exit 1; } - -N=15; SZ=204800 -for i in $(seq 1 $N); do - curl -s -o /dev/null -H "$AUTH" "$B/npm/big/$i?bytes=$SZ" -done -kb0=$(du -sk "$RUN/cache/npm" 2>/dev/null | awk '{print $1}') -files0=$(find "$RUN/cache/npm" -type f 2>/dev/null | wc -l | tr -d ' ') -echo " 灌完后立即:磁盘 ${kb0}KB / ${files0} 个文件(灌入量约 $((N*SZ/1024))KB,上限 1m=1024KB)" - -# ★ nginx 的容量淘汰是**渐进**的,不是硬配额: -# cache manager 每秒跑一轮,每轮只淘汰有限个条目(LRU 序),于是 -# max_size 是**软上限**——短时猛灌可以短暂远超它(本测实测到 3x),之后逐步收敛。 -# 所以断言不能写成「3 秒内必须达标」,那是在测一个 nginx 没有承诺的东西; -# 要测的是「会不会收敛」以及「收敛用多久」(后者对运维更有用)。 -echo " -- 观察收敛(每 2s 采样,最多 30s)--" -kb2="$kb0"; files2="$files0"; secs="" -for s in 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30; do - kb2=$(du -sk "$RUN/cache/npm" 2>/dev/null | awk '{print $1}') - files2=$(find "$RUN/cache/npm" -type f 2>/dev/null | wc -l | tr -d ' ') - printf " t=%-2ss %5sKB %2s 个文件\n" "$s" "${kb2:-0}" "${files2:-0}" - if [ "${kb2:-0}" -le 1300 ]; then secs="$s"; break; fi - sleep 2 -done - -if [ "${kb2:-0}" -le 1300 ]; then - ok "收敛到上限附近:${kb2}KB ≤ 1300KB 容忍线(上限 1m=1024KB),耗时约 ${secs}s" -else - bad "30s 内没收敛(${kb2}KB)—— 淘汰没生效,缓存会无限增长" -fi -if [ "${files2:-0}" -lt "$N" ]; then - ok "条目数下降(${files2} < 灌入的 ${N})—— 确实发生了淘汰" -else - bad "条目数没下降(${files2})—— 淘汰没生效" -fi - -echo " -- LRU 方向性检查(该被淘汰的是最久未访问的)--" -# 第 1 个是全场最久未访问 → 期望被淘汰(MISS);最后 1 个刚写进来 → 期望仍在(HIT) -st_old=$(curl -s -D - -o /dev/null -H "$AUTH" "$B/npm/big/1?bytes=$SZ" | xc) -st_new=$(curl -s -D - -o /dev/null -H "$AUTH" "$B/npm/big/$N?bytes=$SZ" | xc) -if [ "$st_old" = "MISS" ]; then - ok "最早的条目 /npm/big/1 已被淘汰(再请求 MISS)" -else - bad "最早的条目还在(${st_old})—— 淘汰的不是最久未访问的?" -fi -if [ "$st_new" = "HIT" ]; then - ok "最新的条目 /npm/big/$N 仍在(HIT)" -else - # 刚探测 /big/1 又写回了一个条目,可能把 /big/$N 挤掉——这本身也是 LRU 行为的证据, - # 但会让断言不稳定,故只在连续两次都不是 HIT 时报失败。 - st_new2=$(curl -s -D - -o /dev/null -H "$AUTH" "$B/npm/big/$N?bytes=$SZ" | xc) - [ "$st_new2" = "HIT" ] && ok "最新的条目 /npm/big/$N 仍在(第二次探测 HIT)" \ - || bad "最新条目也丢了(${st_new}→${st_new2})" -fi - -# =========================================================================== -# B 段:闲置淘汰(inactive) -# =========================================================================== -echo -echo "== B. 闲置淘汰:maven zone inactive=10s ==" -h1=$(curl -s -D - -o /dev/null -H "$AUTH" "$B/maven/keepalive?bytes=1024" | xc) -h2=$(curl -s -D - -o /dev/null -H "$AUTH" "$B/maven/keepalive?bytes=1024" | xc) -[ "$h1" = "MISS" ] && [ "$h2" = "HIT" ] \ - && ok "刚写完:MISS → HIT(缓存生效)" \ - || bad "刚写完就不是 MISS→HIT(${h1} → ${h2})" - -n_before=$(find "$RUN/cache/maven" -type f 2>/dev/null | wc -l | tr -d ' ') -echo " 等 15s(> inactive=10s)后不该再命中…" -sleep 15 -# cache manager 扫描是异步的,多给几秒 -for _ in 1 2 3 4 5 6; do - n_now=$(find "$RUN/cache/maven" -type f 2>/dev/null | wc -l | tr -d ' ') - [ "$n_now" = "0" ] && break - sleep 2 -done -n_after=$(find "$RUN/cache/maven" -type f 2>/dev/null | wc -l | tr -d ' ') -if [ "$n_after" = "0" ]; then - ok "闲置条目已被 cache manager 删除(磁盘文件 ${n_before:-1} → 0)" -else - bad "闲置条目仍在(${n_after} 个文件)—— inactive 淘汰没生效" -fi -st_after=$(curl -s -D - -o /dev/null -H "$AUTH" "$B/maven/keepalive?bytes=1024" | xc) -[ "$st_after" = "MISS" ] \ - && ok "再请求变 MISS(确证被清掉了,不是仅文件索引失效)" \ - || bad "再请求仍是 ${st_after}—— 闲置淘汰没生效" - -echo -echo "==== 结果:通过 ${pass},失败 ${fail} ====" -echo "清理:bash tests/cache/verify-cache-eviction.sh 跑完会自动停实例;" -echo " 要删净临时目录: rm -rf $RUN" -[ "$fail" -eq 0 ] || exit 1 diff --git a/www/apix.html b/www/apix.html deleted file mode 100644 index 446d418..0000000 --- a/www/apix.html +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - -API 代理 · 尚数网 山海关 - - - -
- -
-
-
-
-

代理列表

-
- 把外部供应商的 API 挂到网关下:调用方用同一把账号 API Key 访问 - /apix/<slug>?参数=值,网关换成该代理自身登记的供应商 Key后转发,并返回供应商原样结果。 - 每家供应商的基址与 Key 都在每一条代理里单独填写,互不影响。停用的代理对调用方表现为 404(共享内存已摘除,立即生效)。 -

- 代理模式: - vendor - 单一供应商收口 POST /api/v1/ai/request,网关按 asset_id 拼体(防止客户端挑最贵的资产刷); - passthrough - 透传内部 REST 服务(OCR / 文生图 / TTS),访问 /apixp/<slug>/<路径尾部>, - 方法/请求体/Content-Type 原样转发,上游路径 = base + 尾部。 -

- 调用语法提示(usage_hint): - passthrough 推荐填写一段机器可读文本,由 GET /api/v1/me 下发给用户 AI, - 让 AI 自己拼出调用语法(路径尾部/Content-Type/字段名/Swagger),不用看文档。 -
-
- -
- - - - - -
slugasset_id调用地址供应商状态创建时间操作
-
-
- -
- - - - - diff --git a/www/assets/admin.css b/www/assets/admin.css deleted file mode 100644 index 2f4ef43..0000000 --- a/www/assets/admin.css +++ /dev/null @@ -1,238 +0,0 @@ -/* ============================================================================ - 管理台通用样式(多页共用) - - 原 www/admin.html 是「单文件塞下全部样式 + 全部逻辑」,改一次要在一个 - 1100 行的文件里找位置。现在按页拆分 HTML/JS,样式仍集中在一处—— - 面板视觉是一致的,没必要跟着拆散。 - ========================================================================== */ -:root{ - --bg:#f5f7fa; --panel:#ffffff; --border:#e3e8ef; --border-strong:#cbd5e1; - --text:#1f2937; --muted:#6b7280; --accent:#2563eb; --accent-hover:#1d4ed8; - --ok-bg:#e7f6ec; --ok-fg:#15803d; - --warn-bg:#fef3c7; --warn-fg:#92400e; - --err-bg:#fdecec; --err-fg:#b91c1c; - --gray-bg:#eef1f5; --gray-fg:#6b7280; - --radius:8px; - - /* 图表配色:蓝=请求数,青=入 token,紫=出 token;与徽标色系同族,不刺眼 */ - --c-req:#2563eb; --c-in:#0d9488; --c-out:#7c3aed; -} -*{box-sizing:border-box} -/* [hidden] 的 display:none 来自 UA 样式表,任何 author 样式里的 display 都会盖掉它 - (下面 .login-wrap 就设了 display:flex),必须显式兜底,否则隐藏不生效 */ -[hidden]{display:none !important} -html,body{margin:0;padding:0} -body{ - background:var(--bg); color:var(--text); font-size:14px; line-height:1.6; - font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif; -} -code,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px} - -/* ---------- 登录 ---------- */ -.login-wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px} -.login-card{width:100%;max-width:380px;background:var(--panel);border:1px solid var(--border); - border-radius:12px;padding:32px 28px;box-shadow:0 8px 28px rgba(15,23,42,.07)} -.login-card h1{font-size:17px;margin:0 0 4px} -.login-card .sub{color:var(--muted);font-size:12.5px;margin-bottom:24px} -.login-card .hint{margin-top:18px;padding-top:14px;border-top:1px dashed var(--border); - color:var(--muted);font-size:12px} - -/* ---------- 通用控件 ---------- */ -label{display:block;font-size:12.5px;color:var(--muted);margin:0 0 6px} -input[type=text],input[type=password],select,textarea{ - width:100%;padding:9px 11px;border:1px solid var(--border-strong);border-radius:var(--radius); - background:#fff;color:var(--text);font-size:13.5px;outline:none;transition:border-color .15s,box-shadow .15s} -input:focus,select:focus,textarea:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(37,99,235,.12)} -button{font-family:inherit;font-size:13px;padding:8px 14px;border-radius:var(--radius);cursor:pointer; - border:1px solid var(--border-strong);background:#fff;color:var(--text);transition:.15s;white-space:nowrap} -button:hover{border-color:var(--muted)} -button:disabled{opacity:.5;cursor:not-allowed} -.btn-primary{background:var(--accent);border-color:var(--accent);color:#fff} -.btn-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover)} -.btn-sm{padding:4px 10px;font-size:12px} -.btn-danger{color:var(--err-fg);border-color:#f3c6c6} -.btn-danger:hover{background:var(--err-bg);border-color:var(--err-fg)} -.btn-ok{color:var(--ok-fg);border-color:#bfe3cb} -.btn-ok:hover{background:var(--ok-bg);border-color:var(--ok-fg)} -.btn-block{width:100%;justify-content:center} -.field{margin-bottom:14px} - -/* ---------- 布局 ---------- */ -.topbar{background:var(--panel);border-bottom:1px solid var(--border);padding:0 24px; - display:flex;align-items:center;justify-content:space-between;height:58px;position:sticky;top:0;z-index:10} -.brand{display:flex;align-items:baseline;gap:10px} -.brand b{font-size:15px} -.brand span{color:var(--muted);font-size:12.5px} -.user-box{display:flex;align-items:center;gap:12px;font-size:13px;color:var(--muted)} -/* 宽度自适应:面板铺满视口(原 max-width:1180px 在大屏上只占中间一小块, - 表格被压窄、右侧留一大片空)。表单另行限宽,见 .grid-form。 */ -.wrap{padding:22px 24px 60px} - -.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;margin-bottom:20px} -.stat{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:14px 16px} -.stat .k{color:var(--muted);font-size:12.5px} -.stat .v{font-size:24px;font-weight:600;margin-top:2px} - -.tabs{display:flex;gap:6px;border-bottom:1px solid var(--border);margin-bottom:18px} -.tab{padding:9px 4px;margin-right:20px;border:0;background:none;border-bottom:2px solid transparent; - color:var(--muted);font-size:14px;border-radius:0;text-decoration:none} -.tab:hover{color:var(--text)} -.tab.active{color:var(--accent);border-bottom-color:var(--accent);font-weight:600} -.tab .pill{display:inline-block;min-width:18px;padding:0 5px;margin-left:6px;border-radius:9px; - background:var(--warn-bg);color:var(--warn-fg);font-size:11.5px;line-height:18px;text-align:center} - -.panel{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:18px} -.panel h2{font-size:14px;margin:0 0 4px} -.panel .desc{color:var(--muted);font-size:12.5px;margin-bottom:16px} -.panel-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap} -.panel-head .desc{margin-bottom:0} -/* 表单限宽:面板铺满后 auto-fit 会把 160px 的字段摊成十几列(一行一个字段, - 表单被拉得又长又散)。限住容器宽度,列数自然收敛;表格不受影响、照常铺满。 */ -.grid-form{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;align-items:end; - max-width:1100px} -/* 跨整行:给长字符串字段用。默认 auto-fit 在宽面板里会排成 6 列, - 每格只剩 ~170px —— 上游地址 / 密钥根本显示不全 */ -.span-all{grid-column:1/-1} -/* 上游表单:短字段(slot / 备注)两列,长字段独占整行;窄屏收成一列 */ -.grid-form.up-form{grid-template-columns:repeat(2,1fr)} -@media (max-width:600px){.grid-form.up-form{grid-template-columns:1fr}} -/* URL / 密钥用等宽字体,便于逐字符核对路径与密钥 */ -input.field-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px} -/* 上游地址很长且没有空格,允许折行,避免把表格撑破 */ -td.base-cell{word-break:break-all} - -table{width:100%;border-collapse:collapse;font-size:13px} -th{text-align:left;color:var(--muted);font-weight:500;font-size:12.5px;padding:9px 10px; - border-bottom:1px solid var(--border);white-space:nowrap} -td{padding:11px 10px;border-bottom:1px solid #f1f4f8;vertical-align:middle} -tr:last-child td{border-bottom:0} -tbody tr:hover{background:#fafbfd} -.empty{text-align:center;color:var(--muted);padding:34px 0 !important;font-size:13px} - -.badge{display:inline-block;padding:2px 8px;border-radius:20px;font-size:12px;line-height:18px;white-space:nowrap} -.b-ok{background:var(--ok-bg);color:var(--ok-fg)} -.b-warn{background:var(--warn-bg);color:var(--warn-fg)} -.b-err{background:var(--err-bg);color:var(--err-fg)} -.b-gray{background:var(--gray-bg);color:var(--gray-fg)} -.b-blue{background:#e6efff;color:#1d4ed8} - -.row-actions{display:flex;gap:6px;flex-wrap:wrap} - -/* 「按制品失效」工具条:输入框 + 缓存区选择 + 预览/确认两个按钮排一行。 - 不复用 .sub-build —— 那是「子域名拼装」专用(max-width:340px、输入居中、 - 左右无边框去拼灰底段),语义与排版都不匹配。窄屏靠 flex-wrap 自动折行, - 标签与按钮 flex:none 保证不被压缩(否则中文标签会被挤成一字一行)。 */ -.inval-bar{display:flex;align-items:center;gap:8px;flex-wrap:wrap; - margin-top:16px;padding-top:14px;border-top:1px dashed var(--border)} -.inval-bar>b{flex:none;font-size:13px} -.inval-bar input[type=text]{flex:1;min-width:240px;width:auto;text-align:left; - font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;letter-spacing:0} -.inval-bar select{flex:none;width:auto;min-width:132px} -.inval-bar button{flex:none} -/* 命中的 key 列表:等宽、可断行、限高滚动(一个宽 pattern 可能命中几百条) */ -.inval-keys{margin-top:8px;padding:8px 10px;max-height:160px;overflow:auto; - background:#f8fafc;border:1px solid var(--border);border-radius:var(--radius); - font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; - font-size:12px;line-height:1.75;word-break:break-all;color:var(--text)} - -/* 「i + 8位随机数 + dm」拼装式子域名输入:视觉上是一个整体, - 固定段用灰底窄块,中间是可编辑的数字段,右侧跟「换一个」 */ -.sub-build{display:flex;align-items:center;gap:0;max-width:340px} -.sub-build .seg{background:#eef2f7;border:1px solid var(--border);color:var(--muted); - font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px; - padding:9px 10px;line-height:1.2;user-select:none} -.sub-build .seg:first-child{border-radius:var(--radius) 0 0 var(--radius);border-right:0} -.sub-build .seg:nth-of-type(2){border-radius:0 var(--radius) var(--radius) 0;border-left:0} -.sub-build input{flex:1;min-width:0;border-radius:0;border-left:0;border-right:0; - font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; - letter-spacing:1px;text-align:center} -.sub-build .btn-sm{margin-left:8px;flex:none} -/* 域名可点即复制:看起来像链接,但仍是按钮(键盘可达) */ -button.host-copy{background:none;border:0;padding:0;font:inherit;font-weight:600;color:var(--accent); - cursor:pointer;text-align:left;text-decoration:underline dotted;text-underline-offset:3px} -button.host-copy:hover{text-decoration:underline solid} -.key-cell{display:flex;align-items:center;gap:6px} -.muted{color:var(--muted)} -.nowrap{white-space:nowrap} -.checkbox{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--text);padding-bottom:9px} -.checkbox input{width:16px;height:16px;accent-color:var(--accent)} - -/* ---------- 图表(纯 SVG,无外部依赖)---------- */ -.chart{width:100%} -.chart svg{display:block;width:100%;height:auto;overflow:visible} -.chart .grid{stroke:#eef1f5;stroke-width:1} -.chart .axis{stroke:var(--border-strong);stroke-width:1} -.chart .tick{fill:var(--muted);font-size:11px} -.chart .dot{stroke:#fff;stroke-width:1.5} -.chart-empty{color:var(--muted);font-size:13px;padding:26px 0;text-align:center} -.chart-legend{display:flex;gap:16px;flex-wrap:wrap;margin-bottom:8px;font-size:12.5px;color:var(--muted)} -.chart-legend i{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:6px} -.chart-legend b{color:var(--text);font-weight:600} -.charts-2{display:grid;grid-template-columns:repeat(auto-fit,minmax(420px,1fr));gap:18px} -@media (max-width:900px){.charts-2{grid-template-columns:1fr}} -.bar-row{display:grid;grid-template-columns:130px 1fr 92px;align-items:center;gap:10px;margin-bottom:8px;font-size:13px} -.bar-row .lb{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} -.bar-track{background:#f1f4f8;border-radius:4px;height:16px;overflow:hidden;display:flex} -.bar-fill{height:16px;border-radius:4px} -.bar-row .vv{text-align:right;color:var(--muted);font-size:12.5px;white-space:nowrap} -.bar-row .vv b{color:var(--text);font-size:13px} - -#toast{position:fixed;top:20px;left:50%;transform:translateX(-50%) translateY(-16px); - background:#111827;color:#fff;padding:10px 18px;border-radius:var(--radius);font-size:13px; - opacity:0;pointer-events:none;transition:.22s;z-index:99;max-width:70vw} -#toast.show{opacity:1;transform:translateX(-50%) translateY(0)} -#toast.err{background:#b91c1c} -.err-msg{color:var(--err-fg);font-size:12.5px;margin-top:10px;min-height:18px} - -/* ---------- 弹窗(modal)---------- */ -/* 编辑内容较多的表单用弹窗:遮罩 + 居中卡片。层级高于顶栏(z-index:10), - 故取 80;内容高时遮罩自身可滚动(padding 顶 8vh 让卡片不贴顶)。 */ -.modal-overlay{position:fixed;inset:0;background:rgba(15,23,42,.45);z-index:80; - display:flex;align-items:flex-start;justify-content:center;padding:8vh 16px 16px;overflow:auto} -.modal-card{background:var(--panel);border:1px solid var(--border);border-radius:12px; - width:100%;max-width:660px;box-shadow:0 18px 50px rgba(15,23,42,.22)} -.modal-head{display:flex;align-items:center;justify-content:space-between; - padding:15px 20px;border-bottom:1px solid var(--border)} -.modal-head h3{margin:0;font-size:15px} -.modal-close{border:0;background:none;font-size:22px;line-height:1;color:var(--muted);cursor:pointer;padding:0 4px} -.modal-close:hover{color:var(--text)} -.modal-body{padding:18px 20px} -.modal-foot{display:flex;justify-content:flex-end;gap:10px;padding:14px 20px;border-top:1px solid var(--border)} -/* 弹窗内表单同样限宽两列,窄屏单列;spa-all 跨整行由通用 .grid-form 规则保证 */ -.modal-body .grid-form.up-form{grid-template-columns:repeat(2,1fr)} -@media (max-width:600px){.modal-body .grid-form.up-form{grid-template-columns:1fr}} -/* 多账号上游:宽弹窗 + 账号行 */ -.modal-card.modal-wide{max-width:860px} -.acct-list{display:flex;flex-direction:column;gap:10px;margin-bottom:8px} -.acct-row{border:1px solid var(--border);border-radius:8px;padding:10px 12px;background:var(--bg); - display:flex;flex-direction:column;gap:8px} -.acct-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap} -.acct-row .acct-auth,.acct-row .acct-note{width:100%} -.acct-row .acct-del{margin-left:auto} -.acct-empty{font-size:12.5px;padding:6px 0} - -/* 上游「密钥」列:每账号负载块(请求/token/耗尽 + 比例条 + 14天迷你趋势)*/ -.acct-load{padding:4px 0;border-bottom:1px dashed #eef1f5} -.acct-load:last-child{border-bottom:0} -.acct-load .load-line{font-size:11.5px;color:var(--muted);margin:2px 0 3px} -.acct-load .load-bar{height:5px;background:#eef1f5;border-radius:3px;overflow:hidden} -.acct-load .load-bar span{display:block;height:100%;background:var(--c-req);border-radius:3px} -.spark{margin-top:3px} -.spark-svg{display:block} -.spark-svg .s-bar{fill:var(--c-req)} -.spark-svg .s-zero{fill:#e6eaf0} - -/* ============================================================================ - me.html 「我能调的 LLM 上游」:按协议分组 + 「OpenAI / Anthropic」复制 URL 按钮 - (1.0.34b:去掉之前的 curl 示例,只复制纯 URL——WorkBuddy / Claude Code - 客户端拿到后**不要尾巴**) - ========================================================================== */ -.upstream-card{border:1px solid var(--border);border-radius:8px;background:var(--panel); - padding:12px 14px;margin-bottom:12px} -.upstream-head{display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-bottom:8px} -.upstream-url-row{display:flex;align-items:center;gap:8px;margin-top:6px} -.upstream-url-row + .upstream-url-row{border-top:1px dashed var(--border);padding-top:6px;margin-top:6px} -.upstream-url{flex:1;min-width:0;padding:6px 10px;background:var(--bg); - border:1px solid var(--border);border-radius:6px;font-size:12px;color:#334155; - font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;word-break:break-all} -.copy-url-btn{flex-shrink:0;min-width:88px} diff --git a/www/assets/apix.js b/www/assets/apix.js deleted file mode 100644 index da46907..0000000 --- a/www/assets/apix.js +++ /dev/null @@ -1,223 +0,0 @@ -/* API 代理:代理列表(新建/编辑弹窗、复制地址、测试、启停、删除)*/ -(function () { - "use strict"; - - var $ = IP.$; - - // 弹窗里的表单:it 存在 = 编辑(slug 只读、Key 留空表示不改),否则 = 新建 - // mode: vendor = 单一供应商收口(POST /api/v1/ai/request,网关拼体);passthrough = - // 透传内部 REST(OCR / 文生图 / TTS 这种多端点多 body 的服务),方法/请求体原样转发。 - function formHtml(it) { - var edit = !!(it && it.slug); - var mode = (it && it.mode) || "vendor"; - var pt = mode === "passthrough"; - return '' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - (pt - ? '
' + - '💡 passthrough:调用方走 /apixp/' + IP.esc(it ? it.slug : "<slug>") + '/<尾部>,上游路径 = base + 尾部,' + - '方法/请求体/Content-Type 原样转发。OCR 类的 multipart/form-data 也能透传。' + - '「测试」按钮会 GET 打上游根地址验连通性。usage_hint 会原样通过 /api/v1/me 下发给用户 AI。' + - '
' - : '') + - '
'; - } - - function openForm(it) { - IP.modal({ - title: it && it.slug ? "编辑 API 代理" : "新建 API 代理", - submitText: "保存代理", - html: formHtml(it), - onMount: function (card, close) { - // mode 切换时给个轻提示(asset_id 与 Key 的 required 会跟着变), - // 不强制挡回——保存时由后端校验,最稳的是「前端展示、后端兜底」。 - var modeSel = card.querySelector("#axMode"); - if (modeSel) { - modeSel.addEventListener("change", function () { - var pt = modeSel.value === "passthrough"; - var hint = card.querySelector("#axModeHint"); - if (hint) hint.remove(); - if (pt) { - hint = document.createElement("div"); - hint.id = "axModeHint"; - hint.className = "muted"; - hint.style.cssText = "font-size:11.5px;border-left:3px solid #6a8;padding:6px 10px;background:rgba(0,128,0,0.04);margin-top:8px"; - hint.innerHTML = "💡 passthrough 模式下 asset_id 可留空,Key 可留空(内部服务免鉴权)。"; - modeSel.parentNode.appendChild(hint); - } - }); - } - var form = card.querySelector("#apixForm"); - form.addEventListener("submit", function (e) { - e.preventDefault(); - IP.api("POST", "/api/admin/apix/save", { - slug: card.querySelector("#axSlug").value.trim(), - asset_id: card.querySelector("#axAsset").value.trim(), - mode: card.querySelector("#axMode").value, - name: card.querySelector("#axName").value.trim(), - supplier: card.querySelector("#axSupplier").value.trim(), - base: card.querySelector("#axBase").value.trim(), - key: card.querySelector("#axKey").value.trim(), - desc: card.querySelector("#axDesc").value.trim(), - params: card.querySelector("#axParams").value.trim(), - note: card.querySelector("#axNote") ? card.querySelector("#axNote").value.trim() : "", - usage_hint: card.querySelector("#axUsageHint").value, - enabled: card.querySelector("#axEnabled").checked - }).then(function (r) { IP.toast(r.msg); close(); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); }); - }); - } - }); - } - - function render(s) { - var body = $("apixBody"); - if (!s.apix.items.length) { - body.innerHTML = '还没有配置任何 API 代理 —— 点右上角「+ 新建代理」添加一条'; - return; - } - - body.innerHTML = s.apix.items.map(function (it) { - var enabled = !!it.enabled; - var toggle = enabled - ? "" - : ""; - - var params = IP.arr(it.params); - // 后端 it.url 现在是纯基址(不再带 ?q=);参数只拼一次,避免 ?q=?q= 的重复 - var url = it.url + (params.length ? "?" + params.map(function (p) { return p + "="; }).join("&") : ""); - // passthrough 没有「参数示例」概念(路径 + 任意尾部 + query),改成「路径示例」 - var example = params.length ? it.url + "?" + params[0] + "=关键词" : it.url; - - var supplier = (it.supplier || "-") + " · " + - (it.key_set - ? "" + IP.esc(it.key_mask) + "" - : "未配置 Key"); - - var isPt = it.mode === "passthrough"; - var modeTag = isPt - ? "passthrough" - : "vendor"; - - // usage_hint:passthrough 模式必填字段——列表行折叠展示让管理员能扫一眼看到 - // 自己写的内容是否完整。vendor 模式也可填(覆盖 params 的提示),但默认折叠。 - var hint = it.usage_hint || ""; - var hintBlock = hint - ? "
📘 usage_hint(" + - hint.length + " 字符," + (isPt ? "passthrough 推荐填" : "选填") + ")" + - "
" +
-          IP.esc(hint) + "
" - : (isPt - ? "
⚠️ passthrough 模式推荐填写 usage_hint,让 /api/v1/me 下发给用户 AI 后 AI 能自己拼出调用语法
" - : ""); - - return "" + - "" + IP.esc(it.slug) + "" + modeTag + - (it.name ? "
" + IP.esc(it.name) + "
" : "") + - (it.desc ? "
" + IP.esc(it.desc) + "
" : "") + - hintBlock + - "" + - "" + (it.asset_id ? IP.esc(it.asset_id) : "—") + "" + - "" + IP.esc(url) + "" + - "
" + - "" + - (isPt - ? "" - : "") + - "
" + - "" + supplier + "" + - "" + (enabled ? "启用中" : "已停用") + "" + - "" + IP.esc(it.created_at_text) + "" + - "
" + - "" + - "" + - toggle + - "" + - "
" + - ""; - }).join(""); - } - - // ---------------- 列表操作 ---------------- - $("apixBody").addEventListener("click", function (e) { - var btn = e.target.closest("button[data-act]"); - if (!btn) return; - var act = btn.getAttribute("data-act"); - var slug = btn.getAttribute("data-slug"); - - if (act === "copy") { - IP.copyText(btn.getAttribute("data-url"), "调用地址"); - return; - } - - if (act === "test") { - var label = btn.textContent; - var restore = function () { btn.disabled = false; btn.textContent = label; }; - btn.disabled = true; btn.textContent = "测试中…"; - var t0 = Date.now(); - IP.api("POST", "/api/admin/apix/test", { slug: slug }) - .then(function (d) { - var data = d.data || {}; - var inner = data.data || data; - var bal = (inner && (inner.current_balance_usd !== undefined ? inner.current_balance_usd : inner.balance)); - var ms = Date.now() - t0; - IP.toast("✅ " + slug + " 通(" + ms + " ms)" + - (bal !== undefined ? " · 余额 $" + bal : "")); - restore(); - }) - .catch(function (err) { IP.toast("✗ " + slug + ":" + err.message, true); restore(); }); - return; - } - - if (act === "toggle") { - var it = IP.state.apix.items.filter(function (x) { return x.slug === slug; })[0]; - if (!it) return; - btn.disabled = true; - IP.api("POST", "/api/admin/apix/save", { - slug: slug, - asset_id: it.asset_id, - enabled: btn.getAttribute("data-enabled") === "1" - }).then(function (r) { IP.toast(r.msg); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); btn.disabled = false; }); - } else if (act === "edit") { - var it2 = IP.state.apix.items.filter(function (x) { return x.slug === slug; })[0]; - if (!it2) return; - openForm(it2); - } else if (act === "del") { - if (!confirm("确认删除代理 " + slug + "?调用方将立即 404。")) return; - btn.disabled = true; - IP.api("POST", "/api/admin/apix/delete", { slug: slug }) - .then(function (r) { IP.toast(r.msg); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); btn.disabled = false; }); - } - }); - - $("newApixBtn").addEventListener("click", function () { openForm(null); }); - - IP.boot("apix", function (s) { render(s); }); -})(); diff --git a/www/assets/cache.js b/www/assets/cache.js deleted file mode 100644 index 9deb3e1..0000000 --- a/www/assets/cache.js +++ /dev/null @@ -1,488 +0,0 @@ -/* ============================================================================ - 制品缓存管理页(cache.html) - - 数据源单一:`GET /api/admin/cache` 一次返回「上游表 + 是否生效 + 下游接入 - 命令 + 命中计数 + 变量契约」。UI 不做任何拼接——下游命令文案由后端 - `config::CLIENT_HINTS` 下发(前缀与路由强耦合,写在前端必然漂移)。 - - 交互:编辑(弹窗)/ 测试连通性 / 删除 / 一键复制接入命令。 - ========================================================================== */ -(function () { - "use strict"; - - var D = null; // 最近一次快照(/api/admin/cache 的 data) - var loading = false; - - function load(scan) { - if (loading) return Promise.resolve(); - loading = true; - // scan=1 → 顺带盘点磁盘(秒级,大 zone 慎点);默认只读 nginx 记账(O(1)) - return IP.api("GET", "/api/admin/cache" + (scan ? "?scan=1" : "")) - .then(function (r) { D = r.data; render(); }) - .catch(function (e) { IP.toast(e.message, true); }) - .finally(function () { loading = false; }); - } - - // ---------------- 渲染 ---------------- - function render() { - if (!D) return; - var items = IP.arr(D.items); - - IP.$("cacheEntry").innerHTML = - "网关入口:" + IP.esc(D.entry) + " · " + - "已配置 " + D.configured + " / " + D.count + " 个路由 · " + - "生效中 " + D.active + " · " + - "连通性探针:" + IP.esc(D.probe_prefix) + "<route>(仅内网可达)"; - - IP.$("cacheBody").innerHTML = items.map(row).join(""); - renderCapacity(); - renderStats(); - renderVars(); - } - - function row(it) { - var status; - if (it.active) { - status = '生效中'; - } else if (!it.configured) { - status = '未配置'; - } else if (!it.enabled) { - status = '已停用'; - } else { - status = '未生效'; - } - - // 「一键复制」只给主路由(route == eco)显示:cargo-dl / pypi-files 属于 - // cargo / pypi 生态,客户端配置同一条,重复给按钮只会让人以为要配两遍。 - var isPrimary = it.route === it.eco; - var down; - if (isPrimary && it.client) { - down = - '
' + IP.esc(D.entry + it.uri) + '
' + - ''; - } else if (isPrimary) { - down = '
' + IP.esc(D.entry + it.uri) + '
'; - } else { - down = - '
' + IP.esc(D.entry + it.uri) + '
' + - '计入 ' + IP.esc(it.eco) + ' 生态'; - } - - var keyCell = it.key_set - ? '' + IP.esc(it.key_masked) + '' - : '无(不注入鉴权头)'; - - var ops = - ' ' + - (it.active - ? ' ' - : "") + - (it.configured - ? '' - : ""); - - return "" + - "" + IP.esc(it.eco) + "" + (isPrimary ? "" : "
" + IP.esc(it.route) + "") + "" + - "" + IP.esc(it.uri) + "
" + down + "" + - "" + (it.base ? "" + IP.esc(it.base) + "" : '未配置') + - (it.base && it.base !== it.default_base ? '
官方源:' + IP.esc(it.default_base) + "" : "") + "" + - "" + keyCell + "" + - "" + status + "" + - "" + ops + "" + - ""; - } - - // ---------------- 容量与淘汰 ---------------- - /// 字节人类可读。保留一位小数——「50 GB 与 49.8 GB」这种差别要看得出来。 - function fmtBytes(n) { - n = Number(n) || 0; - if (n < 1024) return n + " B"; - var u = ["KB", "MB", "GB", "TB", "PB"], i = -1; - do { n /= 1024; i++; } while (n >= 1024 && i < u.length - 1); - return (Math.round(n * 10) / 10) + " " + u[i]; - } - - function fmtSecs(s) { - s = Number(s) || 0; - if (s >= 86400) return Math.round(s / 86400) + " 天"; - if (s >= 3600) return Math.round(s / 3600) + " 小时"; - return s + " 秒"; - } - - /// 水位条。颜色只看后端下发的 `level`——若在这里再比一遍阈值, - /// 总览页与这页迟早会出现「一个绿一个红」,而数据是同一份。 - function capBar(pct, level) { - var color = level === "crit" ? "#dc2626" : (level === "warn" ? "#f59e0b" : "#16a34a"); - var w = Math.max(0, Math.min(100, Number(pct) || 0)); - return '
' + - '
'; - } - - function renderCapacity() { - var c = D.capacity || {}; - var zones = IP.arr(c.zones); - var body = IP.$("capBody"); - if (!c.available) { - IP.$("capSummary").innerHTML = - '容量读数不可用:' + IP.esc(c.reason || ""); - body.innerHTML = '读不到 proxy_cache 区'; - return; - } - var t = c.totals || {}; - var diskTxt = (t.disk_bytes === null || t.disk_bytes === undefined) - ? "" - : " · 磁盘实测 " + fmtBytes(t.disk_bytes) + ""; - IP.$("capSummary").innerHTML = - "共 " + zones.length + " 个缓存区 · nginx 记账占用 " + fmtBytes(t.used_bytes) + " / " + - fmtBytes(t.limit_bytes) + "(" + t.pct + "%)" + diskTxt + - " · 条目 " + t.entries + " · 偏高 " + (t.warn || 0) + " · 严重 " + (t.crit || 0) + - " · " + (c.scanned - ? '已含磁盘实测:两者差额 = nginx 尚未回收的条目(手工清过缓存时会滞后,见下)' - : '超上限按 LRU 自动淘汰;改容量需改 conf 的 max_size 后 reload'); - body.innerHTML = zones.map(capRow).join(""); - - // 「按制品失效」的下拉跟容量表同源:不硬编码生态列表, - // 免得加了 zone 之后这里少一项、只能靠「全部」兜着。 - var sel = IP.$("capZone"); - var keep = sel.value || "all"; - sel.innerHTML = '' + - zones.map(function (z) { - return '"; - }).join(""); - sel.value = IP.arr(zones).some(function (z) { return z.zone === keep; }) ? keep : "all"; - } - - function capRow(z) { - var lv = z.level; - var badge, note = ""; - if (!z.dir_exists) { - badge = '目录缺失'; - note = '
磁盘目录不存在。nginx 只在启动时创建这些目录、运行期不自愈,' + - '此后每次写缓存都会失败并断开客户端 —— 需 restart(reload 不够)'; - } else if (z.index_pressure) { - badge = '索引吃紧'; - note = '
keys_zone 曾被打满,nginx 已改按条目数强制回收 —— 建议扩大 keys_zone'; - } else if (z.cold || z.loading) { - badge = '装载中'; - note = '
正在从磁盘重建索引(条目数会一路上涨,属正常)'; - } else if (lv === "crit") { - badge = '接近上限'; - } else if (lv === "warn") { - badge = '占用偏高'; - } else { - badge = '正常'; - } - - var routes = IP.arr(z.routes); - var routeNote = routes.length > 1 - ? '
' + IP.esc(routes.join(" / ")) + " 共用本区" - : ""; - var zoneNote = z.eco && z.eco !== z.zone - ? '
zone ' + IP.esc(z.zone) + "" - : ""; - - // 磁盘实测(点了「盘点磁盘」才有)。差额 = nginx 还没回收的条目: - // 手工清过缓存文件时它会明显偏大(节点要等再被访问或到期才释放), - // 所以这个差**如实显示**,而不是替用户抹平。 - var diskLine = ""; - if (z.disk_bytes !== null && z.disk_bytes !== undefined) { - var lag = z.used_bytes - z.disk_bytes; - var lagPct = z.used_bytes > 0 ? Math.abs(lag) / z.used_bytes : 0; - var lagTxt = lagPct > 0.02 - ? ' 账比盘多 ' + fmtBytes(lag) + "" - : ""; - diskLine = '
磁盘实测 ' + fmtBytes(z.disk_bytes) + - " / " + z.disk_files + " 文件" + (z.disk_truncated ? "(已截断)" : "") + lagTxt + "
"; - } - - return "" + - "" + IP.esc(z.eco || z.zone) + "" + routeNote + zoneNote + "" + - "" + IP.esc(z.dir) + "" + - '
块 ' + fmtBytes(z.bsize) + " · inactive " + fmtSecs(z.inactive_secs) + "" + - "" + capBar(z.pct, lv) + - '
nginx 记账 ' + fmtBytes(z.used_bytes) + " / " + - fmtBytes(z.limit_bytes) + " " + z.pct + "%
" + diskLine + "" + - "" + z.entries + "" + - "" + fmtBytes(z.keys_zone_bytes) + - '
上限约 ' + (z.entries_cap_est || "-") + " 条" + - "" + badge + note + "" + - '' + - ""; - } - - /// 清空一个缓存区(`all` = 全部)。 - /// - /// 删除必须由后端做——**只删文件、不删目录**。手工 `rm -rf cache/` 会让 - /// 该路由此后每次写缓存都 [crit] mkdir 失败并断开客户端(直到 restart), - /// 这个坑在脚本里踩过一次。 - function purge(zone) { - var z = IP.arr((D.capacity || {}).zones).filter(function (x) { return x.zone === zone; })[0]; - var what = zone === "all" ? "全部缓存区" : ("「" + ((z && (z.eco || z.zone)) || zone) + "」"); - var detail = z ? "\n将删除 " + z.entries + " 个条目(约占 " + fmtBytes(z.used_bytes) + ")" : ""; - if (!window.confirm("确定清空 " + what + " 的磁盘缓存?" + detail + "。\n" + - "目录本身保留;清空后下次请求重新回源,不影响正确性。\n" + - "(nginx 的容量记账要等下一轮 cache manager 才回落,刚清完可能仍显示旧值)")) return; - IP.api("POST", "/api/admin/cache/purge", { zone: zone }).then(function (r) { - var t = r.data.total || {}; - IP.toast(r.msg + " 释放 " + fmtBytes(t.bytes)); - load(); - }).catch(function (e) { IP.toast(e.message, true); }); - } - - // ---------------- 按制品失效(两步:预览 → 确认) ---------------- - - var lastPreview = null; // 上一次预览的结果,用于「确认失效」时复述删什么 - - /// 把缓存的命中结果渲染出来。命中为空也要明说 —— 最常见的情况其实是 - /// 「关键字拼错了 / 记错了 key 形态」,沉默会让人以为功能坏了。 - function showInval(r, applied) { - var sum = IP.$("capInvalResult"); - var box = IP.$("capInvalKeys"); - var d = (r && r.data) || {}; - var t = d.total || {}; - var lines = []; - - if (!t.matched) { - box.style.display = "none"; - box.textContent = ""; - sum.innerHTML = '没有命中任何条目' + - ' · 请确认关键字;cache key 形如 <路由>:<URI><方法><Accept>' + - ',例如 npm:/npm/lodashGET*/*(可先填 * 预览一遍看全部形态)'; - return; - } - - IP.arr(d.items).forEach(function (it) { - if (!it.matched) return; - lines.push("# " + it.zone + ":" + - (applied ? ("已删除 " + it.deleted + " 个") : (it.matched + " 个命中")) + - " " + fmtBytes(it.bytes)); - IP.arr(it.keys).forEach(function (k) { lines.push(" → " + k); }); - if (it.matched > IP.arr(it.keys).length) { - lines.push(" …另有 " + (it.matched - IP.arr(it.keys).length) + " 个同类条目"); - } - }); - - sum.innerHTML = (applied - ? '已失效 ' - : '预览(未删除) ') + - "共 " + t.matched + " 个 / " + fmtBytes(t.bytes) + - (d.truncated - ? ' ⚠️ 已达单次上限,数字是下界' + - (applied ? "" : ";请把关键字写窄一些再执行") + "" - : ""); - box.textContent = lines.join("\n"); - box.style.display = ""; - } - - function invalidate(apply) { - var pat = (IP.$("capMatch").value || "").trim(); - if (!pat) { IP.toast("先填要失效的制品关键字", true); return Promise.resolve(); } - var zone = IP.$("capZone").value || "all"; - - if (apply) { - var t = (lastPreview && lastPreview.total) || {}; - // 二次确认:把「删什么、删多少」复述清楚,而不是一句「确定吗」 - if (!window.confirm("确定失效「" + pat + "」?\n" + - "范围:" + (zone === "all" ? "全部缓存区" : zone) + "\n" + - "将删除 " + (t.matched || "?") + " 个条目(约 " + fmtBytes(t.bytes || 0) + ")\n" + - "目录本身保留;删掉的只是磁盘副本,下次请求重新回源,不影响正确性。")) { - return Promise.resolve(); - } - } - - IP.$("capApply").disabled = true; - return IP.api("POST", "/api/admin/cache/invalidate", - { zone: zone, match: pat, apply: apply ? 1 : 0 }) - .then(function (r) { - if (apply) { - lastPreview = null; - IP.toast(r.msg); - load(); - } else { - lastPreview = r.data; - // 只有真的命中了才允许进入「确认」——否则按钮会诱人误点 - IP.$("capApply").disabled = !((r.data.total || {}).matched > 0); - } - showInval(r, apply); - }) - .catch(function (e) { - IP.toast(e.message, true); - IP.$("capApply").disabled = true; - }); - } - - function renderStats() { - var s = (D.stats && D.stats.by_ecosystem) || {}; - var order = ["go", "cargo", "pypi", "npm", "maven", "docker", "global"]; - IP.$("statsBody").innerHTML = order.map(function (eco) { - var m = s[eco]; - if (!m) return ""; - var hit = m.HIT || 0; - var miss = m.MISS || 0; - var denom = hit + miss; - var rate = denom ? Math.round((hit / denom) * 1000) / 10 + "%" : "-"; - var cls = eco === "global" ? ' style="font-weight:600"' : ""; - return "" + - "" + IP.esc(eco) + "" + - "" + hit + "" + miss + "" + - "" + (m.BYPASS || 0) + "" + (m.EXPIRED || 0) + "" + - "" + (m.REVALIDATED || 0) + "" + (m.UPDATING || 0) + "" + - "" + (m.STALE || 0) + "" + - "" + rate + ""; - }).join(""); - } - - function renderVars() { - IP.$("varBody").innerHTML = IP.arr(D.variables).map(function (v) { - return "" + IP.esc(v.name) + "" + IP.esc(v.desc) + ""; - }).join(""); - } - - // ---------------- 编辑弹窗 ---------------- - /// 凭据字段刻意用「勾选才提交」:JSON body 里 key 字段**不出现** = 保留原值, - /// 出现空串 = 清空。若默认提交空串,打开弹窗改个备注就会把上游凭据抹掉。 - function edit(route) { - var it = (D.items || []).filter(function (x) { return x.route === route; })[0] || {}; - IP.modal({ - title: "上游配置 · " + route, - wide: true, - submitText: "保存", - html: - '
' + - '
' + - '
' + - '
' + - '' + - '' + - '
必须带 http:// 或 https://,不要带尾斜杠。转发的目标 = 本地址 + location 前缀之后的路径。
' + - '
' + - '' + - '' + - '
填完整的 Authorization 头值(如 Bearer xxx / Basic yyy),不是只填 token —— 换成上游就换一套,模块不去猜 scheme。' + - '留空则透传客户端自带的 Authorization(Docker Hub 的短期 Bearer token 走这条);' + - '无论哪种,本网关自己的 sk_ 都会被剔除,不会传给上游。
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - '
' + - "
", - onMount: function (card, close) { - var setKey = card.querySelector("#setKey"); - var keyInput = card.querySelector('input[name="key"]'); - setKey.addEventListener("change", function () { - keyInput.disabled = !setKey.checked; - if (setKey.checked) keyInput.focus(); - }); - card.querySelector("#fillDefault").addEventListener("click", function () { - card.querySelector('input[name="base"]').value = it.default_base || ""; - }); - card.querySelector("form").addEventListener("submit", function (e) { - e.preventDefault(); - var f = e.target; - var body = { - route: route, - base: f.base.value.trim(), - name: f.name.value.trim(), - desc: f.desc.value.trim(), - note: f.note.value.trim(), - enabled: card.querySelector("#enabled").checked - }; - // 只有勾了「修改凭据」才带 key 字段(空串 = 清空) - if (setKey.checked) body.key = keyInput.value; - IP.api("POST", "/api/admin/cache/save", body).then(function (r) { - close(); - IP.toast("已保存:" + r.data.route + (r.data.active ? "(生效中)" : "(未生效)")); - load(); - }).catch(function (err) { IP.toast(err.message, true); }); - }); - } - }); - } - - // ---------------- 连通性测试 ---------------- - /// 走 `/_cache_test/`:与真实转发同一套「拼目标 + 换凭据」逻辑, - /// 所以这里通了 = 真实请求能到上游。上游响应原样返回,故用原生 fetch 读文本 - /// (不能走 IP.api:它假定响应是 ipass 的 JSON 信封)。 - function test(route) { - IP.toast("正在测试 " + route + " …"); - fetch("/api/admin/cache/test?route=" + encodeURIComponent(route), { - method: "POST", - credentials: "same-origin", - headers: { "Content-Type": "application/json" }, - body: "{}" - }).then(function (res) { - return res.text().then(function (t) { - var brief = t.replace(/\s+/g, " ").slice(0, 200); - IP.toast(route + " → HTTP " + res.status + " " + brief, !res.ok); - }); - }).catch(function (e) { IP.toast(route + " 测试失败:" + e.message, true); }); - } - - // ---------------- 删除 ---------------- - function del(route) { - if (!window.confirm("确定删除路由 " + route + " 的上游配置?\n删除后该生态立即返回 503,已缓存的制品在磁盘上仍可命中。")) return; - IP.api("POST", "/api/admin/cache/delete", { route: route }).then(function () { - IP.toast("已删除 " + route); - load(); - }).catch(function (e) { IP.toast(e.message, true); }); - } - - // ---------------- 事件委托 ---------------- - document.addEventListener("click", function (e) { - var t = e.target; - if (!t || !t.getAttribute) return; - var copy = t.getAttribute("data-copy"); - var edit_ = t.getAttribute("data-edit"); - var test_ = t.getAttribute("data-test"); - var del_ = t.getAttribute("data-del"); - var purge_ = t.getAttribute("data-purge"); - if (copy) { - var it = (D.items || []).filter(function (x) { return x.route === copy; })[0]; - var cmd = it && it.client && it.client.command; - if (cmd) IP.copyText(cmd, "「" + copy + "」接入命令"); - else IP.toast("该路由没有独立的客户端配置", true); - return; - } - if (edit_) return edit(edit_); - if (test_) return test(test_); - if (del_) return del(del_); - if (purge_) return purge(purge_); - }); - - IP.$("cRefresh").addEventListener("click", function () { - load().then(function () { IP.toast("已刷新"); }); - }); - - IP.$("capRefresh").addEventListener("click", function () { - load().then(function () { IP.toast("容量读数已刷新"); }); - }); - - IP.$("capScan").addEventListener("click", function () { - IP.toast("正在盘点磁盘…"); - load(true).then(function () { IP.toast("磁盘盘点完成"); }); - }); - - IP.$("capPurgeAll").addEventListener("click", function () { purge("all"); }); - - IP.$("capPreview").addEventListener("click", function () { invalidate(false); }); - IP.$("capApply").addEventListener("click", function () { invalidate(true); }); - // 改了关键字就把上一次的预览作废 —— 否则「确认失效」会拿着旧结果去删 - IP.$("capMatch").addEventListener("input", function () { - lastPreview = null; - IP.$("capApply").disabled = true; - IP.$("capInvalResult").innerHTML = ""; - IP.$("capInvalKeys").style.display = "none"; - IP.$("capInvalKeys").textContent = ""; - }); - IP.$("capMatch").addEventListener("keydown", function (e) { - if (e.key === "Enter") invalidate(false); - }); - - // 页面入口:boot 会先确认管理会话、装外壳,再调本回调 - IP.boot("cache", function () { load(); }); -})(); diff --git a/www/assets/chart.js b/www/assets/chart.js deleted file mode 100644 index 507734f..0000000 --- a/www/assets/chart.js +++ /dev/null @@ -1,141 +0,0 @@ -/* ============================================================================ - 图表:纯 SVG / HTML,**零外部依赖** - - 为什么不用 Chart.js / ECharts:管理台是网关容器里的一把静态文件, - 引 CDN 等于把面板可用性押在公网可达性上(内网部署直接白屏), - 引本地副本又要把几百 KB 第三方代码塞进镜像。趋势图只有折线和条形两种, - 自己画不到 200 行,且颜色/字体能直接吃页面的 CSS 变量。 - ========================================================================== */ -window.IP = window.IP || {}; -IP.chart = (function () { - "use strict"; - - var VB_W = 720; // viewBox 宽度;实际宽度由 CSS 拉满容器 - var COLOR = ["#2563eb", "#0d9488", "#7c3aed", "#ea580c", "#0891b2", "#db2777"]; - - /// 轴上限取整到 1/2/2.5/5/10 × 10^n,避免 y 轴刻度出现 8734 这种数 - function niceMax(v) { - if (!(v > 0)) return 1; - var exp = Math.pow(10, Math.floor(Math.log10(v))); - var f = v / exp; - var n = f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10; - return n * exp; - } - - /// 大数简写:12345 → 1.2万。图表刻度里写全串数字会挤成一团 - function fmtNum(n) { - n = Number(n) || 0; - if (n >= 100000000) return (n / 100000000).toFixed(1).replace(/\.0$/, "") + "亿"; - if (n >= 10000) return (n / 10000).toFixed(n >= 1000000 ? 0 : 1).replace(/\.0$/, "") + "万"; - return String(n); - } - - function empty(el, text) { - if (el) el.innerHTML = '
' + IP.esc(text || "暂无数据") + "
"; - } - - /** - * 折线(面积)图。 - * @param el 容器元素 - * @param opts.labels x 轴标签(如 ["09-07", ...]) - * @param opts.series [{ name, values, color, fill }] - * @param opts.height 图形高度(px,默认 220) - */ - function line(el, opts) { - if (!el) return; - opts = opts || {}; - var labels = opts.labels || []; - var series = (opts.series || []).filter(function (s) { return s && s.values && s.values.length; }); - if (!labels.length || !series.length) return empty(el, opts.emptyText || "该区间内还没有数据"); - - var H = opts.height || 220; - var L = 48, R = 14, T = 16, B = 26; - var n = labels.length; - var max = 0; - series.forEach(function (s) { - s.values.forEach(function (v) { if (v > max) max = v; }); - }); - max = niceMax(max); - - var iw = VB_W - L - R, ih = H - T - B; - var X = function (i) { return n === 1 ? L + iw / 2 : L + (iw * i) / (n - 1); }; - var Y = function (v) { return T + ih * (1 - v / max); }; - - var parts = []; - - // 网格 + y 轴刻度(5 条,含 0 与顶) - for (var g = 0; g <= 4; g++) { - var yv = (max * g) / 4, y = Y(yv); - parts.push(''); - parts.push('' + fmtNum(yv) + ""); - } - // x 轴 - parts.push(''); - - // x 轴标签:点多时抽稀,最多 8 个,否则 14 天标签会互相叠 - var step = Math.ceil(n / 8); - for (var i = 0; i < n; i++) { - if (i % step !== 0 && i !== n - 1) continue; - parts.push('' + - IP.esc(labels[i]) + ""); - } - - series.forEach(function (s, si) { - var color = s.color || COLOR[si % COLOR.length]; - var pts = s.values.map(function (v, i) { return X(i).toFixed(1) + "," + Y(v).toFixed(1); }).join(" "); - if (s.fill !== false && series.length === 1) { - parts.push(''); - } - parts.push(''); - // 点:带 ,鼠标停上去显示「日期 · 序列名:值」 - s.values.forEach(function (v, i) { - parts.push('<circle class="dot" cx="' + X(i).toFixed(1) + '" cy="' + Y(v).toFixed(1) + '" r="2.8" fill="' + color + '">' + - "<title>" + IP.esc(labels[i] + " · " + s.name + ":" + v) + ""); - }); - }); - - var legend = series.map(function (s, si) { - var color = s.color || COLOR[si % COLOR.length]; - return '' + IP.esc(s.name) + ""; - }).join(""); - - el.innerHTML = - (series.length > 1 ? '
' + legend + "
" : "") + - // 不设 preserveAspectRatio="none":那会按容器横向拉伸,圆点变椭圆、文字变形。 - // 保持默认等比缩放(CSS 里 height:auto),图表随宽度整体放大,文字始终正。 - '' + - parts.join("") + ""; - } - - /** - * 横向条形图(HTML 实现:文字对齐与换行交给浏览器,比 SVG text 稳)。 - * @param opts.items [{ label, value, sub, color }] 已按业务排序 - * @param opts.valueText 自定义右侧数值文本 - */ - function bars(el, opts) { - if (!el) return; - opts = opts || {}; - var items = opts.items || []; - if (!items.length) return empty(el, opts.emptyText || "该区间内还没有数据"); - - var max = 0; - items.forEach(function (it) { if (it.value > max) max = it.value; }); - if (max <= 0) max = 1; - - el.innerHTML = items.map(function (it, i) { - var pct = Math.max(2, Math.round((it.value / max) * 100)); - var color = it.color || COLOR[i % COLOR.length]; - var right = opts.valueText ? opts.valueText(it) : "" + fmtNum(it.value) + "" + - (it.sub ? ' ' + IP.esc(it.sub) + "" : ""); - return '
' + - '
' + IP.esc(it.label) + "
" + - '
' + - '
' + right + "
" + - "
"; - }).join(""); - } - - return { line: line, bars: bars, fmtNum: fmtNum, niceMax: niceMax, COLOR: COLOR }; -})(); diff --git a/www/assets/core.js b/www/assets/core.js deleted file mode 100644 index 4ced019..0000000 --- a/www/assets/core.js +++ /dev/null @@ -1,316 +0,0 @@ -/* ============================================================================ - 管理台内核:请求封装、登录态守卫、外壳(顶栏 + Tab)、数据加载 - - 多页改造后的分工: - core.js —— 每页都要用的东西(fetch 封装 / 转义 / toast / 外壳 / 数据装载) - chart.js —— 纯 SVG 图表 - .js —— 只管自己那一页的渲染与交互 - - 约定:所有 API 用**绝对路径** `/api/...`,页面用 ``, - 于是不论页面挂在 /admin 还是 /admin/xxx.html,资源与接口都不会错位。 - ========================================================================== */ -window.IP = (function () { - "use strict"; - - var TABS = [ - { key: "overview", name: "数据总览", href: "overview.html" }, - { key: "review", name: "审核队列", href: "review.html", pill: "pillPending" }, - { key: "domains", name: "全部域名", href: "domains.html" }, - { key: "users", name: "账号管理", href: "users.html" }, - { key: "upstreams", name: "LLM 上游", href: "upstreams.html" }, - { key: "apix", name: "API 代理", href: "apix.html" }, - { key: "cache", name: "制品缓存", href: "cache.html" }, - { key: "usage", name: "用量统计", href: "usage.html" }, - { key: "hourly", name: "24h 热力", href: "hourly.html" }, - { key: "me", name: "我的用量", href: "me.html" } - ]; - - var state = { - me: null, - users: [], - domains: [], - upstreams: [], - apix: { items: [] }, - usage: { total: {}, tokens: {}, users: [], models: [] }, - trend: null, - trendDays: 14, - pending: 0, - // 子域名命名规则。真源在后端 config.rs,由 /api/admin/domains 下发, - // 前端不硬编码前缀/后缀/zone——否则改了后端常量页面还在拼旧值 - subRule: { zone: "", prefix: "i", suffix: "dm", digits: 8 } - }; - - var currentRender = null; - - function $(id) { return document.getElementById(id); } - - function esc(v) { - if (v === null || v === undefined) return ""; - return String(v).replace(/[&<>"']/g, function (c) { - return ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]; - }); - } - - function arr(v) { return Array.isArray(v) ? v : []; } - - function toast(msg, isErr) { - var el = $("toast"); - if (!el) return; - el.textContent = msg; - el.className = "show" + (isErr ? " err" : ""); - clearTimeout(el._t); - el._t = setTimeout(function () { el.className = ""; }, 2600); - } - - function api(method, path, body) { - var opt = { method: method, credentials: "same-origin", headers: {} }; - if (body) { - opt.headers["Content-Type"] = "application/json"; - opt.body = JSON.stringify(body); - } - return fetch(path, opt).then(function (res) { - return res.json().catch(function () { return { code: res.status, msg: "响应解析失败" }; }) - .then(function (data) { - if (res.status === 401 && path.indexOf("/login") === -1 && path !== "/api/admin/session") { - // 多页之后没有「就地切回登录卡片」这回事,直接送回登录页 - // 例外:/api/admin/session 是登录页自己用来探「是否已登录」的, - // 401 = 未登录(正常态),不能在这里重定向,否则登录页会自刷新死循环 - location.replace("login.html"); - throw new Error(data.msg || "会话已过期,请重新登录"); - } - if (!res.ok) throw new Error(data.msg || ("请求失败 HTTP " + res.status)); - return data; - }); - }); - } - - // 统一复制入口:非安全上下文下 navigator.clipboard 不可用,退回 prompt 让用户手抄 - function copyText(text, label) { - var name = label || "内容"; - var done = function () { toast(name + "已复制:" + text); }; - if (navigator.clipboard && navigator.clipboard.writeText) { - navigator.clipboard.writeText(text).then(done, function () { - window.prompt("手动复制" + name + ":", text); - }); - } else { - window.prompt("手动复制" + name + ":", text); - } - } - - // ---------------- 子域名规则:`i` + 8 位随机数字 + `dm` ---------------- - // 后缀必须是 dm:企业域名 server 的正则是 ^(.+dm)\.mayishangshu\.cn$, - // 不以 dm 结尾的子域名建出来也匹配不上转发 server(规则在 domains::gen_subdomain)。 - function randDigits(n) { - var s = ""; - for (var i = 0; i < n; i++) s += Math.floor(Math.random() * 10); - return s; - } - - /// 端口跟随调用方:面板走 :88 访问,复制的域名就带 :88(readme §15 同理) - function portSuffix() { return location.port ? (":" + location.port) : ""; } - - function fullHost(sub) { return sub + "." + state.subRule.zone; } - - // ---------------- 外壳 ---------------- - function mountShell(active) { - var host = $("shell"); - if (!host) return; - - var me = state.me || {}; - var tabs = TABS.map(function (t) { - var pill = t.pill ? '' : ""; - return '' + - t.name + pill + ""; - }).join(""); - - host.innerHTML = - '
' + - '
尚数网 山海关管理控制台
' + - '
' + - '' + esc(me.username || "-") + " · " + - (me.role === "admin" ? "管理员" : "普通账号") + "" + - '' + - '' + - "
" + - "
" + - '
' + tabs + "
"; - - $("refreshBtn").addEventListener("click", function () { - loadAll().then(function () { toast("已刷新"); }); - }); - $("logoutBtn").addEventListener("click", function () { - api("POST", "/api/admin/logout") - .then(function () { location.replace("login.html"); }) - .catch(function () { location.replace("login.html"); }); - }); - } - - function syncPendingPill() { - var pill = $("pillPending"); - if (!pill) return; - if (state.pending > 0) { pill.hidden = false; pill.textContent = state.pending; } - else { pill.hidden = true; } - } - - // ---------------- 数据加载 ---------------- - function loadAll() { - return Promise.all([ - api("GET", "/api/admin/domains"), - api("GET", "/api/admin/users"), - api("GET", "/api/admin/upstreams"), - // API 代理是后加的板块,老镜像没有这两个接口——缺了不能让整个面板挂掉 - api("GET", "/api/admin/apix").catch(function () { - return { data: { items: [] } }; - }), - // 老版本后端没有用量接口时不要让整个面板挂掉 - api("GET", "/api/admin/usage").catch(function () { - return { data: { total: {}, tokens: {}, users: [], models: [] } }; - }), - api("GET", "/api/admin/trend?days=" + state.trendDays).catch(function () { return { data: null }; }) - ]).then(function (res) { - state.domains = arr(res[0].data.items); - state.pending = res[0].data.pending || 0; - if (res[0].data.subdomain_rule && res[0].data.subdomain_rule.zone) { - state.subRule = res[0].data.subdomain_rule; - } - state.users = arr(res[1].data.items); - state.upstreams = arr(res[2].data.items); - state.apix = res[3].data || { items: [] }; - state.usage = res[4].data || { total: {}, tokens: {}, users: [], models: [] }; - state.trend = res[5].data || null; - syncPendingPill(); - if (currentRender) currentRender(state); - autoProbeUpstreams(); - }).catch(function (err) { - toast(err.message, true); - }); - } - - function reload() { return loadAll(); } - - // ---------------- 上游健康自动探测 ---------------- - // 「失效的自动缓存,有人来看就顺手更新」:真实流量本来就会更新 uh: 缓存, - // 这里补的是**没有流量**的上游——打开上游页时对「未探测 / 失效」的启用上游 - // 逐个发一次 1-token 探测(走 /api/admin/upstreams/test,与手动「测试」 - // 按钮同一条转发链路),探测结果由网关 log 阶段写回缓存,最后刷新一次列表。 - var probing = false; - var probeTried = {}; // 本会话已自动探过的 slot:真失效的上游探完仍是 failed, - // 不加标记的话每次 loadAll 都会对它再来一轮探测(死循环打上游) - function autoProbeUpstreams() { - if (probing || !$("upstreamsBody")) return; - var stale = state.upstreams.filter(function (u) { - return u.enabled && (u.status || "unknown") !== "ok" && !probeTried[u.slot]; - }); - if (!stale.length) return; - probing = true; - var chain = Promise.resolve(); - stale.forEach(function (u) { - probeTried[u.slot] = true; - chain = chain.then(function () { - var model = arr(u.models)[0] || "gpt-4o-mini"; - return fetch("/api/admin/upstreams/test?slot=" + encodeURIComponent(u.slot), { - method: "POST", - credentials: "same-origin", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ model: model, max_tokens: 1, stream: false, messages: [{ role: "user", content: "ping" }] }) - }).catch(function () {}).then(function () { /* 结果只落在网关缓存,这里不关心状态码 */ }); - }); - }); - chain.then(function () { return loadAll(); }).finally(function () { probing = false; }); - } - - // ---------------- 公共小部件 ---------------- - function typeBadge(t) { - return t === "long" - ? '长期' - : '临时 6h'; - } - - function statusBadge(s) { - var map = { - pending: ["b-warn", "待审核"], - approved: ["b-ok", "已放行"], - rejected: ["b-err", "已驳回"], - expired: ["b-gray", "已过期"] - }; - var it = map[s] || ["b-gray", s]; - return '' + it[1] + ""; - } - - /// 优先展示名(中文姓名),空则回落账号名 - function displayName(u) { return (u && (u.name || u.display_name)) || (u && u.username) || "-"; } - - // ---------------- 弹窗(modal) ---------------- - // 编辑内容较多的表单(API 代理 / LLM 上游)用弹窗操作,避免长表单把列表顶下去。 - // 用法:IP.modal({ title, submitText, html, onMount(card, close) }); - // html 里放一个
,弹窗「保存」按钮会触发该 form 的 submit(带原生 required 校验)。 - function modal(opts) { - opts = opts || {}; - var overlay = document.createElement("div"); - overlay.className = "modal-overlay"; - overlay.innerHTML = - ''; - document.body.appendChild(overlay); - - var closed = false; - function close() { - if (closed) return; - closed = true; - if (overlay.parentNode) overlay.parentNode.removeChild(overlay); - } - overlay.addEventListener("click", function (e) { if (e.target === overlay) close(); }); - overlay.querySelector(".modal-close").addEventListener("click", close); - overlay.querySelector(".modal-cancel").addEventListener("click", close); - var onKey = function (e) { - if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKey); } - }; - document.addEventListener("keydown", onKey); - - var card = overlay.querySelector(".modal-card"); - var form = card.querySelector("form"); - var okBtn = overlay.querySelector(".modal-ok"); - if (form) { - okBtn.addEventListener("click", function () { - if (form.requestSubmit) form.requestSubmit(); - else form.dispatchEvent(new Event("submit", { cancelable: true })); - }); - } else if (opts.onOk) { - okBtn.addEventListener("click", function () { opts.onOk(close); }); - } - if (opts.onMount) opts.onMount(card, close); - - var first = card.querySelector("input,textarea,select"); - if (first) first.focus(); - return close; - } - - // ---------------- 启动 ---------------- - /// 每页入口:先确认会话 → 装外壳 → 拉数据 → 交给页面自己的 render - function boot(page, render) { - currentRender = render || null; - api("GET", "/api/admin/session").then(function (r) { - state.me = r.data; - mountShell(page); - return loadAll(); - }).catch(function () { - location.replace("login.html"); - }); - } - - return { - TABS: TABS, state: state, - $: $, esc: esc, arr: arr, toast: toast, api: api, copyText: copyText, - randDigits: randDigits, portSuffix: portSuffix, fullHost: fullHost, - typeBadge: typeBadge, statusBadge: statusBadge, displayName: displayName, - modal: modal, - boot: boot, loadAll: loadAll, reload: reload - }; -})(); diff --git a/www/assets/domains.js b/www/assets/domains.js deleted file mode 100644 index be68789..0000000 --- a/www/assets/domains.js +++ /dev/null @@ -1,129 +0,0 @@ -/* 全部域名:新建(直接放行)+ 列表(复制 / 删除)*/ -(function () { - "use strict"; - - var $ = IP.$; - - // ---------------- 子域名输入 ---------------- - function subValue() { - return IP.state.subRule.prefix + $("cdSubRand").value.trim() + IP.state.subRule.suffix; - } - - function syncSubPreview() { - var v = $("cdSubRand").value.trim(); - $("cdSubPreview").textContent = v - ? "完整域名:" + IP.fullHost(subValue()) + IP.portSuffix() - : ""; - } - - function rollSub() { - $("cdSubRand").value = IP.randDigits(IP.state.subRule.digits || 8); - syncSubPreview(); - } - - /// 把后端下发的规则套到输入框上(固定段文字 / 最大位数 / 首次自动摇一个号) - function applySubRule() { - var d = IP.state.subRule.digits || 8; - $("cdSubPre").textContent = IP.state.subRule.prefix; - $("cdSubSuf").textContent = IP.state.subRule.suffix; - $("cdSubRand").maxLength = d; - $("cdSubRand").placeholder = d + "位数字"; - if (!$("cdSubRand").value) rollSub(); else syncSubPreview(); - } - - // ---------------- 列表 ---------------- - function render(s) { - var body = $("domainsBody"); - if (!s.domains.length) { - body.innerHTML = '还没有任何域名'; - } else { - body.innerHTML = s.domains.map(function (d) { - var expiry = "-"; - if (d.type === "temp") { - if (d.status === "approved" && d.expires_left > 0) { - expiry = "" + IP.esc(d.expires_at_text) + "" + - "
剩余 " + IP.esc(d.expires_left_text) + "
"; - } else if (d.status === "expired") { - expiry = "" + IP.esc(d.expires_at_text) + "
已失效
"; - } else { - expiry = "通过后开始计时"; - } - } - - var reviewer = ""; - if (d.auto_approved) reviewer = "
免审放行
"; - else if (d.reviewed_by) reviewer = "
by " + IP.esc(d.reviewed_by) + "
"; - - // 完整域名可点即复制(含端口——端口跟随当前访问方式,见 readme §15) - var host = d.host || IP.fullHost(d.subdomain); - return "" + - "" + - "
" + IP.esc(d.subdomain) + " · " + IP.esc(d.id) + "
" + - "" + IP.esc(d.backend) + "" + - "" + IP.typeBadge(d.type) + "" + - "" + IP.esc(d.owner) + "" + - "" + IP.statusBadge(d.status) + reviewer + "" + - "" + expiry + "" + - "
" + - "" + - "
" + - ""; - }).join(""); - } - - // 归属账号下拉 - var sel = $("cdOwner"); - var keep = sel.value; - sel.innerHTML = s.users.map(function (u) { - return ""; - }).join(""); - if (keep) sel.value = keep; - - applySubRule(); - } - - // ---------------- 事件 ---------------- - $("cdSubRand").addEventListener("input", function () { - this.value = this.value.replace(/\D/g, "").slice(0, IP.state.subRule.digits || 8); - syncSubPreview(); - }); - $("cdSubRoll").addEventListener("click", function () { rollSub(); }); - - $("createDomainForm").addEventListener("submit", function (e) { - e.preventDefault(); - IP.api("POST", "/api/admin/domains/create", { - subdomain: subValue(), - backend: $("cdBackend").value.trim(), - type: $("cdType").value, - owner: $("cdOwner").value - }).then(function (r) { - IP.toast(r.msg); - $("cdBackend").value = ""; - // 建完立刻摇下一个号:连着建多个域名时不用手点「换一个」 - rollSub(); - return IP.reload(); - }).catch(function (err) { IP.toast(err.message, true); }); - }); - - $("domainsBody").addEventListener("click", function (e) { - var btn = e.target.closest("button[data-act]"); - if (!btn) return; - var act = btn.getAttribute("data-act"); - - if (act === "copy-domain") { - IP.copyText(btn.getAttribute("data-host") + IP.portSuffix(), "域名"); - return; - } - if (act === "del-domain") { - var id = btn.getAttribute("data-id"); - if (!confirm("确认删除该域名映射?删除后该子域名将立即停止转发。")) return; - btn.disabled = true; - IP.api("POST", "/api/admin/domains/delete", { id: id }) - .then(function (r) { IP.toast(r.msg); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); btn.disabled = false; }); - } - }); - - IP.boot("domains", render); -})(); diff --git a/www/assets/hourly.js b/www/assets/hourly.js deleted file mode 100644 index 3de0125..0000000 --- a/www/assets/hourly.js +++ /dev/null @@ -1,363 +0,0 @@ -/* 24 小时热力视图:直接读 meta.jsonl → 按 (slot, 小时) 聚合 → 渲染 SVG heatmap - 1.0.27 配套前端。 - 零外部依赖:纯 SVG/HTML,用现有的 admin.css 颜色变量 + chart.js fmtNum/niceMax。 -*/ -(function () { - "use strict"; - - var $ = IP.$; - - function num(v) { return Number(v) || 0; } - function esc(s) { return IP.esc(s); } - - /** - * 按 (slot, hour) 二维聚合;每行 = { slot, hours: [{h, req, tin, tout, users:{u:n,...}}], total_req, total_tin, total_tout } - */ - function aggregate(rows) { - var bySlot = {}; // slot -> { hours: array(24), users: Map, total_req, total_tin, total_tout } - for (var i = 0; i < rows.length; i++) { - var r = rows[i]; - var ts = num(r.ts); - if (!ts) continue; - var h = new Date(ts * 1000).getHours(); // 上海时区(meta time 已是 SH,但 Date 对象按浏览器时区,TODO:按 SH 取小时) - var slot = r.slot || "-"; - var user = r.user || "-"; - var tin = num(r.tin); - var tout = num(r.tout); - var req = 1; - if (!bySlot[slot]) { - bySlot[slot] = { slot: slot, hours: new Array(24), users: {}, total_req: 0, total_tin: 0, total_tout: 0 }; - for (var k = 0; k < 24; k++) bySlot[slot].hours[k] = { req: 0, tin: 0, tout: 0, users: {} }; - } - var b = bySlot[slot]; - var bh = b.hours[h]; - bh.req += req; bh.tin += tin; bh.tout += tout; - bh.users[user] = (bh.users[user] || 0) + req; - b.total_req += req; b.total_tin += tin; b.total_tout += tout; - b.users[user] = (b.users[user] || 0) + req; - } - // 排序:按 total_req 降序 - var list = Object.keys(bySlot).map(function (k) { return bySlot[k]; }); - list.sort(function (a, b) { return b.total_req - a.total_req; }); - return list; - } - - /** - * 把每行的 (小时, 用户) 拆开成纯用户 map(聚合小时维度) - */ - function uniqueUsers(bySlot) { - var s = {}; - for (var i = 0; i < bySlot.length; i++) { - var k = Object.keys(bySlot[i].users); - for (var j = 0; j < k.length; j++) s[k[j]] = 1; - } - return Object.keys(s); - } - - function metricVal(bh, metric) { - if (metric === "in") return bh.tin; - if (metric === "out") return bh.tout; - return bh.req; - } - - function metricLabel(metric) { - if (metric === "in") return "入 token"; - if (metric === "out") return "出 token"; - return "请求数"; - } - - function fmt(v, metric) { - if (metric === "requests") return String(v); - return IP.chart.fmtNum(v); - } - - // ─────────────────────────────────────────────────────────────────────── - // Heatmap 渲染(SVG,不依赖 chart.js heatmap 工厂) - // ─────────────────────────────────────────────────────────────────────── - function renderHeatmap(el, bySlot, metric) { - if (!bySlot.length) { - el.innerHTML = '
所选区间内还没有审计数据
'; - return; - } - - // 取全局最大值用于配色 - var max = 0; - for (var i = 0; i < bySlot.length; i++) { - for (var k = 0; k < 24; k++) { - var v = metricVal(bySlot[i].hours[k], metric); - if (v > max) max = v; - } - } - if (max === 0) { - el.innerHTML = '
所选区间内请求数/token 均为 0
'; - return; - } - - var ROW_H = 22; // 每行像素高 - var CELL_W = 32; // 每格宽(24 列 × 32 = 768)+ 标签宽 - var LABEL_W = 110; // slot 标签宽 - var PAD = 36; // 上/下 padding(含坐标轴) - var ROWS = bySlot.length; - var HEIGHT = ROWS * ROW_H + PAD * 2; // 标题区 + 行 - var HEAT_TOP = PAD + 14; // X 轴 0..23 标签占 14px - - var totalH = HEIGHT; - var totalW = CELL_W * 24 + LABEL_W + 30; - - var html = ""; - html += ''; - - // X 轴小时标签(0..23) - html += ''; - for (var h = 0; h < 24; h++) { - if (h % 3 !== 0 && h !== 23) continue; // 间隔 3 小时画标签,末端加 23 - html += '' + h + ''; - } - html += ''; - - // 行:slot label + 24 个色块 - html += ''; - for (var r = 0; r < bySlot.length; r++) { - var slot = bySlot[r]; - var yTop = HEAT_TOP + r * ROW_H; - - // slot 名 - html += '' + - esc(slot.slot) + ''; - - // 24 格 - for (var h2 = 0; h2 < 24; h2++) { - var cell = slot.hours[h2]; - var v = metricVal(cell, metric); - var ratio = v / max; - var fill = heatColor(ratio); - var x = LABEL_W + h2 * CELL_W; - html += ''; - html += '' + esc(slot.slot) + ' @ ' + h2 + ':00 — ' + metricLabel(metric) + ' ' + - fmt(v, metric) + ''; - // 高值显示数字(≥30% 才显示,避免全屏数字) - if (ratio >= 0.3 && v > 0) { - var txt = fmt(v, metric); - html += '' + txt + ''; - } - } - } - html += ''; - - // 图例(底部):色阶 - html += ''; - html += '0'; - var legSteps = 6; - for (var s2 = 1; s2 <= legSteps; s2++) { - var ratio2 = s2 / legSteps; - var xx = ratio2 * 180; - html += ''; - } - html += '' + IP.chart.fmtNum(max) + ''; - html += '最深 = ' + metricLabel(metric) + ' ' + fmt(max, metric) + ''; - html += ''; - - html += ''; - el.innerHTML = html; - } - - /** - * 配色:白 → 浅蓝 → 深蓝(蓝绿渐变,符合现有 .css 颜色基调) - */ - function heatColor(ratio) { - if (ratio <= 0) return "#f1f5f9"; - // 4 段渐变:浅蓝(#dbeafe) → 中蓝(#60a5fa) → 深蓝(#2563eb) → 极深蓝(#1e3a8a) - var stops = [ - [0.0, "#f1f5f9"], - [0.25, "#dbeafe"], - [0.5, "#60a5fa"], - [0.75, "#2563eb"], - [1.0, "#1e3a8a"] - ]; - for (var i = 1; i < stops.length; i++) { - if (ratio <= stops[i][0]) { - var a = stops[i - 1], b = stops[i]; - var t = (ratio - a[0]) / (b[0] - a[0]); - return lerpColor(a[1], b[1], t); - } - } - return stops[stops.length - 1][1]; - } - - function lerpColor(c1, c2, t) { - var p1 = parseInt(c1.slice(1), 16); - var p2 = parseInt(c2.slice(1), 16); - var r = Math.round(((p1 >> 16) & 255) * (1 - t) + ((p2 >> 16) & 255) * t); - var g = Math.round(((p1 >> 8) & 255) * (1 - t) + ((p2 >> 8) & 255) * t); - var b = Math.round((p1 & 255) * (1 - t) + (p2 & 255) * t); - return "#" + ((r << 16) | (g << 8) | b).toString(16).padStart(6, "0"); - } - - // ─────────────────────────────────────────────────────────────────────── - // Top 10 繁忙时段 - // ─────────────────────────────────────────────────────────────────────── - function renderTop10(bySlot, days) { - var flat = []; - for (var i = 0; i < bySlot.length; i++) { - var slot = bySlot[i]; - for (var h = 0; h < 24; h++) { - var c = slot.hours[h]; - if (c.req > 0) { - flat.push({ slot: slot.slot, h: h, req: c.req, tin: c.tin, tout: c.tout }); - } - } - } - flat.sort(function (a, b) { return b.req - a.req; }); - flat = flat.slice(0, 10); - - var body = $("hourlyTopBody"); - if (!flat.length) { - body.innerHTML = '区间内没有请求'; - return; - } - body.innerHTML = flat.map(function (r) { - return '' + esc(r.slot) + '' + - '' + days[0] + '...' + days[days.length - 1] + '' + - '' + r.h + ':00' + - '' + r.req + '' + - '' + IP.chart.fmtNum(r.tin) + '' + - '' + IP.chart.fmtNum(r.tout) + '' + - ''; - }).join(''); - } - - // ─────────────────────────────────────────────────────────────────────── - // 日历列表 - // ─────────────────────────────────────────────────────────────────────── - function renderDays(days) { - var el = $("hourlyDays"); - if (!days.length) { - el.innerHTML = '审计目录无数据(请确认管理员已启用 LLM 上游,且审计 meta.jsonl 已写入)'; - return; - } - el.innerHTML = '当前可查日期:' + days.length + ' 天' + - '
' + - days.slice(0, 14).map(function (d) { return '' + d + ''; }).join(" · ") + - (days.length > 14 ? ' · …' : '') + ''; - Array.prototype.forEach.call(el.querySelectorAll("a[data-day]"), function (a) { - a.addEventListener("click", function (e) { - e.preventDefault(); - $("hourlyRange").value = "1"; - queryDays = [a.getAttribute("data-day")]; - runQuery(); - }); - }); - } - - // ─────────────────────────────────────────────────────────────────────── - // 主流程 - // ─────────────────────────────────────────────────────────────────────── - var queryDays = []; - var lastMetric = "requests"; - - async function fetchDays() { - var d = await IP.api("GET", "/api/admin/audit/days"); - return (d.data && d.data.days) || []; - } - - async function fetchDay(day) { - var d = await IP.api("GET", "/api/admin/audit/day?day=" + encodeURIComponent(day)); - return (d.data && d.data.rows) || []; - } - - function pickRecentDays(allDays, n) { - if (!allDays.length) return []; - return allDays.slice(0, n); - } - - async function runQuery() { - var range = parseInt($("hourlyRange").value, 10) || 3; - var slotFilter = $("hourlySlot").value; - var metric = $("hourlyMetric").value; - lastMetric = metric; - - $("hourlyHeatmap").innerHTML = '
加载中…
'; - - try { - var days = await fetchDays(); - queryDays = pickRecentDays(days, range); - if (!queryDays.length) { - $("hourlyHeatmap").innerHTML = '
审计无数据,请确认已启用上游
'; - return; - } - renderDays(days); - - var allRows = []; - for (var i = 0; i < queryDays.length; i++) { - var rs = await fetchDay(queryDays[i]); - allRows = allRows.concat(rs); - } - // slot 过滤 - if (slotFilter) allRows = allRows.filter(function (r) { return r.slot === slotFilter; }); - - var bySlot = aggregate(allRows); - renderHeatmap($("hourlyHeatmap"), bySlot, metric); - renderTop10(bySlot, queryDays); - - // 概览 - var totReq = bySlot.reduce(function (a, b) { return a + b.total_req; }, 0); - var totIn = bySlot.reduce(function (a, b) { return a + b.total_tin; }, 0); - var totOut = bySlot.reduce(function (a, b) { return a + b.total_tout; }, 0); - $("hrsTotal").textContent = IP.chart.fmtNum(totReq); - $("hrsTin").textContent = IP.chart.fmtNum(totIn); - $("hrsTout").textContent = IP.chart.fmtNum(totOut); - $("hrsSlots").textContent = bySlot.length; - $("hrsUsers").textContent = uniqueUsers(bySlot).length; - $("hrsSource").textContent = "meta.jsonl × " + queryDays.length + "天"; - } catch (e) { - $("hourlyHeatmap").innerHTML = '
加载失败:' + esc(e.message || String(e)) + '
'; - } - } - - async function bootSlotOptions() { - try { - var days = await fetchDays(); - renderDays(days); - // 收集所有 slot - var allRows = []; - for (var i = 0; i < Math.min(days.length, 2); i++) { - var rs = await fetchDay(days[i]); - allRows = allRows.concat(rs); - } - var seen = {}; - for (var k = 0; k < allRows.length; k++) seen[allRows[k].slot] = 1; - var sl = Object.keys(seen).sort(); - var sel = $("hourlySlot"); - for (var j = 0; j < sl.length; j++) { - var opt = document.createElement("option"); - opt.value = sl[j]; - opt.textContent = sl[j]; - sel.appendChild(opt); - } - } catch (e) { /* 静默失败:boot 期 fetch 失败只是没 slot 选项,不影响主查询 */ } - } - - function bind() { - $("hourlyRefresh").addEventListener("click", runQuery); - $("hourlyRange").addEventListener("change", runQuery); - $("hourlySlot").addEventListener("change", runQuery); - $("hourlyMetric").addEventListener("change", runQuery); - $("hourlyDaysRefresh").addEventListener("click", async function () { - try { - var days = await fetchDays(); - renderDays(days); - } catch (e) { IP.toast("刷新日期失败", true); } - }); - } - - IP.boot("hourly", function () { - bind(); - bootSlotOptions(); - runQuery(); - }); -})(); \ No newline at end of file diff --git a/www/assets/me.js b/www/assets/me.js deleted file mode 100644 index c5f477e..0000000 --- a/www/assets/me.js +++ /dev/null @@ -1,270 +0,0 @@ -/* 账号态「我的用量」面板(1.0.30) - 输入 API Key → 调 /api/v1/me → 渲染概览 / 24h 小时分布 / 按 slot 拆分 / - 我能调的上游 + apix + 我的域名。 - Key 只在 sessionStorage,关页面即清。 -*/ -(function () { - "use strict"; - var KEY_STORE = "ipass.me.key"; - var $ = IP.$; - - function esc(s) { return IP.esc(s); } - - function setKey(k) { - if (k) sessionStorage.setItem(KEY_STORE, k); - else sessionStorage.removeItem(KEY_STORE); - } - - function getKey() { - return sessionStorage.getItem(KEY_STORE) || ""; - } - - /** 走 X-API-Key 头,调 API。不能用 IP.api(那个走 cookie)。 - * 401 直接 throw 让 UI 显出重新输入 Key。 */ - function meApi(method, path, body) { - var key = getKey(); - if (!key) return Promise.reject(new Error("未设置 API Key")); - var opt = { method: method, headers: { "X-API-Key": key } }; - if (body) { - opt.headers["Content-Type"] = "application/json"; - opt.body = JSON.stringify(body); - } - return fetch(path, opt).then(function (res) { - return res.json().catch(function () { return { code: res.status, msg: "响应解析失败" }; }) - .then(function (data) { - if (!res.ok) throw new Error(data.msg || ("请求失败 HTTP " + res.status)); - return data; - }); - }); - } - - function showKeyCard() { - $("keyCard").hidden = false; - $("dashCard").hidden = true; - $("apiKey").focus(); - } - - function showDash() { - $("keyCard").hidden = true; - $("dashCard").hidden = false; - } - - function renderTopbar(me) { - $("topbar").innerHTML = - '
' + - '
尚数网 山海关个人用量面板
' + - '
' + - '' + esc(me.username) + " · " + - (me.role === "admin" ? "管理员" : "账号") + "" + - '' + - "
" + - "
"; - if (me.role === "admin") { - $("topbarAdminBtn").addEventListener("click", function () { - // 跳 admin login(cookie 鉴权不走 me Key) - location.href = "login.html"; - }); - } - } - - function renderHourly(hour24, labels) { - var el = $("dHourChart"); - // server 返回 hour_24h_labels("23h前"…"现在"),老 server 没这个字段时降级到索引 - var lbls = (labels && labels.length === hour24.length) ? labels - : hour24.map(function (_, h) { return h; }); - IP.chart.line(el, { - labels: lbls, - series: [{ name: "调用数", values: hour24.map(function (v) { return Number(v) || 0; }) }], - height: 90, - emptyText: "过去 24 小时没有调用记录" - }); - } - - function renderSlots(bySlot) { - var body = $("dSlotBody"); - if (!bySlot || !bySlot.length) { - body.innerHTML = '过去 7 天没有调用记录'; - return; - } - body.innerHTML = bySlot.map(function (s) { - var lastStatus = s.last_status || 0; - var badgeClass = lastStatus >= 200 && lastStatus < 300 ? "b-ok" - : lastStatus >= 400 && lastStatus < 500 ? "b-warn" - : lastStatus >= 500 ? "b-bad" : "b-gray"; - return '' + - '' + esc(s.slot) + '' + - '' + (s.calls_24h || 0) + '' + - '' + (s.calls_7d || 0) + '' + - '' + IP.chart.fmtNum(s.tin_7d || 0) + '' + - '' + IP.chart.fmtNum(s.tout_7d || 0) + '' + - '' + lastStatus + '' + - ''; - }).join(""); - } - - /** - * 同一个 upstream 通常**两个 base_url 都存在**: - * - `base_url`:OpenAI 协议出口(如 `https://lm.mayishangshu.cn:88/deepseek`) - * - `anthropic_base_url`:Anthropic 协议出口(如 `https://lm.mayishangshu.cn:88/deepseek/anthropic`) - * - * 网关出口是**纯 slot**(不带厂商路径、不带 /v1)——厂商版本/协议路径段 - * 原样存在上游配置里,转发时拼到 SDK 余下路径前。客户端 SDK 自己拼 - * `/chat/completions` 或 `/v1/messages`,网关不猜路径。 - * - * **1.0.34b**:只展示**纯 URL**(不加任何尾巴),点击按钮直接复制。 - * 不展示 curl —— WorkBuddy / Claude Code 客户端拿到 URL 后**自行拼路径**, - * 中间再加 `/chat/completions` 这种尾巴会 404。 - */ - function renderUpstreams(upstreams) { - var el = $("dUpstream"); - if (!upstreams || !upstreams.length) { - el.innerHTML = '当前账号无可用上游(可能白名单为空,或全部 slot 被停用)'; - return; - } - - function renderBtn(proto, url) { - return ''; - } - - function renderUrlRow(proto, url) { - return '
' + - renderBtn(proto, url) + - '' + esc(url) + '' + - '
'; - } - - el.innerHTML = upstreams.map(function (u) { - var protocols = []; - if (u.base_url) protocols.push(["openai", u.base_url]); - if (u.anthropic_base_url) protocols.push(["anthropic", u.anthropic_base_url]); - return '
' + - '
' + - '' + esc(u.slot || "") + '' + - '' + - esc((u.models || []).join("、") || "—") + '' + - (u.note ? '— ' + esc(u.note) + '' : '') + - '
' + - protocols.map(function (p) { return renderUrlRow(p[0], p[1]); }).join("") + - '
'; - }).join(""); - - // 复制按钮:原样复制 URL,不加尾巴 - Array.prototype.forEach.call(el.querySelectorAll(".copy-url-btn"), function (btn) { - btn.addEventListener("click", function (e) { - e.preventDefault(); - IP.copyText(btn.getAttribute("data-url"), "URL"); - }); - }); - } - - function renderApix(apix) { - var el = $("dApix"); - if (!apix || !apix.length) { - el.innerHTML = '当前账号无可用 API 代理'; - return; - } - el.innerHTML = '' + - '' + - '' + - apix.map(function (a) { - var mode = a.mode || "vendor"; - var call = mode === "passthrough" - ? 'POST /apixp/' + esc(a.slug) + '/<tail>' - : 'GET /apix/' + esc(a.slug) + '?参数=值'; - return '' + - '' + - '' + - '' + - '' + - ''; - }).join("") + '
slug用途调用方式说明
' + esc(a.slug || "") + '' + esc(a.display_name || a.url || "—") + '' + call + '' + esc((a.desc || a.usage_hint || "").slice(0, 80)) + '
'; - } - - function renderDomains(domains) { - var el = $("dDomains"); - if (!domains || !domains.length) { - el.innerHTML = '当前账号没有域名(需要去"全部域名"页申请)'; - return; - } - el.innerHTML = '' + - '' + - '' + - domains.map(function (d) { - return '' + - '' + - '' + - '' + - '' + - ''; - }).join("") + '
子域名后端状态创建时间
' + esc(d.full || d.subdomain || "—") + '' + esc(d.backend || "—") + '' + - (d.enabled ? "启用" : "停用") + '' + esc(d.created_at_text || "") + '
'; - } - - function renderDash(me) { - renderTopbar(me); - $("dUser").textContent = me.username || "-"; - var r = me.recent || {}; - $("dCalls24").textContent = r.calls_24h || 0; - $("dCalls7").textContent = r.calls_7d || 0; - $("dTin24").textContent = IP.chart.fmtNum(r.tin_24h || 0); - $("dTout24").textContent = IP.chart.fmtNum(r.tout_24h || 0); - $("dLast").textContent = r.last_at - ? esc(r.last_at + " · " + (r.last_slot || "-")) - : "—"; - renderHourly(r.hour_24h || [], r.hour_24h_labels || []); - renderSlots(r.by_slot || []); - renderUpstreams(me.upstreams || []); - renderApix(me.apix || []); - renderDomains(me.domains || []); - } - - function loadDash() { - IP.toast("加载中…"); - meApi("GET", "/api/v1/me").then(function (resp) { - var me = resp.data || {}; - if (!me.username) { - IP.toast("接口返回异常:缺 username", true); - showKeyCard(); - return; - } - renderDash(me); - showDash(); - IP.toast("已加载"); - }).catch(function (err) { - if (err.message && err.message.indexOf("HTTP 401") >= 0) { - setKey(""); - IP.toast("Key 无效或已过期,请重新输入", true); - showKeyCard(); - $("apiKey").value = ""; - $("apiKey").focus(); - } else { - IP.toast("加载失败:" + (err.message || err), true); - } - }); - } - - function bind() { - $("keyForm").addEventListener("submit", function (e) { - e.preventDefault(); - var k = $("apiKey").value.trim(); - if (!k) { IP.toast("请输入 API Key", true); return; } - setKey(k); - loadDash(); - }); - $("refreshBtn").addEventListener("click", loadDash); - } - - function boot() { - bind(); - if (getKey()) loadDash(); - else showKeyCard(); - } - - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", boot); - } else { - boot(); - } -})(); \ No newline at end of file diff --git a/www/assets/overview.js b/www/assets/overview.js deleted file mode 100644 index a15179b..0000000 --- a/www/assets/overview.js +++ /dev/null @@ -1,95 +0,0 @@ -/* 数据总览:卡片 + 趋势图 + Top 排名条形图 */ -(function () { - "use strict"; - - var C = { req: "#2563eb", in: "#0d9488", out: "#7c3aed" }; - - function num(v) { return Number(v) || 0; } - - /// 可用模型 = 全部(启用中的)上游登记模型去重后的条数 - function distinctModels(s) { - var seen = {}; - s.upstreams.forEach(function (u) { - if (!u.enabled) return; - IP.arr(u.models).forEach(function (m) { seen[m] = true; }); - }); - return Object.keys(seen).length; - } - - function renderCards(s) { - var active = s.domains.filter(function (d) { return d.status === "approved"; }).length; - var tot = s.usage.total || {}; - var tok = s.usage.tokens || {}; - - IP.$("statPending").textContent = s.pending; - IP.$("statDomains").textContent = s.domains.length; - IP.$("statActive").textContent = active; - IP.$("statUsers").textContent = s.users.length; - IP.$("statUpstreams").textContent = s.upstreams.length; - IP.$("statLlmtoday").textContent = tot.today || 0; - IP.$("statLlmtotal").textContent = tot.total || 0; - - var tokToday = num(tok.in_today) + num(tok.out_today); - var tokTotal = num(tok.in_total) + num(tok.out_total); - IP.$("statTokToday").textContent = IP.chart.fmtNum(tokToday); - IP.$("statTokTotal").textContent = IP.chart.fmtNum(tokTotal); - // 1.0.32:自服务上线以来累计(来自 audit meta.jsonl 真源,不受 stats 落盘/恢复影响) - var allTime = tok.all_time || {}; - var allTimeTokens = num(allTime.tin) + num(allTime.tout); - IP.$("statTokAllTime").textContent = IP.chart.fmtNum(allTimeTokens) + - (allTime.since ? " (" + allTime.since + " 起)" : ""); - IP.$("statModels").textContent = distinctModels(s); - } - - function renderTrend(s) { - var t = s.trend; - if (!t || !t.labels || !t.labels.length) { - IP.chart.line(IP.$("chReq"), { labels: [], series: [] }); - IP.chart.line(IP.$("chTok"), { labels: [], series: [] }); - return; - } - IP.chart.line(IP.$("chReq"), { - labels: t.labels, - series: [{ name: "请求数", values: t.total.requests, color: C.req }] - }); - IP.chart.line(IP.$("chTok"), { - labels: t.labels, - series: [ - { name: "入 token", values: t.total["in"], color: C["in"] }, - { name: "出 token", values: t.total.out, color: C.out } - ] - }); - } - - /// 取累计调用 Top N,按累计降序;全 0 的不进榜(榜上堆一排 0 没信息量) - function top(list, key, n) { - return list - .filter(function (x) { return num(x[key]) > 0; }) - .sort(function (a, b) { return num(b[key]) - num(a[key]); }) - .slice(0, n); - } - - function renderRanks(s) { - var byUser = top(s.usage.users || [], "total", 8).map(function (u) { - var owner = (s.users.filter(function (x) { return x.username === u.username; })[0] || {}); - return { - label: IP.displayName(owner) + "(@" + u.username + ")", - value: num(u.total), - sub: "今 " + num(u.today) - }; - }); - IP.chart.bars(IP.$("chUsers"), { items: byUser, emptyText: "还没有任何 LLM 调用" }); - - var bySlot = top(s.usage.models || [], "total", 8).map(function (m) { - return { label: m.slot, value: num(m.total), sub: "今 " + num(m.today) }; - }); - IP.chart.bars(IP.$("chSlots"), { items: bySlot, emptyText: "还没有任何 LLM 调用" }); - } - - IP.boot("overview", function (s) { - renderCards(s); - renderTrend(s); - renderRanks(s); - if (IP.review) IP.review.render(s); - }); -})(); diff --git a/www/assets/review.js b/www/assets/review.js deleted file mode 100644 index 4f5519f..0000000 --- a/www/assets/review.js +++ /dev/null @@ -1,57 +0,0 @@ -/* 审核队列:总览页与审核页共用同一份渲染(「待审」在两个地方都要看到) */ -window.IP = window.IP || {}; -IP.review = (function () { - "use strict"; - - function rows(s) { - return s.domains.filter(function (d) { return d.status === "pending"; }); - } - - function render(s) { - var body = IP.$("reviewBody"); - if (!body) return; - - var list = rows(s); - if (!list.length) { - body.innerHTML = '暂无待审核申请'; - var panel = IP.$("pendingPanel"); - if (panel) panel.hidden = true; - return; - } - - var panel = IP.$("pendingPanel"); - if (panel) panel.hidden = false; - - body.innerHTML = list.map(function (d) { - return "" + - "" + IP.esc(d.subdomain) + "
" + - IP.esc(d.host || IP.fullHost(d.subdomain)) + IP.portSuffix() + "
" + - "" + IP.esc(d.backend) + "" + - "" + IP.typeBadge(d.type) + "" + - "" + IP.esc(d.owner) + "" + - "" + IP.esc(d.created_at_text) + "" + - "
" + - "" + - "" + - "
" + - ""; - }).join(""); - } - - var body = IP.$("reviewBody"); - if (body) { - body.addEventListener("click", function (e) { - var btn = e.target.closest("button[data-act]"); - if (!btn) return; - var id = btn.getAttribute("data-id"); - var act = btn.getAttribute("data-act"); - - btn.disabled = true; - IP.api("POST", "/api/admin/domains/review", { id: id, action: act }) - .then(function (r) { IP.toast(r.msg); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); btn.disabled = false; }); - }); - } - - return { render: render, rows: rows }; -})(); diff --git a/www/assets/upstreams.js b/www/assets/upstreams.js deleted file mode 100644 index 5ec0de2..0000000 --- a/www/assets/upstreams.js +++ /dev/null @@ -1,337 +0,0 @@ -/* LLM 上游(API 组):列表(新建/编辑弹窗、复制地址、连通性测试、启停、删除)*/ -(function () { - "use strict"; - - var $ = IP.$; - - /// 迷你趋势:一组数值画成等宽竖条 SVG(14 点)。0 用浅灰、有值用蓝。 - /// 用于「密钥」列里每把上游 Key 的近 14 天请求量,一眼看出负载分布; - /// 悬停给出合计 / 峰值 / 首个非零日,便于「跟踪」(不必逐条点开)。 - function spark(arr, labels) { - arr = arr || []; - if (!arr.length) return ""; - var max = Math.max.apply(null, arr.concat([1])); - var sum = arr.reduce(function (a, b) { return a + b; }, 0); - var w = 140, h = 22, n = arr.length, gap = 1; - var bw = (w - (n - 1) * gap) / n; - var bars = arr.map(function (v, i) { - var bh = Math.max(1, Math.round(v / max * (h - 2))); - var x = i * (bw + gap); - var y = h - bh; - return ""; - }).join(""); - var tip = "近 " + n + " 天:" + sum + " 请求,峰值 " + max; - if (labels && labels.length === n) { - var peak = arr.indexOf(max); - if (peak >= 0 && max > 0) tip += "(" + labels[peak] + ")"; - } - return "" + IP.esc(tip) + "" + bars + ""; - } - - /// 由 base_url(协议中立,端口跟随当前访问管理台所用的 Host)推导两种协议的完整 API 地址。 - /// base 写了路径(钉死粒度)时不重复追加对应后缀 - function apiUrls(up) { - // **1.0.40 口径**:直接用后端 view 返回的 base_url / anthropic_base_url—— - // 网关出口是**纯 slot**(`/` 与 `//anthropic`,都不带 /v1); - // 厂商版本段存在上游 base 里,转发时 join_target 归一,客户端 SDK 带不带 /v1 都对。 - // 前端不做任何拼接(历史版本正则拼出过 `…/v1/anthropic` 错 URL)。 - return { - openai: up.base_url || "", - anthropic: up.anthropic_base_url || "" - }; - } - - /// epoch 秒 → HH:MM(浏览器本地时区;面板读者与网关同区) - function hhmm(ts) { - if (!ts) return ""; - var d = new Date(ts * 1000); - function p(n) { return (n < 10 ? "0" : "") + n; } - return p(d.getHours()) + ":" + p(d.getMinutes()); - } - - /// 单账号行 HTML(编辑态用,i 为序号;a 为已有账号视图,可能来自后端 view()) - function acctRowHtml(a, i) { - a = a || {}; - var masked = a.auth_mask - ? "" + IP.esc(a.auth_mask) + "(留空=保留原值)" - : "新账号"; - // 1.0.44 探测闭环:冷却不再是「锁到某个边界」,而是到期放一个真实请求去探测, - // 2xx 自动回队、失败退避翻倍。tooltip 把时间线摊开,别再让人猜厂商重置点。 - var coolTip = a.cooled - ? "额度耗尽冷却中:约 " + hhmm(a.probe_next) + " 由下一个无绑定真实请求探测恢复;最迟 " + hhmm(a.cool_hard_cap) + " 无条件回队(退避指数增长,封顶 30 分钟一探)" - : ""; - return "
" + - "
" + - "#" + i + "" + masked + - (a.cooled ? "冷却中" : "") + - "" + - "
" + - "" + - "" + - "
"; - } - - // 弹窗表单:up 存在 = 编辑(slot 只读、auth 留空表示不改),否则 = 新建 - function formHtml(up) { - var edit = !!(up && up.slot); - var accts = (up && up.accounts) ? up.accounts : []; - var rows = accts.length - ? accts.map(acctRowHtml).join("") - : "
还没有账号,点下方「+ 添加账号」
"; - var statusVal = up && up.exhaust_status && up.exhaust_status.length ? up.exhaust_status.join(",") : "402,429,403"; - var markerVal = up && up.exhaust_markers && up.exhaust_markers.length ? up.exhaust_markers.join(",") : ""; - return '' + - '' + - '
' + - '
' + - '
' + - '
' + - '' + - '
网关出口即 https://lm…:88/<slot>,路径段原样存在这里,网关不拼 /v1。
' + - '
' + - '' + - '
网关出口即 https://lm…:88/<slot>/anthropic。各家与 OpenAI 路径不同(阿里 /apps/anthropic、智谱 /api/anthropic),**必须显式配**;留空则按 base 派生(仅 deepseek/minimax 正确)。
' + - '
' + - '
每行填 Authorization 头值(Bearer sk-…)。只填裸 key 也会自动补 Bearer 。
' + - '
' + rows + '
' + - "" + - '
' + - '
' + - '
' + - '
' + - "
" + - "" + - "" + - "
" + - ''; - } - - function openForm(up) { - IP.modal({ - title: up && up.slot ? "编辑 LLM 上游" : "新建 LLM 上游", - submitText: "保存上游", - wide: true, - html: formHtml(up), - onMount: function (card, close) { - var list = card.querySelector("#upAccounts"); - function nextIdx() { return list.querySelectorAll(".acct-row").length; } - card.querySelector("#addAcct").addEventListener("click", function () { - var empty = list.querySelector(".acct-empty"); - if (empty) empty.remove(); - var div = document.createElement("div"); - div.innerHTML = acctRowHtml(null, nextIdx()); - list.appendChild(div.firstChild); - }); - list.addEventListener("click", function (e) { - if (e.target.classList.contains("acct-del")) { - var row = e.target.closest(".acct-row"); - if (row) row.remove(); - // 重排序号 - list.querySelectorAll(".acct-row").forEach(function (r, i) { - r.setAttribute("data-idx", i); - var badge = r.querySelector(".badge"); - if (badge) badge.textContent = "#" + i; - }); - } - }); - - var form = card.querySelector("#upForm"); - form.addEventListener("submit", function (e) { - e.preventDefault(); - var accounts = []; - list.querySelectorAll(".acct-row").forEach(function (row) { - // 1.0.44 起不再提交 resets(重置周期):恢复判定改为「指数退避 + 真实请求 - // 探测」闭环,不再要求用户懂厂商窗口口径。存量数据里该字段仍保留、只不路由。 - accounts.push({ - auth: row.querySelector(".acct-auth").value.trim(), - note: row.querySelector(".acct-note").value.trim() - }); - }); - var payload = { - slot: card.querySelector("#upSlot").value.trim(), - base: card.querySelector("#upBase").value.trim(), - base_anthropic: card.querySelector("#upBaseAnthropic").value.trim(), - note: card.querySelector("#upNote").value.trim(), - // 模型清单总是显式提交:编辑框里就是"当前值",清空即清空(可预期) - models: card.querySelector("#upModels").value, - accounts: JSON.stringify(accounts) - }; - var st = card.querySelector("#upExhaustStatus").value.trim(); - if (st) payload.exhaust_status = st; - var mk = card.querySelector("#upExhaustMarkers").value.trim(); - if (mk) payload.exhaust_markers = JSON.stringify(mk.split(",").map(function (s) { return s.trim(); }).filter(Boolean)); - IP.api("POST", "/api/admin/upstreams/save", payload) - .then(function (r) { IP.toast(r.msg); close(); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); }); - }); - } - }); - } - - function render(s) { - var body = $("upstreamsBody"); - if (!s.upstreams.length) { - body.innerHTML = '还没有配置任何 LLM 上游'; - return; - } - - body.innerHTML = s.upstreams.map(function (u) { - var enabled = !!u.enabled; - var toggle = enabled - ? "" - : ""; - - // 账号视图:数量 + 各账号掩码 + 冷却标记 + 今日负载 + 比例条 + 14天迷你趋势 - var accts = IP.arr(u.accounts); - var maxLoad = accts.reduce(function (m, a) { - return Math.max(m, (a.load && a.load.requests) || 0); - }, 0); - var trend = IP.arr(u.account_trend); - var trendLabels = IP.arr(u.trend_labels); - var totalReq = accts.reduce(function (s, a) { return s + ((a.load && a.load.requests) || 0); }, 0); - var keyCell = accts.length - ? "
" + accts.length + " 把 Key · 今日合计 " + totalReq + " 请求
" + - accts.map(function (a, i) { - var m = a.auth_mask || (a.auth_set ? "已设" : "未设"); - var load = a.load || { requests: 0, tokens_in: 0, tokens_out: 0, exhausts: 0 }; - // 比例条 = 该 Key 占「本上游最大负载 Key」的百分比(不是占总量): - // 目的是让「谁在扛、有没有偏斜」一眼可见,本上游内部相对量最有信息量 - var pct = maxLoad > 0 ? Math.round(load.requests / maxLoad * 100) : 0; - var exBadge = load.exhausts > 0 - ? " 耗尽" + load.exhausts + "" - : ""; - var series = (trend[i] && trend[i].requests) || []; - var coolBadge = a.cooled - ? " 冷却" - : ""; - return "
" + - "" + IP.esc(m) + "" + - coolBadge + exBadge + - "
今日 " + load.requests + " 请求 · 入 " + load.tokens_in + " / 出 " + load.tokens_out + " tok
" + - "
" + - "
" + spark(series, trendLabels) + "
" + - "
"; - }).join("") - : (u.auth_set - ? "" + IP.esc(u.auth_mask) + "" - : "未设置"); - - var models = IP.arr(u.models); - var modelCell = models.length - ? "
" + models.map(IP.esc).join("
") + "
" - : "未登记"; - - var urls = apiUrls(u); - var urlBtns = - "" + - ""; - - // 健康徽标:数据来自网关 log 阶段对**真实转发**结果的记录(uh: 缓存)。 - // 5xx/连不上 = 失效(红);4xx 也算活着(上游对请求内容的意见); - // 从没被调用过 = 未探测(灰)。状态会在每次真实调用后自动更新。 - var st = u.status || "unknown"; - var stBadge = - st === "ok" - ? "● 正常" - : st === "failed" - ? "● 失效" + (u.status_code ? " HTTP " + IP.esc(u.status_code) : "") + "" - : "○ 未探测"; - - return "" + - "" + IP.esc(u.slot) + "
" + stBadge + "
" + - "
" + urlBtns + "
" + - "
点击复制 API 地址
" + - "" + IP.esc(u.base) + - (u.base_anthropic ? "
" + IP.esc(u.base_anthropic) + "" : "") + "" + - "" + keyCell + "" + - "" + (models.length ? "" + models.length + " 个" + modelCell : modelCell) + "" + - "" + IP.esc(u.note || "-") + "" + - "" + (enabled ? "启用中" : "已停用") + "" + - "" + IP.esc(u.created_at_text) + "" + - "
" + - "" + - "" + - toggle + - "" + - "
" + - ""; - }).join(""); - } - - /// 探测体就是发给上游的真实请求:第一个登记模型 + max_tokens=1(成本≈0)。 - /// slot 走 query(模块要用它定位上游),body 会被网关**原样**转给上游。 - function probe(slot, body) { - return fetch("/api/admin/upstreams/test?slot=" + encodeURIComponent(slot), { - method: "POST", - credentials: "same-origin", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body) - }); - } - - $("upstreamsBody").addEventListener("click", function (e) { - var btn = e.target.closest("button[data-act]"); - if (!btn) return; - var act = btn.getAttribute("data-act"); - var slot = btn.getAttribute("data-slot"); - - if (act === "copy-url") { - IP.copyText(btn.getAttribute("data-url"), "API 地址"); - return; - } - - if (act === "test-up") { - var up = IP.state.upstreams.filter(function (x) { return x.slot === slot; })[0]; - if (!up) return; - var model = IP.arr(up.models)[0] || "gpt-4o-mini"; - var label = btn.textContent; - var restore = function () { btn.disabled = false; btn.textContent = label; }; - btn.disabled = true; btn.textContent = "测试中…"; - var t0 = Date.now(); - probe(slot, { model: model, max_tokens: 1, stream: false, messages: [{ role: "user", content: "ping" }] }) - .then(function (res) { - return res.json().catch(function () { return {}; }).then(function (data) { - var ms = Date.now() - t0; - if (res.ok) { - IP.toast("✅ " + slot + " 通(HTTP " + res.status + "," + ms + " ms,model=" + model + ")"); - } else { - // 上游错误体是 OpenAI 形状(error.message),管理台错误体是 msg——都认 - var msg = (data && data.error && data.error.message) || (data && data.msg) || ("HTTP " + res.status); - IP.toast("✗ " + slot + " 不通:" + msg + "(" + ms + " ms)", true); - } - restore(); - }); - }).catch(function () { - IP.toast("✗ " + slot + " 不通:网络错误或超时", true); - }); - return; - } - - if (act === "toggle-up") { - // 后端约定:save 省略 auth/note/models 即保留原值,enabled 缺省视为 true—— - // 所以启停必须显式带 enabled,其余一律不传,避免误清密钥/模型清单 - btn.disabled = true; - IP.api("POST", "/api/admin/upstreams/save", { - slot: slot, - enabled: btn.getAttribute("data-enabled") === "1" - }).then(function (r) { IP.toast(r.msg); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); btn.disabled = false; }); - } else if (act === "edit-up") { - var up2 = IP.state.upstreams.filter(function (x) { return x.slot === slot; })[0]; - if (!up2) return; - openForm(up2); - } else if (act === "del-up") { - if (!confirm("确认删除上游 " + slot + "?删除后指向它的调用将立即 404。")) return; - btn.disabled = true; - IP.api("POST", "/api/admin/upstreams/delete", { slot: slot }) - .then(function (r) { IP.toast(r.msg); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); btn.disabled = false; }); - } - }); - - $("newUpBtn").addEventListener("click", function () { openForm(null); }); - - IP.boot("upstreams", render); -})(); diff --git a/www/assets/usage.js b/www/assets/usage.js deleted file mode 100644 index 1d6e8c3..0000000 --- a/www/assets/usage.js +++ /dev/null @@ -1,185 +0,0 @@ -/* 用量统计:趋势(全局 / 按账号 / 按 API 组)+ 按人 / 按 API 组 的表格与排名图 */ -(function () { - "use strict"; - - var $ = IP.$; - var C = { req: "#2563eb", in: "#0d9488", out: "#7c3aed" }; - - function num(v) { return Number(v) || 0; } - function tok(o) { return o || {}; } - - // ---------------- 概览卡片 ---------------- - function renderCards(s) { - var t = s.trend; - var sum = function (arr) { return (arr || []).reduce(function (a, b) { return a + num(b); }, 0); }; - - IP.$("uReq").textContent = t ? sum(t.total.requests) : 0; - IP.$("uTin").textContent = t ? IP.chart.fmtNum(sum(t.total["in"])) : 0; - IP.$("uTout").textContent = t ? IP.chart.fmtNum(sum(t.total.out)) : 0; - IP.$("uToday").textContent = num((s.usage.total || {}).today); - IP.$("uTotal").textContent = num((s.usage.total || {}).total); - - var tk = tok(s.usage.tokens); - IP.$("uTokTotal").textContent = IP.chart.fmtNum(num(tk.in_total) + num(tk.out_total)); - } - - // ---------------- 趋势 ---------------- - function renderTrend(s) { - var t = s.trend; - if (!t || !t.labels || !t.labels.length) { - IP.chart.line($("chReq"), { labels: [], series: [] }); - IP.chart.line($("chTok"), { labels: [], series: [] }); - return; - } - var view = $("trendView").value; - - if (view === "total") { - IP.chart.line($("chReq"), { - labels: t.labels, - series: [{ name: "请求数", values: t.total.requests, color: C.req }] - }); - IP.chart.line($("chTok"), { - labels: t.labels, - series: [ - { name: "入 token", values: t.total["in"], color: C["in"] }, - { name: "出 token", values: t.total.out, color: C.out } - ] - }); - return; - } - - // 分视角:每个账号 / 每个上游一条线。全 0 的(`empty`)不画, - // 否则一个从没调过的账号会变成贴着轴的死线,把图例挤爆 - var list = (view === "users" ? t.users : t.slots) || []; - var live = list.filter(function (x) { return !x.empty; }); - - IP.chart.line($("chReq"), { - labels: t.labels, - series: live.map(function (x) { - return { name: view === "users" ? x.username : x.slot, values: x.requests }; - }), - emptyText: "该区间内还没有数据" - }); - IP.chart.line($("chTok"), { - labels: t.labels, - series: live.map(function (x) { - return { - name: view === "users" ? x.username : x.slot, - values: (x["in"] || []).map(function (v, i) { return num(v) + num((x.out || [])[i]); }) - }; - }), - emptyText: "该区间内还没有数据" - }); - } - - // ---------------- 排名图 ---------------- - /// 按选中指标排序取 Top N - function rank(list, metric, nameOf, n) { - var pick = function (x) { - var tk = tok(x.tokens); - if (metric === "in") return num(tk.in_total); - if (metric === "out") return num(tk.out_total); - if (metric === "tok") return num(tk.in_total) + num(tk.out_total); - return num(x.total); - }; - return list - .filter(function (x) { return pick(x) > 0; }) - .sort(function (a, b) { return pick(b) - pick(a); }) - .slice(0, n) - .map(function (x) { return { label: nameOf(x), value: pick(x) }; }); - } - - function renderRanks(s) { - IP.chart.bars($("chUsers"), { - items: rank(s.usage.users || [], $("metricUser").value, function (u) { - var owner = (s.users.filter(function (x) { return x.username === u.username; })[0] || {}); - return IP.displayName(owner) + "(@" + u.username + ")"; - }, 10), - emptyText: "还没有任何用量" - }); - IP.chart.bars($("chSlots"), { - items: rank(s.usage.models || [], $("metricSlot").value, function (m) { return m.slot; }, 10), - emptyText: "还没有任何用量" - }); - } - - // ---------------- 表格 ---------------- - function renderTables(s) { - var ub = $("usageUsersBody"); - var rows = IP.arr(s.usage.users); - if (!rows.length) { - ub.innerHTML = '还没有任何 LLM 调用'; - } else { - ub.innerHTML = rows.map(function (u) { - var tk = tok(u.tokens); - var byModel = IP.arr(u.models).length - ? IP.arr(u.models).map(function (m) { - return "
" + IP.esc(m.slot) + ":" + (m.today || 0) + " / " + (m.total || 0) + "
"; - }).join("") - : "-"; - return "" + - "" + IP.esc(u.username) + "" + - "" + (u.today || 0) + "" + - "" + (u.total || 0) + "" + - "" + IP.chart.fmtNum(tk.in_total) + "" + - "" + IP.chart.fmtNum(tk.out_total) + "" + - "" + IP.esc(u.last_ts_text || "-") + "" + - "" + byModel + "" + - ""; - }).join(""); - } - - var mb = $("usageModelsBody"); - var mrows = IP.arr(s.usage.models); - if (!mrows.length) { - mb.innerHTML = '还没有任何 LLM 调用'; - return; - } - mb.innerHTML = mrows.map(function (m) { - var tk = tok(m.tokens); - var users = IP.arr(m.users).length - ? IP.arr(m.users).map(function (x) { - return "
" + IP.esc(x.username) + ":" + (x.today || 0) + " / " + (x.total || 0) + "
"; - }).join("") - : "-"; - return "" + - "" + IP.esc(m.slot) + "" + - "" + (m.today || 0) + "" + - "" + (m.total || 0) + "" + - "" + IP.chart.fmtNum(tk.in_total) + "" + - "" + IP.chart.fmtNum(tk.out_total) + "" + - "" + IP.esc(m.last_ts_text || "-") + "" + - "" + users + "" + - ""; - }).join(""); - } - - function syncDayButtons() { - var btns = $("dayBtns").querySelectorAll("button[data-days]"); - Array.prototype.forEach.call(btns, function (b) { - var on = Number(b.getAttribute("data-days")) === IP.state.trendDays; - b.className = "btn-sm" + (on ? " btn-primary" : ""); - }); - } - - // ---------------- 事件 ---------------- - $("dayBtns").addEventListener("click", function (e) { - var b = e.target.closest("button[data-days]"); - if (!b) return; - IP.state.trendDays = Number(b.getAttribute("data-days")); - syncDayButtons(); - IP.reload(); - }); - $("trendView").addEventListener("change", function () { renderTrend(IP.state); }); - $("metricUser").addEventListener("change", function () { renderRanks(IP.state); }); - $("metricSlot").addEventListener("change", function () { renderRanks(IP.state); }); - - syncDayButtons(); - - IP.boot("usage", function (s) { - renderCards(s); - renderTrend(s); - renderRanks(s); - renderTables(s); - }); -})(); diff --git a/www/assets/users.js b/www/assets/users.js deleted file mode 100644 index aa005bb..0000000 --- a/www/assets/users.js +++ /dev/null @@ -1,150 +0,0 @@ -/* 账号管理:新建 + 列表(复制/重置 Key、改密码、展示名、授权、上游白名单、限额、删除)*/ -(function () { - "use strict"; - - var $ = IP.$; - - function render(s) { - var body = $("usersBody"); - if (!s.users.length) { - body.innerHTML = '还没有账号'; - return; - } - - body.innerHTML = s.users.map(function (u) { - var grant = u.temp_grant - ? "生效中
剩余 " + IP.esc(u.temp_grant_left_text) + "
" - : "未授权"; - - var grantBtn = u.temp_grant - ? "" - : ""; - - var models = IP.arr(u.allowed_models); - var modelsInfo = models.length - ? "
上游白名单:" + IP.esc(models.join(", ")) + "
" - : "
上游白名单:不限
"; - - var lu = u.llm_usage || {}; - var usageCell = "" + (lu.today || 0) + " / " + (lu.total || 0) + "" + - "
" + (lu.last_ts_text ? IP.esc(lu.last_ts_text) : "从未调用") + "
" + - "
限 " + (u.llm_rpm > 0 ? u.llm_rpm + "/分" : "不限") + " · " + - (u.llm_daily > 0 ? u.llm_daily + "/日" : "不限") + "
"; - - var displayName = u.display_name || ""; - return "" + - "" + IP.esc(IP.displayName(u)) + "
@" + IP.esc(u.username) + " · " + - IP.esc(u.created_at_text) + "
" + modelsInfo + "" + - "" + (u.role === "admin" ? "管理员" : "普通") + "" + - "
" + IP.esc(u.api_key_masked) + "" + - "" + - "" + - "
" + - "" + usageCell + "" + - "" + grant + "" + - "" + IP.esc(u.domain_count) + "" + - "
" + - "" + - "" + - grantBtn + - "" + - "" + - "" + - "
" + - ""; - }).join(""); - } - - $("createUserForm").addEventListener("submit", function (e) { - e.preventDefault(); - IP.api("POST", "/api/admin/users/create", { - username: $("cuName").value.trim(), - display_name: $("cuDisplay").value.trim(), - password: $("cuPass").value, - role: $("cuRole").value, - grant_temp: $("cuGrant").checked - }).then(function (r) { - IP.toast(r.msg + ",API Key:" + r.data.api_key); - $("cuName").value = ""; - $("cuDisplay").value = ""; - $("cuPass").value = ""; - $("cuGrant").checked = false; - return IP.reload(); - }).catch(function (err) { IP.toast(err.message, true); }); - }); - - $("usersBody").addEventListener("click", function (e) { - var btn = e.target.closest("button[data-act]"); - if (!btn) return; - - var act = btn.getAttribute("data-act"); - var user = btn.getAttribute("data-user"); - - if (act === "copy-key") { - IP.copyText(btn.getAttribute("data-key"), "API Key"); - return; - } - - var req = null; - if (act === "reset-key") { - if (!confirm("重置后旧 Key 立即失效,确认继续?")) return; - req = IP.api("POST", "/api/admin/users/key", { username: user }); - } else if (act === "grant-temp") { - req = IP.api("POST", "/api/admin/users/grant", { username: user }); - } else if (act === "revoke-temp") { - req = IP.api("POST", "/api/admin/users/grant", { username: user, revoke: true }); - } else if (act === "reset-pass") { - var pwd = prompt("为账号 " + user + " 设置新密码(至少 6 位):"); - if (!pwd) return; - req = IP.api("POST", "/api/admin/users/password", { username: user, password: pwd }); - } else if (act === "set-display") { - var curDisplay = btn.getAttribute("data-display") || ""; - var dn = prompt("账号 " + user + " 的展示名(中文姓名,留空 = 清空):", curDisplay); - if (dn === null) return; - req = IP.api("POST", "/api/admin/users/display", { username: user, display_name: dn.trim() }); - } else if (act === "set-models") { - var me = IP.state.users.filter(function (x) { return x.username === user; })[0] || {}; - var cur = IP.arr(me.allowed_models).join(", "); - var input = prompt( - "账号 " + user + " 可用的上游 slot,逗号分隔(留空 = 不限制)。\n" + - "现有上游:" + (IP.state.upstreams.map(function (x) { return x.slot; }).join(", ") || "(无)") + "\n" + - "当前白名单:" + (cur || "(不限)"), - cur - ); - if (input === null) return; - req = IP.api("POST", "/api/admin/users/models", { username: user, models: input.trim() }); - } else if (act === "set-limits") { - var mu = IP.state.users.filter(function (x) { return x.username === user; })[0] || {}; - var curLimits = (mu.llm_rpm !== undefined ? mu.llm_rpm : "") + "," + (mu.llm_daily !== undefined ? mu.llm_daily : ""); - var input2 = prompt( - "账号 " + user + " 的 LLM 限流,格式「每分钟上限,每日上限」。\n" + - "0 = 不限;只改其中一项时另一项留空(如 ,100 只改每日)。", - curLimits - ); - if (input2 === null) return; - var parts = input2.split(","); - var rpmS = (parts[0] || "").trim(); - var dailyS = (parts[1] || "").trim(); - var payload = { username: user }; - if (rpmS !== "") payload.rpm = Number(rpmS); - if (dailyS !== "") payload.daily = Number(dailyS); - if (payload.rpm === undefined && payload.daily === undefined) { IP.toast("未做任何修改"); return; } - if ((payload.rpm !== undefined && (isNaN(payload.rpm) || payload.rpm < 0)) || - (payload.daily !== undefined && (isNaN(payload.daily) || payload.daily < 0))) { - IP.toast("限流值必须是非负整数", true); - return; - } - req = IP.api("POST", "/api/admin/users/limits", payload); - } else if (act === "del-user") { - if (!confirm("删除账号 " + user + " 会同时删除其名下所有域名,确认继续?")) return; - req = IP.api("POST", "/api/admin/users/delete", { username: user }); - } - - if (!req) return; - btn.disabled = true; - req.then(function (r) { IP.toast(r.msg); return IP.reload(); }) - .catch(function (err) { IP.toast(err.message, true); btn.disabled = false; }); - }); - - IP.boot("users", render); -})(); diff --git a/www/cache.html b/www/cache.html deleted file mode 100644 index aa898cc..0000000 --- a/www/cache.html +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - -制品缓存 · 尚数网 山海关 - - - -
- -
- -
-
-
-

制品缓存 · 上游

-
- 客户端把包管理器指向左侧的「下游地址」并携带账号 API Key,网关校验 Key 后按本表配置转发到上游、把响应落到本地磁盘缓存(命中不再回源)。 - 一个生态可能有两个上游:例如 crates.io 的索引在 index.crates.io、而 .crate 包本体在 static.crates.io,所以要分开配 /cargo/ 与 /cargo-dl/。 - 「凭据」填完整的 Authorization 头值(如 Bearer xxx),留空则透传客户端自带的 Authorization;网关自己的 sk_ 始终不会传给上游。 - 停用某个路由,对客户端表现为 503 上游未配置。 -
-
- -
- - - - - -
生态路由 / 下游地址上游地址凭据状态操作
-
-
- - -
-
-
-

容量与淘汰

-
- 数字直接读自 nginx 自己的缓存记账(proxy_cache_path 的共享内存),口径与淘汰动作同源 —— 「这里显示 91%」与「nginx 正在淘汰」说的是同一件事,不是扫盘估算。 - 上限来自 conf 的 max_size(默认每生态 50g、docker 200g),超了按 LRU 自动淘汰;inactive 到期的条目也会被清掉。淘汰是渐进的(cache manager 每秒一轮),短时猛灌可短暂超过上限再收敛,它不是硬配额。 -
「盘点磁盘」会把真实占用也列出来:两者差额是 nginx 还没回收的条目(手工清过缓存文件后会明显偏大,节点要等再被访问或到期才释放)—— 差多少就照实显示,不替你对平。 -
另一条容易漏掉的轴是索引内存(keys_zone:条目元数据住这里,不占磁盘)。它吃紧时 nginx 会改按条目数强制回收,看板上的「索引吃紧」标记就是它 —— 该扩 keys_zone 了。 -
「清空」只删缓存文件、保留目录:手工 rm 掉 cache/<生态> 目录会让该路由此后每次写缓存都失败并断开客户端(直到 restart),这个坑踩过,所以清理必须由网关来做。 -
-
-
- - - -
-
-
- - - - - - -
缓存区磁盘目录占用 / 上限条目数索引内存状态操作
- - -
- 按制品失效 - - - - -
-
- -
- - -
-
-
-

命中计数

-
- 来自网关共享内存的运行期读数(按生态 × $upstream_cache_status,含跨生态汇总行 global)。 - 只统计真的进了缓存层的请求;被鉴权拦下或上游连不上的请求不计入分母。网关重启读数归零,但磁盘上的缓存文件仍在(命中不会因此变回 MISS)。 -
-
-
- - - - - -
生态HITMISSBYPASSEXPIREDREVALIDATEDUPDATINGSTALE命中率
-
- - -
-
-
-

nginx 变量契约

-
- 下面这几个变量由网关模块按「上游表 + 请求 URI」实时算出,nginx 配置里直接引用即可。 - 改上游地址/凭据不需要改 conf、也不需要 reload —— 变量每次求值都读共享内存。 -
-
-
- - - -
变量含义
-
-
- -
- - - - - diff --git a/www/domains.html b/www/domains.html deleted file mode 100644 index f8d3742..0000000 --- a/www/domains.html +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - -全部域名 · 尚数网 山海关 - - - -
- -
-
-

新建域名(直接放行)

-
管理员创建即生效,跳过审核流程。
-
-
- -
- i - - dm - -
-
-
-
-
- - -
-
-
-
-
- -
-

全部域名

-
临时域名到期后自动失效(状态变为「已过期」),记录保留供查阅。
- - - - - -
子域名后端类型归属状态到期操作
-
-
- -
- - - - - diff --git a/www/hourly.html b/www/hourly.html deleted file mode 100644 index 7493449..0000000 --- a/www/hourly.html +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - -24 小时热力 · 尚数网 山海关 - - - -
- -
-
-
-
-

请求热力(按小时 × 上游)

-
- 直接读审计 meta.jsonl 聚合,实时反映所有请求(含被拒的 401/404)。 - 数据源与 shm 日桶 / 趋势接口无关——审计落盘即聚合,零延迟。 - 颜色越深 = 请求越多;格内数字为该 (slot, 小时) 的请求数与 token 数。 -
-
-
- - - - -
-
- -
-
区间内请求
-
-
区间内入 token
-
-
区间内出 token
-
-
覆盖 slot
-
-
覆盖账号
-
-
数据来源
meta.jsonl
-
- -
- -
-
Top 10 繁忙 (slot, 小时) 组合
- - - - - -
slot日期小时请求入 token出 token
-
-
- -
-
-
-

审计数据来源

-
- 审计 meta.jsonl 按天分目录,容量超 AUDIT_MAX_BYTES 时从最旧整目录删; - 取数前先调 /api/admin/audit/days 列出实际可用日期。 -
-
- -
-
-
-
- -
- - - - - - \ No newline at end of file diff --git a/www/login.html b/www/login.html deleted file mode 100644 index 8d679c6..0000000 --- a/www/login.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - -登录 · 尚数网 山海关 - - - - - -
- - - - - diff --git a/www/me.html b/www/me.html deleted file mode 100644 index 5f5e30a..0000000 --- a/www/me.html +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - -我的用量 · 尚数网 山海关 - - - -
- -
- -
-
-
-

用 API Key 看我的用量

-
- 输入账号的 sk_xxx 即可查询本账号的最近调用、消耗、能用的上游/代理等数据。 - Key 只在浏览器 sessionStorage,关页面即清,不会落盘也不会上传。 -
-
-
- -
- - - -
- -
- - - - - - \ No newline at end of file diff --git a/www/overview.html b/www/overview.html deleted file mode 100644 index 00169ca..0000000 --- a/www/overview.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - -数据总览 · 尚数网 山海关 - - - -
- -
-
-
待审核申请
-
-
域名总数
-
-
可用中
-
-
账号总数
-
-
LLM 上游
-
-
今日 LLM 调用
-
-
累计调用
-
-
今日 token
-
-
累计 token
-
-
累计 token (自上线)
-
-
可用模型
-
-
- -
-
-

调用量趋势

-
按本地自然日分桶,只统计真正转发给上游的请求(401/403/404/429 不计)。
-
-
-
-

token 趋势

-
入 = prompt,出 = completion;取自上游响应体里的 usage,抓不到记 0、不补估。
-
-
-
- -
-
-
-
-

按账号 · 累计调用

-
Top 8;完整明细见「用量统计」。
-
- 明细 -
-
-
-
-
-
-

按 API 组 · 累计调用

-
每条 = 一个上游 slot。
-
- 明细 -
-
-
-
- - -
- -
- - - - - - - diff --git a/www/review.html b/www/review.html deleted file mode 100644 index dbbad0b..0000000 --- a/www/review.html +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - -审核队列 · 尚数网 山海关 - - - -
- -
-
-

待审核申请

-
临时域名在申请人没有「临时授权权限」时进入待审;长期域名一律需要人工审核。通过后立即生效,无需重启网关。
- - - - - -
子域名后端类型申请人提交时间操作
-
-
- -
- - - - - - diff --git a/www/upstreams.html b/www/upstreams.html deleted file mode 100644 index c1f42a1..0000000 --- a/www/upstreams.html +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - -LLM 上游 · 尚数网 山海关 - - - -
- -
-
-
-
-

上游列表

-
slot 即 URL 前缀:客户端把 base_url 指向 https://lm.mayishangshu.cn/<slot>/v1 并携带其账号 API Key,网关把 Key 换成本处配置的上游密钥后转发。一家厂商通常挂很多模型,把模型名登记在这里,客户端就能通过 GET /v1/models 或 GET /api/v1/models 先列出可用模型再调用。停用的上游对客户端表现为 404;删除不可恢复,指向它的调用会立即失败。
-
- -
- - - - - -
slot上游地址密钥 / 负载模型备注状态创建时间操作
-
-
- -
- - - - - diff --git a/www/usage.html b/www/usage.html deleted file mode 100644 index 3f4e19f..0000000 --- a/www/usage.html +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - -用量统计 · 尚数网 山海关 - - - -
- -
-
-
区间内调用
-
-
区间内入 token
-
-
区间内出 token
-
-
今日调用
-
-
累计调用
-
-
累计 token
-
-
- -
-
-
-

趋势

-
按本地自然日分桶(最多 90 天),只统计真正转发给上游的请求;token 取自上游响应体里的 usage。
-
-
- -
-
-
- - - - -
-
-
-
请求数 / 天
-
-
-
-
token / 天
-
-
-
-
- -
-
-
-

按账号

-
口径是请求数与真实 token;被拒的 401/403/404/429 不计。
-
- -
-
- - - - - -
账号今日累计入 token出 token最近调用分上游明细
-
- -
-
-
-

按 API 组(上游 slot)

-
每条 = 一个上游 slot 的总量;「使用者」列出各账号的今日/累计。
-
- -
-
- - - - - -
slot今日累计入 token出 token最近调用使用者
-
-
- -
- - - - - - diff --git a/www/users.html b/www/users.html deleted file mode 100644 index 899406b..0000000 --- a/www/users.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - -账号管理 · 尚数网 山海关 - - - -
- -
-
-

新建账号

-
每个账号自动生成一个随机 API Key,用于调用申请接口。勾选「临时授权权限」后,该账号申请临时域名可免审核直接放行,权限本身 6 小时后失效。
-
-
-
-
-
- - -
-
-
-
-
- -
-

账号列表

-
API Key 完整值在创建时展示一次;此处可复制或重置。
- - - - - -
账号角色API KeyLLM 用量临时授权权限域名操作
-
-
- -
- - - - -