Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions controller/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -1033,7 +1033,10 @@ func FetchModels(c *gin.Context) {
return
}

client := &http.Client{}
client := service.GetHttpClient()
if client == nil {
client = http.DefaultClient
}
url := fmt.Sprintf("%s/v1/models", baseURL)

request, err := http.NewRequest("GET", url, nil)
Expand All @@ -1055,6 +1058,8 @@ func FetchModels(c *gin.Context) {
})
return
}
defer response.Body.Close()

//check status code
if response.StatusCode != http.StatusOK {
c.JSON(http.StatusInternalServerError, gin.H{
Expand All @@ -1063,7 +1068,6 @@ func FetchModels(c *gin.Context) {
})
return
}
defer response.Body.Close()

var result struct {
Data []struct {
Expand Down
52 changes: 9 additions & 43 deletions controller/model_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import (
"fmt"
"io"
"math/rand"
"net"
"net/http"
"strings"
"sync"
"time"

"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"

"github.com/gin-gonic/gin"
"gorm.io/gorm"
Expand Down Expand Up @@ -89,45 +89,11 @@ type syncRequest struct {
Locale string `json:"locale"`
}

func newHTTPClient() *http.Client {
timeoutSec := common.GetEnvOrDefault("SYNC_HTTP_TIMEOUT_SECONDS", 10)
dialer := &net.Dialer{Timeout: time.Duration(timeoutSec) * time.Second}
transport := &http.Transport{
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: time.Duration(timeoutSec) * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ResponseHeaderTimeout: time.Duration(timeoutSec) * time.Second,
}
if common.TLSInsecureSkipVerify {
transport.TLSClientConfig = common.InsecureTLSConfig
}
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = addr
}
if strings.HasSuffix(host, "github.io") {
if conn, err := dialer.DialContext(ctx, "tcp4", addr); err == nil {
return conn, nil
}
return dialer.DialContext(ctx, "tcp6", addr)
}
return dialer.DialContext(ctx, network, addr)
}
return &http.Client{Transport: transport}
}

var (
httpClientOnce sync.Once
httpClient *http.Client
)

func getHTTPClient() *http.Client {
httpClientOnce.Do(func() {
httpClient = newHTTPClient()
})
return httpClient
if client := service.GetHttpClient(); client != nil {
return client
}
return http.DefaultClient
}

func fetchJSON[T any](ctx context.Context, url string, out *upstreamEnvelope[T]) error {
Expand Down Expand Up @@ -180,10 +146,10 @@ func fetchJSON[T any](ctx context.Context, url string, out *upstreamEnvelope[T])
cacheMutex.Unlock()

// Try decode as envelope first
if err := json.Unmarshal(buf, out); err != nil {
if err := common.Unmarshal(buf, out); err != nil {
// Try decode as pure array
var arr []T
if err2 := json.Unmarshal(buf, &arr); err2 != nil {
if err2 := common.Unmarshal(buf, &arr); err2 != nil {
lastErr = err
return
}
Expand All @@ -205,9 +171,9 @@ func fetchJSON[T any](ctx context.Context, url string, out *upstreamEnvelope[T])
lastErr = errors.New("cache miss for 304 response")
return
}
if err := json.Unmarshal(buf, out); err != nil {
if err := common.Unmarshal(buf, out); err != nil {
var arr []T
if err2 := json.Unmarshal(buf, &arr); err2 != nil {
if err2 := common.Unmarshal(buf, &arr); err2 != nil {
lastErr = err
return
}
Expand Down
30 changes: 9 additions & 21 deletions controller/ratio_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"fmt"
"io"
"math"
"net"
"net/http"
"net/url"
"sort"
Expand All @@ -21,6 +20,7 @@ import (

"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/ratio_setting"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -67,6 +67,13 @@ type upstreamResult struct {
Err string `json:"err,omitempty"`
}

func getRatioSyncHTTPClient() *http.Client {
if client := service.GetHttpClient(); client != nil {
return client
}
return http.DefaultClient
}
Comment on lines +94 to +99

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

cat -n controller/ratio_sync.go | head -100

Repository: QuantumNous/new-api

Length of output: 3139


🏁 Script executed:

git log --oneline -20 controller/ratio_sync.go

Repository: QuantumNous/new-api

Length of output: 134


🏁 Script executed:

rg "getRatioSyncHTTPClient|GetHttpClient" -B 3 -A 5

Repository: QuantumNous/new-api

Length of output: 20192


🏁 Script executed:

rg "github\.io" --type go

Repository: QuantumNous/new-api

Length of output: 496


🏁 Script executed:

rg "IPv4|IPv6|Dial" controller/ --type go -B 2 -A 2

Repository: QuantumNous/new-api

Length of output: 45


🏁 Script executed:

git show 9c4d5126 --stat

Repository: QuantumNous/new-api

Length of output: 50375


🏁 Script executed:

git show 9c4d5126 -- controller/ratio_sync.go | head -150

Repository: QuantumNous/new-api

Length of output: 4188


🏁 Script executed:

cat -n service/http_client.go | head -80

Repository: QuantumNous/new-api

Length of output: 2874


🏁 Script executed:

cat -n controller/ratio_sync.go | sed -n '125,215p'

Repository: QuantumNous/new-api

Length of output: 3493


🏁 Script executed:

cat -n controller/model_sync.go | sed -n '1,100p'

Repository: QuantumNous/new-api

Length of output: 3318


🏁 Script executed:

rg "IPv4|IPv6|Dial|github\.io" --type go -B 5 -A 5

Repository: QuantumNous/new-api

Length of output: 10583


🏁 Script executed:

git log --all --oneline -- controller/ratio_sync.go

Repository: QuantumNous/new-api

Length of output: 1189


🏁 Script executed:

git log --all --oneline -50 | grep -i ratio

Repository: QuantumNous/new-api

Length of output: 388


🏁 Script executed:

git show 55c82713:controller/ratio_sync.go 2>/dev/null | head -100

Repository: QuantumNous/new-api

Length of output: 2306


🏁 Script executed:

rg "retryIPv4|fallback|ipv4.*ipv6|github\.io.*retry" --type go

Repository: QuantumNous/new-api

Length of output: 2906


🏁 Script executed:

cat -n service/http_client.go | sed -n '80,169p'

Repository: QuantumNous/new-api

Length of output: 3107


🏁 Script executed:

git log --all --oneline -- controller/ratio_sync.go

Repository: QuantumNous/new-api

Length of output: 1189


🏁 Script executed:

git show 55c82713 -- controller/ratio_sync.go | grep -A 20 -B 5 "getRatioSyncHTTPClient\|IPv4\|IPv6\|fallback\|Dial" | head -60

Repository: QuantumNous/new-api

Length of output: 2806


🏁 Script executed:

git log -p --all -S "github.io" -- "*.go" | head -200

Repository: QuantumNous/new-api

Length of output: 45


Shared client adoption LGTM; note: removed github.io IPv4→IPv6 dial fallback.

The helper and swap to client.Do(httpReq) are correct and enable HTTP_PROXY/HTTPS_PROXY env vars (fixing #4466).

The prior implementation at commit 55c8271 included a custom dialer that tried IPv4 first for *.github.io, falling back to IPv6 on failure. This fallback is now gone. For users without a proxy configured but relying on IPv4 reachability for basellm.github.io, this surfaces a connectivity regression. Consider either:

  • Adding a dedicated dialer fallback for *.github.io preset hosts, or
  • Documenting that the recommended fix for github.io reachability issues is now HTTP_PROXY/HTTPS_PROXY.

The retry loop at lines 200-208 safely reuses the same httpReq since the body is nil.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@controller/ratio_sync.go` around lines 70 - 75, getRatioSyncHTTPClient
currently returns service.GetHttpClient() or http.DefaultClient but dropped a
previous custom dialer that tried IPv4 first for github.io hosts, causing
regressions for users who rely on IPv4 reachability; restore a targeted fallback
by returning an *http.Client whose Transport uses Proxy:
http.ProxyFromEnvironment and a DialContext that, for hosts matching
"*.github.io" or "basellm.github.io", first attempts a "tcp4" dial and on
failure tries "tcp6" (using net.Dialer.DialContext for each); leave other hosts
to the normal DialContext behavior; implement this inside getRatioSyncHTTPClient
only when service.GetHttpClient() is nil so existing shared clients continue to
be used.


func FetchUpstreamRatios(c *gin.Context) {
var req dto.UpstreamRequest
if err := c.ShouldBindJSON(&req); err != nil {
Expand Down Expand Up @@ -124,26 +131,7 @@ func FetchUpstreamRatios(c *gin.Context) {

sem := make(chan struct{}, maxConcurrentFetches)

dialer := &net.Dialer{Timeout: 10 * time.Second}
transport := &http.Transport{MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, ResponseHeaderTimeout: 10 * time.Second}
if common.TLSInsecureSkipVerify {
transport.TLSClientConfig = common.InsecureTLSConfig
}
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = addr
}
// 对 github.io 优先尝试 IPv4,失败则回退 IPv6
if strings.HasSuffix(host, "github.io") {
if conn, err := dialer.DialContext(ctx, "tcp4", addr); err == nil {
return conn, nil
}
return dialer.DialContext(ctx, "tcp6", addr)
}
return dialer.DialContext(ctx, network, addr)
}
client := &http.Client{Transport: transport}
client := getRatioSyncHTTPClient()

for _, chn := range upstreams {
wg.Add(1)
Expand Down
5 changes: 4 additions & 1 deletion relay/channel/ali/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,10 @@ func updateTask(info *relaycommon.RelayInfo, taskID string) (*AliResponse, error

req.Header.Set("Authorization", "Bearer "+info.ApiKey)

client := &http.Client{}
client := service.GetHttpClient()
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
if err != nil {
common.SysLog("updateTask client.Do err: " + err.Error())
Expand Down
30 changes: 21 additions & 9 deletions relay/channel/ollama/relay-ollama.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@ import (
"github.com/samber/lo"
)

func getOllamaHTTPClient(timeout time.Duration) *http.Client {
baseClient := service.GetHttpClient()
if baseClient == nil {
if timeout > 0 {
return &http.Client{Timeout: timeout}
}
return http.DefaultClient
}
if timeout <= 0 {
return baseClient
}
clientCopy := *baseClient
clientCopy.Timeout = timeout
return &clientCopy
}

func openAIChatToOllamaChat(c *gin.Context, r *dto.GeneralOpenAIRequest) (*OllamaChatRequest, error) {
chatReq := &OllamaChatRequest{
Model: r.Model,
Expand Down Expand Up @@ -281,7 +297,7 @@ func ollamaEmbeddingHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *h
func FetchOllamaModels(baseURL, apiKey string) ([]OllamaModel, error) {
url := fmt.Sprintf("%s/api/tags", baseURL)

client := &http.Client{}
client := getOllamaHTTPClient(0)
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("创建请求失败: %v", err)
Expand Down Expand Up @@ -331,9 +347,7 @@ func PullOllamaModel(baseURL, apiKey, modelName string) error {
return fmt.Errorf("序列化请求失败: %v", err)
}

client := &http.Client{
Timeout: 30 * 60 * 1000 * time.Millisecond, // 30分钟超时,支持大模型
}
client := getOllamaHTTPClient(30 * time.Minute)
request, err := http.NewRequest("POST", url, strings.NewReader(string(requestBody)))
if err != nil {
return fmt.Errorf("创建请求失败: %v", err)
Expand Down Expand Up @@ -372,9 +386,7 @@ func PullOllamaModelStream(baseURL, apiKey, modelName string, progressCallback f
return fmt.Errorf("序列化请求失败: %v", err)
}

client := &http.Client{
Timeout: 60 * 60 * 1000 * time.Millisecond, // 1小时超时,支持超大模型
}
client := getOllamaHTTPClient(time.Hour)
request, err := http.NewRequest("POST", url, strings.NewReader(string(requestBody)))
if err != nil {
return fmt.Errorf("创建请求失败: %v", err)
Expand Down Expand Up @@ -448,7 +460,7 @@ func DeleteOllamaModel(baseURL, apiKey, modelName string) error {
return fmt.Errorf("序列化请求失败: %v", err)
}

client := &http.Client{}
client := getOllamaHTTPClient(0)
request, err := http.NewRequest("DELETE", url, strings.NewReader(string(requestBody)))
if err != nil {
return fmt.Errorf("创建请求失败: %v", err)
Expand Down Expand Up @@ -481,7 +493,7 @@ func FetchOllamaVersion(baseURL, apiKey string) (string, error) {

url := fmt.Sprintf("%s/api/version", trimmedBase)

client := &http.Client{Timeout: 10 * time.Second}
client := getOllamaHTTPClient(10 * time.Second)
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", fmt.Errorf("创建请求失败: %v", err)
Expand Down