Skip to content
This repository has been archived by the owner on Aug 9, 2018. It is now read-only.

Commit

Permalink
Implement a DAGService
Browse files Browse the repository at this point in the history
  • Loading branch information
mildred committed Feb 17, 2016
1 parent e4f6be6 commit 5d28ec2
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions dag/service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package ipld

import (
"github.com/ipfs/go-ipfs/blocks"
"github.com/ipfs/go-ipfs/blocks/key"
"github.com/ipfs/go-ipfs/blockservice"
"github.com/ipfs/go-ipfs/util"
"github.com/ipfs/go-ipld/coding"
"github.com/ipfs/go-ipld/memory"
"github.com/ipfs/go-ipld/stream"
"golang.org/x/net/context"

mh "github.com/jbenet/go-multihash"
)

var ErrNotFound error = blockservice.ErrNotFound

type Node struct {
stream.NodeReader
Key key.Key
}

func (n *Node) Multihash() mh.Multihash {
return mh.Multihash(n.Key.ToMultihash())
}

type DAGService interface {

// Add a memory Node to the BlockService
Add(node memory.Node) (key.Key, error)

// Get a node from the BlockService
Get(ctx context.Context, key key.Key) (*Node, error)

// Removes a node thom the BlockService
Remove(key key.Key) error
}

type dagService struct {
bs *blockservice.BlockService
}

func NewDAGService(bs *blockservice.BlockService) DAGService {
return &dagService{bs}
}

func (ds *dagService) Add(node memory.Node) (key.Key, error) {
data, err := coding.EncodeBytes(coding.CodecProtobuf, node)
if err != nil {
return "", err
}

return ds.bs.AddBlock(&blocks.Block{
Data: data,
Multihash: util.Hash(data),
})
}

func (ds *dagService) Get(ctx context.Context, key key.Key) (*Node, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()

b, err := ds.bs.GetBlock(ctx, key)
if err != nil {
if err == blockservice.ErrNotFound {
return nil, ErrNotFound
}
return nil, err
}

n, err := coding.DecodeBytes(b.Data)
return &Node{n, key}, err
}

func (ds *dagService) Remove(key key.Key) error {
return ds.bs.DeleteBlock(key)
}

0 comments on commit 5d28ec2

Please sign in to comment.