-
Notifications
You must be signed in to change notification settings - Fork 4
/
store.go
executable file
·81 lines (71 loc) · 1.83 KB
/
store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"sync"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// LimitStore defines the interface for the store of faucet limits.
type LimitStore interface {
// Get returns limit from store by the given key.
Get(key string) (*WithdrawalLimit, bool)
// Set sets limit to store by the given key.
Set(key string, value *WithdrawalLimit)
// Remove removes limit from store by the given key.
Remove(key string)
// Clean removes deprecated limits.
Clean(timeLimit time.Duration)
}
// limitStore defines the store of faucet limits.
type limitStore struct {
sync.RWMutex
limits map[string]*WithdrawalLimit
}
// WithdrawalLimit defines a store of faucet withdrawals.
type WithdrawalLimit struct {
WithdrawalAmount sdk.Coins
LastWithdrawals map[string]time.Time
}
// NewLimitStore creates a new LimitStore.
func NewLimitStore() LimitStore {
return &limitStore{
RWMutex: sync.RWMutex{},
limits: make(map[string]*WithdrawalLimit),
}
}
// Get implements LimitStore interface.
func (s *limitStore) Get(key string) (*WithdrawalLimit, bool) {
s.RLock()
defer s.RUnlock()
res, ok := s.limits[key]
return res, ok
}
// Set implements LimitStore interface.
func (s *limitStore) Set(key string, value *WithdrawalLimit) {
s.Lock()
defer s.Unlock()
s.limits[key] = value
}
// Remove implements LimitStore interface.
func (s *limitStore) Remove(key string) {
s.Lock()
defer s.Unlock()
delete(s.limits, key)
}
// Clean implements LimitStore interface.
func (s *limitStore) Clean(timeLimit time.Duration) {
toRemove := make([]string, 0, 10)
for k, v := range s.limits {
denomsUnpend := 0
for _, lw := range v.LastWithdrawals {
if time.Now().Sub(lw) > timeLimit {
denomsUnpend++
}
}
if denomsUnpend == len(v.LastWithdrawals) {
toRemove = append(toRemove, k)
}
}
for _, k := range toRemove {
s.Remove(k)
}
}