openai_ws_pool.go 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "net/http"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "github.com/Wei-Shaw/sub2api/internal/config"
  15. "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
  16. "golang.org/x/sync/errgroup"
  17. )
  18. const (
  19. openAIWSConnMaxAge = 60 * time.Minute
  20. openAIWSConnHealthCheckIdle = 90 * time.Second
  21. // coder/websocket cannot consume pong frames without a reader. Recycle
  22. // unsupported idle sockets before the upstream keepalive window expires.
  23. openAIWSConnIdleRecycleAfter = 90 * time.Second
  24. openAIWSConnHealthCheckTO = 2 * time.Second
  25. openAIWSConnPrewarmExtraDelay = 2 * time.Second
  26. openAIWSAcquireCleanupInterval = 3 * time.Second
  27. openAIWSBackgroundPingInterval = 30 * time.Second
  28. openAIWSBackgroundSweepTicker = 30 * time.Second
  29. openAIWSPrewarmFailureWindow = 30 * time.Second
  30. openAIWSPrewarmFailureSuppress = 2
  31. )
  32. var (
  33. errOpenAIWSConnClosed = errors.New("openai ws connection closed")
  34. errOpenAIWSConnQueueFull = errors.New("openai ws connection queue full")
  35. errOpenAIWSPreferredConnUnavailable = errors.New("openai ws preferred connection unavailable")
  36. )
  37. type openAIWSDialError struct {
  38. StatusCode int
  39. ResponseHeaders http.Header
  40. ResponseBody []byte
  41. Err error
  42. }
  43. func (e *openAIWSDialError) Error() string {
  44. if e == nil {
  45. return ""
  46. }
  47. if e.StatusCode > 0 {
  48. return fmt.Sprintf("openai ws dial failed: status=%d err=%v", e.StatusCode, e.Err)
  49. }
  50. return fmt.Sprintf("openai ws dial failed: %v", e.Err)
  51. }
  52. func (e *openAIWSDialError) Unwrap() error {
  53. if e == nil {
  54. return nil
  55. }
  56. return e.Err
  57. }
  58. type openAIWSAcquireRequest struct {
  59. Account *Account
  60. WSURL string
  61. Headers http.Header
  62. // HeadersFactory is evaluated inside dialConn. It exists so credentials
  63. // whose authorization is per-dial (Agent Identity) are never cached in
  64. // lastAcquire or delayed prewarm state.
  65. HeadersFactory func(context.Context, http.Header) (http.Header, error)
  66. ProxyURL string
  67. PreferredConnID string
  68. // ForceNewConn: 强制本次获取新连接(避免复用导致连接内续链状态互相污染)。
  69. ForceNewConn bool
  70. // ForcePreferredConn: 强制本次只使用 PreferredConnID,禁止漂移到其它连接。
  71. ForcePreferredConn bool
  72. // Snapshot retained for delayed prewarm; never silently re-resolve a new
  73. // template under an old handshake compatibility key.
  74. tlsProfile *tlsfingerprint.Profile
  75. }
  76. type openAIWSHandshakeCompatibilityKey struct {
  77. betaFeatures string
  78. codexInstallationID string
  79. sessionIDHyphen string
  80. sessionIDUnderscore string
  81. threadID string
  82. clientRequestID string
  83. codexWindowID string
  84. conversationID string
  85. transportKey string
  86. }
  87. type openAIWSConnLease struct {
  88. pool *openAIWSConnPool
  89. accountID int64
  90. conn *openAIWSConn
  91. queueWait time.Duration
  92. connPick time.Duration
  93. reused bool
  94. released atomic.Bool
  95. }
  96. func (l *openAIWSConnLease) activeConn() (*openAIWSConn, error) {
  97. if l == nil || l.conn == nil {
  98. return nil, errOpenAIWSConnClosed
  99. }
  100. if l.released.Load() {
  101. return nil, errOpenAIWSConnClosed
  102. }
  103. return l.conn, nil
  104. }
  105. func (l *openAIWSConnLease) ConnID() string {
  106. if l == nil || l.conn == nil {
  107. return ""
  108. }
  109. return l.conn.id
  110. }
  111. func (l *openAIWSConnLease) QueueWaitDuration() time.Duration {
  112. if l == nil {
  113. return 0
  114. }
  115. return l.queueWait
  116. }
  117. func (l *openAIWSConnLease) ConnPickDuration() time.Duration {
  118. if l == nil {
  119. return 0
  120. }
  121. return l.connPick
  122. }
  123. func (l *openAIWSConnLease) Reused() bool {
  124. if l == nil {
  125. return false
  126. }
  127. return l.reused
  128. }
  129. func (l *openAIWSConnLease) HandshakeHeader(name string) string {
  130. if l == nil || l.conn == nil {
  131. return ""
  132. }
  133. return l.conn.handshakeHeader(name)
  134. }
  135. func (l *openAIWSConnLease) HandshakeHeaders() http.Header {
  136. if l == nil || l.conn == nil {
  137. return nil
  138. }
  139. return cloneHeader(l.conn.handshakeHeaders)
  140. }
  141. func (l *openAIWSConnLease) IsPrewarmed() bool {
  142. if l == nil || l.conn == nil {
  143. return false
  144. }
  145. return l.conn.isPrewarmed()
  146. }
  147. func (l *openAIWSConnLease) MarkPrewarmed() {
  148. if l == nil || l.conn == nil {
  149. return
  150. }
  151. l.conn.markPrewarmed()
  152. }
  153. func (l *openAIWSConnLease) WriteJSON(value any, timeout time.Duration) error {
  154. conn, err := l.activeConn()
  155. if err != nil {
  156. return err
  157. }
  158. return conn.writeJSONWithTimeout(context.Background(), value, timeout)
  159. }
  160. func (l *openAIWSConnLease) WriteJSONWithContextTimeout(ctx context.Context, value any, timeout time.Duration) error {
  161. conn, err := l.activeConn()
  162. if err != nil {
  163. return err
  164. }
  165. return conn.writeJSONWithTimeout(ctx, value, timeout)
  166. }
  167. func (l *openAIWSConnLease) WriteJSONContext(ctx context.Context, value any) error {
  168. conn, err := l.activeConn()
  169. if err != nil {
  170. return err
  171. }
  172. return conn.writeJSON(value, ctx)
  173. }
  174. func (l *openAIWSConnLease) ReadMessage(timeout time.Duration) ([]byte, error) {
  175. conn, err := l.activeConn()
  176. if err != nil {
  177. return nil, err
  178. }
  179. return conn.readMessageWithTimeout(timeout)
  180. }
  181. func (l *openAIWSConnLease) ReadMessageContext(ctx context.Context) ([]byte, error) {
  182. conn, err := l.activeConn()
  183. if err != nil {
  184. return nil, err
  185. }
  186. return conn.readMessage(ctx)
  187. }
  188. func (l *openAIWSConnLease) ReadMessageWithContextTimeout(ctx context.Context, timeout time.Duration) ([]byte, error) {
  189. conn, err := l.activeConn()
  190. if err != nil {
  191. return nil, err
  192. }
  193. return conn.readMessageWithContextTimeout(ctx, timeout)
  194. }
  195. func (l *openAIWSConnLease) PingWithTimeout(timeout time.Duration) error {
  196. conn, err := l.activeConn()
  197. if err != nil {
  198. return err
  199. }
  200. return conn.pingWithTimeout(timeout)
  201. }
  202. func (l *openAIWSConnLease) SupportsIdlePingWithoutReader() bool {
  203. conn, err := l.activeConn()
  204. if err != nil {
  205. return false
  206. }
  207. return conn.supportsIdlePingWithoutReader()
  208. }
  209. func (l *openAIWSConnLease) MarkBroken() {
  210. if l == nil || l.pool == nil || l.conn == nil || l.released.Load() {
  211. return
  212. }
  213. l.pool.evictConn(l.accountID, l.conn.id)
  214. }
  215. func (l *openAIWSConnLease) Release() {
  216. if l == nil || l.conn == nil {
  217. return
  218. }
  219. if !l.released.CompareAndSwap(false, true) {
  220. return
  221. }
  222. l.conn.release()
  223. if l.pool != nil {
  224. l.pool.notifyAccountPoolChanged(l.accountID)
  225. }
  226. }
  227. type openAIWSConn struct {
  228. id string
  229. ws openAIWSClientConn
  230. handshakeHeaders http.Header
  231. handshakeCompatibility openAIWSHandshakeCompatibilityKey
  232. routingAffinity string
  233. leaseCh chan struct{}
  234. closedCh chan struct{}
  235. closeOnce sync.Once
  236. readMu sync.Mutex
  237. writeMu sync.Mutex
  238. waiters atomic.Int32
  239. createdAtNano atomic.Int64
  240. lastUsedNano atomic.Int64
  241. prewarmed atomic.Bool
  242. }
  243. func newOpenAIWSConn(id string, _ int64, ws openAIWSClientConn, handshakeHeaders http.Header) *openAIWSConn {
  244. now := time.Now()
  245. conn := &openAIWSConn{
  246. id: id,
  247. ws: ws,
  248. handshakeHeaders: cloneHeader(handshakeHeaders),
  249. leaseCh: make(chan struct{}, 1),
  250. closedCh: make(chan struct{}),
  251. }
  252. conn.leaseCh <- struct{}{}
  253. conn.createdAtNano.Store(now.UnixNano())
  254. conn.lastUsedNano.Store(now.UnixNano())
  255. return conn
  256. }
  257. func (c *openAIWSConn) tryAcquire() bool {
  258. if c == nil {
  259. return false
  260. }
  261. select {
  262. case <-c.closedCh:
  263. return false
  264. default:
  265. }
  266. select {
  267. case <-c.leaseCh:
  268. select {
  269. case <-c.closedCh:
  270. c.release()
  271. return false
  272. default:
  273. }
  274. return true
  275. default:
  276. return false
  277. }
  278. }
  279. func (c *openAIWSConn) acquire(ctx context.Context) error {
  280. if c == nil {
  281. return errOpenAIWSConnClosed
  282. }
  283. for {
  284. select {
  285. case <-ctx.Done():
  286. return ctx.Err()
  287. case <-c.closedCh:
  288. return errOpenAIWSConnClosed
  289. case <-c.leaseCh:
  290. // A cancellation and a lease delivery can become ready together. Once
  291. // the semaphore token has been consumed, check the context again and
  292. // return it before reporting cancellation so a canceled waiter cannot
  293. // strand a pooled connection.
  294. if err := ctx.Err(); err != nil {
  295. c.release()
  296. return err
  297. }
  298. select {
  299. case <-c.closedCh:
  300. c.release()
  301. return errOpenAIWSConnClosed
  302. default:
  303. }
  304. return nil
  305. }
  306. }
  307. }
  308. func (c *openAIWSConn) release() {
  309. if c == nil {
  310. return
  311. }
  312. select {
  313. case c.leaseCh <- struct{}{}:
  314. default:
  315. }
  316. c.touch()
  317. }
  318. func (c *openAIWSConn) close() {
  319. if c == nil {
  320. return
  321. }
  322. c.closeOnce.Do(func() {
  323. close(c.closedCh)
  324. if c.ws != nil {
  325. _ = c.ws.Close()
  326. }
  327. select {
  328. case c.leaseCh <- struct{}{}:
  329. default:
  330. }
  331. })
  332. }
  333. func (c *openAIWSConn) writeJSONWithTimeout(parent context.Context, value any, timeout time.Duration) error {
  334. if c == nil {
  335. return errOpenAIWSConnClosed
  336. }
  337. select {
  338. case <-c.closedCh:
  339. return errOpenAIWSConnClosed
  340. default:
  341. }
  342. writeCtx := parent
  343. if writeCtx == nil {
  344. writeCtx = context.Background()
  345. }
  346. if timeout <= 0 {
  347. return c.writeJSON(value, writeCtx)
  348. }
  349. var cancel context.CancelFunc
  350. writeCtx, cancel = context.WithTimeout(writeCtx, timeout)
  351. defer cancel()
  352. return c.writeJSON(value, writeCtx)
  353. }
  354. func (c *openAIWSConn) writeJSON(value any, writeCtx context.Context) error {
  355. c.writeMu.Lock()
  356. defer c.writeMu.Unlock()
  357. if c.ws == nil {
  358. return errOpenAIWSConnClosed
  359. }
  360. if writeCtx == nil {
  361. writeCtx = context.Background()
  362. }
  363. if err := c.ws.WriteJSON(writeCtx, value); err != nil {
  364. return err
  365. }
  366. c.touch()
  367. return nil
  368. }
  369. func (c *openAIWSConn) readMessageWithTimeout(timeout time.Duration) ([]byte, error) {
  370. return c.readMessageWithContextTimeout(context.Background(), timeout)
  371. }
  372. func (c *openAIWSConn) readMessageWithContextTimeout(parent context.Context, timeout time.Duration) ([]byte, error) {
  373. if c == nil {
  374. return nil, errOpenAIWSConnClosed
  375. }
  376. select {
  377. case <-c.closedCh:
  378. return nil, errOpenAIWSConnClosed
  379. default:
  380. }
  381. if parent == nil {
  382. parent = context.Background()
  383. }
  384. if timeout <= 0 {
  385. return c.readMessage(parent)
  386. }
  387. readCtx, cancel := context.WithTimeout(parent, timeout)
  388. defer cancel()
  389. return c.readMessage(readCtx)
  390. }
  391. func (c *openAIWSConn) readMessage(readCtx context.Context) ([]byte, error) {
  392. c.readMu.Lock()
  393. defer c.readMu.Unlock()
  394. if c.ws == nil {
  395. return nil, errOpenAIWSConnClosed
  396. }
  397. if readCtx == nil {
  398. readCtx = context.Background()
  399. }
  400. payload, err := c.ws.ReadMessage(readCtx)
  401. if err != nil {
  402. return nil, err
  403. }
  404. c.touch()
  405. return payload, nil
  406. }
  407. func (c *openAIWSConn) pingWithTimeout(timeout time.Duration) error {
  408. if c == nil {
  409. return errOpenAIWSConnClosed
  410. }
  411. select {
  412. case <-c.closedCh:
  413. return errOpenAIWSConnClosed
  414. default:
  415. }
  416. c.writeMu.Lock()
  417. defer c.writeMu.Unlock()
  418. if c.ws == nil {
  419. return errOpenAIWSConnClosed
  420. }
  421. if timeout <= 0 {
  422. timeout = openAIWSConnHealthCheckTO
  423. }
  424. pingCtx, cancel := context.WithTimeout(context.Background(), timeout)
  425. defer cancel()
  426. if err := c.ws.Ping(pingCtx); err != nil {
  427. return err
  428. }
  429. return nil
  430. }
  431. func (c *openAIWSConn) supportsIdlePingWithoutReader() bool {
  432. if c == nil || c.ws == nil {
  433. return false
  434. }
  435. capable, ok := c.ws.(openAIWSIdlePingCapable)
  436. // Test and alternate implementations keep the historical probe behavior
  437. // unless they explicitly declare it unsafe.
  438. return !ok || capable.SupportsIdlePingWithoutReader()
  439. }
  440. func (c *openAIWSConn) touch() {
  441. if c == nil {
  442. return
  443. }
  444. c.lastUsedNano.Store(time.Now().UnixNano())
  445. }
  446. func (c *openAIWSConn) createdAt() time.Time {
  447. if c == nil {
  448. return time.Time{}
  449. }
  450. nano := c.createdAtNano.Load()
  451. if nano <= 0 {
  452. return time.Time{}
  453. }
  454. return time.Unix(0, nano)
  455. }
  456. func (c *openAIWSConn) lastUsedAt() time.Time {
  457. if c == nil {
  458. return time.Time{}
  459. }
  460. nano := c.lastUsedNano.Load()
  461. if nano <= 0 {
  462. return time.Time{}
  463. }
  464. return time.Unix(0, nano)
  465. }
  466. func (c *openAIWSConn) idleDuration(now time.Time) time.Duration {
  467. if c == nil {
  468. return 0
  469. }
  470. last := c.lastUsedAt()
  471. if last.IsZero() {
  472. return 0
  473. }
  474. return now.Sub(last)
  475. }
  476. func (c *openAIWSConn) age(now time.Time) time.Duration {
  477. if c == nil {
  478. return 0
  479. }
  480. created := c.createdAt()
  481. if created.IsZero() {
  482. return 0
  483. }
  484. return now.Sub(created)
  485. }
  486. func (c *openAIWSConn) isLeased() bool {
  487. if c == nil {
  488. return false
  489. }
  490. return len(c.leaseCh) == 0
  491. }
  492. func (c *openAIWSConn) handshakeHeader(name string) string {
  493. if c == nil || c.handshakeHeaders == nil {
  494. return ""
  495. }
  496. return strings.TrimSpace(c.handshakeHeaders.Get(strings.TrimSpace(name)))
  497. }
  498. func (c *openAIWSConn) matchesHandshakeCompatibility(compatibility openAIWSHandshakeCompatibilityKey) bool {
  499. return c != nil && c.handshakeCompatibility == compatibility
  500. }
  501. func (c *openAIWSConn) matchesRoutingAffinity(routingAffinity string) bool {
  502. return c != nil && c.routingAffinity == routingAffinity
  503. }
  504. func (c *openAIWSConn) isPrewarmed() bool {
  505. if c == nil {
  506. return false
  507. }
  508. return c.prewarmed.Load()
  509. }
  510. func (c *openAIWSConn) markPrewarmed() {
  511. if c == nil {
  512. return
  513. }
  514. c.prewarmed.Store(true)
  515. }
  516. type openAIWSAccountPool struct {
  517. mu sync.Mutex
  518. conns map[string]*openAIWSConn
  519. pinnedConns map[string]int
  520. changedCh chan struct{}
  521. creating int
  522. generation uint64
  523. lastCleanupAt time.Time
  524. lastAcquire *openAIWSAcquireRequest
  525. prewarmActive bool
  526. prewarmUntil time.Time
  527. prewarmFails int
  528. prewarmFailAt time.Time
  529. }
  530. func (ap *openAIWSAccountPool) changeChannelLocked() chan struct{} {
  531. if ap.changedCh == nil {
  532. ap.changedCh = make(chan struct{})
  533. }
  534. return ap.changedCh
  535. }
  536. func (ap *openAIWSAccountPool) signalChangedLocked() {
  537. if ap == nil {
  538. return
  539. }
  540. if ap.changedCh != nil {
  541. close(ap.changedCh)
  542. }
  543. ap.changedCh = make(chan struct{})
  544. }
  545. type OpenAIWSPoolMetricsSnapshot struct {
  546. AcquireTotal int64
  547. AcquireReuseTotal int64
  548. AcquireCreateTotal int64
  549. AcquireQueueWaitTotal int64
  550. AcquireQueueWaitMsTotal int64
  551. ConnPickTotal int64
  552. ConnPickMsTotal int64
  553. ScaleUpTotal int64
  554. ScaleDownTotal int64
  555. }
  556. type openAIWSPoolMetrics struct {
  557. acquireTotal atomic.Int64
  558. acquireReuseTotal atomic.Int64
  559. acquireCreateTotal atomic.Int64
  560. acquireQueueWaitTotal atomic.Int64
  561. acquireQueueWaitMs atomic.Int64
  562. connPickTotal atomic.Int64
  563. connPickMs atomic.Int64
  564. scaleUpTotal atomic.Int64
  565. scaleDownTotal atomic.Int64
  566. }
  567. type openAIWSConnPool struct {
  568. cfg *config.Config
  569. // 通过接口解耦底层 WS 客户端实现,默认使用 coder/websocket。
  570. clientDialer openAIWSClientDialer
  571. accounts sync.Map // key: int64(accountID), value: *openAIWSAccountPool
  572. seq atomic.Uint64
  573. metrics openAIWSPoolMetrics
  574. workerStopCh chan struct{}
  575. workerWg sync.WaitGroup
  576. closeOnce sync.Once
  577. }
  578. func newOpenAIWSConnPool(cfg *config.Config) *openAIWSConnPool {
  579. pool := &openAIWSConnPool{
  580. cfg: cfg,
  581. clientDialer: newDefaultOpenAIWSClientDialer(),
  582. workerStopCh: make(chan struct{}),
  583. }
  584. pool.startBackgroundWorkers()
  585. return pool
  586. }
  587. func (p *openAIWSConnPool) SnapshotMetrics() OpenAIWSPoolMetricsSnapshot {
  588. if p == nil {
  589. return OpenAIWSPoolMetricsSnapshot{}
  590. }
  591. return OpenAIWSPoolMetricsSnapshot{
  592. AcquireTotal: p.metrics.acquireTotal.Load(),
  593. AcquireReuseTotal: p.metrics.acquireReuseTotal.Load(),
  594. AcquireCreateTotal: p.metrics.acquireCreateTotal.Load(),
  595. AcquireQueueWaitTotal: p.metrics.acquireQueueWaitTotal.Load(),
  596. AcquireQueueWaitMsTotal: p.metrics.acquireQueueWaitMs.Load(),
  597. ConnPickTotal: p.metrics.connPickTotal.Load(),
  598. ConnPickMsTotal: p.metrics.connPickMs.Load(),
  599. ScaleUpTotal: p.metrics.scaleUpTotal.Load(),
  600. ScaleDownTotal: p.metrics.scaleDownTotal.Load(),
  601. }
  602. }
  603. func (p *openAIWSConnPool) SnapshotTransportMetrics() OpenAIWSTransportMetricsSnapshot {
  604. if p == nil {
  605. return OpenAIWSTransportMetricsSnapshot{}
  606. }
  607. if dialer, ok := p.clientDialer.(openAIWSTransportMetricsDialer); ok {
  608. return dialer.SnapshotTransportMetrics()
  609. }
  610. return OpenAIWSTransportMetricsSnapshot{}
  611. }
  612. func (p *openAIWSConnPool) setClientDialerForTest(dialer openAIWSClientDialer) {
  613. if p == nil || dialer == nil {
  614. return
  615. }
  616. p.clientDialer = dialer
  617. }
  618. // Close 停止后台 worker 并关闭所有空闲连接,应在优雅关闭时调用。
  619. func (p *openAIWSConnPool) Close() {
  620. if p == nil {
  621. return
  622. }
  623. p.closeOnce.Do(func() {
  624. if p.workerStopCh != nil {
  625. close(p.workerStopCh)
  626. }
  627. p.workerWg.Wait()
  628. // 遍历所有账户池,关闭全部空闲连接。
  629. p.accounts.Range(func(key, value any) bool {
  630. ap, ok := value.(*openAIWSAccountPool)
  631. if !ok || ap == nil {
  632. return true
  633. }
  634. ap.mu.Lock()
  635. for _, conn := range ap.conns {
  636. if conn != nil && !conn.isLeased() {
  637. conn.close()
  638. }
  639. }
  640. ap.mu.Unlock()
  641. return true
  642. })
  643. })
  644. }
  645. func (p *openAIWSConnPool) startBackgroundWorkers() {
  646. if p == nil || p.workerStopCh == nil {
  647. return
  648. }
  649. p.workerWg.Add(2)
  650. go func() {
  651. defer p.workerWg.Done()
  652. p.runBackgroundPingWorker()
  653. }()
  654. go func() {
  655. defer p.workerWg.Done()
  656. p.runBackgroundCleanupWorker()
  657. }()
  658. }
  659. type openAIWSIdlePingCandidate struct {
  660. accountID int64
  661. conn *openAIWSConn
  662. }
  663. func (p *openAIWSConnPool) runBackgroundPingWorker() {
  664. if p == nil {
  665. return
  666. }
  667. ticker := time.NewTicker(openAIWSBackgroundPingInterval)
  668. defer ticker.Stop()
  669. for {
  670. select {
  671. case <-ticker.C:
  672. p.runBackgroundPingSweep()
  673. case <-p.workerStopCh:
  674. return
  675. }
  676. }
  677. }
  678. func (p *openAIWSConnPool) runBackgroundPingSweep() {
  679. if p == nil {
  680. return
  681. }
  682. candidates := p.snapshotIdleConnsForPing()
  683. var g errgroup.Group
  684. g.SetLimit(10)
  685. for _, item := range candidates {
  686. item := item
  687. if item.conn == nil || item.conn.isLeased() || item.conn.waiters.Load() > 0 || !item.conn.supportsIdlePingWithoutReader() {
  688. continue
  689. }
  690. g.Go(func() error {
  691. if err := item.conn.pingWithTimeout(openAIWSConnHealthCheckTO); err != nil {
  692. p.evictConn(item.accountID, item.conn.id)
  693. }
  694. return nil
  695. })
  696. }
  697. _ = g.Wait()
  698. }
  699. func (p *openAIWSConnPool) snapshotIdleConnsForPing() []openAIWSIdlePingCandidate {
  700. if p == nil {
  701. return nil
  702. }
  703. candidates := make([]openAIWSIdlePingCandidate, 0)
  704. p.accounts.Range(func(key, value any) bool {
  705. accountID, ok := key.(int64)
  706. if !ok || accountID <= 0 {
  707. return true
  708. }
  709. ap, ok := value.(*openAIWSAccountPool)
  710. if !ok || ap == nil {
  711. return true
  712. }
  713. ap.mu.Lock()
  714. for _, conn := range ap.conns {
  715. if conn == nil || conn.isLeased() || conn.waiters.Load() > 0 {
  716. continue
  717. }
  718. candidates = append(candidates, openAIWSIdlePingCandidate{
  719. accountID: accountID,
  720. conn: conn,
  721. })
  722. }
  723. ap.mu.Unlock()
  724. return true
  725. })
  726. return candidates
  727. }
  728. func (p *openAIWSConnPool) runBackgroundCleanupWorker() {
  729. if p == nil {
  730. return
  731. }
  732. ticker := time.NewTicker(openAIWSBackgroundSweepTicker)
  733. defer ticker.Stop()
  734. for {
  735. select {
  736. case <-ticker.C:
  737. p.runBackgroundCleanupSweep(time.Now())
  738. case <-p.workerStopCh:
  739. return
  740. }
  741. }
  742. }
  743. func (p *openAIWSConnPool) runBackgroundCleanupSweep(now time.Time) {
  744. if p == nil {
  745. return
  746. }
  747. type cleanupResult struct {
  748. evicted []*openAIWSConn
  749. }
  750. results := make([]cleanupResult, 0)
  751. p.accounts.Range(func(_ any, value any) bool {
  752. ap, ok := value.(*openAIWSAccountPool)
  753. if !ok || ap == nil {
  754. return true
  755. }
  756. maxConns := p.maxConnsHardCap()
  757. ap.mu.Lock()
  758. if ap.lastAcquire != nil && ap.lastAcquire.Account != nil {
  759. maxConns = p.effectiveMaxConnsByAccount(ap.lastAcquire.Account)
  760. }
  761. evicted := p.cleanupAccountLocked(ap, now, maxConns)
  762. ap.lastCleanupAt = now
  763. ap.mu.Unlock()
  764. if len(evicted) > 0 {
  765. results = append(results, cleanupResult{evicted: evicted})
  766. }
  767. return true
  768. })
  769. for _, result := range results {
  770. closeOpenAIWSConns(result.evicted)
  771. }
  772. }
  773. func (p *openAIWSConnPool) Acquire(ctx context.Context, req openAIWSAcquireRequest) (*openAIWSConnLease, error) {
  774. if p != nil {
  775. p.metrics.acquireTotal.Add(1)
  776. }
  777. profile, err := resolveMode1TLSProfile(req.Account)
  778. if err != nil {
  779. return nil, err
  780. }
  781. if profile != nil && p != nil && p.cfg != nil && !p.cfg.Gateway.TLSFingerprint.Enabled {
  782. profile = nil
  783. }
  784. req.tlsProfile = profile
  785. return p.acquire(ctx, cloneOpenAIWSAcquireRequest(req), 0)
  786. }
  787. func (p *openAIWSConnPool) acquire(ctx context.Context, req openAIWSAcquireRequest, retry int) (*openAIWSConnLease, error) {
  788. if p == nil || req.Account == nil || req.Account.ID <= 0 {
  789. return nil, errors.New("invalid ws acquire request")
  790. }
  791. if stringsTrim(req.WSURL) == "" {
  792. return nil, errors.New("ws url is empty")
  793. }
  794. retryAcquire:
  795. accountID := req.Account.ID
  796. compatibility := openAIWSAcquireCompatibility(req)
  797. routingAffinity := normalizeOpenAIWSRoutingAffinity(req.Headers)
  798. effectiveMaxConns := p.effectiveMaxConnsByAccount(req.Account)
  799. if effectiveMaxConns <= 0 {
  800. return nil, errOpenAIWSConnQueueFull
  801. }
  802. var evicted []*openAIWSConn
  803. ap := p.getOrCreateAccountPool(accountID)
  804. ap.mu.Lock()
  805. acquireGeneration := ap.generation
  806. now := time.Now()
  807. if ap.lastCleanupAt.IsZero() || now.Sub(ap.lastCleanupAt) >= openAIWSAcquireCleanupInterval {
  808. evicted = p.cleanupAccountLocked(ap, now, effectiveMaxConns)
  809. ap.lastCleanupAt = now
  810. }
  811. pickStartedAt := time.Now()
  812. allowReuse := !req.ForceNewConn
  813. preferredConnID := stringsTrim(req.PreferredConnID)
  814. forcePreferredConn := allowReuse && req.ForcePreferredConn
  815. if allowReuse {
  816. if forcePreferredConn {
  817. if preferredConnID == "" {
  818. p.recordConnPickDuration(time.Since(pickStartedAt))
  819. ap.mu.Unlock()
  820. closeOpenAIWSConns(evicted)
  821. return nil, errOpenAIWSPreferredConnUnavailable
  822. }
  823. preferredConn, ok := ap.conns[preferredConnID]
  824. if !ok || !preferredConn.matchesHandshakeCompatibility(compatibility) {
  825. p.recordConnPickDuration(time.Since(pickStartedAt))
  826. ap.mu.Unlock()
  827. closeOpenAIWSConns(evicted)
  828. return nil, errOpenAIWSPreferredConnUnavailable
  829. }
  830. if preferredConn.tryAcquire() {
  831. connPick := time.Since(pickStartedAt)
  832. p.recordConnPickDuration(connPick)
  833. ap.mu.Unlock()
  834. closeOpenAIWSConns(evicted)
  835. if p.shouldHealthCheckConn(preferredConn) {
  836. if err := preferredConn.pingWithTimeout(openAIWSConnHealthCheckTO); err != nil {
  837. preferredConn.close()
  838. p.evictConn(accountID, preferredConn.id)
  839. if retry < 1 {
  840. return p.acquire(ctx, req, retry+1)
  841. }
  842. return nil, err
  843. }
  844. }
  845. lease := &openAIWSConnLease{
  846. pool: p,
  847. accountID: accountID,
  848. conn: preferredConn,
  849. connPick: connPick,
  850. reused: true,
  851. }
  852. p.metrics.acquireReuseTotal.Add(1)
  853. p.recordLastSuccessfulAcquire(accountID, acquireGeneration, req)
  854. p.ensureTargetIdleAsync(accountID)
  855. return lease, nil
  856. }
  857. connPick := time.Since(pickStartedAt)
  858. p.recordConnPickDuration(connPick)
  859. if int(preferredConn.waiters.Load()) >= p.queueLimitPerConn() {
  860. ap.mu.Unlock()
  861. closeOpenAIWSConns(evicted)
  862. return nil, errOpenAIWSConnQueueFull
  863. }
  864. preferredConn.waiters.Add(1)
  865. ap.mu.Unlock()
  866. closeOpenAIWSConns(evicted)
  867. defer preferredConn.waiters.Add(-1)
  868. waitStart := time.Now()
  869. p.metrics.acquireQueueWaitTotal.Add(1)
  870. if err := preferredConn.acquire(ctx); err != nil {
  871. if errors.Is(err, errOpenAIWSConnClosed) && retry < 1 {
  872. return p.acquire(ctx, req, retry+1)
  873. }
  874. return nil, err
  875. }
  876. if p.shouldHealthCheckConn(preferredConn) {
  877. if err := preferredConn.pingWithTimeout(openAIWSConnHealthCheckTO); err != nil {
  878. preferredConn.release()
  879. preferredConn.close()
  880. p.evictConn(accountID, preferredConn.id)
  881. if retry < 1 {
  882. return p.acquire(ctx, req, retry+1)
  883. }
  884. return nil, err
  885. }
  886. }
  887. queueWait := time.Since(waitStart)
  888. p.metrics.acquireQueueWaitMs.Add(queueWait.Milliseconds())
  889. lease := &openAIWSConnLease{
  890. pool: p,
  891. accountID: accountID,
  892. conn: preferredConn,
  893. queueWait: queueWait,
  894. connPick: connPick,
  895. reused: true,
  896. }
  897. p.metrics.acquireReuseTotal.Add(1)
  898. p.recordLastSuccessfulAcquire(accountID, acquireGeneration, req)
  899. p.ensureTargetIdleAsync(accountID)
  900. return lease, nil
  901. }
  902. if preferredConnID != "" {
  903. if conn, ok := ap.conns[preferredConnID]; ok && conn.matchesHandshakeCompatibility(compatibility) && conn.tryAcquire() {
  904. connPick := time.Since(pickStartedAt)
  905. p.recordConnPickDuration(connPick)
  906. ap.mu.Unlock()
  907. closeOpenAIWSConns(evicted)
  908. if p.shouldHealthCheckConn(conn) {
  909. if err := conn.pingWithTimeout(openAIWSConnHealthCheckTO); err != nil {
  910. conn.close()
  911. p.evictConn(accountID, conn.id)
  912. if retry < 1 {
  913. return p.acquire(ctx, req, retry+1)
  914. }
  915. return nil, err
  916. }
  917. }
  918. lease := &openAIWSConnLease{pool: p, accountID: accountID, conn: conn, connPick: connPick, reused: true}
  919. p.metrics.acquireReuseTotal.Add(1)
  920. p.recordLastSuccessfulAcquire(accountID, acquireGeneration, req)
  921. p.ensureTargetIdleAsync(accountID)
  922. return lease, nil
  923. }
  924. }
  925. // A routing hint is advisory at WebSocket dial time. Prefer a pooled
  926. // connection whose handshake used the same hint, but do not make that
  927. // preference a continuation compatibility requirement.
  928. best := p.pickLeastBusyConnWithRoutingAffinityLocked(ap, compatibility, routingAffinity)
  929. if best != nil && best.tryAcquire() {
  930. connPick := time.Since(pickStartedAt)
  931. p.recordConnPickDuration(connPick)
  932. ap.mu.Unlock()
  933. closeOpenAIWSConns(evicted)
  934. if p.shouldHealthCheckConn(best) {
  935. if err := best.pingWithTimeout(openAIWSConnHealthCheckTO); err != nil {
  936. best.close()
  937. p.evictConn(accountID, best.id)
  938. if retry < 1 {
  939. return p.acquire(ctx, req, retry+1)
  940. }
  941. return nil, err
  942. }
  943. }
  944. lease := &openAIWSConnLease{pool: p, accountID: accountID, conn: best, connPick: connPick, reused: true}
  945. p.metrics.acquireReuseTotal.Add(1)
  946. p.recordLastSuccessfulAcquire(accountID, acquireGeneration, req)
  947. p.ensureTargetIdleAsync(accountID)
  948. return lease, nil
  949. }
  950. if routingAffinity == "" || len(ap.conns)+ap.creating >= effectiveMaxConns {
  951. for _, conn := range ap.conns {
  952. if conn == nil || conn == best || !conn.matchesHandshakeCompatibility(compatibility) {
  953. continue
  954. }
  955. if conn.tryAcquire() {
  956. connPick := time.Since(pickStartedAt)
  957. p.recordConnPickDuration(connPick)
  958. ap.mu.Unlock()
  959. closeOpenAIWSConns(evicted)
  960. if p.shouldHealthCheckConn(conn) {
  961. if err := conn.pingWithTimeout(openAIWSConnHealthCheckTO); err != nil {
  962. conn.close()
  963. p.evictConn(accountID, conn.id)
  964. if retry < 1 {
  965. return p.acquire(ctx, req, retry+1)
  966. }
  967. return nil, err
  968. }
  969. }
  970. lease := &openAIWSConnLease{pool: p, accountID: accountID, conn: conn, connPick: connPick, reused: true}
  971. p.metrics.acquireReuseTotal.Add(1)
  972. p.recordLastSuccessfulAcquire(accountID, acquireGeneration, req)
  973. p.ensureTargetIdleAsync(accountID)
  974. return lease, nil
  975. }
  976. }
  977. }
  978. }
  979. if !req.ForceNewConn && len(ap.conns)+ap.creating >= effectiveMaxConns {
  980. affine := p.pickLeastBusyConnWithRoutingAffinityLocked(ap, compatibility, routingAffinity)
  981. if idle := p.pickOldestIdleConnWithoutHandshakeCompatibilityLocked(ap, compatibility); idle != nil {
  982. delete(ap.conns, idle.id)
  983. evicted = append(evicted, idle)
  984. p.metrics.scaleDownTotal.Add(1)
  985. } else if affine == nil {
  986. compatible := p.pickLeastBusyConnLocked(ap, "", compatibility)
  987. if compatible != nil {
  988. // Capacity is full and every compatible connection is busy. The
  989. // hint remains soft here: queue on a compatible connection below.
  990. goto acquireAtCapacity
  991. }
  992. hasConnection := false
  993. for _, conn := range ap.conns {
  994. if conn != nil {
  995. hasConnection = true
  996. break
  997. }
  998. }
  999. if !hasConnection && ap.creating == 0 {
  1000. ap.mu.Unlock()
  1001. closeOpenAIWSConns(evicted)
  1002. return nil, errOpenAIWSConnClosed
  1003. }
  1004. changedCh := ap.changeChannelLocked()
  1005. ap.mu.Unlock()
  1006. closeOpenAIWSConns(evicted)
  1007. select {
  1008. case <-ctx.Done():
  1009. return nil, ctx.Err()
  1010. case <-changedCh:
  1011. goto retryAcquire
  1012. }
  1013. }
  1014. }
  1015. if req.ForceNewConn && len(ap.conns)+ap.creating >= effectiveMaxConns {
  1016. if idle := p.pickOldestIdleConnLocked(ap); idle != nil {
  1017. delete(ap.conns, idle.id)
  1018. evicted = append(evicted, idle)
  1019. p.metrics.scaleDownTotal.Add(1)
  1020. }
  1021. }
  1022. if len(ap.conns)+ap.creating < effectiveMaxConns {
  1023. connPick := time.Since(pickStartedAt)
  1024. p.recordConnPickDuration(connPick)
  1025. ap.creating++
  1026. ap.mu.Unlock()
  1027. closeOpenAIWSConns(evicted)
  1028. conn, dialErr := p.dialConn(ctx, req)
  1029. ap = p.getOrCreateAccountPool(accountID)
  1030. ap.mu.Lock()
  1031. ap.creating--
  1032. if ap.generation != acquireGeneration {
  1033. ap.signalChangedLocked()
  1034. ap.mu.Unlock()
  1035. if conn != nil {
  1036. conn.close()
  1037. }
  1038. if retry < 1 {
  1039. return p.acquire(ctx, req, retry+1)
  1040. }
  1041. return nil, errOpenAIWSConnClosed
  1042. }
  1043. if dialErr != nil {
  1044. ap.prewarmFails++
  1045. ap.prewarmFailAt = time.Now()
  1046. ap.signalChangedLocked()
  1047. ap.mu.Unlock()
  1048. return nil, dialErr
  1049. }
  1050. // Claim the freshly dialed connection before publishing it. Otherwise a
  1051. // topology waiter awakened below can take the free semaphore first and
  1052. // make the caller that paid for the dial queue behind it.
  1053. if !conn.tryAcquire() {
  1054. ap.signalChangedLocked()
  1055. ap.mu.Unlock()
  1056. conn.close()
  1057. return nil, errOpenAIWSConnClosed
  1058. }
  1059. ap.conns[conn.id] = conn
  1060. ap.prewarmFails = 0
  1061. ap.prewarmFailAt = time.Time{}
  1062. // Wake acquires that observed creating>0 with no compatible connection.
  1063. // Without this signal they can remain asleep until the new lease is
  1064. // released, even though the pool topology already changed.
  1065. ap.signalChangedLocked()
  1066. ap.mu.Unlock()
  1067. p.metrics.acquireCreateTotal.Add(1)
  1068. lease := &openAIWSConnLease{pool: p, accountID: accountID, conn: conn, connPick: connPick}
  1069. p.recordLastSuccessfulAcquire(accountID, acquireGeneration, req)
  1070. p.ensureTargetIdleAsync(accountID)
  1071. return lease, nil
  1072. }
  1073. if req.ForceNewConn {
  1074. p.recordConnPickDuration(time.Since(pickStartedAt))
  1075. ap.mu.Unlock()
  1076. closeOpenAIWSConns(evicted)
  1077. return nil, errOpenAIWSConnQueueFull
  1078. }
  1079. acquireAtCapacity:
  1080. target := p.pickLeastBusyConnLocked(ap, req.PreferredConnID, compatibility)
  1081. connPick := time.Since(pickStartedAt)
  1082. p.recordConnPickDuration(connPick)
  1083. if target == nil {
  1084. ap.mu.Unlock()
  1085. closeOpenAIWSConns(evicted)
  1086. return nil, errOpenAIWSConnClosed
  1087. }
  1088. if int(target.waiters.Load()) >= p.queueLimitPerConn() {
  1089. ap.mu.Unlock()
  1090. closeOpenAIWSConns(evicted)
  1091. return nil, errOpenAIWSConnQueueFull
  1092. }
  1093. target.waiters.Add(1)
  1094. ap.mu.Unlock()
  1095. closeOpenAIWSConns(evicted)
  1096. defer target.waiters.Add(-1)
  1097. waitStart := time.Now()
  1098. p.metrics.acquireQueueWaitTotal.Add(1)
  1099. if err := target.acquire(ctx); err != nil {
  1100. if errors.Is(err, errOpenAIWSConnClosed) && retry < 1 {
  1101. return p.acquire(ctx, req, retry+1)
  1102. }
  1103. return nil, err
  1104. }
  1105. if p.shouldHealthCheckConn(target) {
  1106. if err := target.pingWithTimeout(openAIWSConnHealthCheckTO); err != nil {
  1107. target.release()
  1108. target.close()
  1109. p.evictConn(accountID, target.id)
  1110. if retry < 1 {
  1111. return p.acquire(ctx, req, retry+1)
  1112. }
  1113. return nil, err
  1114. }
  1115. }
  1116. queueWait := time.Since(waitStart)
  1117. p.metrics.acquireQueueWaitMs.Add(queueWait.Milliseconds())
  1118. lease := &openAIWSConnLease{pool: p, accountID: accountID, conn: target, queueWait: queueWait, connPick: connPick, reused: true}
  1119. p.metrics.acquireReuseTotal.Add(1)
  1120. p.recordLastSuccessfulAcquire(accountID, acquireGeneration, req)
  1121. p.ensureTargetIdleAsync(accountID)
  1122. return lease, nil
  1123. }
  1124. func (p *openAIWSConnPool) recordConnPickDuration(duration time.Duration) {
  1125. if p == nil {
  1126. return
  1127. }
  1128. if duration < 0 {
  1129. duration = 0
  1130. }
  1131. p.metrics.connPickTotal.Add(1)
  1132. p.metrics.connPickMs.Add(duration.Milliseconds())
  1133. }
  1134. func (p *openAIWSConnPool) recordLastSuccessfulAcquire(accountID int64, generation uint64, req openAIWSAcquireRequest) {
  1135. if p == nil || accountID <= 0 {
  1136. return
  1137. }
  1138. ap, ok := p.getAccountPool(accountID)
  1139. if !ok || ap == nil {
  1140. return
  1141. }
  1142. ap.mu.Lock()
  1143. if ap.generation != generation {
  1144. ap.mu.Unlock()
  1145. return
  1146. }
  1147. ap.lastAcquire = cloneOpenAIWSAcquireRequestPtr(&req)
  1148. ap.mu.Unlock()
  1149. }
  1150. func (p *openAIWSConnPool) pickOldestIdleConnLocked(ap *openAIWSAccountPool) *openAIWSConn {
  1151. if ap == nil || len(ap.conns) == 0 {
  1152. return nil
  1153. }
  1154. var oldest *openAIWSConn
  1155. for _, conn := range ap.conns {
  1156. if conn == nil || conn.isLeased() || conn.waiters.Load() > 0 || p.isConnPinnedLocked(ap, conn.id) {
  1157. continue
  1158. }
  1159. if oldest == nil || conn.lastUsedAt().Before(oldest.lastUsedAt()) {
  1160. oldest = conn
  1161. }
  1162. }
  1163. return oldest
  1164. }
  1165. func (p *openAIWSConnPool) pickOldestIdleConnWithoutHandshakeCompatibilityLocked(
  1166. ap *openAIWSAccountPool,
  1167. compatibility openAIWSHandshakeCompatibilityKey,
  1168. ) *openAIWSConn {
  1169. if ap == nil || len(ap.conns) == 0 {
  1170. return nil
  1171. }
  1172. var oldest *openAIWSConn
  1173. for _, conn := range ap.conns {
  1174. if conn == nil ||
  1175. conn.matchesHandshakeCompatibility(compatibility) ||
  1176. conn.isLeased() || conn.waiters.Load() > 0 || p.isConnPinnedLocked(ap, conn.id) {
  1177. continue
  1178. }
  1179. if oldest == nil || conn.lastUsedAt().Before(oldest.lastUsedAt()) {
  1180. oldest = conn
  1181. }
  1182. }
  1183. return oldest
  1184. }
  1185. func (p *openAIWSConnPool) getOrCreateAccountPool(accountID int64) *openAIWSAccountPool {
  1186. if p == nil || accountID <= 0 {
  1187. return nil
  1188. }
  1189. if existing, ok := p.accounts.Load(accountID); ok {
  1190. if ap, typed := existing.(*openAIWSAccountPool); typed && ap != nil {
  1191. return ap
  1192. }
  1193. }
  1194. ap := &openAIWSAccountPool{
  1195. conns: make(map[string]*openAIWSConn),
  1196. pinnedConns: make(map[string]int),
  1197. changedCh: make(chan struct{}),
  1198. }
  1199. actual, _ := p.accounts.LoadOrStore(accountID, ap)
  1200. if typed, ok := actual.(*openAIWSAccountPool); ok && typed != nil {
  1201. return typed
  1202. }
  1203. return ap
  1204. }
  1205. // ensureAccountPoolLocked 兼容旧调用。
  1206. func (p *openAIWSConnPool) ensureAccountPoolLocked(accountID int64) *openAIWSAccountPool {
  1207. return p.getOrCreateAccountPool(accountID)
  1208. }
  1209. func (p *openAIWSConnPool) getAccountPool(accountID int64) (*openAIWSAccountPool, bool) {
  1210. if p == nil || accountID <= 0 {
  1211. return nil, false
  1212. }
  1213. value, ok := p.accounts.Load(accountID)
  1214. if !ok || value == nil {
  1215. return nil, false
  1216. }
  1217. ap, typed := value.(*openAIWSAccountPool)
  1218. return ap, typed && ap != nil
  1219. }
  1220. func (p *openAIWSConnPool) notifyAccountPoolChanged(accountID int64) {
  1221. ap, ok := p.getAccountPool(accountID)
  1222. if !ok || ap == nil {
  1223. return
  1224. }
  1225. ap.mu.Lock()
  1226. ap.signalChangedLocked()
  1227. ap.mu.Unlock()
  1228. }
  1229. func (p *openAIWSConnPool) isConnPinnedLocked(ap *openAIWSAccountPool, connID string) bool {
  1230. if ap == nil || connID == "" || len(ap.pinnedConns) == 0 {
  1231. return false
  1232. }
  1233. return ap.pinnedConns[connID] > 0
  1234. }
  1235. func (p *openAIWSConnPool) cleanupAccountLocked(ap *openAIWSAccountPool, now time.Time, maxConns int) []*openAIWSConn {
  1236. if ap == nil {
  1237. return nil
  1238. }
  1239. maxAge := p.maxConnAge()
  1240. evicted := make([]*openAIWSConn, 0)
  1241. for id, conn := range ap.conns {
  1242. if conn == nil {
  1243. delete(ap.conns, id)
  1244. if len(ap.pinnedConns) > 0 {
  1245. delete(ap.pinnedConns, id)
  1246. }
  1247. continue
  1248. }
  1249. select {
  1250. case <-conn.closedCh:
  1251. delete(ap.conns, id)
  1252. if len(ap.pinnedConns) > 0 {
  1253. delete(ap.pinnedConns, id)
  1254. }
  1255. evicted = append(evicted, conn)
  1256. continue
  1257. default:
  1258. }
  1259. if p.isConnPinnedLocked(ap, id) {
  1260. continue
  1261. }
  1262. if !conn.isLeased() && conn.waiters.Load() == 0 &&
  1263. !conn.supportsIdlePingWithoutReader() &&
  1264. conn.idleDuration(now) >= openAIWSConnIdleRecycleAfter {
  1265. delete(ap.conns, id)
  1266. if len(ap.pinnedConns) > 0 {
  1267. delete(ap.pinnedConns, id)
  1268. }
  1269. evicted = append(evicted, conn)
  1270. p.metrics.scaleDownTotal.Add(1)
  1271. continue
  1272. }
  1273. if maxAge > 0 && !conn.isLeased() && conn.age(now) > maxAge {
  1274. delete(ap.conns, id)
  1275. if len(ap.pinnedConns) > 0 {
  1276. delete(ap.pinnedConns, id)
  1277. }
  1278. evicted = append(evicted, conn)
  1279. }
  1280. }
  1281. if maxConns <= 0 {
  1282. maxConns = p.maxConnsHardCap()
  1283. }
  1284. maxIdle := p.maxIdlePerAccount()
  1285. if maxIdle < 0 || maxIdle > maxConns {
  1286. maxIdle = maxConns
  1287. }
  1288. if maxIdle >= 0 && len(ap.conns) > maxIdle {
  1289. idleConns := make([]*openAIWSConn, 0, len(ap.conns))
  1290. for id, conn := range ap.conns {
  1291. if conn == nil {
  1292. delete(ap.conns, id)
  1293. if len(ap.pinnedConns) > 0 {
  1294. delete(ap.pinnedConns, id)
  1295. }
  1296. continue
  1297. }
  1298. // 有等待者的连接不能在清理阶段被淘汰,否则等待中的 acquire 会收到 closed 错误。
  1299. if conn.isLeased() || conn.waiters.Load() > 0 || p.isConnPinnedLocked(ap, conn.id) {
  1300. continue
  1301. }
  1302. idleConns = append(idleConns, conn)
  1303. }
  1304. sort.SliceStable(idleConns, func(i, j int) bool {
  1305. return idleConns[i].lastUsedAt().Before(idleConns[j].lastUsedAt())
  1306. })
  1307. redundant := len(ap.conns) - maxIdle
  1308. if redundant > len(idleConns) {
  1309. redundant = len(idleConns)
  1310. }
  1311. for i := 0; i < redundant; i++ {
  1312. conn := idleConns[i]
  1313. delete(ap.conns, conn.id)
  1314. if len(ap.pinnedConns) > 0 {
  1315. delete(ap.pinnedConns, conn.id)
  1316. }
  1317. evicted = append(evicted, conn)
  1318. }
  1319. if redundant > 0 {
  1320. p.metrics.scaleDownTotal.Add(int64(redundant))
  1321. }
  1322. }
  1323. if len(evicted) > 0 {
  1324. ap.signalChangedLocked()
  1325. }
  1326. return evicted
  1327. }
  1328. func (p *openAIWSConnPool) pickLeastBusyConnLocked(
  1329. ap *openAIWSAccountPool,
  1330. preferredConnID string,
  1331. compatibility openAIWSHandshakeCompatibilityKey,
  1332. ) *openAIWSConn {
  1333. if ap == nil || len(ap.conns) == 0 {
  1334. return nil
  1335. }
  1336. preferredConnID = stringsTrim(preferredConnID)
  1337. if preferredConnID != "" {
  1338. if conn, ok := ap.conns[preferredConnID]; ok && conn.matchesHandshakeCompatibility(compatibility) {
  1339. return conn
  1340. }
  1341. }
  1342. var best *openAIWSConn
  1343. var bestWaiters int32
  1344. var bestLastUsed time.Time
  1345. for _, conn := range ap.conns {
  1346. if conn == nil || !conn.matchesHandshakeCompatibility(compatibility) {
  1347. continue
  1348. }
  1349. waiters := conn.waiters.Load()
  1350. lastUsed := conn.lastUsedAt()
  1351. if best == nil ||
  1352. waiters < bestWaiters ||
  1353. (waiters == bestWaiters && lastUsed.Before(bestLastUsed)) {
  1354. best = conn
  1355. bestWaiters = waiters
  1356. bestLastUsed = lastUsed
  1357. }
  1358. }
  1359. return best
  1360. }
  1361. func (p *openAIWSConnPool) pickLeastBusyConnWithRoutingAffinityLocked(
  1362. ap *openAIWSAccountPool,
  1363. compatibility openAIWSHandshakeCompatibilityKey,
  1364. routingAffinity string,
  1365. ) *openAIWSConn {
  1366. if ap == nil || len(ap.conns) == 0 {
  1367. return nil
  1368. }
  1369. var best *openAIWSConn
  1370. var bestWaiters int32
  1371. var bestLastUsed time.Time
  1372. for _, conn := range ap.conns {
  1373. if conn == nil ||
  1374. !conn.matchesHandshakeCompatibility(compatibility) ||
  1375. !conn.matchesRoutingAffinity(routingAffinity) {
  1376. continue
  1377. }
  1378. waiters := conn.waiters.Load()
  1379. lastUsed := conn.lastUsedAt()
  1380. if best == nil ||
  1381. waiters < bestWaiters ||
  1382. (waiters == bestWaiters && lastUsed.Before(bestLastUsed)) {
  1383. best = conn
  1384. bestWaiters = waiters
  1385. bestLastUsed = lastUsed
  1386. }
  1387. }
  1388. return best
  1389. }
  1390. func accountPoolLoadLocked(ap *openAIWSAccountPool) (inflight int, waiters int) {
  1391. if ap == nil {
  1392. return 0, 0
  1393. }
  1394. for _, conn := range ap.conns {
  1395. if conn == nil {
  1396. continue
  1397. }
  1398. if conn.isLeased() {
  1399. inflight++
  1400. }
  1401. waiters += int(conn.waiters.Load())
  1402. }
  1403. return inflight, waiters
  1404. }
  1405. // AccountPoolLoad 返回指定账号连接池的并发与排队快照。
  1406. func (p *openAIWSConnPool) AccountPoolLoad(accountID int64) (inflight int, waiters int, conns int) {
  1407. if p == nil || accountID <= 0 {
  1408. return 0, 0, 0
  1409. }
  1410. ap, ok := p.getAccountPool(accountID)
  1411. if !ok || ap == nil {
  1412. return 0, 0, 0
  1413. }
  1414. ap.mu.Lock()
  1415. defer ap.mu.Unlock()
  1416. inflight, waiters = accountPoolLoadLocked(ap)
  1417. return inflight, waiters, len(ap.conns)
  1418. }
  1419. func (p *openAIWSConnPool) ensureTargetIdleAsync(accountID int64) {
  1420. if p == nil || accountID <= 0 {
  1421. return
  1422. }
  1423. var req openAIWSAcquireRequest
  1424. generation := uint64(0)
  1425. need := 0
  1426. ap, ok := p.getAccountPool(accountID)
  1427. if !ok || ap == nil {
  1428. return
  1429. }
  1430. ap.mu.Lock()
  1431. defer ap.mu.Unlock()
  1432. if ap.lastAcquire == nil {
  1433. return
  1434. }
  1435. if ap.prewarmActive {
  1436. return
  1437. }
  1438. now := time.Now()
  1439. if !ap.prewarmUntil.IsZero() && now.Before(ap.prewarmUntil) {
  1440. return
  1441. }
  1442. if p.shouldSuppressPrewarmLocked(ap, now) {
  1443. return
  1444. }
  1445. effectiveMaxConns := p.maxConnsHardCap()
  1446. if ap.lastAcquire != nil && ap.lastAcquire.Account != nil {
  1447. effectiveMaxConns = p.effectiveMaxConnsByAccount(ap.lastAcquire.Account)
  1448. }
  1449. target := p.targetConnCountLocked(ap, effectiveMaxConns)
  1450. current := len(ap.conns) + ap.creating
  1451. if current >= target {
  1452. return
  1453. }
  1454. need = target - current
  1455. if need <= 0 {
  1456. return
  1457. }
  1458. req = cloneOpenAIWSAcquireRequest(*ap.lastAcquire)
  1459. generation = ap.generation
  1460. ap.prewarmActive = true
  1461. if cooldown := p.prewarmCooldown(); cooldown > 0 {
  1462. ap.prewarmUntil = now.Add(cooldown)
  1463. }
  1464. ap.creating += need
  1465. p.metrics.scaleUpTotal.Add(int64(need))
  1466. go p.prewarmConns(accountID, req, need, generation)
  1467. }
  1468. func (p *openAIWSConnPool) targetConnCountLocked(ap *openAIWSAccountPool, maxConns int) int {
  1469. if ap == nil {
  1470. return 0
  1471. }
  1472. if maxConns <= 0 {
  1473. return 0
  1474. }
  1475. minIdle := p.minIdlePerAccount()
  1476. if minIdle < 0 {
  1477. minIdle = 0
  1478. }
  1479. if minIdle > maxConns {
  1480. minIdle = maxConns
  1481. }
  1482. inflight, waiters := accountPoolLoadLocked(ap)
  1483. utilization := p.targetUtilization()
  1484. demand := inflight + waiters
  1485. if demand <= 0 {
  1486. return minIdle
  1487. }
  1488. target := 1
  1489. if demand > 1 {
  1490. target = int(math.Ceil(float64(demand) / utilization))
  1491. }
  1492. if waiters > 0 && target < len(ap.conns)+1 {
  1493. target = len(ap.conns) + 1
  1494. }
  1495. if target < minIdle {
  1496. target = minIdle
  1497. }
  1498. if target > maxConns {
  1499. target = maxConns
  1500. }
  1501. return target
  1502. }
  1503. func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequest, total int, generations ...uint64) {
  1504. generation := uint64(0)
  1505. if len(generations) > 0 {
  1506. generation = generations[0]
  1507. }
  1508. staleTarget := false
  1509. defer func() {
  1510. if ap, ok := p.getAccountPool(accountID); ok && ap != nil {
  1511. ap.mu.Lock()
  1512. ap.prewarmActive = false
  1513. ap.signalChangedLocked()
  1514. ap.mu.Unlock()
  1515. }
  1516. if staleTarget {
  1517. // A newer acquire arrived while the old dial was in flight. Re-run
  1518. // target selection only after clearing prewarmActive so the latest
  1519. // beta/hint target can fill the idle budget.
  1520. p.ensureTargetIdleAsync(accountID)
  1521. }
  1522. }()
  1523. for i := 0; i < total; i++ {
  1524. ctx, cancel := context.WithTimeout(context.Background(), p.dialTimeout()+openAIWSConnPrewarmExtraDelay)
  1525. conn, err := p.dialConn(ctx, req)
  1526. cancel()
  1527. ap, ok := p.getAccountPool(accountID)
  1528. if !ok || ap == nil {
  1529. if conn != nil {
  1530. conn.close()
  1531. }
  1532. return
  1533. }
  1534. ap.mu.Lock()
  1535. if ap.creating > 0 {
  1536. ap.creating--
  1537. }
  1538. if err != nil {
  1539. ap.prewarmFails++
  1540. ap.prewarmFailAt = time.Now()
  1541. ap.signalChangedLocked()
  1542. ap.mu.Unlock()
  1543. continue
  1544. }
  1545. if ap.generation != generation || ap.lastAcquire == nil {
  1546. ap.mu.Unlock()
  1547. conn.close()
  1548. continue
  1549. }
  1550. if !sameOpenAIWSPrewarmTarget(req, *ap.lastAcquire) {
  1551. staleTarget = true
  1552. ap.signalChangedLocked()
  1553. ap.mu.Unlock()
  1554. conn.close()
  1555. continue
  1556. }
  1557. if len(ap.conns) >= p.effectiveMaxConnsByAccount(req.Account) {
  1558. ap.signalChangedLocked()
  1559. ap.mu.Unlock()
  1560. conn.close()
  1561. continue
  1562. }
  1563. ap.conns[conn.id] = conn
  1564. ap.prewarmFails = 0
  1565. ap.prewarmFailAt = time.Time{}
  1566. ap.signalChangedLocked()
  1567. ap.mu.Unlock()
  1568. }
  1569. }
  1570. // ClearAccount closes all pooled connections and discards delayed prewarm
  1571. // state for one account. The generation guard prevents an in-flight prewarm
  1572. // started before credential recovery from re-entering the pool afterwards.
  1573. func (p *openAIWSConnPool) ClearAccount(accountID int64) {
  1574. if p == nil || accountID <= 0 {
  1575. return
  1576. }
  1577. ap, ok := p.getAccountPool(accountID)
  1578. if !ok || ap == nil {
  1579. return
  1580. }
  1581. ap.mu.Lock()
  1582. ap.generation++
  1583. conns := make([]*openAIWSConn, 0, len(ap.conns))
  1584. for id, conn := range ap.conns {
  1585. delete(ap.conns, id)
  1586. delete(ap.pinnedConns, id)
  1587. if conn != nil {
  1588. conns = append(conns, conn)
  1589. }
  1590. }
  1591. ap.lastAcquire = nil
  1592. ap.prewarmUntil = time.Time{}
  1593. ap.prewarmFails = 0
  1594. ap.prewarmFailAt = time.Time{}
  1595. ap.signalChangedLocked()
  1596. ap.mu.Unlock()
  1597. closeOpenAIWSConns(conns)
  1598. }
  1599. func (p *openAIWSConnPool) evictConn(accountID int64, connID string) {
  1600. if p == nil || accountID <= 0 || stringsTrim(connID) == "" {
  1601. return
  1602. }
  1603. var conn *openAIWSConn
  1604. ap, ok := p.getAccountPool(accountID)
  1605. if ok && ap != nil {
  1606. ap.mu.Lock()
  1607. if c, exists := ap.conns[connID]; exists {
  1608. conn = c
  1609. delete(ap.conns, connID)
  1610. if len(ap.pinnedConns) > 0 {
  1611. delete(ap.pinnedConns, connID)
  1612. }
  1613. ap.signalChangedLocked()
  1614. }
  1615. ap.mu.Unlock()
  1616. }
  1617. if conn != nil {
  1618. conn.close()
  1619. }
  1620. }
  1621. func (p *openAIWSConnPool) PinConn(accountID int64, connID string) bool {
  1622. if p == nil || accountID <= 0 {
  1623. return false
  1624. }
  1625. connID = stringsTrim(connID)
  1626. if connID == "" {
  1627. return false
  1628. }
  1629. ap, ok := p.getAccountPool(accountID)
  1630. if !ok || ap == nil {
  1631. return false
  1632. }
  1633. ap.mu.Lock()
  1634. defer ap.mu.Unlock()
  1635. if _, exists := ap.conns[connID]; !exists {
  1636. return false
  1637. }
  1638. if ap.pinnedConns == nil {
  1639. ap.pinnedConns = make(map[string]int)
  1640. }
  1641. ap.pinnedConns[connID]++
  1642. return true
  1643. }
  1644. func (p *openAIWSConnPool) UnpinConn(accountID int64, connID string) {
  1645. if p == nil || accountID <= 0 {
  1646. return
  1647. }
  1648. connID = stringsTrim(connID)
  1649. if connID == "" {
  1650. return
  1651. }
  1652. ap, ok := p.getAccountPool(accountID)
  1653. if !ok || ap == nil {
  1654. return
  1655. }
  1656. ap.mu.Lock()
  1657. defer ap.mu.Unlock()
  1658. if len(ap.pinnedConns) == 0 {
  1659. return
  1660. }
  1661. count := ap.pinnedConns[connID]
  1662. if count <= 1 {
  1663. delete(ap.pinnedConns, connID)
  1664. ap.signalChangedLocked()
  1665. return
  1666. }
  1667. ap.pinnedConns[connID] = count - 1
  1668. ap.signalChangedLocked()
  1669. }
  1670. func (p *openAIWSConnPool) dialConn(ctx context.Context, req openAIWSAcquireRequest) (*openAIWSConn, error) {
  1671. if p == nil || p.clientDialer == nil {
  1672. return nil, errors.New("openai ws client dialer is nil")
  1673. }
  1674. headers := cloneHeader(req.Headers)
  1675. var err error
  1676. if req.HeadersFactory != nil {
  1677. headers, err = req.HeadersFactory(ctx, headers)
  1678. if err != nil {
  1679. return nil, err
  1680. }
  1681. }
  1682. dialCtx := withOpenAIWSTLSProfile(ctx, req.Account.ID, req.tlsProfile)
  1683. conn, status, handshakeHeaders, err := p.clientDialer.Dial(dialCtx, req.WSURL, headers, req.ProxyURL)
  1684. if err != nil {
  1685. var handshakeErr *openAIWSHandshakeError
  1686. var responseBody []byte
  1687. if errors.As(err, &handshakeErr) && handshakeErr != nil {
  1688. responseBody = append([]byte(nil), handshakeErr.Body...)
  1689. }
  1690. return nil, &openAIWSDialError{
  1691. StatusCode: status,
  1692. ResponseHeaders: cloneHeader(handshakeHeaders),
  1693. ResponseBody: responseBody,
  1694. Err: err,
  1695. }
  1696. }
  1697. if conn == nil {
  1698. return nil, &openAIWSDialError{
  1699. StatusCode: status,
  1700. ResponseHeaders: cloneHeader(handshakeHeaders),
  1701. Err: errors.New("openai ws dialer returned nil connection"),
  1702. }
  1703. }
  1704. id := p.nextConnID(req.Account.ID)
  1705. pooledConn := newOpenAIWSConn(id, req.Account.ID, conn, handshakeHeaders)
  1706. pooledConn.handshakeCompatibility = openAIWSAcquireCompatibility(req)
  1707. pooledConn.routingAffinity = normalizeOpenAIWSRoutingAffinity(req.Headers)
  1708. return pooledConn, nil
  1709. }
  1710. func (p *openAIWSConnPool) nextConnID(accountID int64) string {
  1711. seq := p.seq.Add(1)
  1712. buf := make([]byte, 0, 32)
  1713. buf = append(buf, "oa_ws_"...)
  1714. buf = strconv.AppendInt(buf, accountID, 10)
  1715. buf = append(buf, '_')
  1716. buf = strconv.AppendUint(buf, seq, 10)
  1717. return string(buf)
  1718. }
  1719. func (p *openAIWSConnPool) shouldHealthCheckConn(conn *openAIWSConn) bool {
  1720. if conn == nil || !conn.supportsIdlePingWithoutReader() {
  1721. return false
  1722. }
  1723. return conn.idleDuration(time.Now()) >= openAIWSConnHealthCheckIdle
  1724. }
  1725. func (p *openAIWSConnPool) maxConnsHardCap() int {
  1726. if p != nil && p.cfg != nil && p.cfg.Gateway.OpenAIWS.MaxConnsPerAccount > 0 {
  1727. return p.cfg.Gateway.OpenAIWS.MaxConnsPerAccount
  1728. }
  1729. return 8
  1730. }
  1731. func (p *openAIWSConnPool) dynamicMaxConnsEnabled() bool {
  1732. if p != nil && p.cfg != nil {
  1733. return p.cfg.Gateway.OpenAIWS.DynamicMaxConnsByAccountConcurrencyEnabled
  1734. }
  1735. return false
  1736. }
  1737. func (p *openAIWSConnPool) modeRouterV2Enabled() bool {
  1738. if p != nil && p.cfg != nil {
  1739. return p.cfg.Gateway.OpenAIWS.ModeRouterV2Enabled
  1740. }
  1741. return false
  1742. }
  1743. func (p *openAIWSConnPool) maxConnsFactorByAccount(account *Account) float64 {
  1744. if p == nil || p.cfg == nil || account == nil {
  1745. return 1.0
  1746. }
  1747. switch account.Type {
  1748. case AccountTypeOAuth:
  1749. if p.cfg.Gateway.OpenAIWS.OAuthMaxConnsFactor > 0 {
  1750. return p.cfg.Gateway.OpenAIWS.OAuthMaxConnsFactor
  1751. }
  1752. case AccountTypeAPIKey:
  1753. if p.cfg.Gateway.OpenAIWS.APIKeyMaxConnsFactor > 0 {
  1754. return p.cfg.Gateway.OpenAIWS.APIKeyMaxConnsFactor
  1755. }
  1756. }
  1757. return 1.0
  1758. }
  1759. func (p *openAIWSConnPool) effectiveMaxConnsByAccount(account *Account) int {
  1760. hardCap := p.maxConnsHardCap()
  1761. if isMode1ProtectionEnabled(account) {
  1762. hardCap = min(hardCap, account.Mode1EffectiveConcurrency())
  1763. }
  1764. if hardCap <= 0 {
  1765. return 0
  1766. }
  1767. if p.modeRouterV2Enabled() {
  1768. if account == nil {
  1769. return hardCap
  1770. }
  1771. if account.Mode1EffectiveConcurrency() <= 0 {
  1772. return 0
  1773. }
  1774. return min(account.Mode1EffectiveConcurrency(), hardCap)
  1775. }
  1776. if account == nil || !p.dynamicMaxConnsEnabled() {
  1777. return hardCap
  1778. }
  1779. if account.Mode1EffectiveConcurrency() <= 0 {
  1780. // 0/-1 等“无限制”并发场景下,仍由全局硬上限兜底。
  1781. return hardCap
  1782. }
  1783. factor := p.maxConnsFactorByAccount(account)
  1784. if factor <= 0 {
  1785. factor = 1.0
  1786. }
  1787. effective := int(math.Ceil(float64(account.Mode1EffectiveConcurrency()) * factor))
  1788. if effective < 1 {
  1789. effective = 1
  1790. }
  1791. if effective > hardCap {
  1792. effective = hardCap
  1793. }
  1794. return effective
  1795. }
  1796. func (p *openAIWSConnPool) minIdlePerAccount() int {
  1797. if p != nil && p.cfg != nil && p.cfg.Gateway.OpenAIWS.MinIdlePerAccount >= 0 {
  1798. return p.cfg.Gateway.OpenAIWS.MinIdlePerAccount
  1799. }
  1800. return 0
  1801. }
  1802. func (p *openAIWSConnPool) maxIdlePerAccount() int {
  1803. if p != nil && p.cfg != nil && p.cfg.Gateway.OpenAIWS.MaxIdlePerAccount >= 0 {
  1804. return p.cfg.Gateway.OpenAIWS.MaxIdlePerAccount
  1805. }
  1806. return 4
  1807. }
  1808. func (p *openAIWSConnPool) maxConnAge() time.Duration {
  1809. return openAIWSConnMaxAge
  1810. }
  1811. func (p *openAIWSConnPool) queueLimitPerConn() int {
  1812. if p != nil && p.cfg != nil && p.cfg.Gateway.OpenAIWS.QueueLimitPerConn > 0 {
  1813. return p.cfg.Gateway.OpenAIWS.QueueLimitPerConn
  1814. }
  1815. return 256
  1816. }
  1817. func (p *openAIWSConnPool) targetUtilization() float64 {
  1818. if p != nil && p.cfg != nil {
  1819. ratio := p.cfg.Gateway.OpenAIWS.PoolTargetUtilization
  1820. if ratio > 0 && ratio <= 1 {
  1821. return ratio
  1822. }
  1823. }
  1824. return 0.7
  1825. }
  1826. func (p *openAIWSConnPool) prewarmCooldown() time.Duration {
  1827. if p != nil && p.cfg != nil && p.cfg.Gateway.OpenAIWS.PrewarmCooldownMS > 0 {
  1828. return time.Duration(p.cfg.Gateway.OpenAIWS.PrewarmCooldownMS) * time.Millisecond
  1829. }
  1830. return 0
  1831. }
  1832. func (p *openAIWSConnPool) shouldSuppressPrewarmLocked(ap *openAIWSAccountPool, now time.Time) bool {
  1833. if ap == nil {
  1834. return true
  1835. }
  1836. if ap.prewarmFails <= 0 {
  1837. return false
  1838. }
  1839. if ap.prewarmFailAt.IsZero() {
  1840. ap.prewarmFails = 0
  1841. return false
  1842. }
  1843. if now.Sub(ap.prewarmFailAt) > openAIWSPrewarmFailureWindow {
  1844. ap.prewarmFails = 0
  1845. ap.prewarmFailAt = time.Time{}
  1846. return false
  1847. }
  1848. return ap.prewarmFails >= openAIWSPrewarmFailureSuppress
  1849. }
  1850. func (p *openAIWSConnPool) dialTimeout() time.Duration {
  1851. if p != nil && p.cfg != nil && p.cfg.Gateway.OpenAIWS.DialTimeoutSeconds > 0 {
  1852. return time.Duration(p.cfg.Gateway.OpenAIWS.DialTimeoutSeconds) * time.Second
  1853. }
  1854. return 10 * time.Second
  1855. }
  1856. func cloneOpenAIWSAcquireRequest(req openAIWSAcquireRequest) openAIWSAcquireRequest {
  1857. copied := req
  1858. copied.Headers = cloneHeader(req.Headers)
  1859. copied.WSURL = stringsTrim(req.WSURL)
  1860. copied.ProxyURL = stringsTrim(req.ProxyURL)
  1861. copied.PreferredConnID = stringsTrim(req.PreferredConnID)
  1862. if req.tlsProfile != nil {
  1863. copied.tlsProfile = req.tlsProfile.Clone()
  1864. }
  1865. return copied
  1866. }
  1867. func cloneOpenAIWSAcquireRequestPtr(req *openAIWSAcquireRequest) *openAIWSAcquireRequest {
  1868. if req == nil {
  1869. return nil
  1870. }
  1871. copied := cloneOpenAIWSAcquireRequest(*req)
  1872. return &copied
  1873. }
  1874. func sameOpenAIWSPrewarmTarget(a, b openAIWSAcquireRequest) bool {
  1875. return stringsTrim(a.WSURL) == stringsTrim(b.WSURL) &&
  1876. stringsTrim(a.ProxyURL) == stringsTrim(b.ProxyURL) &&
  1877. openAIWSAcquireCompatibility(a) == openAIWSAcquireCompatibility(b)
  1878. }
  1879. func openAIWSAcquireCompatibility(req openAIWSAcquireRequest) openAIWSHandshakeCompatibilityKey {
  1880. key := normalizeOpenAIWSHandshakeCompatibility(req.Account, req.Headers)
  1881. if req.Account != nil {
  1882. key.transportKey = openAIWSTransportKey(req.Account.ID, req.WSURL, req.ProxyURL, req.tlsProfile)
  1883. }
  1884. return key
  1885. }
  1886. func normalizeOpenAIWSBetaFeatures(headers http.Header) string {
  1887. features := make(map[string]struct{})
  1888. for name, values := range headers {
  1889. if !strings.EqualFold(strings.TrimSpace(name), "x-codex-beta-features") {
  1890. continue
  1891. }
  1892. for _, value := range values {
  1893. for _, feature := range strings.Split(value, ",") {
  1894. if feature = strings.TrimSpace(feature); feature != "" {
  1895. features[feature] = struct{}{}
  1896. }
  1897. }
  1898. }
  1899. }
  1900. if len(features) == 0 {
  1901. return ""
  1902. }
  1903. normalized := make([]string, 0, len(features))
  1904. for feature := range features {
  1905. normalized = append(normalized, feature)
  1906. }
  1907. sort.Strings(normalized)
  1908. return strings.Join(normalized, ",")
  1909. }
  1910. func normalizeOpenAIWSHandshakeCompatibility(account *Account, headers http.Header) openAIWSHandshakeCompatibilityKey {
  1911. key := openAIWSHandshakeCompatibilityKey{
  1912. betaFeatures: normalizeOpenAIWSBetaFeatures(headers),
  1913. }
  1914. mode := activeCodexFingerprintMode(account)
  1915. if mode == codexFingerprintOff {
  1916. return key
  1917. }
  1918. key.codexInstallationID = normalizeOpenAIWSStableIdentityHeader(headers, "x-codex-installation-id")
  1919. if mode == codexFingerprintDevice && !account.AntiDegradationEnabled() {
  1920. return key
  1921. }
  1922. key.sessionIDHyphen = normalizeOpenAIWSStableIdentityHeader(headers, "session-id")
  1923. key.sessionIDUnderscore = normalizeOpenAIWSStableIdentityHeader(headers, "session_id")
  1924. key.threadID = normalizeOpenAIWSStableIdentityHeader(headers, "thread-id")
  1925. key.clientRequestID = normalizeOpenAIWSStableIdentityHeader(headers, "x-client-request-id")
  1926. key.codexWindowID = normalizeOpenAIWSStableIdentityHeader(headers, "x-codex-window-id")
  1927. if account.AntiDegradationEnabled() {
  1928. key.conversationID = normalizeOpenAIWSStableIdentityHeader(headers, "conversation_id")
  1929. }
  1930. return key
  1931. }
  1932. func activeCodexFingerprintMode(account *Account) codexFingerprintMode {
  1933. if account == nil || account.GetCodexFingerprintMode() == codexFingerprintOff {
  1934. return codexFingerprintOff
  1935. }
  1936. if _, ok := codexFingerprintSeed(account.Extra); !ok {
  1937. return codexFingerprintOff
  1938. }
  1939. return account.GetCodexFingerprintMode()
  1940. }
  1941. func normalizeOpenAIWSStableIdentityHeader(headers http.Header, name string) string {
  1942. if headers == nil {
  1943. return ""
  1944. }
  1945. return strings.TrimSpace(headers.Get(name))
  1946. }
  1947. func normalizeOpenAIWSRoutingAffinity(headers http.Header) string {
  1948. canonicalName := http.CanonicalHeaderKey(openAICodexRoutingHintHeader)
  1949. if values, ok := headers[canonicalName]; ok {
  1950. for _, value := range values {
  1951. if value = strings.TrimSpace(value); value != "" {
  1952. return value
  1953. }
  1954. }
  1955. }
  1956. variantNames := make([]string, 0)
  1957. for name := range headers {
  1958. if name != canonicalName && strings.EqualFold(strings.TrimSpace(name), openAICodexRoutingHintHeader) {
  1959. variantNames = append(variantNames, name)
  1960. }
  1961. }
  1962. sort.Strings(variantNames)
  1963. for _, name := range variantNames {
  1964. for _, value := range headers[name] {
  1965. if value = strings.TrimSpace(value); value != "" {
  1966. return value
  1967. }
  1968. }
  1969. }
  1970. return ""
  1971. }
  1972. func cloneHeader(src http.Header) http.Header {
  1973. if src == nil {
  1974. return nil
  1975. }
  1976. dst := make(http.Header, len(src))
  1977. for k, vals := range src {
  1978. if len(vals) == 0 {
  1979. dst[k] = nil
  1980. continue
  1981. }
  1982. copied := make([]string, len(vals))
  1983. copy(copied, vals)
  1984. dst[k] = copied
  1985. }
  1986. return dst
  1987. }
  1988. func closeOpenAIWSConns(conns []*openAIWSConn) {
  1989. if len(conns) == 0 {
  1990. return
  1991. }
  1992. for _, conn := range conns {
  1993. if conn == nil {
  1994. continue
  1995. }
  1996. conn.close()
  1997. }
  1998. }
  1999. func stringsTrim(value string) string {
  2000. return strings.TrimSpace(value)
  2001. }