2024-02-29 01:08:18 +08:00
|
|
|
|
package channel
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2025-05-09 13:57:00 +08:00
|
|
|
|
"context"
|
2024-02-29 01:08:18 +08:00
|
|
|
|
"errors"
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
"io"
|
|
|
|
|
|
"net/http"
|
2025-03-13 19:32:08 +08:00
|
|
|
|
common2 "one-api/common"
|
2025-08-14 20:05:06 +08:00
|
|
|
|
"one-api/logger"
|
2024-02-29 16:21:25 +08:00
|
|
|
|
"one-api/relay/common"
|
2024-07-16 22:07:10 +08:00
|
|
|
|
"one-api/relay/constant"
|
2025-05-09 13:57:00 +08:00
|
|
|
|
"one-api/relay/helper"
|
2024-02-29 01:08:18 +08:00
|
|
|
|
"one-api/service"
|
2025-05-09 13:57:00 +08:00
|
|
|
|
"one-api/setting/operation_setting"
|
2025-08-24 01:02:23 +08:00
|
|
|
|
"one-api/types"
|
2025-05-09 13:57:00 +08:00
|
|
|
|
"sync"
|
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/bytedance/gopkg/util/gopool"
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
2024-02-29 01:08:18 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2024-10-04 16:08:18 +08:00
|
|
|
|
func SetupApiRequestHeader(info *common.RelayInfo, c *gin.Context, req *http.Header) {
|
2024-07-16 22:07:10 +08:00
|
|
|
|
if info.RelayMode == constant.RelayModeAudioTranscription || info.RelayMode == constant.RelayModeAudioTranslation {
|
|
|
|
|
|
// multipart/form-data
|
2024-10-04 16:08:18 +08:00
|
|
|
|
} else if info.RelayMode == constant.RelayModeRealtime {
|
|
|
|
|
|
// websocket
|
2024-07-16 22:07:10 +08:00
|
|
|
|
} else {
|
2024-10-04 16:08:18 +08:00
|
|
|
|
req.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
|
|
|
|
|
req.Set("Accept", c.Request.Header.Get("Accept"))
|
2024-07-16 22:07:10 +08:00
|
|
|
|
if info.IsStream && c.Request.Header.Get("Accept") == "" {
|
2024-10-04 16:08:18 +08:00
|
|
|
|
req.Set("Accept", "text/event-stream")
|
2024-07-16 22:07:10 +08:00
|
|
|
|
}
|
2024-02-29 01:08:18 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-02-29 16:21:25 +08:00
|
|
|
|
func DoApiRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
|
2024-02-29 01:08:18 +08:00
|
|
|
|
fullRequestURL, err := a.GetRequestURL(info)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("get request url failed: %w", err)
|
|
|
|
|
|
}
|
2025-03-13 19:32:08 +08:00
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("fullRequestURL:", fullRequestURL)
|
|
|
|
|
|
}
|
2024-02-29 01:08:18 +08:00
|
|
|
|
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("new request failed: %w", err)
|
|
|
|
|
|
}
|
2025-08-24 01:02:23 +08:00
|
|
|
|
headers := req.Header
|
|
|
|
|
|
headerOverride := make(map[string]string)
|
|
|
|
|
|
for k, v := range info.HeadersOverride {
|
|
|
|
|
|
if str, ok := v.(string); ok {
|
|
|
|
|
|
headerOverride[k] = str
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return nil, types.NewError(err, types.ErrorCodeChannelHeaderOverrideInvalid)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
for key, value := range headerOverride {
|
|
|
|
|
|
headers.Set(key, value)
|
|
|
|
|
|
}
|
|
|
|
|
|
err = a.SetupRequestHeader(c, &headers, info)
|
2024-02-29 01:08:18 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("setup request header failed: %w", err)
|
|
|
|
|
|
}
|
2025-02-02 22:15:06 +08:00
|
|
|
|
resp, err := doRequest(c, req, info)
|
2024-02-29 01:08:18 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("do request failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
return resp, nil
|
2024-07-16 22:07:10 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
}
|
2025-05-09 18:57:06 +08:00
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("fullRequestURL:", fullRequestURL)
|
|
|
|
|
|
}
|
2024-07-16 22:07:10 +08:00
|
|
|
|
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("new request failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
// set form data
|
|
|
|
|
|
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
2025-08-24 01:02:23 +08:00
|
|
|
|
headers := req.Header
|
|
|
|
|
|
headerOverride := make(map[string]string)
|
|
|
|
|
|
for k, v := range info.HeadersOverride {
|
|
|
|
|
|
if str, ok := v.(string); ok {
|
|
|
|
|
|
headerOverride[k] = str
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return nil, types.NewError(err, types.ErrorCodeChannelHeaderOverrideInvalid)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
for key, value := range headerOverride {
|
|
|
|
|
|
headers.Set(key, value)
|
|
|
|
|
|
}
|
|
|
|
|
|
err = a.SetupRequestHeader(c, &headers, info)
|
2024-07-16 22:07:10 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("setup request header failed: %w", err)
|
|
|
|
|
|
}
|
2025-02-02 22:15:06 +08:00
|
|
|
|
resp, err := doRequest(c, req, info)
|
2024-07-16 22:07:10 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("do request failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
return resp, nil
|
2024-02-29 01:08:18 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2024-10-04 16:08:18 +08:00
|
|
|
|
func DoWssRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*websocket.Conn, error) {
|
|
|
|
|
|
fullRequestURL, err := a.GetRequestURL(info)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("get request url failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
targetHeader := http.Header{}
|
|
|
|
|
|
err = a.SetupRequestHeader(c, &targetHeader, info)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("setup request header failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
targetHeader.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
|
|
|
|
|
targetConn, _, err := websocket.DefaultDialer.Dial(fullRequestURL, targetHeader)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("dial failed to %s: %w", fullRequestURL, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
// send request body
|
|
|
|
|
|
//all, err := io.ReadAll(requestBody)
|
|
|
|
|
|
//err = service.WssString(c, targetConn, string(all))
|
|
|
|
|
|
return targetConn, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-05-31 22:13:17 +08:00
|
|
|
|
func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.CancelFunc {
|
|
|
|
|
|
pingerCtx, stopPinger := context.WithCancel(context.Background())
|
|
|
|
|
|
|
|
|
|
|
|
gopool.Go(func() {
|
|
|
|
|
|
defer func() {
|
2025-06-10 03:42:23 +08:00
|
|
|
|
// 增加panic恢复处理
|
|
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("SSE ping goroutine panic recovered:", fmt.Sprintf("%v", r))
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-05-31 22:13:17 +08:00
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("SSE ping goroutine stopped.")
|
|
|
|
|
|
}
|
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
|
|
if pingInterval <= 0 {
|
|
|
|
|
|
pingInterval = helper.DefaultPingInterval
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
ticker := time.NewTicker(pingInterval)
|
2025-06-10 03:42:23 +08:00
|
|
|
|
// 确保在任何情况下都清理ticker
|
|
|
|
|
|
defer func() {
|
|
|
|
|
|
ticker.Stop()
|
|
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("SSE ping ticker stopped")
|
|
|
|
|
|
}
|
|
|
|
|
|
}()
|
2025-05-31 22:13:17 +08:00
|
|
|
|
|
|
|
|
|
|
var pingMutex sync.Mutex
|
|
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("SSE ping goroutine started")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-06-10 03:42:23 +08:00
|
|
|
|
// 增加超时控制,防止goroutine长时间运行
|
|
|
|
|
|
maxPingDuration := 120 * time.Minute // 最大ping持续时间
|
|
|
|
|
|
pingTimeout := time.NewTimer(maxPingDuration)
|
|
|
|
|
|
defer pingTimeout.Stop()
|
|
|
|
|
|
|
2025-05-31 22:13:17 +08:00
|
|
|
|
for {
|
|
|
|
|
|
select {
|
|
|
|
|
|
// 发送 ping 数据
|
|
|
|
|
|
case <-ticker.C:
|
|
|
|
|
|
if err := sendPingData(c, &pingMutex); err != nil {
|
2025-06-10 03:42:23 +08:00
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("SSE ping error, stopping goroutine:", err.Error())
|
|
|
|
|
|
}
|
2025-05-31 22:13:17 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
// 收到退出信号
|
|
|
|
|
|
case <-pingerCtx.Done():
|
|
|
|
|
|
return
|
|
|
|
|
|
// request 结束
|
|
|
|
|
|
case <-c.Request.Context().Done():
|
|
|
|
|
|
return
|
2025-06-10 03:42:23 +08:00
|
|
|
|
// 超时保护,防止goroutine无限运行
|
|
|
|
|
|
case <-pingTimeout.C:
|
|
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("SSE ping goroutine timeout, stopping")
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
2025-05-31 22:13:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
return stopPinger
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func sendPingData(c *gin.Context, mutex *sync.Mutex) error {
|
2025-06-10 03:42:23 +08:00
|
|
|
|
// 增加超时控制,防止锁死等待
|
|
|
|
|
|
done := make(chan error, 1)
|
|
|
|
|
|
go func() {
|
|
|
|
|
|
mutex.Lock()
|
|
|
|
|
|
defer mutex.Unlock()
|
2025-05-31 22:13:17 +08:00
|
|
|
|
|
2025-06-10 03:42:23 +08:00
|
|
|
|
err := helper.PingData(c)
|
|
|
|
|
|
if err != nil {
|
2025-08-14 20:05:06 +08:00
|
|
|
|
logger.LogError(c, "SSE ping error: "+err.Error())
|
2025-06-10 03:42:23 +08:00
|
|
|
|
done <- err
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-05-31 22:13:17 +08:00
|
|
|
|
|
2025-06-10 03:42:23 +08:00
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("SSE ping data sent.")
|
|
|
|
|
|
}
|
|
|
|
|
|
done <- nil
|
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
|
|
// 设置发送ping数据的超时时间
|
|
|
|
|
|
select {
|
|
|
|
|
|
case err := <-done:
|
|
|
|
|
|
return err
|
|
|
|
|
|
case <-time.After(10 * time.Second):
|
|
|
|
|
|
return errors.New("SSE ping data send timeout")
|
|
|
|
|
|
case <-c.Request.Context().Done():
|
|
|
|
|
|
return errors.New("request context cancelled during ping")
|
2025-05-31 22:13:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-07-10 05:21:45 +00:00
|
|
|
|
func DoRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
|
|
|
|
|
|
return doRequest(c, req, info)
|
|
|
|
|
|
}
|
2025-02-02 22:15:06 +08:00
|
|
|
|
func doRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
|
|
|
|
|
|
var client *http.Client
|
|
|
|
|
|
var err error
|
2025-07-07 14:26:37 +08:00
|
|
|
|
if info.ChannelSetting.Proxy != "" {
|
|
|
|
|
|
client, err = service.NewProxyHttpClient(info.ChannelSetting.Proxy)
|
2025-02-02 22:15:06 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("new proxy http client failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
client = service.GetHttpClient()
|
|
|
|
|
|
}
|
2025-05-31 22:13:17 +08:00
|
|
|
|
|
2025-06-10 03:42:23 +08:00
|
|
|
|
var stopPinger context.CancelFunc
|
2025-05-09 13:57:00 +08:00
|
|
|
|
if info.IsStream {
|
|
|
|
|
|
helper.SetEventStreamHeaders(c)
|
2025-05-31 22:13:17 +08:00
|
|
|
|
// 处理流式请求的 ping 保活
|
|
|
|
|
|
generalSettings := operation_setting.GetGeneralSetting()
|
2025-07-18 23:38:35 +08:00
|
|
|
|
if generalSettings.PingIntervalEnabled && !info.DisablePing {
|
2025-05-28 21:34:45 +08:00
|
|
|
|
pingInterval := time.Duration(generalSettings.PingIntervalSeconds) * time.Second
|
2025-06-10 03:42:23 +08:00
|
|
|
|
stopPinger = startPingKeepAlive(c, pingInterval)
|
|
|
|
|
|
// 使用defer确保在任何情况下都能停止ping goroutine
|
|
|
|
|
|
defer func() {
|
|
|
|
|
|
if stopPinger != nil {
|
|
|
|
|
|
stopPinger()
|
|
|
|
|
|
if common2.DebugEnabled {
|
|
|
|
|
|
println("SSE ping goroutine stopped by defer")
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}()
|
2025-05-09 13:57:00 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-02-02 22:15:06 +08:00
|
|
|
|
resp, err := client.Do(req)
|
2025-05-31 22:13:17 +08:00
|
|
|
|
|
2024-02-29 01:08:18 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
|
|
|
|
|
if resp == nil {
|
|
|
|
|
|
return nil, errors.New("resp is nil")
|
|
|
|
|
|
}
|
2025-05-31 22:13:17 +08:00
|
|
|
|
|
2024-02-29 01:08:18 +08:00
|
|
|
|
_ = req.Body.Close()
|
|
|
|
|
|
_ = c.Request.Body.Close()
|
|
|
|
|
|
return resp, nil
|
|
|
|
|
|
}
|
2024-06-12 20:37:42 +08:00
|
|
|
|
|
|
|
|
|
|
func DoTaskApiRequest(a TaskAdaptor, c *gin.Context, info *common.TaskRelayInfo, requestBody io.Reader) (*http.Response, error) {
|
|
|
|
|
|
fullRequestURL, err := a.BuildRequestURL(info)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
|
|
|
|
|
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("new request failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
req.GetBody = func() (io.ReadCloser, error) {
|
|
|
|
|
|
return io.NopCloser(requestBody), nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
err = a.BuildRequestHeader(c, req, info)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("setup request header failed: %w", err)
|
|
|
|
|
|
}
|
2025-02-25 20:56:16 +08:00
|
|
|
|
resp, err := doRequest(c, req, info.RelayInfo)
|
2024-06-12 20:37:42 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("do request failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
return resp, nil
|
|
|
|
|
|
}
|