mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-16 15:30:41 +09:00
Merge branch 'master' into feature/datastore
This commit is contained in:
102 files changed
+1252
-366
No files matched your search
@@ -1,14 +1,36 @@
|
||||
"use strict";
|
||||
const assert = require("assert").strict;
|
||||
const { Controller } = require("@clusterio/controller");
|
||||
const { ControllerConfig } = require("@clusterio/lib");
|
||||
const { ControllerConfig, Address, RequestError } = require("@clusterio/lib");
|
||||
const { EventEmitter } = require("stream");
|
||||
|
||||
class MockEvent {}
|
||||
|
||||
class MockInstanceConfig extends EventEmitter {
|
||||
constructor(data = new Map()) {
|
||||
super();
|
||||
this._data = data;
|
||||
}
|
||||
|
||||
get(field) {
|
||||
return this._data.get(field);
|
||||
}
|
||||
|
||||
set(field, value) {
|
||||
return this._data.set(field, value);
|
||||
}
|
||||
}
|
||||
|
||||
describe("controller/src/Controller", function() {
|
||||
describe("class Controller", function() {
|
||||
/** @type {Controller} */
|
||||
let controller;
|
||||
before(function() {
|
||||
let controller, mockInstanceConfig;
|
||||
before(async function() {
|
||||
controller = new Controller({}, [], "", new ControllerConfig("controller"));
|
||||
mockInstanceConfig = new MockInstanceConfig(new Map([
|
||||
["instance.id", 100], ["instance.name", "test"], ["factorio.settings", []],
|
||||
]));
|
||||
await controller.instanceCreate(mockInstanceConfig);
|
||||
});
|
||||
function check(list, ip, present = true) {
|
||||
if (present === false) {
|
||||
@@ -50,5 +72,112 @@ describe("controller/src/Controller", function() {
|
||||
check(list, "192.168.0.18", false);
|
||||
});
|
||||
});
|
||||
|
||||
describe(".sendRequest()", function() {
|
||||
it("should error on loopback", function() {
|
||||
assert.throws(
|
||||
() => controller.sendRequest(new MockEvent(), Address.fromShorthand("controller")),
|
||||
new Error(`Message would return back to sender ${Address.fromShorthand("controller")}.`)
|
||||
);
|
||||
});
|
||||
it("should error on invalid controller", function() {
|
||||
assert.throws(
|
||||
() => controller.sendRequest(new MockEvent(), Address.fromShorthand({ controlId: 99 })),
|
||||
new RequestError("Target control connection does not exist.")
|
||||
);
|
||||
});
|
||||
it("should error on invalid instance", function() {
|
||||
assert.throws(
|
||||
() => controller.sendRequest(new MockEvent(), Address.fromShorthand({ instanceId: 99 })),
|
||||
new RequestError("Instance with ID 99 does not exist")
|
||||
);
|
||||
});
|
||||
it("should error on unassigned instance", function() {
|
||||
mockInstanceConfig.set("instance.assigned_host", null);
|
||||
assert.throws(
|
||||
() => controller.sendRequest(new MockEvent(), Address.fromShorthand({ instanceId: 100 })),
|
||||
new RequestError("Instance is not assigned to a host")
|
||||
);
|
||||
});
|
||||
it("should error on instance with disconnected host", function() {
|
||||
mockInstanceConfig.set("instance.assigned_host", 99);
|
||||
assert.throws(
|
||||
() => controller.sendRequest(new MockEvent(), Address.fromShorthand({ instanceId: 100 })),
|
||||
new RequestError("Host containing instance is not connected")
|
||||
);
|
||||
});
|
||||
it("should error on invalid host", function() {
|
||||
assert.throws(
|
||||
() => controller.sendRequest(new MockEvent(), Address.fromShorthand({ hostId: 99 })),
|
||||
new RequestError("Host is not connected")
|
||||
);
|
||||
});
|
||||
it("should error on invalid broadcast", function() {
|
||||
// This is different to sendEvent because requests do not support broadcasting
|
||||
assert.throws(
|
||||
() => controller.sendRequest(new MockEvent(), new Address(Address.broadcast, 99)),
|
||||
new Error(`Unknown address type ${Address.broadcast}`)
|
||||
);
|
||||
});
|
||||
it("should error on invalid address", function() {
|
||||
assert.throws(
|
||||
() => controller.sendRequest(new MockEvent(), new Address(99, 99)),
|
||||
new Error("Unknown address type 99")
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(".sendEvent()", function() {
|
||||
it("should error on loopback", function() {
|
||||
assert.throws(
|
||||
() => controller.sendEvent(new MockEvent(), Address.fromShorthand("controller")),
|
||||
new Error(`Message would return back to sender ${Address.fromShorthand("controller")}.`)
|
||||
);
|
||||
});
|
||||
it("should error on invalid controller", function() {
|
||||
assert.throws(
|
||||
() => controller.sendEvent(new MockEvent(), Address.fromShorthand({ controlId: 99 })),
|
||||
new Error("Target control connection does not exist.")
|
||||
);
|
||||
});
|
||||
it("should error on invalid instance", function() {
|
||||
assert.throws(
|
||||
() => controller.sendEvent(new MockEvent(), Address.fromShorthand({ instanceId: 99 })),
|
||||
new Error("Instance with ID 99 does not exist")
|
||||
);
|
||||
});
|
||||
it("should error on unassigned instance", function() {
|
||||
mockInstanceConfig.set("instance.assigned_host", null);
|
||||
assert.throws(
|
||||
() => controller.sendEvent(new MockEvent(), Address.fromShorthand({ instanceId: 100 })),
|
||||
new Error("Instance is not assigned to a host")
|
||||
);
|
||||
});
|
||||
it("should error on instance with disconnected host", function() {
|
||||
mockInstanceConfig.set("instance.assigned_host", 99);
|
||||
assert.throws(
|
||||
() => controller.sendEvent(new MockEvent(), Address.fromShorthand({ instanceId: 100 })),
|
||||
new Error("Host containing instance is not connected")
|
||||
);
|
||||
});
|
||||
it("should error on invalid host", function() {
|
||||
assert.throws(
|
||||
() => controller.sendEvent(new MockEvent(), Address.fromShorthand({ hostId: 99 })),
|
||||
new Error("Host is not connected")
|
||||
);
|
||||
});
|
||||
it("should error on invalid broadcast", function() {
|
||||
assert.throws(
|
||||
() => controller.sendEvent(new MockEvent(), new Address(Address.broadcast, 99)),
|
||||
new Error("Unexpected broadcast target 99")
|
||||
);
|
||||
});
|
||||
it("should error on invalid address", function() {
|
||||
assert.throws(
|
||||
() => controller.sendEvent(new MockEvent(), new Address(99, 99)),
|
||||
new Error("Unknown address type 99")
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
"use strict";
|
||||
if (module === require.main) {
|
||||
process.stdout.write(JSON.stringify(process.argv.slice(2)));
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
"use strict";
|
||||
const child_process = require("child_process");
|
||||
const util = require("util");
|
||||
const assert = require("assert").strict;
|
||||
const path = require("path");
|
||||
|
||||
const { escapeArg } = require("../../packages/create/escape_arg");
|
||||
const execFile = util.promisify(child_process.execFile);
|
||||
|
||||
async function exec(file, args) {
|
||||
const { stdout, stderr } = await execFile(
|
||||
file,
|
||||
args.map(escapeArg),
|
||||
// eslint-disable-next-line node/no-process-env
|
||||
{ shell: true, cwd: __dirname, env: { ...process.env, pct: "%"} }
|
||||
);
|
||||
return { stdout: JSON.parse(stdout), stderr };
|
||||
}
|
||||
|
||||
const strings = [
|
||||
'"a"',
|
||||
"a sentence of text.",
|
||||
" irregular \tspaces ",
|
||||
'"C:\\path\\"',
|
||||
"C:\\path\\",
|
||||
'\\ "\\" \\\\ "\\\\" \\\\\\ "\\\\\\" \\\\\\\\ "\\\\\\\\" \\\\\\\\\\ "\\\\\\\\\\" \\\\\\\\\\\ "\\\\\\\\\\\\"',
|
||||
'"C:\\path"',
|
||||
"C:\\path",
|
||||
"%OS%",
|
||||
"!OS!",
|
||||
"😮",
|
||||
];
|
||||
for (let i=1; i < 128; i++) {
|
||||
const char = String.fromCodePoint(i);
|
||||
// Skip newline and carriage return because those are difficult to escape
|
||||
// Skip most alphanumeric characters as they don't behave differently to each other.
|
||||
if (/[\n\r1-9B-Zb-z]/.test(char)) {
|
||||
continue;
|
||||
}
|
||||
strings.push(char, `${char}${char}`, `${char}"`);
|
||||
}
|
||||
|
||||
// Test 100 strings at a time.
|
||||
const tests = [[]];
|
||||
for (const string of strings) {
|
||||
if (tests[tests.length - 1].length >= 100) {
|
||||
tests.push([]);
|
||||
}
|
||||
tests[tests.length - 1].push(string);
|
||||
}
|
||||
|
||||
|
||||
describe("create/escape_arg", function() {
|
||||
it("should correctly escape strings when args are forwarded", async function() {
|
||||
const ext = process.platform === "win32" ? ".cmd" : ".sh";
|
||||
for (const args of tests) {
|
||||
assert.deepEqual(
|
||||
await exec(`.${path.sep}forward_args${ext}`, ["echo_args.js", ...args]),
|
||||
{ stdout: args, stderr: "" }
|
||||
);
|
||||
}
|
||||
});
|
||||
it("should correctly escape strings when invoking node directly", async function() {
|
||||
for (const args of tests) {
|
||||
assert.deepEqual(
|
||||
await exec("node", ["echo_args.js", ...args]),
|
||||
{ stdout: args, stderr: "" }
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
@ECHO off
|
||||
REM this is how npm and package.json bin entries forwards arguments on Windows
|
||||
node.exe %*
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
# this is how package.json bin entries forwards arguments on Linux
|
||||
exec node "$@"
|
||||
@@ -206,6 +206,12 @@ describe("Integration of Clusterio", function() {
|
||||
});
|
||||
});
|
||||
it("should auto start instances with auto_start enabled", async function() {
|
||||
// On windows there's currently no way to automate graceful shutdown of the host
|
||||
// process as CTRL+C is some weird terminal thing and SIGINT isn't a thing.
|
||||
if (process.platform === "win32") {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
slowTest(this);
|
||||
|
||||
let hostProcess;
|
||||
|
||||
@@ -45,7 +45,7 @@ describe("Integration of create tool", function () {
|
||||
assert.equal(hostConfig["host.name"], "local");
|
||||
assert.equal(hostConfig["host.public_address"], "localhost");
|
||||
assert.equal(hostConfig["host.factorio_directory"], "test/factorio");
|
||||
assert.equal(hostConfig["host.controller_url"], "http://localhost:8099");
|
||||
assert.equal(hostConfig["host.controller_url"], "http://localhost:8099/");
|
||||
}).timeout(1200000);
|
||||
it("should create a new controller installation", async function () {
|
||||
this.skip();
|
||||
|
||||
@@ -5,12 +5,14 @@ const path = require("path");
|
||||
const { _exportLocale } = require("@clusterio/host/dist/node/src/export");
|
||||
const { FactorioServer } = require("@clusterio/host/dist/node/src/server");
|
||||
|
||||
const { factorioDir } = require("./index");
|
||||
|
||||
|
||||
describe("Integration of lib/factorio/export", function() {
|
||||
describe("exportLocale()", function() {
|
||||
it("returns a nested Map with base game locale information", async function() {
|
||||
let writePath = path.join("temp", "test", "server");
|
||||
let testServer = new FactorioServer("factorio", writePath, {});
|
||||
let testServer = new FactorioServer(factorioDir, writePath, {});
|
||||
await testServer.init();
|
||||
|
||||
let locale = await _exportLocale(testServer, new Map(), ["base"], "en");
|
||||
|
||||
@@ -126,15 +126,35 @@ async function get(urlPath) {
|
||||
return res;
|
||||
}
|
||||
|
||||
function loadJSON(filePath) {
|
||||
try {
|
||||
// eslint-disable-next-line node/no-sync
|
||||
return JSON.parse(fs.readFileSync(filePath, "utf8"));
|
||||
} catch (err) {
|
||||
if (err.code === "ENOENT") {
|
||||
return undefined;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function getFactorioDir(hostConfig) {
|
||||
const factorioDir = hostConfig?.["host.factorio_directory"] ?? "factorio";
|
||||
return path.join(factorioDir);
|
||||
}
|
||||
|
||||
let controllerProcess;
|
||||
let hostProcess;
|
||||
let control;
|
||||
|
||||
const baseHostConfig = loadJSON("config-host.json");
|
||||
|
||||
let url = "https://localhost:4443/";
|
||||
let controlToken = jwt.sign({ aud: "user", user: "test" }, Buffer.from("TestSecretDoNotUse", "base64"));
|
||||
let instancesDir = path.join("temp", "test", "instances");
|
||||
let modsDir = path.join("temp", "test", "mods");
|
||||
let databaseDir = path.join("temp", "test", "database");
|
||||
let factorioDir = getFactorioDir(baseHostConfig);
|
||||
let pluginListPath = path.join("temp", "test", "plugin-list.json");
|
||||
let controllerConfigPath = path.join("temp", "test", "config-controller.json");
|
||||
let hostConfigPath = path.join("temp", "test", "config-host.json");
|
||||
@@ -161,20 +181,30 @@ function getControl() {
|
||||
}
|
||||
|
||||
function spawn(name, cmd, waitFor) {
|
||||
// eslint-disable-next-line node/no-process-env
|
||||
const silent = process.env.SILENT_TEST;
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log(cmd);
|
||||
let parts = cmd.split(" ");
|
||||
let process = child_process.spawn(parts[0], parts.slice(1), { cwd: path.join("temp", "test") });
|
||||
let stdout = new LineSplitter({ readableObjectMode: true });
|
||||
stdout.on("data", line => {
|
||||
let stderr = new LineSplitter({ readableObjectMode: true });
|
||||
let onDataOut = line => {
|
||||
line = line.toString("utf8");
|
||||
if (waitFor.test(line)) {
|
||||
if (silent) {
|
||||
stdout.off("data", onDataOut);
|
||||
stderr.off("data", onDataErr);
|
||||
}
|
||||
resolve(process);
|
||||
}
|
||||
console.log(name, line);
|
||||
});
|
||||
let stderr = new LineSplitter({ readableObjectMode: true });
|
||||
stderr.on("data", line => { console.log(name, line.toString("utf8")); });
|
||||
};
|
||||
let onDataErr = line => {
|
||||
console.log(name, line.toString("utf8"));
|
||||
};
|
||||
stdout.on("data", onDataOut);
|
||||
stderr.on("data", onDataErr);
|
||||
process.stdout.pipe(stdout);
|
||||
process.stderr.pipe(stderr);
|
||||
});
|
||||
@@ -183,10 +213,17 @@ function spawn(name, cmd, waitFor) {
|
||||
before(async function() {
|
||||
this.timeout(40000);
|
||||
|
||||
// eslint-disable-next-line node/no-process-env
|
||||
const silent = process.env.SILENT_TEST;
|
||||
if (silent) {
|
||||
console.log("SILENT_TEST is present in env, loggers after bootstrap will be muted.");
|
||||
}
|
||||
|
||||
// Some integration tests may cause log events
|
||||
logger.add(new ConsoleTransport({
|
||||
level: "info",
|
||||
format: new lib.TerminalFormat(),
|
||||
filter: () => !silent,
|
||||
}));
|
||||
|
||||
// If fast test is enabled then output that it is
|
||||
@@ -206,6 +243,7 @@ before(async function() {
|
||||
|
||||
await fs.ensureDir(path.join("temp", "test"));
|
||||
|
||||
console.log("Building Mods");
|
||||
await fs.ensureDir(modsDir);
|
||||
await lib.build({
|
||||
build: true,
|
||||
@@ -232,6 +270,7 @@ before(async function() {
|
||||
}
|
||||
await fs.copyFile(`mods/${ssZip}`, `${modsDir}/${ssZip}`);
|
||||
|
||||
console.log("Setting Controller Config");
|
||||
await exec("node ../../packages/controller config set controller.auth_secret TestSecretDoNotUse");
|
||||
await exec("node ../../packages/controller config set controller.http_port 8880");
|
||||
await exec("node ../../packages/controller config set controller.https_port 4443");
|
||||
@@ -240,12 +279,14 @@ before(async function() {
|
||||
await exec("node ../../packages/controller config set controller.tls_certificate ../../test/file/tls/cert.pem");
|
||||
await exec("node ../../packages/controller config set controller.tls_private_key ../../test/file/tls/key.pem");
|
||||
|
||||
console.log("Setting Controller Plugins");
|
||||
await exec("node ../../packages/ctl plugin add ../../plugins/global_chat");
|
||||
await exec("node ../../packages/ctl plugin add ../../plugins/research_sync");
|
||||
await exec("node ../../packages/ctl plugin add ../../plugins/statistics_exporter");
|
||||
await exec("node ../../packages/ctl plugin add ../../plugins/subspace_storage");
|
||||
await exec("node ../../packages/ctl plugin add ../../plugins/player_auth");
|
||||
|
||||
console.log("Bootstrapping");
|
||||
await exec("node ../../packages/controller bootstrap create-admin test");
|
||||
await exec("node ../../packages/controller bootstrap create-ctl-config test");
|
||||
await exec("node ../../packages/ctl control-config set control.tls_ca ../../test/file/tls/cert.pem");
|
||||
@@ -253,7 +294,9 @@ before(async function() {
|
||||
controllerProcess = await spawn("controller:", "node ../../packages/controller run", /Started controller/);
|
||||
|
||||
await execCtl("host create-config --id 4 --name host --generate-token");
|
||||
await exec(`node ../../packages/host config set host.factorio_directory ${path.join("..", "..", "factorio")}`);
|
||||
|
||||
const relativeFactorioDir = path.isAbsolute(factorioDir) ? factorioDir : path.join("..", "..", factorioDir);
|
||||
await exec(`node ../../packages/host config set host.factorio_directory ${relativeFactorioDir}`);
|
||||
await exec("node ../../packages/host config set host.tls_ca ../../test/file/tls/cert.pem");
|
||||
|
||||
hostProcess = await spawn("host:", "node ../../packages/host run", /Started host/);
|
||||
@@ -317,6 +360,7 @@ module.exports = {
|
||||
instancesDir,
|
||||
modsDir,
|
||||
databaseDir,
|
||||
factorioDir,
|
||||
controllerConfigPath,
|
||||
hostConfigPath,
|
||||
controlConfigPath,
|
||||
|
||||
@@ -8,13 +8,13 @@ const lib = require("@clusterio/lib");
|
||||
const { FactorioServer, _getVersion } = require("@clusterio/host/dist/node/src/server");
|
||||
const { logger } = lib;
|
||||
|
||||
const { slowTest } = require("./index");
|
||||
const { slowTest, factorioDir } = require("./index");
|
||||
|
||||
|
||||
describe("Integration of host/src/server", function() {
|
||||
describe("_getVersion()", function() {
|
||||
it("should get a version from factorio's changelog.txt", async function() {
|
||||
let version = await _getVersion(path.join("factorio", "data", "changelog.txt"));
|
||||
let version = await _getVersion(path.join(factorioDir, "data", "changelog.txt"));
|
||||
if (!/^\d+\.\d+\.\d+$/.test(version)) {
|
||||
assert.fail(`Detected version '${version}' does not followed the format x.y.z`);
|
||||
}
|
||||
@@ -23,7 +23,7 @@ describe("Integration of host/src/server", function() {
|
||||
|
||||
describe("class FactorioServer", function() {
|
||||
let writePath = path.join("temp", "test", "integration");
|
||||
let server = new FactorioServer("factorio", writePath, {});
|
||||
let server = new FactorioServer(factorioDir, writePath, {});
|
||||
let logFile;
|
||||
|
||||
before(async function() {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"use strict";
|
||||
const assert = require("assert").strict;
|
||||
const lib = require("@clusterio/lib");
|
||||
const { Address } = lib;
|
||||
|
||||
describe("lib/data/messages_core", function() {
|
||||
describe("class Address", function() {
|
||||
const controller = new Address(Address.controller, 0);
|
||||
const host1 = new Address(Address.host, 1);
|
||||
const host2 = new Address(Address.host, 2);
|
||||
const instance1 = new Address(Address.instance, 1);
|
||||
const instance2 = new Address(Address.instance, 2);
|
||||
const control1 = new Address(Address.control, 1);
|
||||
const control2 = new Address(Address.control, 2);
|
||||
const hostBr = new Address(Address.broadcast, Address.host);
|
||||
const instanceBr = new Address(Address.broadcast, Address.instance);
|
||||
const controlBr = new Address(Address.broadcast, Address.control);
|
||||
|
||||
it("Should correctly resolve addressedTo", function() {
|
||||
assert(controller.addressedTo(controller));
|
||||
assert(!controller.addressedTo(host1));
|
||||
assert(!controller.addressedTo(instance1));
|
||||
assert(!controller.addressedTo(control1));
|
||||
assert(!controller.addressedTo(hostBr));
|
||||
assert(!controller.addressedTo(instanceBr));
|
||||
assert(!controller.addressedTo(controlBr));
|
||||
|
||||
assert(!host1.addressedTo(controller));
|
||||
assert(host1.addressedTo(host1));
|
||||
assert(!host1.addressedTo(host2));
|
||||
assert(!host1.addressedTo(instance1));
|
||||
assert(!host1.addressedTo(control1));
|
||||
assert(!host1.addressedTo(hostBr));
|
||||
assert(!host1.addressedTo(instanceBr));
|
||||
assert(!host1.addressedTo(controlBr));
|
||||
|
||||
assert(!instance1.addressedTo(controller));
|
||||
assert(!instance1.addressedTo(host1));
|
||||
assert(instance1.addressedTo(instance1));
|
||||
assert(!instance1.addressedTo(instance2));
|
||||
assert(!instance1.addressedTo(control1));
|
||||
assert(!instance1.addressedTo(hostBr));
|
||||
assert(!instance1.addressedTo(instanceBr));
|
||||
assert(!instance1.addressedTo(controlBr));
|
||||
|
||||
assert(!control1.addressedTo(controller));
|
||||
assert(!control1.addressedTo(host1));
|
||||
assert(!control1.addressedTo(instance1));
|
||||
assert(control1.addressedTo(control1));
|
||||
assert(!control1.addressedTo(control2));
|
||||
assert(!control1.addressedTo(hostBr));
|
||||
assert(!control1.addressedTo(instanceBr));
|
||||
assert(!control1.addressedTo(controlBr));
|
||||
|
||||
assert(!hostBr.addressedTo(controller));
|
||||
assert(hostBr.addressedTo(host1));
|
||||
assert(hostBr.addressedTo(host2));
|
||||
assert(!hostBr.addressedTo(instance1));
|
||||
assert(!hostBr.addressedTo(control1));
|
||||
assert(!hostBr.addressedTo(hostBr));
|
||||
assert(!hostBr.addressedTo(instanceBr));
|
||||
assert(!hostBr.addressedTo(controlBr));
|
||||
|
||||
assert(!instanceBr.addressedTo(controller));
|
||||
assert(!instanceBr.addressedTo(host1));
|
||||
assert(instanceBr.addressedTo(instance1));
|
||||
assert(instanceBr.addressedTo(instance2));
|
||||
assert(!instanceBr.addressedTo(control1));
|
||||
assert(!instanceBr.addressedTo(hostBr));
|
||||
assert(!instanceBr.addressedTo(instanceBr));
|
||||
assert(!instanceBr.addressedTo(controlBr));
|
||||
|
||||
assert(!controlBr.addressedTo(controller));
|
||||
assert(!controlBr.addressedTo(host1));
|
||||
assert(!controlBr.addressedTo(instance1));
|
||||
assert(controlBr.addressedTo(control1));
|
||||
assert(controlBr.addressedTo(control2));
|
||||
assert(!controlBr.addressedTo(hostBr));
|
||||
assert(!controlBr.addressedTo(instanceBr));
|
||||
assert(!controlBr.addressedTo(controlBr));
|
||||
});
|
||||
});
|
||||
});
|
||||
+109
-52
@@ -101,13 +101,13 @@ describe("lib/subscriptions", function() {
|
||||
const connectorSetupDate = [{
|
||||
id: 0,
|
||||
request: new lib.SubscriptionRequest(RegisteredEvent.name, true),
|
||||
src: addr({ controlId: 0 }),
|
||||
dst: addr("controller"),
|
||||
dst: addr({ controlId: 0 }),
|
||||
src: addr("controller"),
|
||||
}, {
|
||||
id: 1,
|
||||
request: new lib.SubscriptionRequest(RegisteredEvent.name, true),
|
||||
src: addr({ controlId: 1 }),
|
||||
dst: addr("controller"),
|
||||
dst: addr({ controlId: 1 }),
|
||||
src: addr("controller"),
|
||||
}];
|
||||
|
||||
function getLink(id) {
|
||||
@@ -163,7 +163,7 @@ describe("lib/subscriptions", function() {
|
||||
subscriptions.handle(RegisteredEvent);
|
||||
for (let connectorData of connectorSetupDate) {
|
||||
subscriptions.handleRequest(
|
||||
getLink(connectorData.id), connectorData.request, connectorData.src, connectorData.dst
|
||||
getLink(connectorData.id), connectorData.request, connectorData.dst, connectorData.src
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -190,7 +190,7 @@ describe("lib/subscriptions", function() {
|
||||
const connectorData = connectorSetupDate[0];
|
||||
const request = new lib.SubscriptionRequest(RegisteredEvent.name, false);
|
||||
await subscriptions.handleRequest(
|
||||
getLink(connectorData.id), request, connectorData.src, connectorData.dst,
|
||||
getLink(connectorData.id), request, connectorData.dst, connectorData.src
|
||||
);
|
||||
subscriptions.broadcast(new RegisteredEvent());
|
||||
await onceConnectorSend(1);
|
||||
@@ -212,14 +212,22 @@ describe("lib/subscriptions", function() {
|
||||
subscriptions.handle(RegisteredEvent);
|
||||
for (let connectorData of connectorSetupDate) {
|
||||
subscriptions.handleRequest(
|
||||
getLink(connectorData.id), connectorData.request, connectorData.src, connectorData.dst
|
||||
getLink(connectorData.id), connectorData.request, connectorData.dst, connectorData.src
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("should remove an active subscription", async function() {
|
||||
it("should remove an active subscription link", async function() {
|
||||
const link = getLink(0);
|
||||
subscriptions.unsubscribe(link);
|
||||
subscriptions.unsubscribeLink(link);
|
||||
subscriptions.broadcast(new RegisteredEvent());
|
||||
await onceConnectorSend(1);
|
||||
assertNoEvent(0);
|
||||
assertLastEvent(1, RegisteredEvent);
|
||||
});
|
||||
it("should remove an active subscription address", async function() {
|
||||
const link = getLink(0);
|
||||
subscriptions.unsubscribeAddress(connectorSetupDate[0].dst);
|
||||
subscriptions.broadcast(new RegisteredEvent());
|
||||
await onceConnectorSend(1);
|
||||
assertNoEvent(0);
|
||||
@@ -251,7 +259,7 @@ describe("lib/subscriptions", function() {
|
||||
it("should accept a subscription", async function() {
|
||||
const request = new lib.SubscriptionRequest(RegisteredEvent.name, true);
|
||||
await subscriptions.handleRequest(
|
||||
getLink(0), request, connectorSetupDate[0].src, connectorSetupDate[0].dst
|
||||
getLink(0), request, connectorSetupDate[0].dst, connectorSetupDate[0].src
|
||||
);
|
||||
subscriptions.broadcast(new RegisteredEvent());
|
||||
await onceConnectorSend(0);
|
||||
@@ -260,7 +268,7 @@ describe("lib/subscriptions", function() {
|
||||
it("should accept an unsubscription", async function() {
|
||||
const request = new lib.SubscriptionRequest(RegisteredEvent.name, true);
|
||||
await subscriptions.handleRequest(
|
||||
getLink(0), request, connectorSetupDate[0].src, connectorSetupDate[0].dst
|
||||
getLink(0), request, connectorSetupDate[0].dst, connectorSetupDate[0].src
|
||||
);
|
||||
subscriptions.broadcast(new RegisteredEvent());
|
||||
await onceConnectorSend(0);
|
||||
@@ -271,7 +279,7 @@ describe("lib/subscriptions", function() {
|
||||
|
||||
const unsubRequest = new lib.SubscriptionRequest(RegisteredEvent.name, false);
|
||||
await subscriptions.handleRequest(
|
||||
getLink(0), unsubRequest, connectorSetupDate[0].src, connectorSetupDate[0].dst
|
||||
getLink(0), unsubRequest, connectorSetupDate[0].dst, connectorSetupDate[0].src
|
||||
);
|
||||
subscriptions.broadcast(new RegisteredEvent());
|
||||
assertNoEvent(0);
|
||||
@@ -283,7 +291,7 @@ describe("lib/subscriptions", function() {
|
||||
|
||||
const request = new lib.SubscriptionRequest(StringPermissionEvent.name, true);
|
||||
await subscriptions.handleRequest(
|
||||
getLink(0), request, connectorSetupDate[0].src, connectorSetupDate[0].dst
|
||||
getLink(0), request, connectorSetupDate[0].dst, connectorSetupDate[0].src
|
||||
);
|
||||
await onceConnectorSend(0);
|
||||
assertLastEvent(0, StringPermissionEvent);
|
||||
@@ -301,7 +309,7 @@ describe("lib/subscriptions", function() {
|
||||
|
||||
const request = new lib.SubscriptionRequest(StringPermissionEvent.name, true);
|
||||
await subscriptions.handleRequest(
|
||||
getLink(0), request, connectorSetupDate[0].src, connectorSetupDate[0].dst
|
||||
getLink(0), request, connectorSetupDate[0].dst, connectorSetupDate[0].src
|
||||
);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assertNoEvent(0);
|
||||
@@ -319,12 +327,12 @@ describe("lib/subscriptions", function() {
|
||||
registeredEvent = new lib.EventSubscriber(RegisteredEvent, mockControl);
|
||||
});
|
||||
|
||||
function assertLastRequest(request) {
|
||||
const Request = request.constructor;
|
||||
function assertLastMessage(message) {
|
||||
const Message = message.constructor;
|
||||
const lastMessage = mockControl.connector.sentMessages.at(-1);
|
||||
const name = Request.plugin ? `${Request.plugin}:${Request.name}` : Request.name;
|
||||
const name = Message.plugin ? `${Message.plugin}:${Message.name}` : Message.name;
|
||||
assert.equal(lastMessage.name, name);
|
||||
assert.deepEqual(lastMessage.data, request);
|
||||
assert.deepEqual(lastMessage.data, message);
|
||||
}
|
||||
|
||||
function assertNoMessageSent() {
|
||||
@@ -348,19 +356,19 @@ describe("lib/subscriptions", function() {
|
||||
let calledWith = null;
|
||||
let calledWithTwo = null;
|
||||
const item = { id: 1, updatedAtMs: 1, isDeleted: false };
|
||||
const event = new RegisteredEvent([item]);
|
||||
registeredEvent.subscribe(function(updates, synced) { calledWith = [updates, synced]; });
|
||||
registeredEvent.subscribe(function(updates, synced) { calledWithTwo = [updates, synced]; });
|
||||
await registeredEvent._handle(event);
|
||||
assert.deepEqual(calledWith, [[item], false]);
|
||||
assert.deepEqual(calledWithTwo, [[item], false]);
|
||||
const eventUpdate = new RegisteredEvent([item]);
|
||||
registeredEvent.subscribe(function(event, synced) { calledWith = [event, synced]; });
|
||||
registeredEvent.subscribe(function(event, synced) { calledWithTwo = [event, synced]; });
|
||||
await registeredEvent._handleEvent(eventUpdate);
|
||||
assert.deepEqual(calledWith, [eventUpdate, true]);
|
||||
assert.deepEqual(calledWithTwo, [eventUpdate, true]);
|
||||
});
|
||||
it("should allow unsubscribing from an event", async function() {
|
||||
let called = false;
|
||||
let event = new RegisteredEvent();
|
||||
function callback() { called = true; }
|
||||
const unsubscribe = registeredEvent.subscribe(callback);
|
||||
await registeredEvent._handle(event);
|
||||
await registeredEvent._handleEvent(event);
|
||||
assert.deepEqual(called, true);
|
||||
|
||||
called = false;
|
||||
@@ -368,7 +376,7 @@ describe("lib/subscriptions", function() {
|
||||
unsubscribe();
|
||||
// Wait for unsubscribe to happen.
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await registeredEvent._handle(event);
|
||||
await registeredEvent._handleEvent(event);
|
||||
assert.equal(called, false);
|
||||
});
|
||||
it("should not throw error on incorrectly unsubscribing multiple times", async function() {
|
||||
@@ -390,13 +398,13 @@ describe("lib/subscriptions", function() {
|
||||
const update3 = [{ id: 1, updatedAtMs: 4, isDeleted: true }];
|
||||
const snap0 = registeredEvent.getSnapshot();
|
||||
assert.deepEqual(snap0, [new Map(), false]);
|
||||
await registeredEvent._handle(new RegisteredEvent(update1));
|
||||
await registeredEvent._handleEvent(new RegisteredEvent(update1));
|
||||
const snap1 = registeredEvent.getSnapshot();
|
||||
assert.deepEqual(snap1, [new Map([[1, update1[0]]]), false]);
|
||||
await registeredEvent._handle(new RegisteredEvent(update2));
|
||||
await registeredEvent._handleEvent(new RegisteredEvent(update2));
|
||||
const snap2 = registeredEvent.getSnapshot();
|
||||
assert.deepEqual(snap2, [new Map([[1, update2[0]], [2, update2[1]]]), false]);
|
||||
await registeredEvent._handle(new RegisteredEvent(update3));
|
||||
await registeredEvent._handleEvent(new RegisteredEvent(update3));
|
||||
const snap3 = registeredEvent.getSnapshot();
|
||||
assert.deepEqual(snap3, [new Map([[2, update2[1]]]), false]);
|
||||
// validate previous snapshots were not modified
|
||||
@@ -406,59 +414,108 @@ describe("lib/subscriptions", function() {
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleConnectionEvent", function() {
|
||||
it("should be called on connector connect event", async function() {
|
||||
registeredEvent.subscribe(() => {});
|
||||
await events.once(mockControl.connector, "send");
|
||||
mockControl.connector.sentMessages.pop();
|
||||
|
||||
registeredEvent.control.connector.emit("connect");
|
||||
await events.once(mockControl.connector, "send");
|
||||
assertLastMessage(new lib.SubscriptionRequest(RegisteredEvent.name, true, -1));
|
||||
mockControl.connector.sentMessages.pop();
|
||||
|
||||
registeredEvent.handleConnectionEvent("connect");
|
||||
await events.once(mockControl.connector, "send");
|
||||
assertLastMessage(new lib.SubscriptionRequest(RegisteredEvent.name, true, -1));
|
||||
mockControl.connector.sentMessages.pop();
|
||||
|
||||
registeredEvent.handleConnectionEvent("resume");
|
||||
await events.once(mockControl.connector, "send");
|
||||
assertLastMessage(new lib.SubscriptionRequest(RegisteredEvent.name, true, -1));
|
||||
});
|
||||
it("should set synced to false on connection close", async function() {
|
||||
registeredEvent.synced = true;
|
||||
registeredEvent.control.connector.emit("close");
|
||||
assert(!registeredEvent.synced, "synced was not set to false during close event");
|
||||
|
||||
registeredEvent.synced = true;
|
||||
registeredEvent.handleConnectionEvent("drop");
|
||||
assert(!registeredEvent.synced, "synced was not set to false during drop");
|
||||
|
||||
registeredEvent.synced = true;
|
||||
registeredEvent.handleConnectionEvent("close");
|
||||
assert(!registeredEvent.synced, "synced was not set to false during close");
|
||||
});
|
||||
it("should invoke callbacks on connector close", async function() {
|
||||
let calledWith;
|
||||
registeredEvent.subscribe((values, synced) => { calledWith = [values, synced]; });
|
||||
const [msg] = await events.once(mockControl.connector, "send");
|
||||
mockControl.connector.emit("message", new lib.MessageResponse(0, msg.dst, msg.src,
|
||||
lib.SubscriptionRequest.Response.fromJSON(false)
|
||||
));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert(registeredEvent.synced, "synced was not set to true before close");
|
||||
calledWith = undefined;
|
||||
|
||||
registeredEvent.control.connector.emit("close");
|
||||
assert(!registeredEvent.synced, "synced was not set to false");
|
||||
assert(calledWith !== undefined, "callback not called");
|
||||
assert.deepEqual(calledWith, [null, false]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("_updateSubscription()", function() {
|
||||
it("should do nothing if not connected", async function() {
|
||||
registeredEvent.control.connector.connected = false;
|
||||
it("should do nothing if connection is not valid", async function() {
|
||||
registeredEvent.control.connector.valid = false;
|
||||
registeredEvent.subscribe(() => true);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assertNoMessageSent();
|
||||
});
|
||||
it("should correctly request a subscription", async function() {
|
||||
const expected = new lib.SubscriptionRequest(RegisteredEvent.name, true, -1);
|
||||
registeredEvent.subscribe(() => true);
|
||||
await events.once(mockControl.connector, "send");
|
||||
assertLastRequest(expected);
|
||||
assertLastMessage(new lib.SubscriptionRequest(RegisteredEvent.name, true, -1));
|
||||
});
|
||||
it("should correctly request no subscriptions", async function() {
|
||||
const expected = new lib.SubscriptionRequest(RegisteredEvent.name, false, -1);
|
||||
it("should correctly request an unsubscription", async function() {
|
||||
function callback() {}
|
||||
const unsubscribe = registeredEvent.subscribe(callback);
|
||||
await events.once(mockControl.connector, "send");
|
||||
unsubscribe();
|
||||
await events.once(mockControl.connector, "send");
|
||||
assertLastRequest(expected);
|
||||
assertLastMessage(new lib.SubscriptionRequest(RegisteredEvent.name, false, -1));
|
||||
});
|
||||
it("should set synced and invoke callbacks when request is responded to", async function() {
|
||||
let calledWith;
|
||||
registeredEvent.subscribe((values, synced) => { calledWith = [values, synced]; });
|
||||
const [msg] = await events.once(mockControl.connector, "send");
|
||||
assert(!registeredEvent.synced, "synced was set before response");
|
||||
mockControl.connector.emit("message", new lib.MessageResponse(0, msg.dst, msg.src));
|
||||
mockControl.connector.emit("message", new lib.MessageResponse(0, msg.dst, msg.src,
|
||||
lib.SubscriptionRequest.Response.fromJSON(false)
|
||||
));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert(calledWith !== undefined, "callback not called");
|
||||
assert.deepEqual(calledWith, [[], true]);
|
||||
assert.deepEqual(calledWith, [null, true]);
|
||||
assert(registeredEvent.synced, "synced was not set");
|
||||
});
|
||||
it("should be called on connector connect event", async function() {
|
||||
const expected = new lib.SubscriptionRequest(RegisteredEvent.name, true, -1);
|
||||
registeredEvent._callbacks.push(() => {});
|
||||
registeredEvent.control.connector.emit("connect");
|
||||
await events.once(mockControl.connector, "send");
|
||||
assertLastRequest(expected);
|
||||
});
|
||||
it("should revert synced and invoke callbacks on connector close event", async function() {
|
||||
it("should set synced and invoke callbacks when request is responded to with data", async function() {
|
||||
let calledWith;
|
||||
registeredEvent.subscribe((values, synced) => { calledWith = [values, synced]; });
|
||||
const [msg] = await events.once(mockControl.connector, "send");
|
||||
mockControl.connector.emit("message", new lib.MessageResponse(0, msg.dst, msg.src));
|
||||
assert(!registeredEvent.synced, "synced was set before response");
|
||||
mockControl.connector.emit("message", new lib.MessageResponse(0, msg.dst, msg.src,
|
||||
lib.SubscriptionRequest.Response.fromJSON(true)
|
||||
));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
assert(registeredEvent.synced, "synced was not set before close");
|
||||
calledWith = undefined;
|
||||
registeredEvent.control.connector.emit("close");
|
||||
assert(!registeredEvent.synced, "synced was set before update");
|
||||
assert(calledWith === undefined, "callback called before update");
|
||||
const eventUpdate = new RegisteredEvent();
|
||||
registeredEvent._handleEvent(eventUpdate);
|
||||
|
||||
assert(registeredEvent.synced, "synced was not set");
|
||||
assert(calledWith !== undefined, "callback not called");
|
||||
assert.deepEqual(calledWith, [[], false]);
|
||||
assert(!registeredEvent.synced, "synced was not reset");
|
||||
assert.deepEqual(calledWith, [eventUpdate, true]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -72,6 +72,7 @@ class MockConnector extends lib.BaseConnector {
|
||||
constructor(src, dst) {
|
||||
super(src, dst);
|
||||
|
||||
this.valid = true;
|
||||
this.connected = true;
|
||||
this.hasSession = true;
|
||||
this.sentMessages = [];
|
||||
|
||||
Reference in new issue
Block a user