Refactor link system to JSON serialisable class pattern

Reverse the direction of the API for sending messages from

    messageDefinition.send(link, { content });

to

    link.send(new MessageClass(content));

and convert all message definitions to use the JSON serialisable class
pattern and explicit registration of message handlers, along with a
end-to-end based routing of messages instead of link to link.

The experience I gained from the existing way messages were defined and
sent over links was that it was difficult to understand for people
unfamiliar with the system.  The automatic registration of message
handlers ment that code was being called as if by magic from nowhere
with no easy way to discover it.  The manual forwarding and rules for
what can be sent where and how obscured its working.

The use of pure JSON as both input and output from message handlers made
it tedious to work with.  Data had to be manually converted between the
program representation and the over the wire format, which made handler
code unplesant to write.  Particularly because the over the wire format
used snake_case while the program code uses camelCase for variables.
The idea behind the decision to do it this way was to make it more clear
which data came from the wire and which from the program, and while this
worked it didn't make message handlers any nicer to write.

The direction of the API and magic registration of message handlers also
meant that a future migration to TypeScript would be troublesome.  While
it may be possible to implement, the degree of TypeScript magic required
would go starkly against the principle of keep it simple stupid.

By refactoring to using the JSON serialisable class pattern most of
these issues go away.  There is no longer a need to distinguish the on
wire format of messages with the program representation because the only
place that deals with the wire format of messages are the toJSON and
fromJSON methods on the classes themselves.  Message handlers will work
with proper instances of classes instead of raw data, something that
makes them easier to write, and trivial to type with TypeScript.

End-to-end routing also simplifies sending messages that need to do
mulitple hops to reach the destination.  And removes the need for having
all messages be specified in plugin's info module, as they can be routed
without having to be parsed completely.

The explicit registration of message handlers is something that I
thought would be tedious boilerplate code that could be automated away.
But experience now shows it to be the opposite.  Allthough dull
repetition, the purpose it serves is to link together the code in a way
that humans can easily find.  With explicit registration searching the
name of the message handler in the editor will show the registration that
ties it together with the type of message it handles and the kind of
registration.  With implicit registration searching the name of the
message handler turns up only the handler with no clue as to what calls
it.
This commit is contained in:
Hornwitser committed 2023-04-23 13:19:46 +02:00
1 parent 9a967a5779
commit bcd94709d2
106 files changed
+8173 -4928

No files matched your search

