一个 slot 挂多把上游账号 Key,解决厂商「单账号额度/并发受限」与 「同一用户缓存命中」两个矛盾诉求。 多账号路由 (plugin-llm) - models: Upstream.accounts[] (auth/note/resets) + 上游级 exhaust_status/exhaust_markers;顶层 auth 保留兼容(accounts 为空时合成单账号) - upstreams::pick_account:粘性绑定 ukb:<key> 优先 → 无绑定时 FNV-1a(下游 Key) % 可用数 冷分散 → 绑定账号冷却则重新分散 → 全冷却取最早恢复 * 分散避开厂商单账号 agent 并发上限;落点固定保住 prompt/token 缓存 - cool_until_until 天锚定冷却:boundary = day0 + ceil(已过/窗口)*窗口, 封顶次日 0 点(MiniMax 5h 窗口、24=5*4+4 → 末段 20:00-24:00 只有 4h 随天重置) - 耗尽双检测 (log 阶段):$upstream_status 命中 exhaust_status,或 usage_filter 流式扫到 marker → $llm_acct 定位本次账号 → 写冷却 uac: - shm: up:/upa:/uac:/ukb:/upe: 五类前缀;$llm_acct 变量 (NOCACHEABLE) 账号级负载统计(问题发现与跟踪) - 新增 uda:<slot>:<idx>:<day>(请求/token)与 uex:(耗尽次数) 日桶, 复用内核 usage::bump_day —— 无数据库、无新进程(项目红线) - 计数点只在 log 阶段一次;pick_account 会被 $llm_target/$llm_auth/$llm_acct 三个变量各触发一次,放进那里会三倍计数 - view() 投影带每账号 load 与 account_trend + trend_labels(日期由后端算) - 管理台「上游」页密钥列:各 Key 今日请求/token/耗尽 + 负载比例条 + 14 天迷你趋势(自绘 SVG,零第三方依赖)+ 冷却/耗尽徽标 + 上游合计 测试与验证 - 回归 279 条全绿(网关 102 + LLM 177),新增 6 条多账号/负载断言 - 假上游新增 UPSTREAM_FAIL_AUTH 模拟账号额度耗尽;靶机验证 Key 真被替换 - 前端以真实 admin.css + upstreams.js 渲染路径做无头浏览器断言: 比例条与负载成比例(412 vs 96 → 100%/23%)、每账号 14 条块、 悬停峰值日期与数据逐位吻合、单账号/无账号兜底正常、无横向溢出、零 JS 错误 文档 - 新增 docs/llm/MULTI_ACCOUNT_ROUTING.md(数据模型/路由/冷却数学/shm 布局/负载统计) - readme §11 数据模型 + §15 上游配置 + §15 用量统计 + §12.6 tag 表 + §16 变更记录 - 修正 docs/llm/*.md 中插件化前的过时路径(rust/src/* → crates/plugin-llm/src/*)
126 lines
5.6 KiB
Python
126 lines
5.6 KiB
Python
"""假上游:记录它**实际收到**的 path / auth / host / body。
|
||
|
||
这是验证「下游 Key 是否真被换成上游真 Key」的唯一可靠手段 ——
|
||
只看网关自己的响应是看不出来的(网关返回 200 不代表上游收到了正确的头)。
|
||
|
||
UPSTREAM_PORT=18999 UPSTREAM_LOG=/path/to/upstream.log python3 upstream.py
|
||
|
||
带 `"stream": true` 的请求体会回 SSE,分 3 块、每块间隔 0.4s,
|
||
用来验证 nginx 侧 `proxy_buffering off` 是否生效(缓冲住的话会攒完一次性返回)。
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
import time
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
|
||
LOG = os.environ.get("UPSTREAM_LOG", "/tmp/upstream.log")
|
||
PORT = int(os.environ.get("UPSTREAM_PORT", "18999"))
|
||
# 故障注入(多账号路由测试):收到的 Authorization 含此子串时模拟「上游账号额度耗尽」,
|
||
# 回 401 + 响应体标记(与 MiniMax 的 status_code:1004 同构),验证网关自动切换。
|
||
FAIL_AUTH = os.environ.get("UPSTREAM_FAIL_AUTH", "")
|
||
|
||
|
||
class H(BaseHTTPRequestHandler):
|
||
protocol_version = "HTTP/1.1"
|
||
|
||
def _record(self, body: bytes):
|
||
# 记录**全部**收到的头,而不是手挑几个字段。
|
||
# 教训:手挑字段会漏掉"没被替换的那个头"——第一版只记 Authorization,
|
||
# 于是 x-api-key 泄漏在整轮回归里全绿通过,完全看不见。
|
||
rec = {
|
||
"path": self.path,
|
||
"method": self.command,
|
||
"headers": {k.lower(): v for k, v in self.headers.items()},
|
||
# 下面几个是长期被断言的字段,保留以免旧断言失效
|
||
"auth": self.headers.get("Authorization", "-"),
|
||
"x_api_key": self.headers.get("x-api-key", "-"),
|
||
"anthropic_version": self.headers.get("anthropic-version", "-"),
|
||
"host": self.headers.get("Host", "-"),
|
||
"body": body.decode("utf-8", "replace"),
|
||
}
|
||
with open(LOG, "a") as f:
|
||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||
|
||
def do_GET(self):
|
||
"""`GET /<slot>/v1/models` 必须原样透传到上游——这里验的就是这条。
|
||
|
||
网关自己的 `GET /v1/models`(无 slot 段)在本地应答、不会打到这里,
|
||
两条路互不干扰。
|
||
"""
|
||
self._record(b"")
|
||
payload = json.dumps({
|
||
"object": "list",
|
||
"data": [{"id": "upstream-model", "object": "model"}],
|
||
}).encode()
|
||
self.send_response(200)
|
||
self.send_header("Content-Type", "application/json")
|
||
self.send_header("Content-Length", str(len(payload)))
|
||
self.end_headers()
|
||
self.wfile.write(payload)
|
||
|
||
def do_POST(self):
|
||
n = int(self.headers.get("Content-Length") or 0)
|
||
body = self.rfile.read(n)
|
||
self._record(body)
|
||
|
||
# 故障注入(多账号路由测试):收到的 Authorization 含 UPSTREAM_FAIL_AUTH 子串时,
|
||
# 模拟「上游账号额度耗尽」——回 401 + 响应体标记(与 MiniMax 的 status_code:1004 同构),
|
||
# 验证网关「状态码 + body marker 双重检测 → 标记冷却 → 下次自动切到下一个账号」。
|
||
if FAIL_AUTH and FAIL_AUTH in self.headers.get("Authorization", "-"):
|
||
payload = json.dumps(
|
||
{"base_resp": {"status_code": 1004, "status_msg": "exhausted"}}
|
||
).encode()
|
||
self.send_response(401)
|
||
self.send_header("Content-Type", "application/json")
|
||
self.send_header("Content-Length", str(len(payload)))
|
||
self.end_headers()
|
||
self.wfile.write(payload)
|
||
return
|
||
|
||
# 故障注入:body 带 `"boom":true` 时回 500,用来验证网关的
|
||
# 上游健康标记(log 阶段把 5xx 写进 uh: 缓存 → 列表标红)
|
||
if b'"boom"' in body:
|
||
payload = json.dumps({"error": {"message": "injected failure", "type": "boom"}}).encode()
|
||
self.send_response(500)
|
||
self.send_header("Content-Type", "application/json")
|
||
self.send_header("Content-Length", str(len(payload)))
|
||
self.end_headers()
|
||
self.wfile.write(payload)
|
||
return
|
||
|
||
if b'"stream"' in body and b"true" in body:
|
||
self.send_response(200)
|
||
self.send_header("Content-Type", "text/event-stream")
|
||
self.send_header("Cache-Control", "no-cache")
|
||
self.send_header("Connection", "close")
|
||
self.end_headers()
|
||
for i in range(3):
|
||
self.wfile.write(('data: {"i":%d}\n\n' % i).encode())
|
||
self.wfile.flush()
|
||
time.sleep(0.4)
|
||
# token 计量探针:body 带 "usage_probe" 才在流尾追加 usage 块。
|
||
# 不带标记时保持 3 块不变——sse_test.py 的 CHUNKS=3 契约不能破。
|
||
if b'"usage_probe"' in body:
|
||
self.wfile.write(b'data: {"choices":[],"usage":{"prompt_tokens":11,"completion_tokens":22}}\n\n')
|
||
self.wfile.write(b'data: [DONE]\n\n')
|
||
self.wfile.flush()
|
||
self.close_connection = True
|
||
else:
|
||
payload = json.dumps({
|
||
"id": "chatcmpl-x",
|
||
"choices": [{"message": {"role": "assistant", "content": "pong"}}],
|
||
"usage": {"prompt_tokens": 7, "completion_tokens": 3},
|
||
}).encode()
|
||
self.send_response(200)
|
||
self.send_header("Content-Type", "application/json")
|
||
self.send_header("Content-Length", str(len(payload)))
|
||
self.end_headers()
|
||
self.wfile.write(payload)
|
||
|
||
def log_message(self, *a):
|
||
pass
|
||
|
||
|
||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|