-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathheads.go
206 lines (179 loc) · 4.4 KB
/
heads.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
package crdt
import (
"bytes"
"context"
"encoding/binary"
"errors"
"sort"
"strings"
"sync"
dshelp "github.com/ipfs/boxo/datastore/dshelp"
cid "github.com/ipfs/go-cid"
ds "github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/query"
logging "github.com/ipfs/go-log/v2"
)
// heads manages the current Merkle-CRDT heads.
type heads struct {
store ds.Datastore
// cache contains the current contents of the store
cache map[cid.Cid]uint64
cacheMux sync.RWMutex
namespace ds.Key
logger logging.StandardLogger
}
func newHeads(ctx context.Context, store ds.Datastore, namespace ds.Key, logger logging.StandardLogger) (*heads, error) {
hh := &heads{
store: store,
namespace: namespace,
logger: logger,
cache: make(map[cid.Cid]uint64),
}
if err := hh.primeCache(ctx); err != nil {
return nil, err
}
return hh, nil
}
func (hh *heads) key(c cid.Cid) ds.Key {
// /<namespace>/<cid>
return hh.namespace.Child(dshelp.MultihashToDsKey(c.Hash()))
}
func (hh *heads) write(ctx context.Context, store ds.Write, c cid.Cid, height uint64) error {
buf := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(buf, height)
if n == 0 {
return errors.New("error encoding height")
}
return store.Put(ctx, hh.key(c), buf[0:n])
}
func (hh *heads) delete(ctx context.Context, store ds.Write, c cid.Cid) error {
err := store.Delete(ctx, hh.key(c))
// The go-datastore API currently says Delete doesn't return
// ErrNotFound, but it used to say otherwise. Leave this
// here to be safe.
if err == ds.ErrNotFound {
return nil
}
return err
}
// IsHead returns if a given cid is among the current heads.
func (hh *heads) IsHead(ctx context.Context, c cid.Cid) (bool, uint64, error) {
var height uint64
var ok bool
hh.cacheMux.RLock()
{
height, ok = hh.cache[c]
}
hh.cacheMux.RUnlock()
return ok, height, nil
}
func (hh *heads) Len(ctx context.Context) (int, error) {
var ret int
hh.cacheMux.RLock()
{
ret = len(hh.cache)
}
hh.cacheMux.RUnlock()
return ret, nil
}
// Replace replaces a head with a new cid.
func (hh *heads) Replace(ctx context.Context, h, c cid.Cid, height uint64) error {
hh.logger.Debugf("replacing DAG head: %s -> %s (new height: %d)", h, c, height)
var store ds.Write = hh.store
batchingDs, batching := store.(ds.Batching)
var err error
if batching {
store, err = batchingDs.Batch(ctx)
if err != nil {
return err
}
}
err = hh.write(ctx, store, c, height)
if err != nil {
return err
}
hh.cacheMux.Lock()
defer hh.cacheMux.Unlock()
if !batching {
hh.cache[c] = height
}
err = hh.delete(ctx, store, h)
if err != nil {
return err
}
if !batching {
delete(hh.cache, h)
}
if batching {
err := store.(ds.Batch).Commit(ctx)
if err != nil {
return err
}
delete(hh.cache, h)
hh.cache[c] = height
}
return nil
}
func (hh *heads) Add(ctx context.Context, c cid.Cid, height uint64) error {
hh.logger.Debugf("adding new DAG head: %s (height: %d)", c, height)
if err := hh.write(ctx, hh.store, c, height); err != nil {
return err
}
hh.cacheMux.Lock()
{
hh.cache[c] = height
}
hh.cacheMux.Unlock()
return nil
}
// List returns the list of current heads plus the max height.
func (hh *heads) List(ctx context.Context) ([]cid.Cid, uint64, error) {
var maxHeight uint64
var heads []cid.Cid
hh.cacheMux.RLock()
{
heads = make([]cid.Cid, 0, len(hh.cache))
for head, height := range hh.cache {
heads = append(heads, head)
if height > maxHeight {
maxHeight = height
}
}
}
hh.cacheMux.RUnlock()
sort.Slice(heads, func(i, j int) bool {
ci := heads[i].Bytes()
cj := heads[j].Bytes()
return bytes.Compare(ci, cj) < 0
})
return heads, maxHeight, nil
}
// primeCache builds the heads cache based on what's in storage; since
// it is called from the constructor only we don't bother locking.
func (hh *heads) primeCache(ctx context.Context) (ret error) {
q := query.Query{
Prefix: hh.namespace.String(),
KeysOnly: false,
}
results, err := hh.store.Query(ctx, q)
if err != nil {
return err
}
defer results.Close()
for r := range results.Next() {
if r.Error != nil {
return r.Error
}
headKey := ds.NewKey(strings.TrimPrefix(r.Key, hh.namespace.String()))
headCid, err := dshelp.DsKeyToCidV1(headKey, cid.DagProtobuf)
if err != nil {
return err
}
height, n := binary.Uvarint(r.Value)
if n <= 0 {
return errors.New("error decoding height")
}
hh.cache[headCid] = height
}
return nil
}