Implement broadcast for events

Add broadcastTo property to events that broadcasts them to all entities
of the specified target that's downstream to the connection it was sent
to.
This commit is contained in:
Hornwitser committed 2019-12-13 22:37:58 +01:00
1 parent 21d9fdff7b
commit e5115df28b
4 files changed
+65 -1

No files matched your search

+32 -1
View File
@@ -313,19 +313,30 @@ class Event {
* @param {?string} forwardTo -
* Optional target to forward this request to. Only 'master' is
* currently supported.
* @param {?string} broadcastTo -
* Optional target to broadcast this event to. Only 'instance' is
* currently supported. An event will only be broadcast towards
* links that are downstream, so sending an event set to instance
* broadcast that's sent to a slave will only be broadcast to that
* slave's instances.
* @param {Object<string, Object>} eventProperties -
* Mapping of property values to JSON schema specifications for the
* properties that are valid in the data payload of this event.
*/
constructor({ type, links, forwardTo = null, eventProperties = {} }) {
constructor({ type, links, forwardTo = null, broadcastTo = null, eventProperties = {} }) {
this.type = type;
this.links = links;
this.forwardTo = forwardTo;
this.broadcastTo = broadcastTo;
if (forwardTo !== 'master' && forwardTo !== null) {
throw new Error(`Invalid forwardTo value ${forwardTo}`);
}
if (broadcastTo !== 'instance' && broadcastTo !== null) {
throw new Error(`Invalid broadcastTo value ${broadcastTo}`);
}
this.eventType = type + '_event';
this._eventValidator = schema.compile({
$schema: "http://json-schema.org/draft-07/schema#",
@@ -349,6 +360,9 @@ class Event {
* If forwardTo was set to 'master' the `forwardEventToMaster` method on
* the link is used as the default handler.
*
* If broadcastTo was set to 'instance' the `broadcastEventToInstance`
* method on the link is invoked before the handler. BUT HOW?
*
* Does nothing if the link is not a target for this event.
*
* @param {Link} link - The link to attach to.
@@ -367,6 +381,23 @@ class Event {
}
}
if (
this.broadcastTo === 'instance'
&& [
'instance-slave', 'slave-master', 'control-master', 'master-slave'
].includes(`${link.target}-${link.source}`)
) {
if (!handler) {
handler = link.broadcastEventToInstance;
} else {
let originalHandler = handler;
handler = async (message, event) => {
await link.broadcastEventToInstance(message, event);
await originalHandler.call(link, message, event);
}
}
}
if (!handler) {
throw new Error(`Missing handler for ${this.eventType} on ${link.source}-${link.target} link`);
}