utils.go 1.9 KB

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