|
| 1 | +package shell |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/binary" |
| 5 | + "encoding/json" |
| 6 | + |
| 7 | + "github.com/libp2p/go-floodsub" |
| 8 | + "github.com/libp2p/go-libp2p-peer" |
| 9 | +) |
| 10 | + |
| 11 | +// PubSubRecord is a record received via PubSub. |
| 12 | +type PubSubRecord interface { |
| 13 | + // From returns the peer ID of the node that published this record |
| 14 | + From() peer.ID |
| 15 | + |
| 16 | + // Data returns the data field |
| 17 | + Data() []byte |
| 18 | + |
| 19 | + // SeqNo is the sequence number of this record |
| 20 | + SeqNo() int64 |
| 21 | + |
| 22 | + //TopicIDs is the list of topics this record belongs to |
| 23 | + TopicIDs() []string |
| 24 | +} |
| 25 | + |
| 26 | +type floodsubRecord struct { |
| 27 | + msg *floodsub.Message |
| 28 | +} |
| 29 | + |
| 30 | +func (r floodsubRecord) From() peer.ID { |
| 31 | + return r.msg.GetFrom() |
| 32 | +} |
| 33 | + |
| 34 | +func (r floodsubRecord) Data() []byte { |
| 35 | + return r.msg.GetData() |
| 36 | +} |
| 37 | + |
| 38 | +func (r floodsubRecord) SeqNo() int64 { |
| 39 | + return int64(binary.BigEndian.Uint64(r.msg.GetSeqno())) |
| 40 | +} |
| 41 | + |
| 42 | +func (r floodsubRecord) TopicIDs() []string { |
| 43 | + return r.msg.GetTopicIDs() |
| 44 | +} |
| 45 | + |
| 46 | +/// |
| 47 | + |
| 48 | +// PubSubSubscription allow you to receive pubsub records that where published on the network. |
| 49 | +type PubSubSubscription struct { |
| 50 | + resp *Response |
| 51 | +} |
| 52 | + |
| 53 | +func newPubSubSubscription(resp *Response) *PubSubSubscription { |
| 54 | + sub := &PubSubSubscription{ |
| 55 | + resp: resp, |
| 56 | + } |
| 57 | + |
| 58 | + sub.Next() // skip empty element used for flushing |
| 59 | + return sub |
| 60 | +} |
| 61 | + |
| 62 | +// Next waits for the next record and returns that. |
| 63 | +func (s *PubSubSubscription) Next() (PubSubRecord, error) { |
| 64 | + if s.resp.Error != nil { |
| 65 | + return nil, s.resp.Error |
| 66 | + } |
| 67 | + |
| 68 | + d := json.NewDecoder(s.resp.Output) |
| 69 | + |
| 70 | + r := &floodsub.Message{} |
| 71 | + err := d.Decode(r) |
| 72 | + |
| 73 | + return floodsubRecord{msg: r}, err |
| 74 | +} |
| 75 | + |
| 76 | +// Cancel cancels the given subscription. |
| 77 | +func (s *PubSubSubscription) Cancel() error { |
| 78 | + if s.resp.Output == nil { |
| 79 | + return nil |
| 80 | + } |
| 81 | + |
| 82 | + return s.resp.Output.Close() |
| 83 | +} |
0 commit comments