aboutsummaryrefslogtreecommitdiffstats
path: root/swarm/shed/index_test.go
blob: ba82216dfeb9c5c0b0bd5c8835e68e299a498f80 (plain) (blame)
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
// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package shed

import (
    "bytes"
    "encoding/binary"
    "fmt"
    "sort"
    "testing"
    "time"

    "github.com/syndtr/goleveldb/leveldb"
)

// Index functions for the index that is used in tests in this file.
var retrievalIndexFuncs = IndexFuncs{
    EncodeKey: func(fields IndexItem) (key []byte, err error) {
        return fields.Address, nil
    },
    DecodeKey: func(key []byte) (e IndexItem, err error) {
        e.Address = key
        return e, nil
    },
    EncodeValue: func(fields IndexItem) (value []byte, err error) {
        b := make([]byte, 8)
        binary.BigEndian.PutUint64(b, uint64(fields.StoreTimestamp))
        value = append(b, fields.Data...)
        return value, nil
    },
    DecodeValue: func(value []byte) (e IndexItem, err error) {
        e.StoreTimestamp = int64(binary.BigEndian.Uint64(value[:8]))
        e.Data = value[8:]
        return e, nil
    },
}

// TestIndex validates put, get and delete functions of the Index implementation.
func TestIndex(t *testing.T) {
    db, cleanupFunc := newTestDB(t)
    defer cleanupFunc()

    index, err := db.NewIndex("retrieval", retrievalIndexFuncs)
    if err != nil {
        t.Fatal(err)
    }

    t.Run("put", func(t *testing.T) {
        want := IndexItem{
            Address:        []byte("put-hash"),
            Data:           []byte("DATA"),
            StoreTimestamp: time.Now().UTC().UnixNano(),
        }

        err := index.Put(want)
        if err != nil {
            t.Fatal(err)
        }
        got, err := index.Get(IndexItem{
            Address: want.Address,
        })
        if err != nil {
            t.Fatal(err)
        }
        checkIndexItem(t, got, want)

        t.Run("overwrite", func(t *testing.T) {
            want := IndexItem{
                Address:        []byte("put-hash"),
                Data:           []byte("New DATA"),
                StoreTimestamp: time.Now().UTC().UnixNano(),
            }

            err = index.Put(want)
            if err != nil {
                t.Fatal(err)
            }
            got, err := index.Get(IndexItem{
                Address: want.Address,
            })
            if err != nil {
                t.Fatal(err)
            }
            checkIndexItem(t, got, want)
        })
    })

    t.Run("put in batch", func(t *testing.T) {
        want := IndexItem{
            Address:        []byte("put-in-batch-hash"),
            Data:           []byte("DATA"),
            StoreTimestamp: time.Now().UTC().UnixNano(),
        }

        batch := new(leveldb.Batch)
        index.PutInBatch(batch, want)
        err := db.WriteBatch(batch)
        if err != nil {
            t.Fatal(err)
        }
        got, err := index.Get(IndexItem{
            Address: want.Address,
        })
        if err != nil {
            t.Fatal(err)
        }
        checkIndexItem(t, got, want)

        t.Run("overwrite", func(t *testing.T) {
            want := IndexItem{
                Address:        []byte("put-in-batch-hash"),
                Data:           []byte("New DATA"),
                StoreTimestamp: time.Now().UTC().UnixNano(),
            }

            batch := new(leveldb.Batch)
            index.PutInBatch(batch, want)
            db.WriteBatch(batch)
            if err != nil {
                t.Fatal(err)
            }
            got, err := index.Get(IndexItem{
                Address: want.Address,
            })
            if err != nil {
                t.Fatal(err)
            }
            checkIndexItem(t, got, want)
        })
    })

    t.Run("put in batch twice", func(t *testing.T) {
        // ensure that the last item of items with the same db keys
        // is actually saved
        batch := new(leveldb.Batch)
        address := []byte("put-in-batch-twice-hash")

        // put the first item
        index.PutInBatch(batch, IndexItem{
            Address:        address,
            Data:           []byte("DATA"),
            StoreTimestamp: time.Now().UTC().UnixNano(),
        })

        want := IndexItem{
            Address:        address,
            Data:           []byte("New DATA"),
            StoreTimestamp: time.Now().UTC().UnixNano(),
        }
        // then put the item that will produce the same key
        // but different value in the database
        index.PutInBatch(batch, want)
        db.WriteBatch(batch)
        if err != nil {
            t.Fatal(err)
        }
        got, err := index.Get(IndexItem{
            Address: address,
        })
        if err != nil {
            t.Fatal(err)
        }
        checkIndexItem(t, got, want)
    })

    t.Run("delete", func(t *testing.T) {
        want := IndexItem{
            Address:        []byte("delete-hash"),
            Data:           []byte("DATA"),
            StoreTimestamp: time.Now().UTC().UnixNano(),
        }

        err := index.Put(want)
        if err != nil {
            t.Fatal(err)
        }
        got, err := index.Get(IndexItem{
            Address: want.Address,
        })
        if err != nil {
            t.Fatal(err)
        }
        checkIndexItem(t, got, want)

        err = index.Delete(IndexItem{
            Address: want.Address,
        })
        if err != nil {
            t.Fatal(err)
        }

        wantErr := leveldb.ErrNotFound
        got, err = index.Get(IndexItem{
            Address: want.Address,
        })
        if err != wantErr {
            t.Fatalf("got error %v, want %v", err, wantErr)
        }
    })

    t.Run("delete in batch", func(t *testing.T) {
        want := IndexItem{
            Address:        []byte("delete-in-batch-hash"),
            Data:           []byte("DATA"),
            StoreTimestamp: time.Now().UTC().UnixNano(),
        }

        err := index.Put(want)
        if err != nil {
            t.Fatal(err)
        }
        got, err := index.Get(IndexItem{
            Address: want.Address,
        })
        if err != nil {
            t.Fatal(err)
        }
        checkIndexItem(t, got, want)

        batch := new(leveldb.Batch)
        index.DeleteInBatch(batch, IndexItem{
            Address: want.Address,
        })
        err = db.WriteBatch(batch)
        if err != nil {
            t.Fatal(err)
        }

        wantErr := leveldb.ErrNotFound
        got, err = index.Get(IndexItem{
            Address: want.Address,
        })
        if err != wantErr {
            t.Fatalf("got error %v, want %v", err, wantErr)
        }
    })
}

