-
Notifications
You must be signed in to change notification settings - Fork 21
/
flatfs_test.go
1228 lines (1041 loc) · 27.3 KB
/
flatfs_test.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package flatfs_test
import (
"context"
"encoding/base32"
"encoding/json"
"fmt"
"math"
"math/rand"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/mount"
"github.com/ipfs/go-datastore/query"
dstest "github.com/ipfs/go-datastore/test"
flatfs "github.com/ipfs/go-ds-flatfs"
)
var bg = context.Background()
func checkTemp(t *testing.T, dir string) {
tempDir, err := os.Open(filepath.Join(dir, ".temp"))
if err != nil {
t.Errorf("failed to open temp dir: %s", err)
return
}
names, err := tempDir.Readdirnames(-1)
tempDir.Close()
if err != nil {
t.Errorf("failed to read temp dir: %s", err)
return
}
for _, name := range names {
t.Errorf("found leftover temporary file: %s", name)
}
}
func tempdir(t testing.TB) (path string, cleanup func()) {
path, err := os.MkdirTemp("", "test-datastore-flatfs-")
if err != nil {
t.Fatalf("cannot create temp directory: %v", err)
}
cleanup = func() {
if err := os.RemoveAll(path); err != nil {
t.Errorf("tempdir cleanup failed: %v", err)
}
}
return path, cleanup
}
func tryAllShardFuncs(t *testing.T, testFunc func(mkShardFunc, *testing.T)) {
t.Run("prefix", func(t *testing.T) { testFunc(flatfs.Prefix, t) })
t.Run("suffix", func(t *testing.T) { testFunc(flatfs.Suffix, t) })
t.Run("next-to-last", func(t *testing.T) { testFunc(flatfs.NextToLast, t) })
}
type mkShardFunc func(int) *flatfs.ShardIdV1
func testBatch(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
batches := make([]datastore.Batch, 9)
for i := range batches {
batch, err := fs.Batch(bg)
if err != nil {
t.Fatal(err)
}
batches[i] = batch
err = batch.Put(bg, datastore.NewKey("QUUX"), []byte("foo"))
if err != nil {
t.Fatal(err)
}
err = batch.Put(bg, datastore.NewKey(fmt.Sprintf("Q%dX", i)), []byte(fmt.Sprintf("bar%d", i)))
if err != nil {
t.Fatal(err)
}
}
var wg sync.WaitGroup
wg.Add(len(batches))
for _, batch := range batches {
batch := batch
go func() {
defer wg.Done()
err := batch.Commit(bg)
if err != nil {
t.Error(err)
}
}()
}
check := func(key, expected string) {
actual, err := fs.Get(bg, datastore.NewKey(key))
if err != nil {
t.Fatalf("get for key %s, error: %s", key, err)
}
if string(actual) != expected {
t.Fatalf("for key %s, expected %s, got %s", key, expected, string(actual))
}
}
wg.Wait()
check("QUUX", "foo")
for i := range batches {
check(fmt.Sprintf("Q%dX", i), fmt.Sprintf("bar%d", i))
}
}
func TestBatch(t *testing.T) { tryAllShardFuncs(t, testBatch) }
func testPut(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
err = fs.Put(bg, datastore.NewKey("QUUX"), []byte("foobar"))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
err = fs.Put(bg, datastore.NewKey("foo"), []byte("nonono"))
if err == nil {
t.Fatalf("did not expect to put a lowercase key")
}
}
func TestPut(t *testing.T) { tryAllShardFuncs(t, testPut) }
func testGet(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
const input = "foobar"
err = fs.Put(bg, datastore.NewKey("QUUX"), []byte(input))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
buf, err := fs.Get(bg, datastore.NewKey("QUUX"))
if err != nil {
t.Fatalf("Get failed: %v", err)
}
if g, e := string(buf), input; g != e {
t.Fatalf("Get gave wrong content: %q != %q", g, e)
}
_, err = fs.Get(bg, datastore.NewKey("/FOO/BAR"))
if err != datastore.ErrNotFound {
t.Fatalf("expected ErrNotFound, got %s", err)
}
}
func TestGet(t *testing.T) { tryAllShardFuncs(t, testGet) }
func testPutOverwrite(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
const (
loser = "foobar"
winner = "xyzzy"
)
err = fs.Put(bg, datastore.NewKey("QUUX"), []byte(loser))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
err = fs.Put(bg, datastore.NewKey("QUUX"), []byte(winner))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
data, err := fs.Get(bg, datastore.NewKey("QUUX"))
if err != nil {
t.Fatalf("Get failed: %v", err)
}
if g, e := string(data), winner; g != e {
t.Fatalf("Get gave wrong content: %q != %q", g, e)
}
}
func TestPutOverwrite(t *testing.T) { tryAllShardFuncs(t, testPutOverwrite) }
func testGetNotFoundError(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
_, err = fs.Get(bg, datastore.NewKey("QUUX"))
if g, e := err, datastore.ErrNotFound; g != e {
t.Fatalf("expected ErrNotFound, got: %v\n", g)
}
}
func TestGetNotFoundError(t *testing.T) { tryAllShardFuncs(t, testGetNotFoundError) }
type params struct {
shard *flatfs.ShardIdV1
dir string
key string
}
func testStorage(p *params, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
target := p.dir + string(os.PathSeparator) + p.key + ".data"
fs, err := flatfs.CreateOrOpen(temp, p.shard, false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
err = fs.Put(bg, datastore.NewKey(p.key), []byte("foobar"))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
fs.Close()
seen := false
haveREADME := false
walk := func(absPath string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
path, err := filepath.Rel(temp, absPath)
if err != nil {
return err
}
switch path {
case ".", "..", "SHARDING", flatfs.DiskUsageFile, ".temp":
// ignore
case "_README":
_, err := os.ReadFile(absPath)
if err != nil {
t.Error("could not read _README file")
}
haveREADME = true
case p.dir:
if !fi.IsDir() {
t.Errorf("directory is not a file? %v", fi.Mode())
}
// we know it's there if we see the file, nothing more to
// do here
case target:
seen = true
if !fi.Mode().IsRegular() {
t.Errorf("expected a regular file, mode: %04o", fi.Mode())
}
if runtime.GOOS != "windows" {
if g, e := fi.Mode()&os.ModePerm&0007, os.FileMode(0000); g != e {
t.Errorf("file should not be world accessible: %04o", fi.Mode())
}
}
default:
t.Errorf("saw unexpected directory entry: %q %v", path, fi.Mode())
}
return nil
}
if err := filepath.Walk(temp, walk); err != nil {
t.Fatalf("walk: %v", err)
}
if !seen {
t.Error("did not see the data file")
}
if fs.ShardStr() == flatfs.IPFS_DEF_SHARD_STR && !haveREADME {
t.Error("expected _README file")
} else if fs.ShardStr() != flatfs.IPFS_DEF_SHARD_STR && haveREADME {
t.Error("did not expect _README file")
}
}
func TestStorage(t *testing.T) {
t.Run("prefix", func(t *testing.T) {
testStorage(¶ms{
shard: flatfs.Prefix(2),
dir: "QU",
key: "QUUX",
}, t)
})
t.Run("suffix", func(t *testing.T) {
testStorage(¶ms{
shard: flatfs.Suffix(2),
dir: "UX",
key: "QUUX",
}, t)
})
t.Run("next-to-last", func(t *testing.T) {
testStorage(¶ms{
shard: flatfs.NextToLast(2),
dir: "UU",
key: "QUUX",
}, t)
})
}
func testHasNotFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
found, err := fs.Has(bg, datastore.NewKey("QUUX"))
if err != nil {
t.Fatalf("Has fail: %v\n", err)
}
if found {
t.Fatal("Has should have returned false")
}
}
func TestHasNotFound(t *testing.T) { tryAllShardFuncs(t, testHasNotFound) }
func testHasFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
err = fs.Put(bg, datastore.NewKey("QUUX"), []byte("foobar"))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
found, err := fs.Has(bg, datastore.NewKey("QUUX"))
if err != nil {
t.Fatalf("Has fail: %v\n", err)
}
if !found {
t.Fatal("Has should have returned true")
}
}
func TestHasFound(t *testing.T) { tryAllShardFuncs(t, testHasFound) }
func testGetSizeFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
_, err = fs.GetSize(bg, datastore.NewKey("QUUX"))
if err != datastore.ErrNotFound {
t.Fatalf("GetSize should have returned ErrNotFound, got: %v\n", err)
}
}
func TestGetSizeFound(t *testing.T) { tryAllShardFuncs(t, testGetSizeFound) }
func testGetSizeNotFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
err = fs.Put(bg, datastore.NewKey("QUUX"), []byte("foobar"))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
size, err := fs.GetSize(bg, datastore.NewKey("QUUX"))
if err != nil {
t.Fatalf("GetSize failed with: %v\n", err)
}
if size != len("foobar") {
t.Fatalf("GetSize returned wrong size: got %d, expected %d", size, len("foobar"))
}
}
func TestGetSizeNotFound(t *testing.T) { tryAllShardFuncs(t, testGetSizeNotFound) }
func testDeleteNotFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
err = fs.Delete(bg, datastore.NewKey("QUUX"))
if err != nil {
t.Fatalf("expected nil, got: %v\n", err)
}
}
func TestDeleteNotFound(t *testing.T) { tryAllShardFuncs(t, testDeleteNotFound) }
func testDeleteFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
err = fs.Put(bg, datastore.NewKey("QUUX"), []byte("foobar"))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
err = fs.Delete(bg, datastore.NewKey("QUUX"))
if err != nil {
t.Fatalf("Delete fail: %v\n", err)
}
// check that it's gone
_, err = fs.Get(bg, datastore.NewKey("QUUX"))
if g, e := err, datastore.ErrNotFound; g != e {
t.Fatalf("expected Get after Delete to give ErrNotFound, got: %v\n", g)
}
}
func TestDeleteFound(t *testing.T) { tryAllShardFuncs(t, testDeleteFound) }
func testQuerySimple(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
const myKey = "QUUX"
err = fs.Put(bg, datastore.NewKey(myKey), []byte("foobar"))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
res, err := fs.Query(bg, query.Query{KeysOnly: true})
if err != nil {
t.Fatalf("Query fail: %v\n", err)
}
entries, err := res.Rest()
if err != nil {
t.Fatalf("Query Results.Rest fail: %v\n", err)
}
seen := false
for _, e := range entries {
switch e.Key {
case datastore.NewKey(myKey).String():
seen = true
default:
t.Errorf("saw unexpected key: %q", e.Key)
}
}
if !seen {
t.Errorf("did not see wanted key %q in %+v", myKey, entries)
}
}
func TestQuerySimple(t *testing.T) { tryAllShardFuncs(t, testQuerySimple) }
func testDiskUsage(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
time.Sleep(100 * time.Millisecond)
duNew, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
t.Log("duNew:", duNew)
count := 200
for i := 0; i < count; i++ {
k := datastore.NewKey(fmt.Sprintf("TEST-%d", i))
v := []byte("10bytes---")
err = fs.Put(bg, k, v)
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
}
time.Sleep(100 * time.Millisecond)
duElems, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
t.Log("duPostPut:", duElems)
for i := 0; i < count; i++ {
k := datastore.NewKey(fmt.Sprintf("TEST-%d", i))
err = fs.Delete(bg, k)
if err != nil {
t.Fatalf("Delete fail: %v\n", err)
}
}
time.Sleep(100 * time.Millisecond)
duDelete, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
t.Log("duPostDelete:", duDelete)
du, err := fs.DiskUsage(bg)
t.Log("duFinal:", du)
if err != nil {
t.Fatal(err)
}
fs.Close()
// Check that disk usage file is correct
duB, err := os.ReadFile(filepath.Join(temp, flatfs.DiskUsageFile))
if err != nil {
t.Fatal(err)
}
contents := make(map[string]interface{})
err = json.Unmarshal(duB, &contents)
if err != nil {
t.Fatal(err)
}
// Make sure diskUsage value is correct
if val, ok := contents["diskUsage"].(float64); !ok || uint64(val) != du {
t.Fatalf("Unexpected value for diskUsage in %s: %v (expected %d)",
flatfs.DiskUsageFile, contents["diskUsage"], du)
}
// Make sure the accuracy value is correct
if val, ok := contents["accuracy"].(string); !ok || val != "initial-exact" {
t.Fatalf("Unexpected value for accuracyin %s: %v",
flatfs.DiskUsageFile, contents["accuracy"])
}
// Make sure size is correctly calculated on re-open
os.Remove(filepath.Join(temp, flatfs.DiskUsageFile))
fs, err = flatfs.Open(temp, false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
duReopen, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
t.Log("duReopen:", duReopen)
// Checks
if duNew == 0 {
t.Error("new datastores should have some size")
}
if duElems <= duNew {
t.Error("size should grow as new elements are added")
}
if duElems-duDelete != uint64(count*10) {
t.Error("size should be reduced exactly as size of objects deleted")
}
if duReopen < duNew {
t.Error("Reopened datastore should not be smaller")
}
}
func TestDiskUsage(t *testing.T) {
tryAllShardFuncs(t, testDiskUsage)
}
func TestDiskUsageDoubleCount(t *testing.T) {
tryAllShardFuncs(t, testDiskUsageDoubleCount)
}
// test that concurrently writing and deleting the same key/value
// does not throw any errors and disk usage does not do
// any double-counting.
func testDiskUsageDoubleCount(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
var count int
var wg sync.WaitGroup
testKey := datastore.NewKey("TEST")
put := func() {
defer wg.Done()
for i := 0; i < count; i++ {
v := []byte("10bytes---")
err := fs.Put(bg, testKey, v)
if err != nil {
t.Errorf("Put fail: %v\n", err)
}
}
}
del := func() {
defer wg.Done()
for i := 0; i < count; i++ {
err := fs.Delete(bg, testKey)
if err != nil && !strings.Contains(err.Error(), "key not found") {
t.Errorf("Delete fail: %v\n", err)
}
}
}
// Add one element and then remove it and check disk usage
// makes sense
count = 1
wg.Add(2)
put()
du, _ := fs.DiskUsage(bg)
del()
du2, _ := fs.DiskUsage(bg)
if du-10 != du2 {
t.Error("should have deleted exactly 10 bytes:", du, du2)
}
// Add and remove many times at the same time
count = 200
wg.Add(4)
go put()
go del()
go put()
go del()
wg.Wait()
du3, _ := fs.DiskUsage(bg)
has, err := fs.Has(bg, testKey)
if err != nil {
t.Fatal(err)
}
if has { // put came last
if du3 != du {
t.Error("du should be the same as after first put:", du, du3)
}
} else { // delete came last
if du3 != du2 {
t.Error("du should be the same as after first delete:", du2, du3)
}
}
}
func testDiskUsageBatch(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
fsBatch, err := fs.Batch(bg)
if err != nil {
t.Fatal(err)
}
count := 200
var wg sync.WaitGroup
testKeys := []datastore.Key{}
for i := 0; i < count; i++ {
k := datastore.NewKey(fmt.Sprintf("TEST%d", i))
testKeys = append(testKeys, k)
}
put := func() {
for i := 0; i < count; i++ {
err := fsBatch.Put(bg, testKeys[i], []byte("10bytes---"))
if err != nil {
t.Error(err)
}
}
}
commit := func() {
defer wg.Done()
err := fsBatch.Commit(bg)
if err != nil {
t.Errorf("Batch Put fail: %v\n", err)
}
}
del := func() {
defer wg.Done()
for _, k := range testKeys {
err := fs.Delete(bg, k)
if err != nil && !strings.Contains(err.Error(), "key not found") {
t.Errorf("Delete fail: %v\n", err)
}
}
}
// Put many elements and then delete them and check disk usage
// makes sense
wg.Add(2)
put()
commit()
du, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
del()
du2, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
if du-uint64(10*count) != du2 {
t.Errorf("should have deleted exactly %d bytes: %d %d", 10*count, du, du2)
}
// Do deletes while doing putManys concurrently
wg.Add(2)
put()
go commit()
go del()
wg.Wait()
du3, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
// Now query how many keys we have
results, err := fs.Query(bg, query.Query{
KeysOnly: true,
})
if err != nil {
t.Fatal(err)
}
rest, err := results.Rest()
if err != nil {
t.Fatal(err)
}
expectedSize := uint64(len(rest) * 10)
if exp := du2 + expectedSize; exp != du3 {
t.Error("diskUsage has skewed off from real size:",
exp, du3)
}
}
func TestDiskUsageBatch(t *testing.T) { tryAllShardFuncs(t, testDiskUsageBatch) }
func testDiskUsageEstimation(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
count := 50000
for i := 0; i < count; i++ {
k := datastore.NewKey(fmt.Sprintf("%d-TEST-%d", i, i))
v := make([]byte, 1000)
err = fs.Put(bg, k, v)
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
}
// Delete checkpoint
fs.Close()
os.Remove(filepath.Join(temp, flatfs.DiskUsageFile))
// This will do a full du
flatfs.DiskUsageFilesAverage = -1
fs, err = flatfs.Open(temp, false)
if err != nil {
t.Fatalf("Open fail: %v\n", err)
}
duReopen, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
fs.Close()
os.Remove(filepath.Join(temp, flatfs.DiskUsageFile))
// This will estimate the size. Since all files are the same
// length we can use a low file average number.
flatfs.DiskUsageFilesAverage = 100
// Make sure size is correctly calculated on re-open
fs, err = flatfs.Open(temp, false)
if err != nil {
t.Fatalf("Open fail: %v\n", err)
}
duEst, err := fs.DiskUsage(bg)
if err != nil {
t.Fatal(err)
}
t.Log("RealDu:", duReopen)
t.Log("Est:", duEst)
diff := int(math.Abs(float64(int(duReopen) - int(duEst))))
maxDiff := int(0.05 * float64(duReopen)) // %5 of actual
if diff > maxDiff {
t.Fatalf("expected a better estimation within 5%%")
}
// Make sure the accuracy value is correct
if fs.Accuracy() != "initial-approximate" {
t.Errorf("Unexpected value for fs.Accuracy(): %s", fs.Accuracy())
}
fs.Close()
// Reopen into a new variable
fs2, err := flatfs.Open(temp, false)
if err != nil {
t.Fatalf("Open fail: %v\n", err)
}
// Make sure the accuracy value is preserved
if fs2.Accuracy() != "initial-approximate" {
t.Errorf("Unexpected value for fs.Accuracy(): %s", fs2.Accuracy())
}
}
func TestDiskUsageEstimation(t *testing.T) { tryAllShardFuncs(t, testDiskUsageEstimation) }
func testBatchPut(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
dstest.RunBatchTest(t, fs)
}
func TestBatchPut(t *testing.T) { tryAllShardFuncs(t, testBatchPut) }
func testBatchDelete(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
dstest.RunBatchDeleteTest(t, fs)
}
func TestBatchDelete(t *testing.T) { tryAllShardFuncs(t, testBatchDelete) }
func testClose(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
defer checkTemp(t, temp)
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
err = fs.Put(bg, datastore.NewKey("QUUX"), []byte("foobar"))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
fs.Close()
err = fs.Put(bg, datastore.NewKey("QAAX"), []byte("foobar"))
if err == nil {
t.Fatal("expected put on closed datastore to fail")
}
}
func TestClose(t *testing.T) { tryAllShardFuncs(t, testClose) }
func TestSHARDINGFile(t *testing.T) {
tempdir, cleanup := tempdir(t)
defer cleanup()
fun := flatfs.IPFS_DEF_SHARD
err := flatfs.Create(tempdir, fun)
if err != nil {
t.Fatalf("Create: %v\n", err)
}
fs, err := flatfs.Open(tempdir, false)
if err != nil {
t.Fatalf("Open fail: %v\n", err)
}
if fs.ShardStr() != flatfs.IPFS_DEF_SHARD_STR {
t.Fatalf("Expected '%s' for shard function got '%s'", flatfs.IPFS_DEF_SHARD_STR, fs.ShardStr())
}
fs.Close()
fs, err = flatfs.CreateOrOpen(tempdir, fun, false)
if err != nil {
t.Fatalf("Could not reopen repo: %v\n", err)
}
fs.Close()
fs, err = flatfs.CreateOrOpen(tempdir, flatfs.Prefix(5), false)
if err == nil {
fs.Close()
t.Fatalf("Was able to open repo with incompatible sharding function")
}