-
Notifications
You must be signed in to change notification settings - Fork 38
/
server.go
379 lines (346 loc) · 11.8 KB
/
server.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
package responsemanager
import (
"context"
"errors"
"math"
"time"
"github.com/ipfs/go-peertaskqueue/peertask"
"github.com/ipfs/go-peertaskqueue/peertracker"
"github.com/libp2p/go-libp2p-core/peer"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"github.com/ipfs/go-graphsync"
"github.com/ipfs/go-graphsync/ipldutil"
gsmsg "github.com/ipfs/go-graphsync/message"
"github.com/ipfs/go-graphsync/peerstate"
"github.com/ipfs/go-graphsync/responsemanager/hooks"
"github.com/ipfs/go-graphsync/responsemanager/queryexecutor"
"github.com/ipfs/go-graphsync/responsemanager/responseassembler"
)
// The code in this file implements the internal thread for the response manager.
// These functions can modify the internal state of the ResponseManager
func (rm *ResponseManager) cleanupInProcessResponses() {
for _, response := range rm.inProgressResponses {
response.cancelFn()
}
}
func (rm *ResponseManager) run() {
defer rm.cleanupInProcessResponses()
for {
select {
case <-rm.ctx.Done():
return
case message := <-rm.messages:
message.handle(rm)
}
}
}
func (rm *ResponseManager) terminateRequest(key responseKey) {
ipr, ok := rm.inProgressResponses[key]
if !ok {
return
}
rm.connManager.Unprotect(key.p, key.requestID.Tag())
delete(rm.inProgressResponses, key)
ipr.cancelFn()
ipr.span.End()
}
func (rm *ResponseManager) processUpdate(ctx context.Context, key responseKey, update gsmsg.GraphSyncRequest) {
response, ok := rm.inProgressResponses[key]
if !ok || response.state == graphsync.CompletingSend {
log.Warnf("received update for non existent request, peer %s, request ID %d", key.p.Pretty(), key.requestID)
return
}
_, span := otel.Tracer("graphsync").Start(
trace.ContextWithSpan(ctx, response.span),
"processUpdate",
trace.WithLinks(trace.LinkFromContext(ctx)),
trace.WithAttributes(
attribute.Int("id", int(update.ID())),
attribute.StringSlice("extensions", update.ExtensionNames()),
))
defer span.End()
if response.state != graphsync.Paused {
response.updates = append(response.updates, update)
select {
case response.signals.UpdateSignal <- struct{}{}:
default:
}
return
} // else this is a paused response, so the update needs to be handled here and not in the executor
result := rm.updateHooks.ProcessUpdateHooks(key.p, response.request, update)
_ = response.responseStream.Transaction(func(rb responseassembler.ResponseBuilder) error {
for _, extension := range result.Extensions {
rb.SendExtensionData(extension)
}
if result.Err != nil {
rb.FinishWithError(graphsync.RequestFailedUnknown)
}
return nil
})
if result.Err != nil {
response.state = graphsync.CompletingSend
response.span.RecordError(result.Err)
response.span.SetStatus(codes.Error, result.Err.Error())
return
}
if result.Unpause {
err := rm.unpauseRequest(key.p, key.requestID)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, result.Err.Error())
log.Warnf("error unpausing request: %s", err.Error())
}
}
}
func (rm *ResponseManager) unpauseRequest(p peer.ID, requestID graphsync.RequestID, extensions ...graphsync.ExtensionData) error {
key := responseKey{p, requestID}
inProgressResponse, ok := rm.inProgressResponses[key]
if !ok {
return errors.New("could not find request")
}
if inProgressResponse.state != graphsync.Paused {
return errors.New("request is not paused")
}
inProgressResponse.state = graphsync.Queued
if len(extensions) > 0 {
_ = inProgressResponse.responseStream.Transaction(func(rb responseassembler.ResponseBuilder) error {
for _, extension := range extensions {
rb.SendExtensionData(extension)
}
return nil
})
}
rm.responseQueue.PushTask(p, peertask.Task{Topic: key, Priority: math.MaxInt32, Work: 1})
return nil
}
func (rm *ResponseManager) abortRequest(ctx context.Context, p peer.ID, requestID graphsync.RequestID, err error) error {
key := responseKey{p, requestID}
rm.responseQueue.Remove(key, key.p)
response, ok := rm.inProgressResponses[key]
if !ok || response.state == graphsync.CompletingSend {
return errors.New("could not find request")
}
_, span := otel.Tracer("graphsync").Start(trace.ContextWithSpan(ctx, response.span),
"abortRequest",
trace.WithLinks(trace.LinkFromContext(ctx)),
)
defer span.End()
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
response.span.RecordError(err)
response.span.SetStatus(codes.Error, err.Error())
if response.state != graphsync.Running {
if ipldutil.IsContextCancelErr(err) {
response.responseStream.ClearRequest()
rm.terminateRequest(key)
rm.cancelledListeners.NotifyCancelledListeners(p, response.request)
return nil
}
if err == queryexecutor.ErrNetworkError {
response.responseStream.ClearRequest()
rm.terminateRequest(key)
return nil
}
response.state = graphsync.CompletingSend
return response.responseStream.Transaction(func(rb responseassembler.ResponseBuilder) error {
rb.FinishWithError(graphsync.RequestCancelled)
return nil
})
}
select {
case response.signals.ErrSignal <- err:
default:
}
return nil
}
func (rm *ResponseManager) processRequests(p peer.ID, requests []gsmsg.GraphSyncRequest) {
ctx, messageSpan := otel.Tracer("graphsync").Start(
rm.ctx,
"processRequests",
trace.WithAttributes(attribute.String("peerID", p.Pretty())),
)
defer messageSpan.End()
for _, request := range requests {
key := responseKey{p: p, requestID: request.ID()}
if request.IsCancel() {
_ = rm.abortRequest(ctx, p, request.ID(), ipldutil.ContextCancelError{})
continue
}
if request.IsUpdate() {
rm.processUpdate(ctx, key, request)
continue
}
rm.connManager.Protect(p, request.ID().Tag())
// don't use `ctx` which has the "message" trace, but rm.ctx for a fresh trace which allows
// for a request hook to join this particular response up to an existing external trace
rctx := rm.requestQueuedHooks.ProcessRequestQueuedHooks(p, request, rm.ctx)
rctx, responseSpan := otel.Tracer("graphsync").Start(
rctx,
"response",
trace.WithLinks(trace.LinkFromContext(ctx)),
trace.WithAttributes(
attribute.Int("id", int(request.ID())),
attribute.Int("priority", int(request.Priority())),
attribute.String("root", request.Root().String()),
attribute.StringSlice("extensions", request.ExtensionNames()),
))
rctx, cancelFn := context.WithCancel(rctx)
sub := &subscriber{
p: key.p,
request: request,
requestCloser: rm,
blockSentListeners: rm.blockSentListeners,
completedListeners: rm.completedListeners,
networkErrorListeners: rm.networkErrorListeners,
connManager: rm.connManager,
}
log.Infow("graphsync request initiated", "request id", request.ID(), "peer", p, "root", request.Root())
ipr, ok := rm.inProgressResponses[key]
if ok && ipr.state == graphsync.Running {
log.Warnf("there is an identical request already in progress", "request id", request.ID(), "peer", p)
}
rm.inProgressResponses[key] =
&inProgressResponseStatus{
ctx: rctx,
span: responseSpan,
cancelFn: cancelFn,
request: request,
signals: queryexecutor.ResponseSignals{
PauseSignal: make(chan struct{}, 1),
UpdateSignal: make(chan struct{}, 1),
ErrSignal: make(chan error, 1),
},
state: graphsync.Queued,
startTime: time.Now(),
responseStream: rm.responseAssembler.NewStream(ctx, key.p, key.requestID, sub),
}
// TODO: Use a better work estimation metric.
rm.responseQueue.PushTask(p, peertask.Task{Topic: key, Priority: int(request.Priority()), Work: 1})
}
}
func (rm *ResponseManager) taskDataForKey(key responseKey) queryexecutor.ResponseTask {
response, hasResponse := rm.inProgressResponses[key]
if !hasResponse || response.state == graphsync.CompletingSend {
return queryexecutor.ResponseTask{Empty: true}
}
log.Infow("graphsync response processing begins", "request id", key.requestID, "peer", key.p, "total time", time.Since(response.startTime))
if response.loader == nil || response.traverser == nil {
loader, traverser, isPaused, err := (&queryPreparer{rm.requestHooks, rm.linkSystem, rm.maxLinksPerRequest}).prepareQuery(response.ctx, key.p, response.request, response.responseStream, response.signals)
if err != nil {
response.state = graphsync.CompletingSend
response.span.RecordError(err)
response.span.SetStatus(codes.Error, err.Error())
return queryexecutor.ResponseTask{Empty: true}
}
response.loader = loader
response.traverser = traverser
if isPaused {
response.state = graphsync.Paused
return queryexecutor.ResponseTask{Empty: true}
}
}
response.state = graphsync.Running
return queryexecutor.ResponseTask{
Ctx: response.ctx,
Span: response.span,
Empty: false,
Request: response.request,
Loader: response.loader,
Traverser: response.traverser,
Signals: response.signals,
ResponseStream: response.responseStream,
}
}
func (rm *ResponseManager) startTask(task *peertask.Task) queryexecutor.ResponseTask {
key := task.Topic.(responseKey)
taskData := rm.taskDataForKey(key)
if taskData.Empty {
rm.responseQueue.TaskDone(key.p, task)
}
return taskData
}
func (rm *ResponseManager) finishTask(task *peertask.Task, err error) {
key := task.Topic.(responseKey)
rm.responseQueue.TaskDone(key.p, task)
response, ok := rm.inProgressResponses[key]
if !ok {
return
}
if _, ok := err.(hooks.ErrPaused); ok {
response.state = graphsync.Paused
return
}
log.Infow("graphsync response processing complete (messages stil sending)", "request id", key.requestID, "peer", key.p, "total time", time.Since(response.startTime))
if err != nil {
response.span.RecordError(err)
response.span.SetStatus(codes.Error, err.Error())
log.Infof("response failed: %w", err)
}
if ipldutil.IsContextCancelErr(err) {
rm.cancelledListeners.NotifyCancelledListeners(key.p, response.request)
rm.terminateRequest(key)
return
}
if err == queryexecutor.ErrNetworkError {
rm.terminateRequest(key)
return
}
response.state = graphsync.CompletingSend
}
func (rm *ResponseManager) getUpdates(key responseKey) []gsmsg.GraphSyncRequest {
response, ok := rm.inProgressResponses[key]
if !ok {
return nil
}
updates := response.updates
response.updates = nil
return updates
}
func (rm *ResponseManager) pauseRequest(p peer.ID, requestID graphsync.RequestID) error {
key := responseKey{p, requestID}
inProgressResponse, ok := rm.inProgressResponses[key]
if !ok || inProgressResponse.state == graphsync.CompletingSend {
return errors.New("could not find request")
}
if inProgressResponse.state == graphsync.Paused {
return errors.New("request is already paused")
}
select {
case inProgressResponse.signals.PauseSignal <- struct{}{}:
default:
}
return nil
}
func (rm *ResponseManager) peerState(p peer.ID) peerstate.PeerState {
var peerState peerstate.PeerState
rm.responseQueue.WithPeerTopics(p, func(peerTopics *peertracker.PeerTrackerTopics) {
requestStates := make(graphsync.RequestStates)
for key, ipr := range rm.inProgressResponses {
if key.p == p {
requestStates[key.requestID] = ipr.state
}
}
peerState = peerstate.PeerState{RequestStates: requestStates, TaskQueueState: fromPeerTopics(peerTopics)}
})
return peerState
}
func fromPeerTopics(pt *peertracker.PeerTrackerTopics) peerstate.TaskQueueState {
if pt == nil {
return peerstate.TaskQueueState{}
}
active := make([]graphsync.RequestID, 0, len(pt.Active))
for _, topic := range pt.Active {
active = append(active, topic.(responseKey).requestID)
}
pending := make([]graphsync.RequestID, 0, len(pt.Pending))
for _, topic := range pt.Pending {
pending = append(pending, topic.(responseKey).requestID)
}
return peerstate.TaskQueueState{
Active: active,
Pending: pending,
}
}