Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Commit bdeb578

Browse files
committed
refactor: switch to async iterators
BREAKING CHANGE: Switch to using async/await and async iterators.
1 parent b7a1366 commit bdeb578

File tree

9 files changed

+643
-719
lines changed

9 files changed

+643
-719
lines changed

.aegir.js

Lines changed: 29 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,22 @@ const {
1313
let wsRendezvous
1414
let node
1515

16-
const before = (done) => {
17-
parallel([
18-
(cb) => {
19-
WebSocketStarRendezvous.start({
20-
port: WS_RENDEZVOUS_MULTIADDR.nodeAddress().port,
21-
refreshPeerListIntervalMS: 1000,
22-
strictMultiaddr: false,
23-
cryptoChallenge: true
24-
}, (err, _server) => {
16+
const before = async () => {
17+
[wsRendezvous, node] = await Promise.all([
18+
WebSocketStarRendezvous.start({
19+
port: WS_RENDEZVOUS_MULTIADDR.nodeAddress().port,
20+
refreshPeerListIntervalMS: 1000,
21+
strictMultiaddr: false,
22+
cryptoChallenge: true
23+
}),
24+
new Promise(async (resolve, reject) => {
25+
// TODO PROMISIFY THIS
26+
getPeerRelay(async (err, peerInfo) => {
2527
if (err) {
26-
return cb(err)
27-
}
28-
wsRendezvous = _server
29-
cb()
30-
})
31-
},
32-
(cb) => {
33-
getPeerRelay((err, peerInfo) => {
34-
if (err) {
35-
return done(err)
28+
return reject(err)
3629
}
3730

38-
node = new Node({
31+
const n = new Node({
3932
peerInfo,
4033
config: {
4134
relay: {
@@ -48,19 +41,25 @@ const before = (done) => {
4841
}
4942
})
5043

51-
node.handle('/echo/1.0.0', (_, conn) => pull(conn, conn))
52-
node.start(cb)
44+
n.handle('/echo/1.0.0', (_, conn) => pull(conn, conn))
45+
await n.start()
46+
47+
resolve(n)
5348
})
54-
}
55-
], done)
49+
})
50+
])
5651
}
5752

58-
const after = (done) => {
59-
setTimeout(() =>
60-
parallel(
61-
[node, wsRendezvous].map((s) => (cb) => s.stop(cb)),
62-
done),
63-
2000)
53+
const after = () => {
54+
return new Promise((resolve) => {
55+
setTimeout(async () => {
56+
await Promise.all([
57+
node.stop(),
58+
wsRendezvous.stop()
59+
])
60+
resolve()
61+
}, 2000)
62+
})
6463
}
6564

6665
module.exports = {

README.md

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,14 @@ const FloodSub = require('libp2p-floodsub')
3838

3939
const fsub = new FloodSub(node)
4040

41-
fsub.start((err) => {
42-
if (err) {
43-
console.log('Upsy', err)
44-
}
45-
fsub.on('fruit', (data) => {
46-
console.log(data)
47-
})
48-
fsub.subscribe('fruit')
49-
50-
fsub.publish('fruit', new Buffer('banana'))
41+
await fsub.start()
42+
43+
fsub.on('fruit', (data) => {
44+
console.log(data)
5145
})
46+
fsub.subscribe('fruit')
47+
48+
fsub.publish('fruit', new Buffer('banana'))
5249
```
5350

5451
## Events

package.json

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,33 +45,32 @@
4545
},
4646
"homepage": "https://github.com/libp2p/js-libp2p-floodsub#readme",
4747
"devDependencies": {
48-
"aegir": "^18.2.1",
48+
"aegir": "^20.0.0",
4949
"benchmark": "^2.1.4",
5050
"chai": "^4.2.0",
5151
"chai-spies": "^1.0.0",
5252
"detect-node": "^2.0.4",
5353
"dirty-chai": "^2.0.1",
54-
"libp2p": "~0.24.4",
54+
"libp2p": "~0.26.1",
5555
"libp2p-secio": "~0.11.1",
5656
"libp2p-spdy": "~0.13.3",
57-
"libp2p-tcp": "~0.13.0",
57+
"libp2p-tcp": "~0.13.1",
5858
"libp2p-websocket-star": "~0.10.2",
59-
"libp2p-websocket-star-rendezvous": "~0.3.0",
60-
"lodash": "^4.17.11",
61-
"multiaddr": "^6.0.6",
59+
"libp2p-websocket-star-rendezvous": "~0.4.1",
60+
"lodash": "^4.17.15",
61+
"multiaddr": "^6.1.0",
6262
"peer-id": "~0.12.2",
6363
"peer-info": "~0.15.1",
64-
"sinon": "^7.3.2"
64+
"sinon": "^7.4.2"
6565
},
6666
"dependencies": {
6767
"async": "^2.6.2",
68-
"bs58": "^4.0.1",
6968
"debug": "^4.1.1",
7069
"length-prefixed-stream": "^2.0.0",
71-
"libp2p-crypto": "~0.16.1",
72-
"libp2p-pubsub": "~0.2.0",
70+
"libp2p-pubsub": "libp2p/js-libp2p-pubsub#refactor/async",
71+
"p-map": "^3.0.0",
7372
"protons": "^1.0.1",
74-
"pull-length-prefixed": "^1.3.2",
73+
"pull-length-prefixed": "^1.3.3",
7574
"pull-pushable": "^2.2.0",
7675
"pull-stream": "^3.6.9"
7776
},

src/index.js

Lines changed: 44 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@ const config = require('./config')
1111
const multicodec = config.multicodec
1212
const ensureArray = utils.ensureArray
1313
const setImmediate = require('async/setImmediate')
14-
const asyncMap = require('async/map')
15-
const noop = () => {}
14+
const pMap = require('p-map')
1615

1716
/**
1817
* FloodSub (aka dumbsub is an implementation of pubsub focused on
@@ -49,19 +48,16 @@ class FloodSub extends BaseProtocol {
4948
* @override
5049
* @param {PeerInfo} peerInfo peer info
5150
* @param {Connection} conn connection to the peer
52-
* @param {function} callback
5351
*/
54-
_onDial (peerInfo, conn, callback) {
55-
super._onDial(peerInfo, conn, (err) => {
56-
if (err) return callback(err)
57-
const idB58Str = peerInfo.id.toB58String()
58-
const peer = this.peers.get(idB58Str)
59-
if (peer && peer.isWritable) {
60-
// Immediately send my own subscriptions to the newly established conn
61-
peer.sendSubscriptions(this.subscriptions)
62-
}
63-
setImmediate(() => callback())
64-
})
52+
_onDial (peerInfo, conn) {
53+
super._onDial(peerInfo, conn)
54+
const idB58Str = peerInfo.id.toB58String()
55+
const peer = this.peers.get(idB58Str)
56+
57+
if (peer && peer.isWritable) {
58+
// Immediately send my own subscriptions to the newly established conn
59+
peer.sendSubscriptions(this.subscriptions)
60+
}
6561
}
6662

6763
/**
@@ -71,7 +67,7 @@ class FloodSub extends BaseProtocol {
7167
* @param {string} idB58Str peer id string in base58
7268
* @param {Connection} conn connection
7369
* @param {PeerInfo} peer peer info
74-
* @returns {undefined}
70+
* @returns {void}
7571
*
7672
*/
7773
_processConnection (idB58Str, conn, peer) {
@@ -119,7 +115,7 @@ class FloodSub extends BaseProtocol {
119115
* @param {rpc.RPC.Message} message The message to process
120116
* @returns {void}
121117
*/
122-
_processRpcMessage (message) {
118+
async _processRpcMessage (message) {
123119
const msg = utils.normalizeInRpcMessage(message)
124120
const seqno = utils.msgId(msg.from, msg.seqno)
125121
// 1. check if I've seen the message, if yes, ignore
@@ -128,19 +124,27 @@ class FloodSub extends BaseProtocol {
128124
}
129125

130126
this.seenCache.put(seqno)
127+
131128
// 2. validate the message (signature verification)
132-
this.validate(message, (err, isValid) => {
133-
if (err || !isValid) {
134-
this.log('Message could not be validated, dropping it. isValid=%s', isValid, err)
135-
return
136-
}
129+
let isValid
130+
let error
137131

138-
// 3. if message is valid, emit to self
139-
this._emitMessages(msg.topicIDs, [msg])
132+
try {
133+
isValid = await this.validate(message)
134+
} catch (err) {
135+
error = err
136+
}
140137

141-
// 4. if message is valid, propagate msg to others
142-
this._forwardMessages(msg.topicIDs, [msg])
143-
})
138+
if (error || !isValid) {
139+
this.log('Message could not be validated, dropping it. isValid=%s', isValid, error)
140+
return
141+
}
142+
143+
// 3. if message is valid, emit to self
144+
this._emitMessages(msg.topicIDs, [msg])
145+
146+
// 4. if message is valid, propagate msg to others
147+
this._forwardMessages(msg.topicIDs, [msg])
144148
}
145149

146150
_emitMessages (topics, messages) {
@@ -170,30 +174,25 @@ class FloodSub extends BaseProtocol {
170174
/**
171175
* Unmounts the floodsub protocol and shuts down every connection
172176
* @override
173-
* @param {Function} callback
174-
* @returns {undefined}
177+
* @returns {void}
175178
*
176179
*/
177-
stop (callback) {
178-
super.stop((err) => {
179-
if (err) return callback(err)
180-
this.subscriptions = new Set()
181-
callback()
182-
})
180+
stop () {
181+
super.stop()
182+
183+
this.subscriptions = new Set()
183184
}
184185

185186
/**
186187
* Publish messages to the given topics.
187188
* @override
188189
* @param {Array<string>|string} topics
189190
* @param {Array<any>|any} messages
190-
* @param {function(Error)} callback
191-
* @returns {undefined}
191+
* @returns {Promise}
192192
*
193193
*/
194-
publish (topics, messages, callback) {
194+
async publish (topics, messages) {
195195
assert(this.started, 'FloodSub is not started')
196-
callback = callback || noop
197196

198197
this.log('publish', topics, messages)
199198

@@ -202,7 +201,7 @@ class FloodSub extends BaseProtocol {
202201

203202
const from = this.libp2p.peerInfo.id.toB58String()
204203

205-
const buildMessage = (msg, cb) => {
204+
const buildMessage = (msg) => {
206205
const seqno = utils.randomSeqno()
207206
this.seenCache.put(utils.msgId(from, seqno))
208207

@@ -216,24 +215,20 @@ class FloodSub extends BaseProtocol {
216215
// Emit to self if I'm interested and it is enabled
217216
this._options.emitSelf && this._emitMessages(topics, [message])
218217

219-
this._buildMessage(message, cb)
218+
return this._buildMessage(message)
220219
}
221220

222-
asyncMap(messages, buildMessage, (err, msgObjects) => {
223-
if (err) return callback(err)
224-
225-
// send to all the other peers
226-
this._forwardMessages(topics, msgObjects)
221+
const msgObjects = await pMap(messages, buildMessage)
227222

228-
callback(null)
229-
})
223+
// send to all the other peers
224+
this._forwardMessages(topics, msgObjects)
230225
}
231226

232227
/**
233228
* Subscribe to the given topic(s).
234229
* @override
235230
* @param {Array<string>|string} topics
236-
* @returns {undefined}
231+
* @returns {void}
237232
*/
238233
subscribe (topics) {
239234
assert(this.started, 'FloodSub is not started')
@@ -261,7 +256,7 @@ class FloodSub extends BaseProtocol {
261256
* Unsubscribe from the given topic(s).
262257
* @override
263258
* @param {Array<string>|string} topics
264-
* @returns {undefined}
259+
* @returns {void}
265260
*/
266261
unsubscribe (topics) {
267262
// Avoid race conditions, by quietly ignoring unsub when shutdown.

0 commit comments

Comments
 (0)