utils.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package model
  2. import (
  3. "one-api/common"
  4. "sync"
  5. "time"
  6. )
  7. const BatchUpdateTypeCount = 4 // if you add a new type, you need to add a new map and a new lock
  8. const (
  9. BatchUpdateTypeUserQuota = iota
  10. BatchUpdateTypeTokenQuota
  11. BatchUpdateTypeUsedQuotaAndRequestCount
  12. BatchUpdateTypeChannelUsedQuota
  13. )
  14. var batchUpdateStores []map[int]int
  15. var batchUpdateLocks []sync.Mutex
  16. func init() {
  17. for i := 0; i < BatchUpdateTypeCount; i++ {
  18. batchUpdateStores = append(batchUpdateStores, make(map[int]int))
  19. batchUpdateLocks = append(batchUpdateLocks, sync.Mutex{})
  20. }
  21. }
  22. func InitBatchUpdater() {
  23. go func() {
  24. for {
  25. time.Sleep(time.Duration(common.BatchUpdateInterval) * time.Second)
  26. batchUpdate()
  27. }
  28. }()
  29. }
  30. func addNewRecord(type_ int, id int, value int) {
  31. batchUpdateLocks[type_].Lock()
  32. defer batchUpdateLocks[type_].Unlock()
  33. if _, ok := batchUpdateStores[type_][id]; !ok {
  34. batchUpdateStores[type_][id] = value
  35. } else {
  36. batchUpdateStores[type_][id] += value
  37. }
  38. }
  39. func batchUpdate() {
  40. common.SysLog("batch update started")
  41. for i := 0; i < BatchUpdateTypeCount; i++ {
  42. batchUpdateLocks[i].Lock()
  43. store := batchUpdateStores[i]
  44. batchUpdateStores[i] = make(map[int]int)
  45. batchUpdateLocks[i].Unlock()
  46. for key, value := range store {
  47. switch i {
  48. case BatchUpdateTypeUserQuota:
  49. err := increaseUserQuota(key, value)
  50. if err != nil {
  51. common.SysError("failed to batch update user quota: " + err.Error())
  52. }
  53. case BatchUpdateTypeTokenQuota:
  54. err := increaseTokenQuota(key, value)
  55. if err != nil {
  56. common.SysError("failed to batch update token quota: " + err.Error())
  57. }
  58. case BatchUpdateTypeUsedQuotaAndRequestCount:
  59. updateUserUsedQuotaAndRequestCount(key, value, 1) // TODO: count is incorrect
  60. case BatchUpdateTypeChannelUsedQuota:
  61. updateChannelUsedQuota(key, value)
  62. }
  63. }
  64. }
  65. common.SysLog("batch update finished")
  66. }