diff --git a/.env.example b/.env.example index 4f43f0a622..43332ea308 100644 --- a/.env.example +++ b/.env.example @@ -68,6 +68,12 @@ # RELAY_TIMEOUT=0 # Relay HTTP 客户端空闲连接超时时间,单位秒,默认跟随 Go 标准库,设置为0表示不限制 # RELAY_IDLE_CONN_TIMEOUT=90 +# HTTP/2 连接连续未收到任何帧多少秒后发送 PING;0(默认)关闭健康探测。 +# 适用于上游连接,包括代理与分片连接;与发给客户端的 SSE 心跳独立。 +# RELAY_HTTP2_PING_IDLE_TIMEOUT=0 +# 启用探测后等待 PING 应答的秒数;0 或负数使用 Go 默认值 15 秒。 +# 仅关闭未应答的连接,正常应答的慢请求可继续等待。 +# RELAY_HTTP2_PING_TIMEOUT=15 # 等待上游返回响应头的超时时间,单位秒,默认 1800,设置为 0 表示不限制。 # 仅约束「等待响应头」这一段;响应头返回之后的流式传输不受影响。 # 注意:非流式请求通常要等上游生成完毕才会返回响应头,因此该值需留足余量。 diff --git a/common/constants.go b/common/constants.go index 0cdf106d74..2b16116970 100644 --- a/common/constants.go +++ b/common/constants.go @@ -173,6 +173,9 @@ var RelayTimeout int // unit is second var RelayIdleConnTimeout int // unit is second +var RelayHTTP2PingIdleTimeout int // seconds without incoming frames before probing; 0 disables probes +var RelayHTTP2PingTimeout int // seconds to wait for a PING acknowledgement + // RelayResponseHeaderTimeout limits how long the relay transport waits for the // upstream response headers after the request has been fully written. // 0 disables it (previous behaviour: wait forever). diff --git a/common/init.go b/common/init.go index 2dcd122302..697143ea77 100644 --- a/common/init.go +++ b/common/init.go @@ -113,6 +113,8 @@ func InitEnv() { BatchUpdateInterval = GetEnvOrDefault("BATCH_UPDATE_INTERVAL", 5) RelayTimeout = GetEnvOrDefault("RELAY_TIMEOUT", 0) RelayIdleConnTimeout = GetEnvOrDefault("RELAY_IDLE_CONN_TIMEOUT", 90) + RelayHTTP2PingIdleTimeout = GetEnvOrDefault("RELAY_HTTP2_PING_IDLE_TIMEOUT", 0) + RelayHTTP2PingTimeout = GetEnvOrDefault("RELAY_HTTP2_PING_TIMEOUT", 15) RelayResponseHeaderTimeout = GetEnvOrDefault("RELAY_RESPONSE_HEADER_TIMEOUT", 1800) RelayMaxIdleConns = GetEnvOrDefault("RELAY_MAX_IDLE_CONNS", 500) RelayMaxIdleConnsPerHost = GetEnvOrDefault("RELAY_MAX_IDLE_CONNS_PER_HOST", 100) diff --git a/service/http_client.go b/service/http_client.go index 5f50863c4a..44bd316d5e 100644 --- a/service/http_client.go +++ b/service/http_client.go @@ -96,6 +96,14 @@ func newRelayHTTPTransport() *http.Transport { transport.MaxIdleConns = common.RelayMaxIdleConns transport.MaxIdleConnsPerHost = common.RelayMaxIdleConnsPerHost transport.IdleConnTimeout = time.Duration(common.RelayIdleConnTimeout) * time.Second + if seconds := common.RelayHTTP2PingIdleTimeout; seconds > 0 { + if transport.HTTP2 == nil { + transport.HTTP2 = &http.HTTP2Config{} + } + // Probe the upstream connection, independently of downstream SSE heartbeats. + transport.HTTP2.SendPingTimeout = time.Duration(min(seconds, maxTimeoutSeconds)) * time.Second + transport.HTTP2.PingTimeout = time.Duration(min(max(common.RelayHTTP2PingTimeout, 0), maxTimeoutSeconds)) * time.Second + } // Bound the wait for upstream response headers. Without it, an upstream that // accepts the connection but never responds (and never sends FIN/RST) parks the // goroutine forever, and every buffer that request owns -- the raw body read by diff --git a/service/http_client_transport_test.go b/service/http_client_transport_test.go index d274c56a4d..305a9d741d 100644 --- a/service/http_client_transport_test.go +++ b/service/http_client_transport_test.go @@ -1,6 +1,8 @@ package service import ( + "bytes" + "context" "crypto/tls" "crypto/x509" "encoding/pem" @@ -12,11 +14,14 @@ import ( "sync" "sync/atomic" "testing" + "time" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "golang.org/x/net/http2" + "golang.org/x/net/http2/hpack" ) func withRelayHTTPTransportSettings(t *testing.T) { @@ -24,13 +29,16 @@ func withRelayHTTPTransportSettings(t *testing.T) { prevMaxIdle := common.RelayMaxIdleConns prevPerHost := common.RelayMaxIdleConnsPerHost prevTimeout := common.RelayIdleConnTimeout + prevPingIdle, prevPingTimeout := common.RelayHTTP2PingIdleTimeout, common.RelayHTTP2PingTimeout common.RelayMaxIdleConns = 500 common.RelayMaxIdleConnsPerHost = 100 common.RelayIdleConnTimeout = 90 + common.RelayHTTP2PingIdleTimeout, common.RelayHTTP2PingTimeout = 1, 1 t.Cleanup(func() { common.RelayMaxIdleConns = prevMaxIdle common.RelayMaxIdleConnsPerHost = prevPerHost common.RelayIdleConnTimeout = prevTimeout + common.RelayHTTP2PingIdleTimeout, common.RelayHTTP2PingTimeout = prevPingIdle, prevPingTimeout }) } @@ -569,3 +577,135 @@ func TestNormalizeHTTPTransportPolicyClampsWithoutPanic(t *testing.T) { assert.Equal(t, HTTPTransportPolicy{Protocol: dto.HTTPProtocolAuto, Shards: 1}, NormalizeHTTPTransportPolicy(dto.ChannelSettings{HTTP2ConnectionShards: -3})) assert.Equal(t, HTTPTransportPolicy{Protocol: dto.HTTPProtocolAuto, Shards: 8}, NormalizeHTTPTransportPolicy(dto.ChannelSettings{HTTP2ConnectionShards: 99})) } + +// serveHTTP2ProbePeer can withhold PING acknowledgements without sending FIN or +// RST, reproducing an upstream connection silently lost by an intermediary. +func serveHTTP2ProbePeer(conn net.Conn, acknowledge bool, pings *atomic.Int32) error { + defer conn.Close() + if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { + return err + } + preface := make([]byte, len(http2.ClientPreface)) + if _, err := io.ReadFull(conn, preface); err != nil { + return err + } + if string(preface) != http2.ClientPreface { + return fmt.Errorf("unexpected HTTP/2 preface: %q", preface) + } + framer := http2.NewFramer(conn, conn) + framer.ReadMetaHeaders = hpack.NewDecoder(4096, nil) + if err := framer.WriteSettings(); err != nil { + return err + } + var streamID uint32 + for { + frame, err := framer.ReadFrame() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + switch frame := frame.(type) { + case *http2.SettingsFrame: + if !frame.IsAck() { + if err := framer.WriteSettingsAck(); err != nil { + return err + } + } + case *http2.MetaHeadersFrame: + streamID = frame.StreamID + var block bytes.Buffer + if err := hpack.NewEncoder(&block).WriteField(hpack.HeaderField{Name: ":status", Value: "200"}); err != nil { + return err + } + if err := framer.WriteHeaders(http2.HeadersFrameParam{StreamID: streamID, BlockFragment: block.Bytes(), EndHeaders: true}); err != nil { + return err + } + if err := framer.WriteData(streamID, false, []byte("start")); err != nil { + return err + } + case *http2.PingFrame: + if frame.IsAck() { + continue + } + count := pings.Add(1) + if acknowledge { + if err := framer.WritePing(true, frame.Data); err != nil { + return err + } + if count >= 2 && streamID != 0 { + if err := framer.WriteData(streamID, true, []byte("end")); err != nil { + return err + } + streamID = 0 + } + } + } + } +} + +func TestRelayHTTP2HealthCheck(t *testing.T) { + for _, tc := range []struct { + name string + idleTimeout int + acknowledge bool + }{ + {name: "disabled", idleTimeout: 0}, + {name: "healthy slow response", idleTimeout: 1, acknowledge: true}, + {name: "unresponsive connection", idleTimeout: 1}, + } { + t.Run(tc.name, func(t *testing.T) { + withRelayHTTPTransportSettings(t) + common.RelayHTTP2PingIdleTimeout = tc.idleTimeout + + var connections, pings atomic.Int32 + peerErrors := make(chan error, 4) + server := httptest.NewUnstartedServer(nil) + server.EnableHTTP2 = true + server.Config.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){ + "h2": func(_ *http.Server, conn *tls.Conn, _ http.Handler) { + connection := connections.Add(1) + acknowledge := tc.acknowledge || connection > 1 + peerErrors <- serveHTTP2ProbePeer(conn, acknowledge, &pings) + }, + } + server.StartTLS() + t.Cleanup(server.Close) + client := newHTTPClientWithPolicyAndTLS(defaultHTTPTransportPolicy(), testTLSClientConfig(t, server)) + client.Timeout = 7 * time.Second + if tc.idleTimeout == 0 { + client.Timeout = 3 * time.Second + } + t.Cleanup(client.CloseIdleConnections) + + resp, err := client.Get(server.URL) + require.NoError(t, err) + require.Equal(t, 2, resp.ProtoMajor) + body, err := io.ReadAll(resp.Body) + require.NoError(t, resp.Body.Close()) + if tc.idleTimeout == 0 { + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.Zero(t, pings.Load(), "disabled probes must preserve the existing transport behavior") + } else if tc.acknowledge { + require.NoError(t, err, "a slow response must survive acknowledged health checks") + assert.Equal(t, "startend", string(body)) + assert.GreaterOrEqual(t, pings.Load(), int32(2)) + assert.Equal(t, int32(1), connections.Load()) + } else { + require.ErrorContains(t, err, "http2: client connection lost") + assert.Equal(t, "start", string(body), "already delivered content must not be replayed") + assert.Equal(t, int32(1), connections.Load()) + require.NoError(t, <-peerErrors, "the peer must observe the failed connection close") + + resp, err = client.Get(server.URL) + require.NoError(t, err) + body, err = io.ReadAll(resp.Body) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + assert.Equal(t, "startend", string(body)) + assert.Equal(t, int32(2), connections.Load(), "the next request must establish a fresh connection") + } + }) + } +}