1package recording_blockstore
2
3import (
4 "context"
5 "fmt"
6
7 blockformat "github.com/ipfs/go-block-format"
8 "github.com/ipfs/go-cid"
9 blockstore "github.com/ipfs/go-ipfs-blockstore"
10)
11
12type RecordingBlockstore struct {
13 base blockstore.Blockstore
14
15 inserts map[cid.Cid]blockformat.Block
16 reads map[cid.Cid]blockformat.Block
17}
18
19func New(base blockstore.Blockstore) *RecordingBlockstore {
20 return &RecordingBlockstore{
21 base: base,
22 inserts: make(map[cid.Cid]blockformat.Block),
23 reads: make(map[cid.Cid]blockformat.Block),
24 }
25}
26
27func (bs *RecordingBlockstore) Has(ctx context.Context, c cid.Cid) (bool, error) {
28 return bs.base.Has(ctx, c)
29}
30
31func (bs *RecordingBlockstore) Get(ctx context.Context, c cid.Cid) (blockformat.Block, error) {
32 b, err := bs.base.Get(ctx, c)
33 if err != nil {
34 return nil, err
35 }
36 bs.reads[c] = b
37 return b, nil
38}
39
40func (bs *RecordingBlockstore) GetSize(ctx context.Context, c cid.Cid) (int, error) {
41 return bs.base.GetSize(ctx, c)
42}
43
44func (bs *RecordingBlockstore) DeleteBlock(ctx context.Context, c cid.Cid) error {
45 return bs.base.DeleteBlock(ctx, c)
46}
47
48func (bs *RecordingBlockstore) Put(ctx context.Context, block blockformat.Block) error {
49 if err := bs.base.Put(ctx, block); err != nil {
50 return err
51 }
52 bs.inserts[block.Cid()] = block
53 return nil
54}
55
56func (bs *RecordingBlockstore) PutMany(ctx context.Context, blocks []blockformat.Block) error {
57 if err := bs.base.PutMany(ctx, blocks); err != nil {
58 return err
59 }
60
61 for _, b := range blocks {
62 bs.inserts[b.Cid()] = b
63 }
64
65 return nil
66}
67
68func (bs *RecordingBlockstore) AllKeysChan(ctx context.Context) (<-chan cid.Cid, error) {
69 return nil, fmt.Errorf("iteration not allowed on recording blockstore")
70}
71
72func (bs *RecordingBlockstore) HashOnRead(enabled bool) {
73}
74
75func (bs *RecordingBlockstore) GetWriteLog() map[cid.Cid]blockformat.Block {
76 return bs.inserts
77}
78
79func (bs *RecordingBlockstore) GetReadLog() []blockformat.Block {
80 var blocks []blockformat.Block
81 for _, b := range bs.reads {
82 blocks = append(blocks, b)
83 }
84 return blocks
85}