write_cache.go 2.01 KB
Newer Older
1 2 3
package blockstore

import (
4 5
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/hashicorp/golang-lru"
	"github.com/ipfs/go-ipfs/blocks"
6
	key "github.com/ipfs/go-ipfs/blocks/key"
Jeromy's avatar
Jeromy committed
7
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
8 9 10
)

// WriteCached returns a blockstore that caches up to |size| unique writes (bs.Put).
Jeromy's avatar
Jeromy committed
11
func WriteCached(bs Blockstore, size int) (*writecache, error) {
12 13 14 15 16 17 18 19 20 21 22 23
	c, err := lru.New(size)
	if err != nil {
		return nil, err
	}
	return &writecache{blockstore: bs, cache: c}, nil
}

type writecache struct {
	cache      *lru.Cache // pointer b/c Cache contains a Mutex as value (complicates copying)
	blockstore Blockstore
}

24
func (w *writecache) DeleteBlock(k key.Key) error {
25
	defer log.EventBegin(context.TODO(), "writecache.BlockRemoved", &k).Done()
26 27 28 29
	w.cache.Remove(k)
	return w.blockstore.DeleteBlock(k)
}

30
func (w *writecache) Has(k key.Key) (bool, error) {
31 32 33 34 35 36
	if _, ok := w.cache.Get(k); ok {
		return true, nil
	}
	return w.blockstore.Has(k)
}

37
func (w *writecache) Get(k key.Key) (blocks.Block, error) {
38 39 40
	return w.blockstore.Get(k)
}

41
func (w *writecache) Put(b blocks.Block) error {
42 43
	k := b.Key()
	if _, ok := w.cache.Get(k); ok {
44 45
		return nil
	}
46 47
	defer log.EventBegin(context.TODO(), "writecache.BlockAdded", &k).Done()

48 49 50
	w.cache.Add(b.Key(), struct{}{})
	return w.blockstore.Put(b)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51

52 53
func (w *writecache) PutMany(bs []blocks.Block) error {
	var good []blocks.Block
54 55 56
	for _, b := range bs {
		if _, ok := w.cache.Get(b.Key()); !ok {
			good = append(good, b)
57 58
			k := b.Key()
			defer log.EventBegin(context.TODO(), "writecache.BlockAdded", &k).Done()
59 60 61 62 63
		}
	}
	return w.blockstore.PutMany(good)
}

64
func (w *writecache) AllKeysChan(ctx context.Context) (<-chan key.Key, error) {
65
	return w.blockstore.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
66
}
Jeromy's avatar
Jeromy committed
67

68
func (w *writecache) GCLock() Unlocker {
69
	return w.blockstore.(GCBlockstore).GCLock()
Jeromy's avatar
Jeromy committed
70 71
}

72
func (w *writecache) PinLock() Unlocker {
73
	return w.blockstore.(GCBlockstore).PinLock()
Jeromy's avatar
Jeromy committed
74
}
Jeromy's avatar
Jeromy committed
75 76 77 78

func (w *writecache) GCRequested() bool {
	return w.blockstore.(GCBlockstore).GCRequested()
}