Move Factorio server implementation to host

Move Factorio related code in lib that's only used by the host into the
host package.
This commit is contained in:
Hornwitser committed 2023-07-28 16:03:29 +02:00
1 parent bc574ee1cb
commit 6af25e085c
13 files changed
+95 -100

No files matched your search

+4
View File
@@ -20,8 +20,12 @@
"dependencies": {
"@clusterio/lib": "^2.0.0-alpha.13",
"fs-extra": "^11.1.1",
"jimp": "^0.22.8",
"jszip": "^3.10.1",
"phin": "^3.7.0",
"pidusage": "^3.0.2",
"rcon-client": "^4.2.3",
"semver": "^7.5.4",
"set-blocking": "^2.0.0",
"winston": "^3.10.0",
"winston-daily-rotate-file": "^4.7.1",
+7 -3
View File
@@ -9,6 +9,10 @@ const util = require("util");
const lib = require("@clusterio/lib");
const { PlayerStats } = lib;
const { FactorioServer } = require("./server");
const { patch } = require("./patch");
const { exportData } = require("./export");
const instanceRconCommandDuration = new lib.Histogram(
"clusterio_instance_rcon_command_duration_seconds",
@@ -143,7 +147,7 @@ class Instance extends lib.Link {
// Valid statuses are stopped, starting, running, stopping, creating_save and exporting_data.
this._status = "stopped";
this._loadedSave = null;
this.server = new lib.FactorioServer(
this.server = new FactorioServer(
factorioDir, this._dir, serverOptions
);
@@ -823,7 +827,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
}
}
await lib.patch(this.path("saves", saveName), [...modules.values()]);
await patch(this.path("saves", saveName), [...modules.values()]);
return saveName;
}
@@ -1082,7 +1086,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
this.logger.info("Exporting data .....");
await this.syncMods();
let zip = await lib.exportData(this.server);
let zip = await exportData(this.server);
let content = await zip.generateAsync({ type: "nodebuffer" });
let url = new URL(this._host.config.get("host.controller_url"));
@@ -5,9 +5,8 @@ const path = require("path");
const Jimp = require("jimp");
const JSZip = require("jszip");
const libIni = require("../ini");
const libBuildMod = require("../../build_mod");
const libZipOps = require("../zip_ops");
const lib = require("@clusterio/lib");
const libBuildMod = require("@clusterio/lib/build_mod");
/**
* Generate the export mod needed for exportData
@@ -16,7 +15,7 @@ const libZipOps = require("../zip_ops");
* the server given, with dependencies generated for all the mods present in
* the server's mods folder.
*
* @param {module:lib.FactorioServer} server -
* @param {module:host/src/server.FactorioServer} server -
* The server to generate the export mod for.
* @memberof module:lib
*/
@@ -34,8 +33,7 @@ async function generateExportMod(server) {
clean: false,
build: true,
pack: true,
// XXX fix path when moving lib/factorio to host
sourceDir: path.join(__dirname, "..", "..", "..", "host", "lua", "export"),
sourceDir: path.join(__dirname, "..", "lua", "export"),
outputDir: server.writePath("mods"),
bumpPatch: false,
factorioVersion: server.version.replace(/\.\d+$/, ""),
@@ -57,13 +55,13 @@ async function loadZip(server, modVersions, mod) {
zipCache.set(zipPath, zip);
}
return zip.folder(libZipOps.findRoot(zip));
return zip.folder(lib.findRoot(zip));
}
/**
* Load the given Factorio file path into a Buffer
*
* @param {module:lib.FactorioServer} server -
* @param {module:host/src/server.FactorioServer} server -
* The server to load the file from.
* @param {Map<string, string>} modVersions - Mapping of mod to version used.
* @param {string} modPath - Factorio style path to the file to load.
@@ -250,7 +248,7 @@ function filterItems(prototypes) {
* Assembles and packs the icons for the item prototypes given into a single
* spritesheet and json file with meta data.
*
* @param {module:lib.FactorioServer} server -
* @param {module:host/src/server.FactorioServer} server -
* The server to generate the export mod for.
* @param {Map<string, string>} modVersions -
* Mapping of mod name to versions to get icons from.
@@ -321,7 +319,7 @@ async function exportItems(server, modVersions, items) {
* Parses and merges all the locales for the all the mods given through
* `modVersions` and `modOrder`.
*
* @param {module:lib.FactorioServer} server -
* @param {module:host/src/server.FactorioServer} server -
* The server to export the locale from.
* @param {Map<string, string>} modVersions -
* Mapping of mod name to version to export locale from.
@@ -349,7 +347,7 @@ async function exportLocale(server, modVersions, modOrder, languageCode) {
}
let baseLocaleFilePath = server.dataPath("base", "locale", languageCode, "base.cfg");
mergeLocale(libIni.parse(await fs.readFile(baseLocaleFilePath, "utf8")));
mergeLocale(lib.parse(await fs.readFile(baseLocaleFilePath, "utf8")));
for (let mod of modOrder) {
if (["core", "base", "export"].includes(mod)) {
@@ -367,7 +365,7 @@ async function exportLocale(server, modVersions, modOrder, languageCode) {
}
for (let file of zip.file(new RegExp(`locale\\/${languageCode}\\/.*\\.cfg`))) {
let content = await file.async("nodebuffer");
mergeLocale(libIni.parse(content.toString("utf8")));
mergeLocale(lib.parse(content.toString("utf8")));
}
}
@@ -377,7 +375,7 @@ async function exportLocale(server, modVersions, modOrder, languageCode) {
/**
* Export the locale and item icons for the given factorio server
*
* @param {module:lib.FactorioServer} server -
* @param {module:host/src/server.FactorioServer} server -
* The server to export the data from.
* @returns {Promise<JSZip>} zip file with exported data.
* @memberof module:lib
@@ -7,8 +7,7 @@ const JSZip = require("jszip");
const path = require("path");
const semver = require("semver");
const libHash = require("../hash");
const { findRoot } = require("../zip_ops");
const lib = require("@clusterio/lib");
const knownScenarios = {
@@ -179,7 +178,7 @@ function reorderDependencies(modules) {
*/
async function patch(savePath, modules) {
let zip = await JSZip.loadAsync(await fs.readFile(savePath));
let root = zip.folder(findRoot(zip));
let root = zip.folder(lib.findRoot(zip));
let patchInfoFile = root.file("clusterio.json");
let patchInfo;
@@ -190,7 +189,7 @@ async function patch(savePath, modules) {
// No info file present, try to detect if it's a known compatible scenario.
} else {
let controlStream = root.file("control.lua").nodeStream("nodebuffer");
let controlHash = await libHash.hashStream(controlStream);
let controlHash = await lib.hashStream(controlStream);
if (controlHash in knownScenarios) {
patchInfo = {
@@ -8,12 +8,7 @@ const util = require("util");
const crypto = require("crypto");
const rconClient = require("rcon-client");
const libErrors = require("../errors");
const libFileOps = require("../file_ops");
const libIni = require("../ini");
const { logger } = require("../logging");
const { escapeRegExp } = require("../helpers");
const { LineSplitter } = require("../stream");
const lib = require("@clusterio/lib");
/**
@@ -449,7 +444,7 @@ class FactorioServer extends events.EventEmitter {
this._version = null;
this._dataDir = null;
this._logger = options.logger || logger;
this._logger = options.logger || lib.logger;
this._targetVersion = options.version || "latest";
/** UDP port used for hosting the Factorio game server on */
this.gamePort = options.gamePort || randomDynamicPort();
@@ -483,9 +478,9 @@ class FactorioServer extends events.EventEmitter {
this._stripRegExp = new RegExp(
// The script printer formats paths using / on both windows and linux.
// But the save path is printed with \ on windows and / on linux.
`(${escapeRegExp(tempPath.replace(/\\/g, "/"))})|` +
`(${escapeRegExp(writePath)})|` +
`(\\.\\.\\.[${escapeRegExp(chars)}/]*?currently-playing/)`,
`(${lib.escapeRegExp(tempPath.replace(/\\/g, "/"))})|` +
`(${lib.escapeRegExp(writePath)})|` +
`(\\.\\.\\.[${lib.escapeRegExp(chars)}/]*?currently-playing/)`,
"g"
);
}
@@ -691,10 +686,10 @@ class FactorioServer extends events.EventEmitter {
}
_attachStdio() {
let stdout = new LineSplitter({ readableObjectMode: true });
let stdout = new lib.LineSplitter({ readableObjectMode: true });
stdout.on("data", line => { this._handleOutput(line, "stdout"); });
this._server.stdout.pipe(stdout);
let stderr = new LineSplitter({ readableObjectMode: true });
let stderr = new lib.LineSplitter({ readableObjectMode: true });
stderr.on("data", line => { this._handleOutput(line, "stderr"); });
this._server.stderr.pipe(stderr);
}
@@ -714,9 +709,9 @@ class FactorioServer extends events.EventEmitter {
if (this._state !== "stopping") {
if (signal === "SIGKILL") {
if (this._killed) {
this.emit("error", new libErrors.EnvironmentError("Factorio server was killed"));
this.emit("error", new lib.EnvironmentError("Factorio server was killed"));
} else {
this.emit("error", new libErrors.EnvironmentError(
this.emit("error", new lib.EnvironmentError(
"Factorio server was unexpectedly killed, is the system low on memory?"
));
}
@@ -729,13 +724,13 @@ class FactorioServer extends events.EventEmitter {
msg = `Factorio server was unexpectedly shut by down by signal ${signal}`;
}
this.emit("error", new libErrors.EnvironmentError(msg));
this.emit("error", new lib.EnvironmentError(msg));
} else if (this._unexpected.length === 1) {
this.emit("error", new libErrors.EnvironmentError(this._unexpected[0]));
this.emit("error", new lib.EnvironmentError(this._unexpected[0]));
} else {
this.emit("error", new libErrors.EnvironmentError(
this.emit("error", new lib.EnvironmentError(
"Factorio server unexpectedly shut down. Possible causes:"+
`\n- ${this._unexpected.join("\n- ")}`
));
@@ -751,9 +746,9 @@ class FactorioServer extends events.EventEmitter {
});
this._server.on("error", err => {
if (err.code === "EACCES") {
this.emit("error", new libErrors.EnvironmentError("Unable to run server: Permission denied"));
this.emit("error", new lib.EnvironmentError("Unable to run server: Permission denied"));
} else {
this.emit("error", new libErrors.EnvironmentError(`Unexpected error:\n${err.stack}`));
this.emit("error", new lib.EnvironmentError(`Unexpected error:\n${err.stack}`));
}
if (this._rconClient) {
@@ -823,7 +818,7 @@ class FactorioServer extends events.EventEmitter {
}
} catch (err) {
if (err.code === "EACCES") {
throw new libErrors.EnvironmentError("Unable to run server: Permission denied");
throw new lib.EnvironmentError("Unable to run server: Permission denied");
}
throw err;
} finally {
@@ -1132,23 +1127,23 @@ class FactorioServer extends events.EventEmitter {
}
async _writeConfigIni() {
let content = libIni.stringify({
let content = lib.stringify({
path: {
"read-data": this.dataPath(),
"write-data": this.writePath(),
},
});
await libFileOps.safeOutputFile(this.writePath("config.ini"), content);
await lib.safeOutputFile(this.writePath("config.ini"), content);
}
async _writeMapSettings(mapGenSettings, mapSettings) {
if (mapGenSettings) {
await libFileOps.safeOutputFile(
await lib.safeOutputFile(
this.writePath("map-gen-settings.json"), JSON.stringify(mapGenSettings, null, 4)
);
}
if (mapSettings) {
await libFileOps.safeOutputFile(
await lib.safeOutputFile(
this.writePath("map-settings.json"), JSON.stringify(mapSettings, null, 4)
);
}
-3
View File
@@ -16,12 +16,9 @@
"chalk": "^4.1.2",
"fast-deep-equal": "^3.1.3",
"fs-extra": "^11.1.1",
"jimp": "^0.22.8",
"jsonwebtoken": "^9.0.1",
"jszip": "^3.10.1",
"klaw": "^4.1.0",
"rcon-client": "^4.2.3",
"semver": "^7.5.4",
"set-blocking": "^2.0.0",
"triple-beam": "^1.4.1",
"winston": "^3.10.0",
-6
View File
@@ -5,13 +5,7 @@
*/
"use strict";
const exchange_string = require("./exchange_string");
const export_ = require("./export");
const patch = require("./patch");
const server = require("./server");
module.exports = {
...exchange_string,
...export_,
...patch,
...server,
};