merkledag.go 2.23 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package format

import (
	"context"
	"fmt"

	cid "github.com/ipfs/go-cid"
)

var ErrNotFound = fmt.Errorf("merkledag: not found")

// Either a node or an error.
type NodeOption struct {
	Node Node
	Err  error
}

Steven Allen's avatar
Steven Allen committed
18
// The basic Node resolution service.
19
type NodeGetter interface {
20 21 22
	// Get retrieves nodes by CID. Depending on the NodeGetter
	// implementation, this may involve fetching the Node from a remote
	// machine; consider setting a deadline in the context.
23
	Get(context.Context, *cid.Cid) (Node, error)
24 25

	// TODO(ipfs/go-ipfs#4009): Remove this method after fixing.
26 27 28

	// OfflineNodeGetter returns an version of this NodeGetter that will
	// make no network requests.
29 30 31 32 33 34 35
	OfflineNodeGetter() NodeGetter
}

// NodeGetters can optionally implement this interface to make finding linked
// objects faster.
type LinkGetter interface {
	NodeGetter
36

37
	// TODO(ipfs/go-ipld-format#9): This should return []*cid.Cid
38 39 40

	// GetLinks returns the children of the node refered to by the given
	// CID.
41 42 43
	GetLinks(ctx context.Context, nd *cid.Cid) ([]*Link, error)
}

44 45 46
// GetLinks returns the CIDs of the children of the given node. Prefer this
// method over looking up the node itself and calling `Links()` on it as this
// method may be able to use a link cache.
47 48 49 50 51 52 53 54 55 56 57 58
func GetLinks(ctx context.Context, ng NodeGetter, c *cid.Cid) ([]*Link, error) {
	if c.Type() == cid.Raw {
		return nil, nil
	}
	if gl, ok := ng.(LinkGetter); ok {
		return gl.GetLinks(ctx, c)
	}
	node, err := ng.Get(ctx, c)
	if err != nil {
		return nil, err
	}
	return node.Links(), nil
59 60 61 62 63 64
}

// DAGService is an IPFS Merkle DAG service.
type DAGService interface {
	NodeGetter

65
	// Add adds a node to this DAG.
66
	Add(Node) (*cid.Cid, error)
67

68 69 70
	// Remove removes a node from this DAG.
	//
	// If the node is not in this DAG, Remove returns ErrNotFound.
71 72
	// TODO(ipfs/go-ipfs#4010): Change this to take a CID.
	// This will require a fair amount of refactoring.
73 74
	Remove(Node) error

75
	// GetMany returns a channel of NodeOptions given a set of CIDs.
76 77
	GetMany(context.Context, []*cid.Cid) <-chan *NodeOption

78 79 80 81
	// AddMany adds many nodes to this DAG.
	//
	// Consider using NewBatch instead of calling this directly if you need
	// to add an unbounded number of nodes to avoid buffering too much.
82
	AddMany([]Node) ([]*cid.Cid, error)
83
}