-
Notifications
You must be signed in to change notification settings - Fork 177
/
collection.go
426 lines (361 loc) · 10.2 KB
/
collection.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
package state
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"runtime"
"github.com/fxamacker/cbor/v2"
"github.com/onflow/atree"
)
const (
storageIDSize = 16
)
// CollectionProvider provides access to collections
type CollectionProvider struct {
rootAddr atree.Address
storage *atree.PersistentSlabStorage
}
// NewCollectionProvider constructs a new CollectionProvider
func NewCollectionProvider(
rootAddr atree.Address,
ledger atree.Ledger,
) (*CollectionProvider, error) {
// empty address is not allowed (causes issues with atree)
if rootAddr == atree.AddressUndefined {
return nil, fmt.Errorf("empty address as root is not allowed")
}
baseStorage := atree.NewLedgerBaseStorage(ledger)
storage, err := NewPersistentSlabStorage(baseStorage)
return &CollectionProvider{
rootAddr: rootAddr,
storage: storage,
}, err
}
// CollectionByID returns the collection by collection ID
//
// if no collection is found with that collection id, it return error
// Warning: this method should only used only once for each collection and
// the returned pointer should be kept for the future.
// calling twice for the same collection might result in odd-behaviours
// currently collection provider doesn't do any internal caching to protect aginast these cases
func (cp *CollectionProvider) CollectionByID(collectionID []byte) (*Collection, error) {
storageID, err := atree.NewStorageIDFromRawBytes(collectionID)
if err != nil {
return nil, err
}
// sanity check the storage ID address
if storageID.Address != cp.rootAddr {
return nil, fmt.Errorf("root address mismatch %x != %x", storageID.Address, cp.rootAddr)
}
omap, err := atree.NewMapWithRootID(cp.storage, storageID, atree.NewDefaultDigesterBuilder())
if err != nil {
return nil, err
}
return &Collection{
omap: omap,
storage: cp.storage,
collectionID: collectionID,
}, nil
}
// NewCollection constructs a new collection
func (cp *CollectionProvider) NewCollection() (*Collection, error) {
omap, err := atree.NewMap(cp.storage, cp.rootAddr, atree.NewDefaultDigesterBuilder(), emptyTypeInfo{})
if err != nil {
return nil, err
}
storageIDBytes := make([]byte, storageIDSize)
_, err = omap.StorageID().ToRawBytes(storageIDBytes)
if err != nil {
return nil, err
}
return &Collection{
storage: cp.storage,
omap: omap,
collectionID: storageIDBytes, // we reuse the storageID bytes as collectionID
}, nil
}
// Commit commits all changes to the collections with changes
func (cp *CollectionProvider) Commit() error {
return cp.storage.FastCommit(runtime.NumCPU())
}
// Collection provides a persistent and compact way of storing key/value pairs
// each collection has a unique collectionID that can be used to fetch the collection
//
// TODO(ramtin): we might not need any extra hashing on the atree side
// and optimize this to just use the key given the keys are hashed ?
type Collection struct {
omap *atree.OrderedMap
storage *atree.PersistentSlabStorage
collectionID []byte
}
// CollectionID returns the unique id for the collection
func (c *Collection) CollectionID() []byte {
return c.collectionID
}
// Get gets the value for the given key
//
// if key doesn't exist it returns nil (no error)
func (c *Collection) Get(key []byte) ([]byte, error) {
data, err := c.omap.Get(compare, hashInputProvider, NewByteStringValue(key))
if err != nil {
var keyNotFoundError *atree.KeyNotFoundError
if errors.As(err, &keyNotFoundError) {
return nil, nil
}
return nil, err
}
value, err := data.StoredValue(c.omap.Storage)
if err != nil {
return nil, err
}
return value.(ByteStringValue).Bytes(), nil
}
// Set sets the value for the given key
//
// if a value already stored at the given key it replaces the value
func (c *Collection) Set(key, value []byte) error {
existingValueStorable, err := c.omap.Set(compare, hashInputProvider, NewByteStringValue(key), NewByteStringValue(value))
if err != nil {
return err
}
if id, ok := existingValueStorable.(atree.StorageIDStorable); ok {
// NOTE: deep remove isn't necessary because value is ByteStringValue (not container)
err := c.storage.Remove(atree.StorageID(id))
if err != nil {
return err
}
}
return nil
}
// Remove removes a key from the collection
//
// if the key doesn't exist it return no error
func (c *Collection) Remove(key []byte) error {
_, existingValueStorable, err := c.omap.Remove(compare, hashInputProvider, NewByteStringValue(key))
if err != nil {
var keyNotFoundError *atree.KeyNotFoundError
if errors.As(err, &keyNotFoundError) {
return nil
}
return err
}
if id, ok := existingValueStorable.(atree.StorageIDStorable); ok {
// NOTE: deep remove isn't necessary because value is ByteStringValue (not container)
err := c.storage.Remove(atree.StorageID(id))
if err != nil {
return err
}
}
return nil
}
// Destroy destroys the whole collection
func (c *Collection) Destroy() ([][]byte, error) {
var cachedErr error
keys := make([][]byte, c.omap.Count())
i := 0
err := c.omap.PopIterate(func(keyStorable atree.Storable, valueStorable atree.Storable) {
if id, ok := valueStorable.(atree.StorageIDStorable); ok {
err := c.storage.Remove(atree.StorageID(id))
if err != nil && cachedErr == nil {
cachedErr = err
}
}
key, err := keyStorable.StoredValue(c.omap.Storage)
if err != nil && cachedErr == nil {
cachedErr = err
}
keys[i] = key.(ByteStringValue).Bytes()
i++
})
if cachedErr != nil {
return keys, cachedErr
}
if err != nil {
return keys, err
}
return keys, c.storage.Remove(c.omap.StorageID())
}
type ByteStringValue struct {
data []byte
size uint32
}
var _ atree.Value = &ByteStringValue{}
var _ atree.Storable = &ByteStringValue{}
func NewByteStringValue(data []byte) ByteStringValue {
size := atree.GetUintCBORSize(uint64(len(data))) + uint32(len(data))
return ByteStringValue{data: data, size: size}
}
func (v ByteStringValue) ChildStorables() []atree.Storable {
return nil
}
func (v ByteStringValue) StoredValue(_ atree.SlabStorage) (atree.Value, error) {
return v, nil
}
func (v ByteStringValue) Storable(storage atree.SlabStorage, address atree.Address, maxInlineSize uint64) (atree.Storable, error) {
if uint64(v.ByteSize()) <= maxInlineSize {
return v, nil
}
// Create StorableSlab
id, err := storage.GenerateStorageID(address)
if err != nil {
return nil, err
}
slab := &atree.StorableSlab{
StorageID: id,
Storable: v,
}
// Store StorableSlab in storage
err = storage.Store(id, slab)
if err != nil {
return nil, err
}
// Return storage id as storable
return atree.StorageIDStorable(id), nil
}
func (v ByteStringValue) Encode(enc *atree.Encoder) error {
return enc.CBOR.EncodeBytes(v.data)
}
func (v ByteStringValue) getHashInput(scratch []byte) ([]byte, error) {
const cborTypeByteString = 0x40
buf := scratch
if uint32(len(buf)) < v.size {
buf = make([]byte, v.size)
} else {
buf = buf[:v.size]
}
slen := len(v.data)
if slen <= 23 {
buf[0] = cborTypeByteString | byte(slen)
copy(buf[1:], v.data)
return buf, nil
}
if slen <= math.MaxUint8 {
buf[0] = cborTypeByteString | byte(24)
buf[1] = byte(slen)
copy(buf[2:], v.data)
return buf, nil
}
if slen <= math.MaxUint16 {
buf[0] = cborTypeByteString | byte(25)
binary.BigEndian.PutUint16(buf[1:], uint16(slen))
copy(buf[3:], v.data)
return buf, nil
}
if slen <= math.MaxUint32 {
buf[0] = cborTypeByteString | byte(26)
binary.BigEndian.PutUint32(buf[1:], uint32(slen))
copy(buf[5:], v.data)
return buf, nil
}
buf[0] = cborTypeByteString | byte(27)
binary.BigEndian.PutUint64(buf[1:], uint64(slen))
copy(buf[9:], v.data)
return buf, nil
}
func (v ByteStringValue) ByteSize() uint32 {
return v.size
}
func (v ByteStringValue) String() string {
return string(v.data)
}
func (v ByteStringValue) Bytes() []byte {
return v.data
}
func decodeStorable(dec *cbor.StreamDecoder, _ atree.StorageID) (atree.Storable, error) {
t, err := dec.NextType()
if err != nil {
return nil, err
}
switch t {
case cbor.ByteStringType:
s, err := dec.DecodeBytes()
if err != nil {
return nil, err
}
return NewByteStringValue(s), nil
case cbor.TagType:
tagNumber, err := dec.DecodeTagNumber()
if err != nil {
return nil, err
}
switch tagNumber {
case atree.CBORTagStorageID:
return atree.DecodeStorageIDStorable(dec)
default:
return nil, fmt.Errorf("invalid tag number %d", tagNumber)
}
default:
return nil, fmt.Errorf("invalid cbor type %s for storable", t)
}
}
func compare(storage atree.SlabStorage, value atree.Value, storable atree.Storable) (bool, error) {
switch v := value.(type) {
case ByteStringValue:
other, ok := storable.(ByteStringValue)
if ok {
return bytes.Equal(other.data, v.data), nil
}
// Retrieve value from storage
otherValue, err := storable.StoredValue(storage)
if err != nil {
return false, err
}
other, ok = otherValue.(ByteStringValue)
if ok {
return bytes.Equal(other.data, v.data), nil
}
return false, nil
}
return false, fmt.Errorf("value %T not supported for comparison", value)
}
func hashInputProvider(value atree.Value, buffer []byte) ([]byte, error) {
switch v := value.(type) {
case ByteStringValue:
return v.getHashInput(buffer)
}
return nil, fmt.Errorf("value %T not supported for hash input", value)
}
func NewPersistentSlabStorage(baseStorage atree.BaseStorage) (*atree.PersistentSlabStorage, error) {
encMode, err := cbor.EncOptions{}.EncMode()
if err != nil {
return nil, err
}
decMode, err := cbor.DecOptions{}.DecMode()
if err != nil {
return nil, err
}
return atree.NewPersistentSlabStorage(
baseStorage,
encMode,
decMode,
decodeStorable,
decodeTypeInfo,
), nil
}
type emptyTypeInfo struct{}
var _ atree.TypeInfo = emptyTypeInfo{}
func (emptyTypeInfo) Encode(e *cbor.StreamEncoder) error {
return e.EncodeNil()
}
func (i emptyTypeInfo) Equal(other atree.TypeInfo) bool {
_, ok := other.(emptyTypeInfo)
return ok
}
func decodeTypeInfo(dec *cbor.StreamDecoder) (atree.TypeInfo, error) {
ty, err := dec.NextType()
if err != nil {
return nil, err
}
switch ty {
case cbor.NilType:
err := dec.DecodeNil()
if err != nil {
return nil, err
}
return emptyTypeInfo{}, nil
default:
}
return nil, fmt.Errorf("not supported type info")
}