blockservice.go 2.22 KB
Newer Older
1 2 3 4
package blockservice

import (
	"fmt"
Jeromy's avatar
Jeromy committed
5
	"time"
6

7
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"
8
	blocks "github.com/jbenet/go-ipfs/blocks"
9
	exchange "github.com/jbenet/go-ipfs/exchange"
10 11
	u "github.com/jbenet/go-ipfs/util"

12
	mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
13 14 15 16 17 18
)

// BlockService is a block datastore.
// It uses an internal `datastore.Datastore` instance to store values.
type BlockService struct {
	Datastore ds.Datastore
19
	Remote    exchange.Exchange
20 21 22
}

// NewBlockService creates a BlockService with given datastore instance.
23
func NewBlockService(d ds.Datastore, rem exchange.Exchange) (*BlockService, error) {
24 25 26
	if d == nil {
		return nil, fmt.Errorf("BlockService requires valid datastore")
	}
Jeromy's avatar
Jeromy committed
27
	if rem == nil {
28
		u.PErr("Caution: blockservice running in local (offline) mode.\n")
Jeromy's avatar
Jeromy committed
29 30
	}
	return &BlockService{Datastore: d, Remote: rem}, nil
31 32 33 34 35 36
}

// AddBlock adds a particular block to the service, Putting it into the datastore.
func (s *BlockService) AddBlock(b *blocks.Block) (u.Key, error) {
	k := b.Key()
	dsk := ds.NewKey(string(k))
Jeromy's avatar
Jeromy committed
37
	u.DOut("storing [%s] in datastore\n", k.Pretty())
38 39
	// TODO(brian): define a block datastore with a Put method which accepts a
	// block parameter
Jeromy's avatar
Jeromy committed
40 41 42 43
	err := s.Datastore.Put(dsk, b.Data)
	if err != nil {
		return k, err
	}
44
	if s.Remote != nil {
45
		err = s.Remote.HasBlock(*b)
46
	}
Jeromy's avatar
Jeromy committed
47
	return k, err
48 49 50 51 52
}

// GetBlock retrieves a particular block from the service,
// Getting it from the datastore using the key (hash).
func (s *BlockService) GetBlock(k u.Key) (*blocks.Block, error) {
53
	u.DOut("BlockService GetBlock: '%s'\n", k.Pretty())
54 55
	dsk := ds.NewKey(string(k))
	datai, err := s.Datastore.Get(dsk)
Jeromy's avatar
Jeromy committed
56
	if err == nil {
57
		u.DOut("Blockservice: Got data in datastore.\n")
Jeromy's avatar
Jeromy committed
58 59 60 61 62 63 64 65
		bdata, ok := datai.([]byte)
		if !ok {
			return nil, fmt.Errorf("data associated with %s is not a []byte", k)
		}
		return &blocks.Block{
			Multihash: mh.Multihash(k),
			Data:      bdata,
		}, nil
66
	} else if err == ds.ErrNotFound && s.Remote != nil {
67
		u.DOut("Blockservice: Searching bitswap.\n")
68
		blk, err := s.Remote.Block(k, time.Second*5)
Jeromy's avatar
Jeromy committed
69 70 71 72 73
		if err != nil {
			return nil, err
		}
		return blk, nil
	} else {
74
		u.DOut("Blockservice GetBlock: Not found.\n")
Jeromy's avatar
Jeromy committed
75
		return nil, u.ErrNotFound
76 77
	}
}