Add exp_server_list to replace expcore/external

The controller keeps a record per instance with its name, mod pack,
Factorio version, players online, status and address, and the instance
plugin pushes the list into lua over rcon. The readme and the connect
commands read it through modules/exp_server_list, so expcore/external
and its hardcoded server fallback are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-10-14 21:35:33 +00:00
1 parent b19bbbe5f3
commit 4d136853c9
31 files changed
+1367 -307

No files matched your search

+188
View File
@@ -0,0 +1,188 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { Controller, HostRecord, InstanceRecord } from "@clusterio/controller";
import entrypoint, { ControllerPlugin } from "../dist/node/controller.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js";
import * as messages from "../dist/node/messages.js";
// The plugin's config fields must be defined before an InstanceConfig can set them
lib.addPluginConfigFields([pluginDeclaration]);
for (const Message of pluginDeclaration.messages) {
lib.Link.register(Message);
}
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
/** Build the plugin around a real controller, which is side effect free while not started. */
async function startPlugin(t2, setup = () => {}) {
const controllerConfig = new lib.ControllerConfig("controller", {
"controller.database_directory": t2.testdir(),
});
const controller = new Controller(logger, [], controllerConfig);
setup(controller);
const broadcasts = [];
controller.subscriptions.broadcast = event => {
if (event instanceof messages.ServerUpdatesEvent) {
broadcasts.push(event);
}
};
const context = { controller, logger, plugin: pluginDeclaration, metrics: undefined };
const plugin = await ControllerPlugin.fromContext(context);
return { plugin, controller, broadcasts };
}
function addHost(controller, id, publicAddress = "") {
controller.hosts.set(new HostRecord(id, `host-${id}`, "2.0.0", new Map(), true, "", publicAddress));
}
function addInstance(controller, id, { hostId = 1, status = "running", gamePort, factorioVersion, fields = {} } = {}) {
const config = new lib.InstanceConfig("controller", {
"instance.id": id,
"instance.name": `instance-${id}`,
"instance.assigned_host": hostId,
...fields,
});
const record = new InstanceRecord(config, status, gamePort, factorioVersion);
controller.instances.records.set(record);
controller.instances.addInstanceHooks(record);
return record;
}
const subscription = since => new lib.SubscriptionRequest("exp_server_list:ServerUpdatesEvent", "subscribe", since);
const join = (controller, name, instanceId) => controller.users.getOrCreateUser(name).notifyJoin(instanceId);
t.test("entrypoint", async t2 => {
const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() });
const controller = new Controller(logger, [], controllerConfig);
await entrypoint({ controller, logger, plugin: pluginDeclaration, metrics: undefined });
const hooks = [
"instanceStatusChanged",
"instanceConfigFieldChanged",
"controllerConfigFieldChanged",
"playerEvent",
"modPacksUpdated",
];
for (const hook of hooks) {
t2.ok([...controller.hooks[hook].attached].includes("exp_server_list"), `attached to ${hook}`);
}
t2.ok(ControllerPlugin.get(controller), "other plugins can find it");
});
t.test("class ControllerPlugin", t2 => {
t2.test("builds a record for every instance on start", async t3 => {
const { plugin } = await startPlugin(t3, controller => {
addHost(controller, 1, "example.com");
addInstance(controller, 10, {
gamePort: 34197,
factorioVersion: "2.1.14",
fields: {
"exp_server_list.description": "Weekly reset",
"exp_server_list.hidden": true,
},
});
addInstance(controller, 11, {
status: "stopped",
factorioVersion: "latest",
fields: { "exp_server_list.short_name": "S11" },
});
});
const server = plugin.servers.get(10);
t3.equal(server.name, "instance-10");
t3.equal(server.shortName, "instance-10", "short name falls back to the name");
t3.equal(server.description, "Weekly reset");
t3.equal(server.hidden, true);
t3.equal(server.factorioVersion, "2.1.14");
t3.equal(server.address, "example.com:34197", "public address of the host and the game port");
t3.equal(server.status, "running");
const stopped = plugin.servers.get(11);
t3.equal(stopped.shortName, "S11");
t3.equal(stopped.factorioVersion, "", "the latest target is not a version");
t3.equal(stopped.address, "example.com", "host address alone without a game port");
});
t2.test("uses the mod pack of the instance or the default", async t3 => {
const { plugin, controller } = await startPlugin(t3, c => {
addHost(c, 1);
c.modPacks.setMany(lib.ModPack.defaultModPacks.map(pack => lib.ModPack.fromJSON(pack.toJSON())));
const packs = [...c.modPacks.values()];
c.config.set("controller.default_mod_pack_id", packs[0].id);
addInstance(c, 10);
addInstance(c, 11, { fields: { "factorio.mod_pack_id": packs[1].id } });
});
const packs = [...controller.modPacks.values()];
t3.equal(plugin.servers.get(10).modPackName, packs[0].name, "the default mod pack");
t3.equal(plugin.servers.get(11).modPackName, packs[1].name, "the instance mod pack");
t3.equal(plugin.servers.get(10).address, "", "no address while the host has none");
});
t2.test("counts players only while running", async t3 => {
const { plugin, controller, broadcasts } = await startPlugin(t3, c => {
addHost(c, 1);
addInstance(c, 10);
});
const instance = controller.instances.get(10);
join(controller, "alice", 10);
join(controller, "bob", 10);
await controller.hooks.playerEvent.invoke(instance, { type: "join", name: "bob" });
t3.equal(plugin.servers.get(10).playerCount, 2);
t3.equal(broadcasts.at(-1).updates[0].playerCount, 2, "the change is broadcast");
instance.status = "stopped";
await controller.hooks.instanceStatusChanged.invoke(instance, "running");
t3.equal(plugin.servers.get(10).playerCount, 0, "players left online by a crash are not counted");
});
t2.test("follows config, host and status changes", async t3 => {
const { plugin, controller, broadcasts } = await startPlugin(t3, c => {
addHost(c, 1);
addInstance(c, 10, { gamePort: 34197 });
});
const instance = controller.instances.getMutable(10);
instance.config.set("instance.name", "Weekly");
t3.equal(plugin.servers.get(10).name, "Weekly", "renames are picked up");
instance.config.set("exp_server_list.welcome", "Hello");
t3.equal(plugin.servers.get(10).welcome, "Hello", "plugin fields are picked up");
addHost(controller, 1, "example.com");
t3.equal(plugin.servers.get(10).address, "example.com:34197", "the public address once the host sends it");
const count = broadcasts.length;
addHost(controller, 1, "example.com");
t3.equal(broadcasts.length, count, "nothing is broadcast when nothing changed");
// What deleteInstance does once the host has deleted it
controller.instances.records.delete(instance);
await controller.hooks.instanceStatusChanged.invoke(instance, "running");
t3.equal(plugin.servers.get(10), undefined, "deleted instances are removed");
t3.equal(broadcasts.at(-1).updates[0].isDeleted, true, "and broadcast as deleted");
});
t2.test(".handleServerSubscription() sends servers updated since the last request", async t3 => {
const { plugin } = await startPlugin(t3, controller => {
addHost(controller, 1);
addInstance(controller, 10);
});
const all = await plugin.handleServerSubscription(subscription(0));
t3.equal(all.updates.length, 1);
const none = await plugin.handleServerSubscription(subscription(Date.now() + 1000));
t3.equal(none, null);
t3.equal((await plugin.handleServerListRequest()).length, 1);
});
t2.end();
});
t.test("ServerRecord round trips through json", async t2 => {
const record = new messages.ServerRecord(
1, "a", "b", "c", "d", "e", true, "Base", "2.1.14", 3, "running", "localhost:1", 5, true,
);
t2.same(messages.ServerRecord.fromJSON(record.toJSON()), record);
t2.ok(record.sameAs(messages.ServerRecord.fromJSON(record.toJSON())));
});
+122
View File
@@ -0,0 +1,122 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { Instance } from "@clusterio/host";
import { InstancePlugin } from "../dist/node/instance.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js";
import * as messages from "../dist/node/messages.js";
// The instance validates message classes against the link registry
for (const Message of pluginDeclaration.messages) {
lib.Link.register(Message);
}
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
class TestConnector extends lib.BaseConnector {
constructor() {
super(lib.Address.fromShorthand({ instanceId: 1 }), lib.Address.fromShorthand({ hostId: 1 }));
this.valid = true;
this.connected = true;
this.hasSession = true;
}
send() {}
}
function server(id, name = `instance-${id}`) {
return new messages.ServerRecord(id, name, name, "", "", "", false, "Base", "2.1.14", 0, "running", "");
}
/** Build a plugin around a real instance with spies on what leaves it. */
async function startPlugin(t2, servers = [server(1), server(2)]) {
const instanceConfig = new lib.InstanceConfig("host");
instanceConfig.set("instance.id", 1);
instanceConfig.set("instance.name", "test");
const instance = new Instance(
{ assignGamePort: () => 1 }, new TestConnector(), t2.testdir(), "factorioDir", instanceConfig
);
const state = { sent: [], rcons: [] };
instance.server = {
handle: () => {},
sendRcon: async command => {
state.rcons.push(command);
return "";
},
};
instance.sendTo = async (dst, request) => {
state.sent.push(request);
return request instanceof messages.ServerListRequest ? servers : undefined;
};
const context = { plugin: { name: "exp_server_list" }, instance, host: {}, logger };
const plugin = await InstancePlugin.fromContext(context);
return { plugin, instance, state };
}
/** The payload of a recorded rcon command. */
function decodeRcon(command) {
const match = command.match(/^\/sc exp_server_list\.receive_update\(helpers\.json_to_table\[(=+)\[(.*)\]\1\]\)$/s);
return JSON.parse(match[2]);
}
t.test("class InstancePlugin", t2 => {
t2.test(".onStart() subscribes and replaces the list in lua", async t3 => {
const { plugin, state } = await startPlugin(t3);
await plugin.onStart();
t3.ok(state.sent[0] instanceof lib.SubscriptionRequest, "subscribes to updates first");
t3.ok(state.sent[1] instanceof messages.ServerListRequest, "then lists the servers");
const payload = decodeRcon(state.rcons[0]);
t3.equal(payload.current_id, 1, "tells lua which server it is");
t3.equal(payload.replace, true);
t3.strictSame(payload.servers.map(entry => entry.short_name), ["instance-1", "instance-2"]);
});
t2.test(".handleServerUpdatesEvent() only sends while the game is up", async t3 => {
const { plugin, state } = await startPlugin(t3);
const event = new messages.ServerUpdatesEvent([server(2, "renamed")]);
await plugin.handleServerUpdatesEvent(event);
t3.strictSame(state.rcons, [], "nothing is sent before start");
await plugin.onStart();
state.rcons.length = 0;
await plugin.handleServerUpdatesEvent(event);
const payload = decodeRcon(state.rcons[0]);
t3.equal(payload.replace, false, "updates are merged");
t3.strictSame(payload.servers.map(entry => entry.name), ["renamed"]);
await plugin.onExit();
state.rcons.length = 0;
await plugin.handleServerUpdatesEvent(event);
t3.strictSame(state.rcons, [], "nothing is sent after exit");
});
t2.test(".onControllerConnectionEvent() syncs again after the controller restarts", async t3 => {
const { plugin, state } = await startPlugin(t3);
await plugin.onControllerConnectionEvent("connect");
t3.strictSame(state.sent, [], "nothing happens before start");
await plugin.onStart();
state.sent.length = 0;
state.rcons.length = 0;
await plugin.onControllerConnectionEvent("resume");
t3.strictSame(state.sent, [], "a resumed session keeps its subscription");
await plugin.onControllerConnectionEvent("connect");
t3.ok(state.sent[0] instanceof lib.SubscriptionRequest, "subscribes again");
t3.equal(decodeRcon(state.rcons[0]).replace, true, "and replaces the list");
});
t2.test(".luaSendServers() picks a long bracket the values do not close", async t3 => {
const { plugin, state } = await startPlugin(t3);
const name = "a]=]b]==]c";
await plugin.luaSendServers([server(3, name)], false);
t3.match(state.rcons[0], "json_to_table[===[", "uses a level not found in the json");
t3.equal(decodeRcon(state.rcons[0]).servers[0].name, name);
});
t2.end();
});
+7
View File
@@ -0,0 +1,7 @@
import path from "node:path";
import t from "tap";
import { reportLuaTests } from "../../test/lua/runner.js";
const envFile = path.join(import.meta.dirname, "module", "env.lua");
t.test("control.lua", t2 => reportLuaTests(t2, envFile, path.join(import.meta.dirname, "module", "control.lua")));
+105
View File
@@ -0,0 +1,105 @@
local Suite = ... --- @type Suite<ExpServerList.TestEnv>
Suite.test("nothing is known before the first update", function(env)
Suite.eq(env.ServerList.get_current(), nil, "no current server")
Suite.empty(env.ServerList.get_servers(), "no servers")
end)
Suite.test("receive_update() with replace swaps the whole list", function(env)
local List = env.ServerList
List.receive_update{ current_id = 1, replace = true, servers = { env.server(1), env.server(2) } }
List.receive_update{ current_id = 1, replace = true, servers = { env.server(1), env.server(3) } }
Suite.eq(List.get_current().id, 1, "the current server is set")
Suite.eq(List.get_server(2), nil, "servers missing from the new list are removed")
Suite.eq(List.get_server(3).name, "Server 3", "new servers are added")
local ids = env.events[2].server_ids
table.sort(ids)
Suite.eq(ids, { 1, 2, 3 }, "the event lists removed and added servers")
end)
Suite.test("receive_update() without replace changes only the given servers", function(env)
local List = env.ServerList
List.receive_update{ current_id = 1, replace = true, servers = { env.server(1), env.server(2), env.server(3) } }
List.receive_update{ current_id = 1, replace = false, servers = {
env.server(2, { player_count = 4 }),
{ id = 3, is_deleted = true },
} }
Suite.eq(List.get_server(1).name, "Server 1", "untouched servers stay")
Suite.eq(List.get_server(2).player_count, 4, "changed servers are replaced")
Suite.eq(List.get_server(3), nil, "deleted servers are removed")
local ids = env.events[2].server_ids
table.sort(ids)
Suite.eq(ids, { 2, 3 }, "the event lists only the given servers")
Suite.eq(env.events[2].name, List.on_servers_updated, "on_servers_updated is raised")
end)
Suite.test("get_servers() leaves out hidden servers and sorts by name", function(env)
local List = env.ServerList
List.receive_update{ current_id = 1, replace = true, servers = {
env.server(1, { name = "Charlie" }),
env.server(2, { name = "Alpha" }),
env.server(3, { name = "Bravo", hidden = true }),
} }
local names = {}
for index, server in ipairs(List.get_servers()) do
names[index] = server.name
end
Suite.eq(names, { "Alpha", "Charlie" }, "hidden servers are not listed")
Suite.eq(List.get_server(3).name, "Bravo", "but can still be looked up by id")
end)
Suite.test("find_servers() matches name, short name and id ignoring case", function(env)
local List = env.ServerList
List.receive_update{ current_id = 1, replace = true, servers = {
env.server(1, { name = "Public Weekly", short_name = "S1" }),
env.server(2, { name = "Modded", short_name = "S2" }),
env.server(37, { name = "Event", short_name = "Event" }),
} }
local function ids(search)
local rtn = {}
for index, server in ipairs(List.find_servers(search)) do
rtn[index] = server.id
end
return rtn
end
Suite.eq(ids("weekly"), { 1 }, "by name")
Suite.eq(ids("s2"), { 2 }, "by short name")
Suite.eq(ids("37"), { 37 }, "by id")
Suite.eq(ids("nothing"), {}, "no match")
end)
Suite.test("is_online() needs a running server with an address", function(env)
local List = env.ServerList
Suite.eq(List.is_online(env.server(1)), true, "running with an address")
Suite.eq(List.is_online(env.server(1, { status = "stopped" })), false, "stopped")
Suite.eq(List.is_online(env.server(1, { address = "" })), false, "no address")
end)
Suite.test("request_connection() connects to a server or an address", function(env)
local List = env.ServerList
local alice = env.add_player{ name = "alice" }
List.request_connection(alice, env.server(2, { description = "Weekly reset" }), true)
List.request_connection(alice, "example.com:34197")
Suite.eq(env.connections, {
{
to = "alice",
address = "localhost:34198",
name = { "exp-server-list.connect-name", "Server 2" },
description = { "exp-server-list.connect-description", "Weekly reset" },
},
{
to = "alice",
address = "example.com:34197",
name = { "exp-server-list.connect-name", { "exp-server-list.unknown-name" } },
description = { "exp-server-list.connect-description-asked", { "exp-server-list.unknown-description" } },
},
}, "players asked by someone else are told so")
end)
return Suite.run()
+63
View File
@@ -0,0 +1,63 @@
--[[-- Test environment for module/control.lua
Extends the shared stubs with a fresh copy of the server list module, a stub
of exp_util storage, and a helper to build the servers the instance plugin
sends.
Run as a chunk by test/lua/runner.js, receiving the shared folder. The suite
returned here becomes `...` in each test file.
]]
local shared_root = ... --- @type string
local source = assert(debug.getinfo(1, "S")).source:gsub("\\", "/")
local plugin_root = assert(source:match("^@(.*)/test/module/env%.lua$"))
local Framework = assert(loadfile(shared_root .. "/framework.lua"))() --- @type Framework
--- @class ExpServerList.TestEnv : Stubs
--- @field ServerList ExpServerList A fresh copy of the server list module
--- @field server fun(id: number, fields: table?): ExpServerList.Server A server as the controller sends it
--- @field connections table[] Calls to connect_to_server, with the player name as `to`
return Framework.suite(function(env)
--- @cast env ExpServerList.TestEnv
env.extend_requires{
["modules/exp_util/storage"] = {
register = function() end,
},
}
env.ServerList = assert(loadfile(plugin_root .. "/module/control.lua"))() --- @type ExpServerList
function env.server(id, fields)
local server = {
id = id,
name = "Server " .. id,
short_name = "S" .. id,
description = "",
welcome = "",
reset_time = "",
hidden = false,
mod_pack_name = "Base",
factorio_version = "2.1.14",
player_count = 0,
status = "running",
address = "localhost:" .. (34196 + id),
}
for key, value in pairs(fields or {}) do
server[key] = value
end
return server
end
env.connections = {}
local add_player = env.add_player
function env.add_player(params)
local player = add_player(params)
rawset(player, "connect_to_server", function(opts)
opts.to = player.name
env.connections[#env.connections + 1] = opts
end)
return player
end
return env
end)