-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing_table.go
70 lines (57 loc) · 1.07 KB
/
routing_table.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
package router
import (
"sync"
"time"
)
type RoutingEntry struct {
tag string
err error
expire time.Time
}
func (v *RoutingEntry) Extend() {
v.expire = time.Now().Add(time.Hour)
}
func (v *RoutingEntry) Expired() bool {
return v.expire.Before(time.Now())
}
type RoutingTable struct {
sync.RWMutex
table map[string]*RoutingEntry
}
func NewRoutingTable() *RoutingTable {
return &RoutingTable{
table: make(map[string]*RoutingEntry),
}
}
func (v *RoutingTable) Cleanup() {
v.Lock()
defer v.Unlock()
for key, value := range v.table {
if value.Expired() {
delete(v.table, key)
}
}
}
func (v *RoutingTable) Set(destination string, tag string, err error) {
v.Lock()
defer v.Unlock()
entry := &RoutingEntry{
tag: tag,
err: err,
}
entry.Extend()
v.table[destination] = entry
if len(v.table) > 1000 {
go v.Cleanup()
}
}
func (v *RoutingTable) Get(destination string) (bool, string, error) {
v.RLock()
defer v.RUnlock()
entry, found := v.table[destination]
if !found {
return false, "", nil
}
entry.Extend()
return true, entry.tag, entry.err
}