mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-20 23:53:13 +09:00
Flatten lib namespace
Move all functions and classes currently available through lib/name and libName to be under a single flat namespace in lib. This make reorganising the lib namespace much simpler as the location of symbols can move without breaking the consumers of lib. The multi-entrypoint design was already problematic for the web plugin system which couldn't effectively use it due to how webpack's shared module system is awkward to set up with multiple entrypoints per package.
This commit is contained in:
1 parent
bb58670597
commit
bfe119eaa3
143 files changed
+1798
-1918
No files matched your search
@@ -205,12 +205,13 @@ Fields in configs and messages sent over links uses lowercase_underscore.
|
|||||||
JavaScript files are named using lowercase_underscore for files that export multiple items.
|
JavaScript files are named using lowercase_underscore for files that export multiple items.
|
||||||
Files containing and exporting a single class should be named the same as the class in PascalCase.
|
Files containing and exporting a single class should be named the same as the class in PascalCase.
|
||||||
|
|
||||||
Imported modules from the lib package are prefixed with lib to make them easier to distinguish, as the names tend to be very generic.
|
Relative imports in lib package are prefixed with lib to make them easier to distinguish, as the names tend to be very generic.
|
||||||
E.g.:
|
E.g.:
|
||||||
|
|
||||||
const libLink = require("@clusterio/lib/link");
|
const libLink = require("./link");
|
||||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
const libLuaTools = require("./lua_tools");
|
||||||
|
|
||||||
|
Note that no sub-modules of the lib package is imported directly from the outside of it with the exception of `build_mod`.
|
||||||
|
|
||||||
For lua code lowercase_underscore is used for everything.
|
For lua code lowercase_underscore is used for everything.
|
||||||
|
|
||||||
|
|||||||
+12
-12
@@ -49,7 +49,7 @@ Without it the plugin will not recognized by Clusterio.
|
|||||||
Here's an example of it:
|
Here's an example of it:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { libLink } = require("@clusterio/lib"); // For messages
|
const lib = require("@clusterio/lib"); // For messages
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
name: "foo_frobber",
|
name: "foo_frobber",
|
||||||
@@ -120,9 +120,9 @@ The plugin class should derive from its respective base class defined in `lib/pl
|
|||||||
For example, to define a ControllerPlugin class the following code can be used:
|
For example, to define a ControllerPlugin class the following code can be used:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
const lib = require("@clusterio/lib");
|
||||||
|
|
||||||
class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||||
async init() {
|
async init() {
|
||||||
this.foo = 42;
|
this.foo = 42;
|
||||||
await this.startFrobnication();
|
await this.startFrobnication();
|
||||||
@@ -206,9 +206,9 @@ You can take advantage of it by subclassing `PluginConfigGroup`, setting `defaul
|
|||||||
For example in info.js:
|
For example in info.js:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const libConfig = require("@clusterio/lib/config");
|
const lib = require("@clusterio/lib");
|
||||||
|
|
||||||
class ControllerConfigGroup extends libConfig.PluginConfigGroup { }
|
class ControllerConfigGroup extends lib.PluginConfigGroup { }
|
||||||
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
||||||
ControllerConfigGroup.groupName = "foo_frobber";
|
ControllerConfigGroup.groupName = "foo_frobber";
|
||||||
ControllerConfigGroup.define({
|
ControllerConfigGroup.define({
|
||||||
@@ -333,7 +333,7 @@ The Event constructor takes an object of properties that define the event, for e
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
messages: {
|
messages: {
|
||||||
startFrobnication: new libLink.Event({
|
startFrobnication: new lib.Event({
|
||||||
type: "foo_frobber:start_frobnication",
|
type: "foo_frobber:start_frobnication",
|
||||||
links: ["controller-host", "host-instance"],
|
links: ["controller-host", "host-instance"],
|
||||||
forwardTo: "instance",
|
forwardTo: "instance",
|
||||||
@@ -408,7 +408,7 @@ For example, the following could be defined in `info.js`:
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
messages: {
|
messages: {
|
||||||
reportFrobnication: new libLink.Request({
|
reportFrobnication: new lib.Request({
|
||||||
type: "foo_frobber:report_frobnication",
|
type: "foo_frobber:report_frobnication",
|
||||||
links: ["controller-host", "host-instance"],
|
links: ["controller-host", "host-instance"],
|
||||||
forwardTo: "instance",
|
forwardTo: "instance",
|
||||||
@@ -530,7 +530,7 @@ In its simplest form collecting data from plugins consists of defining the metri
|
|||||||
For example:
|
For example:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { Counter } = require("@clusterio/lib/prometheus");
|
const { Counter } = require("@clusterio/lib");
|
||||||
|
|
||||||
const fooMetric = new Counter(
|
const fooMetric = new Counter(
|
||||||
"clusterio_foo_frobber_foo_metric", "Measures the level of foo",
|
"clusterio_foo_frobber_foo_metric", "Measures the level of foo",
|
||||||
@@ -546,7 +546,7 @@ It's recommended that plugin metrics follow `clusterio_<plugin_name>_<metric_nam
|
|||||||
For metrics that are per-instance, you must define an `instance_id` label and set it accordingly, for example:
|
For metrics that are per-instance, you must define an `instance_id` label and set it accordingly, for example:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { Counter } = require("@clusterio/lib/prometheus");
|
const { Counter } = require("@clusterio/lib");
|
||||||
|
|
||||||
const barMetric = new Gauge(
|
const barMetric = new Gauge(
|
||||||
"clusterio_foo_frobber_bar_metric", "Bar instance level",
|
"clusterio_foo_frobber_bar_metric", "Bar instance level",
|
||||||
@@ -570,7 +570,7 @@ The control entrypoint for plugins allows you to extend clustectl with your own
|
|||||||
The creation of custom commands typically starts with defining a command tree for the plugin:
|
The creation of custom commands typically starts with defining a command tree for the plugin:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { Command, CommandTree } = require("@clusterio/lib/command");
|
const { Command, CommandTree } = require("@clusterio/lib");
|
||||||
const fooFrobberCommands = new CommandTree({
|
const fooFrobberCommands = new CommandTree({
|
||||||
name: "foo-frobber", description: "Foo Frobber Plugin commands"
|
name: "foo-frobber", description: "Foo Frobber Plugin commands"
|
||||||
});
|
});
|
||||||
@@ -605,9 +605,9 @@ Note that messages sent from clusterioctl needs to have `"control-controller"` a
|
|||||||
To have the command tree become part of clusterioctl it needs to be added to the rootCommand tree in `addCommands` callback of the Control plugin:
|
To have the command tree become part of clusterioctl it needs to be added to the rootCommand tree in `addCommands` callback of the Control plugin:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
const lib = require("@clusterio/lib");
|
||||||
|
|
||||||
class ControlPlugin extends libPlugin.BaseControlPlugin {
|
class ControlPlugin extends lib.BaseControlPlugin {
|
||||||
async addCommands(rootCommand) {
|
async addCommands(rootCommand) {
|
||||||
rootCommand.add(fooFrobberCommands);
|
rootCommand.add(fooFrobberCommands);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,16 +26,8 @@ require("winston-daily-rotate-file");
|
|||||||
const jwt = require("jsonwebtoken");
|
const jwt = require("jsonwebtoken");
|
||||||
|
|
||||||
// homebrew modules
|
// homebrew modules
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
const lib = require("@clusterio/lib");
|
||||||
const libFileOps = require("@clusterio/lib/file_ops");
|
const { ConsoleTransport, levels, logger } = lib;
|
||||||
const libLink = require("@clusterio/lib/link");
|
|
||||||
const libPluginLoader = require("@clusterio/lib/plugin_loader");
|
|
||||||
const libPrometheus = require("@clusterio/lib/prometheus");
|
|
||||||
const libConfig = require("@clusterio/lib/config");
|
|
||||||
const libUsers = require("@clusterio/lib/users");
|
|
||||||
const libSharedCommands = require("@clusterio/lib/shared_commands");
|
|
||||||
const { ConsoleTransport, levels, logger } = require("@clusterio/lib/logging");
|
|
||||||
const libLoggingUtils = require("@clusterio/lib/logging_utils");
|
|
||||||
|
|
||||||
const Controller = require("./src/Controller");
|
const Controller = require("./src/Controller");
|
||||||
const UserManager = require("./src/UserManager");
|
const UserManager = require("./src/UserManager");
|
||||||
@@ -45,7 +37,7 @@ const version = require("./package").version;
|
|||||||
let controller;
|
let controller;
|
||||||
|
|
||||||
|
|
||||||
void new libPrometheus.Gauge(
|
void new lib.Gauge(
|
||||||
"clusterio_controller_host_mapping",
|
"clusterio_controller_host_mapping",
|
||||||
"Mapping of Host ID to name",
|
"Mapping of Host ID to name",
|
||||||
{
|
{
|
||||||
@@ -65,7 +57,7 @@ void new libPrometheus.Gauge(
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
void new libPrometheus.Gauge(
|
void new lib.Gauge(
|
||||||
"clusterio_controller_instance_mapping",
|
"clusterio_controller_instance_mapping",
|
||||||
"Mapping of Instance ID to name and host",
|
"Mapping of Instance ID to name and host",
|
||||||
{
|
{
|
||||||
@@ -86,19 +78,19 @@ void new libPrometheus.Gauge(
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
void new libPrometheus.Gauge(
|
void new lib.Gauge(
|
||||||
"clusterio_controller_websocket_active_connections",
|
"clusterio_controller_websocket_active_connections",
|
||||||
"How many WebSocket connections are currently open to the controller",
|
"How many WebSocket connections are currently open to the controller",
|
||||||
{ callback: function(gauge) { gauge.set(controller.wsServer.activeConnectors.size); }}
|
{ callback: function(gauge) { gauge.set(controller.wsServer.activeConnectors.size); }}
|
||||||
);
|
);
|
||||||
|
|
||||||
void new libPrometheus.Gauge(
|
void new lib.Gauge(
|
||||||
"clusterio_controller_active_hosts",
|
"clusterio_controller_active_hosts",
|
||||||
"How many hosts are currently connected to the controller",
|
"How many hosts are currently connected to the controller",
|
||||||
{ callback: function(gauge) { gauge.set(controller.wsServer.hostConnections.size); }}
|
{ callback: function(gauge) { gauge.set(controller.wsServer.hostConnections.size); }}
|
||||||
);
|
);
|
||||||
|
|
||||||
void new libPrometheus.Gauge(
|
void new lib.Gauge(
|
||||||
"clusterio_controller_connected_clients_count", "How many clients are currently connected to this controller",
|
"clusterio_controller_connected_clients_count", "How many clients are currently connected to this controller",
|
||||||
{
|
{
|
||||||
labels: ["type"], callback: async function(gauge) {
|
labels: ["type"], callback: async function(gauge) {
|
||||||
@@ -125,7 +117,7 @@ async function handleBootstrapCommand(args, controllerConfig) {
|
|||||||
admin = userManager.createUser(args.name);
|
admin = userManager.createUser(args.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
let adminRole = libUsers.ensureDefaultAdminRole(userManager.roles);
|
let adminRole = lib.ensureDefaultAdminRole(userManager.roles);
|
||||||
admin.roles.add(adminRole);
|
admin.roles.add(adminRole);
|
||||||
admin.isAdmin = true;
|
admin.isAdmin = true;
|
||||||
await userManager.save(path.join(controllerConfig.get("controller.database_directory"), "users.json"));
|
await userManager.save(path.join(controllerConfig.get("controller.database_directory"), "users.json"));
|
||||||
@@ -154,7 +146,7 @@ async function handleBootstrapCommand(args, controllerConfig) {
|
|||||||
process.exitCode = 1;
|
process.exitCode = 1;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let controlConfig = new libConfig.ControlConfig("control");
|
let controlConfig = new lib.ControlConfig("control");
|
||||||
await controlConfig.init();
|
await controlConfig.init();
|
||||||
|
|
||||||
controlConfig.set("control.controller_url", Controller.calculateControllerUrl(controllerConfig));
|
controlConfig.set("control.controller_url", Controller.calculateControllerUrl(controllerConfig));
|
||||||
@@ -168,7 +160,7 @@ async function handleBootstrapCommand(args, controllerConfig) {
|
|||||||
console.log(content);
|
console.log(content);
|
||||||
} else {
|
} else {
|
||||||
logger.info(`Writing ${args.output}`);
|
logger.info(`Writing ${args.output}`);
|
||||||
await libFileOps.safeOutputFile(args.output, content);
|
await lib.safeOutputFile(args.output, content);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -212,8 +204,8 @@ async function initialize() {
|
|||||||
default: "plugin-list.json",
|
default: "plugin-list.json",
|
||||||
type: "string",
|
type: "string",
|
||||||
})
|
})
|
||||||
.command("plugin", "Manage available plugins", libSharedCommands.pluginCommand)
|
.command("plugin", "Manage available plugins", lib.pluginCommand)
|
||||||
.command("config", "Manage Controller config", libSharedCommands.configCommand)
|
.command("config", "Manage Controller config", lib.configCommand)
|
||||||
.command("bootstrap", "Bootstrap access to cluster", yargs => {
|
.command("bootstrap", "Bootstrap access to cluster", yargs => {
|
||||||
yargs
|
yargs
|
||||||
.command("create-admin <name>", "Create a cluster admin")
|
.command("create-admin <name>", "Create a cluster admin")
|
||||||
@@ -262,10 +254,10 @@ async function initialize() {
|
|||||||
if (parameters.args.logLevel !== "none") {
|
if (parameters.args.logLevel !== "none") {
|
||||||
logger.add(new ConsoleTransport({
|
logger.add(new ConsoleTransport({
|
||||||
level: parameters.args.logLevel,
|
level: parameters.args.logLevel,
|
||||||
format: new libLoggingUtils.TerminalFormat(),
|
format: new lib.TerminalFormat(),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
libLoggingUtils.handleUnhandledErrors(logger);
|
lib.handleUnhandledErrors(logger);
|
||||||
|
|
||||||
let command = parameters.args._[0];
|
let command = parameters.args._[0];
|
||||||
if (command === "run") {
|
if (command === "run") {
|
||||||
@@ -285,19 +277,19 @@ async function initialize() {
|
|||||||
|
|
||||||
// If the command is plugin management we don't try to load plugins
|
// If the command is plugin management we don't try to load plugins
|
||||||
if (command === "plugin") {
|
if (command === "plugin") {
|
||||||
await libSharedCommands.handlePluginCommand(parameters.args, pluginList, parameters.args.pluginList);
|
await lib.handlePluginCommand(parameters.args, pluginList, parameters.args.pluginList);
|
||||||
return parameters;
|
return parameters;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("Loading Plugin info");
|
logger.info("Loading Plugin info");
|
||||||
parameters.pluginInfos = await libPluginLoader.loadPluginInfos(pluginList);
|
parameters.pluginInfos = await lib.loadPluginInfos(pluginList);
|
||||||
libLink.registerPluginMessages(parameters.pluginInfos);
|
lib.registerPluginMessages(parameters.pluginInfos);
|
||||||
libConfig.registerPluginConfigGroups(parameters.pluginInfos);
|
lib.registerPluginConfigGroups(parameters.pluginInfos);
|
||||||
libConfig.finalizeConfigs();
|
lib.finalizeConfigs();
|
||||||
|
|
||||||
parameters.controllerConfigPath = parameters.args.config;
|
parameters.controllerConfigPath = parameters.args.config;
|
||||||
logger.info(`Loading config from ${parameters.controllerConfigPath}`);
|
logger.info(`Loading config from ${parameters.controllerConfigPath}`);
|
||||||
parameters.controllerConfig = new libConfig.ControllerConfig("controller");
|
parameters.controllerConfig = new lib.ControllerConfig("controller");
|
||||||
try {
|
try {
|
||||||
await parameters.controllerConfig.load(JSON.parse(await fs.readFile(parameters.controllerConfigPath)));
|
await parameters.controllerConfig.load(JSON.parse(await fs.readFile(parameters.controllerConfigPath)));
|
||||||
|
|
||||||
@@ -307,7 +299,7 @@ async function initialize() {
|
|||||||
await parameters.controllerConfig.init();
|
await parameters.controllerConfig.init();
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
throw new libErrors.StartupError(`Failed to load ${parameters.controllerConfigPath}: ${err.message}`);
|
throw new lib.StartupError(`Failed to load ${parameters.controllerConfigPath}: ${err.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,13 +308,13 @@ async function initialize() {
|
|||||||
let asyncRandomBytes = util.promisify(crypto.randomBytes);
|
let asyncRandomBytes = util.promisify(crypto.randomBytes);
|
||||||
let bytes = await asyncRandomBytes(256);
|
let bytes = await asyncRandomBytes(256);
|
||||||
parameters.controllerConfig.set("controller.auth_secret", bytes.toString("base64"));
|
parameters.controllerConfig.set("controller.auth_secret", bytes.toString("base64"));
|
||||||
await libFileOps.safeOutputFile(
|
await lib.safeOutputFile(
|
||||||
parameters.controllerConfigPath, JSON.stringify(parameters.controllerConfig.serialize(), null, 4)
|
parameters.controllerConfigPath, JSON.stringify(parameters.controllerConfig.serialize(), null, 4)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (command === "config") {
|
if (command === "config") {
|
||||||
await libSharedCommands.handleConfigCommand(
|
await lib.handleConfigCommand(
|
||||||
parameters.args, parameters.controllerConfig, parameters.controllerConfigPath
|
parameters.args, parameters.controllerConfig, parameters.controllerConfigPath
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -393,14 +385,14 @@ I version of clusterio. Expect things to break. I
|
|||||||
`
|
`
|
||||||
);
|
);
|
||||||
startup().catch(err => {
|
startup().catch(err => {
|
||||||
if (err instanceof libErrors.StartupError) {
|
if (err instanceof lib.StartupError) {
|
||||||
logger.fatal(`
|
logger.fatal(`
|
||||||
+-------------------------------+
|
+-------------------------------+
|
||||||
| Unable to to start controller |
|
| Unable to to start controller |
|
||||||
+-------------------------------+
|
+-------------------------------+
|
||||||
${err.stack}`
|
${err.stack}`
|
||||||
);
|
);
|
||||||
} else if (err instanceof libErrors.PluginError) {
|
} else if (err instanceof lib.PluginError) {
|
||||||
logger.fatal(`
|
logger.fatal(`
|
||||||
${err.pluginName} plugin threw an unexpected error
|
${err.pluginName} plugin threw an unexpected error
|
||||||
during startup, please report it to the plugin author.
|
during startup, please report it to the plugin author.
|
||||||
|
|||||||
@@ -1,19 +1,16 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
const { logger } = lib;
|
||||||
const libLink = require("@clusterio/lib/link");
|
|
||||||
const { logger } = require("@clusterio/lib/logging");
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const ControllerRouter = require("./ControllerRouter");
|
const ControllerRouter = require("./ControllerRouter");
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base class for controller connections
|
* Base class for controller connections
|
||||||
*
|
*
|
||||||
* @extends module:lib/link.Link
|
* @extends module:lib.Link
|
||||||
* @alias module:controller/src/BaseConnection
|
* @alias module:controller/src/BaseConnection
|
||||||
*/
|
*/
|
||||||
class BaseConnection extends libLink.Link {
|
class BaseConnection extends lib.Link {
|
||||||
constructor(connector, controller) {
|
constructor(connector, controller) {
|
||||||
/** @member {module:controller/src/WsServerConnector} module:controller/src/BaseConnection#connector */
|
/** @member {module:controller/src/WsServerConnector} module:controller/src/BaseConnection#connector */
|
||||||
super(connector);
|
super(connector);
|
||||||
@@ -24,15 +21,15 @@ class BaseConnection extends libLink.Link {
|
|||||||
for (let [Event, handler] of controller._registeredEvents) { this.handle(Event, handler); }
|
for (let [Event, handler] of controller._registeredEvents) { this.handle(Event, handler); }
|
||||||
for (let [Event, handler] of controller._snoopedEvents) { this.snoopEvent(Event, handler); }
|
for (let [Event, handler] of controller._snoopedEvents) { this.snoopEvent(Event, handler); }
|
||||||
|
|
||||||
this.handle(libData.ModPackGetRequest, this.handleModPackGetRequest.bind(this));
|
this.handle(lib.ModPackGetRequest, this.handleModPackGetRequest.bind(this));
|
||||||
this.handle(libData.ModPackGetDefaultRequest, this.handleModPackGetDefaultRequest.bind(this));
|
this.handle(lib.ModPackGetDefaultRequest, this.handleModPackGetDefaultRequest.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
async disconnect(code, reason) {
|
async disconnect(code, reason) {
|
||||||
try {
|
try {
|
||||||
await this.connector.disconnect();
|
await this.connector.disconnect();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!(err instanceof libErrors.SessionLost)) {
|
if (!(err instanceof lib.SessionLost)) {
|
||||||
logger.error(`"Unexpected error preparing disconnect:\n${err.stack}`);
|
logger.error(`"Unexpected error preparing disconnect:\n${err.stack}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,7 +48,7 @@ class BaseConnection extends libLink.Link {
|
|||||||
let { id } = request;
|
let { id } = request;
|
||||||
let modPack = this._controller.modPacks.get(id);
|
let modPack = this._controller.modPacks.get(id);
|
||||||
if (!modPack) {
|
if (!modPack) {
|
||||||
throw new libErrors.RequestError(`Mod pack with ID ${id} does not exist`);
|
throw new lib.RequestError(`Mod pack with ID ${id} does not exist`);
|
||||||
}
|
}
|
||||||
return modPack;
|
return modPack;
|
||||||
}
|
}
|
||||||
@@ -59,11 +56,11 @@ class BaseConnection extends libLink.Link {
|
|||||||
async handleModPackGetDefaultRequest() {
|
async handleModPackGetDefaultRequest() {
|
||||||
let id = this._controller.config.get("controller.default_mod_pack_id");
|
let id = this._controller.config.get("controller.default_mod_pack_id");
|
||||||
if (id === null) {
|
if (id === null) {
|
||||||
throw new libErrors.RequestError("Default mod pack not set on controller");
|
throw new lib.RequestError("Default mod pack not set on controller");
|
||||||
}
|
}
|
||||||
let modPack = this._controller.modPacks.get(id);
|
let modPack = this._controller.modPacks.get(id);
|
||||||
if (!modPack) {
|
if (!modPack) {
|
||||||
throw new libErrors.RequestError(`Default mod pack configured (${id}) does not exist`);
|
throw new lib.RequestError(`Default mod pack configured (${id}) does not exist`);
|
||||||
}
|
}
|
||||||
return modPack;
|
return modPack;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,22 +3,15 @@ const events = require("events");
|
|||||||
const fs = require("fs-extra");
|
const fs = require("fs-extra");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
|
|
||||||
const libConfig = require("@clusterio/lib/config");
|
const lib = require("@clusterio/lib");
|
||||||
const libData = require("@clusterio/lib/data");
|
const { logFilter, logger } = lib;
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
const libHelpers = require("@clusterio/lib/helpers");
|
|
||||||
const libLink = require("@clusterio/lib/link");
|
|
||||||
const { logFilter, logger } = require("@clusterio/lib/logging");
|
|
||||||
const libLoggingUtils = require("@clusterio/lib/logging_utils");
|
|
||||||
const libPrometheus = require("@clusterio/lib/prometheus");
|
|
||||||
const libUsers = require("@clusterio/lib/users");
|
|
||||||
|
|
||||||
const BaseConnection = require("./BaseConnection");
|
const BaseConnection = require("./BaseConnection");
|
||||||
const routes = require("./routes");
|
const routes = require("./routes");
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
||||||
|
|
||||||
const queryLogTime = new libPrometheus.Summary(
|
const queryLogTime = new lib.Summary(
|
||||||
"clusterio_controller_query_log_duration_seconds",
|
"clusterio_controller_query_log_duration_seconds",
|
||||||
"Time in seconds log queries took to execute."
|
"Time in seconds log queries took to execute."
|
||||||
);
|
);
|
||||||
@@ -39,7 +32,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The user making this connection.
|
* The user making this connection.
|
||||||
* @type {module:lib/users.User}
|
* @type {module:lib.User}
|
||||||
*/
|
*/
|
||||||
this.user = user;
|
this.user = user;
|
||||||
|
|
||||||
@@ -103,75 +96,75 @@ class ControlConnection extends BaseConnection {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this.handle(libData.ControllerConfigGetRequest, this.handleControllerConfigGetRequest.bind(this));
|
this.handle(lib.ControllerConfigGetRequest, this.handleControllerConfigGetRequest.bind(this));
|
||||||
this.handle(libData.ControllerConfigSetFieldRequest, this.handleControllerConfigSetFieldRequest.bind(this));
|
this.handle(lib.ControllerConfigSetFieldRequest, this.handleControllerConfigSetFieldRequest.bind(this));
|
||||||
this.handle(libData.ControllerConfigSetPropRequest, this.handleControllerConfigSetPropRequest.bind(this));
|
this.handle(lib.ControllerConfigSetPropRequest, this.handleControllerConfigSetPropRequest.bind(this));
|
||||||
this.handle(libData.HostListRequest, this.handleHostListRequest.bind(this));
|
this.handle(lib.HostListRequest, this.handleHostListRequest.bind(this));
|
||||||
this.handle(libData.HostSetSubscriptionsRequest, this.handleHostSetSubscriptionsRequest.bind(this));
|
this.handle(lib.HostSetSubscriptionsRequest, this.handleHostSetSubscriptionsRequest.bind(this));
|
||||||
this.handle(libData.HostGenerateTokenRequest, this.handleHostGenerateTokenRequest.bind(this));
|
this.handle(lib.HostGenerateTokenRequest, this.handleHostGenerateTokenRequest.bind(this));
|
||||||
this.handle(libData.HostConfigCreateRequest, this.handleHostConfigCreateRequest.bind(this));
|
this.handle(lib.HostConfigCreateRequest, this.handleHostConfigCreateRequest.bind(this));
|
||||||
this.handle(libData.InstanceDetailsGetRequest, this.handleInstanceDetailsGetRequest.bind(this));
|
this.handle(lib.InstanceDetailsGetRequest, this.handleInstanceDetailsGetRequest.bind(this));
|
||||||
this.handle(libData.InstanceDetailsListRequest, this.handleInstanceDetailsListRequest.bind(this));
|
this.handle(lib.InstanceDetailsListRequest, this.handleInstanceDetailsListRequest.bind(this));
|
||||||
this.handle(
|
this.handle(
|
||||||
libData.InstanceDetailsSetSubscriptionsRequest, this.handleInstanceDetailsSetSubscriptionsRequest.bind(this)
|
lib.InstanceDetailsSetSubscriptionsRequest, this.handleInstanceDetailsSetSubscriptionsRequest.bind(this)
|
||||||
);
|
);
|
||||||
this.handle(libData.InstanceCreateRequest, this.handleInstanceCreateRequest.bind(this));
|
this.handle(lib.InstanceCreateRequest, this.handleInstanceCreateRequest.bind(this));
|
||||||
this.handle(libData.InstanceDeleteRequest, this.handleInstanceDeleteRequest.bind(this));
|
this.handle(lib.InstanceDeleteRequest, this.handleInstanceDeleteRequest.bind(this));
|
||||||
this.handle(libData.InstanceConfigGetRequest, this.handleInstanceConfigGetRequest.bind(this));
|
this.handle(lib.InstanceConfigGetRequest, this.handleInstanceConfigGetRequest.bind(this));
|
||||||
this.handle(libData.InstanceConfigSetFieldRequest, this.handleInstanceConfigSetFieldRequest.bind(this));
|
this.handle(lib.InstanceConfigSetFieldRequest, this.handleInstanceConfigSetFieldRequest.bind(this));
|
||||||
this.handle(libData.InstanceConfigSetPropRequest, this.handleInstanceConfigSetPropRequest.bind(this));
|
this.handle(lib.InstanceConfigSetPropRequest, this.handleInstanceConfigSetPropRequest.bind(this));
|
||||||
this.handle(libData.InstanceAssignRequest, this.handleInstanceAssignRequest.bind(this));
|
this.handle(lib.InstanceAssignRequest, this.handleInstanceAssignRequest.bind(this));
|
||||||
this.handle(
|
this.handle(
|
||||||
libData.InstanceSetSaveListSubscriptionsRequest,
|
lib.InstanceSetSaveListSubscriptionsRequest,
|
||||||
this.handleInstanceSetSaveListSubscriptionsRequest.bind(this)
|
this.handleInstanceSetSaveListSubscriptionsRequest.bind(this)
|
||||||
);
|
);
|
||||||
this.handle(
|
this.handle(
|
||||||
libData.InstanceRenameSaveRequest, this._controller.sendToHostByInstanceId.bind(this._controller)
|
lib.InstanceRenameSaveRequest, this._controller.sendToHostByInstanceId.bind(this._controller)
|
||||||
);
|
);
|
||||||
this.handle(libData.InstanceCopySaveRequest, this._controller.sendToHostByInstanceId.bind(this._controller));
|
this.handle(lib.InstanceCopySaveRequest, this._controller.sendToHostByInstanceId.bind(this._controller));
|
||||||
this.handle(
|
this.handle(
|
||||||
libData.InstanceDeleteSaveRequest, this._controller.sendToHostByInstanceId.bind(this._controller)
|
lib.InstanceDeleteSaveRequest, this._controller.sendToHostByInstanceId.bind(this._controller)
|
||||||
);
|
);
|
||||||
this.handle(libData.InstanceDownloadSaveRequest, this.handleInstanceDownloadSaveRequest.bind(this));
|
this.handle(lib.InstanceDownloadSaveRequest, this.handleInstanceDownloadSaveRequest.bind(this));
|
||||||
this.handle(libData.InstanceTransferSaveRequest, this.handleInstanceTransferSaveRequest.bind(this));
|
this.handle(lib.InstanceTransferSaveRequest, this.handleInstanceTransferSaveRequest.bind(this));
|
||||||
this.handle(libData.ModPackListRequest, this.handleModPackListRequest.bind(this));
|
this.handle(lib.ModPackListRequest, this.handleModPackListRequest.bind(this));
|
||||||
this.handle(libData.ModPackSetSubscriptionsRequest, this.handleModPackSetSubscriptionsRequest.bind(this));
|
this.handle(lib.ModPackSetSubscriptionsRequest, this.handleModPackSetSubscriptionsRequest.bind(this));
|
||||||
this.handle(libData.ModPackCreateRequest, this.handleModPackCreateRequest.bind(this));
|
this.handle(lib.ModPackCreateRequest, this.handleModPackCreateRequest.bind(this));
|
||||||
this.handle(libData.ModPackUpdateRequest, this.handleModPackUpdateRequest.bind(this));
|
this.handle(lib.ModPackUpdateRequest, this.handleModPackUpdateRequest.bind(this));
|
||||||
this.handle(libData.ModPackDeleteRequest, this.handleModPackDeleteRequest.bind(this));
|
this.handle(lib.ModPackDeleteRequest, this.handleModPackDeleteRequest.bind(this));
|
||||||
this.handle(libData.ModGetRequest, this.handleModGetRequest.bind(this));
|
this.handle(lib.ModGetRequest, this.handleModGetRequest.bind(this));
|
||||||
this.handle(libData.ModListRequest, this.handleModListRequest.bind(this));
|
this.handle(lib.ModListRequest, this.handleModListRequest.bind(this));
|
||||||
this.handle(libData.ModSearchRequest, this.handleModSearchRequest.bind(this));
|
this.handle(lib.ModSearchRequest, this.handleModSearchRequest.bind(this));
|
||||||
this.handle(libData.ModSetSubscriptionsRequest, this.handleModSetSubscriptionsRequest.bind(this));
|
this.handle(lib.ModSetSubscriptionsRequest, this.handleModSetSubscriptionsRequest.bind(this));
|
||||||
this.handle(libData.ModDownloadRequest, this.handleModDownloadRequest.bind(this));
|
this.handle(lib.ModDownloadRequest, this.handleModDownloadRequest.bind(this));
|
||||||
this.handle(libData.ModDeleteRequest, this.handleModDeleteRequest.bind(this));
|
this.handle(lib.ModDeleteRequest, this.handleModDeleteRequest.bind(this));
|
||||||
this.handle(libData.LogSetSubscriptionsRequest, this.handleLogSetSubscriptionsRequest.bind(this));
|
this.handle(lib.LogSetSubscriptionsRequest, this.handleLogSetSubscriptionsRequest.bind(this));
|
||||||
this.handle(libData.LogQueryRequest, this.handleLogQueryRequest.bind(this));
|
this.handle(lib.LogQueryRequest, this.handleLogQueryRequest.bind(this));
|
||||||
this.handle(libData.PermissionListRequest, this.handlePermissionListRequest.bind(this));
|
this.handle(lib.PermissionListRequest, this.handlePermissionListRequest.bind(this));
|
||||||
this.handle(libData.RoleListRequest, this.handleRoleListRequest.bind(this));
|
this.handle(lib.RoleListRequest, this.handleRoleListRequest.bind(this));
|
||||||
this.handle(libData.RoleCreateRequest, this.handleRoleCreateRequest.bind(this));
|
this.handle(lib.RoleCreateRequest, this.handleRoleCreateRequest.bind(this));
|
||||||
this.handle(libData.RoleUpdateRequest, this.handleRoleUpdateRequest.bind(this));
|
this.handle(lib.RoleUpdateRequest, this.handleRoleUpdateRequest.bind(this));
|
||||||
this.handle(
|
this.handle(
|
||||||
libData.RoleGrantDefaultPermissionsRequest, this.handleRoleGrantDefaultPermissionsRequest.bind(this)
|
lib.RoleGrantDefaultPermissionsRequest, this.handleRoleGrantDefaultPermissionsRequest.bind(this)
|
||||||
);
|
);
|
||||||
this.handle(libData.RoleDeleteRequest, this.handleRoleDeleteRequest.bind(this));
|
this.handle(lib.RoleDeleteRequest, this.handleRoleDeleteRequest.bind(this));
|
||||||
this.handle(libData.UserGetRequest, this.handleUserGetRequest.bind(this));
|
this.handle(lib.UserGetRequest, this.handleUserGetRequest.bind(this));
|
||||||
this.handle(libData.UserListRequest, this.handleUserListRequest.bind(this));
|
this.handle(lib.UserListRequest, this.handleUserListRequest.bind(this));
|
||||||
this.handle(libData.UserSetSubscriptionsRequest, this.handleUserSetSubscriptionsRequest.bind(this));
|
this.handle(lib.UserSetSubscriptionsRequest, this.handleUserSetSubscriptionsRequest.bind(this));
|
||||||
this.handle(libData.UserCreateRequest, this.handleUserCreateRequest.bind(this));
|
this.handle(lib.UserCreateRequest, this.handleUserCreateRequest.bind(this));
|
||||||
this.handle(libData.UserRevokeTokenRequest, this.handleUserRevokeTokenRequest.bind(this));
|
this.handle(lib.UserRevokeTokenRequest, this.handleUserRevokeTokenRequest.bind(this));
|
||||||
this.handle(libData.UserUpdateRolesRequest, this.handleUserUpdateRolesRequest.bind(this));
|
this.handle(lib.UserUpdateRolesRequest, this.handleUserUpdateRolesRequest.bind(this));
|
||||||
this.handle(libData.UserSetAdminRequest, this.handleUserSetAdminRequest.bind(this));
|
this.handle(lib.UserSetAdminRequest, this.handleUserSetAdminRequest.bind(this));
|
||||||
this.handle(libData.UserSetBannedRequest, this.handleUserSetBannedRequest.bind(this));
|
this.handle(lib.UserSetBannedRequest, this.handleUserSetBannedRequest.bind(this));
|
||||||
this.handle(libData.UserSetWhitelistedRequest, this.handleUserSetWhitelistedRequest.bind(this));
|
this.handle(lib.UserSetWhitelistedRequest, this.handleUserSetWhitelistedRequest.bind(this));
|
||||||
this.handle(libData.UserDeleteRequest, this.handleUserDeleteRequest.bind(this));
|
this.handle(lib.UserDeleteRequest, this.handleUserDeleteRequest.bind(this));
|
||||||
this.handle(libData.DebugDumpWsRequest, this.handleDebugDumpWsRequest.bind(this));
|
this.handle(lib.DebugDumpWsRequest, this.handleDebugDumpWsRequest.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
validateIngress(message) {
|
validateIngress(message) {
|
||||||
let origin = this.connector.dst;
|
let origin = this.connector.dst;
|
||||||
if (origin.type !== message.src.type || origin.id !== message.src.id) {
|
if (origin.type !== message.src.type || origin.id !== message.src.id) {
|
||||||
throw new libErrors.InvalidMessage(`Received message with invalid src ${message.src} from ${origin}`);
|
throw new lib.InvalidMessage(`Received message with invalid src ${message.src} from ${origin}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +172,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
try {
|
try {
|
||||||
this.checkPermission(message, entry);
|
this.checkPermission(message, entry);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
|
this.connector.sendResponseError(new lib.ResponseError(err.message, err.code), message.src);
|
||||||
logger.audit(`Permission denied for ${message.name} by ${this.user.name} from ${this.connector.dst}`);
|
logger.audit(`Permission denied for ${message.name} by ${this.user.name} from ${this.connector.dst}`);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -213,7 +206,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleControllerConfigGetRequest() {
|
async handleControllerConfigGetRequest() {
|
||||||
return new libData.RawConfig(this._controller.config.serialize("control"));
|
return new lib.RawConfig(this._controller.config.serialize("control"));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleControllerConfigSetFieldRequest(request) {
|
async handleControllerConfigSetFieldRequest(request) {
|
||||||
@@ -228,7 +221,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleHostListRequest() {
|
async handleHostListRequest() {
|
||||||
let list = [];
|
let list = [];
|
||||||
for (let host of this._controller.hosts.values()) {
|
for (let host of this._controller.hosts.values()) {
|
||||||
list.push(new libData.HostDetails(
|
list.push(new lib.HostDetails(
|
||||||
host.agent,
|
host.agent,
|
||||||
host.version,
|
host.version,
|
||||||
host.name,
|
host.name,
|
||||||
@@ -249,7 +242,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.hostSubscriptions.all
|
this.hostSubscriptions.all
|
||||||
|| this.hostSubscriptions.hostIds.includes(host.id)
|
|| this.hostSubscriptions.hostIds.includes(host.id)
|
||||||
) {
|
) {
|
||||||
this.send(new libData.HostUpdateEvent(update));
|
this.send(new lib.HostUpdateEvent(update));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,7 +255,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleHostConfigCreateRequest(request) {
|
async handleHostConfigCreateRequest(request) {
|
||||||
let hostConfig = new libConfig.HostConfig("control");
|
let hostConfig = new lib.HostConfig("control");
|
||||||
await hostConfig.init();
|
await hostConfig.init();
|
||||||
|
|
||||||
hostConfig.set("host.controller_url", this._controller.getControllerUrl());
|
hostConfig.set("host.controller_url", this._controller.getControllerUrl());
|
||||||
@@ -276,13 +269,13 @@ 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 libData.RawConfig(hostConfig.serialize());
|
return new lib.RawConfig(hostConfig.serialize());
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceDetailsGetRequest(request) {
|
async handleInstanceDetailsGetRequest(request) {
|
||||||
let instance = this._controller.getRequestInstance(request.instanceId);
|
let instance = this._controller.getRequestInstance(request.instanceId);
|
||||||
|
|
||||||
return new libData.InstanceDetails(
|
return new lib.InstanceDetails(
|
||||||
instance.config.get("instance.name"),
|
instance.config.get("instance.name"),
|
||||||
instance.id,
|
instance.id,
|
||||||
instance.config.get("instance.assigned_host"),
|
instance.config.get("instance.assigned_host"),
|
||||||
@@ -294,7 +287,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleInstanceDetailsListRequest() {
|
async handleInstanceDetailsListRequest() {
|
||||||
let list = [];
|
let list = [];
|
||||||
for (let instance of this._controller.instances.values()) {
|
for (let instance of this._controller.instances.values()) {
|
||||||
list.push(new libData.InstanceDetails(
|
list.push(new lib.InstanceDetails(
|
||||||
instance.config.get("instance.name"),
|
instance.config.get("instance.name"),
|
||||||
instance.id,
|
instance.id,
|
||||||
instance.config.get("instance.assigned_host"),
|
instance.config.get("instance.assigned_host"),
|
||||||
@@ -314,8 +307,8 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.instanceSubscriptions.all
|
this.instanceSubscriptions.all
|
||||||
|| this.instanceSubscriptions.instanceIds.includes(instance.id)
|
|| this.instanceSubscriptions.instanceIds.includes(instance.id)
|
||||||
) {
|
) {
|
||||||
this.send(new libData.InstanceDetailsUpdateEvent(
|
this.send(new lib.InstanceDetailsUpdateEvent(
|
||||||
new libData.InstanceDetails(
|
new lib.InstanceDetails(
|
||||||
instance.config.get("instance.name"),
|
instance.config.get("instance.name"),
|
||||||
instance.id,
|
instance.id,
|
||||||
instance.config.get("instance.assigned_host"),
|
instance.config.get("instance.assigned_host"),
|
||||||
@@ -328,7 +321,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
// XXX should probably add a hook for host reuqests?
|
// XXX should probably add a hook for host reuqests?
|
||||||
async handleInstanceCreateRequest(request) {
|
async handleInstanceCreateRequest(request) {
|
||||||
let instanceConfig = new libConfig.InstanceConfig("controller");
|
let instanceConfig = new lib.InstanceConfig("controller");
|
||||||
await instanceConfig.load(request.config);
|
await instanceConfig.load(request.config);
|
||||||
await this._controller.instanceCreate(instanceConfig);
|
await this._controller.instanceCreate(instanceConfig);
|
||||||
}
|
}
|
||||||
@@ -339,18 +332,18 @@ class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
async handleInstanceConfigGetRequest(request) {
|
async handleInstanceConfigGetRequest(request) {
|
||||||
let instance = this._controller.getRequestInstance(request.instanceId);
|
let instance = this._controller.getRequestInstance(request.instanceId);
|
||||||
return new libData.InstanceConfigGetRequest.Response(instance.config.serialize("control"));
|
return new lib.InstanceConfigGetRequest.Response(instance.config.serialize("control"));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceConfigSetFieldRequest(request) {
|
async handleInstanceConfigSetFieldRequest(request) {
|
||||||
let instance = this._controller.getRequestInstance(request.instanceId);
|
let instance = this._controller.getRequestInstance(request.instanceId);
|
||||||
if (request.field === "instance.assigned_host") {
|
if (request.field === "instance.assigned_host") {
|
||||||
throw new libErrors.RequestError("instance.assigned_host must be set through the assign-host interface");
|
throw new lib.RequestError("instance.assigned_host must be set through the assign-host interface");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (request.field === "instance.id") {
|
if (request.field === "instance.id") {
|
||||||
// XXX is this worth implementing? It's race condition galore.
|
// XXX is this worth implementing? It's race condition galore.
|
||||||
throw new libErrors.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, request.value, "control");
|
||||||
@@ -377,7 +370,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.saveListSubscriptions.all
|
this.saveListSubscriptions.all
|
||||||
|| this.saveListSubscriptions.instanceIds.includes(instanceId)
|
|| this.saveListSubscriptions.instanceIds.includes(instanceId)
|
||||||
) {
|
) {
|
||||||
this.send(new libData.InstanceSaveListUpdateEvent(instanceId, saves));
|
this.send(new lib.InstanceSaveListUpdateEvent(instanceId, saves));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -389,12 +382,12 @@ class ControlConnection extends BaseConnection {
|
|||||||
let ready = new Promise((resolve, reject) => {
|
let ready = new Promise((resolve, reject) => {
|
||||||
stream.events.on("source", resolve);
|
stream.events.on("source", resolve);
|
||||||
stream.events.on("timeout", () => reject(
|
stream.events.on("timeout", () => reject(
|
||||||
new libErrors.RequestError("Timed out establishing stream from host")
|
new lib.RequestError("Timed out establishing stream from host")
|
||||||
));
|
));
|
||||||
});
|
});
|
||||||
ready.catch(() => {});
|
ready.catch(() => {});
|
||||||
|
|
||||||
await this._controller.sendToHostByInstanceId(new libData.InstancePushSaveRequest(
|
await this._controller.sendToHostByInstanceId(new lib.InstancePushSaveRequest(
|
||||||
instanceId,
|
instanceId,
|
||||||
stream.id,
|
stream.id,
|
||||||
name,
|
name,
|
||||||
@@ -406,17 +399,17 @@ class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
async handleInstanceTransferSaveRequest(request) {
|
async handleInstanceTransferSaveRequest(request) {
|
||||||
if (request.sourceInstanceId === request.targetInstanceId) {
|
if (request.sourceInstanceId === request.targetInstanceId) {
|
||||||
throw new libErrors.RequestError("Source and target instance may not be the same");
|
throw new lib.RequestError("Source and target instance may not be the same");
|
||||||
}
|
}
|
||||||
let sourceInstance = this._controller.getRequestInstance(request.sourceInstanceId);
|
let sourceInstance = this._controller.getRequestInstance(request.sourceInstanceId);
|
||||||
let targetInstance = this._controller.getRequestInstance(request.targetInstanceId);
|
let targetInstance = this._controller.getRequestInstance(request.targetInstanceId);
|
||||||
let sourceHostId = sourceInstance.config.get("instance.assigned_host");
|
let sourceHostId = sourceInstance.config.get("instance.assigned_host");
|
||||||
let targetHostId = targetInstance.config.get("instance.assigned_host");
|
let targetHostId = targetInstance.config.get("instance.assigned_host");
|
||||||
if (sourceHostId === null) {
|
if (sourceHostId === null) {
|
||||||
throw new libErrors.RequestError("Source instance is not assigned a host");
|
throw new lib.RequestError("Source instance is not assigned a host");
|
||||||
}
|
}
|
||||||
if (targetHostId === null) {
|
if (targetHostId === null) {
|
||||||
throw new libErrors.RequestError("Target instance is not assigned a host");
|
throw new lib.RequestError("Target instance is not assigned a host");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Let host handle request if source and target is on the same host.
|
// Let host handle request if source and target is on the same host.
|
||||||
@@ -427,12 +420,12 @@ class ControlConnection extends BaseConnection {
|
|||||||
// Check connectivity
|
// Check connectivity
|
||||||
let sourceHostConnection = this._controller.wsServer.hostConnections.get(sourceHostId);
|
let sourceHostConnection = this._controller.wsServer.hostConnections.get(sourceHostId);
|
||||||
if (!sourceHostConnection || sourceHostConnection.closing) {
|
if (!sourceHostConnection || sourceHostConnection.closing) {
|
||||||
throw new libErrors.RequestError("Source host is not connected to the controller");
|
throw new lib.RequestError("Source host is not connected to the controller");
|
||||||
}
|
}
|
||||||
|
|
||||||
let targetHostConnection = this._controller.wsServer.hostConnections.get(targetHostId);
|
let targetHostConnection = this._controller.wsServer.hostConnections.get(targetHostId);
|
||||||
if (!targetHostConnection || targetHostConnection.closing) {
|
if (!targetHostConnection || targetHostConnection.closing) {
|
||||||
throw new libErrors.RequestError("Target host is not connected to the controller");
|
throw new lib.RequestError("Target host is not connected to the controller");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create stream to proxy from target to source
|
// Create stream to proxy from target to source
|
||||||
@@ -441,7 +434,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
if (stream.source) {
|
if (stream.source) {
|
||||||
stream.source.destroy();
|
stream.source.destroy();
|
||||||
}
|
}
|
||||||
stream.events.emit("error", new libErrors.RequestError("Timed out establishing transfer stream"));
|
stream.events.emit("error", new lib.RequestError("Timed out establishing transfer stream"));
|
||||||
});
|
});
|
||||||
|
|
||||||
// Ignore errors if not listening for them to avoid crash.
|
// Ignore errors if not listening for them to avoid crash.
|
||||||
@@ -452,7 +445,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
await Promise.all([
|
await Promise.all([
|
||||||
this._controller.sendTo(
|
this._controller.sendTo(
|
||||||
{ hostId: sourceHostId },
|
{ hostId: sourceHostId },
|
||||||
new libData.InstancePushSaveRequest(request.sourceInstanceId, stream.id, request.sourceName),
|
new lib.InstancePushSaveRequest(request.sourceInstanceId, stream.id, request.sourceName),
|
||||||
),
|
),
|
||||||
events.once(stream.events, "source"),
|
events.once(stream.events, "source"),
|
||||||
]);
|
]);
|
||||||
@@ -460,14 +453,14 @@ class ControlConnection extends BaseConnection {
|
|||||||
// Establish pull from target host to stream and wait for completion.
|
// Establish pull from target host to stream and wait for completion.
|
||||||
let storedName = await this._controller.sendTo(
|
let storedName = await this._controller.sendTo(
|
||||||
{ hostId: targetHostId },
|
{ hostId: targetHostId },
|
||||||
new libData.InstancePullSaveRequest(request.targetInstanceId, stream.id, request.targetName),
|
new lib.InstancePullSaveRequest(request.targetInstanceId, stream.id, request.targetName),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Delete source save if this is not a copy
|
// Delete source save if this is not a copy
|
||||||
if (!request.copy) {
|
if (!request.copy) {
|
||||||
await this._controller.sendTo(
|
await this._controller.sendTo(
|
||||||
{ hostId: sourceHostId },
|
{ hostId: sourceHostId },
|
||||||
new libData.InstanceDeleteSaveRequest(request.sourceInstanceId, request.sourceName),
|
new lib.InstanceDeleteSaveRequest(request.sourceInstanceId, request.sourceName),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -485,7 +478,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleModPackCreateRequest(request) {
|
async handleModPackCreateRequest(request) {
|
||||||
let modPack = request.modPack;
|
let modPack = request.modPack;
|
||||||
if (this._controller.modPacks.has(modPack.id)) {
|
if (this._controller.modPacks.has(modPack.id)) {
|
||||||
throw new libErrors.RequestError(`Mod pack with ID ${modPack.id} already exist`);
|
throw new lib.RequestError(`Mod pack with ID ${modPack.id} already exist`);
|
||||||
}
|
}
|
||||||
this._controller.modPacks.set(modPack.id, modPack);
|
this._controller.modPacks.set(modPack.id, modPack);
|
||||||
this._controller.modPackUpdated(modPack);
|
this._controller.modPackUpdated(modPack);
|
||||||
@@ -494,7 +487,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleModPackUpdateRequest(request) {
|
async handleModPackUpdateRequest(request) {
|
||||||
let modPack = request.modPack;
|
let modPack = request.modPack;
|
||||||
if (!this._controller.modPacks.has(modPack.id)) {
|
if (!this._controller.modPacks.has(modPack.id)) {
|
||||||
throw new libErrors.RequestError(`Mod pack with ID ${modPack.id} does not exist`);
|
throw new lib.RequestError(`Mod pack with ID ${modPack.id} does not exist`);
|
||||||
}
|
}
|
||||||
this._controller.modPacks.set(modPack.id, modPack);
|
this._controller.modPacks.set(modPack.id, modPack);
|
||||||
this._controller.modPackUpdated(modPack);
|
this._controller.modPackUpdated(modPack);
|
||||||
@@ -504,7 +497,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
let { id } = request;
|
let { id } = request;
|
||||||
let modPack = this._controller.modPacks.get(id);
|
let modPack = this._controller.modPacks.get(id);
|
||||||
if (!modPack) {
|
if (!modPack) {
|
||||||
throw new libErrors.RequestError(`Mod pack with ID ${id} does not exist`);
|
throw new lib.RequestError(`Mod pack with ID ${id} does not exist`);
|
||||||
}
|
}
|
||||||
modPack.isDeleted = true;
|
modPack.isDeleted = true;
|
||||||
this._controller.modPacks.delete(id);
|
this._controller.modPacks.delete(id);
|
||||||
@@ -516,7 +509,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.modPackSubscriptions.all
|
this.modPackSubscriptions.all
|
||||||
|| this.modPackSubscriptions.modPackIds.includes(modPack.id)
|
|| this.modPackSubscriptions.modPackIds.includes(modPack.id)
|
||||||
) {
|
) {
|
||||||
this.send(new libData.ModPackUpdateEvent(modPack));
|
this.send(new lib.ModPackUpdateEvent(modPack));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -525,7 +518,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
let filename = `${name}_${version}.zip`;
|
let filename = `${name}_${version}.zip`;
|
||||||
let mod = this._controller.mods.get(filename);
|
let mod = this._controller.mods.get(filename);
|
||||||
if (!mod) {
|
if (!mod) {
|
||||||
throw new libErrors.RequestError(`Mod ${filename} does not exist`);
|
throw new lib.RequestError(`Mod ${filename} does not exist`);
|
||||||
}
|
}
|
||||||
return mod;
|
return mod;
|
||||||
}
|
}
|
||||||
@@ -537,14 +530,14 @@ class ControlConnection extends BaseConnection {
|
|||||||
static termsMatchesMod(terms, mod) {
|
static termsMatchesMod(terms, mod) {
|
||||||
for (let term of terms) {
|
for (let term of terms) {
|
||||||
if (term.type === "word") {
|
if (term.type === "word") {
|
||||||
if (!libHelpers.wordMatches(term,
|
if (!lib.wordMatches(term,
|
||||||
mod.name, mod.version, mod.title, mod.author, mod.contact,
|
mod.name, mod.version, mod.title, mod.author, mod.contact,
|
||||||
mod.homepage, mod.description, mod.filename
|
mod.homepage, mod.description, mod.filename
|
||||||
)) {
|
)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} else if (term.type === "attribute") {
|
} else if (term.type === "attribute") {
|
||||||
if (!libHelpers.wordMatches(term.value, mod[term.name])) {
|
if (!lib.wordMatches(term.value, mod[term.name])) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -553,7 +546,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleModSearchRequest(request) {
|
async handleModSearchRequest(request) {
|
||||||
let query = libHelpers.parseSearchString(request.query, {
|
let query = lib.parseSearchString(request.query, {
|
||||||
name: "word",
|
name: "word",
|
||||||
// version
|
// version
|
||||||
title: "word",
|
title: "word",
|
||||||
@@ -601,7 +594,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
author: (a, b) => strcmp(a.versions[0].author, b.versions[0].author),
|
author: (a, b) => strcmp(a.versions[0].author, b.versions[0].author),
|
||||||
};
|
};
|
||||||
if (!Object.prototype.hasOwnProperty.call(sorters, sort)) {
|
if (!Object.prototype.hasOwnProperty.call(sorters, sort)) {
|
||||||
throw new libErrors.RequestError(`Invalid value for sort: ${sort}`);
|
throw new lib.RequestError(`Invalid value for sort: ${sort}`);
|
||||||
}
|
}
|
||||||
resultList.sort(sorters[sort]);
|
resultList.sort(sorters[sort]);
|
||||||
let order = request.sortOrder;
|
let order = request.sortOrder;
|
||||||
@@ -631,7 +624,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
let filename = `${name}_${version}.zip`;
|
let filename = `${name}_${version}.zip`;
|
||||||
let mod = this._controller.mods.get(filename);
|
let mod = this._controller.mods.get(filename);
|
||||||
if (!mod) {
|
if (!mod) {
|
||||||
throw new libErrors.RequestError(`Mod ${filename} does not exist`);
|
throw new lib.RequestError(`Mod ${filename} does not exist`);
|
||||||
}
|
}
|
||||||
let modPath = path.join(this._controller.config.get("controller.mods_directory"), mod.filename);
|
let modPath = path.join(this._controller.config.get("controller.mods_directory"), mod.filename);
|
||||||
|
|
||||||
@@ -658,7 +651,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.modSubscriptions.all
|
this.modSubscriptions.all
|
||||||
|| this.modSubscriptions.modNames.includes(mod.name)
|
|| this.modSubscriptions.modNames.includes(mod.name)
|
||||||
) {
|
) {
|
||||||
this.send(new libData.ModUpdateEvent(mod));
|
this.send(new lib.ModUpdateEvent(mod));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -666,7 +659,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
let { all, controller, hostIds, instanceIds } = this.logSubscriptions;
|
let { all, controller, hostIds, instanceIds } = this.logSubscriptions;
|
||||||
if (all || controller || hostIds.length || instanceIds.length) {
|
if (all || controller || hostIds.length || instanceIds.length) {
|
||||||
if (!this.logTransport) {
|
if (!this.logTransport) {
|
||||||
this.logTransport = new libLoggingUtils.LinkTransport({ link: this });
|
this.logTransport = new lib.LinkTransport({ link: this });
|
||||||
this._controller.clusterLogger.add(this.logTransport);
|
this._controller.clusterLogger.add(this.logTransport);
|
||||||
}
|
}
|
||||||
this.logTransport.filter = logFilter(this.logSubscriptions);
|
this.logTransport.filter = logFilter(this.logSubscriptions);
|
||||||
@@ -694,8 +687,8 @@ class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
async handlePermissionListRequest() {
|
async handlePermissionListRequest() {
|
||||||
let list = [];
|
let list = [];
|
||||||
for (let permission of libUsers.permissions.values()) {
|
for (let permission of lib.permissions.values()) {
|
||||||
list.push(new libData.RawPermission(
|
list.push(new lib.RawPermission(
|
||||||
permission.name,
|
permission.name,
|
||||||
permission.title,
|
permission.title,
|
||||||
permission.description,
|
permission.description,
|
||||||
@@ -707,7 +700,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleRoleListRequest() {
|
async handleRoleListRequest() {
|
||||||
let list = [];
|
let list = [];
|
||||||
for (let role of this._controller.userManager.roles.values()) {
|
for (let role of this._controller.userManager.roles.values()) {
|
||||||
list.push(new libData.RawRole(
|
list.push(new lib.RawRole(
|
||||||
role.id,
|
role.id,
|
||||||
role.name,
|
role.name,
|
||||||
role.description,
|
role.description,
|
||||||
@@ -722,7 +715,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
// Start at 5 to leave space for future default roles
|
// Start at 5 to leave space for future default roles
|
||||||
let id = Math.max(5, lastId+1);
|
let id = Math.max(5, lastId+1);
|
||||||
this._controller.userManager.roles.set(id, new libUsers.Role({ id, ...request }));
|
this._controller.userManager.roles.set(id, new lib.Role({ id, ...request }));
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -730,7 +723,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
let { id, name, description, permissions } = request;
|
let { id, name, description, permissions } = request;
|
||||||
let role = this._controller.userManager.roles.get(id);
|
let role = this._controller.userManager.roles.get(id);
|
||||||
if (!role) {
|
if (!role) {
|
||||||
throw new libErrors.RequestError(`Role with ID ${id} does not exist`);
|
throw new lib.RequestError(`Role with ID ${id} does not exist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
role.name = name;
|
role.name = name;
|
||||||
@@ -742,7 +735,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleRoleGrantDefaultPermissionsRequest(request) {
|
async handleRoleGrantDefaultPermissionsRequest(request) {
|
||||||
let role = this._controller.userManager.roles.get(request.id);
|
let role = this._controller.userManager.roles.get(request.id);
|
||||||
if (!role) {
|
if (!role) {
|
||||||
throw new libErrors.RequestError(`Role with ID ${request.id} does not exist`);
|
throw new lib.RequestError(`Role with ID ${request.id} does not exist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
role.grantDefaultPermissions();
|
role.grantDefaultPermissions();
|
||||||
@@ -753,7 +746,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
let id = request.id;
|
let id = request.id;
|
||||||
let role = this._controller.userManager.roles.get(id);
|
let role = this._controller.userManager.roles.get(id);
|
||||||
if (!role) {
|
if (!role) {
|
||||||
throw new libErrors.RequestError(`Role with ID ${id} does not exist`);
|
throw new lib.RequestError(`Role with ID ${id} does not exist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._controller.userManager.roles.delete(id);
|
this._controller.userManager.roles.delete(id);
|
||||||
@@ -767,10 +760,10 @@ class ControlConnection extends BaseConnection {
|
|||||||
let name = request.name;
|
let name = request.name;
|
||||||
let user = this._controller.userManager.users.get(name);
|
let user = this._controller.userManager.users.get(name);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new libErrors.RequestError(`User ${name} does not exist`);
|
throw new lib.RequestError(`User ${name} does not exist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new libData.RawUser(
|
return new lib.RawUser(
|
||||||
user.name,
|
user.name,
|
||||||
[...user.roles].map(role => role.id),
|
[...user.roles].map(role => role.id),
|
||||||
[...user.instances],
|
[...user.instances],
|
||||||
@@ -787,7 +780,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleUserListRequest() {
|
async handleUserListRequest() {
|
||||||
let list = [];
|
let list = [];
|
||||||
for (let user of this._controller.userManager.users.values()) {
|
for (let user of this._controller.userManager.users.values()) {
|
||||||
list.push(new libData.RawUser(
|
list.push(new lib.RawUser(
|
||||||
user.name,
|
user.name,
|
||||||
[...user.roles].map(role => role.id),
|
[...user.roles].map(role => role.id),
|
||||||
[...user.instances],
|
[...user.instances],
|
||||||
@@ -812,8 +805,8 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.userSubscriptions.all
|
this.userSubscriptions.all
|
||||||
|| this.userSubscriptions.names.includes(user.name)
|
|| this.userSubscriptions.names.includes(user.name)
|
||||||
) {
|
) {
|
||||||
this.send(new libData.UserUpdateEvent(
|
this.send(new lib.UserUpdateEvent(
|
||||||
new libData.RawUser(
|
new lib.RawUser(
|
||||||
user.name,
|
user.name,
|
||||||
[...user.roles].map(role => role.id),
|
[...user.roles].map(role => role.id),
|
||||||
[...user.instances],
|
[...user.instances],
|
||||||
@@ -837,7 +830,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleUserRevokeTokenRequest(request) {
|
async handleUserRevokeTokenRequest(request) {
|
||||||
let user = this._controller.userManager.users.get(request.name);
|
let user = this._controller.userManager.users.get(request.name);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new libErrors.RequestError(`User '${request.name}' does not exist`);
|
throw new lib.RequestError(`User '${request.name}' does not exist`);
|
||||||
}
|
}
|
||||||
if (user.name !== this.user.name) {
|
if (user.name !== this.user.name) {
|
||||||
this.user.checkPermission("core.user.revoke_other_token");
|
this.user.checkPermission("core.user.revoke_other_token");
|
||||||
@@ -855,14 +848,14 @@ class ControlConnection extends BaseConnection {
|
|||||||
async handleUserUpdateRolesRequest(request) {
|
async handleUserUpdateRolesRequest(request) {
|
||||||
let user = this._controller.userManager.users.get(request.name);
|
let user = this._controller.userManager.users.get(request.name);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new libErrors.RequestError(`User '${request.name}' does not exist`);
|
throw new lib.RequestError(`User '${request.name}' does not exist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
let resolvedRoles = new Set();
|
let resolvedRoles = new Set();
|
||||||
for (let roleId of request.roles) {
|
for (let roleId of request.roles) {
|
||||||
let role = this._controller.userManager.roles.get(roleId);
|
let role = this._controller.userManager.roles.get(roleId);
|
||||||
if (!role) {
|
if (!role) {
|
||||||
throw new libErrors.RequestError(`Role with ID ${roleId} does not exist`);
|
throw new lib.RequestError(`Role with ID ${roleId} does not exist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
resolvedRoles.add(role);
|
resolvedRoles.add(role);
|
||||||
@@ -881,13 +874,13 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.user.checkPermission("core.user.create");
|
this.user.checkPermission("core.user.create");
|
||||||
user = this._controller.userManager.createUser(name);
|
user = this._controller.userManager.createUser(name);
|
||||||
} else {
|
} else {
|
||||||
throw new libErrors.RequestError(`User '${name}' does not exist`);
|
throw new lib.RequestError(`User '${name}' does not exist`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
user.isAdmin = admin;
|
user.isAdmin = admin;
|
||||||
this._controller.userUpdated(user);
|
this._controller.userUpdated(user);
|
||||||
this._controller.sendTo("allInstances", new libData.InstanceAdminlistUpdateEvent(name, admin));
|
this._controller.sendTo("allInstances", new lib.InstanceAdminlistUpdateEvent(name, admin));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleUserSetBannedRequest(request) {
|
async handleUserSetBannedRequest(request) {
|
||||||
@@ -898,14 +891,14 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.user.checkPermission("core.user.create");
|
this.user.checkPermission("core.user.create");
|
||||||
user = this._controller.userManager.createUser(name);
|
user = this._controller.userManager.createUser(name);
|
||||||
} else {
|
} else {
|
||||||
throw new libErrors.RequestError(`User '${name}' does not exist`);
|
throw new lib.RequestError(`User '${name}' does not exist`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
user.isBanned = banned;
|
user.isBanned = banned;
|
||||||
user.banReason = reason;
|
user.banReason = reason;
|
||||||
this._controller.userUpdated(user);
|
this._controller.userUpdated(user);
|
||||||
this._controller.sendTo("allInstances", new libData.InstanceBanlistUpdateEvent(name, banned, reason));
|
this._controller.sendTo("allInstances", new lib.InstanceBanlistUpdateEvent(name, banned, reason));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleUserSetWhitelistedRequest(request) {
|
async handleUserSetWhitelistedRequest(request) {
|
||||||
@@ -916,20 +909,20 @@ class ControlConnection extends BaseConnection {
|
|||||||
this.user.checkPermission("core.user.create");
|
this.user.checkPermission("core.user.create");
|
||||||
user = this._controller.userManager.createUser(name);
|
user = this._controller.userManager.createUser(name);
|
||||||
} else {
|
} else {
|
||||||
throw new libErrors.RequestError(`User '${name}' does not exist`);
|
throw new lib.RequestError(`User '${name}' does not exist`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
user.isWhitelisted = whitelisted;
|
user.isWhitelisted = whitelisted;
|
||||||
this._controller.userUpdated(user);
|
this._controller.userUpdated(user);
|
||||||
this._controller.sendTo("allInstances", new libData.InstanceWhitelistUpdateEvent(name, whitelisted));
|
this._controller.sendTo("allInstances", new lib.InstanceWhitelistUpdateEvent(name, whitelisted));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleUserDeleteRequest(request) {
|
async handleUserDeleteRequest(request) {
|
||||||
let name = request.name;
|
let name = request.name;
|
||||||
let user = this._controller.userManager.users.get(name);
|
let user = this._controller.userManager.users.get(name);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new libErrors.RequestError(`User '${name}' does not exist`);
|
throw new lib.RequestError(`User '${name}' does not exist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
user.isDeleted = true;
|
user.isDeleted = true;
|
||||||
@@ -937,20 +930,20 @@ class ControlConnection extends BaseConnection {
|
|||||||
this._controller.userUpdated(user);
|
this._controller.userUpdated(user);
|
||||||
|
|
||||||
if (user.is_admin) {
|
if (user.is_admin) {
|
||||||
this._controller.sendTo("allInstances", new libData.InstanceAdminlistUpdateEvent(name, false));
|
this._controller.sendTo("allInstances", new lib.InstanceAdminlistUpdateEvent(name, false));
|
||||||
}
|
}
|
||||||
if (user.is_whitelisted) {
|
if (user.is_whitelisted) {
|
||||||
this._controller.sendTo("allInstances", new libData.InstanceWhitelistUpdateEvent(name, false));
|
this._controller.sendTo("allInstances", new lib.InstanceWhitelistUpdateEvent(name, false));
|
||||||
}
|
}
|
||||||
if (user.is_banned) {
|
if (user.is_banned) {
|
||||||
this._controller.sendTo("allInstances", new libData.InstanceBanlistUpdateEvent(name, false, ""));
|
this._controller.sendTo("allInstances", new lib.InstanceBanlistUpdateEvent(name, false, ""));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleDebugDumpWsRequest(request) {
|
async handleDebugDumpWsRequest(request) {
|
||||||
this.ws_dumper = data => {
|
this.ws_dumper = data => {
|
||||||
if (this.connector.connected) {
|
if (this.connector.connected) {
|
||||||
this.send(new libData.DebugWsMessageEvent(data.direction, data.content));
|
this.send(new lib.DebugWsMessageEvent(data.direction, data.content));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
this.connector._socket.clusterio_ignore_dump = true;
|
this.connector._socket.clusterio_ignore_dump = true;
|
||||||
|
|||||||
@@ -9,16 +9,8 @@ const jwt = require("jsonwebtoken");
|
|||||||
const path = require("path");
|
const path = require("path");
|
||||||
const stream = require("stream");
|
const stream = require("stream");
|
||||||
|
|
||||||
const libConfig = require("@clusterio/lib/config");
|
const lib = require("@clusterio/lib");
|
||||||
const libData = require("@clusterio/lib/data");
|
const { logger } = lib;
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
const libFileOps = require("@clusterio/lib/file_ops");
|
|
||||||
const libLink = require("@clusterio/lib/link");
|
|
||||||
const libLoggingUtils = require("@clusterio/lib/logging_utils");
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const libPluginLoader = require("@clusterio/lib/plugin_loader");
|
|
||||||
const libPrometheus = require("@clusterio/lib/prometheus");
|
|
||||||
const { logger } = require("@clusterio/lib/logging");
|
|
||||||
|
|
||||||
const HttpCloser = require("./HttpCloser");
|
const HttpCloser = require("./HttpCloser");
|
||||||
const InstanceInfo = require("./InstanceInfo");
|
const InstanceInfo = require("./InstanceInfo");
|
||||||
@@ -28,13 +20,13 @@ const UserManager = require("./UserManager");
|
|||||||
const WsServer = require("./WsServer");
|
const WsServer = require("./WsServer");
|
||||||
|
|
||||||
|
|
||||||
const endpointDurationSummary = new libPrometheus.Summary(
|
const endpointDurationSummary = new lib.Summary(
|
||||||
"clusterio_controller_http_endpoint_duration_seconds",
|
"clusterio_controller_http_endpoint_duration_seconds",
|
||||||
"Time it took to respond to a an HTTP request",
|
"Time it took to respond to a an HTTP request",
|
||||||
{ labels: ["route"] }
|
{ labels: ["route"] }
|
||||||
);
|
);
|
||||||
|
|
||||||
const logSizeGauge = new libPrometheus.Gauge(
|
const logSizeGauge = new lib.Gauge(
|
||||||
"clusterio_controller_log_bytes",
|
"clusterio_controller_log_bytes",
|
||||||
"Size of all log files currently stored on the controller."
|
"Size of all log files currently stored on the controller."
|
||||||
);
|
);
|
||||||
@@ -54,7 +46,7 @@ class Controller {
|
|||||||
this.configPath = configPath;
|
this.configPath = configPath;
|
||||||
/**
|
/**
|
||||||
* Controller config.
|
* Controller config.
|
||||||
* @type {module:lib/config.ControllerConfig}
|
* @type {module:lib.ControllerConfig}
|
||||||
*/
|
*/
|
||||||
this.config = config;
|
this.config = config;
|
||||||
|
|
||||||
@@ -76,13 +68,13 @@ class Controller {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Mapping of mod pack id to mod pack
|
* Mapping of mod pack id to mod pack
|
||||||
* @type {Map<number, module:lib/data.ModPack>}
|
* @type {Map<number, module:lib.ModPack>}
|
||||||
*/
|
*/
|
||||||
this.modPacks = null;
|
this.modPacks = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mapping of mod names to mod infos
|
* Mapping of mod names to mod infos
|
||||||
* @type {Map<string, module:lib/data.ModInfo>}
|
* @type {Map<string, module:lib.ModInfo>}
|
||||||
*/
|
*/
|
||||||
this.mods = null;
|
this.mods = null;
|
||||||
|
|
||||||
@@ -98,7 +90,7 @@ class Controller {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Mapping of plugin name to loaded plugin
|
* Mapping of plugin name to loaded plugin
|
||||||
* @type {Map<string, module:lib/plugin.BaseControllerPlugin>}
|
* @type {Map<string, module:lib.BaseControllerPlugin>}
|
||||||
*/
|
*/
|
||||||
this.plugins = new Map();
|
this.plugins = new Map();
|
||||||
|
|
||||||
@@ -150,15 +142,15 @@ class Controller {
|
|||||||
*/
|
*/
|
||||||
async logSize() {
|
async logSize() {
|
||||||
return (await Promise.all([
|
return (await Promise.all([
|
||||||
libFileOps.directorySize(path.join(this.logDirectory, "cluster")),
|
lib.directorySize(path.join(this.logDirectory, "cluster")),
|
||||||
libFileOps.directorySize(path.join(this.logDirectory, "controller")),
|
lib.directorySize(path.join(this.logDirectory, "controller")),
|
||||||
libFileOps.directorySize(path.join(this.logDirectory, "host")),
|
lib.directorySize(path.join(this.logDirectory, "host")),
|
||||||
])).reduce((a, v) => a + v, 0);
|
])).reduce((a, v) => a + v, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
async _startInternal(args) {
|
async _startInternal(args) {
|
||||||
this.logDirectory = args.logDirectory;
|
this.logDirectory = args.logDirectory;
|
||||||
this.clusterLogIndex = await libLoggingUtils.LogIndex.load(path.join(this.logDirectory, "cluster"));
|
this.clusterLogIndex = await lib.LogIndex.load(path.join(this.logDirectory, "cluster"));
|
||||||
this.clusterLogBuildInterval = setInterval(() => {
|
this.clusterLogBuildInterval = setInterval(() => {
|
||||||
this.clusterLogIndex.buildIndex().catch(
|
this.clusterLogIndex.buildIndex().catch(
|
||||||
err => logger.error(`Error building cluster log index:\n${err.stack}`)
|
err => logger.error(`Error building cluster log index:\n${err.stack}`)
|
||||||
@@ -181,7 +173,7 @@ class Controller {
|
|||||||
for (let name of args.devPlugin) {
|
for (let name of args.devPlugin) {
|
||||||
let info = this.pluginInfos.find(i => i.name === name);
|
let info = this.pluginInfos.find(i => i.name === name);
|
||||||
if (!info) {
|
if (!info) {
|
||||||
throw new libErrors.StartupError(`No plugin named ${name}`);
|
throw new lib.StartupError(`No plugin named ${name}`);
|
||||||
}
|
}
|
||||||
let config = require(path.posix.join(info.requirePath, "webpack.config"))({});
|
let config = require(path.posix.join(info.requirePath, "webpack.config"))({});
|
||||||
devPlugins.set(name, webpackConfigs.length);
|
devPlugins.set(name, webpackConfigs.length);
|
||||||
@@ -210,7 +202,7 @@ class Controller {
|
|||||||
this.mods = await Controller.loadModInfos(modsDirectory);
|
this.mods = await Controller.loadModInfos(modsDirectory);
|
||||||
|
|
||||||
this.config.on("fieldChanged", (group, field, prev) => {
|
this.config.on("fieldChanged", (group, field, prev) => {
|
||||||
libPlugin.invokeHook(this.plugins, "onControllerConfigFieldChanged", group, field, prev);
|
lib.invokeHook(this.plugins, "onControllerConfigFieldChanged", group, field, prev);
|
||||||
});
|
});
|
||||||
for (let instance of this.instances.values()) {
|
for (let instance of this.instances.values()) {
|
||||||
this.addInstanceHooks(instance);
|
this.addInstanceHooks(instance);
|
||||||
@@ -230,7 +222,7 @@ class Controller {
|
|||||||
let tls_key = this.config.get("controller.tls_private_key");
|
let tls_key = this.config.get("controller.tls_private_key");
|
||||||
|
|
||||||
if (httpsPort && (!tls_cert || !tls_key)) {
|
if (httpsPort && (!tls_cert || !tls_key)) {
|
||||||
throw new libErrors.StartupError(
|
throw new lib.StartupError(
|
||||||
"tls_certificate and tls_private_key must be configure in order to use https_port"
|
"tls_certificate and tls_private_key must be configure in order to use https_port"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -265,7 +257,7 @@ class Controller {
|
|||||||
privateKey = await fs.readFile(tls_key);
|
privateKey = await fs.readFile(tls_key);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new libErrors.StartupError(
|
throw new lib.StartupError(
|
||||||
`Error loading ssl certificate: ${err.message}`
|
`Error loading ssl certificate: ${err.message}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -313,7 +305,7 @@ class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
logger.info("Saving config");
|
logger.info("Saving config");
|
||||||
await libFileOps.safeOutputFile(this.configPath, JSON.stringify(this.config.serialize(), null, 4));
|
await lib.safeOutputFile(this.configPath, JSON.stringify(this.config.serialize(), null, 4));
|
||||||
|
|
||||||
if (this.devMiddleware) {
|
if (this.devMiddleware) {
|
||||||
await new Promise((resolve, reject) => { this.devMiddleware.close(resolve); });
|
await new Promise((resolve, reject) => { this.devMiddleware.close(resolve); });
|
||||||
@@ -336,7 +328,7 @@ class Controller {
|
|||||||
await this.userManager.save(path.join(databaseDirectory, "users.json"));
|
await this.userManager.save(path.join(databaseDirectory, "users.json"));
|
||||||
}
|
}
|
||||||
|
|
||||||
await libPlugin.invokeHook(this.plugins, "onShutdown");
|
await lib.invokeHook(this.plugins, "onShutdown");
|
||||||
|
|
||||||
if (this.wsServer) {
|
if (this.wsServer) {
|
||||||
await this.wsServer.stop();
|
await this.wsServer.stop();
|
||||||
@@ -373,7 +365,7 @@ class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async saveHosts(filePath, hosts) {
|
static async saveHosts(filePath, hosts) {
|
||||||
await libFileOps.safeOutputFile(filePath, JSON.stringify([...hosts.entries()], null, 4));
|
await lib.safeOutputFile(filePath, JSON.stringify([...hosts.entries()], null, 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
static async loadInstances(filePath) {
|
static async loadInstances(filePath) {
|
||||||
@@ -383,7 +375,7 @@ class Controller {
|
|||||||
try {
|
try {
|
||||||
let serialized = JSON.parse(await fs.readFile(filePath));
|
let serialized = JSON.parse(await fs.readFile(filePath));
|
||||||
for (let serializedConfig of serialized) {
|
for (let serializedConfig of serialized) {
|
||||||
let instanceConfig = new libConfig.InstanceConfig("controller");
|
let instanceConfig = new lib.InstanceConfig("controller");
|
||||||
await instanceConfig.load(serializedConfig);
|
await instanceConfig.load(serializedConfig);
|
||||||
let status = instanceConfig.get("instance.assigned_host") === null ? "unassigned" : "unknown";
|
let status = instanceConfig.get("instance.assigned_host") === null ? "unassigned" : "unknown";
|
||||||
let instance = new InstanceInfo({ config: instanceConfig, status });
|
let instance = new InstanceInfo({ config: instanceConfig, status });
|
||||||
@@ -405,7 +397,7 @@ class Controller {
|
|||||||
serialized.push(instance.config.serialize());
|
serialized.push(instance.config.serialize());
|
||||||
}
|
}
|
||||||
|
|
||||||
await libFileOps.safeOutputFile(filePath, JSON.stringify(serialized, null, 4));
|
await lib.safeOutputFile(filePath, JSON.stringify(serialized, null, 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
static async loadModPacks(filePath) {
|
static async loadModPacks(filePath) {
|
||||||
@@ -418,11 +410,11 @@ class Controller {
|
|||||||
}
|
}
|
||||||
return new Map();
|
return new Map();
|
||||||
}
|
}
|
||||||
return new Map(json.map(e => [e.id, libData.ModPack.fromJSON(e)]));
|
return new Map(json.map(e => [e.id, lib.ModPack.fromJSON(e)]));
|
||||||
}
|
}
|
||||||
|
|
||||||
static async saveModPacks(filePath, modPacks) {
|
static async saveModPacks(filePath, modPacks) {
|
||||||
await libFileOps.safeOutputFile(filePath, JSON.stringify([...modPacks.values()], null, 4));
|
await lib.safeOutputFile(filePath, JSON.stringify([...modPacks.values()], null, 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
static async loadModInfos(modsDirectory) {
|
static async loadModInfos(modsDirectory) {
|
||||||
@@ -440,7 +432,7 @@ class Controller {
|
|||||||
logger.info(`Loading info for Mod ${entry.name}`);
|
logger.info(`Loading info for Mod ${entry.name}`);
|
||||||
let modInfo;
|
let modInfo;
|
||||||
try {
|
try {
|
||||||
modInfo = await libData.ModInfo.fromModFile(path.join(modsDirectory, entry.name));
|
modInfo = await lib.ModInfo.fromModFile(path.join(modsDirectory, entry.name));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(`Error loading mod ${entry.name}: ${err.message}`);
|
logger.error(`Error loading mod ${entry.name}: ${err.message}`);
|
||||||
continue;
|
continue;
|
||||||
@@ -488,13 +480,13 @@ class Controller {
|
|||||||
/**
|
/**
|
||||||
* Query controller log
|
* Query controller log
|
||||||
*
|
*
|
||||||
* @param {module:lib/logging_utils~QueryLogFilter} filter -
|
* @param {module:lib~QueryLogFilter} filter -
|
||||||
* Filter to limit entries with. Note that only the controller log can
|
* Filter to limit entries with. Note that only the controller log can
|
||||||
* be queried from this function.
|
* be queried from this function.
|
||||||
* @returns {Promise<Array<Object>>} log entries matching the filter
|
* @returns {Promise<Array<Object>>} log entries matching the filter
|
||||||
*/
|
*/
|
||||||
async queryControllerLog(filter) {
|
async queryControllerLog(filter) {
|
||||||
return await libLoggingUtils.queryLog(
|
return await lib.queryLog(
|
||||||
path.join(this.logDirectory, "controller"), filter,
|
path.join(this.logDirectory, "controller"), filter,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -502,12 +494,12 @@ class Controller {
|
|||||||
/**
|
/**
|
||||||
* Query cluster log
|
* Query cluster log
|
||||||
*
|
*
|
||||||
* @param {module:lib/logging_utils~QueryLogFilter} filter -
|
* @param {module:lib~QueryLogFilter} filter -
|
||||||
* Filter to limit entries with.
|
* Filter to limit entries with.
|
||||||
* @returns {Promise<Array<Object>>} log entries matching the filter
|
* @returns {Promise<Array<Object>>} log entries matching the filter
|
||||||
*/
|
*/
|
||||||
async queryClusterLog(filter) {
|
async queryClusterLog(filter) {
|
||||||
return await libLoggingUtils.queryLog(
|
return await lib.queryLog(
|
||||||
path.join(this.logDirectory, "cluster"), filter, this.clusterLogIndex,
|
path.join(this.logDirectory, "cluster"), filter, this.clusterLogIndex,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -564,7 +556,7 @@ class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
hostUpdated(host) {
|
hostUpdated(host) {
|
||||||
let update = new libData.HostDetails(
|
let update = new lib.HostDetails(
|
||||||
host.agent,
|
host.agent,
|
||||||
host.version,
|
host.version,
|
||||||
host.name,
|
host.name,
|
||||||
@@ -587,12 +579,12 @@ class Controller {
|
|||||||
*
|
*
|
||||||
* @param {number} instanceId - ID of instance to get.
|
* @param {number} instanceId - ID of instance to get.
|
||||||
* @returns {object} instance
|
* @returns {object} instance
|
||||||
* @throws {module:lib/errors.RequestError} if the instance does not exist.
|
* @throws {module:lib.RequestError} if the instance does not exist.
|
||||||
*/
|
*/
|
||||||
getRequestInstance(instanceId) {
|
getRequestInstance(instanceId) {
|
||||||
let instance = this.instances.get(instanceId);
|
let instance = this.instances.get(instanceId);
|
||||||
if (!instance) {
|
if (!instance) {
|
||||||
throw new libErrors.RequestError(`Instance with ID ${instanceId} does not exist`);
|
throw new lib.RequestError(`Instance with ID ${instanceId} does not exist`);
|
||||||
}
|
}
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
@@ -604,20 +596,20 @@ class Controller {
|
|||||||
* creates an instance using that config in the cluster.
|
* creates an instance using that config in the cluster.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* let instanceConfig = new libConfig.InstanceConfig("controller");
|
* let instanceConfig = new lib.InstanceConfig("controller");
|
||||||
* await instanceConfig.init();
|
* 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);
|
||||||
*
|
*
|
||||||
* @param {module:lib/config.InstanceConfig} instanceConfig -
|
* @param {module:lib.InstanceConfig} instanceConfig -
|
||||||
* Config to base newly created instance on.
|
* Config to base newly created instance on.
|
||||||
* @returns {module:controller/src/InstanceInfo} The created instance
|
* @returns {module:controller/src/InstanceInfo} The created instance
|
||||||
*/
|
*/
|
||||||
async instanceCreate(instanceConfig) {
|
async instanceCreate(instanceConfig) {
|
||||||
let instanceId = instanceConfig.get("instance.id");
|
let instanceId = instanceConfig.get("instance.id");
|
||||||
if (this.instances.has(instanceId)) {
|
if (this.instances.has(instanceId)) {
|
||||||
throw new libErrors.RequestError(`Instance with ID ${instanceId} already exists`);
|
throw new lib.RequestError(`Instance with ID ${instanceId} already exists`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add common settings for the Factorio server
|
// Add common settings for the Factorio server
|
||||||
@@ -648,7 +640,7 @@ class Controller {
|
|||||||
|
|
||||||
let instance = new InstanceInfo({ config: instanceConfig, status: "unassigned" });
|
let instance = new InstanceInfo({ config: instanceConfig, status: "unassigned" });
|
||||||
this.instances.set(instanceId, instance);
|
this.instances.set(instanceId, instance);
|
||||||
await libPlugin.invokeHook(this.plugins, "onInstanceStatusChanged", instance, null);
|
await lib.invokeHook(this.plugins, "onInstanceStatusChanged", instance, null);
|
||||||
this.addInstanceHooks(instance);
|
this.addInstanceHooks(instance);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -678,7 +670,7 @@ class Controller {
|
|||||||
// target host be connected to the controller while doing the
|
// target host be connected to the controller while doing the
|
||||||
// assignment, but it is IMHO a better user experience if this
|
// assignment, but it is IMHO a better user experience if this
|
||||||
// is the case.
|
// is the case.
|
||||||
throw new libErrors.RequestError("Target host is not connected to the controller");
|
throw new lib.RequestError("Target host is not connected to the controller");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -687,7 +679,7 @@ class Controller {
|
|||||||
if (currentAssignedHost !== null && hostId !== currentAssignedHost) {
|
if (currentAssignedHost !== null && hostId !== currentAssignedHost) {
|
||||||
let oldHostConnection = this.wsServer.hostConnections.get(currentAssignedHost);
|
let oldHostConnection = this.wsServer.hostConnections.get(currentAssignedHost);
|
||||||
if (oldHostConnection && !oldHostConnection.connector.closing) {
|
if (oldHostConnection && !oldHostConnection.connector.closing) {
|
||||||
await oldHostConnection.send(new libData.InstanceUnassignInternalRequest(instanceId));
|
await oldHostConnection.send(new lib.InstanceUnassignInternalRequest(instanceId));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -695,7 +687,7 @@ class Controller {
|
|||||||
instance.config.set("instance.assigned_host", hostId);
|
instance.config.set("instance.assigned_host", hostId);
|
||||||
if (hostId !== null) {
|
if (hostId !== null) {
|
||||||
await newHostConnection.send(
|
await newHostConnection.send(
|
||||||
new libData.InstanceAssignInternalRequest(instanceId, instance.config.serialize("host"))
|
new lib.InstanceAssignInternalRequest(instanceId, instance.config.serialize("host"))
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
instance.status = "unassigned";
|
instance.status = "unassigned";
|
||||||
@@ -715,14 +707,14 @@ class Controller {
|
|||||||
let instance = this.getRequestInstance(instanceId);
|
let instance = this.getRequestInstance(instanceId);
|
||||||
let hostId = instance.config.get("instance.assigned_host");
|
let hostId = instance.config.get("instance.assigned_host");
|
||||||
if (hostId !== null) {
|
if (hostId !== null) {
|
||||||
await this.sendTo({ hostId }, new libData.InstanceDeleteInternalRequest(instanceId));
|
await this.sendTo({ hostId }, new lib.InstanceDeleteInternalRequest(instanceId));
|
||||||
}
|
}
|
||||||
this.instances.delete(instanceId);
|
this.instances.delete(instanceId);
|
||||||
|
|
||||||
let prev = instance.status;
|
let prev = instance.status;
|
||||||
instance.status = "deleted";
|
instance.status = "deleted";
|
||||||
this.instanceUpdated(instance);
|
this.instanceUpdated(instance);
|
||||||
await libPlugin.invokeHook(this.plugins, "onInstanceStatusChanged", instance, prev);
|
await lib.invokeHook(this.plugins, "onInstanceStatusChanged", instance, prev);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -740,7 +732,7 @@ 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 libData.InstanceAssignInternalRequest(instance.id, instance.config.serialize("host"))
|
new lib.InstanceAssignInternalRequest(instance.id, instance.config.serialize("host"))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -752,7 +744,7 @@ class Controller {
|
|||||||
this.instanceUpdated(instance);
|
this.instanceUpdated(instance);
|
||||||
}
|
}
|
||||||
|
|
||||||
libPlugin.invokeHook(this.plugins, "onInstanceConfigFieldChanged", instance, group, field, prev);
|
lib.invokeHook(this.plugins, "onInstanceConfigFieldChanged", instance, group, field, prev);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.instanceUpdated(instance);
|
this.instanceUpdated(instance);
|
||||||
@@ -786,7 +778,7 @@ class Controller {
|
|||||||
controlConnection.modPackUpdated(modPack);
|
controlConnection.modPackUpdated(modPack);
|
||||||
}
|
}
|
||||||
|
|
||||||
libPlugin.invokeHook(this.plugins, "onModPackUpdated", modPack);
|
lib.invokeHook(this.plugins, "onModPackUpdated", modPack);
|
||||||
}
|
}
|
||||||
|
|
||||||
modUpdated(mod) {
|
modUpdated(mod) {
|
||||||
@@ -798,7 +790,7 @@ class Controller {
|
|||||||
controlConnection.modUpdated(mod);
|
controlConnection.modUpdated(mod);
|
||||||
}
|
}
|
||||||
|
|
||||||
libPlugin.invokeHook(this.plugins, "onModUpdated", mod);
|
lib.invokeHook(this.plugins, "onModUpdated", mod);
|
||||||
}
|
}
|
||||||
|
|
||||||
userUpdated(user) {
|
userUpdated(user) {
|
||||||
@@ -814,13 +806,13 @@ class Controller {
|
|||||||
/**
|
/**
|
||||||
* Notify connected control clients under the given user that the
|
* Notify connected control clients under the given user that the
|
||||||
* permissions for this user may have changed.
|
* permissions for this user may have changed.
|
||||||
* @param {module:lib/users.User} user - User permisions updated for.
|
* @param {module:lib.User} user - User permisions updated for.
|
||||||
*/
|
*/
|
||||||
userPermissionsUpdated(user) {
|
userPermissionsUpdated(user) {
|
||||||
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
||||||
if (controlConnection.user === user) {
|
if (controlConnection.user === user) {
|
||||||
controlConnection.send(
|
controlConnection.send(
|
||||||
new libData.AccountUpdateEvent([...user.roles].map(r => ({
|
new lib.AccountUpdateEvent([...user.roles].map(r => ({
|
||||||
name: r.name,
|
name: r.name,
|
||||||
id: r.id,
|
id: r.id,
|
||||||
permissions: [...r.permissions],
|
permissions: [...r.permissions],
|
||||||
@@ -833,13 +825,13 @@ class Controller {
|
|||||||
/**
|
/**
|
||||||
* Notify connected control clients with the given role that the
|
* Notify connected control clients with the given role that the
|
||||||
* permissions may have changed.
|
* permissions may have changed.
|
||||||
* @param {module:lib/users.Role} role - Role permisions updated for.
|
* @param {module:lib.Role} role - Role permisions updated for.
|
||||||
*/
|
*/
|
||||||
rolePermissionsUpdated(role) {
|
rolePermissionsUpdated(role) {
|
||||||
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
||||||
if (controlConnection.user.roles.has(role)) {
|
if (controlConnection.user.roles.has(role)) {
|
||||||
controlConnection.send(
|
controlConnection.send(
|
||||||
new libData.AccountUpdateEvent(
|
new lib.AccountUpdateEvent(
|
||||||
[...controlConnection.user.roles].map(r => ({
|
[...controlConnection.user.roles].map(r => ({
|
||||||
name: r.name,
|
name: r.name,
|
||||||
id: r.id,
|
id: r.id,
|
||||||
@@ -864,10 +856,10 @@ class Controller {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let ControllerPluginClass = libPlugin.BaseControllerPlugin;
|
let ControllerPluginClass = lib.BaseControllerPlugin;
|
||||||
try {
|
try {
|
||||||
if (pluginInfo.controllerEntrypoint) {
|
if (pluginInfo.controllerEntrypoint) {
|
||||||
ControllerPluginClass = await libPluginLoader.loadControllerPluginClass(pluginInfo);
|
ControllerPluginClass = await lib.loadControllerPluginClass(pluginInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
let controllerPlugin = new ControllerPluginClass(pluginInfo, this, metrics, logger);
|
let controllerPlugin = new ControllerPluginClass(pluginInfo, this, metrics, logger);
|
||||||
@@ -875,7 +867,7 @@ class Controller {
|
|||||||
this.plugins.set(pluginInfo.name, controllerPlugin);
|
this.plugins.set(pluginInfo.name, controllerPlugin);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new libErrors.PluginError(pluginInfo.name, err);
|
throw new lib.PluginError(pluginInfo.name, err);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(`Loaded plugin ${pluginInfo.name}`);
|
logger.info(`Loaded plugin ${pluginInfo.name}`);
|
||||||
@@ -899,7 +891,7 @@ class Controller {
|
|||||||
});
|
});
|
||||||
|
|
||||||
function wrapError(err) {
|
function wrapError(err) {
|
||||||
reject(new libErrors.StartupError(
|
reject(new lib.StartupError(
|
||||||
`Server listening failed: ${err.message}`
|
`Server listening failed: ${err.message}`
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -982,7 +974,7 @@ class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleRequest(Request, handler) {
|
handleRequest(Request, handler) {
|
||||||
if (!libLink.Link._requestsByClass.has(Request)) {
|
if (!lib.Link._requestsByClass.has(Request)) {
|
||||||
throw new Error(`Unregistered Request class ${Request.name}`);
|
throw new Error(`Unregistered Request class ${Request.name}`);
|
||||||
}
|
}
|
||||||
if (this._registeredRequests.has(Request)) {
|
if (this._registeredRequests.has(Request)) {
|
||||||
@@ -992,7 +984,7 @@ class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fallbackRequest(Request, handler) {
|
fallbackRequest(Request, handler) {
|
||||||
if (!libLink.Link._requestsByClass.has(Request)) {
|
if (!lib.Link._requestsByClass.has(Request)) {
|
||||||
throw new Error(`Unregistered Request class ${Request.name}`);
|
throw new Error(`Unregistered Request class ${Request.name}`);
|
||||||
}
|
}
|
||||||
if (this._fallbackedRequests.has(Request)) {
|
if (this._fallbackedRequests.has(Request)) {
|
||||||
@@ -1002,7 +994,7 @@ class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleEvent(Event, handler) {
|
handleEvent(Event, handler) {
|
||||||
if (!libLink.Link._eventsByClass.has(Event)) {
|
if (!lib.Link._eventsByClass.has(Event)) {
|
||||||
throw new Error(`Unregistered Event class ${Event.name}`);
|
throw new Error(`Unregistered Event class ${Event.name}`);
|
||||||
}
|
}
|
||||||
if (this._registeredEvents.has(Event)) {
|
if (this._registeredEvents.has(Event)) {
|
||||||
@@ -1012,7 +1004,7 @@ class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
snoopEvent(Event, handler) {
|
snoopEvent(Event, handler) {
|
||||||
if (!libLink.Link._eventsByClass.has(Event)) {
|
if (!lib.Link._eventsByClass.has(Event)) {
|
||||||
throw new Error(`Unregistered Event class ${Event.name}`);
|
throw new Error(`Unregistered Event class ${Event.name}`);
|
||||||
}
|
}
|
||||||
if (this._snoopedEvents.has(Event)) {
|
if (this._snoopedEvents.has(Event)) {
|
||||||
@@ -1026,16 +1018,16 @@ class Controller {
|
|||||||
*
|
*
|
||||||
* Routes the given request or event to the given destination. The
|
* Routes the given request or event to the given destination. The
|
||||||
* destination argument supports address shorthands, see {@link
|
* destination argument supports address shorthands, see {@link
|
||||||
* module:lib/data.Address.fromShorthand}
|
* module:lib.Address.fromShorthand}
|
||||||
*
|
*
|
||||||
* @param {*|module:lib/data.Address} address - Where to send it.
|
* @param {*|module:lib.Address} address - Where to send it.
|
||||||
* @param {*} requestOrEvent - The request or event to send.
|
* @param {*} requestOrEvent - The request or event to send.
|
||||||
* @returns {Promise<*>|undefined}
|
* @returns {Promise<*>|undefined}
|
||||||
* Promise that resolves to the response if a request was sent or
|
* Promise that resolves to the response if a request was sent or
|
||||||
* undefined if it was an event.
|
* undefined if it was an event.
|
||||||
*/
|
*/
|
||||||
sendTo(address, requestOrEvent) {
|
sendTo(address, requestOrEvent) {
|
||||||
let dst = libData.Address.fromShorthand(address);
|
let dst = lib.Address.fromShorthand(address);
|
||||||
if (requestOrEvent.constructor.type === "request") {
|
if (requestOrEvent.constructor.type === "request") {
|
||||||
return this.sendRequest(requestOrEvent, dst);
|
return this.sendRequest(requestOrEvent, dst);
|
||||||
}
|
}
|
||||||
@@ -1047,30 +1039,30 @@ class Controller {
|
|||||||
|
|
||||||
async sendRequest(request, dst) {
|
async sendRequest(request, dst) {
|
||||||
let connection;
|
let connection;
|
||||||
if (dst.type === libData.Address.controller) {
|
if (dst.type === lib.Address.controller) {
|
||||||
throw new Error("controller as dst is not supported.");
|
throw new Error("controller as dst is not supported.");
|
||||||
|
|
||||||
} else if (dst.type === libData.Address.control) {
|
} else if (dst.type === lib.Address.control) {
|
||||||
connection = this.wsServer.controlConnections.get(dst.id);
|
connection = this.wsServer.controlConnections.get(dst.id);
|
||||||
if (!connection) {
|
if (!connection) {
|
||||||
throw new libErrors.RequestError("Target control connection does not exist.");
|
throw new lib.RequestError("Target control connection does not exist.");
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (dst.type === libData.Address.instance) {
|
} else if (dst.type === lib.Address.instance) {
|
||||||
let instance = this.getRequestInstance(dst.id);
|
let instance = this.getRequestInstance(dst.id);
|
||||||
let hostId = instance.config.get("instance.assigned_host");
|
let hostId = instance.config.get("instance.assigned_host");
|
||||||
if (hostId === null) {
|
if (hostId === null) {
|
||||||
throw new libErrors.RequestError("Instance is not assigned to a host");
|
throw new lib.RequestError("Instance is not assigned to a host");
|
||||||
}
|
}
|
||||||
connection = this.wsServer.hostConnections.get(hostId);
|
connection = this.wsServer.hostConnections.get(hostId);
|
||||||
if (!connection) {
|
if (!connection) {
|
||||||
throw new libErrors.RequestError("Host containing instance is not connected");
|
throw new lib.RequestError("Host containing instance is not connected");
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (dst.type === libData.Address.host) {
|
} else if (dst.type === lib.Address.host) {
|
||||||
connection = this.wsServer.hostConnections.get(dst.id);
|
connection = this.wsServer.hostConnections.get(dst.id);
|
||||||
if (!connection) {
|
if (!connection) {
|
||||||
throw new libErrors.RequestError("Host is not connected");
|
throw new lib.RequestError("Host is not connected");
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
@@ -1082,13 +1074,13 @@ class Controller {
|
|||||||
|
|
||||||
sendEvent(event, dst) {
|
sendEvent(event, dst) {
|
||||||
let connection;
|
let connection;
|
||||||
if (dst.type === libData.Address.controller) {
|
if (dst.type === lib.Address.controller) {
|
||||||
throw new Error("controller as dst is not supported.");
|
throw new Error("controller as dst is not supported.");
|
||||||
|
|
||||||
} else if (dst.type === libData.Address.control) {
|
} else if (dst.type === lib.Address.control) {
|
||||||
connection = this.wsServer.controlConnections.get(dst.id);
|
connection = this.wsServer.controlConnections.get(dst.id);
|
||||||
|
|
||||||
} else if (dst.type === libData.Address.instance) {
|
} else if (dst.type === lib.Address.instance) {
|
||||||
let instance = this.instances.get(dst.id);
|
let instance = this.instances.get(dst.id);
|
||||||
if (!instance) {
|
if (!instance) {
|
||||||
return;
|
return;
|
||||||
@@ -1099,16 +1091,16 @@ class Controller {
|
|||||||
}
|
}
|
||||||
connection = this.wsServer.hostConnections.get(hostId);
|
connection = this.wsServer.hostConnections.get(hostId);
|
||||||
|
|
||||||
} else if (dst.type === libData.Address.host) {
|
} else if (dst.type === lib.Address.host) {
|
||||||
connection = this.wsServer.hostConnections.get(dst.id);
|
connection = this.wsServer.hostConnections.get(dst.id);
|
||||||
|
|
||||||
} else if (dst.type === libData.Address.broadcast) {
|
} else if (dst.type === lib.Address.broadcast) {
|
||||||
if (dst.id === libData.Address.control) {
|
if (dst.id === lib.Address.control) {
|
||||||
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
||||||
controlConnection.sendEvent(event, dst);
|
controlConnection.sendEvent(event, dst);
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (dst.id === libData.Address.instance || dst.id === libData.Address.host) {
|
} else if (dst.id === lib.Address.instance || dst.id === lib.Address.host) {
|
||||||
for (let hostConnection of this.wsServer.hostConnections.values()) {
|
for (let hostConnection of this.wsServer.hostConnections.values()) {
|
||||||
hostConnection.sendEvent(event, dst);
|
hostConnection.sendEvent(event, dst);
|
||||||
}
|
}
|
||||||
@@ -1141,11 +1133,11 @@ class Controller {
|
|||||||
let instance = this.getRequestInstance(request.instanceId);
|
let instance = this.getRequestInstance(request.instanceId);
|
||||||
let hostId = instance.config.get("instance.assigned_host");
|
let hostId = instance.config.get("instance.assigned_host");
|
||||||
if (hostId === null) {
|
if (hostId === null) {
|
||||||
throw new libErrors.RequestError("Instance is not assigned to a host");
|
throw new lib.RequestError("Instance is not assigned to a host");
|
||||||
}
|
}
|
||||||
let connection = this.wsServer.hostConnections.get(hostId);
|
let connection = this.wsServer.hostConnections.get(hostId);
|
||||||
if (!connection) {
|
if (!connection) {
|
||||||
throw new libErrors.RequestError("Host containing instance is not connected");
|
throw new lib.RequestError("Host containing instance is not connected");
|
||||||
}
|
}
|
||||||
return await connection.send(request);
|
return await connection.send(request);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
|
|
||||||
class ControllerRouter {
|
class ControllerRouter {
|
||||||
/** @type {module:controller/src/Controller} */
|
/** @type {module:controller/src/Controller} */
|
||||||
@@ -20,8 +20,8 @@ class ControllerRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {module:lib/link.Link} origin - Source link of the message.
|
* @param {module:lib.Link} origin - Source link of the message.
|
||||||
* @param {module:lib/data.Message} message
|
* @param {module:lib.Message} message
|
||||||
* Link the message originated from.
|
* Link the message originated from.
|
||||||
* @param {boolean} hasFallback - true if fallback handling is available.
|
* @param {boolean} hasFallback - true if fallback handling is available.
|
||||||
* @returns {boolean} true if the message was handled
|
* @returns {boolean} true if the message was handled
|
||||||
@@ -34,15 +34,15 @@ class ControllerRouter {
|
|||||||
let dst = message.dst;
|
let dst = message.dst;
|
||||||
let nextHop;
|
let nextHop;
|
||||||
let msg;
|
let msg;
|
||||||
if (dst.type === libData.Address.broadcast) {
|
if (dst.type === lib.Address.broadcast) {
|
||||||
this.broadcastMessage(origin, message);
|
this.broadcastMessage(origin, message);
|
||||||
return true;
|
return true;
|
||||||
} else if (dst.type === libData.Address.host) {
|
} else if (dst.type === lib.Address.host) {
|
||||||
nextHop = this.controller.wsServer.hostConnections.get(dst.id);
|
nextHop = this.controller.wsServer.hostConnections.get(dst.id);
|
||||||
if (!nextHop) {
|
if (!nextHop) {
|
||||||
msg = `Host ${dst.id} is offline`;
|
msg = `Host ${dst.id} is offline`;
|
||||||
}
|
}
|
||||||
} else if (dst.type === libData.Address.instance) {
|
} else if (dst.type === lib.Address.instance) {
|
||||||
let instance = this.controller.instances.get(dst.id);
|
let instance = this.controller.instances.get(dst.id);
|
||||||
if (!instance) {
|
if (!instance) {
|
||||||
msg = `Instance ${dst.id} does not exist`;
|
msg = `Instance ${dst.id} does not exist`;
|
||||||
@@ -57,12 +57,12 @@ class ControllerRouter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (dst.type === libData.Address.control) {
|
} else if (dst.type === lib.Address.control) {
|
||||||
nextHop = this.controller.wsServer.controlConnections.get(dst.id);
|
nextHop = this.controller.wsServer.controlConnections.get(dst.id);
|
||||||
if (!nextHop) {
|
if (!nextHop) {
|
||||||
msg = "Control connection does not exist";
|
msg = "Control connection does not exist";
|
||||||
}
|
}
|
||||||
} else if (dst.type === libData.Address.controller) {
|
} else if (dst.type === lib.Address.controller) {
|
||||||
msg = `Unexpected message forwarded to ${dst}`;
|
msg = `Unexpected message forwarded to ${dst}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ class ControllerRouter {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
origin.connector.sendResponseError(
|
origin.connector.sendResponseError(
|
||||||
new libData.ResponseError(msg || "Unroutable destination"), message.src
|
new lib.ResponseError(msg || "Unroutable destination"), message.src
|
||||||
);
|
);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -100,13 +100,13 @@ class ControllerRouter {
|
|||||||
let dst = message.dst;
|
let dst = message.dst;
|
||||||
if (message.type !== "event") {
|
if (message.type !== "event") {
|
||||||
this.warnUnrouted(message, `Unexpected broadcast of ${message.type}`);
|
this.warnUnrouted(message, `Unexpected broadcast of ${message.type}`);
|
||||||
} else if (dst.id === libData.Address.host || dst.id === libData.Address.instance) {
|
} else if (dst.id === lib.Address.host || dst.id === lib.Address.instance) {
|
||||||
for (let hostConnection of this.controller.wsServer.hostConnections.values()) {
|
for (let hostConnection of this.controller.wsServer.hostConnections.values()) {
|
||||||
if (hostConnection !== origin) {
|
if (hostConnection !== origin) {
|
||||||
hostConnection.connector.send(message);
|
hostConnection.connector.send(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (dst.id === libData.Address.control) {
|
} else if (dst.id === lib.Address.control) {
|
||||||
for (let controlConnection of this.controller.wsServer.controlConnections.values()) {
|
for (let controlConnection of this.controller.wsServer.controlConnections.values()) {
|
||||||
if (controlConnection !== origin) {
|
if (controlConnection !== origin) {
|
||||||
controlConnection.connector.send(message);
|
controlConnection.connector.send(message);
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libConfig = require("@clusterio/lib/config");
|
const { logger, PlayerStats } = lib;
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
const { logger } = require("@clusterio/lib/logging");
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const PlayerStats = require("@clusterio/lib/PlayerStats");
|
|
||||||
|
|
||||||
const BaseConnection = require("./BaseConnection");
|
const BaseConnection = require("./BaseConnection");
|
||||||
const InstanceInfo = require("./InstanceInfo");
|
const InstanceInfo = require("./InstanceInfo");
|
||||||
@@ -55,36 +51,36 @@ class HostConnection extends BaseConnection {
|
|||||||
let prev = instance.status;
|
let prev = instance.status;
|
||||||
instance.status = "unknown";
|
instance.status = "unknown";
|
||||||
this._controller.instanceUpdated(instance);
|
this._controller.instanceUpdated(instance);
|
||||||
libPlugin.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
|
lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.handle(libData.InstanceStatusChangedEvent, this.handleInstanceStatusChangedEvent.bind(this));
|
this.handle(lib.InstanceStatusChangedEvent, this.handleInstanceStatusChangedEvent.bind(this));
|
||||||
this.handle(libData.InstancesUpdateRequest, this.handleInstancesUpdateRequest.bind(this));
|
this.handle(lib.InstancesUpdateRequest, this.handleInstancesUpdateRequest.bind(this));
|
||||||
this.handle(libData.InstanceSaveListUpdateEvent, this.handleInstanceSaveListUpdateEvent.bind(this));
|
this.handle(lib.InstanceSaveListUpdateEvent, this.handleInstanceSaveListUpdateEvent.bind(this));
|
||||||
this.handle(libData.LogMessageEvent, this.handleLogMessageEvent.bind(this));
|
this.handle(lib.LogMessageEvent, this.handleLogMessageEvent.bind(this));
|
||||||
this.handle(libData.InstancePlayerUpdateEvent, this.handleInstancePlayerUpdateEvent.bind(this));
|
this.handle(lib.InstancePlayerUpdateEvent, this.handleInstancePlayerUpdateEvent.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
validateIngress(message) {
|
validateIngress(message) {
|
||||||
let origin = this.connector.dst;
|
let origin = this.connector.dst;
|
||||||
switch (message.src.type) {
|
switch (message.src.type) {
|
||||||
case libData.Address.control:
|
case lib.Address.control:
|
||||||
case libData.Address.controller:
|
case lib.Address.controller:
|
||||||
throw new libErrors.InvalidMessage(`Received message with invalid src ${message.src} from ${origin}`);
|
throw new lib.InvalidMessage(`Received message with invalid src ${message.src} from ${origin}`);
|
||||||
|
|
||||||
case libData.Address.host:
|
case lib.Address.host:
|
||||||
if (message.src.id !== origin.id) {
|
if (message.src.id !== origin.id) {
|
||||||
throw new libErrors.InvalidMessage(
|
throw new lib.InvalidMessage(
|
||||||
`Received message with invalid src ${message.src} from ${origin}`
|
`Received message with invalid src ${message.src} from ${origin}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case libData.Address.instance:
|
case lib.Address.instance:
|
||||||
let instance = this._controller.instances.get(message.src.id);
|
let instance = this._controller.instances.get(message.src.id);
|
||||||
if (!instance || instance.config.get("instance.assigned_host") !== this._id) {
|
if (!instance || instance.config.get("instance.assigned_host") !== this._id) {
|
||||||
throw new libErrors.InvalidMessage(
|
throw new lib.InvalidMessage(
|
||||||
`Received message with invalid src ${message.src} from ${origin}`
|
`Received message with invalid src ${message.src} from ${origin}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -120,7 +116,7 @@ class HostConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async prepareDisconnect() {
|
async prepareDisconnect() {
|
||||||
await libPlugin.invokeHook(this._controller.plugins, "onPrepareHostDisconnect", this);
|
await lib.invokeHook(this._controller.plugins, "onPrepareHostDisconnect", this);
|
||||||
return await super.prepareDisconnect();
|
return await super.prepareDisconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,7 +155,7 @@ class HostConnection extends BaseConnection {
|
|||||||
instance.game_port = request.gamePort;
|
instance.game_port = request.gamePort;
|
||||||
logger.verbose(`Instance ${instance.config.get("instance.name")} State: ${instance.status}`);
|
logger.verbose(`Instance ${instance.config.get("instance.name")} State: ${instance.status}`);
|
||||||
this._controller.instanceUpdated(instance);
|
this._controller.instanceUpdated(instance);
|
||||||
await libPlugin.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
|
await lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstancesUpdateRequest(request) {
|
async handleInstancesUpdateRequest(request) {
|
||||||
@@ -167,14 +163,14 @@ 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 libData.InstanceAssignInternalRequest(instance.id, instance.config.serialize("host"))
|
new lib.InstanceAssignInternalRequest(instance.id, instance.config.serialize("host"))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assign instances the host has but controller does not
|
// Assign instances the host has but controller does not
|
||||||
for (let instanceData of request.instances) {
|
for (let instanceData of request.instances) {
|
||||||
let instanceConfig = new libConfig.InstanceConfig("controller");
|
let instanceConfig = new lib.InstanceConfig("controller");
|
||||||
await instanceConfig.load(instanceData.config, "host");
|
await instanceConfig.load(instanceData.config, "host");
|
||||||
|
|
||||||
let controllerInstance = this._controller.instances.get(instanceConfig.get("instance.id"));
|
let controllerInstance = this._controller.instances.get(instanceConfig.get("instance.id"));
|
||||||
@@ -182,7 +178,7 @@ class HostConnection extends BaseConnection {
|
|||||||
// Check if this instance is assigned somewhere else.
|
// Check if this instance is assigned somewhere else.
|
||||||
if (controllerInstance.config.get("instance.assigned_host") !== this._id) {
|
if (controllerInstance.config.get("instance.assigned_host") !== this._id) {
|
||||||
await this.send(
|
await this.send(
|
||||||
new libData.InstanceUnassignInternalRequest(instanceConfig.get("instance.id"))
|
new lib.InstanceUnassignInternalRequest(instanceConfig.get("instance.id"))
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -193,7 +189,7 @@ class HostConnection extends BaseConnection {
|
|||||||
controllerInstance.status = instanceData.status;
|
controllerInstance.status = instanceData.status;
|
||||||
logger.verbose(`Instance ${instanceConfig.get("instance.name")} State: ${instanceData.status}`);
|
logger.verbose(`Instance ${instanceConfig.get("instance.name")} State: ${instanceData.status}`);
|
||||||
this._controller.instanceUpdated(controllerInstance);
|
this._controller.instanceUpdated(controllerInstance);
|
||||||
await libPlugin.invokeHook(
|
await lib.invokeHook(
|
||||||
this._controller.plugins, "onInstanceStatusChanged", controllerInstance, prev
|
this._controller.plugins, "onInstanceStatusChanged", controllerInstance, prev
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -205,11 +201,11 @@ class HostConnection extends BaseConnection {
|
|||||||
this._controller.instances.set(instanceConfig.get("instance.id"), newInstance);
|
this._controller.instances.set(instanceConfig.get("instance.id"), newInstance);
|
||||||
this._controller.addInstanceHooks(newInstance);
|
this._controller.addInstanceHooks(newInstance);
|
||||||
await this.send(
|
await this.send(
|
||||||
new libData.InstanceAssignInternalRequest(
|
new lib.InstanceAssignInternalRequest(
|
||||||
instanceConfig.get("instance.id"), instanceConfig.serialize("host")
|
instanceConfig.get("instance.id"), instanceConfig.serialize("host")
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
await libPlugin.invokeHook(this._controller.plugins, "onInstanceStatusChanged", newInstance, null);
|
await lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", newInstance, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Push lists to make sure they are in sync.
|
// Push lists to make sure they are in sync.
|
||||||
@@ -229,7 +225,7 @@ class HostConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.send(new libData.SyncUserListsEvent(adminlist, banlist, whitelist));
|
await this.send(new lib.SyncUserListsEvent(adminlist, banlist, whitelist));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceSaveListUpdateEvent(event) {
|
async handleInstanceSaveListUpdateEvent(event) {
|
||||||
@@ -261,7 +257,7 @@ class HostConnection extends BaseConnection {
|
|||||||
this._controller.userUpdated(user);
|
this._controller.userUpdated(user);
|
||||||
|
|
||||||
let instance = this._controller.instances.get(instanceId);
|
let instance = this._controller.instances.get(instanceId);
|
||||||
await libPlugin.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
|
await lib.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
|
||||||
type: event.type,
|
type: event.type,
|
||||||
name: event.name,
|
name: event.name,
|
||||||
reason: event.reason,
|
reason: event.reason,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
* @alias module:controller/src/InstanceInfo
|
* @alias module:controller/src/InstanceInfo
|
||||||
*/
|
*/
|
||||||
class InstanceInfo {
|
class InstanceInfo {
|
||||||
/** @type {module:lib/config.InstanceConfig} */
|
/** @type {module:lib.InstanceConfig} */
|
||||||
config;
|
config;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const fs = require("fs-extra");
|
const fs = require("fs-extra");
|
||||||
|
|
||||||
const libFileOps = require("@clusterio/lib/file_ops");
|
const lib = require("@clusterio/lib");
|
||||||
const libUsers = require("@clusterio/lib/users");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Manages users and roles
|
* Manages users and roles
|
||||||
@@ -21,12 +20,12 @@ class UserManager {
|
|||||||
try {
|
try {
|
||||||
let content = JSON.parse(await fs.readFile(filePath));
|
let content = JSON.parse(await fs.readFile(filePath));
|
||||||
for (let serializedRole of content.roles) {
|
for (let serializedRole of content.roles) {
|
||||||
let role = new libUsers.Role(serializedRole);
|
let role = new lib.Role(serializedRole);
|
||||||
loadedRoles.set(role.id, role);
|
loadedRoles.set(role.id, role);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let serializedUser of content.users) {
|
for (let serializedUser of content.users) {
|
||||||
let user = new libUsers.User(serializedUser, loadedRoles);
|
let user = new lib.User(serializedUser, loadedRoles);
|
||||||
loadedUsers.set(user.name, user);
|
loadedUsers.set(user.name, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,8 +35,8 @@ class UserManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create default roles if loading failed
|
// Create default roles if loading failed
|
||||||
libUsers.ensureDefaultAdminRole(loadedRoles);
|
lib.ensureDefaultAdminRole(loadedRoles);
|
||||||
libUsers.ensureDefaultPlayerRole(loadedRoles);
|
lib.ensureDefaultPlayerRole(loadedRoles);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.roles = loadedRoles;
|
this.roles = loadedRoles;
|
||||||
@@ -63,7 +62,7 @@ class UserManager {
|
|||||||
users: serializedUsers,
|
users: serializedUsers,
|
||||||
roles: serializedRoles,
|
roles: serializedRoles,
|
||||||
};
|
};
|
||||||
await libFileOps.safeOutputFile(filePath, JSON.stringify(serialized, null, 4));
|
await lib.safeOutputFile(filePath, JSON.stringify(serialized, null, 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -72,7 +71,7 @@ class UserManager {
|
|||||||
* Creates a new user and add it to the user database.
|
* Creates a new user and add it to the user database.
|
||||||
*
|
*
|
||||||
* @param {string} name - Name of the user to create.
|
* @param {string} name - Name of the user to create.
|
||||||
* @returns {module:lib/users.User} newly created user.
|
* @returns {module:lib.User} newly created user.
|
||||||
*/
|
*/
|
||||||
createUser(name) {
|
createUser(name) {
|
||||||
if (this.users.has(name)) {
|
if (this.users.has(name)) {
|
||||||
@@ -80,7 +79,7 @@ class UserManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let defaultRoleId = this._config.get("controller.default_role_id");
|
let defaultRoleId = this._config.get("controller.default_role_id");
|
||||||
let user = new libUsers.User({ name, roles: [defaultRoleId] }, this.roles);
|
let user = new lib.User({ name, roles: [defaultRoleId] }, this.roles);
|
||||||
this.users.set(name, user);
|
this.users.set(name, user);
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,8 @@
|
|||||||
const jwt = require("jsonwebtoken");
|
const jwt = require("jsonwebtoken");
|
||||||
const WebSocket = require("ws");
|
const WebSocket = require("ws");
|
||||||
|
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
const { logger } = lib;
|
||||||
const { logger } = require("@clusterio/lib/logging");
|
|
||||||
const libPrometheus = require("@clusterio/lib/prometheus");
|
|
||||||
|
|
||||||
const ControlConnection = require("./ControlConnection");
|
const ControlConnection = require("./ControlConnection");
|
||||||
const packageVersion = require("../package").version;
|
const packageVersion = require("../package").version;
|
||||||
@@ -13,18 +11,18 @@ const HostConnection = require("./HostConnection");
|
|||||||
const WsServerConnector = require("./WsServerConnector");
|
const WsServerConnector = require("./WsServerConnector");
|
||||||
|
|
||||||
|
|
||||||
const wsMessageCounter = new libPrometheus.Counter(
|
const wsMessageCounter = new lib.Counter(
|
||||||
"clusterio_controller_websocket_message_total",
|
"clusterio_controller_websocket_message_total",
|
||||||
"How many messages have been received over WebSocket on the controller",
|
"How many messages have been received over WebSocket on the controller",
|
||||||
{ labels: ["direction"] }
|
{ labels: ["direction"] }
|
||||||
);
|
);
|
||||||
|
|
||||||
const wsConnectionsCounter = new libPrometheus.Counter(
|
const wsConnectionsCounter = new lib.Counter(
|
||||||
"clusterio_controller_websocket_connections_total",
|
"clusterio_controller_websocket_connections_total",
|
||||||
"How many WebSocket connections have been initiated on the controller"
|
"How many WebSocket connections have been initiated on the controller"
|
||||||
);
|
);
|
||||||
|
|
||||||
const wsRejectedConnectionsCounter = new libPrometheus.Counter(
|
const wsRejectedConnectionsCounter = new lib.Counter(
|
||||||
"clusterio_controller_websocket_rejected_connections_total",
|
"clusterio_controller_websocket_rejected_connections_total",
|
||||||
"How many WebSocket connections have been rejected during the handshake on the controller"
|
"How many WebSocket connections have been rejected during the handshake on the controller"
|
||||||
);
|
);
|
||||||
@@ -78,7 +76,7 @@ class WsServer {
|
|||||||
try {
|
try {
|
||||||
await task;
|
await task;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!(err instanceof libErrors.SessionLost)) {
|
if (!(err instanceof lib.SessionLost)) {
|
||||||
logger.warn(`Unexpected error disconnecting connector:\n${err.stack}`);
|
logger.warn(`Unexpected error disconnecting connector:\n${err.stack}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -123,7 +121,7 @@ class WsServer {
|
|||||||
loadedPlugins[name] = plugin.info.version;
|
loadedPlugins[name] = plugin.info.version;
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.send(JSON.stringify(new libData.MessageHello(new libData.HelloData(packageVersion, loadedPlugins))));
|
socket.send(JSON.stringify(new lib.MessageHello(new lib.HelloData(packageVersion, loadedPlugins))));
|
||||||
this.attachHandler(socket, req);
|
this.attachHandler(socket, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,8 +158,8 @@ ${err.stack}`
|
|||||||
let message;
|
let message;
|
||||||
try {
|
try {
|
||||||
const json = JSON.parse(rawMessage);
|
const json = JSON.parse(rawMessage);
|
||||||
libData.Message.validate(json);
|
lib.Message.validate(json);
|
||||||
message = libData.Message.fromJSON(json);
|
message = lib.Message.fromJSON(json);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.verbose(`WsServer | closing ${req.socket.remoteAddress} after receiving invalid message`);
|
logger.verbose(`WsServer | closing ${req.socket.remoteAddress} after receiving invalid message`);
|
||||||
wsRejectedConnectionsCounter.inc();
|
wsRejectedConnectionsCounter.inc();
|
||||||
@@ -239,7 +237,7 @@ ${err.stack}`
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let [connector, sessionToken] = this.createSession(new libData.Address(libData.Address.host, data.id));
|
let [connector, sessionToken] = this.createSession(new lib.Address(lib.Address.host, data.id));
|
||||||
let connection = this.hostConnections.get(data.id);
|
let connection = this.hostConnections.get(data.id);
|
||||||
if (connection) {
|
if (connection) {
|
||||||
logger.verbose(`WsServer | disconnecting existing connection for host ${data.id}`);
|
logger.verbose(`WsServer | disconnecting existing connection for host ${data.id}`);
|
||||||
@@ -267,7 +265,7 @@ ${err.stack}`
|
|||||||
});
|
});
|
||||||
this.hostConnections.set(data.id, connection);
|
this.hostConnections.set(data.id, connection);
|
||||||
this.controller.hostUpdated(this.controller.hosts.get(data.id));
|
this.controller.hostUpdated(this.controller.hosts.get(data.id));
|
||||||
let src = new libData.Address(libData.Address.host, data.id);
|
let src = new lib.Address(lib.Address.host, data.id);
|
||||||
connector.ready(socket, src, sessionToken);
|
connector.ready(socket, src, sessionToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,7 +296,7 @@ ${err.stack}`
|
|||||||
|
|
||||||
let id = this.nextControlId;
|
let id = this.nextControlId;
|
||||||
this.nextControlId += 1;
|
this.nextControlId += 1;
|
||||||
let [connector, sessionToken] = this.createSession(new libData.Address(libData.Address.control, id));
|
let [connector, sessionToken] = this.createSession(new lib.Address(lib.Address.control, id));
|
||||||
|
|
||||||
logger.verbose(`WsServer | registered control ${id} from ${req.socket.remoteAddress}`);
|
logger.verbose(`WsServer | registered control ${id} from ${req.socket.remoteAddress}`);
|
||||||
let connection = new ControlConnection(data, connector, this.controller, user, id);
|
let connection = new ControlConnection(data, connector, this.controller, user, id);
|
||||||
@@ -306,7 +304,7 @@ ${err.stack}`
|
|||||||
this.controlConnections.delete(id);
|
this.controlConnections.delete(id);
|
||||||
});
|
});
|
||||||
this.controlConnections.set(id, connection);
|
this.controlConnections.set(id, connection);
|
||||||
let account = new libData.AccountDetails(
|
let account = new lib.AccountDetails(
|
||||||
user.name,
|
user.name,
|
||||||
[...user.roles].map(r => ({
|
[...user.roles].map(r => ({
|
||||||
name: r.name,
|
name: r.name,
|
||||||
@@ -315,7 +313,7 @@ ${err.stack}`
|
|||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
|
|
||||||
let src = new libData.Address(libData.Address.control, id);
|
let src = new lib.Address(lib.Address.control, id);
|
||||||
connector.ready(socket, src, sessionToken, account);
|
connector.ready(socket, src, sessionToken, account);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,7 +332,7 @@ ${err.stack}`
|
|||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
socket.send(JSON.stringify(new libData.MessageInvalidate()));
|
socket.send(JSON.stringify(new lib.MessageInvalidate()));
|
||||||
this.attachHandler(socket, req);
|
this.attachHandler(socket, req);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,19 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const events = require("events");
|
const events = require("events");
|
||||||
|
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libLink = require("@clusterio/lib/link");
|
const { logger } = lib;
|
||||||
const { logger } = require("@clusterio/lib/logging");
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connector for controller connections
|
* Connector for controller connections
|
||||||
*
|
*
|
||||||
* @extends module:lib/link.WebSocketBaseConnector
|
* @extends module:lib.WebSocketBaseConnector
|
||||||
* @alias module:controller/src/WsServerConnector
|
* @alias module:controller/src/WsServerConnector
|
||||||
*/
|
*/
|
||||||
class WsServerConnector extends libLink.WebSocketBaseConnector {
|
class WsServerConnector extends lib.WebSocketBaseConnector {
|
||||||
constructor(dst, sessionId, sessionTimeout, heartbeatInterval) {
|
constructor(dst, sessionId, sessionTimeout, heartbeatInterval) {
|
||||||
super(new libData.Address(libData.Address.controller, 0), dst);
|
super(new lib.Address(lib.Address.controller, 0), dst);
|
||||||
|
|
||||||
this._sessionTimeout = sessionTimeout;
|
this._sessionTimeout = sessionTimeout;
|
||||||
this._socket = null;
|
this._socket = null;
|
||||||
@@ -40,16 +39,16 @@ class WsServerConnector extends libLink.WebSocketBaseConnector {
|
|||||||
* Sends the ready message over the socket to initiate the session.
|
* Sends the ready message over the socket to initiate the session.
|
||||||
*
|
*
|
||||||
* @param {Object} socket - WebSocket connection to client.
|
* @param {Object} socket - WebSocket connection to client.
|
||||||
* @param {module:lib/data.Address} src - Source address for this link.
|
* @param {module:lib.Address} src - Source address for this link.
|
||||||
* @param {string} sessionToken -
|
* @param {string} sessionToken -
|
||||||
* the session token to send to the client.
|
* the session token to send to the client.
|
||||||
* @param {module:lib/data.AccountDetails=} account -
|
* @param {module:lib.AccountDetails=} account -
|
||||||
* account data to provide to control connection
|
* account data to provide to control connection
|
||||||
*/
|
*/
|
||||||
ready(socket, src, sessionToken, account) {
|
ready(socket, src, sessionToken, account) {
|
||||||
this._socket = socket;
|
this._socket = socket;
|
||||||
this._sendInternal(new libData.MessageReady(
|
this._sendInternal(new lib.MessageReady(
|
||||||
new libData.ReadyData(
|
new lib.ReadyData(
|
||||||
src,
|
src,
|
||||||
sessionToken,
|
sessionToken,
|
||||||
this._sessionTimeout,
|
this._sessionTimeout,
|
||||||
@@ -89,8 +88,8 @@ class WsServerConnector extends libLink.WebSocketBaseConnector {
|
|||||||
this._timeoutId = null;
|
this._timeoutId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
this._sendInternal(new libData.MessageContinue(
|
this._sendInternal(new lib.MessageContinue(
|
||||||
new libData.ContinueData(this._sessionTimeout, this._heartbeatInterval, this._lastReceivedSeq)
|
new lib.ContinueData(this._sessionTimeout, this._heartbeatInterval, this._lastReceivedSeq)
|
||||||
));
|
));
|
||||||
|
|
||||||
this._state = "connected";
|
this._state = "connected";
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// Shared metrics
|
// Shared metrics
|
||||||
"use strict";
|
"use strict";
|
||||||
const libPrometheus = require("@clusterio/lib/prometheus");
|
const lib = require("@clusterio/lib");
|
||||||
const util = require("util");
|
const util = require("util");
|
||||||
|
|
||||||
exports.endpointHitCounter = new libPrometheus.Counter(
|
exports.endpointHitCounter = new lib.Counter(
|
||||||
"clusterio_controller_http_endpoint_hits_total",
|
"clusterio_controller_http_endpoint_hits_total",
|
||||||
"How many requests a particular HTTP endpoint has gotten",
|
"How many requests a particular HTTP endpoint has gotten",
|
||||||
{ labels: ["route"], register: false }
|
{ labels: ["route"], register: false }
|
||||||
|
|||||||
@@ -9,15 +9,8 @@ const path = require("path");
|
|||||||
const nodeStream = require("stream");
|
const nodeStream = require("stream");
|
||||||
const util = require("util");
|
const util = require("util");
|
||||||
|
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
const { logger } = lib;
|
||||||
const libFileOps = require("@clusterio/lib/file_ops");
|
|
||||||
const libHash = require("@clusterio/lib/hash");
|
|
||||||
const libHelpers = require("@clusterio/lib/helpers");
|
|
||||||
const libLink = require("@clusterio/lib/link");
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const libPrometheus = require("@clusterio/lib/prometheus");
|
|
||||||
const { logger } = require("@clusterio/lib/logging");
|
|
||||||
|
|
||||||
const finished = util.promisify(nodeStream.finished);
|
const finished = util.promisify(nodeStream.finished);
|
||||||
|
|
||||||
@@ -40,7 +33,7 @@ function mergeSamples(destinationResult, sourceResult) {
|
|||||||
// Prometheus polling endpoint
|
// Prometheus polling endpoint
|
||||||
async function getMetrics(req, res, next) {
|
async function getMetrics(req, res, next) {
|
||||||
let results = [];
|
let results = [];
|
||||||
let pluginResults = await libPlugin.invokeHook(req.app.locals.controller.plugins, "onMetrics");
|
let pluginResults = await lib.invokeHook(req.app.locals.controller.plugins, "onMetrics");
|
||||||
for (let metricIterator of pluginResults) {
|
for (let metricIterator of pluginResults) {
|
||||||
for await (let metric of metricIterator) {
|
for await (let metric of metricIterator) {
|
||||||
results.push(metric);
|
results.push(metric);
|
||||||
@@ -53,9 +46,9 @@ async function getMetrics(req, res, next) {
|
|||||||
if (!hostConnection.connected) {
|
if (!hostConnection.connected) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
requests.push(libHelpers.timeout(
|
requests.push(lib.timeout(
|
||||||
hostConnection.send(new libData.HostMetricsRequest()).catch(err => {
|
hostConnection.send(new lib.HostMetricsRequest()).catch(err => {
|
||||||
if (!(err instanceof libErrors.SessionLost)) {
|
if (!(err instanceof lib.SessionLost)) {
|
||||||
logger.error(`Unexpected error gathering metrics from host:\n${err.stack}`);
|
logger.error(`Unexpected error gathering metrics from host:\n${err.stack}`);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -64,7 +57,7 @@ async function getMetrics(req, res, next) {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
for await (let result of await libPrometheus.defaultRegistry.collect()) {
|
for await (let result of await lib.defaultRegistry.collect()) {
|
||||||
results.push(result);
|
results.push(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,12 +80,12 @@ async function getMetrics(req, res, next) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (let result of resultMap.values()) {
|
for (let result of resultMap.values()) {
|
||||||
results.push(libPrometheus.deserializeResult(result));
|
results.push(lib.deserializeResult(result));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
let text = await libPrometheus.exposition(results);
|
let text = await lib.exposition(results);
|
||||||
res.set("Content-Type", libPrometheus.exposition.contentType);
|
res.set("Content-Type", lib.exposition.contentType);
|
||||||
res.send(text);
|
res.send(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,12 +220,12 @@ async function uploadExport(req, res) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let { name, ext } = path.posix.parse(filePath);
|
let { name, ext } = path.posix.parse(filePath);
|
||||||
let hash = await libHash.hashStream(file.nodeStream());
|
let hash = await lib.hashStream(file.nodeStream());
|
||||||
assets[name] = `${name}.${hash}${ext}`;
|
assets[name] = `${name}.${hash}${ext}`;
|
||||||
await libFileOps.safeOutputFile(path.join("static", `${name}.${hash}${ext}`), await file.async("nodebuffer"));
|
await lib.safeOutputFile(path.join("static", `${name}.${hash}${ext}`), await file.async("nodebuffer"));
|
||||||
}
|
}
|
||||||
|
|
||||||
modPack.exportManifest = new libData.ExportManifest(assets);
|
modPack.exportManifest = new lib.ExportManifest(assets);
|
||||||
modPack.fillDefaultSettings(settingPrototypes, logger);
|
modPack.fillDefaultSettings(settingPrototypes, logger);
|
||||||
res.app.locals.controller.modPackUpdated(modPack);
|
res.app.locals.controller.modPackUpdated(modPack);
|
||||||
|
|
||||||
@@ -363,7 +356,7 @@ async function uploadSave(req, res) {
|
|||||||
try {
|
try {
|
||||||
let storedName = await Promise.race([
|
let storedName = await Promise.race([
|
||||||
req.app.locals.controller.sendToHostByInstanceId(
|
req.app.locals.controller.sendToHostByInstanceId(
|
||||||
new libData.InstancePullSaveRequest(
|
new lib.InstancePullSaveRequest(
|
||||||
instanceId,
|
instanceId,
|
||||||
proxyStream.id,
|
proxyStream.id,
|
||||||
filename,
|
filename,
|
||||||
@@ -462,9 +455,9 @@ async function uploadSave(req, res) {
|
|||||||
|
|
||||||
function checkModName(name) {
|
function checkModName(name) {
|
||||||
try {
|
try {
|
||||||
libFileOps.checkFilename(name);
|
lib.checkFilename(name);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new libErrors.RequestError(`Mod name ${err.message}`);
|
throw new lib.RequestError(`Mod name ${err.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -512,7 +505,7 @@ async function uploadMod(req, res) {
|
|||||||
break;
|
break;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.code === "EEXIST") {
|
if (err.code === "EEXIST") {
|
||||||
tempFilename = await libFileOps.findUnusedName(modsDirectory, tempFilename, ".tmp.zip");
|
tempFilename = await lib.findUnusedName(modsDirectory, tempFilename, ".tmp.zip");
|
||||||
} else {
|
} else {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -521,7 +514,7 @@ async function uploadMod(req, res) {
|
|||||||
stream.pipe(writeStream);
|
stream.pipe(writeStream);
|
||||||
await finished(writeStream);
|
await finished(writeStream);
|
||||||
|
|
||||||
const modInfo = await libData.ModInfo.fromModFile(path.join(modsDirectory, tempFilename));
|
const modInfo = await lib.ModInfo.fromModFile(path.join(modsDirectory, tempFilename));
|
||||||
await fs.rename(path.join(modsDirectory, tempFilename), path.join(modsDirectory, modInfo.filename));
|
await fs.rename(path.join(modsDirectory, tempFilename), path.join(modsDirectory, modInfo.filename));
|
||||||
req.app.locals.controller.mods.set(modInfo.filename, modInfo);
|
req.app.locals.controller.mods.set(modInfo.filename, modInfo);
|
||||||
req.app.locals.controller.modUpdated(modInfo);
|
req.app.locals.controller.modUpdated(modInfo);
|
||||||
|
|||||||
+31
-39
@@ -10,16 +10,8 @@ const yargs = require("yargs");
|
|||||||
const version = require("./package").version;
|
const version = require("./package").version;
|
||||||
const setBlocking = require("set-blocking");
|
const setBlocking = require("set-blocking");
|
||||||
|
|
||||||
const libLink = require("@clusterio/lib/link");
|
const lib = require("@clusterio/lib");
|
||||||
const libData = require("@clusterio/lib/data");
|
const { ConsoleTransport, levels, logger } = lib;
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
const libConfig = require("@clusterio/lib/config");
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const libPluginLoader = require("@clusterio/lib/plugin_loader");
|
|
||||||
const libCommand = require("@clusterio/lib/command");
|
|
||||||
const libSharedCommands = require("@clusterio/lib/shared_commands");
|
|
||||||
const { ConsoleTransport, levels, logger } = require("@clusterio/lib/logging");
|
|
||||||
const libLoggingUtils = require("@clusterio/lib/logging_utils");
|
|
||||||
|
|
||||||
const commands = require("./src/commands");
|
const commands = require("./src/commands");
|
||||||
|
|
||||||
@@ -28,7 +20,7 @@ const commands = require("./src/commands");
|
|||||||
* Connector for control connection to controller
|
* Connector for control connection to controller
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
class ControlConnector extends libLink.WebSocketClientConnector {
|
class ControlConnector extends lib.WebSocketClientConnector {
|
||||||
constructor(url, maxReconnectDelay, tlsCa, token) {
|
constructor(url, maxReconnectDelay, tlsCa, token) {
|
||||||
super(url, maxReconnectDelay, tlsCa);
|
super(url, maxReconnectDelay, tlsCa);
|
||||||
this._token = token;
|
this._token = token;
|
||||||
@@ -37,8 +29,8 @@ class ControlConnector extends libLink.WebSocketClientConnector {
|
|||||||
register() {
|
register() {
|
||||||
logger.verbose("Connector | registering control");
|
logger.verbose("Connector | registering control");
|
||||||
this.sendHandshake(
|
this.sendHandshake(
|
||||||
new libData.MessageRegisterControl(
|
new lib.MessageRegisterControl(
|
||||||
new libData.RegisterControlData(
|
new lib.RegisterControlData(
|
||||||
this._token,
|
this._token,
|
||||||
"clusterioctl",
|
"clusterioctl",
|
||||||
version,
|
version,
|
||||||
@@ -54,13 +46,13 @@ class ControlConnector extends libLink.WebSocketClientConnector {
|
|||||||
* Connects to the controller over WebSocket and sends commands to it.
|
* Connects to the controller over WebSocket and sends commands to it.
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
class Control extends libLink.Link {
|
class Control extends lib.Link {
|
||||||
constructor(connector, controlConfig, tlsCa, controlPlugins) {
|
constructor(connector, controlConfig, tlsCa, controlPlugins) {
|
||||||
super(connector);
|
super(connector);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Control config used for connecting to the controller.
|
* Control config used for connecting to the controller.
|
||||||
* @type {module:lib/config.ControlConfig}
|
* @type {module:lib.ControlConfig}
|
||||||
*/
|
*/
|
||||||
this.config = controlConfig;
|
this.config = controlConfig;
|
||||||
/**
|
/**
|
||||||
@@ -70,7 +62,7 @@ class Control extends libLink.Link {
|
|||||||
this.tlsCa = tlsCa;
|
this.tlsCa = tlsCa;
|
||||||
/**
|
/**
|
||||||
* Mapping of plugin names to their instance for loaded plugins.
|
* Mapping of plugin names to their instance for loaded plugins.
|
||||||
* @type {Map<string, module:lib/plugin.BaseControlPlugin>}
|
* @type {Map<string, module:lib.BaseControlPlugin>}
|
||||||
*/
|
*/
|
||||||
this.plugins = controlPlugins;
|
this.plugins = controlPlugins;
|
||||||
|
|
||||||
@@ -80,8 +72,8 @@ class Control extends libLink.Link {
|
|||||||
*/
|
*/
|
||||||
this.keepOpen = false;
|
this.keepOpen = false;
|
||||||
|
|
||||||
this.handle(libData.LogMessageEvent, this.handleLogMessageEvent.bind(this));
|
this.handle(lib.LogMessageEvent, this.handleLogMessageEvent.bind(this));
|
||||||
this.handle(libData.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
|
this.handle(lib.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
async setLogSubscriptions({
|
async setLogSubscriptions({
|
||||||
@@ -92,7 +84,7 @@ class Control extends libLink.Link {
|
|||||||
maxLevel = null,
|
maxLevel = null,
|
||||||
}) {
|
}) {
|
||||||
await this.send(
|
await this.send(
|
||||||
new libData.LogSetSubscriptionsRequest(
|
new lib.LogSetSubscriptionsRequest(
|
||||||
all, controller, hostIds, instanceIds, maxLevel,
|
all, controller, hostIds, instanceIds, maxLevel,
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -111,7 +103,7 @@ class Control extends libLink.Link {
|
|||||||
try {
|
try {
|
||||||
await this.connector.disconnect();
|
await this.connector.disconnect();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!(err instanceof libErrors.SessionLost)) {
|
if (!(err instanceof lib.SessionLost)) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -119,10 +111,10 @@ class Control extends libLink.Link {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadPlugins(pluginList) {
|
async function loadPlugins(pluginList) {
|
||||||
let pluginInfos = await libPluginLoader.loadPluginInfos(pluginList);
|
let pluginInfos = await lib.loadPluginInfos(pluginList);
|
||||||
libLink.registerPluginMessages(pluginInfos);
|
lib.registerPluginMessages(pluginInfos);
|
||||||
libConfig.registerPluginConfigGroups(pluginInfos);
|
lib.registerPluginConfigGroups(pluginInfos);
|
||||||
libConfig.finalizeConfigs();
|
lib.finalizeConfigs();
|
||||||
|
|
||||||
let controlPlugins = new Map();
|
let controlPlugins = new Map();
|
||||||
for (let pluginInfo of pluginInfos) {
|
for (let pluginInfo of pluginInfos) {
|
||||||
@@ -130,7 +122,7 @@ async function loadPlugins(pluginList) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let ControlPluginClass = await libPluginLoader.loadControlPluginClass(pluginInfo);
|
let ControlPluginClass = await lib.loadControlPluginClass(pluginInfo);
|
||||||
let controlPlugin = new ControlPluginClass(pluginInfo, logger);
|
let controlPlugin = new ControlPluginClass(pluginInfo, logger);
|
||||||
controlPlugins.set(pluginInfo.name, controlPlugin);
|
controlPlugins.set(pluginInfo.name, controlPlugin);
|
||||||
await controlPlugin.init();
|
await controlPlugin.init();
|
||||||
@@ -162,8 +154,8 @@ async function startControl() {
|
|||||||
default: "plugin-list.json",
|
default: "plugin-list.json",
|
||||||
type: "string",
|
type: "string",
|
||||||
})
|
})
|
||||||
.command("plugin", "Manage available plugins", libSharedCommands.pluginCommand)
|
.command("plugin", "Manage available plugins", lib.pluginCommand)
|
||||||
.command("control-config", "Manage Control config", libSharedCommands.configCommand)
|
.command("control-config", "Manage Control config", lib.configCommand)
|
||||||
.wrap(yargs.terminalWidth())
|
.wrap(yargs.terminalWidth())
|
||||||
.help(false) // Disable help to avoid triggering it on the first parse.
|
.help(false) // Disable help to avoid triggering it on the first parse.
|
||||||
;
|
;
|
||||||
@@ -176,10 +168,10 @@ async function startControl() {
|
|||||||
new ConsoleTransport({
|
new ConsoleTransport({
|
||||||
errorLevels: Object.keys(levels),
|
errorLevels: Object.keys(levels),
|
||||||
level: args.logLevel,
|
level: args.logLevel,
|
||||||
format: new libLoggingUtils.TerminalFormat(),
|
format: new lib.TerminalFormat(),
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
libLoggingUtils.handleUnhandledErrors(logger);
|
lib.handleUnhandledErrors(logger);
|
||||||
|
|
||||||
logger.verbose(`Loading available plugins from ${args.pluginList}`);
|
logger.verbose(`Loading available plugins from ${args.pluginList}`);
|
||||||
let pluginList = new Map();
|
let pluginList = new Map();
|
||||||
@@ -193,7 +185,7 @@ async function startControl() {
|
|||||||
|
|
||||||
// If the command is plugin management we don't try to load plugins
|
// If the command is plugin management we don't try to load plugins
|
||||||
if (args._[0] === "plugin") {
|
if (args._[0] === "plugin") {
|
||||||
await libSharedCommands.handlePluginCommand(args, pluginList, args.pluginList);
|
await lib.handlePluginCommand(args, pluginList, args.pluginList);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,7 +203,7 @@ async function startControl() {
|
|||||||
;
|
;
|
||||||
|
|
||||||
logger.verbose(`Loading config from ${args.config}`);
|
logger.verbose(`Loading config from ${args.config}`);
|
||||||
let controlConfig = new libConfig.ControlConfig("control");
|
let controlConfig = new lib.ControlConfig("control");
|
||||||
try {
|
try {
|
||||||
await controlConfig.load(JSON.parse(await fs.readFile(args.config)));
|
await controlConfig.load(JSON.parse(await fs.readFile(args.config)));
|
||||||
|
|
||||||
@@ -221,7 +213,7 @@ async function startControl() {
|
|||||||
await controlConfig.init();
|
await controlConfig.init();
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
throw new libErrors.StartupError(`Failed to load ${args.config}: ${err.message}`);
|
throw new lib.StartupError(`Failed to load ${args.config}: ${err.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,14 +224,14 @@ async function startControl() {
|
|||||||
|
|
||||||
// Handle the control-config command before trying to connect.
|
// Handle the control-config command before trying to connect.
|
||||||
if (args._[0] === "control-config") {
|
if (args._[0] === "control-config") {
|
||||||
await libSharedCommands.handleConfigCommand(args, controlConfig, args.config);
|
await lib.handleConfigCommand(args, controlConfig, args.config);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine which command is being executed.
|
// Determine which command is being executed.
|
||||||
let commandPath = [...args._];
|
let commandPath = [...args._];
|
||||||
let targetCommand = rootCommands;
|
let targetCommand = rootCommands;
|
||||||
while (commandPath.length && targetCommand instanceof libCommand.CommandTree) {
|
while (commandPath.length && targetCommand instanceof lib.CommandTree) {
|
||||||
targetCommand = targetCommand.get(commandPath.shift());
|
targetCommand = targetCommand.get(commandPath.shift());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -266,8 +258,8 @@ async function startControl() {
|
|||||||
try {
|
try {
|
||||||
await controlConnector.connect();
|
await controlConnector.connect();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof libErrors.AuthenticationFailed) {
|
if (err instanceof lib.AuthenticationFailed) {
|
||||||
throw new libErrors.StartupError(err.message);
|
throw new lib.StartupError(err.message);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -287,11 +279,11 @@ async function startControl() {
|
|||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
control.keepOpen = false;
|
control.keepOpen = false;
|
||||||
if (err instanceof libErrors.CommandError) {
|
if (err instanceof lib.CommandError) {
|
||||||
logger.error(`Error running command: ${err.message}`);
|
logger.error(`Error running command: ${err.message}`);
|
||||||
process.exitCode = 1;
|
process.exitCode = 1;
|
||||||
|
|
||||||
} else if (err instanceof libErrors.RequestError) {
|
} else if (err instanceof lib.RequestError) {
|
||||||
logger.error(`Error sending request:\n${err.stack}`);
|
logger.error(`Error sending request:\n${err.stack}`);
|
||||||
process.exitCode = 1;
|
process.exitCode = 1;
|
||||||
|
|
||||||
@@ -321,7 +313,7 @@ I version of clusterio. Expect things to break. I
|
|||||||
`
|
`
|
||||||
);
|
);
|
||||||
startControl().catch(err => {
|
startControl().catch(err => {
|
||||||
if (!(err instanceof libErrors.StartupError)) {
|
if (!(err instanceof lib.StartupError)) {
|
||||||
logger.fatal(`
|
logger.fatal(`
|
||||||
+------------------------------------------------------------+
|
+------------------------------------------------------------+
|
||||||
| Unexpected error occured while starting control, please |
|
| Unexpected error occured while starting control, please |
|
||||||
|
|||||||
+208
-215
File diff suppressed because it is too large.
Load diff
+21
-27
@@ -22,19 +22,13 @@ const winston = require("winston");
|
|||||||
require("winston-daily-rotate-file");
|
require("winston-daily-rotate-file");
|
||||||
|
|
||||||
// internal libraries
|
// internal libraries
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libLink = require("@clusterio/lib/link");
|
const { ConsoleTransport, levels, logger } = lib;
|
||||||
const libPluginLoader = require("@clusterio/lib/plugin_loader");
|
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
const libConfig = require("@clusterio/lib/config");
|
|
||||||
const libSharedCommands = require("@clusterio/lib/shared_commands");
|
|
||||||
const { ConsoleTransport, FilteredTransport, levels, logger } = require("@clusterio/lib/logging");
|
|
||||||
const libLoggingUtils = require("@clusterio/lib/logging_utils");
|
|
||||||
|
|
||||||
const Host = require("./src/Host");
|
const Host = require("./src/Host");
|
||||||
|
|
||||||
|
|
||||||
class HostConnector extends libLink.WebSocketClientConnector {
|
class HostConnector extends lib.WebSocketClientConnector {
|
||||||
constructor(hostConfig, tlsCa, pluginInfos) {
|
constructor(hostConfig, tlsCa, pluginInfos) {
|
||||||
super(
|
super(
|
||||||
hostConfig.get("host.controller_url"),
|
hostConfig.get("host.controller_url"),
|
||||||
@@ -53,8 +47,8 @@ class HostConnector extends libLink.WebSocketClientConnector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.sendHandshake(
|
this.sendHandshake(
|
||||||
new libData.MessageRegisterHost(
|
new lib.MessageRegisterHost(
|
||||||
new libData.RegisterHostData(
|
new lib.RegisterHostData(
|
||||||
this.hostConfig.get("host.controller_token"),
|
this.hostConfig.get("host.controller_token"),
|
||||||
"Clusterio Host",
|
"Clusterio Host",
|
||||||
version,
|
version,
|
||||||
@@ -99,8 +93,8 @@ async function startHost() {
|
|||||||
default: "plugin-list.json",
|
default: "plugin-list.json",
|
||||||
type: "string",
|
type: "string",
|
||||||
})
|
})
|
||||||
.command("plugin", "Manage available plugins", libSharedCommands.pluginCommand)
|
.command("plugin", "Manage available plugins", lib.pluginCommand)
|
||||||
.command("config", "Manage Host config", libSharedCommands.configCommand)
|
.command("config", "Manage Host config", lib.configCommand)
|
||||||
.command("run", "Run host")
|
.command("run", "Run host")
|
||||||
.demandCommand(1, "You need to specify a command to run")
|
.demandCommand(1, "You need to specify a command to run")
|
||||||
.strict()
|
.strict()
|
||||||
@@ -116,11 +110,11 @@ async function startHost() {
|
|||||||
if (args.logLevel !== "none") {
|
if (args.logLevel !== "none") {
|
||||||
logger.add(new ConsoleTransport({
|
logger.add(new ConsoleTransport({
|
||||||
level: args.logLevel,
|
level: args.logLevel,
|
||||||
format: new libLoggingUtils.TerminalFormat(),
|
format: new lib.TerminalFormat(),
|
||||||
filter: info => info.instance_id === undefined,
|
filter: info => info.instance_id === undefined,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
libLoggingUtils.handleUnhandledErrors(logger);
|
lib.handleUnhandledErrors(logger);
|
||||||
|
|
||||||
let command = args._[0];
|
let command = args._[0];
|
||||||
if (command === "run") {
|
if (command === "run") {
|
||||||
@@ -139,18 +133,18 @@ async function startHost() {
|
|||||||
|
|
||||||
// If the command is plugin management we don't try to load plugins
|
// If the command is plugin management we don't try to load plugins
|
||||||
if (command === "plugin") {
|
if (command === "plugin") {
|
||||||
await libSharedCommands.handlePluginCommand(args, pluginList, args.pluginList);
|
await lib.handlePluginCommand(args, pluginList, args.pluginList);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("Loading Plugin info");
|
logger.info("Loading Plugin info");
|
||||||
let pluginInfos = await libPluginLoader.loadPluginInfos(pluginList);
|
let pluginInfos = await lib.loadPluginInfos(pluginList);
|
||||||
libLink.registerPluginMessages(pluginInfos);
|
lib.registerPluginMessages(pluginInfos);
|
||||||
libConfig.registerPluginConfigGroups(pluginInfos);
|
lib.registerPluginConfigGroups(pluginInfos);
|
||||||
libConfig.finalizeConfigs();
|
lib.finalizeConfigs();
|
||||||
|
|
||||||
logger.info(`Loading config from ${args.config}`);
|
logger.info(`Loading config from ${args.config}`);
|
||||||
let hostConfig = new libConfig.HostConfig("host");
|
let hostConfig = new lib.HostConfig("host");
|
||||||
try {
|
try {
|
||||||
await hostConfig.load(JSON.parse(await fs.readFile(args.config)));
|
await hostConfig.load(JSON.parse(await fs.readFile(args.config)));
|
||||||
|
|
||||||
@@ -160,12 +154,12 @@ async function startHost() {
|
|||||||
await hostConfig.init();
|
await hostConfig.init();
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
throw new libErrors.StartupError(`Failed to load ${args.config}: ${err.message}`);
|
throw new lib.StartupError(`Failed to load ${args.config}: ${err.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (command === "config") {
|
if (command === "config") {
|
||||||
await libSharedCommands.handleConfigCommand(args, hostConfig, args.config);
|
await lib.handleConfigCommand(args, hostConfig, args.config);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,7 +236,7 @@ async function startHost() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
hostConnector.once("connect", () => {
|
hostConnector.once("connect", () => {
|
||||||
logger.add(new libLoggingUtils.LinkTransport({ link: host }));
|
logger.add(new lib.LinkTransport({ link: host }));
|
||||||
});
|
});
|
||||||
|
|
||||||
await hostConnector.connect();
|
await hostConnector.connect();
|
||||||
@@ -259,10 +253,10 @@ I version of clusterio. Expect things to break. I
|
|||||||
`
|
`
|
||||||
);
|
);
|
||||||
startHost().catch(err => {
|
startHost().catch(err => {
|
||||||
if (err instanceof libErrors.AuthenticationFailed) {
|
if (err instanceof lib.AuthenticationFailed) {
|
||||||
logger.fatal(err.message);
|
logger.fatal(err.message);
|
||||||
|
|
||||||
} else if (err instanceof libErrors.StartupError) {
|
} else if (err instanceof lib.StartupError) {
|
||||||
logger.fatal(`
|
logger.fatal(`
|
||||||
+----------------------------------+
|
+----------------------------------+
|
||||||
| Unable to to start clusteriohost |
|
| Unable to to start clusteriohost |
|
||||||
@@ -270,7 +264,7 @@ I version of clusterio. Expect things to break. I
|
|||||||
${err.stack}`
|
${err.stack}`
|
||||||
);
|
);
|
||||||
|
|
||||||
} else if (err instanceof libErrors.PluginError) {
|
} else if (err instanceof lib.PluginError) {
|
||||||
logger.fatal(`
|
logger.fatal(`
|
||||||
${err.pluginName} plugin threw an unexpected error
|
${err.pluginName} plugin threw an unexpected error
|
||||||
during startup, please report it to the plugin author.
|
during startup, please report it to the plugin author.
|
||||||
|
|||||||
+85
-93
@@ -1,7 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const fs = require("fs-extra");
|
const fs = require("fs-extra");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
const yargs = require("yargs");
|
|
||||||
const events = require("events");
|
const events = require("events");
|
||||||
const pidusage = require("pidusage");
|
const pidusage = require("pidusage");
|
||||||
const setBlocking = require("set-blocking");
|
const setBlocking = require("set-blocking");
|
||||||
@@ -10,15 +9,8 @@ const stream = require("stream");
|
|||||||
const util = require("util");
|
const util = require("util");
|
||||||
|
|
||||||
// internal libraries
|
// internal libraries
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libFileOps = require("@clusterio/lib/file_ops");
|
const { logger } = lib;
|
||||||
const libLink = require("@clusterio/lib/link");
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
const libPrometheus = require("@clusterio/lib/prometheus");
|
|
||||||
const libConfig = require("@clusterio/lib/config");
|
|
||||||
const { logger } = require("@clusterio/lib/logging");
|
|
||||||
const libHelpers = require("@clusterio/lib/helpers");
|
|
||||||
|
|
||||||
const Instance = require("./Instance");
|
const Instance = require("./Instance");
|
||||||
const InstanceConnection = require("./InstanceConnection");
|
const InstanceConnection = require("./InstanceConnection");
|
||||||
@@ -28,9 +20,9 @@ const finished = util.promisify(stream.finished);
|
|||||||
|
|
||||||
function checkRequestSaveName(name) {
|
function checkRequestSaveName(name) {
|
||||||
try {
|
try {
|
||||||
libFileOps.checkFilename(name);
|
lib.checkFilename(name);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new libErrors.RequestError(`Save name ${err.message}`);
|
throw new lib.RequestError(`Save name ${err.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,7 +42,7 @@ async function discoverInstances(instancesDir) {
|
|||||||
let instanceInfos = new Map();
|
let instanceInfos = new Map();
|
||||||
for (let entry of await fs.readdir(instancesDir, { withFileTypes: true })) {
|
for (let entry of await fs.readdir(instancesDir, { withFileTypes: true })) {
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
let instanceConfig = new libConfig.InstanceConfig("host");
|
let instanceConfig = new lib.InstanceConfig("host");
|
||||||
let configPath = path.join(instancesDir, entry.name, "instance.json");
|
let configPath = path.join(instancesDir, entry.name, "instance.json");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -82,14 +74,14 @@ async function discoverInstances(instancesDir) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const instanceStartingMessages = new Set([
|
const instanceStartingMessages = new Set([
|
||||||
libData.InstanceStartRequest.name,
|
lib.InstanceStartRequest.name,
|
||||||
libData.InstanceLoadScenarioRequest.name,
|
lib.InstanceLoadScenarioRequest.name,
|
||||||
libData.InstanceCreateSaveRequest.name,
|
lib.InstanceCreateSaveRequest.name,
|
||||||
libData.InstanceExportDataRequest.name,
|
lib.InstanceExportDataRequest.name,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
class HostRouter {
|
class HostRouter {
|
||||||
/** @type {module:lib/host/src/Host} */
|
/** @type {module:host/src/Host} */
|
||||||
host;
|
host;
|
||||||
|
|
||||||
constructor(host) {
|
constructor(host) {
|
||||||
@@ -99,9 +91,9 @@ class HostRouter {
|
|||||||
/**
|
/**
|
||||||
* Forward a message to the next hop towards its destination.
|
* Forward a message to the next hop towards its destination.
|
||||||
*
|
*
|
||||||
* @param {module:lib/link.Link} origin -
|
* @param {module:lib.Link} origin -
|
||||||
* Link the message originated from.
|
* Link the message originated from.
|
||||||
* @param {module:lib/data.Message} message - Message to process.
|
* @param {module:lib.Message} message - Message to process.
|
||||||
* @param {boolean} hasFallback - is fallback available
|
* @param {boolean} hasFallback - is fallback available
|
||||||
* @returns {boolean} true if the message was handled, false if fallback
|
* @returns {boolean} true if the message was handled, false if fallback
|
||||||
* is requested
|
* is requested
|
||||||
@@ -110,17 +102,17 @@ class HostRouter {
|
|||||||
let dst = message.dst;
|
let dst = message.dst;
|
||||||
let nextHop;
|
let nextHop;
|
||||||
let msg;
|
let msg;
|
||||||
if (dst.type === libData.Address.broadcast) {
|
if (dst.type === lib.Address.broadcast) {
|
||||||
this.broadcastMessage(origin, message);
|
this.broadcastMessage(origin, message);
|
||||||
return true;
|
return true;
|
||||||
} else if (
|
} else if (
|
||||||
dst.type === libData.Address.controller
|
dst.type === lib.Address.controller
|
||||||
|| dst.type === libData.Address.control
|
|| dst.type === lib.Address.control
|
||||||
|| dst.type === libData.Address.host && dst.id !== this.host.config.get("host.id")
|
|| dst.type === lib.Address.host && dst.id !== this.host.config.get("host.id")
|
||||||
|| dst.type === libData.Address.instance && !this.host.instanceInfos.has(dst.id)
|
|| dst.type === lib.Address.instance && !this.host.instanceInfos.has(dst.id)
|
||||||
) {
|
) {
|
||||||
nextHop = this.host;
|
nextHop = this.host;
|
||||||
} else if (dst.type === libData.Address.instance && this.host.instanceInfos.has(dst.id)) {
|
} else if (dst.type === lib.Address.instance && this.host.instanceInfos.has(dst.id)) {
|
||||||
nextHop = this.host.instanceConnections.get(dst.id);
|
nextHop = this.host.instanceConnections.get(dst.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,17 +122,17 @@ class HostRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (message.type === "request") {
|
if (message.type === "request") {
|
||||||
if (dst.type === libData.Address.instance && instanceStartingMessages.has(message.name)) {
|
if (dst.type === lib.Address.instance && instanceStartingMessages.has(message.name)) {
|
||||||
this.wakeInstance(origin, message, nextHop);
|
this.wakeInstance(origin, message, nextHop);
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
} else if (!nextHop) {
|
} else if (!nextHop) {
|
||||||
if (dst.type === libData.Address.instance) {
|
if (dst.type === lib.Address.instance) {
|
||||||
if (hasFallback) {
|
if (hasFallback) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
origin.connector.sendResponseError(
|
origin.connector.sendResponseError(
|
||||||
new libData.ResponseError("Instance is not running."), message.src
|
new lib.ResponseError("Instance is not running."), message.src
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -163,7 +155,7 @@ class HostRouter {
|
|||||||
let dst = message.dst;
|
let dst = message.dst;
|
||||||
if (message.type !== "event") {
|
if (message.type !== "event") {
|
||||||
this.warnUnrouted(message, `Unexpected broadcast of ${message.type}`);
|
this.warnUnrouted(message, `Unexpected broadcast of ${message.type}`);
|
||||||
} else if (dst.id === libData.Address.host || dst.id === libData.Address.instance) {
|
} else if (dst.id === lib.Address.host || dst.id === lib.Address.instance) {
|
||||||
for (let instanceConnection of this.host.instanceConnections.values()) {
|
for (let instanceConnection of this.host.instanceConnections.values()) {
|
||||||
if (instanceConnection !== origin) {
|
if (instanceConnection !== origin) {
|
||||||
instanceConnection.connector.send(message);
|
instanceConnection.connector.send(message);
|
||||||
@@ -172,7 +164,7 @@ class HostRouter {
|
|||||||
if (this.host !== origin) {
|
if (this.host !== origin) {
|
||||||
this.host.connector.send(message);
|
this.host.connector.send(message);
|
||||||
}
|
}
|
||||||
} else if (dst.id === libData.Address.control) {
|
} else if (dst.id === lib.Address.control) {
|
||||||
if (this.host !== origin) {
|
if (this.host !== origin) {
|
||||||
this.host.connector.send(message);
|
this.host.connector.send(message);
|
||||||
} else {
|
} else {
|
||||||
@@ -187,13 +179,13 @@ class HostRouter {
|
|||||||
let dst = message.dst;
|
let dst = message.dst;
|
||||||
if (nextHop) {
|
if (nextHop) {
|
||||||
origin.connector.sendResponseError(
|
origin.connector.sendResponseError(
|
||||||
new libData.ResponseError("Instance is already running."), message.src
|
new lib.ResponseError("Instance is already running."), message.src
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.host._shuttingDown) {
|
if (this.host._shuttingDown) {
|
||||||
origin.connector.sendResponseError(
|
origin.connector.sendResponseError(
|
||||||
new libData.ResponseError("Host is shutting down."), message.src
|
new lib.ResponseError("Host is shutting down."), message.src
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -203,7 +195,7 @@ class HostRouter {
|
|||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Error starting instance:\n${err.stack}`, this.host.instanceLogMeta(dst.id));
|
logger.error(`Error starting instance:\n${err.stack}`, this.host.instanceLogMeta(dst.id));
|
||||||
origin.connector.sendResponseError(
|
origin.connector.sendResponseError(
|
||||||
new libData.ResponseError(err.message, err.code, err.stack), message.src
|
new lib.ResponseError(err.message, err.code, err.stack), message.src
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -218,7 +210,7 @@ class HostRouter {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (message.type === "request") {
|
if (message.type === "request") {
|
||||||
origin.connector.sendResponseError(
|
origin.connector.sendResponseError(
|
||||||
new libData.ResponseError(err.message, err.code, err.stack), message.src
|
new lib.ResponseError(err.message, err.code, err.stack), message.src
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
logger.warn(`Failed to deliver ${message.name || "message"} (${message.type}): ${err.message}`);
|
logger.warn(`Failed to deliver ${message.name || "message"} (${message.type}): ${err.message}`);
|
||||||
@@ -238,7 +230,7 @@ class HostRouter {
|
|||||||
* Connects to the controller over the WebSocket and manages intsances.
|
* Connects to the controller over the WebSocket and manages intsances.
|
||||||
* @alias module:host/src/Host
|
* @alias module:host/src/Host
|
||||||
*/
|
*/
|
||||||
class Host extends libLink.Link {
|
class Host extends lib.Link {
|
||||||
constructor(connector, hostConfig, tlsCa, pluginInfos) {
|
constructor(connector, hostConfig, tlsCa, pluginInfos) {
|
||||||
super(connector);
|
super(connector);
|
||||||
|
|
||||||
@@ -275,7 +267,7 @@ class Host extends libLink.Link {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.updateInstances().catch((err) => {
|
this.updateInstances().catch((err) => {
|
||||||
if (err instanceof libErrors.SessionLost) {
|
if (err instanceof lib.SessionLost) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,41 +296,41 @@ class Host extends libLink.Link {
|
|||||||
|
|
||||||
for (let event of ["connect", "drop", "resume", "close"]) {
|
for (let event of ["connect", "drop", "resume", "close"]) {
|
||||||
this.connector.on(event, () => {
|
this.connector.on(event, () => {
|
||||||
let message = new libData.ControllerConnectionEvent(event);
|
let message = new lib.ControllerConnectionEvent(event);
|
||||||
for (let instanceConnection of this.instanceConnections.values()) {
|
for (let instanceConnection of this.instanceConnections.values()) {
|
||||||
instanceConnection.send(message);
|
instanceConnection.send(message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this.handle(libData.SyncUserListsEvent, this.handleSyncUserListsEvent.bind(this));
|
this.handle(lib.SyncUserListsEvent, this.handleSyncUserListsEvent.bind(this));
|
||||||
this.snoopEvent(libData.InstanceAdminlistUpdateEvent, this.handleAdminlistUpdateEvent.bind(this));
|
this.snoopEvent(lib.InstanceAdminlistUpdateEvent, this.handleAdminlistUpdateEvent.bind(this));
|
||||||
this.snoopEvent(libData.InstanceBanlistUpdateEvent, this.handleBanlistUpdateEvent.bind(this));
|
this.snoopEvent(lib.InstanceBanlistUpdateEvent, this.handleBanlistUpdateEvent.bind(this));
|
||||||
this.snoopEvent(libData.InstanceWhitelistUpdateEvent, this.handleWhitelistUpdateEvent.bind(this));
|
this.snoopEvent(lib.InstanceWhitelistUpdateEvent, this.handleWhitelistUpdateEvent.bind(this));
|
||||||
this.handle(libData.InstanceAssignInternalRequest, this.handleInstanceAssignInternalRequest.bind(this));
|
this.handle(lib.InstanceAssignInternalRequest, this.handleInstanceAssignInternalRequest.bind(this));
|
||||||
this.handle(libData.InstanceUnassignInternalRequest, this.handleInstanceUnassignInternalRequest.bind(this));
|
this.handle(lib.InstanceUnassignInternalRequest, this.handleInstanceUnassignInternalRequest.bind(this));
|
||||||
this.handle(libData.HostMetricsRequest, this.handleHostMetricsRequest.bind(this));
|
this.handle(lib.HostMetricsRequest, this.handleHostMetricsRequest.bind(this));
|
||||||
this.fallbackRequest(libData.InstanceListSavesRequest, this.fallbackInstanceListSavesRequest.bind(this));
|
this.fallbackRequest(lib.InstanceListSavesRequest, this.fallbackInstanceListSavesRequest.bind(this));
|
||||||
this.handle(libData.InstanceRenameSaveRequest, this.handleInstanceRenameSaveRequest.bind(this));
|
this.handle(lib.InstanceRenameSaveRequest, this.handleInstanceRenameSaveRequest.bind(this));
|
||||||
this.handle(libData.InstanceCopySaveRequest, this.handleInstanceCopySaveRequest.bind(this));
|
this.handle(lib.InstanceCopySaveRequest, this.handleInstanceCopySaveRequest.bind(this));
|
||||||
this.handle(libData.InstanceTransferSaveRequest, this.handleInstanceTransferSaveRequest.bind(this));
|
this.handle(lib.InstanceTransferSaveRequest, this.handleInstanceTransferSaveRequest.bind(this));
|
||||||
this.handle(libData.InstanceDeleteSaveRequest, this.handleInstanceDeleteSaveRequest.bind(this));
|
this.handle(lib.InstanceDeleteSaveRequest, this.handleInstanceDeleteSaveRequest.bind(this));
|
||||||
this.handle(libData.InstancePullSaveRequest, this.handleInstancePullSaveRequest.bind(this));
|
this.handle(lib.InstancePullSaveRequest, this.handleInstancePullSaveRequest.bind(this));
|
||||||
this.handle(libData.InstancePushSaveRequest, this.handleInstancePushSaveRequest.bind(this));
|
this.handle(lib.InstancePushSaveRequest, this.handleInstancePushSaveRequest.bind(this));
|
||||||
this.handle(libData.InstanceDeleteInternalRequest, this.handleInstanceDeleteInternalRequest.bind(this));
|
this.handle(lib.InstanceDeleteInternalRequest, this.handleInstanceDeleteInternalRequest.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
async _createNewInstanceDir(name) {
|
async _createNewInstanceDir(name) {
|
||||||
name = libFileOps.cleanFilename(name);
|
name = lib.cleanFilename(name);
|
||||||
try {
|
try {
|
||||||
libFileOps.checkFilename(name);
|
lib.checkFilename(name);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new Error(`Instance folder was unepectedly invalid: name ${err.message}`);
|
throw new Error(`Instance folder was unepectedly invalid: name ${err.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
let instancesDir = this.config.get("host.instances_directory");
|
let instancesDir = this.config.get("host.instances_directory");
|
||||||
for (let i = 0; i < 10; i++) { // Limit attempts in case this is somehow an infinite loop
|
for (let i = 0; i < 10; i++) { // Limit attempts in case this is somehow an infinite loop
|
||||||
let candidateDir = path.join(instancesDir, await libFileOps.findUnusedName(instancesDir, name));
|
let candidateDir = path.join(instancesDir, await lib.findUnusedName(instancesDir, name));
|
||||||
try {
|
try {
|
||||||
await fs.mkdir(candidateDir);
|
await fs.mkdir(candidateDir);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -377,8 +369,8 @@ class Host extends libLink.Link {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
updateList(this.adminlist, request.adminlist, libData.InstanceAdminlistUpdateEvent);
|
updateList(this.adminlist, request.adminlist, lib.InstanceAdminlistUpdateEvent);
|
||||||
updateList(this.whitelist, request.whitelist, libData.InstanceWhitelistUpdateEvent);
|
updateList(this.whitelist, request.whitelist, lib.InstanceWhitelistUpdateEvent);
|
||||||
|
|
||||||
let addedOrChanged = new Map(request.banlist);
|
let addedOrChanged = new Map(request.banlist);
|
||||||
let removed = new Set(this.banlist.keys());
|
let removed = new Set(this.banlist.keys());
|
||||||
@@ -391,12 +383,12 @@ class Host extends libLink.Link {
|
|||||||
|
|
||||||
for (let [name, reason] of addedOrChanged) {
|
for (let [name, reason] of addedOrChanged) {
|
||||||
this.banlist.set(name, reason);
|
this.banlist.set(name, reason);
|
||||||
this.broadcastEventToInstance(new libData.InstanceBanlistUpdateEvent(name, true, reason));
|
this.broadcastEventToInstance(new lib.InstanceBanlistUpdateEvent(name, true, reason));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let name of removed) {
|
for (let name of removed) {
|
||||||
this.banlist.delete(name);
|
this.banlist.delete(name);
|
||||||
this.broadcastEventToInstance(new libData.InstanceBanlistUpdateEvent(name, false, ""));
|
this.broadcastEventToInstance(new lib.InstanceBanlistUpdateEvent(name, false, ""));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -440,7 +432,7 @@ class Host extends libLink.Link {
|
|||||||
instanceInfo.config.update(config, true, "controller");
|
instanceInfo.config.update(config, true, "controller");
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
let instanceConfig = new libConfig.InstanceConfig("host");
|
let instanceConfig = new lib.InstanceConfig("host");
|
||||||
await instanceConfig.load(config, "controller");
|
await instanceConfig.load(config, "controller");
|
||||||
|
|
||||||
let instanceDir = await this._createNewInstanceDir(instanceConfig.get("instance.name"));
|
let instanceDir = await this._createNewInstanceDir(instanceConfig.get("instance.name"));
|
||||||
@@ -464,7 +456,7 @@ class Host extends libLink.Link {
|
|||||||
// request for all the instances it knows should be on this host.
|
// request for all the instances it knows should be on this host.
|
||||||
let instanceConnection = this.instanceConnections.get(instanceId);
|
let instanceConnection = this.instanceConnections.get(instanceId);
|
||||||
this.send(
|
this.send(
|
||||||
new libData.InstanceStatusChangedEvent(
|
new lib.InstanceStatusChangedEvent(
|
||||||
instanceId, instanceConnection ? instanceConnection.status : "stopped", null
|
instanceId, instanceConnection ? instanceConnection.status : "stopped", null
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -474,7 +466,7 @@ class Host extends libLink.Link {
|
|||||||
_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.serialize(),
|
||||||
};
|
};
|
||||||
await libFileOps.safeOutputFile(
|
await lib.safeOutputFile(
|
||||||
path.join(instanceInfo.path, "instance.json"),
|
path.join(instanceInfo.path, "instance.json"),
|
||||||
JSON.stringify(warnedOutput, null, 4)
|
JSON.stringify(warnedOutput, null, 4)
|
||||||
);
|
);
|
||||||
@@ -486,7 +478,7 @@ class Host extends libLink.Link {
|
|||||||
if (instanceInfo) {
|
if (instanceInfo) {
|
||||||
let instanceConnection = this.instanceConnections.get(instanceId);
|
let instanceConnection = this.instanceConnections.get(instanceId);
|
||||||
if (instanceConnection && ["starting", "running"].includes(instanceConnection.status)) {
|
if (instanceConnection && ["starting", "running"].includes(instanceConnection.status)) {
|
||||||
await instanceConnection.send(new libData.InstanceStopRequest());
|
await instanceConnection.send(new lib.InstanceStopRequest());
|
||||||
}
|
}
|
||||||
|
|
||||||
this.instanceInfos.delete(instanceId);
|
this.instanceInfos.delete(instanceId);
|
||||||
@@ -505,7 +497,7 @@ class Host extends libLink.Link {
|
|||||||
getRequestInstanceInfo(instanceId) {
|
getRequestInstanceInfo(instanceId) {
|
||||||
let instanceInfo = this.instanceInfos.get(instanceId);
|
let instanceInfo = this.instanceInfos.get(instanceId);
|
||||||
if (!instanceInfo) {
|
if (!instanceInfo) {
|
||||||
throw new libErrors.RequestError(`Instance with ID ${instanceId} does not exist`);
|
throw new lib.RequestError(`Instance with ID ${instanceId} does not exist`);
|
||||||
}
|
}
|
||||||
return instanceInfo;
|
return instanceInfo;
|
||||||
}
|
}
|
||||||
@@ -519,12 +511,12 @@ class Host extends libLink.Link {
|
|||||||
async _connectInstance(instanceId) {
|
async _connectInstance(instanceId) {
|
||||||
let instanceInfo = this.getRequestInstanceInfo(instanceId);
|
let instanceInfo = this.getRequestInstanceInfo(instanceId);
|
||||||
if (this.instanceConnections.has(instanceId)) {
|
if (this.instanceConnections.has(instanceId)) {
|
||||||
throw new libErrors.RequestError(`Instance with ID ${instanceId} is running`);
|
throw new lib.RequestError(`Instance with ID ${instanceId} is running`);
|
||||||
}
|
}
|
||||||
|
|
||||||
let hostAddress = new libData.Address(libData.Address.host, this.id);
|
let hostAddress = new lib.Address(lib.Address.host, this.id);
|
||||||
let instanceAddress = new libData.Address(libData.Address.instance, instanceId);
|
let instanceAddress = new lib.Address(lib.Address.instance, instanceId);
|
||||||
let [connectionClient, connectionServer] = libLink.VirtualConnector.makePair(instanceAddress, hostAddress);
|
let [connectionClient, connectionServer] = lib.VirtualConnector.makePair(instanceAddress, hostAddress);
|
||||||
let instanceConnection = new InstanceConnection(connectionServer, this, instanceId);
|
let instanceConnection = new InstanceConnection(connectionServer, this, instanceId);
|
||||||
let instance = new Instance(
|
let instance = new Instance(
|
||||||
this, connectionClient, instanceInfo.path, this.config.get("host.factorio_directory"), instanceInfo.config
|
this, connectionClient, instanceInfo.path, this.config.get("host.factorio_directory"), instanceInfo.config
|
||||||
@@ -539,7 +531,7 @@ class Host extends libLink.Link {
|
|||||||
async handleHostMetricsRequest() {
|
async handleHostMetricsRequest() {
|
||||||
let requests = [];
|
let requests = [];
|
||||||
for (let instanceConnection of this.instanceConnections.values()) {
|
for (let instanceConnection of this.instanceConnections.values()) {
|
||||||
requests.push(instanceConnection.send(new libData.InstanceMetricsRequest()));
|
requests.push(instanceConnection.send(new lib.InstanceMetricsRequest()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let results = [];
|
let results = [];
|
||||||
@@ -547,15 +539,15 @@ class Host extends libLink.Link {
|
|||||||
results.push(...response.results);
|
results.push(...response.results);
|
||||||
}
|
}
|
||||||
|
|
||||||
for await (let result of libPrometheus.defaultRegistry.collect()) {
|
for await (let result of lib.defaultRegistry.collect()) {
|
||||||
if (result.metric.name.startsWith("process_")) {
|
if (result.metric.name.startsWith("process_")) {
|
||||||
results.push(libPrometheus.serializeResult(result, {
|
results.push(lib.serializeResult(result, {
|
||||||
addLabels: { "host_id": String(this.config.get("host.id")) },
|
addLabels: { "host_id": String(this.config.get("host.id")) },
|
||||||
metricName: result.metric.name.replace("process_", "clusterio_host_"),
|
metricName: result.metric.name.replace("process_", "clusterio_host_"),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
results.push(libPrometheus.serializeResult(result));
|
results.push(lib.serializeResult(result));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -580,7 +572,7 @@ class Host extends libLink.Link {
|
|||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.code === "ENOENT") {
|
if (err.code === "ENOENT") {
|
||||||
throw new libErrors.RequestError(`${oldName} does not exist`);
|
throw new lib.RequestError(`${oldName} does not exist`);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -600,7 +592,7 @@ class Host extends libLink.Link {
|
|||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.code === "ENOENT") {
|
if (err.code === "ENOENT") {
|
||||||
throw new libErrors.RequestError(`${source} does not exist`);
|
throw new lib.RequestError(`${source} does not exist`);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -616,7 +608,7 @@ class Host extends libLink.Link {
|
|||||||
|
|
||||||
// For consistency with remote transfer initiated through pullSave the
|
// For consistency with remote transfer initiated through pullSave the
|
||||||
// target is renamed if it already exists.
|
// target is renamed if it already exists.
|
||||||
targetName = await libFileOps.findUnusedName(
|
targetName = await lib.findUnusedName(
|
||||||
path.join(targetInstanceInfo.path, "saves"), targetName, ".zip"
|
path.join(targetInstanceInfo.path, "saves"), targetName, ".zip"
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -636,7 +628,7 @@ class Host extends libLink.Link {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.code === "ENOENT") {
|
if (err.code === "ENOENT") {
|
||||||
throw new libErrors.RequestError(`${sourceName} does not exist`);
|
throw new lib.RequestError(`${sourceName} does not exist`);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -650,12 +642,12 @@ class Host extends libLink.Link {
|
|||||||
let instanceConnection = this.instanceConnections.get(instanceId);
|
let instanceConnection = this.instanceConnections.get(instanceId);
|
||||||
let saveList;
|
let saveList;
|
||||||
if (instanceConnection) {
|
if (instanceConnection) {
|
||||||
saveList = await instanceConnection.send(new libData.InstanceListSavesRequest());
|
saveList = await instanceConnection.send(new lib.InstanceListSavesRequest());
|
||||||
} else {
|
} else {
|
||||||
saveList = await Instance.listSaves(savesDir, null);
|
saveList = await Instance.listSaves(savesDir, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.send(new libData.InstanceSaveListUpdateEvent(instanceId, saveList));
|
this.send(new lib.InstanceSaveListUpdateEvent(instanceId, saveList));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceDeleteSaveRequest(request) {
|
async handleInstanceDeleteSaveRequest(request) {
|
||||||
@@ -667,7 +659,7 @@ class Host extends libLink.Link {
|
|||||||
await fs.unlink(path.join(instanceInfo.path, "saves", name));
|
await fs.unlink(path.join(instanceInfo.path, "saves", name));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.code === "ENOENT") {
|
if (err.code === "ENOENT") {
|
||||||
throw new libErrors.RequestError(`${name} does not exist`);
|
throw new lib.RequestError(`${name} does not exist`);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -688,8 +680,8 @@ class Host extends libLink.Link {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (response.statusCode !== 200) {
|
if (response.statusCode !== 200) {
|
||||||
let content = await libHelpers.readStream(response);
|
let content = await lib.readStream(response);
|
||||||
throw new libErrors.RequestError(`Stream returned ${response.statusCode}: ${content.toString()}`);
|
throw new lib.RequestError(`Stream returned ${response.statusCode}: ${content.toString()}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
let savesDir = path.join(instanceInfo.path, "saves");
|
let savesDir = path.join(instanceInfo.path, "saves");
|
||||||
@@ -702,7 +694,7 @@ class Host extends libLink.Link {
|
|||||||
break;
|
break;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.code === "EEXIST") {
|
if (err.code === "EEXIST") {
|
||||||
tempFilename = await libFileOps.findUnusedName(savesDir, tempFilename, ".tmp.zip");
|
tempFilename = await lib.findUnusedName(savesDir, tempFilename, ".tmp.zip");
|
||||||
} else {
|
} else {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -711,7 +703,7 @@ class Host extends libLink.Link {
|
|||||||
response.pipe(writeStream);
|
response.pipe(writeStream);
|
||||||
await finished(writeStream);
|
await finished(writeStream);
|
||||||
|
|
||||||
name = await libFileOps.findUnusedName(savesDir, name, ".zip");
|
name = await lib.findUnusedName(savesDir, name, ".zip");
|
||||||
await fs.rename(path.join(savesDir, tempFilename), path.join(savesDir, name));
|
await fs.rename(path.join(savesDir, tempFilename), path.join(savesDir, name));
|
||||||
|
|
||||||
await this.sendSaveListUpdate(instanceId, savesDir);
|
await this.sendSaveListUpdate(instanceId, savesDir);
|
||||||
@@ -729,7 +721,7 @@ class Host extends libLink.Link {
|
|||||||
content = await fs.readFile(path.join(instanceInfo.path, "saves", name));
|
content = await fs.readFile(path.join(instanceInfo.path, "saves", name));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.code === "ENOENT") {
|
if (err.code === "ENOENT") {
|
||||||
throw new libErrors.RequestError(`${name} does not exist`);
|
throw new lib.RequestError(`${name} does not exist`);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -747,18 +739,18 @@ class Host extends libLink.Link {
|
|||||||
|
|
||||||
async stopInstance(instanceId) {
|
async stopInstance(instanceId) {
|
||||||
let instanceConnection = this.instanceConnections.get(instanceId);
|
let instanceConnection = this.instanceConnections.get(instanceId);
|
||||||
await instanceConnection.send(new libData.InstanceStopRequest());
|
await instanceConnection.send(new lib.InstanceStopRequest());
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceDeleteInternalRequest(request) {
|
async handleInstanceDeleteInternalRequest(request) {
|
||||||
let instanceId = request.instanceId;
|
let instanceId = request.instanceId;
|
||||||
if (this.instanceConnections.has(instanceId)) {
|
if (this.instanceConnections.has(instanceId)) {
|
||||||
throw new libErrors.RequestError(`Instance with ID ${instanceId} is running`);
|
throw new lib.RequestError(`Instance with ID ${instanceId} is running`);
|
||||||
}
|
}
|
||||||
|
|
||||||
let instanceInfo = this.discoveredInstanceInfos.get(instanceId);
|
let instanceInfo = this.discoveredInstanceInfos.get(instanceId);
|
||||||
if (!instanceInfo) {
|
if (!instanceInfo) {
|
||||||
throw new libErrors.RequestError(`Instance with ID ${instanceId} does not exist`);
|
throw new lib.RequestError(`Instance with ID ${instanceId} does not exist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.discoveredInstanceInfos.delete(instanceId);
|
this.discoveredInstanceInfos.delete(instanceId);
|
||||||
@@ -777,12 +769,12 @@ class Host extends libLink.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 libData.RawInstanceInfo(
|
list.push(new lib.RawInstanceInfo(
|
||||||
instanceInfo.config.serialize("controller"),
|
instanceInfo.config.serialize("controller"),
|
||||||
instanceConnection ? instanceConnection.status : "stopped",
|
instanceConnection ? instanceConnection.status : "stopped",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
await this.send(new libData.InstancesUpdateRequest(list));
|
await this.send(new lib.InstancesUpdateRequest(list));
|
||||||
|
|
||||||
// Handle configured auto startup instances
|
// Handle configured auto startup instances
|
||||||
if (this._startup) {
|
if (this._startup) {
|
||||||
@@ -792,7 +784,7 @@ class Host extends libLink.Link {
|
|||||||
if (instanceInfo.config.get("instance.auto_start")) {
|
if (instanceInfo.config.get("instance.auto_start")) {
|
||||||
try {
|
try {
|
||||||
let instanceConnection = await this._connectInstance(instanceId);
|
let instanceConnection = await this._connectInstance(instanceId);
|
||||||
await instanceConnection.send(new libData.InstanceStartRequest(null));
|
await instanceConnection.send(new lib.InstanceStartRequest(null));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(
|
logger.error(
|
||||||
`Error during auto startup for ${instanceInfo.config.get("instance.name")}:\n${err.stack}`,
|
`Error during auto startup for ${instanceInfo.config.get("instance.name")}:\n${err.stack}`,
|
||||||
@@ -806,7 +798,7 @@ class Host extends libLink.Link {
|
|||||||
|
|
||||||
async prepareDisconnect() {
|
async prepareDisconnect() {
|
||||||
for (let instanceConnection of this.instanceConnections.values()) {
|
for (let instanceConnection of this.instanceConnections.values()) {
|
||||||
await instanceConnection.send(new libData.PrepareControllerDisconnectRequest());
|
await instanceConnection.send(new lib.PrepareControllerDisconnectRequest());
|
||||||
}
|
}
|
||||||
this._disconnecting = true;
|
this._disconnecting = true;
|
||||||
return await super.prepareDisconnect();
|
return await super.prepareDisconnect();
|
||||||
@@ -832,7 +824,7 @@ class Host extends libLink.Link {
|
|||||||
try {
|
try {
|
||||||
await this.connector.disconnect();
|
await this.connector.disconnect();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!(err instanceof libErrors.SessionLost)) {
|
if (!(err instanceof lib.SessionLost)) {
|
||||||
logger.error(`Unexpected error preparing disconnect:\n${err.stack}`);
|
logger.error(`Unexpected error preparing disconnect:\n${err.stack}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,47 +6,38 @@ const phin = require("phin");
|
|||||||
const util = require("util");
|
const util = require("util");
|
||||||
|
|
||||||
// internal libraries
|
// internal libraries
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libFileOps = require("@clusterio/lib/file_ops");
|
const { PlayerStats } = lib;
|
||||||
const libFactorio = require("@clusterio/lib/factorio");
|
|
||||||
const libLink = require("@clusterio/lib/link");
|
|
||||||
const PlayerStats = require("@clusterio/lib/PlayerStats");
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const libPluginLoader = require("@clusterio/lib/plugin_loader");
|
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
const libPrometheus = require("@clusterio/lib/prometheus");
|
|
||||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
|
||||||
const libLogging = require("@clusterio/lib/logging");
|
|
||||||
|
|
||||||
|
|
||||||
const instanceRconCommandDuration = new libPrometheus.Histogram(
|
const instanceRconCommandDuration = new lib.Histogram(
|
||||||
"clusterio_instance_rcon_command_duration_seconds",
|
"clusterio_instance_rcon_command_duration_seconds",
|
||||||
"Histogram of the RCON command duration from request to response.",
|
"Histogram of the RCON command duration from request to response.",
|
||||||
{ labels: ["instance_id"] }
|
{ labels: ["instance_id"] }
|
||||||
);
|
);
|
||||||
|
|
||||||
const instanceRconCommandSize = new libPrometheus.Histogram(
|
const instanceRconCommandSize = new lib.Histogram(
|
||||||
"clusterio_instance_rcon_command_size_bytes",
|
"clusterio_instance_rcon_command_size_bytes",
|
||||||
"Histogram of the RCON command sizes that are sent.",
|
"Histogram of the RCON command sizes that are sent.",
|
||||||
{
|
{
|
||||||
labels: ["instance_id", "plugin"],
|
labels: ["instance_id", "plugin"],
|
||||||
buckets: libPrometheus.Histogram.exponential(16, 2, 12),
|
buckets: lib.Histogram.exponential(16, 2, 12),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const instanceFactorioCpuTime = new libPrometheus.Gauge(
|
const instanceFactorioCpuTime = new lib.Gauge(
|
||||||
"clusterio_instance_factorio_cpu_time_total",
|
"clusterio_instance_factorio_cpu_time_total",
|
||||||
"Factorio CPU time spent in seconds.",
|
"Factorio CPU time spent in seconds.",
|
||||||
{ labels: ["instance_id"] }
|
{ labels: ["instance_id"] }
|
||||||
);
|
);
|
||||||
|
|
||||||
const instanceFactorioMemoryUsage = new libPrometheus.Gauge(
|
const instanceFactorioMemoryUsage = new lib.Gauge(
|
||||||
"clusterio_instance_factorio_resident_memory_bytes",
|
"clusterio_instance_factorio_resident_memory_bytes",
|
||||||
"Factorio resident memory size in bytes.",
|
"Factorio resident memory size in bytes.",
|
||||||
{ labels: ["instance_id"] }
|
{ labels: ["instance_id"] }
|
||||||
);
|
);
|
||||||
|
|
||||||
const instanceFactorioAutosaveSize = new libPrometheus.Gauge(
|
const instanceFactorioAutosaveSize = new lib.Gauge(
|
||||||
"clusterio_instance_factorio_autosave_bytes",
|
"clusterio_instance_factorio_autosave_bytes",
|
||||||
"Size of Factorio server autosave in bytes.",
|
"Size of Factorio server autosave in bytes.",
|
||||||
{ labels: ["instance_id"] }
|
{ labels: ["instance_id"] }
|
||||||
@@ -100,7 +91,7 @@ const serverSettingsActions = {
|
|||||||
* Keeps track of the runtime parameters of an instance
|
* Keeps track of the runtime parameters of an instance
|
||||||
* @alias module:host/src/Instance
|
* @alias module:host/src/Instance
|
||||||
*/
|
*/
|
||||||
class Instance extends libLink.Link {
|
class Instance extends lib.Link {
|
||||||
constructor(host, connector, dir, factorioDir, instanceConfig) {
|
constructor(host, connector, dir, factorioDir, instanceConfig) {
|
||||||
super(connector);
|
super(connector);
|
||||||
this._host = host;
|
this._host = host;
|
||||||
@@ -115,13 +106,13 @@ class Instance extends libLink.Link {
|
|||||||
*/
|
*/
|
||||||
this.id = this.config.get("instance.id");
|
this.id = this.config.get("instance.id");
|
||||||
|
|
||||||
this.logger = libLogging.logger.child({
|
this.logger = lib.logger.child({
|
||||||
instance_id: this.id,
|
instance_id: this.id,
|
||||||
instance_name: this.name,
|
instance_name: this.name,
|
||||||
});
|
});
|
||||||
|
|
||||||
this._configFieldChanged = (group, field, prev) => {
|
this._configFieldChanged = (group, field, prev) => {
|
||||||
let hook = () => libPlugin.invokeHook(this.plugins, "onInstanceConfigFieldChanged", group, field, prev);
|
let hook = () => lib.invokeHook(this.plugins, "onInstanceConfigFieldChanged", group, field, prev);
|
||||||
|
|
||||||
if (group.name === "factorio" && field === "settings") {
|
if (group.name === "factorio" && field === "settings") {
|
||||||
this.updateFactorioSettings(group.get(field), prev).finally(hook);
|
this.updateFactorioSettings(group.get(field), prev).finally(hook);
|
||||||
@@ -152,18 +143,18 @@ class Instance extends libLink.Link {
|
|||||||
// Valid statuses are stopped, starting, running, stopping, creating_save and exporting_data.
|
// Valid statuses are stopped, starting, running, stopping, creating_save and exporting_data.
|
||||||
this._status = "stopped";
|
this._status = "stopped";
|
||||||
this._loadedSave = null;
|
this._loadedSave = null;
|
||||||
this.server = new libFactorio.FactorioServer(
|
this.server = new lib.FactorioServer(
|
||||||
factorioDir, this._dir, serverOptions
|
factorioDir, this._dir, serverOptions
|
||||||
);
|
);
|
||||||
|
|
||||||
this.server.on("output", (parsed, line) => {
|
this.server.on("output", (parsed, line) => {
|
||||||
this.logger.log("server", { message: line, instance_id: this.id, parsed });
|
this.logger.log("server", { message: line, instance_id: this.id, parsed });
|
||||||
|
|
||||||
libPlugin.invokeHook(this.plugins, "onOutput", parsed, line);
|
lib.invokeHook(this.plugins, "onOutput", parsed, line);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.server.on("error", err => {
|
this.server.on("error", err => {
|
||||||
if (err instanceof libErrors.EnvironmentError) {
|
if (err instanceof lib.EnvironmentError) {
|
||||||
this.logger.error(err.message);
|
this.logger.error(err.message);
|
||||||
} else {
|
} else {
|
||||||
this.logger.error(`${this.name}:\n${err.stack}`);
|
this.logger.error(`${this.name}:\n${err.stack}`);
|
||||||
@@ -192,13 +183,13 @@ class Instance extends libLink.Link {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Mod pack currently running on this instance
|
* Mod pack currently running on this instance
|
||||||
* @type {module:lib/data.ModPack}
|
* @type {module:lib.ModPack}
|
||||||
*/
|
*/
|
||||||
this.activeModPack = undefined;
|
this.activeModPack = undefined;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Per player statistics recorded by this instance.
|
* Per player statistics recorded by this instance.
|
||||||
* @type {Map<string, module:lib/PlayerStats>}
|
* @type {Map<string, module:lib.PlayerStats>}
|
||||||
*/
|
*/
|
||||||
this.playerStats = new Map();
|
this.playerStats = new Map();
|
||||||
|
|
||||||
@@ -211,23 +202,23 @@ class Instance extends libLink.Link {
|
|||||||
this._hadPlayersOnline = false;
|
this._hadPlayersOnline = false;
|
||||||
this._playerAutosaveSlot = 1;
|
this._playerAutosaveSlot = 1;
|
||||||
|
|
||||||
this.handle(libData.InstanceExtractPlayersRequest, this.handleInstanceExtractPlayersRequest.bind(this));
|
this.handle(lib.InstanceExtractPlayersRequest, this.handleInstanceExtractPlayersRequest.bind(this));
|
||||||
this.handle(libData.InstanceAdminlistUpdateEvent, this.handleInstanceAdminlistUpdateEvent.bind(this));
|
this.handle(lib.InstanceAdminlistUpdateEvent, this.handleInstanceAdminlistUpdateEvent.bind(this));
|
||||||
this.handle(libData.InstanceBanlistUpdateEvent, this.handleInstanceBanlistUpdateEvent.bind(this));
|
this.handle(lib.InstanceBanlistUpdateEvent, this.handleInstanceBanlistUpdateEvent.bind(this));
|
||||||
this.handle(libData.InstanceWhitelistUpdateEvent, this.handleInstanceWhitelistUpdateEvent.bind(this));
|
this.handle(lib.InstanceWhitelistUpdateEvent, this.handleInstanceWhitelistUpdateEvent.bind(this));
|
||||||
this.handle(libData.ControllerConnectionEvent, this.handleControllerConnectionEvent.bind(this));
|
this.handle(lib.ControllerConnectionEvent, this.handleControllerConnectionEvent.bind(this));
|
||||||
this.handle(
|
this.handle(
|
||||||
libData.PrepareControllerDisconnectRequest, this.handlePrepareControllerDisconnectRequest.bind(this)
|
lib.PrepareControllerDisconnectRequest, this.handlePrepareControllerDisconnectRequest.bind(this)
|
||||||
);
|
);
|
||||||
this.handle(libData.InstanceMetricsRequest, this.handleInstanceMetricsRequest.bind(this));
|
this.handle(lib.InstanceMetricsRequest, this.handleInstanceMetricsRequest.bind(this));
|
||||||
this.handle(libData.InstanceStartRequest, this.handleInstanceStartRequest.bind(this));
|
this.handle(lib.InstanceStartRequest, this.handleInstanceStartRequest.bind(this));
|
||||||
this.handle(libData.InstanceLoadScenarioRequest, this.handleInstanceLoadScenarioRequest.bind(this));
|
this.handle(lib.InstanceLoadScenarioRequest, this.handleInstanceLoadScenarioRequest.bind(this));
|
||||||
this.handle(libData.InstanceListSavesRequest, this.handleInstanceListSavesRequest.bind(this));
|
this.handle(lib.InstanceListSavesRequest, this.handleInstanceListSavesRequest.bind(this));
|
||||||
this.handle(libData.InstanceCreateSaveRequest, this.handleInstanceCreateSaveRequest.bind(this));
|
this.handle(lib.InstanceCreateSaveRequest, this.handleInstanceCreateSaveRequest.bind(this));
|
||||||
this.handle(libData.InstanceExportDataRequest, this.handleInstanceExportDataRequest.bind(this));
|
this.handle(lib.InstanceExportDataRequest, this.handleInstanceExportDataRequest.bind(this));
|
||||||
this.handle(libData.InstanceStopRequest, this.handleInstanceStopRequest.bind(this));
|
this.handle(lib.InstanceStopRequest, this.handleInstanceStopRequest.bind(this));
|
||||||
this.handle(libData.InstanceKillRequest, this.handleInstanceKillRequest.bind(this));
|
this.handle(lib.InstanceKillRequest, this.handleInstanceKillRequest.bind(this));
|
||||||
this.handle(libData.InstanceSendRconRequest, this.handleInstanceSendRconRequest.bind(this));
|
this.handle(lib.InstanceSendRconRequest, this.handleInstanceSendRconRequest.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
_watchPlayerJoinsByChat() {
|
_watchPlayerJoinsByChat() {
|
||||||
@@ -303,8 +294,8 @@ class Instance extends libLink.Link {
|
|||||||
name,
|
name,
|
||||||
stats,
|
stats,
|
||||||
};
|
};
|
||||||
this.sendTo("controller", new libData.InstancePlayerUpdateEvent("join", name, undefined, stats));
|
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("join", name, undefined, stats));
|
||||||
libPlugin.invokeHook(this.plugins, "onPlayerEvent", event);
|
lib.invokeHook(this.plugins, "onPlayerEvent", event);
|
||||||
}
|
}
|
||||||
|
|
||||||
_recordPlayerLeave(name, reason) {
|
_recordPlayerLeave(name, reason) {
|
||||||
@@ -325,8 +316,8 @@ class Instance extends libLink.Link {
|
|||||||
reason,
|
reason,
|
||||||
stats,
|
stats,
|
||||||
};
|
};
|
||||||
this.sendTo("controller", new libData.InstancePlayerUpdateEvent("leave", name, reason, stats));
|
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("leave", name, reason, stats));
|
||||||
libPlugin.invokeHook(this.plugins, "onPlayerEvent", event);
|
lib.invokeHook(this.plugins, "onPlayerEvent", event);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceExtractPlayersRequest() {
|
async handleInstanceExtractPlayersRequest() {
|
||||||
@@ -353,8 +344,8 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
name,
|
name,
|
||||||
stats: stats.toJSON(),
|
stats: stats.toJSON(),
|
||||||
};
|
};
|
||||||
this.sendTo("controller", new libData.InstancePlayerUpdateEvent("import", name, undefined, stats));
|
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("import", name, undefined, stats));
|
||||||
libPlugin.invokeHook(this.plugins, "onPlayerEvent", event);
|
lib.invokeHook(this.plugins, "onPlayerEvent", event);
|
||||||
count += 1;
|
count += 1;
|
||||||
}
|
}
|
||||||
this.logger.info(`Extracted data for ${count} player(s)`);
|
this.logger.info(`Extracted data for ${count} player(s)`);
|
||||||
@@ -374,7 +365,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
static async listSaves(savesDir, loadedSave) {
|
static async listSaves(savesDir, loadedSave) {
|
||||||
let defaultSave = null;
|
let defaultSave = null;
|
||||||
if (loadedSave === null) {
|
if (loadedSave === null) {
|
||||||
defaultSave = await libFileOps.getNewestFile(
|
defaultSave = await lib.getNewestFile(
|
||||||
savesDir, (name) => !name.endsWith(".tmp.zip")
|
savesDir, (name) => !name.endsWith(".tmp.zip")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -391,7 +382,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
type = "special";
|
type = "special";
|
||||||
}
|
}
|
||||||
|
|
||||||
list.push(new libData.SaveDetails(
|
list.push(new lib.SaveDetails(
|
||||||
type,
|
type,
|
||||||
name,
|
name,
|
||||||
stat.size,
|
stat.size,
|
||||||
@@ -407,7 +398,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
async sendSaveListUpdate() {
|
async sendSaveListUpdate() {
|
||||||
this.sendTo(
|
this.sendTo(
|
||||||
"controller",
|
"controller",
|
||||||
new libData.InstanceSaveListUpdateEvent(
|
new lib.InstanceSaveListUpdateEvent(
|
||||||
this.id,
|
this.id,
|
||||||
await Instance.listSaves(this.path("saves"), this._loadedSave),
|
await Instance.listSaves(this.path("saves"), this._loadedSave),
|
||||||
),
|
),
|
||||||
@@ -440,7 +431,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
this._status = status;
|
this._status = status;
|
||||||
this.sendTo(
|
this.sendTo(
|
||||||
"controller",
|
"controller",
|
||||||
new libData.InstanceStatusChangedEvent(
|
new lib.InstanceStatusChangedEvent(
|
||||||
this.id,
|
this.id,
|
||||||
status,
|
status,
|
||||||
this.server && this.server.gamePort || this.config.get("factorio.game_port") || null,
|
this.server && this.server.gamePort || this.config.get("factorio.game_port") || null,
|
||||||
@@ -467,9 +458,9 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
clearTimeout(this._playerCheckInterval);
|
clearTimeout(this._playerCheckInterval);
|
||||||
|
|
||||||
// Clear metrics this instance is exporting
|
// Clear metrics this instance is exporting
|
||||||
for (let collector of libPrometheus.defaultRegistry.collectors) {
|
for (let collector of lib.defaultRegistry.collectors) {
|
||||||
if (
|
if (
|
||||||
collector instanceof libPrometheus.ValueCollector
|
collector instanceof lib.ValueCollector
|
||||||
&& collector.metric.labels.includes("instance_id")
|
&& collector.metric.labels.includes("instance_id")
|
||||||
) {
|
) {
|
||||||
collector.removeAll({ instance_id: String(this.id) });
|
collector.removeAll({ instance_id: String(this.id) });
|
||||||
@@ -489,7 +480,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
|
|
||||||
async _loadPlugin(pluginInfo, host) {
|
async _loadPlugin(pluginInfo, host) {
|
||||||
let pluginLoadStarted = Date.now();
|
let pluginLoadStarted = Date.now();
|
||||||
let InstancePluginClass = await libPluginLoader.loadInstancePluginClass(pluginInfo);
|
let InstancePluginClass = await lib.loadInstancePluginClass(pluginInfo);
|
||||||
let instancePlugin = new InstancePluginClass(pluginInfo, this, host);
|
let instancePlugin = new InstancePluginClass(pluginInfo, this, host);
|
||||||
this.plugins.set(pluginInfo.name, instancePlugin);
|
this.plugins.set(pluginInfo.name, instancePlugin);
|
||||||
await instancePlugin.init();
|
await instancePlugin.init();
|
||||||
@@ -516,7 +507,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
players: [...this.playerStats],
|
players: [...this.playerStats],
|
||||||
player_autosave_slot: this._playerAutosaveSlot,
|
player_autosave_slot: this._playerAutosaveSlot,
|
||||||
}, null, 4);
|
}, null, 4);
|
||||||
await libFileOps.safeOutputFile(this.path("instance-stats.json"), content);
|
await lib.safeOutputFile(this.path("instance-stats.json"), content);
|
||||||
}
|
}
|
||||||
|
|
||||||
async init(pluginInfos) {
|
async init(pluginInfos) {
|
||||||
@@ -553,7 +544,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
for (let [name, plugin] of this.plugins) {
|
for (let [name, plugin] of this.plugins) {
|
||||||
plugins[name] = plugin.info.version;
|
plugins[name] = plugin.info.version;
|
||||||
}
|
}
|
||||||
this.send(new libData.InstanceInitialisedEvent(plugins));
|
this.send(new lib.InstanceInitialisedEvent(plugins));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -588,7 +579,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
*/
|
*/
|
||||||
async writeServerSettings() {
|
async writeServerSettings() {
|
||||||
let serverSettings = await this.resolveServerSettings(this.config.get("factorio.settings"));
|
let serverSettings = await this.resolveServerSettings(this.config.get("factorio.settings"));
|
||||||
await libFileOps.safeOutputFile(
|
await lib.safeOutputFile(
|
||||||
this.server.writePath("server-settings.json"),
|
this.server.writePath("server-settings.json"),
|
||||||
JSON.stringify(serverSettings, null, 4)
|
JSON.stringify(serverSettings, null, 4)
|
||||||
);
|
);
|
||||||
@@ -625,9 +616,9 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
const modPackId = this.config.get("factorio.mod_pack");
|
const modPackId = this.config.get("factorio.mod_pack");
|
||||||
let modPack;
|
let modPack;
|
||||||
if (modPackId === null) {
|
if (modPackId === null) {
|
||||||
modPack = await this.sendTo("controller", new libData.ModPackGetDefaultRequest());
|
modPack = await this.sendTo("controller", new lib.ModPackGetDefaultRequest());
|
||||||
} else {
|
} else {
|
||||||
modPack = await this.sendTo("controller", new libData.ModPackGetRequest(modPackId));
|
modPack = await this.sendTo("controller", new lib.ModPackGetRequest(modPackId));
|
||||||
}
|
}
|
||||||
this.activeModPack = modPack;
|
this.activeModPack = modPack;
|
||||||
|
|
||||||
@@ -691,7 +682,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
|
|
||||||
if (this.config.get("factorio.sync_adminlist")) {
|
if (this.config.get("factorio.sync_adminlist")) {
|
||||||
this.logger.verbose("Writing server-adminlist.json");
|
this.logger.verbose("Writing server-adminlist.json");
|
||||||
libFileOps.safeOutputFile(
|
lib.safeOutputFile(
|
||||||
this.server.writePath("server-adminlist.json"),
|
this.server.writePath("server-adminlist.json"),
|
||||||
JSON.stringify([...this._host.adminlist], null, 4)
|
JSON.stringify([...this._host.adminlist], null, 4)
|
||||||
);
|
);
|
||||||
@@ -699,7 +690,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
|
|
||||||
if (this.config.get("factorio.sync_banlist")) {
|
if (this.config.get("factorio.sync_banlist")) {
|
||||||
this.logger.verbose("Writing server-banlist.json");
|
this.logger.verbose("Writing server-banlist.json");
|
||||||
libFileOps.safeOutputFile(
|
lib.safeOutputFile(
|
||||||
this.server.writePath("server-banlist.json"),
|
this.server.writePath("server-banlist.json"),
|
||||||
JSON.stringify([...this._host.banlist].map(
|
JSON.stringify([...this._host.banlist].map(
|
||||||
([username, reason]) => ({ username, reason })
|
([username, reason]) => ({ username, reason })
|
||||||
@@ -709,7 +700,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
|
|
||||||
if (this.config.get("factorio.sync_whitelist")) {
|
if (this.config.get("factorio.sync_whitelist")) {
|
||||||
this.logger.verbose("Writing server-whitelist.json");
|
this.logger.verbose("Writing server-whitelist.json");
|
||||||
libFileOps.safeOutputFile(
|
lib.safeOutputFile(
|
||||||
this.server.writePath("server-whitelist.json"),
|
this.server.writePath("server-whitelist.json"),
|
||||||
JSON.stringify([...this._host.whitelist], null, 4)
|
JSON.stringify([...this._host.whitelist], null, 4)
|
||||||
);
|
);
|
||||||
@@ -731,7 +722,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
async prepareSave(saveName) {
|
async prepareSave(saveName) {
|
||||||
// Use latest save if no save was specified
|
// Use latest save if no save was specified
|
||||||
if (saveName === undefined) {
|
if (saveName === undefined) {
|
||||||
saveName = await libFileOps.getNewestFile(
|
saveName = await lib.getNewestFile(
|
||||||
this.path("saves"), (name) => !name.endsWith(".tmp.zip")
|
this.path("saves"), (name) => !name.endsWith(".tmp.zip")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -832,7 +823,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await libFactorio.patch(this.path("saves", saveName), [...modules.values()]);
|
await lib.patch(this.path("saves", saveName), [...modules.values()]);
|
||||||
return saveName;
|
return saveName;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -860,7 +851,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
|
|
||||||
await this.sendSaveListUpdate();
|
await this.sendSaveListUpdate();
|
||||||
await libPlugin.invokeHook(this.plugins, "onStart");
|
await lib.invokeHook(this.plugins, "onStart");
|
||||||
|
|
||||||
this.notifyStatus("running");
|
this.notifyStatus("running");
|
||||||
}
|
}
|
||||||
@@ -885,7 +876,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
await this.server.startScenario(scenario, seed, mapGenSettings, mapSettings);
|
await this.server.startScenario(scenario, seed, mapGenSettings, mapSettings);
|
||||||
this._watchPlayerJoinsByChat();
|
this._watchPlayerJoinsByChat();
|
||||||
|
|
||||||
await libPlugin.invokeHook(this.plugins, "onStart");
|
await lib.invokeHook(this.plugins, "onStart");
|
||||||
|
|
||||||
this.notifyStatus("running");
|
this.notifyStatus("running");
|
||||||
}
|
}
|
||||||
@@ -894,7 +885,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
* Update instance information on the Factorio side
|
* Update instance information on the Factorio side
|
||||||
*/
|
*/
|
||||||
async updateInstanceData() {
|
async updateInstanceData() {
|
||||||
let name = libLuaTools.escapeString(this.name);
|
let name = lib.escapeString(this.name);
|
||||||
await this.sendRcon(`/sc clusterio_private.update_instance(${this.id}, "${name}")`, true);
|
await this.sendRcon(`/sc clusterio_private.update_instance(${this.id}, "${name}")`, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -973,7 +964,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
|
|
||||||
// XXX this needs more thought to it
|
// XXX this needs more thought to it
|
||||||
if (this.server._state === "running") {
|
if (this.server._state === "running") {
|
||||||
await libPlugin.invokeHook(this.plugins, "onStop");
|
await lib.invokeHook(this.plugins, "onStop");
|
||||||
await this.server.stop();
|
await this.server.stop();
|
||||||
await this.sendSaveListUpdate();
|
await this.sendSaveListUpdate();
|
||||||
}
|
}
|
||||||
@@ -987,20 +978,20 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleControllerConnectionEvent(event) {
|
async handleControllerConnectionEvent(event) {
|
||||||
await libPlugin.invokeHook(this.plugins, "onControllerConnectionEvent", event.event);
|
await lib.invokeHook(this.plugins, "onControllerConnectionEvent", event.event);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handlePrepareControllerDisconnectRequest() {
|
async handlePrepareControllerDisconnectRequest() {
|
||||||
await libPlugin.invokeHook(this.plugins, "onPrepareControllerDisconnect");
|
await lib.invokeHook(this.plugins, "onPrepareControllerDisconnect");
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceMetricsRequest() {
|
async handleInstanceMetricsRequest() {
|
||||||
let results = [];
|
let results = [];
|
||||||
if (!["stopped", "stopping"].includes(this._status)) {
|
if (!["stopped", "stopping"].includes(this._status)) {
|
||||||
let pluginResults = await libPlugin.invokeHook(this.plugins, "onMetrics");
|
let pluginResults = await lib.invokeHook(this.plugins, "onMetrics");
|
||||||
for (let metricIterator of pluginResults) {
|
for (let metricIterator of pluginResults) {
|
||||||
for await (let metric of metricIterator) {
|
for await (let metric of metricIterator) {
|
||||||
results.push(libPrometheus.serializeResult(metric));
|
results.push(lib.serializeResult(metric));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1012,7 +1003,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
instanceFactorioMemoryUsage.labels(String(this.id)).set(stats.memory);
|
instanceFactorioMemoryUsage.labels(String(this.id)).set(stats.memory);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new libData.InstanceMetricsRequest.Response(results);
|
return new lib.InstanceMetricsRequest.Response(results);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceStartRequest(request) {
|
async handleInstanceStartRequest(request) {
|
||||||
@@ -1037,7 +1028,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
async handleInstanceLoadScenarioRequest(request) {
|
async handleInstanceLoadScenarioRequest(request) {
|
||||||
if (this.config.get("factorio.enable_save_patching")) {
|
if (this.config.get("factorio.enable_save_patching")) {
|
||||||
this.notifyExit();
|
this.notifyExit();
|
||||||
throw new libErrors.RequestError("Load scenario cannot be used with save patching enabled");
|
throw new lib.RequestError("Load scenario cannot be used with save patching enabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -1091,7 +1082,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
|
|
||||||
this.logger.info("Exporting data .....");
|
this.logger.info("Exporting data .....");
|
||||||
await this.syncMods();
|
await this.syncMods();
|
||||||
let zip = await libFactorio.exportData(this.server);
|
let zip = await lib.exportData(this.server);
|
||||||
|
|
||||||
let content = await zip.generateAsync({ type: "nodebuffer" });
|
let content = await zip.generateAsync({ type: "nodebuffer" });
|
||||||
let url = new URL(this._host.config.get("host.controller_url"));
|
let url = new URL(this._host.config.get("host.controller_url"));
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libLink = require("@clusterio/lib/link");
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
|
|
||||||
|
|
||||||
class InstanceConnection extends libLink.Link {
|
class InstanceConnection extends lib.Link {
|
||||||
constructor(connector, host, instanceId) {
|
constructor(connector, host, instanceId) {
|
||||||
super(connector);
|
super(connector);
|
||||||
this.host = host;
|
this.host = host;
|
||||||
@@ -14,8 +11,8 @@ class InstanceConnection extends libLink.Link {
|
|||||||
this.plugins = new Map();
|
this.plugins = new Map();
|
||||||
this.status = "stopped";
|
this.status = "stopped";
|
||||||
|
|
||||||
this.handle(libData.InstanceInitialisedEvent, this.handleInstanceInitialisedEvent.bind(this));
|
this.handle(lib.InstanceInitialisedEvent, this.handleInstanceInitialisedEvent.bind(this));
|
||||||
this.snoopEvent(libData.InstanceStatusChangedEvent, this.snoopInstanceStatusChangedEvent.bind(this));
|
this.snoopEvent(lib.InstanceStatusChangedEvent, this.snoopInstanceStatusChangedEvent.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
async broadcastEventToInstance(message, event) {
|
async broadcastEventToInstance(message, event) {
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
* `base` if more time than the value for `reset` has passed between two
|
* `base` if more time than the value for `reset` has passed between two
|
||||||
* invocations of delay.
|
* invocations of delay.
|
||||||
*
|
*
|
||||||
* @alias module:lib/ExponentialBackoff
|
* @alias module:lib.ExponentialBackoff
|
||||||
*/
|
*/
|
||||||
class ExponentialBackoff {
|
class ExponentialBackoff {
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Stastics collected about a player.
|
* Stastics collected about a player.
|
||||||
* @alias module:lib/PlayerStats
|
* @alias module:lib.PlayerStats
|
||||||
*/
|
*/
|
||||||
class PlayerStats {
|
class PlayerStats {
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
* // and one more time 1 second later for 99 other activations that were
|
* // and one more time 1 second later for 99 other activations that were
|
||||||
* // exceeding the rate limit.
|
* // exceeding the rate limit.
|
||||||
* }
|
* }
|
||||||
* @alias module:lib/RateLimiter
|
* @alias module:lib.RateLimiter
|
||||||
*/
|
*/
|
||||||
class RateLimiter {
|
class RateLimiter {
|
||||||
/**
|
/**
|
||||||
|
|||||||
+12
-10
@@ -1,13 +1,15 @@
|
|||||||
export { default as libConfig } from "./config";
|
export * from "./config";
|
||||||
export { default as libData } from "./data";
|
export * from "./data";
|
||||||
export { default as libErrors } from "./errors";
|
export * from "./errors";
|
||||||
export { default as libFactorio } from "./factorio/exchange_string";
|
export * from "./factorio/exchange_string";
|
||||||
export { default as libHelpers } from "./helpers";
|
export * from "./helpers";
|
||||||
export { default as libLink } from "./link";
|
export * from "./ini";
|
||||||
export { default as libLogging } from "./logging";
|
export * from "./link";
|
||||||
export { default as libPlugin } from "./plugin";
|
export * from "./logging";
|
||||||
export { default as libSchema } from "./schema";
|
export * from "./plugin";
|
||||||
export { default as libUsers } from "./users";
|
export * from "./schema";
|
||||||
|
export * from "./users";
|
||||||
|
|
||||||
export { default as ExponentialBackoff } from "./ExponentialBackoff";
|
export { default as ExponentialBackoff } from "./ExponentialBackoff";
|
||||||
|
export { default as PlayerStats } from "./PlayerStats";
|
||||||
export { default as RateLimiter } from "./RateLimiter";
|
export { default as RateLimiter } from "./RateLimiter";
|
||||||
@@ -52,10 +52,10 @@ class Command {
|
|||||||
/**
|
/**
|
||||||
* A node in the command tree that can hold commands and sub trees
|
* A node in the command tree that can hold commands and sub trees
|
||||||
*
|
*
|
||||||
* Container which can contain {@link module:lib/command.Command}s and other
|
* Container which can contain {@link module:lib.Command}s and other
|
||||||
* CommandTrees. This is used by clusterioctl to hold the full tree of
|
* CommandTrees. This is used by clusterioctl to hold the full tree of
|
||||||
* available commands, you may extend this tree by using a control plugin,
|
* available commands, you may extend this tree by using a control plugin,
|
||||||
* see {@link module:lib/plugin.BaseControlPlugin#addCommands}
|
* see {@link module:lib.BaseControlPlugin#addCommands}
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
@@ -83,7 +83,7 @@ class CommandTree {
|
|||||||
/**
|
/**
|
||||||
* Add a command or command tree to this tree
|
* Add a command or command tree to this tree
|
||||||
*
|
*
|
||||||
* @param {module:lib/command.Command|module:lib/command.CommandTree} command -
|
* @param {module:lib.Command|module:lib.CommandTree} command -
|
||||||
* The command to add to this command tree.
|
* The command to add to this command tree.
|
||||||
*/
|
*/
|
||||||
add(command) {
|
add(command) {
|
||||||
@@ -104,7 +104,7 @@ class CommandTree {
|
|||||||
*
|
*
|
||||||
* @param {string} name -
|
* @param {string} name -
|
||||||
* The name of the command or command tree to retrieve.
|
* The name of the command or command tree to retrieve.
|
||||||
* @return {?module:lib/command.Command|module:lib/command.CommandTree}
|
* @return {?module:lib.Command|module:lib.CommandTree}
|
||||||
* The command to add to this command tree.
|
* The command to add to this command tree.
|
||||||
*/
|
*/
|
||||||
get(name) {
|
get(name) {
|
||||||
@@ -141,7 +141,7 @@ class CommandTree {
|
|||||||
* Resolves a string with either an host name or an id into an integer with
|
* Resolves a string with either an host name or an id into an integer with
|
||||||
* the host ID.
|
* the host ID.
|
||||||
*
|
*
|
||||||
* @param {module:lib/link.Link} client - link to controller to query host on.
|
* @param {module:lib.Link} client - link to controller to query host on.
|
||||||
* @param {string} hostName - string with name or id of host.
|
* @param {string} hostName - string with name or id of host.
|
||||||
* @returns {Promise<number>} host ID.
|
* @returns {Promise<number>} host ID.
|
||||||
* @static
|
* @static
|
||||||
@@ -173,7 +173,7 @@ async function resolveHost(client, hostName) {
|
|||||||
* Resolves a string with either an instance name or an id into an integer
|
* Resolves a string with either an instance name or an id into an integer
|
||||||
* with the instance ID.
|
* with the instance ID.
|
||||||
*
|
*
|
||||||
* @param {module:lib/link.Link} client - link to controller to query instance on.
|
* @param {module:lib.Link} client - link to controller to query instance on.
|
||||||
* @param {string} instanceName - string with name or id of instance.
|
* @param {string} instanceName - string with name or id of instance.
|
||||||
* @returns {Promise<number>} instance ID.
|
* @returns {Promise<number>} instance ID.
|
||||||
* @static
|
* @static
|
||||||
@@ -205,7 +205,7 @@ async function resolveInstance(client, instanceName) {
|
|||||||
* Resolevs a string with either a mod pack name or an id into an integer
|
* Resolevs a string with either a mod pack name or an id into an integer
|
||||||
* with the mod pack ID.
|
* with the mod pack ID.
|
||||||
*
|
*
|
||||||
* @param {module:lib/link.Link} client -
|
* @param {module:lib.Link} client -
|
||||||
* link to controller to query mod pack on.
|
* link to controller to query mod pack on.
|
||||||
* @param {string} modPackName - string with name or id of mod pack.
|
* @param {string} modPackName - string with name or id of mod pack.
|
||||||
* @returns {Promise<number>} mod pack ID.
|
* @returns {Promise<number>} mod pack ID.
|
||||||
@@ -238,7 +238,7 @@ async function resolveModPack(client, modPackName) {
|
|||||||
* Resolves a string with either a role name or an id into an object
|
* Resolves a string with either a role name or an id into an object
|
||||||
* representing the role.
|
* representing the role.
|
||||||
*
|
*
|
||||||
* @param {module:lib/link.Link} client - link to controller to query role on.
|
* @param {module:lib.Link} client - link to controller to query role on.
|
||||||
* @param {string} roleName - string with name or id of role.
|
* @param {string} roleName - string with name or id of role.
|
||||||
* @returns {Promise<object>} Role info.
|
* @returns {Promise<object>} Role info.
|
||||||
* @static
|
* @static
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ const { basicType } = require("../helpers");
|
|||||||
* does not permitt this access is done.
|
* does not permitt this access is done.
|
||||||
*
|
*
|
||||||
* @extends Error
|
* @extends Error
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class InvalidAccess extends Error { };
|
class InvalidAccess extends Error { };
|
||||||
|
|
||||||
@@ -25,7 +25,7 @@ class InvalidAccess extends Error { };
|
|||||||
* field.
|
* field.
|
||||||
*
|
*
|
||||||
* @extends Error
|
* @extends Error
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class InvalidValue extends Error { };
|
class InvalidValue extends Error { };
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ class InvalidValue extends Error { };
|
|||||||
* attempted to be accessed.
|
* attempted to be accessed.
|
||||||
*
|
*
|
||||||
* @extends Error
|
* @extends Error
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class InvalidField extends Error { };
|
class InvalidField extends Error { };
|
||||||
|
|
||||||
@@ -51,7 +51,7 @@ class InvalidField extends Error { };
|
|||||||
* @param {string} separator - Separator to split string by.
|
* @param {string} separator - Separator to split string by.
|
||||||
* @param {string} string - String to split
|
* @param {string} string - String to split
|
||||||
* @returns {Array} string split on separator.
|
* @returns {Array} string split on separator.
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -77,7 +77,7 @@ function splitOn(separator, string) {
|
|||||||
*
|
*
|
||||||
* @extends events.EventEmitter
|
* @extends events.EventEmitter
|
||||||
*
|
*
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class Config extends events.EventEmitter {
|
class Config extends events.EventEmitter {
|
||||||
/**
|
/**
|
||||||
@@ -236,7 +236,7 @@ class Config extends events.EventEmitter {
|
|||||||
* Get the config group instance with the given name
|
* Get the config group instance with the given name
|
||||||
*
|
*
|
||||||
* @param {string} name - Name of group to get.
|
* @param {string} name - Name of group to get.
|
||||||
* @returns {module:lib/config.ConfigGroup} config group.
|
* @returns {module:lib.ConfigGroup} config group.
|
||||||
*/
|
*/
|
||||||
group(name) {
|
group(name) {
|
||||||
if (!this._initialized) {
|
if (!this._initialized) {
|
||||||
@@ -287,7 +287,7 @@ class Config extends events.EventEmitter {
|
|||||||
* Adds the ConfigGroup to this config as a group that will get
|
* Adds the ConfigGroup to this config as a group that will get
|
||||||
* initialized, loaded and serialized with this config class.
|
* initialized, loaded and serialized with this config class.
|
||||||
*
|
*
|
||||||
* @param {module:lib/config.ConfigGroup} group - class to register.
|
* @param {module:lib.ConfigGroup} group - class to register.
|
||||||
*/
|
*/
|
||||||
static registerGroup(group) {
|
static registerGroup(group) {
|
||||||
this._initSubclass();
|
this._initSubclass();
|
||||||
@@ -317,7 +317,7 @@ class Config extends events.EventEmitter {
|
|||||||
* loading a config with invalid values will result in those being replaced
|
* loading a config with invalid values will result in those being replaced
|
||||||
* by the innitial value for those fields.
|
* by the innitial value for those fields.
|
||||||
*
|
*
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class ConfigGroup {
|
class ConfigGroup {
|
||||||
/**
|
/**
|
||||||
@@ -326,7 +326,7 @@ class ConfigGroup {
|
|||||||
* After the creation of the new config group you have to call
|
* After the creation of the new config group you have to call
|
||||||
* either .init() or .load() on it in order to fully initialize it.
|
* either .init() or .load() on it in order to fully initialize it.
|
||||||
*
|
*
|
||||||
* @param {module:lib/config.Config} config -
|
* @param {module:lib.Config} config -
|
||||||
* Parent config for this group instance.
|
* Parent config for this group instance.
|
||||||
*/
|
*/
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
@@ -345,7 +345,7 @@ class ConfigGroup {
|
|||||||
* @param {object} def - definition for for the field to check.
|
* @param {object} def - definition for for the field to check.
|
||||||
* @param {string} remote - location of remote access to check for.
|
* @param {string} remote - location of remote access to check for.
|
||||||
* @param {boolean} error - throw on failure to pass check.
|
* @param {boolean} error - throw on failure to pass check.
|
||||||
* @throws {module:lib/config.InvalidAccess}
|
* @throws {module:lib.InvalidAccess}
|
||||||
* if access is not granted and error is true.
|
* if access is not granted and error is true.
|
||||||
* @returns {boolean} true if access is granted
|
* @returns {boolean} true if access is granted
|
||||||
* @private
|
* @private
|
||||||
@@ -456,8 +456,8 @@ class ConfigGroup {
|
|||||||
* @param {string} name - Name of field to set.
|
* @param {string} name - Name of field to set.
|
||||||
* @param {*} value - Value to set for field.
|
* @param {*} value - Value to set for field.
|
||||||
* @param {string=} location - Location used for access control.
|
* @param {string=} location - Location used for access control.
|
||||||
* @throws {module:lib/config.InvalidField} if field is not defined.
|
* @throws {module:lib.InvalidField} if field is not defined.
|
||||||
* @throws {module:lib/config.InvalidValue} if value is not allowed for the field.
|
* @throws {module:lib.InvalidValue} if value is not allowed for the field.
|
||||||
*/
|
*/
|
||||||
set(name, value, location = this.config.location) {
|
set(name, value, location = this.config.location) {
|
||||||
let def = this.constructor._definitions.get(name);
|
let def = this.constructor._definitions.get(name);
|
||||||
@@ -524,8 +524,8 @@ class ConfigGroup {
|
|||||||
* @param {string} prop - Name of property to set on field.
|
* @param {string} prop - Name of property to set on field.
|
||||||
* @param {*} value - the value to set the property to.
|
* @param {*} value - the value to set the property to.
|
||||||
* @param {string=} location - Location used for access control.
|
* @param {string=} location - Location used for access control.
|
||||||
* @throws {module:lib/config.InvalidField} if field is not defined.
|
* @throws {module:lib.InvalidField} if field is not defined.
|
||||||
* @throws {module:lib/config.InvalidValue} if field is not an object.
|
* @throws {module:lib.InvalidValue} if field is not an object.
|
||||||
*/
|
*/
|
||||||
setProp(name, prop, value, location = this.config.location) {
|
setProp(name, prop, value, location = this.config.location) {
|
||||||
let def = this.constructor._definitions.get(name);
|
let def = this.constructor._definitions.get(name);
|
||||||
@@ -829,8 +829,8 @@ class ConfigGroup {
|
|||||||
* plugins. This is currently only the enabled field. It is otherwise
|
* plugins. This is currently only the enabled field. It is otherwise
|
||||||
* identical to the ConfigGroup class.
|
* identical to the ConfigGroup class.
|
||||||
*
|
*
|
||||||
* @extends module:lib/config.ConfigGroup
|
* @extends module:lib.ConfigGroup
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class PluginConfigGroup extends ConfigGroup {
|
class PluginConfigGroup extends ConfigGroup {
|
||||||
static _initSubclass() {
|
static _initSubclass() {
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ const classes = require("./classes");
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Controller config group for {@link module:lib/config.ControllerConfig}
|
* Controller config group for {@link module:lib.ControllerConfig}
|
||||||
* @extends module:lib/config.ConfigGroup
|
* @extends module:lib.ConfigGroup
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class ControllerGroup extends classes.ConfigGroup { }
|
class ControllerGroup extends classes.ConfigGroup { }
|
||||||
ControllerGroup.defaultAccess = ["controller", "host", "control"];
|
ControllerGroup.defaultAccess = ["controller", "host", "control"];
|
||||||
@@ -140,17 +140,17 @@ ControllerGroup.finalize();
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Controller Config class
|
* Controller Config class
|
||||||
* @extends module:lib/config.Config
|
* @extends module:lib.Config
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class ControllerConfig extends classes.Config { }
|
class ControllerConfig extends classes.Config { }
|
||||||
ControllerConfig.registerGroup(ControllerGroup);
|
ControllerConfig.registerGroup(ControllerGroup);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Host config group for {@link module:lib/config.HostConfig}
|
* Host config group for {@link module:lib.HostConfig}
|
||||||
* @extends module:lib/config.ConfigGroup
|
* @extends module:lib.ConfigGroup
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class HostGroup extends classes.ConfigGroup {}
|
class HostGroup extends classes.ConfigGroup {}
|
||||||
HostGroup.defaultAccess = ["controller", "host", "control"];
|
HostGroup.defaultAccess = ["controller", "host", "control"];
|
||||||
@@ -232,17 +232,17 @@ HostGroup.finalize();
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Host Config class
|
* Host Config class
|
||||||
* @extends module:lib/config.Config
|
* @extends module:lib.Config
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class HostConfig extends classes.Config { }
|
class HostConfig extends classes.Config { }
|
||||||
HostConfig.registerGroup(HostGroup);
|
HostConfig.registerGroup(HostGroup);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instance config group for {@link module:lib/config.InstanceConfig}
|
* Instance config group for {@link module:lib.InstanceConfig}
|
||||||
* @extends module:lib/config.ConfigGroup
|
* @extends module:lib.ConfigGroup
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class InstanceGroup extends classes.ConfigGroup { }
|
class InstanceGroup extends classes.ConfigGroup { }
|
||||||
InstanceGroup.defaultAccess = ["controller", "host", "control"];
|
InstanceGroup.defaultAccess = ["controller", "host", "control"];
|
||||||
@@ -272,9 +272,9 @@ InstanceGroup.define({
|
|||||||
InstanceGroup.finalize();
|
InstanceGroup.finalize();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Factorio config group for {@link module:lib/config.InstanceConfig}
|
* Factorio config group for {@link module:lib.InstanceConfig}
|
||||||
* @extends module:lib/config.ConfigGroup
|
* @extends module:lib.ConfigGroup
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class FactorioGroup extends classes.ConfigGroup { }
|
class FactorioGroup extends classes.ConfigGroup { }
|
||||||
FactorioGroup.defaultAccess = ["controller", "host", "control"];
|
FactorioGroup.defaultAccess = ["controller", "host", "control"];
|
||||||
@@ -398,8 +398,8 @@ FactorioGroup.finalize();
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Instance config class
|
* Instance config class
|
||||||
* @extends module:lib/config.Config
|
* @extends module:lib.Config
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class InstanceConfig extends classes.Config { }
|
class InstanceConfig extends classes.Config { }
|
||||||
InstanceConfig.registerGroup(InstanceGroup);
|
InstanceConfig.registerGroup(InstanceGroup);
|
||||||
@@ -407,9 +407,9 @@ InstanceConfig.registerGroup(FactorioGroup);
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Control config group for {@link module:lib/config.ControlConfig}
|
* Control config group for {@link module:lib.ControlConfig}
|
||||||
* @extends module:lib/config.ConfigGroup
|
* @extends module:lib.ConfigGroup
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class ControlGroup extends classes.ConfigGroup {}
|
class ControlGroup extends classes.ConfigGroup {}
|
||||||
ControlGroup.defaultAccess = ["control"];
|
ControlGroup.defaultAccess = ["control"];
|
||||||
@@ -443,8 +443,8 @@ ControlGroup.finalize();
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Control config class
|
* Control config class
|
||||||
* @extends module:lib/config.Config
|
* @extends module:lib.Config
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class ControlConfig extends classes.Config { }
|
class ControlConfig extends classes.Config { }
|
||||||
ControlConfig.registerGroup(ControlGroup);
|
ControlConfig.registerGroup(ControlGroup);
|
||||||
@@ -468,7 +468,7 @@ function validateGroup(pluginInfo, groupName) {
|
|||||||
* Registers the config groups for the provided plugin infos
|
* Registers the config groups for the provided plugin infos
|
||||||
*
|
*
|
||||||
* @param {Array<Object>} pluginInfos - Array of plugin info objects.
|
* @param {Array<Object>} pluginInfos - Array of plugin info objects.
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
function registerPluginConfigGroups(pluginInfos) {
|
function registerPluginConfigGroups(pluginInfos) {
|
||||||
for (let pluginInfo of pluginInfos) {
|
for (let pluginInfo of pluginInfos) {
|
||||||
@@ -503,7 +503,7 @@ function registerPluginConfigGroups(pluginInfos) {
|
|||||||
/**
|
/**
|
||||||
* Lock configs from adding more groups and make them usable
|
* Lock configs from adding more groups and make them usable
|
||||||
*
|
*
|
||||||
* @memberof module:lib/config
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
function finalizeConfigs() {
|
function finalizeConfigs() {
|
||||||
ControllerConfig.finalize();
|
ControllerConfig.finalize();
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
*
|
*
|
||||||
* Tracks files stored on disk for data that extracted from Factorio using a
|
* Tracks files stored on disk for data that extracted from Factorio using a
|
||||||
* given mod pack.
|
* given mod pack.
|
||||||
* @alias module:lib/data.ExportManifest
|
* @alias module:lib.ExportManifest
|
||||||
*/
|
*/
|
||||||
class ExportManifest {
|
class ExportManifest {
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ const { integerModVersion, integerFactorioVersion, modVersionRegExp } = require(
|
|||||||
*
|
*
|
||||||
* See https://wiki.factorio.com/Tutorial:Mod_structure#info.json for
|
* See https://wiki.factorio.com/Tutorial:Mod_structure#info.json for
|
||||||
* details of the invidiual fields sourced from info.json.
|
* details of the invidiual fields sourced from info.json.
|
||||||
* @alias module:lib/data.ModInfo
|
* @alias module:lib.ModInfo
|
||||||
*/
|
*/
|
||||||
class ModInfo {
|
class ModInfo {
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const { integerFactorioVersion } = require("./version");
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A setting for a mod.
|
* A setting for a mod.
|
||||||
* @typedef {object} module:lib/data.ModPack~ModSetting
|
* @typedef {object} module:lib.ModPack~ModSetting
|
||||||
* @property {boolean|number|string} value - Value of the given mod setting.
|
* @property {boolean|number|string} value - Value of the given mod setting.
|
||||||
*/
|
*/
|
||||||
const ModSettingJsonSchema = {
|
const ModSettingJsonSchema = {
|
||||||
@@ -28,7 +28,7 @@ const ModSettingsJsonSchema = {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A mod in a mod pack
|
* A mod in a mod pack
|
||||||
* @typedef {object} module:lib/data.ModPack~ModRecord
|
* @typedef {object} module:lib.ModPack~ModRecord
|
||||||
* @property {string} name - name of the mod.
|
* @property {string} name - name of the mod.
|
||||||
* @property {boolean} enabled - if mod is to be loaded.
|
* @property {boolean} enabled - if mod is to be loaded.
|
||||||
* @property {string} version - version of the mod.
|
* @property {string} version - version of the mod.
|
||||||
@@ -49,7 +49,7 @@ const ModRecordJsonSchema = {
|
|||||||
* Factorio Mod Pack
|
* Factorio Mod Pack
|
||||||
*
|
*
|
||||||
* Tracks mods and settings for a collection of Factorio mods.
|
* Tracks mods and settings for a collection of Factorio mods.
|
||||||
* @alias module:lib/data.ModPack
|
* @alias module:lib.ModPack
|
||||||
*/
|
*/
|
||||||
class ModPack {
|
class ModPack {
|
||||||
/**
|
/**
|
||||||
@@ -86,13 +86,13 @@ class ModPack {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Mods included in this mod pack
|
* Mods included in this mod pack
|
||||||
* @type {Map<string, module:lib/data.ModPack~ModRecord>}
|
* @type {Map<string, module:lib.ModPack~ModRecord>}
|
||||||
*/
|
*/
|
||||||
mods = new Map();
|
mods = new Map();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mod settings for this mod pack
|
* Mod settings for this mod pack
|
||||||
* @type {Object<string, Map<string, module:lib/data.ModPack~ModSetting>>=}
|
* @type {Object<string, Map<string, module:lib.ModPack~ModSetting>>=}
|
||||||
*/
|
*/
|
||||||
settings = {
|
settings = {
|
||||||
"startup": new Map(),
|
"startup": new Map(),
|
||||||
@@ -102,7 +102,7 @@ class ModPack {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Mapping to files containing exported data for this modpack
|
* Mapping to files containing exported data for this modpack
|
||||||
* @type {module:lib/data.ExportManifest|undefined}
|
* @type {module:lib.ExportManifest|undefined}
|
||||||
*/
|
*/
|
||||||
exportManifest;
|
exportManifest;
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
const { JsonString } = require("./composites");
|
const { JsonString } = require("./composites");
|
||||||
|
|
||||||
// TODO: remove after config refactor
|
// TODO: remove after config refactor
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class RawConfig {
|
class RawConfig {
|
||||||
/** @type {object} */
|
/** @type {object} */
|
||||||
serializedConfig;
|
serializedConfig;
|
||||||
@@ -24,7 +24,7 @@ class RawConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ControllerConfigGetRequest {
|
class ControllerConfigGetRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -33,7 +33,7 @@ class ControllerConfigGetRequest {
|
|||||||
static Response = RawConfig;
|
static Response = RawConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class ControllerConfigSetFieldRequest {
|
class ControllerConfigSetFieldRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -64,7 +64,7 @@ class ControllerConfigSetFieldRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ControllerConfigSetPropRequest {
|
class ControllerConfigSetPropRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -99,7 +99,7 @@ class ControllerConfigSetPropRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class HostGenerateTokenRequest {
|
class HostGenerateTokenRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -128,7 +128,7 @@ class HostGenerateTokenRequest {
|
|||||||
static Response = JsonString;
|
static Response = JsonString;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class HostConfigCreateRequest {
|
class HostConfigCreateRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -165,7 +165,7 @@ class HostConfigCreateRequest {
|
|||||||
static Response = RawConfig;
|
static Response = RawConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class LogSetSubscriptionsRequest {
|
class LogSetSubscriptionsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -214,7 +214,7 @@ class LogSetSubscriptionsRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class LogQueryRequest {
|
class LogQueryRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -298,7 +298,7 @@ LogQueryRequest.Response = class Response {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class LogMessageEvent {
|
class LogMessageEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = ["host", "controller"];
|
static src = ["host", "controller"];
|
||||||
@@ -331,7 +331,7 @@ class LogMessageEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class DebugDumpWsRequest {
|
class DebugDumpWsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -339,7 +339,7 @@ class DebugDumpWsRequest {
|
|||||||
static permission = "core.debug.dump_ws";
|
static permission = "core.debug.dump_ws";
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class DebugWsMessageEvent {
|
class DebugWsMessageEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
const libSchema = require("../schema");
|
const libSchema = require("../schema");
|
||||||
|
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class Address {
|
class Address {
|
||||||
/** Controller address */
|
/** Controller address */
|
||||||
static controller = 0;
|
static controller = 0;
|
||||||
@@ -44,9 +44,9 @@ class Address {
|
|||||||
* `"allHosts"`: new Address(Address.broadcast, Address.host)
|
* `"allHosts"`: new Address(Address.broadcast, Address.host)
|
||||||
* `"allInstances"`: new Address(Address.broadcast, Address.instance)
|
* `"allInstances"`: new Address(Address.broadcast, Address.instance)
|
||||||
* `"allControls"`: new Address(Address.broadcast, Address.control)
|
* `"allControls"`: new Address(Address.broadcast, Address.control)
|
||||||
* @param {module:lib/data.Address|string|object} shorthand -
|
* @param {module:lib.Address|string|object} shorthand -
|
||||||
* Shorthand to translate with.
|
* Shorthand to translate with.
|
||||||
* @returns {module:lib/data.Address} Translated address.
|
* @returns {module:lib.Address} Translated address.
|
||||||
*/
|
*/
|
||||||
static fromShorthand(shorthand) {
|
static fromShorthand(shorthand) {
|
||||||
if (shorthand instanceof Address) { return shorthand; }
|
if (shorthand instanceof Address) { return shorthand; }
|
||||||
@@ -107,7 +107,7 @@ class Address {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns true if this address targets the given destination
|
* Returns true if this address targets the given destination
|
||||||
* @param {module:lib/Data.Address} dst - Destination to check
|
* @param {module:lib.Address} dst - Destination to check
|
||||||
* @returns {boolean} true if this address is addressed to the given destination
|
* @returns {boolean} true if this address is addressed to the given destination
|
||||||
*/
|
*/
|
||||||
addressedTo(dst) {
|
addressedTo(dst) {
|
||||||
@@ -129,7 +129,7 @@ class Address {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class Message {
|
class Message {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
type;
|
type;
|
||||||
@@ -161,7 +161,7 @@ class Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class HelloData {
|
class HelloData {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
version;
|
version;
|
||||||
@@ -190,9 +190,9 @@ class HelloData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageHello extends Message {
|
class MessageHello extends Message {
|
||||||
/** @type {module:lib/data.HelloData} */
|
/** @type {module:lib.HelloData} */
|
||||||
data;
|
data;
|
||||||
|
|
||||||
constructor(data) {
|
constructor(data) {
|
||||||
@@ -214,7 +214,7 @@ class MessageHello extends Message {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class RegisterHostData {
|
class RegisterHostData {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
token;
|
token;
|
||||||
@@ -263,9 +263,9 @@ class RegisterHostData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageRegisterHost extends Message {
|
class MessageRegisterHost extends Message {
|
||||||
/** @type {module:lib/data.RegisterHostData} */
|
/** @type {module:lib.RegisterHostData} */
|
||||||
data;
|
data;
|
||||||
|
|
||||||
constructor(data) {
|
constructor(data) {
|
||||||
@@ -287,7 +287,7 @@ class MessageRegisterHost extends Message {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class RegisterControlData {
|
class RegisterControlData {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
token;
|
token;
|
||||||
@@ -317,9 +317,9 @@ class RegisterControlData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageRegisterControl extends Message {
|
class MessageRegisterControl extends Message {
|
||||||
/** @type {module:lib/data.RegisterControlData} */
|
/** @type {module:lib.RegisterControlData} */
|
||||||
data;
|
data;
|
||||||
|
|
||||||
constructor(data) {
|
constructor(data) {
|
||||||
@@ -341,7 +341,7 @@ class MessageRegisterControl extends Message {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class AccountDetails {
|
class AccountDetails {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
name;
|
name;
|
||||||
@@ -381,9 +381,9 @@ class AccountDetails {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class ReadyData {
|
class ReadyData {
|
||||||
/** @type {module:lib/data.Address} */
|
/** @type {module:lib.Address} */
|
||||||
src;
|
src;
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
sessionToken;
|
sessionToken;
|
||||||
@@ -427,9 +427,9 @@ class ReadyData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageReady extends Message {
|
class MessageReady extends Message {
|
||||||
/** @type {module:lib/data.ReadyData} */
|
/** @type {module:lib.ReadyData} */
|
||||||
data;
|
data;
|
||||||
|
|
||||||
constructor(data) {
|
constructor(data) {
|
||||||
@@ -451,7 +451,7 @@ class MessageReady extends Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class ResumeData {
|
class ResumeData {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
sessionToken;
|
sessionToken;
|
||||||
@@ -478,9 +478,9 @@ class ResumeData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageResume extends Message {
|
class MessageResume extends Message {
|
||||||
/** @type {module:lib/data.ResumeData} */
|
/** @type {module:lib.ResumeData} */
|
||||||
data;
|
data;
|
||||||
|
|
||||||
constructor(data) {
|
constructor(data) {
|
||||||
@@ -502,7 +502,7 @@ class MessageResume extends Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class ContinueData {
|
class ContinueData {
|
||||||
/** @type {number} */
|
/** @type {number} */
|
||||||
sessionTimeout;
|
sessionTimeout;
|
||||||
@@ -532,9 +532,9 @@ class ContinueData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageContinue extends Message {
|
class MessageContinue extends Message {
|
||||||
/** @type {module:lib/data.ContinueData} */
|
/** @type {module:lib.ContinueData} */
|
||||||
data;
|
data;
|
||||||
|
|
||||||
constructor(data) {
|
constructor(data) {
|
||||||
@@ -556,7 +556,7 @@ class MessageContinue extends Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageInvalidate extends Message {
|
class MessageInvalidate extends Message {
|
||||||
constructor() {
|
constructor() {
|
||||||
super("invalidate");
|
super("invalidate");
|
||||||
@@ -574,7 +574,7 @@ class MessageInvalidate extends Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageHeartbeat extends Message {
|
class MessageHeartbeat extends Message {
|
||||||
/** @type {integer|undefined} */
|
/** @type {integer|undefined} */
|
||||||
seq;
|
seq;
|
||||||
@@ -598,7 +598,7 @@ class MessageHeartbeat extends Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageRequest extends Message {
|
class MessageRequest extends Message {
|
||||||
/** @type {number} */
|
/** @type {number} */
|
||||||
seq;
|
seq;
|
||||||
@@ -644,7 +644,7 @@ class MessageRequest extends Message {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageResponse extends Message {
|
class MessageResponse extends Message {
|
||||||
/** @type {number} */
|
/** @type {number} */
|
||||||
seq;
|
seq;
|
||||||
@@ -685,7 +685,7 @@ class MessageResponse extends Message {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class ResponseError {
|
class ResponseError {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
message;
|
message;
|
||||||
@@ -715,7 +715,7 @@ class ResponseError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageResponseError extends Message {
|
class MessageResponseError extends Message {
|
||||||
/** @type {number} */
|
/** @type {number} */
|
||||||
seq;
|
seq;
|
||||||
@@ -723,7 +723,7 @@ class MessageResponseError extends Message {
|
|||||||
src;
|
src;
|
||||||
/** @type {Address} */
|
/** @type {Address} */
|
||||||
dst;
|
dst;
|
||||||
/** @type {module:lib/data.ResponseError} */
|
/** @type {module:lib.ResponseError} */
|
||||||
data;
|
data;
|
||||||
|
|
||||||
constructor(seq, src, dst, data) {
|
constructor(seq, src, dst, data) {
|
||||||
@@ -756,7 +756,7 @@ class MessageResponseError extends Message {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageEvent extends Message {
|
class MessageEvent extends Message {
|
||||||
/** @type {number} */
|
/** @type {number} */
|
||||||
seq;
|
seq;
|
||||||
@@ -802,7 +802,7 @@ class MessageEvent extends Message {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class MessageDisconnect extends Message {
|
class MessageDisconnect extends Message {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
data;
|
data;
|
||||||
@@ -853,7 +853,7 @@ Message.jsonSchema = {
|
|||||||
};
|
};
|
||||||
Message.validate = libSchema.compile(Message.jsonSchema);
|
Message.validate = libSchema.compile(Message.jsonSchema);
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class PingRequest {
|
class PingRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["controller", "host", "control"];
|
static src = ["controller", "host", "control"];
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
const { jsonArray } = require("./composites");
|
const { jsonArray } = require("./composites");
|
||||||
|
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class HostDetails {
|
class HostDetails {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
agent;
|
agent;
|
||||||
@@ -44,7 +44,7 @@ class HostDetails {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class HostListRequest {
|
class HostListRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -53,7 +53,7 @@ class HostListRequest {
|
|||||||
static Response = jsonArray(HostDetails);
|
static Response = jsonArray(HostDetails);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class HostSetSubscriptionsRequest {
|
class HostSetSubscriptionsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -88,13 +88,13 @@ class HostSetSubscriptionsRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class HostUpdateEvent {
|
class HostUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
static dst = "control";
|
static dst = "control";
|
||||||
|
|
||||||
/** @type {module:lib/data.HostDetails} */
|
/** @type {module:lib.HostDetails} */
|
||||||
update;
|
update;
|
||||||
|
|
||||||
constructor(update) {
|
constructor(update) {
|
||||||
@@ -114,7 +114,7 @@ class HostUpdateEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class HostMetricsRequest {
|
class HostMetricsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -143,7 +143,7 @@ HostMetricsRequest.Response = class Response { // TODO: Use JSON class pattern i
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class ControllerConnectionEvent {
|
class ControllerConnectionEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "host";
|
static src = "host";
|
||||||
@@ -169,14 +169,14 @@ class ControllerConnectionEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class PrepareControllerDisconnectRequest {
|
class PrepareControllerDisconnectRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "host";
|
static src = "host";
|
||||||
static dst = "instance";
|
static dst = "instance";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class SyncUserListsEvent {
|
class SyncUserListsEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
const PlayerStats = require("../PlayerStats");
|
const PlayerStats = require("../PlayerStats");
|
||||||
const { JsonString, jsonArray } = require("./composites");
|
const { JsonString, jsonArray } = require("./composites");
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDetails {
|
class InstanceDetails {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
name;
|
name;
|
||||||
@@ -43,7 +43,7 @@ class InstanceDetails {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDetailsGetRequest {
|
class InstanceDetailsGetRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -72,7 +72,7 @@ class InstanceDetailsGetRequest {
|
|||||||
static Response = InstanceDetails;
|
static Response = InstanceDetails;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDetailsListRequest {
|
class InstanceDetailsListRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -81,7 +81,7 @@ class InstanceDetailsListRequest {
|
|||||||
static Response = jsonArray(InstanceDetails);
|
static Response = jsonArray(InstanceDetails);
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDetailsSetSubscriptionsRequest {
|
class InstanceDetailsSetSubscriptionsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -115,13 +115,13 @@ class InstanceDetailsSetSubscriptionsRequest {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDetailsUpdateEvent {
|
class InstanceDetailsUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
static dst = "control";
|
static dst = "control";
|
||||||
|
|
||||||
/** @type {module:lib/data.InstanceDetails} */
|
/** @type {module:lib.InstanceDetails} */
|
||||||
details;
|
details;
|
||||||
|
|
||||||
constructor(details) {
|
constructor(details) {
|
||||||
@@ -139,7 +139,7 @@ class InstanceDetailsUpdateEvent {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceCreateRequest {
|
class InstanceCreateRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -167,7 +167,7 @@ class InstanceCreateRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceConfigGetRequest {
|
class InstanceConfigGetRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -215,7 +215,7 @@ InstanceConfigGetRequest.Response = class Response {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceConfigSetFieldRequest {
|
class InstanceConfigSetFieldRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -250,7 +250,7 @@ class InstanceConfigSetFieldRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceConfigSetPropRequest {
|
class InstanceConfigSetPropRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -291,7 +291,7 @@ class InstanceConfigSetPropRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceAssignRequest {
|
class InstanceAssignRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -322,7 +322,7 @@ class InstanceAssignRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceMetricsRequest {
|
class InstanceMetricsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "host";
|
static src = "host";
|
||||||
@@ -351,7 +351,7 @@ InstanceMetricsRequest.Response = class Response { // TODO: Use JSON class patte
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceStartRequest {
|
class InstanceStartRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["control", "controller"];
|
static src = ["control", "controller"];
|
||||||
@@ -377,7 +377,7 @@ class InstanceStartRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class SaveDetails {
|
class SaveDetails {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
type;
|
type;
|
||||||
@@ -419,7 +419,7 @@ class SaveDetails {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceListSavesRequest {
|
class InstanceListSavesRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -428,7 +428,7 @@ class InstanceListSavesRequest {
|
|||||||
static Response = jsonArray(SaveDetails);
|
static Response = jsonArray(SaveDetails);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceSetSaveListSubscriptionsRequest {
|
class InstanceSetSaveListSubscriptionsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -462,7 +462,7 @@ class InstanceSetSaveListSubscriptionsRequest {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceSaveListUpdateEvent {
|
class InstanceSaveListUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = ["instance", "host", "controller"];
|
static src = ["instance", "host", "controller"];
|
||||||
@@ -470,7 +470,7 @@ class InstanceSaveListUpdateEvent {
|
|||||||
|
|
||||||
/** @type {number} */
|
/** @type {number} */
|
||||||
instanceId;
|
instanceId;
|
||||||
/** @type {module:lib/data.SaveDetails} */
|
/** @type {module:lib.SaveDetails} */
|
||||||
saves;
|
saves;
|
||||||
|
|
||||||
constructor(instanceId, saves) {
|
constructor(instanceId, saves) {
|
||||||
@@ -495,7 +495,7 @@ class InstanceSaveListUpdateEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceCreateSaveRequest {
|
class InstanceCreateSaveRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -534,7 +534,7 @@ class InstanceCreateSaveRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceRenameSaveRequest {
|
class InstanceRenameSaveRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["control", "controller"];
|
static src = ["control", "controller"];
|
||||||
@@ -569,7 +569,7 @@ class InstanceRenameSaveRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceCopySaveRequest {
|
class InstanceCopySaveRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["control", "controller"];
|
static src = ["control", "controller"];
|
||||||
@@ -604,7 +604,7 @@ class InstanceCopySaveRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDeleteSaveRequest {
|
class InstanceDeleteSaveRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["control", "controller"];
|
static src = ["control", "controller"];
|
||||||
@@ -635,7 +635,7 @@ class InstanceDeleteSaveRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDownloadSaveRequest {
|
class InstanceDownloadSaveRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -668,7 +668,7 @@ class InstanceDownloadSaveRequest {
|
|||||||
static Response = JsonString;
|
static Response = JsonString;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceTransferSaveRequest {
|
class InstanceTransferSaveRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["control", "controller"];
|
static src = ["control", "controller"];
|
||||||
@@ -724,7 +724,7 @@ class InstanceTransferSaveRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstancePullSaveRequest {
|
class InstancePullSaveRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -760,7 +760,7 @@ class InstancePullSaveRequest {
|
|||||||
static Response = JsonString;
|
static Response = JsonString;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstancePushSaveRequest {
|
class InstancePushSaveRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -794,7 +794,7 @@ class InstancePushSaveRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceLoadScenarioRequest {
|
class InstanceLoadScenarioRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -833,7 +833,7 @@ class InstanceLoadScenarioRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceExportDataRequest {
|
class InstanceExportDataRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -841,7 +841,7 @@ class InstanceExportDataRequest {
|
|||||||
static permission = "core.instance.export_data";
|
static permission = "core.instance.export_data";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceExtractPlayersRequest {
|
class InstanceExtractPlayersRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -849,7 +849,7 @@ class InstanceExtractPlayersRequest {
|
|||||||
static permission = "core.instance.extract_players";
|
static permission = "core.instance.extract_players";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceStopRequest {
|
class InstanceStopRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -857,7 +857,7 @@ class InstanceStopRequest {
|
|||||||
static permission = "core.instance.stop";
|
static permission = "core.instance.stop";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceKillRequest {
|
class InstanceKillRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -865,7 +865,7 @@ class InstanceKillRequest {
|
|||||||
static permission = "core.instance.kill";
|
static permission = "core.instance.kill";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDeleteRequest {
|
class InstanceDeleteRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -892,7 +892,7 @@ class InstanceDeleteRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDeleteInternalRequest {
|
class InstanceDeleteInternalRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -918,7 +918,7 @@ class InstanceDeleteInternalRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceSendRconRequest {
|
class InstanceSendRconRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -948,7 +948,7 @@ class InstanceSendRconRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO remove this after config refactor
|
// TODO remove this after config refactor
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class RawInstanceInfo {
|
class RawInstanceInfo {
|
||||||
/** @type {object} */
|
/** @type {object} */
|
||||||
config;
|
config;
|
||||||
@@ -977,13 +977,13 @@ class RawInstanceInfo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstancesUpdateRequest {
|
class InstancesUpdateRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "host";
|
static src = "host";
|
||||||
static dst = "controller";
|
static dst = "controller";
|
||||||
|
|
||||||
/** @type {Array<module:lib/data.RawInstanceInfo>} */
|
/** @type {Array<module:lib.RawInstanceInfo>} */
|
||||||
instances;
|
instances;
|
||||||
|
|
||||||
constructor(instances) {
|
constructor(instances) {
|
||||||
@@ -1004,7 +1004,7 @@ class InstancesUpdateRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceAssignInternalRequest {
|
class InstanceAssignInternalRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -1035,7 +1035,7 @@ class InstanceAssignInternalRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceUnassignInternalRequest {
|
class InstanceUnassignInternalRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -1061,7 +1061,7 @@ class InstanceUnassignInternalRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceInitialisedEvent {
|
class InstanceInitialisedEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "instance";
|
static src = "instance";
|
||||||
@@ -1090,7 +1090,7 @@ class InstanceInitialisedEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceStatusChangedEvent {
|
class InstanceStatusChangedEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = ["instance", "host"];
|
static src = ["instance", "host"];
|
||||||
@@ -1129,13 +1129,13 @@ class InstanceStatusChangedEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceDetailsChangedEvent {
|
class InstanceDetailsChangedEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "instance";
|
static src = "instance";
|
||||||
static dst = "controller";
|
static dst = "controller";
|
||||||
|
|
||||||
/** @type {module:lib/data.InstanceDetails} */
|
/** @type {module:lib.InstanceDetails} */
|
||||||
details;
|
details;
|
||||||
|
|
||||||
constructor(details) {
|
constructor(details) {
|
||||||
@@ -1149,7 +1149,7 @@ class InstanceDetailsChangedEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceBanlistUpdateEvent {
|
class InstanceBanlistUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -1185,7 +1185,7 @@ class InstanceBanlistUpdateEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceAdminlistUpdateEvent {
|
class InstanceAdminlistUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -1216,7 +1216,7 @@ class InstanceAdminlistUpdateEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstanceWhitelistUpdateEvent {
|
class InstanceWhitelistUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -1247,7 +1247,7 @@ class InstanceWhitelistUpdateEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class InstancePlayerUpdateEvent {
|
class InstancePlayerUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "instance";
|
static src = "instance";
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ const ModInfo = require("./ModInfo");
|
|||||||
const { jsonArray, JsonString } = require("./composites");
|
const { jsonArray, JsonString } = require("./composites");
|
||||||
|
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModPackGetRequest {
|
class ModPackGetRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["instance", "control"];
|
static src = ["instance", "control"];
|
||||||
@@ -33,7 +33,7 @@ class ModPackGetRequest {
|
|||||||
static Response = ModPack;
|
static Response = ModPack;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModPackGetDefaultRequest {
|
class ModPackGetDefaultRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["instance", "control"];
|
static src = ["instance", "control"];
|
||||||
@@ -42,7 +42,7 @@ class ModPackGetDefaultRequest {
|
|||||||
static Response = ModPack;
|
static Response = ModPack;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModPackListRequest {
|
class ModPackListRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -51,14 +51,14 @@ class ModPackListRequest {
|
|||||||
static Response = jsonArray(ModPack);
|
static Response = jsonArray(ModPack);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @memberof module:lib/data */
|
/** @memberof module:lib */
|
||||||
class ModPackCreateRequest {
|
class ModPackCreateRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
static dst = "controller";
|
static dst = "controller";
|
||||||
static permission = "core.mod_pack.create";
|
static permission = "core.mod_pack.create";
|
||||||
|
|
||||||
/** @type {module:lib/data.ModPack} */
|
/** @type {module:lib.ModPack} */
|
||||||
modPack;
|
modPack;
|
||||||
|
|
||||||
constructor(modPack) {
|
constructor(modPack) {
|
||||||
@@ -78,14 +78,14 @@ class ModPackCreateRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModPackUpdateRequest {
|
class ModPackUpdateRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
static dst = "controller";
|
static dst = "controller";
|
||||||
static permission = "core.mod_pack.update";
|
static permission = "core.mod_pack.update";
|
||||||
|
|
||||||
/** @type {module:lib/data.ModPack} */
|
/** @type {module:lib.ModPack} */
|
||||||
modPack;
|
modPack;
|
||||||
|
|
||||||
constructor(modPack) {
|
constructor(modPack) {
|
||||||
@@ -105,7 +105,7 @@ class ModPackUpdateRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModPackDeleteRequest {
|
class ModPackDeleteRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -132,7 +132,7 @@ class ModPackDeleteRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModPackSetSubscriptionsRequest {
|
class ModPackSetSubscriptionsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -166,7 +166,7 @@ class ModPackSetSubscriptionsRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModGetRequest {
|
class ModGetRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -199,7 +199,7 @@ class ModGetRequest {
|
|||||||
static Response = ModInfo;
|
static Response = ModInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModListRequest {
|
class ModListRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -208,7 +208,7 @@ class ModListRequest {
|
|||||||
static Response = jsonArray(ModInfo);
|
static Response = jsonArray(ModInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModSearchRequest {
|
class ModSearchRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -305,7 +305,7 @@ ModSearchRequest.Response = class Response {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModSetSubscriptionsRequest {
|
class ModSetSubscriptionsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -339,7 +339,7 @@ class ModSetSubscriptionsRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModDownloadRequest {
|
class ModDownloadRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -372,7 +372,7 @@ class ModDownloadRequest {
|
|||||||
static Response = JsonString;
|
static Response = JsonString;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModDeleteRequest {
|
class ModDeleteRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -403,13 +403,13 @@ class ModDeleteRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModPackUpdateEvent {
|
class ModPackUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
static dst = "control";
|
static dst = "control";
|
||||||
|
|
||||||
/** @type {module:lib/data.ModPack} */
|
/** @type {module:lib.ModPack} */
|
||||||
modPack;
|
modPack;
|
||||||
|
|
||||||
constructor(modPack) {
|
constructor(modPack) {
|
||||||
@@ -429,13 +429,13 @@ class ModPackUpdateEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class ModUpdateEvent {
|
class ModUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
static dst = "control";
|
static dst = "control";
|
||||||
|
|
||||||
/** @type {module:lib/data.ModInfo} */
|
/** @type {module:lib.ModInfo} */
|
||||||
mod;
|
mod;
|
||||||
|
|
||||||
constructor(mod) {
|
constructor(mod) {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
const PlayerStats = require("../PlayerStats");
|
const PlayerStats = require("../PlayerStats");
|
||||||
const { jsonArray, JsonNumber } = require("./composites");
|
const { jsonArray, JsonNumber } = require("./composites");
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class RawPermission { // TODO refactor into lib/user.Permission
|
class RawPermission { // TODO refactor into lib/user.Permission
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
name;
|
name;
|
||||||
@@ -32,7 +32,7 @@ class RawPermission { // TODO refactor into lib/user.Permission
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class PermissionListRequest {
|
class PermissionListRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -77,7 +77,7 @@ class RawRole { // TODO refactor into lib/user.Role
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class RoleListRequest {
|
class RoleListRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -86,7 +86,7 @@ class RoleListRequest {
|
|||||||
static Response = jsonArray(RawRole);
|
static Response = jsonArray(RawRole);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class RoleCreateRequest {
|
class RoleCreateRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -126,7 +126,7 @@ class RoleCreateRequest {
|
|||||||
static Response = JsonNumber;
|
static Response = JsonNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class RoleUpdateRequest {
|
class RoleUpdateRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -168,7 +168,7 @@ class RoleUpdateRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class RoleGrantDefaultPermissionsRequest {
|
class RoleGrantDefaultPermissionsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -195,7 +195,7 @@ class RoleGrantDefaultPermissionsRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class RoleDeleteRequest {
|
class RoleDeleteRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -222,7 +222,7 @@ class RoleDeleteRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class RawUser { // TODO refactor into lib/user.User
|
class RawUser { // TODO refactor into lib/user.User
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
name;
|
name;
|
||||||
@@ -240,9 +240,9 @@ class RawUser { // TODO refactor into lib/user.User
|
|||||||
banReason;
|
banReason;
|
||||||
/** @type {boolean|undefined} */
|
/** @type {boolean|undefined} */
|
||||||
isDeleted;
|
isDeleted;
|
||||||
/** @type {module:lib/PlayerStats} */
|
/** @type {module:lib.PlayerStats} */
|
||||||
playerStats;
|
playerStats;
|
||||||
/** @type {Map<number, module:lib/PlayerStats>|undefined} */
|
/** @type {Map<number, module:lib.PlayerStats>|undefined} */
|
||||||
instanceStats;
|
instanceStats;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@@ -321,7 +321,7 @@ class RawUser { // TODO refactor into lib/user.User
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserGetRequest {
|
class UserGetRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -350,7 +350,7 @@ class UserGetRequest {
|
|||||||
static Response = RawUser;
|
static Response = RawUser;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserListRequest {
|
class UserListRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -359,7 +359,7 @@ class UserListRequest {
|
|||||||
static Response = jsonArray(RawUser);
|
static Response = jsonArray(RawUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserSetSubscriptionsRequest {
|
class UserSetSubscriptionsRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -393,7 +393,7 @@ class UserSetSubscriptionsRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserCreateRequest {
|
class UserCreateRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -420,7 +420,7 @@ class UserCreateRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserRevokeTokenRequest {
|
class UserRevokeTokenRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -447,7 +447,7 @@ class UserRevokeTokenRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserUpdateRolesRequest {
|
class UserUpdateRolesRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -481,7 +481,7 @@ class UserUpdateRolesRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserSetAdminRequest {
|
class UserSetAdminRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -516,7 +516,7 @@ class UserSetAdminRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserSetWhitelistedRequest {
|
class UserSetWhitelistedRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -551,7 +551,7 @@ class UserSetWhitelistedRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserSetBannedRequest {
|
class UserSetBannedRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -590,7 +590,7 @@ class UserSetBannedRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserDeleteRequest {
|
class UserDeleteRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = "control";
|
static src = "control";
|
||||||
@@ -618,7 +618,7 @@ class UserDeleteRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class AccountUpdateEvent {
|
class AccountUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
@@ -657,13 +657,13 @@ class AccountUpdateEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @memberof module:lib/data */
|
/* @memberof module:lib */
|
||||||
class UserUpdateEvent {
|
class UserUpdateEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
static dst = "control";
|
static dst = "control";
|
||||||
|
|
||||||
/** @type {module:lib/data.RawUser} */
|
/** @type {module:lib.RawUser} */
|
||||||
user;
|
user;
|
||||||
|
|
||||||
constructor(user) {
|
constructor(user) {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
* number of leading zeros in them.
|
* number of leading zeros in them.
|
||||||
* @param {string} version - string representation of version.
|
* @param {string} version - string representation of version.
|
||||||
* @returns {number} numeric representation.
|
* @returns {number} numeric representation.
|
||||||
* @alias module:lib/data.integerModVersion
|
* @alias module:lib.integerModVersion
|
||||||
*/
|
*/
|
||||||
function integerModVersion(version) {
|
function integerModVersion(version) {
|
||||||
const [major, minor, sub] = version.split(".").map(n => Number.parseInt(n, 10));
|
const [major, minor, sub] = version.split(".").map(n => Number.parseInt(n, 10));
|
||||||
@@ -23,7 +23,7 @@ function integerModVersion(version) {
|
|||||||
* number of leading zeros in them.
|
* number of leading zeros in them.
|
||||||
* @param {string} version - string representation of version.
|
* @param {string} version - string representation of version.
|
||||||
* @returns {number} numeric representation.
|
* @returns {number} numeric representation.
|
||||||
* @alias module:lib/data.integerFactorioVersion
|
* @alias module:lib.integerFactorioVersion
|
||||||
*/
|
*/
|
||||||
function integerFactorioVersion(version) {
|
function integerFactorioVersion(version) {
|
||||||
const [main, major, minor] = version.split(".").map(n => Number.parseInt(n, 10));
|
const [main, major, minor] = version.split(".").map(n => Number.parseInt(n, 10));
|
||||||
@@ -33,7 +33,7 @@ function integerFactorioVersion(version) {
|
|||||||
/**
|
/**
|
||||||
* Matches valid mod versions.
|
* Matches valid mod versions.
|
||||||
* @type {RegExp}
|
* @type {RegExp}
|
||||||
* @alias module:lib/data.modVersionRegExp
|
* @alias module:lib.modVersionRegExp
|
||||||
*/
|
*/
|
||||||
const modVersionRegExp = /^\d+\.\d+\.\d+$/;
|
const modVersionRegExp = /^\d+\.\d+\.\d+$/;
|
||||||
|
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ class ItemDatabase {
|
|||||||
* Create a new item database
|
* Create a new item database
|
||||||
*
|
*
|
||||||
* @param {object|undefined} serialized - An object from a previous call to
|
* @param {object|undefined} serialized - An object from a previous call to
|
||||||
* {@link module:lib/database~ItemDatabase#serialize} to restore the
|
* {@link module:libbase~ItemDatabase#serialize} to restore the
|
||||||
* database from. An empty database will be created if this parameter
|
* database from. An empty database will be created if this parameter
|
||||||
* is left undefined.
|
* is left undefined.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -324,7 +324,7 @@ function readMapSettings(state) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {object} module:lib/factorio.MapExchangeResult
|
* @typedef {object} module:lib.MapExchangeResult
|
||||||
* @property {array} version -
|
* @property {array} version -
|
||||||
* Version of Factorio the string was created with.
|
* Version of Factorio the string was created with.
|
||||||
* @property {object} map_gen_settings -
|
* @property {object} map_gen_settings -
|
||||||
@@ -344,8 +344,8 @@ function readMapSettings(state) {
|
|||||||
* save to set the map gen settings and the map settings for the save.
|
* save to set the map gen settings and the map settings for the save.
|
||||||
*
|
*
|
||||||
* @param {string} exchangeString - Max Exchange String to parse.
|
* @param {string} exchangeString - Max Exchange String to parse.
|
||||||
* @returns {module:lib/factorio.MapExchangeResult} Parsed result.
|
* @returns {module:lib.MapExchangeResult} Parsed result.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
function readMapExchangeString(exchangeString) {
|
function readMapExchangeString(exchangeString) {
|
||||||
exchangeString = exchangeString.replace(/[ \t\n\r]+/g, "");
|
exchangeString = exchangeString.replace(/[ \t\n\r]+/g, "");
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ const libZipOps = require("../zip_ops");
|
|||||||
* the server given, with dependencies generated for all the mods present in
|
* the server given, with dependencies generated for all the mods present in
|
||||||
* the server's mods folder.
|
* the server's mods folder.
|
||||||
*
|
*
|
||||||
* @param {module:lib/factorio.FactorioServer} server -
|
* @param {module:lib.FactorioServer} server -
|
||||||
* The server to generate the export mod for.
|
* The server to generate the export mod for.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
async function generateExportMod(server) {
|
async function generateExportMod(server) {
|
||||||
let dependencies = [];
|
let dependencies = [];
|
||||||
@@ -63,12 +63,12 @@ async function loadZip(server, modVersions, mod) {
|
|||||||
/**
|
/**
|
||||||
* Load the given Factorio file path into a Buffer
|
* Load the given Factorio file path into a Buffer
|
||||||
*
|
*
|
||||||
* @param {module:lib/factorio.FactorioServer} server -
|
* @param {module:lib.FactorioServer} server -
|
||||||
* The server to load the file from.
|
* The server to load the file from.
|
||||||
* @param {Map<string, string>} modVersions - Mapping of mod to version used.
|
* @param {Map<string, string>} modVersions - Mapping of mod to version used.
|
||||||
* @param {string} modPath - Factorio style path to the file to load.
|
* @param {string} modPath - Factorio style path to the file to load.
|
||||||
* @returns {Promise<?Buffer>} The content of the file or null if not found.
|
* @returns {Promise<?Buffer>} The content of the file or null if not found.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -250,14 +250,14 @@ function filterItems(prototypes) {
|
|||||||
* Assembles and packs the icons for the item prototypes given into a single
|
* Assembles and packs the icons for the item prototypes given into a single
|
||||||
* spritesheet and json file with meta data.
|
* spritesheet and json file with meta data.
|
||||||
*
|
*
|
||||||
* @param {module:lib/factorio.FactorioServer} server -
|
* @param {module:lib.FactorioServer} server -
|
||||||
* The server to generate the export mod for.
|
* The server to generate the export mod for.
|
||||||
* @param {Map<string, string>} modVersions -
|
* @param {Map<string, string>} modVersions -
|
||||||
* Mapping of mod name to versions to get icons from.
|
* Mapping of mod name to versions to get icons from.
|
||||||
* @param {Array<Object>} items - Array of item prototypes.
|
* @param {Array<Object>} items - Array of item prototypes.
|
||||||
* @return {Promise<{itemSheet: Jimp, itemData: Map<string,Object>}>}
|
* @return {Promise<{itemSheet: Jimp, itemData: Map<string,Object>}>}
|
||||||
* Item spritesheet and metadata.
|
* Item spritesheet and metadata.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -321,14 +321,14 @@ async function exportItems(server, modVersions, items) {
|
|||||||
* Parses and merges all the locales for the all the mods given through
|
* Parses and merges all the locales for the all the mods given through
|
||||||
* `modVersions` and `modOrder`.
|
* `modVersions` and `modOrder`.
|
||||||
*
|
*
|
||||||
* @param {module:lib/factorio.FactorioServer} server -
|
* @param {module:lib.FactorioServer} server -
|
||||||
* The server to export the locale from.
|
* The server to export the locale from.
|
||||||
* @param {Map<string, string>} modVersions -
|
* @param {Map<string, string>} modVersions -
|
||||||
* Mapping of mod name to version to export locale from.
|
* Mapping of mod name to version to export locale from.
|
||||||
* @param {Array<string>} modOrder - Load order of the mods.
|
* @param {Array<string>} modOrder - Load order of the mods.
|
||||||
* @param {string} languageCode - Language to export locale for.
|
* @param {string} languageCode - Language to export locale for.
|
||||||
* @returns {Promise<Map<string, string>>} merged locale information
|
* @returns {Promise<Map<string, string>>} merged locale information
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -377,10 +377,10 @@ async function exportLocale(server, modVersions, modOrder, languageCode) {
|
|||||||
/**
|
/**
|
||||||
* Export the locale and item icons for the given factorio server
|
* Export the locale and item icons for the given factorio server
|
||||||
*
|
*
|
||||||
* @param {module:lib/factorio.FactorioServer} server -
|
* @param {module:lib.FactorioServer} server -
|
||||||
* The server to export the data from.
|
* The server to export the data from.
|
||||||
* @returns {Promise<JSZip>} zip file with exported data.
|
* @returns {Promise<JSZip>} zip file with exported data.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
async function exportData(server) {
|
async function exportData(server) {
|
||||||
await generateExportMod(server);
|
await generateExportMod(server);
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ const knownScenarios = {
|
|||||||
*
|
*
|
||||||
* @param {Object} patchInfo - The patch info files's json content
|
* @param {Object} patchInfo - The patch info files's json content
|
||||||
* @returns {string} Generated control.lua code.
|
* @returns {string} Generated control.lua code.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -77,7 +77,7 @@ function generateLoader(patchInfo) {
|
|||||||
* their dependents. Throws an error if this is not possible.
|
* their dependents. Throws an error if this is not possible.
|
||||||
*
|
*
|
||||||
* @param {Array<Object>} modules - Array of modules to reorder
|
* @param {Array<Object>} modules - Array of modules to reorder
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -175,7 +175,7 @@ function reorderDependencies(modules) {
|
|||||||
*
|
*
|
||||||
* @param {string} savePath - Path to the Factorio save to patch.
|
* @param {string} savePath - Path to the Factorio save to patch.
|
||||||
* @param {Array<Object>} modules - Description of the modules to patch.
|
* @param {Array<Object>} modules - Description of the modules to patch.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
async function patch(savePath, modules) {
|
async function patch(savePath, modules) {
|
||||||
let zip = await JSZip.loadAsync(await fs.readFile(savePath));
|
let zip = await JSZip.loadAsync(await fs.readFile(savePath));
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ const { LineSplitter } = require("../stream");
|
|||||||
* reading the changelog.txt in it.
|
* reading the changelog.txt in it.
|
||||||
*
|
*
|
||||||
* @param {string} changelogPath - Path to changelog.txt.
|
* @param {string} changelogPath - Path to changelog.txt.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -55,7 +55,7 @@ async function getVersion(changelogPath) {
|
|||||||
* @param {string} a - Version to compare.
|
* @param {string} a - Version to compare.
|
||||||
* @param {string} b - Version to compare.
|
* @param {string} b - Version to compare.
|
||||||
* @returns {number} 1 if a < b, 0 if a = b and -1 if a > b.
|
* @returns {number} 1 if a < b, 0 if a = b and -1 if a > b.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -87,7 +87,7 @@ function versionOrder(a, b) {
|
|||||||
* Version to look for, supports the special value "latest" for the
|
* Version to look for, supports the special value "latest" for the
|
||||||
* latest version available.
|
* latest version available.
|
||||||
* @returns {Promise<Array>} Array with path to data dir and version found.
|
* @returns {Promise<Array>} Array with path to data dir and version found.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -145,7 +145,7 @@ async function findVersion(factorioDir, targetVersion) {
|
|||||||
* RFC 6335.
|
* RFC 6335.
|
||||||
*
|
*
|
||||||
* @return {number} a number in the range 49152 to 65535.
|
* @return {number} a number in the range 49152 to 65535.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -164,7 +164,7 @@ function randomDynamicPort() {
|
|||||||
*
|
*
|
||||||
* @param {number} length - the length of the password to generate.
|
* @param {number} length - the length of the password to generate.
|
||||||
* @return {Promise<string>} password of the given length
|
* @return {Promise<string>} password of the given length
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -207,7 +207,7 @@ async function generatePassword(length) {
|
|||||||
* @param {string} source - Passed into the output structure as source
|
* @param {string} source - Passed into the output structure as source
|
||||||
*
|
*
|
||||||
* @returns {object} - An object with interpeted data.
|
* @returns {object} - An object with interpeted data.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
@@ -412,7 +412,7 @@ const outputHeuristics = [
|
|||||||
* - save-finished - invoked when the server has finished a manual save
|
* - save-finished - invoked when the server has finished a manual save
|
||||||
* - exit - invoked when the sterver has exited
|
* - exit - invoked when the sterver has exited
|
||||||
* @extends events.EventEmitter
|
* @extends events.EventEmitter
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class FactorioServer extends events.EventEmitter {
|
class FactorioServer extends events.EventEmitter {
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -210,18 +210,18 @@ function wordMatches(word, ...texts) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {object} module:lib/helpers~ParsedTerm
|
* @typedef {object} module:lib~ParsedTerm
|
||||||
* @property {string} type - Type of term, either attribute or word.
|
* @property {string} type - Type of term, either attribute or word.
|
||||||
* @property {string=} name - attribute only: Name of attribute.
|
* @property {string=} name - attribute only: Name of attribute.
|
||||||
* @property {boolean=} exclude - word only: exclude results with this word.
|
* @property {boolean=} exclude - word only: exclude results with this word.
|
||||||
* @property {string | module:lib/helpers.ParsedTerm} value -
|
* @property {string | module:lib.ParsedTerm} value -
|
||||||
* Parsed value of this term. Is a string if type is word, and a
|
* Parsed value of this term. Is a string if type is word, and a
|
||||||
* ParsedTerm if type is attribute.
|
* ParsedTerm if type is attribute.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {object} module:lib/helpers~ParsedSearch
|
* @typedef {object} module:lib~ParsedSearch
|
||||||
* @property {Array<module:lib/helpers~ParsedTerm>} terms -
|
* @property {Array<module:lib~ParsedTerm>} terms -
|
||||||
* Parsed result of search terms.
|
* Parsed result of search terms.
|
||||||
* @property {Array<string>} issues -
|
* @property {Array<string>} issues -
|
||||||
* Issues detected while parsing the seach string.
|
* Issues detected while parsing the seach string.
|
||||||
@@ -248,7 +248,7 @@ function wordMatches(word, ...texts) {
|
|||||||
* @param {Object<string, string>} attributes -
|
* @param {Object<string, string>} attributes -
|
||||||
* Recognized attributes and their format. Currently only word is
|
* Recognized attributes and their format. Currently only word is
|
||||||
* supported.
|
* supported.
|
||||||
* @returns {module:lib/helpers~ParsedSearch} parsed terms of the search.
|
* @returns {module:lib~ParsedSearch} parsed terms of the search.
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
function parseSearchString(input, attributes = {}) {
|
function parseSearchString(input, attributes = {}) {
|
||||||
|
|||||||
+31
-21
@@ -1,3 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* Shared library for Clusterio
|
||||||
|
* @module lib
|
||||||
|
*/
|
||||||
"use strict";
|
"use strict";
|
||||||
const libBuildMod = require("./build_mod");
|
const libBuildMod = require("./build_mod");
|
||||||
const libCommand = require("./command");
|
const libCommand = require("./command");
|
||||||
@@ -9,6 +13,7 @@ const libFactorio = require("./factorio");
|
|||||||
const libFileOps = require("./file_ops");
|
const libFileOps = require("./file_ops");
|
||||||
const libHash = require("./hash");
|
const libHash = require("./hash");
|
||||||
const libHelpers = require("./helpers");
|
const libHelpers = require("./helpers");
|
||||||
|
const libIni = require("./ini");
|
||||||
const libLink = require("./link");
|
const libLink = require("./link");
|
||||||
const libLogging = require("./logging");
|
const libLogging = require("./logging");
|
||||||
const libLoggingUtils = require("./logging_utils");
|
const libLoggingUtils = require("./logging_utils");
|
||||||
@@ -18,36 +23,41 @@ const libPluginLoader = require("./plugin_loader");
|
|||||||
const libPrometheus = require("./prometheus");
|
const libPrometheus = require("./prometheus");
|
||||||
const libSchema = require("./schema");
|
const libSchema = require("./schema");
|
||||||
const libSharedCommands = require("./shared_commands");
|
const libSharedCommands = require("./shared_commands");
|
||||||
|
const libStream = require("./stream");
|
||||||
const libUsers = require("./users");
|
const libUsers = require("./users");
|
||||||
const libZipOps = require("./zip_ops");
|
const libZipOps = require("./zip_ops");
|
||||||
|
|
||||||
const ExponentialBackoff = require("./ExponentialBackoff");
|
const ExponentialBackoff = require("./ExponentialBackoff");
|
||||||
|
const PlayerStats = require("./PlayerStats");
|
||||||
const RateLimiter = require("./RateLimiter");
|
const RateLimiter = require("./RateLimiter");
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
libBuildMod,
|
...libBuildMod,
|
||||||
libCommand,
|
...libCommand,
|
||||||
libConfig,
|
...libConfig,
|
||||||
libData,
|
...libData,
|
||||||
libDatabase,
|
...libDatabase,
|
||||||
libErrors,
|
...libErrors,
|
||||||
libFactorio,
|
...libFactorio,
|
||||||
libFileOps,
|
...libFileOps,
|
||||||
libHash,
|
...libHash,
|
||||||
libHelpers,
|
...libHelpers,
|
||||||
libLink,
|
...libIni,
|
||||||
libLogging,
|
...libLink,
|
||||||
libLoggingUtils,
|
...libLogging,
|
||||||
libLuaTools,
|
...libLoggingUtils,
|
||||||
libPlugin,
|
...libLuaTools,
|
||||||
libPluginLoader,
|
...libPlugin,
|
||||||
libPrometheus,
|
...libPluginLoader,
|
||||||
libSchema,
|
...libPrometheus,
|
||||||
libSharedCommands,
|
...libSchema,
|
||||||
libUsers,
|
...libSharedCommands,
|
||||||
libZipOps,
|
...libStream,
|
||||||
|
...libUsers,
|
||||||
|
...libZipOps,
|
||||||
|
|
||||||
ExponentialBackoff,
|
ExponentialBackoff,
|
||||||
|
PlayerStats,
|
||||||
RateLimiter,
|
RateLimiter,
|
||||||
};
|
};
|
||||||
@@ -15,7 +15,7 @@ const ExponentialBackoff = require("../ExponentialBackoff");
|
|||||||
* Base connector for links
|
* Base connector for links
|
||||||
*
|
*
|
||||||
* @extends events.EventEmitter
|
* @extends events.EventEmitter
|
||||||
* @memberof module:lib/link
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class BaseConnector extends events.EventEmitter {
|
class BaseConnector extends events.EventEmitter {
|
||||||
constructor(src, dst) {
|
constructor(src, dst) {
|
||||||
@@ -76,8 +76,8 @@ class BaseConnector extends events.EventEmitter {
|
|||||||
/**
|
/**
|
||||||
* Base connector for links
|
* Base connector for links
|
||||||
*
|
*
|
||||||
* @extends module:lib/link.BaseConnector
|
* @extends module:lib.BaseConnector
|
||||||
* @memberof module:lib/link
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class WebSocketBaseConnector extends BaseConnector {
|
class WebSocketBaseConnector extends BaseConnector {
|
||||||
constructor(src, dst) {
|
constructor(src, dst) {
|
||||||
@@ -231,7 +231,7 @@ class WebSocketBaseConnector extends BaseConnector {
|
|||||||
* This is a low level method that should only be used for implementing
|
* This is a low level method that should only be used for implementing
|
||||||
* links. See sendTo for sending requests and events.
|
* links. See sendTo for sending requests and events.
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.Message} message - Message to send.
|
* @param {module:lib.Message} message - Message to send.
|
||||||
*/
|
*/
|
||||||
send(message) {
|
send(message) {
|
||||||
if (!["connected", "resuming"].includes(this._state)) {
|
if (!["connected", "resuming"].includes(this._state)) {
|
||||||
@@ -313,8 +313,8 @@ class WebSocketBaseConnector extends BaseConnector {
|
|||||||
/**
|
/**
|
||||||
* Connector for controller clients
|
* Connector for controller clients
|
||||||
*
|
*
|
||||||
* @extends module:lib/link.WebSocketBaseConnector
|
* @extends module:lib.WebSocketBaseConnector
|
||||||
* @memberof module:lib/link
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class WebSocketClientConnector extends WebSocketBaseConnector {
|
class WebSocketClientConnector extends WebSocketBaseConnector {
|
||||||
constructor(url, maxReconnectDelay, tlsCa = null) {
|
constructor(url, maxReconnectDelay, tlsCa = null) {
|
||||||
@@ -360,7 +360,7 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
|
|||||||
* Used in the register function in order to send the handshake messages
|
* Used in the register function in order to send the handshake messages
|
||||||
* over the WebSocket.
|
* over the WebSocket.
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.Message} message - Message to send.
|
* @param {module:lib.Message} message - Message to send.
|
||||||
*/
|
*/
|
||||||
sendHandshake(message) {
|
sendHandshake(message) {
|
||||||
this._check("connecting", "resuming");
|
this._check("connecting", "resuming");
|
||||||
@@ -647,7 +647,7 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
|
|||||||
* Connector for in-memory local links
|
* Connector for in-memory local links
|
||||||
*
|
*
|
||||||
* @extends events.EventEmitter
|
* @extends events.EventEmitter
|
||||||
* @memberof module:lib/link
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class VirtualConnector extends BaseConnector {
|
class VirtualConnector extends BaseConnector {
|
||||||
constructor(src, dst) {
|
constructor(src, dst) {
|
||||||
@@ -662,8 +662,8 @@ class VirtualConnector extends BaseConnector {
|
|||||||
* Creates two virtual connectors that are liked to each othes such that
|
* Creates two virtual connectors that are liked to each othes such that
|
||||||
* a message sent on one is received by the other.
|
* a message sent on one is received by the other.
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.Address} src - Source for obverse connector
|
* @param {module:lib.Address} src - Source for obverse connector
|
||||||
* @param {module:lib/data.Address} dst - destination for obverse connector
|
* @param {module:lib.Address} dst - destination for obverse connector
|
||||||
* @returns {Array} two virtuarl connectors.
|
* @returns {Array} two virtuarl connectors.
|
||||||
*/
|
*/
|
||||||
static makePair(src, dst) {
|
static makePair(src, dst) {
|
||||||
@@ -677,7 +677,7 @@ class VirtualConnector extends BaseConnector {
|
|||||||
/**
|
/**
|
||||||
* Send a message to the other end of the connector
|
* Send a message to the other end of the connector
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.Message} message - Message type to send.
|
* @param {module:lib.Message} message - Message type to send.
|
||||||
*/
|
*/
|
||||||
send(message) {
|
send(message) {
|
||||||
this.other.emit("message", message);
|
this.other.emit("message", message);
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const { dataClasses } = require("./messages");
|
|||||||
/**
|
/**
|
||||||
* Common interface for server and client connections
|
* Common interface for server and client connections
|
||||||
*
|
*
|
||||||
* @memberof module:lib/link
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class Link {
|
class Link {
|
||||||
constructor(connector) {
|
constructor(connector) {
|
||||||
@@ -95,8 +95,8 @@ class Link {
|
|||||||
* Validates and invokes the handler and/or waiters for a message that has
|
* Validates and invokes the handler and/or waiters for a message that has
|
||||||
* been received. An unhandled message is considered to be an error.
|
* been received. An unhandled message is considered to be an error.
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.Message} message - Message to process.
|
* @param {module:lib.Message} message - Message to process.
|
||||||
* @throws {module:lib/errors.InvalidMessage} if the message is invalid or not handled.
|
* @throws {module:lib.InvalidMessage} if the message is invalid or not handled.
|
||||||
*/
|
*/
|
||||||
_processMessage(message) {
|
_processMessage(message) {
|
||||||
if (!["request", "response", "responseError", "event"].includes(message.type)) {
|
if (!["request", "response", "responseError", "event"].includes(message.type)) {
|
||||||
@@ -149,8 +149,8 @@ class Link {
|
|||||||
*
|
*
|
||||||
* Should be overridden by sub-classes to validate messages received.
|
* Should be overridden by sub-classes to validate messages received.
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.Message} message - Message to check.
|
* @param {module:lib.Message} message - Message to check.
|
||||||
* @throws {module:lib/errors.InvalidMessage} if the message is invalid.
|
* @throws {module:lib.InvalidMessage} if the message is invalid.
|
||||||
*/
|
*/
|
||||||
validateIngress(message) { }
|
validateIngress(message) { }
|
||||||
|
|
||||||
@@ -222,9 +222,9 @@ class Link {
|
|||||||
* Called when an request or event is received by a control connector.
|
* Called when an request or event is received by a control connector.
|
||||||
* Should be overridden by sub-classes to validate messages received.
|
* Should be overridden by sub-classes to validate messages received.
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.Message} message - Message to check.
|
* @param {module:lib.Message} message - Message to check.
|
||||||
* @param {object} entry - Request or Event entry for this Message.
|
* @param {object} entry - Request or Event entry for this Message.
|
||||||
* @throws {module:lib/errors.PermissionError} if unauthorized.
|
* @throws {module:lib.PermissionError} if unauthorized.
|
||||||
*/
|
*/
|
||||||
validatePermission(message, entry) { }
|
validatePermission(message, entry) { }
|
||||||
|
|
||||||
@@ -380,7 +380,7 @@ class Link {
|
|||||||
/**
|
/**
|
||||||
* Send a request or event to the given address
|
* Send a request or event to the given address
|
||||||
*
|
*
|
||||||
* @param {*|module:lib/data.Address} destination - Where to send it
|
* @param {*|module:lib.Address} destination - Where to send it
|
||||||
* @param {*} requestOrEvent - Request or event to send
|
* @param {*} requestOrEvent - Request or event to send
|
||||||
* @returns {Promise<*>|undefined}
|
* @returns {Promise<*>|undefined}
|
||||||
* Promise that resolves to the response if a request was sent or
|
* Promise that resolves to the response if a request was sent or
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ class WebConsoleFormat {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Filter object for logs
|
* Filter object for logs
|
||||||
* @typedef {Object} module:lib/logging~LogFilter
|
* @typedef {Object} module:lib~LogFilter
|
||||||
* @property {string} [maxLevel] -
|
* @property {string} [maxLevel] -
|
||||||
* Maximum log level to include. Higher levels are more verbose.
|
* Maximum log level to include. Higher levels are more verbose.
|
||||||
* @property {boolean} [all] -
|
* @property {boolean} [all] -
|
||||||
@@ -101,7 +101,7 @@ class WebConsoleFormat {
|
|||||||
/**
|
/**
|
||||||
* Create log filter by level and source.
|
* Create log filter by level and source.
|
||||||
*
|
*
|
||||||
* @param {module:lib/logging~LogFilter} filter -
|
* @param {module:lib~LogFilter} filter -
|
||||||
* Filter to filter log entries by.
|
* Filter to filter log entries by.
|
||||||
* @returns {function(object): boolean}
|
* @returns {function(object): boolean}
|
||||||
* filter returning true for log entries that match it.
|
* filter returning true for log entries that match it.
|
||||||
|
|||||||
@@ -188,10 +188,10 @@ class LogIndex {
|
|||||||
*
|
*
|
||||||
* Loads index.json from the given log directy expecting it to contain
|
* Loads index.json from the given log directy expecting it to contain
|
||||||
* data about previously indexed files saved with {@link
|
* data about previously indexed files saved with {@link
|
||||||
* module:lib/logging_utils.LogIndex#save}.
|
* module:lib.LogIndex#save}.
|
||||||
*
|
*
|
||||||
* @param {string} logDirectory - Path to directory to load from.
|
* @param {string} logDirectory - Path to directory to load from.
|
||||||
* @returns {Promise<module:lib/logging_utils.LogIndex>} loaded or created log index.
|
* @returns {Promise<module:lib.LogIndex>} loaded or created log index.
|
||||||
*/
|
*/
|
||||||
static async load(logDirectory) {
|
static async load(logDirectory) {
|
||||||
try {
|
try {
|
||||||
@@ -275,7 +275,7 @@ class LogIndex {
|
|||||||
*
|
*
|
||||||
* @param {string} file -
|
* @param {string} file -
|
||||||
* Name of file in the log directory to check for.
|
* Name of file in the log directory to check for.
|
||||||
* @param {module:lib/logging~LogFilter} filter -
|
* @param {module:lib~LogFilter} filter -
|
||||||
* Filter to check index if file contains entries for.
|
* Filter to check index if file contains entries for.
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
* true if the file may contain entries included by the filter.
|
* true if the file may contain entries included by the filter.
|
||||||
@@ -314,7 +314,7 @@ class LogIndex {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Filter object for querying logs
|
* Filter object for querying logs
|
||||||
* @typedef {Object} module:lib/logging_utils~QueryLogFilter
|
* @typedef {Object} module:lib~QueryLogFilter
|
||||||
* @property {number} [limit=100] - Maximum number of entries to return.
|
* @property {number} [limit=100] - Maximum number of entries to return.
|
||||||
* @property {string} [order="asc"] -
|
* @property {string} [order="asc"] -
|
||||||
* Return entries in ascending ("asc") date order or desceding ("desc")
|
* Return entries in ascending ("asc") date order or desceding ("desc")
|
||||||
@@ -336,9 +336,9 @@ class LogIndex {
|
|||||||
* Query log directory
|
* Query log directory
|
||||||
*
|
*
|
||||||
* @param {string} logDirectory - path to directory with logs.
|
* @param {string} logDirectory - path to directory with logs.
|
||||||
* @param {module:lib/logging_utils~QueryLogFilter} filter -
|
* @param {module:lib~QueryLogFilter} filter -
|
||||||
* Filter to limit logs by.
|
* Filter to limit logs by.
|
||||||
* @param {module:lib/logging_utils.LogIndex=} index -
|
* @param {module:lib.LogIndex=} index -
|
||||||
* Index to speed up query with.
|
* Index to speed up query with.
|
||||||
* @returns {Promise<Array<Object>>} log entries matching the filter
|
* @returns {Promise<Array<Object>>} log entries matching the filter
|
||||||
*/
|
*/
|
||||||
|
|||||||
+16
-16
@@ -9,10 +9,10 @@ const helpers = require("./helpers");
|
|||||||
/**
|
/**
|
||||||
* Conceptual base for controller and instance plugins.
|
* Conceptual base for controller and instance plugins.
|
||||||
* @typedef {
|
* @typedef {
|
||||||
* module:lib/plugin.BaseControllerPlugin
|
* module:lib.BaseControllerPlugin
|
||||||
* |module:lib/plugin.BaseInstancePlugin
|
* |module:lib.BaseInstancePlugin
|
||||||
* |module:lib/plugin.BaseControlPlugin
|
* |module:lib.BaseControlPlugin
|
||||||
* } module:lib/plugin.BasePlugin
|
* } module:lib.BasePlugin
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -77,7 +77,7 @@ 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 {module:lib/config.ConfigGroup} group -
|
* @param {module:lib.ConfigGroup} group -
|
||||||
* The group who's field got changed.
|
* The group who's field got changed.
|
||||||
* @param {string} field - Name of the field that changed.
|
* @param {string} field - Name of the field that changed.
|
||||||
* @param {*} prev - The previous value of the field.
|
* @param {*} prev - The previous value of the field.
|
||||||
@@ -366,7 +366,7 @@ 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 {module:lib/config.ConfigGroup} group -
|
* @param {module:lib.ConfigGroup} group -
|
||||||
* The group who's field got changed.
|
* The group who's field got changed.
|
||||||
* @param {string} field - Name of the field that changed.
|
* @param {string} field - Name of the field that changed.
|
||||||
* @param {*} prev - The previous value of the field.
|
* @param {*} prev - The previous value of the field.
|
||||||
@@ -381,7 +381,7 @@ class BaseControllerPlugin {
|
|||||||
*
|
*
|
||||||
* @param {module:controller/src/InstanceInfo} instance -
|
* @param {module:controller/src/InstanceInfo} instance -
|
||||||
* The instance the config changed on.
|
* The instance the config changed on.
|
||||||
* @param {module:lib/config.ConfigGroup} group -
|
* @param {module:lib.ConfigGroup} group -
|
||||||
* The group who's field got changed.
|
* The group who's field got changed.
|
||||||
* @param {string} field - Name of the field that changed.
|
* @param {string} field - Name of the field that changed.
|
||||||
* @param {*} prev - The previous value of the field.
|
* @param {*} prev - The previous value of the field.
|
||||||
@@ -504,7 +504,7 @@ class BaseControllerPlugin {
|
|||||||
* If the mod pack has been deleted its `.isDeleted` property will be
|
* If the mod pack has been deleted its `.isDeleted` property will be
|
||||||
* true.
|
* true.
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.ModPack} modPack - Mod pack that updated.
|
* @param {module:lib.ModPack} modPack - Mod pack that updated.
|
||||||
*/
|
*/
|
||||||
async onModPackUpdated(modPack) { }
|
async onModPackUpdated(modPack) { }
|
||||||
|
|
||||||
@@ -516,7 +516,7 @@ class BaseControllerPlugin {
|
|||||||
*
|
*
|
||||||
* If a mod has been deleted its `.isDeleted` property will be true.
|
* If a mod has been deleted its `.isDeleted` property will be true.
|
||||||
*
|
*
|
||||||
* @param {module:lib/data.ModInfo} mod - Mod that updated.
|
* @param {module:lib.ModInfo} mod - Mod that updated.
|
||||||
*/
|
*/
|
||||||
async onModUpdated(mod) { }
|
async onModUpdated(mod) { }
|
||||||
|
|
||||||
@@ -601,9 +601,9 @@ class BaseControlPlugin {
|
|||||||
*
|
*
|
||||||
* Invoked by clusterioctl to let plugins add commands. `rootCommand` is
|
* Invoked by clusterioctl to let plugins add commands. `rootCommand` is
|
||||||
* the top level command node which the plugin should add its own {@link
|
* the top level command node which the plugin should add its own {@link
|
||||||
* module:lib/command.CommandTree} to.
|
* module:lib.CommandTree} to.
|
||||||
*
|
*
|
||||||
* @param {module:lib/command.CommandTree} rootCommand -
|
* @param {module:lib.CommandTree} rootCommand -
|
||||||
* Root of the clusterioctl command tree.
|
* Root of the clusterioctl command tree.
|
||||||
*/
|
*/
|
||||||
async addCommands(rootCommand) { }
|
async addCommands(rootCommand) { }
|
||||||
@@ -612,7 +612,7 @@ class BaseControlPlugin {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin supplied login form
|
* Plugin supplied login form
|
||||||
* @typedef {Object} module:lib/plugin~LoginForm
|
* @typedef {Object} module:lib~LoginForm
|
||||||
* @property {string} name -
|
* @property {string} name -
|
||||||
* Internal name of the login form, this should start with the
|
* Internal name of the login form, this should start with the
|
||||||
* plugin name followed by a dot.
|
* plugin name followed by a dot.
|
||||||
@@ -627,7 +627,7 @@ class BaseControlPlugin {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin supplied pages
|
* Plugin supplied pages
|
||||||
* @typedef {Object} module:lib/plugin~Page
|
* @typedef {Object} module:lib~Page
|
||||||
* @property {string} path - URL path to this page.
|
* @property {string} path - URL path to this page.
|
||||||
* @property {string=} sidebarPath -
|
* @property {string=} sidebarPath -
|
||||||
* If present and this path matches one of the pages in the sidebar it
|
* If present and this path matches one of the pages in the sidebar it
|
||||||
@@ -669,7 +669,7 @@ class BaseWebPlugin {
|
|||||||
/**
|
/**
|
||||||
* Control link to the controller, not available until the
|
* Control link to the controller, not available until the
|
||||||
* connect event in onControllerConnectionEvent is signaled.
|
* connect event in onControllerConnectionEvent is signaled.
|
||||||
* @type {?module:lib/link.Link}
|
* @type {?module:lib.Link}
|
||||||
*/
|
*/
|
||||||
this.control = null;
|
this.control = null;
|
||||||
|
|
||||||
@@ -685,14 +685,14 @@ class BaseWebPlugin {
|
|||||||
/**
|
/**
|
||||||
* List of login forms provided by this plugin
|
* List of login forms provided by this plugin
|
||||||
*
|
*
|
||||||
* @type {Array<module:lib/plugin~LoginForm>}
|
* @type {Array<module:lib~LoginForm>}
|
||||||
*/
|
*/
|
||||||
this.loginForms = [];
|
this.loginForms = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* List of pages provided by this plugin
|
* List of pages provided by this plugin
|
||||||
*
|
*
|
||||||
* @type {Array<module:lib/plugin~Page>}
|
* @type {Array<module:lib~Page>}
|
||||||
*/
|
*/
|
||||||
this.pages = [];
|
this.pages = [];
|
||||||
|
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ function loadPluginClass(entrypointName, className, pluginClass, pluginInfo) {
|
|||||||
*
|
*
|
||||||
* @param {Object} pluginInfo -
|
* @param {Object} pluginInfo -
|
||||||
* Plugin info object returned from {@link
|
* Plugin info object returned from {@link
|
||||||
* module:lib/plugin_loader.loadPluginInfos} to load class from.
|
* module:lib.loadPluginInfos} to load class from.
|
||||||
* @returns {Promise<function>} plugin class
|
* @returns {Promise<function>} plugin class
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
@@ -90,7 +90,7 @@ async function loadControllerPluginClass(pluginInfo) {
|
|||||||
*
|
*
|
||||||
* @param {Object} pluginInfo -
|
* @param {Object} pluginInfo -
|
||||||
* Plugin info object returned from {@link
|
* Plugin info object returned from {@link
|
||||||
* module:lib/plugin_loader.loadPluginInfos} to load class from.
|
* module:lib.loadPluginInfos} to load class from.
|
||||||
* @returns {Promise<function>} plugin class
|
* @returns {Promise<function>} plugin class
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
@@ -103,7 +103,7 @@ async function loadInstancePluginClass(pluginInfo) {
|
|||||||
*
|
*
|
||||||
* @param {Object} pluginInfo -
|
* @param {Object} pluginInfo -
|
||||||
* Plugin info object returned from {@link
|
* Plugin info object returned from {@link
|
||||||
* module:lib/plugin_loader.loadPluginInfos} to load class from.
|
* module:lib.loadPluginInfos} to load class from.
|
||||||
* @returns {Promise<function>} plugin class
|
* @returns {Promise<function>} plugin class
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
|
|||||||
+26
-26
@@ -7,13 +7,13 @@
|
|||||||
* metric collections in prom-client.
|
* metric collections in prom-client.
|
||||||
*
|
*
|
||||||
* The ordinary use case of instrumenting a code base should be covered by
|
* The ordinary use case of instrumenting a code base should be covered by
|
||||||
* {@link module:lib/prometheus.Counter}, {@link
|
* {@link module:lib.Counter}, {@link
|
||||||
* module:lib/prometheus.Gauge}, {@link module:lib/prometheus.Histogram} and
|
* module:lib.Gauge}, {@link module:lib.Histogram} and
|
||||||
* {@link module:lib/prometheus.exposition}. See documentation for each of
|
* {@link module:lib.exposition}. See documentation for each of
|
||||||
* the listed interfaces for more information.
|
* the listed interfaces for more information.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const { Counter, exposition } = require("@clusterio/lib/prometheus");
|
* const { Counter, exposition } = require("@clusterio/lib");
|
||||||
*
|
*
|
||||||
* // Collectors are by default registered to the default collector regitry.
|
* // Collectors are by default registered to the default collector regitry.
|
||||||
* const totalRequests = new Counter(
|
* const totalRequests = new Counter(
|
||||||
@@ -42,9 +42,9 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Result from collecting a {@link module:lib/prometheus.Collector}
|
* Result from collecting a {@link module:lib.Collector}
|
||||||
* @typedef {Object} CollectorResult
|
* @typedef {Object} CollectorResult
|
||||||
* @property {module:lib/prometheus.Metric} metric -
|
* @property {module:lib.Metric} metric -
|
||||||
* Metric collected.
|
* Metric collected.
|
||||||
* @property {Map<string, Map<string, number>>} samples -
|
* @property {Map<string, Map<string, number>>} samples -
|
||||||
* Mapping of metric suffix to mapping of label keys to values
|
* Mapping of metric suffix to mapping of label keys to values
|
||||||
@@ -165,7 +165,7 @@ class Metric {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The default registry which collectors are regististered to.
|
* The default registry which collectors are regististered to.
|
||||||
* @type {module:lib/prometheus.CollectorRegistry}
|
* @type {module:lib.CollectorRegistry}
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
let defaultRegistry;
|
let defaultRegistry;
|
||||||
@@ -176,7 +176,7 @@ let defaultRegistry;
|
|||||||
* This servers mostly as a conceptual base for all collectors, the only
|
* This servers mostly as a conceptual base for all collectors, the only
|
||||||
* feature implemented here is registring to the default registry on
|
* feature implemented here is registring to the default registry on
|
||||||
* construction. If you want to implement a custom collector you most
|
* construction. If you want to implement a custom collector you most
|
||||||
* likely want to base it on {@link module:lib/prometheus.LabeledCollector}
|
* likely want to base it on {@link module:lib.LabeledCollector}
|
||||||
* instead.
|
* instead.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
@@ -197,7 +197,7 @@ class Collector {
|
|||||||
/**
|
/**
|
||||||
* Retrieve metric data from this collctor.
|
* Retrieve metric data from this collctor.
|
||||||
*
|
*
|
||||||
* Called by {@link module:lib/prometheus.CollectorRegistry} to gather
|
* Called by {@link module:lib.CollectorRegistry} to gather
|
||||||
* the metric data this Collector exports.
|
* the metric data this Collector exports.
|
||||||
*
|
*
|
||||||
* @returns {*} Async iterator of {@link CollectorResult}.
|
* @returns {*} Async iterator of {@link CollectorResult}.
|
||||||
@@ -318,7 +318,7 @@ function removeMatchingLabels(mapping, labels) {
|
|||||||
* set is a child to the collector that can be retrieved with the .labels()
|
* set is a child to the collector that can be retrieved with the .labels()
|
||||||
* method.
|
* method.
|
||||||
*
|
*
|
||||||
* @extends module:lib/prometheus.Collector
|
* @extends module:lib.Collector
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
class LabeledCollector extends Collector {
|
class LabeledCollector extends Collector {
|
||||||
@@ -341,7 +341,7 @@ class LabeledCollector extends Collector {
|
|||||||
* collected. The collector being collected is passed as the
|
* collected. The collector being collected is passed as the
|
||||||
* argument.
|
* argument.
|
||||||
* @param {
|
* @param {
|
||||||
* function(module:lib/prometheus.LabeledCollector,string)
|
* function(module:lib.LabeledCollector,string)
|
||||||
* } childClass -
|
* } childClass -
|
||||||
* Constructor taking instance of collector and label key as
|
* Constructor taking instance of collector and label key as
|
||||||
* arguments and returns a child instance.
|
* arguments and returns a child instance.
|
||||||
@@ -461,7 +461,7 @@ class LabeledCollector extends Collector {
|
|||||||
/**
|
/**
|
||||||
* Base class for implementing single value per label collectors
|
* Base class for implementing single value per label collectors
|
||||||
*
|
*
|
||||||
* @extends module:lib/prometheus.LabeledCollector
|
* @extends module:lib.LabeledCollector
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
class ValueCollector extends LabeledCollector {
|
class ValueCollector extends LabeledCollector {
|
||||||
@@ -485,8 +485,8 @@ class ValueCollector extends LabeledCollector {
|
|||||||
* argument.
|
* argument.
|
||||||
* @param {
|
* @param {
|
||||||
* function(
|
* function(
|
||||||
* new:module:lib/prometheus.ValueCollectorChild,
|
* new:module:lib.ValueCollectorChild,
|
||||||
* module:lib/prometheus.LabeledCollector,
|
* module:lib.LabeledCollector,
|
||||||
* string
|
* string
|
||||||
* )
|
* )
|
||||||
* } childClass -
|
* } childClass -
|
||||||
@@ -555,7 +555,7 @@ class ValueCollectorChild {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Child counter holding the value for a single label set.
|
* Child counter holding the value for a single label set.
|
||||||
* @extends module:lib/prometheus~ValueCollectorChild
|
* @extends module:lib~ValueCollectorChild
|
||||||
*/
|
*/
|
||||||
class CounterChild extends ValueCollectorChild {
|
class CounterChild extends ValueCollectorChild {
|
||||||
/**
|
/**
|
||||||
@@ -597,7 +597,7 @@ class CounterChild extends ValueCollectorChild {
|
|||||||
*
|
*
|
||||||
* The `totalRequests` counter will register with the default registry and
|
* The `totalRequests` counter will register with the default registry and
|
||||||
* provided exposition is set up (see {@link
|
* provided exposition is set up (see {@link
|
||||||
* module:lib/prometheus.exposition}) the counter will be exported to
|
* module:lib.exposition}) the counter will be exported to
|
||||||
* Prometheus starting out with a value of 0. And that is all there is to
|
* Prometheus starting out with a value of 0. And that is all there is to
|
||||||
* it.
|
* it.
|
||||||
*
|
*
|
||||||
@@ -652,7 +652,7 @@ class CounterChild extends ValueCollectorChild {
|
|||||||
* labels you actually need as resource usage for a metric increases
|
* labels you actually need as resource usage for a metric increases
|
||||||
* exponentially with the number of labels used.
|
* exponentially with the number of labels used.
|
||||||
*
|
*
|
||||||
* @extends module:lib/prometheus.ValueCollector
|
* @extends module:lib.ValueCollector
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
class Counter extends ValueCollector {
|
class Counter extends ValueCollector {
|
||||||
@@ -689,7 +689,7 @@ class Counter extends ValueCollector {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Child gauge holding the value for a single label set.
|
* Child gauge holding the value for a single label set.
|
||||||
* @extends module:lib/prometheus~ValueCollectorChild
|
* @extends module:lib~ValueCollectorChild
|
||||||
*/
|
*/
|
||||||
class GaugeChild extends ValueCollectorChild {
|
class GaugeChild extends ValueCollectorChild {
|
||||||
/**
|
/**
|
||||||
@@ -771,7 +771,7 @@ class GaugeChild extends ValueCollectorChild {
|
|||||||
*
|
*
|
||||||
* The `activeRequests` gauge will register with the default registry and
|
* The `activeRequests` gauge will register with the default registry and
|
||||||
* provided exposition is set up (see {@link
|
* provided exposition is set up (see {@link
|
||||||
* module:lib/prometheus.exposition}) the gauge will be exported to
|
* module:lib.exposition}) the gauge will be exported to
|
||||||
* Prometheus starting out with a value of 0.
|
* Prometheus starting out with a value of 0.
|
||||||
*
|
*
|
||||||
* Sometimes keeping track of the value measured is impractical or
|
* Sometimes keeping track of the value measured is impractical or
|
||||||
@@ -842,7 +842,7 @@ class GaugeChild extends ValueCollectorChild {
|
|||||||
* labels you actually need as resource usage for a metric increases
|
* labels you actually need as resource usage for a metric increases
|
||||||
* exponentially with the number of labels used.
|
* exponentially with the number of labels used.
|
||||||
*
|
*
|
||||||
* @extends module:lib/prometheus.ValueCollector
|
* @extends module:lib.ValueCollector
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
class Gauge extends ValueCollector {
|
class Gauge extends ValueCollector {
|
||||||
@@ -1637,7 +1637,7 @@ async function* expositionLines(resultsIterator) {
|
|||||||
* @param {*} resultsIterator -
|
* @param {*} resultsIterator -
|
||||||
* Asynchronously itreable of {@link CollectorResult} results to create
|
* Asynchronously itreable of {@link CollectorResult} results to create
|
||||||
* exposition for. Defaults to collecting results from {@link
|
* exposition for. Defaults to collecting results from {@link
|
||||||
* module:lib/prometheus.defaultRegistry}.
|
* module:lib.defaultRegistry}.
|
||||||
* @returns {string} Prometheus exposition.
|
* @returns {string} Prometheus exposition.
|
||||||
*
|
*
|
||||||
* @property {string} exposition.contentType
|
* @property {string} exposition.contentType
|
||||||
@@ -1658,10 +1658,10 @@ exposition.contentType = "text/plain; version=0.0.4";
|
|||||||
/**
|
/**
|
||||||
* Serialize CollectorResult into a plain object
|
* Serialize CollectorResult into a plain object
|
||||||
*
|
*
|
||||||
* Converts a {@link module:lib/prometheus~CollectorResult} into a plain
|
* Converts a {@link module:lib~CollectorResult} into a plain
|
||||||
* object form that can be stringified to JSON.
|
* object form that can be stringified to JSON.
|
||||||
*
|
*
|
||||||
* @param {module:lib/prometheus~CollectorResult} result -
|
* @param {module:lib~CollectorResult} result -
|
||||||
* Result to serialize into plain object form.
|
* Result to serialize into plain object form.
|
||||||
* @param {Object} options - Options for controlling the serialization.
|
* @param {Object} options - Options for controlling the serialization.
|
||||||
* @param {string} options.addLabels -
|
* @param {string} options.addLabels -
|
||||||
@@ -1724,10 +1724,10 @@ function serializeResult(result, options = {}) {
|
|||||||
/**
|
/**
|
||||||
* Deserialize CollectorResult from plain object
|
* Deserialize CollectorResult from plain object
|
||||||
*
|
*
|
||||||
* Reverse counterpart to {@link module:lib/prometheus.serializeResult}.
|
* Reverse counterpart to {@link module:lib.serializeResult}.
|
||||||
*
|
*
|
||||||
* @param {Object} serializedResult - Previously serialized result object.
|
* @param {Object} serializedResult - Previously serialized result object.
|
||||||
* @returns {module:lib/prometheus~CollectorResult} deserialized result.
|
* @returns {module:lib~CollectorResult} deserialized result.
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
function deserializeResult(serializedResult) {
|
function deserializeResult(serializedResult) {
|
||||||
@@ -1748,7 +1748,7 @@ function deserializeResult(serializedResult) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Default collectors provided by this library
|
* Default collectors provided by this library
|
||||||
* @type {Object<string, module:lib/prometheus.Collector>}
|
* @type {Object<string, module:lib.Collector>}
|
||||||
*/
|
*/
|
||||||
let defaultCollectors = {};
|
let defaultCollectors = {};
|
||||||
defaultCollectors.processCpuSecondsTotal = new Gauge(
|
defaultCollectors.processCpuSecondsTotal = new Gauge(
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ function configCommand(yargs) {
|
|||||||
* Handle the actions that are made available by configCommand.
|
* Handle the actions that are made available by configCommand.
|
||||||
*
|
*
|
||||||
* @param {Object} args - yargs args object.
|
* @param {Object} args - yargs args object.
|
||||||
* @param {module:lib/config.Config} instance - Config instance.
|
* @param {module:lib.Config} instance - Config instance.
|
||||||
* @param {string} configPath - Path to configuration file.
|
* @param {string} configPath - Path to configuration file.
|
||||||
*/
|
*/
|
||||||
async function handleConfigCommand(args, instance, configPath) {
|
async function handleConfigCommand(args, instance, configPath) {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ const stream = require("stream");
|
|||||||
* let fileStream = fs.createReadStream(path);
|
* let fileStream = fs.createReadStream(path);
|
||||||
* fileStream.pipe(lineStream);
|
* fileStream.pipe(lineStream);
|
||||||
*
|
*
|
||||||
* @memberof module:lib/stream
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class LineSplitter extends stream.Transform {
|
class LineSplitter extends stream.Transform {
|
||||||
constructor(options) {
|
constructor(options) {
|
||||||
@@ -63,7 +63,7 @@ class LineSplitter extends stream.Transform {
|
|||||||
* Transform splitting a reverse stream into lines
|
* Transform splitting a reverse stream into lines
|
||||||
*
|
*
|
||||||
* Splits up a reverse stream of chunks created by {@link
|
* Splits up a reverse stream of chunks created by {@link
|
||||||
* module:lib/stream.createReverseReadStream} by newlines and passes on the
|
* module:lib.createReverseReadStream} by newlines and passes on the
|
||||||
* lines one by one in reverse order removing the line feed and optional
|
* lines one by one in reverse order removing the line feed and optional
|
||||||
* carriage return from the lines.
|
* carriage return from the lines.
|
||||||
*
|
*
|
||||||
@@ -73,7 +73,7 @@ class LineSplitter extends stream.Transform {
|
|||||||
* let revFileStream = await libStream.createReverseReadStream(path);
|
* let revFileStream = await libStream.createReverseReadStream(path);
|
||||||
* revFileStream.pipe(revLineStream);
|
* revFileStream.pipe(revLineStream);
|
||||||
*
|
*
|
||||||
* @memberof module:lib/stream
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
class ReverseLineSplitter extends stream.Transform {
|
class ReverseLineSplitter extends stream.Transform {
|
||||||
constructor(options) {
|
constructor(options) {
|
||||||
@@ -141,7 +141,7 @@ class ReverseLineSplitter extends stream.Transform {
|
|||||||
* @param {object} options -
|
* @param {object} options -
|
||||||
* Options to pass to fs.createReadStream. Values passed for `fd` and
|
* Options to pass to fs.createReadStream. Values passed for `fd` and
|
||||||
* `fs` will be ignored.
|
* `fs` will be ignored.
|
||||||
* @memberof module:lib/stream
|
* @memberof module:lib
|
||||||
*/
|
*/
|
||||||
async function createReverseReadStream(path, options) {
|
async function createReverseReadStream(path, options) {
|
||||||
const fileFd = await fs.open(path, "r");
|
const fileFd = await fs.open(path, "r");
|
||||||
|
|||||||
@@ -100,8 +100,8 @@ class Role {
|
|||||||
*
|
*
|
||||||
* Ensures the role with id 0 exisits and has the core.admin permission.
|
* Ensures the role with id 0 exisits and has the core.admin permission.
|
||||||
*
|
*
|
||||||
* @param {Map<number, module:lib/user.Role>} roles - role storage to modify.
|
* @param {Map<number, module:lib.Role>} roles - role storage to modify.
|
||||||
* @returns {module:lib/permission.Role} the default admin role
|
* @returns {module:lib.Role} the default admin role
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
function ensureDefaultAdminRole(roles) {
|
function ensureDefaultAdminRole(roles) {
|
||||||
@@ -121,7 +121,7 @@ function ensureDefaultAdminRole(roles) {
|
|||||||
* assigned by default. Note that this may not be the same role as the one
|
* assigned by default. Note that this may not be the same role as the one
|
||||||
* that is assigned to new users by default.
|
* that is assigned to new users by default.
|
||||||
*
|
*
|
||||||
* @param {Map<number, module:lib/user.Role>} roles - role storage to modify.
|
* @param {Map<number, module:lib.Role>} roles - role storage to modify.
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
function ensureDefaultPlayerRole(roles) {
|
function ensureDefaultPlayerRole(roles) {
|
||||||
@@ -186,7 +186,7 @@ class User {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Roles this user has
|
* Roles this user has
|
||||||
* @type {Set<module:lib/permissions.Role>}
|
* @type {Set<module:lib.Role>}
|
||||||
*/
|
*/
|
||||||
this.roles = new Set();
|
this.roles = new Set();
|
||||||
if (serializedUser.roles) {
|
if (serializedUser.roles) {
|
||||||
@@ -200,7 +200,7 @@ class User {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Per instance statistics for the player this user account is tied to.
|
* Per instance statistics for the player this user account is tied to.
|
||||||
* @type {Map<number, module:lib/PlayerStats>}
|
* @type {Map<number, module:lib.PlayerStats>}
|
||||||
*/
|
*/
|
||||||
this.instanceStats = new Map(
|
this.instanceStats = new Map(
|
||||||
(serializedUser.instance_stats ? serializedUser.instance_stats : []).map(
|
(serializedUser.instance_stats ? serializedUser.instance_stats : []).map(
|
||||||
@@ -210,7 +210,7 @@ class User {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Combined statistics for the player this user account is tied to.
|
* Combined statistics for the player this user account is tied to.
|
||||||
* @type {module:lib/PlayerStats}
|
* @type {module:lib.PlayerStats}
|
||||||
*/
|
*/
|
||||||
this.playerStats = this._calculatePlayerStats();
|
this.playerStats = this._calculatePlayerStats();
|
||||||
|
|
||||||
@@ -286,7 +286,7 @@ class User {
|
|||||||
*
|
*
|
||||||
* @param {string} permission - The permission to check for.
|
* @param {string} permission - The permission to check for.
|
||||||
* @throws {Error} If the given permission does not exist.
|
* @throws {Error} If the given permission does not exist.
|
||||||
* @throws {module:lib/errors.PermissionError} if the user does noh have the given permission.
|
* @throws {module:lib.PermissionError} if the user does noh have the given permission.
|
||||||
*/
|
*/
|
||||||
checkPermission(permission) {
|
checkPermission(permission) {
|
||||||
if (!permissions.has(permission)) {
|
if (!permissions.has(permission)) {
|
||||||
@@ -336,7 +336,7 @@ class User {
|
|||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Set of users currently online in the cluster.
|
* Set of users currently online in the cluster.
|
||||||
* @type {module:lib/users.User}
|
* @type {module:lib.User}
|
||||||
*/
|
*/
|
||||||
User.onlineUsers = new Set();
|
User.onlineUsers = new Set();
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
*
|
*
|
||||||
* @param {JSZip} zip - Zip to search through.
|
* @param {JSZip} zip - Zip to search through.
|
||||||
* @returns {string} name of the root folder.
|
* @returns {string} name of the root folder.
|
||||||
* @memberof module:lib/factorio
|
* @memberof module:lib
|
||||||
* @private
|
* @private
|
||||||
* @inner
|
* @inner
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ import "./index.css";
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { createRoot } from "react-dom/client";
|
import { createRoot } from "react-dom/client";
|
||||||
|
|
||||||
import { libConfig, libLink, libLogging, libPlugin } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { ConsoleTransport, WebConsoleFormat, logger } = libLogging;
|
|
||||||
|
|
||||||
import App from "./components/App";
|
import App from "./components/App";
|
||||||
import { Control, ControlConnector } from "./util/websocket";
|
import { Control, ControlConnector } from "./util/websocket";
|
||||||
|
|
||||||
|
const { ConsoleTransport, WebConsoleFormat, logger } = lib;
|
||||||
|
|
||||||
async function loadScript(url) {
|
async function loadScript(url) {
|
||||||
let script = document.createElement("script");
|
let script = document.createElement("script");
|
||||||
@@ -73,7 +73,7 @@ async function loadPlugins(pluginInfos) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
let WebPluginClass = libPlugin.BaseWebPlugin;
|
let WebPluginClass = lib.BaseWebPlugin;
|
||||||
if (pluginInfo.webEntrypoint) {
|
if (pluginInfo.webEntrypoint) {
|
||||||
let webModule = (await pluginInfo.container.get(pluginInfo.webEntrypoint))();
|
let webModule = (await pluginInfo.container.get(pluginInfo.webEntrypoint))();
|
||||||
if (!webModule.WebPlugin) {
|
if (!webModule.WebPlugin) {
|
||||||
@@ -102,9 +102,9 @@ export default async function bootstrap() {
|
|||||||
format: new WebConsoleFormat(),
|
format: new WebConsoleFormat(),
|
||||||
}));
|
}));
|
||||||
let pluginInfos = await loadPluginInfos();
|
let pluginInfos = await loadPluginInfos();
|
||||||
libLink.registerPluginMessages(pluginInfos);
|
lib.registerPluginMessages(pluginInfos);
|
||||||
libConfig.registerPluginConfigGroups(pluginInfos);
|
lib.registerPluginConfigGroups(pluginInfos);
|
||||||
libConfig.finalizeConfigs();
|
lib.finalizeConfigs();
|
||||||
let plugins = await loadPlugins(pluginInfos);
|
let plugins = await loadPlugins(pluginInfos);
|
||||||
|
|
||||||
let wsUrl = new URL(window.webRoot, document.location);
|
let wsUrl = new URL(window.webRoot, document.location);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { BrowserRouter } from "react-router-dom";
|
import { BrowserRouter } from "react-router-dom";
|
||||||
|
|
||||||
import { libLogging } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import ErrorBoundary from "./ErrorBoundary";
|
import ErrorBoundary from "./ErrorBoundary";
|
||||||
import SiteLayout from "./SiteLayout";
|
import SiteLayout from "./SiteLayout";
|
||||||
@@ -11,7 +11,6 @@ import LoginForm from "./LoginForm";
|
|||||||
import { Card, ConfigProvider, Spin, Typography, theme } from "antd";
|
import { Card, ConfigProvider, Spin, Typography, theme } from "antd";
|
||||||
|
|
||||||
const { Paragraph } = Typography;
|
const { Paragraph } = Typography;
|
||||||
const { logger } = libLogging;
|
|
||||||
|
|
||||||
|
|
||||||
function ErrorCard(props) {
|
function ErrorCard(props) {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useContext, useState } from "react";
|
import React, { useContext, useState } from "react";
|
||||||
import { Button, Form, Modal, Select, Typography } from "antd";
|
import { Button, Form, Modal, Select, Typography } from "antd";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
@@ -30,7 +30,7 @@ export default function AssignInstanceModal(props) {
|
|||||||
|
|
||||||
setApplying(true);
|
setApplying(true);
|
||||||
control.send(
|
control.send(
|
||||||
new libData.InstanceAssignRequest(props.id, hostId)
|
new lib.InstanceAssignRequest(props.id, hostId)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
if (props.onFinish) {
|
if (props.onFinish) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { useContext } from "react";
|
import React, { useContext } from "react";
|
||||||
|
|
||||||
import { libConfig, libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import BaseConfigTree from "./BaseConfigTree";
|
import BaseConfigTree from "./BaseConfigTree";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -10,12 +10,12 @@ export default function ControllerConfigTree(props) {
|
|||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
|
|
||||||
async function retrieveConfig() {
|
async function retrieveConfig() {
|
||||||
let result = await control.send(new libData.ControllerConfigGetRequest());
|
let result = await control.send(new lib.ControllerConfigGetRequest());
|
||||||
return result.serializedConfig;
|
return result.serializedConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setField(field, value) {
|
async function setField(field, value) {
|
||||||
await control.send(new libData.ControllerConfigSetFieldRequest(
|
await control.send(new lib.ControllerConfigSetFieldRequest(
|
||||||
field,
|
field,
|
||||||
String(value),
|
String(value),
|
||||||
));
|
));
|
||||||
@@ -29,11 +29,11 @@ export default function ControllerConfigTree(props) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await control.send(new libData.ControllerConfigSetPropRequest(field, prop, value));
|
await control.send(new lib.ControllerConfigSetPropRequest(field, prop, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
return <BaseConfigTree
|
return <BaseConfigTree
|
||||||
ConfigClass={libConfig.ControllerConfig}
|
ConfigClass={lib.ControllerConfig}
|
||||||
retrieveConfig={retrieveConfig}
|
retrieveConfig={retrieveConfig}
|
||||||
setField={setField}
|
setField={setField}
|
||||||
setProp={setProp}
|
setProp={setProp}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useContext, useState } from "react";
|
import React, { useContext, useState } from "react";
|
||||||
import { Button, Form, Input, Modal } from "antd";
|
import { Button, Form, Input, Modal } from "antd";
|
||||||
|
|
||||||
import { libFactorio, libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
@@ -22,7 +22,7 @@ export default function CreateSaveModal(props) {
|
|||||||
if (values.exchangeString && values.exchangeString.trim()) {
|
if (values.exchangeString && values.exchangeString.trim()) {
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = libFactorio.readMapExchangeString(values.exchangeString);
|
result = lib.readMapExchangeString(values.exchangeString);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
@@ -53,7 +53,7 @@ export default function CreateSaveModal(props) {
|
|||||||
setCreatingSave(true);
|
setCreatingSave(true);
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId: props.instance.id },
|
{ instanceId: props.instance.id },
|
||||||
new libData.InstanceCreateSaveRequest(name, seed, mapGenSettings, mapSettings),
|
new lib.InstanceCreateSaveRequest(name, seed, mapGenSettings, mapSettings),
|
||||||
).then(() => {
|
).then(() => {
|
||||||
form.resetFields();
|
form.resetFields();
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
@@ -68,7 +68,7 @@ export default function CreateSaveModal(props) {
|
|||||||
let exchangeString = form.getFieldValue("exchangeString");
|
let exchangeString = form.getFieldValue("exchangeString");
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = libFactorio.readMapExchangeString(exchangeString);
|
result = lib.readMapExchangeString(exchangeString);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { useNavigate } from "react-router-dom";
|
|||||||
import { Button, Form, InputNumber, Modal, Table, Tag, Typography } from "antd";
|
import { Button, Form, InputNumber, Modal, Table, Tag, Typography } from "antd";
|
||||||
import CopyOutlined from "@ant-design/icons/lib/icons/CopyOutlined";
|
import CopyOutlined from "@ant-design/icons/lib/icons/CopyOutlined";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -47,7 +47,7 @@ function GenerateHostTokenButton(props) {
|
|||||||
form.setFields([{ name: "hostId", errors: [] }]);
|
form.setFields([{ name: "hostId", errors: [] }]);
|
||||||
}
|
}
|
||||||
|
|
||||||
let newToken = await control.send(new libData.HostGenerateTokenRequest(id));
|
let newToken = await control.send(new lib.HostGenerateTokenRequest(id));
|
||||||
setToken(newToken);
|
setToken(newToken);
|
||||||
setHostId(id);
|
setHostId(id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { useContext } from "react";
|
import React, { useContext } from "react";
|
||||||
|
|
||||||
import { libConfig, libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import BaseConfigTree from "./BaseConfigTree";
|
import BaseConfigTree from "./BaseConfigTree";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -10,12 +10,12 @@ export default function InstanceConfigTree(props) {
|
|||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
|
|
||||||
async function retrieveConfig() {
|
async function retrieveConfig() {
|
||||||
let result = await control.send(new libData.InstanceConfigGetRequest(props.id));
|
let result = await control.send(new lib.InstanceConfigGetRequest(props.id));
|
||||||
return result.config;
|
return result.config;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setField(field, value) {
|
async function setField(field, value) {
|
||||||
await control.send(new libData.InstanceConfigSetFieldRequest(props.id, field, value));
|
await control.send(new lib.InstanceConfigSetFieldRequest(props.id, field, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setProp(field, prop, value) {
|
async function setProp(field, prop, value) {
|
||||||
@@ -26,11 +26,11 @@ export default function InstanceConfigTree(props) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await control.send(new libData.InstanceConfigSetPropRequest(props.id, field, prop, value));
|
await control.send(new lib.InstanceConfigSetPropRequest(props.id, field, prop, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
return <BaseConfigTree
|
return <BaseConfigTree
|
||||||
ConfigClass={libConfig.InstanceConfig}
|
ConfigClass={lib.InstanceConfig}
|
||||||
retrieveConfig={retrieveConfig}
|
retrieveConfig={retrieveConfig}
|
||||||
setField={setField}
|
setField={setField}
|
||||||
setProp={setProp}
|
setProp={setProp}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useContext, useState } from "react";
|
import React, { useContext, useState } from "react";
|
||||||
import { Input, Typography } from "antd";
|
import { Input, Typography } from "antd";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
@@ -24,7 +24,7 @@ export default function InstanceRcon(props) {
|
|||||||
try {
|
try {
|
||||||
let result = await control.sendTo(
|
let result = await control.sendTo(
|
||||||
{ instanceId: props.id },
|
{ instanceId: props.id },
|
||||||
new libData.InstanceSendRconRequest(command),
|
new lib.InstanceSendRconRequest(command),
|
||||||
);
|
);
|
||||||
setOutput(result);
|
setOutput(result);
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { Alert, Button, Descriptions, Dropdown, Menu, Modal, Space, Spin, Typogr
|
|||||||
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
||||||
import DownOutlined from "@ant-design/icons/DownOutlined";
|
import DownOutlined from "@ant-design/icons/DownOutlined";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -134,7 +134,7 @@ export default function InstanceViewPage(props) {
|
|||||||
setExportingData(true);
|
setExportingData(true);
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId },
|
{ instanceId },
|
||||||
new libData.InstanceExportDataRequest(),
|
new lib.InstanceExportDataRequest(),
|
||||||
).catch(
|
).catch(
|
||||||
notifyErrorHandler("Error exporting data")
|
notifyErrorHandler("Error exporting data")
|
||||||
).finally(() => {
|
).finally(() => {
|
||||||
@@ -144,13 +144,13 @@ export default function InstanceViewPage(props) {
|
|||||||
} else if (key === "extract") {
|
} else if (key === "extract") {
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId },
|
{ instanceId },
|
||||||
new libData.InstanceExtractPlayersRequest(),
|
new lib.InstanceExtractPlayersRequest(),
|
||||||
).catch(notifyErrorHandler("Error extracting player data"));
|
).catch(notifyErrorHandler("Error extracting player data"));
|
||||||
|
|
||||||
} else if (key === "kill") {
|
} else if (key === "kill") {
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId },
|
{ instanceId },
|
||||||
new libData.InstanceKillRequest(),
|
new lib.InstanceKillRequest(),
|
||||||
).catch(notifyErrorHandler("Error killing instance"));
|
).catch(notifyErrorHandler("Error killing instance"));
|
||||||
|
|
||||||
} else if (key === "delete") {
|
} else if (key === "delete") {
|
||||||
@@ -161,7 +161,7 @@ export default function InstanceViewPage(props) {
|
|||||||
okButtonProps: { danger: true },
|
okButtonProps: { danger: true },
|
||||||
onOk: () => {
|
onOk: () => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.InstanceDeleteRequest(instanceId)
|
new lib.InstanceDeleteRequest(instanceId)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
navigate("/instances");
|
navigate("/instances");
|
||||||
}).catch(notifyErrorHandler("Error deleting instance"));
|
}).catch(notifyErrorHandler("Error deleting instance"));
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { useContext, useState } from "react";
|
|||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { Button, Form, Input, Modal } from "antd";
|
import { Button, Form, Input, Modal } from "antd";
|
||||||
|
|
||||||
import { libConfig, libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -26,11 +26,11 @@ function CreateInstanceButton(props) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let instanceConfig = new libConfig.InstanceConfig("control");
|
let instanceConfig = new lib.InstanceConfig("control");
|
||||||
await instanceConfig.init();
|
await instanceConfig.init();
|
||||||
instanceConfig.set("instance.name", values.instanceName);
|
instanceConfig.set("instance.name", values.instanceName);
|
||||||
let serializedConfig = instanceConfig.serialize("controller");
|
let serializedConfig = instanceConfig.serialize("controller");
|
||||||
await control.send(new libData.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`);
|
||||||
}
|
}
|
||||||
@@ -73,7 +73,7 @@ export default function InstancesPage() {
|
|||||||
&& <Button onClick={e => instanceList.forEach(instance => {
|
&& <Button onClick={e => instanceList.forEach(instance => {
|
||||||
if (instance.status === "stopped") {
|
if (instance.status === "stopped") {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.InstanceStartRequest(undefined), { instanceId: instance.id }
|
new lib.InstanceStartRequest(undefined), { instanceId: instance.id }
|
||||||
).catch(notifyErrorHandler("Error starting instance"));
|
).catch(notifyErrorHandler("Error starting instance"));
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -85,7 +85,7 @@ export default function InstancesPage() {
|
|||||||
if (["starting", "running"].includes(instance.status)) {
|
if (["starting", "running"].includes(instance.status)) {
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId: instance.id },
|
{ instanceId: instance.id },
|
||||||
new libData.InstanceStopRequest(),
|
new lib.InstanceStopRequest(),
|
||||||
).catch(notifyErrorHandler("Error stopping instance"));
|
).catch(notifyErrorHandler("Error stopping instance"));
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useContext, useState } from "react";
|
import React, { useContext, useState } from "react";
|
||||||
import { Button, Form, Input, Modal } from "antd";
|
import { Button, Form, Input, Modal } from "antd";
|
||||||
|
|
||||||
import { libFactorio, libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
@@ -22,7 +22,7 @@ export default function LoadScenarioModal(props) {
|
|||||||
if (values.exchangeString && values.exchangeString.trim()) {
|
if (values.exchangeString && values.exchangeString.trim()) {
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = libFactorio.readMapExchangeString(values.exchangeString);
|
result = lib.readMapExchangeString(values.exchangeString);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
@@ -53,7 +53,7 @@ export default function LoadScenarioModal(props) {
|
|||||||
setLoadingScenario(true);
|
setLoadingScenario(true);
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId: props.instance.id },
|
{ instanceId: props.instance.id },
|
||||||
new libData.InstanceLoadScenarioRequest(scenario, seed, mapGenSettings, mapSettings),
|
new lib.InstanceLoadScenarioRequest(scenario, seed, mapGenSettings, mapSettings),
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
}).catch(
|
}).catch(
|
||||||
@@ -67,7 +67,7 @@ export default function LoadScenarioModal(props) {
|
|||||||
let exchangeString = form.getFieldValue("exchangeString");
|
let exchangeString = form.getFieldValue("exchangeString");
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = libFactorio.readMapExchangeString(exchangeString);
|
result = lib.readMapExchangeString(exchangeString);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useEffect, useContext, useRef, useState } from "react";
|
import React, { useEffect, useContext, useRef, useState } from "react";
|
||||||
import { Typography } from "antd";
|
import { Typography } from "antd";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -70,7 +70,7 @@ export default function LogConsole(props) {
|
|||||||
|
|
||||||
if (account.hasPermission("core.log.query")) {
|
if (account.hasPermission("core.log.query")) {
|
||||||
setPastLines([<span key={0}>{"Loading past entries..."}<br/></span>]);
|
setPastLines([<span key={0}>{"Loading past entries..."}<br/></span>]);
|
||||||
control.send(new libData.LogQueryRequest(
|
control.send(new lib.LogQueryRequest(
|
||||||
logFilter.all,
|
logFilter.all,
|
||||||
logFilter.controller,
|
logFilter.controller,
|
||||||
logFilter.hostIds,
|
logFilter.hostIds,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { Fragment } from "react";
|
|||||||
import { Descriptions, Grid, Typography } from "antd";
|
import { Descriptions, Grid, Typography } from "antd";
|
||||||
import ExclamationCircleOutlined from "@ant-design/icons/ExclamationCircleOutlined";
|
import ExclamationCircleOutlined from "@ant-design/icons/ExclamationCircleOutlined";
|
||||||
|
|
||||||
import { libHelpers } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
const { useBreakpoint } = Grid;
|
const { useBreakpoint } = Grid;
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ export default function ModDetails(props) {
|
|||||||
}
|
}
|
||||||
{mod.filename && <Descriptions.Item label="Filename">{mod.filename}</Descriptions.Item>}
|
{mod.filename && <Descriptions.Item label="Filename">{mod.filename}</Descriptions.Item>}
|
||||||
{mod.size !== undefined
|
{mod.size !== undefined
|
||||||
&& <Descriptions.Item label="Size">{libHelpers.formatBytes(mod.size)}</Descriptions.Item>
|
&& <Descriptions.Item label="Size">{lib.formatBytes(mod.size)}</Descriptions.Item>
|
||||||
}
|
}
|
||||||
{mod.sha1 && <Descriptions.Item label="SHA1" span={2}>{mod.sha1}</Descriptions.Item>}
|
{mod.sha1 && <Descriptions.Item label="SHA1" span={2}>{mod.sha1}</Descriptions.Item>}
|
||||||
{mod.dependencies && mod.dependencies.length
|
{mod.dependencies && mod.dependencies.length
|
||||||
|
|||||||
@@ -4,16 +4,14 @@ import {
|
|||||||
Button, Card, Checkbox, Col, ConfigProvider, Descriptions, Form, Input, Pagination,
|
Button, Card, Checkbox, Col, ConfigProvider, Descriptions, Form, Input, Pagination,
|
||||||
Popconfirm, Row, Table, Tag, Typography, Select, Skeleton, Space, Spin, Switch, Modal, Tooltip,
|
Popconfirm, Row, Table, Tag, Typography, Select, Skeleton, Space, Spin, Switch, Modal, Tooltip,
|
||||||
} from "antd";
|
} from "antd";
|
||||||
import InfoCircleOutlined from "@ant-design/icons/InfoCircleOutlined";
|
|
||||||
import ExportOutlined from "@ant-design/icons/ExportOutlined";
|
import ExportOutlined from "@ant-design/icons/ExportOutlined";
|
||||||
import FileUnknownOutlined from "@ant-design/icons/FileUnknownOutlined";
|
import FileUnknownOutlined from "@ant-design/icons/FileUnknownOutlined";
|
||||||
import FileExclamationOutlined from "@ant-design/icons/FileExclamationOutlined";
|
import FileExclamationOutlined from "@ant-design/icons/FileExclamationOutlined";
|
||||||
import CloseOutlined from "@ant-design/icons/CloseOutlined";
|
import CloseOutlined from "@ant-design/icons/CloseOutlined";
|
||||||
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
||||||
import PlusOutlined from "@ant-design/icons/PlusOutlined";
|
import PlusOutlined from "@ant-design/icons/PlusOutlined";
|
||||||
import UploadOutlined from "@ant-design/icons/UploadOutlined";
|
|
||||||
|
|
||||||
import { libData, libLogging } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import { useModPack } from "../model/mod_pack";
|
import { useModPack } from "../model/mod_pack";
|
||||||
@@ -25,7 +23,7 @@ import PageLayout from "./PageLayout";
|
|||||||
import SectionHeader from "./SectionHeader";
|
import SectionHeader from "./SectionHeader";
|
||||||
import ModDetails from "./ModDetails";
|
import ModDetails from "./ModDetails";
|
||||||
|
|
||||||
const { logger } = libLogging;
|
const { logger } = lib;
|
||||||
const { Paragraph, Text } = Typography;
|
const { Paragraph, Text } = Typography;
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
||||||
|
|
||||||
@@ -44,7 +42,7 @@ function SearchModsTable(props) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let canceled = false;
|
let canceled = false;
|
||||||
control.send(new libData.ModSearchRequest(
|
control.send(new lib.ModSearchRequest(
|
||||||
searchText,
|
searchText,
|
||||||
factorioVersion,
|
factorioVersion,
|
||||||
modResultPage,
|
modResultPage,
|
||||||
@@ -535,7 +533,7 @@ function ExportButton(props) {
|
|||||||
function useExportedAsset(modPack, asset) {
|
function useExportedAsset(modPack, asset) {
|
||||||
let [assetData, setAssetData] = useState(asset === "locale" ? new Map() : {});
|
let [assetData, setAssetData] = useState(asset === "locale" ? new Map() : {});
|
||||||
let assetFilename;
|
let assetFilename;
|
||||||
if (modPack instanceof libData.ModPack && modPack.exportManifest && modPack.exportManifest.assets[asset]) {
|
if (modPack instanceof lib.ModPack && modPack.exportManifest && modPack.exportManifest.assets[asset]) {
|
||||||
assetFilename = modPack.exportManifest.assets[asset];
|
assetFilename = modPack.exportManifest.assets[asset];
|
||||||
}
|
}
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -612,7 +610,7 @@ export default function ModPackViewPage() {
|
|||||||
let syncTimeout = useRef();
|
let syncTimeout = useRef();
|
||||||
|
|
||||||
let modifiedModPack;
|
let modifiedModPack;
|
||||||
if (!(modPack instanceof libData.ModPack)) {
|
if (!(modPack instanceof lib.ModPack)) {
|
||||||
// Loading or invalid id
|
// Loading or invalid id
|
||||||
modifiedModPack = modPack;
|
modifiedModPack = modPack;
|
||||||
|
|
||||||
@@ -707,7 +705,7 @@ export default function ModPackViewPage() {
|
|||||||
okButtonProps={{ danger: true }}
|
okButtonProps={{ danger: true }}
|
||||||
onConfirm={() => {
|
onConfirm={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.ModPackDeleteRequest(modPack.id)
|
new lib.ModPackDeleteRequest(modPack.id)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
navigate("/mods");
|
navigate("/mods");
|
||||||
}).catch(notifyErrorHandler("Error deleting mod pack"));
|
}).catch(notifyErrorHandler("Error deleting mod pack"));
|
||||||
@@ -802,7 +800,7 @@ export default function ModPackViewPage() {
|
|||||||
type="primary"
|
type="primary"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.ModPackUpdateRequest(modifiedModPack)
|
new lib.ModPackUpdateRequest(modifiedModPack)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
form.resetFields();
|
form.resetFields();
|
||||||
setChanges([]);
|
setChanges([]);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import ImportOutlined from "@ant-design/icons/ImportOutlined";
|
|||||||
import PlusOutlined from "@ant-design/icons/PlusOutlined";
|
import PlusOutlined from "@ant-design/icons/PlusOutlined";
|
||||||
import UploadOutlined from "@ant-design/icons/UploadOutlined";
|
import UploadOutlined from "@ant-design/icons/UploadOutlined";
|
||||||
|
|
||||||
import { libData, libHelpers, libLogging } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import { useModList } from "../model/mods";
|
import { useModList } from "../model/mods";
|
||||||
@@ -20,8 +20,6 @@ import ModDetails from "./ModDetails";
|
|||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
||||||
|
|
||||||
const { logger } = libLogging;
|
|
||||||
|
|
||||||
|
|
||||||
function ImportModPackButton() {
|
function ImportModPackButton() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
@@ -47,8 +45,8 @@ function ImportModPackButton() {
|
|||||||
} catch {
|
} catch {
|
||||||
return; // Validation failed
|
return; // Validation failed
|
||||||
}
|
}
|
||||||
const modPack = libData.ModPack.fromModPackString(values.string);
|
const modPack = lib.ModPack.fromModPackString(values.string);
|
||||||
await control.send(new libData.ModPackCreateRequest(modPack));
|
await control.send(new lib.ModPackCreateRequest(modPack));
|
||||||
navigate(`/mods/mod-packs/${modPack.id}/view`);
|
navigate(`/mods/mod-packs/${modPack.id}/view`);
|
||||||
})().catch(notifyErrorHandler("Error creating mod pack"));
|
})().catch(notifyErrorHandler("Error creating mod pack"));
|
||||||
}}
|
}}
|
||||||
@@ -60,7 +58,7 @@ function ImportModPackButton() {
|
|||||||
{ required: true },
|
{ required: true },
|
||||||
{ async validator(rule, value) {
|
{ async validator(rule, value) {
|
||||||
if (value) {
|
if (value) {
|
||||||
libData.ModPack.fromModPackString(value);
|
lib.ModPack.fromModPackString(value);
|
||||||
}
|
}
|
||||||
}},
|
}},
|
||||||
]}
|
]}
|
||||||
@@ -96,11 +94,11 @@ function CreateModPackButton() {
|
|||||||
} catch {
|
} catch {
|
||||||
return; // Validation failed
|
return; // Validation failed
|
||||||
}
|
}
|
||||||
const modPack = libData.ModPack.fromJSON({});
|
const modPack = lib.ModPack.fromJSON({});
|
||||||
modPack.name = values.name;
|
modPack.name = values.name;
|
||||||
modPack.factorioVersion = values.factorioVersion;
|
modPack.factorioVersion = values.factorioVersion;
|
||||||
if (values.description) { modPack.description = values.description; }
|
if (values.description) { modPack.description = values.description; }
|
||||||
await control.send(new libData.ModPackCreateRequest(modPack.toJSON()));
|
await control.send(new lib.ModPackCreateRequest(modPack.toJSON()));
|
||||||
navigate(`/mods/mod-packs/${modPack.id}/view`);
|
navigate(`/mods/mod-packs/${modPack.id}/view`);
|
||||||
})().catch(notifyErrorHandler("Error creating mod pack"));
|
})().catch(notifyErrorHandler("Error creating mod pack"));
|
||||||
}}
|
}}
|
||||||
@@ -141,7 +139,7 @@ export default function ModsPage() {
|
|||||||
&& <Typography.Link
|
&& <Typography.Link
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.ModDownloadRequest(mod.name, mod.version)
|
new lib.ModDownloadRequest(mod.name, mod.version)
|
||||||
).then(streamId => {
|
).then(streamId => {
|
||||||
let url = new URL(webRoot, document.location);
|
let url = new URL(webRoot, document.location);
|
||||||
url.pathname += `api/stream/${streamId}`;
|
url.pathname += `api/stream/${streamId}`;
|
||||||
@@ -157,7 +155,7 @@ export default function ModsPage() {
|
|||||||
title={`Delete ${mod.name}_${mod.version}.zip?`}
|
title={`Delete ${mod.name}_${mod.version}.zip?`}
|
||||||
onConfirm={event => {
|
onConfirm={event => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.ModDeleteRequest(mod.name, mod.version)
|
new lib.ModDeleteRequest(mod.name, mod.version)
|
||||||
).catch(notifyErrorHandler("Error deleting mod"));
|
).catch(notifyErrorHandler("Error deleting mod"));
|
||||||
}}
|
}}
|
||||||
okText="Delete"
|
okText="Delete"
|
||||||
@@ -251,7 +249,7 @@ export default function ModsPage() {
|
|||||||
title: "Size",
|
title: "Size",
|
||||||
key: "size",
|
key: "size",
|
||||||
responsive: ["lg"],
|
responsive: ["lg"],
|
||||||
render: mod => libHelpers.formatBytes(mod.size),
|
render: mod => lib.formatBytes(mod.size),
|
||||||
align: "right",
|
align: "right",
|
||||||
sorter: (a, b) => a.size - b.size,
|
sorter: (a, b) => a.size - b.size,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { useNavigate, useParams } from "react-router-dom";
|
|||||||
import { Button, Checkbox, Form, Input, Popconfirm, Spin } from "antd";
|
import { Button, Checkbox, Form, Input, Popconfirm, Spin } from "antd";
|
||||||
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
||||||
|
|
||||||
import { libData, libUsers } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -19,7 +19,7 @@ function useRole(id) {
|
|||||||
|
|
||||||
function updateRole() {
|
function updateRole() {
|
||||||
// XXX optimize by requesting only the role in question
|
// XXX optimize by requesting only the role in question
|
||||||
control.send(new libData.RoleListRequest()).then(roles => {
|
control.send(new lib.RoleListRequest()).then(roles => {
|
||||||
let match = roles.find(u => u.id === id);
|
let match = roles.find(u => u.id === id);
|
||||||
if (!match) {
|
if (!match) {
|
||||||
setRole({ missing: true });
|
setRole({ missing: true });
|
||||||
@@ -70,7 +70,7 @@ export default function RoleViewPage() {
|
|||||||
name: role["name"],
|
name: role["name"],
|
||||||
description: role["description"],
|
description: role["description"],
|
||||||
permissions: {
|
permissions: {
|
||||||
...Object.fromEntries([...libUsers.permissions.values()].map(perm => [
|
...Object.fromEntries([...lib.permissions.values()].map(perm => [
|
||||||
perm.name, role["permissions"].includes(perm.name),
|
perm.name, role["permissions"].includes(perm.name),
|
||||||
])),
|
])),
|
||||||
},
|
},
|
||||||
@@ -88,7 +88,7 @@ export default function RoleViewPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
control.send(
|
control.send(
|
||||||
new libData.RoleUpdateRequest(roleId, values.name || "", values.description || "", newPermissions)
|
new lib.RoleUpdateRequest(roleId, values.name || "", values.description || "", newPermissions)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setEdited(false);
|
setEdited(false);
|
||||||
updateRole();
|
updateRole();
|
||||||
@@ -106,7 +106,7 @@ export default function RoleViewPage() {
|
|||||||
okButtonProps={{ danger: true }}
|
okButtonProps={{ danger: true }}
|
||||||
onConfirm={() => {
|
onConfirm={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.RoleDeleteRequest(roleId)
|
new lib.RoleDeleteRequest(roleId)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
navigate("/roles");
|
navigate("/roles");
|
||||||
}).catch(notifyErrorHandler("Error deleting role"));
|
}).catch(notifyErrorHandler("Error deleting role"));
|
||||||
@@ -125,7 +125,7 @@ export default function RoleViewPage() {
|
|||||||
<Input disabled={!canUpdate}/>
|
<Input disabled={!canUpdate}/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<h3>Permissions</h3>
|
<h3>Permissions</h3>
|
||||||
{[...libUsers.permissions.values()].map(({name, title, description}) => (
|
{[...lib.permissions.values()].map(({name, title, description}) => (
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name={["permissions", name]}
|
name={["permissions", name]}
|
||||||
key={name}
|
key={name}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { useContext, useEffect, useState } from "react";
|
|||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { Button, Form, Input, Modal, Table } from "antd";
|
import { Button, Form, Input, Modal, Table } from "antd";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -28,7 +28,7 @@ function CreateRoleButton() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let result = await control.send(
|
let result = await control.send(
|
||||||
new libData.RoleCreateRequest(values.roleName, values.description || "", [])
|
new lib.RoleCreateRequest(values.roleName, values.description || "", [])
|
||||||
);
|
);
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
navigate(`/roles/${result.id}/view`);
|
navigate(`/roles/${result.id}/view`);
|
||||||
@@ -67,7 +67,7 @@ export default function RolesPage() {
|
|||||||
let [roles, setRoles] = useState([]);
|
let [roles, setRoles] = useState([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
control.send(new libData.RoleListRequest()).then(newRoles => {
|
control.send(new lib.RoleListRequest()).then(newRoles => {
|
||||||
setRoles(newRoles);
|
setRoles(newRoles);
|
||||||
}).catch(notifyErrorHandler("Error fetching role list"));
|
}).catch(notifyErrorHandler("Error fetching role list"));
|
||||||
}, []);
|
}, []);
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
import CaretLeftOutlined from "@ant-design/icons/CaretLeftOutlined";
|
import CaretLeftOutlined from "@ant-design/icons/CaretLeftOutlined";
|
||||||
import LeftOutlined from "@ant-design/icons/LeftOutlined";
|
import LeftOutlined from "@ant-design/icons/LeftOutlined";
|
||||||
|
|
||||||
import { libData, libHelpers } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -37,7 +37,7 @@ function RenameModal(props) {
|
|||||||
initialValues={{ newName: props.save.name }}
|
initialValues={{ newName: props.save.name }}
|
||||||
onFinish={values => {
|
onFinish={values => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.InstanceRenameSaveRequest(props.instanceId, props.save.name, values.newName)
|
new lib.InstanceRenameSaveRequest(props.instanceId, props.save.name, values.newName)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
form.resetFields();
|
form.resetFields();
|
||||||
@@ -76,7 +76,7 @@ function CopyModal(props) {
|
|||||||
initialValues={{ newName: props.save.name }}
|
initialValues={{ newName: props.save.name }}
|
||||||
onFinish={values => {
|
onFinish={values => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.InstanceCopySaveRequest(props.instanceId, props.save.name, values.newName)
|
new lib.InstanceCopySaveRequest(props.instanceId, props.save.name, values.newName)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
form.resetFields();
|
form.resetFields();
|
||||||
@@ -120,7 +120,7 @@ function TransferModal(props) {
|
|||||||
onFinish={values => {
|
onFinish={values => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
let hide = message.loading("Transferring save...", 0);
|
let hide = message.loading("Transferring save...", 0);
|
||||||
control.send(new libData.InstanceTransferSaveRequest(
|
control.send(new lib.InstanceTransferSaveRequest(
|
||||||
props.instanceId,
|
props.instanceId,
|
||||||
props.save.name,
|
props.save.name,
|
||||||
values.targetInstanceId,
|
values.targetInstanceId,
|
||||||
@@ -203,7 +203,7 @@ export default function SavesList(props) {
|
|||||||
title: "Size",
|
title: "Size",
|
||||||
key: "size",
|
key: "size",
|
||||||
responsive: ["sm"],
|
responsive: ["sm"],
|
||||||
render: save => libHelpers.formatBytes(save.size),
|
render: save => lib.formatBytes(save.size),
|
||||||
align: "right",
|
align: "right",
|
||||||
sorter: (a, b) => a.size - b.size,
|
sorter: (a, b) => a.size - b.size,
|
||||||
},
|
},
|
||||||
@@ -229,7 +229,7 @@ export default function SavesList(props) {
|
|||||||
setStarting(true);
|
setStarting(true);
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId: props.instance.id },
|
{ instanceId: props.instance.id },
|
||||||
new libData.InstanceStartRequest(save.name),
|
new lib.InstanceStartRequest(save.name),
|
||||||
).catch(
|
).catch(
|
||||||
notifyErrorHandler("Error loading save")
|
notifyErrorHandler("Error loading save")
|
||||||
).finally(
|
).finally(
|
||||||
@@ -247,7 +247,7 @@ export default function SavesList(props) {
|
|||||||
disabled={hostOffline}
|
disabled={hostOffline}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.InstanceDownloadSaveRequest(props.instance.id, save.name)
|
new lib.InstanceDownloadSaveRequest(props.instance.id, save.name)
|
||||||
).then(streamId => {
|
).then(streamId => {
|
||||||
let url = new URL(webRoot, document.location);
|
let url = new URL(webRoot, document.location);
|
||||||
url.pathname += `api/stream/${streamId}`;
|
url.pathname += `api/stream/${streamId}`;
|
||||||
@@ -267,7 +267,7 @@ export default function SavesList(props) {
|
|||||||
okButtonProps={{ danger: true }}
|
okButtonProps={{ danger: true }}
|
||||||
onConfirm={() => {
|
onConfirm={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.InstanceDeleteSaveRequest(props.instance.id, save.name)
|
new lib.InstanceDeleteSaveRequest(props.instance.id, save.name)
|
||||||
).catch(notifyErrorHandler("Error deleting save"));
|
).catch(notifyErrorHandler("Error deleting save"));
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useContext, useState } from "react";
|
import React, { useContext, useState } from "react";
|
||||||
import { Button } from "antd";
|
import { Button } from "antd";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
@@ -18,7 +18,7 @@ export default function StartStopInstanceButton(props) {
|
|||||||
if (props.instance["status"] === "stopped") {
|
if (props.instance["status"] === "stopped") {
|
||||||
action = control.sendTo(
|
action = control.sendTo(
|
||||||
{ instanceId: props.instance["id"] },
|
{ instanceId: props.instance["id"] },
|
||||||
new libData.InstanceStartRequest(undefined),
|
new lib.InstanceStartRequest(undefined),
|
||||||
).catch(
|
).catch(
|
||||||
notifyErrorHandler("Error starting instance")
|
notifyErrorHandler("Error starting instance")
|
||||||
);
|
);
|
||||||
@@ -26,7 +26,7 @@ export default function StartStopInstanceButton(props) {
|
|||||||
} else if (["starting", "running"].includes(props.instance["status"])) {
|
} else if (["starting", "running"].includes(props.instance["status"])) {
|
||||||
action = control.sendTo(
|
action = control.sendTo(
|
||||||
{ instanceId: props.instance["id"] },
|
{ instanceId: props.instance["id"] },
|
||||||
new libData.InstanceStopRequest(),
|
new lib.InstanceStopRequest(),
|
||||||
).catch(
|
).catch(
|
||||||
notifyErrorHandler("Error stopping instance")
|
notifyErrorHandler("Error stopping instance")
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
} from "antd";
|
} from "antd";
|
||||||
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
||||||
|
|
||||||
import { libErrors, libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import { useInstanceList } from "../model/instance";
|
import { useInstanceList } from "../model/instance";
|
||||||
@@ -43,7 +43,7 @@ export default function UserViewPage() {
|
|||||||
let [rolesError, setRolesError] = useState();
|
let [rolesError, setRolesError] = useState();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
control.send(new libData.RoleListRequest()).then(newRoles => {
|
control.send(new lib.RoleListRequest()).then(newRoles => {
|
||||||
setRoles(new Map(newRoles.map(role => [role.id, role])));
|
setRoles(new Map(newRoles.map(role => [role.id, role])));
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
setRoles(new Map());
|
setRoles(new Map());
|
||||||
@@ -122,11 +122,11 @@ export default function UserViewPage() {
|
|||||||
danger
|
danger
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.UserRevokeTokenRequest(userName)
|
new lib.UserRevokeTokenRequest(userName)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
notify("User token revoked");
|
notify("User token revoked");
|
||||||
}, err => {
|
}, err => {
|
||||||
if (err instanceof libErrors.SessionLost && userName === account.name) {
|
if (err instanceof lib.SessionLost && userName === account.name) {
|
||||||
// Got kicked out after revoking our own token
|
// Got kicked out after revoking our own token
|
||||||
notify("User token revoked");
|
notify("User token revoked");
|
||||||
return;
|
return;
|
||||||
@@ -145,7 +145,7 @@ export default function UserViewPage() {
|
|||||||
okButtonProps={{ danger: true }}
|
okButtonProps={{ danger: true }}
|
||||||
onConfirm={() => {
|
onConfirm={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.UserDeleteRequest(userName)
|
new lib.UserDeleteRequest(userName)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
navigate("/users");
|
navigate("/users");
|
||||||
}).catch(notifyErrorHandler("Error deleting user"));
|
}).catch(notifyErrorHandler("Error deleting user"));
|
||||||
@@ -195,7 +195,7 @@ export default function UserViewPage() {
|
|||||||
let newRoles = form.getFieldValue("roles");
|
let newRoles = form.getFieldValue("roles");
|
||||||
setApplyingRoles(true);
|
setApplyingRoles(true);
|
||||||
control.send(
|
control.send(
|
||||||
new libData.UserUpdateRolesRequest(userName, newRoles)
|
new lib.UserUpdateRolesRequest(userName, newRoles)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setRolesDirty(false);
|
setRolesDirty(false);
|
||||||
setRolesError();
|
setRolesError();
|
||||||
@@ -215,7 +215,7 @@ export default function UserViewPage() {
|
|||||||
checked={user.isAdmin}
|
checked={user.isAdmin}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.UserSetAdminRequest(userName, false, !user.isAdmin)
|
new lib.UserSetAdminRequest(userName, false, !user.isAdmin)
|
||||||
).catch(notifyErrorHandler("Error toggling user admin status"));
|
).catch(notifyErrorHandler("Error toggling user admin status"));
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -225,7 +225,7 @@ export default function UserViewPage() {
|
|||||||
checked={user.isWhitelisted}
|
checked={user.isWhitelisted}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.UserSetWhitelistedRequest(userName, false, !user.isWhitelisted)
|
new lib.UserSetWhitelistedRequest(userName, false, !user.isWhitelisted)
|
||||||
).catch(notifyErrorHandler("Error toggling user whitelisted status"));
|
).catch(notifyErrorHandler("Error toggling user whitelisted status"));
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -249,7 +249,7 @@ export default function UserViewPage() {
|
|||||||
type={banReasonDirty ? "primary" : "default"}
|
type={banReasonDirty ? "primary" : "default"}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.UserSetBannedRequest(
|
new lib.UserSetBannedRequest(
|
||||||
userName, false, true, form.getFieldValue("banReason")
|
userName, false, true, form.getFieldValue("banReason")
|
||||||
)
|
)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
@@ -260,7 +260,7 @@ export default function UserViewPage() {
|
|||||||
<Button
|
<Button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.UserSetBannedRequest(userName, false, false, "")
|
new lib.UserSetBannedRequest(userName, false, false, "")
|
||||||
).catch(notifyErrorHandler("Error unbanning user"));
|
).catch(notifyErrorHandler("Error unbanning user"));
|
||||||
}}
|
}}
|
||||||
>Unban</Button>
|
>Unban</Button>
|
||||||
@@ -269,7 +269,7 @@ export default function UserViewPage() {
|
|||||||
type={banReasonDirty ? "primary" : "default"}
|
type={banReasonDirty ? "primary" : "default"}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new libData.UserSetBannedRequest(
|
new lib.UserSetBannedRequest(
|
||||||
userName, false, true, form.getFieldValue("banReason")
|
userName, false, true, form.getFieldValue("banReason")
|
||||||
)
|
)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { useEffect, useContext, useState } from "react";
|
|||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { Button, Form, Input, Modal, Space, Table, Tag } from "antd";
|
import { Button, Form, Input, Modal, Space, Table, Tag } from "antd";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
@@ -29,7 +29,7 @@ function CreateUserButton() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await control.send(new libData.UserCreateRequest(values.userName));
|
await control.send(new lib.UserCreateRequest(values.userName));
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
navigate(`/users/${values.userName}/view`);
|
navigate(`/users/${values.userName}/view`);
|
||||||
}
|
}
|
||||||
@@ -65,7 +65,7 @@ export default function UsersPage() {
|
|||||||
let [roles, setRoles] = useState(new Map());
|
let [roles, setRoles] = useState(new Map());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
control.send(new libData.RoleListRequest()).then(newRoles => {
|
control.send(new lib.RoleListRequest()).then(newRoles => {
|
||||||
setRoles(new Map(newRoles.map(role => [role.id, role])));
|
setRoles(new Map(newRoles.map(role => [role.id, role])));
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
// ignore
|
// ignore
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useEffect, useContext, useState } from "react";
|
import { useEffect, useContext, useState } from "react";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ export function useExportManifest() {
|
|||||||
let [exportManifest, setExportManifest] = useState(exportManifestCache || emptyCache);
|
let [exportManifest, setExportManifest] = useState(exportManifestCache || emptyCache);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function load() {
|
async function load() {
|
||||||
let modPack = await control.send(new libData.ModPackGetDefaultRequest());
|
let modPack = await control.send(new lib.ModPackGetDefaultRequest());
|
||||||
if (modPack.exportManifest) {
|
if (modPack.exportManifest) {
|
||||||
exportManifestCache = modPack.exportManifest;
|
exportManifestCache = modPack.exportManifest;
|
||||||
setExportManifest(exportManifestCache);
|
setExportManifest(exportManifestCache);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useContext, useState } from "react";
|
import { useEffect, useContext, useState } from "react";
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
import { libData } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
|
|
||||||
export function useHost(id) {
|
export function useHost(id) {
|
||||||
@@ -10,7 +10,7 @@ export function useHost(id) {
|
|||||||
|
|
||||||
function updateHost() {
|
function updateHost() {
|
||||||
// XXX optimize by requesting only the host in question
|
// XXX optimize by requesting only the host in question
|
||||||
control.send(new libData.HostListRequest()).then(hosts => {
|
control.send(new lib.HostListRequest()).then(hosts => {
|
||||||
let match = hosts.find(i => i.id === id);
|
let match = hosts.find(i => i.id === id);
|
||||||
if (!match) {
|
if (!match) {
|
||||||
setHost({ missing: true });
|
setHost({ missing: true });
|
||||||
@@ -45,7 +45,7 @@ export function useHostList() {
|
|||||||
let [hostList, setHostList] = useState([]);
|
let [hostList, setHostList] = useState([]);
|
||||||
|
|
||||||
function updateHostList() {
|
function updateHostList() {
|
||||||
control.send(new libData.HostListRequest()).then(hosts => {
|
control.send(new lib.HostListRequest()).then(hosts => {
|
||||||
setHostList(hosts);
|
setHostList(hosts);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
import { useEffect, useContext, useState } from "react";
|
import { useEffect, useContext, useState } from "react";
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
import { libData, libLogging } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = libLogging;
|
|
||||||
|
|
||||||
|
const { logger } = lib;
|
||||||
|
|
||||||
export function useInstance(id) {
|
export function useInstance(id) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [instance, setInstance] = useState({ loading: true });
|
let [instance, setInstance] = useState({ loading: true });
|
||||||
|
|
||||||
function updateInstance() {
|
function updateInstance() {
|
||||||
control.send(new libData.InstanceDetailsGetRequest(id)).then(updatedInstance => {
|
control.send(new lib.InstanceDetailsGetRequest(id)).then(updatedInstance => {
|
||||||
setInstance({ ...updatedInstance, present: true });
|
setInstance({ ...updatedInstance, present: true });
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to get instance: ${err}`);
|
logger.error(`Failed to get instance: ${err}`);
|
||||||
@@ -44,7 +44,7 @@ export function useInstanceList() {
|
|||||||
let [instanceList, setInstanceList] = useState([]);
|
let [instanceList, setInstanceList] = useState([]);
|
||||||
|
|
||||||
function updateInstanceList() {
|
function updateInstanceList() {
|
||||||
control.send(new libData.InstanceDetailsListRequest()).then(instances => {
|
control.send(new lib.InstanceDetailsListRequest()).then(instances => {
|
||||||
setInstanceList(instances);
|
setInstanceList(instances);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to list instances:\n${err}`);
|
logger.error(`Failed to list instances:\n${err}`);
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
import { useContext, useEffect, useState } from "react";
|
import { useContext, useEffect, useState } from "react";
|
||||||
|
|
||||||
import { libData, libLogging } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
const { logger } = libLogging;
|
const { logger } = lib;
|
||||||
|
|
||||||
export function useModPack(id) {
|
export function useModPack(id) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [modPack, setModPack] = useState({ loading: true });
|
let [modPack, setModPack] = useState({ loading: true });
|
||||||
|
|
||||||
function updateModPack() {
|
function updateModPack() {
|
||||||
control.send(new libData.ModPackGetRequest(id)).then(updatedModPack => {
|
control.send(new lib.ModPackGetRequest(id)).then(updatedModPack => {
|
||||||
setModPack(updatedModPack);
|
setModPack(updatedModPack);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to get mod pack: ${err}`);
|
logger.error(`Failed to get mod pack: ${err}`);
|
||||||
@@ -40,7 +40,7 @@ export function useModPackList() {
|
|||||||
let [modPackList, setModPackList] = useState([]);
|
let [modPackList, setModPackList] = useState([]);
|
||||||
|
|
||||||
function updateModPackList() {
|
function updateModPackList() {
|
||||||
control.send(new libData.ModPackListRequest()).then(modPacks => {
|
control.send(new lib.ModPackListRequest()).then(modPacks => {
|
||||||
setModPackList(modPacks);
|
setModPackList(modPacks);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to list mod packs:\n${err}`);
|
logger.error(`Failed to list mod packs:\n${err}`);
|
||||||
|
|||||||
@@ -1,18 +1,17 @@
|
|||||||
import { useContext, useEffect, useState } from "react";
|
import { useContext, useEffect, useState } from "react";
|
||||||
|
|
||||||
import { libData, libLogging } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
const { logger } = libLogging;
|
const { logger } = lib;
|
||||||
|
|
||||||
|
|
||||||
export function useModList() {
|
export function useModList() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [modList, setModList] = useState([]);
|
let [modList, setModList] = useState([]);
|
||||||
|
|
||||||
function updateModList() {
|
function updateModList() {
|
||||||
control.send(new libData.ModListRequest()).then(mods => {
|
control.send(new lib.ModListRequest()).then(mods => {
|
||||||
setModList(mods);
|
setModList(mods);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to list mods:\n${err}`);
|
logger.error(`Failed to list mods:\n${err}`);
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
import { useEffect, useContext, useState } from "react";
|
import { useEffect, useContext, useState } from "react";
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
import { libData, libLogging } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = libLogging;
|
|
||||||
|
|
||||||
|
const { logger } = lib;
|
||||||
|
|
||||||
export function useSaves(instanceId) {
|
export function useSaves(instanceId) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [saves, setSaves] = useState([]);
|
let [saves, setSaves] = useState([]);
|
||||||
|
|
||||||
function updateSaves() {
|
function updateSaves() {
|
||||||
control.sendTo({ instanceId }, new libData.InstanceListSavesRequest()).then(updatedSaves => {
|
control.sendTo({ instanceId }, new lib.InstanceListSavesRequest()).then(updatedSaves => {
|
||||||
setSaves(updatedSaves);
|
setSaves(updatedSaves);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to list instance saves: ${err}`);
|
logger.error(`Failed to list instance saves: ${err}`);
|
||||||
|
|||||||
@@ -2,8 +2,9 @@ import React, { useEffect, useContext, useState } from "react";
|
|||||||
import { Tag } from "antd";
|
import { Tag } from "antd";
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
import { libData, libLogging } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = libLogging;
|
|
||||||
|
const { logger } = lib;
|
||||||
|
|
||||||
function calculateLastSeen(user, instanceId) {
|
function calculateLastSeen(user, instanceId) {
|
||||||
let stats;
|
let stats;
|
||||||
@@ -56,7 +57,7 @@ export function useUser(name) {
|
|||||||
let [user, setUser] = useState({ loading: true });
|
let [user, setUser] = useState({ loading: true });
|
||||||
|
|
||||||
function updateUser() {
|
function updateUser() {
|
||||||
control.send(new libData.UserGetRequest(name)).then(updatedUser => {
|
control.send(new lib.UserGetRequest(name)).then(updatedUser => {
|
||||||
setUser({ ...updatedUser, present: true });
|
setUser({ ...updatedUser, present: true });
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to get user: ${err}`);
|
logger.error(`Failed to get user: ${err}`);
|
||||||
@@ -90,7 +91,7 @@ export function useUserList() {
|
|||||||
let [userList, setUserList] = useState([]);
|
let [userList, setUserList] = useState([]);
|
||||||
|
|
||||||
function updateUserList() {
|
function updateUserList() {
|
||||||
control.send(new libData.UserListRequest()).then(users => {
|
control.send(new lib.UserListRequest()).then(users => {
|
||||||
setUserList(users);
|
setUserList(users);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to list users:\n${err}`);
|
logger.error(`Failed to list users:\n${err}`);
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { notification } from "antd";
|
import { notification } from "antd";
|
||||||
import { libLogging } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
const { logger } = libLogging;
|
|
||||||
|
|
||||||
|
|
||||||
export default function notify(message, type = "info", description = undefined) {
|
export default function notify(message, type = "info", description = undefined) {
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { libData, libErrors, libLink, libLogging, libPlugin } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logFilter, logger } = libLogging;
|
|
||||||
import packageJson from "../../package.json";
|
import packageJson from "../../package.json";
|
||||||
|
|
||||||
|
const { logFilter, logger } = lib;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connector for control connection to controller
|
* Connector for control connection to controller
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
export class ControlConnector extends libLink.WebSocketClientConnector {
|
export class ControlConnector extends lib.WebSocketClientConnector {
|
||||||
constructor(url, maxReconnectDelay) {
|
constructor(url, maxReconnectDelay) {
|
||||||
super(url, maxReconnectDelay);
|
super(url, maxReconnectDelay);
|
||||||
this.token = null;
|
this.token = null;
|
||||||
@@ -20,8 +20,8 @@ export class ControlConnector extends libLink.WebSocketClientConnector {
|
|||||||
|
|
||||||
logger.verbose("Connector | registering control");
|
logger.verbose("Connector | registering control");
|
||||||
this.sendHandshake(
|
this.sendHandshake(
|
||||||
new libData.MessageRegisterControl(
|
new lib.MessageRegisterControl(
|
||||||
new libData.RegisterControlData(
|
new lib.RegisterControlData(
|
||||||
this.token,
|
this.token,
|
||||||
"Clusterio Web UI",
|
"Clusterio Web UI",
|
||||||
packageJson.version,
|
packageJson.version,
|
||||||
@@ -37,13 +37,13 @@ export class ControlConnector extends libLink.WebSocketClientConnector {
|
|||||||
* Connects to the controller over WebSocket and sends commands to it.
|
* Connects to the controller over WebSocket and sends commands to it.
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
export class Control extends libLink.Link {
|
export class Control extends lib.Link {
|
||||||
constructor(connector, plugins) {
|
constructor(connector, plugins) {
|
||||||
super(connector);
|
super(connector);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mapping of plugin names to their instance for loaded plugins.
|
* Mapping of plugin names to their instance for loaded plugins.
|
||||||
* @type {Map<string, module:lib/plugin.BaseWebPlugin>}
|
* @type {Map<string, module:lib.BaseWebPlugin>}
|
||||||
*/
|
*/
|
||||||
this.plugins = plugins;
|
this.plugins = plugins;
|
||||||
for (let plugin of plugins.values()) {
|
for (let plugin of plugins.values()) {
|
||||||
@@ -118,15 +118,15 @@ export class Control extends libLink.Link {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this.handle(libData.AccountUpdateEvent, this.handleAccountUpdateEvent.bind(this));
|
this.handle(lib.AccountUpdateEvent, this.handleAccountUpdateEvent.bind(this));
|
||||||
this.handle(libData.HostUpdateEvent, this.handleHostUpdateEvent.bind(this));
|
this.handle(lib.HostUpdateEvent, this.handleHostUpdateEvent.bind(this));
|
||||||
this.handle(libData.InstanceDetailsUpdateEvent, this.handleInstanceDetailsUpdateEvent.bind(this));
|
this.handle(lib.InstanceDetailsUpdateEvent, this.handleInstanceDetailsUpdateEvent.bind(this));
|
||||||
this.handle(libData.InstanceSaveListUpdateEvent, this.handleInstanceSaveListUpdateEvent.bind(this));
|
this.handle(lib.InstanceSaveListUpdateEvent, this.handleInstanceSaveListUpdateEvent.bind(this));
|
||||||
this.handle(libData.ModPackUpdateEvent, this.handleModPackUpdateEvent.bind(this));
|
this.handle(lib.ModPackUpdateEvent, this.handleModPackUpdateEvent.bind(this));
|
||||||
this.handle(libData.ModUpdateEvent, this.handleModUpdateEvent.bind(this));
|
this.handle(lib.ModUpdateEvent, this.handleModUpdateEvent.bind(this));
|
||||||
this.handle(libData.UserUpdateEvent, this.handleUserUpdateEvent.bind(this));
|
this.handle(lib.UserUpdateEvent, this.handleUserUpdateEvent.bind(this));
|
||||||
this.handle(libData.LogMessageEvent, this.handleLogMessageEvent.bind(this));
|
this.handle(lib.LogMessageEvent, this.handleLogMessageEvent.bind(this));
|
||||||
this.handle(libData.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
|
this.handle(lib.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleAccountUpdateEvent(event) {
|
async handleAccountUpdateEvent(event) {
|
||||||
@@ -206,7 +206,7 @@ export class Control extends libLink.Link {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.send(new libData.HostSetSubscriptionsRequest(
|
await this.send(new lib.HostSetSubscriptionsRequest(
|
||||||
this.hostUpdateHandlers.has(null),
|
this.hostUpdateHandlers.has(null),
|
||||||
[...this.hostUpdateHandlers.keys()].filter(e => e !== null),
|
[...this.hostUpdateHandlers.keys()].filter(e => e !== null),
|
||||||
));
|
));
|
||||||
@@ -263,7 +263,7 @@ export class Control extends libLink.Link {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.send(new libData.InstanceDetailsSetSubscriptionsRequest(
|
await this.send(new lib.InstanceDetailsSetSubscriptionsRequest(
|
||||||
this.instanceUpdateHandlers.has(null),
|
this.instanceUpdateHandlers.has(null),
|
||||||
[...this.instanceUpdateHandlers.keys()].filter(e => e !== null),
|
[...this.instanceUpdateHandlers.keys()].filter(e => e !== null),
|
||||||
));
|
));
|
||||||
@@ -317,7 +317,7 @@ export class Control extends libLink.Link {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.send(new libData.InstanceSetSaveListSubscriptionsRequest(
|
await this.send(new lib.InstanceSetSaveListSubscriptionsRequest(
|
||||||
false,
|
false,
|
||||||
[...this.saveListUpdateHandlers.keys()],
|
[...this.saveListUpdateHandlers.keys()],
|
||||||
));
|
));
|
||||||
@@ -375,7 +375,7 @@ export class Control extends libLink.Link {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.send(new libData.ModPackSetSubscriptionsRequest(
|
await this.send(new lib.ModPackSetSubscriptionsRequest(
|
||||||
this.modPackUpdateHandlers.has(null),
|
this.modPackUpdateHandlers.has(null),
|
||||||
[...this.modPackUpdateHandlers.keys()].filter(k => k !== null),
|
[...this.modPackUpdateHandlers.keys()].filter(k => k !== null),
|
||||||
));
|
));
|
||||||
@@ -433,7 +433,7 @@ export class Control extends libLink.Link {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.send(new libData.ModSetSubscriptionsRequest(
|
await this.send(new lib.ModSetSubscriptionsRequest(
|
||||||
this.modUpdateHandlers.has(null),
|
this.modUpdateHandlers.has(null),
|
||||||
[...this.modUpdateHandlers.keys()].filter(k => k !== null),
|
[...this.modUpdateHandlers.keys()].filter(k => k !== null),
|
||||||
));
|
));
|
||||||
@@ -490,7 +490,7 @@ export class Control extends libLink.Link {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.send(new libData.UserSetSubscriptionsRequest(
|
await this.send(new lib.UserSetSubscriptionsRequest(
|
||||||
this.userUpdateHandlers.has(null),
|
this.userUpdateHandlers.has(null),
|
||||||
[...this.userUpdateHandlers.keys()].filter(e => e !== null),
|
[...this.userUpdateHandlers.keys()].filter(e => e !== null),
|
||||||
));
|
));
|
||||||
@@ -565,7 +565,7 @@ export class Control extends libLink.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.send(new libData.LogSetSubscriptionsRequest(all, controller, hostIds, instanceIds, null));
|
await this.send(new lib.LogSetSubscriptionsRequest(all, controller, hostIds, instanceIds, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleDebugWsMessageEvent(message) {
|
async handleDebugWsMessageEvent(message) {
|
||||||
@@ -577,7 +577,7 @@ export class Control extends libLink.Link {
|
|||||||
try {
|
try {
|
||||||
await this.connector.disconnect();
|
await this.connector.disconnect();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!(err instanceof libErrors.SessionLost)) {
|
if (!(err instanceof lib.SessionLost)) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
const { BaseControlPlugin, CommandTree, Command } = require("@clusterio/lib");
|
||||||
const { ChatEvent } = require("./messages");
|
const { ChatEvent } = require("./messages");
|
||||||
const libCommand = require("@clusterio/lib/command");
|
|
||||||
|
|
||||||
|
|
||||||
const globalChatCommands = new libCommand.CommandTree({
|
const globalChatCommands = new CommandTree({
|
||||||
name: "global-chat", description: "Global Chat plugin commands",
|
name: "global-chat", description: "Global Chat plugin commands",
|
||||||
});
|
});
|
||||||
globalChatCommands.add(new libCommand.Command({
|
globalChatCommands.add(new Command({
|
||||||
definition: ["shout <message>", "Send message to all instances", (yargs) => {
|
definition: ["shout <message>", "Send message to all instances", (yargs) => {
|
||||||
yargs.positional("message", { describe: "message to send", type: "string" });
|
yargs.positional("message", { describe: "message to send", type: "string" });
|
||||||
}],
|
}],
|
||||||
@@ -16,7 +15,7 @@ globalChatCommands.add(new libCommand.Command({
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
class ControlPlugin extends libPlugin.BaseControlPlugin {
|
class ControlPlugin extends BaseControlPlugin {
|
||||||
async addCommands(rootCommand) {
|
async addCommands(rootCommand) {
|
||||||
rootCommand.add(globalChatCommands);
|
rootCommand.add(globalChatCommands);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,7 @@
|
|||||||
* @module
|
* @module
|
||||||
*/
|
*/
|
||||||
"use strict";
|
"use strict";
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
const lib = require("@clusterio/lib");
|
||||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
|
||||||
const { ChatEvent } = require("./messages");
|
const { ChatEvent } = require("./messages");
|
||||||
|
|
||||||
|
|
||||||
@@ -17,7 +16,7 @@ function removeTags(content) {
|
|||||||
return content.replace(/(\[gps=-?\d+,-?\d+\]|\[train=\d+\])/g, "");
|
return content.replace(/(\[gps=-?\d+,-?\d+\]|\[train=\d+\])/g, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
class InstancePlugin extends lib.BaseInstancePlugin {
|
||||||
async init() {
|
async init() {
|
||||||
this.messageQueue = [];
|
this.messageQueue = [];
|
||||||
this.instance.handle(ChatEvent, this.handleChatEvent.bind(this));
|
this.instance.handle(ChatEvent, this.handleChatEvent.bind(this));
|
||||||
@@ -35,7 +34,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|||||||
async handleChatEvent(event) {
|
async handleChatEvent(event) {
|
||||||
// TODO check if cross server chat is enabled
|
// TODO check if cross server chat is enabled
|
||||||
let content = `[${event.instanceName}] ${removeTags(event.content)}`;
|
let content = `[${event.instanceName}] ${removeTags(event.content)}`;
|
||||||
await this.sendRcon(`/sc game.print('${libLuaTools.escapeString(content)}')`, true);
|
await this.sendRcon(`/sc game.print('${lib.escapeString(content)}')`, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
sendChat(message) {
|
sendChat(message) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const assert = require("assert").strict;
|
const assert = require("assert").strict;
|
||||||
const libLink = require("@clusterio/lib/link");
|
const lib = require("@clusterio/lib");
|
||||||
|
|
||||||
const mock = require("../../../test/mock");
|
const mock = require("../../../test/mock");
|
||||||
const lines = require("../../../test/lib/factorio/lines");
|
const lines = require("../../../test/lib/factorio/lines");
|
||||||
@@ -26,7 +26,7 @@ describe("global_chat plugin", function() {
|
|||||||
let instancePlugin;
|
let instancePlugin;
|
||||||
|
|
||||||
before(async function() {
|
before(async function() {
|
||||||
libLink.Link.register(ChatEvent);
|
lib.Link.register(ChatEvent);
|
||||||
instancePlugin = new instance.InstancePlugin(info, new mock.MockInstance(), new mock.MockHost());
|
instancePlugin = new instance.InstancePlugin(info, new mock.MockInstance(), new mock.MockHost());
|
||||||
await instancePlugin.init();
|
await instancePlugin.init();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,8 +2,7 @@
|
|||||||
const fs = require("fs-extra");
|
const fs = require("fs-extra");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
|
|
||||||
const libFileOps = require("@clusterio/lib/file_ops");
|
const lib = require("@clusterio/lib");
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
AcquireRequest,
|
AcquireRequest,
|
||||||
@@ -34,11 +33,11 @@ async function saveDatabase(controllerConfig, playerDatastore, logger) {
|
|||||||
let file = path.resolve(controllerConfig.get("controller.database_directory"), "inventories.json");
|
let file = path.resolve(controllerConfig.get("controller.database_directory"), "inventories.json");
|
||||||
logger.verbose(`writing ${file}`);
|
logger.verbose(`writing ${file}`);
|
||||||
let content = JSON.stringify(Array.from(playerDatastore));
|
let content = JSON.stringify(Array.from(playerDatastore));
|
||||||
await libFileOps.safeOutputFile(file, content);
|
await lib.safeOutputFile(file, content);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||||
async init() {
|
async init() {
|
||||||
this.acquiredPlayers = new Map();
|
this.acquiredPlayers = new Map();
|
||||||
this.playerDatastore = await loadDatabase(this.controller.config, this.logger);
|
this.playerDatastore = await loadDatabase(this.controller.config, this.logger);
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const { libConfig, libUsers } = require("@clusterio/lib");
|
const lib = require("@clusterio/lib");
|
||||||
let messages = require("./messages");
|
let messages = require("./messages");
|
||||||
|
|
||||||
class ControllerConfigGroup extends libConfig.PluginConfigGroup { }
|
class ControllerConfigGroup extends lib.PluginConfigGroup { }
|
||||||
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
||||||
ControllerConfigGroup.groupName = "inventory_sync";
|
ControllerConfigGroup.groupName = "inventory_sync";
|
||||||
ControllerConfigGroup.define({
|
ControllerConfigGroup.define({
|
||||||
@@ -22,7 +22,7 @@ ControllerConfigGroup.define({
|
|||||||
});
|
});
|
||||||
ControllerConfigGroup.finalize();
|
ControllerConfigGroup.finalize();
|
||||||
|
|
||||||
class InstanceConfigGroup extends libConfig.PluginConfigGroup { }
|
class InstanceConfigGroup extends lib.PluginConfigGroup { }
|
||||||
InstanceConfigGroup.defaultAccess = ["controller", "host", "control"];
|
InstanceConfigGroup.defaultAccess = ["controller", "host", "control"];
|
||||||
InstanceConfigGroup.groupName = "inventory_sync";
|
InstanceConfigGroup.groupName = "inventory_sync";
|
||||||
InstanceConfigGroup.define({
|
InstanceConfigGroup.define({
|
||||||
@@ -34,7 +34,7 @@ InstanceConfigGroup.define({
|
|||||||
});
|
});
|
||||||
InstanceConfigGroup.finalize();
|
InstanceConfigGroup.finalize();
|
||||||
|
|
||||||
libUsers.definePermission({
|
lib.definePermission({
|
||||||
name: "inventory_sync.inventory.view",
|
name: "inventory_sync.inventory.view",
|
||||||
title: "View player inventories",
|
title: "View player inventories",
|
||||||
description: "View player inventories",
|
description: "View player inventories",
|
||||||
|
|||||||
@@ -2,16 +2,13 @@
|
|||||||
* @module
|
* @module
|
||||||
*/
|
*/
|
||||||
"use strict";
|
"use strict";
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
const lib = require("@clusterio/lib");
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
|
||||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
AcquireRequest,
|
AcquireRequest,
|
||||||
ReleaseRequest,
|
ReleaseRequest,
|
||||||
UploadRequest,
|
UploadRequest,
|
||||||
DownloadRequest,
|
DownloadRequest,
|
||||||
DatabaseStatsRequest,
|
|
||||||
} = require("./messages");
|
} = require("./messages");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,7 +21,7 @@ function chunkify(chunkSize, string) {
|
|||||||
return string.match(new RegExp(`.{1,${chunkSize}}`, "g"));
|
return string.match(new RegExp(`.{1,${chunkSize}}`, "g"));
|
||||||
}
|
}
|
||||||
|
|
||||||
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
class InstancePlugin extends lib.BaseInstancePlugin {
|
||||||
async init() {
|
async init() {
|
||||||
this.playersToRelease = new Set();
|
this.playersToRelease = new Set();
|
||||||
this.disconnecting = false;
|
this.disconnecting = false;
|
||||||
@@ -82,14 +79,14 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|||||||
message: acquireResponse.message,
|
message: acquireResponse.message,
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!(err instanceof libErrors.SessionLost)) {
|
if (!(err instanceof lib.SessionLost)) {
|
||||||
this.logger.error(`Unexpected error sending aquire request:\n${err.stack}`);
|
this.logger.error(`Unexpected error sending aquire request:\n${err.stack}`);
|
||||||
response.message = err.message;
|
response.message = err.message;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let json = libLuaTools.escapeString(JSON.stringify(response));
|
let json = lib.escapeString(JSON.stringify(response));
|
||||||
await this.sendRcon(`/sc inventory_sync.acquire_response("${json}")`, true);
|
await this.sendRcon(`/sc inventory_sync.acquire_response("${json}")`, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,7 +98,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|||||||
try {
|
try {
|
||||||
await this.instance.sendTo("controller", new ReleaseRequest(this.instance.id, request.player_name));
|
await this.instance.sendTo("controller", new ReleaseRequest(this.instance.id, request.player_name));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof libErrors.SessionLost) {
|
if (err instanceof lib.SessionLost) {
|
||||||
this.playersToRelease.set(request.player_name);
|
this.playersToRelease.set(request.player_name);
|
||||||
} else {
|
} else {
|
||||||
this.logger.error(`Unexpected error releasing player ${request.player_name}:\n${err.stack}`);
|
this.logger.error(`Unexpected error releasing player ${request.player_name}:\n${err.stack}`);
|
||||||
@@ -122,7 +119,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|||||||
);
|
);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!(err instanceof libErrors.SessionLost)) {
|
if (!(err instanceof lib.SessionLost)) {
|
||||||
this.logger.error(`Unexpected error uploading inventory for ${player_data.name}:\n${err.stack}`);
|
this.logger.error(`Unexpected error uploading inventory for ${player_data.name}:\n${err.stack}`);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
@@ -149,7 +146,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|||||||
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++) {
|
||||||
// this.logger.verbose(`Sending chunk ${i+1} of ${chunks.length}`)
|
// this.logger.verbose(`Sending chunk ${i+1} of ${chunks.length}`)
|
||||||
const chunk = libLuaTools.escapeString(chunks[i]);
|
const chunk = lib.escapeString(chunks[i]);
|
||||||
await this.sendRcon(
|
await this.sendRcon(
|
||||||
`/sc inventory_sync.download_inventory('${playerName}','${chunk}',${i + 1},${chunks.length})`,
|
`/sc inventory_sync.download_inventory('${playerName}','${chunk}',${i + 1},${chunks.length})`,
|
||||||
true
|
true
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { useContext, useEffect, useState } from "react";
|
import React, { useContext, useEffect, useState } from "react";
|
||||||
|
|
||||||
import { libPlugin } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { PageLayout, ControlContext } from "@clusterio/web_ui";
|
import { PageLayout, ControlContext } from "@clusterio/web_ui";
|
||||||
import { DatabaseStatsRequest } from "../messages";
|
import { DatabaseStatsRequest } from "../messages";
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ function InventoryPage() {
|
|||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WebPlugin extends libPlugin.BaseWebPlugin {
|
export class WebPlugin extends lib.BaseWebPlugin {
|
||||||
async init() {
|
async init() {
|
||||||
this.pages = [
|
this.pages = [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,9 +7,8 @@ const express = require("express");
|
|||||||
const util = require("util");
|
const util = require("util");
|
||||||
const jwt = require("jsonwebtoken");
|
const jwt = require("jsonwebtoken");
|
||||||
|
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
const lib = require("@clusterio/lib");
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
const { basicType } = lib;
|
||||||
const { basicType } = require("@clusterio/lib/helpers");
|
|
||||||
|
|
||||||
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("./messages");
|
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("./messages");
|
||||||
|
|
||||||
@@ -30,7 +29,7 @@ async function generateCode(length) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||||
async init() {
|
async init() {
|
||||||
// Store of validation attempts by players
|
// Store of validation attempts by players
|
||||||
this.players = new Map();
|
this.players = new Map();
|
||||||
@@ -174,12 +173,12 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
|||||||
async handleSetVerifyCodeRequest(request) {
|
async handleSetVerifyCodeRequest(request) {
|
||||||
let { player, verifyCode } = request;
|
let { player, verifyCode } = request;
|
||||||
if (!this.players.has(player)) {
|
if (!this.players.has(player)) {
|
||||||
throw new libErrors.RequestError("invalid player");
|
throw new lib.RequestError("invalid player");
|
||||||
}
|
}
|
||||||
|
|
||||||
let entry = this.players.get(player);
|
let entry = this.players.get(player);
|
||||||
if (entry.expires < Date.now()) {
|
if (entry.expires < Date.now()) {
|
||||||
throw new libErrors.RequestError("invalid player");
|
throw new lib.RequestError("invalid player");
|
||||||
}
|
}
|
||||||
|
|
||||||
entry.verifyCode = verifyCode;
|
entry.verifyCode = verifyCode;
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
let { libConfig } = require("@clusterio/lib");
|
const lib = require("@clusterio/lib");
|
||||||
let messages = require("./messages");
|
let messages = require("./messages");
|
||||||
|
|
||||||
|
|
||||||
class ControllerConfigGroup extends libConfig.PluginConfigGroup {}
|
class ControllerConfigGroup extends lib.PluginConfigGroup {}
|
||||||
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
||||||
ControllerConfigGroup.groupName = "player_auth";
|
ControllerConfigGroup.groupName = "player_auth";
|
||||||
ControllerConfigGroup.define({
|
ControllerConfigGroup.define({
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
* @module
|
* @module
|
||||||
*/
|
*/
|
||||||
"use strict";
|
"use strict";
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
const lib = require("@clusterio/lib");
|
||||||
|
|
||||||
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("./messages");
|
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("./messages");
|
||||||
|
|
||||||
|
|
||||||
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
class InstancePlugin extends lib.BaseInstancePlugin {
|
||||||
async init() {
|
async init() {
|
||||||
if (!this.instance.config.get("factorio.enable_save_patching")) {
|
if (!this.instance.config.get("factorio.enable_save_patching")) {
|
||||||
throw new Error("player_auth plugin requires save patching.");
|
throw new Error("player_auth plugin requires save patching.");
|
||||||
|
|||||||
@@ -9,8 +9,7 @@ const controller = require("../controller");
|
|||||||
const instance = require("../instance");
|
const instance = require("../instance");
|
||||||
const info = require("../info");
|
const info = require("../info");
|
||||||
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("../messages");
|
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("../messages");
|
||||||
const libData = require("@clusterio/lib/data");
|
const lib = require("@clusterio/lib");
|
||||||
const libErrors = require("@clusterio/lib/errors");
|
|
||||||
|
|
||||||
|
|
||||||
describe("player_auth", function() {
|
describe("player_auth", function() {
|
||||||
@@ -312,7 +311,7 @@ describe("player_auth", function() {
|
|||||||
controllerPlugin.handleSetVerifyCodeRequest(
|
controllerPlugin.handleSetVerifyCodeRequest(
|
||||||
new SetVerifyCodeRequest("invalid", "invalid")
|
new SetVerifyCodeRequest("invalid", "invalid")
|
||||||
),
|
),
|
||||||
new libErrors.RequestError("invalid player")
|
new lib.RequestError("invalid player")
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
it("should throw if player code has expired", async function() {
|
it("should throw if player code has expired", async function() {
|
||||||
@@ -322,7 +321,7 @@ describe("player_auth", function() {
|
|||||||
controllerPlugin.handleSetVerifyCodeRequest(
|
controllerPlugin.handleSetVerifyCodeRequest(
|
||||||
new SetVerifyCodeRequest("expired", "expired")
|
new SetVerifyCodeRequest("expired", "expired")
|
||||||
),
|
),
|
||||||
new libErrors.RequestError("invalid player")
|
new lib.RequestError("invalid player")
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -379,8 +378,8 @@ describe("player_auth", function() {
|
|||||||
instancePlugin.instance.server.reset();
|
instancePlugin.instance.server.reset();
|
||||||
instancePlugin.instance.connector.once("send", message => {
|
instancePlugin.instance.connector.once("send", message => {
|
||||||
instancePlugin.instance.connector.emit("message",
|
instancePlugin.instance.connector.emit("message",
|
||||||
new libData.MessageResponseError(1, message.dst, message.src,
|
new lib.MessageResponseError(1, message.dst, message.src,
|
||||||
new libData.ResponseError("controller error")
|
new lib.ResponseError("controller error")
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -392,7 +391,7 @@ describe("player_auth", function() {
|
|||||||
instancePlugin.instance.server.reset();
|
instancePlugin.instance.server.reset();
|
||||||
instancePlugin.instance.connector.once("send", message => {
|
instancePlugin.instance.connector.once("send", message => {
|
||||||
instancePlugin.instance.connector.emit("message",
|
instancePlugin.instance.connector.emit("message",
|
||||||
new libData.MessageResponse(1, message.dst, message.src,
|
new lib.MessageResponse(1, message.dst, message.src,
|
||||||
new FetchPlayerCodeRequest.Response("code", "controller-url")
|
new FetchPlayerCodeRequest.Response("code", "controller-url")
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -407,7 +406,7 @@ describe("player_auth", function() {
|
|||||||
instancePlugin.instance.server.reset();
|
instancePlugin.instance.server.reset();
|
||||||
instancePlugin.instance.connector.once("send", message => {
|
instancePlugin.instance.connector.once("send", message => {
|
||||||
instancePlugin.instance.connector.emit("message",
|
instancePlugin.instance.connector.emit("message",
|
||||||
new libData.MessageResponse(1, message.dst, message.src)
|
new lib.MessageResponse(1, message.dst, message.src)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
await instancePlugin.handleEvent(
|
await instancePlugin.handleEvent(
|
||||||
@@ -420,8 +419,8 @@ describe("player_auth", function() {
|
|||||||
instancePlugin.instance.server.reset();
|
instancePlugin.instance.server.reset();
|
||||||
instancePlugin.instance.connector.once("send", message => {
|
instancePlugin.instance.connector.once("send", message => {
|
||||||
instancePlugin.instance.connector.emit("message",
|
instancePlugin.instance.connector.emit("message",
|
||||||
new libData.MessageResponseError(1, message.dst, message.src,
|
new lib.MessageResponseError(1, message.dst, message.src,
|
||||||
new libData.ResponseError("controller error")
|
new lib.ResponseError("controller error")
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
|
|
||||||
import { libPlugin } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { notifyErrorHandler } from "@clusterio/web_ui";
|
import { notifyErrorHandler } from "@clusterio/web_ui";
|
||||||
import { Button, Form, Input, Spin, Typography } from "antd";
|
import { Button, Form, Input, Spin, Typography } from "antd";
|
||||||
|
|
||||||
@@ -146,7 +146,7 @@ function LoginForm(props) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export class WebPlugin extends libPlugin.BaseWebPlugin {
|
export class WebPlugin extends lib.BaseWebPlugin {
|
||||||
async init() {
|
async init() {
|
||||||
this.logger.info("Player Auth init");
|
this.logger.info("Player Auth init");
|
||||||
this.loginForms = [{
|
this.loginForms = [{
|
||||||
|
|||||||
@@ -2,9 +2,8 @@
|
|||||||
const fs = require("fs-extra");
|
const fs = require("fs-extra");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
|
|
||||||
const libFileOps = require("@clusterio/lib/file_ops");
|
const lib = require("@clusterio/lib");
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
const { RateLimiter } = lib;
|
||||||
const RateLimiter = require("@clusterio/lib/RateLimiter");
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
ContributionEvent,
|
ContributionEvent,
|
||||||
@@ -34,10 +33,10 @@ async function loadTechnologies(controllerConfig, logger) {
|
|||||||
async function saveTechnologies(controllerConfig, technologies, logger) {
|
async function saveTechnologies(controllerConfig, technologies, logger) {
|
||||||
let filePath = path.join(controllerConfig.get("controller.database_directory"), "technologies.json");
|
let filePath = path.join(controllerConfig.get("controller.database_directory"), "technologies.json");
|
||||||
logger.verbose(`writing ${filePath}`);
|
logger.verbose(`writing ${filePath}`);
|
||||||
await libFileOps.safeOutputFile(filePath, JSON.stringify([...technologies.entries()], null, 4));
|
await lib.safeOutputFile(filePath, JSON.stringify([...technologies.entries()], null, 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
class ControllerPlugin extends lib.BaseControllerPlugin {
|
||||||
async init() {
|
async init() {
|
||||||
this.technologies = await loadTechnologies(this.controller.config, this.logger);
|
this.technologies = await loadTechnologies(this.controller.config, this.logger);
|
||||||
this.progressRateLimiter = new RateLimiter({
|
this.progressRateLimiter = new RateLimiter({
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const libPlugin = require("@clusterio/lib/plugin");
|
const lib = require("@clusterio/lib");
|
||||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
|
||||||
const {
|
const {
|
||||||
ContributionEvent,
|
ContributionEvent,
|
||||||
ProgressEvent,
|
ProgressEvent,
|
||||||
@@ -10,7 +9,7 @@ const {
|
|||||||
} = require("./messages");
|
} = require("./messages");
|
||||||
|
|
||||||
|
|
||||||
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
class InstancePlugin extends lib.BaseInstancePlugin {
|
||||||
unexpectedError(err) {
|
unexpectedError(err) {
|
||||||
this.logger.error(`Unexpected error:\n${err.stack}`);
|
this.logger.error(`Unexpected error:\n${err.stack}`);
|
||||||
}
|
}
|
||||||
@@ -40,7 +39,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|||||||
if (!this.syncStarted || !["starting", "running"].includes(this.instance.status)) {
|
if (!this.syncStarted || !["starting", "running"].includes(this.instance.status)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let techsJson = libLuaTools.escapeString(JSON.stringify(event.technologies));
|
let techsJson = lib.escapeString(JSON.stringify(event.technologies));
|
||||||
await this.sendOrderedRcon(`/sc research_sync.update_progress("${techsJson}")`, true);
|
await this.sendOrderedRcon(`/sc research_sync.update_progress("${techsJson}")`, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +53,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|||||||
}
|
}
|
||||||
let { name, level } = event;
|
let { name, level } = event;
|
||||||
await this.sendOrderedRcon(
|
await this.sendOrderedRcon(
|
||||||
`/sc research_sync.research_technology("${libLuaTools.escapeString(name)}", ${level})`, true
|
`/sc research_sync.research_technology("${lib.escapeString(name)}", ${level})`, true
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +88,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (techsToSync.length) {
|
if (techsToSync.length) {
|
||||||
let syncJson = libLuaTools.escapeString(JSON.stringify(techsToSync));
|
let syncJson = lib.escapeString(JSON.stringify(techsToSync));
|
||||||
await this.sendOrderedRcon(`/sc research_sync.sync_technologies("${syncJson}")`, true);
|
await this.sendOrderedRcon(`/sc research_sync.sync_technologies("${syncJson}")`, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
const { libData } = require("@clusterio/lib");
|
const lib = require("@clusterio/lib");
|
||||||
|
|
||||||
class ContributionEvent {
|
class ContributionEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
@@ -41,7 +41,7 @@ class ProgressEvent {
|
|||||||
static dst = "instance";
|
static dst = "instance";
|
||||||
static plugin = "research_sync";
|
static plugin = "research_sync";
|
||||||
|
|
||||||
/** @type {Array<>} */
|
/** @type {Array<Technology>} */
|
||||||
technologies;
|
technologies;
|
||||||
|
|
||||||
constructor(technologies) {
|
constructor(technologies) {
|
||||||
@@ -167,7 +167,7 @@ class SyncTechnologiesRequest {
|
|||||||
return new this(json.map(e => Technology.fromJSON(e)));
|
return new this(json.map(e => Technology.fromJSON(e)));
|
||||||
}
|
}
|
||||||
|
|
||||||
static Response = libData.jsonArray(Technology);
|
static Response = lib.jsonArray(Technology);
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|||||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user