Add UDP communication support for instances

Add opt-in UDP messaging between the host and the Factorio server using
the --enable-lua-udp option of Factorio 2.0.59+.  When
factorio.enable_lua_udp is set the instance binds a localhost UDP socket,
starts Factorio with --enable-lua-udp on factorio.lua_udp_port (random
if null, like the RCON port) and tells the clusterio module the host port
via clusterio_private.update_instance.

Data from Factorio is sent with clusterio_api.send_udp(channel, data) in
the same IPC format as send_json, so plugins receive it through the
existing ipc-<channel> events.  Packets not sent from the Lua UDP port
are ignored, as that is the only unauthenticated way into the IPC
handler.  Data to Factorio is sent with the new sendUdp method on
instances and instance plugins, and is dispatched in-game as
on_udp_packet_received events by polling helpers.recv_udp every tick
from the clusterio module.

Plugins requiring UDP declare the new LuaUdp feature flag, which like
SavePatching and ScriptCommands refuses to load the plugin on instances
without the option enabled.

Verified against a headless 2.1.17 server: send_udp and recv_udp are
silent no-ops when the option is off, so a stale port in a save that is
moved to an instance without UDP does no harm.  The integration test
matrix now starts the instance with UDP enabled on Factorio 2.0.59+ and
round trips a player event over it.

Closes #969

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Fable 5.1 committed 2026-10-15 16:38:28 +00:00
1 parent ec51adc71c
commit 788ae17657
15 files changed
+394 -17

No files matched your search

