This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 178
/
pubsub.go
79 lines (70 loc) · 1.68 KB
/
pubsub.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
package shell
import (
"encoding/json"
"io"
"github.com/libp2p/go-libp2p/core/peer"
mbase "github.com/multiformats/go-multibase"
)
// Message is a pubsub message.
type Message struct {
From peer.ID
Data []byte
Seqno []byte
TopicIDs []string
}
// PubSubSubscription allow you to receive pubsub records that where published on the network.
type PubSubSubscription struct {
resp io.Closer
dec *json.Decoder
}
func newPubSubSubscription(resp io.ReadCloser) *PubSubSubscription {
return &PubSubSubscription{
resp: resp,
dec: json.NewDecoder(resp),
}
}
// Next waits for the next record and returns that.
func (s *PubSubSubscription) Next() (*Message, error) {
var r struct {
From string `json:"from,omitempty"`
Data string `json:"data,omitempty"`
Seqno string `json:"seqno,omitempty"`
TopicIDs []string `json:"topicIDs,omitempty"`
}
err := s.dec.Decode(&r)
if err != nil {
return nil, err
}
// fields are wrapped in multibase when sent over HTTP RPC
// and need to be decoded (https://github.com/ipfs/go-ipfs/pull/8183)
from, err := peer.Decode(r.From)
if err != nil {
return nil, err
}
_, data, err := mbase.Decode(r.Data)
if err != nil {
return nil, err
}
_, seqno, err := mbase.Decode(r.Seqno)
if err != nil {
return nil, err
}
topics := make([]string, len(r.TopicIDs))
for i, mbtopic := range r.TopicIDs {
_, topic, err := mbase.Decode(mbtopic)
if err != nil {
return nil, err
}
topics[i] = string(topic)
}
return &Message{
From: from,
Data: data,
Seqno: seqno,
TopicIDs: topics,
}, nil
}
// Cancel cancels the given subscription.
func (s *PubSubSubscription) Cancel() error {
return s.resp.Close()
}