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

import (
4 5 6
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/hashicorp/golang-lru"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	"github.com/ipfs/go-ipfs/blocks"
7
	key "github.com/ipfs/go-ipfs/blocks/key"
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 26 27 28
	w.cache.Remove(k)
	return w.blockstore.DeleteBlock(k)
}

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

36
func (w *writecache) Get(k key.Key) (*blocks.Block, error) {
37 38 39 40 41 42 43 44 45 46
	return w.blockstore.Get(k)
}

func (w *writecache) Put(b *blocks.Block) error {
	if _, ok := w.cache.Get(b.Key()); ok {
		return nil
	}
	w.cache.Add(b.Key(), struct{}{})
	return w.blockstore.Put(b)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47

48 49 50 51 52 53 54 55 56 57
func (w *writecache) PutMany(bs []*blocks.Block) error {
	var good []*blocks.Block
	for _, b := range bs {
		if _, ok := w.cache.Get(b.Key()); !ok {
			good = append(good, b)
		}
	}
	return w.blockstore.PutMany(good)
}

58
func (w *writecache) AllKeysChan(ctx context.Context) (<-chan key.Key, error) {
59
	return w.blockstore.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60
}
Jeromy's avatar
Jeromy committed
61

62 63
func (w *writecache) GCLock() func() {
	return w.blockstore.(GCBlockstore).GCLock()
Jeromy's avatar
Jeromy committed
64 65
}

66 67
func (w *writecache) PinLock() func() {
	return w.blockstore.(GCBlockstore).PinLock()
Jeromy's avatar
Jeromy committed
68
}
Jeromy's avatar
Jeromy committed
69 70 71 72

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