-
Notifications
You must be signed in to change notification settings - Fork 7
/
range.go
467 lines (389 loc) · 9.85 KB
/
range.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
package cete
import (
"errors"
"reflect"
"sync"
"sync/atomic"
"github.com/1lann/msgpack"
)
const bufferSize = 100
type bufferEntry struct {
key string
data []byte
counter uint64
err error
}
// Range represents a result with multiple values in it and is usually sorted
// by index/key.
type Range struct {
buffer chan bufferEntry
next func() (string, []byte, uint64, error)
close func()
closed int32
lastEntry bufferEntry
table *Table
}
// Next retrieves the next item in the range, and returns true if the
// next item is successfully retrieved.
func (r *Range) Next() bool {
if r.lastEntry.err != nil {
return false
}
entry, more := <-r.buffer
if !more {
r.lastEntry.err = ErrEndOfRange
return false
}
r.lastEntry = entry
if entry.err != nil {
return false
}
return true
}
// Document returns the current item's Document representation.
func (r *Range) Document() Document {
return Document{
data: r.lastEntry.data,
table: r.table,
}
}
// Decode decodes the current item into a pointer.
func (r *Range) Decode(dst interface{}) error {
if r.table != nil && r.table.keyToCompressed != nil {
return msgpack.UnmarshalCompressed(r.table.cToKey, r.lastEntry.data,
dst)
}
return msgpack.Unmarshal(r.lastEntry.data, dst)
}
// Counter returns the counter of the current item.
func (r *Range) Counter() uint64 {
return r.lastEntry.counter
}
// Key returns the key of the current item.
func (r *Range) Key() string {
return r.lastEntry.key
}
// Error returns the last error causing Next to return false. It will be nil
// if Next returned true.
func (r *Range) Error() error {
return r.lastEntry.err
}
// All stores all of the results into slice dst provided by as a pointer.
// A nil error will be returned if the range reaches ErrEndOfRange.
func (r *Range) All(dst interface{}) error {
// Code baseed on github.com/GoRethink/gorethink's `Cursor.All`.
slicePtr := reflect.ValueOf(dst)
if slicePtr.Kind() != reflect.Ptr ||
slicePtr.Elem().Kind() != reflect.Slice {
return errors.New("cete: dst must be a pointer to a silce")
}
sliceValue := slicePtr.Elem()
sliceValue = sliceValue.Slice(0, sliceValue.Cap())
elemType := sliceValue.Type().Elem()
i := 0
compressed := r.table != nil && r.table.keyToCompressed != nil
defer func() {
slicePtr.Elem().Set(sliceValue.Slice(0, i))
}()
var err error
for {
entry, more := <-r.buffer
if !more {
return nil
}
if entry.err == ErrEndOfRange {
return nil
} else if entry.err != nil {
return entry.err
}
if sliceValue.Len() == i {
thisElem := reflect.New(elemType)
if compressed {
err = msgpack.UnmarshalCompressed(r.table.cToKey, entry.data,
thisElem.Interface())
} else {
err = msgpack.Unmarshal(entry.data, thisElem.Interface())
}
if err != nil {
return err
}
sliceValue = reflect.Append(sliceValue, thisElem.Elem())
sliceValue = sliceValue.Slice(0, sliceValue.Cap())
} else {
if compressed {
err = msgpack.UnmarshalCompressed(r.table.cToKey, entry.data,
sliceValue.Index(i).Addr().Interface())
} else {
err = msgpack.Unmarshal(entry.data,
sliceValue.Index(i).Addr().Interface())
}
if err != nil {
return err
}
}
i++
}
}
// Limit limits the number of documents that can be read from the range.
// When this limit is reached, ErrEndOfRange will be returned.
func (r *Range) Limit(n int64) *Range {
return newRange(func() (string, []byte, uint64, error) {
entry := <-r.buffer
if n <= 0 {
return "", nil, 0, ErrEndOfRange
}
n--
return entry.key, entry.data, entry.counter, entry.err
}, r.Close, r.table)
}
// Close closes the range. The range will automatically close upon the
// first encountered error.
func (r *Range) Close() {
if atomic.CompareAndSwapInt32(&r.closed, 0, 1) {
r.close()
}
}
func newRange(next func() (string, []byte, uint64, error), closer func(),
table *Table) *Range {
r := &Range{
buffer: make(chan bufferEntry, bufferSize),
next: next,
close: closer,
table: table,
}
go func() {
for {
key, data, counter, err := r.next()
// r.Close before sending to channel to prevent race condition
if err != nil {
r.Close()
}
r.buffer <- bufferEntry{key, data, counter, err}
if err != nil {
close(r.buffer)
return
}
}
}()
return r
}
// Filter applies a filter onto the range, skipping values where the provided
// filter returns false. If the filter returns a non-nil error, the range
// will be stopped, and the error will be returned.
//
// You can optionally specify the number of workers
// to concurrently operate the filter to speed up long running filter queries.
// Note that you will still be limited by the read speed, and having too many
// workers will increase concurrency overhead. The default number of workers
// is 5.
func (r *Range) Filter(filter func(doc Document) (bool, error),
workers ...int) *Range {
numWorkers := 5
if len(workers) > 0 && workers[0] != 0 {
numWorkers = workers[0]
}
inboxes := make([]chan *bufferEntry, numWorkers)
outboxes := make([]chan *bufferEntry, numWorkers)
for i := range inboxes {
inboxes[i] = make(chan *bufferEntry)
outboxes[i] = make(chan *bufferEntry)
go filterWorker(filter, r.table, inboxes[i], outboxes[i])
}
go func() {
sendToWorker := 0
for {
entry, more := <-r.buffer
if !more {
break
}
inboxes[sendToWorker] <- &entry
sendToWorker = (sendToWorker + 1) % numWorkers
}
for _, inbox := range inboxes {
close(inbox)
}
}()
readFromWorker := 0
var entry *bufferEntry
return newRange(func() (string, []byte, uint64, error) {
for {
entry = <-outboxes[readFromWorker]
readFromWorker = (readFromWorker + 1) % numWorkers
if entry.key == "" && entry.err == nil {
continue
}
if entry.err != nil {
r.Close()
}
return entry.key, entry.data, entry.counter, entry.err
}
}, r.Close, r.table)
}
func filterWorker(filter func(doc Document) (bool, error),
table *Table, inbox chan *bufferEntry, outbox chan *bufferEntry) {
var entry *bufferEntry
var ok bool
var err error
var more bool
for {
entry, more = <-inbox
if !more {
return
}
if entry.err != nil {
outbox <- entry
continue
}
ok, err = filter(Document{
data: entry.data,
table: table,
})
if err != nil {
entry.err = err
outbox <- entry
continue
}
if !ok {
entry.key = ""
}
outbox <- entry
}
}
// Do applies a operation onto the range concurrently. Order is not guaranteed.
// If the operation returns an error, Do will stop and return the error.
// An error with the operation may not stop Do immediately, as the range buffer
// must be exhausted first.
// Errors during the range will also be returned. A nil error will be returned
// if ErrEndOfRange is reached.
//
// You can optionally specify the number of workers to concurrently operate
// on. By default the number of workers is 10.
func (r *Range) Do(operation func(key string, counter uint64, doc Document) error,
workers ...int) error {
numWorkers := 10
if len(workers) > 0 && workers[0] != 0 {
numWorkers = workers[0]
}
wg := new(sync.WaitGroup)
wg.Add(numWorkers)
completion := make(chan error, numWorkers)
inboxes := make([]chan *bufferEntry, numWorkers)
for i := range inboxes {
inboxes[i] = make(chan *bufferEntry)
go doWorker(wg, operation, r.table, inboxes[i], completion)
}
go func() {
sendToWorker := 0
for {
entry, more := <-r.buffer
if !more {
break
}
inboxes[sendToWorker] <- &entry
sendToWorker = (sendToWorker + 1) % numWorkers
}
for _, inbox := range inboxes {
close(inbox)
}
}()
result := <-completion
if result == nil {
r.Close()
wg.Wait()
// Find errors
for {
select {
case err := <-completion:
if err != nil {
return err
}
default:
return nil
}
}
}
r.Close()
wg.Wait()
return result
}
func doWorker(wg *sync.WaitGroup, operation func(key string, counter uint64,
doc Document) error, table *Table, inbox chan *bufferEntry,
completion chan error) {
var entry *bufferEntry
var err error
var more bool
defer wg.Done()
for {
entry, more = <-inbox
if !more {
return
}
if entry.err == ErrEndOfRange {
completion <- nil
return
} else if entry.err != nil {
completion <- entry.err
return
}
err = operation(entry.key, entry.counter, Document{
data: entry.data,
table: table,
})
if err != nil {
completion <- err
return
}
}
}
// Skip skips a number of values from the range, and returns back
// the range. Any errors during skip will result in a range that
// only returns that error.
func (r *Range) Skip(n int) *Range {
var entry bufferEntry
for i := 0; i < n; i++ {
entry = <-r.buffer
if entry.err != nil {
return newRange(func() (string, []byte, uint64, error) {
return "", nil, 0, entry.err
}, func() {}, nil)
}
}
return r
}
// Count will count the number of elements in the range and consume the values
// in the range. If it reaches the end of the range, it will return the count
// with a nil error. If a non-nil error is encountered, it returns the
// current count and the error.
func (r *Range) Count() (int64, error) {
var count int64
var entry bufferEntry
for {
entry = <-r.buffer
if entry.err != nil {
if entry.err == ErrEndOfRange {
return count, nil
}
return count, entry.err
}
count++
}
}
// Unique will remove all duplicate entries from the range. It does this by
// saving all of the seen keys to a map. If there are a lot of unique keys,
// Unique may use a lot of memory.
func (r *Range) Unique() *Range {
var entry bufferEntry
seen := make(map[string]bool)
return newRange(func() (string, []byte, uint64, error) {
for {
entry = <-r.buffer
if entry.err != nil {
return entry.key, entry.data, entry.counter, entry.err
}
if !seen[entry.key] {
seen[entry.key] = true
return entry.key, entry.data, entry.counter, entry.err
}
}
}, r.Close, r.table)
}