Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: examples pubsub #504

Merged
merged 1 commit into from
Dec 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 33 additions & 85 deletions examples/pubsub/1.js
Original file line number Diff line number Diff line change
@@ -1,103 +1,51 @@
/* eslint-disable no-console */
'use strict'

const libp2p = require('../../')
const Libp2p = require('../../')
const TCP = require('libp2p-tcp')
const Mplex = require('libp2p-mplex')
const SECIO = require('libp2p-secio')
const PeerInfo = require('peer-info')
const MulticastDNS = require('libp2p-mdns')
const Gossipsub = require('libp2p-gossipsub')
const defaultsDeep = require('@nodeutils/defaults-deep')
const waterfall = require('async/waterfall')
const parallel = require('async/parallel')
const series = require('async/series')

class MyBundle extends libp2p {
constructor (_options) {
const defaults = {
modules: {
transport: [ TCP ],
streamMuxer: [ Mplex ],
connEncryption: [ SECIO ],
peerDiscovery: [ MulticastDNS ],
pubsub: Gossipsub
},
config: {
peerDiscovery: {
mdns: {
interval: 2000,
enabled: true
}
},
pubsub: {
enabled: true,
emitSelf: true
}
}
const createNode = async () => {
const peerInfo = await PeerInfo.create()
peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')

const node = await Libp2p.create({
peerInfo,
modules: {
transport: [TCP],
streamMuxer: [Mplex],
connEncryption: [SECIO],
pubsub: Gossipsub
}
})

super(defaultsDeep(_options, defaults))
}
await node.start()
return node
}

function createNode (callback) {
let node

waterfall([
(cb) => PeerInfo.create(cb),
(peerInfo, cb) => {
peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
node = new MyBundle({
peerInfo
})
node.start(cb)
}
], (err) => callback(err, node))
}
;(async () => {
const topic = 'news'

parallel([
(cb) => createNode(cb),
(cb) => createNode(cb)
], (err, nodes) => {
if (err) { throw err }
const [node1, node2] = await Promise.all([
createNode(),
createNode(),
])

const node1 = nodes[0]
const node2 = nodes[1]
await node1.dial(node2.peerInfo)

node1.once('peer:connect', (peer) => {
console.log('connected to %s', peer.id.toB58String())
await node1.pubsub.subscribe(topic, (msg) => {
console.log(`node1 received: ${msg.data.toString()}`)
})

series([
// node1 subscribes to "news"
(cb) => node1.pubsub.subscribe(
'news',
(msg) => console.log(`node1 received: ${msg.data.toString()}`),
cb
),
(cb) => setTimeout(cb, 500),
// node2 subscribes to "news"
(cb) => node2.pubsub.subscribe(
'news',
(msg) => console.log(`node2 received: ${msg.data.toString()}`),
cb
),
(cb) => setTimeout(cb, 500),
// node2 publishes "news" every second
(cb) => {
setInterval(() => {
node2.pubsub.publish(
'news',
Buffer.from('Bird bird bird, bird is the word!'),
(err) => {
if (err) { throw err }
}
)
}, 1000)
cb()
},
], (err) => {
if (err) { throw err }
})
await node2.pubsub.subscribe(topic, (msg) => {
console.log(`node2 received: ${msg.data.toString()}`)
})
})

// node2 publishes "news" every second
setInterval(() => {
node2.pubsub.publish(topic, Buffer.from('Bird bird bird, bird is the word!'))
}, 1000)
})();
77 changes: 37 additions & 40 deletions examples/pubsub/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,42 +14,45 @@ For this example, we will use MulticastDNS for automatic Peer Discovery. This ex

Using PubSub is super simple, you only need to provide the implementation of your choice and you are ready to go. No need for extra configuration.

First, let's update our libp2p configuration with a pubsub implementation.

```JavaScript
const Libp2p = require('libp2p')
const Gossipsub = require('libp2p-gossipsub')

const node = await Libp2p.create({
modules: {
transport: [ TCP ],
streamMuxer: [ Mplex ],
connEncryption: [ SECIO ],
// we add the Pubsub module we want
pubsub: Gossipsub
}
})
```

Once that is done, we only need to create a few libp2p nodes, connect them and everything is ready to start using pubsub.

```JavaScript
node1.once('peer:connect', (peer) => {
console.log('connected to %s', peer.id.toB58String())

series([
// node1 subscribes to "news"
(cb) => node1.pubsub.subscribe(
'news',
(msg) => console.log(`node1 received: ${msg.data.toString()}`),
cb
),
(cb) => setTimeout(cb, 500),
// node2 subscribes to "news"
(cb) => node2.pubsub.subscribe(
'news',
(msg) => console.log(`node2 received: ${msg.data.toString()}`),
cb
),
(cb) => setTimeout(cb, 500),
// node2 publishes "news" every second
(cb) => {
setInterval(() => {
node2.pubsub.publish(
'news',
Buffer.from('Bird bird bird, bird is the word!'),
(err) => {
if (err) { throw err }
}
)
}, 1000)
cb()
},
], (err) => {
if (err) { throw err }
})
const topic = 'news'

const node1 = nodes[0]
const node2 = nodes[1]

await node1.dial(node2.peerInfo)

await node1.pubsub.subscribe(topic, (msg) => {
console.log(`node1 received: ${msg.data.toString()}`)
})

await node2.pubsub.subscribe(topic, (msg) => {
console.log(`node2 received: ${msg.data.toString()}`)
})

// node2 publishes "news" every second
setInterval(() => {
node2.pubsub.publish(topic, Buffer.from('Bird bird bird, bird is the word!'))
}, 1000)
```

The output of the program should look like:
Expand All @@ -68,12 +71,6 @@ You can change the pubsub `emitSelf` option if you don't want the publishing nod
```JavaScript
const defaults = {
config: {
peerDiscovery: {
mdns: {
interval: 2000,
enabled: true
}
},
pubsub: {
enabled: true,
emitSelf: false
Expand Down