Files
factorio-clusterio/test/lib/plugin.js
T
Hornwitser bcd94709d2 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.
2023-04-23 13:19:46 +02:00

102 lines
3.7 KiB
JavaScript

"use strict";
const assert = require("assert").strict;
const mock = require("../mock");
const libPlugin = require("@clusterio/lib/plugin");
describe("lib/plugin", function() {
describe("class BaseInstancePlugin", function() {
let instancePlugin;
it("should be constructible", async function() {
instancePlugin = new libPlugin.BaseInstancePlugin({}, new mock.MockInstance(), {});
await instancePlugin.init();
});
it("should define defaults for hooks", async function() {
await instancePlugin.onMetrics();
await instancePlugin.onStart();
await instancePlugin.onStop();
instancePlugin.onExit();
await instancePlugin.onOutput({});
instancePlugin.onControllerConnectionEvent("connect");
await instancePlugin.onPrepareControllerDisconnect();
});
describe("sendRcon", function() {
it("should send commands out of order", async function() {
instancePlugin.instance.server.rconCommandResults.set("a", { time: 100, response: "a" });
instancePlugin.instance.server.rconCommandResults.set("b", { time: 50, response: "b" });
let a = instancePlugin.sendRcon("a");
let b = instancePlugin.sendRcon("b");
let result = await Promise.race([a, b]);
assert.equal(result, "b");
});
it("should propagate errors", async function() {
instancePlugin.instance.server.rconCommandResults.set("a", new Error("ref"));
await assert.rejects(instancePlugin.sendRcon("a"), new Error("ref"));
});
});
describe("sendOrderedRcon", function() {
it("should send commands in order", async function() {
instancePlugin.instance.server.rconCommandResults.set("a", { time: 100, response: "a" });
instancePlugin.instance.server.rconCommandResults.set("b", { time: 50, response: "b" });
let a = instancePlugin.sendOrderedRcon("a");
let b = instancePlugin.sendOrderedRcon("b");
let result = await Promise.race([a, b]);
assert.equal(result, "a");
});
it("should propagate errors", async function() {
instancePlugin.instance.server.rconCommandResults.set("a", new Error("ref"));
await assert.rejects(instancePlugin.sendOrderedRcon("a"), new Error("ref"));
});
});
});
describe("class BaseControllerPlugin", function() {
let controllerPlugin;
it("should be constructible", async function() {
controllerPlugin = new libPlugin.BaseControllerPlugin({}, {}, {}, new mock.MockLogger());
await controllerPlugin.init();
});
it("should define defaults for hooks", async function() {
await controllerPlugin.onInstanceStatusChanged({}, "running", "initialized");
await controllerPlugin.onControllerConfigFieldChanged({}, "foo", null);
await controllerPlugin.onInstanceConfigFieldChanged({}, {}, "foo", null);
await controllerPlugin.onMetrics();
await controllerPlugin.onShutdown();
controllerPlugin.onHostConnectionEvent({}, "connect");
await controllerPlugin.onPrepareHostDisconnect({});
});
});
describe("invokeHook()", function() {
let betaTestCalled = false;
let plugins = new Map([
["alpha", {
test: async function() { },
pass: async function(arg) { return arg; },
error: async function() { throw new Error("Test"); },
logger: new mock.MockLogger(),
}],
["beta", {
test: async function() { betaTestCalled = true; },
pass: async function() { },
error: async function() { },
logger: new mock.MockLogger(),
}],
]);
it("should invoke the hook on the plugin", async function() {
await libPlugin.invokeHook(plugins, "test");
assert(betaTestCalled, "Hook was not called");
});
it("should pass and return args", async function() {
let result = await libPlugin.invokeHook(plugins, "pass", 1234);
assert.deepEqual(result, [1234]);
});
it("should ignore errors", async function() {
await libPlugin.invokeHook(plugins, "error");
});
});
});