-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbasic.go
403 lines (346 loc) · 9.07 KB
/
basic.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
395
396
397
398
399
400
401
402
403
package collect
import (
"context"
"fmt"
"io/ioutil"
"math/rand"
"sync/atomic"
"github.com/bdware/go-libp2p-collect/pb"
"github.com/bdware/go-libp2p-collect/pubsub"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/protocol"
)
// BasicPubSubCollector implements of psc.BasicPubSubCollector Interface.
// It broadcasts request by libp2p.PubSub.
// When the remote nodes receive the request, they will try to dial the request node
// and return the response directly.
type BasicPubSubCollector struct {
// conf is static configuration of BasicPubSubCollector
conf *conf
// seqno is an increasing number to give each request ID
seqno uint64
host host.Host
// a wrapper of apsub system
apsub *AsyncPubSub
// RequestCache is a cache of requests.
// We don't know when there is no incoming response for a certain request.
// We have to eliminate the out-dated request resource.
// After elimination, the response related to this request will be ignored.
reqWorkerPool *requestWorkerPool
ridgen ReqIDFn
logger *standardLogger
}
// NewBasicPubSubCollector returns a new BasicPubSubCollector
func NewBasicPubSubCollector(h host.Host, options ...InitOpt) (bpsc *BasicPubSubCollector, err error) {
var (
opts *InitOpts
c *conf
apsub *AsyncPubSub
reqWorkerPool *requestWorkerPool
)
{
opts, err = NewInitOpts(options)
}
if err == nil {
c, err = checkOptConfAndGetInnerConf(&opts.Conf)
}
if err == nil {
apsub, err = NewAsyncPubSub(
h,
WithSelfNotif(true),
WithCustomPubSubFactory(
func(h host.Host) (*pubsub.PubSub, error) {
return pubsub.NewRandomSub(
// TODO: add context in initopts
context.TODO(),
h,
defaultRandomSubSize,
// we do the pubsub with conf.RequestProtocol
pubsub.WithCustomProtocols([]protocol.ID{c.requestProtocol}),
)
}),
)
}
if err == nil {
reqWorkerPool, err = newRequestWorkerPool(c.requestCacheSize)
}
if err == nil {
bpsc = &BasicPubSubCollector{
conf: c,
seqno: rand.Uint64(),
host: h,
apsub: apsub,
reqWorkerPool: reqWorkerPool,
ridgen: opts.ReqIDFn,
logger: &standardLogger{opts.Logger},
}
// add stream handler when responses return
bpsc.host.SetStreamHandler(bpsc.conf.responseProtocol, bpsc.streamHandler)
}
return
}
// Join the overlay network defined by topic
// Join the same topic is allowed here.
// Rejoin will refresh the requestHandler.
func (bpsc *BasicPubSubCollector) Join(topic string, opts ...JoinOpt) (err error) {
bpsc.logger.funcCall("debug", "Join",
map[string]interface{}{
"topic": topic,
})
var options *JoinOpts
{
options, err = NewJoinOptions(opts)
}
// subscribe the topic
if err == nil {
err = bpsc.apsub.Subscribe(topic, bpsc.topicHandle)
}
// register request handler
if err == nil {
err = bpsc.apsub.SetTopicItem(topic, requestHandlerKey, options.RequestHandler)
}
if err != nil {
bpsc.logger.error(err)
}
return
}
// Publish a serilized request payload.
func (bpsc *BasicPubSubCollector) Publish(topic string, payload []byte, opts ...PubOpt) (err error) {
bpsc.logger.funcCall("debug", "publish", map[string]interface{}{
"topic": topic,
})
var (
rqID RequestID
options *PubOpts
tosend []byte
)
{
options, err = NewPublishOptions(opts)
}
if err == nil {
myself := bpsc.host.ID()
req := &Request{
Control: pb.RequestControl{
Requester: myself,
Sender: myself,
Seqno: atomic.AddUint64(&(bpsc.seqno), 1),
},
Payload: payload,
}
rqID = bpsc.ridgen(req)
tosend, err = req.Marshal()
}
if err == nil {
// register notif handler
bpsc.reqWorkerPool.AddReqItem(options.RequestContext, rqID, &reqItem{
finalHandler: options.FinalRespHandle,
topic: topic,
})
// publish marshaled request
err = bpsc.apsub.Publish(options.RequestContext, topic, tosend)
}
if err != nil {
bpsc.logger.error(err)
}
return
}
// Leave the overlay.
// The registered topichandles and responseHandlers will be closed.
func (bpsc *BasicPubSubCollector) Leave(topic string) (err error) {
bpsc.logger.funcCall("debug", "leave", map[string]interface{}{
"topic": topic,
})
err = bpsc.apsub.Unsubscribe(topic)
bpsc.reqWorkerPool.RemoveTopic(topic)
if err != nil {
bpsc.logger.error(err)
}
return
}
// Close the BasicPubSubCollector.
func (bpsc *BasicPubSubCollector) Close() (err error) {
bpsc.logger.funcCall("debug", "close", nil)
bpsc.reqWorkerPool.RemoveAll()
err = bpsc.apsub.Close()
if err != nil {
bpsc.logger.error(err)
}
return
}
// topicHandle will be called when a request arrived.
func (bpsc *BasicPubSubCollector) topicHandle(topic string, msg *Message) {
bpsc.logger.funcCall("debug", "topicHandle", map[string]interface{}{
"topic": topic,
"receive-from": func() string {
if msg == nil {
return ""
}
return msg.ReceivedFrom.Pretty()
}(),
"from": func() string {
if msg == nil {
return ""
}
pid, err := peer.IDFromBytes(msg.From)
if err != nil {
return ""
}
return pid.Pretty()
}(),
})
var err error
if msg == nil {
err = fmt.Errorf("unexpected nil msg")
}
var (
ok bool
req *Request
rqhandleRaw interface{}
rqhandle RequestHandler
rqresult *Intermediate
rqID RequestID
resp *Response
respBytes []byte
s network.Stream
ctx context.Context
)
{
ctx = context.TODO()
// unmarshal the received data into request struct
req = &Request{}
err = req.Unmarshal(msg.Data)
}
if err == nil {
rqID = bpsc.ridgen(req)
// not self-publish, add a reqItem
if msg.ReceivedFrom != bpsc.host.ID() {
bpsc.reqWorkerPool.AddReqItem(context.Background(), rqID, &reqItem{
req: req,
topic: topic,
})
// clean up later
defer bpsc.reqWorkerPool.RemoveReqItem(rqID)
}
}
if err == nil {
// Dispatch request to relative topic request handler,
// which should be initialized in join function
rqhandleRaw, err = bpsc.apsub.LoadTopicItem(topic, requestHandlerKey)
if err != nil {
err = fmt.Errorf("cannot find request handler:%w", err)
} else {
rqhandle, ok = rqhandleRaw.(RequestHandler)
}
if err == nil && !ok {
err = fmt.Errorf("unexpected request handler type")
}
}
if err == nil {
// handle request
rqresult = rqhandle(ctx, req)
// After request is processed, we will have a Intermediate.
// We send the response to the root node directly if sendback is set to true.
// Another protocol will be used to inform the root node.
if rqresult == nil || !rqresult.Hit {
// drop any response if sendback is false or sendback == nil
bpsc.logger.message("info", "not sendback")
goto handleEnd
}
// assemble the response
resp = &Response{
Control: pb.ResponseControl{
RequestId: rqID,
},
Payload: rqresult.Payload,
}
respBytes, err = resp.Marshal()
}
if err == nil {
// receive self-published message
if req.Control.Requester == bpsc.host.ID() {
bpsc.logger.message("info", "self publish")
err = bpsc.handleFinalResponse(resp)
goto handleEnd
}
bpsc.logger.message("debug", "answering response")
s, err = bpsc.host.NewStream(ctx, req.Control.Requester, bpsc.conf.responseProtocol)
}
// everything is done, send payload by write to stream
if err == nil {
// don't forget to close the stream
defer s.Close()
_, err = s.Write(respBytes)
}
handleEnd:
if err != nil {
bpsc.logger.error(err)
}
}
// streamHandler reads response from stream, and calls related notifHandler
func (bpsc *BasicPubSubCollector) streamHandler(s network.Stream) {
bpsc.logger.funcCall("debug", "streamHandler", map[string]interface{}{
"from": s.Conn().RemotePeer().Pretty(),
})
var (
respBytes []byte
err error
)
defer s.Close()
respBytes, err = ioutil.ReadAll(s)
if err == nil {
err = bpsc.handleResponseBytes(respBytes)
}
if err != nil {
bpsc.logger.error(err)
}
}
// handleResponsePayload unmarshals the ResponseBytes, and calls the notifHandler
func (bpsc *BasicPubSubCollector) handleResponseBytes(respBytes []byte) (err error) {
var (
resp *Response
)
if err == nil {
resp = &Response{}
err = resp.Unmarshal(respBytes)
}
if err == nil {
err = bpsc.handleFinalResponse(resp)
}
return
}
// handleFinalResponse calls finalResponseHandler
func (bpsc *BasicPubSubCollector) handleFinalResponse(resp *Response) (err error) {
bpsc.logger.funcCall("debug", "handleFinalResponse", map[string]interface{}{
"receive-from": func() string {
if resp == nil {
return ""
}
return resp.Control.Sender.Pretty()
}(),
})
if resp == nil {
err = fmt.Errorf("unexpect nil response")
}
var (
reqID RequestID
item *reqItem
ok bool
)
if err == nil {
reqID = resp.Control.RequestId
item, ok, _ = bpsc.reqWorkerPool.GetReqItem(reqID)
if !ok {
err = fmt.Errorf("cannot find reqitem for request %s", reqID)
}
}
if err == nil {
// TODO: add context
item.finalHandler(context.TODO(), resp)
}
if err != nil {
bpsc.logger.error(err)
}
return err
}