Skip to content

Commit

Permalink
Add function IsLockedTTLWithLimit checks if the key has been incremen…
Browse files Browse the repository at this point in the history
…ted more than the specified limit
  • Loading branch information
WanMuhafidzFaldi committed Nov 15, 2024
1 parent 44080aa commit c9c6226
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
30 changes: 30 additions & 0 deletions candiutils/locker.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,33 @@ func (r *RedisLocker) IsLockedTTL(key string, TTL time.Duration) bool {
return incr > 1
}

// IsLockedTTLWithLimit checks if the key has been incremented more than the specified limit
// within the given TTL. If the key is being created for the first time, it sets the TTL.
// Example usage: check if a key has been incremented more than 10 times within 1 minute.
func (r *RedisLocker) IsLockedTTLWithLimit(key string, limit int, TTL time.Duration) bool {
conn := r.pool.Get()
defer conn.Close()

lockKey := fmt.Sprintf("%s:%s", r.lockeroptions.Prefix, key)
incr, err := redis.Int64(conn.Do("INCR", lockKey))
if err != nil {
return false
}

var expireTime time.Duration
if TTL > 0 {
expireTime = TTL
} else {
expireTime = r.lockeroptions.TTL
}

if expireTime > 0 && incr == 1 {
conn.Do("EXPIRE", lockKey, int(expireTime.Seconds()))
}

return incr > int64(limit)
}

func (r *RedisLocker) HasBeenLocked(key string) bool {
conn := r.pool.Get()
defer conn.Close()
Expand Down Expand Up @@ -234,3 +261,6 @@ func (NoopLocker) GetPrefixLocker() string { return "" }

// GetTTLLocker method
func (NoopLocker) GetTTLLocker() time.Duration { return 0 }

// IsLockedTTLWithLimit method
func (NoopLocker) IsLockedTTLWithLimit(string, int, time.Duration) bool { return false }
1 change: 1 addition & 0 deletions codebase/interfaces/locker.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type (
Lock(key string, timeout time.Duration) (unlockFunc func(), err error)
GetPrefixLocker() string
GetTTLLocker() time.Duration
IsLockedTTLWithLimit(key string, limit int, TTL time.Duration) bool
Closer
}
)

0 comments on commit c9c6226

Please sign in to comment.