merkledag.go 2.13 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 26 27
	// GetMany returns a channel of NodeOptions given a set of CIDs.
	GetMany(context.Context, []*cid.Cid) <-chan *NodeOption

28
	// TODO(ipfs/go-ipfs#4009): Remove this method after fixing.
29 30 31

	// OfflineNodeGetter returns an version of this NodeGetter that will
	// make no network requests.
32 33 34 35 36 37 38
	OfflineNodeGetter() NodeGetter
}

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

40
	// TODO(ipfs/go-ipld-format#9): This should return []*cid.Cid
41 42 43

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

47 48 49
// 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.
50 51 52 53 54 55 56 57 58 59 60 61
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
62 63 64 65 66 67
}

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

68
	// Add adds a node to this DAG.
69
	Add(Node) (*cid.Cid, error)
70

71 72 73
	// Remove removes a node from this DAG.
	//
	// If the node is not in this DAG, Remove returns ErrNotFound.
74
	Remove(*cid.Cid) error
75

76 77 78 79
	// 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.
80
	AddMany([]Node) ([]*cid.Cid, error)
81
}