forked from libp2p/go-libp2p-routing-helpers
/
tiered.go
85 lines (72 loc) · 2.31 KB
/
tiered.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package routinghelpers
import (
"context"
routing "github.com/libp2p/go-libp2p-routing"
ropts "github.com/libp2p/go-libp2p-routing/options"
multierror "github.com/hashicorp/go-multierror"
cid "github.com/ipfs/go-cid"
ci "github.com/libp2p/go-libp2p-crypto"
peer "github.com/libp2p/go-libp2p-peer"
pstore "github.com/libp2p/go-libp2p-peerstore"
)
// Tiered is like the Parallel except that GetValue and FindPeer
// are called in series.
type Tiered []routing.IpfsRouting
func (r Tiered) PutValue(ctx context.Context, key string, value []byte, opts ...ropts.Option) error {
return Parallel(r).PutValue(ctx, key, value, opts...)
}
func (r Tiered) get(ctx context.Context, do func(routing.IpfsRouting) (interface{}, error)) (interface{}, error) {
var errs []error
for _, ri := range r {
val, err := do(ri)
switch err {
case nil:
return val, nil
case routing.ErrNotFound, routing.ErrNotSupported:
continue
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
errs = append(errs, err)
}
switch len(errs) {
case 0:
return nil, routing.ErrNotFound
case 1:
return nil, errs[0]
default:
return nil, &multierror.Error{Errors: errs}
}
}
func (r Tiered) GetValue(ctx context.Context, key string, opts ...ropts.Option) ([]byte, error) {
valInt, err := r.get(ctx, func(ri routing.IpfsRouting) (interface{}, error) {
return ri.GetValue(ctx, key, opts...)
})
val, _ := valInt.([]byte)
return val, err
}
func (r Tiered) GetPublicKey(ctx context.Context, p peer.ID) (ci.PubKey, error) {
vInt, err := r.get(ctx, func(ri routing.IpfsRouting) (interface{}, error) {
return routing.GetPublicKey(ri, ctx, p)
})
val, _ := vInt.(ci.PubKey)
return val, err
}
func (r Tiered) Provide(ctx context.Context, c *cid.Cid, local bool) error {
return Parallel(r).Provide(ctx, c, local)
}
func (r Tiered) FindProvidersAsync(ctx context.Context, c *cid.Cid, count int) <-chan pstore.PeerInfo {
return Parallel(r).FindProvidersAsync(ctx, c, count)
}
func (r Tiered) FindPeer(ctx context.Context, p peer.ID) (pstore.PeerInfo, error) {
valInt, err := r.get(ctx, func(ri routing.IpfsRouting) (interface{}, error) {
return ri.FindPeer(ctx, p)
})
val, _ := valInt.(pstore.PeerInfo)
return val, err
}
func (r Tiered) Bootstrap(ctx context.Context) error {
return Parallel(r).Bootstrap(ctx)
}
var _ routing.IpfsRouting = (Tiered)(nil)