This repository has been archived by the owner on Sep 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
90 lines (78 loc) · 1.47 KB
/
storage.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
82
83
84
85
86
87
88
89
90
package main
import (
"log"
"sync"
"time"
"github.com/gortc/stun"
)
var messages = &storage{
data: make(map[string]*storageEntry),
}
type storageEntry struct {
*stun.Message
createdAt time.Time
}
func (s storageEntry) timedOut(timeout time.Time) bool {
return s.createdAt.Before(timeout)
}
type storage struct {
data map[string]*storageEntry
sync.Mutex
}
func (storage) timeout() time.Time {
return time.Now().Add(time.Second * -60)
}
func mustClone(m *stun.Message) *stun.Message {
b := new(stun.Message)
if err := m.CloneTo(b); err != nil {
panic(err)
}
return b
}
func (s *storage) pop(addr string) *stun.Message {
s.Lock()
defer s.Unlock()
if s.data[addr] == nil {
return nil
}
m := mustClone(s.data[addr].Message)
delete(s.data, addr)
return m
}
func (s *storage) add(addr string, m *stun.Message) {
c := new(stun.Message)
m.CloneTo(c)
entry := &storageEntry{
Message: c,
createdAt: time.Now(),
}
s.Lock()
s.data[addr] = entry
s.Unlock()
log.Println("storage: added", addr)
}
func (s *storage) collect() {
s.Lock()
var (
toRemove = make([]string, 0, 10)
timeout = s.timeout()
)
for addr, m := range s.data {
if m.timedOut(timeout) {
toRemove = append(toRemove, addr)
}
}
for _, addr := range toRemove {
delete(s.data, addr)
}
s.Unlock()
if len(toRemove) > 0 {
log.Println("storage: collected", len(toRemove))
}
}
func (s *storage) gc() {
ticker := time.NewTicker(time.Second * 2)
for range ticker.C {
s.collect()
}
}