-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhelpers.go
83 lines (67 loc) · 1.68 KB
/
helpers.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
package gpq
import (
"sync"
"github.com/JustinTimperio/gpq/disk"
"github.com/JustinTimperio/gpq/schema"
)
type batchHandler[T any] struct {
mux *sync.Mutex
syncedBatches map[uint]bool
deletedBatches map[uint]bool
diskCache *disk.Disk[T]
}
func newBatchHandler[T any](diskCache *disk.Disk[T]) *batchHandler[T] {
return &batchHandler[T]{
mux: &sync.Mutex{},
syncedBatches: make(map[uint]bool),
deletedBatches: make(map[uint]bool),
diskCache: diskCache,
}
}
func (bh *batchHandler[T]) processBatch(batch []*schema.Item[T], batchNumber uint) {
bh.mux.Lock()
defer bh.mux.Unlock()
deleted, ok := bh.deletedBatches[batchNumber]
if !ok || (ok && !deleted) {
bh.diskCache.ProcessBatch(batch)
}
bh.syncedBatches[batchNumber] = true
bh.deletedBatches[batchNumber] = false
}
func (bh *batchHandler[T]) deleteBatch(batch []*schema.DeleteMessage, batchNumber uint, wasRestored bool) {
bh.mux.Lock()
defer bh.mux.Unlock()
if wasRestored {
bh.diskCache.DeleteBatch(batch)
return
}
bh.syncedBatches[batchNumber] = false
bh.deletedBatches[batchNumber] = true
if _, ok := bh.syncedBatches[batchNumber]; ok {
bh.diskCache.DeleteBatch(batch)
return
}
}
type batchCounter struct {
mux *sync.Mutex
batchNumber uint
batchCounter uint
batchSize uint
}
func newBatchCounter(batchSize uint) *batchCounter {
return &batchCounter{
mux: &sync.Mutex{},
batchNumber: 0,
batchCounter: 0,
batchSize: batchSize,
}
}
func (bc *batchCounter) increment() (batchNumber uint) {
bc.mux.Lock()
defer bc.mux.Unlock()
if (bc.batchCounter % bc.batchSize) == 0 {
bc.batchNumber++
}
bc.batchCounter++
return bc.batchNumber
}