account_traffic_service.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "log/slog"
  7. "net/http"
  8. "strings"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/google/uuid"
  13. )
  14. type AccountTrafficService struct{ cache AccountTrafficCache }
  15. func NewAccountTrafficService(cache AccountTrafficCache) *AccountTrafficService {
  16. return &AccountTrafficService{cache: cache}
  17. }
  18. func AccountTrafficFailover(err error) *UpstreamFailoverError {
  19. var limited *AccountTrafficLimitError
  20. if errors.As(err, &limited) {
  21. return limited.FailoverError()
  22. }
  23. return nil
  24. }
  25. func accountTrafficController(upstream HTTPUpstream) *AccountTrafficService {
  26. if provider, ok := upstream.(AccountTrafficProvider); ok {
  27. return provider.AccountTrafficController()
  28. }
  29. return nil
  30. }
  31. func beginAccountTrafficTurn(ctx context.Context, upstream HTTPUpstream, a *Account) (context.Context, *AccountTrafficPermit, error) {
  32. plan, err := AccountTrafficPlanFor(a)
  33. if err != nil {
  34. return ctx, nil, err
  35. }
  36. ctx, permit, err := accountTrafficController(upstream).Begin(ctx, plan)
  37. if limited := AccountTrafficFailover(err); limited != nil {
  38. return ctx, nil, limited
  39. }
  40. return ctx, permit, err
  41. }
  42. func finishAccountTrafficTurn(permit *AccountTrafficPermit, err error) {
  43. if permit == nil {
  44. return
  45. }
  46. status := 0
  47. if err == nil {
  48. status = 200
  49. } else {
  50. var upstream *UpstreamFailoverError
  51. if errors.As(err, &upstream) && upstream.Reason != "account_traffic_limit" {
  52. status = upstream.StatusCode
  53. }
  54. }
  55. permit.Finish(status)
  56. }
  57. type AccountTrafficPermit struct {
  58. service *AccountTrafficService
  59. plan AccountTrafficPlan
  60. id string
  61. started time.Time
  62. cancel context.CancelFunc
  63. stop chan struct{}
  64. once sync.Once
  65. }
  66. func (s *AccountTrafficService) Begin(ctx context.Context, plan AccountTrafficPlan, onLeaseLost ...func()) (context.Context, *AccountTrafficPermit, error) {
  67. if err := ctx.Err(); err != nil {
  68. return ctx, nil, err
  69. }
  70. if !plan.Policy.Enabled() || ctx.Value(accountTrafficCoveredKey{}) == plan.AccountID {
  71. return ctx, nil, nil
  72. }
  73. if s == nil || s.cache == nil {
  74. if !plan.Policy.Enforces() {
  75. return ctx, nil, nil
  76. }
  77. return ctx, nil, &AccountTrafficLimitError{Reason: "流量控制暂不可用,请稍后重试", Status: 503, RetryAfter: time.Second}
  78. }
  79. id := uuid.NewString()
  80. admission, err := s.cache.Acquire(ctx, plan, id)
  81. if err != nil {
  82. slog.Warn("account_traffic_acquire_failed", "account_id", plan.AccountID, "error", err)
  83. if !plan.Policy.Enforces() {
  84. return ctx, nil, nil
  85. }
  86. return ctx, nil, &AccountTrafficLimitError{Reason: "流量控制暂不可用,请稍后重试", Status: 503, RetryAfter: time.Second}
  87. }
  88. if !admission.Allowed {
  89. return ctx, nil, &AccountTrafficLimitError{Reason: admission.Reason, RetryAfter: admission.RetryAfter}
  90. }
  91. if admission.SkipObservation {
  92. return ctx, nil, nil
  93. }
  94. child, cancel := context.WithCancel(context.WithValue(ctx, accountTrafficCoveredKey{}, plan.AccountID))
  95. p := &AccountTrafficPermit{service: s, plan: plan, id: id, started: time.Now(), cancel: cancel, stop: make(chan struct{})}
  96. go func() {
  97. ticker := time.NewTicker(30 * time.Second)
  98. defer ticker.Stop()
  99. for {
  100. select {
  101. case <-p.stop:
  102. return
  103. case <-child.Done():
  104. p.Finish(0)
  105. return
  106. case <-ticker.C:
  107. refreshCtx, end := context.WithTimeout(context.Background(), 5*time.Second)
  108. ok, err := s.cache.Refresh(refreshCtx, plan.AccountID, id)
  109. end()
  110. if err != nil || !ok {
  111. p.loseLease(onLeaseLost)
  112. return
  113. }
  114. }
  115. }
  116. }()
  117. return child, p, nil
  118. }
  119. func (p *AccountTrafficPermit) Finish(status int) {
  120. if p == nil {
  121. return
  122. }
  123. p.finishObservation(status, true)
  124. p.cancel()
  125. }
  126. func (p *AccountTrafficPermit) loseLease(callbacks []func()) {
  127. if p.plan.Policy.Enforces() {
  128. for _, callback := range callbacks {
  129. callback()
  130. }
  131. p.Finish(0)
  132. return
  133. }
  134. // Losing telemetry must never interrupt a request in recommendation-only mode.
  135. p.finishObservation(0, false)
  136. }
  137. func (p *AccountTrafficPermit) finishObservation(status int, cancelRequest bool) {
  138. p.once.Do(func() {
  139. close(p.stop)
  140. if cancelRequest {
  141. p.cancel()
  142. }
  143. ctx, end := context.WithTimeout(context.Background(), 5*time.Second)
  144. defer end()
  145. if err := p.service.cache.Finish(ctx, p.plan, p.id, status, time.Since(p.started).Milliseconds()); err != nil {
  146. slog.Warn("account_traffic_finish_failed", "account_id", p.plan.AccountID, "error", err)
  147. }
  148. })
  149. }
  150. func (s *AccountTrafficService) State(ctx context.Context, a *Account) (AccountTrafficState, error) {
  151. plan, err := AccountTrafficPlanFor(a)
  152. if err != nil {
  153. return AccountTrafficState{}, err
  154. }
  155. if s == nil || s.cache == nil {
  156. return AccountTrafficState{}, errors.New("流量控制状态暂不可用")
  157. }
  158. return s.cache.Snapshot(ctx, plan)
  159. }
  160. func (s *AccountTrafficService) Sync(ctx context.Context, a *Account) error {
  161. plan, err := AccountTrafficPlanFor(a)
  162. if err != nil {
  163. return err
  164. }
  165. if s == nil || s.cache == nil {
  166. return errors.New("流量控制状态暂不可用")
  167. }
  168. return s.cache.Sync(ctx, plan)
  169. }
  170. // DoHTTP covers the complete response-body lifetime. Nested plugin/decorator
  171. // transports see the covered marker and cannot double charge a request.
  172. func (s *AccountTrafficService) DoHTTP(req *http.Request, send func(*http.Request) (*http.Response, error)) (*http.Response, error) {
  173. if req == nil {
  174. return send(req)
  175. }
  176. if _, ok := req.Context().Value(accountTrafficConfigErrorKey{}).(error); ok {
  177. return nil, &AccountTrafficLimitError{Reason: "账号流量控制配置无效,请管理员检查", Status: 400}
  178. }
  179. plan, ok := req.Context().Value(accountTrafficPlanKey{}).(AccountTrafficPlan)
  180. if !ok || !plan.Policy.Enabled() || req.Context().Value(accountTrafficCoveredKey{}) == plan.AccountID {
  181. return send(req)
  182. }
  183. ctx, permit, err := s.Begin(req.Context(), plan)
  184. if err != nil {
  185. if run := intelligentContext(req.Context()); run != nil {
  186. var wait *AccountTrafficLimitError
  187. if errors.As(err, &wait) {
  188. run.capture.trafficWait = wait
  189. }
  190. }
  191. return nil, err
  192. }
  193. if permit == nil {
  194. return send(req.WithContext(ctx))
  195. }
  196. resp, err := send(req.WithContext(ctx))
  197. if err != nil || resp == nil {
  198. permit.Finish(0)
  199. return resp, err
  200. }
  201. if resp.Body == nil {
  202. permit.Finish(resp.StatusCode)
  203. return resp, nil
  204. }
  205. resp.Body = &accountTrafficBody{ReadCloser: resp.Body, permit: permit, status: resp.StatusCode, sse: strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream"), expectedBytes: resp.ContentLength}
  206. return resp, nil
  207. }
  208. type accountTrafficBody struct {
  209. io.ReadCloser
  210. permit *AccountTrafficPermit
  211. status int
  212. sse bool
  213. line []byte
  214. discardLine bool
  215. terminalStatus atomic.Int32
  216. expectedBytes int64
  217. readBytes atomic.Int64
  218. }
  219. func (b *accountTrafficBody) Read(data []byte) (int, error) {
  220. n, err := b.ReadCloser.Read(data)
  221. b.readBytes.Add(int64(n))
  222. if b.sse {
  223. b.inspect(data[:n])
  224. }
  225. if err != nil {
  226. status := b.status
  227. if value := b.terminalStatus.Load(); value != 0 {
  228. status = int(value)
  229. } else if b.sse && status < 400 {
  230. status = 0
  231. }
  232. if err != io.EOF && status < 400 {
  233. status = 0
  234. }
  235. b.permit.Finish(status)
  236. }
  237. return n, err
  238. }
  239. func (b *accountTrafficBody) Close() error {
  240. err := b.ReadCloser.Close()
  241. status := b.status
  242. // Without EOF a 2xx stream might have been abandoned; it is not recovery evidence.
  243. if value := b.terminalStatus.Load(); value != 0 {
  244. status = int(value)
  245. } else if status < 400 && (b.sse || b.expectedBytes <= 0 || b.readBytes.Load() < b.expectedBytes) {
  246. status = 0
  247. }
  248. b.permit.Finish(status)
  249. return err
  250. }
  251. func (b *accountTrafficBody) inspect(data []byte) {
  252. for _, ch := range data {
  253. if ch == '\n' {
  254. if !b.discardLine {
  255. line := strings.TrimSpace(string(b.line))
  256. if strings.HasPrefix(line, "data:") {
  257. raw := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
  258. status, terminal := accountTrafficEventStatus([]byte(raw))
  259. if raw == "[DONE]" {
  260. status, terminal = 200, true
  261. }
  262. previous := int(b.terminalStatus.Load())
  263. if terminal && (previous < 400 || status == 429 || status >= 500) {
  264. b.terminalStatus.Store(int32(status))
  265. }
  266. }
  267. }
  268. b.line = nil
  269. b.discardLine = false
  270. } else if !b.discardLine {
  271. if len(b.line) >= 64<<10 {
  272. b.line = nil
  273. b.discardLine = true
  274. } else {
  275. b.line = append(b.line, ch)
  276. }
  277. }
  278. }
  279. }