Skip to content

Commit

Permalink
fix: update cache immediately after cache get
Browse files Browse the repository at this point in the history
Co-authored-by: chikasaki <[email protected]>
Co-authored-by: Cruel <[email protected]>
  • Loading branch information
3 people committed Aug 16, 2023
1 parent 90b4cac commit 86c2627
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
5 changes: 5 additions & 0 deletions common/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,8 @@ func RedisDel(key string) error {
ctx := context.Background()
return RDB.Del(ctx, key).Err()
}

func RedisDecrease(key string, value int64) error {
ctx := context.Background()
return RDB.DecrBy(ctx, key, value).Err()
}
6 changes: 5 additions & 1 deletion controller/relay-text.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,11 @@ func relayTextHelper(c *gin.Context, relayMode int) *OpenAIErrorWithStatusCode {
if err != nil {
return errorWrapper(err, "get_user_quota_failed", http.StatusInternalServerError)
}
if userQuota > 10*preConsumedQuota {
err = model.CacheDecreaseUserQuota(userId, preConsumedQuota)
if err != nil {
return errorWrapper(err, "decrease_user_quota_failed", http.StatusInternalServerError)
}
if userQuota > 100*preConsumedQuota {
// in this case, we do not pre-consume quota
// because the user has enough quota
preConsumedQuota = 0
Expand Down
8 changes: 8 additions & 0 deletions model/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@ func CacheUpdateUserQuota(id int) error {
return err
}

func CacheDecreaseUserQuota(id int, quota int) error {
if !common.RedisEnabled {
return nil
}
err := common.RedisDecrease(fmt.Sprintf("user_quota:%d", id), int64(quota))
return err
}

func CacheIsUserEnabled(userId int) bool {
if !common.RedisEnabled {
return IsUserEnabled(userId)
Expand Down

0 comments on commit 86c2627

Please sign in to comment.