utils.go 2.1 KB

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