This repository has been archived by the owner on Jun 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
346 lines (284 loc) · 7.95 KB
/
index.js
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
'use strict'
const EventEmitter = require('events')
const TimeCache = require('time-cache')
const values = require('lodash.values')
const pull = require('pull-stream')
const lp = require('pull-length-prefixed')
const assert = require('assert')
const asyncEach = require('async/each')
const Peer = require('./peer')
const utils = require('./utils')
const pb = require('./message')
const config = require('./config')
const Buffer = require('safe-buffer').Buffer
const log = config.log
const multicodec = config.multicodec
const ensureArray = utils.ensureArray
const setImmediate = require('async/setImmediate')
/**
* FloodSub (aka dumbsub is an implementation of pubsub focused on
* delivering an API for Publish/Subscribe, but with no CastTree Forming
* (it just floods the network).
*/
class FloodSub extends EventEmitter {
/**
* @param {Object} libp2p
* @returns {FloodSub}
*/
constructor (libp2p) {
super()
this.libp2p = libp2p
this.started = false
/**
* Time based cache for sequence numbers.
*
* @type {TimeCache}
*/
this.cache = new TimeCache()
/**
* Map of peers.
*
* @type {Map<string, Peer>}
*/
this.peers = new Map()
/**
* List of our subscriptions
* @type {Set<string>}
*/
this.subscriptions = new Set()
this._onConnection = this._onConnection.bind(this)
this._dialPeer = this._dialPeer.bind(this)
}
_dialPeer (peerInfo, callback) {
callback = callback || function noop () {}
const idB58Str = peerInfo.id.toB58String()
log('dialing %s', idB58Str)
// If already have a PubSub conn, ignore
const peer = this.peers.get(idB58Str)
if (peer && peer.isConnected) {
return callback()
}
this.libp2p.dial(peerInfo, multicodec, (err, conn) => {
if (err) {
log.err(err)
return callback()
}
this._onDial(peerInfo, conn, callback)
})
}
_onDial (peerInfo, conn, callback) {
const idB58Str = peerInfo.id.toB58String()
// If already had a dial to me, just add the conn
if (!this.peers.has(idB58Str)) {
this.peers.set(idB58Str, new Peer(peerInfo))
}
const peer = this.peers.get(idB58Str)
peer.attachConnection(conn)
// Immediately send my own subscriptions to the newly established conn
peer.sendSubscriptions(this.subscriptions)
setImmediate(() => callback())
}
_onConnection (protocol, conn) {
conn.getPeerInfo((err, peerInfo) => {
if (err) {
log.err('Failed to identify incomming conn', err)
return pull(pull.empty(), conn)
}
const idB58Str = peerInfo.id.toB58String()
if (!this.peers.has(idB58Str)) {
log('new peer', idB58Str)
this.peers.set(idB58Str, new Peer(peerInfo))
}
this._processConnection(idB58Str, conn)
})
}
_processConnection (idB58Str, conn) {
pull(
conn,
lp.decode(),
pull.map((data) => pb.rpc.RPC.decode(data)),
pull.drain(
(rpc) => this._onRpc(idB58Str, rpc),
(err) => this._onConnectionEnd(idB58Str, err)
)
)
}
_onRpc (idB58Str, rpc) {
if (!rpc) {
return
}
const subs = rpc.subscriptions
const msgs = rpc.msgs
if (msgs && msgs.length) {
this._processRpcMessages(rpc.msgs)
}
if (subs && subs.length) {
const peer = this.peers.get(idB58Str)
if (peer) {
peer.updateSubscriptions(subs)
}
}
}
_processRpcMessages (msgs) {
msgs.forEach((msg) => {
const seqno = utils.msgId(msg.from, msg.seqno.toString())
// 1. check if I've seen the message, if yes, ignore
if (this.cache.has(seqno)) {
return
}
this.cache.put(seqno)
// 2. emit to self
this._emitMessages(msg.topicCIDs, [msg])
// 3. propagate msg to others
this._forwardMessages(msg.topicCIDs, [msg])
})
}
_onConnectionEnd (idB58Str, err) {
// socket hang up, means the one side canceled
if (err && err.message !== 'socket hang up') {
log.err(err)
}
this.peers.delete(idB58Str)
}
_emitMessages (topics, messages) {
topics.forEach((topic) => {
if (!this.subscriptions.has(topic)) {
return
}
messages.forEach((message) => {
this.emit(topic, message)
})
})
}
_forwardMessages (topics, messages) {
this.peers.forEach((peer) => {
if (!peer.isWritable ||
!utils.anyMatch(peer.topics, topics)) {
return
}
peer.sendMessages(messages)
log('publish msgs on topics', topics, peer.info.id.toB58String())
})
}
/**
* Mounts the floodsub protocol onto the libp2p node and sends our
* subscriptions to every peer conneceted
*
* @param {Function} callback
* @returns {undefined}
*
*/
start (callback) {
if (this.started) {
return setImmediate(() => callback(new Error('already started')))
}
this.libp2p.handle(multicodec, this._onConnection)
// Speed up any new peer that comes in my way
this.libp2p.on('peer:connect', this._dialPeer)
// Dial already connected peers
const peerInfos = values(this.libp2p.peerBook.getAll())
asyncEach(peerInfos, (peer, cb) => this._dialPeer(peer, cb), (err) => {
setImmediate(() => {
this.started = true
callback(err)
})
})
}
/**
* Unmounts the floodsub protocol and shuts down every connection
*
* @param {Function} callback
* @returns {undefined}
*
*/
stop (callback) {
if (!this.started) {
return setImmediate(() => callback(new Error('not started yet')))
}
this.libp2p.unhandle(multicodec)
this.libp2p.removeListener('peer:connect', this._dialPeer)
asyncEach(this.peers.values(), (peer, cb) => peer.close(cb), (err) => {
if (err) {
return callback(err)
}
this.peers = new Map()
this.started = false
callback()
})
}
/**
* Publish messages to the given topics.
*
* @param {Array<string>|string} topics
* @param {Array<any>|any} messages
* @returns {undefined}
*
*/
publish (topics, messages) {
assert(this.started, 'FloodSub is not started')
log('publish', topics, messages)
topics = ensureArray(topics)
messages = ensureArray(messages)
const from = this.libp2p.peerInfo.id.toB58String()
const buildMessage = (msg) => {
const seqno = utils.randomSeqno()
this.cache.put(utils.msgId(from, seqno))
return {
from: from,
data: msg,
seqno: new Buffer(seqno),
topicCIDs: topics
}
}
const msgObjects = messages.map(buildMessage)
// Emit to self if I'm interested
this._emitMessages(topics, msgObjects)
// send to all the other peers
this._forwardMessages(topics, messages.map(buildMessage))
}
/**
* Subscribe to the given topic(s).
*
* @param {Array<string>|string} topics
* @returns {undefined}
*/
subscribe (topics) {
assert(this.started, 'FloodSub is not started')
topics = ensureArray(topics)
topics.forEach((topic) => {
this.subscriptions.add(topic)
})
this.peers.forEach((peer) => checkIfReady(peer))
// make sure that FloodSub is already mounted
function checkIfReady (peer) {
if (peer && peer.isWritable) {
peer.sendSubscriptions(topics)
} else {
setImmediate(checkIfReady.bind(peer))
}
}
}
/**
* Unsubscribe from the given topic(s).
*
* @param {Array<string>|string} topics
* @returns {undefined}
*/
unsubscribe (topics) {
assert(this.started, 'FloodSub is not started')
topics = ensureArray(topics)
topics.forEach((topic) => {
this.subscriptions.delete(topic)
})
this.peers.forEach((peer) => checkIfReady(peer))
// make sure that FloodSub is already mounted
function checkIfReady (peer) {
if (peer && peer.isWritable) {
peer.sendUnsubscriptions(topics)
} else {
setImmediate(checkIfReady.bind(peer))
}
}
}
}
module.exports = FloodSub