Broadcast
Abstract module to send broadcast messages.
Allows a node to originate a message that will be received at least once, within a
reasonably short time, on all nodes that are reachable from the origin node. Messages are
propagated via the middleware
specified. Broadcast storms are
avoided by means of a flooding routing scheme.
Broadcast messages follows the schema:
message Packet {
bytes seqno = 1;
bytes origin = 2;
bytes from = 3;
bytes data = 4;
}
seqno
: By default is a random 32-bit but could be used to provide an alternative sorted sequence number.origin
: Represents the author's ID of the message. To identify a message (msgId
) in the network you should check for the: seqno + origin
.from
: Represents the current sender's ID of the message.data
: Represents an opaque blob of data, it can contain any data that the publisher wants
it to defined by higher layers (e.g. a presence information message).
Nodes send any message originating locally to all current peers. Upon receiving a message, a
node delivers it locally to any listeners, and forward the message on to its current
peers, excluding the peer from which it was received.
Nodes maintain a record of the messages they have received and originated
recently, by msgId(seqno + from)
. This is used to avoid sending the same message to the same peer
more than once. These records expire after some time to limit memory consumption by: maxAge
and maxSize
.
Install
$ npm install @dxos/broadcast
Usage
import { Broadcast } from '@dxos/broadcast';
const middleware = {
subscribe: (onData, updatePeers) => {
return () => {
}
},
send: async (packet, node) => {
}
};
const broadcast = new Broadcast(middleware, {
id: crypto.randomBytes(32),
maxAge: 15 * 1000,
maxSize: 1000
})
await broadcast.open()
broadcast.publish(Buffer.from('Hello everyone'))
await broadcast.close()
You can check a real example in: example
API
const broadcast = new Broadcast(middleware, [options])
broadcast.open() => Promise
Initialize the cache and runs the defined subscription.
broadcast.close() => Promise
Clear the cache and unsubscribe from incoming messages.
broadcast.publish(data, [options]) -> Promise<Packet>
Broadcast a flooding message to the peers neighboors.