~tsileo/blobstash

ref: b178995e346d blobstash/pkg/vkv/vkv.go -rw-r--r-- 7.3 KiB
b178995eThomas Sileo vendor: update deps 2 years ago
                                                                                
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
package vkv // import "a4.io/blobstash/pkg/vkv"

import (
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"strconv"
	"time"

	"github.com/vmihailenco/msgpack"

	"a4.io/blobstash/pkg/rangedb"
)

const schemaVersion = 1

const (
	Sep              = ':'
	FlagUnknown byte = iota
	FlagMetaBlob
	FlagVersion
	FlagKey
)

// KvType for meta serialization
const KvType = "kv"

var ErrNotFound = errors.New("vkv: key not found")

type KeyValue struct {
	SchemaVersion int `msgpack:"_v"`

	Key     string `msgpack:"k,omitempty"`
	Version int64  `msgpack:"v"`
	Hash    []byte `msgpack:"h,omitempty"`
	Data    []byte `msgpack:"d,omitempty"`
}

// Implements the `MetaData` interface
func (kv *KeyValue) Type() string {
	return KvType
}

// Implements the `MetaData` interface
func (kv *KeyValue) Dump() ([]byte, error) {
	kv.SchemaVersion = schemaVersion
	return msgpack.Marshal(kv)
}

func (kv *KeyValue) SetHexHash(h string) error {
	hash, err := hex.DecodeString(h)
	if err != nil {
		return err
	}
	kv.Hash = hash
	return nil
}

func (kv *KeyValue) HexHash() string {
	if kv.Hash != nil && len(kv.Hash) > 0 {
		return hex.EncodeToString(kv.Hash)
	}
	return ""
}

// KeyValueVersions holds the full history for a key value pair
type KeyValueVersions struct {
	Key string `json:"key"`

	// FIXME(tsileo): turn this into a []*VkvEntry
	Versions []*KeyValue `json:"versions"`
}

func NextVersionCursor(key string) string {
	v, err := strconv.ParseInt(key, 10, 0)
	if err != nil {
		panic(fmt.Errorf("should never happen, key=%s", key))
	}
	return strconv.FormatInt(v-1, 10)
}

// NextKey returns the next key for lexigraphical (key = NextKey(lastkey))
func NextKey(key string) string {
	bkey := []byte(key)
	i := len(bkey)
	for i > 0 {
		i--
		bkey[i]++
		if bkey[i] != 0 {
			break
		}
	}
	return string(bkey)
}

// PextKey returns the next key for lexigraphical (key = PextKey(lastkey))
func PrevKey(key string) string {
	bkey := []byte(key)
	i := len(bkey)
	for i > 0 {
		i--
		bkey[i]--
		if bkey[i] != 255 {
			break
		}
	}
	return string(bkey)
}

type DB struct {
	rdb *rangedb.RangeDB
}

// New creates a new database.
func New(path string) (*DB, error) {
	rdb, err := rangedb.New(path)
	if err != nil {
		return nil, err
	}
	return &DB{rdb: rdb}, nil
}

func (db *DB) Close() error { return db.rdb.Close() }

func (db *DB) Destroy() error { return db.rdb.Destroy() }

func (db *DB) Get(key string, version int64) (*KeyValue, error) {
	if version <= 0 {
		return db.get(key)
	}
	return db.getAt(key, version)
}

func (db *DB) get(key string) (*KeyValue, error) {
	kvkey := append([]byte{FlagKey}, []byte(key)...)
	data, err := db.rdb.Get(kvkey)
	if err != nil {
		return nil, err
	}
	if data == nil || len(data) == 0 {
		return nil, ErrNotFound
	}

	res := &KeyValue{Key: key}
	if err := msgpack.Unmarshal(data, res); err != nil {
		return nil, err
	}

	return res, nil
}

func (db *DB) Put(kv *KeyValue) error {
	kv.SchemaVersion = schemaVersion

	if kv.Version < 1 {
		kv.Version = time.Now().UTC().UnixNano()
	}

	encoded, err := kv.Dump()
	if err != nil {
		return err
	}

	// Set the regular key
	kvkey := append([]byte{FlagKey}, []byte(kv.Key)...)

	// But only if it's the latest version (or there's no previous version)
	ckv, err := db.get(kv.Key)
	if err != nil && err != ErrNotFound {
		return err
	}

	if ckv == nil || kv.Version > ckv.Version {
		if err := db.rdb.Set(kvkey, encoded); err != nil {
			return err
		}
	}

	// Set the version key (for keeping track of all the versions)
	vkey := buildVkey(kvkey, kv.Version)
	if err := db.rdb.Set(vkey, encoded); err != nil {
		return err
	}

	return nil
}

