-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhelpers.go
More file actions
86 lines (71 loc) · 1.88 KB
/
helpers.go
File metadata and controls
86 lines (71 loc) · 1.88 KB
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
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
}
// Check if this batch was already synced to disk
if alreadySynced, ok := bh.syncedBatches[batchNumber]; ok && alreadySynced {
// Batch is on disk, safe to delete
bh.diskCache.DeleteBatch(batch)
delete(bh.syncedBatches, batchNumber)
delete(bh.deletedBatches, batchNumber)
return
}
// Batch not synced yet, just mark for deletion
bh.deletedBatches[batchNumber] = true
}
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
}