Files
ipass__ipass/tests/llm/upstream.py
T
admin 1b0bde9f72 feat(llm): 上游健康自动标记 + 管理台连通性测试 + 可复制 API 地址
- 健康标记(log 阶段):真实转发的上游状态码写入 uh:<slot>(4xx=活着,
  5xx/502/504=失效,下次成功自动自愈),数据来源就是真实流量本身,
  无需常驻探测进程。状态码读 $upstream_status 变量(r->upstream 在
  上游 finalize 时已置空,log 阶段读不到——access log 同款手法)。
- 管理台「测试」按钮:POST /api/admin/upstreams/test?slot=X,校验后
  ngx_http_internal_redirect 到管理 server 内部 location /_upstream_test,
  复用 LLM 链路的取 slot / 拼路径 / 换真 Key 逻辑,上游原话透传给面板。
  ⚠️ 内部重定向只浅拷贝 ngx_str_t,URI 必须拷进请求池——否则函数返回
  即悬垂,log 阶段 r->uri 全是 NUL,健康标记静默失效(实测踩坑)。
- 上游列表每行 slot 旁 OpenAI / Anthropic 两枚点击复制地址按钮,
  模型发现(/v1/models 与 /api/v1/models、/api/v1/upstreams)附
  anthropic_base_url 与健康状态;anthropic_base_url 统一收口
  upstreams::anthropic_base_url(),base 已钉 /anthropic 时不重复追加。
- 统计卡片挪进独立「数据总览」tab 并设为默认页。
- 回归 +12 条(第 12 节健康标记断言),LLM 111 + 网关 78,失败 0。
- 测试卫生:run.sh 启动靶机前 pkill 残留进程(占 18999 会造成假 200)。
2026-09-12 14:42:32 +08:00

102 lines
4.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""假上游:记录它**实际收到**的 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"))
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)
# 故障注入: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)
self.close_connection = True
else:
payload = json.dumps({
"id": "chatcmpl-x",
"choices": [{"message": {"role": "assistant", "content": "pong"}}],
}).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()