-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtime_window.go
337 lines (303 loc) · 8.66 KB
/
time_window.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
* Copyright 2020 Saffat Technologies, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unitdb
import (
"encoding/binary"
"fmt"
"sync"
"time"
"github.com/unit-io/unitdb/hash"
)
type (
_WinEntry struct {
sequence uint64
expiresAt uint32
}
_WinBlock struct {
topicHash uint64
entries [entriesPerWindowBlock]_WinEntry
// Next stores offset that links multiple winBlocks for a topic hash.
// Most recent offset is stored into the trie to iterate entries in reverse time order.
next int64
cutoffTime int64
entryIdx uint16
// dirty used during timeWindow append and not persisted.
dirty bool
// leased used in timeWindow write and not persisted.
leased bool
}
)
func newWinEntry(seq uint64, expiresAt uint32) _WinEntry {
return _WinEntry{sequence: seq, expiresAt: expiresAt}
}
func (e _WinEntry) seq() uint64 {
return e.sequence
}
func (e _WinEntry) expiryTime() uint32 {
return e.expiresAt
}
func (e _WinEntry) isExpired() bool {
return e.expiresAt != 0 && e.expiresAt <= uint32(time.Now().Unix())
}
func (b _WinBlock) cutoff(cutoff int64) bool {
return b.cutoffTime != 0 && b.cutoffTime < cutoff
}
// marshalBinary serialized window block into binary data.
func (b _WinBlock) marshalBinary() []byte {
buf := make([]byte, blockSize)
data := buf
for i := 0; i < entriesPerWindowBlock; i++ {
e := b.entries[i]
binary.LittleEndian.PutUint64(buf[:8], e.sequence)
binary.LittleEndian.PutUint32(buf[8:12], e.expiresAt)
buf = buf[12:]
}
binary.LittleEndian.PutUint64(buf[:8], uint64(b.cutoffTime))
binary.LittleEndian.PutUint64(buf[8:16], b.topicHash)
binary.LittleEndian.PutUint64(buf[16:24], uint64(b.next))
binary.LittleEndian.PutUint16(buf[24:26], b.entryIdx)
return data
}
// unmarshalBinary de-serialized window block from binary data.
func (b *_WinBlock) unmarshalBinary(data []byte) error {
for i := 0; i < entriesPerWindowBlock; i++ {
_ = data[12] // bounds check hint to compiler; see golang.org/issue/14808.
b.entries[i].sequence = binary.LittleEndian.Uint64(data[:8])
b.entries[i].expiresAt = binary.LittleEndian.Uint32(data[8:12])
data = data[12:]
}
b.cutoffTime = int64(binary.LittleEndian.Uint64(data[:8]))
b.topicHash = binary.LittleEndian.Uint64(data[8:16])
b.next = int64(binary.LittleEndian.Uint64(data[16:24]))
b.entryIdx = binary.LittleEndian.Uint16(data[24:26])
return nil
}
func winBlockOffset(idx int32) int64 {
return int64(blockSize * idx)
}
type (
_TimeOptions struct {
maxDuration time.Duration
expDurationType time.Duration
maxExpDurations int
backgroundKeyExpiry bool
}
_TimeWindowBucket struct {
sync.RWMutex
windowBlocks *_WindowBlocks
expiryWindowBucket *_ExpiryWindowBucket
opts *_TimeOptions
}
)
type _WindowEntries []_WinEntry
type _Key struct {
timeID int64
topicHash uint64
}
type _TimeWindow struct {
mu sync.RWMutex
entries map[_Key]_WindowEntries
}
// A "thread" safe windowBlocks.
// To avoid lock bottlenecks windowBlocks are divided into several shards (nShards).
type _WindowBlocks struct {
sync.RWMutex
window []*_TimeWindow
consistent *hash.Consistent
}
// newWindowBlocks creates a new concurrent windows.
func newWindowBlocks() *_WindowBlocks {
wb := &_WindowBlocks{
window: make([]*_TimeWindow, nShards),
consistent: hash.InitConsistent(nShards, nShards),
}
for i := 0; i < nShards; i++ {
wb.window[i] = &_TimeWindow{entries: make(map[_Key]_WindowEntries)}
}
return wb
}
// getWindowBlock returns shard under given blockID.
func (w *_WindowBlocks) getWindowBlock(blockID uint64) *_TimeWindow {
w.RLock()
defer w.RUnlock()
return w.window[w.consistent.FindBlock(blockID)]
}
func newTimeWindowBucket(opts *_TimeOptions) *_TimeWindowBucket {
l := &_TimeWindowBucket{}
l.windowBlocks = newWindowBlocks()
l.expiryWindowBucket = newExpiryWindowBucket(opts.backgroundKeyExpiry, opts.expDurationType, opts.maxExpDurations)
return l
}
func (tw *_TimeWindowBucket) add(timeID int64, topicHash uint64, e _WinEntry) (ok bool) {
// get windowBlock shard.
tw.RLock()
b := tw.windowBlocks.getWindowBlock(topicHash)
tw.RUnlock()
b.mu.Lock()
defer b.mu.Unlock()
key := _Key{
timeID: timeID,
topicHash: topicHash,
}
if _, ok := b.entries[key]; ok {
b.entries[key] = append(b.entries[key], e)
} else {
b.entries[key] = _WindowEntries{e}
}
return true
}
func (tw *_TimeWindowBucket) release() func(timeID int64) error {
releasedKeys := make(map[int64][]_Key)
for i := 0; i < nShards; i++ {
wb := tw.windowBlocks.window[i]
wb.mu.RLock()
for k := range wb.entries {
if _, ok := releasedKeys[k.timeID]; ok {
releasedKeys[k.timeID] = append(releasedKeys[k.timeID], k)
} else {
releasedKeys[k.timeID] = []_Key{k}
}
}
wb.mu.RUnlock()
}
return func(timeID int64) error {
keys, ok := releasedKeys[timeID]
if !ok {
return errBadRequest
}
for _, k := range keys {
b := tw.windowBlocks.getWindowBlock(k.topicHash)
b.mu.Lock()
delete(b.entries, k)
b.mu.Unlock()
}
return nil
}
}
// ilookup lookups window entries from timeWindowBucket and not yet sync to DB.
func (tw *_TimeWindowBucket) ilookup(topicHash uint64, limit int) (winEntries _WindowEntries) {
winEntries = make([]_WinEntry, 0)
// get windowBlock shard.
b := tw.windowBlocks.getWindowBlock(topicHash)
b.mu.RLock()
defer b.mu.RUnlock()
var l int
var expiryCount int
for key := range b.entries {
if key.topicHash != topicHash {
continue
}
wEntries := b.entries[key]
if len(wEntries) > 0 {
l = limit + expiryCount - l
if len(wEntries) < l {
l = len(wEntries)
}
for i := len(wEntries) - 1; i >= len(wEntries)-l; i-- {
we := wEntries[i]
if we.isExpired() {
if err := tw.expiryWindowBucket.addExpiry(we); err != nil {
expiryCount++
logger.Error().Err(err).Str("context", "timeWindow.addExpiry")
}
// if id is expired it does not return an error but continue the iteration.
continue
}
winEntries = append(winEntries, we)
}
}
}
return winEntries
}
// lookup lookups window entries from window file.
func (tw *_TimeWindowBucket) lookup(fs *_FileSet, topicHash uint64, off, cutoff int64, limit int) (winEntries _WindowEntries) {
winEntries = make([]_WinEntry, 0)
winEntries = tw.ilookup(topicHash, limit)
if len(winEntries) >= limit {
return winEntries
}
winFile, err := fs.getFile(_FileDesc{fileType: typeTimeWindow})
if err != nil {
return winEntries
}
next := func(blockOff int64, f func(_WinBlock) (bool, error)) error {
for {
r := _WindowReader{winFile: winFile, offset: blockOff}
b, err := r.readWindowBlock()
if err != nil {
return err
}
if stop, err := f(b); stop || err != nil {
return err
}
if b.next == 0 {
return nil
}
blockOff = b.next
}
}
expiryCount := 0
err = next(off, func(curb _WinBlock) (bool, error) {
b := &curb
if b.topicHash != topicHash {
return true, nil
}
if len(winEntries) > limit-int(b.entryIdx) {
limit = limit - len(winEntries)
for i := len(b.entries[:b.entryIdx]) - 1; i >= len(b.entries[:b.entryIdx])-limit; i-- {
we := b.entries[i]
if we.isExpired() {
if err := tw.expiryWindowBucket.addExpiry(we); err != nil {
expiryCount++
logger.Error().Err(err).Str("context", "timeWindow.addExpiry")
}
// if id is expired it does not return an error but continue the iteration.
continue
}
winEntries = append(winEntries, we)
}
if len(winEntries) >= limit {
return true, nil
}
}
for i := len(b.entries[:b.entryIdx]) - 1; i >= 0; i-- {
we := b.entries[i]
if we.isExpired() {
if err := tw.expiryWindowBucket.addExpiry(we); err != nil {
expiryCount++
logger.Error().Err(err).Str("context", "timeWindow.addExpiry")
}
// if id is expired it does not return an error but continue the iteration.
continue
}
winEntries = append(winEntries, we)
}
if b.cutoff(cutoff) {
return true, nil
}
return false, nil
})
if err != nil {
return winEntries
}
return winEntries
}
func (b _WinBlock) validation(topicHash uint64) error {
if b.topicHash != topicHash {
return fmt.Errorf("timeWindow.write: validation failed block topicHash %d, topicHash %d", b.topicHash, topicHash)
}
return nil
}