mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-23 00:13:13 +09:00
Enable the player proxy by default and give lobbies an empty save
The player proxy now listens on 34197 by default. New hosts default to the port range 34200-34299 so they don't hand that port to instances, and the controller logs an error and runs without the proxy if the port is taken, as hosts with the old range only skip it when the controller already holds it. Lobby instances start the save lobby.zip, created on first start as a one tile map with no autoplace and with the freeplay scenario replaced by an empty one. This uses the new chooseSave instance hook, which lets plugins pick or create the save to start, and setSaveScenario from @clusterio/host, which sets the scenario the save patcher keeps loading. Map gen settings can't use a width and height of 0 for this, as Factorio takes 0 to mean an unlimited map. The address players reach the proxy on moves from lobby.public_address to controller.player_proxy_public_address. When it's set the player_auth login page lists it once for the instances behind the proxy instead of their own addresses, and lobbies with player_auth loaded get a button that opens the web interface login dialog.
This commit is contained in:
23 files changed
+391
-121
No files matched your search
@@ -1089,6 +1089,35 @@ export default class Controller {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Address players reach the player proxy on
|
||||
*
|
||||
* @param port -
|
||||
* Proxy port to give the address for, defaults to the main port.
|
||||
* @returns controller.player_proxy_public_address, or the host name of
|
||||
* controller.public_url with the port if not set. Undefined if the
|
||||
* proxy is disabled or neither is set.
|
||||
*/
|
||||
getPlayerProxyAddress(port?: number) {
|
||||
if (!this.playerProxyServer) {
|
||||
return undefined;
|
||||
}
|
||||
const configured = this.config.get("controller.player_proxy_public_address");
|
||||
if (configured) {
|
||||
if (port === undefined) {
|
||||
return configured;
|
||||
}
|
||||
// Swap the port, host may be a name, IPv4 address or IPv6 address in brackets
|
||||
const host = /^(\[[^\]]+\]|[^:]+)(?::\d+)?$/.exec(configured)?.[1] ?? `[${configured}]`;
|
||||
return `${host}:${port}`;
|
||||
}
|
||||
const publicUrl = this.config.get("controller.public_url");
|
||||
if (!publicUrl) {
|
||||
return undefined;
|
||||
}
|
||||
return `${new URL(publicUrl).hostname}:${port ?? this.playerProxyServer.port}`;
|
||||
}
|
||||
|
||||
private _lastInstanceOfPlayer(name: string) {
|
||||
const user = this.users.getByName(name);
|
||||
let lastId: number | undefined;
|
||||
|
||||
@@ -120,7 +120,16 @@ export default class PlayerProxyServer {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
await this._listen(this._port);
|
||||
try {
|
||||
await this._listen(this._port);
|
||||
} catch (err: any) {
|
||||
// Not fatal so the rest of the controller still works, for example if a host on the
|
||||
// same machine runs an instance on the port.
|
||||
this._logger.error(
|
||||
`Failed to listen on player proxy port ${this._port}, players can't connect through the ` +
|
||||
`proxy: ${err.message}`
|
||||
);
|
||||
}
|
||||
this._controller.instances.records.on("update", this._onInstancesUpdated);
|
||||
await this.syncListeners();
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ export { BaseInstancePlugin, InstanceHooks, type InstancePluginContext } from ".
|
||||
export { default as Host, HostRouter } from "./src/Host.js";
|
||||
export { default as Instance } from "./src/Instance.js";
|
||||
export { default as InstanceConnection } from "./src/InstanceConnection.js";
|
||||
export { setSaveScenario } from "./src/patch.js";
|
||||
|
||||
if (import.meta.main) {
|
||||
bootstrap();
|
||||
|
||||
@@ -24,6 +24,8 @@ export class InstanceHooks extends lib.AsyncHookCollection {
|
||||
this.prepareControllerDisconnect = this.newHook();
|
||||
this.playerEvent = this.newHook();
|
||||
this.autoPauseChanged = this.newHook();
|
||||
// Long timeout as handlers may create a save
|
||||
this.chooseSave = this.newHook(logger, 300_000);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,6 +57,19 @@ export class InstanceHooks extends lib.AsyncHookCollection {
|
||||
*/
|
||||
readonly metrics: lib.AsyncHook<[], AsyncIterable<lib.CollectorResult> | void>;
|
||||
|
||||
/**
|
||||
* Called to pick the save to start when none was requested
|
||||
*
|
||||
* Invoked after mods have been synced when the instance is started
|
||||
* without a save being specified. Handlers may create a save in the
|
||||
* saves directory of the instance and return its name to have it
|
||||
* started instead of the newest save. Return undefined to leave the
|
||||
* choice to other plugins and the default of the newest save.
|
||||
*
|
||||
* @returns name of save in the instance's saves directory to start.
|
||||
*/
|
||||
readonly chooseSave: lib.AsyncHook<[], string | undefined>;
|
||||
|
||||
/**
|
||||
* Called after the Factorio server is started
|
||||
*/
|
||||
|
||||
@@ -1045,7 +1045,16 @@ end`.replace(/\r?\n/g, " ");
|
||||
* @returns Name of the save prepared.
|
||||
*/
|
||||
async prepareSave(saveName?: string) {
|
||||
// Use latest save if no save was specified
|
||||
// Let plugins pick the save, otherwise use latest save if no save was specified
|
||||
if (saveName === undefined) {
|
||||
for (const result of await this.hooks.chooseSave.collect()) {
|
||||
if (result) {
|
||||
checkRequestSaveName(result);
|
||||
saveName = result;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (saveName === undefined) {
|
||||
saveName = await lib.getNewestFile(
|
||||
this.path("saves"), (name) => !name.endsWith(".tmp.zip")
|
||||
|
||||
+77
-27
@@ -465,37 +465,87 @@ export async function patch(savePath: string, modules: SaveModule[]) {
|
||||
|
||||
// Write back the save, keeping the order of the entries in the original
|
||||
const added = new Map([...files].map(([relativePath, contents]) => [rootPath(relativePath), contents]));
|
||||
const output = new lib.ZipWriter();
|
||||
let writeStream;
|
||||
[tempSavePath, writeStream] = await lib.createTempWriteStream(savePath);
|
||||
const writing = pipeline(output.outputStream, writeStream);
|
||||
// Awaited below, but a write error can reject it before then.
|
||||
writing.catch(() => {});
|
||||
try {
|
||||
for (const entry of zip.entries.values()) {
|
||||
const name = entry.fileName;
|
||||
if (removed.has(name)) {
|
||||
continue;
|
||||
}
|
||||
const contents = added.get(name);
|
||||
if (contents !== undefined) {
|
||||
await output.addBuffer(contents, name);
|
||||
added.delete(name);
|
||||
} else {
|
||||
await output.addEntry(zip, entry);
|
||||
}
|
||||
tempSavePath = await writeSaveCopy(zip, savePath, added, removed);
|
||||
} finally {
|
||||
zip.close();
|
||||
}
|
||||
await fs.rename(tempSavePath, savePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a copy of a save with entries replaced, added and removed
|
||||
*
|
||||
* The copy is written next to the save, and must be renamed over it after
|
||||
* the save has been closed.
|
||||
*
|
||||
* @param zip - Opened save to copy.
|
||||
* @param savePath - Path the save was opened from.
|
||||
* @param added - Entries by full path in the zip to add or replace.
|
||||
* @param removed - Full paths of entries to leave out.
|
||||
* @returns path to the copy written.
|
||||
*/
|
||||
async function writeSaveCopy(
|
||||
zip: lib.ZipArchive,
|
||||
savePath: string,
|
||||
added: Map<string, Buffer>,
|
||||
removed = new Set<string>(),
|
||||
) {
|
||||
const output = new lib.ZipWriter();
|
||||
const [tempSavePath, writeStream] = await lib.createTempWriteStream(savePath);
|
||||
const writing = pipeline(output.outputStream, writeStream);
|
||||
// Awaited below, but a write error can reject it before then.
|
||||
writing.catch(() => {});
|
||||
try {
|
||||
for (const entry of zip.entries.values()) {
|
||||
const name = entry.fileName;
|
||||
if (removed.has(name)) {
|
||||
continue;
|
||||
}
|
||||
for (const [name, contents] of added) {
|
||||
const contents = added.get(name);
|
||||
if (contents !== undefined) {
|
||||
await output.addBuffer(contents, name);
|
||||
added.delete(name);
|
||||
} else {
|
||||
await output.addEntry(zip, entry);
|
||||
}
|
||||
await output.end();
|
||||
await writing;
|
||||
} catch (err) {
|
||||
output.outputStream.destroy();
|
||||
await writing.catch(() => {});
|
||||
await fs.rm(tempSavePath, { force: true });
|
||||
throw err;
|
||||
}
|
||||
for (const [name, contents] of added) {
|
||||
await output.addBuffer(contents, name);
|
||||
}
|
||||
await output.end();
|
||||
await writing;
|
||||
} catch (err) {
|
||||
output.outputStream.destroy();
|
||||
await writing.catch(() => {});
|
||||
await fs.rm(tempSavePath, { force: true });
|
||||
throw err;
|
||||
}
|
||||
return tempSavePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the scenario code the save patcher keeps loading in a save
|
||||
*
|
||||
* Saves created by Factorio run the freeplay scenario, which the patcher
|
||||
* keeps when patching them. This replaces it with the given scenario info,
|
||||
* for example a scenario that loads no modules to get a save without
|
||||
* freeplay. The save must not have been patched before.
|
||||
*
|
||||
* @param savePath - Path to the save to change.
|
||||
* @param scenario - Scenario modules to load in place of the original scenario.
|
||||
*/
|
||||
export async function setSaveScenario(savePath: string, scenario: lib.ModuleInfo) {
|
||||
const zip = await lib.ZipArchive.fromFile(savePath);
|
||||
let tempSavePath: string;
|
||||
try {
|
||||
const root = lib.findRoot(zip);
|
||||
if (await zip.readFile(path.posix.join(root, "clusterio.json")) !== null) {
|
||||
throw new Error("Unable to set scenario of a save that has already been patched");
|
||||
}
|
||||
const patchInfo = new PatchInfo(0, scenario, []);
|
||||
tempSavePath = await writeSaveCopy(zip, savePath, new Map([[
|
||||
path.posix.join(root, "clusterio.json"), Buffer.from(JSON.stringify(patchInfo, null, " "), "utf8"),
|
||||
]]));
|
||||
} finally {
|
||||
zip.close();
|
||||
}
|
||||
|
||||
@@ -153,9 +153,10 @@ export class AsyncHookCollection {
|
||||
Args extends unknown[],
|
||||
Result = void,
|
||||
> (
|
||||
_logger = this._logger
|
||||
_logger = this._logger,
|
||||
timeoutMs?: number,
|
||||
) {
|
||||
const hook = new AsyncHook<Args, Result>(_logger);
|
||||
const hook = new AsyncHook<Args, Result>(_logger, timeoutMs);
|
||||
this.hooks.push(hook);
|
||||
return hook;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ export interface ControllerConfigFields {
|
||||
"controller.proxy_stream_timeout": number;
|
||||
"controller.player_proxy_port": number | null;
|
||||
"controller.player_proxy_default_instance_id": number | null;
|
||||
"controller.player_proxy_public_address": string | null;
|
||||
"controller.factorio_username": string | null;
|
||||
"controller.factorio_token": string | null;
|
||||
"controller.share_factorio_credentials_with_hosts": boolean;
|
||||
@@ -253,6 +254,7 @@ export class ControllerConfig extends classes.Config<ControllerConfigFields> {
|
||||
restartRequired: true,
|
||||
type: "number",
|
||||
optional: true,
|
||||
initialValue: 34197,
|
||||
validator: validators.optional(validators.greaterThanZero),
|
||||
},
|
||||
"controller.player_proxy_default_instance_id": {
|
||||
@@ -263,6 +265,15 @@ export class ControllerConfig extends classes.Config<ControllerConfigFields> {
|
||||
type: "number",
|
||||
optional: true,
|
||||
},
|
||||
"controller.player_proxy_public_address": {
|
||||
title: "Player Proxy Public Address",
|
||||
description:
|
||||
"Address players reach the player proxy on, for example play.example.com:34197. Used by plugins " +
|
||||
"to tell players where to connect. If null plugins may assume the host name of " +
|
||||
"controller.public_url and controller.player_proxy_port.",
|
||||
type: "string",
|
||||
optional: true,
|
||||
},
|
||||
"controller.factorio_username": {
|
||||
title: "Factorio Username",
|
||||
description: "Username to authenticate with Factorio API with.",
|
||||
@@ -433,7 +444,7 @@ export class HostConfig extends classes.Config<HostConfigFields> {
|
||||
"Range of UDP ports to use for game connections. Supports both comma separated values and " +
|
||||
"ranges separated with a dash.",
|
||||
type: "string",
|
||||
initialValue: "34100-34199",
|
||||
initialValue: "34200-34299",
|
||||
// TODO extendedValidation, port range
|
||||
},
|
||||
"host.factorio_username": {
|
||||
|
||||
Reference in new issue
Block a user