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

+4
View File
@@ -62,6 +62,10 @@ class PlayerStats {
}
}
static fromJSON(json) {
return new this(json);
}
toJSON() {
let json = {};
if (this.joinCount) {
+12 -11
View File
@@ -7,6 +7,7 @@
* @module lib/command
*/
"use strict";
const libData = require("./data");
const libLink = require("./link");
const libErrors = require("./errors");
@@ -150,8 +151,8 @@ async function resolveHost(client, hostName) {
if (/^-?\d+$/.test(hostName)) {
hostId = parseInt(hostName, 10);
} else {
let response = await libLink.messages.listHosts.send(client);
for (let host of response.list) {
let hosts = await client.sendTo(new libData.HostListRequest(), "controller");
for (let host of hosts) {
if (host.name === hostName) {
hostId = host.id;
break;
@@ -182,8 +183,8 @@ async function resolveInstance(client, instanceName) {
if (/^-?\d+$/.test(instanceName)) {
instanceId = parseInt(instanceName, 10);
} else {
let response = await libLink.messages.listInstances.send(client);
for (let instance of response.list) {
let instances = await client.sendTo(new libData.InstanceDetailsListRequest(), "controller");
for (let instance of instances) {
if (instance.name === instanceName) {
instanceId = instance.id;
break;
@@ -215,10 +216,10 @@ async function resolveModPack(client, modPackName) {
if (/^-?\d+/.test(modPackName)) {
modPackId = parseInt(modPackName, 10);
} else {
let response = await libLink.messages.listModPacks.send(client);
for (let mod_pack of response.list) {
if (mod_pack["name"] === modPackName) {
modPackId = mod_pack["id"];
let modPacks = await client.sendTo(new libData.ModPackListRequest(), "controller");
for (let modPack of modPacks) {
if (modPack.name === modPackName) {
modPackId = modPack.id;
break;
}
}
@@ -243,12 +244,12 @@ async function resolveModPack(client, modPackName) {
* @static
*/
async function retrieveRole(client, roleName) {
let response = await libLink.messages.listRoles.send(client);
let roles = await client.sendTo(new libData.RoleListRequest(), "controller");
let resolvedRole;
if (/^-?\d+$/.test(roleName)) {
let roleId = parseInt(roleName, 10);
for (let role of response.list) {
for (let role of roles) {
if (role.id === roleId) {
resolvedRole = role;
break;
@@ -256,7 +257,7 @@ async function retrieveRole(client, roleName) {
}
} else {
for (let role of response.list) {
for (let role of roles) {
if (role.name === roleName) {
resolvedRole = role;
break;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
function jsonArray(ItemClass) {
return {
jsonSchema: {
type: "array",
items: ItemClass.jsonSchema,
},
fromJSON(json) {
return json.map(i => ItemClass.fromJSON(i));
},
};
}
function jsonPrimitive(type) {
return {
jsonSchema: { type },
fromJSON(json) {
return json;
},
};
}
module.exports = {
JsonBoolean: jsonPrimitive("boolean"),
JsonNumber: jsonPrimitive("number"),
JsonString: jsonPrimitive("string"),
jsonArray,
jsonPrimitive,
};
+14
View File
@@ -7,11 +7,25 @@
const ExportManifest = require("./ExportManifest");
const ModInfo = require("./ModInfo");
const ModPack = require("./ModPack");
const composites = require("./composites");
const messagesCore = require("./messages_core");
const messagesController = require("./messages_controller");
const messagesHost = require("./messages_host");
const messagesInstance = require("./messages_instance");
const messagesMod = require("./messages_mod");
const messagesUser = require("./messages_user");
const version = require("./version");
module.exports = {
ExportManifest,
ModInfo,
ModPack,
...composites,
...messagesCore,
...messagesController,
...messagesHost,
...messagesInstance,
...messagesMod,
...messagesUser,
...version,
};
+384
View File
@@ -0,0 +1,384 @@
"use strict";
const { JsonString } = require("./composites");
// TODO: remove after config refactor
/** @memberof module:lib/data */
class RawConfig {
/** @type {object} */
serializedConfig;
constructor(serializedConfig) {
this.serializedConfig = serializedConfig;
}
static jsonSchema = {
type: "object",
required: ["serializedConfig"],
properties: {
"serializedConfig": { type: "object" },
},
};
static fromJSON(json) {
return new this(json.serializedConfig);
}
}
/* @memberof module:lib/data */
class ControllerConfigGetRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.controller.get_config";
static Response = RawConfig;
}
/** @memberof module:lib/data */
class ControllerConfigSetFieldRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.controller.update_config";
/** @type {string} */
field;
/** @type {string} */
value;
constructor(field, value) {
this.field = field;
this.value = value;
}
static jsonSchema = {
type: "object",
required: ["field", "value"],
properties: {
"field": { type: "string" },
"value": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.field, json.value);
}
}
/* @memberof module:lib/data */
class ControllerConfigSetPropRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.controller.update_config";
/** @type {string} */
field;
/** @type {string} */
prop;
/** @type {undefined} */
value;
constructor(field, prop, value) {
this.field = field;
this.prop = prop;
if (value) { this.value = value; }
}
static jsonSchema = {
type: "object",
required: ["field", "prop"],
properties: {
field: { type: "string" },
prop: { type: "string" },
value: {},
},
};
static fromJSON(json) {
return new this(json.field, json.prop, json.value);
}
}
/* @memberof module:lib/data */
class HostGenerateTokenRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.host.generate_token";
/** @type {?number} */
hostId;
constructor(hostId) {
this.hostId = hostId;
}
static jsonSchema = {
type: "object",
required: ["hostId"],
properties: {
hostId: { type: ["integer", "null"] },
},
};
static fromJSON(json) {
return new this(json.hostId);
}
static Response = JsonString;
}
/** @memberof module:lib/data */
class HostConfigCreateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.host.create_config";
/** @type {?number} */
id;
/** @type {?string} */
name;
/** @type {boolean} */
generateToken;
constructor(id, name, generateToken) {
this.id = id;
this.name = name;
this.generateToken = generateToken;
}
static jsonSchema = {
type: "object",
required: ["id", "name", "generateToken"],
properties: {
"id": { type: ["integer", "null"] },
"name": { type: ["string", "null"] },
"generateToken": { type: "boolean" },
},
};
static fromJSON(json) {
return new this(json.id, json.name, json.generateToken);
}
static Response = RawConfig;
}
/* @memberof module:lib/data */
class LogSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.log.follow";
/** @type {boolean} */
all;
/** @type {boolean} */
controller;
/** @type {array} */
hostIds;
/** @type {array} */
instanceIds;
/** @type {?string} */
maxLevel;
constructor(all, controller, hostIds, instanceIds, maxLevel) {
this.all = all;
this.controller = controller;
this.hostIds = hostIds;
this.instanceIds = instanceIds;
this.maxLevel = maxLevel;
}
static jsonSchema = {
type: "object",
required: ["all", "controller", "hostIds", "instanceIds", "maxLevel"],
properties: {
all: { type: "boolean" },
controller: { type: "boolean" },
hostIds: {
type: "array",
items: { type: "integer" },
},
instanceIds: {
type: "array",
items: { type: "integer" },
},
maxLevel: { type: ["string", "null"] },
},
};
static fromJSON(json) {
return new this(json.all, json.controller, json.hostIds, json.instanceIds, json.maxLevel);
}
}
/* @memberof module:lib/data */
class LogQueryRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.log.query";
/** @type {boolean} */
all;
/** @type {boolean} */
controller;
/** @type {Array<number>} */
hostIds;
/** @type {Array<number>} */
instanceIds;
/** @type {?string} */
maxLevel;
/** @type {integer} */
limit;
/** @type {undefined} */
order;
constructor(all, controller, hostIds, instanceIds, maxLevel, limit, order) {
this.all = all;
this.controller = controller;
this.hostIds = hostIds;
this.instanceIds = instanceIds;
this.maxLevel = maxLevel;
this.limit = limit;
this.order = order;
}
static jsonSchema = {
type: "object",
required: ["all", "controller", "hostIds", "instanceIds", "maxLevel", "limit", "order"],
properties: {
all: { type: "boolean" },
controller: { type: "boolean" },
hostIds: {
type: "array",
items: { type: "integer" },
},
instanceIds: {
type: "array",
items: { type: "integer" },
},
maxLevel: { type: ["string", "null"] },
limit: { type: "integer" },
order: {
enum: ["asc", "desc"],
},
},
};
static fromJSON(json) {
return new this(
json.all, json.controller, json.hostIds, json.instanceIds, json.maxLevel, json.limit, json.order
);
}
}
LogQueryRequest.Response = class Response {
/** @type {Array<object>} */
log;
constructor(log) {
this.log = log;
}
static jsonSchema = {
type: "object",
required: ["log"],
properties: {
log: {
type: "array",
items: { type: "object" },
},
},
};
static fromJSON(json) {
return new this(json.log);
}
};
/** @memberof module:lib/data */
class LogMessageEvent {
static type = "event";
static src = "host";
static dst = "controller";
/** @type {object} */
info;
constructor(info) {
this.info = info;
}
static jsonSchema = {
type: "object",
required: ["info"],
properties: {
"info": {
type: "object",
required: ["level", "message"],
properties: {
"level": { type: "string" },
"message": { type: "string" },
},
},
},
};
static fromJSON(json) {
return new this(json.info);
}
}
/* @memberof module:lib/data */
class DebugDumpWsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.debug.dump_ws";
}
/* @memberof module:lib/data */
class DebugWsMessageEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {string} */
direction;
/** @type {string} */
content;
constructor(direction, content) {
this.direction = direction;
this.content = content;
}
static jsonSchema = {
type: "object",
required: ["direction", "content"],
properties: {
direction: { type: "string" },
content: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.direction, json.content);
}
}
module.exports = {
RawConfig,
ControllerConfigGetRequest,
ControllerConfigSetFieldRequest,
ControllerConfigSetPropRequest,
HostGenerateTokenRequest,
HostConfigCreateRequest,
LogSetSubscriptionsRequest,
LogQueryRequest,
LogMessageEvent,
DebugDumpWsRequest,
DebugWsMessageEvent,
};
+880
View File
@@ -0,0 +1,880 @@
"use strict";
const libSchema = require("../schema");
/** @memberof module:lib/data */
class Address {
/** Controller address */
static controller = 0;
/** Instance address */
static instance = 1;
/** Host address */
static host = 2;
/** Control address */
static control = 3;
/** Broadcast */
static broadcast = 4;
/** @type {number} */
type;
/** @type {string} */
id;
/** @type {string|undefined} */
requestId;
constructor(type, id, requestId) {
if (typeof type !== "number") {
throw Error(`Invalid type ${type}`);
}
this.type = type;
this.id = id;
this.requestId = requestId;
}
/**
* Convert from convenient shorthand notation to address.
*
* Supported notations and their corresponding address:
* - `"controller"`: new Address(Address.controller, 0)
* - `{ hostId: id }`: new Address(Address.host, id)
* - `{ instanceId: id }`: new Address(Address.instance, id)
* - `{ controlId: id }`: new Address(Address.control, id)
* `"allHosts"`: new Address(Address.broadcast, Address.host)
* `"allInstances"`: new Address(Address.broadcast, Address.instance)
* `"allControls"`: new Address(Address.broadcast, Address.control)
* @param {module:lib/data.Address|string|object} shorthand -
* Shorthand to translate with.
* @returns {module:lib/data.Address} Translated address.
*/
static fromShorthand(shorthand) {
if (shorthand instanceof Address) { return shorthand; }
if (shorthand === "controller") { return new Address(Address.controller, 0); }
if (shorthand === "allHosts") { return new Address(Address.broadcast, Address.host); }
if (shorthand === "allInstances") { return new Address(Address.broadcast, Address.instance); }
if (shorthand === "allControls") { return new Address(Address.broadcast, Address.control); }
let entries = Object.entries(shorthand);
if (entries.length === 1) {
let [name, value] = entries[0];
if (name === "hostId") { return new Address(Address.host, value); }
if (name === "instanceId") { return new Address(Address.instance, value); }
if (name === "controlId") { return new Address(Address.control, value); }
}
throw Error("Unrecognized shorthand");
}
static jsonSchema = {
type: "array",
minItems: 2,
maxItems: 3,
items: [
{ type: "integer", minimum: 0, maximum: 4 },
{ type: "integer" },
{ type: "integer" },
],
};
static fromJSON(json) {
return new this(json[0], json[1], json[2]);
}
toJSON() {
if (this.requestId !== undefined) {
return [this.type, this.id, this.requestId];
}
return [this.type, this.id];
}
toString() {
const typeMap = ["controller", "instance", "host", "control"];
const type = typeMap[this.type] || this.type;
if (this.type === Address.broadcast) {
return `[Address ${type}:${typeMap[this.id] || this.id}]`;
}
if (this.requestId === undefined) {
return `[Address ${type}:${this.id}]`;
}
return `[Address ${type}:${this.id}:${this.requestId}]`;
}
/**
* Returns true if this address targets the given destination
* @param {module:lib/Data.Address} dst - Destination to check
* @returns {boolean} true if this address is addressed to the given destination
*/
addressedTo(dst) {
if (this.type !== Address.broadcast) {
return (
this.type === dst.type
&& this.id === dst.id
);
}
return dst.type !== Address.broadcast && this.id === dst.type;
}
equals(other) {
return (
this.type === other.type
&& this.id === other.id
&& this.requestId === other.requestId
);
}
}
/** @memberof module:lib/data */
class Message {
/** @type {string} */
type;
constructor(type) {
this.type = type;
}
static jsonSchema;
static validate;
static fromJSON(json) {
/* eslint-disable no-use-before-define */
if (json.type === "hello") { return MessageHello.fromJSON(json); }
if (json.type === "registerHost") { return MessageRegisterHost.fromJSON(json); }
if (json.type === "registerControl") { return MessageRegisterControl.fromJSON(json); }
if (json.type === "ready") { return MessageReady.fromJSON(json); }
if (json.type === "resume") { return MessageResume.fromJSON(json); }
if (json.type === "continue") { return MessageContinue.fromJSON(json); }
if (json.type === "invalidate") { return MessageInvalidate.fromJSON(json); }
if (json.type === "heartbeat") { return MessageHeartbeat.fromJSON(json); }
if (json.type === "request") { return MessageRequest.fromJSON(json); }
if (json.type === "response") { return MessageResponse.fromJSON(json); }
if (json.type === "responseError") { return MessageResponseError.fromJSON(json); }
if (json.type === "event") { return MessageEvent.fromJSON(json); }
if (json.type === "disconnect") { return MessageDisconnect.fromJSON(json); }
/* eslint-enable no-use-before-define */
throw new Error(`Unrecognized message type ${json.type}`);
}
}
/** @memberof module:lib/data */
class HelloData {
/** @type {string} */
version;
/** @type {object} */
plugins;
constructor(version, plugins) {
this.version = version;
this.plugins = plugins;
}
static jsonSchema = {
required: ["version", "plugins"],
properties: {
"version": { type: "string" },
"plugins": {
type: "object",
additionalProperties: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.version, json.plugins);
}
}
/** @memberof module:lib/data */
class MessageHello extends Message {
/** @type {module:lib/data.HelloData} */
data;
constructor(data) {
super("hello");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "data"],
properties: {
"type": { const: "hello" },
"data": HelloData.jsonSchema,
},
};
static fromJSON(json) {
return new this(HelloData.fromJSON(json.data));
}
};
/** @memberof module:lib/data */
class RegisterHostData {
/** @type {string} */
token;
/** @type {string} */
agent;
/** @type {string} */
version;
/** @type {string} */
name;
/** @type {string} */
id;
/** @type {string|undefined} */
publicAddress;
/** @type {Object<string, string>} */
plugins;
constructor(token, agent, version, name, id, publicAddress, plugins) {
this.token = token;
this.agent = agent;
this.version = version;
this.name = name;
this.id = id;
this.publicAddress = publicAddress;
this.plugins = plugins;
}
static jsonSchema = {
type: "object",
required: ["token", "agent", "version", "name", "id", "plugins"],
properties: {
"token": { type: "string" },
"agent": { type: "string" },
"version": { type: "string" },
"name": { type: "string" },
"id": { type: "integer" },
"publicAddress": { type: "string" },
"plugins": {
type: "object",
additionalProperties: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.token, json.agent, json.version, json.name, json.id, json.publicAddress, json.plugins);
}
}
/** @memberof module:lib/data */
class MessageRegisterHost extends Message {
/** @type {module:lib/data.RegisterHostData} */
data;
constructor(data) {
super("registerHost");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "data"],
properties: {
"type": { const: "registerHost" },
"data": RegisterHostData.jsonSchema,
},
};
static fromJSON(json) {
return new this(RegisterHostData.fromJSON(json.data));
}
};
/** @memberof module:lib/data */
class RegisterControlData {
/** @type {string} */
token;
/** @type {string} */
agent;
/** @type {string} */
version;
constructor(token, agent, version) {
this.token = token;
this.agent = agent;
this.version = version;
}
static jsonSchema = {
type: "object",
required: ["token", "agent", "version"],
properties: {
"token": { type: "string" },
"agent": { type: "string" },
"version": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.token, json.agent, json.version);
}
}
/** @memberof module:lib/data */
class MessageRegisterControl extends Message {
/** @type {module:lib/data.RegisterControlData} */
data;
constructor(data) {
super("registerControl");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["data"],
properties: {
"type": { const: "registerControl" },
"data": RegisterControlData.jsonSchema,
},
};
static fromJSON(json) {
return new this(RegisterControlData.fromJSON(json.data));
}
};
/** @memberof module:lib/data */
class AccountDetails {
/** @type {string} */
name;
/** @type {Array} */
roles;
constructor(name, roles) {
this.name = name;
this.roles = roles;
}
static jsonSchema = {
additionalProperties: false,
required: ["name", "roles"],
properties: {
"name": { type: "string" },
"roles": {
type: "array",
items: {
additionalProperties: false,
type: "object",
required: ["name", "id", "permissions"],
properties: {
"name": { type: "string" },
"id": { type: "integer" },
"permissions": {
type: "array",
items: { type: "string" },
},
},
},
},
},
};
static fromJSON(json) {
return new this(json.name, json.roles);
}
}
/** @memberof module:lib/data */
class ReadyData {
/** @type {module:lib/data.Address} */
src;
/** @type {string} */
sessionToken;
/** @type {number} */
sessionTimeout;
/** @type {number} */
heartbeatInterval;
/** @type {AccountDetails|undefined} */
account;
constructor(src, sessionToken, sessionTimeout, heartbeatInterval, account) {
this.src = src;
this.sessionToken = sessionToken;
this.sessionTimeout = sessionTimeout;
this.heartbeatInterval = heartbeatInterval;
if (account) { this.account = account; }
}
static jsonSchema = {
additionalProperties: false,
required: ["src", "sessionToken", "sessionTimeout", "heartbeatInterval"],
properties: {
"src": Address.jsonSchema,
"sessionToken": { type: "string" },
"sessionTimeout": { type: "number" },
"heartbeatInterval": { type: "number" },
"account": AccountDetails.jsonSchema,
},
};
static fromJSON(json) {
let account;
if (json.account) { account = AccountDetails.fromJSON(json.account); }
return new this(
Address.fromJSON(json.src),
json.sessionToken,
json.sessionTimeout,
json.heartbeatInterval,
account
);
}
}
/** @memberof module:lib/data */
class MessageReady extends Message {
/** @type {module:lib/data.ReadyData} */
data;
constructor(data) {
super("ready");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["data"],
properties: {
"type": { const: "ready" },
"data": ReadyData.jsonSchema,
},
};
static fromJSON(json) {
return new this(ReadyData.fromJSON(json.data));
}
}
/** @memberof module:lib/data */
class ResumeData {
/** @type {string} */
sessionToken;
/** @type {integer|undefined} */
lastSeq;
constructor(sessionToken, lastSeq) {
this.sessionToken = sessionToken;
if (lastSeq !== undefined) { this.lastSeq = lastSeq; }
}
static jsonSchema = {
type: "object",
required: ["sessionToken"],
properties: {
"sessionToken": { type: "string" },
"lastSeq": { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.sessionToken, json.lastSeq);
}
}
/** @memberof module:lib/data */
class MessageResume extends Message {
/** @type {module:lib/data.ResumeData} */
data;
constructor(data) {
super("resume");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["data"],
properties: {
"type": { const: "resume" },
"data": ResumeData.jsonSchema,
},
};
static fromJSON(json) {
return new this(ResumeData.fromJSON(json.data));
}
}
/** @memberof module:lib/data */
class ContinueData {
/** @type {number} */
sessionTimeout;
/** @type {number} */
heartbeatInterval;
/** @type {integer|undefined} */
lastSeq;
constructor(sessionTimeout, heartbeatInterval, lastSeq) {
this.sessionTimeout = sessionTimeout;
this.heartbeatInterval = heartbeatInterval;
if (lastSeq !== undefined) { this.lastSeq = lastSeq; }
}
static jsonSchema = {
required: ["sessionTimeout", "heartbeatInterval"],
properties: {
"sessionTimeout": { type: "number" },
"heartbeatInterval": { type: "number" },
"lastSeq": { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.sessionTimeout, json.heartbeatInterval, json.lastSeq);
}
}
/** @memberof module:lib/data */
class MessageContinue extends Message {
/** @type {module:lib/data.ContinueData} */
data;
constructor(data) {
super("continue");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["data"],
properties: {
"type": { const: "continue" },
"data": ContinueData.jsonSchema,
},
};
static fromJSON(json) {
return new this(ContinueData.fromJSON(json.data));
}
}
/** @memberof module:lib/data */
class MessageInvalidate extends Message {
constructor() {
super("invalidate");
}
static jsonSchema = {
type: "object",
properties: {
"type": { const: "invalidate" },
},
};
static fromJSON(json) {
return new this();
}
}
/** @memberof module:lib/data */
class MessageHeartbeat extends Message {
/** @type {integer|undefined} */
seq;
constructor(seq) {
super("heartbeat");
this.seq = seq;
}
static jsonSchema = {
type: "object",
required: ["type"],
properties: {
"type": { const: "heartbeat" },
"seq": { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.seq);
}
}
/** @memberof module:lib/data */
class MessageRequest extends Message {
/** @type {number} */
seq;
/** @type {Address} */
src;
/** @type {Address} */
dst;
/** @type {string} */
name;
/** @type {*} */
data;
constructor(seq, src, dst, name, data) {
super("request");
this.seq = seq;
this.src = src;
this.dst = dst;
this.name = name;
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "seq", "src", "dst", "name"],
properties: {
"type": { const: "request" },
"seq": { type: "integer" },
"src": Address.jsonSchema,
"dst": Address.jsonSchema,
"name": { type: "string" },
"data": {},
},
};
static fromJSON(json) {
return new this(
json.seq,
Address.fromJSON(json.src),
Address.fromJSON(json.dst),
json.name,
json.data,
);
}
};
/** @memberof module:lib/data */
class MessageResponse extends Message {
/** @type {number} */
seq;
/** @type {Address} */
src;
/** @type {Address} */
dst;
/** @type {*} */
data;
constructor(seq, src, dst, data) {
super("response");
this.seq = seq;
this.src = src;
this.dst = dst;
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "seq", "src", "dst"],
properties: {
"type": { const: "response" },
"seq": { type: "integer" },
"src": Address.jsonSchema,
"dst": Address.jsonSchema,
"data": {},
},
};
static fromJSON(json) {
return new this(
json.seq,
Address.fromJSON(json.src),
Address.fromJSON(json.dst),
json.data,
);
}
};
/** @memberof module:lib/data */
class ResponseError {
/** @type {string} */
message;
/** @type {string|undefined} */
code;
/** @type {string|undefined} */
stack;
constructor(message, code, stack) {
this.message = message;
if (code) { this.code = code; }
if (stack) { this.stack = stack; }
}
static jsonSchema = {
required: ["message"],
properties: {
"message": { type: "string" },
"code": { type: "string" },
"stack": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.message, json.code, json.stack);
}
}
/** @memberof module:lib/data */
class MessageResponseError extends Message {
/** @type {number} */
seq;
/** @type {Address} */
src;
/** @type {Address} */
dst;
/** @type {module:lib/data.ResponseError} */
data;
constructor(seq, src, dst, data) {
super("responseError");
this.seq = seq;
this.src = src;
this.dst = dst;
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "seq", "src", "dst", "data"],
properties: {
"type": { const: "responseError" },
"seq": { type: "integer" },
"src": Address.jsonSchema,
"dst": Address.jsonSchema,
"data": ResponseError.jsonSchema,
},
};
static fromJSON(json) {
return new this(
json.seq,
Address.fromJSON(json.src),
Address.fromJSON(json.dst),
ResponseError.fromJSON(json.data),
);
}
};
/** @memberof module:lib/data */
class MessageEvent extends Message {
/** @type {number} */
seq;
/** @type {Address} */
src;
/** @type {Address} */
dst;
/** @type {string} */
name;
/** @type {*} */
data;
constructor(seq, src, dst, name, data) {
super("event");
this.seq = seq;
this.src = src;
this.dst = dst;
this.name = name;
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "seq", "src", "dst", "name"],
properties: {
"type": { const: "event" },
"seq": { type: "integer" },
"src": Address.jsonSchema,
"dst": Address.jsonSchema,
"name": { type: "string" },
"data": {},
},
};
static fromJSON(json) {
return new this(
json.seq,
Address.fromJSON(json.src),
Address.fromJSON(json.dst),
json.name,
json.data,
);
}
};
/** @memberof module:lib/data */
class MessageDisconnect extends Message {
/** @type {string} */
data;
constructor(stage) {
super("disconnect");
this.data = stage;
}
static jsonSchema = {
type: "object",
required: ["type"],
properties: {
"type": { const: "disconnect" },
"data": { enum: ["prepare", "ready"] },
},
};
static fromJSON(json) {
return new this(json.data);
}
};
Message.jsonSchema = {
type: "object",
required: ["type"],
properties: {
"type": { enum: [
"hello", "registerHost", "registerControl", "ready", "resume", "continue", "invalidate",
"heartbeat", "request", "response", "responseError", "event", "disconnect",
] },
},
oneOf: [
MessageHello.jsonSchema,
MessageRegisterHost.jsonSchema,
MessageRegisterControl.jsonSchema,
MessageReady.jsonSchema,
MessageResume.jsonSchema,
MessageContinue.jsonSchema,
MessageInvalidate.jsonSchema,
MessageHeartbeat.jsonSchema,
MessageRequest.jsonSchema,
MessageResponse.jsonSchema,
MessageResponseError.jsonSchema,
MessageEvent.jsonSchema,
MessageDisconnect.jsonSchema,
],
};
Message.validate = libSchema.compile(Message.jsonSchema);
/** @memberof module:lib/data */
class PingRequest {
static type = "request";
static src = ["controller", "host", "control"];
static dest = ["controller", "host", "control"];
static permission = null;
}
module.exports = {
Message,
HelloData,
MessageHello,
RegisterHostData,
MessageRegisterHost,
RegisterControlData,
MessageRegisterControl,
AccountDetails,
ReadyData,
MessageReady,
ResumeData,
MessageResume,
ContinueData,
MessageContinue,
MessageInvalidate,
MessageHeartbeat,
Address,
MessageRequest,
MessageResponse,
ResponseError,
MessageResponseError,
MessageEvent,
MessageDisconnect,
PingRequest,
};
+240
View File
@@ -0,0 +1,240 @@
"use strict";
const { jsonArray } = require("./composites");
/** @memberof module:lib/data */
class HostDetails {
/** @type {string} */
agent;
/** @type {string} */
version;
/** @type {string} */
name;
/** @type {number} */
id;
/** @type {boolean} */
connected;
/** @type {string|undefined} */
publicAddress;
constructor(agent, version, name, id, connected, publicAddress) {
this.agent = agent;
this.version = version;
this.name = name;
this.id = id;
this.connected = connected;
if (publicAddress !== undefined) { this.publicAddress = publicAddress; }
}
static jsonSchema = {
required: ["agent", "version", "name", "id", "connected"],
properties: {
"agent": { type: "string" },
"version": { type: "string" },
"name": { type: "string" },
"id": { type: "integer" },
"connected": { type: "boolean" },
"publicAddress": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.agent, json.version, json.name, json.id, json.connected, json.publicAddress);
}
}
/** @memberof module:lib/data */
class HostListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.host.list";
static Response = jsonArray(HostDetails);
}
/* @memberof module:lib/data */
class HostSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.host.subscribe";
/** @type {boolean} */
all;
/** @type {Array<number>} */
hostIds;
constructor(all, hostIds) {
this.all = all;
this.hostIds = hostIds;
}
static jsonSchema = {
type: "object",
required: ["all", "hostIds"],
properties: {
all: { type: "boolean" },
hostIds: {
type: "array",
items: { type: "integer" },
},
},
};
static fromJSON(json) {
return new this(json.all, json.hostIds);
}
}
/* @memberof module:lib/data */
class HostUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {module:lib/data.HostDetails} */
update;
constructor(update) {
this.update = update;
}
static jsonSchema = {
type: "object",
required: ["update"],
properties: {
update: HostDetails.jsonSchema,
},
};
static fromJSON(json) {
return new this(HostDetails.fromJSON(json.update));
}
}
/** @memberof module:lib/data */
class HostMetricsRequest {
static type = "request";
static src = "controller";
static dst = "host";
}
HostMetricsRequest.Response = class Response { // TODO: Use JSON class pattern in Prometheus
/** @type {array} */
results;
constructor(results) {
this.results = results;
}
static jsonSchema = {
type: "object",
required: ["results"],
properties: {
"results": {
type: "array",
},
},
};
static fromJSON(json) {
return new this(json.results);
}
};
/** @memberof module:lib/data */
class ControllerConnectionEvent {
static type = "event";
static src = "host";
static dst = "instance";
/** @type {string} */
event;
constructor(event) {
this.event = event;
}
static jsonSchema = {
required: ["event"],
properties: {
"event": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.event);
}
}
/* @memberof module:lib/data */
class PrepareControllerDisconnectRequest {
static type = "request";
static src = "host";
static dst = "instance";
}
/** @memberof module:lib/data */
class SyncUserListsEvent {
static type = "event";
static src = "controller";
static dst = "host";
/** @type {Set<string>} */
adminlist;
/** @type {Map<string, string>} */
banlist;
/** @type {Set<string>} */
whitelist;
constructor(adminlist, banlist, whitelist) {
this.adminlist = adminlist;
this.banlist = banlist;
this.whitelist = whitelist;
}
static jsonSchema = {
required: ["adminlist", "banlist", "whitelist"],
properties: {
"adminlist": {
type: "array",
items: { type: "string" },
},
"banlist": {
type: "array",
items: {
type: "array",
additionalItems: false,
items: [{ type: "string" }, { type: "string" }],
},
},
"whitelist": {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(new Set(json.adminlist), new Set(json.banlist), new Set(json.whitelist));
}
static toJSON() {
return {
adminlist: [...this.adminlist],
banlist: [...this.banlist],
whitelist: [...this.whitelist],
};
}
}
module.exports = {
HostDetails,
HostListRequest,
HostSetSubscriptionsRequest,
HostUpdateEvent,
HostMetricsRequest,
ControllerConnectionEvent,
PrepareControllerDisconnectRequest,
SyncUserListsEvent,
};
File diff suppressed because it is too large. Load diff
+474
View File
@@ -0,0 +1,474 @@
"use strict";
const ModPack = require("./ModPack");
const ModInfo = require("./ModInfo");
const { jsonArray, JsonString } = require("./composites");
/* @memberof module:lib/data */
class ModPackGetRequest {
static type = "request";
static src = ["instance", "control"];
static dst = "controller";
static permission = "core.mod_pack.get";
/** @type {number} */
id;
constructor(id) {
this.id = id;
}
static jsonSchema = {
type: "object",
required: ["id"],
properties: {
id: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.id);
}
static Response = ModPack;
}
/* @memberof module:lib/data */
class ModPackGetDefaultRequest {
static type = "request";
static src = ["instance", "control"];
static dst = "controller";
static permission = "core.mod_pack.get";
static Response = ModPack;
}
/* @memberof module:lib/data */
class ModPackListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.list";
static Response = jsonArray(ModPack);
}
/** @memberof module:lib/data */
class ModPackCreateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.create";
/** @type {module:lib/data.ModPack} */
modPack;
constructor(modPack) {
this.modPack = modPack;
}
static jsonSchema = {
type: "object",
required: ["modPack"],
properties: {
"modPack": ModPack.jsonSchema,
},
};
static fromJSON(json) {
return new this(ModPack.fromJSON(json.modPack));
}
}
/* @memberof module:lib/data */
class ModPackUpdateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.update";
/** @type {module:lib/data.ModPack} */
modPack;
constructor(modPack) {
this.modPack = modPack;
}
static jsonSchema = {
type: "object",
required: ["modPack"],
properties: {
"modPack": ModPack.jsonSchema,
},
};
static fromJSON(json) {
return new this(ModPack.fromJSON(json.modPack));
}
}
/* @memberof module:lib/data */
class ModPackDeleteRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.delete";
/** @type {number} */
id;
constructor(id) {
this.id = id;
}
static jsonSchema = {
type: "object",
required: ["id"],
properties: {
id: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.id);
}
}
/* @memberof module:lib/data */
class ModPackSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.subscribe";
/** @type {boolean} */
all;
/** @type {Array<number>} */
modPackIds;
constructor(all, modPackIds) {
this.all = all;
this.modPackIds = modPackIds;
}
static jsonSchema = {
type: "object",
required: ["all", "modPackIds"],
properties: {
all: { type: "boolean" },
modPackIds: {
type: "array",
items: { type: "integer" },
},
},
};
static fromJSON(json) {
return new this(json.all, json.modPackIds);
}
}
/* @memberof module:lib/data */
class ModGetRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.get";
/** @type {string} */
name;
/** @type {string} */
version;
constructor(name, version) {
this.name = name;
this.version = version;
}
static jsonSchema = {
type: "object",
required: ["name", "version"],
properties: {
name: { type: "string" },
version: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.version);
}
static Response = ModInfo;
}
/* @memberof module:lib/data */
class ModListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.list";
static Response = jsonArray(ModInfo);
}
/* @memberof module:lib/data */
class ModSearchRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.search";
/** @type {string} */
query;
/** @type {string} */
factorioVersion;
/** @type {number} */
page;
/** @type {number|undefined} */
pageSize;
/** @type {string|undefined} */
sort;
/** @type {string|undefined} */
sortOrder;
constructor(query, factorioVersion, page, pageSize, sort, sortOrder) {
this.query = query;
this.factorioVersion = factorioVersion;
this.page = page;
if (pageSize) { this.pageSize = pageSize; }
if (sort) { this.sort = sort; }
if (sortOrder) { this.sortOrder = sortOrder; }
}
static jsonSchema = {
type: "object",
required: ["query", "factorioVersion", "page"],
properties: {
query: { type: "string" },
factorioVersion: { type: "string" },
pageSize: { type: "integer" },
page: { type: "integer" },
sort: { type: "string" },
sortOrder: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.query, json.factorioVersion, json.page, json.pageSize, json.sort, json.sortOrder);
}
}
ModSearchRequest.Response = class Response {
/** @type {Array<string>} */
queryIssues;
/** @type {number} */
pageCount;
/** @type {number} */
resultCount;
/** @type {Array<object>} */
results;
constructor(queryIssues, pageCount, resultCount, results) {
this.queryIssues = queryIssues;
this.pageCount = pageCount;
this.resultCount = resultCount;
this.results = results;
}
static jsonSchema = {
type: "object",
required: ["queryIssues", "pageCount", "resultCount", "results"],
properties: {
queryIssues: {
type: "array",
items: { type: "string" },
},
pageCount: { type: "integer" },
resultCount: { type: "integer" },
results: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
versions: {
type: "array",
items: ModInfo.jsonSchema,
},
},
},
},
},
};
static fromJSON(json) {
let results = json.results.map(
({ name, versions }) => ({ name, versions: versions.map(mod => ModInfo.fromJSON(mod)) })
);
return new this(json.queryIssues, json.pageCount, json.resultCount, results);
}
};
/* @memberof module:lib/data */
class ModSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.subscribe";
/** @type {boolean} */
all;
/** @type {Array<string>} */
modNames;
constructor(all, modNames) {
this.all = all;
this.modNames = modNames;
}
static jsonSchema = {
type: "object",
required: ["all", "modNames"],
properties: {
all: { type: "boolean" },
modNames: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.all, json.modNames);
}
}
/* @memberof module:lib/data */
class ModDownloadRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.download";
/** @type {string} */
name;
/** @type {string} */
version;
constructor(name, version) {
this.name = name;
this.version = version;
}
static jsonSchema = {
type: "object",
required: ["name", "version"],
properties: {
name: { type: "string" },
version: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.version);
}
static Response = JsonString;
}
/* @memberof module:lib/data */
class ModDeleteRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.delete";
/** @type {string} */
name;
/** @type {string} */
version;
constructor(name, version) {
this.name = name;
this.version = version;
}
static jsonSchema = {
type: "object",
required: ["name", "version"],
properties: {
name: { type: "string" },
version: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.version);
}
}
/* @memberof module:lib/data */
class ModPackUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {module:lib/data.ModPack} */
modPack;
constructor(modPack) {
this.modPack = modPack;
}
static jsonSchema = {
type: "object",
required: ["modPack"],
properties: {
modPack: ModPack.jsonSchema,
},
};
static fromJSON(json) {
return new this(ModPack.fromJSON(json.modPack));
}
}
/* @memberof module:lib/data */
class ModUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {module:lib/data.ModInfo} */
mod;
constructor(mod) {
this.mod = mod;
}
static jsonSchema = {
type: "object",
required: ["mod"],
properties: {
mod: ModInfo.jsonSchema,
},
};
static fromJSON(json) {
return new this(ModInfo.fromJSON(json.mod));
}
}
module.exports = {
ModPackGetRequest,
ModPackGetDefaultRequest,
ModPackListRequest,
ModPackCreateRequest,
ModPackUpdateRequest,
ModPackDeleteRequest,
ModPackSetSubscriptionsRequest,
ModGetRequest,
ModListRequest,
ModSearchRequest,
ModSetSubscriptionsRequest,
ModDownloadRequest,
ModDeleteRequest,
ModPackUpdateEvent,
ModUpdateEvent,
};
+688
View File
@@ -0,0 +1,688 @@
"use strict";
const PlayerStats = require("../PlayerStats");
const { jsonArray, JsonNumber } = require("./composites");
/* @memberof module:lib/data */
class RawPermission { // TODO refactor into lib/user.Permission
/** @type {string} */
name;
/** @type {string} */
title;
/** @type {string} */
description;
constructor(name, title, description) {
this.name = name;
this.title = title;
this.description = description;
}
static jsonSchema = {
required: ["name", "title", "description"],
properties: {
name: { type: "string" },
title: { type: "string" },
description: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.title, json.description);
}
}
/* @memberof module:lib/data */
class PermissionListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.permission.list";
static Response = jsonArray(RawPermission);
}
class RawRole { // TODO refactor into lib/user.Role
/** @type {number} */
id;
/** @type {string} */
name;
/** @type {string} */
description;
/** @type {Array<string>} */
permissions;
constructor(id, name, description, permissions) {
this.id = id;
this.name = name;
this.description = description;
this.permissions = permissions;
}
static jsonSchema = {
type: "object",
required: ["id", "name", "description", "permissions"],
properties: {
id: { type: "integer" },
name: { type: "string" },
description: { type: "string" },
permissions: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.id, json.name, json.description, json.permissions);
}
}
/* @memberof module:lib/data */
class RoleListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.list";
static Response = jsonArray(RawRole);
}
/* @memberof module:lib/data */
class RoleCreateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.create";
/** @type {string} */
name;
/** @type {string} */
description;
/** @type {Array<string>} */
permissions;
constructor(name, description, permissions) {
this.name = name;
this.description = description;
this.permissions = permissions;
}
static jsonSchema = {
type: "object",
required: ["name", "description", "permissions"],
properties: {
name: { type: "string" },
description: { type: "string" },
permissions: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.name, json.description, json.permissions);
}
static Response = JsonNumber;
}
/* @memberof module:lib/data */
class RoleUpdateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.update";
/** @type {number} */
id;
/** @type {string} */
name;
/** @type {string} */
description;
/** @type {Array<string>} */
permissions;
constructor(id, name, description, permissions) {
this.id = id;
this.name = name;
this.description = description;
this.permissions = permissions;
}
static jsonSchema = {
type: "object",
required: ["id", "name", "description", "permissions"],
properties: {
id: { type: "integer" },
name: { type: "string" },
description: { type: "string" },
permissions: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.id, json.name, json.description, json.permissions);
}
}
/* @memberof module:lib/data */
class RoleGrantDefaultPermissionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.update";
/** @type {number} */
id;
constructor(id) {
this.id = id;
}
static jsonSchema = {
type: "object",
required: ["id"],
properties: {
id: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.id);
}
}
/* @memberof module:lib/data */
class RoleDeleteRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.delete";
/** @type {number} */
id;
constructor(id) {
this.id = id;
}
static jsonSchema = {
type: "object",
required: ["id"],
properties: {
id: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.id);
}
}
/* @memberof module:lib/data */
class RawUser { // TODO refactor into lib/user.User
/** @type {string} */
name;
/** @type {Array<number>} */
roles;
/** @type {Array<number>} */
instances;
/** @type {boolean|undefined} */
isAdmin;
/** @type {boolean|undefined} */
isBanned;
/** @type {boolean|undefined} */
isWhitelisted;
/** @type {string|undefined} */
banReason;
/** @type {boolean|undefined} */
isDeleted;
/** @type {module:lib/PlayerStats} */
playerStats;
/** @type {Map<number, module:lib/PlayerStats>|undefined} */
instanceStats;
constructor(
name, roles, instances, isAdmin, isBanned, isWhitelisted, banReason,
isDeleted, playerStats, instanceStats
) {
this.name = name;
this.roles = roles;
this.instances = instances;
if (isAdmin !== undefined) { this.isAdmin = isAdmin; }
if (isBanned !== undefined) { this.isBanned = isBanned; }
if (isWhitelisted !== undefined) { this.isWhitelisted = isWhitelisted; }
if (banReason !== undefined) { this.banReason = banReason; }
if (isDeleted !== undefined) { this.isDeleted = isDeleted; }
if (playerStats !== undefined) { this.playerStats = playerStats; }
if (instanceStats !== undefined) { this.instanceStats = instanceStats; }
}
static jsonSchema = {
type: "object",
required: ["name", "roles", "instances"],
properties: {
name: { type: "string" },
roles: { type: "array", items: { type: "integer" } },
isAdmin: { type: "boolean" },
isBanned: { type: "boolean" },
isWhitelisted: { type: "boolean" },
banReason: { type: "string" },
instances: { type: "array", items: { type: "integer" } },
isDeleted: { type: "boolean" },
playerStats: PlayerStats.jsonSchema,
instanceStats: {
type: "array",
items: {
type: "array",
items: [{ type: "integer" }, PlayerStats.jsonSchema],
},
},
},
};
static fromJSON(json) {
let playerStats;
if (json.playerStats) {
playerStats = PlayerStats.fromJSON(json.playerStats);
}
let instanceStats;
if (json.instanceStats) {
instanceStats = new Map(
json.instanceStats.map(([id, stats]) => [id, PlayerStats.fromJSON(stats)])
);
}
return new this(
json.name, json.roles, json.instances, json.isAdmin, json.isBanned, json.isWhitelisted, json.banReason,
json.isDeleted, playerStats, instanceStats
);
}
}
/* @memberof module:lib/data */
class UserGetRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.get";
/** @type {string} */
name;
constructor(name) {
this.name = name;
}
static jsonSchema = {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name);
}
static Response = RawUser;
}
/* @memberof module:lib/data */
class UserListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.list";
static Response = jsonArray(RawUser);
}
/* @memberof module:lib/data */
class UserSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.subscribe";
/** @type {boolean} */
all;
/** @type {Array<string>} */
names;
constructor(all, names) {
this.all = all;
this.names = names;
}
static jsonSchema = {
type: "object",
required: ["all", "names"],
properties: {
all: { type: "boolean" },
names: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.all, json.names);
}
}
/* @memberof module:lib/data */
class UserCreateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.create";
/** @type {string} */
name;
constructor(name) {
this.name = name;
}
static jsonSchema = {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name);
}
}
/* @memberof module:lib/data */
class UserRevokeTokenRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.revoke_token";
/** @type {string} */
name;
constructor(name) {
this.name = name;
}
static jsonSchema = {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name);
}
}
/* @memberof module:lib/data */
class UserUpdateRolesRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.update_roles";
/** @type {string} */
name;
/** @type {Array<number>} */
roles;
constructor(name, roles) {
this.name = name;
this.roles = roles;
}
static jsonSchema = {
type: "object",
required: ["name", "roles"],
properties: {
name: { type: "string" },
roles: {
type: "array",
items: { type: "integer" },
},
},
};
static fromJSON(json) {
return new this(json.name, json.roles);
}
}
/* @memberof module:lib/data */
class UserSetAdminRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.set_admin";
/** @type {string} */
name;
/** @type {boolean} */
create;
/** @type {boolean} */
admin;
constructor(name, create, admin) {
this.name = name;
this.create = create;
this.admin = admin;
}
static jsonSchema = {
type: "object",
required: ["name", "create", "admin"],
properties: {
name: { type: "string" },
create: { type: "boolean" },
admin: { type: "boolean" },
},
};
static fromJSON(json) {
return new this(json.name, json.create, json.admin);
}
}
/* @memberof module:lib/data */
class UserSetWhitelistedRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.set_whitelisted";
/** @type {string} */
name;
/** @type {boolean} */
create;
/** @type {boolean} */
whitelisted;
constructor(name, create, whitelisted) {
this.name = name;
this.create = create;
this.whitelisted = whitelisted;
}
static jsonSchema = {
type: "object",
required: ["name", "create", "whitelisted"],
properties: {
name: { type: "string" },
create: { type: "boolean" },
whitelisted: { type: "boolean" },
},
};
static fromJSON(json) {
return new this(json.name, json.create, json.whitelisted);
}
}
/* @memberof module:lib/data */
class UserSetBannedRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.set_banned";
/** @type {string} */
name;
/** @type {boolean} */
create;
/** @type {boolean} */
banned;
/** @type {string} */
reason;
constructor(name, create, banned, reason) {
this.name = name;
this.create = create;
this.banned = banned;
this.reason = reason;
}
static jsonSchema = {
type: "object",
required: ["name", "create", "banned", "reason"],
properties: {
name: { type: "string" },
create: { type: "boolean" },
banned: { type: "boolean" },
reason: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.create, json.banned, json.reason);
}
}
/* @memberof module:lib/data */
class UserDeleteRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.delete";
/** @type {string} */
name;
constructor(name) {
this.name = name;
}
static jsonSchema = {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name);
}
}
/* @memberof module:lib/data */
class AccountUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {Array<object>|undefined} */
roles;
constructor(roles) {
if (roles) { this.roles = roles; }
}
static jsonSchema = {
type: "object",
properties: {
roles: {
type: "array",
items: {
type: "object",
required: ["name", "id", "permissions"],
properties: {
name: { type: "string" },
id: { type: "integer" },
permissions: {
type: "array",
items: { type: "string" },
},
},
},
},
},
};
static fromJSON(json) {
return new this(json.roles);
}
}
/* @memberof module:lib/data */
class UserUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {module:lib/data.RawUser} */
user;
constructor(user) {
this.user = user;
}
static jsonSchema = {
type: "object",
required: ["user"],
properties: {
user: RawUser.jsonSchema,
},
};
static fromJSON(json) {
return new this(RawUser.fromJSON(json.user));
}
}
module.exports = {
RawPermission,
PermissionListRequest,
RawRole,
RoleListRequest,
RoleCreateRequest,
RoleUpdateRequest,
RoleGrantDefaultPermissionsRequest,
RoleDeleteRequest,
RawUser,
UserGetRequest,
UserListRequest,
UserSetSubscriptionsRequest,
UserCreateRequest,
UserRevokeTokenRequest,
UserUpdateRolesRequest,
UserSetAdminRequest,
UserSetWhitelistedRequest,
UserSetBannedRequest,
UserDeleteRequest,
AccountUpdateEvent,
UserUpdateEvent,
};
+7 -1
View File
@@ -14,7 +14,13 @@ class CommandError extends Error { }
* Thrown from requests sent when an error occured handling it
* @static
*/
class RequestError extends Error { }
class RequestError extends Error {
constructor(message, code, stack) {
super(message);
if (code) { this.code = code; }
if (stack) { this.stack = stack; }
}
}
/**
* Thrown when a permission check fails.
+2 -2
View File
@@ -13,13 +13,13 @@ const crypto = require("crypto"); // needed for getTempFile
* @param {function(string): boolean} filter -
* Optional function to filter out files to ignore. Should return true
* if the file is to be considered.
* @returns {Promise<?string>}
* @returns {Promise<string|undefined>}
* Name of the file with the newest timestamp or null if the
* directory contains no files.
*/
async function getNewestFile(directory, filter = (name) => true) {
let newestTime = new Date(0);
let newestFile = null;
let newestFile;
for (let entry of await fs.readdir(directory, { withFileTypes: true })) {
if (entry.isFile()) {
let stat = await fs.stat(path.join(directory, entry.name));
+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
+8 -8
View File
@@ -85,16 +85,16 @@ class WebConsoleFormat {
/**
* Filter object for logs
* @typedef {Object} module:lib/logging~LogFilter
* @property {string} [max_level] -
* @property {string} [maxLevel] -
* Maximum log level to include. Higher levels are more verbose.
* @property {boolean} [all] -
* Include log entries from controller, all hosts and all instances.
* @property {boolean} [controller] -
* Include log entries from the controller.
* @property {Array<number>} [host_ids] -
* @property {Array<number>} [hostIds] -
* Include log entries for the given hosts and instances of those
* hosts by id.
* @property {Array<number>} [instance_ids] -
* @property {Array<number>} [instanceIds] -
* Include log entries for the given instances by id.
*/
@@ -107,10 +107,10 @@ class WebConsoleFormat {
* filter returning true for log entries that match it.
* @static
*/
function logFilter({ all, controller, host_ids, instance_ids, max_level }) {
function logFilter({ all, controller, hostIds, instanceIds, maxLevel }) {
return info => {
// Note: reversed to filter out undefined levels
if (max_level && !(levels[info.level] <= levels[max_level])) {
if (maxLevel && !(levels[info.level] <= levels[maxLevel])) {
return false;
}
@@ -121,14 +121,14 @@ function logFilter({ all, controller, host_ids, instance_ids, max_level }) {
return true;
}
if (
host_ids
hostIds
&& info.host_id !== undefined
&& info.instance_id === undefined
&& host_ids.includes(info.host_id)
&& hostIds.includes(info.host_id)
) {
return true;
}
if (instance_ids && info.instance_id !== undefined && instance_ids.includes(info.instance_id)) {
if (instanceIds && info.instance_id !== undefined && instanceIds.includes(info.instance_id)) {
return true;
}
return false;
+19 -19
View File
@@ -15,7 +15,7 @@ const Transport = require("winston-transport");
const { LEVEL, MESSAGE } = require("triple-beam");
const chalk = require("chalk");
const libLink = require("./link");
const libData = require("./data");
const libErrors = require("./errors");
const libFileOps = require("./file_ops");
const { levels, logFilter, logger } = require("./logging");
@@ -128,7 +128,7 @@ class LinkTransport extends Transport {
}
try {
libLink.messages.logMessage.send(this.link, { info });
this.link.send(new libData.LogMessageEvent(info));
} catch (err) {
// Ignore session lost errors.
if (!(err instanceof libErrors.SessionLost)) {
@@ -140,7 +140,7 @@ class LinkTransport extends Transport {
}
const logFileGlob = /^[a-z]+-(\d{4}-\d{2}-\d{2})\.log$/;
const logIndexVersion = 1;
const logIndexVersion = 2;
/**
* Keeps an index over a log directory to speed up queries to it
@@ -159,8 +159,8 @@ class LogIndex {
this.index.set(file, {
levels: new Set(serializedEntry.levels),
controller: serializedEntry.controller,
host_ids: new Set(serializedEntry.host_ids),
instance_ids: new Set(serializedEntry.instance_ids),
hostIds: new Set(serializedEntry.hostIds),
instanceIds: new Set(serializedEntry.instanceIds),
});
}
}
@@ -175,8 +175,8 @@ class LogIndex {
serialized.files[file] = {
levels: [...entry.levels],
controller: entry.controller,
host_ids: [...entry.host_ids],
instance_ids: [...entry.instance_ids],
hostIds: [...entry.hostIds],
instanceIds: [...entry.instanceIds],
};
}
@@ -226,8 +226,8 @@ class LogIndex {
let entry = {
levels: new Set(),
controller: false,
host_ids: new Set(),
instance_ids: new Set(),
hostIds: new Set(),
instanceIds: new Set(),
};
for await (let line of lineStream) {
let info;
@@ -244,10 +244,10 @@ class LogIndex {
if (info.host_id === undefined) {
entry.controller = true;
} else if (info.instance_id === undefined) {
entry.host_ids.add(info.host_id);
entry.hostIds.add(info.host_id);
}
if (info.instance_id !== undefined) {
entry.instance_ids.add(info.instance_id);
entry.instanceIds.add(info.instance_id);
}
}
return entry;
@@ -280,18 +280,18 @@ class LogIndex {
* @returns {boolean}
* true if the file may contain entries included by the filter.
*/
filterIncludesFile(file, { max_level, all, controller, instance_ids, host_ids }) {
filterIncludesFile(file, { maxLevel, all, controller, instanceIds, hostIds }) {
let entry = this.index.get(file);
if (!entry) {
return true;
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
if (max_level && hasOwnProperty.call(levels, max_level)) {
if (maxLevel && hasOwnProperty.call(levels, maxLevel)) {
let fileLevels = [...entry.levels].map(
fileLevel => (hasOwnProperty.call(levels, fileLevel) ? levels[fileLevel] : levels.verbose)
);
if (fileLevels.every(level => level > levels[max_level])) {
if (fileLevels.every(level => level > levels[maxLevel])) {
return false;
}
}
@@ -302,10 +302,10 @@ class LogIndex {
if (controller && entry.controller) {
return true;
}
if (host_ids && host_ids.some(id => entry.host_ids.has(id))) {
if (hostIds && hostIds.some(id => entry.hostIds.has(id))) {
return true;
}
if (instance_ids && instance_ids.some(id => entry.instance_ids.has(id))) {
if (instanceIds && instanceIds.some(id => entry.instanceIds.has(id))) {
return true;
}
return false;
@@ -319,16 +319,16 @@ class LogIndex {
* @property {string} [order="asc"] -
* Return entries in ascending ("asc") date order or desceding ("desc")
* date order.
* @property {string} [max_level] -
* @property {string} [maxLevel] -
* Maximum log level to include. Higher levels are more verbose.
* @property {boolean} [all] -
* Include log entries from controller, all hosts and all instances.
* @property {boolean} [controller] -
* Include log entries from the controller.
* @property {Array<number>} [host_ids] -
* @property {Array<number>} [hostIds] -
* Include log entries for the given hosts and instances of those
* hosts by id.
* @property {Array<number>} [instance_ids] -
* @property {Array<number>} [instanceIds] -
* Include log entries for the given instances by id.
*/
+5 -39
View File
@@ -545,10 +545,14 @@ class BaseControllerPlugin {
* This does not include hosts that are in the process of closing the
* connection, which typically happens when they are shutting down.
*
* @param {module:lib/link.Event} event - Event to send
* @param {*} event - Event to send
* @param {Object} data - Data ta pass with the event.
*/
broadcastEventToHosts(event, data={}) {
if (event.type !== "event") {
this.logger.warn(`Ignoring broadcast of ${event.type}`);
return;
}
for (let hostConnection of this.controller.wsServer.hostConnections.values()) {
if (
!hostConnection.connector.closing
@@ -771,43 +775,6 @@ class BaseWebPlugin {
onControllerConnectionEvent(event) { }
}
/**
* Attach plugin messages
*
* Attaches all messages defined in the `.info.message` property of the
* `plugin` passed with handlers taken from the `pluin`.
*
* @param {module:lib/link.Link} link - Link to attach handlers to.
* @param {module:lib/plugin.BasePlugin} plugin -
* The instance of the plugin attach messages and handlers from.
*/
function attachPluginMessages(link, plugin) {
let messageDefinitions = plugin.info.messages || [];
for (let [name, messageFormat] of Object.entries(messageDefinitions)) {
if (messageFormat.plugin !== plugin.info.name) {
throw new Error(`Type of ${name} message must start with "${plugin.info.name}:"`);
}
let handler = name + messageFormat.handlerSuffix;
try {
if (plugin === null || !plugin[handler]) {
messageFormat.attach(link);
} else {
messageFormat.attach(link, async (message, format) => await plugin[handler](message, format, link));
}
} catch (err) {
if (err.code === "MISSING_LINK_HANDLER") {
err.plugin = plugin.info.name;
err.handler = handler;
}
throw err;
}
}
}
/**
* Invokes the given hook on all plugins
*
@@ -847,6 +814,5 @@ module.exports = {
BaseControlPlugin,
BaseWebPlugin,
attachPluginMessages,
invokeHook,
};
+1 -213
View File
@@ -8,216 +8,10 @@ const ajv = new Ajv({
verbose: true,
format: "full",
extendRefs: "fail",
strictDefaluts: true,
strictDefaults: true,
strictKeywords: true,
});
/**
* The base format for any message sent over the link
*/
const messageSchema = {
$schema: "http://json-schema.org/draft-07/schema#",
title: "Message",
description: "Format for messages on a link",
type: "object",
additionalProperties: false,
required: ["seq", "type", "data"],
properties: {
"seq": { type: ["integer", "null"] },
"type": { type: "string" },
"data": { type: "object" },
},
};
/**
* Validator for message schemas
* @function
* @param {Object} obj - Object to validate
* @returns {boolean} True if object passed validation.
*/
const message = ajv.compile(messageSchema);
/**
* Validator for heartbeat messages
* @function
* @param {Object} obj - Object to validate
* @returns {boolean} True if object passed validation.
*/
const heartbeat = ajv.compile({
$schema: "http://json-schema.org/draft-07/schema#",
title: "Heartbeat",
description: "Heartbeat sent over link",
type: "object",
additionalProperties: false,
required: ["seq", "type", "data"],
properties: {
"seq": { const: null },
"type": { const: "heartbeat" },
"data": {
type: "object",
additionalProperties: false,
required: ["seq"],
properties: {
"seq": { type: ["integer", "null"] },
},
},
},
});
/**
* Validator for server sent part of handshake
* @function
* @param {Object} obj - Object to validate
* @returns {boolean} True if object passed validation.
*/
const serverHandshake = ajv.compile({
$schema: "http://json-schema.org/draft-07/schema#",
title: "Server Handshake",
description: "Message sent from the server to a client during the handshake",
allOf: [messageSchema],
anyOf: [
{
properties: {
"type": { const: "hello" },
"data": {
additionalProperties: false,
required: ["version", "plugins"],
properties: {
"version": { type: "string" },
"plugins": {
type: "object",
additionalProperties: { type: "string" },
},
},
},
},
},
{
properties: {
"type": { const: "ready" },
"data": {
additionalProperties: false,
required: ["session_token", "session_timeout", "heartbeat_interval"],
properties: {
"session_token": { type: "string" },
"session_timeout": { type: "number" },
"heartbeat_interval": { type: "number" },
"account": {
type: "object",
additionalProperties: false,
required: ["name", "roles"],
properties: {
"name": { type: "string" },
"roles": {
type: "array",
items: {
additionalProperties: false,
type: "object",
required: ["name", "id", "permissions"],
properties: {
"name": { type: "string" },
"id": { type: "integer" },
"permissions": {
type: "array",
items: { type: "string" },
},
},
},
},
},
},
},
},
},
},
{
properties: {
"type": { const: "continue" },
"data": {
additionalProperties: false,
required: ["last_seq", "session_timeout", "heartbeat_interval"],
properties: {
"last_seq": { type: ["integer", "null"] },
"session_timeout": { type: "number" },
"heartbeat_interval": { type: "number" },
},
},
},
},
{
properties: {
"type": { const: "invalidate" },
"data": { const: {} },
},
},
],
});
/**
* Validator for client sent part of handshake
* @function
* @param {Object} obj - Object to validate
* @returns {boolean} True if object passed validation.
*/
const clientHandshake = ajv.compile({
$schema: "http://json-schema.org/draft-07/schema#",
title: "Client Message",
description: "Message sent from a client to the server",
allOf: [messageSchema],
anyOf: [
{
properties: {
"type": { const: "register_host" },
"data": {
additionalProperties: false,
required: ["token", "agent", "version", "name", "id", "plugins"],
properties: {
"token": { type: "string" },
"agent": { type: "string" },
"version": { type: "string" },
"name": { type: "string" },
"id": { type: "integer" },
"public_address": { type: "string" },
"plugins": {
type: "object",
additionalProperties: { type: "string" },
},
},
},
},
},
{
properties: {
"type": { const: "register_control" },
"data": {
additionalProperties: false,
required: ["token", "agent", "version"],
properties: {
"token": { type: "string" },
"agent": { type: "string" },
"version": { type: "string" },
},
},
},
},
{
properties: {
"type": { const: "resume" },
"data": {
additionalProperties: false,
required: ["session_token", "last_seq"],
properties: {
"session_token": { type: "string" },
"last_seq": { type: ["integer", "null"] },
},
},
},
},
],
});
module.exports = {
/**
* Compile JSON schema into validator
@@ -226,10 +20,4 @@ module.exports = {
* @returns {Function} Validator for the schema.
*/
compile: ajv.compile.bind(ajv),
message,
heartbeat,
serverHandshake,
clientHandshake,
};