+65
View File
@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
import dgram from "node:dgram";
import events from "node:events";
import fs from "node:fs/promises";
import path from "node:path";
@@ -336,6 +337,70 @@ describe("host/server", function() {
});
});
describe("Lua UDP", function() {
let udpServer;
let received;
before(async function() {
// Stand-in for the Factorio server's --enable-lua-udp socket
udpServer = dgram.createSocket("udp4");
received = [];
udpServer.on("message", (msg, rinfo) => received.push([msg, rinfo]));
await events.once(udpServer.bind(0, "127.0.0.1"), "listening");
});
after(function() {
udpServer.close();
});
it("should not have a host port when not running", function() {
assert.equal(server.hostUdpPort, undefined);
});
it("should reject sendUdp when not enabled", async function() {
server._state = "running";
try {
await assert.rejects(server.sendUdp("data"), new Error("Lua UDP is not enabled"));
} finally {
server._state = "init";
}
});
it("should bind a socket, send and receive ipc over UDP", async function() {
server.enableLuaUdp = true;
server.luaUdpPort = udpServer.address().port;
await server._bindUdpSocket();
server._state = "running";
try {
assert(server.hostUdpPort > 0, "hostUdpPort not set");
await server.sendUdp("hello");
await server.sendUdp(Buffer.from("world"));
while (received.length < 2) {
await wait(1);
}
assert.equal(received[0][0].toString(), "hello");
assert.equal(received[1][0].toString(), "world");
assert.equal(received[0][1].port, server.hostUdpPort);
let ipcReceived = [];
let onIpc = content => ipcReceived.push(content);
server.on("ipc-udp_channel", onIpc);
let waiter = events.once(server, "ipc-udp_channel");
// Packets not from the Factorio server's port are ignored
let other = dgram.createSocket("udp4");
await events.once(other.bind(0, "127.0.0.1"), "listening");
other.send(Buffer.from('\f$ipc:udp_channel?j{"data":"bad"}'), server.hostUdpPort, "127.0.0.1");
udpServer.send(Buffer.from('\f$ipc:udp_channel?j{"data":"spam"}'), server.hostUdpPort, "127.0.0.1");
await waiter;
server.off("ipc-udp_channel", onIpc);
other.close();
assert.deepEqual(ipcReceived, [{ data: "spam" }]);
} finally {
server._resetState();
server.enableLuaUdp = false;
}
assert.equal(server._udpSocket, null);
assert.equal(server.hostUdpPort, undefined);
});
});
describe(".stop()", function() {
it("should handle server quitting on its own during stop", async function() {
server.shutdownTimeoutMs = 20;
+6 -1
View File
@@ -138,6 +138,10 @@ export function hasFactorio() {
return haveFactorioInstall;
}
export function getFactorioVersion() {
return latestFactorioVersion;
}
export async function get(urlPath) {
const url = new URL("https://localhost:4443");
url.pathname = urlPath;
@@ -170,6 +174,7 @@ let controllerProcess;
let hostProcess;
let control;
let haveFactorioInstall;
let latestFactorioVersion;
const baseHostConfig = loadJSON("config-host.json");
@@ -356,7 +361,7 @@ before(async function() {
controllerProcess = await spawnNode("controller:", "../../packages/controller run", /Started controller/);
const factorioVersions = (await _listFactorioVersions(factorioDir)).versions;
const latestFactorioVersion = [...factorioVersions.values()]
latestFactorioVersion = [...factorioVersions.values()]
.sort((a, b) => lib.integerFullVersion(b) - lib.integerFullVersion(a))[0];
haveFactorioInstall = factorioVersions.size > 0;
+25 -1
View File
@@ -6,7 +6,7 @@ import fs from "node:fs/promises";
import { slowTest, testMatrix } from "../common.js";
import {
execCtl, execCtlProcess, sendRcon, getControl,
requiresFactorio, hasFactorio, instancesDir,
requiresFactorio, hasFactorio, getFactorioVersion, instancesDir,
} from "./index.js";
const instId = 48;
@@ -21,6 +21,11 @@ const requireApi = [
"or package.loaded['__level__/modules/clusterio/api.lua']", // 2.0.0
].join(" ");
// --enable-lua-udp was added in Factorio 2.0.59
function hasLuaUdp() {
return lib.integerFullVersion(getFactorioVersion()) >= lib.integerFullVersion("2.0.59");
}
function getUser(name) {
return getControl().send(new lib.UserGetRequest(name));
}
@@ -111,6 +116,7 @@ describe("Clusterio Instance", function() {
await execCtl(`${instSetConfig} factorio.enable_whitelist true`);
await execCtl(`${instSetConfig} factorio.enable_save_patching ${savePatchingEnabled}`);
await execCtl(`${instSetConfig} factorio.enable_script_commands ${scriptCommandsEnabled}`);
await execCtl(`${instSetConfig} factorio.enable_lua_udp ${hasLuaUdp()}`);
await execCtl(`instance save create ${instName}`);
await execCtl(`instance start ${instName}`);
});
@@ -152,6 +158,24 @@ describe("Clusterio Instance", function() {
const userLeave = await getUser("JoiningPlayer");
assert(!userLeave.instances.has(instId), "Player is not shown as offline");
});
it("should respond to a player join and leave event sent over UDP", async function() {
// The host port is passed to the module by updateInstanceData on startup
if (!hasLuaUdp() || !scriptCommandsEnabled) {
this.skip();
}
await sendRcon(instId,
`/sc ${requireApi} api.send_udp("player_event",` +
"{ type='join', name='UdpPlayer' })"
);
const userJoin = await getUser("UdpPlayer");
assert(userJoin.instances.has(instId), "Player is not shown as online");
await sendRcon(instId,
`/sc ${requireApi} api.send_udp("player_event",` +
"{ type='leave', name='UdpPlayer', reason='quit' })"
);
const userLeave = await getUser("UdpPlayer");
assert(!userLeave.instances.has(instId), "Player is not shown as offline");
});
}
it("should respond to a player ban and unban event", async function() {
await execCtl(`${instSetConfig} factorio.sync_banlist bidirectional`);
+29
View File
@@ -340,6 +340,35 @@ describe("lib/config/definitions/validators", function() {
/requires script commands/
);
});
it("should validate against factorio.enable_lua_udp", function() {
class TestInstanceConfig extends InstanceConfig {
static fieldDefinitions = { ...InstanceConfig.fieldDefinitions };
}
lib.addPluginFieldDefinitions(
{ name: "lua_udp", features: ["LuaUdp"] },
"instanceConfigFields", TestInstanceConfig
);
const config = new TestInstanceConfig("controller", initialConfigFields);
// valid: does not require save patching or script commands
assert.doesNotThrow(() => config.set("factorio.enable_save_patching", false));
assert.doesNotThrow(() => config.set("factorio.enable_script_commands", false));
// valid: can have load disabled
assert.doesNotThrow(() => config.set("lua_udp.load_plugin", false));
// invalid: requires lua udp when loaded (disabled by default)
assert.throws(
() => config.set("lua_udp.load_plugin", true),
/requires Lua UDP/
);
// valid: requirement satisfied
assert.doesNotThrow(() => config.set("factorio.enable_lua_udp", true));
assert.doesNotThrow(() => config.set("lua_udp.load_plugin", true));
});
it("should allow when no feature flags are present", function() {
class TestInstanceConfig extends InstanceConfig {
static fieldDefinitions = { ...InstanceConfig.fieldDefinitions };