Merge pull request #537 from Hornwitser/refactor-config

Refactor config
This commit is contained in:
Hornwitser authored and GitHub committed 2024-01-11 00:05:44 +01:00
commit c87493af0c
49 files changed
+1386 -2263

No files matched your search

+18 -20
View File
@@ -2,36 +2,34 @@
<sub>This document describes the implementation and inner working of the configuration system in Clusterio, and unless you're developing Clusterio it's probably not going to be very useful for you.</sub> <sub>This document describes the implementation and inner working of the configuration system in Clusterio, and unless you're developing Clusterio it's probably not going to be very useful for you.</sub>
Clusterio uses a group based configuration system to manage settings for the controller, instances, hosts, and the clusterioctl utility. Clusterio uses a field based configuration system to manage settings for the controller, instances, hosts, and the clusterioctl utility.
Plugins get their own config group for the controller and instances which they can add their own fields to. Plugins can add their own config fields for the controller and instances configs.
The fields are defined early in the startup, and the groups and their fields for disabled plugins will still be created. The fields are defined early in the startup, and fields for disabled plugins will still be created.
The built-in config groups and their fields are defined in [packages/lib/config/definitions.js](/packages/lib/config/definitions.js) while plugins can add their own config groups to the `ControllerConfigGroup` and `InstanceConfigGroup` properties of the `info.js` export using subclasses of `PluginConfigGroup`. The built-in config fields are defined in [packages/lib/config/definitions.js](/packages/lib/config/definitions.js) while plugins can add their own config field definitions to the `controllerConfigFields` and `instanceConfigFields` properties of the `info.js` export.
The plugin group has the enabled field pre-defined on it, and it's used to enable/disable plugins. A `<plugin_name>.load_plugin` field is automatically created for each plugin and it's used to enable/disable the loading plugins on startup.
## Defing Fields ## Defing Fields
Fields are defined using the `define` class method on group classes after the groupName have been set and before the class has been finalized. Fields are defined as POJS object properties where the name of the property correspond to the name of the configuration field.
The `define` method takes an object as argument with the following properties: The property name is the primary way the field is accessed both in code and on the command line, as such it should follow the lower\_case\_underscore style and consist of a group name and a field name separated by a dot.
For plugins the group name is the name of the plugin, e.g., the `level` field of the `foo_frobber` plugin would be named `foo_frobber.lavel`.
**access**: **access**:
The locations this config field can be read and modified from. The locations this config field can be read and modified from.
This is an array of strings which can contain the values `"controller"`, `"host"` and `"control"`. This is an array of strings which can contain the values `"controller"`, `"host"` and `"control"`.
If a party is missing in this array then that party will not receive the value of this field when the config is shared, and will be unable to modify the field. If a party is missing in this array then that party will not receive the value of this field when the config is shared, and will be unable to modify the field.
Takes the value of `defaultAccess` set on the config group class if not passed. If not set any party can read and modify this config entry.
Note that instance config groups should have both `"controller"` and `"host"` for all of its fields or unexpected behaviour may occur. Note that instance config fields should have both `"controller"` and `"host"` or unexpected behaviour may occur.
**type**: **type**:
The type of config value this field will support. The type of config value this field will support.
The supported values are boolean, string, number, and object, and if an attept is made to set the field to a value that is not of the right type it will be reject unless it's a string that can be converted to the right type. The supported values are boolean, string, number, and object, and if an attept is made to set the field to a value that is not of the right type it will be reject unless it's a string that can be converted to the right type.
**name**:
Name of the configuration field, this is the primary way the field is accessed, both in code and on the command line.
As such it should follow the lower\_case\_underscore style and not contain any spaces or dots.
**title** (optional): **title** (optional):
Text used to identify the config field in user interfaces. Text used to identify the config field in user interfaces.
This should not contain the grouping used in `name`.
**description** (optional): **description** (optional):
Text used to describe the config field in user interfaces. Text used to describe the config field in user interfaces.
@@ -44,7 +42,7 @@ The `define` method takes an object as argument with the following properties:
True if this field can be set to null. True if this field can be set to null.
Defaults to false. Defaults to false.
**initial_value** (optional if optional is true): **initialValue** (optional if optional is true):
Value this config field should take in a newly initialized config. Value this config field should take in a newly initialized config.
This can also be an async function returning the value to use. This can also be an async function returning the value to use.
@@ -53,24 +51,24 @@ If the value for a field stored in on disk somehow ends up being invalid the fie
## Accessing Fields ## Accessing Fields
On the Config instance there's two ways to access fields: through the set and get methods using dot notation. On the Config instance there's two ways to access fields: through the set and get methods.
E.g.: E.g.:
let value = configInstance.get("group.field"); let value = configInstance.get("group.field");
Or by getting the group first and then calling set or get on that. Or by through the raw fields object (which is best avoided as it doesn't check types or whether the accessed field exists).
E.g.: E.g.:
let value = configInstance.group("group").get("field") let value = configInstance.fields["group.field"]
The set method takes an extra argument, which is the value to set the field to. The set method also takes an extra argument, which is the value to set the field to.
If the value is not valid this will throw an InvalidValue exception, if the group or field doesn't exist it will throw an InvalidField exception. If the value is not valid this will throw an InvalidValue exception, if the field doesn't exist it will throw an InvalidField exception.
## Config Lifecycle ## Config Lifecycle
Values for all config fields are created when the config is initialized, as well as for any fields with missing values when a config is loaded. Values for all config fields are created when the config is initialized, as well as for any fields with missing values when a config is loaded.
Once a field has a value it is never automatically removed, even if the field or group it was part of no longer exists. Once a field has a value it is never automatically removed, even if the field it was part of no longer exists.
This ensures that plugin configuration is not lost should the server be started up without the plugins that defined the configuration installed. This ensures that plugin configuration is not lost should the server be started up without the plugins that defined the configuration installed.
For instance configs, they are kept on the controller and serialized and sent over to the relevant hosts on startup. For instance configs, they are kept on the controller and serialized and sent over to the relevant hosts on startup.
+23 -20
View File
@@ -82,8 +82,8 @@ The following properties are recognized:
This is an optional paramater. This is an optional paramater.
A plugin may have code only for instances but it must still be loaded on the controller in order for it to be possible to load it on an instance. A plugin may have code only for instances but it must still be loaded on the controller in order for it to be possible to load it on an instance.
**InstanceConfigGroup**: **instanceConfigFields**:
Subclass of `PluginConfigGroup` for defining the per instance configuration fields for this plugin. Object mapping instance configuration fields to `FieldDefinitions`for this plugin.
See [Plugin Configuration](#plugin-configuration) See [Plugin Configuration](#plugin-configuration)
**controllerEntrypoint**: **controllerEntrypoint**:
@@ -92,7 +92,7 @@ The following properties are recognized:
A plugin can be made that only runs on the controller. A plugin can be made that only runs on the controller.
**ControllerConfigGroup**: **ControllerConfigGroup**:
Subclass of `PluginConfigGroup` for defining the controller configuration fields for this plugin. Object mapping controller configuration fields to `FieldDefinitions`for this plugin.
See [Plugin Configuration](#plugin-configuration) See [Plugin Configuration](#plugin-configuration)
**ctlEntrypoint**: **ctlEntrypoint**:
@@ -202,32 +202,35 @@ For plugin hooks expections thrown are automatically catched and logged, but for
## Plugin Configuration ## Plugin Configuration
Clusterio provides a configuration system that handles storing, distributing, editing and validating config fields for you. Clusterio provides a configuration system that handles storing, distributing, editing and validating config fields for you.
You can take advantage of it by subclassing `PluginConfigGroup`, setting `defaultAccess` to where config entries can be accessed from, setting the `groupName` to your plugin name, defining fields on it, finalizing it, and passing it as either `ControllerConfigGroup` or `InstanceConfigGroup` in the `info.js` export. You can take advantage of it by declaring config fields under either `controllerConfigFields` or `instanceConfigFields` in the `info.js` export.
For example in info.js: For example in info.js:
```js ```ts
const lib = require("@clusterio/lib"); import type * as lib from "@clusterio/lib";
class ControllerConfigGroup extends lib.PluginConfigGroup { } declare module "@clusterio/lib" {
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"]; // Extend the interface defining available fields so that instance.config.get(...)
ControllerConfigGroup.groupName = "foo_frobber"; // will have our own options.
ControllerConfigGroup.define({ export interface ControllerConfigFields {
name: "level", "foo_frobber.level": number, // If optional is true then this should have | null in addition.
description: "Level of frobnication done", }
type: "number", }
initial_value: 2,
});
ControllerConfigGroup.finalize();
module.exports = { export default {
... ...
ControllerConfigGroup: ControllerConfigGroup, controllerConfigFields: {
}; "foo_frobber.level": {
description: "Level of frobnication done",
type: "number",
initialValue: 2,
},
}
} satisfies lib.PluginDeclaration;
``` ```
Code inside the `ControllerPlugin` class will then be able to access the level config field through the `Config` object at `this.controller.config`, for example in the ControllerPluginClass: Code inside the `ControllerPlugin` class will then be able to access the level config field through the `Config` object at `this.controller.config`, for example in the ControllerPluginClass:
```js ```ts
async init() { async init() {
let level = this.controller.config.get("foo_frobber.level"); let level = this.controller.config.get("foo_frobber.level");
this.logger.info(`I got a frobnication level of ${level}`); this.logger.info(`I got a frobnication level of ${level}`);
+7 -9
View File
@@ -156,7 +156,6 @@ async function handleBootstrapCommand(
return; return;
} }
let controlConfig = new lib.ControlConfig("control"); let controlConfig = new lib.ControlConfig("control");
await controlConfig.init();
controlConfig.set("control.controller_url", Controller.calculateControllerUrl(controllerConfig)); controlConfig.set("control.controller_url", Controller.calculateControllerUrl(controllerConfig));
controlConfig.set( controlConfig.set(
@@ -164,7 +163,7 @@ async function handleBootstrapCommand(
userManager.signUserToken(admin.name), userManager.signUserToken(admin.name),
); );
let content = JSON.stringify(controlConfig.serialize(), null, "\t"); let content = JSON.stringify(controlConfig, null, "\t");
if (args.output === "-") { if (args.output === "-") {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(content); console.log(content);
@@ -317,20 +316,19 @@ async function initialize(): Promise<InitializeParameters> {
logger.info("Loading Plugin info"); logger.info("Loading Plugin info");
const pluginInfos = await lib.loadPluginInfos(pluginList); const pluginInfos = await lib.loadPluginInfos(pluginList);
lib.registerPluginMessages(pluginInfos); lib.registerPluginMessages(pluginInfos);
lib.registerPluginConfigGroups(pluginInfos); lib.addPluginConfigFields(pluginInfos);
lib.finalizeConfigs();
const controllerConfigPath = args.config; const controllerConfigPath = args.config;
logger.info(`Loading config from ${controllerConfigPath}`); logger.info(`Loading config from ${controllerConfigPath}`);
const controllerConfig = new lib.ControllerConfig("controller"); let controllerConfig = new lib.ControllerConfig("controller");
try { try {
let fileData = await fs.readFile(controllerConfigPath, { encoding: "utf8" }); let jsonConfig = JSON.parse(await fs.readFile(controllerConfigPath, { encoding: "utf8" }));
await controllerConfig.load(JSON.parse(fileData)); controllerConfig = lib.ControllerConfig.fromJSON(jsonConfig, "controller");
} catch (err: any) { } catch (err: any) {
if (err.code === "ENOENT") { if (err.code === "ENOENT") {
logger.info("Config not found, initializing new config"); logger.info("Config not found, initializing new config");
await controllerConfig.init(); controllerConfig = new lib.ControllerConfig("controller");
} else { } else {
throw new lib.StartupError(`Failed to load ${controllerConfigPath}: ${err.message}`); throw new lib.StartupError(`Failed to load ${controllerConfigPath}: ${err.message}`);
@@ -343,7 +341,7 @@ async function initialize(): Promise<InitializeParameters> {
let bytes = await asyncRandomBytes(256); let bytes = await asyncRandomBytes(256);
controllerConfig.set("controller.auth_secret", bytes.toString("base64")); controllerConfig.set("controller.auth_secret", bytes.toString("base64"));
await lib.safeOutputFile( await lib.safeOutputFile(
controllerConfigPath, JSON.stringify(controllerConfig.serialize(), null, "\t") controllerConfigPath, JSON.stringify(controllerConfig, null, "\t")
); );
} }
@@ -1,5 +1,5 @@
import type { import type {
CollectorResult, ConfigGroup, Event, InstanceStatus, Logger, CollectorResult, Event, InstanceStatus, Logger,
ModPack, ModInfo, PlayerEvent, PluginNodeEnvInfo, ModPack, ModInfo, PlayerEvent, PluginNodeEnvInfo,
} from "@clusterio/lib"; } from "@clusterio/lib";
import type Controller from "./Controller"; import type Controller from "./Controller";
@@ -99,12 +99,11 @@ export default class BaseControllerPlugin {
* Invoked after the value of the config field given by `field` has * Invoked after the value of the config field given by `field` has
* changed on the controller. * changed on the controller.
* *
* @param group -
* The group who's field got changed.
* @param field - Name of the field that changed. * @param field - Name of the field that changed.
* @param curr - The current value of the field.
* @param prev - The previous value of the field. * @param prev - The previous value of the field.
*/ */
async onControllerConfigFieldChanged(group: ConfigGroup, field: string, prev: unknown) { } async onControllerConfigFieldChanged(field: string, curr: unknown, prev: unknown) { }
/** /**
* Called when the value of an instance config field changed. * Called when the value of an instance config field changed.
@@ -114,12 +113,11 @@ export default class BaseControllerPlugin {
* *
* @param instance - * @param instance -
* The instance the config changed on. * The instance the config changed on.
* @param group -
* The group who's field got changed.
* @param field - Name of the field that changed. * @param field - Name of the field that changed.
* @param curr - The current value of the field.
* @param prev - The previous value of the field. * @param prev - The previous value of the field.
*/ */
async onInstanceConfigFieldChanged(instance: InstanceInfo, group: ConfigGroup, field: string, prev: unknown) { } async onInstanceConfigFieldChanged(instance: InstanceInfo, field: string, curr: unknown, prev: unknown) { }
/** /**
* Called before collecting Prometheus metrics * Called before collecting Prometheus metrics
+11 -13
View File
@@ -169,17 +169,17 @@ export default class ControlConnection extends BaseConnection {
throw new Error("Should be unreachable"); throw new Error("Should be unreachable");
} }
async handleControllerConfigGetRequest(): Promise<lib.RawConfig> { async handleControllerConfigGetRequest() {
return new lib.RawConfig(this._controller.config.serialize("control")); return this._controller.config.toRemote("control");
} }
async handleControllerConfigSetFieldRequest(request: lib.ControllerConfigSetFieldRequest) { async handleControllerConfigSetFieldRequest(request: lib.ControllerConfigSetFieldRequest) {
this._controller.config.set(request.field, request.value, "control"); this._controller.config.set(request.field as keyof lib.ControllerConfigFields, request.value, "control");
} }
async handleControllerConfigSetPropRequest(request: lib.ControllerConfigSetPropRequest) { async handleControllerConfigSetPropRequest(request: lib.ControllerConfigSetPropRequest) {
let { field, prop, value } = request; let { field, prop, value } = request;
this._controller.config.setProp(field, prop, value, "control"); this._controller.config.setProp(field as keyof lib.ControllerConfigFields, prop, value, "control");
} }
async handleHostRevokeTokensRequest(request: lib.HostRevokeTokensRequest) { async handleHostRevokeTokensRequest(request: lib.HostRevokeTokensRequest) {
@@ -211,8 +211,7 @@ export default class ControlConnection extends BaseConnection {
} }
async handleHostConfigCreateRequest(request: lib.HostConfigCreateRequest) { async handleHostConfigCreateRequest(request: lib.HostConfigCreateRequest) {
let hostConfig = new lib.HostConfig("control"); const hostConfig = new lib.HostConfig("host");
await hostConfig.init();
hostConfig.set("host.controller_url", this._controller.getControllerUrl()); hostConfig.set("host.controller_url", this._controller.getControllerUrl());
if (request.id !== undefined) { if (request.id !== undefined) {
@@ -225,7 +224,7 @@ export default class ControlConnection extends BaseConnection {
this.user.checkPermission("core.host.generate_token"); this.user.checkPermission("core.host.generate_token");
hostConfig.set("host.controller_token", this._controller.generateHostToken(hostConfig.get("host.id"))); hostConfig.set("host.controller_token", this._controller.generateHostToken(hostConfig.get("host.id")));
} }
return new lib.RawConfig(hostConfig.serialize()); return hostConfig.toJSON();
} }
async handleInstanceDetailsGetRequest(request: lib.InstanceDetailsGetRequest) { async handleInstanceDetailsGetRequest(request: lib.InstanceDetailsGetRequest) {
@@ -236,10 +235,9 @@ export default class ControlConnection extends BaseConnection {
return [...this._controller.instances.values()].map(instance => instance.toInstanceDetails()); return [...this._controller.instances.values()].map(instance => instance.toInstanceDetails());
} }
// XXX should probably add a hook for host reuqests?
async handleInstanceCreateRequest(request: lib.InstanceCreateRequest) { async handleInstanceCreateRequest(request: lib.InstanceCreateRequest) {
let instanceConfig = new lib.InstanceConfig("controller"); const instanceConfig = new lib.InstanceConfig("controller");
await instanceConfig.load(request.config as lib.SerializedConfig); instanceConfig.update(request.config, false, "control");
await this._controller.instanceCreate(instanceConfig); await this._controller.instanceCreate(instanceConfig);
} }
@@ -249,7 +247,7 @@ export default class ControlConnection extends BaseConnection {
async handleInstanceConfigGetRequest(request: lib.InstanceConfigGetRequest) { async handleInstanceConfigGetRequest(request: lib.InstanceConfigGetRequest) {
let instance = this._controller.getRequestInstance(request.instanceId); let instance = this._controller.getRequestInstance(request.instanceId);
return new lib.InstanceConfigGetRequest.Response(instance.config.serialize("control")); return instance.config.toRemote("control");
} }
async handleInstanceConfigSetFieldRequest(request: lib.InstanceConfigSetFieldRequest) { async handleInstanceConfigSetFieldRequest(request: lib.InstanceConfigSetFieldRequest) {
@@ -263,14 +261,14 @@ export default class ControlConnection extends BaseConnection {
throw new lib.RequestError("Setting instance.id is not supported"); throw new lib.RequestError("Setting instance.id is not supported");
} }
instance.config.set(request.field, request.value, "control"); instance.config.set(request.field as keyof lib.InstanceConfigFields, request.value, "control");
await this._controller.instanceConfigUpdated(instance); await this._controller.instanceConfigUpdated(instance);
} }
async handleInstanceConfigSetPropRequest(request: lib.InstanceConfigSetPropRequest) { async handleInstanceConfigSetPropRequest(request: lib.InstanceConfigSetPropRequest) {
let instance = this._controller.getRequestInstance(request.instanceId); let instance = this._controller.getRequestInstance(request.instanceId);
let { field, prop, value } = request; let { field, prop, value } = request;
instance.config.setProp(field, prop, value, "control"); instance.config.setProp(field as keyof lib.InstanceConfigFields, prop, value, "control");
await this._controller.instanceConfigUpdated(instance); await this._controller.instanceConfigUpdated(instance);
} }
+14 -17
View File
@@ -216,11 +216,11 @@ export default class Controller {
this._startDevServer(args); this._startDevServer(args);
} }
this.config.on("fieldChanged", (group, field, prev) => { this.config.on("fieldChanged", (field, curr, prev) => {
if (group.name === "controller" && field === "autosave_interval") { if (field === "controller.autosave_interval") {
this.onAutosaveIntervalChanged(); this.onAutosaveIntervalChanged();
} }
lib.invokeHook(this.plugins, "onControllerConfigFieldChanged", group, field, prev); lib.invokeHook(this.plugins, "onControllerConfigFieldChanged", field, curr, prev);
}); });
for (let instance of this.instances.values()) { for (let instance of this.instances.values()) {
this.addInstanceHooks(instance); this.addInstanceHooks(instance);
@@ -421,7 +421,7 @@ export default class Controller {
private async _saveDataInternal() { private async _saveDataInternal() {
if (this.config.dirty) { if (this.config.dirty) {
this.config.dirty = false; this.config.dirty = false;
await lib.safeOutputFile(this.configPath, JSON.stringify(this.config.serialize(), null, "\t")); await lib.safeOutputFile(this.configPath, JSON.stringify(this.config, null, "\t"));
} }
let databaseDirectory = this.config.get("controller.database_directory"); let databaseDirectory = this.config.get("controller.database_directory");
@@ -495,11 +495,9 @@ export default class Controller {
) as Static<typeof InstanceInfo.jsonSchema>[]; ) as Static<typeof InstanceInfo.jsonSchema>[];
for (let json of serialized) { for (let json of serialized) {
if (!json.config) { // migrate: from pre Alpha 14 format. if (!json.config) { // migrate: from pre Alpha 14 format.
json = { config: json, status: "running" }; // Use running to force updatedAt json = { config: json as any, status: "running" }; // Use running to force updatedAt
} }
let instanceConfig = new lib.InstanceConfig("controller"); const instance = InstanceInfo.fromJSON(json, "controller");
await instanceConfig.load(json.config as lib.SerializedConfig);
let instance = InstanceInfo.fromJSON(json, instanceConfig);
const status = instance.config.get("instance.assigned_host") === null ? "unassigned" : "unknown"; const status = instance.config.get("instance.assigned_host") === null ? "unassigned" : "unknown";
if (instance.status !== status) { if (instance.status !== status) {
instance.status = status; instance.status = status;
@@ -519,7 +517,7 @@ export default class Controller {
} }
static async saveInstances(filePath: string, instances: Map<number, InstanceInfo>) { static async saveInstances(filePath: string, instances: Map<number, InstanceInfo>) {
let serialized = [...instances.values()].map(instance => instance.toJSON()); let serialized = [...instances.values()];
await lib.safeOutputFile(filePath, JSON.stringify(serialized, null, "\t")); await lib.safeOutputFile(filePath, JSON.stringify(serialized, null, "\t"));
} }
@@ -690,7 +688,6 @@ export default class Controller {
* *
* @example * @example
* let instanceConfig = new lib.InstanceConfig("controller"); * let instanceConfig = new lib.InstanceConfig("controller");
* await instanceConfig.init();
* instanceConfig.set("instance.name", "My instance"); * instanceConfig.set("instance.name", "My instance");
* let instance = await controller.instanceAssign(instanceConfig); * let instance = await controller.instanceAssign(instanceConfig);
* await controller.instanceAssign(instance.id, hostId); * await controller.instanceAssign(instance.id, hostId);
@@ -802,11 +799,11 @@ export default class Controller {
this.clearSavesOfInstance(instanceId); this.clearSavesOfInstance(instanceId);
// Assign to target // Assign to target
instance.config.set("instance.assigned_host", hostId); instance.config.set("instance.assigned_host", hostId ?? null);
// "fieldChanged" event handler will set this.instancesDirty // "fieldChanged" event handler will set this.instancesDirty
if (hostId !== undefined && newHostConnection) { if (hostId !== undefined && newHostConnection) {
await newHostConnection.send( await newHostConnection.send(
new lib.InstanceAssignInternalRequest(instanceId, instance.config.serialize("host")) new lib.InstanceAssignInternalRequest(instanceId, instance.config.toRemote("host"))
); );
} else { } else {
instance.status = "unassigned"; instance.status = "unassigned";
@@ -855,21 +852,21 @@ export default class Controller {
let connection = this.wsServer.hostConnections.get(hostId); let connection = this.wsServer.hostConnections.get(hostId);
if (connection) { if (connection) {
await connection.send( await connection.send(
new lib.InstanceAssignInternalRequest(instance.id, instance.config.serialize("host")) new lib.InstanceAssignInternalRequest(instance.id, instance.config.toRemote("host"))
); );
} }
} }
} }
addInstanceHooks(instance: InstanceInfo) { addInstanceHooks(instance: InstanceInfo) {
instance.config.on("fieldChanged", (group: lib.ConfigGroup, field: string, prev: any) => { instance.config.on("fieldChanged", (field: string, curr: any, prev: any) => {
instance.updatedAt = Date.now(); instance.updatedAt = Date.now();
if (group.name === "instance" && field === "name") { if (field === "instance.name") {
this.instanceDetailsUpdated([instance]); this.instanceDetailsUpdated([instance]);
} }
this.instancesDirty = true; this.instancesDirty = true;
lib.invokeHook(this.plugins, "onInstanceConfigFieldChanged", instance, group, field, prev); lib.invokeHook(this.plugins, "onInstanceConfigFieldChanged", instance, field, curr, prev);
}); });
} }
@@ -991,7 +988,7 @@ export default class Controller {
logger.warn(`Unable to load dist/web/manifest.json for plugin ${pluginInfo.name}`); logger.warn(`Unable to load dist/web/manifest.json for plugin ${pluginInfo.name}`);
} }
if (!this.config.group(pluginInfo.name).get("load_plugin")) { if (!this.config.get(`${pluginInfo.name}.load_plugin` as keyof lib.ControllerConfigFields)) {
continue; continue;
} }
+4 -4
View File
@@ -189,7 +189,7 @@ export default class HostConnection extends BaseConnection {
for (let instance of this._controller.instances.values()) { for (let instance of this._controller.instances.values()) {
if (instance.config.get("instance.assigned_host") === this._id) { if (instance.config.get("instance.assigned_host") === this._id) {
await this.send( await this.send(
new lib.InstanceAssignInternalRequest(instance.id, instance.config.serialize("host")) new lib.InstanceAssignInternalRequest(instance.id, instance.config.toRemote("host"))
); );
} }
} }
@@ -197,8 +197,8 @@ export default class HostConnection extends BaseConnection {
// Assign instances the host has but controller does not // Assign instances the host has but controller does not
const instanceUpdates: InstanceInfo[] = []; const instanceUpdates: InstanceInfo[] = [];
for (let instanceData of request.instances) { for (let instanceData of request.instances) {
let instanceConfig = new lib.InstanceConfig("controller"); const instanceConfig = new lib.InstanceConfig("controller");
await instanceConfig.load(instanceData.config as lib.SerializedConfig, "host"); instanceConfig.update(instanceData.config, false, "host");
let controllerInstance = this._controller.instances.get(instanceConfig.get("instance.id")); let controllerInstance = this._controller.instances.get(instanceConfig.get("instance.id"));
if (controllerInstance) { if (controllerInstance) {
@@ -237,7 +237,7 @@ export default class HostConnection extends BaseConnection {
this._controller.addInstanceHooks(newInstance); this._controller.addInstanceHooks(newInstance);
await this.send( await this.send(
new lib.InstanceAssignInternalRequest( new lib.InstanceAssignInternalRequest(
instanceConfig.get("instance.id"), instanceConfig.serialize("host") instanceConfig.get("instance.id"), instanceConfig.toRemote("host")
) )
); );
instanceUpdates.push(newInstance); instanceUpdates.push(newInstance);
+3 -12
View File
@@ -18,30 +18,21 @@ export default class InstanceInfo {
} }
static jsonSchema = Type.Object({ static jsonSchema = Type.Object({
"config": Type.Object({}), "config": lib.InstanceConfig.jsonSchema,
"status": lib.InstanceStatus, "status": lib.InstanceStatus,
"gamePort": Type.Optional(Type.Number()), "gamePort": Type.Optional(Type.Number()),
"updatedAt": Type.Optional(Type.Number()), "updatedAt": Type.Optional(Type.Number()),
}); });
static fromJSON(json: Static<typeof this.jsonSchema>, config: lib.InstanceConfig) { static fromJSON(json: Static<typeof this.jsonSchema>, location: lib.ConfigLocation) {
return new this( return new this(
config, lib.InstanceConfig.fromJSON(json.config, location),
json.status, json.status,
json.gamePort, json.gamePort,
json.updatedAt, json.updatedAt,
); );
} }
toJSON(): Static<typeof InstanceInfo.jsonSchema> {
return {
config: this.config.serialize(),
status: this.status,
gamePort: this.gamePort,
updatedAt: this.updatedAt,
};
}
toInstanceDetails() { toInstanceDetails() {
return new lib.InstanceDetails( return new lib.InstanceDetails(
this.config.get("instance.name"), this.config.get("instance.name"),
+6 -1
View File
@@ -109,7 +109,12 @@ function getPlugins(req: Request, res: Response) {
for (let pluginInfo of req.app.locals.controller.pluginInfos) { for (let pluginInfo of req.app.locals.controller.pluginInfos) {
let name = pluginInfo.name; let name = pluginInfo.name;
let loaded = req.app.locals.controller.plugins.has(name); let loaded = req.app.locals.controller.plugins.has(name);
let enabled = loaded && req.app.locals.controller.config.group(pluginInfo.name).get("load_plugin") as boolean; let enabled = loaded && req.app.locals.controller.config.get(
`${pluginInfo.name}.load_plugin` as keyof lib.ControllerConfigFields,
) as unknown as boolean;
// Note: Cast through unknown is needed because load_plugin is
// defined at runtime and no other fields in the controller config
// currently have the boolean type.
let web: { main:any, error:string|undefined } = { main: undefined, error: undefined}; let web: { main:any, error:string|undefined } = { main: undefined, error: undefined};
let devPlugins = req.app.locals.devPlugins; let devPlugins = req.app.locals.devPlugins;
if (devPlugins && devPlugins.has(name)) { if (devPlugins && devPlugins.has(name)) {
+9 -9
View File
@@ -114,8 +114,7 @@ export class Control extends lib.Link {
async function loadPlugins(pluginList: Map<string, string>) { async function loadPlugins(pluginList: Map<string, string>) {
let pluginInfos = await lib.loadPluginInfos(pluginList); let pluginInfos = await lib.loadPluginInfos(pluginList);
lib.registerPluginMessages(pluginInfos); lib.registerPluginMessages(pluginInfos);
lib.registerPluginConfigGroups(pluginInfos); lib.addPluginConfigFields(pluginInfos);
lib.finalizeConfigs();
let ctlPlugins = new Map<string, BaseCtlPlugin>(); let ctlPlugins = new Map<string, BaseCtlPlugin>();
for (let pluginInfo of pluginInfos) { for (let pluginInfo of pluginInfos) {
@@ -219,14 +218,15 @@ async function startControl() {
; ;
logger.verbose(`Loading config from ${args.config}`); logger.verbose(`Loading config from ${args.config}`);
let controlConfig = new lib.ControlConfig("control"); let controlConfig;
try { try {
await controlConfig.load(JSON.parse(await fs.readFile(args.config, "utf8"))); const jsonConfig = JSON.parse(await fs.readFile(args.config, "utf8"));
controlConfig = lib.ControlConfig.fromJSON(jsonConfig, "control");
} catch (err: any) { } catch (err: any) {
if (err.code === "ENOENT") { if (err.code === "ENOENT") {
logger.verbose("Config not found, initializing new config"); logger.verbose("Config not found, initializing new config");
await controlConfig.init(); controlConfig = new lib.ControlConfig("control");
} else { } else {
throw new lib.StartupError(`Failed to load ${args.config}: ${err.message}`); throw new lib.StartupError(`Failed to load ${args.config}: ${err.message}`);
@@ -260,16 +260,16 @@ async function startControl() {
} }
let tlsCa: string | undefined; let tlsCa: string | undefined;
let tlsCaPath = controlConfig.get("control.tls_ca") as string | null; let tlsCaPath = controlConfig.get("control.tls_ca");
if (tlsCaPath) { if (tlsCaPath) {
tlsCa = await fs.readFile(tlsCaPath, "utf8"); tlsCa = await fs.readFile(tlsCaPath, "utf8");
} }
let controlConnector = new ControlConnector( let controlConnector = new ControlConnector(
controlConfig.get("control.controller_url") as string, controlConfig.get("control.controller_url")!,
controlConfig.get("control.max_reconnect_delay") as number, controlConfig.get("control.max_reconnect_delay"),
tlsCa, tlsCa,
controlConfig.get("control.controller_token") as string, controlConfig.get("control.controller_token")!,
); );
let control = new Control(controlConnector, controlConfig, tlsCa, ctlPlugins); let control = new Control(controlConnector, controlConfig, tlsCa, ctlPlugins);
try { try {
+38 -45
View File
@@ -56,29 +56,27 @@ async function configToKeyVal(data: string) {
return final; return final;
} }
async function serializedConfigToString( function serializedConfigToString(
serializedConfig: any, serializedConfig: lib.ConfigSchema,
configGroup: typeof lib.Config, configGroup: typeof lib.ControllerConfig | typeof lib.InstanceConfig,
disallowedList: Record<string, unknown>, disallowedList: Record<string, unknown>,
) { ) {
let allConfigElements = ""; let allConfigElements = "";
for (let group of serializedConfig.groups) { for (let [name, value] of Object.entries(serializedConfig)) {
for (let [name, value] of Object.entries(group.fields)) { if (name in disallowedList) {
if (`${group.name}.${name}` in disallowedList) { continue;
continue;
}
let desc = "";
try {
desc += configGroup.groups.get(group.name)!._definitions.get(name)!.description;
} catch (err) {
desc += "No description found";
}
// split onto two lines for readability and es-lint
if (String(value) === "null") {
value = "";
}
allConfigElements += `${group.name}.${name} = ${value}\n\n`;
} }
let desc = "";
try {
desc += (configGroup.fieldDefinitions as any)[name]!.description;
} catch (err) {
desc += "No description found";
}
// split onto two lines for readability and es-lint
if (String(value) === "null") {
value = "";
}
allConfigElements += `${name} = ${value}\n\n`;
} }
return allConfigElements; return allConfigElements;
} }
@@ -91,12 +89,10 @@ const controllerConfigCommands = new lib.CommandTree({
controllerConfigCommands.add(new lib.Command({ controllerConfigCommands.add(new lib.Command({
definition: ["list", "List controller configuration"], definition: ["list", "List controller configuration"],
handler: async function(args: object, control: Control) { handler: async function(args: object, control: Control) {
let response = await control.send(new lib.ControllerConfigGetRequest()); let config = await control.send(new lib.ControllerConfigGetRequest());
for (let group of (response.serializedConfig as any).groups) { for (let [name, value] of Object.entries(config)) {
for (let [name, value] of Object.entries(group.fields)) { print(`${name} ${JSON.stringify(value)}`);
print(`${group.name}.${name} ${JSON.stringify(value)}`);
}
} }
}, },
})); }));
@@ -115,7 +111,7 @@ controllerConfigCommands.add(new lib.Command({
} else if (args.value === undefined) { } else if (args.value === undefined) {
args.value = ""; args.value = "";
} }
await control.send(new lib.ControllerConfigSetFieldRequest(args.field as string, args.value as string)); await control.send(new lib.ControllerConfigSetFieldRequest(args.field, args.value));
}, },
})); }));
@@ -156,15 +152,15 @@ controllerConfigCommands.add(new lib.Command({
}); });
}], }],
handler: async function(args: { editor: string }, control: Control) { handler: async function(args: { editor: string }, control: Control) {
let response = await control.send(new lib.ControllerConfigGetRequest()); let config = await control.send(new lib.ControllerConfigGetRequest());
let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir()); let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir());
let editor = await getEditor(args.editor); let editor = await getEditor(args.editor);
if (editor === undefined) { if (editor === undefined) {
throw new lib.CommandError(`No editor avalible. Checked CLI input, EDITOR and VISUAL env vars throw new lib.CommandError(`No editor avalible. Checked CLI input, EDITOR and VISUAL env vars
Try "ctl controller config edit <editor of choice>"`); Try "ctl controller config edit <editor of choice>"`);
} }
let allConfigElements = await serializedConfigToString( let allConfigElements = serializedConfigToString(
response.serializedConfig, lib.ControllerConfig, {} config, lib.ControllerConfig, {}
); );
await fs.writeFile(tmpFile, allConfigElements); await fs.writeFile(tmpFile, allConfigElements);
let editorSpawn = child_process.spawn(editor, [tmpFile], { let editorSpawn = child_process.spawn(editor, [tmpFile], {
@@ -214,7 +210,7 @@ const controllerPluginCommands = new lib.CommandTree({
controllerPluginCommands.add(new lib.Command({ controllerPluginCommands.add(new lib.Command({
definition: ["list", "List plugins on controller"], definition: ["list", "List plugins on controller"],
handler: async function(args: object, control: Control) { handler: async function(args: object, control: Control) {
let url = new URL(control.config.get("control.controller_url") as string); let url = new URL(control.config.get("control.controller_url")!);
url.pathname += "api/plugins"; url.pathname += "api/plugins";
let response = await phin<[]>({ let response = await phin<[]>({
url, url,
@@ -272,11 +268,11 @@ hostCommands.add(new lib.Command({
args: { id?: number, name?: string, generateToken: boolean, output: string }, args: { id?: number, name?: string, generateToken: boolean, output: string },
control: Control control: Control
) { ) {
let rawConfig = await control.send( let config = await control.send(
new lib.HostConfigCreateRequest(args.id, args.name, args.generateToken) new lib.HostConfigCreateRequest(args.id, args.name, args.generateToken)
); );
let content = JSON.stringify(rawConfig.serializedConfig, null, "\t"); let content = JSON.stringify(config, null, "\t");
if (args.output === "-") { if (args.output === "-") {
print(content); print(content);
} else { } else {
@@ -315,12 +311,11 @@ instanceCommands.add(new lib.Command({
}], }],
handler: async function(args: { name: string, id?: number }, control: Control) { handler: async function(args: { name: string, id?: number }, control: Control) {
let instanceConfig = new lib.InstanceConfig("control"); let instanceConfig = new lib.InstanceConfig("control");
await instanceConfig.init();
if (args.id !== undefined) { if (args.id !== undefined) {
instanceConfig.set("instance.id", args.id); instanceConfig.set("instance.id", args.id);
} }
instanceConfig.set("instance.name", args.name); instanceConfig.set("instance.name", args.name);
let serializedConfig = instanceConfig.serialize("controller"); const serializedConfig = instanceConfig.toRemote("controller");
await control.send(new lib.InstanceCreateRequest(serializedConfig)); await control.send(new lib.InstanceCreateRequest(serializedConfig));
}, },
})); }));
@@ -334,12 +329,10 @@ instanceConfigCommands.add(new lib.Command({
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, control: Control) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(control, args.instance);
let response = await control.send(new lib.InstanceConfigGetRequest(instanceId)); let config = await control.send(new lib.InstanceConfigGetRequest(instanceId));
for (let group of response.serializedConfig.groups) { for (let [name, value] of Object.entries(config)) {
for (let [name, value] of Object.entries(group.fields)) { print(`${name} ${JSON.stringify(value)}`);
print(`${group.name}.${name} ${JSON.stringify(value)}`);
}
} }
}, },
})); }));
@@ -427,7 +420,7 @@ instanceConfigCommands.add(new lib.Command({
}], }],
handler: async function(args: { instance: string, editor: string }, control: Control) { handler: async function(args: { instance: string, editor: string }, control: Control) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(control, args.instance);
let response = await control.send(new lib.InstanceConfigGetRequest(instanceId)); let config = await control.send(new lib.InstanceConfigGetRequest(instanceId));
let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir()); let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir());
let editor = await getEditor(args.editor); let editor = await getEditor(args.editor);
if (editor === undefined) { if (editor === undefined) {
@@ -435,8 +428,8 @@ instanceConfigCommands.add(new lib.Command({
Try "ctl controller config edit <editor of choice>"`); Try "ctl controller config edit <editor of choice>"`);
} }
let disallowedList = {"instance.id": 0, "instance.assigned_host": 0, "factorio.settings": 0}; let disallowedList = {"instance.id": 0, "instance.assigned_host": 0, "factorio.settings": 0};
let allConfigElements = await serializedConfigToString( let allConfigElements = serializedConfigToString(
response.serializedConfig, config,
lib.InstanceConfig, lib.InstanceConfig,
disallowedList disallowedList
); );
@@ -613,7 +606,7 @@ instanceSaveCommands.add(new lib.Command({
let content = await fs.readFile(args.filepath); let content = await fs.readFile(args.filepath);
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(control, args.instance);
let url = new URL(control.config.get("control.controller_url") as string); let url = new URL(control.config.get("control.controller_url")!);
url.pathname += "api/upload-save"; url.pathname += "api/upload-save";
url.searchParams.append("instance_id", String(instanceId)); url.searchParams.append("instance_id", String(instanceId));
url.searchParams.append("filename", filename); url.searchParams.append("filename", filename);
@@ -695,7 +688,7 @@ instanceSaveCommands.add(new lib.Command({
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(control, args.instance);
let streamId = await control.send(new lib.InstanceDownloadSaveRequest(instanceId, args.save)); let streamId = await control.send(new lib.InstanceDownloadSaveRequest(instanceId, args.save));
let url = new URL(control.config.get("control.controller_url") as string); let url = new URL(control.config.get("control.controller_url")!);
url.pathname += `api/stream/${streamId}`; url.pathname += `api/stream/${streamId}`;
let response = await phin({ let response = await phin({
url, method: "GET", url, method: "GET",
@@ -1281,7 +1274,7 @@ modCommands.add(new lib.Command({
// phin doesn't support streaming requests :( // phin doesn't support streaming requests :(
let content = await fs.readFile(args.file); let content = await fs.readFile(args.file);
let url = new URL(control.config.get("control.controller_url") as string); let url = new URL(control.config.get("control.controller_url")!);
url.pathname += "api/upload-mod"; url.pathname += "api/upload-mod";
url.searchParams.append("filename", filename); url.searchParams.append("filename", filename);
@@ -1325,7 +1318,7 @@ modCommands.add(new lib.Command({
handler: async function(args: { name: string, modVersion: string }, control: Control) { handler: async function(args: { name: string, modVersion: string }, control: Control) {
let streamId = await control.send(new lib.ModDownloadRequest(args.name, args.modVersion)); let streamId = await control.send(new lib.ModDownloadRequest(args.name, args.modVersion));
let url = new URL(control.config.get("control.controller_url") as string); let url = new URL(control.config.get("control.controller_url")!);
url.pathname += `api/stream/${streamId}`; url.pathname += `api/stream/${streamId}`;
let response = await phin({ let response = await phin({
url, method: "GET", url, method: "GET",
+5 -5
View File
@@ -142,18 +142,18 @@ async function startHost() {
logger.info("Loading Plugin info"); logger.info("Loading Plugin info");
let pluginInfos = await lib.loadPluginInfos(pluginList); let pluginInfos = await lib.loadPluginInfos(pluginList);
lib.registerPluginMessages(pluginInfos); lib.registerPluginMessages(pluginInfos);
lib.registerPluginConfigGroups(pluginInfos); lib.addPluginConfigFields(pluginInfos);
lib.finalizeConfigs();
logger.info(`Loading config from ${args.config}`); logger.info(`Loading config from ${args.config}`);
let hostConfig = new lib.HostConfig("host"); let hostConfig;
try { try {
await hostConfig.load(JSON.parse(await fs.readFile(args.config, "utf8"))); const jsonConfig = JSON.parse(await fs.readFile(args.config, "utf8"));
hostConfig = lib.HostConfig.fromJSON(jsonConfig, "host");
} catch (err: any) { } catch (err: any) {
if (err.code === "ENOENT") { if (err.code === "ENOENT") {
logger.info("Config not found, initializing new config"); logger.info("Config not found, initializing new config");
await hostConfig.init(); hostConfig = new lib.HostConfig("host");
} else { } else {
throw new lib.StartupError(`Failed to load ${args.config}: ${err.message}`); throw new lib.StartupError(`Failed to load ${args.config}: ${err.message}`);
+3 -4
View File
@@ -1,5 +1,5 @@
import type { import type {
ConfigGroup, CollectorResult, Logger, ParsedFactorioOutput, PlayerEvent, PluginNodeEnvInfo, CollectorResult, Logger, ParsedFactorioOutput, PlayerEvent, PluginNodeEnvInfo,
} from "@clusterio/lib"; } from "@clusterio/lib";
import type Host from "./Host"; import type Host from "./Host";
@@ -46,12 +46,11 @@ export default class BaseHostPlugin {
* Invoked after the value of the config field given by `field` has * Invoked after the value of the config field given by `field` has
* changed on this host. * changed on this host.
* *
* @param group -
* The group who's field got changed.
* @param field - Name of the field that changed. * @param field - Name of the field that changed.
* @param curr - The current value of the field.
* @param prev - The previous value of the field. * @param prev - The previous value of the field.
*/ */
async onHostConfigFieldChanged(group: ConfigGroup, field: string, prev: unknown) { } async onHostConfigFieldChanged(field: string, curr: unknown, prev: unknown) { }
/** /**
* Called before collecting Prometheus metrics * Called before collecting Prometheus metrics
+3 -4
View File
@@ -1,5 +1,5 @@
import type { import type {
ConfigGroup, CollectorResult, Logger, ParsedFactorioOutput, PlayerEvent, PluginNodeEnvInfo, CollectorResult, Logger, ParsedFactorioOutput, PlayerEvent, PluginNodeEnvInfo,
} from "@clusterio/lib"; } from "@clusterio/lib";
import type Instance from "./Instance"; import type Instance from "./Instance";
import type Host from "./Host"; import type Host from "./Host";
@@ -70,12 +70,11 @@ export default class BaseInstancePlugin {
* Invoked after the value of the config field given by `field` has * Invoked after the value of the config field given by `field` has
* changed. * changed.
* *
* @param group -
* The group who's field got changed.
* @param field - Name of the field that changed. * @param field - Name of the field that changed.
* @param curr - The current value of the field.
* @param prev - The previous value of the field. * @param prev - The previous value of the field.
*/ */
async onInstanceConfigFieldChanged(group: ConfigGroup, field: string, prev: unknown) { } async onInstanceConfigFieldChanged(field: string, curr: unknown, prev: unknown) { }
/** /**
* Called before collecting Prometheus metrics * Called before collecting Prometheus metrics
+12 -11
View File
@@ -47,7 +47,8 @@ async function discoverInstances(instancesDir: string) {
let configPath = path.join(instancesDir, entry.name, "instance.json"); let configPath = path.join(instancesDir, entry.name, "instance.json");
try { try {
await instanceConfig.load(JSON.parse(await fs.readFile(configPath, "utf8"))); const jsonConfig = JSON.parse(await fs.readFile(configPath, "utf8"));
instanceConfig = lib.InstanceConfig.fromJSON(jsonConfig, "host");
} catch (err: any) { } catch (err: any) {
if (err.code === "ENOENT") { if (err.code === "ENOENT") {
@@ -286,8 +287,8 @@ export default class Host extends lib.Link {
this.configPath = hostConfigPath; this.configPath = hostConfigPath;
this.config = hostConfig; this.config = hostConfig;
this.config.on("fieldChanged", (group, field, prev) => { this.config.on("fieldChanged", (name, curr, prev) => {
lib.invokeHook(this.plugins, "onHostConfigFieldChanged", group, field, prev); lib.invokeHook(this.plugins, "onHostConfigFieldChanged", name, curr, prev);
}); });
this.connector.on("hello", data => { this.connector.on("hello", data => {
@@ -361,7 +362,7 @@ export default class Host extends lib.Link {
async loadPlugins() { async loadPlugins() {
for (let pluginInfo of this.pluginInfos) { for (let pluginInfo of this.pluginInfos) {
if (!this.config.group(pluginInfo.name).get("load_plugin")) { if (!this.config.get(`${pluginInfo.name}.load_plugin` as keyof lib.HostConfigFields)) {
continue; continue;
} }
@@ -564,17 +565,17 @@ export default class Host extends lib.Link {
let { instanceId, config } = request; let { instanceId, config } = request;
let instanceInfo = this.instanceInfos.get(instanceId); let instanceInfo = this.instanceInfos.get(instanceId);
if (instanceInfo) { if (instanceInfo) {
instanceInfo.config.update(config as any, true, "controller"); instanceInfo.config.update(config, true, "controller");
logger.verbose(`Updated config for ${instanceInfo.path}`, this.instanceLogMeta(instanceId, instanceInfo)); logger.verbose(`Updated config for ${instanceInfo.path}`, this.instanceLogMeta(instanceId, instanceInfo));
} else { } else {
instanceInfo = this.discoveredInstanceInfos.get(instanceId); instanceInfo = this.discoveredInstanceInfos.get(instanceId);
if (instanceInfo) { if (instanceInfo) {
instanceInfo.config.update(config as any, true, "controller"); instanceInfo.config.update(config, true, "controller");
} else { } else {
let instanceConfig = new lib.InstanceConfig("host"); let instanceConfig = new lib.InstanceConfig("host");
await instanceConfig.load(config as any, "controller"); instanceConfig.update(config, false, "controller");
let instanceDir = await this._createNewInstanceDir(instanceConfig.get("instance.name")); let instanceDir = await this._createNewInstanceDir(instanceConfig.get("instance.name"));
@@ -608,7 +609,7 @@ export default class Host extends lib.Link {
// save a copy of the instance config // save a copy of the instance config
let warnedOutput = { let warnedOutput = {
_warning: "Changes to this file will be overwritten by the controller's copy.", _warning: "Changes to this file will be overwritten by the controller's copy.",
...instanceInfo.config.serialize(), ...instanceInfo.config.toJSON(),
}; };
await lib.safeOutputFile( await lib.safeOutputFile(
path.join(instanceInfo.path, "instance.json"), path.join(instanceInfo.path, "instance.json"),
@@ -919,8 +920,8 @@ export default class Host extends lib.Link {
let list = []; let list = [];
for (let [instanceId, instanceInfo] of this.discoveredInstanceInfos) { for (let [instanceId, instanceInfo] of this.discoveredInstanceInfos) {
let instanceConnection = this.instanceConnections.get(instanceId); let instanceConnection = this.instanceConnections.get(instanceId);
list.push(new lib.RawInstanceInfo( list.push(new lib.HostInstanceUpdate(
instanceInfo.config.serialize("controller"), instanceInfo.config.toRemote("controller"),
instanceConnection ? instanceConnection.instance.status : "stopped", instanceConnection ? instanceConnection.instance.status : "stopped",
instanceConnection ? instanceConnection.instance.server.gamePort : undefined, instanceConnection ? instanceConnection.instance.server.gamePort : undefined,
)); ));
@@ -984,7 +985,7 @@ export default class Host extends lib.Link {
} }
logger.info("Saving config"); logger.info("Saving config");
await lib.safeOutputFile(this.configPath, JSON.stringify(this.config.serialize(), null, "\t")); await lib.safeOutputFile(this.configPath, JSON.stringify(this.config, null, "\t"));
try { try {
// Clear silly interval in pidfile library. // Clear silly interval in pidfile library.
+10 -10
View File
@@ -121,7 +121,7 @@ export default class Instance extends lib.Link {
_host: Host; _host: Host;
_dir: string; _dir: string;
_configFieldChanged: (group: lib.ConfigGroup, field: string, prev: unknown) => void; _configFieldChanged: (field: string, curr: unknown, prev: unknown) => void;
_status: "stopped" | "starting" | "running" | "stopping" | "creating_save" | "exporting_data" = "stopped"; _status: "stopped" | "starting" | "running" | "stopping" | "creating_save" | "exporting_data" = "stopped";
_loadedSave: string | null = null; _loadedSave: string | null = null;
_playerCheckInterval: ReturnType<typeof setInterval> | undefined; _playerCheckInterval: ReturnType<typeof setInterval> | undefined;
@@ -150,16 +150,16 @@ export default class Instance extends lib.Link {
instance_name: this.name, instance_name: this.name,
}); });
this._configFieldChanged = (group: lib.ConfigGroup, field: string, prev: unknown) => { this._configFieldChanged = (field: string, curr: unknown, prev: unknown) => {
let hook = () => lib.invokeHook(this.plugins, "onInstanceConfigFieldChanged", group, field, prev); let hook = () => lib.invokeHook(this.plugins, "onInstanceConfigFieldChanged", field, curr, prev);
if (group.name === "factorio" && field === "settings") { if (field === "factorio.settings") {
this.updateFactorioSettings(group.get(field) as any, prev as any).finally(hook); this.updateFactorioSettings(curr as any, prev as any).finally(hook);
} else if (group.name === "factorio" && field === "enable_whitelist") { } else if (field === "factorio.enable_whitelist") {
this.updateFactorioWhitelist(group.get(field) as any).finally(hook); this.updateFactorioWhitelist(curr as any).finally(hook);
} else { } else {
if (group.name === "factorio" && field === "max_concurrent_commands") { if (field === "factorio.max_concurrent_commands") {
this.server.maxConcurrentCommands = group.get(field) as number; this.server.maxConcurrentCommands = curr as number;
} }
hook(); hook();
} }
@@ -546,7 +546,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
if ( if (
!pluginInfo.instanceEntrypoint !pluginInfo.instanceEntrypoint
|| !this._host.serverPlugins.has(pluginInfo.name) || !this._host.serverPlugins.has(pluginInfo.name)
|| !this.config.group(pluginInfo.name).get("load_plugin") || !this.config.get(`${pluginInfo.name}.load_plugin` as keyof lib.InstanceConfigFields)
) { ) {
continue; continue;
} }
+1
View File
@@ -14,3 +14,4 @@ export * from "./src/subscriptions";
export { default as ExponentialBackoff } from "./src/ExponentialBackoff"; export { default as ExponentialBackoff } from "./src/ExponentialBackoff";
export { default as RateLimiter } from "./src/RateLimiter"; export { default as RateLimiter } from "./src/RateLimiter";
export { default as TypedEventEmitter } from "./src/TypedEventEmitter";
+1
View File
@@ -31,3 +31,4 @@ export * from "./src/subscriptions";
export { default as ExponentialBackoff } from "./src/ExponentialBackoff"; export { default as ExponentialBackoff } from "./src/ExponentialBackoff";
export { default as ModStore } from "./src/ModStore"; export { default as ModStore } from "./src/ModStore";
export { default as RateLimiter } from "./src/RateLimiter"; export { default as RateLimiter } from "./src/RateLimiter";
export { default as TypedEventEmitter } from "./src/TypedEventEmitter";
+1 -11
View File
@@ -2,17 +2,7 @@ import fs from "fs-extra";
import path from "path"; import path from "path";
import { logger } from "./logging"; import { logger } from "./logging";
import { ModInfo } from "./data"; import { ModInfo } from "./data";
import EventEmitter from "events"; import TypedEventEmitter from "./TypedEventEmitter";
abstract class TypedEventEmitter<
Keys extends string,
Events extends Record<Keys, (...args: [...any]) => void>,
> extends EventEmitter {
declare ["on"]: <E extends Keys>(event: E, listener: Events[E]) => this;
declare ["off"]: <E extends Keys>(event: E, listener: Events[E]) => this;
declare ["once"]: <E extends Keys>(event: E, listener: Events[E]) => this;
declare ["emit"]: <E extends Keys>(event: E, ...args: Parameters<Events[E]>) => boolean;
}
export interface ModStoreEvents { export interface ModStoreEvents {
/** A stored mod was created, updated or deleted */ /** A stored mod was created, updated or deleted */
+27
View File
@@ -0,0 +1,27 @@
import EventEmitter from "events";
/**
* Type checked version of EventEmitter
*
* @example
* ```ts
* interface Events {
* "foo": (a: number, b: number) => void,
* "bar": (spam: string) => void,
* }
*
* class Emitter extends TypedEventEmitter<keyof Events, Events> {}
*
* const e = new Emitter();
* e.emit("foo", 1, 2) // type checked arguments
* ```
*/
export default abstract class TypedEventEmitter<
Keys extends string,
Events extends Record<Keys, (...args: [...any]) => void>,
> extends EventEmitter {
declare ["on"]: <E extends Keys>(event: E, listener: Events[E]) => this;
declare ["off"]: <E extends Keys>(event: E, listener: Events[E]) => this;
declare ["once"]: <E extends Keys>(event: E, listener: Events[E]) => this;
declare ["emit"]: <E extends Keys>(event: E, ...args: Parameters<Events[E]>) => boolean;
}
File diff suppressed because it is too large. Load diff
+415 -511
View File
@@ -3,565 +3,469 @@ import * as classes from "./classes";
import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin"; import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin";
/** export interface ControllerConfigFields {
* Controller config group for {@link ControllerConfig} "controller.name": string;
* @extends classes.ConfigGroup "controller.mods_directory": string;
*/ "controller.database_directory": string;
export class ControllerGroup extends classes.ConfigGroup { } "controller.http_port": number | null;
ControllerGroup.defaultAccess = ["controller", "host", "control"]; "controller.https_port": number | null;
ControllerGroup.groupName = "controller"; "controller.bind_address": string | null;
ControllerGroup.define({ "controller.external_address": string | null;
name: "name", "controller.tls_certificate": string | null;
title: "Name", "controller.tls_private_key": string | null;
description: "Name of the cluster.", "controller.auth_secret": string;
type: "string", "controller.heartbeat_interval": number;
initial_value: "Your Cluster", "controller.session_timeout": number;
}); "controller.metrics_timeout": number;
ControllerGroup.define({ "controller.proxy_stream_timeout": number;
name: "mods_directory", "controller.default_mod_pack_id": number | null;
title: "Mods Directory", "controller.default_role_id": number | null;
description: "Path to directory where mods shared with the cluster are stored.", "controller.autosave_interval": number;
restartRequired: true, }
type: "string",
initial_value: "mods",
});
ControllerGroup.define({
name: "database_directory",
title: "Database directory",
description: "Directory where item and configuration data is stored.",
type: "string",
initial_value: "database",
});
ControllerGroup.define({
name: "autosave_interval",
title: "Autosave Interval",
description: "Interval in seconds to autosave data in memory to disk.",
type: "number",
initial_value: 60,
});
ControllerGroup.define({
name: "http_port",
title: "HTTP Port",
description: "Port to listen for HTTP connections on, set to null to not listen for HTTP connections.",
restartRequired: true,
type: "number",
optional: true,
initial_value: 8080,
});
ControllerGroup.define({
name: "https_port",
title: "HTTPS Port",
description: "Port to listen for HTTPS connection on, set to null to not listen for HTTPS connections.",
restartRequired: true,
type: "number",
optional: true,
});
ControllerGroup.define({
name: "bind_address",
title: "Bind Address",
description: "IP address to bind the HTTP and HTTPS ports on.",
restartRequired: true,
type: "string",
optional: true,
});
ControllerGroup.define({
name: "external_address",
title: "External Address",
description: "Public facing address the controller is hosted on.",
type: "string",
optional: true,
});
ControllerGroup.define({
name: "tls_certificate",
title: "TLS Certificate",
description: "Path to the certificate to use for HTTPS.",
restartRequired: true,
type: "string",
optional: true,
});
ControllerGroup.define({
name: "tls_private_key",
title: "TLS Private Key",
description: "Path to the private key to use for HTTPS.",
restartRequired: true,
type: "string",
optional: true,
});
ControllerGroup.define({
access: ["controller"],
name: "auth_secret",
title: "Controller Authentication Secret",
description:
"Secret used to generate and verify authentication tokens. " +
"Should be a long string of random letters and numbers. " +
"Do not share this.",
restartRequired: true,
type: "string",
optional: true,
});
ControllerGroup.define({
name: "heartbeat_interval",
title: "Heartbeat Interval",
description: "Interval heartbeats are sent out on WebSocket connections.",
type: "number",
initial_value: 15,
});
ControllerGroup.define({
name: "session_timeout",
title: "Session Timeout",
description: "Time in seconds before giving up resuming a dropped WebSocket session.",
type: "number",
initial_value: 60,
});
ControllerGroup.define({
name: "metrics_timeout",
title: "Metrics Timeout",
description: "Timeout in seconds for metrics gathering from hosts.",
type: "number",
initial_value: 8,
});
ControllerGroup.define({
name: "proxy_stream_timeout",
title: "Proxy Stream Timeout",
description: "Timeout in seconds for proxy streams to start flowing.",
type: "number",
initial_value: 15,
});
ControllerGroup.define({
name: "default_mod_pack_id",
title: "Default Mod Pack",
description: "Mod pack used by default for instances.",
type: "number",
optional: true,
});
ControllerGroup.define({
name: "default_role_id",
title: "Default role",
description: "ID of role assigned by default to new users.",
type: "number",
optional: true,
initial_value: 1,
});
ControllerGroup.finalize();
/** /**
* Controller Config class * Controller Config class
* @extends classes.Config * @extends classes.Config
*/ */
export class ControllerConfig extends classes.Config { export class ControllerConfig extends classes.Config<ControllerConfigFields> {
get(name: "controller.name"): string; declare static fromJSON: (json: classes.ConfigSchema, location: classes.ConfigLocation) => ControllerConfig;
get(name: "controller.mods_directory"): string; static fieldDefinitions: classes.ConfigDefs<ControllerConfigFields> = {
get(name: "controller.database_directory"): string; "controller.name": {
get(name: "controller.http_port"): number | null; title: "Name",
get(name: "controller.https_port"): number | null; description: "Name of the cluster.",
get(name: "controller.bind_address"): string | null; type: "string",
get(name: "controller.external_address"): string | null; initialValue: "Your Cluster",
get(name: "controller.tls_certificate"): string | null; },
get(name: "controller.tls_private_key"): string | null; "controller.mods_directory": {
get(name: "controller.auth_secret"): string; title: "Mods Directory",
get(name: "controller.heartbeat_interval"): number; description: "Path to directory where mods shared with the cluster are stored.",
get(name: "controller.session_timeout"): number; restartRequired: true,
get(name: "controller.metrics_timeout"): number; type: "string",
get(name: "controller.proxy_stream_timeout"): number; initialValue: "mods",
get(name: "controller.default_mod_pack_id"): number | null; },
get(name: "controller.default_role_id"): number | null; "controller.database_directory": {
get(name: "controller.autosave_interval"): number; title: "Database directory",
get(name: string): unknown; description: "Directory where item and configuration data is stored.",
get(name: string) { type: "string",
return super.get(name); initialValue: "database",
} },
"controller.autosave_interval": {
title: "Autosave Interval",
description: "Interval in seconds to autosave data in memory to disk.",
type: "number",
initialValue: 60,
},
"controller.http_port": {
title: "HTTP Port",
description: "Port to listen for HTTP connections on, set to null to not listen for HTTP connections.",
restartRequired: true,
type: "number",
optional: true,
initialValue: 8080,
},
"controller.https_port": {
title: "HTTPS Port",
description: "Port to listen for HTTPS connection on, set to null to not listen for HTTPS connections.",
restartRequired: true,
type: "number",
optional: true,
},
"controller.bind_address": {
title: "Bind Address",
description: "IP address to bind the HTTP and HTTPS ports on.",
restartRequired: true,
type: "string",
optional: true,
},
"controller.external_address": {
title: "External Address",
description: "Public facing address the controller is hosted on.",
type: "string",
optional: true,
},
"controller.tls_certificate": {
title: "TLS Certificate",
description: "Path to the certificate to use for HTTPS.",
restartRequired: true,
type: "string",
optional: true,
},
"controller.tls_private_key": {
title: "TLS Private Key",
description: "Path to the private key to use for HTTPS.",
restartRequired: true,
type: "string",
optional: true,
},
"controller.auth_secret": {
access: ["controller"],
title: "Controller Authentication Secret",
description:
"Secret used to generate and verify authentication tokens. " +
"Should be a long string of random letters and numbers. " +
"Do not share this.",
restartRequired: true,
type: "string",
optional: true,
},
"controller.heartbeat_interval": {
title: "Heartbeat Interval",
description: "Interval heartbeats are sent out on WebSocket connections.",
type: "number",
initialValue: 15,
},
"controller.session_timeout": {
title: "Session Timeout",
description: "Time in seconds before giving up resuming a dropped WebSocket session.",
type: "number",
initialValue: 60,
},
"controller.metrics_timeout": {
title: "Metrics Timeout",
description: "Timeout in seconds for metrics gathering from hosts.",
type: "number",
initialValue: 8,
},
"controller.proxy_stream_timeout": {
title: "Proxy Stream Timeout",
description: "Timeout in seconds for proxy streams to start flowing.",
type: "number",
initialValue: 15,
},
"controller.default_mod_pack_id": {
title: "Default Mod Pack",
description: "Mod pack used by default for instances.",
type: "number",
optional: true,
},
"controller.default_role_id": {
title: "Default role",
description: "ID of role assigned by default to new users.",
type: "number",
optional: true,
initialValue: 1,
},
};
} }
ControllerConfig.registerGroup(ControllerGroup);
export interface HostConfigFields {
/** "host.name": string;
* Host config group for {@link HostConfig} "host.id": number;
* @extends classes.ConfigGroup "host.factorio_directory": string;
*/ "host.mods_directory": string;
export class HostGroup extends classes.ConfigGroup {} "host.instances_directory": string;
HostGroup.defaultAccess = ["controller", "host", "control"]; "host.controller_url": string;
HostGroup.groupName = "host"; "host.controller_token": string;
HostGroup.define({ "host.tls_ca": string | null;
name: "name", "host.public_address": string;
description: "Name of the host", "host.max_reconnect_delay": number;
type: "string", }
initial_value: "New Host",
});
HostGroup.define({
name: "id",
description: "ID of the host",
type: "number",
initial_value: () => Math.random() * 2**31 | 0,
});
HostGroup.define({
name: "factorio_directory",
description: "Path to directory to look for factorio installs",
type: "string",
initial_value: "factorio",
});
HostGroup.define({
name: "mods_directory",
title: "Mods Directory",
description: "Path to directory where mods for instances are cached.",
restartRequired: true,
type: "string",
initial_value: "mods",
});
HostGroup.define({
name: "instances_directory",
description: "Path to directory to store instances in.",
restartRequired: true,
type: "string",
initial_value: "instances",
});
HostGroup.define({
name: "controller_url",
description: "URL to connect to the controller at",
restartRequired: true,
type: "string",
initial_value: "http://localhost:8080/",
});
HostGroup.define({
name: "controller_token",
description: "Token to authenticate to controller with.",
restartRequired: true,
type: "string",
initial_value: "enter token here",
});
HostGroup.define({
name: "tls_ca",
description: "Path to Certificate Authority to validate TLS connection to controller against.",
restartRequired: true,
type: "string",
optional: true,
});
HostGroup.define({
name: "public_address",
description: "Public facing address players should connect to in order to join instances on this host",
type: "string",
initial_value: "localhost",
});
HostGroup.define({
name: "max_reconnect_delay",
title: "Max Reconnect Delay",
description: "Maximum delay to wait before attempting to reconnect WebSocket",
type: "number",
initial_value: 60,
});
HostGroup.finalize();
/** /**
* Host Config class * Host Config class
* @extends classes.Config * @extends classes.Config
*/ */
export class HostConfig extends classes.Config { export class HostConfig extends classes.Config<HostConfigFields> {
get(name: "host.name"): string; declare static fromJSON: (json: classes.ConfigSchema, location: classes.ConfigLocation) => HostConfig;
get(name: "host.id"): number; static fieldDefinitions: classes.ConfigDefs<HostConfigFields> = {
get(name: "host.factorio_directory"): string; "host.name": {
get(name: "host.mods_directory"): string; description: "Name of the host",
get(name: "host.instances_directory"): string; type: "string",
get(name: "host.controller_url"): string; initialValue: "New Host",
get(name: "host.controller_token"): string; },
get(name: "host.tls_ca"): string | null; "host.id": {
get(name: "host.public_address"): string; description: "ID of the host",
get(name: "host.max_reconnect_delay"): number; type: "number",
get(name: string): unknown; initialValue: () => Math.random() * 2**31 | 0,
get(name: string) { },
return super.get(name); "host.factorio_directory": {
} description: "Path to directory to look for factorio installs",
type: "string",
initialValue: "factorio",
},
"host.mods_directory": {
title: "Mods Directory",
description: "Path to directory where mods for instances are cached.",
restartRequired: true,
type: "string",
initialValue: "mods",
},
"host.instances_directory": {
description: "Path to directory to store instances in.",
restartRequired: true,
type: "string",
initialValue: "instances",
},
"host.controller_url": {
description: "URL to connect to the controller at",
restartRequired: true,
type: "string",
initialValue: "http://localhost:8080/",
},
"host.controller_token": {
access: ["host"],
description: "Token to authenticate to controller with.",
restartRequired: true,
type: "string",
initialValue: "enter token here",
},
"host.tls_ca": {
description: "Path to Certificate Authority to validate TLS connection to controller against.",
restartRequired: true,
type: "string",
optional: true,
},
"host.public_address": {
description: "Public facing address players should connect to in order to join instances on this host",
type: "string",
initialValue: "localhost",
},
"host.max_reconnect_delay": {
title: "Max Reconnect Delay",
description: "Maximum delay to wait before attempting to reconnect WebSocket",
type: "number",
initialValue: 60,
},
};
} }
HostConfig.registerGroup(HostGroup);
export interface InstanceConfigFields {
"instance.name": string;
"instance.id": number;
"instance.assigned_host": number | null;
"instance.auto_start": boolean;
/** "factorio.version": string;
* Instance config group for {@link classes.InstanceConfig} "factorio.game_port": number | null;
* @extends classes.ConfigGroup "factorio.rcon_port": number | null;
*/ "factorio.rcon_password": string | null;
export class InstanceGroup extends classes.ConfigGroup { } "factorio.player_online_autosave_slots": number;
InstanceGroup.defaultAccess = ["controller", "host", "control"]; "factorio.mod_pack": number | null;
InstanceGroup.groupName = "instance"; "factorio.enable_save_patching": boolean;
InstanceGroup.define({ "factorio.enable_whitelist": boolean;
name: "name", "factorio.enable_authserver_bans": boolean;
type: "string", "factorio.settings": Record<string, unknown>;
initial_value: "New Instance", "factorio.verbose_logging": boolean;
}); "factorio.strip_paths": boolean;
InstanceGroup.define({ "factorio.sync_adminlist": boolean;
name: "id", "factorio.sync_whitelist": boolean;
description: "ID of the instance", "factorio.sync_banlist": boolean;
type: "number", "factorio.max_concurrent_commands": number;
initial_value: () => Math.random() * 2**31 | 0, }
});
InstanceGroup.define({
name: "assigned_host",
type: "number",
optional: true,
});
InstanceGroup.define({
name: "auto_start",
description: "Automatically start this instance when the host hosting it is started up",
type: "boolean",
initial_value: false,
});
InstanceGroup.finalize();
/**
* Factorio config group for {@link classes.InstanceConfig}
* @extends classes.ConfigGroup
*/
export class FactorioGroup extends classes.ConfigGroup { }
FactorioGroup.defaultAccess = ["controller", "host", "control"];
FactorioGroup.groupName = "factorio";
FactorioGroup.define({
name: "version",
description: "Version of the game to run, use latest to run the latest installed version",
restartRequired: true,
type: "string",
initial_value: "latest",
});
FactorioGroup.define({
name: "game_port",
description: "UDP port to run game on, uses a random port if null",
restartRequired: true,
type: "number",
optional: true,
});
FactorioGroup.define({
name: "rcon_port",
description: "TCP port to run RCON on, uses a random port if null",
restartRequired: true,
type: "number",
optional: true,
});
FactorioGroup.define({
name: "rcon_password",
description: "Password for RCON, randomly generated if null",
restartRequired: true,
type: "string",
optional: true,
});
FactorioGroup.define({
name: "player_online_autosave_slots",
description:
"Rename autosaves where players have been online since the previous autosave into a separate autosave " +
"pool with this many slots. Requires autosaves to be enabled to work. Set to 0 to disable.",
type: "number",
initial_value: 5,
});
FactorioGroup.define({
name: "mod_pack",
description: "Mod pack to use on this server",
restartRequired: true,
type: "number",
optional: true,
});
FactorioGroup.define({
name: "enable_save_patching",
description: "Patch saves with Lua code. Required for Clusterio integrations, lua modules, and most plugins.",
restartRequired: true,
type: "boolean",
initial_value: true,
});
FactorioGroup.define({
name: "enable_whitelist",
description: "Turn on whitelist for joining the server.",
type: "boolean",
initial_value: false,
});
FactorioGroup.define({
name: "enable_authserver_bans",
description: "Turn on Factorio.com based multiplayer bans.",
restartRequired: true,
type: "boolean",
initial_value: false,
});
FactorioGroup.define({
name: "settings",
description: "Settings overridden in server-settings.json",
restartRequired: true,
restartRequiredProps: [
"afk_autokick_interval", "allow_commands", "autosave_interval", "autosave_only_on_server", "description",
"ignore_player_limit_for_returning_players", "max_players", "max_upload_slots",
"max_upload_in_kilobytes_per_second", "name", "only_admins_can_pause_the_game", "game_password",
"require_user_verification", "tags", "visibility",
],
type: "object",
initial_value: {}, // See create instance handler in controller.
});
FactorioGroup.define({
name: "verbose_logging",
description: "Enable verbose logging on the Factorio server",
restartRequired: true,
type: "boolean",
initial_value: false,
});
FactorioGroup.define({
name: "strip_paths",
description: "Strip down instance paths in the log",
restartRequired: true,
type: "boolean",
initial_value: true,
});
FactorioGroup.define({
name: "sync_adminlist",
description: "Synchronize adminlist with controller",
type: "boolean",
initial_value: true,
});
FactorioGroup.define({
name: "sync_whitelist",
description: "Synchronize whitelist with controller",
type: "boolean",
initial_value: true,
});
FactorioGroup.define({
name: "sync_banlist",
description: "Synchronize banlist with controller",
type: "boolean",
initial_value: true,
});
FactorioGroup.define({
name: "max_concurrent_commands",
description: "Maximum number of RCON commands trasmitted in parallel",
restartRequired: true,
type: "number",
initial_value: 5,
});
FactorioGroup.finalize();
/** /**
* Instance config class * Instance config class
* @extends classes.Config * @extends classes.Config
*/ */
export class InstanceConfig extends classes.Config { export class InstanceConfig extends classes.Config<InstanceConfigFields> {
get(name: "instance.name"): string; declare static fromJSON: (json: classes.ConfigSchema, location: classes.ConfigLocation) => InstanceConfig;
get(name: "instance.id"): number; static fieldDefinitions: classes.ConfigDefs<InstanceConfigFields> = {
get(name: "instance.assigned_host"): number | null; "instance.name": {
get(name: "instance.auto_start"): boolean; type: "string",
initialValue: "New Instance",
get(name: "factorio.version"): string; },
get(name: "factorio.game_port"): number | null; "instance.id": {
get(name: "factorio.rcon_port"): number | null; description: "ID of the instance",
get(name: "factorio.rcon_password"): string | null; type: "number",
get(name: "factorio.player_online_autosave_slots"): number; initialValue: () => Math.random() * 2**31 | 0,
get(name: "factorio.mod_pack"): number | null; },
get(name: "factorio.enable_save_patching"): boolean; "instance.assigned_host": {
get(name: "factorio.enable_whitelist"): boolean; type: "number",
get(name: "factorio.enable_authserver_bans"): boolean; optional: true,
get(name: "factorio.settings"): Record<string, unknown>; },
get(name: "factorio.verbose_logging"): boolean; "instance.auto_start": {
get(name: "factorio.strip_paths"): boolean; description: "Automatically start this instance when the host hosting it is started up",
get(name: "factorio.sync_adminlist"): boolean; type: "boolean",
get(name: "factorio.sync_whitelist"): boolean; initialValue: false,
get(name: "factorio.sync_banlist"): boolean; },
get(name: "factorio.max_concurrent_commands"): number; "factorio.version": {
get(name: string): unknown; description: "Version of the game to run, use latest to run the latest installed version",
get(name: string) { restartRequired: true,
return super.get(name); type: "string",
} initialValue: "latest",
},
"factorio.game_port": {
description: "UDP port to run game on, uses a random port if null",
restartRequired: true,
type: "number",
optional: true,
},
"factorio.rcon_port": {
description: "TCP port to run RCON on, uses a random port if null",
restartRequired: true,
type: "number",
optional: true,
},
"factorio.rcon_password": {
description: "Password for RCON, randomly generated if null",
restartRequired: true,
type: "string",
optional: true,
},
"factorio.player_online_autosave_slots": {
description:
"Rename autosaves where players have been online since the previous autosave into a separate " +
"autosave pool with this many slots. Requires autosaves to be enabled to work. Set to 0 to disable.",
type: "number",
initialValue: 5,
},
"factorio.mod_pack": {
description: "Mod pack to use on this server",
restartRequired: true,
type: "number",
optional: true,
},
"factorio.enable_save_patching": {
description:
"Patch saves with Lua code. Required for Clusterio integrations, lua modules, and most plugins.",
restartRequired: true,
type: "boolean",
initialValue: true,
},
"factorio.enable_whitelist": {
description: "Turn on whitelist for joining the server.",
type: "boolean",
initialValue: false,
},
"factorio.enable_authserver_bans": {
description: "Turn on Factorio.com based multiplayer bans.",
restartRequired: true,
type: "boolean",
initialValue: false,
},
"factorio.settings": {
description: "Settings overridden in server-settings.json",
restartRequired: true,
restartRequiredProps: [
"afk_autokick_interval", "allow_commands", "autosave_interval", "autosave_only_on_server",
"description", "ignore_player_limit_for_returning_players", "max_players", "max_upload_slots",
"max_upload_in_kilobytes_per_second", "name", "only_admins_can_pause_the_game", "game_password",
"require_user_verification", "tags", "visibility",
],
type: "object",
initialValue: {}, // See create instance handler in controller.
},
"factorio.verbose_logging": {
description: "Enable verbose logging on the Factorio server",
restartRequired: true,
type: "boolean",
initialValue: false,
},
"factorio.strip_paths": {
description: "Strip down instance paths in the log",
restartRequired: true,
type: "boolean",
initialValue: true,
},
"factorio.sync_adminlist": {
description: "Synchronize adminlist with controller",
type: "boolean",
initialValue: true,
},
"factorio.sync_whitelist": {
description: "Synchronize whitelist with controller",
type: "boolean",
initialValue: true,
},
"factorio.sync_banlist": {
description: "Synchronize banlist with controller",
type: "boolean",
initialValue: true,
},
"factorio.max_concurrent_commands": {
description: "Maximum number of RCON commands trasmitted in parallel",
restartRequired: true,
type: "number",
initialValue: 5,
},
};
} }
InstanceConfig.registerGroup(InstanceGroup);
InstanceConfig.registerGroup(FactorioGroup);
export interface ControlConfigFields {
/** "control.controller_url": string | null;
* Control config group for {@link classes.ControlConfig} "control.controller_token": string | null;
* @extends classes.ConfigGroup "control.tls_ca": string | null;
*/ "control.max_reconnect_delay": number;
export class ControlGroup extends classes.ConfigGroup {} }
ControlGroup.defaultAccess = ["control"];
ControlGroup.groupName = "control";
ControlGroup.define({
name: "controller_url",
description: "URL to connect to the controller at",
type: "string",
optional: true,
});
ControlGroup.define({
name: "controller_token",
description: "Token to authenticate to controller with.",
type: "string",
optional: true,
});
ControlGroup.define({
name: "tls_ca",
description: "Path to Certificate Authority to validate TLS connection to controller against.",
type: "string",
optional: true,
});
ControlGroup.define({
name: "max_reconnect_delay",
title: "Max Reconnect Delay",
description: "Maximum delay to wait before attempting to reconnect WebSocket",
type: "number",
initial_value: 60,
});
ControlGroup.finalize();
/** /**
* Control config class * Control config class
* @extends classes.Config * @extends classes.Config
*/ */
export class ControlConfig extends classes.Config { } export class ControlConfig extends classes.Config<ControlConfigFields> {
ControlConfig.registerGroup(ControlGroup); declare static fromJSON: (json: classes.ConfigSchema, location: classes.ConfigLocation) => ControlConfig;
static fieldDefinitions: classes.ConfigDefs<ControlConfigFields> = {
"control.controller_url": {
description: "URL to connect to the controller at",
type: "string",
optional: true,
},
"control.controller_token": {
access: ["control"],
description: "Token to authenticate to controller with.",
type: "string",
optional: true,
},
"control.tls_ca": {
description: "Path to Certificate Authority to validate TLS connection to controller against.",
type: "string",
optional: true,
},
"control.max_reconnect_delay": {
title: "Max Reconnect Delay",
description: "Maximum delay to wait before attempting to reconnect WebSocket",
type: "number",
initialValue: 60,
},
};
}
function validateGroup( function validateFields(
pluginInfo: PluginNodeEnvInfo | PluginWebpackEnvInfo, pluginName: string,
groupName: "ControllerConfigGroup" | "HostConfigGroup" | "InstanceConfigGroup", fields: Record<string, classes.FieldDefinition>,
) { ) {
if (!(pluginInfo[groupName]?.prototype instanceof classes.PluginConfigGroup)) { for (const [name, field] of Object.entries(fields)) {
throw new Error( if (!name.startsWith(`${pluginName}.`)) {
`Expected ${groupName} for ${pluginInfo.name} to be a subclass of PluginConfigGroup` throw new Error(
); `Expected name of config field '${name}' for ${pluginName} to start with '${pluginName}.'`
} );
}
if (pluginInfo[groupName]?.groupName !== pluginInfo.name) {
throw new Error(
`Expected ${groupName} for ${pluginInfo.name} to be named after the plugin`
);
} }
} }
/** /**
* Registers the config groups for the provided plugin infos * Add config fields defined by the provided plugin infos
* *
* @param {Array<Object>} pluginInfos - Array of plugin info objects. * @param {Array<Object>} pluginInfos - Array of plugin info objects.
*/ */
export function registerPluginConfigGroups(pluginInfos: PluginNodeEnvInfo[] | PluginWebpackEnvInfo[]) { export function addPluginConfigFields(pluginInfos: PluginNodeEnvInfo[] | PluginWebpackEnvInfo[]) {
function pluginConfig( function pluginConfig(
pluginInfo: PluginNodeEnvInfo | PluginWebpackEnvInfo, pluginInfo: PluginNodeEnvInfo | PluginWebpackEnvInfo,
group: "ControllerConfigGroup" | "HostConfigGroup" | "InstanceConfigGroup", kind: "controllerConfigFields" | "hostConfigFields" | "instanceConfigFields",
Config: typeof classes.Config, Config: typeof ControllerConfig | typeof HostConfig | typeof InstanceConfig,
) { ) {
if (pluginInfo[group]) { (Config.fieldDefinitions as any)[`${pluginInfo.name}.load_plugin`] = {
validateGroup(pluginInfo, group); title: "Load Plugin",
Config.registerGroup(pluginInfo[group]!); restartRequired: true,
type: "boolean",
initialValue: true,
};
} else { const fields = pluginInfo[kind];
class ConfigGroup extends classes.PluginConfigGroup { } if (fields) {
ConfigGroup.defaultAccess = ["controller", "host", "control"]; validateFields(pluginInfo.name, fields);
ConfigGroup.groupName = pluginInfo.name; Object.assign(Config.fieldDefinitions, fields);
ConfigGroup.finalize();
Config.registerGroup(ConfigGroup);
} }
} }
for (let pluginInfo of pluginInfos) { for (let pluginInfo of pluginInfos) {
pluginConfig(pluginInfo, "ControllerConfigGroup", ControllerConfig); pluginConfig(pluginInfo, "controllerConfigFields", ControllerConfig);
if (pluginInfo.hostEntrypoint || pluginInfo.instanceEntrypoint) { if (pluginInfo.hostEntrypoint || pluginInfo.instanceEntrypoint) {
pluginConfig(pluginInfo, "HostConfigGroup", HostConfig); pluginConfig(pluginInfo, "hostConfigFields", HostConfig);
} }
if (pluginInfo.instanceEntrypoint) { if (pluginInfo.instanceEntrypoint) {
pluginConfig(pluginInfo, "InstanceConfigGroup", InstanceConfig); pluginConfig(pluginInfo, "instanceConfigFields", InstanceConfig);
} }
} }
} }
/**
* Lock configs from adding more groups and make them usable
*/
export function finalizeConfigs() {
ControllerConfig.finalize();
HostConfig.finalize();
InstanceConfig.finalize();
ControlConfig.finalize();
}
+10 -1
View File
@@ -1,4 +1,4 @@
import { Type } from "@sinclair/typebox"; import { Static, TSchema, Type } from "@sinclair/typebox";
export function StringEnum<T extends string[]>(values: [...T]) { export function StringEnum<T extends string[]>(values: [...T]) {
return Type.Unsafe<T[number]>({ type: "string", enum: values }); return Type.Unsafe<T[number]>({ type: "string", enum: values });
@@ -32,3 +32,12 @@ export function jsonPrimitive<T, U>(type: U) {
export const JsonBoolean = jsonPrimitive<boolean, "boolean">("boolean"); export const JsonBoolean = jsonPrimitive<boolean, "boolean">("boolean");
export const JsonNumber = jsonPrimitive<number, "number">("number"); export const JsonNumber = jsonPrimitive<number, "number">("number");
export const JsonString = jsonPrimitive<string, "string">("string"); export const JsonString = jsonPrimitive<string, "string">("string");
export function plainJson<T extends TSchema>(schema: T) {
return {
jsonSchema: schema,
fromJSON(json: Static<T>) {
return json;
},
};
}
+4 -4
View File
@@ -1,7 +1,7 @@
import { Type, Static } from "@sinclair/typebox"; import { Type, Static } from "@sinclair/typebox";
import { JsonString, StringEnum } from "./composites"; import { JsonString, StringEnum, plainJson } from "./composites";
import { levels } from "../logging"; import { levels } from "../logging";
import { RawConfig } from "../config"; import { ControllerConfig, HostConfig } from "../config";
export class ControllerConfigGetRequest { export class ControllerConfigGetRequest {
declare ["constructor"]: typeof ControllerConfigGetRequest; declare ["constructor"]: typeof ControllerConfigGetRequest;
@@ -9,7 +9,7 @@ export class ControllerConfigGetRequest {
static src = "control" as const; static src = "control" as const;
static dst = "controller" as const; static dst = "controller" as const;
static permission = "core.controller.get_config" as const; static permission = "core.controller.get_config" as const;
static Response = RawConfig; static Response = plainJson(ControllerConfig.jsonSchema);
} }
export class ControllerConfigSetFieldRequest { export class ControllerConfigSetFieldRequest {
@@ -103,7 +103,7 @@ export class HostConfigCreateRequest {
return new this(json.id, json.name, json.generateToken); return new this(json.id, json.name, json.generateToken);
} }
static Response = RawConfig; static Response = plainJson(HostConfig.jsonSchema);
} }
export class LogSetSubscriptionsRequest { export class LogSetSubscriptionsRequest {
+13 -18
View File
@@ -1,7 +1,7 @@
import { Type, Static } from "@sinclair/typebox"; import { Type, Static } from "@sinclair/typebox";
import PlayerStats from "./PlayerStats"; import PlayerStats from "./PlayerStats";
import { JsonString, StringEnum, jsonArray } from "./composites"; import { JsonString, StringEnum, jsonArray, plainJson } from "./composites";
import { RawConfig } from "../config"; import { InstanceConfig } from "../config";
import type { IControllerUser } from "./User"; import type { IControllerUser } from "./User";
import type { MessageRequest } from "./messages_core"; import type { MessageRequest } from "./messages_core";
import { CollectorResultSerialized } from "../prometheus"; import { CollectorResultSerialized } from "../prometheus";
@@ -133,15 +133,14 @@ export class InstanceCreateRequest {
static permission = "core.instance.create" as const; static permission = "core.instance.create" as const;
constructor( constructor(
public config: object, public config: Static<typeof InstanceConfig.jsonSchema>,
) { } ) { }
static jsonSchema = Type.Object({ static jsonSchema = Type.Object({
"config": Type.Object({}), "config": InstanceConfig.jsonSchema,
}); });
static fromJSON(json: Static<typeof this.jsonSchema>) { static fromJSON(json: Static<typeof this.jsonSchema>) {
// TODO deserialise config here after config refactor
return new this(json.config); return new this(json.config);
} }
} }
@@ -152,8 +151,7 @@ export class InstanceConfigGetRequest {
static src = "control" as const; static src = "control" as const;
static dst = "controller" as const; static dst = "controller" as const;
static permission = "core.instance.get_config" as const; static permission = "core.instance.get_config" as const;
// TODO replace with InstanceConfig after config refactor static Response = plainJson(InstanceConfig.jsonSchema);
static Response = RawConfig;
constructor( constructor(
public instanceId: number, public instanceId: number,
@@ -714,17 +712,15 @@ export class InstanceSendRconRequest {
static Response = JsonString; static Response = JsonString;
} }
// TODO remove this after config refactor export class HostInstanceUpdate {
export class RawInstanceInfo {
constructor( constructor(
public config: object, public config: Static<typeof InstanceConfig.jsonSchema>,
public status: InstanceStatus, public status: InstanceStatus,
public gamePort: undefined | number, public gamePort: undefined | number,
) { } ) { }
static jsonSchema = Type.Object({ static jsonSchema = Type.Object({
"config": Type.Object({}), "config": InstanceConfig.jsonSchema,
"status": StringEnum([ "status": StringEnum([
"stopped", "starting", "running", "stopping", "creating_save", "exporting_data", "stopped", "starting", "running", "stopping", "creating_save", "exporting_data",
]), ]),
@@ -743,17 +739,17 @@ export class InstancesUpdateRequest {
static dst = "controller" as const; static dst = "controller" as const;
constructor( constructor(
public instances: RawInstanceInfo[], public instances: HostInstanceUpdate[],
) { } ) { }
static jsonSchema = Type.Array(RawInstanceInfo.jsonSchema); static jsonSchema = Type.Array(HostInstanceUpdate.jsonSchema);
toJSON() { toJSON() {
return this.instances; return this.instances;
} }
static fromJSON(json: Static<typeof this.jsonSchema>) { static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.map(i => RawInstanceInfo.fromJSON(i))); return new this(json.map(i => HostInstanceUpdate.fromJSON(i)));
} }
} }
@@ -765,16 +761,15 @@ export class InstanceAssignInternalRequest {
constructor( constructor(
public instanceId: number, public instanceId: number,
public config: object, public config: Static<typeof InstanceConfig.jsonSchema>,
) { } ) { }
static jsonSchema = Type.Object({ static jsonSchema = Type.Object({
"instanceId": Type.Integer(), "instanceId": Type.Integer(),
"config": Type.Object({}), "config": InstanceConfig.jsonSchema,
}); });
static fromJSON(json: Static<typeof this.jsonSchema>) { static fromJSON(json: Static<typeof this.jsonSchema>) {
// TODO deserialise config here after config refactor
return new this(json.instanceId, json.config); return new this(json.instanceId, json.config);
} }
} }
+19
View File
@@ -177,6 +177,25 @@ export async function readStream(stream: NodeJS.ReadableStream & { isTTY?: boole
return Buffer.concat(chunks); return Buffer.concat(chunks);
} }
/**
* Split the given string on the first instance of separator
*
* Splits `string` on the first instance of `separator` and returns an
* array consisting of the string up to the separator and the string
* after the separator. Returns an array with the string and an empty
* string if the separator is not present.
*
* @param separator - Separator to split string by.
* @param string - String to split
* @returns string split on separator.
*/
export function splitOn(separator: string, string: string) {
let index = string.indexOf(separator);
if (index === -1) {
return [string, ""];
}
return [string.slice(0, index), string.slice(index + separator.length)];
}
/** /**
* Escapes text for inclusion in a RegExp * Escapes text for inclusion in a RegExp
+5 -5
View File
@@ -4,7 +4,7 @@
*/ */
import * as libHelpers from "./helpers"; import * as libHelpers from "./helpers";
import type { Logger } from "./logging"; import type { Logger } from "./logging";
import type { PluginConfigGroup } from "./config"; import type { FieldDefinition } from "./config";
import type { PlayerStats } from "./data"; import type { PlayerStats } from "./data";
// TODO Add proper typing for plugins // TODO Add proper typing for plugins
@@ -15,17 +15,17 @@ export type PluginDeclaration = {
description?: string; description?: string;
controllerEntrypoint?: string; controllerEntrypoint?: string;
ControllerConfigGroup?: typeof PluginConfigGroup; controllerConfigFields?: Record<string, FieldDefinition>;
hostEntrypoint?: string; hostEntrypoint?: string;
HostConfigGroup?: typeof PluginConfigGroup; hostConfigFields?: Record<string, FieldDefinition>;
instanceEntrypoint?: string; instanceEntrypoint?: string;
InstanceConfigGroup?: typeof PluginConfigGroup; instanceConfigFields?: Record<string, FieldDefinition>;
ctlEntrypoint?: string; ctlEntrypoint?: string;
webEntrypoint?: string; webEntrypoint?: string;
ControlConfigGroup?: typeof PluginConfigGroup; controlConfigFields?: Record<string, FieldDefinition>;
messages?: any[]; messages?: any[];
routes?: string[]; routes?: string[];
+4 -7
View File
@@ -128,17 +128,14 @@ export function configCommand(yargs: any) {
*/ */
export async function handleConfigCommand( export async function handleConfigCommand(
args: Record<string, unknown>, args: Record<string, unknown>,
instance: libConfig.Config, instance: libConfig.Config<any>,
configPath: string configPath: string
) { ) {
let command = (args._ as string[])[1]; let command = (args._ as string[])[1];
if (command === "list") { if (command === "list") {
for (let GroupClass of (instance.constructor as typeof libConfig.Config).groups.values()) { for (const name of Object.keys(instance.constructor.fieldDefinitions)) {
for (let def of GroupClass.definitions.values()) { print(`${name} ${JSON.stringify(instance.get(name))}`);
let value = instance.get(def.fullName);
print(`${def.fullName} ${JSON.stringify(value)}`);
}
} }
} else if (command === "show") { } else if (command === "show") {
@@ -162,7 +159,7 @@ export async function handleConfigCommand(
try { try {
instance.set(args.field as string, args.value); instance.set(args.field as string, args.value);
await libFileOps.safeOutputFile(configPath, JSON.stringify(instance.serialize(), null, "\t")); await libFileOps.safeOutputFile(configPath, JSON.stringify(instance, null, "\t"));
} catch (err) { } catch (err) {
if (err instanceof libConfig.InvalidField || err instanceof libConfig.InvalidValue) { if (err instanceof libConfig.InvalidField || err instanceof libConfig.InvalidValue) {
logger.error(err.message); logger.error(err.message);
+1 -2
View File
@@ -104,8 +104,7 @@ export default async function bootstrap() {
})); }));
let pluginInfos = await loadPluginInfos(); let pluginInfos = await loadPluginInfos();
lib.registerPluginMessages(pluginInfos); lib.registerPluginMessages(pluginInfos);
lib.registerPluginConfigGroups(pluginInfos); lib.addPluginConfigFields(pluginInfos);
lib.finalizeConfigs();
let wsUrl = new URL(webRoot, document.location.href); let wsUrl = new URL(webRoot, document.location.href);
let controlConnector = new ControlConnector(wsUrl.href, 120, undefined); let controlConnector = new ControlConnector(wsUrl.href, 120, undefined);
@@ -1,4 +1,4 @@
import type * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { Button, Card, Checkbox, Form, Input, InputNumber, Space, Spin, Tooltip, Tree, Typography } from "antd"; import { Button, Card, Checkbox, Form, Input, InputNumber, Space, Spin, Tooltip, Tree, Typography } from "antd";
@@ -6,41 +6,35 @@ import ReloadOutlined from "@ant-design/icons/ReloadOutlined";
const { Title } = Typography; const { Title } = Typography;
function getInitialValues(config: lib.Config, props: BaseConfigTreeProps) { function getInitialValues(config: lib.Config<any>, props: BaseConfigTreeProps) {
let initialValues: any = {}; let initialValues: any = {};
for (let [name, GroupClass] of props.ConfigClass.groups) { for (let [name, def] of Object.entries(config.constructor.fieldDefinitions)) {
let group = config.group(name); if (!config.canAccess(name)) {
for (let def of GroupClass.definitions.values()) { continue;
if (!group.canAccess(def.name)) { }
continue;
}
let value = group.get(def.name) as any; let value = config.get(name) as any;
let fieldName = `${group.name}.${def.name}`; if (def.type === "object") {
for (let prop of Object.keys(value)) {
if (def.type === "object") { initialValues[`${name}.${prop}`] = JSON.stringify(value[prop]);
for (let prop of Object.keys(value)) {
let propPath = `${group.name}.${def.name}.${prop}`;
initialValues[propPath] = JSON.stringify(value[prop]);
}
} else {
initialValues[fieldName] = value;
} }
} else {
initialValues[name] = value;
} }
} }
return initialValues; return initialValues;
} }
type BaseConfigTreeProps = { type BaseConfigTreeProps = {
ConfigClass: typeof lib.Config; ConfigClass: typeof lib.ControllerConfig | typeof lib.InstanceConfig;
retrieveConfig: () => Promise<lib.SerializedConfig>; retrieveConfig: () => Promise<lib.ConfigSchema>;
setField: (field:string, value:any) => Promise<void>; setField: (field:string, value:any) => Promise<void>;
setProp: (field:string, prop:string, value:any) => Promise<void>; setProp: (field:string, prop:string, value:any) => Promise<void>;
id?: number; id?: number;
onApply?: () => void; onApply?: () => void;
}; };
export default function BaseConfigTree(props: BaseConfigTreeProps) { export default function BaseConfigTree(props: BaseConfigTreeProps) {
let [config, setConfig] = useState<lib.Config|null>(null); let [config, setConfig] = useState<lib.Config<any>|null>(null);
let [form] = Form.useForm(); let [form] = Form.useForm();
let [changedFields, setChangedFields] = useState<Set<string>>(new Set()); let [changedFields, setChangedFields] = useState<Set<string>>(new Set());
let [errorFields, setErrorFields] = useState(new Map()); let [errorFields, setErrorFields] = useState(new Map());
@@ -48,8 +42,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
async function updateConfig() { async function updateConfig() {
let serializedConfig = await props.retrieveConfig(); let serializedConfig = await props.retrieveConfig();
let newConfig = new props.ConfigClass("control"); const newConfig = props.ConfigClass.fromJSON(serializedConfig, "control");
await newConfig.load(serializedConfig);
setConfig(newConfig); setConfig(newConfig);
return newConfig; return newConfig;
} }
@@ -117,21 +110,30 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
let treeData = []; let treeData = [];
let propsMap = new Map(); let propsMap = new Map();
for (let [name, GroupClass] of props.ConfigClass.groups) { const groups = new Map<string, { [name: string]: lib.FieldDefinition }>();
let group = config.group(name); for (let [fieldName, def] of Object.entries(props.ConfigClass.fieldDefinitions)) {
const [groupName, field] = lib.splitOn(".", fieldName);
let group = groups.get(groupName);
if (!group) {
group = {};
groups.set(groupName, group);
}
group[field] = def;
}
for (let [groupName, groupDefs] of groups) {
let treeNode: TreeNode = { let treeNode: TreeNode = {
key: group.name, key: groupName,
title: group.name, title: groupName,
children: [], children: [],
}; };
for (let def of GroupClass.definitions.values()) { for (let [field, def] of Object.entries(groupDefs)) {
if (!group.canAccess(def.name)) { if (!config.canAccess(`${groupName}.${field}`)) {
continue; continue;
} }
let value = group.get(def.name) as any; let fieldName = `${groupName}.${field}`;
let fieldName = `${group.name}.${def.name}`; let value = config.get(fieldName) as any;
let childNode: ChildNode = { let childNode: ChildNode = {
key: fieldName, key: fieldName,
children: [], children: [],
@@ -141,13 +143,13 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
let restartRequiredProps = new Set(def.restartRequiredProps || []); let restartRequiredProps = new Set(def.restartRequiredProps || []);
childNode.title = <Form.Item childNode.title = <Form.Item
label={<> label={<>
{def.title || def.name} {def.title || field}
{!def.restartRequiredProps && def.restartRequired && restartTip} {!def.restartRequiredProps && def.restartRequired && restartTip}
</>} </>}
tooltip={def.description} tooltip={def.description}
/>; />;
for (let prop of Object.keys(value)) { for (let prop of Object.keys(value)) {
let propPath = `${group.name}.${def.name}.${prop}`; let propPath = `${groupName}.${field}.${prop}`;
let restart = Boolean( let restart = Boolean(
def.restartRequiredProps && Number(def.restartRequired) ^ Number(restartRequiredProps.has(prop)) def.restartRequiredProps && Number(def.restartRequired) ^ Number(restartRequiredProps.has(prop))
); );
@@ -179,7 +181,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
propsMap.set(propPath, [fieldName, prop]); propsMap.set(propPath, [fieldName, prop]);
} }
let newPropPath = `${group.name}.${def.name}:add`; let newPropPath = `${groupName}.${field}:add`;
childNode.children.push({ childNode.children.push({
key: newPropPath, key: newPropPath,
title: <Space> title: <Space>
@@ -197,17 +199,16 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
</Form.Item> </Form.Item>
<Button <Button
size="small" size="small"
onClick={async () => { onClick={() => {
let propName = form.getFieldValue(`${newPropPath}.name`); let propName = form.getFieldValue(`${newPropPath}.name`);
let propValue = form.getFieldValue(`${newPropPath}.value`); let propValue = form.getFieldValue(`${newPropPath}.value`);
if (!Object.prototype.hasOwnProperty.call(value, propName)) { if (!Object.prototype.hasOwnProperty.call(value, propName)) {
let newConfig = new props.ConfigClass("control"); let newConfig = props.ConfigClass.fromJSON(config!.toJSON(), "control");
await newConfig.load(config!.serialize()); (newConfig as lib.Config<any>).setProp(fieldName, propName, null);
newConfig.setProp(fieldName, propName, null);
setConfig(newConfig); setConfig(newConfig);
} }
let propPath = `${group.name}.${def.name}.${propName}`; let propPath = `${groupName}.${field}.${propName}`;
form.setFieldsValue({ form.setFieldsValue({
[`${newPropPath}.name`]: "", [`${newPropPath}.name`]: "",
[`${newPropPath}.value`]: "", [`${newPropPath}.value`]: "",
@@ -226,7 +227,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
childNode.title = <Form.Item childNode.title = <Form.Item
name={fieldName} name={fieldName}
label={<> label={<>
{def.title || def.name} {def.title || field}
{def.restartRequired && restartTip} {def.restartRequired && restartTip}
</>} </>}
validateStatus={errorFields.has(fieldName) ? "error" : undefined} validateStatus={errorFields.has(fieldName) ? "error" : undefined}
@@ -10,8 +10,7 @@ export default function ControllerConfigTree() {
let control = useContext(ControlContext); let control = useContext(ControlContext);
async function retrieveConfig() { async function retrieveConfig() {
let result = await control.send(new lib.ControllerConfigGetRequest()); return await control.send(new lib.ControllerConfigGetRequest());
return result.serializedConfig;
} }
async function setField(field: string, value: any) { async function setField(field: string, value: any) {
@@ -14,8 +14,7 @@ export default function InstanceConfigTree(props: InstanceConfigTreeProps) {
let control = useContext(ControlContext); let control = useContext(ControlContext);
async function retrieveConfig() { async function retrieveConfig() {
let result = await control.send(new lib.InstanceConfigGetRequest(props.id)); return await control.send(new lib.InstanceConfigGetRequest(props.id));
return result.serializedConfig;
} }
async function setField(field: string, value: any) { async function setField(field: string, value: any) {
@@ -27,9 +27,8 @@ function CreateInstanceButton() {
} }
let instanceConfig = new lib.InstanceConfig("control"); let instanceConfig = new lib.InstanceConfig("control");
await instanceConfig.init();
instanceConfig.set("instance.name", values.instanceName); instanceConfig.set("instance.name", values.instanceName);
let serializedConfig = instanceConfig.serialize("controller"); const serializedConfig = instanceConfig.toRemote("controller");
await control.send(new lib.InstanceCreateRequest(serializedConfig)); await control.send(new lib.InstanceCreateRequest(serializedConfig));
setOpen(false); setOpen(false);
navigate(`/instances/${instanceConfig.get("instance.id")}/view`); navigate(`/instances/${instanceConfig.get("instance.id")}/view`);
+2 -2
View File
@@ -1,5 +1,5 @@
import { BaseControllerPlugin, type InstanceInfo } from "@clusterio/controller"; import { BaseControllerPlugin, type InstanceInfo } from "@clusterio/controller";
import type { IpcPlayerData } from "./instance"; import type { IpcPlayerData } from "./messages";
import fs from "fs-extra"; import fs from "fs-extra";
import path from "path"; import path from "path";
@@ -62,7 +62,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
} }
if (["unknown", "stopped"].includes(instance.status)) { if (["unknown", "stopped"].includes(instance.status)) {
let timeout = this.controller.config.get("inventory_sync.player_lock_timeout") as number * 1000; let timeout = this.controller.config.get("inventory_sync.player_lock_timeout") * 1000;
for (let acquisitonRecord of this.acquiredPlayers.values()) { for (let acquisitonRecord of this.acquiredPlayers.values()) {
if (acquisitonRecord.instanceId === instanceId && !acquisitonRecord.expires) { if (acquisitonRecord.instanceId === instanceId && !acquisitonRecord.expires) {
acquisitonRecord.expires = Date.now() + timeout; acquisitonRecord.expires = Date.now() + timeout;
+27 -26
View File
@@ -1,30 +1,14 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import * as messages from "./messages"; import * as messages from "./messages";
class ControllerConfigGroup extends lib.PluginConfigGroup { } declare module "@clusterio/lib" {
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"]; export interface InstanceConfigFields {
ControllerConfigGroup.groupName = "inventory_sync"; "inventory_sync.rcon_chunk_size": number;
ControllerConfigGroup.define({ }
name: "player_lock_timeout", export interface ControllerConfigFields {
title: "Player Lock Timeout", "inventory_sync.player_lock_timeout": number;
description: }
"Time in seconds before the lock on a player inventory expires after an instance stops or is disconnected", }
type: "number",
initial_value: 60,
});
ControllerConfigGroup.finalize();
class InstanceConfigGroup extends lib.PluginConfigGroup { }
InstanceConfigGroup.defaultAccess = ["controller", "host", "control"];
InstanceConfigGroup.groupName = "inventory_sync";
InstanceConfigGroup.define({
name: "rcon_chunk_size",
title: "Rcon inventory chunk size",
description: "Divide inventories into multiple chunks before sending with rcon to prevent blocking the pipe",
type: "number",
initial_value: 1000,
});
InstanceConfigGroup.finalize();
lib.definePermission({ lib.definePermission({
name: "inventory_sync.inventory.view", name: "inventory_sync.inventory.view",
@@ -39,10 +23,27 @@ export default {
description: "Synchronizes players inventories between instances", description: "Synchronizes players inventories between instances",
instanceEntrypoint: "dist/plugin/instance", instanceEntrypoint: "dist/plugin/instance",
InstanceConfigGroup, instanceConfigFields: {
"inventory_sync.rcon_chunk_size": {
title: "Rcon inventory chunk size",
description:
"Divide inventories into chunks of this size before sending with rcon to prevent blocking the pipe",
type: "number",
initialValue: 1000,
},
},
controllerEntrypoint: "dist/plugin/controller", controllerEntrypoint: "dist/plugin/controller",
ControllerConfigGroup, controllerConfigFields: {
"inventory_sync.player_lock_timeout": {
title: "Player Lock Timeout",
description:
"Time in seconds before the lock on a player inventory expires after an instance stops " +
"or is disconnected",
type: "number",
initialValue: 60,
},
},
messages: [ messages: [
messages.AcquireRequest, messages.AcquireRequest,
+2 -21
View File
@@ -1,32 +1,13 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { BaseInstancePlugin } from "@clusterio/host"; import { BaseInstancePlugin } from "@clusterio/host";
import { import {
AcquireRequest, AcquireResponse, ReleaseRequest, UploadRequest, DownloadRequest, DownloadResponse, AcquireRequest, AcquireResponse, ReleaseRequest, UploadRequest, DownloadRequest, DownloadResponse, IpcPlayerData,
} from "./messages"; } from "./messages";
type IpcPlayerName = { type IpcPlayerName = {
player_name: string player_name: string
} }
// .\module\serialize.lua:serialize.serialize_player()
export type IpcPlayerData = {
generation: number,
controller: string,
name: string,
color: number[],
chat_color: number[],
tag: string,
force: string,
cheat_mode: boolean,
flashlight: boolean,
ticks_to_respawn?: number,
character?: any,
inventories?: any,
hotbar?: string[],
personal_logistic_slots?: {name:string, min:number, max:number}[],
crafting_queue?: any,
}
type IpcAcquireResponse = { type IpcAcquireResponse = {
player_name: string, player_name: string,
status: string, status: string,
@@ -196,7 +177,7 @@ export class InstancePlugin extends BaseInstancePlugin {
return; return;
} }
const chunkSize = this.instance.config.get("inventory_sync.rcon_chunk_size") as number; const chunkSize = this.instance.config.get("inventory_sync.rcon_chunk_size");
const chunks = chunkify(chunkSize, JSON.stringify(response.playerData)); const chunks = chunkify(chunkSize, JSON.stringify(response.playerData));
this.logger.verbose(`Sending inventory for ${playerName} in ${chunks.length} chunks`); this.logger.verbose(`Sending inventory for ${playerName} in ${chunks.length} chunks`);
for (let i = 0; i < chunks.length; i++) { for (let i = 0; i < chunks.length; i++) {
+19 -2
View File
@@ -1,8 +1,25 @@
import type { IpcPlayerData } from "./instance";
import { Type, Static } from "@sinclair/typebox"; import { Type, Static } from "@sinclair/typebox";
import { StringEnum } from "@clusterio/lib"; import { StringEnum } from "@clusterio/lib";
// .\module\serialize.lua:serialize.serialize_player()
export type IpcPlayerData = {
generation: number,
controller: string,
name: string,
color: number[],
chat_color: number[],
tag: string,
force: string,
cheat_mode: boolean,
flashlight: boolean,
ticks_to_respawn?: number,
character?: any,
inventories?: any,
hotbar?: string[],
personal_logistic_slots?: {name:string, min:number, max:number}[],
crafting_queue?: any,
}
const jsonPlayerData = Type.Object({ const jsonPlayerData = Type.Object({
generation: Type.Number(), generation: Type.Number(),
name: Type.String(), name: Type.String(),
+1 -1
View File
@@ -4,7 +4,7 @@
{ "path": "../../packages/lib" }, { "path": "../../packages/lib" },
{ "path": "../../packages/web_ui/tsconfig.web.json" }, { "path": "../../packages/web_ui/tsconfig.web.json" },
], ],
"include": [ "web/**/*.tsx", "web/**/*.ts", "messages.ts", "instance.ts", "package.json" ], "include": [ "web/**/*.tsx", "web/**/*.ts", "messages.ts", "package.json" ],
"compilerOptions": { "compilerOptions": {
"outDir": "dist/web/build", "outDir": "dist/web/build",
} }
+3 -3
View File
@@ -89,7 +89,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
for (let entry of this.players.values()) { for (let entry of this.players.values()) {
if (entry.playerCode === playerCode && entry.expires > Date.now()) { if (entry.playerCode === playerCode && entry.expires > Date.now()) {
let verifyCode = await generateCode(this.controller.config.get("player_auth.code_length") as number); let verifyCode = await generateCode(this.controller.config.get("player_auth.code_length"));
let secret = Buffer.from(this.controller.config.get("controller.auth_secret"), "base64"); let secret = Buffer.from(this.controller.config.get("controller.auth_secret"), "base64");
let verifyToken = jwt.sign( let verifyToken = jwt.sign(
{ {
@@ -173,8 +173,8 @@ export class ControllerPlugin extends BaseControllerPlugin {
} }
async handleFetchPlayerCodeRequest(request: FetchPlayerCodeRequest) { async handleFetchPlayerCodeRequest(request: FetchPlayerCodeRequest) {
let playerCode = await generateCode(this.controller.config.get("player_auth.code_length") as number); let playerCode = await generateCode(this.controller.config.get("player_auth.code_length"));
let expires = Date.now() + (this.controller.config.get("player_auth.code_timeout") as number) * 1000; let expires = Date.now() + this.controller.config.get("player_auth.code_timeout") * 1000;
this.players.set(request.player, { playerCode, verifyCode: null, expires }); this.players.set(request.player, { playerCode, verifyCode: null, expires });
return { player_code: playerCode, controller_url: this.controller.getControllerUrl() }; return { player_code: playerCode, controller_url: this.controller.getControllerUrl() };
} }
+23 -19
View File
@@ -1,24 +1,15 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import * as messages from "./messages"; import * as messages from "./messages";
class ControllerConfigGroup extends lib.PluginConfigGroup {} declare module "@clusterio/lib" {
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"]; export interface InstanceConfigFields {
ControllerConfigGroup.groupName = "player_auth"; "player_auth.load_plugin": boolean;
ControllerConfigGroup.define({ }
name: "code_length", export interface ControllerConfigFields {
title: "Code Length", "player_auth.code_length": number;
description: "Length in characters of the generated codes.", "player_auth.code_timeout": number;
type: "number", }
initial_value: 6, }
});
ControllerConfigGroup.define({
name: "code_timeout",
title: "Code Timeout",
description: "Time in seconds for the generated codes to stay valid.",
type: "number",
initial_value: 120,
});
ControllerConfigGroup.finalize();
export default { export default {
name: "player_auth", name: "player_auth",
@@ -27,7 +18,20 @@ export default {
controllerEntrypoint: "dist/plugin/controller", controllerEntrypoint: "dist/plugin/controller",
instanceEntrypoint: "dist/plugin/instance", instanceEntrypoint: "dist/plugin/instance",
webEntrypoint: "./web", webEntrypoint: "./web",
ControllerConfigGroup, controllerConfigFields: {
"player_auth.code_length": {
title: "Code Length",
description: "Length in characters of the generated codes.",
type: "number",
initialValue: 6,
},
"player_auth.code_timeout": {
title: "Code Timeout",
description: "Time in seconds for the generated codes to stay valid.",
type: "number",
initialValue: 120,
},
},
messages: [ messages: [
messages.FetchPlayerCodeRequest, messages.FetchPlayerCodeRequest,
+14 -12
View File
@@ -1,16 +1,10 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
class InstanceConfigGroup extends lib.PluginConfigGroup {} declare module "@clusterio/lib" {
InstanceConfigGroup.defaultAccess = ["controller", "host", "control"]; export interface InstanceConfigFields {
InstanceConfigGroup.groupName = "statistics_exporter"; "statistics_exporter.command_timeout": number;
InstanceConfigGroup.define({ }
name: "command_timeout", }
title: "Command Timeout",
description: "Timeout in seconds of the metrics command before returning results from the previous invocation.",
type: "number",
initial_value: 1,
});
InstanceConfigGroup.finalize();
export default { export default {
name: "statistics_exporter", name: "statistics_exporter",
@@ -19,5 +13,13 @@ export default {
"Provides in-game item/fluid production, builds, kills, and pollution "+ "Provides in-game item/fluid production, builds, kills, and pollution "+
"statistics to the cluster's Prometheus endpoint.", "statistics to the cluster's Prometheus endpoint.",
instanceEntrypoint: "dist/plugin/instance", instanceEntrypoint: "dist/plugin/instance",
InstanceConfigGroup, instanceConfigFields: {
"statistics_exporter.command_timeout": {
title: "Command Timeout",
description:
"Timeout in seconds of the metrics command before returning results from the previous invocation.",
type: "number",
initialValue: 1,
},
},
} satisfies lib.PluginDeclaration; } satisfies lib.PluginDeclaration;
+1 -1
View File
@@ -109,7 +109,7 @@ export class InstancePlugin extends BaseInstancePlugin {
// take a long time for the command to go through if the command // take a long time for the command to go through if the command
// stream is overloaded. Should the timeout be exceeded the // stream is overloaded. Should the timeout be exceeded the
// previous values for the metrics will end up being sent to controller. // previous values for the metrics will end up being sent to controller.
let timeout = this.instance.config.get("statistics_exporter.command_timeout") as number * 1000; let timeout = this.instance.config.get("statistics_exporter.command_timeout") * 1000;
await lib.timeout(this.gatherMetrics(), timeout, undefined); await lib.timeout(this.gatherMetrics(), timeout, undefined);
} }
} }
+1 -1
View File
@@ -196,7 +196,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
let count = dole.doleDivider({ let count = dole.doleDivider({
object: { name: item.name, count: item.count, instanceId, instanceName }, object: { name: item.name, count: item.count, instanceId, instanceName },
items: this.items, items: this.items,
logItemTransfers: this.controller.config.get("subspace_storage.log_item_transfers") as boolean, logItemTransfers: this.controller.config.get("subspace_storage.log_item_transfers"),
logger: this.logger, logger: this.logger,
}); });
if (count > 0) { if (count > 0) {
+32 -33
View File
@@ -1,37 +1,15 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import * as messages from "./messages"; import * as messages from "./messages";
class ControllerConfigGroup extends lib.PluginConfigGroup {} declare module "@clusterio/lib" {
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"]; export interface ControllerConfigFields {
ControllerConfigGroup.groupName = "subspace_storage"; "subspace_storage.division_method": "simple" | "dole" | "neural_dole";
ControllerConfigGroup.define({ "subspace_storage.log_item_transfers": boolean;
name: "division_method", }
title: "Division Method", export interface InstanceConfigFields {
description: "Method for dividing resource requests between instances.", "subspace_storage.log_item_transfers": boolean;
type: "string", }
enum: ["simple", "dole", "neural_dole"], }
initial_value: "simple",
});
ControllerConfigGroup.define({
name: "log_item_transfers",
title: "Log Item Transfers",
description: "Spam controller console with item transfers done.",
type: "boolean",
initial_value: false,
});
ControllerConfigGroup.finalize();
class InstanceConfigGroup extends lib.PluginConfigGroup {}
InstanceConfigGroup.defaultAccess = ["controller", "host", "control"];
InstanceConfigGroup.groupName = "subspace_storage";
InstanceConfigGroup.define({
name: "log_item_transfers",
title: "Log Item Transfers",
description: "Spam host console with item transfers done.",
type: "boolean",
initial_value: false,
});
InstanceConfigGroup.finalize();
lib.definePermission({ lib.definePermission({
name: "subspace_storage.storage.view", name: "subspace_storage.storage.view",
@@ -45,10 +23,31 @@ export default {
title: "Subspace Storage", title: "Subspace Storage",
description: "Provides shared storage across instances for the Subspace Storage mod", description: "Provides shared storage across instances for the Subspace Storage mod",
instanceEntrypoint: "dist/plugin/instance", instanceEntrypoint: "dist/plugin/instance",
InstanceConfigGroup, instanceConfigFields: {
"subspace_storage.log_item_transfers": {
title: "Log Item Transfers",
description: "Spam host console with item transfers done.",
type: "boolean",
initialValue: false,
},
},
controllerEntrypoint: "dist/plugin/controller", controllerEntrypoint: "dist/plugin/controller",
ControllerConfigGroup, controllerConfigFields: {
"subspace_storage.division_method": {
title: "Division Method",
description: "Method for dividing resource requests between instances.",
type: "string",
enum: ["simple", "dole", "neural_dole"],
initialValue: "simple",
},
"subspace_storage.log_item_transfers": {
title: "Log Item Transfers",
description: "Spam controller console with item transfers done.",
type: "boolean",
initialValue: false,
},
},
messages: [ messages: [
messages.PlaceEvent, messages.PlaceEvent,
+8 -12
View File
@@ -7,26 +7,22 @@ const lib = require("@clusterio/lib");
describe("controller/InstanceInfo", function() { describe("controller/InstanceInfo", function() {
describe("class InstanceInfo", function() { describe("class InstanceInfo", function() {
it("should round trip serialize", async function() { it("should round trip serialize", function() {
const validate = lib.compile(InstanceInfo.jsonSchema); const validate = lib.compile(InstanceInfo.jsonSchema);
function check(info) { function check(info) {
const json = JSON.parse(JSON.stringify(info)); const json = JSON.parse(JSON.stringify(info));
if (!validate(json)) { if (!validate(json)) {
throw validate.errors; throw validate.errors;
} }
assert.deepEqual(InstanceInfo.fromJSON(json, info.config), info); assert.deepEqual(InstanceInfo.fromJSON(json, "controller"), info);
} }
if (!lib.InstanceConfig._finalized) { const config = new lib.InstanceConfig("controller").toJSON();
lib.InstanceConfig.finalize();
}
const config = new lib.InstanceConfig("controller");
await config.init();
check(InstanceInfo.fromJSON({ config, status: "stopped" }, config)); check(InstanceInfo.fromJSON({ config, status: "stopped" }, "controller"));
check(InstanceInfo.fromJSON({ config, status: "running" }, config)); check(InstanceInfo.fromJSON({ config, status: "running" }, "controller"));
check(InstanceInfo.fromJSON({ config, status: "running", gamePort: 34197 }, config)); check(InstanceInfo.fromJSON({ config, status: "running", gamePort: 34197 }, "controller"));
check(InstanceInfo.fromJSON({ config, status: "running", updatedAt: Date.now() }, config)); check(InstanceInfo.fromJSON({ config, status: "running", updatedAt: Date.now() }, "controller"));
// All at once // All at once
check(InstanceInfo.fromJSON({ check(InstanceInfo.fromJSON({
@@ -34,7 +30,7 @@ describe("controller/InstanceInfo", function() {
status: "unknown", status: "unknown",
gamePort: 10000, gamePort: 10000,
updateAt: 20000, updateAt: 20000,
}, config)); }, "controller"));
}); });
}); });
}); });
-5
View File
@@ -7,17 +7,12 @@ const Host = require("@clusterio/host/dist/src/Host").default;
const { _discoverInstances } = require("@clusterio/host/dist/src/Host"); const { _discoverInstances } = require("@clusterio/host/dist/src/Host");
describe("Host testing", function() { describe("Host testing", function() {
before(function() {
lib.InstanceConfig.finalize();
});
describe("discoverInstances()", function() { describe("discoverInstances()", function() {
it("should discover test instance", async function() { it("should discover test instance", async function() {
let instancePath = path.join("test", "file", "instances"); let instancePath = path.join("test", "file", "instances");
let instanceInfos = await _discoverInstances(instancePath); let instanceInfos = await _discoverInstances(instancePath);
let referenceConfig = new lib.InstanceConfig("host"); let referenceConfig = new lib.InstanceConfig("host");
await referenceConfig.init();
referenceConfig.set("instance.id", 1); referenceConfig.set("instance.id", 1);
referenceConfig.set("instance.name", "test"); referenceConfig.set("instance.name", "test");
referenceConfig.dirty = false; referenceConfig.dirty = false;
+1 -6
View File
@@ -11,17 +11,12 @@ const addr = lib.Address.fromShorthand;
describe("class Instance", function() { describe("class Instance", function() {
before(function() {
lib.InstanceConfig.finalize();
});
let src; let src;
let dst = addr({ hostId: 1 }); let dst = addr({ hostId: 1 });
let instance; let instance;
let connector; let connector;
beforeEach(async function() { beforeEach(function() {
let instanceConfig = new lib.InstanceConfig("host"); let instanceConfig = new lib.InstanceConfig("host");
await instanceConfig.init();
instanceConfig.set("instance.name", "foo"); instanceConfig.set("instance.name", "foo");
src = addr({ instanceId: instanceConfig.get("instance.id") }); src = addr({ instanceId: instanceConfig.get("instance.id") });
connector = new MockConnector(src, dst); connector = new MockConnector(src, dst);
+2 -18
View File
@@ -205,30 +205,14 @@ describe("Integration of Clusterio", function() {
}); });
it("should not leak auth_secret", async function() { it("should not leak auth_secret", async function() {
let result = await getControl().send(new lib.ControllerConfigGetRequest()); let result = await getControl().send(new lib.ControllerConfigGetRequest());
let done = false; assert.equal(Object.prototype.hasOwnProperty.call(result, "controller.auth_secret"), false);
for (let group of result.serializedConfig.groups) {
if (group.name === "controller") {
assert.equal(Object.prototype.hasOwnProperty.call(group.fields, "auth_secret"), false);
done = true;
break;
}
}
assert(done, "controller group not found");
}); });
}); });
describe("controller config set", function() { describe("controller config set", function() {
it("sets given config option", async function() { it("sets given config option", async function() {
await execCtl('controller config set controller.name "Test Cluster"'); await execCtl('controller config set controller.name "Test Cluster"');
let result = await getControl().send(new lib.ControllerConfigGetRequest()); let result = await getControl().send(new lib.ControllerConfigGetRequest());
let done = false; assert.equal(result["controller.name"], "Test Cluster");
for (let group of result.serializedConfig.groups) {
if (group.name === "controller") {
assert.equal(group.fields.name, "Test Cluster");
done = true;
break;
}
}
assert(done, "controller group not found");
}); });
it("should not allow setting auth_secret", async function() { it("should not allow setting auth_secret", async function() {
await assert.rejects(execCtl("controller config set controller.auth_secret root")); await assert.rejects(execCtl("controller config set controller.auth_secret root"));
+269 -600
View File
File diff suppressed because it is too large. Load diff