openai_first_output_timeout.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. package service
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "os"
  11. "runtime"
  12. "strings"
  13. "sync"
  14. "sync/atomic"
  15. "time"
  16. "github.com/Wei-Shaw/sub2api/internal/pkg/logger"
  17. "github.com/gin-gonic/gin"
  18. )
  19. const (
  20. openAIFirstOutputStageMemoryLimit = 64 * 1024
  21. openAIFirstOutputStageMaxBytes = 8 * 1024 * 1024
  22. openAIFirstOutputScannerFramingAllowance = 64
  23. openAIFirstOutputGuardQueueSize = 1
  24. openAIDefaultStreamQueueSize = 16
  25. )
  26. var (
  27. errOpenAIFirstOutputStageLimit = errors.New("openai first-output staging limit exceeded")
  28. errOpenAIFirstOutputScannerLimit = errors.New("openai pre-output scanner token limit exceeded")
  29. )
  30. type openAIFirstOutputStage struct {
  31. limit int64
  32. size int64
  33. memory bytes.Buffer
  34. tempFile *os.File
  35. tempPath string
  36. createTemp func() (*os.File, error)
  37. removeFile func(string) error
  38. memoryOnly bool
  39. cleanupErr error
  40. closed bool
  41. }
  42. func newOpenAIFirstOutputStage(limit int64) *openAIFirstOutputStage {
  43. if limit < 1 {
  44. limit = 1
  45. }
  46. return &openAIFirstOutputStage{
  47. limit: limit,
  48. createTemp: func() (*os.File, error) { return os.CreateTemp("", "sub2api-openai-first-output-*") },
  49. removeFile: os.Remove,
  50. memoryOnly: runtime.GOOS == "windows",
  51. }
  52. }
  53. func newDefaultOpenAIFirstOutputStage() *openAIFirstOutputStage {
  54. return newOpenAIFirstOutputStage(openAIFirstOutputStageMaxBytes)
  55. }
  56. func openAIFirstOutputEventQueueSize(guardFirstOutput bool) int {
  57. if guardFirstOutput {
  58. return openAIFirstOutputGuardQueueSize
  59. }
  60. return openAIDefaultStreamQueueSize
  61. }
  62. func openAIFirstOutputDynamicScanLines(guardActive *atomic.Bool) bufio.SplitFunc {
  63. return func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  64. advance, token, err = bufio.ScanLines(data, atEOF)
  65. if err != nil || guardActive == nil || !guardActive.Load() {
  66. return advance, token, err
  67. }
  68. limit := openAIFirstOutputStageMaxBytes + openAIFirstOutputScannerFramingAllowance
  69. if token != nil {
  70. if len(token) > limit {
  71. return 0, nil, errOpenAIFirstOutputScannerLimit
  72. }
  73. return advance, token, nil
  74. }
  75. // At the limit with no delimiter, another byte would necessarily exceed
  76. // the guarded token budget. Fail before Scanner grows toward MaxLineSize.
  77. if len(data) >= limit {
  78. return 0, nil, errOpenAIFirstOutputScannerLimit
  79. }
  80. return advance, token, nil
  81. }
  82. }
  83. func (s *openAIFirstOutputStage) Buffered() int64 {
  84. if s == nil {
  85. return 0
  86. }
  87. return s.size
  88. }
  89. func (s *openAIFirstOutputStage) WriteString(value string) (int, error) {
  90. if err := s.prepareWrite(len(value)); err != nil {
  91. return 0, err
  92. }
  93. var n int
  94. var err error
  95. if s.tempFile == nil {
  96. n, err = s.memory.WriteString(value)
  97. } else {
  98. n, err = io.WriteString(s.tempFile, value)
  99. }
  100. s.size += int64(n)
  101. if err != nil {
  102. return n, fmt.Errorf("write first-output stage: %w", err)
  103. }
  104. return n, nil
  105. }
  106. func (s *openAIFirstOutputStage) Write(p []byte) (int, error) {
  107. if err := s.prepareWrite(len(p)); err != nil {
  108. return 0, err
  109. }
  110. var n int
  111. var err error
  112. if s.tempFile == nil {
  113. n, err = s.memory.Write(p)
  114. } else {
  115. n, err = s.tempFile.Write(p)
  116. }
  117. s.size += int64(n)
  118. if err != nil {
  119. return n, fmt.Errorf("write first-output stage: %w", err)
  120. }
  121. return n, nil
  122. }
  123. func (s *openAIFirstOutputStage) prepareWrite(incoming int) error {
  124. if s == nil || s.closed {
  125. return os.ErrClosed
  126. }
  127. if int64(incoming) > s.limit-s.size {
  128. return fmt.Errorf("%w: buffered=%d incoming=%d limit=%d", errOpenAIFirstOutputStageLimit, s.size, incoming, s.limit)
  129. }
  130. if s.tempFile != nil || s.memoryOnly || s.size+int64(incoming) <= openAIFirstOutputStageMemoryLimit {
  131. return nil
  132. }
  133. file, err := s.createTemp()
  134. if err != nil {
  135. return fmt.Errorf("create first-output spool: %w", err)
  136. }
  137. path := file.Name()
  138. // Unlink before writing any request data. Unix keeps the file descriptor
  139. // readable, while crashes and SIGKILL cannot leave a named plaintext spool.
  140. if unlinkErr := s.removeFile(path); unlinkErr != nil {
  141. closeErr := file.Close()
  142. removeErr := s.removeFile(path)
  143. if errors.Is(removeErr, os.ErrNotExist) {
  144. removeErr = nil
  145. }
  146. s.memoryOnly = true
  147. if removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
  148. s.tempPath = path
  149. }
  150. s.cleanupErr = errors.Join(
  151. s.cleanupErr,
  152. fmt.Errorf("unlink first-output spool before use: %w", unlinkErr),
  153. closeErr,
  154. removeErr,
  155. )
  156. return nil
  157. }
  158. if _, err := file.Write(s.memory.Bytes()); err != nil {
  159. _ = file.Close()
  160. return fmt.Errorf("initialize first-output spool: %w", err)
  161. }
  162. s.tempFile = file
  163. s.tempPath = path
  164. s.memory.Reset()
  165. return nil
  166. }
  167. func (s *openAIFirstOutputStage) CommitTo(dst io.Writer) error {
  168. if s == nil || s.closed {
  169. return os.ErrClosed
  170. }
  171. if s.tempFile == nil {
  172. if _, err := io.Copy(dst, bytes.NewReader(s.memory.Bytes())); err != nil {
  173. return err
  174. }
  175. } else {
  176. if _, err := s.tempFile.Seek(0, io.SeekStart); err != nil {
  177. return fmt.Errorf("seek first-output spool: %w", err)
  178. }
  179. if _, err := io.CopyN(dst, s.tempFile, s.size); err != nil {
  180. return err
  181. }
  182. }
  183. if err := s.Close(); err != nil {
  184. // Delivery succeeded. Preserve cleanup failures for the handler's deferred
  185. // cleanup/logging pass instead of turning committed bytes into a stream error.
  186. s.cleanupErr = errors.Join(s.cleanupErr, err)
  187. }
  188. return nil
  189. }
  190. func (s *openAIFirstOutputStage) Close() error {
  191. if s == nil {
  192. return nil
  193. }
  194. if s.closed && s.tempFile == nil && s.tempPath == "" && s.cleanupErr == nil {
  195. return nil
  196. }
  197. s.closed = true
  198. s.size = 0
  199. s.memory.Reset()
  200. closeErr := s.cleanupErr
  201. s.cleanupErr = nil
  202. if s.tempFile != nil {
  203. closeErr = errors.Join(closeErr, s.tempFile.Close())
  204. s.tempFile = nil
  205. }
  206. if s.tempPath != "" {
  207. removeErr := s.removeFile(s.tempPath)
  208. if removeErr == nil || errors.Is(removeErr, os.ErrNotExist) {
  209. s.tempPath = ""
  210. } else {
  211. closeErr = errors.Join(closeErr, removeErr)
  212. }
  213. }
  214. return closeErr
  215. }
  216. func (s *OpenAIGatewayService) openAIFirstOutputTimeout(reasoningEffort string) time.Duration {
  217. if s == nil || s.cfg == nil || s.cfg.Gateway.OpenAIFirstOutputTimeoutSeconds <= 0 {
  218. return 0
  219. }
  220. seconds := s.cfg.Gateway.OpenAIFirstOutputTimeoutSeconds
  221. switch strings.ToLower(strings.TrimSpace(reasoningEffort)) {
  222. case "high", "xhigh", "max":
  223. if override := s.cfg.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds; override > 0 {
  224. seconds = override
  225. }
  226. }
  227. return time.Duration(seconds) * time.Second
  228. }
  229. // newOpenAIFirstOutputTimeoutError records the timeout as an upstream attempt
  230. // and returns the failover error. proxyID/proxyName are supplied by the caller
  231. // because the same deadline is enforced over HTTP and WebSocket transports,
  232. // whose direct-route semantics differ (see opsUpstreamWSProxyAttribution).
  233. func (s *OpenAIGatewayService) newOpenAIFirstOutputTimeoutError(
  234. ctx context.Context,
  235. c *gin.Context,
  236. account *Account,
  237. proxyID *int64,
  238. proxyName string,
  239. startTime time.Time,
  240. originalModel string,
  241. reasoningEffort string,
  242. timeout time.Duration,
  243. phase string,
  244. responseHeaders http.Header,
  245. ) *UpstreamFailoverError {
  246. elapsed := time.Since(startTime)
  247. logger.LegacyPrintf(
  248. "service.openai_gateway",
  249. "OpenAI first output timeout: account=%d model=%s effort=%s phase=%s elapsed=%s limit=%s",
  250. account.ID, originalModel, reasoningEffort, phase, elapsed, timeout,
  251. )
  252. requestID := strings.TrimSpace(responseHeaders.Get("x-request-id"))
  253. appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
  254. ProxyID: proxyID,
  255. ProxyName: proxyName,
  256. Platform: account.Platform, AccountID: account.ID, AccountName: account.Name,
  257. UpstreamStatusCode: http.StatusGatewayTimeout, UpstreamRequestID: requestID,
  258. Kind: "first_output_timeout", Message: "OpenAI upstream produced no semantic output before the deadline",
  259. Detail: fmt.Sprintf("phase=%s elapsed_ms=%d timeout_ms=%d", phase, elapsed.Milliseconds(), timeout.Milliseconds()),
  260. })
  261. if s.rateLimitService != nil {
  262. s.rateLimitService.HandleStreamTimeout(ctx, account, originalModel)
  263. }
  264. return &UpstreamFailoverError{
  265. StatusCode: http.StatusGatewayTimeout,
  266. ResponseBody: []byte(`{"error":{"type":"first_output_timeout","message":"Upstream produced no output before the deadline"}}`),
  267. ResponseHeaders: responseHeaders.Clone(), SafeToFailoverAfterWrite: true,
  268. }
  269. }
  270. type openAIFirstOutputHeaderGuard struct {
  271. cancel context.CancelFunc
  272. release context.CancelFunc
  273. timer *time.Timer
  274. fired chan struct{}
  275. once sync.Once
  276. }
  277. func newOpenAIFirstOutputHeaderGuard(
  278. ctx context.Context,
  279. release context.CancelFunc,
  280. deadline time.Time,
  281. ) (context.Context, *openAIFirstOutputHeaderGuard) {
  282. guardedCtx, cancel := context.WithCancel(ctx)
  283. guard := &openAIFirstOutputHeaderGuard{cancel: cancel, release: release, fired: make(chan struct{})}
  284. remaining := time.Until(deadline)
  285. if remaining <= 0 {
  286. remaining = time.Nanosecond
  287. }
  288. guard.timer = time.AfterFunc(remaining, func() {
  289. close(guard.fired)
  290. cancel()
  291. })
  292. return guardedCtx, guard
  293. }
  294. func (g *openAIFirstOutputHeaderGuard) stopHeaderWait() bool {
  295. if g.timer.Stop() {
  296. return false
  297. }
  298. <-g.fired
  299. return true
  300. }
  301. func (g *openAIFirstOutputHeaderGuard) close() {
  302. g.once.Do(func() {
  303. g.timer.Stop()
  304. g.cancel()
  305. g.release()
  306. })
  307. }
  308. type openAIRequestContextReadCloser struct {
  309. io.ReadCloser
  310. cleanup func()
  311. once sync.Once
  312. err error
  313. }
  314. func (r *openAIRequestContextReadCloser) Close() error {
  315. r.once.Do(func() {
  316. r.cleanup()
  317. r.err = r.ReadCloser.Close()
  318. })
  319. return r.err
  320. }