mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-11-25 05:38:42 +08:00
457 lines
15 KiB
Go
457 lines
15 KiB
Go
package proxy
|
|
|
|
import (
|
|
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/netpolicy"
|
|
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/web"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/audit"
|
|
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/llmurl"
|
|
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
|
sessionreporting "github.com/chaitin/MonkeyCode/monkeyai/backend/internal/session"
|
|
"github.com/chaitin/MonkeyCode/monkeyai/backend/logging"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
const upstreamFailureMessage = "连接上游模型失败,请检查模型配置,或重试"
|
|
|
|
var endpoints = []struct {
|
|
path string
|
|
upstream string
|
|
}{
|
|
{path: "/v1/chat/completions", upstream: "/chat/completions"},
|
|
{path: "/v1/responses", upstream: "/responses"},
|
|
{path: "/v1/messages", upstream: "/messages"},
|
|
}
|
|
|
|
type Target struct {
|
|
ModelID string
|
|
OwnershipType string
|
|
UpstreamModel string
|
|
Protocol string
|
|
UserID string
|
|
SessionID string
|
|
BaseURL string
|
|
ProxyURL string
|
|
APIKey string
|
|
}
|
|
|
|
// Resolver 根据代理凭据和请求模型返回真实上游配置。
|
|
type Resolver interface {
|
|
Resolve(ctx context.Context, credential, requestedModel string) (Target, error)
|
|
}
|
|
|
|
// SessionResolver 校验并确保调用会话属于指定用户。
|
|
// 由应用层用 session.Service 适配注入,代理不依赖具体会话服务。
|
|
type SessionResolver interface {
|
|
EnsureSession(context.Context, string, string, string, string) error
|
|
}
|
|
|
|
const (
|
|
maiSessionHeader = "X-MAI-Session-ID"
|
|
legacySessionHeader = "X-Session-ID"
|
|
parentSessionHeader = "X-MAI-Parent-Session-ID"
|
|
machineSessionHeader = "X-MAI-Machine-ID"
|
|
)
|
|
|
|
type ResolverFunc func(context.Context, string, string) (Target, error)
|
|
|
|
func (f ResolverFunc) Resolve(ctx context.Context, credential, requestedModel string) (Target, error) {
|
|
return f(ctx, credential, requestedModel)
|
|
}
|
|
|
|
// UsageRecorder 持久化成功响应中解析出的模型调用用量。
|
|
type UsageRecorder interface {
|
|
Record(context.Context, Call) error
|
|
}
|
|
|
|
type proxyContextKey struct{}
|
|
|
|
type proxyContext struct {
|
|
target Target
|
|
upstream *url.URL
|
|
upstreamPath string
|
|
stream bool
|
|
requestBody []byte
|
|
startedAt time.Time
|
|
reservation Reservation
|
|
settled sync.Once
|
|
logged sync.Once
|
|
upstreamStatus int
|
|
upstreamRequestID string
|
|
}
|
|
|
|
type Proxy struct {
|
|
lookupRejectedUser func(context.Context, string) (string, error)
|
|
resolver Resolver
|
|
sessions SessionResolver
|
|
logger *slog.Logger
|
|
recorder UsageRecorder
|
|
billing Billing
|
|
captures sync.WaitGroup
|
|
reverse *httputil.ReverseProxy
|
|
}
|
|
|
|
func DirectTransport() *http.Transport {
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
|
transport.Proxy = nil
|
|
return transport
|
|
}
|
|
|
|
func NewProxy(resolver Resolver, logger *slog.Logger) *Proxy {
|
|
if logger == nil {
|
|
logger = slog.Default()
|
|
}
|
|
p := &Proxy{
|
|
resolver: resolver,
|
|
logger: logger.With("module", "proxy"),
|
|
}
|
|
p.reverse = &httputil.ReverseProxy{
|
|
ErrorLog: logging.ErrorLog(p.logger),
|
|
Transport: withUpstreamTimeouts(GatewayTransport(nil)),
|
|
Rewrite: p.rewrite,
|
|
ModifyResponse: p.modifyResponse,
|
|
ErrorHandler: p.errorHandler,
|
|
FlushInterval: 100 * time.Millisecond,
|
|
}
|
|
return p
|
|
}
|
|
|
|
func (p *Proxy) WithUsageRecorder(recorder UsageRecorder) *Proxy {
|
|
p.recorder = recorder
|
|
return p
|
|
}
|
|
|
|
func (p *Proxy) WithRejectedUserLookup(lookup func(context.Context, string) (string, error)) *Proxy {
|
|
p.lookupRejectedUser = lookup
|
|
return p
|
|
}
|
|
|
|
func (p *Proxy) WithSessionResolver(resolver SessionResolver) *Proxy {
|
|
p.sessions = resolver
|
|
return p
|
|
}
|
|
|
|
func (p *Proxy) WithTransport(transport http.RoundTripper) *Proxy {
|
|
if transport != nil {
|
|
p.reverse.Transport = withUpstreamTimeouts(transport)
|
|
}
|
|
return p
|
|
}
|
|
|
|
func (p *Proxy) Register(router chi.Router) {
|
|
for _, endpoint := range endpoints {
|
|
router.Method(http.MethodPost, endpoint.path, p)
|
|
}
|
|
}
|
|
|
|
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
web.HTTPError(w, r, http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
upstreamPath, ok := upstreamPath(r.URL.Path)
|
|
if !ok {
|
|
web.NotFound(w, r)
|
|
return
|
|
}
|
|
logging.Bind(r.Context(), slog.String("route", r.URL.Path))
|
|
if ua := r.UserAgent(); !strings.Contains(ua, "ohmyagent") {
|
|
p.logRejectedUserAgent(r, ua)
|
|
web.HTTPError(w, r, http.StatusUnauthorized)
|
|
return
|
|
}
|
|
credential, ok := Credential(r)
|
|
if !ok {
|
|
web.HTTPError(w, r, http.StatusUnauthorized)
|
|
return
|
|
}
|
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 32<<20))
|
|
if err != nil {
|
|
slog.WarnContext(r.Context(), "操作失败", "module", "proxy", "operation", "ServeHTTP", "error", err)
|
|
web.HTTPError(w, r, http.StatusBadRequest)
|
|
return
|
|
}
|
|
meta, err := readRequestMeta(body)
|
|
if err != nil {
|
|
slog.WarnContext(r.Context(), "操作失败", "module", "proxy", "operation", "ServeHTTP", "error", err)
|
|
web.HTTPError(w, r, http.StatusBadRequest)
|
|
return
|
|
}
|
|
encoding, ok := negotiateEncoding(r.Header.Values("Accept-Encoding"))
|
|
if !ok {
|
|
http.Error(w, web.Message(r.Context(), "not_acceptable", "客户端不接受代理支持的响应编码"), http.StatusNotAcceptable)
|
|
return
|
|
}
|
|
if encoding != "" {
|
|
r.Header.Set("Accept-Encoding", encoding)
|
|
}
|
|
if p.resolver == nil {
|
|
logging.Event(r.Context(), p.logger, slog.LevelError, "proxy.operation.error", "模型代理未配置凭据解析器", "module", "proxy", "operation", "ServeHTTP")
|
|
web.HTTPError(w, r, http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
logging.Bind(r.Context(), slog.String("phase", "resolve_model"))
|
|
target, err := p.resolver.Resolve(r.Context(), credential, meta.Model)
|
|
if err != nil {
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
|
resource.Fail(r.Context(), w, err)
|
|
return
|
|
}
|
|
logging.Event(r.Context(), p.logger, slog.LevelWarn, "proxy.operation.warn", "解析模型失败", "module", "proxy", "operation", "ServeHTTP", "error", err)
|
|
web.HTTPError(w, r, http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if target.Protocol != "" && target.Protocol != protocolForPath(r.URL.Path) {
|
|
http.Error(w, web.Message(r.Context(), "model_protocol_mismatch", "模型协议与请求端点不匹配"), http.StatusBadRequest)
|
|
return
|
|
}
|
|
logging.Bind(r.Context(), slog.String("model_id", target.ModelID), slog.String("user_id", target.UserID), slog.String("operation", "proxy_request"))
|
|
upstream, err := parseBaseURL(target.BaseURL)
|
|
if err != nil {
|
|
logging.Diagnostic(r.Context(), p.logger, slog.LevelError, "model.configuration.failed", err, slog.String("model_id", target.ModelID), slog.String("operation", "parse_base_url"))
|
|
p.writeUpstreamFailure(w, r, target.ModelID, "")
|
|
return
|
|
}
|
|
if target.UpstreamModel != "" && target.UpstreamModel != meta.Model {
|
|
body, err = rewriteModel(body, target.UpstreamModel)
|
|
if err != nil {
|
|
slog.WarnContext(r.Context(), "操作失败", "module", "proxy", "operation", "ServeHTTP", "error", err)
|
|
web.HTTPError(w, r, http.StatusBadRequest)
|
|
return
|
|
}
|
|
}
|
|
logging.Bind(r.Context(), slog.String("phase", "ensure_session"))
|
|
sessionID, parentID := requestSession(r)
|
|
if sessionID != "" {
|
|
if p.sessions != nil {
|
|
if err := p.sessions.EnsureSession(r.Context(), target.UserID, sessionID, parentID, ""); err != nil {
|
|
if errors.Is(err, sessionreporting.ErrReportingDisabled) {
|
|
sessionID = ""
|
|
} else {
|
|
resource.Fail(r.Context(), w, err)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
target.SessionID = sessionID
|
|
}
|
|
var reservation Reservation
|
|
if p.billing != nil && target.OwnershipType != "user" {
|
|
logging.Bind(r.Context(), slog.String("phase", "billing_begin"))
|
|
reservation, err = p.billing.Begin(r.Context(), target, BillingRequest{Path: r.URL.Path, Body: body, IdempotencyKey: r.Header.Get("Idempotency-Key"), SessionID: sessionID})
|
|
if err != nil {
|
|
billingError(r.Context(), w, err)
|
|
return
|
|
}
|
|
logging.Bind(r.Context(), slog.String("phase", "billing_start"))
|
|
if err = p.billing.Start(r.Context(), reservation.ID); err != nil {
|
|
billingError(r.Context(), w, err)
|
|
return
|
|
}
|
|
w.Header().Set("X-Billing-Transaction-ID", reservation.ID)
|
|
}
|
|
logging.Bind(r.Context(), slog.String("phase", "upstream"))
|
|
r.GetBody = func() (io.ReadCloser, error) {
|
|
return io.NopCloser(bytes.NewReader(body)), nil
|
|
}
|
|
r.Body, _ = r.GetBody()
|
|
r.ContentLength = int64(len(body))
|
|
ctx := context.WithValue(r.Context(), proxyContextKey{}, &proxyContext{
|
|
target: target,
|
|
upstream: upstream,
|
|
upstreamPath: upstreamPath,
|
|
stream: meta.Stream,
|
|
requestBody: body,
|
|
startedAt: time.Now(),
|
|
reservation: reservation,
|
|
})
|
|
p.reverse.ServeHTTP(w, r.WithContext(ctx))
|
|
}
|
|
|
|
func (p *Proxy) logRejectedUserAgent(r *http.Request, ua string) {
|
|
if !p.logger.Enabled(r.Context(), slog.LevelWarn) {
|
|
return
|
|
}
|
|
var userID string
|
|
if key, ok := Credential(r); ok && p.lookupRejectedUser != nil {
|
|
// 归属查询失败或超时不改变 401,也不触发模型解析和计费。
|
|
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
|
|
defer cancel()
|
|
if id, err := p.lookupRejectedUser(ctx, key); err == nil {
|
|
userID = id
|
|
}
|
|
}
|
|
logging.Event(r.Context(), p.logger, slog.LevelWarn, "proxy.user_agent.rejected", "模型代理拒绝请求:User-Agent 不含 ohmyagent",
|
|
"route", r.URL.Path, "status", http.StatusUnauthorized, "user_agent", ua, "user_agent_missing", ua == "",
|
|
"user_id", userID, "client_ip", audit.ClientIP(r))
|
|
}
|
|
|
|
func protocolForPath(requestPath string) string {
|
|
switch requestPath {
|
|
case "/v1/chat/completions":
|
|
return "openai_chat_completions"
|
|
case "/v1/responses":
|
|
return "openai_responses"
|
|
case "/v1/messages":
|
|
return "anthropic"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
func rewriteModel(body []byte, upstreamModel string) ([]byte, error) {
|
|
request, _, err := rawObject(body)
|
|
if err != nil || request == nil {
|
|
if err != nil {
|
|
slog.Warn("操作失败", "module", "proxy", "operation", "rewriteModel", "error", err)
|
|
}
|
|
return nil, errors.New("请求体必须是 JSON 对象")
|
|
}
|
|
encoded, err := json.Marshal(upstreamModel)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
request["model"] = encoded
|
|
return json.Marshal(request)
|
|
}
|
|
|
|
func (p *Proxy) rewrite(r *httputil.ProxyRequest) {
|
|
ctx, ok := r.In.Context().Value(proxyContextKey{}).(*proxyContext)
|
|
if !ok || ctx == nil || ctx.upstream == nil {
|
|
logging.Event(r.In.Context(), p.logger, slog.LevelError, "proxy.operation.error", "模型代理上下文缺失", "module", "proxy", "operation", "rewrite")
|
|
return
|
|
}
|
|
r.Out.URL.Scheme = ctx.upstream.Scheme
|
|
r.Out.URL.Host = ctx.upstream.Host
|
|
r.Out.URL.Path = llmurl.JoinPath(ctx.upstream.Path, ctx.upstreamPath, protocolForPath(r.In.URL.Path) == "anthropic")
|
|
r.Out.URL.RawPath = ""
|
|
if ctx.upstream.RawQuery != "" {
|
|
if r.Out.URL.RawQuery == "" {
|
|
r.Out.URL.RawQuery = ctx.upstream.RawQuery
|
|
} else {
|
|
r.Out.URL.RawQuery = ctx.upstream.RawQuery + "&" + r.Out.URL.RawQuery
|
|
}
|
|
}
|
|
r.Out.Header.Del("Authorization")
|
|
r.Out.Header.Del("X-Api-Key")
|
|
r.Out.Header.Del("Idempotency-Key")
|
|
for _, header := range []string{maiSessionHeader, parentSessionHeader, machineSessionHeader} {
|
|
r.Out.Header.Del(header)
|
|
}
|
|
if ctx.target.APIKey != "" {
|
|
r.Out.Header.Set("Authorization", "Bearer "+ctx.target.APIKey)
|
|
r.Out.Header.Set("X-Api-Key", ctx.target.APIKey)
|
|
}
|
|
r.SetXForwarded()
|
|
r.Out.Header.Del("X-Forwarded-For")
|
|
r.Out.Host = ctx.upstream.Host
|
|
}
|
|
|
|
func (p *Proxy) errorHandler(w http.ResponseWriter, r *http.Request, err error) {
|
|
modelID, transactionID := "", ""
|
|
if pc, ok := r.Context().Value(proxyContextKey{}).(*proxyContext); ok {
|
|
modelID, transactionID = pc.target.ModelID, pc.reservation.ID
|
|
code := "upstream_connection_failed"
|
|
policyCode := netpolicy.ModelErrorCode(err)
|
|
if policyCode != "" {
|
|
code = policyCode
|
|
} else if upstreamTimedOut(r.Context(), err) {
|
|
code = "upstream_timeout"
|
|
}
|
|
// 拒绝发生在发送请求前,零用量是已知的,不应保留待核对的冻结额度。
|
|
call := Call{Stream: pc.stream, Known: policyCode != "", Result: "failed", ErrorCode: code}
|
|
p.logCall(r.Context(), pc, call, err)
|
|
p.finish(r.Context(), pc, call)
|
|
}
|
|
if errors.Is(err, netpolicy.ErrDenied) {
|
|
http.Error(w, web.Message(r.Context(), "model_address_denied", netpolicy.ErrDenied.Error()), http.StatusForbidden)
|
|
return
|
|
}
|
|
p.writeUpstreamFailure(w, r, modelID, transactionID)
|
|
}
|
|
|
|
func (p *Proxy) writeUpstreamFailure(w http.ResponseWriter, r *http.Request, modelID, transactionID string) {
|
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
w.WriteHeader(http.StatusBadGateway)
|
|
if _, writeErr := io.WriteString(w, web.Message(r.Context(), "upstream_connection_failed", upstreamFailureMessage)); writeErr != nil && r.Context().Err() == nil && !errors.Is(writeErr, io.ErrClosedPipe) {
|
|
logging.Event(r.Context(), p.logger, slog.LevelWarn, "proxy.operation.warn", "写入代理错误响应失败", "module", "proxy", "operation", "writeUpstreamFailure", "model_id", modelID, "transaction_id", transactionID, "operation", "write_error_response", "error", writeErr)
|
|
}
|
|
}
|
|
|
|
func upstreamPath(requestPath string) (string, bool) {
|
|
for _, endpoint := range endpoints {
|
|
if endpoint.path == requestPath {
|
|
return endpoint.upstream, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
func parseBaseURL(raw string) (*url.URL, error) {
|
|
upstream, err := url.Parse(strings.TrimSpace(raw))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("解析模型地址: %w", err)
|
|
}
|
|
if upstream.Scheme != "http" && upstream.Scheme != "https" {
|
|
return nil, fmt.Errorf("模型地址协议 %q 不受支持", upstream.Scheme)
|
|
}
|
|
if upstream.Hostname() == "" || upstream.User != nil {
|
|
return nil, errors.New("模型地址主机无效")
|
|
}
|
|
upstream.Fragment = ""
|
|
return upstream, nil
|
|
}
|
|
|
|
func requestSession(req *http.Request) (string, string) {
|
|
sessionID := strings.TrimSpace(req.Header.Get(maiSessionHeader))
|
|
if sessionID == "" {
|
|
sessionID = strings.TrimSpace(req.Header.Get(legacySessionHeader))
|
|
}
|
|
return strings.ToLower(sessionID), strings.ToLower(strings.TrimSpace(req.Header.Get(parentSessionHeader)))
|
|
}
|
|
|
|
// Credential 保持 X-Api-Key 优先于 Bearer 的模型调用凭据提取规则。
|
|
func Credential(req *http.Request) (string, bool) {
|
|
credential := strings.TrimSpace(req.Header.Get("X-Api-Key"))
|
|
if credential != "" {
|
|
return credential, true
|
|
}
|
|
credential, ok := strings.CutPrefix(req.Header.Get("Authorization"), "Bearer ")
|
|
if !ok {
|
|
return "", false
|
|
}
|
|
credential = strings.TrimSpace(credential)
|
|
return credential, credential != ""
|
|
}
|
|
|
|
type requestMeta struct {
|
|
Model string `json:"model"`
|
|
Stream bool `json:"stream"`
|
|
}
|
|
|
|
func readRequestMeta(body []byte) (requestMeta, error) {
|
|
var meta *requestMeta
|
|
if err := json.Unmarshal(body, &meta); err != nil || meta == nil {
|
|
if err == nil {
|
|
err = errors.New("请求体必须是 JSON 对象")
|
|
}
|
|
return requestMeta{}, fmt.Errorf("解析模型请求: %w", err)
|
|
}
|
|
return *meta, nil
|
|
}
|