-
Notifications
You must be signed in to change notification settings - Fork 0
/
cassette.go
210 lines (194 loc) · 4.91 KB
/
cassette.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package cassette
import (
"context"
"net/http"
"time"
"github.com/ipfs/boxo/bitswap/network"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/multiformats/go-multihash"
)
var (
logger = log.Logger("cassette")
)
type Cassette struct {
*options
server *http.Server
// Context and cancellation used to terminate streaming responses on shutdown.
ctx context.Context
cancel context.CancelFunc
bsn network.BitSwapNetwork
r *receiver
broadcaster *broadcaster
discoverer *peerDiscoverer
metrics *metrics
cache *cache
}
func New(o ...Option) (*Cassette, error) {
opts, err := newOptions(o...)
if err != nil {
return nil, err
}
c := Cassette{
options: opts,
}
c.server = &http.Server{
Addr: opts.httpListenAddr,
Handler: c.serveMux(),
}
c.ctx, c.cancel = context.WithCancel(context.Background())
if c.metrics, err = newMetrics(&c); err != nil {
return nil, err
}
if c.cache, err = newCache(&c); err != nil {
return nil, err
}
return &c, nil
}
func (c *Cassette) Start(ctx context.Context) error {
if err := c.metrics.Start(ctx); err != nil {
return err
}
c.bsn = network.NewFromIpfsHost(c.h, nil)
var err error
c.r, err = newReceiver(c)
if err != nil {
return err
}
c.bsn.Start(c.r)
c.discoverer = newPeerDiscoverer(c)
if err := c.discoverer.start(ctx); err != nil {
return err
}
c.broadcaster = newBroadcaster(c)
c.broadcaster.start(ctx)
c.server.RegisterOnShutdown(c.cancel)
go func() { _ = c.server.ListenAndServe() }()
logger.Infow("Lookup server started", "id", c.h.ID(), "libp2pAddrs", c.h.Addrs(), "httpAddr", c.server.Addr, "protocols", c.h.Mux().Protocols())
return nil
}
func (c *Cassette) Find(ctx context.Context, k cid.Cid) chan peer.AddrInfo {
start := time.Now()
c.metrics.notifyLookupRequested(context.Background())
rch := make(chan peer.AddrInfo, 1)
go func() {
ctx, cancel := context.WithTimeout(ctx, c.responseTimeout)
defer func() {
cancel()
close(rch)
}()
var resultCount int64
var timeToFirstProvider time.Duration
var cacheHit bool
defer func() {
c.metrics.notifyLookupResponded(context.Background(), resultCount, timeToFirstProvider, time.Since(start), cacheHit)
}()
// Attempt to get provider IDs from cache
if providers, found := c.cache.getProviders(k); found {
cacheHit = true
for _, provider := range providers {
select {
case <-ctx.Done():
return
case rch <- provider:
resultCount++
if resultCount == 1 {
timeToFirstProvider = time.Since(start)
}
}
}
return
}
providers, unregister, err := c.r.registerFoundHook(ctx, k)
if err != nil {
return
}
defer unregister()
targets := c.toFindTargets(k)
if err := c.broadcaster.broadcastWant(ctx, targets); err != nil {
return
}
providersSoFar := make(map[peer.ID]struct{})
returnIfUnseen := func(provider peer.ID) *peer.AddrInfo {
select {
case <-ctx.Done():
return nil
default:
if _, seen := providersSoFar[provider]; seen {
return nil
}
providersSoFar[provider] = struct{}{}
addrs := c.h.Peerstore().Addrs(provider)
if !c.addrFilterDisabled {
addrs = multiaddr.FilterAddrs(addrs, IsPubliclyDialableAddr)
}
if len(addrs) == 0 {
return nil
}
result := peer.AddrInfo{ID: provider, Addrs: addrs}
select {
case <-ctx.Done():
return nil
case rch <- result:
resultCount++
if resultCount == 1 {
timeToFirstProvider = time.Since(start)
}
return &result
}
}
}
var returnedProviders []peer.AddrInfo
defer func() {
if len(returnedProviders) > 0 || c.cacheNoResults {
c.cache.putProviders(k, returnedProviders)
}
}()
for {
select {
case <-ctx.Done():
return
case provider, ok := <-providers:
if !ok {
return
}
if returned := returnIfUnseen(provider); returned != nil {
returnedProviders = append(returnedProviders, *returned)
}
}
}
// TODO add option to stop based on provider count limit
}()
return rch
}
func (c *Cassette) toFindTargets(k cid.Cid) []cid.Cid {
// TODO add option for codecs other than cid.Raw
switch {
case cid.Undef.Equals(k):
return nil
case !c.findByMultihash:
return []cid.Cid{k}
case k.Prefix().Version == 0:
return []cid.Cid{k, cid.NewCidV1(cid.Raw, k.Hash())}
default:
hash := k.Hash()
prefix := k.Prefix()
targets := make([]cid.Cid, 0, 3)
targets = append(targets, k)
// Strictly check multihash code and length; otherwise, cid.NewCidV0 will panic.
if prefix.MhType == multihash.SHA2_256 && prefix.MhLength == 32 {
targets = append(targets, cid.NewCidV0(hash))
}
if prefix.Codec != cid.Raw {
targets = append(targets, cid.NewCidV1(cid.Raw, hash))
}
return targets
}
}
func (c *Cassette) Shutdown(ctx context.Context) error {
c.bsn.Stop()
_ = c.metrics.Shutdown(ctx)
return c.server.Shutdown(ctx)
}