This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Don't reissue tokens for the same task id
- Loading branch information
1 parent
8b120cf
commit cb62fcf
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package main | ||
|
||
import ( | ||
"sync" | ||
"time" | ||
) | ||
|
||
type TtlSet struct { | ||
sync.RWMutex | ||
s map[string]time.Time | ||
quit chan struct{} | ||
} | ||
|
||
func NewTtlSet() *TtlSet { | ||
t := &TtlSet{} | ||
t.s = make(map[string]time.Time) | ||
t.quit = make(chan struct{}) | ||
go t.garbageCollector() | ||
return t | ||
} | ||
|
||
func (t *TtlSet) Has(key string) bool { | ||
t.RLock() | ||
defer t.RUnlock() | ||
_, ok := t.s[key] | ||
return ok | ||
} | ||
|
||
func (t *TtlSet) Put(key string, ttl time.Duration) { | ||
t.Lock() | ||
t.s[key] = time.Now().Add(ttl) | ||
t.Unlock() | ||
} | ||
|
||
func (t *TtlSet) cleanup() { | ||
t.Lock() | ||
for k, v := range t.s { | ||
if time.Now().After(v) { | ||
delete(t.s, k) | ||
} | ||
} | ||
t.Unlock() | ||
} | ||
|
||
func (t *TtlSet) garbageCollector() { | ||
ticker := time.Tick(5 * time.Second) | ||
for { | ||
select { | ||
case <-ticker: | ||
t.cleanup() | ||
case <-t.quit: | ||
return | ||
} | ||
} | ||
} |