Files
Calcium-Ion 7b857f5a1e feat(plugins): add provider plugins, request plugins and a community marketplace (#8271)
* feat(plugins): add provider plugins, request plugins and a community marketplace

- Provider plugins turn an upstream vendor into a channel type: routes,
  protocol conversion, models, static keys, sign-in flows with token
  refresh, balance queries, per-channel config and a scheduled hook.
- Request plugins run on requests and replies (ingress, request,
  outbound, egress, reply, report), with instances by scope, model
  ranges, dry runs and per-log records. Built-ins: request filter,
  request redaction, parameter override, auto reasoning effort, image
  compression and content moderation. Sensitive words move into a
  request filter instance on first start.
- Node sync: a system_sync_topics table lets every node reload settings,
  channels, plugins and other data within seconds, and the system info
  page shows each node's state.
- Marketplace: a community source next to the official one, lookup by
  plugin code for official and community plugins, key rules for
  community plugins, install counts and takedown warnings.

* docs(plugins): name request protocols and host-only members in the plugin API

- Protocol names: ctx.format and samples use relaykit's protocol names.
  The spec lists the client paths and body of each name, so every host
  passes the same names to plugins.
- Host-specific members: channel, group, user, token, channelTypes,
  channelOther and utils.paramOverride exist only on new-api. The types
  mark them optional.
- Relay routes: the spec now writes out the route keys and the converters
  each incoming path accepts. The schema lists the converter names.

* feat(plugins): show recommended plugins from the official list too

The site now marks official plugins as recommended in its index. The
built-in official and community lists both get a Recommended group;
lists added by the administrator still cannot recommend plugins.

* feat(plugins): fall back to www.newapi.pro when www.newapi.ai does not answer

Plugin lists, plugin files and logos from www.newapi.ai are downloaded
from www.newapi.pro, the mainland China site, when newapi.ai gives no
answer within 10 seconds; the browser remembers this for a day. The
marketplace toolbar has a download site picker: Auto, or Mainland China
to always use www.newapi.pro. Saved source addresses stay on newapi.ai,
and every file is still checked against its sha256.

Community install counts go to newapi.ai first and to newapi.pro when
newapi.ai cannot be reached.

* fix(plugins): leaving the page does not switch the plugin site to www.newapi.pro

Reloading or leaving the marketplace cancels requests still running.
That was read as www.newapi.ai not answering, so the browser moved to
www.newapi.pro for a day although newapi.ai was reachable. Requests
cut off by leaving the page are no longer counted.

* feat(plugins): choose the plugin download site by hand

The marketplace no longer switches between plugin sites by itself. The
toolbar menu lists the main site www.newapi.ai, the backup site
www.newapi.pro and the other plugin lists; picking an entry is the only
thing that changes where plugins are downloaded from, and the main site
can always be picked again.

A browser that the earlier automatic switch had moved to www.newapi.pro
opens on the main site again. The download site, the source choice and
managing sources now share one menu in the list header.

* feat(plugins): show plugin usage guides and require README and changelog

Every marketplace plugin version now ships a usage guide, README.md, and a
changelog, CHANGELOG.md, next to plugin.js. The install dialog shows the
guide in the reader's language when a translation is listed, falls back to
English, and links to the source file. A guide or changelog that breaks the
format is reported with its file, line and rule instead of being shown.

The plugin API document describes both formats, the translations they may
list, and the checks the community marketplace runs before it accepts a
version: readme_missing, readme_invalid, changelog_missing and
changelog_invalid. Versions accepted before these checks are not checked
again.

* fix(plugins): address review findings on plugin parts, limits and access

- Only the root user reads request plugin instance configs; an admin who
  may bind instances to channels gets them without configs.
- Outbound hooks that grow the body are held to MAX_REQUEST_BODY_MB, as
  ingress hooks are, and answer 413 without a retry.
- An admin who cannot read plugin options keeps the balance and model
  list actions on plugin channels; the server answers whether they work.
- Reading the parts of a plugin source gives up when the source does not
  parse or code elsewhere refers to meta, as the meta preview does.

* fix(plugins): address review findings on request processing, documents and node sync

- PDF checks resolve indirect parameters and bound every value the parser
  allocates or loops on: predictor columns, object stream counts, nested
  object streams, cross-reference streams and ToUnicode ranges. Font and
  CMap work checks the deadline.
- A WebP frame must match its declared canvas, and keyword search stops at
  its match limit.
- Request processing treats a body as JSON whenever the gateway parses it
  as JSON, keeps Gemini reply parts in place, scopes instances by the
  settled auto group, hides channel header overrides from plugin param
  overrides, and captures replies only for report instances in scope.
- Request processing no longer follows the plugin master switch, which now
  covers plugin tasks and channels only.
- json.patch copies stop at MAX_REQUEST_BODY_MB, and provider prepareRequest
  effects past it answer 413.
- Image billing reads the count from the final upstream body, including the
  count members of SiliconFlow, Imagen and Replicate and the Imagen default.
- Automatic channel status changes no longer reload every node's channel
  cache. A credential refresh holds no channel lock while it waits on the
  vendor. A key that needs login is disabled and the request can retry.
- Balance requests must go to the channel host or allowedHosts, and provider
  stream events a plugin drops keep the stream alive.
- Node sync: OAuth provider writes bump inside their transaction, a failed
  startup load is retried, and each node is judged by its own topics.
- request-filter checks the text the old sensitive-word check did,
  request-redact and content-moderation handle large inputs, and
  image-compress lossless mode leaves JPEG and WebP alone.

* fix(plugins): address the second review on balances, egress and routes

- Channel other_info writes (status changes, balance queries and manual
  multi-key actions) only land while other_info is still the value read,
  and retry otherwise, so a write on one node no longer overwrites another
  node's balance or status reason. They write only their own columns.
- On the Responses path egress reads the body after the channel finalizes
  it, which is the body sent upstream.
- The Vertex AI plugin picks the region by the model the client asked for,
  as the built-in Vertex AI channel does.
- /request-processing and /security are reserved route namespaces, and a
  test checks that every console page is reserved.
- The plugin API docs say what egress reads on a provider plugin channel.

* feat(channels): run the balance update as a system task with progress

"Update all balances" now queues a channel_balance system task instead of
starting a goroutine guarded by an in-process flag. The task row holds the
progress (enabled channels queried of total), so any node can answer it,
and its active key keeps one run at a time across nodes. The
CHANNEL_UPDATE_FREQUENCY schedule becomes the same task's schedule, so
manual and scheduled runs no longer overlap.

GET /api/channel/update_balance answers with the task id, and with the
running one when a run is already queued. GET
/api/channel/update_balance/task/:task_id, under the same channel
permission, returns the status, progress and failure of balance update
tasks only. The channel list follows the task, reloads as more channels
are queried and once more at the end, and reports how the run ended.

* feat(system): sync nodes through system tasks and clean up task history

Node sync no longer needs its own table. A write to synced data adds a
pending sync_<topic> system task. Every node polls the newest task of each
topic it keeps every 3 s and reloads when that task is newer than the one
it applied. Custom OAuth providers still add their task inside the write
transaction, and lock the newest task of the topic first, so tasks commit
in id order. The master marks a sync task succeeded once every online node
that keeps the topic has applied it. Until then the task shows how many
nodes have applied it and why the others have not. The
system_sync_topics table is gone.

A composite (type, id) index answers the newest task of a type from the
index. The latest-per-type and earliest-pending queries now read ids first,
because MySQL 5.7 scanned the whole table for them.

A daily system_task_cleanup task deletes finished system tasks older than
system_task_setting.retention_days (default 30, at least 1), in batches.
It never deletes active tasks or the newest task of any type. The
retention is set under Operations > Log maintenance.
2026-11-12 20:50:58 +08:00

648 lines
21 KiB
Go

package channel
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
"github.com/MoeForge/moego/regexp"
common2 "github.com/QuantumNous/new-api/common"
appconstant "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
// ApplyUpstreamBodyMetadata restores metadata that net/http cannot infer from
// a ReplayableBody. Callers pass the body given to NewRequest, which wraps a
// body that has no Close method.
func ApplyUpstreamBodyMetadata(req *http.Request, body io.Reader) {
replayable, ok := body.(common2.ReplayableBody)
if !ok {
return
}
// BodyStorage structurally satisfies ReplayableBody, but its Read uses the
// shared storage cursor and its Close closes the storage. Send it through
// a body with its own cursor so the replay source stays open for GetBody.
if storage, rawStorage := body.(common2.BodyStorage); rawStorage {
replayable = common2.NewReplayableBodyReader(storage)
req.Body = replayable.(io.ReadCloser)
}
req.ContentLength = replayable.Size()
if req.GetBody == nil {
req.GetBody = replayable.NewReader
}
}
func SetupApiRequestHeader(info *common.RelayInfo, c *gin.Context, req *http.Header) {
if info.RelayMode == constant.RelayModeAudioTranscription || info.RelayMode == constant.RelayModeAudioTranslation {
// multipart/form-data
} else if info.RelayMode == constant.RelayModeRealtime {
// websocket
} else {
req.Set("Content-Type", c.Request.Header.Get("Content-Type"))
req.Set("Accept", c.Request.Header.Get("Accept"))
if info.IsStream && c.Request.Header.Get("Accept") == "" {
req.Set("Accept", "text/event-stream")
}
}
}
const clientHeaderPlaceholderPrefix = "{client_header:"
const (
headerPassthroughAllKey = "*"
headerPassthroughRegexPrefix = "re:"
headerPassthroughRegexPrefixV2 = "regex:"
)
var passthroughSkipHeaderNamesLower = map[string]struct{}{
// RFC 7230 hop-by-hop headers.
"connection": {},
"keep-alive": {},
"proxy-authenticate": {},
"proxy-authorization": {},
"te": {},
"trailer": {},
"transfer-encoding": {},
"upgrade": {},
"cookie": {},
// Additional headers that should not be forwarded by name-matching passthrough rules.
"host": {},
"content-length": {},
"accept-encoding": {},
// Do not passthrough credentials by wildcard/regex.
"authorization": {},
"x-api-key": {},
"x-goog-api-key": {},
// WebSocket handshake headers are generated by the client/dialer.
"sec-websocket-key": {},
"sec-websocket-version": {},
"sec-websocket-extensions": {},
}
var headerPassthroughRegexCache sync.Map // map[string]*regexp.Regexp
func getHeaderPassthroughRegex(pattern string) (*regexp.Regexp, error) {
pattern = strings.TrimSpace(pattern)
if pattern == "" {
return nil, errors.New("empty regex pattern")
}
if v, ok := headerPassthroughRegexCache.Load(pattern); ok {
if re, ok := v.(*regexp.Regexp); ok {
return re, nil
}
headerPassthroughRegexCache.Delete(pattern)
}
compiled, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
actual, _ := headerPassthroughRegexCache.LoadOrStore(pattern, compiled)
if re, ok := actual.(*regexp.Regexp); ok {
return re, nil
}
return compiled, nil
}
func IsHeaderPassthroughRuleKey(key string) bool {
return isHeaderPassthroughRuleKey(key)
}
func isHeaderPassthroughRuleKey(key string) bool {
key = strings.TrimSpace(key)
if key == "" {
return false
}
if key == headerPassthroughAllKey {
return true
}
lower := strings.ToLower(key)
return strings.HasPrefix(lower, headerPassthroughRegexPrefix) || strings.HasPrefix(lower, headerPassthroughRegexPrefixV2)
}
func shouldSkipPassthroughHeader(name string) bool {
name = strings.TrimSpace(name)
if name == "" {
return true
}
lower := strings.ToLower(name)
if _, ok := passthroughSkipHeaderNamesLower[lower]; ok {
return true
}
return false
}
func applyHeaderOverridePlaceholders(template string, c *gin.Context, apiKey string) (string, bool, error) {
trimmed := strings.TrimSpace(template)
if strings.HasPrefix(trimmed, clientHeaderPlaceholderPrefix) {
afterPrefix := trimmed[len(clientHeaderPlaceholderPrefix):]
end := strings.Index(afterPrefix, "}")
if end < 0 || end != len(afterPrefix)-1 {
return "", false, fmt.Errorf("client_header placeholder must be the full value: %q", template)
}
name := strings.TrimSpace(afterPrefix[:end])
if name == "" {
return "", false, fmt.Errorf("client_header placeholder name is empty: %q", template)
}
if c == nil || c.Request == nil {
return "", false, fmt.Errorf("missing request context for client_header placeholder")
}
clientHeaderValue := c.Request.Header.Get(name)
if strings.TrimSpace(clientHeaderValue) == "" {
return "", false, nil
}
// Do not interpolate {api_key} inside client-supplied content.
return clientHeaderValue, true, nil
}
if strings.Contains(template, "{api_key}") {
template = strings.ReplaceAll(template, "{api_key}", apiKey)
}
if strings.TrimSpace(template) == "" {
return "", false, nil
}
return template, true, nil
}
// processHeaderOverride applies channel header overrides, with placeholder substitution.
// Supported placeholders:
// - {api_key}: resolved to the channel API key
// - {client_header:<name>}: resolved to the incoming request header value
//
// Header passthrough rules (keys only; values are ignored):
// - "*": passthrough all incoming headers by name (excluding unsafe headers)
// - "re:<regex>" / "regex:<regex>": passthrough headers whose names match the regex (Go regexp)
//
// Passthrough rules are applied first, then normal overrides are applied, so explicit overrides win.
func processHeaderOverride(info *common.RelayInfo, c *gin.Context) (map[string]string, error) {
headerOverride := make(map[string]string)
if info == nil {
return headerOverride, nil
}
headerOverrideSource := common.GetEffectiveHeaderOverride(info)
// Background polling has no client request from which to copy headers.
hasClientRequest := !info.IsChannelTest && c != nil && c.Request != nil
passAll := false
var passthroughRegex []*regexp.Regexp
if hasClientRequest {
for k := range headerOverrideSource {
key := strings.TrimSpace(strings.ToLower(k))
if key == "" {
continue
}
if key == headerPassthroughAllKey {
passAll = true
continue
}
var pattern string
switch {
case strings.HasPrefix(key, headerPassthroughRegexPrefix):
pattern = strings.TrimSpace(key[len(headerPassthroughRegexPrefix):])
case strings.HasPrefix(key, headerPassthroughRegexPrefixV2):
pattern = strings.TrimSpace(key[len(headerPassthroughRegexPrefixV2):])
default:
continue
}
if pattern == "" {
return nil, types.NewError(fmt.Errorf("header passthrough regex pattern is empty: %q", k), types.ErrorCodeChannelHeaderOverrideInvalid)
}
compiled, err := getHeaderPassthroughRegex(pattern)
if err != nil {
return nil, types.NewError(err, types.ErrorCodeChannelHeaderOverrideInvalid)
}
passthroughRegex = append(passthroughRegex, compiled)
}
}
if passAll || len(passthroughRegex) > 0 {
for name := range c.Request.Header {
if shouldSkipPassthroughHeader(name) {
continue
}
if !passAll {
matched := false
for _, re := range passthroughRegex {
if re.MatchString(name) {
matched = true
break
}
}
if !matched {
continue
}
}
value := strings.TrimSpace(c.Request.Header.Get(name))
if value == "" {
continue
}
headerOverride[strings.ToLower(strings.TrimSpace(name))] = value
}
}
for k, v := range headerOverrideSource {
if isHeaderPassthroughRuleKey(k) {
continue
}
key := strings.TrimSpace(strings.ToLower(k))
if key == "" {
continue
}
str, ok := v.(string)
if !ok {
return nil, types.NewError(nil, types.ErrorCodeChannelHeaderOverrideInvalid)
}
if !hasClientRequest && strings.HasPrefix(strings.TrimSpace(str), clientHeaderPlaceholderPrefix) {
continue
}
value, include, err := applyHeaderOverridePlaceholders(str, c, info.ApiKey)
if err != nil {
return nil, types.NewError(err, types.ErrorCodeChannelHeaderOverrideInvalid)
}
if !include {
continue
}
headerOverride[key] = value
}
return headerOverride, nil
}
func ResolveHeaderOverride(info *common.RelayInfo, c *gin.Context) (map[string]string, error) {
return processHeaderOverride(info, c)
}
// ApplyHeaderOverride applies the request plugins' header changes, then the
// channel overrides, after the adaptor's headers. Without a client request,
// only static values and {api_key} are resolved.
func ApplyHeaderOverride(info *common.RelayInfo, c *gin.Context, req *http.Request) error {
headers, err := processHeaderOverride(info, c)
if err != nil {
return err
}
if info == nil || req == nil || len(info.RequestPluginHeaders) == 0 {
applyHeaderOverrideToRequest(req, headers)
return nil
}
// The outbound stage refused protected and credential header names; a
// header that carries the channel key is a credential too and stays as
// the adaptor set it.
pluginValues := map[string][]string{}
for _, effect := range info.RequestPluginHeaders {
for _, name := range effect.Remove {
name = strings.TrimSpace(name)
if info.ApiKey == "" || !strings.Contains(req.Header.Get(name), info.ApiKey) {
req.Header.Del(name)
}
pluginValues[strings.ToLower(name)] = nil
}
for name, value := range effect.Set {
name = strings.TrimSpace(name)
if info.ApiKey == "" || !strings.Contains(req.Header.Get(name), info.ApiKey) {
req.Header.Set(name, value)
}
pluginValues[strings.ToLower(name)] = nil
}
}
for name := range pluginValues {
pluginValues[name] = req.Header.Values(name)
}
applyHeaderOverrideToRequest(req, headers)
var replaced []string
for name, values := range pluginValues {
if !slices.Equal(values, req.Header.Values(name)) {
replaced = append(replaced, name)
}
}
info.MarkRequestPluginHeaderOverrides(replaced)
return nil
}
func applyHeaderOverrideToRequest(req *http.Request, headerOverride map[string]string) {
if req == nil {
return
}
for key, value := range headerOverride {
req.Header.Set(key, value)
// set Host in req
if strings.EqualFold(key, "Host") {
req.Host = value
}
}
}
// RequestSigner is an adaptor that signs every upstream request it sends.
// The request senders call it last, after the header overrides; it may
// change only the headers and the URL query.
type RequestSigner interface {
SignUpstreamRequest(c *gin.Context, info *common.RelayInfo, method string, target *url.URL, header http.Header) error
}
func signUpstreamRequest(adaptor any, c *gin.Context, info *common.RelayInfo, method string, target *url.URL, header http.Header) error {
signer, ok := adaptor.(RequestSigner)
if !ok {
return nil
}
if err := signer.SignUpstreamRequest(c, info, method, target, header); err != nil {
return fmt.Errorf("sign request failed: %w", err)
}
return nil
}
func DoApiRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
fullRequestURL, err := a.GetRequestURL(info)
if err != nil {
return nil, fmt.Errorf("get request url failed: %w", err)
}
logger.LogDebug(c, "fullRequestURL: %s", common.SanitizeURLForLog(fullRequestURL))
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
if err != nil {
return nil, fmt.Errorf("new request failed: %w", err)
}
ApplyUpstreamBodyMetadata(req, requestBody)
headers := req.Header
err = a.SetupRequestHeader(c, &headers, info)
if err != nil {
return nil, fmt.Errorf("setup request header failed: %w", err)
}
// 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
// 这样可以覆盖默认的 Authorization header 设置
if err = ApplyHeaderOverride(info, c, req); err != nil {
return nil, err
}
if err = signUpstreamRequest(a, c, info, req.Method, req.URL, req.Header); err != nil {
return nil, err
}
resp, err := doRequest(c, req, info)
if err != nil {
return nil, fmt.Errorf("do request failed: %w", err)
}
return resp, nil
}
func DoFormRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
fullRequestURL, err := a.GetRequestURL(info)
if err != nil {
return nil, fmt.Errorf("get request url failed: %w", err)
}
logger.LogDebug(c, "fullRequestURL: %s", common.SanitizeURLForLog(fullRequestURL))
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
if err != nil {
return nil, fmt.Errorf("new request failed: %w", err)
}
ApplyUpstreamBodyMetadata(req, requestBody)
// set form data
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
headers := req.Header
err = a.SetupRequestHeader(c, &headers, info)
if err != nil {
return nil, fmt.Errorf("setup request header failed: %w", err)
}
// 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
// 这样可以覆盖默认的 Authorization header 设置
if err = ApplyHeaderOverride(info, c, req); err != nil {
return nil, err
}
if err = signUpstreamRequest(a, c, info, req.Method, req.URL, req.Header); err != nil {
return nil, err
}
resp, err := doRequest(c, req, info)
if err != nil {
return nil, fmt.Errorf("do request failed: %w", err)
}
return resp, nil
}
// WebSocketPreparer is an adaptor that prepares the request before its
// WebSocket handshake is built, such as binding the key it sends.
type WebSocketPreparer interface {
PrepareWebSocket(c *gin.Context, info *common.RelayInfo) error
}
// DoWssRequest dials the adaptor's upstream over WebSocket for the realtime
// and Responses WebSocket relays. It honors the channel proxy, is bound to the
// request context, and reports a rejected handshake as a *types.NewAPIError
// carrying the upstream status code (types.NewError preserves it).
func DoWssRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*websocket.Conn, error) {
if preparer, ok := a.(WebSocketPreparer); ok {
if err := preparer.PrepareWebSocket(c, info); err != nil {
return nil, err
}
}
fullRequestURL, err := a.GetRequestURL(info)
if err != nil {
return nil, fmt.Errorf("get request url failed: %w", err)
}
fullRequestURL = toWebSocketURL(fullRequestURL)
if targetURL, parseErr := url.Parse(fullRequestURL); parseErr == nil {
common2.SetContextKey(c, appconstant.ContextKeyUpstreamRequestOrigin, targetURL.Scheme+"://"+targetURL.Host)
}
targetHeader := http.Header{}
err = a.SetupRequestHeader(c, &targetHeader, info)
if err != nil {
return nil, fmt.Errorf("setup request header failed: %w", err)
}
// 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
// 这样可以覆盖默认的 Authorization header 设置
headerOverride, err := processHeaderOverride(info, c)
if err != nil {
return nil, err
}
for key, value := range headerOverride {
targetHeader.Set(key, value)
}
targetHeader.Set("Content-Type", c.Request.Header.Get("Content-Type"))
if _, signs := a.(RequestSigner); signs {
targetURL, parseErr := url.Parse(fullRequestURL)
if parseErr != nil {
return nil, fmt.Errorf("get request url failed: %w", parseErr)
}
if err = signUpstreamRequest(a, c, info, http.MethodGet, targetURL, targetHeader); err != nil {
return nil, err
}
fullRequestURL = targetURL.String()
}
dialer := *websocket.DefaultDialer
if info.ChannelSetting.Proxy != "" {
proxyURL, _, proxyErr := common2.ParseProxyURLRuntime(info.ChannelSetting.Proxy)
if proxyErr != nil {
return nil, proxyErr
}
dialer.Proxy = http.ProxyURL(proxyURL)
}
if info.ChannelSetting.TLSInsecureSkipVerify {
dialer.TLSClientConfig = common2.InsecureTLSConfig
}
targetConn, resp, err := dialer.DialContext(c.Request.Context(), fullRequestURL, targetHeader)
if err != nil {
statusCode := http.StatusInternalServerError
if resp != nil {
statusCode = resp.StatusCode
if resp.Body != nil {
_ = resp.Body.Close()
}
}
return nil, types.NewErrorWithStatusCode(fmt.Errorf("dial failed to %s: %w", common.SanitizeURLForLog(fullRequestURL), err), types.ErrorCodeDoRequestFailed, statusCode)
}
return targetConn, nil
}
// toWebSocketURL maps an http(s) endpoint to ws(s). Realtime adaptors already
// return ws(s) URLs, which pass through unchanged.
func toWebSocketURL(raw string) string {
switch {
case strings.HasPrefix(raw, "https://"):
return "wss://" + strings.TrimPrefix(raw, "https://")
case strings.HasPrefix(raw, "http://"):
return "ws://" + strings.TrimPrefix(raw, "http://")
default:
return raw
}
}
func DoRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
return doRequest(c, req, info)
}
// keepUpstreamRedirectResponse stops net/http from following redirects while
// returning the upstream 3xx response to the relay without an extra error.
func keepUpstreamRedirectResponse(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
func doRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
client, err := service.GetHttpClientWithProxySettings(info.ChannelSetting.Proxy, info.ChannelSetting)
if err != nil {
return nil, fmt.Errorf("new proxy http client failed: %w", err)
}
// Clients are cached and shared across channels, so override redirect
// behavior on a shallow copy instead of mutating the cached client. This
// still reuses its transport and connection pools, including HTTP/2's
// transparent stream retries.
relayClient := *client
relayClient.CheckRedirect = keepUpstreamRedirectResponse
if common2.DebugEnabled && req != nil && req.URL != nil {
policy := service.NormalizeHTTPTransportPolicy(info.ChannelSetting)
logger.LogDebug(c, "http transport select: host=%s protocol=%s shards=%d policy=%s",
req.URL.Host,
policy.Protocol,
policy.Shards,
policy.String())
}
if info.IsStream {
helper.SetEventStreamHeaders(c)
// 处理流式请求的 ping 保活
generalSettings := operation_setting.GetGeneralSetting()
if generalSettings.PingIntervalEnabled && !info.DisablePing {
pingInterval := time.Duration(generalSettings.PingIntervalSeconds) * time.Second
stopPinger := helper.StartStreamKeepAlive(c, pingInterval)
defer stopPinger()
}
}
common2.SetContextKey(c, appconstant.ContextKeyUpstreamRequestOrigin, req.URL.Scheme+"://"+req.URL.Host)
resp, err := relayClient.Do(req)
if err != nil {
// A url.Error quotes the request URL, whose query may carry a
// credential: log its operation, the host and the cause only.
reason := err.Error()
var urlErr *url.Error
if errors.As(err, &urlErr) && urlErr.Err != nil {
reason = fmt.Sprintf("%s %s: %v", urlErr.Op, req.URL.Host, urlErr.Err)
}
logger.LogError(c, common2.LogText("do request failed: %s", reason))
return nil, types.NewError(err, types.ErrorCodeDoRequestFailed, types.ErrOptionWithHideErrMsg("upstream error: do request failed"))
}
if resp == nil {
return nil, errors.New("resp is nil")
}
if common2.DebugEnabled {
policy := service.NormalizeHTTPTransportPolicy(info.ChannelSetting)
logger.LogDebug(c, "http transport negotiated: host=%s protocol=%s shards=%d policy=%s negotiated=%s",
req.URL.Host,
policy.Protocol,
policy.Shards,
policy.String(),
resp.Proto)
}
if upID := resp.Header.Get(common2.RequestIdKey); upID != "" {
c.Set(common2.UpstreamRequestIdKey, upID)
}
// The transport closes req.Body once it has written it. Closing it here
// would abort a body still being written after an early response and
// make the transport drop the connection that carries the response.
_ = c.Request.Body.Close()
return resp, nil
}
func DoTaskApiRequest(a TaskAdaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
fullRequestURL, err := a.BuildRequestURL(info)
if err != nil {
return nil, err
}
req, err := newTaskAPIRequest(c, fullRequestURL, requestBody)
if err != nil {
return nil, fmt.Errorf("new request failed: %w", err)
}
ApplyUpstreamBodyMetadata(req, requestBody)
// Do NOT wrap requestBody in a GetBody closure here: returning the same
// (already consumed) reader would make any transport-level retry silently
// replay an empty body. http.NewRequest already derives a correct,
// snapshot-based GetBody for *bytes.Reader/Buffer/strings.Reader bodies
// (which most task adaptors pass in); ApplyUpstreamBodyMetadata wires the
// same contract for bodies that explicitly implement ReplayableBody.
// Otherwise GetBody stays nil so the transport fails the retry instead of
// sending a corrupted request.
err = a.BuildRequestHeader(c, req, info)
if err != nil {
return nil, fmt.Errorf("setup request header failed: %w", err)
}
if err = ApplyHeaderOverride(info, c, req); err != nil {
return nil, err
}
if err = signUpstreamRequest(a, c, info, req.Method, req.URL, req.Header); err != nil {
return nil, err
}
resp, err := doRequest(c, req, info)
if err != nil {
return nil, fmt.Errorf("do request failed: %w", err)
}
return resp, nil
}
func newTaskAPIRequest(c *gin.Context, fullRequestURL string, requestBody io.Reader) (*http.Request, error) {
if c == nil || c.Request == nil {
return nil, errors.New("task client request is missing")
}
return http.NewRequestWithContext(c.Request.Context(), c.Request.Method, fullRequestURL, requestBody)
}