// TestIndex_iterate validates index iterator functions for correctness.
func TestIndex_iterate(t *testing.T) {
    db, cleanupFunc := newTestDB(t)
    defer cleanupFunc()

    index, err := db.NewIndex("retrieval", retrievalIndexFuncs)
    if err != nil {
        t.Fatal(err)
    }

    items := []IndexItem{
        {
            Address: []byte("iterate-hash-01"),
            Data:    []byte("data80"),
        },
        {
            Address: []byte("iterate-hash-03"),
            Data:    []byte("data22"),
        },
        {
            Address: []byte("iterate-hash-05"),
            Data:    []byte("data41"),
        },
        {
            Address: []byte("iterate-hash-02"),
            Data:    []byte("data84"),
        },
        {
            Address: []byte("iterate-hash-06"),
            Data:    []byte("data1"),
        },
    }
    batch := new(leveldb.Batch)
    for _, i := range items {
        index.PutInBatch(batch, i)
    }
    err = db.WriteBatch(batch)
    if err != nil {
        t.Fatal(err)
    }
    item04 := IndexItem{
        Address: []byte("iterate-hash-04"),
        Data:    []byte("data0"),
    }
    err = index.Put(item04)
    if err != nil {
        t.Fatal(err)
    }
    items = append(items, item04)

    sort.SliceStable(items, func(i, j int) bool {
        return bytes.Compare(items[i].Address, items[j].Address) < 0
    })

    t.Run("all", func(t *testing.T) {
        var i int
        err := index.IterateAll(func(item IndexItem) (stop bool, err error) {
            if i > len(items)-1 {
                return true, fmt.Errorf("got unexpected index item: %#v", item)
            }
            want := items[i]
            checkIndexItem(t, item, want)
            i++
            return false, nil
        })
        if err != nil {
            t.Fatal(err)
        }
    })

    t.Run("from", func(t *testing.T) {
        startIndex := 2
        i := startIndex
        err := index.IterateFrom(items[startIndex], func(item IndexItem) (stop bool, err error) {
            if i > len(items)-1 {
                return true, fmt.Errorf("got unexpected index item: %#v", item)
            }
            want := items[i]
            checkIndexItem(t, item, want)
            i++
            return false, nil
        })
        if err != nil {
            t.Fatal(err)
        }
    })

    t.Run("stop", func(t *testing.T) {
        var i int
        stopIndex := 3
        var count int
        err := index.IterateAll(func(item IndexItem) (stop bool, err error) {
            if i > len(items)-1 {
                return true, fmt.Errorf("got unexpected index item: %#v", item)
            }
            want := items[i]
            checkIndexItem(t, item, want)
            count++
            if i == stopIndex {
                return true, nil
            }
            i++
            return false, nil
        })
        if err != nil {
            t.Fatal(err)
        }
        wantItemsCount := stopIndex + 1
        if count != wantItemsCount {
            t.Errorf("got %v items, expected %v", count, wantItemsCount)
        }
    })

    t.Run("no overflow", func(t *testing.T) {
        secondIndex, err := db.NewIndex("second-index", retrievalIndexFuncs)
        if err != nil {
            t.Fatal(err)
        }

        secondIndexItem := IndexItem{
            Address: []byte("iterate-hash-10"),
            Data:    []byte("data-second"),
        }
        err = secondIndex.Put(secondIndexItem)
        if err != nil {
            t.Fatal(err)
        }

        var i int
        err = index.IterateAll(func(item IndexItem) (stop bool, err error) {
            if i > len(items)-1 {
                return true, fmt.Errorf("got unexpected index item: %#v", item)
            }
            want := items[i]
            checkIndexItem(t, item, want)
            i++
            return false, nil
        })
        if err != nil {
            t.Fatal(err)
        }

        i = 0
        err = secondIndex.IterateAll(func(item IndexItem) (stop bool, err error) {
            if i > 1 {
                return true, fmt.Errorf("got unexpected index item: %#v", item)
            }
            checkIndexItem(t, item, secondIndexItem)
            i++
            return false, nil
        })
        if err != nil {
            t.Fatal(err)
        }
    })
}

// checkIndexItem is a test helper function that compares if two Index items are the same.
func checkIndexItem(t *testing.T, got, want IndexItem) {
    t.Helper()

    if !bytes.Equal(got.Address, want.Address) {
        t.Errorf("got hash %q, expected %q", string(got.Address), string(want.Address))
    }
    if !bytes.Equal(got.Data, want.Data) {
        t.Errorf("got data %q, expected %q", string(got.Data), string(want.Data))
    }
    if got.StoreTimestamp != want.StoreTimestamp {
        t.Errorf("got store timestamp %v, expected %v", got.StoreTimestamp, want.StoreTimestamp)
    }
    if got.AccessTimestamp != want.AccessTimestamp {
        t.Errorf("got access timestamp %v, expected %v", got.AccessTimestamp, want.AccessTimestamp)
    }
}