-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.go
121 lines (100 loc) · 1.64 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package debugserver
import (
"sync"
"time"
)
const TTL = 60 * 5
type Storage struct {
sync.RWMutex
buckets map[string][]Request
records *list
}
func NewStorage() *Storage {
s := &Storage{
buckets: make(map[string][]Request),
records: &list{},
}
go func() {
for t := range time.Tick(5 * time.Second) {
s.Expire(t.Unix() - TTL)
}
}()
return s
}
func (s *Storage) Get(id string) []Request {
s.RLock()
defer s.RUnlock()
return s.buckets[id]
}
func (s *Storage) Add(id string, r Request) {
s.Lock()
s.records.add(id)
s.buckets[id] = append(s.buckets[id], r)
s.Unlock()
}
func (s *Storage) Del(id string) {
s.Lock()
defer s.Unlock()
delete(s.buckets, id)
s.records.del(id)
}
func (s *Storage) Expire(timestamp int64) {
s.Lock()
defer s.Unlock()
item := s.records.First
for {
if item == nil {
s.records.First = nil
s.records.Last = nil
return
}
if item.CreatedAt > timestamp {
s.records.First = item
return
}
delete(s.buckets, item.Value)
item = item.Next
}
}
type node struct {
CreatedAt int64
Value string
Next *node
}
type list struct {
First *node
Last *node
}
func (l *list) add(s string) {
newNode := &node{
CreatedAt: time.Now().Unix(),
Value: s,
}
if l.First == nil {
l.First = newNode
l.Last = l.First
return
}
l.Last.Next = newNode
l.Last = newNode
}
func (l *list) del(s string) {
item := l.First
if item.Value == s {
l.First = item.Next
if item == l.Last {
l.Last = nil
}
return
}
for {
if item == nil || item.Next == nil {
return
}
if item.Next.Value == s {
item.Next = item.Next.Next
return
}
item = item.Next
}
}