Merge branch 'master' into feature/datastore

This commit is contained in:
Hornwitser authored and GitHub committed 2024-09-04 00:08:52 +02:00
commit a2ea2f2604
102 files changed
+1252 -366

No files matched your search

+6 -2
View File
@@ -248,8 +248,12 @@ async function initialize(): Promise<InitializeParameters> {
.command("config", "Manage Controller config", lib.configCommand)
.command("bootstrap", "Bootstrap access to cluster", yargs => {
yargs
.command("create-admin <name>", "Create a cluster admin")
.command("generate-user-token <name>", "Generate authentication token for the given user")
.command("create-admin <name>", "Create a cluster admin", yargs => {
yargs.positional("name", { describe: "Name of the admin user", type: "string" });
})
.command("generate-user-token <name>", "Generate authentication token for the given user", yargs => {
yargs.positional("name", { describe: "Name of the user", type: "string" });
})
.command("generate-host-token <id>", "Generate authentication token for the given host", yargs => {
yargs.positional("id", { describe: "ID of the host", type: "number" });
})
+3 -3
View File
@@ -29,7 +29,6 @@
"jsonwebtoken": "^9.0.1",
"jszip": "^3.10.1",
"set-blocking": "^2.0.0",
"webpack-cli": "^5.1.4",
"winston": "^3.10.0",
"winston-daily-rotate-file": "^4.7.1",
"ws": "^8.13.0",
@@ -51,10 +50,11 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.14",
"typescript": "^5.1.6",
"typescript": "^5.5.3",
"webpack": "^5.88.2",
"webpack-dev-middleware": "^6.1.1",
"webpack-merge": "^5.9.0"
"webpack-merge": "^5.9.0",
"webpack-cli": "^5.1.4"
},
"publishConfig": {
"access": "public"
+1 -1
View File
@@ -35,7 +35,7 @@ export default class BaseConnection extends lib.Link {
this.handle(lib.SubscriptionRequest, this.handleSubscriptionRequest.bind(this));
this.connector.on("close", () => {
this._controller.subscriptions.unsubscribe(this);
this._controller.subscriptions.unsubscribeLink(this);
});
}
+7 -2
View File
@@ -84,7 +84,7 @@ export default class Controller {
public shouldRestart: boolean = false;
_fallbackedRequests: Map<lib.RequestClass<unknown, unknown>, lib.RequestHandler<unknown, unknown>> = new Map();
_registeredRequests: Map<lib.RequestClass<unknown, unknown>, lib.RequestHandler<unknown, unknown>> = new Map();
_registeredEvents = new Map();
_registeredEvents = new Map<lib.EventClass<unknown>, lib.EventHandler<unknown>>();
_snoopedEvents = new Map();
devMiddleware: any | null = null;
@@ -808,7 +808,7 @@ export default class Controller {
};
instanceConfig.set("factorio.settings", settings);
let instance = new InstanceInfo(instanceConfig, "unassigned", undefined, Date.now());
let instance = new InstanceInfo(instanceConfig, "unassigned", undefined, undefined, Date.now());
this.instances.set(instance);
await lib.invokeHook(this.plugins, "onInstanceStatusChanged", instance);
this.addInstanceHooks(instance);
@@ -935,6 +935,11 @@ export default class Controller {
}
instanceDetailsUpdated(instances: InstanceInfo[]) {
for (const instance of instances) {
if (instance.status === "stopped") {
this.subscriptions.unsubscribeAddress(lib.Address.fromShorthand({instanceId: instance.id}));
}
}
const updates = instances.map(instance => instance.toInstanceDetails());
this.subscriptions.broadcast(new lib.InstanceDetailsUpdatesEvent(updates));
}
@@ -185,6 +185,7 @@ export default class HostConnection extends BaseConnection {
let prev = instance.status;
instance.status = request.status;
instance.gamePort = request.gamePort;
instance.factorioVersion = request.factorioVersion;
this._controller.instances.set(instance);
logger.verbose(`Instance ${instance.config.get("instance.name")} State: ${instance.status}`);
await lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
@@ -221,6 +222,7 @@ export default class HostConnection extends BaseConnection {
let prev = controllerInstance.status;
controllerInstance.status = instanceData.status;
controllerInstance.gamePort = instanceData.gamePort;
controllerInstance.factorioVersion = instanceData.factorioVersion;
instanceUpdates.push(controllerInstance);
logger.verbose(`Instance ${instanceConfig.get("instance.name")} State: ${instanceData.status}`);
await lib.invokeHook(
@@ -235,6 +237,7 @@ export default class HostConnection extends BaseConnection {
instanceConfig,
instanceData.status,
instanceData.gamePort,
instanceData.factorioVersion,
Date.now(),
);
instanceUpdates.push(newInstance);
+4
View File
@@ -11,6 +11,7 @@ export default class InstanceInfo {
public config: lib.InstanceConfig,
public status: lib.InstanceStatus,
public gamePort?: number,
public factorioVersion?: string,
public updatedAtMs = 0,
) {
this.config = config;
@@ -22,6 +23,7 @@ export default class InstanceInfo {
"status": lib.InstanceStatus,
"gamePort": Type.Optional(Type.Number()),
"updatedAtMs": Type.Optional(Type.Number()),
"factorioVersion": Type.Optional(Type.String()),
});
static fromJSON(json: Static<typeof this.jsonSchema>, location: lib.ConfigLocation) {
@@ -29,6 +31,7 @@ export default class InstanceInfo {
lib.InstanceConfig.fromJSON(json.config, location),
json.status,
json.gamePort,
json.factorioVersion,
json.updatedAtMs,
);
}
@@ -40,6 +43,7 @@ export default class InstanceInfo {
this.config.get("instance.assigned_host") ?? undefined,
this.gamePort,
this.status,
this.factorioVersion,
this.updatedAtMs,
);
}
@@ -7,6 +7,5 @@
"include": [ "web/**/*.tsx", "web/**/*.ts", "package.json" ],
"compilerOptions": {
"rootDir": "..",
"outDir": "dist/browser",
}
}
-3
View File
@@ -4,7 +4,4 @@
{ "path": "../lib/tsconfig.node.json" },
],
"include": ["index.ts", "controller.ts", "package.json", "src/**/*.ts"],
"compilerOptions": {
"outDir": "dist/node",
},
}
+20 -8
View File
@@ -16,6 +16,7 @@ const { copyPluginTemplates } = require("./template");
let dev = false;
const scriptExt = process.platform === "win32" ? ".cmd" : "";
const finished = util.promisify(stream.finished);
const { escapeArg } = require("./escape_arg");
// I hate this, there is a bug with rl.close on windows that was meant to have been fixed in Node14.4
// See nodejs/node#21771 and nodejs/node#30701 for the apparent fix that was applied
@@ -106,15 +107,25 @@ async function safeOutputFile(file, data, options={}) {
}
async function execFile(cmd, args) {
logger.verbose(`executing ${cmd} ${args.join(" ")}`);
const escaped = args.map(escapeArg);
logger.verbose(`executing ${cmd} ${escaped.join(" ")}`);
return new Promise((resolve, reject) => {
let child = child_process.execFile(cmd, args, { shell: true }, (err, stdout, stderr) => {
if (err) {
reject(err);
} else {
resolve({ stdout, stderr });
let child = child_process.execFile(
cmd,
escaped,
{
shell: true,
// eslint-disable-next-line node/no-process-env
env: process.platform === "win32" ? { ...process.env, pct: "%" } : undefined,
},
(err, stdout, stderr) => {
if (err) {
reject(err);
} else {
resolve({ stdout, stderr });
}
}
});
);
let stdout = new LineSplitter({ readableObjectMode: true });
stdout.on("data", line => { logger.verbose(line.toString()); });
child.stdout.pipe(stdout);
@@ -699,6 +710,7 @@ async function inquirerMissingArgs(args) {
{ name: "Command Line", value: "ctl" },
{ name: "Web UI", value: "web" },
{ name: "No Typescript", value: "js" },
{ name: "No Config", value: "no_config" },
],
},
{
@@ -892,7 +904,7 @@ async function main() {
let hostToken = result.stdout.split("\n").slice(-2)[0];
// Default to localhost on correct port for host in standalone mode
await execHost(["config", "set", "host.controller_url", `http://localhost:${answers.httpPort}`]);
await execHost(["config", "set", "host.controller_url", `http://localhost:${answers.httpPort}/`]);
await execHost(["config", "set", "host.controller_token", hostToken]);
await execHost(["config", "set", "host.public_address", answers.publicAddress]);
await execHost(["config", "set", "host.factorio_directory", answers.factorioDir]);
+62
View File
@@ -0,0 +1,62 @@
"use strict";
function escapeArg(arg) {
// When shell: true is used execFile does not escaping of arguments, they are
// simply joined by space and then passed to the shell.
// For Windows the command is cmd.exe /d /s /c "command arg arg ..."
// The parsing and escaping on windows is cursed. The following references are not for mortals:
// https://daviddeley.com/autohotkey/parameters/parameters.htm#WIN
// https://stackoverflow.com/a/4095133
// https://ss64.com/nt/syntax-esc.html
if (process.platform === "win32") {
if (!/[\t "%&<>\\^|]/.test(arg)) {
return arg;
}
const escaped = [];
let pos = 0;
while (pos < arg.length) {
if (arg[pos] === "\\") {
// If a backslash is followed by a quote or the end of the string, then
// double the number of backslashes because why not!
let peek = pos + 1;
while (peek !== arg.length && arg[peek] === "\\") {
peek += 1;
}
if (peek === arg.length || arg[peek] === '"') {
const count = peek - pos;
escaped.push("\\".repeat(count * 2));
pos = peek;
continue;
} else {
escaped.push("\\");
}
} else if (arg[pos] === '"') {
escaped.push('""');
} else if (arg[pos] === "%") {
// Expect a pct environment variable to contain %, because cmd does variable substitutions
// before parsing string quotes, and there's no mechanism for escaping % symbols, and this
// is a half sane workaround. The less sane workaround is to replace % with %%cd:~,%.
escaped.push("%pct%");
} else {
escaped.push(arg[pos]);
}
pos += 1;
}
return `"${escaped.join("")}"`;
}
// For all other platforms the command is /bin/sh -c <command arg arg ...>
// The command and its arguments are passed as a single argument to the shell.
// See https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02
// eslint-disable-next-line no-lonely-if
if (!/[|&;<>()$`\\"' \t*?\[#~=%]/.test(arg)) {
return arg;
}
return `"${arg.replace(/[$`"\\]/g, "\\$&")}"`;
}
module.exports = {
escapeArg,
};
+28 -5
View File
@@ -76,8 +76,15 @@ async function copyPluginTemplates(pluginName, templates) {
const files = new Map();
const prepare = [];
// Some basic flags for selecting files to include
const javascriptOnly = templates.includes("js");
const webpack = templates.includes("controller") || templates.includes("web");
const config = !templates.includes("no_config") && templates.some(value => (
["controller", "host", "instance", "ctl"].includes(value)
));
const webpack = config || templates.includes("controller") || templates.includes("web");
// A count of the number of isolated contexts the plugin runs under
let pluginContexts = 0;
// Get the file extension and path to the templates
const ext = javascriptOnly ? "js" : "ts";
@@ -88,7 +95,6 @@ async function copyPluginTemplates(pluginName, templates) {
files.set(".gitignore", path.join(commonPath, ".gitignore"));
files.set(".npmignore", path.join(commonPath, ".npmignore"));
files.set("package.json", path.join(commonPath, "package.json"));
files.set(`messages.${ext}`, path.join(templatePath, `messages.${ext}`));
files.set(`index.${ext}`, path.join(templatePath, `index.${ext}`));
// Files and dependencies to support typescript
@@ -105,24 +111,30 @@ async function copyPluginTemplates(pluginName, templates) {
if (webpack) {
prepare.push("webpack-cli --env production");
files.set("webpack.config.js", path.join(commonPath, "webpack.config.js"));
files.set(`web/index.${ext}x`, path.join(templatePath,
templates.includes("web") ? `web/plugin.${ext}x` : `web/no_plugin.${ext}x`
));
if (templates.includes("web")) {
files.set(`web/index.${ext}x`, path.join(templatePath, `web/plugin.${ext}x`));
pluginContexts += 1;
} else {
files.set(`web/index.${ext}x`, path.join(templatePath, `web/no_plugin.${ext}x`));
}
}
// Files for the controller
if (templates.includes("controller")) {
files.set(`controller.${ext}`, path.join(templatePath, `controller.${ext}`));
pluginContexts += 1;
}
// Files for hosts
if (templates.includes("host")) {
files.set(`host.${ext}`, path.join(templatePath, `host.${ext}`));
pluginContexts += 1;
}
// Files for instances
if (templates.includes("instance")) {
files.set(`instance.${ext}`, path.join(templatePath, `instance.${ext}`));
pluginContexts += 1;
}
// Files for lua modules
@@ -133,16 +145,26 @@ async function copyPluginTemplates(pluginName, templates) {
files.set("module/module_exports.lua", path.join(commonPath, "module/module_exports.lua"));
if (templates.includes("instance")) {
files.set("module/globals.lua", path.join(commonPath, "module/globals.lua"));
} else {
files.set(`instance.${ext}`, path.join(templatePath, `instance_empty.${ext}`));
pluginContexts += 1;
}
}
// Files for the control tool
if (templates.includes("ctl")) {
files.set(`ctl.${ext}`, path.join(templatePath, `ctl.${ext}`));
pluginContexts += 1;
}
// If there are more than one contexts then include the message file
if (pluginContexts > 1) {
files.set(`messages.${ext}`, path.join(templatePath, `messages.${ext}`));
}
// Properties that will control the replacements in the templates
const properties = {
config: config,
typescript: !javascriptOnly,
controller: templates.includes("controller"),
host: templates.includes("host"),
@@ -150,6 +172,7 @@ async function copyPluginTemplates(pluginName, templates) {
module: templates.includes("module"),
ctl: templates.includes("ctl"),
web: templates.includes("web"),
multi_context: pluginContexts > 1,
plugin_name: pluginName,
prepare: prepare.join(" && "),
ext: ext,
@@ -6,8 +6,10 @@ local MyModule = {
on_nth_tick = {},
}
--- global is 'synced' between players, you should use your plugin name to avoid conflicts
-- setupGlobalData should either be removed or called during clusterio_api.events.on_server_startup
--- global is 'synced' between players, you should use your plugin name to avoid name conflicts
-- The following helper function is desync safe and avoids name conflicts after being called during on_server_startup
-- There are edge cases in the following events: pre player left, player left, console command, and config changed
-- If you use any of these events and access globalData then make sure to call this function first
local globalData = {}
local function setupGlobalData()
if global["__plugin_name__"] == nil then
@@ -15,6 +17,12 @@ local function setupGlobalData()
-- starting values go here
}
end
MyModule.on_load()
end
--- The on_load function is called independently for each client when they first load the map
-- It should be used to restore global aliases and metatables not registered with script.register_metatable
function MyModule.on_load()
globalData = global["__plugin_name__"]
end
@@ -28,7 +36,7 @@ local function bar()
game.print("bar")
end
--- Clusterio provides a few custom events, on_server_startup is the most useful and should be used in place of on_load
--- Clusterio provides a few custom events, on_server_startup is the most useful and should be used in place of on_init
MyModule.events[clusterio_api.events.on_server_startup] = function(event)
setupGlobalData()
game.print(game.table_to_json(event))
@@ -20,7 +20,7 @@
"devDependencies": {
//%// Typescript and type declarations
//%if typescript
"typescript": "^5.1.6",
"typescript": "^5.5.3",
"@types/node": "^20.4.5",
//%endif
//%if typescript & web
@@ -1,13 +1,17 @@
"use strict";
const lib = require("@clusterio/lib");
const { BaseControllerPlugin } = require("@clusterio/controller");
//%if multi_context // Subscribing requires multi context
const {
PluginExampleEvent, PluginExampleRequest,
//%endif
//%if controller & web // Subscribing requires web content and the controller
ExampleSubscribableUpdate, ExampleSubscribableValue,
//%endif
//%if multi_context // Subscribing requires multi context
} = require("./messages");
//%endif
class ControllerPlugin extends BaseControllerPlugin {
//%if controller & web // Subscribing requires web content and the controller
@@ -15,14 +19,18 @@ class ControllerPlugin extends BaseControllerPlugin {
storageDirty = false;
//%endif
//%if multi_context // Subscribing requires multi context
async init() {
this.controller.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
this.controller.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
//%endif
//%if controller & web // Subscribing requires web content and the controller
this.controller.subscriptions.handle(ExampleSubscribableUpdate, this.handleExampleSubscription.bind(this));
this.exampleDatabase = new Map(); // If needed, replace with loading from database file
//%endif
//%if multi_context // Subscribing requires multi context
}
//%endif
async onControllerConfigFieldChanged(field, curr, prev) {
this.logger.info(`controller::onControllerConfigFieldChanged ${field}`);
@@ -45,6 +53,7 @@ class ControllerPlugin extends BaseControllerPlugin {
async onPlayerEvent(instance, event) {
this.logger.info(`controller::onPlayerEvent ${instance.id} ${JSON.stringify(event)}`);
}
//%if multi_context
async handlePluginExampleEvent(event) {
this.logger.info(JSON.stringify(event));
@@ -57,6 +66,7 @@ class ControllerPlugin extends BaseControllerPlugin {
myResponseNumbers: request.myNumberArray,
};
}
//%endif
//%if controller & web // Subscribing requires web content and the controller
async handleExampleSubscription(request) {
@@ -1,6 +1,7 @@
"use strict";
const { BaseCtlPlugin } = require("@clusterio/ctl");
const { CommandTree, Command } = require("@clusterio/lib");
//%// We do not check for multi context here because it doesn't make sense to have a ctl without messages
const { PluginExampleEvent, PluginExampleRequest } = require("./messages");
/* eslint-disable no-console */
@@ -1,13 +1,17 @@
"use strict";
const lib = require("@clusterio/lib");
const { BaseHostPlugin } = require("@clusterio/host");
//%if multi_context
const { PluginExampleEvent, PluginExampleRequest } = require("./messages");
//%endif
class HostPlugin extends BaseHostPlugin {
//%if multi_context
async init() {
this.host.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
this.host.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
}
//%endif
async onHostConfigFieldChanged(field, curr, prev) {
this.logger.info(`host::onInstanceConfigFieldChanged ${field}`);
@@ -16,6 +20,7 @@ class HostPlugin extends BaseHostPlugin {
async onShutdown() {
this.logger.info("host::onShutdown");
}
//%if multi_context
async handlePluginExampleEvent(event) {
this.logger.info(JSON.stringify(event));
@@ -28,6 +33,7 @@ class HostPlugin extends BaseHostPlugin {
myResponseNumbers: request.myNumberArray,
};
}
//%endif
}
module.exports = {
+30 -13
View File
@@ -1,5 +1,6 @@
"use strict";
const lib = require("@clusterio/lib");
//%if multi_context
const Messages = require("./messages");
lib.definePermission({
@@ -13,6 +14,7 @@ lib.definePermission({
title: "Example permission request",
description: "Example Description. Request. Change me in index.js",
});
//%endif
//%if controller & web // Subscribing requires web content and the controller
lib.definePermission({
@@ -34,9 +36,13 @@ const plugin = {
name: "__plugin_name__",
title: "__plugin_name__",
description: "Example Description. Plugin. Change me in index.js",
//%if controller
//%if controller | host & !config | instance & !config | ctl & !config // Blank line for formatting
controllerEntrypoint: "./controller",
//%endif
//%if controller
controllerEntrypoint: "./dist/node/controller",
//%endif
//%if controller & config
controllerConfigFields: {
"__plugin_name__.myControllerField": {
title: "My Controller Field",
@@ -46,9 +52,13 @@ const plugin = {
},
},
//%endif
//%if host
//%if host & config // Blank line for formatting
hostEntrypoint: "./host",
//%endif
//%if host
hostEntrypoint: "./dist/node/host",
//%endif
//%if host & config
hostConfigFields: {
"__plugin_name__.myHostField": {
title: "My Host Field",
@@ -58,9 +68,13 @@ const plugin = {
},
},
//%endif
//%if instance
//%if instance & config | module & config // Blank line for formatting
instanceEntrypoint: "./instance",
//%endif
//%if instance | module // Modules load an empty instance plugin
instanceEntrypoint: "./dist/node/instance",
//%endif
//%if instance & config
instanceConfigFields: {
"__plugin_name__.myInstanceField": {
title: "My Instance Field",
@@ -70,9 +84,13 @@ const plugin = {
},
},
//%endif
//%if ctl
//%if ctl & config // Blank line for formatting
ctlEntrypoint: "./ctl",
//%endif
//%if ctl
ctlEntrypoint: "./dist/node/ctl",
//%endif
//%if ctl & config
controlConfigFields: {
"__plugin_name__.myControlField": {
title: "My Control Field",
@@ -82,14 +100,18 @@ const plugin = {
},
},
//%endif
//%if multi_context // Subscribing requires multi context
messages: [
Messages.PluginExampleEvent,
Messages.PluginExampleRequest,
//%endif
//%if controller & web // Subscribing requires web content and the controller
Messages.ExampleSubscribableUpdate,
//%endif
//%if multi_context // Subscribing requires multi context
],
//%endif
//%if web // Web content template has an example route which is the plugin name
webEntrypoint: "./web",
@@ -97,11 +119,6 @@ const plugin = {
"/__plugin_name__",
],
//%endif
//%if controller & !web // The controller always includes web entry even if there is no content
webEntrypoint: "./web",
routes: [],
//%endif
};
module.exports = {
@@ -1,16 +1,23 @@
"use strict";
const lib = require("@clusterio/lib");
const { BaseInstancePlugin } = require("@clusterio/host");
//%if multi_context
const { PluginExampleEvent, PluginExampleRequest } = require("./messages");
//%endif
class InstancePlugin extends BaseInstancePlugin {
//%if multi_context | module
async init() {
//%if multi_context
this.instance.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
this.instance.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
//%endif
//%if module
this.instance.server.handle("__plugin_name__-plugin_example_ipc", this.handlePluginExampleIPC.bind(this));
//%endif
//%if multi_context | module
}
//%endif
async onInstanceConfigFieldChanged(field, curr, prev) {
this.logger.info(`instance::onInstanceConfigFieldChanged ${field}`);
@@ -26,13 +33,16 @@ class InstancePlugin extends BaseInstancePlugin {
async onPlayerEvent(event) {
this.logger.info(`onPlayerEvent::onPlayerEvent ${JSON.stringify(event)}`);
//%if module
if (this.instance.status === "running") {
this.sendRcon("/sc __plugin_name__.foo()");
}
//%endif
}
//%if multi_context
async handlePluginExampleEvent(event) {
this.logger.info(JSON.stringify(event));
//%if module
this.sendRcon("/sc __plugin_name__.foo()");
//%endif
}
async handlePluginExampleRequest(request) {
@@ -42,6 +52,7 @@ class InstancePlugin extends BaseInstancePlugin {
myResponseNumbers: request.myNumberArray,
};
}
//%endif
//%if module
async handlePluginExampleIPC(event) {
@@ -0,0 +1,11 @@
"use strict";
const { BaseInstancePlugin } = require("@clusterio/host");
class InstancePlugin extends BaseInstancePlugin {
// This class is empty because an instance plugin must be defined for a module to be injected
// This requirement may change in the future to allow for standalone modules
}
module.exports = {
InstancePlugin,
};
@@ -1,6 +1,6 @@
import React, {
useContext, useEffect, useState,
//%if controller & web // Subscribing requires web content and the controller
//%if controller // Subscribing requires web content and the controller
useCallback, useSyncExternalStore,
//%endif
} from "react";
@@ -10,35 +10,39 @@ import React, {
// } from "antd";
import {
BaseWebPlugin, PageLayout, Control, ControlContext, notifyErrorHandler,
BaseWebPlugin, PageLayout, PageHeader, Control, ControlContext, notifyErrorHandler,
} from "@clusterio/web_ui";
//%if multi_context // Subscribing requires multi context
import {
PluginExampleEvent, PluginExampleRequest,
//%if controller & web // Subscribing requires web content and the controller
ExampleSubscribableUpdate,
//%endif
//%if controller // Subscribing requires web content and the controller
ExampleSubscribableUpdate, ExampleSubscribableValue,
//%endif
//%if multi_context // Subscribing requires multi context
} from "../messages";
//%endif
import * as lib from "@clusterio/lib";
function MyTemplatePage() {
let control = useContext(ControlContext);
//%if controller & web // Subscribing requires web content and the controller
//%if controller // Subscribing requires web content and the controller
const plugin = control.plugins.get("__plugin_name__");
const [subscribableData, synced] = plugin.useSubscribableData();
//%endif
return <PageLayout nav={[{ name: "__plugin_name__" }]}>
<h2>__plugin_name__</h2>
//%if controller & web // Subscribing requires web content and the controller
<PageHeader title="__plugin_name__" />
//%if controller // Subscribing requires web content and the controller
Synced: {String(synced)} Data: {JSON.stringify([...subscribableData.values()])}
//%endif
</PageLayout>;
}
export class WebPlugin extends BaseWebPlugin {
//%if controller & web // Subscribing requires web content and the controller
//%if controller // Subscribing requires web content and the controller
subscribableData = new lib.EventSubscriber(ExampleSubscribableUpdate, this.control);
//%endif
@@ -47,15 +51,24 @@ export class WebPlugin extends BaseWebPlugin {
{
path: "/__plugin_name__",
sidebarName: "__plugin_name__",
permission: "__plugin_name__.page.view",
// This permission is client side only, so it must match the permission string of a resource request to be secure
// An undefined value means that the page will always be visible
//%if controller // Subscribing requires web content and the controller
permission: "__plugin_name__.example.permission.subscribe",
//%endif
//%if !controller
permission: undefined, // "__plugin_name__.example.permission.request",
//%endif
content: <MyTemplatePage/>,
},
];
//%if multi_context
this.control.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
this.control.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
//%endif
}
//%if controller & web // Subscribing requires web content and the controller
//%if controller// Subscribing requires web content and the controller
useSubscribableData() {
const control = useContext(ControlContext);
@@ -63,6 +76,7 @@ export class WebPlugin extends BaseWebPlugin {
return useSyncExternalStore(subscribe, () => this.subscribableData.getSnapshot());
}
//%endif
//%if multi_context
async handlePluginExampleEvent(event) {
this.logger.info(JSON.stringify(event));
@@ -75,4 +89,5 @@ export class WebPlugin extends BaseWebPlugin {
myResponseNumbers: request.myNumberArray,
};
}
//%endif
}
@@ -1,12 +1,16 @@
import * as lib from "@clusterio/lib";
import { BaseControllerPlugin, InstanceInfo } from "@clusterio/controller";
//%if multi_context // Subscribing requires multi context
import {
PluginExampleEvent, PluginExampleRequest,
//%endif
//%if controller & web // Subscribing requires web content and the controller
ExampleSubscribableUpdate, ExampleSubscribableValue,
//%endif
//%if multi_context // Subscribing requires multi context
} from "./messages";
//%endif
export class ControllerPlugin extends BaseControllerPlugin {
//%if controller & web // Subscribing requires web content and the controller
@@ -14,14 +18,18 @@ export class ControllerPlugin extends BaseControllerPlugin {
storageDirty = false;
//%endif
//%if multi_context // Subscribing requires multi context
async init() {
this.controller.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
this.controller.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
//%endif
//%if controller & web // Subscribing requires web content and the controller
this.controller.subscriptions.handle(ExampleSubscribableUpdate, this.handleExampleSubscription.bind(this));
this.exampleDatabase = new Map(); // If needed, replace with loading from database file
//%endif
//%if multi_context // Subscribing requires multi context
}
//%endif
async onControllerConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
this.logger.info(`controller::onControllerConfigFieldChanged ${field}`);
@@ -44,6 +52,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
async onPlayerEvent(instance: InstanceInfo, event: lib.PlayerEvent) {
this.logger.info(`controller::onPlayerEvent ${instance.id} ${JSON.stringify(event)}`);
}
//%if multi_context
async handlePluginExampleEvent(event: PluginExampleEvent) {
this.logger.info(JSON.stringify(event));
@@ -56,6 +65,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
myResponseNumbers: request.myNumberArray,
};
}
//%endif
//%if controller & web // Subscribing requires web content and the controller
async handleExampleSubscription(request: lib.SubscriptionRequest) {
+2 -2
View File
@@ -1,6 +1,6 @@
type Control = any; // import type { Control } from "@clusterio/ctl";
import { BaseCtlPlugin } from "@clusterio/ctl";
import { BaseCtlPlugin, type Control } from "@clusterio/ctl";
import { CommandTree, Command } from "@clusterio/lib";
//%// We do not check for multi context here because it doesn't make sense to have a ctl without messages
import { PluginExampleEvent, PluginExampleRequest } from "./messages";
/* eslint-disable no-console */
@@ -1,12 +1,16 @@
import * as lib from "@clusterio/lib";
import { BaseHostPlugin } from "@clusterio/host";
//%if multi_context
import { PluginExampleEvent, PluginExampleRequest } from "./messages";
//%endif
export class HostPlugin extends BaseHostPlugin {
//%if multi_context
async init() {
this.host.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
this.host.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
}
//%endif
async onHostConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
this.logger.info(`host::onInstanceConfigFieldChanged ${field}`);
@@ -15,6 +19,7 @@ export class HostPlugin extends BaseHostPlugin {
async onShutdown() {
this.logger.info("host::onShutdown");
}
//%if multi_context
async handlePluginExampleEvent(event: PluginExampleEvent) {
this.logger.info(JSON.stringify(event));
@@ -27,4 +32,5 @@ export class HostPlugin extends BaseHostPlugin {
myResponseNumbers: request.myNumberArray,
};
}
//%endif
}
+35 -13
View File
@@ -1,4 +1,5 @@
import * as lib from "@clusterio/lib";
//%if multi_context
import * as Messages from "./messages";
lib.definePermission({
@@ -12,6 +13,7 @@ lib.definePermission({
title: "Example permission request",
description: "Example Description. Request. Change me in index.ts",
});
//%endif
//%if controller & web // Subscribing requires web content and the controller
lib.definePermission({
@@ -28,37 +30,46 @@ lib.definePermission({
description: "Example Description. View. Change me in index.ts",
});
//%endif
//%if config
declare module "@clusterio/lib" {
//%if controller
//%endif
//%if controller & config
export interface ControllerConfigFields {
"__plugin_name__.myControllerField": string;
}
//%endif
//%if host
//%if host & config
export interface HostConfigFields {
"__plugin_name__.myHostField": string;
}
//%endif
//%if instance
//%if instance & config
export interface InstanceConfigFields {
"__plugin_name__.myInstanceField": string;
}
//%endif
//%if ctl
//%if ctl & config
export interface ControlConfigFields {
"__plugin_name__.myControlField": string;
}
//%endif
//%if config
}
//%endif
export const plugin: lib.PluginDeclaration = {
name: "__plugin_name__",
title: "__plugin_name__",
description: "Example Description. Plugin. Change me in index.ts",
//%if controller
//%// There are a lot of statements here to make the formatting look good with and without 'config'
//%if controller | host & !config | instance & !config | ctl & !config // Blank line for formatting
//%endif
//%if controller
controllerEntrypoint: "./dist/node/controller",
//%endif
//%if controller & config
controllerConfigFields: {
"__plugin_name__.myControllerField": {
title: "My Controller Field",
@@ -68,9 +79,13 @@ export const plugin: lib.PluginDeclaration = {
},
},
//%endif
//%if host
//%if host & config // Blank line for formatting
//%endif
//%if host
hostEntrypoint: "./dist/node/host",
//%endif
//%if host & config
hostConfigFields: {
"__plugin_name__.myHostField": {
title: "My Host Field",
@@ -80,9 +95,13 @@ export const plugin: lib.PluginDeclaration = {
},
},
//%endif
//%if instance
//%if instance & config | module & config // Blank line for formatting
//%endif
//%if instance | module // Modules load an empty instance plugin
instanceEntrypoint: "./dist/node/instance",
//%endif
//%if instance & config
instanceConfigFields: {
"__plugin_name__.myInstanceField": {
title: "My Instance Field",
@@ -92,9 +111,13 @@ export const plugin: lib.PluginDeclaration = {
},
},
//%endif
//%if ctl
//%if ctl & config // Blank line for formatting
//%endif
//%if ctl
ctlEntrypoint: "./dist/node/ctl",
//%endif
//%if ctl & config
controlConfigFields: {
"__plugin_name__.myControlField": {
title: "My Control Field",
@@ -104,14 +127,18 @@ export const plugin: lib.PluginDeclaration = {
},
},
//%endif
//%if multi_context // Subscribing requires multi context
messages: [
Messages.PluginExampleEvent,
Messages.PluginExampleRequest,
//%endif
//%if controller & web // Subscribing requires web content and the controller
Messages.ExampleSubscribableUpdate,
//%endif
//%if multi_context // Subscribing requires multi context
],
//%endif
//%if web // Web content template has an example route which is the plugin name
webEntrypoint: "./web",
@@ -119,9 +146,4 @@ export const plugin: lib.PluginDeclaration = {
"/__plugin_name__",
],
//%endif
//%if controller & !web // The controller always includes web entry even if there is no content
webEntrypoint: "./web",
routes: [],
//%endif
};
@@ -1,6 +1,8 @@
import * as lib from "@clusterio/lib";
import { BaseInstancePlugin } from "@clusterio/host";
//%if multi_context
import { PluginExampleEvent, PluginExampleRequest } from "./messages";
//%endif
//%if module
type PuginExampleIPC = {
@@ -10,13 +12,19 @@ type PuginExampleIPC = {
//%endif
export class InstancePlugin extends BaseInstancePlugin {
//%if multi_context | module
async init() {
//%endif
//%if multi_context
this.instance.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
this.instance.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
//%endif
//%if module
this.instance.server.handle("__plugin_name__-plugin_example_ipc", this.handlePluginExampleIPC.bind(this));
//%endif
//%if multi_context | module
}
//%endif
async onInstanceConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
this.logger.info(`instance::onInstanceConfigFieldChanged ${field}`);
@@ -33,9 +41,12 @@ export class InstancePlugin extends BaseInstancePlugin {
async onPlayerEvent(event: lib.PlayerEvent) {
this.logger.info(`onPlayerEvent::onPlayerEvent ${JSON.stringify(event)}`);
//%if module
this.sendRcon("/sc __plugin_name__.foo()");
if (this.instance.status === "running") {
this.sendRcon("/sc __plugin_name__.foo()");
}
//%endif
}
//%if multi_context
async handlePluginExampleEvent(event: PluginExampleEvent) {
this.logger.info(JSON.stringify(event));
@@ -48,6 +59,7 @@ export class InstancePlugin extends BaseInstancePlugin {
myResponseNumbers: request.myNumberArray,
};
}
//%endif
//%if module
async handlePluginExampleIPC(event: PuginExampleIPC) {
@@ -0,0 +1,7 @@
import * as lib from "@clusterio/lib";
import { BaseInstancePlugin } from "@clusterio/host";
export class InstancePlugin extends BaseInstancePlugin {
// This class is empty because an instance plugin must be defined for a module to be injected
// This requirement may change in the future to allow for standalone modules
}
@@ -5,7 +5,4 @@
{ "path": "../../packages/web_ui/tsconfig.browser.json" },
],
"include": [ "web/**/*.tsx", "web/**/*.ts", "messages.ts", "package.json" ],
"compilerOptions": {
"outDir": "dist/browser",
}
}
@@ -5,7 +5,4 @@
],
"include": ["./**/*.ts"],
"exclude": ["test/*", "./dist/*"],
"compilerOptions": {
"outDir": "dist/node",
},
}
@@ -10,35 +10,39 @@ import React, {
// } from "antd";
import {
BaseWebPlugin, PageLayout, Control, ControlContext, notifyErrorHandler,
BaseWebPlugin, PageLayout, PageHeader, Control, ControlContext, notifyErrorHandler,
} from "@clusterio/web_ui";
//%if multi_context // Subscribing requires multi context
import {
PluginExampleEvent, PluginExampleRequest,
//%if controller & web // Subscribing requires web content and the controller
ExampleSubscribableUpdate,
//%endif
//%if controller & web // Subscribing requires web content and the controller
ExampleSubscribableUpdate, ExampleSubscribableValue,
//%endif
//%if multi_context // Subscribing requires multi context
} from "../messages";
//%endif
import * as lib from "@clusterio/lib";
function MyTemplatePage() {
const control = useContext(ControlContext);
//%if controller & web // Subscribing requires web content and the controller
//%if controller // Subscribing requires web content and the controller
const plugin = control.plugins.get("__plugin_name__") as WebPlugin;
const [subscribableData, synced] = plugin.useSubscribableData();
//%endif
return <PageLayout nav={[{ name: "__plugin_name__" }]}>
<h2>__plugin_name__</h2>
//%if controller & web // Subscribing requires web content and the controller
<PageHeader title="__plugin_name__" />
//%if controller // Subscribing requires web content and the controller
Synced: {String(synced)} Data: {JSON.stringify([...subscribableData.values()])}
//%endif
</PageLayout>;
}
export class WebPlugin extends BaseWebPlugin {
//%if controller & web // Subscribing requires web content and the controller
//%if controller // Subscribing requires web content and the controller
subscribableData = new lib.EventSubscriber(ExampleSubscribableUpdate, this.control);
//%endif
@@ -49,20 +53,22 @@ export class WebPlugin extends BaseWebPlugin {
sidebarName: "__plugin_name__",
// This permission is client side only, so it must match the permission string of a resource request to be secure
// An undefined value means that the page will always be visible
//%if controller & web // Subscribing requires web content and the controller
//%if controller // Subscribing requires web content and the controller
permission: "__plugin_name__.example.permission.subscribe",
//%endif
//%if !controller | !web
//%if !controller
permission: undefined, // "__plugin_name__.example.permission.request",
//%endif
content: <MyTemplatePage/>,
},
];
//%if multi_context
this.control.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
this.control.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
//%endif
}
//%if controller & web // Subscribing requires web content and the controller
//%if controller // Subscribing requires web content and the controller
useSubscribableData() {
const control = useContext(ControlContext);
@@ -70,6 +76,7 @@ export class WebPlugin extends BaseWebPlugin {
return useSyncExternalStore(subscribe, () => this.subscribableData.getSnapshot());
}
//%endif
//%if multi_context
async handlePluginExampleEvent(event: PluginExampleEvent) {
this.logger.info(JSON.stringify(event));
@@ -82,4 +89,5 @@ export class WebPlugin extends BaseWebPlugin {
myResponseNumbers: request.myNumberArray,
};
}
//%endif
}
+1 -1
View File
@@ -35,6 +35,6 @@
"@types/node": "^20.4.5",
"@types/set-blocking": "^2.0.0",
"@types/yargs": "^17.0.24",
"typescript": "^5.1.6"
"typescript": "^5.5.3"
}
}
-3
View File
@@ -4,7 +4,4 @@
{ "path": "../lib/tsconfig.node.json" },
],
"include": ["index.ts", "package.json", "ctl.ts", "src/**/*.ts"],
"compilerOptions": {
"outDir": "dist/node",
},
}
+1 -1
View File
@@ -43,6 +43,6 @@
"@types/semver": "^7.5.0",
"@types/set-blocking": "^2.0.0",
"@types/yargs": "^17.0.24",
"typescript": "^5.1.6"
"typescript": "^5.5.3"
}
}
+5 -1
View File
@@ -667,6 +667,9 @@ export default class Host extends lib.Link {
instanceId,
instanceConnection ? instanceConnection.instance.status : "stopped",
instanceConnection ? instanceConnection.instance.server.gamePort : this.gamePort(instanceId),
instanceConnection
? instanceConnection.instance.server.version
: instanceInfo.config.get("factorio.version"),
)
);
@@ -736,7 +739,7 @@ export default class Host extends lib.Link {
}
assignGamePort(instanceId: number) {
const availablePorts = lib.parseRanges(this.config.get("host.factorio_port_range"), 1, 2**16 - 1);
const availablePorts = lib.parseRanges(this.config.get("host.factorio_port_range"), 1, 2 ** 16 - 1);
for (const [id, instance] of this.instanceInfos) {
if (id === instanceId) {
continue;
@@ -1060,6 +1063,7 @@ export default class Host extends lib.Link {
instanceInfo.config.toRemote("controller"),
instanceConnection ? instanceConnection.instance.status : "stopped",
instanceConnection ? instanceConnection.instance.server.gamePort : this.gamePort(instanceId),
instanceConnection ? instanceConnection.instance.server.version : undefined,
));
}
await this.send(new lib.InstancesUpdateRequest(list));
+3
View File
@@ -169,6 +169,7 @@ export default class Instance extends lib.Link {
let serverOptions = {
logger: this.logger,
version: this.config.get("factorio.version"),
executablePath: this.config.get("factorio.executable_path") ?? undefined,
gamePort: this.config.get("factorio.game_port") ?? host.assignGamePort(this.id),
rconPort: this.config.get("factorio.rcon_port") ?? undefined,
rconPassword: this.config.get("factorio.rcon_password") ?? undefined,
@@ -453,6 +454,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
this.id,
status,
this.server.gamePort,
status === "running"? this.server.version : this.config.get("factorio.version"),
),
);
}
@@ -469,6 +471,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
notifyExit() {
this._loadedSave = null;
this.notifyStatus("stopped");
this.connector.emit("close");
this.config.off("fieldChanged", this._configFieldChanged);
clearTimeout(this._playerCheckInterval);
+1 -1
View File
@@ -64,7 +64,7 @@ async function generateExportMod(server: FactorioServer) {
sourceDir: path.join(__dirname, "..", "..", "..", "lua", "export"),
outputDir: server.writePath("mods"),
bumpPatch: false,
factorioVersion: server.version.replace(/\.\d+$/, ""),
factorioVersion: server.version?.replace(/\.\d+$/, ""),
dependencies,
});
}
+15 -6
View File
@@ -407,6 +407,8 @@ export interface FactorioServerOptions {
* the latest version found in `factorioDir`.
*/
version?: string,
/** Path to executable to invoke when starting the server */
executablePath?: string;
/** UDP port to host game on. */
gamePort?: number,
/** TCP port to use for RCON. */
@@ -450,6 +452,8 @@ export interface FactorioServerOptions {
* @extends events.EventEmitter
*/
export class FactorioServer extends events.EventEmitter {
/** Path to executable to invoke when starting the server */
executablePath?: string;
/** UDP port used for hosting the Factorio game server on */
gamePort: number;
/** TCP port used for RCON on the Factorio game server */
@@ -504,6 +508,7 @@ export class FactorioServer extends events.EventEmitter {
this._logger = options.logger || lib.logger;
this._targetVersion = options.version || "latest";
this.executablePath = options.executablePath;
/** UDP port used for hosting the Factorio game server on */
this.gamePort = options.gamePort || randomDynamicPort();
/** TCP port used for RCON on the Factorio game server */
@@ -725,12 +730,12 @@ export class FactorioServer extends events.EventEmitter {
}
/**
* The version of Factorio in use. This will be the actual version if
* "latest" (the default) was specified as `factorioVersion` to the
* constructor.
* The version of Factorio in use. This will be the actual version if
* "latest" (the default) was specified as `factorioVersion` to the constructor.
* This will be undefined before the server is initialized, or if init failed.
*/
get version() {
return this._version!;
get version(): string | undefined {
return this._version ?? undefined;
}
/**
@@ -1155,11 +1160,15 @@ export class FactorioServer extends events.EventEmitter {
/**
* Get Factorio binary path
*
* Get the path to the factorio binary depending on the platform (MacOS support)
* Get the path to the factorio binary depending on the configuration
* and or the platform (MacOS support)
*
* @returns Path to factorio binary
*/
binaryPath() {
if (this.executablePath) {
return this.dataPath("..", this.executablePath);
}
if (process.platform === "darwin") {
return this.dataPath("..", "MacOS", "factorio");
}
-3
View File
@@ -4,7 +4,4 @@
{ "path": "../lib/tsconfig.node.json" },
],
"include": ["index.ts", "host.ts", "package.json", "src/**/*.ts", "src/**/*.js"],
"compilerOptions": {
"outDir": "dist/node",
},
}
+1 -1
View File
@@ -41,6 +41,6 @@
"@types/triple-beam": "^1.3.2",
"@types/ws": "^8.5.5",
"@types/yargs": "^17.0.24",
"typescript": "^5.1.6"
"typescript": "^5.5.3"
}
}
+9
View File
@@ -261,6 +261,7 @@ export interface InstanceConfigFields {
"instance.auto_start": boolean;
"factorio.version": string;
"factorio.executable_path": string | null;
"factorio.game_port": number | null;
"factorio.host_assigned_game_port": number | null;
"factorio.rcon_port": number | null;
@@ -311,6 +312,14 @@ export class InstanceConfig extends classes.Config<InstanceConfigFields> {
type: "string",
initialValue: "latest",
},
"factorio.executable_path": {
description:
"Relative path from the Factorio installation directory to the executable to run. " +
"Defaults to auto detect the path, only needed in special setups.",
restartRequired: true,
type: "string",
optional: true,
},
"factorio.game_port": {
description: "UDP port to run game on, uses a port in host.factorio_port_range if null",
restartRequired: true,
+9 -2
View File
@@ -42,6 +42,7 @@ export class InstanceDetails {
public assignedHost: number | undefined,
public gamePort: number | undefined,
public status: InstanceStatus,
public factorioVersion: string | undefined,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAtMs = 0,
) { }
@@ -55,6 +56,7 @@ export class InstanceDetails {
"unknown", "unassigned", "stopped", "starting", "running", "stopping",
"creating_save", "exporting_data", "deleted",
]),
"factorioVersion": Type.Optional(Type.String()),
"updatedAtMs": Type.Optional(Type.Number()),
});
@@ -65,6 +67,7 @@ export class InstanceDetails {
json.assignedHost,
json.gamePort,
json.status,
json.factorioVersion,
json.updatedAtMs,
);
}
@@ -717,6 +720,7 @@ export class HostInstanceUpdate {
public config: Static<typeof InstanceConfig.jsonSchema>,
public status: InstanceStatus,
public gamePort: undefined | number,
public factorioVersion: undefined | string,
) { }
static jsonSchema = Type.Object({
@@ -725,10 +729,11 @@ export class HostInstanceUpdate {
"stopped", "starting", "running", "stopping", "creating_save", "exporting_data",
]),
"gamePort": Type.Optional(Type.Number()),
"factorioVersion": Type.Optional(Type.String()),
});
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.config, json.status, json.gamePort);
return new this(json.config, json.status, json.gamePort, json.factorioVersion);
}
}
@@ -822,6 +827,7 @@ export class InstanceStatusChangedEvent {
public instanceId: number,
public status: InstanceStatus,
public gamePort?: number,
public factorioVersion?: string,
) { }
static jsonSchema = Type.Object({
@@ -830,10 +836,11 @@ export class InstanceStatusChangedEvent {
"stopped", "starting", "running", "stopping", "creating_save", "exporting_data",
]),
"gamePort": Type.Optional(Type.Integer()),
"factorioVersion": Type.Optional(Type.String()),
});
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.instanceId, json.status, json.gamePort);
return new this(json.instanceId, json.status, json.gamePort, json.factorioVersion);
}
}
+19
View File
@@ -34,6 +34,7 @@ export abstract class BaseConnector extends events.EventEmitter {
}
protected abstract send(message: libData.MessageRoutable): void;
abstract get valid(): boolean;
forward(message: libData.MessageRoutable) {
const seq = this._seq;
@@ -346,6 +347,14 @@ export abstract class WebSocketBaseConnector extends BaseConnector {
get hasSession() {
return ["connected", "resuming"].includes(this._state);
}
/**
* True if the connector is valid and can accept new messages,
* only needs to be checked on fringe cases during setup and tear down.
*/
get valid() {
return this.hasSession;
}
}
/**
@@ -723,4 +732,14 @@ export class VirtualConnector extends BaseConnector {
send(message: libData.Message) {
this.other.emit("message", message);
}
/**
* True if the connector is valid and can accept new messages,
* only needs to be checked on fringe cases during setup and tear down.
*
* For a virtual connector this is always true.
*/
get valid() {
return true;
}
}
+2 -2
View File
@@ -538,7 +538,7 @@ export class Link {
if (!entry) {
throw new Error(`Attempt to send unregistered Request ${request.constructor.name}`);
}
if (this.connector.src.equals(dst)) {
if (this.connector.src.addressedTo(dst)) {
throw new Error(`Message would return back to sender ${dst}.`);
}
if (this.validateSent) {
@@ -575,7 +575,7 @@ export class Link {
if (!entry) {
throw new Error(`Attempt to send unregistered Event ${event.constructor.name}`);
}
if (this.connector.src.equals(dst)) {
if (this.connector.src.addressedTo(dst)) {
throw new Error(`Message would return back to sender ${dst}.`);
}
if (this.validateSent) {
+3 -1
View File
@@ -207,7 +207,9 @@ export class LinkTransport extends Transport {
}
try {
this.link.send(new libData.LogMessageEvent(info));
if (this.link.connector.valid) {
this.link.send(new libData.LogMessageEvent(info));
}
} catch (err) {
// Ignore session lost errors.
if (!(err instanceof libErrors.SessionLost)) {
+108 -48
View File
@@ -1,11 +1,12 @@
import { Type, Static } from "@sinclair/typebox";
import { Link, Event, EventClass, RequestHandler, WebSocketClientConnector, WebSocketBaseConnector } from "./link";
import { logger } from "./logging";
import { Address, MessageRequest, IControllerUser } from "./data";
import { Link, Event, EventClass, RequestHandler, WebSocketBaseConnector } from "./link";
import { Address, MessageRequest, IControllerUser, plainJson, JsonBoolean } from "./data";
import isDeepStrictEqual from "./is_deep_strict_equal";
import { RequestError, SessionLost } from "./errors";
import { logger } from "./logging";
export type SubscriptionRequestHandler<T> = RequestHandler<SubscriptionRequest, Event<T> | null>;
export type EventSubscriberCallback<T> = (updates: T[], synced: boolean) => void
export type EventSubscriberCallback<T> = (event: T | null, synced: boolean) => void
/**
* A subscription request sent by a subscriber, this updates what events the subscriber will be sent
@@ -15,7 +16,7 @@ export type EventSubscriberCallback<T> = (updates: T[], synced: boolean) => void
export class SubscriptionRequest {
declare ["constructor"]: typeof SubscriptionRequest;
static type = "request" as const;
static src = ["control", "instance"] as const;
static src = ["control", "host", "instance"] as const;
static dst = "controller" as const;
static permission(user: IControllerUser, message: MessageRequest) {
if (typeof message.data === "object" && message.data !== null) {
@@ -31,6 +32,9 @@ export class SubscriptionRequest {
}
}
/** Indicates if updates have been sent */
static Response = JsonBoolean;
constructor(
public eventName: string,
public subscribe: boolean,
@@ -56,9 +60,14 @@ export class SubscriptionRequest {
}
}
type Subscriber = {
link: Link,
dst: Address,
}
type EventData = {
subscriptionUpdate?: SubscriptionRequestHandler<unknown>,
subscriptions: Set<Link>,
subscriptions: Array<Subscriber>,
};
/**
@@ -85,7 +94,7 @@ export class SubscriptionController {
}
this._events.set(entry.name, {
subscriptionUpdate: subscriptionUpdate,
subscriptions: new Set(),
subscriptions: [],
});
}
@@ -102,13 +111,28 @@ export class SubscriptionController {
if (!eventData) {
throw new Error(`Event ${entry.name} is not a registered as subscribable`);
}
for (let link of eventData.subscriptions) {
if ((link.connector as WebSocketBaseConnector).closing) {
eventData.subscriptions.delete(link);
const toRemove: Subscriber[] = [];
for (const subscriber of eventData.subscriptions) {
if ((subscriber.link.connector as WebSocketBaseConnector).closing) {
toRemove.push(subscriber);
} else {
link.send(event);
subscriber.link.sendTo(subscriber.dst, event);
}
}
eventData.subscriptions = eventData.subscriptions.filter(subscriber => !toRemove.includes(subscriber));
}
/**
* Unsubscribe from all events of a given address.
* Used when an instance is stopped to stop all active subscriptions.
* @param address - Address to stop sending events to.
*/
unsubscribeAddress(address: Address) {
for (let eventData of this._events.values()) {
eventData.subscriptions = eventData.subscriptions.filter(
subscriber => !subscriber.dst.addressedTo(address)
);
}
}
/**
@@ -116,9 +140,11 @@ export class SubscriptionController {
* Used when a link is closed to stop all active subscriptions.
* @param link - Link to stop sending events to.
*/
unsubscribe(link: Link) {
unsubscribeLink(link: Link) {
for (let eventData of this._events.values()) {
eventData.subscriptions.delete(link);
eventData.subscriptions = eventData.subscriptions.filter(
subscriber => subscriber.link !== link
);
}
}
@@ -138,16 +164,23 @@ export class SubscriptionController {
throw new Error(`Event ${event.eventName} is not a registered as subscribable`);
}
if (event.subscribe === false) {
eventData.subscriptions.delete(link);
const index = eventData.subscriptions.findLastIndex(subscriber => subscriber.dst.addressedTo(src));
if (index >= 0) {
eventData.subscriptions.splice(index, 1);
}
} else {
eventData.subscriptions.add(link);
if (!eventData.subscriptions.some(subscriber => subscriber.dst.addressedTo(src))) {
eventData.subscriptions.push({ link: link, dst: src });
}
if (eventData.subscriptionUpdate) {
const eventReplay = await eventData.subscriptionUpdate(event, src, dst);
if (eventReplay) {
link.send(eventReplay);
link.sendTo(src, eventReplay);
return true;
}
}
}
return false;
}
}
@@ -157,9 +190,9 @@ export interface SubscribableValue {
isDeleted: boolean,
}
export interface EventSubscribable<T, V extends SubscribableValue> extends Event<T> {
export type EventSubscribable<T, V extends SubscribableValue> = Event<T> & Partial<{
updates: V[],
}
}>
/**
* Component for subscribing to and tracking updates of a remote resource
@@ -167,43 +200,61 @@ export interface EventSubscribable<T, V extends SubscribableValue> extends Event
*/
export class EventSubscriber<
T extends EventSubscribable<T, V>,
K extends string | number = T["updates"][number]["id"],
V extends SubscribableValue = T["updates"][number],
K extends string | number = NonNullable<T["updates"]>[number]["id"],
V extends SubscribableValue = NonNullable<T["updates"]>[number],
> {
_callbacks = new Array<EventSubscriberCallback<V>>();
/** The time at which an event was last received, is less than 0 when there have been no events */
lastResponseTimeMs = -1;
/** Values of the subscribed resource */
values = new Map<K, V>();
/** True if this subscriber is currently synced with the source */
synced = false;
_snapshot?: readonly [ReadonlyMap<K, Readonly<V>>, boolean];
_snapshotLastUpdatedMs = 0;
lastResponseTimeMs = -1;
/** True if this subscriber is expecting to receive updates from the source */
_syncing = false;
/** Repeat calls to getSnapshot will return the same readonly copy unless values has updated */
_snapshot: readonly [ReadonlyMap<K, Readonly<V>>, boolean] = [new Map<K, V>(), false];
_snapshotLastUpdatedMs = -1;
/** Callbacks will be called when an event is received or the synced state changes */
_callbacks = new Array<EventSubscriberCallback<T>>();
constructor(
private Event: EventClass<T>,
public control: Link,
) {
control.handle(Event, this._handle.bind(this));
control.handle(Event, this._handleEvent.bind(this));
control.connector.on("connect", () => {
this._updateSubscription();
this.handleConnectionEvent("connect");
});
control.connector.on("close", () => {
if (this.synced) {
this.synced = false;
for (let callback of this._callbacks) {
callback([], this.synced);
}
}
this.handleConnectionEvent("close");
});
}
/**
* Handle connection events from this connector or another in the chain to the controller
* This should be called by an instance plugin during onControllerConnectionEvent
* @param event - event type that occurred
*/
handleConnectionEvent(event: "connect" | "drop" | "resume" | "close") {
if (event === "connect" || event === "resume") {
this._updateSubscription();
} else if (this.synced) {
this.synced = false;
for (let callback of this._callbacks) {
callback(null, false);
}
}
}
/**
* Handle incoming events and distribute it to the correct callbacks
* @param event - event from subscribed resource
* @internal
*/
async _handle(event: EventSubscribable<T, V>) {
for (const value of event.updates) {
async _handleEvent(event: T) {
// We support the automatic maintaining of a map for events with the updates property
const updates = event.updates ?? [];
for (const value of updates) {
this.lastResponseTimeMs = Math.max(this.lastResponseTimeMs, value.updatedAtMs);
// Warn about updates which changes content but don't update updatedAtMs
const existing = this.values.get(value.id as K);
@@ -219,8 +270,13 @@ export class EventSubscriber<
this.values.set(value.id as K, value);
}
}
for (let callback of this._callbacks) {
callback(event.updates, this.synced);
// Event handling logic
if (this._syncing && !this.synced) {
this._snapshotLastUpdatedMs = -1;
this.synced = true;
}
for (const callback of this._callbacks) {
callback(event, this.synced);
}
}
@@ -228,10 +284,10 @@ export class EventSubscriber<
* Subscribe to receive all event notifications
* @param handler -
* callback invoked whenever the subscribed resource changes or the
* synced property changes, in which case the updates will be empty.
* synced property changes, in which case the event will be null.
* @returns function that will unsubscribe from notifications
*/
subscribe(handler: EventSubscriberCallback<V>) {
subscribe(handler: EventSubscriberCallback<T>) {
this._callbacks.push(handler);
if (this._callbacks.length === 1) {
this._updateSubscription();
@@ -277,26 +333,30 @@ export class EventSubscriber<
* Update the subscription with the controller based on current handler counts
*/
async _updateSubscription() {
if (!(this.control.connector as WebSocketClientConnector).connected) {
if (!this.control.connector.valid) {
return;
}
const entry = Link._eventsByClass.get(this.Event)!;
try {
await this.control.send(new SubscriptionRequest(
this._syncing = this._callbacks.length > 0;
const updatesSent = await this.control.sendTo("controller", new SubscriptionRequest(
entry.name,
this._callbacks.length > 0,
this._syncing,
this.lastResponseTimeMs
));
this.synced = this._callbacks.length > 0;
this._snapshotLastUpdatedMs = 0;
for (let callback of this._callbacks) {
callback([], this.synced);
if (!updatesSent) {
this.synced = this._syncing;
for (const callback of this._callbacks) {
callback(null, this.synced);
}
}
} catch (err: any) {
logger.error(
`Unexpected error updating ${entry.name} subscription:\n${err.stack}`
);
if (!(err instanceof RequestError) || err.code !== "SessionLost") {
logger.error(
`Unexpected error updating ${entry.name} subscription:\n${err.stack}`
);
}
}
}
}
-1
View File
@@ -26,6 +26,5 @@
],
"compilerOptions": {
"rootDir": ".",
"outDir": "dist/browser",
}
}
-1
View File
@@ -2,7 +2,6 @@
"extends": "../../tsconfig.node.json",
"include": ["index.ts", "browser.ts", "build_mod.js", "src/**/*.ts", "src/**/*.js"],
"compilerOptions": {
"outDir": "dist/node",
"allowJs": true,
},
}
+1 -1
View File
@@ -40,7 +40,7 @@
"style-loader": "^3.3.3",
"swc-loader": "^0.2.6",
"terser-webpack-plugin": "^5.3.9",
"typescript": "^5.1.6",
"typescript": "^5.5.3",
"util": "^0.12.5",
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4",
@@ -9,7 +9,7 @@ import { useAccount } from "../model/account";
import { useHosts } from "../model/host";
import InstanceStatusTag from "./InstanceStatusTag";
import StartStopInstanceButton from "./StartStopInstanceButton";
import { InstanceDetails } from "@clusterio/lib";
import { InstanceDetails, integerFactorioVersion } from "@clusterio/lib";
import Link from "./Link";
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
@@ -46,6 +46,13 @@ export default function InstanceList(props: InstanceListProps) {
return `${host.publicAddress}:${instance.gamePort}`;
}
function integerFactorioVersionOrDefault(instance: InstanceDetails) {
if (instance.factorioVersion === undefined) {
return -1;
}
return integerFactorioVersion(instance.factorioVersion);
}
let columns: ColumnsType<InstanceDetails> = [
{
title: "Name",
@@ -86,6 +93,13 @@ export default function InstanceList(props: InstanceListProps) {
sorter: (a, b) => strcmp(instancePublicAddress(a), instancePublicAddress(b)),
responsive: ["lg"],
},
{
title: "Factorio Version",
key: "version",
render: (_, instance) => instance.factorioVersion ?? "unknown",
sorter: (a, b) => integerFactorioVersionOrDefault(a) - integerFactorioVersionOrDefault(b),
responsive: ["xl"],
},
{
title: "Status",
key: "status",
@@ -1,7 +1,6 @@
import React, { useContext, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Alert, Button, Descriptions, Dropdown, Menu, MenuProps, Modal, Space, Spin, Typography } from "antd";
import type { ItemType } from "antd/es/menu/hooks/useItems";
import { Alert, Button, Descriptions, Dropdown, MenuProps, Modal, Space, Spin, Typography } from "antd";
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
import DownOutlined from "@ant-design/icons/DownOutlined";
@@ -25,6 +24,7 @@ import { useHost } from "../model/host";
import InstanceStatusTag from "./InstanceStatusTag";
import Link from "./Link";
type MenuItem = Required<MenuProps>["items"][number];
const { Title } = Typography;
type InstanceDescriptionProps = {
@@ -59,6 +59,9 @@ function InstanceDescription(props: InstanceDescriptionProps) {
buttonContent={assigned ? "Reassign" : "Assign"}
/>}
</Descriptions.Item>
<Descriptions.Item label="Version">
{instance.factorioVersion ?? "unknown"}
</Descriptions.Item>
<Descriptions.Item label="Status"><InstanceStatusTag status={instance.status!} /></Descriptions.Item>
</Descriptions>;
}
@@ -71,7 +74,7 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
let instance = props.instance;
let instanceId = instance.id!;
let instanceButtonMenuItems: ItemType[] = [];
let instanceButtonMenuItems: MenuItem[] = [];
if (account.hasPermission("core.instance.export_data")) {
instanceButtonMenuItems.push({
disabled: exportingData || instance.status !== "stopped",
+48 -55
View File
@@ -236,62 +236,55 @@ export default function ModsPage() {
action={`${webRoot}api/upload-mod`}
showUploadList={false}
>
<div
style={{
position: "relative",
zIndex: "1010",
<Dropzone />
<Table
columns={[
{
title: "Name",
dataIndex: "title",
defaultSortOrder: "ascend",
sorter: (a, b) => (
strcmp(a.name, b.name) || a.integerVersion - b.integerVersion
),
},
{
title: "Version",
key: "version",
align: "right",
render: (_, mod) => <>
{`${mod.version} `}
<Typography.Text type="secondary">{`/ ${mod.factorioVersion}`}</Typography.Text>
</>,
},
{
title: "Filename",
dataIndex: "filename",
responsive: ["xl"],
sorter: (a, b) => strcmp(a.filename, b.filename),
},
{
title: "Size",
key: "size",
responsive: ["lg"],
render: (_, mod) => lib.formatBytes(mod.size),
align: "right",
sorter: (a, b) => a.size - b.size,
},
{
title: "Action",
key: "action",
responsive: ["lg"],
render: (_, mod) => actions(mod),
},
]}
expandable={{
expandedRowRender: (mod: lib.ModInfo) => <ModDetails mod={mod} actions={actions} />,
expandedRowClassName: () => "no-expanded-padding",
}}
>
<Dropzone />
<Table
columns={[
{
title: "Name",
dataIndex: "title",
defaultSortOrder: "ascend",
sorter: (a, b) => (
strcmp(a.name, b.name) || a.integerVersion - b.integerVersion
),
},
{
title: "Version",
key: "version",
align: "right",
render: (_, mod) => <>
{`${mod.version} `}
<Typography.Text type="secondary">{`/ ${mod.factorioVersion}`}</Typography.Text>
</>,
},
{
title: "Filename",
dataIndex: "filename",
responsive: ["xl"],
sorter: (a, b) => strcmp(a.filename, b.filename),
},
{
title: "Size",
key: "size",
responsive: ["lg"],
render: (_, mod) => lib.formatBytes(mod.size),
align: "right",
sorter: (a, b) => a.size - b.size,
},
{
title: "Action",
key: "action",
responsive: ["lg"],
render: (_, mod) => actions(mod),
},
]}
expandable={{
expandedRowRender: (mod: lib.ModInfo) => <ModDetails mod={mod} actions={actions} />,
expandedRowClassName: () => "no-expanded-padding",
}}
dataSource={[...mods.values()]}
pagination={false}
rowKey={mod => mod.id}
/>
</div>
dataSource={[...mods.values()]}
pagination={false}
rowKey={mod => mod.id}
/>
</Upload.Dragger>
<PluginExtra component="ModsPage" />
</PageLayout>;
@@ -1,13 +1,19 @@
import React from "react";
import { Space, Typography } from "antd";
const { Text } = Typography;
type PageHeaderProps = {
title: string|React.ReactElement;
title: string | React.ReactElement;
subTitle?: string | React.ReactElement;
extra?: React.JSX.Element;
};
export default function PageHeader(props: PageHeaderProps): React.JSX.Element {
return <div className="page-header">
<h2 className="page-header-title">{props.title}</h2>
<Space>
<h2 className="page-header-title">{props.title}</h2>
{props.subTitle && <Text type="secondary">{props.subTitle}</Text>}
</Space>
{props.extra && <div className="page-header-extra">{props.extra}</div>}
</div>;
}
@@ -6,6 +6,7 @@ import type { PluginWebApi } from "@clusterio/lib";
import ControlContext from "./ControlContext";
import PageLayout from "./PageLayout";
import PageHeader from "./PageHeader";
import notify from "../util/notify";
export default function PluginViewPage() {
@@ -39,7 +40,7 @@ export default function PluginViewPage() {
let pluginMeta = pluginList.find(p => p.name === pluginName);
if (!pluginMeta) {
return <PageLayout nav={nav}>
<h2>Plugin not found</h2>
<PageHeader title="Plugin not found" />
<p>Plugin with name {pluginName} was not found on the controller.</p>
</PageLayout>;
}
@@ -9,6 +9,7 @@ import type { PluginWebApi } from "@clusterio/lib";
import notify from "../util/notify";
import ControlContext from "./ControlContext";
import PageLayout from "./PageLayout";
import PageHeader from "./PageHeader";
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
@@ -47,7 +48,7 @@ export default function PluginsPage() {
}
return <PageLayout nav={[{ name: "Plugins" }]}>
<h2>Plugins</h2>
<PageHeader title="Plugins" />
<Table
columns={[
{
+2 -9
View File
@@ -357,15 +357,8 @@ export default function SavesList(props: { instance: lib.InstanceDetails }) {
{
account.hasPermission("core.instance.save.upload")
? <Upload.Dragger className="save-list-dragger" openFileDialogOnClick={false} {...uploadProps}>
<div
style={{
position: "relative",
zIndex: "1010",
}}
>
<Dropzone disabled={hostOffline} />
{saveTable}
</div>
<Dropzone disabled={hostOffline} />
{saveTable}
</Upload.Dragger>
: saveTable
}
@@ -11,6 +11,8 @@ import ControlContext from "./ControlContext";
import { pages } from "../pages";
import { DraggingContext } from "../model/is_dragging";
type MenuItem = Required<MenuProps>["items"][number];
const { Header, Sider } = Layout;
function isActiveDropzone(element: HTMLElement | null): boolean {
@@ -63,7 +65,7 @@ export default function SiteLayout() {
combinedPages.push(...plugin.pages);
}
let menuItems = [];
let menuItems: MenuItem[] = [];
let menuGroups = new Map();
for (let { sidebarName, sidebarGroup, permission, path } of combinedPages) {
if (
+1 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="../global.d.ts" />
/// <reference path="../global.d.ts" preserve="true" />
export { default as bootstrap } from "./bootstrap";
export { default as notify, notifyErrorHandler } from "./util/notify";
export { default as BaseWebPlugin } from "./BaseWebPlugin";
-3
View File
@@ -4,7 +4,4 @@
{ "path": "../lib/tsconfig.browser.json" },
],
"include": [ "src/**/*.tsx", "src/**/*.ts", "package.json", "global.d.ts" ],
"compilerOptions": {
"outDir": "dist/browser",
}
}