mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-16 23:30:41 +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
@@ -266,7 +266,7 @@ describe("controller/src/routes", function() {
|
||||
});
|
||||
|
||||
it("should respond with 500 if the transfer failed", async function() {
|
||||
controller.forwardRequestToInstance = async (data, request) => {
|
||||
controller.sendToHostByInstanceId = async (request) => {
|
||||
throw new Error("Something went wrong");
|
||||
};
|
||||
let response;
|
||||
@@ -294,7 +294,7 @@ describe("controller/src/routes", function() {
|
||||
});
|
||||
assert.equal(response.statusCode, 500);
|
||||
assert.deepEqual(JSON.parse(response.body), { errors: ["Something went wrong"], request_errors: [] });
|
||||
controller.forwardRequestToInstance = async (data, request) => {
|
||||
controller.sendToHostByInstanceId = async (request) => {
|
||||
await new Promise(() => {});
|
||||
};
|
||||
response = await phin({
|
||||
@@ -312,12 +312,12 @@ describe("controller/src/routes", function() {
|
||||
});
|
||||
|
||||
it("should complete a valid transfer", async function() {
|
||||
controller.forwardRequestToInstance = async (request, data) => {
|
||||
controller.sendToHostByInstanceId = async (request) => {
|
||||
let stream = await phin({
|
||||
url: `http://localhost:${port}/api/stream/${data.stream_id}`,
|
||||
url: `http://localhost:${port}/api/stream/${request.streamId}`,
|
||||
});
|
||||
assert.equal(stream.body.toString(), "totally a zip file");
|
||||
return { save: data.filename };
|
||||
return request.name;
|
||||
};
|
||||
let response;
|
||||
response = await phin({
|
||||
@@ -332,12 +332,12 @@ describe("controller/src/routes", function() {
|
||||
assert.equal(response.statusCode, 200);
|
||||
});
|
||||
it("should complete a valid transfer with non-standerd mime type", async function() {
|
||||
controller.forwardRequestToInstance = async (request, data) => {
|
||||
controller.sendToHostByInstanceId = async (request) => {
|
||||
let stream = await phin({
|
||||
url: `http://localhost:${port}/api/stream/${data.stream_id}`,
|
||||
url: `http://localhost:${port}/api/stream/${request.streamId}`,
|
||||
});
|
||||
assert.equal(stream.body.toString(), "totally a zip file");
|
||||
return { save: data.filename };
|
||||
return request.name;
|
||||
};
|
||||
let response;
|
||||
response = await phin({
|
||||
|
||||
+17
-18
@@ -3,6 +3,7 @@ const assert = require("assert").strict;
|
||||
const path = require("path");
|
||||
|
||||
const libConfig = require("@clusterio/lib/config");
|
||||
const libData = require("@clusterio/lib/data");
|
||||
const Host = require("@clusterio/host/src/Host");
|
||||
|
||||
describe("Host testing", function() {
|
||||
@@ -30,7 +31,7 @@ describe("Host testing", function() {
|
||||
});
|
||||
|
||||
describe("class Host", function() {
|
||||
describe(".syncUserListsEventHandler()", function() {
|
||||
describe(".handleSyncUserListsEvent()", function() {
|
||||
let mockHost;
|
||||
beforeEach(function() {
|
||||
mockHost = {
|
||||
@@ -38,16 +39,14 @@ describe("Host testing", function() {
|
||||
whitelist: new Set(),
|
||||
banlist: new Map(),
|
||||
broadcasts: [],
|
||||
broadcastEventToInstance(message, event) {
|
||||
this.broadcasts.push(message["data"]);
|
||||
broadcastEventToInstance(event) {
|
||||
this.broadcasts.push(event);
|
||||
},
|
||||
syncUserListsEventHandler: Host.prototype.syncUserListsEventHandler,
|
||||
handleSyncUserListsEvent: Host.prototype.handleSyncUserListsEvent,
|
||||
syncLists(adminlist, banlist, whitelist) {
|
||||
return this.syncUserListsEventHandler({ "data": {
|
||||
"adminlist": adminlist,
|
||||
"banlist": banlist,
|
||||
"whitelist": whitelist,
|
||||
}});
|
||||
return this.handleSyncUserListsEvent(
|
||||
new libData.SyncUserListsEvent(adminlist, banlist, whitelist)
|
||||
);
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -57,8 +56,8 @@ describe("Host testing", function() {
|
||||
await mockHost.syncLists(["admin1", "admin2"], [], []);
|
||||
|
||||
assert.deepEqual(mockHost.broadcasts, [
|
||||
{ "name": "admin1", "admin": true },
|
||||
{ "name": "admin2", "admin": true },
|
||||
new libData.InstanceAdminlistUpdateEvent("admin1", true),
|
||||
new libData.InstanceAdminlistUpdateEvent("admin2", true),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -66,7 +65,7 @@ describe("Host testing", function() {
|
||||
mockHost.adminlist.add("admin1").add("admin2");
|
||||
await mockHost.syncLists(["admin1"], [], []);
|
||||
assert.deepEqual(mockHost.broadcasts, [
|
||||
{ "name": "admin2", "admin": false },
|
||||
new libData.InstanceAdminlistUpdateEvent("admin2", false),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -75,8 +74,8 @@ describe("Host testing", function() {
|
||||
await mockHost.syncLists([], [], ["player1", "player2"]);
|
||||
|
||||
assert.deepEqual(mockHost.broadcasts, [
|
||||
{ "name": "player1", "whitelisted": true },
|
||||
{ "name": "player2", "whitelisted": true },
|
||||
new libData.InstanceWhitelistUpdateEvent("player1", true),
|
||||
new libData.InstanceWhitelistUpdateEvent("player2", true),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -85,7 +84,7 @@ describe("Host testing", function() {
|
||||
await mockHost.syncLists([], [], ["player1"]);
|
||||
|
||||
assert.deepEqual(mockHost.broadcasts, [
|
||||
{ "name": "player2", "whitelisted": false },
|
||||
new libData.InstanceWhitelistUpdateEvent("player2", false),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -94,8 +93,8 @@ describe("Host testing", function() {
|
||||
await mockHost.syncLists([], [["badie1", "greifing"], ["badie2", "annoying"]], []);
|
||||
|
||||
assert.deepEqual(mockHost.broadcasts, [
|
||||
{ "name": "badie1", "banned": true, "reason": "greifing" },
|
||||
{ "name": "badie2", "banned": true, "reason": "annoying" },
|
||||
new libData.InstanceBanlistUpdateEvent("badie1", true, "greifing"),
|
||||
new libData.InstanceBanlistUpdateEvent("badie2", true, "annoying"),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -104,7 +103,7 @@ describe("Host testing", function() {
|
||||
await mockHost.syncLists([], [["badie1", "greifing"]], []);
|
||||
|
||||
assert.deepEqual(mockHost.broadcasts, [
|
||||
{ "name": "badie2", "banned": false, "reason": "" },
|
||||
new libData.InstanceBanlistUpdateEvent("badie2", false, ""),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
+38
-61
@@ -3,23 +3,30 @@ const assert = require("assert").strict;
|
||||
const path = require("path");
|
||||
|
||||
const libConfig = require("@clusterio/lib/config");
|
||||
const libData = require("@clusterio/lib/data");
|
||||
const { wait } = require("@clusterio/lib/helpers");
|
||||
const PlayerStats = require("@clusterio/lib/PlayerStats");
|
||||
const Instance = require("@clusterio/host/src/Instance");
|
||||
const { MockConnector, MockServer } = require("../mock");
|
||||
|
||||
const addr = libData.Address.fromShorthand;
|
||||
|
||||
|
||||
describe("class Instance", function() {
|
||||
before(function() {
|
||||
libConfig.InstanceConfig.finalize();
|
||||
});
|
||||
|
||||
let src;
|
||||
let dst = addr({ hostId: 1 });
|
||||
let instance;
|
||||
let connector;
|
||||
beforeEach(async function() {
|
||||
let instanceConfig = new libConfig.InstanceConfig("host");
|
||||
await instanceConfig.init();
|
||||
instanceConfig.set("instance.name", "foo");
|
||||
connector = new MockConnector();
|
||||
src = addr({ instanceId: instanceConfig.get("instance.id") });
|
||||
connector = new MockConnector(src, dst);
|
||||
instance = new Instance({}, connector, "dir", "factorioDir", instanceConfig);
|
||||
instance.server = new MockServer();
|
||||
});
|
||||
@@ -57,19 +64,12 @@ describe("class Instance", function() {
|
||||
let stats = instance.playerStats.get("player");
|
||||
assert.deepEqual(
|
||||
connector.sentMessages[0],
|
||||
{
|
||||
seq: 1,
|
||||
type: "player_event_event",
|
||||
data: {
|
||||
type: "join",
|
||||
instance_id: instance.id,
|
||||
name: "player",
|
||||
stats: {
|
||||
join_count: 1,
|
||||
last_join_at: stats.lastJoinAt.getTime(),
|
||||
},
|
||||
},
|
||||
},
|
||||
new libData.MessageEvent(1, src, addr("controller"), "InstancePlayerUpdateEvent",
|
||||
new libData.InstancePlayerUpdateEvent("join", "player", undefined, new PlayerStats({
|
||||
join_count: 1,
|
||||
last_join_at: stats.lastJoinAt.getTime(),
|
||||
}))
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -105,23 +105,15 @@ describe("class Instance", function() {
|
||||
let stats = instance.playerStats.get("player");
|
||||
assert.deepEqual(
|
||||
connector.sentMessages[1],
|
||||
{
|
||||
seq: 2,
|
||||
type: "player_event_event",
|
||||
data: {
|
||||
type: "leave",
|
||||
instance_id: instance.id,
|
||||
name: "player",
|
||||
reason: "quit",
|
||||
stats: {
|
||||
join_count: 1,
|
||||
online_time_ms: stats.onlineTimeMs,
|
||||
last_join_at: stats.lastJoinAt.getTime(),
|
||||
last_leave_at: stats.lastLeaveAt.getTime(),
|
||||
last_leave_reason: "quit",
|
||||
},
|
||||
},
|
||||
},
|
||||
new libData.MessageEvent(2, src, addr("controller"), "InstancePlayerUpdateEvent",
|
||||
new libData.InstancePlayerUpdateEvent("leave", "player", "quit", new PlayerStats({
|
||||
join_count: 1,
|
||||
online_time_ms: stats.onlineTimeMs,
|
||||
last_join_at: stats.lastJoinAt.getTime(),
|
||||
last_leave_at: stats.lastLeaveAt.getTime(),
|
||||
last_leave_reason: "quit",
|
||||
}))
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -159,19 +151,12 @@ describe("class Instance", function() {
|
||||
let stats = instance.playerStats.get("foo");
|
||||
assert.deepEqual(
|
||||
connector.sentMessages[1],
|
||||
{
|
||||
seq: 2,
|
||||
type: "player_event_event",
|
||||
data: {
|
||||
type: "join",
|
||||
instance_id: instance.id,
|
||||
name: "foo",
|
||||
stats: {
|
||||
join_count: 1,
|
||||
last_join_at: stats.lastJoinAt.getTime(),
|
||||
},
|
||||
},
|
||||
},
|
||||
new libData.MessageEvent(2, src, addr("controller"), "InstancePlayerUpdateEvent",
|
||||
new libData.InstancePlayerUpdateEvent("join", "foo", undefined, new PlayerStats({
|
||||
join_count: 1,
|
||||
last_join_at: stats.lastJoinAt.getTime(),
|
||||
}))
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -183,23 +168,15 @@ describe("class Instance", function() {
|
||||
let stats = instance.playerStats.get("player");
|
||||
assert.deepEqual(
|
||||
connector.sentMessages[1],
|
||||
{
|
||||
seq: 2,
|
||||
type: "player_event_event",
|
||||
data: {
|
||||
type: "leave",
|
||||
instance_id: instance.id,
|
||||
name: "player",
|
||||
reason: "quit",
|
||||
stats: {
|
||||
join_count: 1,
|
||||
online_time_ms: stats.onlineTimeMs,
|
||||
last_join_at: stats.lastJoinAt.getTime(),
|
||||
last_leave_at: stats.lastLeaveAt.getTime(),
|
||||
last_leave_reason: "quit",
|
||||
},
|
||||
},
|
||||
},
|
||||
new libData.MessageEvent(2, src, addr("controller"), "InstancePlayerUpdateEvent",
|
||||
new libData.InstancePlayerUpdateEvent("leave", "player", "quit", new PlayerStats({
|
||||
join_count: 1,
|
||||
online_time_ms: stats.onlineTimeMs,
|
||||
last_join_at: stats.lastJoinAt.getTime(),
|
||||
last_leave_at: stats.lastLeaveAt.getTime(),
|
||||
last_leave_reason: "quit",
|
||||
}))
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+80
-107
@@ -21,8 +21,8 @@ const {
|
||||
|
||||
|
||||
async function getInstances() {
|
||||
let result = await libLink.messages.listInstances.send(getControl());
|
||||
return new Map(result.list.map(instance => [instance.id, instance]));
|
||||
let instances = await getControl().send(new libData.InstanceDetailsListRequest());
|
||||
return new Map(instances.map(instance => [instance.id, instance]));
|
||||
}
|
||||
|
||||
async function checkInstanceStatus(id, status) {
|
||||
@@ -45,7 +45,7 @@ async function uploadSave(instanceId, name, content) {
|
||||
}
|
||||
|
||||
async function deleteSave(instanceId, save) {
|
||||
await libLink.messages.deleteSave.send(getControl(), { instance_id: instanceId, save });
|
||||
await getControl().send(new libData.InstanceDeleteSaveRequest(instanceId, save));
|
||||
}
|
||||
|
||||
describe("Integration of Clusterio", function() {
|
||||
@@ -76,6 +76,7 @@ describe("Integration of Clusterio", function() {
|
||||
|
||||
let connectorB = new TestControlConnector(url, 2, tlsCa);
|
||||
connectorB.token = controlToken;
|
||||
connectorB.src = connectorA.src;
|
||||
let controlB = new TestControl(connectorB);
|
||||
connectorB._sessionToken = connectorA._sessionToken;
|
||||
connectorB._sessionTimeout = connectorA._sessionTimeout;
|
||||
@@ -89,36 +90,12 @@ describe("Integration of Clusterio", function() {
|
||||
|
||||
describe("queryLogRequestHandler", function() {
|
||||
it("should honnor the limit", async function() {
|
||||
let result = await libLink.messages.queryLog.send(getControl(), {
|
||||
all: true,
|
||||
controller: false,
|
||||
host_ids: [],
|
||||
instance_ids: [],
|
||||
max_level: null,
|
||||
limit: 10,
|
||||
order: "asc",
|
||||
});
|
||||
let result = await getControl().send(new libData.LogQueryRequest(true, false, [], [], null, 10, "asc"));
|
||||
assert.equal(result.log.length, 10);
|
||||
});
|
||||
it("should return entries by order", async function() {
|
||||
let first = await libLink.messages.queryLog.send(getControl(), {
|
||||
all: true,
|
||||
controller: false,
|
||||
host_ids: [],
|
||||
instance_ids: [],
|
||||
max_level: null,
|
||||
limit: 1,
|
||||
order: "asc",
|
||||
});
|
||||
let last = await libLink.messages.queryLog.send(getControl(), {
|
||||
all: true,
|
||||
controller: false,
|
||||
host_ids: [],
|
||||
instance_ids: [],
|
||||
max_level: null,
|
||||
limit: 1,
|
||||
order: "desc",
|
||||
});
|
||||
let first = await getControl().send(new libData.LogQueryRequest(true, false, [], [], null, 1, "asc"));
|
||||
let last = await getControl().send(new libData.LogQueryRequest(true, false, [], [], null, 1, "desc"));
|
||||
assert(first.log[0].timestamp < last.log[0].timestamp, "first log entry happened after last");
|
||||
});
|
||||
});
|
||||
@@ -183,8 +160,8 @@ describe("Integration of Clusterio", function() {
|
||||
assert(sawConnected, "No host update with status connected was sent");
|
||||
assert(sawDisconnected, "No host update with status disconnected was sent");
|
||||
|
||||
let result = await libLink.messages.listHosts.send(getControl());
|
||||
let hosts = new Map(result.list.map(instance => [instance.id, instance]));
|
||||
let result = await getControl().send(new libData.HostListRequest());
|
||||
let hosts = new Map(result.map(instance => [instance.id, instance]));
|
||||
assert(hosts.has(5), "Host list was not updated");
|
||||
});
|
||||
});
|
||||
@@ -196,9 +173,9 @@ describe("Integration of Clusterio", function() {
|
||||
await execCtl("controller config list");
|
||||
});
|
||||
it("should not leak auth_secret", async function() {
|
||||
let result = await libLink.messages.getControllerConfig.send(getControl());
|
||||
let result = await getControl().send(new libData.ControllerConfigGetRequest());
|
||||
let done = false;
|
||||
for (let group of result.serialized_config.groups) {
|
||||
for (let group of result.serializedConfig.groups) {
|
||||
if (group.name === "controller") {
|
||||
assert.equal(Object.prototype.hasOwnProperty.call(group.fields, "auth_secret"), false);
|
||||
done = true;
|
||||
@@ -211,9 +188,9 @@ describe("Integration of Clusterio", function() {
|
||||
describe("controller config set", function() {
|
||||
it("sets given config option", async function() {
|
||||
await execCtl('controller config set controller.name "Test Cluster"');
|
||||
let result = await libLink.messages.getControllerConfig.send(getControl());
|
||||
let result = await getControl().send(new libData.ControllerConfigGetRequest());
|
||||
let done = false;
|
||||
for (let group of result.serialized_config.groups) {
|
||||
for (let group of result.serializedConfig.groups) {
|
||||
if (group.name === "controller") {
|
||||
assert.equal(group.fields.name, "Test Cluster");
|
||||
done = true;
|
||||
@@ -289,7 +266,7 @@ describe("Integration of Clusterio", function() {
|
||||
describe("saveListUpdateEventHandler()", function() {
|
||||
it("should have triggered for the created save", function() {
|
||||
slowTest(this);
|
||||
assert.equal(getControl().saveListUpdates.slice(-1)[0].list[0].name, "world.zip");
|
||||
assert.equal(getControl().saveListUpdates.slice(-1)[0].saves[0].name, "world.zip");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -307,8 +284,7 @@ describe("Integration of Clusterio", function() {
|
||||
let exportPath = path.join("temp", "test", "static");
|
||||
await fs.remove(exportPath);
|
||||
await execCtl("instance export-data test");
|
||||
let result = await libLink.messages.getDefaultModPack.send(getControl());
|
||||
let modPack = libData.ModPack.fromJSON(result.mod_pack);
|
||||
let modPack = await getControl().send(new libData.ModPackGetDefaultRequest());
|
||||
let assets = modPack.exportManifest.assets;
|
||||
assert(Object.keys(assets).length > 1, "Export assets is empty");
|
||||
for (let key of ["settings", "prototypes", "item-metadata", "item-spritesheet", "locale"]) {
|
||||
@@ -357,8 +333,8 @@ describe("Integration of Clusterio", function() {
|
||||
let savesDir = path.join("temp", "test", "instances", "test", "saves");
|
||||
await fs.copy(path.join(savesDir, "world.zip"), path.join(savesDir, "_autosave1.zip"));
|
||||
await execCtl("instance start test");
|
||||
let result = await libLink.messages.listSaves.send(getControl(), { instance_id: 44 });
|
||||
let running = result.list.find(s => s.loaded);
|
||||
let saves = await getControl().sendTo(new libData.InstanceListSavesRequest(), { instanceId: 44 });
|
||||
let running = saves.find(s => s.loaded);
|
||||
assert(running.name !== "_autosave1.zip");
|
||||
});
|
||||
});
|
||||
@@ -367,15 +343,9 @@ describe("Integration of Clusterio", function() {
|
||||
it("sends the command", async function() {
|
||||
slowTest(this);
|
||||
await execCtl("instance send-rcon test technobabble");
|
||||
let { log } = await libLink.messages.queryLog.send(getControl(), {
|
||||
all: false,
|
||||
controller: false,
|
||||
host_ids: [],
|
||||
instance_ids: [44],
|
||||
max_level: null,
|
||||
limit: 10,
|
||||
order: "desc",
|
||||
});
|
||||
let { log } = await getControl().send(
|
||||
new libData.LogQueryRequest(false, false, [], [44], null, 10, "desc")
|
||||
);
|
||||
assert(log.some(info => /technobabble/.test(info.message)), "Command was not sent");
|
||||
});
|
||||
|
||||
@@ -486,41 +456,41 @@ describe("Integration of Clusterio", function() {
|
||||
|
||||
describe("user set-admin/whitelisted/banned", function() {
|
||||
async function getUsers() {
|
||||
let result = await libLink.messages.listUsers.send(getControl());
|
||||
return new Map(result.list.map(user => [user.name, user]));
|
||||
let users = await getControl().send(new libData.UserListRequest());
|
||||
return new Map(users.map(user => [user.name, user]));
|
||||
}
|
||||
|
||||
async function getUser(name) {
|
||||
return await libLink.messages.getUser.send(getControl(), { name });
|
||||
return await getControl().send(new libData.UserGetRequest(name));
|
||||
}
|
||||
|
||||
let lists = ["admin", "whitelisted", "banned"];
|
||||
let lists = [["admin", "isAdmin"], ["whitelisted", "isWhitelisted"], ["banned", "isBanned"]];
|
||||
it("should add and remove the given user to the list", async function() {
|
||||
slowTest(this);
|
||||
getControl().userUpdates = [];
|
||||
await libLink.messages.createUser.send(getControl(), { name: "list_test" });
|
||||
await getControl().send(new libData.UserCreateRequest("list_test"));
|
||||
let user = (await getUsers()).get("list_test");
|
||||
for (let list of lists) {
|
||||
assert.equal(user[`is_${list}`], false, `unexpected ${list} status`);
|
||||
await execCtl(`user set-${list} list_test`);
|
||||
for (let [listName, prop] of lists) {
|
||||
assert.equal(user[prop], false, `unexpected ${listName} status`);
|
||||
await execCtl(`user set-${listName} list_test`);
|
||||
}
|
||||
user = (await getUsers()).get("list_test");
|
||||
for (let list of lists) {
|
||||
assert.equal(user[`is_${list}`], true, `unexpected ${list} status`);
|
||||
let remove = { admin: "--revoke", whitelisted: "--remove", banned: "--pardon" }[list];
|
||||
await execCtl(`user set-${list} ${remove} list_test`);
|
||||
for (let [listName, prop] of lists) {
|
||||
assert.equal(user[prop], true, `unexpected ${listName} status`);
|
||||
let remove = { admin: "--revoke", whitelisted: "--remove", banned: "--pardon" }[listName];
|
||||
await execCtl(`user set-${listName} ${remove} list_test`);
|
||||
}
|
||||
user = (await getUsers()).get("list_test");
|
||||
for (let list of lists) {
|
||||
assert.equal(user[`is_${list}`], false, `unexpected ${list} status`);
|
||||
for (let [listName, prop] of lists) {
|
||||
assert.equal(user[prop], false, `unexpected ${listName} status`);
|
||||
}
|
||||
assert.equal(getControl().userUpdates.length, 7);
|
||||
});
|
||||
it("should not create the user if not instructed to", async function() {
|
||||
slowTest(this);
|
||||
for (let list of lists) {
|
||||
for (let [listName, prop] of lists) {
|
||||
try {
|
||||
await execCtl(`user set-${list} no_create_test`);
|
||||
await execCtl(`user set-${listName} no_create_test`);
|
||||
} catch (err) { /* ignore */ }
|
||||
}
|
||||
let user = (await getUsers()).get("no_create_test");
|
||||
@@ -529,10 +499,10 @@ describe("Integration of Clusterio", function() {
|
||||
it("should create the user if instructed to", async function() {
|
||||
slowTest(this);
|
||||
getControl().userUpdates = [];
|
||||
for (let list of lists) {
|
||||
await execCtl(`user set-${list} --create test_create_${list}`);
|
||||
let user = (await getUsers()).get(`test_create_${list}`);
|
||||
assert.equal(user && user[`is_${list}`], true, `user not created and added to ${list}`);
|
||||
for (let [listName, prop] of lists) {
|
||||
await execCtl(`user set-${listName} --create test_create_${listName}`);
|
||||
let user = (await getUsers()).get(`test_create_${listName}`);
|
||||
assert.equal(user && user[prop], true, `user not created and added to ${listName}`);
|
||||
}
|
||||
assert.equal(getControl().userUpdates.length, 3);
|
||||
});
|
||||
@@ -541,9 +511,9 @@ describe("Integration of Clusterio", function() {
|
||||
getControl().userUpdates = [];
|
||||
await execCtl("user set-banned --create test_ban_reason --reason a-reason");
|
||||
assert.equal(getControl().userUpdates.length, 1);
|
||||
assert.equal(getControl().userUpdates[0].ban_reason, "a-reason");
|
||||
assert.equal(getControl().userUpdates[0].banReason, "a-reason");
|
||||
let user = await getUser("test_ban_reason");
|
||||
assert.equal(user["ban_reason"], "a-reason");
|
||||
assert.equal(user.banReason, "a-reason");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -831,8 +801,8 @@ describe("Integration of Clusterio", function() {
|
||||
describe("mod-pack create", function() {
|
||||
it("should create a mod-pack", async function() {
|
||||
await execCtl("mod-pack create empty-pack 1.1.0");
|
||||
let response = await libLink.messages.listModPacks.send(getControl());
|
||||
assert(response.list.some(modPack => modPack.name === "empty-pack"), "created pack is not in the list");
|
||||
let modPacks = await getControl().send(new libData.ModPackListRequest());
|
||||
assert(modPacks.some(modPack => modPack.name === "empty-pack"), "created pack is not in the list");
|
||||
});
|
||||
it("should allow setting all fields", async function() {
|
||||
await execCtl(
|
||||
@@ -844,8 +814,8 @@ describe("Integration of Clusterio", function() {
|
||||
"--double-setting runtime-global MyDouble 12.25 " +
|
||||
"--string-setting runtime-per-user MyString a-string"
|
||||
);
|
||||
let response = await libLink.messages.listModPacks.send(getControl());
|
||||
let modPack = response.list.find(entry => entry.name === "full-pack");
|
||||
let modPacks = await getControl().send(new libData.ModPackListRequest());
|
||||
let modPack = modPacks.find(entry => entry.name === "full-pack");
|
||||
assert(modPack, "created mod pack not found");
|
||||
let reference = libData.ModPack.fromJSON({});
|
||||
reference.id = modPack.id;
|
||||
@@ -857,7 +827,7 @@ describe("Integration of Clusterio", function() {
|
||||
reference.settings["runtime-global"].set("MyInt", { value: 1235 });
|
||||
reference.settings["runtime-global"].set("MyDouble", { value: 12.25 });
|
||||
reference.settings["runtime-per-user"].set("MyString", { value: "a-string" });
|
||||
assert.deepEqual(libData.ModPack.fromJSON(modPack), reference);
|
||||
assert.deepEqual(modPack, reference);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -895,18 +865,18 @@ describe("Integration of Clusterio", function() {
|
||||
describe("mod-pack edit", function() {
|
||||
it("runs", async function() {
|
||||
await execCtl("mod-pack edit full-pack --factorio-version 1.2.0");
|
||||
let response = await libLink.messages.listModPacks.send(getControl());
|
||||
let modPack = response.list.find(entry => entry.name === "full-pack");
|
||||
let modPacks = await getControl().send(new libData.ModPackListRequest());
|
||||
let modPack = modPacks.find(entry => entry.name === "full-pack");
|
||||
assert(modPack, "created mod pack not found");
|
||||
assert.equal(modPack.factorio_version, "1.2.0");
|
||||
assert.equal(modPack.factorioVersion, "1.2.0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mod-pack delete", function() {
|
||||
it("deletes the pack", async function() {
|
||||
await execCtl("mod-pack delete full-pack");
|
||||
let response = await libLink.messages.listModPacks.send(getControl());
|
||||
let modPack = response.list.find(entry => entry.name === "full-pack");
|
||||
let modPacks = await getControl().send(new libData.ModPackListRequest());
|
||||
let modPack = modPacks.find(entry => entry.name === "full-pack");
|
||||
assert(!modPack, "mod pack not deleted");
|
||||
});
|
||||
});
|
||||
@@ -938,11 +908,14 @@ describe("Integration of Clusterio", function() {
|
||||
"version: 1.0.0\n" +
|
||||
"title: An Empty Mod\n" +
|
||||
"author: Me\n" +
|
||||
"contact: \n" +
|
||||
"homepage: \n" +
|
||||
"description: An empty mod for testing\n" +
|
||||
"factorio_version: 1.1\n" +
|
||||
"factorioVersion: 1.1\n" +
|
||||
"dependencies:\n" +
|
||||
`size: ${stat.size}\n` +
|
||||
`sha1: ${hash}\n`,
|
||||
`sha1: ${hash}\n` +
|
||||
"isDeleted: false\n",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -991,7 +964,7 @@ describe("Integration of Clusterio", function() {
|
||||
if (modUpdate.name !== "empty_mod" || modUpdate.version !== "1.0.0") {
|
||||
continue;
|
||||
}
|
||||
if (modUpdate.is_deleted) {
|
||||
if (modUpdate.isDeleted) {
|
||||
eventsNotSeen.delete("deleted");
|
||||
} else {
|
||||
eventsNotSeen.delete("updated");
|
||||
@@ -1018,11 +991,11 @@ describe("Integration of Clusterio", function() {
|
||||
it("should create the given role", async function() {
|
||||
let args = "--description \"A temp role\" --permissions core.control.connect";
|
||||
await execCtl(`role create temp ${args}`);
|
||||
let result = await libLink.messages.listRoles.send(getControl());
|
||||
let tempRole = result.list.find(role => role.name === "temp");
|
||||
let roles = await getControl().send(new libData.RoleListRequest());
|
||||
let tempRole = roles.find(role => role.name === "temp");
|
||||
assert.deepEqual(
|
||||
tempRole,
|
||||
{ id: 5, name: "temp", description: "A temp role", permissions: ["core.control.connect"] }
|
||||
new libData.RawRole(5, "temp", "A temp role", ["core.control.connect"])
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1031,28 +1004,28 @@ describe("Integration of Clusterio", function() {
|
||||
it("should modify the given role", async function() {
|
||||
let args = "--name new --description \"A new role\" --set-perms";
|
||||
await execCtl(`role edit temp ${args}`);
|
||||
let result = await libLink.messages.listRoles.send(getControl());
|
||||
let newRole = result.list.find(role => role.name === "new");
|
||||
assert.deepEqual(newRole, { id: 5, name: "new", description: "A new role", permissions: [] });
|
||||
let roles = await getControl().send(new libData.RoleListRequest());
|
||||
let newRole = roles.find(role => role.name === "new");
|
||||
assert.deepEqual(newRole, new libData.RawRole(5, "new", "A new role", []));
|
||||
});
|
||||
it("should add permissions with --add-perms", async function() {
|
||||
let args = "--name new --add-perms core.host.list core.instance.list";
|
||||
await execCtl(`role edit new ${args}`);
|
||||
let result = await libLink.messages.listRoles.send(getControl());
|
||||
let newRole = result.list.find(role => role.name === "new");
|
||||
let roles = await getControl().send(new libData.RoleListRequest());
|
||||
let newRole = roles.find(role => role.name === "new");
|
||||
assert.deepEqual(newRole.permissions, ["core.host.list", "core.instance.list"]);
|
||||
});
|
||||
it("should remove permissions with --remove-perms", async function() {
|
||||
let args = "--name new --remove-perms core.host.list";
|
||||
await execCtl(`role edit new ${args}`);
|
||||
let result = await libLink.messages.listRoles.send(getControl());
|
||||
let newRole = result.list.find(role => role.name === "new");
|
||||
let roles = await getControl().send(new libData.RoleListRequest());
|
||||
let newRole = roles.find(role => role.name === "new");
|
||||
assert.deepEqual(newRole.permissions, ["core.instance.list"]);
|
||||
});
|
||||
it("should grant default permissions with --grant-default", async function() {
|
||||
await execCtl("role edit new --grant-default");
|
||||
let result = await libLink.messages.listRoles.send(getControl());
|
||||
let newRole = result.list.find(role => role.name === "new");
|
||||
let roles = await getControl().send(new libData.RoleListRequest());
|
||||
let newRole = roles.find(role => role.name === "new");
|
||||
let defaultPermissions = [...libUsers.permissions.values()]
|
||||
.filter(p => p.grantByDefault)
|
||||
.map(p => p.name)
|
||||
@@ -1064,8 +1037,8 @@ describe("Integration of Clusterio", function() {
|
||||
describe("role delete", function() {
|
||||
it("should delete the given role", async function() {
|
||||
await execCtl("role delete new");
|
||||
let result = await libLink.messages.listRoles.send(getControl());
|
||||
let newRole = result.list.find(role => role.name === "new");
|
||||
let roles = await getControl().send(new libData.RoleListRequest());
|
||||
let newRole = roles.find(role => role.name === "new");
|
||||
assert(!newRole, "Role was not deleted");
|
||||
});
|
||||
});
|
||||
@@ -1080,8 +1053,8 @@ describe("Integration of Clusterio", function() {
|
||||
it("should create the given user", async function() {
|
||||
getControl().userUpdates = [];
|
||||
await execCtl("user create temp");
|
||||
let result = await libLink.messages.listUsers.send(getControl());
|
||||
let tempUser = result.list.find(user => user.name === "temp");
|
||||
let users = await getControl().send(new libData.UserListRequest());
|
||||
let tempUser = users.find(user => user.name === "temp");
|
||||
assert(tempUser, "user was not created");
|
||||
assert.equal(getControl().userUpdates.length, 1);
|
||||
assert.equal(getControl().userUpdates[0].name, "temp");
|
||||
@@ -1091,7 +1064,7 @@ describe("Integration of Clusterio", function() {
|
||||
describe("user revoke-token", function() {
|
||||
it("should kick existing sessions for the user", async function() {
|
||||
slowTest(this);
|
||||
await libLink.messages.createUser.send(getControl(), { name: "revokee" });
|
||||
await getControl().send(new libData.UserCreateRequest("revokee"));
|
||||
let tlsCa = await fs.readFile("test/file/tls/cert.pem");
|
||||
let connector = new TestControlConnector(url, 2, tlsCa);
|
||||
connector.token = jwt.sign(
|
||||
@@ -1112,8 +1085,8 @@ describe("Integration of Clusterio", function() {
|
||||
it("should set the roles on the user", async function() {
|
||||
getControl().userUpdates = [];
|
||||
await execCtl('user set-roles temp "Cluster Admin"');
|
||||
let result = await libLink.messages.listUsers.send(getControl());
|
||||
let tempUser = result.list.find(user => user.name === "temp");
|
||||
let users = await getControl().send(new libData.UserListRequest());
|
||||
let tempUser = users.find(user => user.name === "temp");
|
||||
assert.deepEqual(tempUser.roles, [0]);
|
||||
assert.equal(getControl().userUpdates.length, 1);
|
||||
});
|
||||
@@ -1123,11 +1096,11 @@ describe("Integration of Clusterio", function() {
|
||||
it("should delete the user", async function() {
|
||||
getControl().userUpdates = [];
|
||||
await execCtl("user delete temp");
|
||||
let result = await libLink.messages.listUsers.send(getControl());
|
||||
let tempUser = result.list.find(user => user.name === "temp");
|
||||
let users = await getControl().send(new libData.UserListRequest());
|
||||
let tempUser = users.find(user => user.name === "temp");
|
||||
assert(!tempUser, "user was note deleted");
|
||||
assert.equal(getControl().userUpdates.length, 1);
|
||||
assert.equal(getControl().userUpdates[0].is_deleted, true);
|
||||
assert.equal(getControl().userUpdates[0].isDeleted, true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+44
-42
@@ -23,9 +23,8 @@ require("../../plugins/subspace_storage/info");
|
||||
|
||||
|
||||
class TestControl extends libLink.Link {
|
||||
constructor(connector) {
|
||||
super("control", "controller", connector);
|
||||
libLink.attachAllMessages(this);
|
||||
constructor(connector, subscribe = true) {
|
||||
super(connector);
|
||||
this.hostUpdates = [];
|
||||
this.instanceUpdates = [];
|
||||
this.saveListUpdates = [];
|
||||
@@ -34,63 +33,67 @@ class TestControl extends libLink.Link {
|
||||
this.userUpdates = [];
|
||||
|
||||
this.connector.on("connect", () => {
|
||||
libLink.messages.setHostSubscriptions.send(
|
||||
this, { all: true, host_ids: [] }
|
||||
if (!subscribe) {
|
||||
return;
|
||||
}
|
||||
this.send(
|
||||
new libData.HostSetSubscriptionsRequest(true, [])
|
||||
).catch(err => logger.error(`Error setting host subscriptions:\n${err.stack}`));
|
||||
libLink.messages.setInstanceSubscriptions.send(
|
||||
this, { all: true, instance_ids: [] }
|
||||
this.send(
|
||||
new libData.InstanceDetailsSetSubscriptionsRequest(true, [])
|
||||
).catch(err => logger.error(`Error setting instance subscriptions:\n${err.stack}`));
|
||||
libLink.messages.setSaveListSubscriptions.send(
|
||||
this, { all: true, instance_ids: [] }
|
||||
this.send(
|
||||
new libData.InstanceSetSaveListSubscriptionsRequest(true, [])
|
||||
).catch(err => logger.error(`Error setting save list subscriptions:\n${err.stack}`));
|
||||
libLink.messages.setModSubscriptions.send(
|
||||
this, { all: true, mod_names: [] }
|
||||
this.send(
|
||||
new libData.ModSetSubscriptionsRequest(true, [])
|
||||
).catch(err => logger.error(`Error setting mod subscriptions:\n${err.stack}`));
|
||||
libLink.messages.setUserSubscriptions.send(
|
||||
this, { all: true, names: [] }
|
||||
this.send(
|
||||
new libData.UserSetSubscriptionsRequest(true, [])
|
||||
).catch(err => logger.error(`Error setting user subscriptions:\n${err.stack}`));
|
||||
});
|
||||
|
||||
this.register(libData.AccountUpdateEvent);
|
||||
this.register(libData.HostUpdateEvent, this.handleHostUpdateEvent.bind(this));
|
||||
this.register(libData.InstanceDetailsUpdateEvent, this.handleInstanceDetailsUpdateEvent.bind(this));
|
||||
this.register(libData.InstanceSaveListUpdateEvent, this.handleInstanceSaveListUpdateEvent.bind(this));
|
||||
this.register(libData.ModUpdateEvent, this.handleModUpdateEvent.bind(this));
|
||||
this.register(libData.ModPackUpdateEvent, this.handleModPackUpdateEvent.bind(this));
|
||||
this.register(libData.UserUpdateEvent, this.handleUserUpdateEvent.bind(this));
|
||||
}
|
||||
|
||||
async prepareDisconnectRequestHandler(message, request) {
|
||||
this.connector.setClosing();
|
||||
return await super.prepareDisconnectRequestHandler(message, request);
|
||||
async handleHostUpdateEvent(event) {
|
||||
this.hostUpdates.push(event.update);
|
||||
}
|
||||
|
||||
async debugWsMessageEventHandler() { }
|
||||
|
||||
async accountUpdateEventHandler() { }
|
||||
|
||||
async hostUpdateEventHandler(message) {
|
||||
this.hostUpdates.push(message.data);
|
||||
async handleInstanceDetailsUpdateEvent(event) {
|
||||
this.instanceUpdates.push(event.details);
|
||||
}
|
||||
|
||||
async instanceUpdateEventHandler(message) {
|
||||
this.instanceUpdates.push(message.data);
|
||||
async handleInstanceSaveListUpdateEvent(event) {
|
||||
this.saveListUpdates.push(event);
|
||||
}
|
||||
|
||||
async saveListUpdateEventHandler(message) {
|
||||
this.saveListUpdates.push(message.data);
|
||||
async handleModUpdateEvent(event) {
|
||||
this.modUpdates.push(event.mod);
|
||||
}
|
||||
|
||||
async modUpdateEventHandler(message) {
|
||||
this.modUpdates.push(message.data.mod);
|
||||
async handleModPackUpdateEvent(event) {
|
||||
this.modPackUpdates.push(event.modPack);
|
||||
}
|
||||
|
||||
async modPackUpdateEventHandler(message) {
|
||||
this.modPackUpdates.push(message.data.mod_pack);
|
||||
async handleUserUpdateEvent(event) {
|
||||
this.userUpdates.push(event.user);
|
||||
}
|
||||
|
||||
async userUpdateEventHandler(message) {
|
||||
this.userUpdates.push(message.data);
|
||||
}
|
||||
|
||||
async logMessageEventHandler() { }
|
||||
}
|
||||
|
||||
class TestControlConnector extends libLink.WebSocketClientConnector {
|
||||
register() {
|
||||
this.sendHandshake("register_control", { token: this.token, agent: "clusterioctl", version: "test" });
|
||||
this.sendHandshake(new libData.MessageRegisterControl(new libData.RegisterControlData(
|
||||
this.token,
|
||||
"clusterioctl",
|
||||
"test",
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,8 +146,7 @@ async function execCtl(...args) {
|
||||
}
|
||||
|
||||
async function sendRcon(instanceId, command) {
|
||||
let response = await libLink.messages.sendRcon.send(control, { instance_id: instanceId, command });
|
||||
return response.result;
|
||||
return await control.sendTo(new libData.InstanceSendRconRequest(command), { instanceId });
|
||||
}
|
||||
|
||||
function getControl() {
|
||||
@@ -228,9 +230,9 @@ before(async function() {
|
||||
testPack.factorioVersion = "1.1.0";
|
||||
testPack.mods.set("clusterio_lib", { name: "clusterio_lib", enabled: true, version: "0.1.2" });
|
||||
testPack.mods.set("subspace_storage", { name: "subspace_storage", enabled: true, version: "1.99.8" });
|
||||
await libLink.messages.createModPack.send(control, { mod_pack: testPack.toJSON() });
|
||||
await libLink.messages.setControllerConfigField.send(
|
||||
control, { field: "controller.default_mod_pack_id", value: "12" }
|
||||
await control.sendTo(new libData.ModPackCreateRequest(testPack), "controller");
|
||||
await control.sendTo(
|
||||
new libData.ControllerConfigSetFieldRequest("controller.default_mod_pack_id", "12"), "controller"
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -15,10 +15,17 @@ describe("Integration of lib/link", function() {
|
||||
before(async function() {
|
||||
tlsCa = await fs.readFile("test/file/tls/cert.pem");
|
||||
});
|
||||
it("should emitt an error if authentication failed", async function() {
|
||||
beforeEach(async function() {
|
||||
controlConnector = new TestControlConnector(url, 0.2, tlsCa);
|
||||
controlConnector.token = token;
|
||||
control = new TestControl(controlConnector, false);
|
||||
});
|
||||
afterEach(async function() {
|
||||
await controlConnector.disconnect();
|
||||
});
|
||||
|
||||
it("should emitt an error if authentication failed", async function() {
|
||||
controlConnector.token = "gibberish";
|
||||
control = new TestControl(controlConnector);
|
||||
await assert.rejects(
|
||||
controlConnector.connect(),
|
||||
new Error("Authentication failed: jwt malformed")
|
||||
@@ -26,28 +33,29 @@ describe("Integration of lib/link", function() {
|
||||
});
|
||||
|
||||
it("should connect with proper credentials", async function() {
|
||||
controlConnector = new TestControlConnector(url, 0.2, tlsCa);
|
||||
controlConnector.token = token;
|
||||
control = new TestControl(controlConnector);
|
||||
await controlConnector.connect();
|
||||
});
|
||||
|
||||
it("should reconnect on connection lost", async function() {
|
||||
await controlConnector.connect();
|
||||
controlConnector._socket.close(1008, "Test");
|
||||
await events.once(controlConnector, "resume");
|
||||
});
|
||||
|
||||
it("should reconnect on connection terminated", async function() {
|
||||
await controlConnector.connect();
|
||||
controlConnector._socket.terminate();
|
||||
await events.once(controlConnector, "resume");
|
||||
});
|
||||
|
||||
it("should reconnect on connection heartbeat timeout", async function() {
|
||||
await controlConnector.connect();
|
||||
controlConnector.stopHeartbeat();
|
||||
await events.once(controlConnector, "resume");
|
||||
});
|
||||
|
||||
it("should invalidate on reconnection with bad session token", async function() {
|
||||
await controlConnector.connect();
|
||||
controlConnector._sessionToken = "blah";
|
||||
controlConnector.stopHeartbeat();
|
||||
await events.once(controlConnector, "invalidate");
|
||||
@@ -55,6 +63,7 @@ describe("Integration of lib/link", function() {
|
||||
});
|
||||
|
||||
it("should properly close connector if close is called during reconnect wait", async function() {
|
||||
await controlConnector.connect();
|
||||
controlConnector._socket.close(1008, "Test");
|
||||
controlConnector.once("drop", () => {
|
||||
controlConnector.close();
|
||||
|
||||
+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([
|
||||
|
||||
+13
-22
@@ -3,6 +3,7 @@ const events = require("events");
|
||||
const http = require("http");
|
||||
const express = require("express");
|
||||
|
||||
const libData = require("@clusterio/lib/data");
|
||||
const libHelpers = require("@clusterio/lib/helpers");
|
||||
const libLink = require("@clusterio/lib/link");
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
@@ -11,6 +12,7 @@ const libPrometheus = require("@clusterio/lib/prometheus");
|
||||
|
||||
const UserManager = require("@clusterio/controller/src/UserManager");
|
||||
|
||||
const addr = libData.Address.fromShorthand;
|
||||
|
||||
class MockLogger {
|
||||
child() { return this; }
|
||||
@@ -70,26 +72,17 @@ class MockSocket {
|
||||
}
|
||||
}
|
||||
|
||||
class MockConnector extends events.EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this._seq = 1;
|
||||
this.sentMessages = [];
|
||||
this.events = new Map();
|
||||
this.handshake = { address: "socket.test" };
|
||||
class MockConnector extends libLink.BaseConnector {
|
||||
constructor(src, dst) {
|
||||
super(src, dst);
|
||||
|
||||
this.connected = true;
|
||||
this.closing = false;
|
||||
this.sentMessages = [];
|
||||
}
|
||||
|
||||
send(type, data) {
|
||||
let seq = this._seq;
|
||||
this._seq += 1;
|
||||
let message = { seq, type, data };
|
||||
send(message) {
|
||||
this.sentMessages.push(message);
|
||||
setImmediate(() => this.emit("send", message));
|
||||
return seq;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +118,7 @@ class MockServer extends events.EventEmitter {
|
||||
|
||||
class MockInstance extends libLink.Link {
|
||||
constructor() {
|
||||
super("instance", "host", new MockConnector());
|
||||
super(new MockConnector(addr({ instanceId: 7357 }), addr({ hostId: 1 })));
|
||||
this.logger = new MockLogger();
|
||||
this.server = new MockServer();
|
||||
this.name = "test";
|
||||
@@ -152,15 +145,11 @@ class MockInstance extends libLink.Link {
|
||||
|
||||
class MockHost extends libLink.Link {
|
||||
constructor() {
|
||||
super("host", "controller", new MockConnector());
|
||||
super(new MockConnector(addr({ hostId: 1 }), addr("controller")));
|
||||
}
|
||||
}
|
||||
|
||||
class MockControl extends libLink.Link {
|
||||
constructor(connector) {
|
||||
super("control", "controller", connector);
|
||||
}
|
||||
}
|
||||
class MockControl extends libLink.Link { }
|
||||
|
||||
class MockController {
|
||||
constructor() {
|
||||
@@ -196,6 +185,9 @@ class MockController {
|
||||
this.hosts = new Map();
|
||||
}
|
||||
|
||||
register() {
|
||||
}
|
||||
|
||||
getControllerUrl() {
|
||||
return "http://controller.example/";
|
||||
}
|
||||
@@ -230,7 +222,6 @@ async function createInstancePlugin(InstancePluginClass, info) {
|
||||
let instance = new MockInstance();
|
||||
let host = new MockHost();
|
||||
let plugin = new InstancePluginClass(info, instance, host);
|
||||
libPlugin.attachPluginMessages(instance, plugin);
|
||||
await plugin.init();
|
||||
return plugin;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user