-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathclient.go
394 lines (348 loc) · 13.1 KB
/
client.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package requestmanager
import (
"context"
"errors"
"fmt"
"sync/atomic"
"time"
"github.com/hannahhoward/go-pubsub"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
logging "github.com/ipfs/go-log/v2"
"github.com/ipfs/go-peertaskqueue/peertask"
"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/traversal"
"github.com/ipld/go-ipld-prime/traversal/selector"
"github.com/libp2p/go-libp2p-core/peer"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"github.com/ipfs/go-graphsync"
"github.com/ipfs/go-graphsync/ipldutil"
"github.com/ipfs/go-graphsync/listeners"
gsmsg "github.com/ipfs/go-graphsync/message"
"github.com/ipfs/go-graphsync/messagequeue"
"github.com/ipfs/go-graphsync/metadata"
"github.com/ipfs/go-graphsync/network"
"github.com/ipfs/go-graphsync/notifications"
"github.com/ipfs/go-graphsync/requestmanager/executor"
"github.com/ipfs/go-graphsync/requestmanager/hooks"
"github.com/ipfs/go-graphsync/requestmanager/types"
"github.com/ipfs/go-graphsync/taskqueue"
)
// The code in this file implements the public interface of the request manager.
// Functions in this file operate outside the internal thread and should
// NOT modify the internal state of the RequestManager.
var log = logging.Logger("graphsync")
const (
// defaultPriority is the default priority for requests sent by graphsync
defaultPriority = graphsync.Priority(0)
)
type inProgressRequestStatus struct {
ctx context.Context
span trace.Span
startTime time.Time
cancelFn func()
p peer.ID
terminalError error
pauseMessages chan struct{}
state graphsync.RequestState
lastResponse atomic.Value
onTerminated []chan<- error
request gsmsg.GraphSyncRequest
doNotSendCids *cid.Set
nodeStyleChooser traversal.LinkTargetNodePrototypeChooser
inProgressChan chan graphsync.ResponseProgress
inProgressErr chan error
traverser ipldutil.Traverser
traverserCancel context.CancelFunc
}
// PeerHandler is an interface that can send requests to peers
type PeerHandler interface {
AllocateAndBuildMessage(p peer.ID, blkSize uint64, buildMessageFn func(*gsmsg.Builder), notifees []notifications.Notifee)
}
// AsyncLoader is an interface for loading links asynchronously, returning
// results as new responses are processed
type AsyncLoader interface {
StartRequest(graphsync.RequestID, string) error
ProcessResponse(responses map[graphsync.RequestID]metadata.Metadata,
blks []blocks.Block)
AsyncLoad(p peer.ID, requestID graphsync.RequestID, link ipld.Link, linkContext ipld.LinkContext) <-chan types.AsyncLoadResult
CompleteResponsesFor(requestID graphsync.RequestID)
CleanupRequest(p peer.ID, requestID graphsync.RequestID)
}
// RequestManager tracks outgoing requests and processes incoming reponses
// to them.
type RequestManager struct {
ctx context.Context
cancel context.CancelFunc
messages chan requestManagerMessage
peerHandler PeerHandler
rc *responseCollector
asyncLoader AsyncLoader
disconnectNotif *pubsub.PubSub
linkSystem ipld.LinkSystem
connManager network.ConnManager
// maximum number of links to traverse per request. A value of zero = infinity, or no limit
maxLinksPerRequest uint64
// dont touch out side of run loop
nextRequestID graphsync.RequestID
inProgressRequestStatuses map[graphsync.RequestID]*inProgressRequestStatus
requestHooks RequestHooks
responseHooks ResponseHooks
networkErrorListeners *listeners.NetworkErrorListeners
outgoingRequestProcessingListeners *listeners.OutgoingRequestProcessingListeners
requestQueue taskqueue.TaskQueue
}
type requestManagerMessage interface {
handle(rm *RequestManager)
}
// RequestHooks run for new requests
type RequestHooks interface {
ProcessRequestHooks(p peer.ID, request graphsync.RequestData) hooks.RequestResult
}
// ResponseHooks run for new responses
type ResponseHooks interface {
ProcessResponseHooks(p peer.ID, response graphsync.ResponseData) hooks.UpdateResult
}
// New generates a new request manager from a context, network, and selectorQuerier
func New(ctx context.Context,
asyncLoader AsyncLoader,
linkSystem ipld.LinkSystem,
requestHooks RequestHooks,
responseHooks ResponseHooks,
networkErrorListeners *listeners.NetworkErrorListeners,
outgoingRequestProcessingListeners *listeners.OutgoingRequestProcessingListeners,
requestQueue taskqueue.TaskQueue,
connManager network.ConnManager,
maxLinksPerRequest uint64,
) *RequestManager {
ctx, cancel := context.WithCancel(ctx)
return &RequestManager{
ctx: ctx,
cancel: cancel,
asyncLoader: asyncLoader,
disconnectNotif: pubsub.New(disconnectDispatcher),
linkSystem: linkSystem,
rc: newResponseCollector(ctx),
messages: make(chan requestManagerMessage, 16),
inProgressRequestStatuses: make(map[graphsync.RequestID]*inProgressRequestStatus),
requestHooks: requestHooks,
responseHooks: responseHooks,
networkErrorListeners: networkErrorListeners,
outgoingRequestProcessingListeners: outgoingRequestProcessingListeners,
requestQueue: requestQueue,
connManager: connManager,
maxLinksPerRequest: maxLinksPerRequest,
}
}
// SetDelegate specifies who will send messages out to the internet.
func (rm *RequestManager) SetDelegate(peerHandler PeerHandler) {
rm.peerHandler = peerHandler
}
type inProgressRequest struct {
requestID graphsync.RequestID
request gsmsg.GraphSyncRequest
incoming chan graphsync.ResponseProgress
incomingError chan error
}
// NewRequest initiates a new GraphSync request to the given peer.
func (rm *RequestManager) NewRequest(ctx context.Context,
p peer.ID,
root ipld.Link,
selectorNode ipld.Node,
extensions ...graphsync.ExtensionData) (<-chan graphsync.ResponseProgress, <-chan error) {
span := trace.SpanFromContext(ctx)
if _, err := selector.ParseSelector(selectorNode); err != nil {
err := fmt.Errorf("invalid selector spec")
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
defer span.End()
return rm.singleErrorResponse(err)
}
inProgressRequestChan := make(chan inProgressRequest)
rm.send(&newRequestMessage{span, p, root, selectorNode, extensions, inProgressRequestChan}, ctx.Done())
var receivedInProgressRequest inProgressRequest
select {
case <-rm.ctx.Done():
return rm.emptyResponse()
case receivedInProgressRequest = <-inProgressRequestChan:
}
// If the connection to the peer is disconnected, fire an error
unsub := rm.listenForDisconnect(p, func(neterr error) {
rm.networkErrorListeners.NotifyNetworkErrorListeners(p, receivedInProgressRequest.request, neterr)
})
return rm.rc.collectResponses(ctx,
receivedInProgressRequest.incoming,
receivedInProgressRequest.incomingError,
func() {
rm.cancelRequestAndClose(receivedInProgressRequest.requestID,
receivedInProgressRequest.incoming,
receivedInProgressRequest.incomingError)
},
// Once the request has completed, stop listening for disconnect events
unsub,
)
}
// Dispatch the Disconnect event to subscribers
func disconnectDispatcher(p pubsub.Event, subscriberFn pubsub.SubscriberFn) error {
listener := subscriberFn.(func(peer.ID))
listener(p.(peer.ID))
return nil
}
// Listen for the Disconnect event for the given peer
func (rm *RequestManager) listenForDisconnect(p peer.ID, onDisconnect func(neterr error)) func() {
// Subscribe to Disconnect notifications
return rm.disconnectNotif.Subscribe(func(evtPeer peer.ID) {
// If the peer is the one we're interested in, call the listener
if evtPeer == p {
onDisconnect(fmt.Errorf("disconnected from peer %s", p))
}
})
}
// Disconnected is called when a peer disconnects
func (rm *RequestManager) Disconnected(p peer.ID) {
// Notify any listeners that a peer has disconnected
_ = rm.disconnectNotif.Publish(p)
}
func (rm *RequestManager) emptyResponse() (chan graphsync.ResponseProgress, chan error) {
ch := make(chan graphsync.ResponseProgress)
close(ch)
errCh := make(chan error)
close(errCh)
return ch, errCh
}
func (rm *RequestManager) singleErrorResponse(err error) (chan graphsync.ResponseProgress, chan error) {
ch := make(chan graphsync.ResponseProgress)
close(ch)
errCh := make(chan error, 1)
errCh <- err
close(errCh)
return ch, errCh
}
func (rm *RequestManager) cancelRequestAndClose(requestID graphsync.RequestID,
incomingResponses chan graphsync.ResponseProgress,
incomingErrors chan error) {
cancelMessageChannel := rm.messages
for cancelMessageChannel != nil || incomingResponses != nil || incomingErrors != nil {
select {
case cancelMessageChannel <- &cancelRequestMessage{requestID, nil, nil}:
cancelMessageChannel = nil
// clear out any remaining responses, in case and "incoming reponse"
// messages get processed before our cancel message
case _, ok := <-incomingResponses:
if !ok {
incomingResponses = nil
}
case _, ok := <-incomingErrors:
if !ok {
incomingErrors = nil
}
case <-rm.ctx.Done():
return
}
}
}
// CancelRequest cancels the given request ID and waits for the request to terminate
func (rm *RequestManager) CancelRequest(ctx context.Context, requestID graphsync.RequestID) error {
terminated := make(chan error, 1)
rm.send(&cancelRequestMessage{requestID, terminated, graphsync.RequestClientCancelledErr{}}, ctx.Done())
select {
case <-rm.ctx.Done():
return errors.New("context cancelled")
case err := <-terminated:
return err
}
}
// ProcessResponses ingests the given responses from the network and
// and updates the in progress requests based on those responses.
func (rm *RequestManager) ProcessResponses(p peer.ID, responses []gsmsg.GraphSyncResponse,
blks []blocks.Block) {
rm.send(&processResponseMessage{p, responses, blks}, nil)
}
// UnpauseRequest unpauses a request that was paused in a block hook based request ID
// Can also send extensions with unpause
func (rm *RequestManager) UnpauseRequest(requestID graphsync.RequestID, extensions ...graphsync.ExtensionData) error {
response := make(chan error, 1)
rm.send(&unpauseRequestMessage{requestID, extensions, response}, nil)
select {
case <-rm.ctx.Done():
return errors.New("context cancelled")
case err := <-response:
return err
}
}
// PauseRequest pauses an in progress request (may take 1 or more blocks to process)
func (rm *RequestManager) PauseRequest(requestID graphsync.RequestID) error {
response := make(chan error, 1)
rm.send(&pauseRequestMessage{requestID, response}, nil)
select {
case <-rm.ctx.Done():
return errors.New("context cancelled")
case err := <-response:
return err
}
}
// GetRequestTask gets data for the given task in the request queue
func (rm *RequestManager) GetRequestTask(p peer.ID, task *peertask.Task, requestExecutionChan chan executor.RequestTask) {
rm.send(&getRequestTaskMessage{p, task, requestExecutionChan}, nil)
}
// ReleaseRequestTask releases a task request the requestQueue
func (rm *RequestManager) ReleaseRequestTask(p peer.ID, task *peertask.Task, err error) {
done := make(chan struct{}, 1)
rm.send(&releaseRequestTaskMessage{p, task, err, done}, nil)
select {
case <-rm.ctx.Done():
case <-done:
}
}
// PeerStats gets stats on all outgoing requests for a given peer
func (rm *RequestManager) PeerStats(p peer.ID) graphsync.RequestStates {
response := make(chan graphsync.RequestStates)
rm.send(&peerStatsMessage{p, response}, nil)
select {
case <-rm.ctx.Done():
return nil
case peerStats := <-response:
return peerStats
}
}
// SendRequest sends a request to the message queue
func (rm *RequestManager) SendRequest(p peer.ID, request gsmsg.GraphSyncRequest) {
sub := notifications.NewTopicDataSubscriber(&reqSubscriber{p, request, rm.networkErrorListeners})
failNotifee := notifications.Notifee{Data: requestNetworkError, Subscriber: sub}
rm.peerHandler.AllocateAndBuildMessage(p, 0, func(builder *gsmsg.Builder) {
builder.AddRequest(request)
}, []notifications.Notifee{failNotifee})
}
// Startup starts processing for the WantManager.
func (rm *RequestManager) Startup() {
go rm.run()
}
// Shutdown ends processing for the want manager.
func (rm *RequestManager) Shutdown() {
rm.cancel()
}
func (rm *RequestManager) send(message requestManagerMessage, done <-chan struct{}) {
select {
case <-rm.ctx.Done():
case <-done:
case rm.messages <- message:
}
}
type reqSubscriber struct {
p peer.ID
request gsmsg.GraphSyncRequest
networkErrorListeners *listeners.NetworkErrorListeners
}
func (r *reqSubscriber) OnNext(topic notifications.Topic, event notifications.Event) {
mqEvt, isMQEvt := event.(messagequeue.Event)
if !isMQEvt || mqEvt.Name != messagequeue.Error {
return
}
r.networkErrorListeners.NotifyNetworkErrorListeners(r.p, r.request, mqEvt.Err)
//r.re.networkError <- mqEvt.Err
//r.re.terminateRequest()
}
func (r reqSubscriber) OnClose(topic notifications.Topic) {
}
const requestNetworkError = "request_network_error"