-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrpc.go
391 lines (350 loc) · 8.93 KB
/
rpc.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
package rpc
import (
"context"
"errors"
"fmt"
"path"
"strings"
"sync"
"github.com/ipfs/go-cid"
util "github.com/ipfs/go-ipfs-util"
cbor "github.com/ipfs/go-ipld-cbor"
"github.com/libp2p/go-libp2p-core/peer"
pubsub "github.com/libp2p/go-libp2p-pubsub"
golog "github.com/textileio/go-log/v2"
)
var (
log = golog.Logger("psrpc")
// ErrResponseNotReceived indicates a response was not received after publishing a message.
ErrResponseNotReceived = errors.New("response not received")
)
// EventHandler is used to receive topic peer events.
type EventHandler func(from peer.ID, topic string, msg []byte)
// MessageHandler is used to receive topic messages.
type MessageHandler func(from peer.ID, topic string, msg []byte) ([]byte, error)
// Response wraps a message response.
type Response struct {
// ID is the cid.Cid of the received message.
ID string
// From is the peer.ID of the sender.
From peer.ID
// Data is the message data.
Data []byte
// Err is an error from the sender.
Err error
}
type internalResponse struct {
ID string
From []byte
Data []byte
Err string
}
func init() {
cbor.RegisterCborType(internalResponse{})
}
func responseTopic(base string, pid peer.ID) string {
return path.Join(base, pid.String(), "_response")
}
type ongoingMessage struct {
ctx context.Context
data []byte
opts []pubsub.PubOpt
respCh chan internalResponse
republish bool
}
// Topic provides a nice interface to a libp2p pubsub topic.
type Topic struct {
ps *pubsub.PubSub
host peer.ID
eventHandler EventHandler
messageHandler MessageHandler
ongoing map[cid.Cid]ongoingMessage
resTopic *Topic
t *pubsub.Topic
h *pubsub.TopicEventHandler
s *pubsub.Subscription
ctx context.Context
cancel context.CancelFunc
lk sync.Mutex
}
// NewTopic returns a new topic for the host.
func NewTopic(ctx context.Context, ps *pubsub.PubSub, host peer.ID, topic string, subscribe bool) (*Topic, error) {
t, err := newTopic(ctx, ps, host, topic, subscribe)
if err != nil {
return nil, fmt.Errorf("creating topic: %v", err)
}
t.resTopic, err = newTopic(ctx, ps, host, responseTopic(topic, host), true)
if err != nil {
_ = t.Close()
return nil, fmt.Errorf("creating response topic: %v", err)
}
t.resTopic.eventHandler = t.resEventHandler
t.resTopic.messageHandler = t.resMessageHandler
return t, nil
}
func newTopic(ctx context.Context, ps *pubsub.PubSub, host peer.ID, topic string, subscribe bool) (*Topic, error) {
top, err := ps.Join(topic)
if err != nil {
return nil, fmt.Errorf("joining topic: %v", err)
}
handler, err := top.EventHandler()
if err != nil {
_ = top.Close()
return nil, fmt.Errorf("getting topic handler: %v", err)
}
var sub *pubsub.Subscription
if subscribe {
sub, err = top.Subscribe()
if err != nil {
handler.Cancel()
_ = top.Close()
return nil, fmt.Errorf("subscribing to topic: %v", err)
}
}
t := &Topic{
ps: ps,
host: host,
t: top,
h: handler,
s: sub,
ongoing: make(map[cid.Cid]ongoingMessage),
}
t.ctx, t.cancel = context.WithCancel(ctx)
go t.watch()
if t.s != nil {
go t.listen()
}
return t, nil
}
// Close the topic.
func (t *Topic) Close() error {
t.lk.Lock()
defer t.lk.Unlock()
t.cancel()
t.h.Cancel()
if t.s != nil {
t.s.Cancel()
}
if err := t.t.Close(); err != nil {
return err
}
if t.resTopic != nil {
return t.resTopic.Close()
}
return nil
}
// SetEventHandler sets a handler func that will be called with peer events.
func (t *Topic) SetEventHandler(handler EventHandler) {
t.lk.Lock()
defer t.lk.Unlock()
t.eventHandler = handler
}
// SetMessageHandler sets a handler func that will be called with topic messages.
// A subscription is required for the handler to be called.
func (t *Topic) SetMessageHandler(handler MessageHandler) {
t.lk.Lock()
defer t.lk.Unlock()
t.messageHandler = handler
}
// Publish data. Note that the data may arrive peers duplicated. And as a
// result, if WithMultiResponse is supplied, the response may be duplicated as
// well. See PublishOptions for option details.
func (t *Topic) Publish(
ctx context.Context,
data []byte,
opts ...PublishOption,
) (<-chan Response, error) {
args := defaultOptions
for _, op := range opts {
if err := op(&args); err != nil {
return nil, fmt.Errorf("applying option: %v", err)
}
}
var respCh chan internalResponse
msgID := cid.NewCidV1(cid.Raw, util.Hash(data))
if !args.ignoreResponse {
respCh = make(chan internalResponse)
}
if !args.ignoreResponse || args.republish {
t.lk.Lock()
t.ongoing[msgID] = ongoingMessage{
ctx: ctx,
data: data,
opts: args.pubOpts,
respCh: respCh,
republish: args.republish,
}
t.lk.Unlock()
}
if err := t.t.Publish(ctx, data, args.pubOpts...); err != nil {
return nil, fmt.Errorf("publishing to topic: %v", err)
}
if args.ignoreResponse && !args.republish {
return nil, nil
}
resultCh := make(chan Response)
go func() {
defer func() {
t.lk.Lock()
delete(t.ongoing, msgID)
t.lk.Unlock()
close(resultCh)
}()
for {
select {
case <-ctx.Done():
if args.ignoreResponse {
return
}
if !args.multiResponse {
resultCh <- Response{Err: ErrResponseNotReceived}
}
return
case r := <-respCh:
res := Response{
ID: r.ID,
From: peer.ID(r.From),
Data: r.Data,
}
if r.Err != "" {
res.Err = errors.New(r.Err)
}
if !args.ignoreResponse {
resultCh <- res
}
if !args.multiResponse {
return
}
}
}
}()
return resultCh, nil
}
func (t *Topic) watch() {
for {
e, err := t.h.NextPeerEvent(t.ctx)
if err != nil {
break
}
var msg string
switch e.Type {
case pubsub.PeerJoin:
msg = "JOINED"
// Note: it looks like we are publishing to this
// specific peer, but the rpc library doesn't have the
// ability, so it actually does is to republish to all
// peers.
t.republishTo(e.Peer)
case pubsub.PeerLeave:
msg = "LEFT"
default:
continue
}
t.lk.Lock()
if t.eventHandler != nil {
t.eventHandler(e.Peer, t.t.String(), []byte(msg))
}
t.lk.Unlock()
}
}
func (t *Topic) republishTo(p peer.ID) {
t.lk.Lock()
for _, m := range t.ongoing {
if m.republish {
go func(m ongoingMessage) {
log.Debugf("republishing %s because peer %s newly joins", t.t, p)
if err := t.t.Publish(m.ctx, m.data, m.opts...); err != nil {
log.Errorf("republishing to topic: %v", err)
}
}(m)
}
}
t.lk.Unlock()
}
func (t *Topic) listen() {
for {
msg, err := t.s.Next(t.ctx)
if err != nil {
break
}
if msg.ReceivedFrom.String() == t.host.String() {
continue
}
t.lk.Lock()
handler := t.messageHandler
t.lk.Unlock()
if handler == nil {
log.Warnf("didn't process topic message since we don't have a handler")
continue
}
go processSubscriptionMessage(handler, msg.ReceivedFrom, t, msg.Data)
}
}
func processSubscriptionMessage(handler MessageHandler, from peer.ID, t *Topic, msgData []byte) {
res, err := handler(from, t.t.String(), msgData)
if err != nil {
log.Errorf("subcription message handler: %v", err)
// Intentionally not returning since we send the error
// to the other side in the response.
}
if !strings.Contains(t.t.String(), "/_response") {
// This is a normal message; respond with data and error
msgID := cid.NewCidV1(cid.Raw, util.Hash(msgData))
t.publishResponse(from, msgID, res, err)
}
}
func (t *Topic) publishResponse(from peer.ID, id cid.Cid, data []byte, e error) {
topic, err := newTopic(t.ctx, t.ps, t.host, responseTopic(t.t.String(), from), false)
if err != nil {
log.Errorf("creating response topic: %v", err)
return
}
defer func() {
if err := topic.Close(); err != nil {
log.Errorf("closing response topic: %v", err)
}
}()
topic.SetEventHandler(t.resEventHandler)
res := internalResponse{
ID: id.String(),
// From: Set on the receiver end using validated data from the received pubsub message
Data: data,
}
if e != nil {
res.Err = e.Error()
}
msg, err := cbor.DumpObject(&res)
if err != nil {
log.Errorf("encoding response: %v", err)
return
}
if err := topic.t.Publish(t.ctx, msg); err != nil {
log.Errorf("publishing response: %v", err)
}
}
func (t *Topic) resEventHandler(from peer.ID, topic string, msg []byte) {
log.Debugf("%s response peer event: %s %s", topic, from, msg)
}
func (t *Topic) resMessageHandler(from peer.ID, topic string, msg []byte) ([]byte, error) {
var res internalResponse
if err := cbor.DecodeInto(msg, &res); err != nil {
return nil, fmt.Errorf("decoding response: %v", err)
}
id, err := cid.Decode(res.ID)
if err != nil {
return nil, fmt.Errorf("decoding response id: %v", err)
}
res.From = []byte(from)
log.Debugf("%s response from %s: %s", topic, from, res.ID)
t.lk.Lock()
m, exists := t.ongoing[id]
t.lk.Unlock()
if exists {
if m.respCh != nil {
m.respCh <- res
}
} else {
log.Debugf("%s response from %s arrives too late, discarding", topic, from)
}
return nil, nil // no response to a response
}