This repository has been archived by the owner on Dec 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 62
/
TSDCache.go
135 lines (117 loc) · 2.4 KB
/
TSDCache.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package collection
import (
"fmt"
"sync"
)
type TSD interface {
GetTimestamp() int64
HasLabels(map[string]string) bool
}
type TSDCache struct {
lock *sync.RWMutex
data []TSD
capacity int
cursor int
num int
}
func NewTSDCache(capacity int) *TSDCache {
if capacity <= 0 {
panic("invalid TSDCache capacity")
}
return &TSDCache{
lock: &sync.RWMutex{},
data: make([]TSD, capacity),
capacity: capacity,
cursor: 0,
}
}
func (c *TSDCache) binarySearch(t int64) int {
if c.num == 0 {
return 0
}
var l, r int
if c.data[c.cursor] == nil {
l = 0
r = c.cursor - 1
} else {
l = c.cursor
r = c.cursor - 1 + c.capacity
}
for {
if l > r {
return l
}
m := l + (r-l)/2
if t <= c.data[m%c.capacity].GetTimestamp() {
r = m - 1
} else {
l = m + 1
}
}
}
func (c *TSDCache) Put(d TSD) {
c.lock.Lock()
defer c.lock.Unlock()
defer func() {
c.num++
}()
if c.num == 0 || d.GetTimestamp() >= c.data[((c.cursor-1)+c.capacity)%c.capacity].GetTimestamp() {
c.data[c.cursor] = d
c.cursor = (c.cursor + 1) % c.capacity
return
}
pos := c.binarySearch(d.GetTimestamp())
if pos == c.cursor && c.data[c.cursor] != nil {
return
}
end := c.cursor
if c.data[end] != nil {
end += c.capacity
}
for i := end; i > pos; i-- {
c.data[i%c.capacity] = c.data[(i-1)%c.capacity]
}
c.data[pos%c.capacity] = d
c.cursor = (c.cursor + 1) % c.capacity
}
func (c *TSDCache) String() string {
c.lock.RLock()
defer c.lock.RUnlock()
var head, tail int
if c.data[c.cursor] == nil {
head = 0
tail = c.cursor - 1
} else {
head = c.cursor
tail = c.cursor + c.capacity - 1
}
s := make([]TSD, tail-head+1)
for i := 0; i <= tail-head; i++ {
s[i] = c.data[(i+head)%c.capacity]
}
return fmt.Sprint(s)
}
//
// Query returns the time series with the timestamp in [start, end)
// If it can not guarantee all the data are in cache, it returns ([start, end), false)
//
func (c *TSDCache) Query(start, end int64, labels map[string]string) ([]TSD, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
if c.num == 0 {
return []TSD{}, false
}
result := []TSD{}
from := c.binarySearch(start)
to := c.binarySearch(end)
for i := from; i < to; i++ {
d := c.data[i%c.capacity]
if d.HasLabels(labels) {
result = append(result, d)
}
}
if c.num < c.capacity {
return result, c.data[0].GetTimestamp() <= start
}
return result, c.data[c.cursor].GetTimestamp() <= start
}