func buildVkey(kvkey []byte, version int64) []byte {
	klen := len(kvkey) - 1
	vkey := make([]byte, klen+10)

	// Set the version flag
	vkey[0] = FlagVersion

	// Copy the key
	copy(vkey[1:], kvkey[1:])

	// Add separator
	vkey[klen+1] = Sep

	// Add the binary encoded version
	binary.BigEndian.PutUint64(vkey[klen+2:], uint64(version))

	return vkey
}

func buildMetaBlobKey(key []byte, version int64) []byte {
	klen := len(key)
	vkey := make([]byte, klen+10)

	// Set the version flag
	vkey[0] = FlagMetaBlob

	// Copy the key
	copy(vkey[1:], key[:])

	// Add separator
	vkey[klen+1] = Sep

	// Add the binary encoded version
	binary.BigEndian.PutUint64(vkey[klen+2:], uint64(version))

	return vkey
}

func (db *DB) SetMetaBlob(key string, version int64, hash string) error {
	vkey := buildMetaBlobKey([]byte(key), version)

	h, err := hex.DecodeString(hash)
	if err != nil {
		return err
	}

	if err := db.rdb.Set(vkey, h); err != nil {
		return err
	}

	return nil
}

func (db *DB) GetMetaBlob(key string, version int64) (string, error) {
	if version <= 0 {
		return "", fmt.Errorf("a valid version must be specified")
	}

	vkey := buildMetaBlobKey([]byte(key), version)

	data, err := db.rdb.Get(vkey)
	if err != nil {
		return "", err
	}

	if data != nil && len(data) > 0 {
		return hex.EncodeToString(data), nil
	}

	return "", nil
}

func (db *DB) getAt(key string, version int64) (*KeyValue, error) {
	kvkey := append([]byte{FlagKey}, []byte(key)...)
	vkey := buildVkey(kvkey, version)
	data, err := db.rdb.Get(vkey)
	if err != nil {
		return nil, err
	}
	if data == nil || len(data) == 0 {
		return nil, ErrNotFound
	}

	res := &KeyValue{Key: key}
	if err := msgpack.Unmarshal(data, res); err != nil {
		return nil, err
	}

	return res, nil
}

func (db *DB) keys(start, end string, limit int, reverse bool) ([]*KeyValue, string, error) {
	var cursor string
	out := []*KeyValue{}

	c := db.rdb.Range(append([]byte{FlagKey}, []byte(start)...), append([]byte{FlagKey}, []byte(end)...), reverse)
	defer c.Close()

	// Iterate the range
	k, v, err := c.Next()
	for ; err == nil && (limit <= 0 || len(out) < limit); k, v, err = c.Next() {
		res := &KeyValue{Key: string(k[1:])}
		if err := msgpack.Unmarshal(v, res); err != nil {
			return nil, cursor, err
		}

		out = append(out, res)
	}

	if len(out) > 0 {
		// Generate next cursor
		rcursor := out[len(out)-1].Key
		if reverse {
			cursor = PrevKey(rcursor)
		} else {
			cursor = NextKey(rcursor)
		}
	}

	// Return
	if err == io.EOF {
		return out, cursor, nil
	}

	return out, cursor, nil

}

func (db *DB) Keys(start, end string, limit int) ([]*KeyValue, string, error) {
	return db.keys(start, end, limit, false)
}

func (db *DB) ReverseKeys(start, end string, limit int) ([]*KeyValue, string, error) {
	return db.keys(start, end, limit, true)
}

func (db *DB) Versions(key string, start, end int64, limit int) (*KeyValueVersions, int64, error) {
	var nstart int64
	res := &KeyValueVersions{
		Key:      key,
		Versions: []*KeyValue{},
	}
	if end <= 0 {
		end = time.Now().UTC().UnixNano()
	}

	kvkey := append([]byte{FlagKey}, []byte(key)...)
	rstart := buildVkey(kvkey, start)
	rend := buildVkey(kvkey, end)
	c := db.rdb.Range(rstart, rend, true)
	defer c.Close()

	// Iterate the range
	_, v, err := c.Next()
	for ; err == nil && (limit <= 0 || len(res.Versions) < limit); _, v, err = c.Next() {
		kv := &KeyValue{Key: key}
		if err := msgpack.Unmarshal(v, kv); err != nil {
			return nil, nstart, err
		}

		res.Versions = append(res.Versions, kv)

		nstart = kv.Version - 1
	}

	if len(res.Versions) == 0 {
		return nil, nstart, ErrNotFound
	}
	return res, nstart, nil
}

func UnserializeBlob(blob []byte) (*KeyValue, error) {
	kv := &KeyValue{}
	if err := msgpack.Unmarshal(blob, kv); err != nil {
		return nil, err
	}
	return kv, nil
}