-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.go
348 lines (298 loc) · 8.92 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
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
package commands
import (
"context"
"encoding/binary"
"fmt"
"io"
"net/http"
"sort"
"sync"
"time"
core "github.com/ipfs/go-ipfs/core"
e "github.com/ipfs/go-ipfs/core/commands/e"
cmds "gx/ipfs/QmNueRyPRQiV7PUEpnP4GgGLuK1rKQLaRW7sfPvUetYig1/go-ipfs-cmds"
blocks "gx/ipfs/QmVzK524a2VWLqyvtBeiHKsUAWYgeAk4DBeZoY7vpNPNRx/go-block-format"
floodsub "gx/ipfs/QmXScvRbYh9X9okLuX9YMnz1HR4WgRTU2hocjBs15nmCNG/go-libp2p-floodsub"
cid "gx/ipfs/QmYVNvtQkeZ6AKSwDrjQTs432QtL6umrrK41EBq3cu7iSP/go-cid"
pstore "gx/ipfs/QmZR2XWVVBCtbgBWnQhWk2xcQfaR3W8faQPriAiaaj7rsr/go-libp2p-peerstore"
cmdkit "gx/ipfs/QmdE4gMduCKCGAcczM2F5ioYDfdeKuPix138wrES1YSr7f/go-ipfs-cmdkit"
)
var PubsubCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "An experimental publish-subscribe system on ipfs.",
ShortDescription: `
ipfs pubsub allows you to publish messages to a given topic, and also to
subscribe to new messages on a given topic.
This is an experimental feature. It is not intended in its current state
to be used in a production environment.
To use, the daemon must be run with '--enable-pubsub-experiment'.
`,
},
Subcommands: map[string]*cmds.Command{
"pub": PubsubPubCmd,
"sub": PubsubSubCmd,
"ls": PubsubLsCmd,
"peers": PubsubPeersCmd,
},
}
var PubsubSubCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Subscribe to messages on a given topic.",
ShortDescription: `
ipfs pubsub sub subscribes to messages on a given topic.
This is an experimental feature. It is not intended in its current state
to be used in a production environment.
To use, the daemon must be run with '--enable-pubsub-experiment'.
`,
LongDescription: `
ipfs pubsub sub subscribes to messages on a given topic.
This is an experimental feature. It is not intended in its current state
to be used in a production environment.
To use, the daemon must be run with '--enable-pubsub-experiment'.
This command outputs data in the following encodings:
* "json"
(Specified by the "--encoding" or "--enc" flag)
`,
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("topic", true, false, "String name of topic to subscribe to."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("discover", "try to discover other peers subscribed to the same topic"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
n, err := GetNode(env)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
// Must be online!
if !n.OnlineMode() {
res.SetError(errNotOnline, cmdkit.ErrClient)
return
}
if n.Floodsub == nil {
res.SetError(fmt.Errorf("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use"), cmdkit.ErrNormal)
return
}
topic := req.Arguments[0]
sub, err := n.Floodsub.Subscribe(topic)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
defer sub.Cancel()
discover, _ := req.Options["discover"].(bool)
if discover {
go func() {
blk := blocks.NewBlock([]byte("floodsub:" + topic))
err := n.Blocks.AddBlock(blk)
if err != nil {
log.Error("pubsub discovery: ", err)
return
}
connectToPubSubPeers(req.Context, n, blk.Cid())
}()
}
if f, ok := res.(http.Flusher); ok {
f.Flush()
}
for {
msg, err := sub.Next(req.Context)
if err == io.EOF || err == context.Canceled {
return
} else if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
res.Emit(msg)
}
},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
m, ok := v.(*floodsub.Message)
if !ok {
return fmt.Errorf("unexpected type: %T", v)
}
_, err := w.Write(m.Data)
return err
}),
"ndpayload": cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
m, ok := v.(*floodsub.Message)
if !ok {
return fmt.Errorf("unexpected type: %T", v)
}
m.Data = append(m.Data, '\n')
_, err := w.Write(m.Data)
return err
}),
"lenpayload": cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
m, ok := v.(*floodsub.Message)
if !ok {
return fmt.Errorf("unexpected type: %T", v)
}
buf := make([]byte, 8, len(m.Data)+8)
n := binary.PutUvarint(buf, uint64(len(m.Data)))
buf = append(buf[:n], m.Data...)
_, err := w.Write(buf)
return err
}),
},
Type: floodsub.Message{},
}
func connectToPubSubPeers(ctx context.Context, n *core.IpfsNode, cid *cid.Cid) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
provs := n.Routing.FindProvidersAsync(ctx, cid, 10)
wg := &sync.WaitGroup{}
for p := range provs {
wg.Add(1)
go func(pi pstore.PeerInfo) {
defer wg.Done()
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
err := n.PeerHost.Connect(ctx, pi)
if err != nil {
log.Info("pubsub discover: ", err)
return
}
log.Info("connected to pubsub peer:", pi.ID)
}(p)
}
wg.Wait()
}
var PubsubPubCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Publish a message to a given pubsub topic.",
ShortDescription: `
ipfs pubsub pub publishes a message to a specified topic.
This is an experimental feature. It is not intended in its current state
to be used in a production environment.
To use, the daemon must be run with '--enable-pubsub-experiment'.
`,
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("topic", true, false, "Topic to publish to."),
cmdkit.StringArg("data", true, true, "Payload of message to publish.").EnableStdin(),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
n, err := GetNode(env)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
// Must be online!
if !n.OnlineMode() {
res.SetError(errNotOnline, cmdkit.ErrClient)
return
}
if n.Floodsub == nil {
res.SetError("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use.", cmdkit.ErrNormal)
return
}
topic := req.Arguments[0]
err = req.ParseBodyArgs()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
for _, data := range req.Arguments[1:] {
if err := n.Floodsub.Publish(topic, []byte(data)); err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
}
},
}
var PubsubLsCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List subscribed topics by name.",
ShortDescription: `
ipfs pubsub ls lists out the names of topics you are currently subscribed to.
This is an experimental feature. It is not intended in its current state
to be used in a production environment.
To use, the daemon must be run with '--enable-pubsub-experiment'.
`,
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
n, err := GetNode(env)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
// Must be online!
if !n.OnlineMode() {
res.SetError(errNotOnline, cmdkit.ErrClient)
return
}
if n.Floodsub == nil {
res.SetError("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use.", cmdkit.ErrNormal)
return
}
cmds.EmitOnce(res, stringList{n.Floodsub.GetTopics()})
},
Type: stringList{},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeEncoder(stringListEncoder),
},
}
func stringListEncoder(req *cmds.Request, w io.Writer, v interface{}) error {
list, ok := v.(*stringList)
if !ok {
return e.TypeErr(list, v)
}
for _, str := range list.Strings {
_, err := fmt.Fprintf(w, "%s\n", str)
if err != nil {
return err
}
}
return nil
}
var PubsubPeersCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List peers we are currently pubsubbing with.",
ShortDescription: `
ipfs pubsub peers with no arguments lists out the pubsub peers you are
currently connected to. If given a topic, it will list connected
peers who are subscribed to the named topic.
This is an experimental feature. It is not intended in its current state
to be used in a production environment.
To use, the daemon must be run with '--enable-pubsub-experiment'.
`,
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("topic", false, false, "topic to list connected peers of"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
n, err := GetNode(env)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
// Must be online!
if !n.OnlineMode() {
res.SetError(errNotOnline, cmdkit.ErrClient)
return
}
if n.Floodsub == nil {
res.SetError(fmt.Errorf("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use"), cmdkit.ErrNormal)
return
}
var topic string
if len(req.Arguments) == 1 {
topic = req.Arguments[0]
}
peers := n.Floodsub.ListPeers(topic)
list := &stringList{make([]string, 0, len(peers))}
for _, peer := range peers {
list.Strings = append(list.Strings, peer.Pretty())
}
sort.Strings(list.Strings)
cmds.EmitOnce(res, list)
},
Type: stringList{},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeEncoder(stringListEncoder),
},
}