-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnapshot.go
More file actions
120 lines (92 loc) · 2.44 KB
/
snapshot.go
File metadata and controls
120 lines (92 loc) · 2.44 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
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
package eventstore
import (
"sync"
"sync/atomic"
"github.com/cockroachdb/pebble"
)
type SnapshotRequest struct {
Sequence uint64
Store *Store
Data []byte
Batch *pebble.Batch
}
var snapshotRequestPool = sync.Pool{
New: func() interface{} {
return NewSnapshotRequest()
},
}
func NewSnapshotRequest() *SnapshotRequest {
return &SnapshotRequest{}
}
func (request *SnapshotRequest) Get(collection []byte, key []byte) ([]byte, error) {
snapshotKey := genSnapshotKey(
collection,
key,
)
value, closer, err := request.Store.cfSnapshot.Get(request.Batch, snapshotKey)
if err != nil {
if err == pebble.ErrNotFound {
return nil, ErrRecordNotFound
}
return nil, err
}
data := make([]byte, len(value))
copy(data, value)
closer.Close()
return data, nil
}
func (request *SnapshotRequest) Upsert(collection []byte, key []byte, value []byte, fn func([]byte, []byte) []byte) error {
snapshotKey := genSnapshotKey(
collection,
key,
)
oldValue, closer, err := request.Store.cfSnapshot.Get(request.Batch, snapshotKey)
if err != nil {
if err != pebble.ErrNotFound {
return err
}
// New record, it should update snapshot states
request.Store.state.snapshotCount.Increase(1)
err = request.Store.state.syncSnapshotCount(request.Store, request.Batch)
if err != nil {
return err
}
}
if closer != nil {
defer closer.Close()
}
err = request.Store.cfSnapshot.Write(request.Batch, snapshotKey, fn(oldValue, value))
if err != nil {
return err
}
// Update snapshot state
err = request.updateDurableState(request.Batch, collection)
if err != nil {
return err
}
return nil
}
func (request *SnapshotRequest) updateDurableState(b *pebble.Batch, collection []byte) error {
// Update snapshot state
return request.Store.SetStateUint64(b, []byte("snapshot"), collection, []byte("lastSeq"), request.Sequence)
}
func (request *SnapshotRequest) UpdateDurableState(b *pebble.Batch, collection []byte) error {
return request.updateDurableState(b, collection)
}
func (request *SnapshotRequest) Delete(collection []byte, key []byte) error {
snapshotKey := genSnapshotKey(
collection,
key,
)
err := request.Store.cfSnapshot.Delete(request.Batch, snapshotKey)
if err != nil {
return err
}
// Update snapshot states
atomic.AddUint64((*uint64)(&request.Store.state.snapshotCount), ^uint64(0))
err = request.Store.state.syncSnapshotCount(request.Store, request.Batch)
if err != nil {
return err
}
return nil
}