Reorganise packages/lib

Move the majority of the script files into a src directory to be
consistent with the organisation of the other packages.
This commit is contained in:
Hornwitser committed 2023-07-28 16:03:29 +02:00
1 parent bfe119eaa3
commit bc574ee1cb
48 files changed
+41 -41

No files matched your search

+692
View File
@@ -0,0 +1,692 @@
// Connection adapters for Links
"use strict";
const assert = require("assert").strict;
const events = require("events");
// eslint-disable-next-line node/no-process-env
const WebSocket = process.env.APP_ENV === "browser" ? window.WebSocket : require("ws");
const libData = require("../data");
const libErrors = require("../errors");
const { logger } = require("../logging");
const ExponentialBackoff = require("../ExponentialBackoff");
/**
* Base connector for links
*
* @extends events.EventEmitter
* @memberof module:lib
*/
class BaseConnector extends events.EventEmitter {
constructor(src, dst) {
super();
this._seq = 1;
this.src = src;
this.dst = dst;
}
_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 Request = request.constructor;
let name = Request.plugin ? `${Request.plugin}:${Request.name}` : Request.name;
let hasData = Boolean(Request.jsonSchema);
const message = new libData.MessageRequest(seq, src, dst, name, hasData ? request : undefined);
this.send(message);
return seq;
}
sendResponse(response, dst, src = this.src) {
let seq = this._seq;
this._seq += 1;
const message = new libData.MessageResponse(seq, src, dst, response);
this.send(message);
return seq;
}
sendResponseError(error, dst, src = this.src) {
let seq = this._seq;
this._seq += 1;
const message = new libData.MessageResponseError(seq, src, dst, error);
this.send(message);
return seq;
}
sendEvent(event, dst) {
let seq = this._seq;
this._seq += 1;
let Event = event.constructor;
let name = Event.plugin ? `${Event.plugin}:${Event.name}` : Event.name;
let hasData = Boolean(Event.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.BaseConnector
* @memberof module:lib
*/
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._lastHeartbeat = null;
this._heartbeatId = null;
this._heartbeatInterval = null;
this._lastReceivedSeq = undefined;
this._sendBuffer = [];
}
_reset() {
this._state = "closed";
this._closing = false;
assert(this._socket === null);
this._lastHeartbeat = null;
assert(this._heartbeatId === null);
this._heartbeatInterval = 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) {
if (!expectedStates.includes(this._state)) {
throw new Error(
`Expected state ${expectedStates} but state is ${this._state}`
);
}
}
_dropSendBufferSeq(seq) {
if (seq === undefined) {
return;
}
let dropCount = 0;
for (let index = 0; index < this._sendBuffer.length; index++) {
if (this._sendBuffer[index].seq <= seq) {
dropCount += 1;
} else {
break;
}
}
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) {
logger.verbose("Connector | closing after heartbeat timed out");
// eslint-disable-next-line node/no-process-env
if (process.env.APP_ENV === "browser") {
this._socket.close(4008, "Heartbeat timeout");
} else {
this._socket.terminate();
}
} else {
this._sendInternal(new libData.MessageHeartbeat(this._lastReceivedSeq));
}
}
_processHeartbeat(message) {
this._lastHeartbeat = Date.now();
this._dropSendBufferSeq(message.seq);
}
/**
* Start sending heartbeats
*/
startHeartbeat() {
if (this._heartbeatId) {
throw new Error("heartbeat is already running");
}
this._lastHeartbeat = Date.now();
this._heartbeatId = setInterval(() => {
this._doHeartbeat();
}, this._heartbeatInterval * 1000);
}
/**
* Stop sending heartbeats
*/
stopHeartbeat() {
if (this._heartbeatId) {
clearInterval(this._heartbeatId);
this._heartbeatId = null;
}
}
/**
* Send a message over the socket
*
* This is a low level method that should only be used for implementing
* links. See sendTo for sending requests and events.
*
* @param {module:lib.Message} message - Message to send.
*/
send(message) {
if (!["connected", "resuming"].includes(this._state)) {
throw new libErrors.SessionLost("No session");
}
this._sendBuffer.push(message);
if (this._state === "connected") {
this._sendInternal(message);
}
}
_sendInternal(message) {
this._socket.send(JSON.stringify(message));
}
/**
* Set connection state to closing
*
* Signal the connection is about to close and that once the close
* frame is received it should be considered finished.
*/
setClosing() {
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._closing && this._state === "connected";
}
/**
* True if the connection is closing down or closed
*/
get closing() {
return this._closing || this._state === "closed";
}
/**
* True if the connector currently has a valid session that is either
* connected or in the process of resuming.
*/
get hasSession() {
return ["connected", "resuming"].includes(this._state);
}
}
/**
* Connector for controller clients
*
* @extends module:lib.WebSocketBaseConnector
* @memberof module:lib
*/
class WebSocketClientConnector extends WebSocketBaseConnector {
constructor(url, maxReconnectDelay, tlsCa = null) {
super(undefined, new libData.Address(libData.Address.controller, 0));
this._url = url;
this._backoff = new ExponentialBackoff({ max: maxReconnectDelay });
this._tlsCa = tlsCa;
// The following states are used in the client connector
// closed: Not connected
// connecting: Attempting to connect to server.
// resuming: Attempting to resume an existing connection to the server.
// connected: Connection is online
this._reconnectId = null;
this._sessionToken = null;
this._sessionTimeout = null;
this._startedResuming = null;
}
_reset() {
clearTimeout(this._reconnectId);
this._reconnectId = null;
this._sessionToken = null;
this._sessionTimeout = null;
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 handshake messages
* over the WebSocket.
*
* @param {module:lib.Message} message - Message to send.
*/
sendHandshake(message) {
this._check("connecting", "resuming");
this._sendInternal(message);
}
/**
* Close the connection with the given reason.
*
* Sends a close frame and disconnects the connector.
*
* @param {number} code - WebSocket close code.
* @param {string} reason - WebSocket close reason.
*/
async close(code, reason) {
if (this._state === "closed") {
return;
}
this._closing = true;
if (this._state === "connected" || this._socket) {
this._socket.close(code, reason);
await events.once(this, "close");
} else {
this._reset();
this.emit("close");
}
}
/**
* Notify the connection is expected to close
*
* Sets the internal flag to signal not to attempt to resume the
* connection if the server closes it. This will close the connection
* if it's currently attempting to connect or resume.
*/
setClosing() {
if (this._state === "closed") {
return;
}
this._closing = true;
if (this._state === "connected") {
return;
}
if (this._socket) {
this._socket.close(1000, "Connector closing");
} else {
this._reset();
this.emit("close");
}
}
/**
* Connect to the controller
*/
async connect() {
this._check("closed");
this._state = "connecting";
this._doConnect();
// Wait for the connection to be ready
await events.once(this, "connect");
}
_doConnect() {
let url = new URL(this._url);
url.pathname += "api/socket";
url.protocol = url.protocol.replace("http", "ws");
// Open WebSocket to controller
logger.verbose(`Connector | connecting to ${url}`);
// eslint-disable-next-line node/no-process-env
if (process.env.APP_ENV === "browser") {
this._socket = new WebSocket(url);
} else {
let options = {};
if (this._tlsCa) { options.ca = this._tlsCa; }
this._socket = new WebSocket(url, options);
}
this._attachSocketHandlers();
}
/**
* Attempt re-establishing the connecting again
*/
reconnect() {
if (this._socket) {
throw new Error("Cannot reconnect while socket is open");
}
if (this._reconnectId !== null) {
logger.error("Unexpected double call to reconnect");
}
let delay = this._backoff.delay();
if (
this._state === "resuming"
&& this._startedResuming + this._sessionTimeout * 1000 < Date.now() + delay
) {
logger.error("Connector | Session timed out trying to resume");
this._reset();
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`
);
this._reconnectId = setTimeout(() => {
this._reconnectId = null;
this._doConnect();
}, delay);
this._reconnectTime = Date.now() + delay;
}
_attachSocketHandlers() {
this._socket.onclose = event => {
const previousState = this._state;
// Authentication failed
if (event.code === 4003) {
this.emit("error", new libErrors.AuthenticationFailed(event.reason));
this._closing = true;
}
this._socket = null;
if (this._state === "connected") {
this.stopHeartbeat();
if (this._closing) {
this._reset();
this.emit("close");
} else {
this._state = "resuming";
this._startedResuming = Date.now();
this.reconnect();
this.emit("drop");
}
} else {
// eslint-disable-next-line no-lonely-if
if (this._closing) {
this._reset();
this.emit("close");
} else {
this.reconnect();
}
}
// Log must be sent after state change is complete
let message = `Connector | Close (code: ${event.code}, reason: ${event.reason})`;
if (previousState === "connected" && event.code !== 1000) {
logger.info(message);
} else {
logger.verbose(message);
}
};
this._socket.onerror = event => {
// It's assumed that close is always called by ws
let code = !event.error ? "" : `, code: ${event.error.code}`;
let message = `Connector | Socket error: ${event.message || "unknown error"}${code}`;
if (this._state === "connected") {
logger.error(message);
} else {
// Don't log as error if not actually connected, prevents
// log spam during reconnecting attempts.
logger.verbose(message);
}
if (event.error) {
// Abort connection if certificate validation failed
if ([
"CERT_HAS_EXPIRED",
"DEPTH_ZERO_SELF_SIGNED_CERT",
"ERR_TLS_CERT_ALTNAME_INVALID",
].includes(event.error.code)) {
this.emit("error", new libErrors.AuthenticationFailed(event.error.message));
this._closing = true;
}
}
};
this._socket.onopen = () => {
logger.verbose("Connector | Open");
};
// Handle messages
this._socket.onmessage = event => {
let message = this._parseMessage(event.data);
if (!message) {
return;
}
if (["connecting", "resuming"].includes(this._state)) {
this._processHandshake(message);
} else if (this._state === "connected") {
this._processMessage(message);
} else {
throw new Error(`Received message in unexpected state ${this._state}`);
}
};
}
_processHandshake(message) {
let { type, data } = message;
if (type === "hello") {
logger.verbose(`Connector | received hello from controller version ${data.version}`);
this.emit("hello", data);
if (this._sessionToken) {
logger.verbose("Connector | Attempting resume");
this.sendHandshake(new libData.MessageResume(
new libData.ResumeData(this._sessionToken, this._lastReceivedSeq)
));
} else {
this.register();
}
} else if (type === "ready") {
logger.verbose("Connector | received ready from controller");
this._state = "connected";
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._sendInternal(bufferedMessage);
}
this.emit("connect", data);
} else if (type === "continue") {
logger.info("Connector | resuming existing session");
this._state = "connected";
this._heartbeatInterval = data.heartbeatInterval;
this._sessionTimeout = data.sessionTimeout;
this.startHeartbeat();
this._dropSendBufferSeq(data.lastSeq);
for (let bufferedMessage of this._sendBuffer) {
this._sendInternal(bufferedMessage);
}
this._startedResuming = null;
this.emit("resume");
} else if (type === "invalidate") {
logger.warn("Connector | session invalidated by controller");
if (this._disconnecting) {
this._reset();
this.emit("close");
} else {
this._invalidate();
this.emit("invalidate");
this.register();
}
}
}
/**
* Register the link with the server
*
* This function is expected to be overriden by sub-classes and send the
* register message over the socket when invoked.
*/
register() {
throw Error("Abstract function");
}
}
/**
* Connector for in-memory local links
*
* @extends events.EventEmitter
* @memberof module:lib
*/
class VirtualConnector extends BaseConnector {
constructor(src, dst) {
super(src, dst);
this.other = this;
}
/**
* Create a pair of virtual connector hooked into each other
*
* 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.Address} src - Source for obverse connector
* @param {module:lib.Address} dst - destination for obverse connector
* @returns {Array} two virtuarl connectors.
*/
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 {module:lib.Message} message - Message type to send.
*/
send(message) {
this.other.emit("message", message);
}
}
module.exports = {
BaseConnector,
WebSocketBaseConnector,
WebSocketClientConnector,
VirtualConnector,
};
+17
View File
@@ -0,0 +1,17 @@
/**
* Library for message based communication between nodes
* @module lib/link
* @author Hornwitser
*/
"use strict";
const link = require("./link");
const connectors = require("./connectors");
module.exports = {
...link,
...connectors,
// migrate: Allow info for plugins from before link refactor to load.
Event: class Event {},
Request: class Request {},
};
+686
View File
@@ -0,0 +1,686 @@
// Implementation of Link class
"use strict";
const libData = require("../data");
const libErrors = require("../errors");
const { logger } = require("../logging");
const libSchema = require("../schema");
const { dataClasses } = require("./messages");
// Some definitions for the terminology used here:
// link: Either side of a controller - client connection
// connector: Adapter between a link and a socket connection
// connection: the controller side of a link
// client: the side that is not the controller of a link
// message: the complete object sent using the 'message' event
/**
* Common interface for server and client connections
*
* @memberof module:lib
*/
class Link {
constructor(connector) {
this.connector = connector;
this.router = undefined;
this.validateSent = true;
this._requestHandlers = new Map();
this._requestFallbacks = new Map();
this._eventHandlers = new Map();
this._eventSnoopers = new Map();
this._pendingRequests = new Map();
this._forwardedRequests = new Map();
this._nextRequestId = 1;
this.handle(libData.PingRequest, () => {});
// Process messages received by the connector
connector.on("message", payload => {
try {
this._processMessage(payload);
} catch (err) {
if (err instanceof libErrors.InvalidMessage) {
logger.error(err.message);
if (err.errors) {
logger.error(JSON.stringify(err.errors, null, 4));
}
} else {
// Unexpected error, bubble back to connector
this.connector.emit("error", err);
}
}
});
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", () => {
this._clearPendingRequests(new libErrors.SessionLost("Session Lost"));
});
connector.on("close", () => {
this._clearPendingRequests(new libErrors.SessionLost("Session Closed"));
});
}
_clearPendingRequests(err) {
for (let pending of this._pendingRequests.values()) {
pending.reject(err);
}
for (let pending of this._forwardedRequests.values()) {
if (pending.origin.connector.hasSession) {
pending.origin.connector.sendResponseError(
new libData.ResponseError(err.message, err.code), pending.src, pending.dst
);
}
}
this._pendingRequests.clear();
this._forwardedRequests.clear();
}
/**
* Process a received message on the 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 {module:lib.Message} message - Message to process.
* @throws {module:lib.InvalidMessage} if the message is invalid or not handled.
*/
_processMessage(message) {
if (!["request", "response", "responseError", "event"].includes(message.type)) {
throw new libErrors.InvalidMessage(`Unhandled message type ${message.type}`);
}
let entry = this._validateMessage(message);
if (entry && this.connector.dst.type === libData.Address.control) {
try {
this.validatePermission(message, entry); // Somewhat hacky, defined in ControlConnection
} catch (err) {
if (err instanceof libErrors.PermissionError) {
return;
}
throw err;
}
}
if (message.type === "event" && this._eventSnoopers.has(entry.Event)) {
let handler = this._eventSnoopers.get(entry.Event);
handler(entry.eventFromJSON(message.data), message.src, message.dst).catch(err => {
logger.error(`Unexpected error snooping ${message.name}:\n${err.stack}`);
});
}
if (!message.dst.addressedTo(this.connector.src)) {
if (message.type === "response" || message.type === "responseError") {
this._forwardedRequests.delete(message.dst.index());
}
this._routeMessage(message, entry);
return;
}
if (message.type === "request") {
this._processRequest(message, entry, this._requestHandlers.get(entry.Request));
} else if (message.type === "response") {
this._processResponse(message);
} else if (message.type === "responseError") {
this._processResponseError(message);
} else if (message.type === "event") {
this._processEvent(message, entry);
}
}
/**
* Ingress message validation
*
* Should be overridden by sub-classes to validate messages received.
*
* @param {module:lib.Message} message - Message to check.
* @throws {module:lib.InvalidMessage} if the message is invalid.
*/
validateIngress(message) { }
_validateMessage(message) {
try {
if (message.src.type === libData.Address.broadcast) {
throw new libErrors.InvalidMessage("Message src may not be broadcast");
}
this.validateIngress(message);
} catch (err) {
if (message.type === "request") {
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
}
throw err;
}
if (message.type === "request") {
let entry = this.constructor._requestsByName.get(message.name);
if (!entry) {
let err = new libErrors.InvalidMessage(`Unrecognized request ${message.name}`);
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
throw err;
}
if (!entry.allowedSrcTypes.has(message.src.type)) {
let err = new libErrors.InvalidMessage(`Source ${message.src} is not allowed for ${message.name}`);
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
throw err;
}
if (!entry.allowedDstTypes.has(message.dst.type)) {
let err = new libErrors.InvalidMessage(`Destination ${message.dst} is not allowed for ${message.name}`);
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
throw err;
}
return entry;
} else if (message.type === "response") {
return undefined;
} else if (message.type === "responseError") {
return undefined;
} else if (message.type === "event") {
let entry = this.constructor._eventsByName.get(message.name);
if (!entry) {
throw new libErrors.InvalidMessage(`Unrecognized event ${message.name}`);
}
if (!entry.allowedSrcTypes.has(message.src.type)) {
throw new libErrors.InvalidMessage(`Source ${message.src} is not allowed for ${message.name}`);
}
if (message.dst.type === libData.Address.broadcast) {
if (!entry.allowedDstTypes.has(message.dst.id)) {
throw new libErrors.InvalidMessage(`Destination ${message.dst} is not allowed for ${message.name}`);
}
} else {
// eslint-disable-next-line no-lonely-if
if (!entry.allowedDstTypes.has(message.dst.type)) {
throw new libErrors.InvalidMessage(`Destination ${message.dst} is not allowed for ${message.name}`);
}
}
return entry;
}
throw new Error("Should be unreachable");
}
/**
* Message permission validation
*
* Called when an request or event is received by a control connector.
* Should be overridden by sub-classes to validate messages received.
*
* @param {module:lib.Message} message - Message to check.
* @param {object} entry - Request or Event entry for this Message.
* @throws {module:lib.PermissionError} if unauthorized.
*/
validatePermission(message, entry) { }
_routeMessage(message, entry) {
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;
}
let fallback = message.type === "request" ? this._requestFallbacks.get(entry.Request) : undefined;
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, entry, fallback, message.dst);
}
_processRequest(message, entry, handler, spoofedSrc) {
if (!handler) {
this.connector.sendResponseError(
new libData.ResponseError(`No handler for ${entry.Request.name}`), message.src
);
return;
}
let response;
try {
response = handler(entry.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 (entry.Response) {
entry.responseFromJSON(JSON.parse(JSON.stringify(result)));
} else if (result !== undefined) {
throw new Error(`Expected empty response from ${entry.Request.name} handler`);
}
}
this.connector.sendResponse(result, message.src, spoofedSrc);
}
).catch(
err => {
if (err instanceof libErrors.InvalidMessage) {
logger.error(err.message);
if (err.errors) {
logger.error(JSON.stringify(err.errors, null, 4));
}
} else 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, spoofedSrc
);
}
);
}
_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`
);
}
if (!pending.dst.equals(message.src)) {
throw new libErrors.InvalidMessage(`Received reply from ${message.src} for message sent to ${pending.dst}`);
}
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, entry) {
let handler = this._eventHandlers.get(entry.Event);
if (!handler) {
throw new libErrors.InvalidMessage(`Unhandled event ${message.name}`);
}
handler(entry.eventFromJSON(message.data), message.src, message.dst).catch(err => {
logger.error(`Unexpected error handling ${message.name}:\n${err.stack}`);
});
}
/**
* Prepare connection for disconnect
*
* Waits for all pending requests on the connection to resolve.
* Sub-classes should implement this handler with code that prevents
* additional requests to be sent out before calling the super class
* method.
*/
async prepareDisconnect() {
let promises = [];
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(this.connector.dst, requestOrEvent);
}
/**
* Send a request or event to the given address
*
* @param {*|module:lib.Address} destination - Where to send it
* @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.
*/
sendTo(destination, requestOrEvent) {
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 entry = this.constructor._requestsByClass.get(request.constructor);
if (!entry) {
throw new Error(`Attempt to send unregistered Request ${request.constructor.name}`);
}
if (this.validateSent) {
entry.requestFromJSON(JSON.parse(JSON.stringify(request)));
}
let pending = {
request: entry,
dst,
};
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;
}
forwardRequest(message, origin) {
if (this.validateSent) {
let entry = this.constructor._requestsByName.get(message.name);
if (!entry) {
throw new Error(`Attempt to forward unregistered Request ${message.name}`);
}
entry.requestFromJSON(message.data);
}
let pending = {
origin,
src: message.src,
dst: message.dst,
};
this._forwardedRequests.set(message.src.index(), pending);
this.connector.send(message);
}
sendEvent(event, dst) {
let entry = this.constructor._eventsByClass.get(event.constructor);
if (!entry) {
throw new Error(`Attempt to send unregistered Event ${event.constructor.name}`);
}
if (this.validateSent) {
entry.eventFromJSON(JSON.parse(JSON.stringify(event)));
}
this.connector.sendEvent(event, dst);
}
handle(Class, handler) {
if (Class.type === "request") {
this.handleRequest(Class, handler);
} else if (Class.type === "event") {
this.handleEvent(Class, handler);
} else {
throw new Error(`Class ${Class.name} has unrecognized type ${Class.type}`);
}
}
handleRequest(Request, handler) {
let entry = this.constructor._requestsByClass.get(Request);
if (!entry) {
throw new Error(`Unregistered Request class ${Request.name}`);
}
if (this._requestHandlers.has(Request)) {
throw new Error(`Request ${entry.name} is already registered`);
}
this._requestHandlers.set(Request, handler);
}
fallbackRequest(Request, handler) {
let entry = this.constructor._requestsByClass.get(Request);
if (!entry) {
throw new Error(`Unregistered Request class ${Request.name}`);
}
if (this._requestFallbacks.has(Request)) {
throw new Error(`Request ${entry.name} is already fallbacked`);
}
this._requestFallbacks.set(Request, handler);
}
handleEvent(Event, handler) {
let entry = this.constructor._eventsByClass.get(Event);
if (!entry) {
throw new Error(`Unregistered Event class ${Event.name}`);
}
if (this._eventHandlers.has(Event)) {
throw new Error(`Event ${entry.name} is already registered`);
}
this._eventHandlers.set(Event, handler);
}
snoopEvent(Event, handler) {
let entry = this.constructor._eventsByClass.get(Event);
if (!entry) {
throw new Error(`Unregistered Event class ${Event.name}`);
}
if (this._eventSnoopers.has(Event)) {
throw new Error(`Event ${entry.name} is already snooped`);
}
this._eventSnoopers.set(Event, handler);
}
static register(Class) {
if (Class.type === "request") {
this.registerRequest(Class);
} else if (Class.type === "event") {
this.registerEvent(Class);
} else {
throw new Error(`Data class ${Class.name} has unknown type ${Class.type}`);
}
}
static requestFromJSON(Request, name) {
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);
return (json) => {
if (!validate(json)) {
throw new libErrors.InvalidMessage(`Request ${name} failed validation`, validate.errors);
}
return Request.fromJSON(json);
};
}
if (Request.jsonSchema) {
throw new Error(`Request ${name} has static jsonSchema but is missing static fromJSON`);
}
return () => new Request();
}
static responseFromJSON(Response, name) {
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);
return (json) => {
if (!validate(json)) {
throw new libErrors.InvalidMessage(
`Response for request ${name} failed validation`, validate.errors
);
}
return Response.fromJSON(json);
};
}
static allowedTypes(types, name, side) {
if (types === undefined) {
throw new Error(`Missing ${side} specification in ${name}`);
}
if (!(types instanceof Array)) {
types = [types];
}
let allowed = new Set();
for (let type of types) {
let id = libData.Address[type];
if (typeof id !== "number") {
throw new Error(`Invalid type ${type} in ${side} specification of ${name}`);
}
if (id === libData.Address.broadcast) {
throw new Error(`${side} specification may not use the broadcast type in ${name}`);
}
allowed.add(id);
}
return allowed;
}
static _requestsByName = new Map();
static _requestsByClass = new Map();
static registerRequest(Request) {
const name = Request.plugin ? `${Request.plugin}:${Request.name}` : Request.name;
if (this._requestsByName.has(name)) {
throw new Error(`Request ${name} is already registered`);
}
let entry = {
Request,
name,
requestFromJSON: this.requestFromJSON(Request, name),
allowedSrcTypes: this.allowedTypes(Request.src, name, "src"),
allowedDstTypes: this.allowedTypes(Request.dst, name, "dst"),
};
if (
entry.allowedSrcTypes.has(libData.Address.control)
&& !(Request.permission === null || ["function", "string"].includes(typeof Request.permission))
) {
throw new Error(`Invalid permission specification ${typeof Request.permission} on ${name}`);
}
let Response = Request.Response;
if (Response) {
entry.Response = Response;
entry.responseFromJSON = this.responseFromJSON(Response, name);
} else {
entry.responseFromJSON = () => undefined;
}
this._requestsByName.set(name, entry);
this._requestsByClass.set(Request, entry);
}
static eventFromJSON(Event, name) {
if (Event.fromJSON) {
if (!Event.jsonSchema) {
throw new Error(`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 ${name} failed validation`, validate.errors);
}
return Event.fromJSON(json);
};
}
if (Event.jsonSchema) {
throw new Error(`Event ${name} has static jsonSchema but is missing static fromJSON`);
}
return () => new Event();
}
static _eventsByName = new Map();
static _eventsByClass = new Map();
static registerEvent(Event) {
const name = Event.plugin ? `${Event.plugin}:${Event.name}` : Event.name;
if (this._eventsByName.has(name)) {
throw new Error(`Event ${name} is already registered`);
}
let entry = {
Event,
name,
eventFromJSON: this.eventFromJSON(Event, name),
allowedSrcTypes: this.allowedTypes(Event.src, name, "src"),
allowedDstTypes: this.allowedTypes(Event.dst, name, "dst"),
};
if (
entry.allowedSrcTypes.has(libData.Address.control)
&& !(Event.permission === null || ["function", "string"].includes(typeof Event.permission))
) {
throw new Error(`Invalid permission specification ${typeof Event.permission} on ${name}`);
}
this._eventsByName.set(name, entry);
this._eventsByClass.set(Event, entry);
}
}
for (let Class of dataClasses) {
Link.register(Class);
}
function registerPluginMessages(pluginInfos) {
for (let pluginInfo of pluginInfos) {
for (let Class of pluginInfo.messages || []) {
if (Class.plugin !== pluginInfo.name) {
throw new Error(
`Expected message ${Class.name} from ${pluginInfo.name} to have a static ` +
`plugin property set to "${pluginInfo.name}"`
);
}
Link.register(Class);
}
}
}
module.exports = {
Link,
registerPluginMessages,
};
+111
View File
@@ -0,0 +1,111 @@
"use strict";
const core = require("../data/messages_core");
const controller = require("../data/messages_controller");
const host = require("../data/messages_host");
const instance = require("../data/messages_instance");
const mod = require("../data/messages_mod");
const user = require("../data/messages_user");
// Event and Request payloads registered with the Link class. Used to decode
// the data payload of incomming requsts and event messages into instances of
// their proper classes.
const dataClasses = [
core.PingRequest,
controller.ControllerConfigGetRequest,
controller.ControllerConfigSetFieldRequest,
controller.ControllerConfigSetPropRequest,
controller.HostGenerateTokenRequest,
controller.HostConfigCreateRequest,
controller.LogSetSubscriptionsRequest,
controller.LogQueryRequest,
controller.LogMessageEvent,
controller.DebugDumpWsRequest,
controller.DebugWsMessageEvent,
host.HostListRequest,
host.HostSetSubscriptionsRequest,
host.HostUpdateEvent,
host.HostMetricsRequest,
host.ControllerConnectionEvent,
host.PrepareControllerDisconnectRequest,
host.SyncUserListsEvent,
instance.InstanceDetailsGetRequest,
instance.InstanceDetailsListRequest,
instance.InstanceDetailsSetSubscriptionsRequest,
instance.InstanceDetailsUpdateEvent,
instance.InstanceCreateRequest,
instance.InstanceConfigGetRequest,
instance.InstanceConfigSetFieldRequest,
instance.InstanceConfigSetPropRequest,
instance.InstanceAssignRequest,
instance.InstanceMetricsRequest,
instance.InstanceStartRequest,
instance.InstanceListSavesRequest,
instance.InstanceSetSaveListSubscriptionsRequest,
instance.InstanceSaveListUpdateEvent,
instance.InstanceCreateSaveRequest,
instance.InstanceRenameSaveRequest,
instance.InstanceCopySaveRequest,
instance.InstanceDeleteSaveRequest,
instance.InstanceDownloadSaveRequest,
instance.InstanceTransferSaveRequest,
instance.InstancePullSaveRequest,
instance.InstancePushSaveRequest,
instance.InstanceLoadScenarioRequest,
instance.InstanceExportDataRequest,
instance.InstanceExtractPlayersRequest,
instance.InstanceStopRequest,
instance.InstanceKillRequest,
instance.InstanceDeleteRequest,
instance.InstanceDeleteInternalRequest,
instance.InstanceSendRconRequest,
instance.InstancesUpdateRequest,
instance.InstanceAssignInternalRequest,
instance.InstanceUnassignInternalRequest,
instance.InstanceInitialisedEvent,
instance.InstanceStatusChangedEvent,
instance.InstanceDetailsChangedEvent,
instance.InstanceBanlistUpdateEvent,
instance.InstanceAdminlistUpdateEvent,
instance.InstanceWhitelistUpdateEvent,
instance.InstancePlayerUpdateEvent,
mod.ModPackGetRequest,
mod.ModPackGetDefaultRequest,
mod.ModPackListRequest,
mod.ModPackCreateRequest,
mod.ModPackUpdateRequest,
mod.ModPackDeleteRequest,
mod.ModPackSetSubscriptionsRequest,
mod.ModGetRequest,
mod.ModListRequest,
mod.ModSearchRequest,
mod.ModSetSubscriptionsRequest,
mod.ModDownloadRequest,
mod.ModDeleteRequest,
mod.ModPackUpdateEvent,
mod.ModUpdateEvent,
user.PermissionListRequest,
user.RoleListRequest,
user.RoleCreateRequest,
user.RoleUpdateRequest,
user.RoleGrantDefaultPermissionsRequest,
user.RoleDeleteRequest,
user.UserGetRequest,
user.UserListRequest,
user.UserSetSubscriptionsRequest,
user.UserCreateRequest,
user.UserRevokeTokenRequest,
user.UserUpdateRolesRequest,
user.UserSetAdminRequest,
user.UserSetWhitelistedRequest,
user.UserSetBannedRequest,
user.UserDeleteRequest,
user.AccountUpdateEvent,
user.UserUpdateEvent,
];
module.exports = { dataClasses };