-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
59 lines (52 loc) · 1.07 KB
/
state.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
package grouter
import (
"sync"
"time"
)
// Routing state. This is attached to a Session
type routerState struct {
state string
timestamp time.Time
}
type stateCache struct {
store sync.Map
ticker *time.Ticker
done chan bool
}
func newStateCache(frequency, stateTTL time.Duration) *stateCache {
c := &stateCache{
ticker: time.NewTicker(frequency),
done: make(chan bool),
}
go func(store *stateCache) {
for {
select {
case <-store.done:
store.ticker.Stop()
return
case <-store.ticker.C:
store.evict(stateTTL)
}
}
}(c)
return c
}
func (c *stateCache) get(name string) (string, bool) {
if vi, ok := c.store.Load(name); ok {
return vi.(*routerState).state, ok
}
return "", false
}
func (c *stateCache) set(name string, state string) {
c.store.Store(name, &routerState{timestamp: time.Now(), state: state})
}
func (c *stateCache) evict(ttl time.Duration) {
now := time.Now()
c.store.Range(func(key, value any) bool {
state := value.(*routerState)
if now.Sub(state.timestamp) >= ttl {
c.store.Delete(key)
}
return true
})
}