mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-19 07:33:12 +09:00
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:
1 parent
9a967a5779
commit
bcd94709d2
106 files changed
+8173
-4928
No files matched your search
+13
-33
@@ -2,46 +2,26 @@
|
||||
const assert = require("assert").strict;
|
||||
|
||||
const libCommand = require("@clusterio/lib/command");
|
||||
const libData = require("@clusterio/lib/data");
|
||||
const libErrors = require("@clusterio/lib/errors");
|
||||
const libLink = require("@clusterio/lib/link");
|
||||
const mock = require("../mock");
|
||||
|
||||
const addr = libData.Address.fromShorthand;
|
||||
|
||||
|
||||
describe("lib/command", function() {
|
||||
let testRole = { id: 28, name: "Test Role", description: "Test", permissions: [] };
|
||||
let mockConnector = new mock.MockConnector();
|
||||
mockConnector.on("send", function(message) {
|
||||
if (message.type === "list_hosts_request") {
|
||||
this.emit("message", {
|
||||
seq: 1, type: "list_hosts_response",
|
||||
data: {
|
||||
seq: message.seq,
|
||||
list: [{ agent: "test", version: "0.1", id: 11, name: "Test Host", connected: false }],
|
||||
},
|
||||
});
|
||||
} else if (message.type === "list_instances_request") {
|
||||
this.emit("message", {
|
||||
seq: 1, type: "list_instances_response",
|
||||
data: {
|
||||
seq: message.seq,
|
||||
list: [{ id: 57, assigned_host: 4, name: "Test Instance", status: "stopped" }],
|
||||
},
|
||||
});
|
||||
} else if (message.type === "list_roles_request") {
|
||||
this.emit("message", {
|
||||
seq: 1, type: "list_roles_response",
|
||||
data: {
|
||||
seq: message.seq,
|
||||
list: [testRole],
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
let testRole = libData.RawRole.fromJSON({ id: 28, name: "Test Role", description: "Test", permissions: [] });
|
||||
|
||||
let testControl = new mock.MockControl(mockConnector);
|
||||
libLink.messages.listHosts.attach(testControl);
|
||||
libLink.messages.listInstances.attach(testControl);
|
||||
libLink.messages.listRoles.attach(testControl);
|
||||
let loopbackConnector = new libLink.VirtualConnector(addr("controller"), addr("controller"));
|
||||
let testControl = new mock.MockControl(loopbackConnector);
|
||||
testControl.register(
|
||||
libData.HostListRequest, () => [new libData.HostDetails("test", "0.1", "Test Host", 11, false)]
|
||||
);
|
||||
testControl.register(
|
||||
libData.InstanceDetailsListRequest, () => [new libData.InstanceDetails("Test Instance", 57, 4, null, "stopped")]
|
||||
);
|
||||
testControl.register(libData.RoleListRequest, () => [testRole]);
|
||||
|
||||
describe("resolveHost", function() {
|
||||
it("should pass an integer like string back", async function() {
|
||||
|
||||
@@ -31,13 +31,13 @@ describe("lib/file_ops", function() {
|
||||
let newest = await libFileOps.getNewestFile(path.join(baseDir, "test"));
|
||||
assert.equal(typeof newest, "string");
|
||||
});
|
||||
it("returns null if all entries were filtered out", async function() {
|
||||
it("returns undefined if all entries were filtered out", async function() {
|
||||
let newest = await libFileOps.getNewestFile(path.join(baseDir, "test"), (name) => !name.endsWith(".txt"));
|
||||
assert.equal(newest, null);
|
||||
assert.equal(newest, undefined);
|
||||
});
|
||||
it("returns null if directory is empty", async function() {
|
||||
it("returns undefined if directory is empty", async function() {
|
||||
let newest = await libFileOps.getNewestFile(path.join(baseDir, "test", "folder"));
|
||||
assert.equal(newest, null);
|
||||
assert.equal(newest, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+29
-19
@@ -3,6 +3,7 @@ const assert = require("assert").strict;
|
||||
const events = require("events");
|
||||
|
||||
const mock = require("../../mock");
|
||||
const libData = require("@clusterio/lib/data");
|
||||
const libLink = require("@clusterio/lib/link");
|
||||
|
||||
|
||||
@@ -50,10 +51,10 @@ describe("lib/link/connectors", function() {
|
||||
it("calls send on the socket", function() {
|
||||
testConnector._state = "connecting";
|
||||
testConnector._socket.sentMessages = [];
|
||||
testConnector.sendHandshake("test", { test: true });
|
||||
testConnector.sendHandshake(new libData.MessageInvalidate());
|
||||
assert.deepEqual(
|
||||
testConnector._socket.sentMessages.map(JSON.parse),
|
||||
[{ seq: null, type: "test", data: { test: true }}]
|
||||
[{ type: "invalidate" }]
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -62,10 +63,10 @@ describe("lib/link/connectors", function() {
|
||||
it("calls send on the socket", function() {
|
||||
testConnector._state = "connected";
|
||||
testConnector._socket.sentMessages = [];
|
||||
let seq = testConnector.send("test", { test: true });
|
||||
testConnector.send(new libData.MessageHeartbeat(1));
|
||||
assert.deepEqual(
|
||||
testConnector._socket.sentMessages.map(JSON.parse),
|
||||
[{ seq, type: "test", data: { test: true }}]
|
||||
[{ seq: 1, type: "heartbeat"}]
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -78,27 +79,34 @@ describe("lib/link/connectors", function() {
|
||||
});
|
||||
});
|
||||
|
||||
describe(".processHandshake()", function() {
|
||||
it("should close on invalid message", function() {
|
||||
describe(".parseMessage()", function() {
|
||||
it("should close on invalid json", function() {
|
||||
testConnector._socket.closeCalled = false;
|
||||
testConnector._processHandshake({ data: "invalid message" });
|
||||
testConnector._parseMessage("invalid json");
|
||||
assert(testConnector._socket.closeCalled, "Close was not called on the socket");
|
||||
});
|
||||
it("should close on invalid message", function() {
|
||||
testConnector._socket.closeCalled = false;
|
||||
testConnector._parseMessage('{"invalid":"message"}');
|
||||
assert(testConnector._socket.closeCalled, "Close was not called on the socket");
|
||||
});
|
||||
});
|
||||
describe(".processHandshake()", function() {
|
||||
it("should call register on hello", function() {
|
||||
let called = false;
|
||||
testConnector.register = () => { called = true; };
|
||||
testConnector._processHandshake({ seq: 1, type: "hello", data: { version: "test", plugins: {} }});
|
||||
testConnector._processHandshake(new libData.MessageHello(new libData.HelloData("test", {})));
|
||||
assert(called, "register was not called");
|
||||
});
|
||||
it("should emit connect on ready", async function() {
|
||||
let result = events.once(testConnector, "connect");
|
||||
testConnector._processHandshake(
|
||||
{ seq: 1, type: "ready", data: {
|
||||
session_token: "x",
|
||||
session_timeout: 20,
|
||||
heartbeat_interval: 10,
|
||||
}}
|
||||
);
|
||||
testConnector._processHandshake(new libData.MessageReady(new libData.ReadyData(
|
||||
new libData.Address(libData.Address.control, 1),
|
||||
"x",
|
||||
20,
|
||||
10,
|
||||
undefined
|
||||
)));
|
||||
await result;
|
||||
clearInterval(testConnector._heartbeatId);
|
||||
});
|
||||
@@ -112,7 +120,7 @@ describe("lib/link/connectors", function() {
|
||||
it("should throw on message received in invalid state", function() {
|
||||
testConnector._state = "closed";
|
||||
assert.throws(
|
||||
() => testConnector._socket.events.get("message")("{}"),
|
||||
() => testConnector._socket.events.get("message")(JSON.stringify(new libData.MessageInvalidate())),
|
||||
new Error("Received message in unexpected state closed")
|
||||
);
|
||||
});
|
||||
@@ -120,15 +128,17 @@ describe("lib/link/connectors", function() {
|
||||
testConnector._state = "connecting";
|
||||
let called = false;
|
||||
testConnector._processHandshake = () => { called = true; };
|
||||
testConnector._socket.events.get("message")("{}");
|
||||
testConnector._socket.events.get("message")(JSON.stringify(new libData.MessageInvalidate()));
|
||||
assert(called, "_processHandshake was not called");
|
||||
});
|
||||
it("should emit message on message in connected state", async function() {
|
||||
testConnector._socket.sentMessages = [];
|
||||
testConnector._state = "connected";
|
||||
let result = events.once(testConnector, "message");
|
||||
testConnector._socket.events.get("message")('{"message":true}');
|
||||
assert.deepEqual(await result, [{ message: true }]);
|
||||
let addr = new libData.Address(libData.Address.control, 1);
|
||||
let event = new libData.MessageEvent(1, addr, addr, "TestEvent");
|
||||
testConnector._socket.events.get("message")(JSON.stringify(event));
|
||||
assert.deepEqual((await result)[0], event);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+366
-151
@@ -2,185 +2,400 @@
|
||||
const assert = require("assert").strict;
|
||||
const events = require("events");
|
||||
|
||||
const libData = require("@clusterio/lib/data");
|
||||
const libLink = require("@clusterio/lib/link");
|
||||
const libErrors = require("@clusterio/lib/errors");
|
||||
const libSchema = require("@clusterio/lib/schema");
|
||||
const mock = require("../../mock");
|
||||
|
||||
const addr = libData.Address.fromShorthand;
|
||||
|
||||
describe("lib/link/link", function() {
|
||||
function throwSimple(message) {
|
||||
let err = new Error(message);
|
||||
err.stack = message;
|
||||
throw err;
|
||||
}
|
||||
|
||||
describe("class Link", function() {
|
||||
let testConnector;
|
||||
let testLink;
|
||||
let src = addr({ controlId: 1 });
|
||||
let dst = addr("controller");
|
||||
|
||||
before(function() {
|
||||
testConnector = new mock.MockConnector();
|
||||
testLink = new libLink.Link("source", "target", testConnector);
|
||||
testLink.setValidator("simple", libSchema.compile({
|
||||
properties: {
|
||||
"data": {
|
||||
type: "object",
|
||||
properties: {
|
||||
"string": { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
class SimpleRequest {
|
||||
static type = "request";
|
||||
static src = ["controller", "control"];
|
||||
static dst = ["controller", "control"];
|
||||
}
|
||||
class NumberRequest {
|
||||
static type = "request";
|
||||
static src = ["controller", "control"];
|
||||
static dst = ["controller", "control"];
|
||||
constructor(value) { this.value = value; }
|
||||
static jsonSchema = { type: "number" };
|
||||
toJSON() { return this.value; }
|
||||
static fromJSON(json) { return new this(json); }
|
||||
}
|
||||
NumberRequest.Response = class {
|
||||
constructor(value) { this.value = value; }
|
||||
static jsonSchema = { type: "number" };
|
||||
toJSON() { return this.value; }
|
||||
static fromJSON(json) { return new this(json); }
|
||||
};
|
||||
class SimpleEvent {
|
||||
static type = "event";
|
||||
static src = ["controller", "control"];
|
||||
static dst = ["controller", "control"];
|
||||
}
|
||||
class NumberEvent {
|
||||
static type = "event";
|
||||
static src = ["controller", "control"];
|
||||
static dst = ["controller", "control"];
|
||||
constructor(value) { this.value = value; }
|
||||
static jsonSchema = { type: "number" };
|
||||
toJSON() { return this.value; }
|
||||
static fromJSON(json) { return new this(json); }
|
||||
}
|
||||
|
||||
beforeEach(function() {
|
||||
testConnector = new mock.MockConnector(src, dst);
|
||||
testLink = new libLink.Link(testConnector);
|
||||
});
|
||||
|
||||
it("should emitt error processing message to connector", async function() {
|
||||
testLink.setHandler("throws", () => { throw new Error("Handler error"); }, () => true);
|
||||
let result = events.once(testConnector, "message");
|
||||
testConnector.emit("message", { seq: 1, type: "throws", data: {}});
|
||||
await assert.rejects(result, new Error("Handler error"));
|
||||
it("should handle unknown message", async function() {
|
||||
testConnector.emit("message", { type: "unknown" });
|
||||
});
|
||||
it("should give an error response back on unrecognized request", function() {
|
||||
testConnector.emit("message", new libData.MessageRequest(1, dst, src, "UnhandledRequest"));
|
||||
assert.deepEqual(testConnector.sentMessages, [
|
||||
new libData.MessageResponseError(
|
||||
testConnector._seq - 1,
|
||||
src,
|
||||
dst,
|
||||
new libData.ResponseError("Unrecognized request UnhandledRequest")
|
||||
),
|
||||
]);
|
||||
});
|
||||
it("should give an error response back on unhandled request", function() {
|
||||
class UnhandledRequest {
|
||||
static type = "request";
|
||||
static src = "controller";
|
||||
static dst = "control";
|
||||
}
|
||||
testLink.register(UnhandledRequest);
|
||||
testConnector.emit("message", new libData.MessageRequest(1, dst, src, "UnhandledRequest"));
|
||||
assert.deepEqual(testConnector.sentMessages, [
|
||||
new libData.MessageResponseError(
|
||||
testConnector._seq - 1,
|
||||
src,
|
||||
dst,
|
||||
new libData.ResponseError("No handler registered for UnhandledRequest")
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should give an error response back on an unhandled request", function() {
|
||||
testConnector.sentMessages = [];
|
||||
testConnector.emit("message", { seq: 1, type: "unhandled_request", data: {}});
|
||||
assert.deepEqual(testConnector.sentMessages, [{
|
||||
type: "unhandled_response",
|
||||
seq: testConnector._seq - 1,
|
||||
data: { seq: 1, error: "No validator for unhandled_request on source-target" },
|
||||
}]);
|
||||
it("should send ready on connector prepareDisconnect", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testConnector.emit("disconnectPrepare");
|
||||
assert.deepEqual(await message, [new libData.MessageDisconnect("ready")]);
|
||||
});
|
||||
it("should send ready on connector prepareDisconnect if an error occurs", async function() {
|
||||
testLink.prepareDisconnect = async () => { throwSimple("Error occured"); };
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testConnector.emit("disconnectPrepare");
|
||||
assert.deepEqual(await message, [new libData.MessageDisconnect("ready")]);
|
||||
});
|
||||
|
||||
describe(".setValidator()", function() {
|
||||
it("should set the validator", function() {
|
||||
testLink.setValidator("test", () => true);
|
||||
assert(testLink._validators.has("test"), "validator was not added");
|
||||
});
|
||||
it("should throw on duplicated validator", function() {
|
||||
assert.throws(
|
||||
() => testLink.setValidator("test", () => true),
|
||||
new Error("test already has a validator")
|
||||
);
|
||||
});
|
||||
it("should reject pending requests on close", async function() {
|
||||
let pending = testLink.send(new SimpleRequest());
|
||||
pending.catch(() => {});
|
||||
testConnector.emit("close");
|
||||
await assert.rejects(pending, { message: "Session Closed" });
|
||||
});
|
||||
it("should reject pending requests on invalidate", async function() {
|
||||
let pending = testLink.send(new SimpleRequest());
|
||||
pending.catch(() => {});
|
||||
testConnector.emit("invalidate");
|
||||
await assert.rejects(pending, { message: "Session Lost" });
|
||||
});
|
||||
|
||||
describe(".setHandler()", function() {
|
||||
it("should throw if validator is not passed", function() {
|
||||
assert.throws(
|
||||
() => testLink.setHandler("no_validator_test", (message) => {}),
|
||||
new Error("validator is required")
|
||||
describe(".send()", function() {
|
||||
it("should send request to the other side of the link", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testLink.send(new SimpleRequest());
|
||||
let srcReq = new libData.Address(libData.Address.control, 1, 1);
|
||||
assert.deepEqual(
|
||||
await message,
|
||||
[new libData.MessageRequest(1, srcReq, dst, "SimpleRequest", undefined)]
|
||||
);
|
||||
});
|
||||
it("should set the handler", function() {
|
||||
function handler(message) { }
|
||||
testLink.setHandler("handler_test", handler, (message) => true);
|
||||
assert.equal(testLink._handlers.get("handler_test"), handler);
|
||||
});
|
||||
it("should throw on duplicated handler", function() {
|
||||
assert.throws(
|
||||
() => testLink.setHandler("handler_test", (message) => {}),
|
||||
new Error("handler_test already has a handler")
|
||||
it("should send request with data to the other side of the link", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testLink.send(new NumberRequest(22));
|
||||
let srcReq = new libData.Address(libData.Address.control, 1, 1);
|
||||
assert.deepEqual(
|
||||
await message,
|
||||
[new libData.MessageRequest(1, srcReq, dst, "NumberRequest", new NumberRequest(22))]
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(".processMessage()", function() {
|
||||
it("should throw on invalid message", function() {
|
||||
assert.throws(
|
||||
() => testLink.processMessage({ data: "invalid message" }),
|
||||
{ message: "Malformed" }
|
||||
it("should send request and resolve when response is received", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
let request = testLink.send(new SimpleRequest());
|
||||
let srcReq = new libData.Address(libData.Address.control, 1, 1);
|
||||
testConnector.emit("message", new libData.MessageResponse(1, dst, srcReq));
|
||||
await request;
|
||||
});
|
||||
it("should send request and reject with error when error response is received", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
let request = testLink.send(new SimpleRequest());
|
||||
let srcReq = new libData.Address(libData.Address.control, 1, 1);
|
||||
testConnector.emit(
|
||||
"message", new libData.MessageResponseError(1, dst, srcReq, new libData.ResponseError("Error"))
|
||||
);
|
||||
});
|
||||
it("should throw on message without validator", function() {
|
||||
assert.throws(
|
||||
() => testLink.processMessage({ seq: 1, type: "no_validator", data: {} }),
|
||||
new libErrors.InvalidMessage("No validator for no_validator on source-target")
|
||||
);
|
||||
});
|
||||
it("should throw on message failing validation", function() {
|
||||
assert.throws(
|
||||
() => testLink.processMessage({ seq: 1, type: "simple", data: { string: 1 }}),
|
||||
{ message: "Validation failed for simple" }
|
||||
);
|
||||
});
|
||||
it("should throw on unhandled message", function() {
|
||||
assert.throws(
|
||||
() => testLink.processMessage({ seq: 1, type: "simple", data: { string: "a" }}),
|
||||
new libErrors.InvalidMessage("Unhandled message simple")
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("._processHandler()", function() {
|
||||
it("should call the handler", function() {
|
||||
let handled = [];
|
||||
testLink.setHandler("handled", (message) => handled.push(message), (message) => true);
|
||||
testLink._processHandler({ seq: 1, type: "handled", data: { test: "foo" } });
|
||||
assert.deepEqual(handled, [{ seq: 1, type: "handled", data: { test: "foo" } }]);
|
||||
});
|
||||
it("should return true if handled", function() {
|
||||
let result = testLink._processHandler({ seq: 1, type: "handled", data: {} });
|
||||
assert.equal(result, true);
|
||||
});
|
||||
it("should return false if not handled", function() {
|
||||
let result = testLink._processHandler({ seq: 1, type: "not_handled", data: {} });
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("._processWaiters()", function() {
|
||||
it("should call waiters", async function() {
|
||||
let waiter = new Promise(resolve => {
|
||||
testLink._waiters.set("test", [{ resolve, data: {} }]);
|
||||
});
|
||||
assert(
|
||||
testLink._processWaiters({ type: "test", seq: 4, data: {} }),
|
||||
"Waiter was not processed"
|
||||
);
|
||||
assert.deepEqual(await waiter, { type: "test", seq: 4, data: {} });
|
||||
});
|
||||
it("should filter on data", async function() {
|
||||
let waiter = new Promise(resolve => {
|
||||
testLink._waiters.set("test", [{ resolve, data: { a: 1, b: 2 } }]);
|
||||
});
|
||||
assert(
|
||||
!testLink._processWaiters({ type: "test", seq: 4, data: {} }),
|
||||
"Incorrectly matched empty message"
|
||||
);
|
||||
assert(
|
||||
!testLink._processWaiters({ type: "test", seq: 4, data: { a: 1, b: 0 } }),
|
||||
"Incorrectly matched message with wrong data"
|
||||
);
|
||||
assert(
|
||||
testLink._processWaiters({ type: "test", seq: 4, data: { a: 1, b: 2, c: 3 } }),
|
||||
"Did not match correct message"
|
||||
);
|
||||
assert.deepEqual(await waiter, { type: "test", seq: 4, data: { a: 1, b: 2, c: 3 } });
|
||||
});
|
||||
});
|
||||
|
||||
describe(".waitFor()", function() {
|
||||
before(function() {
|
||||
testLink.setValidator("waiter", (message) => true);
|
||||
});
|
||||
|
||||
it("should throw on missing validator", async function() {
|
||||
await assert.rejects(
|
||||
testLink.waitFor("no_validator", {}),
|
||||
new Error("No validator for no_validator on source-target")
|
||||
request,
|
||||
{ message: "Error" }
|
||||
);
|
||||
});
|
||||
it("should wait for a given message", async function() {
|
||||
let result = testLink.waitFor("waiter", {});
|
||||
assert(
|
||||
testLink._processWaiters({ type: "waiter", seq: 5, data: {} }),
|
||||
"Did not proccess waiter"
|
||||
);
|
||||
assert.deepEqual(await result, { type: "waiter", seq: 5, data: {} });
|
||||
it("should send request and resolve with data when response is received", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
let request = testLink.send(new NumberRequest(22));
|
||||
let srcReq = new libData.Address(libData.Address.control, 1, 1);
|
||||
testConnector.emit("message", new libData.MessageResponse(1, dst, srcReq, 44));
|
||||
assert.deepEqual(await request, new NumberRequest.Response(44));
|
||||
});
|
||||
it("should handle multiple waiters", async function() {
|
||||
let result1 = testLink.waitFor("waiter", {});
|
||||
let result2 = testLink.waitFor("waiter", {});
|
||||
assert(
|
||||
testLink._processWaiters({ type: "waiter", seq: 5, data: {} }),
|
||||
"Did not proccess waiter"
|
||||
it("should send event to the other side of the link", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testLink.send(new SimpleEvent());
|
||||
assert.deepEqual(
|
||||
await message,
|
||||
[new libData.MessageEvent(1, src, dst, "SimpleEvent", undefined)]
|
||||
);
|
||||
});
|
||||
it("should send event with data to the other side of the link", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testLink.send(new NumberEvent(22));
|
||||
assert.deepEqual(
|
||||
await message,
|
||||
[new libData.MessageEvent(1, src, dst, "NumberEvent", new NumberEvent(22))]
|
||||
);
|
||||
});
|
||||
});
|
||||
describe(".register()", function() {
|
||||
it("should register a request", function() {
|
||||
let handled = false;
|
||||
testLink.register(SimpleRequest, async () => { handled = true; });
|
||||
assert(testLink._registeredRequests.has("SimpleRequest"), "request was not registered");
|
||||
testConnector.emit("message", new libData.MessageRequest(1, dst, src, "SimpleRequest"));
|
||||
assert(handled, "request was not handled");
|
||||
});
|
||||
it("should send response error from request handler throwing", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testLink.register(SimpleRequest, async () => { throwSimple("Error"); });
|
||||
testConnector.emit("message", new libData.MessageRequest(1, dst, src, "SimpleRequest"));
|
||||
assert.deepEqual(
|
||||
await message,
|
||||
[new libData.MessageResponseError(
|
||||
1, src, dst, new libData.ResponseError("Error", undefined, "Error")
|
||||
)]
|
||||
);
|
||||
});
|
||||
it("should send response error on request validation failing", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testLink.register(NumberRequest, async () => 1);
|
||||
testConnector.emit("message", new libData.MessageRequest(1, dst, src, "NumberRequest", "not a number"));
|
||||
let response = (await message)[0];
|
||||
assert.deepEqual(
|
||||
response,
|
||||
new libData.MessageResponseError(1, src, dst, new libData.ResponseError(
|
||||
"Request NumberRequest failed validation",
|
||||
response.data.code,
|
||||
response.data.stack,
|
||||
))
|
||||
);
|
||||
});
|
||||
it("should send response error on response validation failing", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testLink.register(NumberRequest, async () => "not a number");
|
||||
testConnector.emit("message", new libData.MessageRequest(1, dst, src, "NumberRequest", 1));
|
||||
let response = (await message)[0];
|
||||
assert.deepEqual(
|
||||
response,
|
||||
new libData.MessageResponseError(1, src, dst, new libData.ResponseError(
|
||||
"Response for request NumberRequest failed validation",
|
||||
response.data.code,
|
||||
response.data.stack,
|
||||
))
|
||||
);
|
||||
});
|
||||
it("should send value returned from request handler", async function() {
|
||||
let message = events.once(testConnector, "send");
|
||||
message.catch(() => {});
|
||||
testLink.register(NumberRequest, async (request) => request.value + 4);
|
||||
testConnector.emit("message", new libData.MessageRequest(1, dst, src, "NumberRequest", 1));
|
||||
let response = (await message)[0];
|
||||
assert.deepEqual(
|
||||
response,
|
||||
new libData.MessageResponse(1, src, dst, 5)
|
||||
);
|
||||
});
|
||||
it("should register an event", function() {
|
||||
let handled = false;
|
||||
testLink.register(SimpleEvent, async () => { handled = true; });
|
||||
assert(testLink._registeredEvents.has("SimpleEvent"), "event was not registered");
|
||||
testConnector.emit("message", new libData.MessageEvent(1, dst, src, "SimpleEvent"));
|
||||
assert(handled, "event was not handled");
|
||||
});
|
||||
it("should pass value to event handler", async function() {
|
||||
let value;
|
||||
testLink.register(NumberEvent, async (event) => { value = event.value; });
|
||||
testConnector.emit("message", new libData.MessageEvent(1, dst, src, "NumberEvent", 9));
|
||||
assert.deepEqual(value, 9);
|
||||
});
|
||||
it("should log errors from event handler", function() {
|
||||
testLink.register(SimpleEvent, async () => { throwSimple("Error"); });
|
||||
testConnector.emit("message", new libData.MessageEvent(1, dst, src, "SimpleEvent"));
|
||||
});
|
||||
it("should throw on unknown type", function() {
|
||||
assert.throws(
|
||||
() => testLink.register({ name: "Bad", type: "bad" }),
|
||||
{ message: "Class Bad has unrecognized type bad" }
|
||||
);
|
||||
});
|
||||
it("should throw on double registration", function() {
|
||||
testLink.register(SimpleRequest);
|
||||
assert.throws(
|
||||
() => testLink.register(SimpleRequest),
|
||||
new Error("Request SimpleRequest is already registered")
|
||||
);
|
||||
testLink.register(SimpleEvent);
|
||||
assert.throws(
|
||||
() => testLink.register(SimpleEvent),
|
||||
new Error("Event SimpleEvent is already registered")
|
||||
);
|
||||
});
|
||||
it("should throw if Request has only one of jsonSchema and fromJSON", function() {
|
||||
class BadRequest1 {
|
||||
static type = "request";
|
||||
static src = "controller";
|
||||
static dst = "control";
|
||||
static jsonSchema = {};
|
||||
}
|
||||
assert.throws(
|
||||
() => testLink.register(BadRequest1),
|
||||
new Error("Request BadRequest1 has static jsonSchema but is missing static fromJSON")
|
||||
);
|
||||
class BadRequest2 {
|
||||
static type = "request";
|
||||
static src = "controller";
|
||||
static dst = "control";
|
||||
static fromJSON() {};
|
||||
}
|
||||
assert.throws(
|
||||
() => testLink.register(BadRequest2),
|
||||
new Error("Request BadRequest2 has static fromJSON but is missing static jsonSchema")
|
||||
);
|
||||
});
|
||||
it("should throw if Event has only one of jsonSchema and fromJSON", function() {
|
||||
class BadEvent1 {
|
||||
static type = "event";
|
||||
static src = "controller";
|
||||
static dst = "control";
|
||||
static jsonSchema = {};
|
||||
}
|
||||
assert.throws(
|
||||
() => testLink.register(BadEvent1),
|
||||
new Error("Event BadEvent1 has static jsonSchema but is missing static fromJSON")
|
||||
);
|
||||
class BadEvent2 {
|
||||
static type = "event";
|
||||
static src = "controller";
|
||||
static dst = "control";
|
||||
static fromJSON() {};
|
||||
}
|
||||
assert.throws(
|
||||
() => testLink.register(BadEvent2),
|
||||
new Error("Event BadEvent2 has static fromJSON but is missing static jsonSchema")
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("._processMessage()", function() {
|
||||
it("should throw on unhandled type", function() {
|
||||
assert.throws(
|
||||
() => testLink._processMessage({ type: "invalid" }),
|
||||
{ message: "Unhandled message type invalid" }
|
||||
);
|
||||
});
|
||||
it("should throw on Event failing validation", function() {
|
||||
class StringEvent {
|
||||
static type = "event";
|
||||
static src = "controller";
|
||||
static dst = "control";
|
||||
constructor(value) { this.value = value; }
|
||||
static jsonSchema = { type: "string" };
|
||||
static fromJSON(json) { return new this(json); };
|
||||
}
|
||||
testLink.register(StringEvent, () => {});
|
||||
assert.throws(
|
||||
() => testLink._processMessage(new libData.MessageEvent(1, dst, src, "StringEvent", 99)),
|
||||
{ message: "Event StringEvent failed validation" }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(".snoopEvent()", function() {
|
||||
it("should snoop an event", function() {
|
||||
let handled = false;
|
||||
testLink.snoopEvent(SimpleEvent, async () => { handled = true; });
|
||||
assert(testLink._snoopedEvents.has("SimpleEvent"), "event was not snooped");
|
||||
testConnector.emit("message", new libData.MessageEvent(1, dst, src, "SimpleEvent"));
|
||||
assert(handled, "event was not handled");
|
||||
});
|
||||
it("should log errors from snoop handler", function() {
|
||||
testLink.snoopEvent(SimpleEvent, async () => { throwSimple("Error"); });
|
||||
testConnector.emit("message", new libData.MessageEvent(1, dst, src, "SimpleEvent"));
|
||||
});
|
||||
it("should throw on double registration", function() {
|
||||
testLink.snoopEvent(SimpleEvent);
|
||||
assert.throws(
|
||||
() => testLink.snoopEvent(SimpleEvent),
|
||||
new Error("Event SimpleEvent is already snooped")
|
||||
);
|
||||
});
|
||||
it("should throw if Event has only one of jsonSchema and fromJSON", function() {
|
||||
class BadEvent1 {
|
||||
static type = "event";
|
||||
static src = "controller";
|
||||
static dst = "control";
|
||||
static jsonSchema = {};
|
||||
}
|
||||
assert.throws(
|
||||
() => testLink.snoopEvent(BadEvent1),
|
||||
new Error("Event BadEvent1 has static jsonSchema but is missing static fromJSON")
|
||||
);
|
||||
class BadEvent2 {
|
||||
static type = "event";
|
||||
static src = "controller";
|
||||
static dst = "control";
|
||||
static fromJSON() {};
|
||||
}
|
||||
assert.throws(
|
||||
() => testLink.snoopEvent(BadEvent2),
|
||||
new Error("Event BadEvent2 has static fromJSON but is missing static jsonSchema")
|
||||
);
|
||||
assert.deepEqual(await result1, { type: "waiter", seq: 5, data: {} });
|
||||
assert.deepEqual(await result2, { type: "waiter", seq: 5, data: {} });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
"use strict";
|
||||
const assert = require("assert").strict;
|
||||
|
||||
const libLink = require("@clusterio/lib/link");
|
||||
const libErrors = require("@clusterio/lib/errors");
|
||||
const mock = require("../../mock");
|
||||
|
||||
|
||||
describe("lib/link/messages", function() {
|
||||
let testSourceLink = new libLink.Link("source", "target", new mock.MockConnector());
|
||||
let testTargetLink = new libLink.Link("target", "source", new mock.MockConnector());
|
||||
|
||||
let lastTargetSent;
|
||||
testTargetLink.send = (type, data) => { lastTargetSent = { type, data }; };
|
||||
|
||||
describe("class Request", function() {
|
||||
let testRequest = new libLink.Request({
|
||||
type: "test",
|
||||
links: ["source-target"],
|
||||
requestRequired: ["test"],
|
||||
requestProperties: {
|
||||
"test": { type: "string" },
|
||||
"optional": { type: "number" },
|
||||
},
|
||||
responseRequired: ["test"],
|
||||
responseProperties: {
|
||||
"test": { type: "string" },
|
||||
"optional": { type: "number" },
|
||||
},
|
||||
});
|
||||
|
||||
describe("constructor", function() {
|
||||
it("should throw on invalid forwardTo", function() {
|
||||
assert.throws(
|
||||
() => new libLink.Request({ links: [], forwardTo: "invalid" }),
|
||||
new Error("Invalid forwardTo value invalid")
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(".attach()", function() {
|
||||
it("should attach validator to a source link", function() {
|
||||
testRequest.attach(testSourceLink);
|
||||
assert(testSourceLink._validators.has("test_response"), "Validator was not set");
|
||||
});
|
||||
it("should throw if missing handler on target link", function() {
|
||||
assert.throws(
|
||||
() => testRequest.attach(testTargetLink),
|
||||
new Error("Missing handler for test_request on target-source link")
|
||||
);
|
||||
});
|
||||
|
||||
let handlerResult;
|
||||
it("should attach handler to a target link", function() {
|
||||
testRequest.attach(testTargetLink, async (message) => handlerResult);
|
||||
assert(testTargetLink._handlers.has("test_request"), "Handler was not set");
|
||||
});
|
||||
it("should send result of calling the handler", async function() {
|
||||
handlerResult = { test: "handler" };
|
||||
testTargetLink._handlers.get("test_request")({ seq: 2 });
|
||||
let result = await new Promise(resolve => {
|
||||
testTargetLink.connector.send = (type, data) => resolve({ type, data });
|
||||
});
|
||||
assert.deepEqual(result, {
|
||||
type: "test_response",
|
||||
data: {
|
||||
test: "handler",
|
||||
seq: 2,
|
||||
},
|
||||
});
|
||||
});
|
||||
it("should implicitly send an empty object on empty return", async function() {
|
||||
let emptyRequest = new libLink.Request({
|
||||
type: "empty",
|
||||
links: ["source-target"],
|
||||
});
|
||||
emptyRequest.attach(testTargetLink, async(message) => {});
|
||||
testTargetLink._handlers.get("empty_request")({ seq: 2 });
|
||||
let result = await new Promise(resolve => {
|
||||
testTargetLink.connector.send = (type, data) => resolve({ type, data });
|
||||
});
|
||||
assert.deepEqual(result, {
|
||||
type: "empty_response",
|
||||
data: {
|
||||
seq: 2,
|
||||
},
|
||||
});
|
||||
});
|
||||
it("should validate response from handler", async function() {
|
||||
handlerResult = { test: 12 };
|
||||
testTargetLink._handlers.get("test_request")({ seq: 2 });
|
||||
let result = await new Promise(resolve => {
|
||||
testTargetLink.connector.send = (type, data) => resolve({ type, data });
|
||||
});
|
||||
assert.deepEqual(result, {
|
||||
type: "test_response",
|
||||
data: {
|
||||
error: "Validation failed responding to test_request",
|
||||
seq: 2,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(".send()", function() {
|
||||
it("should send request with send and use waitFor to get response", async function() {
|
||||
let request;
|
||||
testSourceLink.connector.send = (type, data) => {
|
||||
request = { type, data };
|
||||
};
|
||||
testSourceLink.waitFor = (type, condition) => ({ data: { type, request }});
|
||||
assert.deepEqual(
|
||||
await testRequest.send(testSourceLink, { test: "request" }),
|
||||
{ type: "test_response", request: { type: "test_request", data: { test: "request" }}}
|
||||
);
|
||||
delete testSourceLink.connector.send;
|
||||
delete testSourceLink.waitFor;
|
||||
});
|
||||
it("should throw error response", async function() {
|
||||
testSourceLink.waitFor = (type, condition) => ({ data: { error: "test error" }});
|
||||
await assert.rejects(
|
||||
testRequest.send(testSourceLink, { test: "blah" }),
|
||||
new libErrors.RequestError("test error")
|
||||
);
|
||||
delete testSourceLink.waitFor;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("class Event", function() {
|
||||
let testEvent = new libLink.Event({
|
||||
type: "test",
|
||||
links: ["source-target"],
|
||||
eventRequired: ["test"],
|
||||
eventProperties: {
|
||||
"test": { type: "string" },
|
||||
"optional": { type: "number" },
|
||||
},
|
||||
});
|
||||
|
||||
describe("constructor", function() {
|
||||
it("should throw on invalid forwardTo", function() {
|
||||
assert.throws(
|
||||
() => new libLink.Event({ forwardTo: "invalid" }),
|
||||
new Error("Invalid forwardTo value invalid")
|
||||
);
|
||||
});
|
||||
it("should throw on invalid broadcastTo", function() {
|
||||
assert.throws(
|
||||
() => new libLink.Event({ broadcastTo: "invalid" }),
|
||||
new Error("Invalid broadcastTo value invalid")
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(".attach()", function() {
|
||||
it("should throw if missing handler on target link", function() {
|
||||
assert.throws(
|
||||
() => testEvent.attach(testTargetLink),
|
||||
new Error("Missing handler for test_event on target-source link")
|
||||
);
|
||||
});
|
||||
let called = false;
|
||||
it("should attach handler and validator to a target link", function() {
|
||||
testEvent.attach(testTargetLink, async (message) => { called = true; });
|
||||
assert(testTargetLink._validators.has("test_event"), "Validator was not set");
|
||||
});
|
||||
it("should call the attached event handler", function() {
|
||||
testTargetLink._handlers.get("test_event")();
|
||||
assert(called, "Handler was not called");
|
||||
});
|
||||
});
|
||||
|
||||
describe(".send()", function() {
|
||||
it("should send the event over the link", async function() {
|
||||
testSourceLink.connector.sentMessages = [];
|
||||
testEvent.send(testSourceLink, { test: "event" });
|
||||
let seq = testSourceLink.connector._seq - 1;
|
||||
assert.deepEqual(
|
||||
testSourceLink.connector.sentMessages,
|
||||
[{ seq, type: "test_event", data: { test: "event" }}]
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("attachAllMessages()", function() {
|
||||
it("does not throw", function() {
|
||||
libLink.attachAllMessages(testSourceLink);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -98,12 +98,12 @@ describe("lib/logging_utils.js", function() {
|
||||
let log = await libLoggingUtils.queryLog(logDir, { limit: 2, all: true }, index());
|
||||
assert.deepEqual(log, allLines.slice(0, 2));
|
||||
});
|
||||
it("should filter by max_level", async function() {
|
||||
let log = await libLoggingUtils.queryLog(logDir, { max_level: "info", all: true }, index());
|
||||
it("should filter by maxLevel", async function() {
|
||||
let log = await libLoggingUtils.queryLog(logDir, { maxLevel: "info", all: true }, index());
|
||||
assert.deepEqual(log, allLines.filter(
|
||||
info => ["fatal", "error", "warn", "audit", "info"].includes(info.level)
|
||||
));
|
||||
log = await libLoggingUtils.queryLog(logDir, { max_level: "fatal", all: true }, index());
|
||||
log = await libLoggingUtils.queryLog(logDir, { maxLevel: "fatal", all: true }, index());
|
||||
assert.deepEqual(log, allLines.filter(
|
||||
info => ["fatal"].includes(info.level)
|
||||
));
|
||||
@@ -114,14 +114,14 @@ describe("lib/logging_utils.js", function() {
|
||||
info => info.host_id === undefined && info.instance_id === undefined
|
||||
));
|
||||
});
|
||||
it("should filter by host_ids", async function() {
|
||||
let log = await libLoggingUtils.queryLog(logDir, { host_ids: [1, 2] }, index());
|
||||
it("should filter by hostIds", async function() {
|
||||
let log = await libLoggingUtils.queryLog(logDir, { hostIds: [1, 2] }, index());
|
||||
assert.deepEqual(log, allLines.filter(
|
||||
info => [1, 2].includes(info.host_id) && info.instance_id === undefined
|
||||
));
|
||||
});
|
||||
it("should filter by instance_ids", async function() {
|
||||
let log = await libLoggingUtils.queryLog(logDir, { instance_ids: [10, 11] }, index());
|
||||
it("should filter by instanceIds", async function() {
|
||||
let log = await libLoggingUtils.queryLog(logDir, { instanceIds: [10, 11] }, index());
|
||||
assert.deepEqual(log, allLines.filter(info => [10, 11].includes(info.instance_id)));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
const assert = require("assert").strict;
|
||||
|
||||
const mock = require("../mock");
|
||||
const libLink = require("@clusterio/lib/link");
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
|
||||
|
||||
@@ -71,33 +70,6 @@ describe("lib/plugin", function() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("attachPluginMessages()", function() {
|
||||
let mockLink = new libLink.Link("source", "target", new mock.MockConnector());
|
||||
let mockEvent = new libLink.Event({ type: "test:test", links: ["target-source"] });
|
||||
it("should accept pluginInfo without messages", function() {
|
||||
libPlugin.attachPluginMessages(mockLink, { info: {} });
|
||||
});
|
||||
it("should attach handler for the given message", function() {
|
||||
function mockEventEventHandler() { };
|
||||
libPlugin.attachPluginMessages(
|
||||
mockLink, { mockEventEventHandler, info: { name: "test", messages: { mockEvent }}}
|
||||
);
|
||||
assert(mockLink._handlers.get("test:test_event"), "handler was not registered");
|
||||
});
|
||||
it("should throw if missing handler for the given message", function() {
|
||||
assert.throws(
|
||||
() => libPlugin.attachPluginMessages(mockLink, { info: { name: "test", messages: { mockEvent }}}),
|
||||
new Error("Missing mockEventEventHandler on plugin test for test:test_event on source-target link")
|
||||
);
|
||||
});
|
||||
it("should throw if message starts with the wrong prefix", function() {
|
||||
assert.throws(
|
||||
() => libPlugin.attachPluginMessages(mockLink, { info: { name: "foo", messages: { mockEvent }}}),
|
||||
new Error('Type of mockEvent message must start with "foo:"')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("invokeHook()", function() {
|
||||
let betaTestCalled = false;
|
||||
let plugins = new Map([
|
||||
|
||||
Reference in new issue
Block a user