+227 -100
View File
@@ -1,9 +1,10 @@
// Connection adapters for Links
"use strict";
const assert = require("assert").strict;
const events = require("events");
const WebSocket = require("isomorphic-ws");
const libSchema = require("../schema");
const libData = require("../data");
const libErrors = require("../errors");
const { logger } = require("../logging");
const ExponentialBackoff = require("../ExponentialBackoff");
@@ -15,34 +16,103 @@ const ExponentialBackoff = require("../ExponentialBackoff");
* @extends events.EventEmitter
* @memberof module:lib/link
*/
class WebSocketBaseConnector extends events.EventEmitter {
constructor(sessionTimeout) {
class BaseConnector extends events.EventEmitter {
constructor(src, dst) {
super();
this._seq = 1;
this.src = src;
this.dst = dst;
}
this._sessionTimeout = sessionTimeout;
_reset() {
this._seq = 1;
}
_invalidate() {
this._seq = 1;
}
sendRequest(request, requestId, dst) {
let seq = this._seq;
this._seq += 1;
let src = new libData.Address(this.src.type, this.src.id, requestId);
let name = request.constructor.name;
let hasData = Boolean(request.constructor.jsonSchema);
const message = new libData.MessageRequest(seq, src, dst, name, hasData ? request : undefined);
this.send(message);
return seq;
}
sendResponse(response, dst) {
let seq = this._seq;
this._seq += 1;
const message = new libData.MessageResponse(seq, this.src, dst, response);
this.send(message);
return seq;
}
sendResponseError(error, dst) {
let seq = this._seq;
this._seq += 1;
const message = new libData.MessageResponseError(seq, this.src, dst, error);
this.send(message);
return seq;
}
sendEvent(event, dst) {
let seq = this._seq;
this._seq += 1;
let name = event.constructor.name;
let hasData = Boolean(event.constructor.jsonSchema);
const message = new libData.MessageEvent(seq, this.src, dst, name, hasData ? event : undefined);
this.send(message);
return seq;
}
}
/**
* Base connector for links
*
* @extends module:lib/link.BaseConnector
* @memberof module:lib/link
*/
class WebSocketBaseConnector extends BaseConnector {
constructor(src, dst) {
super(src, dst);
// One of closed, connecting (client only), connected and resuming.
this._state = "closed";
this._closing = false;
this._socket = null;
this._seq = 1;
this._lastHeartbeat = null;
this._heartbeatId = null;
this._heartbeatInterval = null;
this._lastReceivedSeq = null;
this._lastReceivedSeq = undefined;
this._sendBuffer = [];
}
_reset() {
this._state = "closed";
this._closing = false;
this._socket = null;
this._seq = 1;
assert(this._socket === null);
this._lastHeartbeat = null;
this._heartbeatId = null;
assert(this._heartbeatId === null);
this._heartbeatInterval = null;
this._lastReceivedSeq = null;
this._lastReceivedSeq = undefined;
this._sendBuffer.length = 0;
super._reset();
}
_invalidate() {
this._state = "connecting";
assert(this._closing === false);
assert(this._socket);
this._lastHeartbeat = null;
assert(this._heartbeatId === null);
this._heartbeatInterval = null;
this._lastReceivedSeq = undefined;
this._sendBuffer.length = 0;
super._invalidate();
}
_check(...expectedStates) {
@@ -54,7 +124,7 @@ class WebSocketBaseConnector extends events.EventEmitter {
}
_dropSendBufferSeq(seq) {
if (seq === null) {
if (seq === undefined) {
return;
}
@@ -69,6 +139,45 @@ class WebSocketBaseConnector extends events.EventEmitter {
this._sendBuffer.splice(0, dropCount);
}
_parseMessage(text) {
let json;
try {
json = JSON.parse(text);
} catch (err) {
this.close(4000, "Malformed JSON");
return undefined;
}
if (!libData.Message.validate(json)) {
logger.error(`Received malformed message: ${text}`);
// logger.error(JSON.stringify(libData.Message.validate.errors, null, 4));
this.close(4000, "Malformed message");
return undefined;
}
return libData.Message.fromJSON(json);
}
_processMessage(message) {
if (message.type === "heartbeat") {
this._processHeartbeat(message);
} else if (message.type === "disconnect") {
if (message.data === "ready") {
this.emit("disconnectReady");
} else if (message.data === "prepare") {
this.setClosing();
this.emit("disconnectPrepare");
}
} else {
if (message.seq !== undefined) {
this._lastReceivedSeq = message.seq;
}
this.emit("message", message);
}
}
_doHeartbeat() {
this._check("connected");
if (Date.now() - this._lastHeartbeat > 2000 * this._heartbeatInterval) {
@@ -81,23 +190,13 @@ class WebSocketBaseConnector extends events.EventEmitter {
}
} else {
this._socket.send(JSON.stringify({
seq: null,
type: "heartbeat",
data: { seq: this._lastReceivedSeq },
}));
this._sendInternal(new libData.MessageHeartbeat(this._lastReceivedSeq));
}
}
_processHeartbeat(message) {
if (!libSchema.heartbeat(message)) {
logger.warn("Connector | closing after received invalid heartbeat");
this._socket.close(1002, "Invalid heartbeat");
return;
}
this._lastHeartbeat = Date.now();
this._dropSendBufferSeq(message.data.seq);
this._dropSendBufferSeq(message.seq);
}
/**
@@ -120,29 +219,30 @@ class WebSocketBaseConnector extends events.EventEmitter {
if (this._heartbeatId) {
clearInterval(this._heartbeatId);
this._heartbeatId = null;
this._lastHeartbeat = null;
}
}
/**
* Send a message over the socket
*
* @param {string} type - Message type to send.
* @param {Object} data - Data to send with message.
* @returns {number} the sequence number of the message sent
* This is a low level method that should only be used for implementing
* links. See sendTo for sending requests and events.
*
* @param {module:lib/data.Message} message - Message to send.
*/
send(type, data) {
send(message) {
if (!["connected", "resuming"].includes(this._state)) {
throw new libErrors.SessionLost("No session");
}
let seq = this._seq;
this._seq += 1;
let message = { seq, type, data };
this._sendBuffer.push(message);
if (this._state === "connected") {
this._socket.send(JSON.stringify(message));
this._sendInternal(message);
}
return seq;
}
_sendInternal(message) {
this._socket.send(JSON.stringify(message));
}
/**
@@ -155,11 +255,40 @@ class WebSocketBaseConnector extends events.EventEmitter {
throw new Error("Abstract function");
}
/**
* Gracefully disconnect
*
* Sets closing flag an initiates the disconnect sequence.
*/
async disconnect() {
if (this._state !== "connected") {
await this.close(1000, "Disconnect");
return;
}
this.setClosing();
this.send(new libData.MessageDisconnect("prepare"));
let timeout;
let waitTimeout = new Promise(resolve => { timeout = setTimeout(resolve, 10000); }); // Make Configurable?
try {
await Promise.race([
waitTimeout,
events.once(this, "close"),
events.once(this, "disconnectReady"),
]);
} finally {
clearTimeout(timeout);
}
await this.close(1000, "Disconnect");
}
/**
* True if the connection is established and active
*/
get connected() {
return this._state === "connected";
return !this._closing && this._state === "connected";
}
/**
@@ -186,7 +315,7 @@ class WebSocketBaseConnector extends events.EventEmitter {
*/
class WebSocketClientConnector extends WebSocketBaseConnector {
constructor(url, maxReconnectDelay, tlsCa = null) {
super(null);
super(undefined, new libData.Address(libData.Address.controller, 0));
this._url = url;
this._backoff = new ExponentialBackoff({ max: maxReconnectDelay });
@@ -199,32 +328,40 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
// connected: Connection is online
this._reconnectId = null;
this._sessionToken = null;
this._sessionTimeout = null;
this._startedResuming = null;
}
_reset() {
clearTimeout(this._reconnectId);
this._reconnectId = null;
this._lastReceivedSeq = null;
this._sessionToken = null;
this._sessionTimeout = null;
this._sendBuffer.length = 0;
this._startedResuming = null;
super._reset();
this.src = undefined;
}
_invalidate() {
assert(this._reconnectId === null);
this._sessionToken = null;
this._sessionTimeout = null;
this._startedResuming = null;
super._invalidate();
this.src = undefined;
}
/**
* Send a handshake message over the socket
*
* Used in the register function in order to send the register handshake
* message over the WebSocket.
* Used in the register function in order to send the handshake messages
* over the WebSocket.
*
* @param {string} type - Message type to send.
* @param {Object} data - Data to send with message.
* @param {module:lib/data.Message} message - Message to send.
*/
sendHandshake(type, data) {
sendHandshake(message) {
this._check("connecting", "resuming");
this._socket.send(JSON.stringify({ seq: null, type, data }));
this._sendInternal(message);
}
/**
@@ -329,8 +466,13 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
) {
logger.error("Connector | Session timed out trying to resume");
this._reset();
this._state = "connecting";
this.emit("invalidate");
if (this._disconnecting) {
this._reset();
this.emit("close");
} else {
this._state = "connecting";
this.emit("invalidate");
}
}
logger.verbose(
`Connector | waiting ${(Math.round(delay / 10) / 100)} seconds for reconnect`
@@ -416,21 +558,15 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
// Handle messages
this._socket.onmessage = event => {
let message = JSON.parse(event.data);
let message = this._parseMessage(event.data);
if (!message) {
return;
}
if (["connecting", "resuming"].includes(this._state)) {
this._processHandshake(message);
} else if (this._state === "connected") {
if (message.seq !== null) {
this._lastReceivedSeq = message.seq;
}
if (message.type === "heartbeat") {
this._processHeartbeat(message);
} else {
this.emit("message", message);
}
this._processMessage(message);
} else {
throw new Error(`Received message in unexpected state ${this._state}`);
@@ -439,11 +575,6 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
}
_processHandshake(message) {
if (!libSchema.serverHandshake(message)) {
logger.warn("Connector | closing after received invalid handshake");
this._socket.close(1002, "Invalid handshake");
return;
}
let { type, data } = message;
if (type === "hello") {
@@ -451,10 +582,9 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
this.emit("hello", data);
if (this._sessionToken) {
logger.verbose("Connector | Attempting resume");
this.sendHandshake("resume", {
session_token: this._sessionToken,
last_seq: this._lastReceivedSeq,
});
this.sendHandshake(new libData.MessageResume(
new libData.ResumeData(this._sessionToken, this._lastReceivedSeq)
));
} else {
this.register();
}
@@ -462,39 +592,39 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
} else if (type === "ready") {
logger.verbose("Connector | received ready from controller");
this._state = "connected";
this._sessionToken = data.session_token;
this._sessionTimeout = data.session_timeout;
this._heartbeatInterval = data.heartbeat_interval;
this.src = data.src;
this._sessionToken = data.sessionToken;
this._sessionTimeout = data.sessionTimeout;
this._heartbeatInterval = data.heartbeatInterval;
this.startHeartbeat();
for (let bufferedMessage of this._sendBuffer) {
this._socket.send(JSON.stringify(bufferedMessage));
this._sendInternal(bufferedMessage);
}
this.emit("connect", data);
} else if (type === "continue") {
logger.info("Connector | resuming existing session");
this._state = "connected";
this._heartbeatInterval = data.heartbeat_interval;
this._sessionTimeout = data.session_timeout;
this._heartbeatInterval = data.heartbeatInterval;
this._sessionTimeout = data.sessionTimeout;
this.startHeartbeat();
this._dropSendBufferSeq(data.last_seq);
this._dropSendBufferSeq(data.lastSeq);
for (let bufferedMessage of this._sendBuffer) {
this._socket.send(JSON.stringify(bufferedMessage));
this._sendInternal(bufferedMessage);
}
this._startedResuming = null;
this.emit("resume");
} else if (type === "invalidate") {
logger.warn("Connector | session invalidated by controller");
this._state = "connecting";
this._seq = 1;
this._lastReceivedSeq = null;
this._sessionToken = null;
this._sessionTimeout = null;
this._sendBuffer.length = 0;
this._startedResuming = null;
this.emit("invalidate");
this.register();
if (this._disconnecting) {
this._reset();
this.emit("close");
} else {
this._invalidate();
this.emit("invalidate");
this.register();
}
}
}
@@ -515,12 +645,11 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
* @extends events.EventEmitter
* @memberof module:lib/link
*/
class VirtualConnector extends events.EventEmitter {
constructor() {
super();
class VirtualConnector extends BaseConnector {
constructor(src, dst) {
super(src, dst);
this.other = this;
this._seq = 1;
}
/**
@@ -529,32 +658,30 @@ class VirtualConnector extends events.EventEmitter {
* Creates two virtual connectors that are liked to each othes such that
* a message sent on one is received by the other.
*
* @param {module:lib/data.Address} src - Source for obverse connector
* @param {module:lib/data.Address} dst - destination for obverse connector
* @returns {Array} two virtuarl connectors.
*/
static makePair() {
let first = new this();
let second = new this();
first.other = second;
second.other = first;
return [first, second];
static makePair(src, dst) {
let obverse = new this(src, dst);
let reverse = new this(dst, src);
obverse.other = reverse;
reverse.other = obverse;
return [obverse, reverse];
}
/**
* Send a message to the other end of the connector
*
* @param {string} type - Message type to send.
* @param {Object} data - Data to send with message.
* @returns {number} the sequence number of the message sent
* @param {module:lib/data.Message} message - Message type to send.
*/
send(type, data) {
let seq = this._seq;
this._seq += 1;
this.other.emit("message", { seq, type, data });
return seq;
send(message) {
this.other.emit("message", message);
}
}
module.exports = {
BaseConnector,
WebSocketBaseConnector,
WebSocketClientConnector,
VirtualConnector,
+2 -2
View File
@@ -5,11 +5,11 @@
*/
"use strict";
const link = require("./link");
const messages = require("./messages");
const connectors = require("./connectors");
module.exports = {
...link,
...messages,
...connectors,
Event: class Event {},
Request: class Request {},
};
+364 -166
View File
@@ -1,9 +1,10 @@
// Implementation of Link class
"use strict";
const libSchema = require("../schema");
const libData = require("../data");
const libErrors = require("../errors");
const { logger } = require("../logging");
const libSchema = require("../schema");
// Some definitions for the terminology used here:
// link: Either side of a controller - client connection
@@ -20,61 +21,65 @@ const { logger } = require("../logging");
* @memberof module:lib/link
*/
class Link {
constructor(source, target, connector) {
this.source = source;
this.target = target;
constructor(connector) {
this.connector = connector;
this.router = undefined;
this.validateSent = true;
this._waiters = new Map();
this._handlers = new Map();
this._validators = new Map();
this._registeredRequests = new Map();
this._fallbackedRequests = new Map();
this._registeredEvents = new Map();
this._snoopedEvents = new Map();
this._eventHandlers = new Map();
this._pendingRequests = new Map();
this._nextRequestId = 1;
this.register(libData.PingRequest, () => {});
// Process messages received by the connector
connector.on("message", payload => {
try {
this.processMessage(payload);
this._processMessage(payload);
} catch (err) {
if (err instanceof libErrors.InvalidMessage) {
logger.error(`Invalid message on ${this.source}-${this.target} link: ${err.message}`);
logger.error(err.message);
if (err.errors) {
logger.error(JSON.stringify(err.errors, null, 4));
}
// Send back an error response if this was a request.
if (
typeof payload.type === "string"
&& payload.type.endsWith("_request")
&& Number.isInteger(payload.seq)
) {
this.connector.send(
`${payload.type.slice(0, -8)}_response`,
{ seq: payload.seq, error: err.message }
);
}
} else {
// Unexpected error, bubble back to connector
this.connector.emit("error", err);
}
}
});
connector.on("invalidate", () => {
for (let waiterType of this._waiters.values()) {
for (let waiter of waiterType) {
waiter.reject(new libErrors.SessionLost("Session Lost"));
connector.on("disconnectPrepare", () => {
this.prepareDisconnect().catch(
err => {
logger.error(`Unexpected error preparing disconnect:\n${err.stack}`);
}
).finally(
() => {
this.connector.send(new libData.MessageDisconnect("ready"));
},
);
});
connector.on("invalidate", () => {
for (let pending of this._pendingRequests.values()) {
pending.reject(new libErrors.SessionLost("Session Lost"));
}
this._waiters.clear();
this._pendingRequests.clear();
});
connector.on("close", () => {
for (let waiterType of this._waiters.values()) {
for (let waiter of waiterType) {
waiter.reject(new libErrors.SessionLost("Session Closed"));
}
for (let pending of this._pendingRequests.values()) {
pending.reject(new libErrors.SessionLost("Session Closed"));
}
this._waiters.clear();
this._pendingRequests.clear();
});
}
@@ -84,159 +89,163 @@ class Link {
* Validates and invokes the handler and/or waiters for a message that has
* been received. An unhandled message is considered to be an error.
*
* @param {Object} message - Message to process.
* @throws {module:lib/errors.InvalidMessage}
* if validation failed, is missing, the message is invalid, or no
* handlers/waiters were invoked to handle the message.
* @param {module:lib/data.Message} message - Message to process.
* @throws {module:lib/errors.InvalidMessage} if the message is invalid or not handled.
*/
processMessage(message) {
if (!libSchema.message(message)) {
throw new libErrors.InvalidMessage("Malformed", libSchema.message.errors);
_processMessage(message) {
if (!["request", "response", "responseError", "event"].includes(message.type)) {
throw new libErrors.InvalidMessage(`Unhandled message type ${message.type}`);
}
let validator = this._validators.get(message.type);
if (!validator) {
throw new libErrors.InvalidMessage(`No validator for ${message.type} on ${this.source}-${this.target}`);
if (message.type === "event" && this._snoopedEvents.has(message.name)) {
let event = this._snoopedEvents.get(message.name);
event.handler(event.eventFromJSON(message.data), message.src, message.dst).catch(err => {
logger.error(`Unexpected error snooping ${message.name}:\n${err.stack}`);
});
}
if (!validator(message)) {
throw new libErrors.InvalidMessage(`Validation failed for ${message.type}`, validator.errors);
if (!message.dst.addressedTo(this.connector.src)) {
this._routeMessage(message);
return;
}
let hadHandlers = this._processHandler(message);
let hadWaiters = this._processWaiters(message);
if (message.type === "request") {
let request = this._registeredRequests.get(message.name);
if (!request) {
this.connector.sendResponseError(
new libData.ResponseError(`Unrecognized request ${message.name}`),
message.src,
);
return;
}
this._processRequest(message, request);
if (!hadWaiters && !hadHandlers) {
// XXX console.error(`Unhandled message: ${JSON.stringify(message, null, 4)}`);
throw new libErrors.InvalidMessage(`Unhandled message ${message.type}`);
} else if (message.type === "response") {
this._processResponse(message);
} else if (message.type === "responseError") {
this._processResponseError(message);
} else if (message.type === "event") {
this._processEvent(message);
}
}
/**
* Invoke the handler for this message if it exists
*
* @param {Object} message - Message to invoke handlers on.
* @returns {Boolean} true if a handler was invoked.
*/
_processHandler(message) {
let handler = this._handlers.get(message.type);
if (handler) {
handler(message);
return true;
_routeMessage(message) {
if (!this.router) {
let err = new libErrors.InvalidMessage(
`Received message addressed to ${message.dst} but this link does not route messages`
);
if (message.type === "request") {
this.connector.sendResponseError(
new libData.ResponseError(err.message, err.code), message.src
);
}
throw err;
}
return false;
let fallback = this._fallbackedRequests.get(message.name);
if (this.router.forwardMessage(this, message, Boolean(fallback))) {
return;
}
if (!fallback) {
throw new Error("Router requested fallback handling when fallback is unavailable");
}
if (message.type !== "request") {
throw new Error(`Router requested fallback handling of unsupported message type ${message.type}`);
}
this._processRequest(message, fallback);
}
/**
* Invokes the waiters for this message if any
*
* @param {Object} message - Message to invoke waiters on.
* @returns {Boolean} true if a waiter was triggered.
*/
_processWaiters(message) {
let { type, data } = message;
let waiters = this._waiters.get(type);
if (!waiters || !waiters.length) {
return false;
_processRequest(message, request) {
if (!request.handler) {
this.connector.sendResponseError(
new libData.ResponseError(`No handler registered for ${request.Request.name}`), message.src
);
return;
}
let matched = [];
waitersLoop: for (let index = 0; index < waiters.length; index++) {
let waiter = waiters[index];
for (let [key, value] of Object.entries(waiter.data)) {
if (data[key] !== value) {
continue waitersLoop;
let response;
try {
response = request.handler(request.requestFromJSON(message.data), message.src, message.dst);
} catch (err) {
if (err.errors) {
logger.error(JSON.stringify(err.errors, null, 4));
}
this.connector.sendResponseError(
new libData.ResponseError(err.message, err.code, err.stack), message.src
);
return;
}
if (!(response instanceof Promise)) {
response = Promise.resolve(response);
}
response.then(
result => {
if (this.validateSent) {
if (request.Response) {
request.responseFromJSON(JSON.parse(JSON.stringify(result)));
} else if (result !== undefined) {
throw new Error(`Expected empty response from ${request.Request.name} handler`);
}
}
this.connector.sendResponse(result, message.src);
}
waiter.resolve(message);
matched.push(index);
}
matched.reverse();
for (let index of matched) {
waiters.splice(index, 1);
}
return matched.length > 0;
}
/**
* Set handler for a message type
*
* Set function called upon receiving a message of the given type.
*
* @param {string} type - Type of message to listen to
* @param {function} handler -
* Callack to invoke on messages of the given type.
* @param {function} validator -
* Function validating the message have the correct format.
*/
setHandler(type, handler, validator) {
if (this._handlers.has(type)) {
throw new Error(`${type} already has a handler`);
}
if (!validator) {
throw new Error("validator is required");
}
this.setValidator(type, validator);
this._handlers.set(type, handler);
}
/**
* Set validator for a message type
*
* Set function called upon receiving a message of the given type in
* order to validate the message. The function should return true if
* the message is valid and false otherwise.
*
* @param {string} type - Type of message to validate
* @param {function} validator - Validation function.
*/
setValidator(type, validator) {
if (this._validators.has(type)) {
throw new Error(`${type} already has a validator`);
}
this._validators.set(type, validator);
}
/**
* Wait for a message matching given type and data
*
* Waits for a message over the link that matches the type given as well
* as any properties specified in data. For example specifying { foo:
* 21 } as the data will cause it to wait until a message with the right
* type and a foo property value of 21 in the data payload.
*
* @param {string} type - Message type to wait for.
* @param {Object} data - Properties to match in the message data.
*/
async waitFor(type, data) {
if (!this._validators.has(type)) {
throw new Error(`No validator for ${type} on ${this.source}-${this.target}`);
}
let waiter = { data };
waiter.promise = new Promise((resolve, reject) => {
waiter.resolve = resolve;
waiter.reject = reject;
if (!this._waiters.has(type)) {
this._waiters.set(type, [waiter]);
} else {
this._waiters.get(type).push(waiter);
).catch(
err => {
if (!(err instanceof libErrors.RequestError)) {
logger.error(`Unexpected error responding to ${message.name}:\n${err.stack}`);
}
this.connector.sendResponseError(
new libData.ResponseError(err.message, err.code, err.stack), message.src
);
}
);
}
_processResponse(message) {
let pending = this._pendingRequests.get(message.dst.requestId);
if (!pending) {
throw new libErrors.InvalidMessage(
`Received response ${message.dst.requestId} without a pending request`
);
}
try {
pending.resolve(pending.request.responseFromJSON(message.data));
} catch (err) {
// An invalid response object was likely received
pending.reject(err);
}
}
_processResponseError(message) {
let pending = this._pendingRequests.get(message.dst.requestId);
if (!pending) {
throw new libErrors.InvalidMessage(
`Received error response ${message.dst.requestId} without a pending request`
);
}
pending.reject(new libErrors.RequestError(message.data.message, message.data.code, message.data.stack));
}
_processEvent(message) {
let event = this._registeredEvents.get(message.name);
if (!event) {
throw new libErrors.InvalidMessage(`Unrecognized event ${message.name}`);
}
if (!event.handler) {
return;
}
event.handler(event.eventFromJSON(message.data), message.src, message.dst).catch(err => {
logger.error(`Unexpected error handling ${message.name}:\n${err.stack}`);
});
return waiter.promise;
}
/**
* Handle ping requests
*/
async pingRequestHandler() { }
/**
* Prepare connection for disconnect
*
@@ -245,16 +254,205 @@ class Link {
* additional requests to be sent out before calling the super class
* method.
*/
async prepareDisconnectRequestHandler() {
async prepareDisconnect() {
let promises = [];
for (let waiterType of this._waiters.values()) {
for (let waiter of waiterType) {
promises.push(waiter.promise.then(() => {}, () => {}));
}
for (let pending of this._pendingRequests.values()) {
promises.push(pending.promise.then(() => {}, () => {}));
}
await Promise.all(promises);
}
/**
* Send a request or event to the other side of this link
* @param {*} requestOrEvent - Request or event to send
* @returns {Promise<*>|undefined}
* Promise that resolves to the response if a request was sent or
* undefined if it was an event.
*/
send(requestOrEvent) {
return this.sendTo(requestOrEvent, this.connector.dst);
}
/**
* Send a request or event to the given address
*
* @param {*} requestOrEvent - Request or event to send
* @param {*|module:lib/data.Address} destination - Where to send it
* @returns {Promise<*>|undefined}
* Promise that resolves to the response if a request was sent or
* undefined if it was an event.
*/
sendTo(requestOrEvent, destination) {
let dst = libData.Address.fromShorthand(destination);
if (requestOrEvent.constructor.type === "request") {
return this.sendRequest(requestOrEvent, dst);
}
if (requestOrEvent.constructor.type === "event") {
return this.sendEvent(requestOrEvent, dst);
}
throw Error(`Expected request or event but got type ${requestOrEvent.constructor.type}`);
}
sendRequest(request, dst) {
let name = request.constructor.name;
if (!this._registeredRequests.has(name)) {
// XXX should this be allowed?
this.registerRequest(request.constructor);
}
let registeredRequest = this._registeredRequests.get(name);
if (this.validateSent) {
registeredRequest.requestFromJSON(JSON.parse(JSON.stringify(request)));
}
let pending = {
request: registeredRequest,
};
pending.promise = new Promise((resolve, reject) => {
pending.resolve = resolve;
pending.reject = reject;
});
let requestId = this._nextRequestId;
this._nextRequestId += 1;
this._pendingRequests.set(requestId, pending);
this.connector.sendRequest(request, requestId, dst);
return pending.promise;
}
sendEvent(event, dst) {
if (this.validateSent) {
let name = event.constructor.name;
if (!this._registeredEvents.has(name)) {
// XXX should this be allowed?
this.registerEvent(event.constructor);
}
this._registeredEvents.get(name).eventFromJSON(JSON.parse(JSON.stringify(event)));
}
this.connector.sendEvent(event, dst);
}
register(Class, handler) {
if (Class.type === "request") {
this.registerRequest(Class, handler);
} else if (Class.type === "event") {
this.registerEvent(Class, handler);
} else {
throw new Error(`Class ${Class.name} has unrecognized type ${Class.type}`);
}
}
_requestEntry(Request, handler) {
let name = Request.name;
let entry = {
Request,
handler,
};
if (Request.fromJSON) {
if (!Request.jsonSchema) {
throw new Error(`Request ${name} has static fromJSON but is missing static jsonSchema`);
}
let validate = libSchema.compile(Request.jsonSchema);
entry.requestFromJSON = (json) => {
if (!validate(json)) {
throw new libErrors.InvalidMessage(`Request ${name} failed validation`, validate.errors);
}
return Request.fromJSON(json);
};
} else if (Request.jsonSchema) {
throw new Error(`Request ${name} has static jsonSchema but is missing static fromJSON`);
} else {
entry.requestFromJSON = () => new Request();
}
let Response = Request.Response;
if (Response) {
if (!Response.jsonSchema) {
throw new Error(`Response for Request ${name} is missing static jsonSchema`);
}
if (!Response.fromJSON) {
throw new Error(`Response for Request ${name} is missing static fromJSON`);
}
let validate = libSchema.compile(Response.jsonSchema);
entry.responseFromJSON = (json) => {
if (!validate(json)) {
throw new libErrors.InvalidMessage(
`Response for request ${name} failed validation`, validate.errors
);
}
return Response.fromJSON(json);
};
entry.Response = Response;
} else {
entry.responseFromJSON = () => undefined;
}
return entry;
}
registerRequest(Request, handler) {
let name = Request.name;
if (this._registeredRequests.has(name)) {
throw new Error(`Request ${name} is already registered`);
}
let request = this._requestEntry(Request, handler);
this._registeredRequests.set(name, request);
}
fallbackRequest(Request, handler) {
let name = Request.name;
if (this._fallbackedRequests.has(name)) {
throw new Error(`Request ${name} is already fallbacked`);
}
let request = this._requestEntry(Request, handler);
this._fallbackedRequests.set(name, request);
}
_createEventFromJSON(Event) {
if (Event.fromJSON) {
if (!Event.jsonSchema) {
throw new Error(`Event ${Event.name} has static fromJSON but is missing static jsonSchema`);
}
let validate = libSchema.compile(Event.jsonSchema);
return (json) => {
if (!validate(json)) {
throw new libErrors.InvalidMessage(`Event ${Event.name} failed validation`, validate.errors);
}
return Event.fromJSON(json);
};
}
if (Event.jsonSchema) {
throw new Error(`Event ${Event.name} has static jsonSchema but is missing static fromJSON`);
}
return () => new Event();
}
registerEvent(Event, handler) {
if (this._registeredEvents.has(Event.name)) {
throw new Error(`Event ${Event.name} is already registered`);
}
let event = {
Event,
handler,
eventFromJSON: this._createEventFromJSON(Event),
};
this._registeredEvents.set(Event.name, event);
}
snoopEvent(Event, handler) {
let name = Event.name;
if (this._snoopedEvents.has(name)) {
throw new Error(`Event ${name} is already snooped`);
}
let event = {
Event,
handler,
eventFromJSON: this._createEventFromJSON(Event),
};
this._snoopedEvents.set(Event.name, event);
}
}
File diff suppressed because it is too large. Load diff