-
Notifications
You must be signed in to change notification settings - Fork 18
/
httpretriever.go
224 lines (192 loc) · 7.32 KB
/
httpretriever.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package retriever
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/benbjohnson/clock"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/lassie/pkg/build"
"github.com/filecoin-project/lassie/pkg/events"
"github.com/filecoin-project/lassie/pkg/types"
"github.com/ipfs/go-cid"
trustlesshttp "github.com/ipld/go-trustless-utils/http"
"github.com/ipld/go-trustless-utils/traversal"
"github.com/ipni/go-libipni/metadata"
"github.com/multiformats/go-multicodec"
)
var (
ErrHttpSelectorRequest = errors.New("HTTP retrieval for an explicit selector request")
ErrNoHttpForPeer = errors.New("no HTTP url for peer")
ErrBadPathForRequest = errors.New("bad path for request")
)
type ErrHttpRequestFailure struct {
Code int
}
func (e ErrHttpRequestFailure) Error() string {
return fmt.Sprintf("HTTP request failed, remote response code: %d", e.Code)
}
// Connect() is currently a noop, so this simply allows parallel goroutines to
// queue and the scoring logic to select one to start.
const HttpDefaultInitialWait time.Duration = 2 * time.Millisecond
var _ TransportProtocol = &ProtocolHttp{}
type ProtocolHttp struct {
Client *http.Client
Clock clock.Clock
}
// NewHttpRetriever makes a new CandidateRetriever for verified CAR HTTP
// retrievals (transport-ipfs-gateway-http).
func NewHttpRetriever(session Session, client *http.Client) types.CandidateRetriever {
return NewHttpRetrieverWithDeps(session, client, clock.New(), nil, HttpDefaultInitialWait, false)
}
func NewHttpRetrieverWithDeps(
session Session,
client *http.Client,
clock clock.Clock,
awaitReceivedCandidates chan<- struct{},
initialPause time.Duration,
noDirtyClose bool,
) types.CandidateRetriever {
return ¶llelPeerRetriever{
Protocol: &ProtocolHttp{
Client: client,
Clock: clock,
},
Session: session,
Clock: clock,
QueueInitialPause: initialPause,
awaitReceivedCandidates: awaitReceivedCandidates,
noDirtyClose: noDirtyClose,
}
}
func (ph ProtocolHttp) Code() multicodec.Code {
return multicodec.TransportIpfsGatewayHttp
}
func (ph ProtocolHttp) GetMergedMetadata(cid cid.Cid, currentMetadata, newMetadata metadata.Protocol) metadata.Protocol {
return &metadata.IpfsGatewayHttp{}
}
func (ph *ProtocolHttp) Connect(ctx context.Context, retrieval *retrieval, candidate types.RetrievalCandidate) (time.Duration, error) {
// We could begin the request here by moving ph.beginRequest() to this function.
// That would result in parallel connections to candidates as they are received,
// then serial reading of bodies.
// If/when we need to share connection state between a Connect() and Retrieve()
// call, we'll need a shared state that we can pass - either return a Context
// here that we pick up in Retrieve, or have something on `retrieval` that can
// be keyed by `candidate` to do this; or similar. ProtocolHttp is not
// per-connection, it's per-protocol, and `retrieval` is not per-candidate
// either, it's per-retrieval.
return 0, nil
}
func (ph *ProtocolHttp) Retrieve(
ctx context.Context,
retrieval *retrieval,
shared *retrievalShared,
timeout time.Duration,
candidate types.RetrievalCandidate,
) (*types.RetrievalStats, error) {
// Connect and read body in one flow, we can move ph.beginRequest() to Connect()
// to parallelise connections if we have confidence in not wasting server time
// by requesting but not reading bodies (or delayed reading which may result in
// timeouts).
retrievalStart := ph.Clock.Now()
resp, err := ph.beginRequest(ctx, retrieval.request, candidate)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, ErrHttpRequestFailure{Code: resp.StatusCode}
}
var expectDuplicates = trustlesshttp.DefaultIncludeDupes
if contentType, valid := trustlesshttp.ParseContentType(resp.Header.Get("Content-Type")); valid {
expectDuplicates = contentType.Duplicates
} // else be permissive and just expect duplicates (DefaultIncludeDupes)
var ttfb time.Duration
rdr := newTimeToFirstByteReader(resp.Body, func() {
ttfb = retrieval.Clock.Since(retrievalStart)
shared.sendEvent(ctx, events.FirstByte(retrieval.Clock.Now(), retrieval.request.RetrievalID, candidate, ttfb, multicodec.TransportIpfsGatewayHttp))
})
cfg := traversal.Config{
Root: retrieval.request.Root,
Selector: retrieval.request.GetSelector(),
ExpectDuplicatesIn: expectDuplicates,
// write out the same as we get in so we're not causing waste here,
// dealing with the actual output duplicates requirements can be done
// in a parent
WriteDuplicatesOut: expectDuplicates,
MaxBlocks: retrieval.request.MaxBlocks,
OnBlockIn: func(read uint64) {
shared.sendEvent(ctx, events.BlockReceived(retrieval.Clock.Now(), retrieval.request.RetrievalID, candidate, multicodec.TransportIpfsGatewayHttp, read))
},
}
traversalResult, err := cfg.VerifyCar(ctx, rdr, retrieval.request.LinkSystem)
if err != nil {
return nil, err
}
duration := retrieval.Clock.Since(retrievalStart)
speed := uint64(float64(traversalResult.BytesIn) / duration.Seconds())
return &types.RetrievalStats{
RootCid: candidate.RootCid,
StorageProviderId: candidate.MinerPeer.ID,
Size: traversalResult.BytesIn,
Blocks: traversalResult.BlocksIn,
Duration: duration,
AverageSpeed: speed,
TotalPayment: big.Zero(),
NumPayments: 0,
AskPrice: big.Zero(),
TimeToFirstByte: ttfb,
}, nil
}
func (ph *ProtocolHttp) beginRequest(ctx context.Context, request types.RetrievalRequest, candidate types.RetrievalCandidate) (resp *http.Response, err error) {
var req *http.Request
req, err = makeRequest(ctx, request, candidate)
logger.Debugf("HTTP request: %s", req.URL.String())
if err == nil {
resp, err = ph.Client.Do(req)
}
return resp, err
}
func makeRequest(ctx context.Context, request types.RetrievalRequest, candidate types.RetrievalCandidate) (*http.Request, error) {
candidateURL, err := candidate.ToURL()
if err != nil {
logger.Warnf("Couldn't construct a url for miner %s: %v", candidate.MinerPeer.ID, err)
return nil, fmt.Errorf("%w: %v", ErrNoHttpForPeer, err)
}
path, err := request.Request.UrlPath()
if err != nil {
logger.Warnf("Couldn't construct a url path for request: %v", err)
return nil, fmt.Errorf("%w: %v", ErrBadPathForRequest, err)
}
reqURL := fmt.Sprintf("%s/ipfs/%s%s", candidateURL, request.Root, path)
req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil)
if err != nil {
logger.Warnf("Couldn't construct a http request %s: %v", candidate.MinerPeer.ID, err)
return nil, fmt.Errorf("%w for peer %s: %v", ErrBadPathForRequest, candidate.MinerPeer.ID, err)
}
req.Header.Add("Accept", trustlesshttp.DefaultContentType().String()) // prefer duplicates
req.Header.Add("X-Request-Id", request.RetrievalID.String())
req.Header.Add("User-Agent", build.UserAgent)
return req, nil
}
var _ io.Reader = (*timeToFirstByteReader)(nil)
type timeToFirstByteReader struct {
r io.Reader
first bool
cb func()
}
func newTimeToFirstByteReader(r io.Reader, cb func()) *timeToFirstByteReader {
return &timeToFirstByteReader{
r: r,
cb: cb,
}
}
func (t *timeToFirstByteReader) Read(p []byte) (int, error) {
if !t.first {
t.first = true
defer t.cb()
}
return t.r.Read(p)
}