mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-25 16:33:12 +09:00
Merge upstream/master and address review
Resolves the ESM conflicts in patch.ts, Instance.ts and host.ts. The module gathering in Instance now goes through patch.loadModules with the instance's loadedPlugins, and imports use explicit extensions. Review changes: the existing-output check only treats ENOENT as "does not exist" and rethrows anything else, a --zip option keeps the output as a zip file for transfer (extracting stays the default), the --scenario option describes that it takes a path and what the default is, and the docs note that IPC is not available outside Clusterio. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
commit
187138bec5
297 files changed
+4980
-3274
No files matched your search
@@ -6,12 +6,11 @@
|
|||||||
* clean-all: Removes all build, test, and execution artifacts. Including cluster config and logs!
|
* clean-all: Removes all build, test, and execution artifacts. Including cluster config and logs!
|
||||||
*/
|
*/
|
||||||
|
|
||||||
"use strict";
|
import path from "node:path";
|
||||||
const path = require("path");
|
import fs from "node:fs/promises";
|
||||||
const fs = require("node:fs/promises");
|
import yargs from "yargs";
|
||||||
const yargs = require("yargs");
|
|
||||||
|
|
||||||
const npmPackage = require("./package.json");
|
import npmPackage from "./package.json" with { type: "json" };
|
||||||
const workspaces = npmPackage.workspaces
|
const workspaces = npmPackage.workspaces
|
||||||
.map(p => p.slice(0, -2))
|
.map(p => p.slice(0, -2))
|
||||||
.filter(p => !p.includes("external_plugins"));
|
.filter(p => !p.includes("external_plugins"));
|
||||||
@@ -116,6 +115,6 @@ async function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Run main if started from command line
|
// Run main if started from command line
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
main();
|
main();
|
||||||
}
|
}
|
||||||
+41
-2
@@ -3,10 +3,10 @@
|
|||||||
<sub>This document describes the implementation and inner working of the configuration system in Clusterio, and unless you're developing Clusterio it's probably not going to be very useful for you.</sub>
|
<sub>This document describes the implementation and inner working of the configuration system in Clusterio, and unless you're developing Clusterio it's probably not going to be very useful for you.</sub>
|
||||||
|
|
||||||
Clusterio uses a field based configuration system to manage settings for the controller, instances, hosts, and the clusterioctl utility.
|
Clusterio uses a field based configuration system to manage settings for the controller, instances, hosts, and the clusterioctl utility.
|
||||||
Plugins can add their own config fields for the controller and instances configs.
|
Plugins can add their own config fields for the controller, host and instance configs.
|
||||||
The fields are defined early in the startup, and fields for disabled plugins will still be created.
|
The fields are defined early in the startup, and fields for disabled plugins will still be created.
|
||||||
|
|
||||||
The built-in config fields are defined in [packages/lib/src/config/definitions.ts](/packages/lib/src/config/definitions.ts) while plugins can add their own config field definitions to the `controllerConfigFields` and `instanceConfigFields` properties of the `plugin` export.
|
The built-in config fields are defined in [packages/lib/src/config/definitions.ts](/packages/lib/src/config/definitions.ts) while plugins can add their own config field definitions to the `controllerConfigFields`, `hostConfigFields` and `instanceConfigFields` properties of the `plugin` export.
|
||||||
A `<plugin_name>.load_plugin` field is automatically created for each plugin and it's used to enable/disable the loading plugins on startup.
|
A `<plugin_name>.load_plugin` field is automatically created for each plugin and it's used to enable/disable the loading plugins on startup.
|
||||||
|
|
||||||
|
|
||||||
@@ -46,6 +46,45 @@ For plugins the group name is the name of the plugin, e.g., the `level` field of
|
|||||||
Value this config field should take in a newly initialized config.
|
Value this config field should take in a newly initialized config.
|
||||||
This can also be an async function returning the value to use.
|
This can also be an async function returning the value to use.
|
||||||
|
|
||||||
|
**validator** (optional):
|
||||||
|
Function called with the value being set and the config it belongs to.
|
||||||
|
It should throw an error if the value is not acceptable, and the message of the error is passed on to whoever tried to set it.
|
||||||
|
Common validators such as `greaterThanZero`, `greaterThanEqualZero`, `integer` and `filePath` are available on `Config.validators`, along with `optional` to skip null and `all` to combine several.
|
||||||
|
The config is read only while the validator runs.
|
||||||
|
|
||||||
|
**dependsOn** (optional):
|
||||||
|
Names of other fields the validator reads the value of.
|
||||||
|
When one of those fields is changed the validator of this field is run again against the new value, and the change is rejected if it fails.
|
||||||
|
|
||||||
|
**restartRequired** (optional):
|
||||||
|
True if a restart of the controller, host or instance the config belongs to is needed for changes to take effect.
|
||||||
|
Changing such a field sets the `restartRequired` flag on the config, which the web interface uses to show that a restart is pending.
|
||||||
|
Defaults to false.
|
||||||
|
|
||||||
|
**restartRequiredProps** (optional):
|
||||||
|
For object fields, names of properties that have the opposite of `restartRequired`.
|
||||||
|
Only used by the web interface to show which properties need a restart, `factorio.settings` uses it to mark the settings that are applied live.
|
||||||
|
|
||||||
|
**credential** (optional):
|
||||||
|
Locations allowed to read the value of this field.
|
||||||
|
Other locations can still change the value if allowed by `access`, which is what you want for tokens and passwords.
|
||||||
|
|
||||||
|
**readonly** (optional):
|
||||||
|
Locations allowed to change the value of this field.
|
||||||
|
Other locations can still read the value if allowed by `access`.
|
||||||
|
|
||||||
|
**hidden** (optional):
|
||||||
|
True if the web interface should not show this field.
|
||||||
|
Used for internal values that are managed by Clusterio.
|
||||||
|
|
||||||
|
**autoComplete** (optional):
|
||||||
|
Value for the autocomplete attribute of the input in the web interface, e.g. `section-factorio new-password`.
|
||||||
|
Only used for string and number fields.
|
||||||
|
|
||||||
|
**inputComponent** (optional):
|
||||||
|
Name of the input component the web interface should render for this field instead of the default for its type.
|
||||||
|
Plugins can add their own components through `inputComponents` on their web plugin class.
|
||||||
|
|
||||||
If the value for a field stored in on disk somehow ends up being invalid the field will take on the initial\_value instead when the config is loaded.
|
If the value for a field stored in on disk somehow ends up being invalid the field will take on the initial\_value instead when the config is loaded.
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+322
-14
@@ -1,5 +1,15 @@
|
|||||||
# Configuration
|
# Configuration
|
||||||
|
|
||||||
|
Config values are changed with the `config set` commands of clusterioctl, clusteriocontroller and clusteriohost, or from the settings pages in the web interface.
|
||||||
|
See [Managing a Cluster](/docs/managing-a-cluster.md) for the commands.
|
||||||
|
|
||||||
|
All values are checked against the type of the field when set.
|
||||||
|
Some fields have additional rules on top of that, such as a number having to be greater than 0, and these are listed under the field.
|
||||||
|
Setting a value that fails a check is rejected with an error and the old value is kept.
|
||||||
|
|
||||||
|
A few fields are internal to Clusterio.
|
||||||
|
These are managed by Clusterio itself, hidden in the web interface and should not be modified by hand.
|
||||||
|
|
||||||
|
|
||||||
## Controller Configuration
|
## Controller Configuration
|
||||||
|
|
||||||
@@ -20,11 +30,30 @@ This is also used by plugins to store its data.
|
|||||||
Defaults to "database".
|
Defaults to "database".
|
||||||
|
|
||||||
|
|
||||||
|
### controller.mods_directory
|
||||||
|
|
||||||
|
Directory where mods shared with the cluster are stored.
|
||||||
|
Mods uploaded through the web interface or downloaded from the mod portal end up here, and hosts fetch the mods they need for their instances from here.
|
||||||
|
Needs to be writeable by the controller.
|
||||||
|
|
||||||
|
Defaults to "mods".
|
||||||
|
|
||||||
|
|
||||||
|
### controller.autosave_interval
|
||||||
|
|
||||||
|
Interval in seconds the controller saves the data it holds in memory, such as users, instances, mod packs and plugin data, to controller.database_directory.
|
||||||
|
The data is also saved on shutdown.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
|
Defaults to 60.
|
||||||
|
|
||||||
|
|
||||||
### controller.http_port
|
### controller.http_port
|
||||||
|
|
||||||
Port to host HTTP server on.
|
Port to host HTTP server on.
|
||||||
If set to null no HTTP server will be exposed.
|
If set to null no HTTP server will be exposed.
|
||||||
At least one of this and controller.https_port needs to be set to a port.
|
At least one of this and controller.https_port needs to be set to a port.
|
||||||
|
Must be a whole number greater than 0.
|
||||||
|
|
||||||
Defaults to 8080.
|
Defaults to 8080.
|
||||||
|
|
||||||
@@ -35,6 +64,7 @@ Port to host HTTPS server on.
|
|||||||
Uses controller.tls_certificate and controller.tls_private_key as the certificate and private key for the HTTPS server.
|
Uses controller.tls_certificate and controller.tls_private_key as the certificate and private key for the HTTPS server.
|
||||||
If set to null no HTTPS server will be exposed.
|
If set to null no HTTPS server will be exposed.
|
||||||
At least one of this and controller.http_port needs to be set to a port.
|
At least one of this and controller.http_port needs to be set to a port.
|
||||||
|
Must be a whole number greater than 0.
|
||||||
|
|
||||||
See the [Setting up TLS](/docs/setting-up-tls.md) document for a guide to setting up HTTPS with Clusterio.
|
See the [Setting up TLS](/docs/setting-up-tls.md) document for a guide to setting up HTTPS with Clusterio.
|
||||||
|
|
||||||
@@ -51,10 +81,19 @@ interfaces.
|
|||||||
Defaults to null.
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.trusted_proxies
|
||||||
|
|
||||||
|
Comma separated list of IP addresses and/or CIDR blocks of reverse proxies in front of the controller to trust the `X-Forwarded-For` header from.
|
||||||
|
When a connection comes from one of these addresses the last address in the `X-Forwarded-For` header is used as the remote address of the connection instead of the address of the proxy.
|
||||||
|
Entries that are not valid IP addresses are logged as errors and ignored.
|
||||||
|
|
||||||
|
Defaults to null meaning the header is never trusted.
|
||||||
|
|
||||||
|
|
||||||
### controller.public_url
|
### controller.public_url
|
||||||
|
|
||||||
Public address the controller is accessible on.
|
Public address the controller is accessible on.
|
||||||
Currently only used for `clusteriocontroller bootstrap create-ctl-config` in order to give the right url to connect to.
|
Used as the URL in configs generated with `clusteriocontroller bootstrap create-ctl-config` and `clusterioctl host create-config`, and by plugins like Player Auth that need to show the address of the web interface in-game.
|
||||||
This should be a full URL ending with a /.
|
This should be a full URL ending with a /.
|
||||||
|
|
||||||
Defaults to null meaning assume localhost.
|
Defaults to null meaning assume localhost.
|
||||||
@@ -64,25 +103,34 @@ Defaults to null meaning assume localhost.
|
|||||||
|
|
||||||
Used to override where static assets such as the web bundle is loaded from.
|
Used to override where static assets such as the web bundle is loaded from.
|
||||||
This can be used if you want to put the static assets on a separate cdn url like `https://cdn.example.com/static/` while keeping the API hosted directly by clusterio.
|
This can be used if you want to put the static assets on a separate cdn url like `https://cdn.example.com/static/` while keeping the API hosted directly by clusterio.
|
||||||
Due to a limitation on how the webpack assets are built the pathname component of the url have to be `/static/`.
|
Due to a limitation on how the webpack assets are built the pathname component of the url have to be `/static/`, values with any other path are rejected.
|
||||||
|
|
||||||
See also the `clusteriocontroller copy-static` command for how to obtain the static asset files that need to be hosted.
|
See also the `clusteriocontroller copy-static` command for how to obtain the static asset files that need to be hosted.
|
||||||
|
|
||||||
Defaults to null meaning use the internally hosted assets.
|
Defaults to null meaning use the internally hosted assets.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.grafana_url
|
||||||
|
|
||||||
|
URL of a Grafana dashboard to link to from the overview page of the web interface, including the protocol.
|
||||||
|
If null no link is shown.
|
||||||
|
|
||||||
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
### controller.tls_certificate
|
### controller.tls_certificate
|
||||||
|
|
||||||
Path to TLS certificate to use for the HTTPS server when controller.https_port is configured.
|
Path to TLS certificate to use for the HTTPS server when controller.https_port is configured.
|
||||||
|
Both this and controller.tls_private_key have to be set for the controller to start with controller.https_port configured.
|
||||||
|
|
||||||
Defaults to "database/certificates/cert.crt".
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
### controller.tls_private_key
|
### controller.tls_private_key
|
||||||
|
|
||||||
Path to TLS private key to use for the HTTPS server when controller.https_port is configured.
|
Path to TLS private key to use for the HTTPS server when controller.https_port is configured.
|
||||||
|
|
||||||
Defaults to "database/certificates/cert.key".
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
### controller.auth_secret
|
### controller.auth_secret
|
||||||
@@ -90,6 +138,7 @@ Defaults to "database/certificates/cert.key".
|
|||||||
Base64 encoded authentication secret used to verify tokens issued to hosts, users, and sessions.
|
Base64 encoded authentication secret used to verify tokens issued to hosts, users, and sessions.
|
||||||
This should contain 256 bytes of random data, and if changed will cause all tokens become invalid.
|
This should contain 256 bytes of random data, and if changed will cause all tokens become invalid.
|
||||||
Keep this secret if leaked an attacker could easily compromise the cluster.
|
Keep this secret if leaked an attacker could easily compromise the cluster.
|
||||||
|
The value can only be read and changed from the controller itself, it is not available through clusterioctl or the web interface.
|
||||||
|
|
||||||
Defaults to null which means generate a secure secret on startup.
|
Defaults to null which means generate a secure secret on startup.
|
||||||
|
|
||||||
@@ -99,6 +148,7 @@ Defaults to null which means generate a secure secret on startup.
|
|||||||
Interval in seconds heartbeats are sent out at for WebSocket connections.
|
Interval in seconds heartbeats are sent out at for WebSocket connections.
|
||||||
If a WebSocket connection hasn't received a heartbeat in 2 times the heartbeat interval it will be considered stale and closed.
|
If a WebSocket connection hasn't received a heartbeat in 2 times the heartbeat interval it will be considered stale and closed.
|
||||||
A lower value means less time between connections going stale and them being closed.
|
A lower value means less time between connections going stale and them being closed.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
Defaults to 15.
|
Defaults to 15.
|
||||||
|
|
||||||
@@ -110,6 +160,8 @@ A higher timeout gives more time for a client to recconect and resume an active
|
|||||||
In the case of the controller or client crashing the data loss is unavoidable.
|
In the case of the controller or client crashing the data loss is unavoidable.
|
||||||
|
|
||||||
Value should not be less than the configured `max_reconnect_delay` of the clients and it should be greater than 2 times `controller.heartbeat_interval`.
|
Value should not be less than the configured `max_reconnect_delay` of the clients and it should be greater than 2 times `controller.heartbeat_interval`.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
Defaults to 60.
|
Defaults to 60.
|
||||||
|
|
||||||
|
|
||||||
@@ -117,18 +169,64 @@ Defaults to 60.
|
|||||||
|
|
||||||
Timeout in seconds before a call to gather metrics from a host times out.
|
Timeout in seconds before a call to gather metrics from a host times out.
|
||||||
This should be less than both the timeout and collection interval configured for the collection job in Prometheus.
|
This should be less than both the timeout and collection interval configured for the collection job in Prometheus.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
Defaults to 8.
|
Defaults to 8.
|
||||||
|
|
||||||
|
|
||||||
### controller.stream_timeout
|
### controller.system_metrics_interval
|
||||||
|
|
||||||
|
Interval in seconds the controller gathers CPU, memory and disk usage from itself and every connected host for display in the web interface.
|
||||||
|
Whether the controller needs a restart to apply an update is also checked on this interval.
|
||||||
|
If 0 system metrics are not gathered.
|
||||||
|
Must be 0 or greater.
|
||||||
|
|
||||||
|
Defaults to 10.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.proxy_stream_timeout
|
||||||
|
|
||||||
Timeout in seconds for proxy streams through the controller that has been created but is not yet sending data to be automatically closed.
|
Timeout in seconds for proxy streams through the controller that has been created but is not yet sending data to be automatically closed.
|
||||||
Streams that have started sending data before this timeout is not affected.
|
Streams that have started sending data before this timeout is not affected.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
Defaults to 15.
|
Defaults to 15.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.factorio_username
|
||||||
|
|
||||||
|
Username of the Factorio.com account to authenticate with the Factorio API with.
|
||||||
|
Together with controller.factorio_token this is used by the controller to download mods from the mod portal, and if controller.share_factorio_credentials_with_hosts is enabled, as the credentials in the server settings of instances.
|
||||||
|
|
||||||
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.factorio_token
|
||||||
|
|
||||||
|
Token of the Factorio.com account to authenticate with the Factorio API with, see controller.factorio_username.
|
||||||
|
This is the token shown on your profile page on factorio.com, not your password.
|
||||||
|
The value is treated as a credential, it can be set from anywhere but only read back from the controller itself.
|
||||||
|
|
||||||
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.share_factorio_credentials_with_hosts
|
||||||
|
|
||||||
|
If enabled hosts get controller.factorio_username and controller.factorio_token from the controller when they start an instance and put them in the server settings of that instance.
|
||||||
|
Credentials set on the host with host.factorio_username and host.factorio_token, or on the instance through `username` and `token` in factorio.settings, take precedence over the ones from the controller.
|
||||||
|
Disable this if you don't want the controller's credentials to be sent to the hosts.
|
||||||
|
|
||||||
|
Defaults to true.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.default_mod_pack_id
|
||||||
|
|
||||||
|
ID of the mod pack to use for instances that don't have factorio.mod_pack_id set.
|
||||||
|
Instances without a mod pack of their own fail to start if this is null.
|
||||||
|
|
||||||
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
### controller.default_role_id
|
### controller.default_role_id
|
||||||
|
|
||||||
Role to automatically grant to new users.
|
Role to automatically grant to new users.
|
||||||
@@ -137,6 +235,55 @@ If null no role is granted.
|
|||||||
Defaults to 1 which correspond to the default Player role.
|
Defaults to 1 which correspond to the default Player role.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.mod_portal_cache_duration_minutes
|
||||||
|
|
||||||
|
Time in minutes the controller caches the list of mods fetched from the Factorio mod portal when browsing it from the web interface.
|
||||||
|
Set to 0 to disable the cache and fetch the list on every request.
|
||||||
|
Must be 0 or greater.
|
||||||
|
|
||||||
|
Defaults to 30.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.mod_portal_page_size
|
||||||
|
|
||||||
|
Number of results to request per page when fetching the list of mods from the Factorio mod portal.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
|
Defaults to 1000.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.allow_remote_updates
|
||||||
|
|
||||||
|
Whether the `controller update` command in clusterioctl and the update button in the web interface are allowed to update the `@clusterio/controller` package with npm.
|
||||||
|
For security reasons this can only be changed locally with `clusteriocontroller config set` while the controller is stopped, and it is hidden in the web interface.
|
||||||
|
See [Managing a Cluster](/docs/managing-a-cluster.md) for details on remote updates.
|
||||||
|
|
||||||
|
Defaults to true.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.allow_plugin_updates
|
||||||
|
|
||||||
|
Whether remote requests to update plugins installed on the controller with npm are allowed.
|
||||||
|
Like controller.allow_remote_updates this can only be changed locally.
|
||||||
|
|
||||||
|
Defaults to true.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.allow_plugin_install
|
||||||
|
|
||||||
|
Whether remote requests to install new plugins on the controller with npm are allowed.
|
||||||
|
Like controller.allow_remote_updates this can only be changed locally.
|
||||||
|
|
||||||
|
Defaults to false.
|
||||||
|
|
||||||
|
|
||||||
|
### controller.version
|
||||||
|
|
||||||
|
Version of the controller package that last loaded this config.
|
||||||
|
Set automatically on startup and used to detect when the controller has been updated or downgraded.
|
||||||
|
Internal, hidden in the web interface and should not be changed.
|
||||||
|
|
||||||
|
|
||||||
### <plugin_name>.load_plugin
|
### <plugin_name>.load_plugin
|
||||||
|
|
||||||
Whether to load the plugin on the controller.
|
Whether to load the plugin on the controller.
|
||||||
@@ -158,6 +305,7 @@ Defaults to "New Host".
|
|||||||
### host.id
|
### host.id
|
||||||
|
|
||||||
Immutable numeric id of the host which uniquely identifies this host in the cluster.
|
Immutable numeric id of the host which uniquely identifies this host in the cluster.
|
||||||
|
Hidden in the web interface.
|
||||||
|
|
||||||
Defaults to a random 31 bit number.
|
Defaults to a random 31 bit number.
|
||||||
|
|
||||||
@@ -170,6 +318,14 @@ This can either point to a Factorio server directory, or to a directory containi
|
|||||||
Defaults to "factorio".
|
Defaults to "factorio".
|
||||||
|
|
||||||
|
|
||||||
|
### host.mods_directory
|
||||||
|
|
||||||
|
Directory the host stores mods downloaded from the controller in.
|
||||||
|
When an instance starts the mods in its mod pack are downloaded here if missing and then linked into the mods directory of the instance.
|
||||||
|
|
||||||
|
Defaults to "mods".
|
||||||
|
|
||||||
|
|
||||||
### host.instances_directory
|
### host.instances_directory
|
||||||
|
|
||||||
Directory to store instances in.
|
Directory to store instances in.
|
||||||
@@ -189,6 +345,7 @@ Defaults to "http://localhost:8080/".
|
|||||||
|
|
||||||
Access token used for authenticating with the controller.
|
Access token used for authenticating with the controller.
|
||||||
You can generate an access token with `clusterioctl host generate-token --id <host-id>`, or use the `clusterioctl host create-config` to create a new host config with the correct url and token in it.
|
You can generate an access token with `clusterioctl host generate-token --id <host-id>`, or use the `clusterioctl host create-config` to create a new host config with the correct url and token in it.
|
||||||
|
The value can only be read and changed from the host itself.
|
||||||
|
|
||||||
Defaults to "enter token here".
|
Defaults to "enter token here".
|
||||||
|
|
||||||
@@ -201,14 +358,82 @@ This is used by plugins like Server Select to give the correct address to switch
|
|||||||
Defaults to "localhost".
|
Defaults to "localhost".
|
||||||
|
|
||||||
|
|
||||||
|
### host.factorio_port_range
|
||||||
|
|
||||||
|
UDP ports the host hands out to instances that don't have factorio.game_port set.
|
||||||
|
Written as a comma separated list of ports and/or ranges of ports separated with a dash, for example "34100-34199" or "34100, 34200-34210".
|
||||||
|
A port is picked when the instance is started and remembered in factorio.host_assigned_game_port, so an instance keeps the same port as long as it is still free.
|
||||||
|
Starting an instance fails if all ports in the range are taken.
|
||||||
|
|
||||||
|
Defaults to "34100-34199".
|
||||||
|
|
||||||
|
|
||||||
|
### host.factorio_username
|
||||||
|
|
||||||
|
Username of the Factorio.com account to put in the server settings of instances on this host.
|
||||||
|
If set this takes precedence over the credentials shared by the controller, but not over `username` set in factorio.settings of an instance.
|
||||||
|
|
||||||
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
|
### host.factorio_token
|
||||||
|
|
||||||
|
Token of the Factorio.com account to go with host.factorio_username.
|
||||||
|
The value is treated as a credential, it can be set from anywhere but only read back from the host itself.
|
||||||
|
|
||||||
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
### host.max_reconnect_delay
|
### host.max_reconnect_delay
|
||||||
|
|
||||||
Maximum delay in seconds to wait after connection to the controller is dropped before attempting to reconnect to it.
|
Maximum delay in seconds to wait after connection to the controller is dropped before attempting to reconnect to it.
|
||||||
The actual delay on each reconnect will be a random number between 0 and this configured value to avoid all clients trying to reconnect at the same time.
|
The actual delay on each reconnect will be a random number between 0 and this configured value to avoid all clients trying to reconnect at the same time.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
Defaults to 60.
|
Defaults to 60.
|
||||||
|
|
||||||
|
|
||||||
|
### host.allow_remote_updates
|
||||||
|
|
||||||
|
Whether the `host update` command in clusterioctl and the update button in the web interface are allowed to update the `@clusterio/host` package with npm.
|
||||||
|
For security reasons this can only be changed locally with `clusteriohost config set` while the host is stopped, and it is hidden in the web interface.
|
||||||
|
See [Managing a Cluster](/docs/managing-a-cluster.md) for details on remote updates.
|
||||||
|
|
||||||
|
Defaults to true.
|
||||||
|
|
||||||
|
|
||||||
|
### host.allow_plugin_updates
|
||||||
|
|
||||||
|
Whether remote requests to update plugins installed on the host with npm are allowed.
|
||||||
|
Like host.allow_remote_updates this can only be changed locally.
|
||||||
|
|
||||||
|
Defaults to true.
|
||||||
|
|
||||||
|
|
||||||
|
### host.allow_plugin_install
|
||||||
|
|
||||||
|
Whether remote requests to install new plugins on the host with npm are allowed.
|
||||||
|
Like host.allow_remote_updates this can only be changed locally.
|
||||||
|
|
||||||
|
Defaults to false.
|
||||||
|
|
||||||
|
|
||||||
|
### host.version
|
||||||
|
|
||||||
|
Version of the host package that last loaded this config.
|
||||||
|
Set automatically on startup and used to detect when the host has been updated or downgraded.
|
||||||
|
Internal, hidden in the web interface and should not be changed.
|
||||||
|
|
||||||
|
|
||||||
|
### <plugin_name>.load_plugin
|
||||||
|
|
||||||
|
Whether to load the plugin on the host.
|
||||||
|
Only plugins with a host or instance part have this field in the host config.
|
||||||
|
Plugins not loaded on the host will not be loaded on the instances it hosts.
|
||||||
|
|
||||||
|
Defaults to true.
|
||||||
|
|
||||||
|
|
||||||
## Instance Configuration
|
## Instance Configuration
|
||||||
|
|
||||||
### instance.name
|
### instance.name
|
||||||
@@ -221,6 +446,7 @@ Defaults to "New Instance".
|
|||||||
### instance.id
|
### instance.id
|
||||||
|
|
||||||
Imutable numeric id of the instance which uniquely identifies this instance in the cluster.
|
Imutable numeric id of the instance which uniquely identifies this instance in the cluster.
|
||||||
|
Hidden in the web interface.
|
||||||
|
|
||||||
Defaluts to a random 31 bit integer.
|
Defaluts to a random 31 bit integer.
|
||||||
|
|
||||||
@@ -230,6 +456,7 @@ Defaluts to a random 31 bit integer.
|
|||||||
Host this instance is assigned to.
|
Host this instance is assigned to.
|
||||||
To change this you need to use the separate assign instance interface.
|
To change this you need to use the separate assign instance interface.
|
||||||
After being assigned to a host the directory for the instance is created on the host.
|
After being assigned to a host the directory for the instance is created on the host.
|
||||||
|
Internal and hidden in the web interface.
|
||||||
|
|
||||||
Defaults to null meaning not assigned.
|
Defaults to null meaning not assigned.
|
||||||
|
|
||||||
@@ -253,23 +480,52 @@ Defaults to false.
|
|||||||
### factorio.version
|
### factorio.version
|
||||||
|
|
||||||
Version of Factorio to use for this instance.
|
Version of Factorio to use for this instance.
|
||||||
Can be a version like "1.0.0" or special string "latest" meaning the latest version of Factorio found on the host.
|
Can be a specific version like "2.0" or "2.0.15", a release channel like "stable" or "experimental", or the special string "latest" meaning the latest version of Factorio found on the host.
|
||||||
|
A release channel is resolved to a version through the latest releases data the controller keeps, and the instance fails to start if that is unavailable.
|
||||||
|
Values that don't match one of these forms are rejected.
|
||||||
|
|
||||||
Defaults to "latest".
|
Defaults to "latest".
|
||||||
|
|
||||||
|
|
||||||
|
### factorio.executable_path
|
||||||
|
|
||||||
|
Path relative to the Factorio installation directory of the executable to run.
|
||||||
|
If null the path is auto detected, which is `bin/x64/factorio` on Linux and Windows and `MacOS/factorio` on macOS.
|
||||||
|
Only needed in special setups.
|
||||||
|
|
||||||
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
|
### factorio.shutdown_timeout
|
||||||
|
|
||||||
|
Time in seconds to wait for the Factorio server to exit after asking it to stop before the process is killed.
|
||||||
|
Set to 0 to wait forever.
|
||||||
|
Changing this while the instance is stopping restarts the timer with the new value.
|
||||||
|
Must be 0 or greater.
|
||||||
|
|
||||||
|
Defaults to 300.
|
||||||
|
|
||||||
|
|
||||||
### factorio.game_port
|
### factorio.game_port
|
||||||
|
|
||||||
UDP port to run the Factorio server on.
|
UDP port to run the Factorio server on.
|
||||||
If null a random port in the dynamyc range assigned each time the instance starts.
|
If null a port from host.factorio_port_range on the host is assigned to the instance.
|
||||||
|
Negative values are rejected.
|
||||||
|
|
||||||
Defaults to null.
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
|
### factorio.host_assigned_game_port
|
||||||
|
|
||||||
|
Port from host.factorio_port_range the host has assigned to this instance while factorio.game_port is null.
|
||||||
|
Internal, set by the host and only accessible from the host.
|
||||||
|
|
||||||
|
|
||||||
### factorio.rcon_port
|
### factorio.rcon_port
|
||||||
|
|
||||||
TCP port to start the RCON interface on the Factorio server on.
|
TCP port to start the RCON interface on the Factorio server on.
|
||||||
If null a random port in the dynamic range is assigned each time the instance starts.
|
If null a random port in the dynamic range is assigned each time the instance starts.
|
||||||
|
Negative values are rejected.
|
||||||
|
|
||||||
Defaults to null.
|
Defaults to null.
|
||||||
|
|
||||||
@@ -278,16 +534,18 @@ Defaults to null.
|
|||||||
|
|
||||||
Password to use for the RCON interafec.
|
Password to use for the RCON interafec.
|
||||||
If null a random secure password is generated and used each time the instance starts.
|
If null a random secure password is generated and used each time the instance starts.
|
||||||
|
The value is treated as a credential and can only be read back by the controller and the host.
|
||||||
|
|
||||||
Defaults to null.
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
### player_online_autosave_slots
|
### factorio.player_online_autosave_slots
|
||||||
|
|
||||||
Keeps a separate pool for autosaves where at least on player has been online since the previous autosave was done.
|
Keeps a separate pool for autosaves where at least on player has been online since the previous autosave was done.
|
||||||
This requires regular autosaving to be enabled and will rename autosaves to `_autosave_poN.zip` (where N is a slot number) whenever a player has been online for that save.
|
This requires regular autosaving to be enabled and will rename autosaves to `_autosave_poN.zip` (where N is a slot number) whenever a player has been online for that save.
|
||||||
The slot numbers start at 1, are incremented by 1 after each autosave that is renamed and reset back to 1 whenever this value is exceeded.
|
The slot numbers start at 1, are incremented by 1 after each autosave that is renamed and reset back to 1 whenever this value is exceeded.
|
||||||
Note that this value should be set to a higher value than the value of `autosave_slots` in `factorio.settings`.
|
Setting this to a value lower than `autosave_slots` in factorio.settings is rejected, unless it is 0.
|
||||||
|
The same check is done when factorio.settings is changed.
|
||||||
Useful for preventing the loss of all progress when nobody is around on always online servers with auto pause disabled.
|
Useful for preventing the loss of all progress when nobody is around on always online servers with auto pause disabled.
|
||||||
|
|
||||||
If 0 no autosave renaming takes place.
|
If 0 no autosave renaming takes place.
|
||||||
@@ -295,12 +553,34 @@ If 0 no autosave renaming takes place.
|
|||||||
Defaults to 5.
|
Defaults to 5.
|
||||||
|
|
||||||
|
|
||||||
|
### factorio.mod_pack_id
|
||||||
|
|
||||||
|
ID of the mod pack to use on this instance.
|
||||||
|
The mods in the pack are linked into the mods directory of the instance every time it starts, and any other files in that directory are removed.
|
||||||
|
If null the mod pack set in controller.default_mod_pack_id is used.
|
||||||
|
|
||||||
|
Defaults to null.
|
||||||
|
|
||||||
|
|
||||||
### factorio.enable_save_patching
|
### factorio.enable_save_patching
|
||||||
|
|
||||||
Whether to use save patching or not.
|
Whether to use save patching or not.
|
||||||
When enabled lua code is patched into the game save before starting it.
|
When enabled lua code is patched into the game save before starting it.
|
||||||
Most plugins require the use of save patching to function.
|
Most plugins require the use of save patching to function.
|
||||||
Turning it off makes it possible to use Clusterio to run and manage regular vanilla games and scenarios not compatible with Clusterio.
|
Turning it off makes it possible to use Clusterio to run and manage regular vanilla games and scenarios not compatible with Clusterio.
|
||||||
|
Plugins that need save patching can't be loaded on the instance while this is disabled.
|
||||||
|
Disabling it while such a plugin is loaded is rejected, and so is loading such a plugin while it is disabled.
|
||||||
|
|
||||||
|
Defaults to true.
|
||||||
|
|
||||||
|
|
||||||
|
### factorio.enable_script_commands
|
||||||
|
|
||||||
|
Allow Clusterio and plugins to send commands that disable achievements to the server over RCON, that is `/c`, `/sc`, `/mc`, `/cheat`, `/editor` and their long forms.
|
||||||
|
Clusterio integrations and most plugins need this, and when enabled achievements are disabled on the server at startup.
|
||||||
|
When disabled attempts to send such a command fail with an error.
|
||||||
|
This does not stop players from using these commands themselves.
|
||||||
|
Like factorio.enable_save_patching, plugins that need script commands can't be loaded on the instance while this is disabled.
|
||||||
|
|
||||||
Defaults to true.
|
Defaults to true.
|
||||||
|
|
||||||
@@ -312,6 +592,13 @@ Turn on the whitelist on the server.
|
|||||||
Defaults to false.
|
Defaults to false.
|
||||||
|
|
||||||
|
|
||||||
|
### factorio.enable_authserver_bans
|
||||||
|
|
||||||
|
Pass the `--use-authserver-bans` flag to Factorio, which makes the server check connecting players against the multiplayer bans on Factorio.com and report bans and unbans done on the server back to it.
|
||||||
|
|
||||||
|
Defaults to false.
|
||||||
|
|
||||||
|
|
||||||
### factorio.settings
|
### factorio.settings
|
||||||
|
|
||||||
Object with the settings to put into `server-settings.json` for the Factorio server.
|
Object with the settings to put into `server-settings.json` for the Factorio server.
|
||||||
@@ -319,7 +606,7 @@ The settings in `data/server-settings.example.json` of the Factorio installation
|
|||||||
|
|
||||||
Changes to the following properties will be applied live if the instance is running while it is changed: `afk_autokick_interval`, `allow_commands`, `autosave_interval`, `autosave_only_on_server`, `description`, `ignore_player_limit_for_returning_players`, `max_players`, `max_upload_slots`, `max_upload_in_kilobytes_per_second`, `name`, `only_admins_can_pause_the_game`, `game_password`, `require_user_verification`, `tags`, `visibility`.
|
Changes to the following properties will be applied live if the instance is running while it is changed: `afk_autokick_interval`, `allow_commands`, `autosave_interval`, `autosave_only_on_server`, `description`, `ignore_player_limit_for_returning_players`, `max_players`, `max_upload_slots`, `max_upload_in_kilobytes_per_second`, `name`, `only_admins_can_pause_the_game`, `game_password`, `require_user_verification`, `tags`, `visibility`.
|
||||||
|
|
||||||
Defaults to {"tags":["clusterio"],"auto_pause":false}.
|
Defaults to a set of common settings filled in when the instance is created, such as `"tags": ["clusterio"]`, `"auto_pause": false` and a `name` and `description` based on the cluster and instance names.
|
||||||
|
|
||||||
|
|
||||||
### factorio.verbose_logging
|
### factorio.verbose_logging
|
||||||
@@ -330,6 +617,14 @@ This prints more messages to the log.
|
|||||||
Defaults to false.
|
Defaults to false.
|
||||||
|
|
||||||
|
|
||||||
|
### factorio.console_logging
|
||||||
|
|
||||||
|
Pass the `--console-log` flag to Factorio to make it write the console output, such as chat, commands and player joins, to `console.log` in the instance directory.
|
||||||
|
Useful for 3rd party tools that read the console log of the server.
|
||||||
|
|
||||||
|
Defaults to false.
|
||||||
|
|
||||||
|
|
||||||
### factorio.strip_paths
|
### factorio.strip_paths
|
||||||
|
|
||||||
Strip down absolute paths in the server log going to files inside the instance directory such that they are relative to the instance directory.
|
Strip down absolute paths in the server log going to files inside the instance directory such that they are relative to the instance directory.
|
||||||
@@ -352,25 +647,35 @@ Defaults to true.
|
|||||||
### factorio.sync_adminlist
|
### factorio.sync_adminlist
|
||||||
|
|
||||||
Synchronize in-game admin list with admin status of the users in cluster.
|
Synchronize in-game admin list with admin status of the users in cluster.
|
||||||
|
One of "disabled", "enabled" or "bidirectional".
|
||||||
If enabled Clusterio will generate a new `server-adminlist.json` on instance startup based on the users in the cluster with admin status set to true, and keep the admins in sync with the users that have admin status while the instance is running.
|
If enabled Clusterio will generate a new `server-adminlist.json` on instance startup based on the users in the cluster with admin status set to true, and keep the admins in sync with the users that have admin status while the instance is running.
|
||||||
|
With "bidirectional" players promoted or demoted in-game with `/promote` and `/demote` are also updated in the cluster, and from there on the other instances.
|
||||||
|
Configs from before this became a choice are migrated from true and false to "enabled" and "disabled".
|
||||||
|
|
||||||
Defaults to true.
|
Defaults to "bidirectional".
|
||||||
|
|
||||||
|
|
||||||
### factorio.sync_whitelist
|
### factorio.sync_whitelist
|
||||||
|
|
||||||
Synchronize in-game whitelist with the whitelisted status of the users in the cluster.
|
Synchronize in-game whitelist with the whitelisted status of the users in the cluster.
|
||||||
|
One of "disabled", "enabled" or "bidirectional".
|
||||||
If enabled Clusterio will generate a new `server-whitelist.json` on instance startup based on the users in the cluster with whitelisted status set to true, and keep the whitelisted users in sync with the users that have whitelisted status while the instance in running.
|
If enabled Clusterio will generate a new `server-whitelist.json` on instance startup based on the users in the cluster with whitelisted status set to true, and keep the whitelisted users in sync with the users that have whitelisted status while the instance in running.
|
||||||
|
With "bidirectional" changes made in-game with `/whitelist` are picked up by watching `server-whitelist.json` for changes and updated in the cluster as well.
|
||||||
|
This requires factorio.enable_whitelist to be on, as Factorio doesn't write the file otherwise.
|
||||||
|
Configs from before this became a choice are migrated from true and false to "enabled" and "disabled".
|
||||||
|
|
||||||
Defaults to true.
|
Defaults to "bidirectional".
|
||||||
|
|
||||||
|
|
||||||
### factorio.sync_banlist
|
### factorio.sync_banlist
|
||||||
|
|
||||||
Synchronize in-game banlist with the banned status of users in the cluster.
|
Synchronize in-game banlist with the banned status of users in the cluster.
|
||||||
|
One of "disabled", "enabled" or "bidirectional".
|
||||||
If enabled Clusterio will generate a new `server-banlist.json` on instance startup based on users in the cluster with banned status set to true, and keep the banned users in sync with the users that have the banned status while the instance is running.
|
If enabled Clusterio will generate a new `server-banlist.json` on instance startup based on users in the cluster with banned status set to true, and keep the banned users in sync with the users that have the banned status while the instance is running.
|
||||||
|
With "bidirectional" players banned or unbanned in-game with `/ban` and `/unban` are also updated in the cluster, and from there on the other instances.
|
||||||
|
Configs from before this became a choice are migrated from true and false to "enabled" and "disabled".
|
||||||
|
|
||||||
Defaults to true.
|
Defaults to "bidirectional".
|
||||||
|
|
||||||
|
|
||||||
### factorio.max_concurrent_commands
|
### factorio.max_concurrent_commands
|
||||||
@@ -387,6 +692,7 @@ This means a high number of concurrent commands can amplify resends due to packe
|
|||||||
|
|
||||||
Prior to 0.18.7 the maximum practical size of game update sent where arround 8 kB due to the UDP receive buffer on windows defaulting to this value, larger updates would not get through the receive buffer and cause the connection to drop.
|
Prior to 0.18.7 the maximum practical size of game update sent where arround 8 kB due to the UDP receive buffer on windows defaulting to this value, larger updates would not get through the receive buffer and cause the connection to drop.
|
||||||
To stay below the 8 kB limit the maximum safe value for this option would be around 7000 / (3 * game_speed * maximum_segment_size), which is around 20 in normal circumstances.
|
To stay below the 8 kB limit the maximum safe value for this option would be around 7000 / (3 * game_speed * maximum_segment_size), which is around 20 in normal circumstances.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
Defaults to 5.
|
Defaults to 5.
|
||||||
|
|
||||||
@@ -394,7 +700,8 @@ Defaults to 5.
|
|||||||
### <plugin_name>.load_plugin
|
### <plugin_name>.load_plugin
|
||||||
|
|
||||||
Whether to load the given plugin on the instance.
|
Whether to load the given plugin on the instance.
|
||||||
Note that plugins need to be loaded on the controller in order for them to be loaded on instances.
|
Note that plugins need to be loaded on the controller and the host in order for them to be loaded on instances.
|
||||||
|
Loading a plugin that requires save patching or script commands is rejected while factorio.enable_save_patching or factorio.enable_script_commands respectively is disabled on the instance.
|
||||||
|
|
||||||
Defaults to true.
|
Defaults to true.
|
||||||
|
|
||||||
@@ -420,5 +727,6 @@ Defaults to null meaning complain about it not being set and exit.
|
|||||||
|
|
||||||
Max duration in seconds to wait before attempting to reconnect with the controller after the connection is dropped.
|
Max duration in seconds to wait before attempting to reconnect with the controller after the connection is dropped.
|
||||||
The actual delay on each reconnect will be a random number between 0 and this configured value to avoid all clients trying to reconnect at the same time.
|
The actual delay on each reconnect will be a random number between 0 and this configured value to avoid all clients trying to reconnect at the same time.
|
||||||
|
Must be 0 or greater.
|
||||||
|
|
||||||
Defaults to 60.
|
Defaults to 60.
|
||||||
@@ -229,8 +229,8 @@ Files containing and exporting a single class should be named the same as the cl
|
|||||||
Relative imports in 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("./link");
|
import libLink from "./link";
|
||||||
const libLuaTools = require("./lua_tools");
|
import libLuaTools from "./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`.
|
Note that no sub-modules of the lib package is imported directly from the outside of it with the exception of `build_mod`.
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ See the following example code for a hypothetical `Data` class with a single pro
|
|||||||
* A Data class example
|
* A Data class example
|
||||||
* @alias module:Data
|
* @alias module:Data
|
||||||
*/
|
*/
|
||||||
class Data {
|
export class Data {
|
||||||
/** @type {string} */
|
/** @type {string} */
|
||||||
member = "foo";
|
member = "foo";
|
||||||
|
|
||||||
@@ -41,8 +41,6 @@ class Data {
|
|||||||
return json;
|
return json;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = Data;
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Serialising an instance of `Data` for JSON is as simple as doing `serialised = JSON.stringify(data)` as the `toJSON` method is automatically called by `JSON.stringify` to create a suitable object.
|
Serialising an instance of `Data` for JSON is as simple as doing `serialised = JSON.stringify(data)` as the `toJSON` method is automatically called by `JSON.stringify` to create a suitable object.
|
||||||
@@ -53,14 +51,13 @@ For example a class holding a data property with an instance of the Data class f
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
// Composed.js
|
// Composed.js
|
||||||
"use strict";
|
import Data from "./Data";
|
||||||
const Data = require("./Data");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Composed data class example
|
* Composed data class example
|
||||||
* @alias module:Data
|
* @alias module:Data
|
||||||
*/
|
*/
|
||||||
class Composed {
|
export class Composed {
|
||||||
/** @type {module:Data|undefined} */
|
/** @type {module:Data|undefined} */
|
||||||
data;
|
data;
|
||||||
|
|
||||||
@@ -83,8 +80,6 @@ class Composed {
|
|||||||
|
|
||||||
// toJSON is optional and not needed for this particular class
|
// toJSON is optional and not needed for this particular class
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = Composed;
|
|
||||||
```
|
```
|
||||||
|
|
||||||
It's easy to create a new instance of Composed by calling `new Composed(new Data("spam"))` and serialising to and from JSON is the same as for Data.
|
It's easy to create a new instance of Composed by calling `new Composed(new Data("spam"))` and serialising to and from JSON is the same as for Data.
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ Mods on the other hand work without modifications.
|
|||||||
|
|
||||||
This can be disabled with the `factorio.enable_save_patching` config on a per instance basis, however disabling it means that modules are not loaded into the game and most plugins will not function.
|
This can be disabled with the `factorio.enable_save_patching` config on a per instance basis, however disabling it means that modules are not loaded into the game and most plugins will not function.
|
||||||
To use the modules outside of Clusterio the `npx clusteriohost create-scenario` command creates a scenario with the modules patched into it.
|
To use the modules outside of Clusterio the `npx clusteriohost create-scenario` command creates a scenario with the modules patched into it.
|
||||||
|
Note that the IPC between the game and the host is not available outside of Clusterio, so modules that depend on it will not work as expected in such a scenario.
|
||||||
|
|
||||||
<sub>1: Before version 2.0 of Clusterio this was done at runtime with a patcher called Hotpatch, but due to the difficulty in supporting run time patching and the lack of documentation it was replace it with save patching instead.</sub>
|
<sub>1: Before version 2.0 of Clusterio this was done at runtime with a patcher called Hotpatch, but due to the difficulty in supporting run time patching and the lack of documentation it was replace it with save patching instead.</sub>
|
||||||
|
|
||||||
|
|||||||
@@ -247,6 +247,13 @@ This command lists all plugins currently known to the remote. Newly installed pl
|
|||||||
|
|
||||||
If remote plugin updates are enabled on the remote, this will execute `npm update --save <name>`. Changes will not be applied until the remote is restarted. If the `--restart` flag is provided, the remote will automatically restart once the update is complete.
|
If remote plugin updates are enabled on the remote, this will execute `npm update --save <name>`. Changes will not be applied until the remote is restarted. If the `--restart` flag is provided, the remote will automatically restart once the update is complete.
|
||||||
|
|
||||||
|
### Update All
|
||||||
|
|
||||||
|
ctl> controller update --all [--restart]
|
||||||
|
ctl> host update <host> --all [--restart]
|
||||||
|
|
||||||
|
Updates the Clusterio package and all plugins installed from npm in a single `npm update --save` command. Updating everything at once avoids ending up with multiple versions of `@clusterio/lib` in the installation. Requires both remote updates and remote plugin updates to be enabled on the remote.
|
||||||
|
|
||||||
### Install
|
### Install
|
||||||
|
|
||||||
ctl> controller plugin install <name> [--restart]
|
ctl> controller plugin install <name> [--restart]
|
||||||
|
|||||||
+166
-92
@@ -1,7 +1,7 @@
|
|||||||
# Writing Plugins
|
# Writing Plugins
|
||||||
|
|
||||||
Plugins for Clusterio are classes written in JavaScript that run under Node.js.
|
Plugins for Clusterio are JavaScript modules that run under Node.js.
|
||||||
The plugin classes have pre-defined hooks that are called during various stages and operations of Clusterio.
|
Each entrypoint of a plugin exports a function that attaches handlers to hooks called during various stages and operations of Clusterio.
|
||||||
|
|
||||||
|
|
||||||
## Contents
|
## Contents
|
||||||
@@ -10,6 +10,7 @@ The plugin classes have pre-defined hooks that are called during various stages
|
|||||||
- [Defining the plugin class](#defining-the-plugin-class)
|
- [Defining the plugin class](#defining-the-plugin-class)
|
||||||
- [Logging Messages](#logging-messages)
|
- [Logging Messages](#logging-messages)
|
||||||
- [Plugin Configuration](#plugin-configuration)
|
- [Plugin Configuration](#plugin-configuration)
|
||||||
|
- [Plugin Permissions](#plugin-permissions)
|
||||||
- [Communicating with Factorio](#communicating-with-factorio)
|
- [Communicating with Factorio](#communicating-with-factorio)
|
||||||
- [Defining Link Messages](#defining-link-messages)
|
- [Defining Link Messages](#defining-link-messages)
|
||||||
- [Sending Link Messages](#sending-link-messages)
|
- [Sending Link Messages](#sending-link-messages)
|
||||||
@@ -48,12 +49,12 @@ By default the main entrypoint is the `index.js` file, but this may be changed b
|
|||||||
Here's an example of `index.js`:
|
Here's an example of `index.js`:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
module.exports.plugin = {
|
export const plugin = {
|
||||||
name: "foo_frobber",
|
name: "foo_frobber",
|
||||||
title: "Foo Frobber",
|
title: "Foo Frobber",
|
||||||
description: "Does advanced frobnication",
|
description: "Does advanced frobnication",
|
||||||
instanceEntrypoint: "instance",
|
instanceEntrypoint: "instance.js",
|
||||||
controllerEntrypoint: "controller",
|
controllerEntrypoint: "controller.js",
|
||||||
messages: {
|
messages: {
|
||||||
/* See below */
|
/* See below */
|
||||||
},
|
},
|
||||||
@@ -75,7 +76,7 @@ The following properties are recognized:
|
|||||||
Currently not used.
|
Currently not used.
|
||||||
|
|
||||||
**instanceEntrypoint**:
|
**instanceEntrypoint**:
|
||||||
Path to a Node.js module relative to the plugin directory which contains the InstancePlugin class definition for this plugin.
|
Path to a Node.js module relative to the plugin directory which exports the instance entrypoint function for this plugin.
|
||||||
This is an optional paramater.
|
This is an optional paramater.
|
||||||
A plugin may have code only for instances but it must still be loaded on the controller in order for it to be possible to load it on an instance.
|
A plugin may have code only for instances but it must still be loaded on the controller in order for it to be possible to load it on an instance.
|
||||||
|
|
||||||
@@ -84,7 +85,7 @@ The following properties are recognized:
|
|||||||
See [Plugin Configuration](#plugin-configuration)
|
See [Plugin Configuration](#plugin-configuration)
|
||||||
|
|
||||||
**controllerEntrypoint**:
|
**controllerEntrypoint**:
|
||||||
Path to a Node.js module relative to the plugin directory which contains the ControllerPlugin class definiton for this plugin.
|
Path to a Node.js module relative to the plugin directory which exports the controller entrypoint function for this plugin.
|
||||||
This is an optional parameter.
|
This is an optional parameter.
|
||||||
A plugin can be made that only runs on the controller.
|
A plugin can be made that only runs on the controller.
|
||||||
|
|
||||||
@@ -93,73 +94,85 @@ The following properties are recognized:
|
|||||||
See [Plugin Configuration](#plugin-configuration)
|
See [Plugin Configuration](#plugin-configuration)
|
||||||
|
|
||||||
**ctlEntrypoint**:
|
**ctlEntrypoint**:
|
||||||
Path to a Node.js module relative to the plugin directory which contains the CtlPlugin class definition for this plugin.
|
Path to a Node.js module relative to the plugin directory which exports the clusterioctl entrypoint function for this plugin.
|
||||||
This is an optional paramater.
|
This is an optional paramater.
|
||||||
A plugin can be made that only runs on the clusterioctl side.
|
A plugin can be made that only runs on the clusterioctl side.
|
||||||
|
|
||||||
|
**features**:
|
||||||
|
Array of features the plugin needs from the instances it is loaded on, `"SavePatching"` and/or `"ScriptCommands"`.
|
||||||
|
See [Handling Invalid Configuration](#handling-invalid-configuration)
|
||||||
|
|
||||||
**messages**:
|
**messages**:
|
||||||
Object with link messages definitions for this plugin.
|
Object with link messages definitions for this plugin.
|
||||||
See guide for [defining link messages](#defining-link-messages) below.
|
See guide for [defining link messages](#defining-link-messages) below.
|
||||||
|
|
||||||
|
**permissions**:
|
||||||
|
Array of permission definitions for this plugin.
|
||||||
|
See [Plugin Permissions](#plugin-permissions)
|
||||||
|
|
||||||
The optional module folder contains a Clusterio module that will be patched into the save when the plugin is loaded.
|
The optional module folder contains a Clusterio module that will be patched into the save when the plugin is loaded.
|
||||||
See the section on [Clusterio Modules](developing-for-clusterio.md) in the Developing for Clusterio document.
|
See the section on [Clusterio Modules](developing-for-clusterio.md) in the Developing for Clusterio document.
|
||||||
The only restriction imposed on modules embedded into plugins is that they must be named the same as the plugin.
|
The only restriction imposed on modules embedded into plugins is that they must be named the same as the plugin.
|
||||||
|
|
||||||
While there is no standard for how to organize a plugin it's recommended to put the ControllerPlugin class definition into controller.js and the InstancePlugin class definition into instance.js.
|
While there is no standard for how to organize a plugin it's recommended to put the controller entrypoint into controller.js and the instance entrypoint into instance.js.
|
||||||
You can put them into whatever file you want (even the same one for both).
|
You can put them into whatever file you want (even the same one for both).
|
||||||
|
|
||||||
For both instanceEntrypoint and controllerEntrypoint the path should not end with .js and it should use forward slashes for directory separators if any.
|
The entrypoint paths must include the .js extension and use forward slashes for directory separators if any.
|
||||||
|
|
||||||
|
|
||||||
## Defining the plugin class
|
## Defining the plugin entrypoint
|
||||||
|
|
||||||
The plugin class should derive from its respective base class defined in `lib/plugin`.
|
Each entrypoint module exports a default async function which is called once when the plugin is loaded.
|
||||||
For example, to define a ControllerPlugin class the following code can be used:
|
It is passed a context object with what the plugin needs to interact with Clusterio, and attaches handlers to the hooks it is interested in.
|
||||||
|
For example, a controller entrypoint can look like this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { BaseControllerPlugin } = require("@clusterio/controller");
|
export default async function(context) {
|
||||||
|
const { controller, logger, plugin } = context;
|
||||||
|
|
||||||
class ControllerPlugin extends BaseControllerPlugin {
|
controller.hooks.save.attach(plugin.name, async () => {
|
||||||
async init() {
|
await saveFrobnicationData();
|
||||||
this.foo = 42;
|
});
|
||||||
await this.startFrobnication();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ...
|
controller.hooks.shutdown.attach(plugin.name, async () => {
|
||||||
}
|
logger.info("Stopping frobnication");
|
||||||
|
});
|
||||||
module.exports = {
|
|
||||||
ControllerPlugin,
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
For the instance plugin it's exactly the same except "Controller" is replaced with "Instance", for host plugins "Host" is used and for the clusterioctl plugin "Ctl" is used.
|
The context has the following properties:
|
||||||
The available hooks that you can override are documented in the base classes.
|
|
||||||
|
|
||||||
It's best to avoid defining a constructor, but if you insist on defining one, forward all arguments to the base class.
|
**plugin**:
|
||||||
E.g.:
|
The plugin's own info, as exported from the main entrypoint.
|
||||||
|
|
||||||
```js
|
**logger**:
|
||||||
constructor(...args) {
|
Logger for this plugin, see [Logging Messages](#logging-messages).
|
||||||
super(...args);
|
|
||||||
|
|
||||||
// Code here
|
**controller**, **host**, **instance**, **hooks** or **control**:
|
||||||
}
|
The object the entrypoint is loaded for.
|
||||||
```
|
Controller entrypoints get `controller`, host entrypoints get `host`, instance entrypoints get both `instance` and `host`, clusterioctl entrypoints get `hooks` and web entrypoints get `control`.
|
||||||
|
|
||||||
The arguments passed may change, and attempting to modify them will result in unpredicatable behaviour.
|
The available hooks are documented on the `ControllerHooks`, `HostHooks`, `InstanceHooks`, `CtlHooks` and `WebHooks` classes.
|
||||||
The async init method is always called immediatly after the constructor, so there's little reason to do this.
|
Handlers are attached under a name, which should be the name of the plugin, and a hook only accepts one handler per name.
|
||||||
|
An error thrown by a handler is logged and does not affect the other handlers, the same goes for handlers that take more than 15 seconds to complete.
|
||||||
|
|
||||||
|
For TypeScript the context types are exported as `ControllerPluginContext`, `HostPluginContext`, `InstancePluginContext`, `CtlPluginContext` and `WebPluginContext` from their respective packages.
|
||||||
|
|
||||||
|
### Class based plugins
|
||||||
|
|
||||||
|
Plugins written as classes deriving from `BaseControllerPlugin`, `BaseHostPlugin`, `BaseInstancePlugin`, `BaseCtlPlugin` or `BaseWebPlugin` still load, but this way of defining plugins is deprecated and a warning is logged when such a plugin is loaded.
|
||||||
|
The base class constructor attaches the `on*` methods overridden by the plugin to the corresponding hooks, and the async `init` method is called immediately after.
|
||||||
|
|
||||||
|
|
||||||
## Logging Messages
|
## Logging Messages
|
||||||
|
|
||||||
The base plugin classes provide a winston logger for logging messages to the shared cluster log.
|
The load context provides a winston logger for logging messages to the shared cluster log.
|
||||||
For instances a copy of the log is also stored on the host the instance is on.
|
For instances a copy of the log is also stored on the host the instance is on.
|
||||||
To use it, pass a string to one of the log levels functions, for example:
|
To use it, pass a string to one of the log levels functions, for example:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
async init() {
|
export default async function(context) {
|
||||||
this.logger.info("Initializing frobbing");
|
context.logger.info("Initializing frobbing");
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -189,7 +202,7 @@ For guarding unexpected errors the best option is to log a short description alo
|
|||||||
try {
|
try {
|
||||||
// Operation that should not throw but may end up throwing
|
// Operation that should not throw but may end up throwing
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error(`Operation failed:\n${err.stack}`);
|
logger.error(`Operation failed:\n${err.stack}`);
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -225,12 +238,12 @@ export default {
|
|||||||
} satisfies lib.PluginDeclaration;
|
} satisfies lib.PluginDeclaration;
|
||||||
```
|
```
|
||||||
|
|
||||||
Code inside the `ControllerPlugin` class will then be able to access the level config field through the `Config` object at `this.controller.config`, for example in the ControllerPluginClass:
|
The controller entrypoint will then be able to access the level config field through the `Config` object at `controller.config`:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
async init() {
|
export default async function(context: ControllerPluginContext) {
|
||||||
let level = this.controller.config.get("foo_frobber.level");
|
const level = context.controller.config.get("foo_frobber.level");
|
||||||
this.logger.info(`I got a frobnication level of ${level}`);
|
context.logger.info(`I got a frobnication level of ${level}`);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -240,33 +253,76 @@ See [Configuration System](config-system.md) for more details on how this system
|
|||||||
|
|
||||||
### Handling Invalid Configuration
|
### Handling Invalid Configuration
|
||||||
|
|
||||||
If the plugin requires a certain feature to be enabled to function it should throw an error during init if this is not the case.
|
If the plugin requires save patching or script commands to function, which can be disabled to run vanilla or scenarios not compatible with Clusterio, declare it under `features` in the `plugin` export:
|
||||||
The most common such feature is the save patching, which can be disabled to run vanilla or scenarios not compatible with Clusterio.
|
|
||||||
For example:
|
|
||||||
|
|
||||||
```js
|
```js
|
||||||
async init() {
|
export const plugin = {
|
||||||
if (!this.instance.config.get("factorio.enable_save_patching")) {
|
name: "foo_frobber",
|
||||||
throw new Error("foo_frobber plugin requires save patching.");
|
// ...
|
||||||
|
features: ["SavePatching"],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Enabling the plugin on an instance that has the feature turned off then fails config validation, so the mistake is caught when the config is edited instead of when the instance starts.
|
||||||
|
|
||||||
|
Other constraints on config fields are expressed with a `validator` on the field definition, which throws when the value is not acceptable.
|
||||||
|
Use `dependsOn` when the check involves other fields so that the validator runs when those change too.
|
||||||
|
See [Configuration System](config-system.md) for details.
|
||||||
|
|
||||||
|
|
||||||
|
## Plugin Permissions
|
||||||
|
|
||||||
|
Permissions are granted to roles and checked on users, both on the controller and in the web UI.
|
||||||
|
A plugin declares the permissions it uses under `permissions` in the `plugin` export.
|
||||||
|
Names must start with the plugin name followed by a dot.
|
||||||
|
For example in index.ts:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import type * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
|
declare module "@clusterio/lib" {
|
||||||
|
// Extend the interface of known permission names so that
|
||||||
|
// user.checkPermission(...) accepts our permission.
|
||||||
|
export interface Permissions {
|
||||||
|
"foo_frobber.frobnicate": never;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
...
|
||||||
|
permissions: [
|
||||||
|
{
|
||||||
|
name: "foo_frobber.frobnicate",
|
||||||
|
title: "Frobnicate",
|
||||||
|
description: "Run frobnication on instances.",
|
||||||
|
grantByDefault: false, // Whether the generated Player role is granted this permission
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} satisfies lib.PluginDeclaration;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The `Permissions` interface only exists at the type level, its values are always `never` and only the keys are used.
|
||||||
|
Adding your permission names to it gives you autocomplete and a compile error on typos when calling `user.checkPermission`, `account.hasPermission` or setting the `permission` of a web UI page.
|
||||||
|
In JavaScript the `declare module` block is not needed.
|
||||||
|
|
||||||
|
Permissions declared this way are registered when the plugin is loaded.
|
||||||
|
The older `lib.definePermission()` function still works, but a plugin should not use both for the same permission name.
|
||||||
|
|
||||||
|
|
||||||
## Communicating with Factorio
|
## Communicating with Factorio
|
||||||
|
|
||||||
For pushing data into Factorio there's RCON, which lets you send arbitrary Lua commands to invoke whatever code you want in the game.
|
For pushing data into Factorio there's RCON, which lets you send arbitrary Lua commands to invoke whatever code you want in the game.
|
||||||
This is done by calling the `sendRcon` method on the plugin object.
|
This is done by calling the `sendRcon` method on the instance.
|
||||||
For example:
|
For example:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
async onStart() {
|
instance.hooks.start.attach(plugin.name, async () => {
|
||||||
let response = await this.sendRcon(
|
const response = await instance.sendRcon(
|
||||||
"/sc rcon.print('data')"
|
"/sc rcon.print('data')"
|
||||||
);
|
);
|
||||||
|
|
||||||
// Do stuff with response.
|
// Do stuff with response.
|
||||||
}
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
Because data into Factorio is streamed at a rate of 3-6 kB/s by default, it is recommended to avoid sending large commands as much as possible, and to strip down the data on the ones you send to only what's strictly necessary.
|
Because data into Factorio is streamed at a rate of 3-6 kB/s by default, it is recommended to avoid sending large commands as much as possible, and to strip down the data on the ones you send to only what's strictly necessary.
|
||||||
@@ -279,15 +335,16 @@ From a plugin you listen for an event named `ipc-channel_name` in order to get d
|
|||||||
For example in the plugin code:
|
For example in the plugin code:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
async init() {
|
export default async function(context) {
|
||||||
this.instance.server.on("ipc-my_plugin_foo", content =>
|
const { instance, logger } = context;
|
||||||
this.handleFoo(content).catch(err => this.logger.error(
|
instance.server.on("ipc-my_plugin_foo", content =>
|
||||||
|
handleFoo(content).catch(err => logger.error(
|
||||||
`Error handling foo:\n${err.stack}`
|
`Error handling foo:\n${err.stack}`
|
||||||
))
|
))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleFoo(content) {
|
async function handleFoo(content) {
|
||||||
// Do stuff with content
|
// Do stuff with content
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -304,11 +361,11 @@ clusterio_api.send_json("my_plugin_foo", { data = 123 })
|
|||||||
For convience a helper function is exposed on server specifically for handling IPC events.
|
For convience a helper function is exposed on server specifically for handling IPC events.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
async init() {
|
export default async function(context) {
|
||||||
this.instance.server.handle("my_plugin_foo", this.handleFoo.bind(this));
|
context.instance.server.handle("my_plugin_foo", handleFoo);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleFoo(content) {
|
async function handleFoo(content) {
|
||||||
// Do stuff with content
|
// Do stuff with content
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -445,9 +502,9 @@ Link messages are sent by calling the `.sendTo()` method on a connection object
|
|||||||
For example:
|
For example:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
// In an InstancePlugin class
|
// In an instance entrypoint
|
||||||
async frobnicate() {
|
async function frobnicate(instance) {
|
||||||
const response = await this.instance.sendTo("controller", new messages.Frobnicate({
|
const response = await instance.sendTo("controller", new messages.Frobnicate({
|
||||||
verbosity: 2,
|
verbosity: 2,
|
||||||
special: false,
|
special: false,
|
||||||
}));
|
}));
|
||||||
@@ -464,14 +521,14 @@ Here is what that looks like in practice:
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
// ❌ BAD: The extracted method loses its `this` binding and crashes when called.
|
// ❌ BAD: The extracted method loses its `this` binding and crashes when called.
|
||||||
const send = this.instance.sendTo;
|
const send = instance.sendTo;
|
||||||
send("controller", new messages.Frobnicate({ foo: "bar" }));
|
send("controller", new messages.Frobnicate({ foo: "bar" }));
|
||||||
|
|
||||||
// ✅ GOOD: Call it directly on the connection object. (Cast args/results here if needed).
|
// ✅ GOOD: Call it directly on the connection object. (Cast args/results here if needed).
|
||||||
this.instance.sendTo("controller", new messages.Frobnicate({ foo: "bar" }));
|
instance.sendTo("controller", new messages.Frobnicate({ foo: "bar" }));
|
||||||
|
|
||||||
// ✅ GOOD: Explicitly bind the receiver if you need to pass a method as a value (like a handler).
|
// ✅ GOOD: Explicitly bind the receiver if you need to pass a method as a value (like a handler).
|
||||||
this.instance.handle(messages.Frobnicate, this.handleFrobnicate.bind(this));
|
instance.handle(messages.Frobnicate, plugin.handleFrobnicate.bind(plugin));
|
||||||
```
|
```
|
||||||
|
|
||||||
For classes with `static type = "request"` the send method is async and returns a promise that resolves to the response data received from the target it was sent to, or rejects with an error if the request failed.
|
For classes with `static type = "request"` the send method is async and returns a promise that resolves to the response data received from the target it was sent to, or rejects with an error if the request failed.
|
||||||
@@ -493,23 +550,23 @@ sendTo({ controlId: 123 }, message);
|
|||||||
|
|
||||||
There are a few connection related events that plugins neeed to repsond to in order to avoid data loss and connection problems.
|
There are a few connection related events that plugins neeed to repsond to in order to avoid data loss and connection problems.
|
||||||
The most important is the prepare disconnect for the link between controller and host.
|
The most important is the prepare disconnect for the link between controller and host.
|
||||||
This is signaled to `ControllerPlugin` classes via the `onPrepareHostDisconnect` hook and to `InstancePlugin` classes via the `onPrepareControllerDisconnect` hook.
|
This is signaled to controller plugins via the `prepareHostDisconnect` hook and to instance plugins via the `prepareControllerDisconnect` hook.
|
||||||
|
|
||||||
After the prepare disconnect the connection will be closed, which will result in pending requests and events being dropped.
|
After the prepare disconnect the connection will be closed, which will result in pending requests and events being dropped.
|
||||||
Plugins must respond to the prepare disconnect by stopping any processess it does that send events or requests over the link in question.
|
Plugins must respond to the prepare disconnect by stopping any processess it does that send events or requests over the link in question.
|
||||||
This can be accomplished either through listening for the prepare disconnect hook, or by checking the `connected` property of the `HostConnection` class and `Host` class on the controller and host respectively.
|
This can be accomplished either through listening for the prepare disconnect hook, or by checking the `connected` property of the `HostConnection` class and `Host` class on the controller and host respectively.
|
||||||
For example the sending of an event from an `InstancePlugin` class can be stopped while the connection is not connected, not in the dropped state, and not in the process of discunnecting by using the following code:
|
For example the sending of an event from an instance plugin can be stopped while the connection is not connected, not in the dropped state, and not in the process of discunnecting by using the following code:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
if (this.host.connected) {
|
if (host.connected) {
|
||||||
this.instance.sendTo("controller", new messages.Frobnicate({ foo: "bar" }));
|
instance.sendTo("controller", new messages.Frobnicate({ foo: "bar" }));
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
If the event or request needs to be sent to the controller it can be put into a queue stored on the plugin instance and sent out when the connection is established again.
|
If the event or request needs to be sent to the controller it can be put into a queue and sent out when the connection is established again.
|
||||||
The re-establishement of the connection is notified to plugins via the `connect` event to the `onControllerConnectionEvent` and `onHostConnectionEvent` hooks.
|
The re-establishement of the connection is notified to plugins via the `connect` event to the `controllerConnectionEvent` and `hostConnectionEvent` hooks.
|
||||||
|
|
||||||
The second connection event which is of lesser importance to respond to is the `drop` connection event served through `onControllerConnectionEvent` for `InstancePlugin` classes and through `onHostConnectionEvent` for `ControllerPlugin` classes.
|
The second connection event which is of lesser importance to respond to is the `drop` connection event served through `controllerConnectionEvent` for instance plugins and through `hostConnectionEvent` for controller plugins.
|
||||||
This is raised when the connection between the controller and host in question is lost, most likely due to networking issues.
|
This is raised when the connection between the controller and host in question is lost, most likely due to networking issues.
|
||||||
When in the dropped state the host will keep trying to reconnect to the controller in order to re-establish it, and if successful no events or requests will be lost.
|
When in the dropped state the host will keep trying to reconnect to the controller in order to re-establish it, and if successful no events or requests will be lost.
|
||||||
However while in the dropped state any requests and events sent gets queued up in memory until the connection is either re-established or the session times out.
|
However while in the dropped state any requests and events sent gets queued up in memory until the connection is either re-established or the session times out.
|
||||||
@@ -525,7 +582,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");
|
import { Counter } from "@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",
|
||||||
@@ -541,7 +598,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");
|
import { Counter } from "@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",
|
||||||
@@ -549,14 +606,39 @@ const barMetric = new Gauge(
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Somewhere in the instance plugin code
|
// Somewhere in the instance plugin code
|
||||||
barMetric.labels(String(this.instance.id)).set(someValue);
|
barMetric.labels(String(instance.id)).set(someValue);
|
||||||
```
|
```
|
||||||
|
|
||||||
Metrics are automatically registered to the default registry, and this default registry is automatically polled by the controller on hosts.
|
Metrics are automatically registered to the default registry, and this default registry is automatically polled by the controller on hosts.
|
||||||
This means that it's important that you place the definition of the metric at module level so that it's not created more than once over the lifetime of a host.
|
This means that it's important that you place the definition of the metric at module level so that it's not created more than once over the lifetime of a host.
|
||||||
Since the metrics remember their values and would continue to be exported after an instance is shutdown, there's code at instance shutdown that removes all the values where the `instance_id` label matches the id of the instance shut down.
|
Since the metrics remember their values and would continue to be exported after an instance is shutdown, there's code at instance shutdown that removes all the values where the `instance_id` label matches the id of the instance shut down.
|
||||||
|
|
||||||
For statistics you need to update on collection there's an `onMetrics` hook on both controller and instance plugins that is run before the metrics in the default registry are collected.
|
For statistics you need to update on collection there's a `metrics` hook on the controller, host and instance that is run before the metrics in the default registry are collected.
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { Gauge } from "@clusterio/lib";
|
||||||
|
|
||||||
|
const frobnicationsMetric = new Gauge(
|
||||||
|
"clusterio_foo_frobber_frobnications", "Frobnications currently in progress"
|
||||||
|
);
|
||||||
|
|
||||||
|
// In the controller entrypoint
|
||||||
|
controller.hooks.metrics.attach(plugin.name, async () => {
|
||||||
|
frobnicationsMetric.set(frobnications.size);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
A handler may also return the results of collecting collectors that are not in the default registry, and they are added to the response.
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { CollectorRegistry, Counter } from "@clusterio/lib";
|
||||||
|
|
||||||
|
const fooRegistry = new CollectorRegistry();
|
||||||
|
const fooCounter = new Counter("clusterio_foo_frobber_foos", "Foos frobbed", { register: false });
|
||||||
|
fooRegistry.register(fooCounter);
|
||||||
|
|
||||||
|
controller.hooks.metrics.attach(plugin.name, async () => fooRegistry.collect());
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
## Adding Custom Commands to clusterioctl
|
## Adding Custom Commands to clusterioctl
|
||||||
@@ -565,7 +647,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");
|
import { Command, CommandTree } from "@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"
|
||||||
});
|
});
|
||||||
@@ -574,7 +656,7 @@ const fooFrobberCommands = new CommandTree({
|
|||||||
Then commands are added to the the plugin's command tree:
|
Then commands are added to the the plugin's command tree:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const info = require("./info");
|
import { messages } from "./index.js";
|
||||||
|
|
||||||
fooFrobberCommands.add(new Command({
|
fooFrobberCommands.add(new Command({
|
||||||
definition: ["frobnicate <type>", "Do frobnications", (yargs) => {
|
definition: ["frobnicate <type>", "Do frobnications", (yargs) => {
|
||||||
@@ -593,22 +675,14 @@ fooFrobberCommands.add(new Command({
|
|||||||
|
|
||||||
For a command the `definition` is the arguments to pass to [yargs.command](http://yargs.js.org/docs/#api-reference-commandcmd-desc-builder-handler) (see also [yargs.positional](http://yargs.js.org/docs/#api-reference-positionalkey-opt) and [yargs.options](http://yargs.js.org/docs/#api-reference-optionskey-opt) for setting up positional and optional arguments to commands).
|
For a command the `definition` is the arguments to pass to [yargs.command](http://yargs.js.org/docs/#api-reference-commandcmd-desc-builder-handler) (see also [yargs.positional](http://yargs.js.org/docs/#api-reference-positionalkey-opt) and [yargs.options](http://yargs.js.org/docs/#api-reference-optionskey-opt) for setting up positional and optional arguments to commands).
|
||||||
The `handler` is an async function that's invoked when the command is executed and it's passed the parsed command line arguments and a reference to the `Control` class of clusterioctl.
|
The `handler` is an async function that's invoked when the command is executed and it's passed the parsed command line arguments and a reference to the `Control` class of clusterioctl.
|
||||||
It's possible to optain a reference to the plugin class with `control.plugins.get(info.name)`.
|
|
||||||
|
|
||||||
Note that messages sent from clusterioctl needs to have `"control-controller"` as a part of the links array for it to be accepted by the controller, see [Defining Link Messages](#defining-link-messages) for how to define the messages that can be sent to the controller.
|
Note that messages sent from clusterioctl needs to have `"control-controller"` as a part of the links array for it to be accepted by the controller, see [Defining Link Messages](#defining-link-messages) for how to define the messages that can be sent to the controller.
|
||||||
|
|
||||||
To have the command tree become part of clusterioctl it needs to be added to the rootCommand tree in `addCommands` callback of the Ctl plugin:
|
To have the command tree become part of clusterioctl it needs to be added to the rootCommand tree in the `addCommands` hook of the ctl entrypoint:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const { BaseCtlPlugin } = require("@clusterio/ctl");
|
export default async function(context) {
|
||||||
|
context.hooks.addCommands.attach(context.plugin.name, async (rootCommand) => {
|
||||||
class CtlPlugin extends BaseCtlPlugin {
|
|
||||||
async addCommands(rootCommand) {
|
|
||||||
rootCommand.add(fooFrobberCommands);
|
rootCommand.add(fooFrobberCommands);
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
CtlPlugin,
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
+2
-2
@@ -418,7 +418,7 @@ export default defineConfig([{
|
|||||||
...globals.mocha,
|
...globals.mocha,
|
||||||
},
|
},
|
||||||
|
|
||||||
sourceType: "commonjs",
|
sourceType: "module",
|
||||||
parserOptions: {},
|
parserOptions: {},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -489,7 +489,7 @@ export default defineConfig([{
|
|||||||
"node/shebang": "off",
|
"node/shebang": "off",
|
||||||
},
|
},
|
||||||
}, {
|
}, {
|
||||||
files: ["packages/create/templates/**/*.{t,j}s?(x)"],
|
files: ["packages/create/templates/**/*.?(c){t,j}s?(x)"],
|
||||||
|
|
||||||
"rules": {
|
"rules": {
|
||||||
"node/no-missing-require": "off",
|
"node/no-missing-require": "off",
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"files": [],
|
"files": [],
|
||||||
"packageManager": "pnpm@10.28.1+sha512.7d7dbbca9e99447b7c3bf7a73286afaaf6be99251eb9498baefa7d406892f67b879adb3a1d7e687fc4ccc1a388c7175fbaae567a26ab44d1067b54fcb0d6a316",
|
"packageManager": "pnpm@10.28.1+sha512.7d7dbbca9e99447b7c3bf7a73286afaaf6be99251eb9498baefa7d406892f67b879adb3a1d7e687fc4ccc1a388c7175fbaae567a26ab44d1067b54fcb0d6a316",
|
||||||
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc --build",
|
"build": "tsc --build",
|
||||||
"watch": "tsc --build --watch",
|
"watch": "tsc --build --watch",
|
||||||
|
|||||||
@@ -27,12 +27,12 @@ import jwt from "jsonwebtoken";
|
|||||||
|
|
||||||
// homebrew modules
|
// homebrew modules
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { ConsoleTransport, levels, logger } = lib;
|
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import Controller from "./src/Controller";
|
import Controller from "./src/Controller.js";
|
||||||
import UserManager from "./src/UserManager";
|
import UserManager from "./src/UserManager.js";
|
||||||
import UserRecord from "./src/UserRecord";
|
import UserRecord from "./src/UserRecord.js";
|
||||||
import { version } from "./package.json";
|
import packageConfig from "./package.json" with { type: "json" };
|
||||||
|
|
||||||
// globals
|
// globals
|
||||||
let controller: Controller;
|
let controller: Controller;
|
||||||
@@ -206,7 +206,7 @@ async function handleBootstrapCommand(
|
|||||||
console.log(content);
|
console.log(content);
|
||||||
} else {
|
} else {
|
||||||
logger.info(`Writing ${args.output}`);
|
logger.info(`Writing ${args.output}`);
|
||||||
await lib.safeOutputFile(args.output, content);
|
await lib.safeOutputFile(args.output, content, { mode: 0o600 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -216,7 +216,7 @@ async function handleCopyStaticCommand(
|
|||||||
pluginInfos: lib.PluginNodeEnvInfo[],
|
pluginInfos: lib.PluginNodeEnvInfo[],
|
||||||
) {
|
) {
|
||||||
await fs.cp(
|
await fs.cp(
|
||||||
path.join(__dirname, "..", "web", "static"),
|
path.join(import.meta.dirname, "..", "web", "static"),
|
||||||
args.target,
|
args.target,
|
||||||
{
|
{
|
||||||
recursive: true,
|
recursive: true,
|
||||||
@@ -268,7 +268,7 @@ interface InitializeParameters {
|
|||||||
|
|
||||||
async function initialize(): Promise<InitializeParameters> {
|
async function initialize(): Promise<InitializeParameters> {
|
||||||
// argument parsing
|
// argument parsing
|
||||||
const args = await yargs
|
const args = await yargs(process.argv.slice(2))
|
||||||
.scriptName("controller")
|
.scriptName("controller")
|
||||||
.usage("$0 <command> [options]")
|
.usage("$0 <command> [options]")
|
||||||
.option("log-level", {
|
.option("log-level", {
|
||||||
@@ -340,7 +340,7 @@ async function initialize(): Promise<InitializeParameters> {
|
|||||||
})
|
})
|
||||||
.demandCommand(1, "You need to specify a command to run")
|
.demandCommand(1, "You need to specify a command to run")
|
||||||
.strict()
|
.strict()
|
||||||
.argv
|
.parse()
|
||||||
;
|
;
|
||||||
|
|
||||||
// Combined log stream of the whole cluster.
|
// Combined log stream of the whole cluster.
|
||||||
@@ -377,7 +377,7 @@ async function initialize(): Promise<InitializeParameters> {
|
|||||||
let command = args._[0];
|
let command = args._[0];
|
||||||
let shouldRun = false;
|
let shouldRun = false;
|
||||||
if (command === "run") {
|
if (command === "run") {
|
||||||
logger.info(`Starting Clusterio controller ${version}`);
|
logger.info(`Starting Clusterio controller ${packageConfig.version}`);
|
||||||
if (args.recovery) {
|
if (args.recovery) {
|
||||||
logger.warn("Controller recovery mode enabled. Some features will be disabled.");
|
logger.warn("Controller recovery mode enabled. Some features will be disabled.");
|
||||||
}
|
}
|
||||||
@@ -402,6 +402,7 @@ async function initialize(): Promise<InitializeParameters> {
|
|||||||
logger.info("Loading Plugin info");
|
logger.info("Loading Plugin info");
|
||||||
const pluginInfos = await lib.loadPluginInfos(pluginList);
|
const pluginInfos = await lib.loadPluginInfos(pluginList);
|
||||||
lib.registerPluginMessages(pluginInfos);
|
lib.registerPluginMessages(pluginInfos);
|
||||||
|
lib.registerPluginPermissions(pluginInfos);
|
||||||
lib.addPluginConfigFields(pluginInfos);
|
lib.addPluginConfigFields(pluginInfos);
|
||||||
|
|
||||||
const controllerConfigPath = args.config;
|
const controllerConfigPath = args.config;
|
||||||
@@ -426,7 +427,7 @@ async function initialize(): Promise<InitializeParameters> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
controllerConfig.set("controller.version", version); // Allows tracking last loaded version
|
controllerConfig.set("controller.version", packageConfig.version); // Allows tracking last loaded version
|
||||||
|
|
||||||
if (!controllerConfig.get("controller.auth_secret")) {
|
if (!controllerConfig.get("controller.auth_secret")) {
|
||||||
logger.info("Generating new controller authentication secret");
|
logger.info("Generating new controller authentication secret");
|
||||||
@@ -537,6 +538,6 @@ ${err.stack}`
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
bootstrap();
|
bootstrap();
|
||||||
}
|
}
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
import { bootstrap } from "./controller";
|
import { bootstrap } from "./controller.js";
|
||||||
export { default as Controller } from "./src/Controller";
|
export { default as Controller } from "./src/Controller.js";
|
||||||
export { default as ControllerRouter } from "./src/ControllerRouter";
|
export { default as ControllerRouter } from "./src/ControllerRouter.js";
|
||||||
export { default as ControlConnection } from "./src/ControlConnection";
|
export { default as ControlConnection } from "./src/ControlConnection.js";
|
||||||
export { default as HostConnection } from "./src/HostConnection";
|
export { default as HostConnection } from "./src/HostConnection.js";
|
||||||
export { default as InstanceRecord } from "./src/InstanceRecord";
|
export { default as InstanceRecord } from "./src/InstanceRecord.js";
|
||||||
export { default as InstanceManager } from "./src/InstanceManager";
|
export { default as InstanceManager } from "./src/InstanceManager.js";
|
||||||
export { default as HostRecord } from "./src/HostRecord";
|
export { default as HostRecord } from "./src/HostRecord.js";
|
||||||
export { default as BaseControllerPlugin } from "./src/BaseControllerPlugin";
|
export { BaseControllerPlugin, ControllerHooks, type ControllerPluginContext } from "./src/BaseControllerPlugin.js";
|
||||||
export { default as UserManager } from "./src/UserManager";
|
export { default as UserManager } from "./src/UserManager.js";
|
||||||
export { default as UserRecord } from "./src/UserRecord";
|
export { default as UserRecord } from "./src/UserRecord.js";
|
||||||
export { default as User } from "./src/User";
|
export { default as User } from "./src/User.js";
|
||||||
export { default as WsServer } from "./src/WsServer";
|
export { default as WsServer } from "./src/WsServer.js";
|
||||||
|
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
bootstrap();
|
bootstrap();
|
||||||
}
|
}
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"type": "module",
|
||||||
"main": "dist/node/index.js",
|
"main": "dist/node/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "tsc --build && webpack-cli --mode production",
|
"prepare": "tsc --build && webpack-cli --mode production",
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import path from "path";
|
import path from "path";
|
||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
|
|
||||||
import type Controller from "./Controller";
|
import type Controller from "./Controller.js";
|
||||||
import type WsServerConnector from "./WsServerConnector";
|
import type WsServerConnector from "./WsServerConnector.js";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = lib;
|
import { logger } from "@clusterio/lib";
|
||||||
import * as routes from "./routes";
|
import * as routes from "./routes.js";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,45 +1,35 @@
|
|||||||
import type {
|
import type Controller from "./Controller.js";
|
||||||
CollectorResult, Event, InstanceStatus, Logger,
|
import type InstanceRecord from "./InstanceRecord.js";
|
||||||
ModPack, ModInfo, PlayerEvent, PluginNodeEnvInfo,
|
import type ControlConnection from "./ControlConnection.js";
|
||||||
} from "@clusterio/lib";
|
import type HostConnection from "./HostConnection.js";
|
||||||
import type Controller from "./Controller";
|
import * as lib from "@clusterio/lib";
|
||||||
import type InstanceRecord from "./InstanceRecord";
|
|
||||||
import type ControlConnection from "./ControlConnection";
|
export type ControllerPluginContext = lib.PluginLoadContext<{
|
||||||
import type HostConnection from "./HostConnection";
|
controller: Controller;
|
||||||
|
metrics: any;
|
||||||
|
}>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base class for controller plugins
|
* Collection of controller plugin hooks
|
||||||
*
|
|
||||||
* Controller plugins are subclasses of this class which get instantiated by
|
|
||||||
* the controller on startup when the plugin is enabled in the config.
|
|
||||||
* To be discovered the class must be exported under the name `ControllerPlugin`
|
|
||||||
* in the module specified by the `controllerEntrypoint` in the plugin's
|
|
||||||
* `plugin` export.
|
|
||||||
*/
|
*/
|
||||||
export default class BaseControllerPlugin {
|
export class ControllerHooks extends lib.AsyncHookCollection {
|
||||||
/**
|
constructor(logger: lib.Logger) {
|
||||||
* Logger for this plugin
|
super(logger);
|
||||||
*
|
this.save = this.newHook();
|
||||||
* Instance of winston Logger for sending log messages from this
|
this.metrics = this.newHook();
|
||||||
* plugin. Supported methods and their corresponding log levels are
|
this.shutdown = this.newHook();
|
||||||
* `error`, `warn`, `audit`, `info` and `verbose`.
|
this.instanceStatusChanged = this.newHook();
|
||||||
*/
|
this.instanceConfigFieldChanged = this.newHook();
|
||||||
logger: Logger;
|
this.controllerConfigFieldChanged = this.newHook();
|
||||||
|
this.controlConnectionEvent = this.newHook();
|
||||||
constructor(
|
this.hostConnectionEvent = this.newHook();
|
||||||
public info: PluginNodeEnvInfo,
|
this.prepareHostDisconnect = this.newHook();
|
||||||
public controller: Controller,
|
this.modPacksUpdated = this.newHook();
|
||||||
public metrics: any,
|
this.modsUpdated = this.newHook();
|
||||||
logger: Logger
|
this.rolesUpdated = this.newHook();
|
||||||
) {
|
this.playerEvent = this.newHook();
|
||||||
this.logger = logger.child({ plugin: this.info.name }) as unknown as Logger;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Called immediately after the class is instantiated
|
|
||||||
*/
|
|
||||||
async init() { }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the controller saves data in memory to disk
|
* Called when the controller saves data in memory to disk
|
||||||
*
|
*
|
||||||
@@ -51,7 +41,7 @@ export default class BaseControllerPlugin {
|
|||||||
* BaseControllerPlugin.onShutdown} have been invoked and all links have
|
* BaseControllerPlugin.onShutdown} have been invoked and all links have
|
||||||
* been disconnected.
|
* been disconnected.
|
||||||
*/
|
*/
|
||||||
async onSaveData() { }
|
readonly save: lib.AsyncHook<[]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the status of an instance changes
|
* Called when the status of an instance changes
|
||||||
@@ -91,7 +81,7 @@ export default class BaseControllerPlugin {
|
|||||||
* The instance that changed.
|
* The instance that changed.
|
||||||
* @param prev - the previous status of the instance.
|
* @param prev - the previous status of the instance.
|
||||||
*/
|
*/
|
||||||
async onInstanceStatusChanged(instance: InstanceRecord, prev?: InstanceStatus) { }
|
readonly instanceStatusChanged: lib.AsyncHook<[instance: InstanceRecord, prev: lib.InstanceStatus | undefined]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the value of a controller config field changed.
|
* Called when the value of a controller config field changed.
|
||||||
@@ -103,7 +93,7 @@ export default class BaseControllerPlugin {
|
|||||||
* @param curr - The current value of the field.
|
* @param curr - The current value of the field.
|
||||||
* @param prev - The previous value of the field.
|
* @param prev - The previous value of the field.
|
||||||
*/
|
*/
|
||||||
async onControllerConfigFieldChanged(field: string, curr: unknown, prev: unknown) { }
|
readonly controllerConfigFieldChanged: lib.AsyncHook<[field: string, curr: unknown, prev: unknown]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the value of an instance config field changed.
|
* Called when the value of an instance config field changed.
|
||||||
@@ -117,7 +107,8 @@ export default class BaseControllerPlugin {
|
|||||||
* @param curr - The current value of the field.
|
* @param curr - The current value of the field.
|
||||||
* @param prev - The previous value of the field.
|
* @param prev - The previous value of the field.
|
||||||
*/
|
*/
|
||||||
async onInstanceConfigFieldChanged(instance: InstanceRecord, field: string, curr: unknown, prev: unknown) { }
|
// eslint-disable-next-line max-len
|
||||||
|
readonly instanceConfigFieldChanged: lib.AsyncHook<[instance: InstanceRecord, field: string, curr: unknown, prev: unknown]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called before collecting Prometheus metrics
|
* Called before collecting Prometheus metrics
|
||||||
@@ -134,12 +125,12 @@ export default class BaseControllerPlugin {
|
|||||||
*
|
*
|
||||||
* @returns an async iterator of prometheus metric results or undefined.
|
* @returns an async iterator of prometheus metric results or undefined.
|
||||||
*/
|
*/
|
||||||
async onMetrics(): Promise<void | AsyncIterable<CollectorResult>> { }
|
readonly metrics: lib.AsyncHook<[], AsyncIterable<lib.CollectorResult>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the controller is shutting down
|
* Called when the controller is shutting down
|
||||||
*/
|
*/
|
||||||
async onShutdown() { }
|
readonly shutdown: lib.AsyncHook<[]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when an event on a host connection happens
|
* Called when an event on a host connection happens
|
||||||
@@ -174,7 +165,8 @@ export default class BaseControllerPlugin {
|
|||||||
* The connection the event occured on.
|
* The connection the event occured on.
|
||||||
* @param event - one of connect, drop, resume and close
|
* @param event - one of connect, drop, resume and close
|
||||||
*/
|
*/
|
||||||
onHostConnectionEvent(connection: HostConnection, event: "connect" | "drop" | "resume" | "close") { }
|
// eslint-disable-next-line max-len
|
||||||
|
readonly hostConnectionEvent: lib.AsyncHook<[connection: HostConnection, event: "connect" | "drop" | "resume" | "close"]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when an avent on a control connection happens
|
* Called when an avent on a control connection happens
|
||||||
@@ -210,7 +202,8 @@ export default class BaseControllerPlugin {
|
|||||||
* The connection the event occured on.
|
* The connection the event occured on.
|
||||||
* @param event - one of connect, drop, resume, and close.
|
* @param event - one of connect, drop, resume, and close.
|
||||||
*/
|
*/
|
||||||
onControlConnectionEvent(connection: ControlConnection, event: "connect" | "drop" | "resume" | "close") { }
|
// eslint-disable-next-line max-len
|
||||||
|
readonly controlConnectionEvent: lib.AsyncHook<[connection: ControlConnection, event: "connect" | "drop" | "resume" | "close"]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when a host is preparing to disconnect from the controller
|
* Called when a host is preparing to disconnect from the controller
|
||||||
@@ -224,7 +217,7 @@ export default class BaseControllerPlugin {
|
|||||||
* @param connection -
|
* @param connection -
|
||||||
* The connection to the host preparing to disconnect.
|
* The connection to the host preparing to disconnect.
|
||||||
*/
|
*/
|
||||||
async onPrepareHostDisconnect(connection: HostConnection) { }
|
readonly prepareHostDisconnect: lib.AsyncHook<[connection: HostConnection]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when one or more mod packs are updated
|
* Called when one or more mod packs are updated
|
||||||
@@ -237,7 +230,7 @@ export default class BaseControllerPlugin {
|
|||||||
*
|
*
|
||||||
* @param modPacks - Mod packs that updated.
|
* @param modPacks - Mod packs that updated.
|
||||||
*/
|
*/
|
||||||
async onModPacksUpdated(modPacks: ModPack[]) { }
|
readonly modPacksUpdated: lib.AsyncHook<[modPacks: lib.ModPack[]]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when one or more mod stored on the controller are updated
|
* Called when one or more mod stored on the controller are updated
|
||||||
@@ -249,7 +242,18 @@ export default class BaseControllerPlugin {
|
|||||||
*
|
*
|
||||||
* @param mods - Mods that updated.
|
* @param mods - Mods that updated.
|
||||||
*/
|
*/
|
||||||
async onModsUpdated(mods: ModInfo[]) { }
|
readonly modsUpdated: lib.AsyncHook<[mods: lib.ModInfo[]]>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when one or more roles stored on the controller are updated
|
||||||
|
*
|
||||||
|
* Invoked when one or more roles have been added, updated or deleted.
|
||||||
|
*
|
||||||
|
* If a role has been deleted its `.isDeleted` property will be true.
|
||||||
|
*
|
||||||
|
* @param roles - Roles that updated.
|
||||||
|
*/
|
||||||
|
readonly rolesUpdated: lib.AsyncHook<[roles: lib.Role[]]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when a player joins or leaves an instance
|
* Called when a player joins or leaves an instance
|
||||||
@@ -261,7 +265,79 @@ export default class BaseControllerPlugin {
|
|||||||
* The instance it occured on.
|
* The instance it occured on.
|
||||||
* @param event - Information about the event.
|
* @param event - Information about the event.
|
||||||
*/
|
*/
|
||||||
async onPlayerEvent(instance: InstanceRecord, event: PlayerEvent) { }
|
readonly playerEvent: lib.AsyncHook<[instance: InstanceRecord, event: lib.PlayerEvent]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||||
|
export interface BaseControllerPlugin {
|
||||||
|
onSaveData?(): Promise<void>;
|
||||||
|
onMetrics?(): Promise<void | AsyncIterable<lib.CollectorResult>>;
|
||||||
|
onShutdown?(): Promise<void>;
|
||||||
|
onInstanceStatusChanged?(instance: InstanceRecord, prev?: lib.InstanceStatus): Promise<void>;
|
||||||
|
onControllerConfigFieldChanged?(field: string, curr: unknown, prev: unknown): Promise<void>;
|
||||||
|
onInstanceConfigFieldChanged?(instance: InstanceRecord, field: string, curr: unknown, prev: unknown): Promise<void>;
|
||||||
|
onHostConnectionEvent?(connection: HostConnection, event: "connect" | "drop" | "resume" | "close"): void;
|
||||||
|
onControlConnectionEvent?(connection: ControlConnection, event: "connect" | "drop" | "resume" | "close"): void;
|
||||||
|
onPrepareHostDisconnect?(connection: HostConnection): Promise<void>;
|
||||||
|
onModPacksUpdated?(modPacks: lib.ModPack[]): Promise<void>;
|
||||||
|
onModsUpdated?(mods: lib.ModInfo[]): Promise<void>;
|
||||||
|
onRolesUpdated?(roles: lib.Role[]): Promise<void>;
|
||||||
|
onPlayerEvent?(instance: InstanceRecord, event: lib.PlayerEvent): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for controller plugins
|
||||||
|
*
|
||||||
|
* Controller plugins are subclasses of this class which get instantiated by
|
||||||
|
* the controller on startup when the plugin is enabled in the config.
|
||||||
|
* To be discovered the class must be exported under the name `ControllerPlugin`
|
||||||
|
* in the module specified by the `controllerEntrypoint` in the plugin's
|
||||||
|
* `plugin` export.
|
||||||
|
*/
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||||
|
export class BaseControllerPlugin {
|
||||||
|
constructor(
|
||||||
|
public info: lib.PluginNodeEnvInfo,
|
||||||
|
public controller: Controller,
|
||||||
|
public metrics: any,
|
||||||
|
public logger: lib.Logger,
|
||||||
|
) {
|
||||||
|
const attach = <Args extends unknown[], Return>(
|
||||||
|
hook: lib.AsyncHook<Args, Return>,
|
||||||
|
fn?: lib.HookHandler<Args, Return>,
|
||||||
|
) => {
|
||||||
|
if (fn) {
|
||||||
|
hook.attach(info.name, fn.bind(this));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
attach(controller.hooks.save, this.onSaveData);
|
||||||
|
attach(controller.hooks.instanceStatusChanged, this.onInstanceStatusChanged);
|
||||||
|
attach(controller.hooks.controllerConfigFieldChanged, this.onControllerConfigFieldChanged);
|
||||||
|
attach(controller.hooks.instanceConfigFieldChanged, this.onInstanceConfigFieldChanged);
|
||||||
|
attach(controller.hooks.metrics, this.onMetrics);
|
||||||
|
attach(controller.hooks.shutdown, this.onShutdown);
|
||||||
|
attach(controller.hooks.hostConnectionEvent, this.onHostConnectionEvent);
|
||||||
|
attach(controller.hooks.controlConnectionEvent, this.onControlConnectionEvent);
|
||||||
|
attach(controller.hooks.prepareHostDisconnect, this.onPrepareHostDisconnect);
|
||||||
|
attach(controller.hooks.modPacksUpdated, this.onModPacksUpdated);
|
||||||
|
attach(controller.hooks.modsUpdated, this.onModsUpdated);
|
||||||
|
attach(controller.hooks.rolesUpdated, this.onRolesUpdated);
|
||||||
|
attach(controller.hooks.playerEvent, this.onPlayerEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromContext(context: ControllerPluginContext) {
|
||||||
|
return new this(context.plugin, context.controller, context.metrics, context.logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
detachHooks() {
|
||||||
|
this.controller.hooks.detachAll(this.info.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called immediately after the class is instantiated
|
||||||
|
*/
|
||||||
|
async init() {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Broadcast event to all connected hosts
|
* Broadcast event to all connected hosts
|
||||||
@@ -272,7 +348,7 @@ export default class BaseControllerPlugin {
|
|||||||
*
|
*
|
||||||
* @param event - Event to send
|
* @param event - Event to send
|
||||||
*/
|
*/
|
||||||
broadcastEventToHosts<T>(event: Event<T>) {
|
broadcastEventToHosts<T>(event: lib.Event<T>) {
|
||||||
for (let hostConnection of this.controller.wsServer.hostConnections.values()) {
|
for (let hostConnection of this.controller.wsServer.hostConnections.values()) {
|
||||||
if (
|
if (
|
||||||
!hostConnection.connector.closing
|
!hostConnection.connector.closing
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
import type WsServerConnector from "./WsServerConnector";
|
import type WsServerConnector from "./WsServerConnector.js";
|
||||||
|
|
||||||
import events from "events";
|
import events from "events";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logFilter, logger } = lib;
|
import { logFilter, logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import BaseConnection from "./BaseConnection";
|
import BaseConnection from "./BaseConnection.js";
|
||||||
import User from "./User";
|
import User from "./User.js";
|
||||||
import UserRecord from "./UserRecord";
|
import UserRecord from "./UserRecord.js";
|
||||||
import * as routes from "./routes";
|
import * as routes from "./routes.js";
|
||||||
import Controller from "./Controller";
|
import Controller from "./Controller.js";
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
@@ -63,9 +63,7 @@ export default class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
||||||
this.connector.on(event, () => {
|
this.connector.on(event, () => {
|
||||||
for (let controllerPlugin of this._controller.plugins.values()) {
|
this._controller.hooks.controlConnectionEvent.invoke(this, event);
|
||||||
controllerPlugin.onControlConnectionEvent(this, event);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,6 +126,7 @@ export default class ControlConnection extends BaseConnection {
|
|||||||
this.handle(lib.PluginListRequest, this.handlePluginListRequest.bind(this));
|
this.handle(lib.PluginListRequest, this.handlePluginListRequest.bind(this));
|
||||||
this.handle(lib.PluginUpdateRequest, this.handlePluginUpdateRequest.bind(this));
|
this.handle(lib.PluginUpdateRequest, this.handlePluginUpdateRequest.bind(this));
|
||||||
this.handle(lib.PluginInstallRequest, this.handlePluginInstallRequest.bind(this));
|
this.handle(lib.PluginInstallRequest, this.handlePluginInstallRequest.bind(this));
|
||||||
|
this.handle(lib.UpdateAllRequest, this.handleUpdateAllRequest.bind(this));
|
||||||
this.handle(lib.DebugDumpWsRequest, this.handleDebugDumpWsRequest.bind(this));
|
this.handle(lib.DebugDumpWsRequest, this.handleDebugDumpWsRequest.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,7 +168,7 @@ export default class ControlConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (typeof permission === "string") {
|
if (typeof permission === "string") {
|
||||||
this.user.checkPermission(permission);
|
this.user.checkPermission(permission as lib.PermissionName);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1307,10 +1306,20 @@ export default class ControlConnection extends BaseConnection {
|
|||||||
return await lib.handlePluginInstall(request.pluginPackage);
|
return await lib.handlePluginInstall(request.pluginPackage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async handleUpdateAllRequest(request: lib.UpdateAllRequest) {
|
||||||
|
if (!this._controller.config.get("controller.allow_remote_updates")) {
|
||||||
|
throw new lib.RequestError("Remote updates are disabled on this machine");
|
||||||
|
}
|
||||||
|
if (!this._controller.config.get("controller.allow_plugin_updates")) {
|
||||||
|
throw new lib.RequestError("Plugin updates are disabled on this machine");
|
||||||
|
}
|
||||||
|
return await lib.handleUpdateAll("@clusterio/controller", this._controller.pluginInfos);
|
||||||
|
}
|
||||||
|
|
||||||
async handlePluginListRequest(request: lib.PluginListRequest) {
|
async handlePluginListRequest(request: lib.PluginListRequest) {
|
||||||
return this._controller.pluginInfos.map(pluginInfo => lib.PluginDetails.fromNodeEnvInfo(
|
return this._controller.pluginInfos.map(pluginInfo => lib.PluginDetails.fromNodeEnvInfo(
|
||||||
pluginInfo,
|
pluginInfo,
|
||||||
this._controller.plugins.has(pluginInfo.name),
|
this._controller.loadedPlugins.has(pluginInfo),
|
||||||
this._controller.config.get(`${pluginInfo.name}.load_plugin`),
|
this._controller.config.get(`${pluginInfo.name}.load_plugin`),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -1325,5 +1334,3 @@ export default class ControlConnection extends BaseConnection {
|
|||||||
this._controller.debugEvents.on("message", this.ws_dumper);
|
this._controller.debugEvents.on("message", this.ws_dumper);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = ControlConnection;
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import type winston from "winston";
|
import type winston from "winston";
|
||||||
import { BlockList, type AddressInfo, isIPv4, isIPv6 } from "net";
|
import { BlockList, type AddressInfo, isIPv4, isIPv6 } from "net";
|
||||||
import type { ControllerArgs } from "../controller";
|
import type { ControllerArgs } from "../controller.js";
|
||||||
import express, { type Request, type Response, type NextFunction, type Application } from "express";
|
import express, { type Request, type Response, type NextFunction, type Application } from "express";
|
||||||
import type { Static } from "@sinclair/typebox";
|
import type { Static } from "@sinclair/typebox";
|
||||||
import finalhandler from "finalhandler";
|
import finalhandler from "finalhandler";
|
||||||
@@ -14,22 +14,23 @@ import jwt from "jsonwebtoken";
|
|||||||
import path from "path";
|
import path from "path";
|
||||||
import semver from "semver";
|
import semver from "semver";
|
||||||
import stream from "stream";
|
import stream from "stream";
|
||||||
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger, Summary, Gauge } = lib;
|
import { logger, Summary, Gauge } from "@clusterio/lib";
|
||||||
|
|
||||||
import HttpCloser from "./HttpCloser";
|
import HttpCloser from "./HttpCloser.js";
|
||||||
import InstanceRecord from "./InstanceRecord";
|
import InstanceRecord from "./InstanceRecord.js";
|
||||||
import * as metrics from "./metrics";
|
import * as metrics from "./metrics.js";
|
||||||
import * as routes from "./routes";
|
import * as routes from "./routes.js";
|
||||||
import User from "./User";
|
import User from "./User.js";
|
||||||
import UserRecord from "./UserRecord";
|
import UserRecord from "./UserRecord.js";
|
||||||
import UserManager from "./UserManager";
|
import UserManager from "./UserManager.js";
|
||||||
import WsServer from "./WsServer";
|
import WsServer from "./WsServer.js";
|
||||||
import HostRecord from "./HostRecord";
|
import HostRecord from "./HostRecord.js";
|
||||||
import BaseControllerPlugin from "./BaseControllerPlugin";
|
import { BaseControllerPlugin, ControllerHooks } from "./BaseControllerPlugin.js";
|
||||||
import ControllerRouter from "./ControllerRouter";
|
import ControllerRouter from "./ControllerRouter.js";
|
||||||
import InstanceManager from "./InstanceManager";
|
import InstanceManager from "./InstanceManager.js";
|
||||||
|
|
||||||
const endpointDurationSummary = new Summary(
|
const endpointDurationSummary = new Summary(
|
||||||
"clusterio_controller_http_endpoint_duration_seconds",
|
"clusterio_controller_http_endpoint_duration_seconds",
|
||||||
@@ -69,8 +70,10 @@ export default class Controller {
|
|||||||
httpsServer: https.Server | null = null;
|
httpsServer: https.Server | null = null;
|
||||||
httpsServerCloser: HttpCloser | null = null;
|
httpsServerCloser: HttpCloser | null = null;
|
||||||
|
|
||||||
/** Mapping of plugin name to loaded plugin */
|
/** Hooks which plugins can attach to */
|
||||||
plugins: Map<string, BaseControllerPlugin> = new Map();
|
hooks = new ControllerHooks(logger);
|
||||||
|
/** Plugins which are currently loaded */
|
||||||
|
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
||||||
|
|
||||||
/** WebSocket server */
|
/** WebSocket server */
|
||||||
wsServer: WsServer;
|
wsServer: WsServer;
|
||||||
@@ -345,7 +348,7 @@ export default class Controller {
|
|||||||
|
|
||||||
// Start webpack development server if enabled
|
// Start webpack development server if enabled
|
||||||
if (args.dev || args.devPlugin) {
|
if (args.dev || args.devPlugin) {
|
||||||
this._startDevServer(args);
|
await this._startDevServer(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.config.on("fieldChanged", (field, curr, prev) => {
|
this.config.on("fieldChanged", (field, curr, prev) => {
|
||||||
@@ -358,7 +361,7 @@ export default class Controller {
|
|||||||
} else if (field === "controller.static_url") {
|
} else if (field === "controller.static_url") {
|
||||||
this.app.locals.staticRoot = this.config.get("controller.static_url");
|
this.app.locals.staticRoot = this.config.get("controller.static_url");
|
||||||
}
|
}
|
||||||
lib.invokeHook(this.plugins, "onControllerConfigFieldChanged", field, curr, prev);
|
this.hooks.controllerConfigFieldChanged.invoke(field, curr, prev);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Make sure we're actually going to listen on a port
|
// Make sure we're actually going to listen on a port
|
||||||
@@ -383,7 +386,7 @@ export default class Controller {
|
|||||||
Controller.addAppRoutes(this.app, this.pluginInfos);
|
Controller.addAppRoutes(this.app, this.pluginInfos);
|
||||||
|
|
||||||
if (!args.dev) {
|
if (!args.dev) {
|
||||||
let manifestPath = path.join(__dirname, "..", "..", "web", "manifest.json");
|
let manifestPath = path.join(import.meta.dirname, "..", "..", "web", "manifest.json");
|
||||||
|
|
||||||
let manifest = await Controller.loadJsonObject(manifestPath);
|
let manifest = await Controller.loadJsonObject(manifestPath);
|
||||||
if (!manifest["main.js"]) {
|
if (!manifest["main.js"]) {
|
||||||
@@ -458,12 +461,13 @@ export default class Controller {
|
|||||||
async _startDevServer(args: ControllerArgs) {
|
async _startDevServer(args: ControllerArgs) {
|
||||||
logger.warn("Webpack development mode enabled");
|
logger.warn("Webpack development mode enabled");
|
||||||
|
|
||||||
const webpack = require("webpack");
|
const webpack = (await import("webpack")).default;
|
||||||
const webpackDevMiddleware = require("webpack-dev-middleware");
|
const webpackDevMiddleware = (await import("webpack-dev-middleware")).default;
|
||||||
const webpackConfigs = [];
|
const webpackConfigs = [];
|
||||||
|
|
||||||
if (args.dev) {
|
if (args.dev) {
|
||||||
webpackConfigs.push(require("../../../webpack.config")({})); // Path outside of build
|
// @ts-expect-error this file is run from a different folder
|
||||||
|
webpackConfigs.push((await import("../../../webpack.config.cjs")).default({})); // Path outside of build
|
||||||
}
|
}
|
||||||
if (args.devPlugin) {
|
if (args.devPlugin) {
|
||||||
let devPlugins = new Map();
|
let devPlugins = new Map();
|
||||||
@@ -472,7 +476,10 @@ export default class Controller {
|
|||||||
if (!info) {
|
if (!info) {
|
||||||
throw new lib.StartupError(`No plugin named ${name}`);
|
throw new lib.StartupError(`No plugin named ${name}`);
|
||||||
}
|
}
|
||||||
let config = require(path.posix.join(info.requirePath, "webpack.config"))({});
|
const webpackConfig = path.posix.join(info.requirePath, "webpack.config.cjs");
|
||||||
|
let config = (await import(
|
||||||
|
path.isAbsolute(webpackConfig) ? pathToFileURL(webpackConfig).href : webpackConfig
|
||||||
|
)).default({});
|
||||||
devPlugins.set(name, webpackConfigs.length);
|
devPlugins.set(name, webpackConfigs.length);
|
||||||
webpackConfigs.push(config);
|
webpackConfigs.push(config);
|
||||||
}
|
}
|
||||||
@@ -537,7 +544,7 @@ export default class Controller {
|
|||||||
await new Promise((resolve, reject) => { this.devMiddleware.close(resolve); });
|
await new Promise((resolve, reject) => { this.devMiddleware.close(resolve); });
|
||||||
}
|
}
|
||||||
|
|
||||||
await lib.invokeHook(this.plugins, "onShutdown");
|
await this.hooks.shutdown.invoke();
|
||||||
|
|
||||||
await this.wsServer.stop();
|
await this.wsServer.stop();
|
||||||
|
|
||||||
@@ -627,7 +634,9 @@ export default class Controller {
|
|||||||
try {
|
try {
|
||||||
// First check the clusterio version
|
// First check the clusterio version
|
||||||
const runningVersion = this.config.get("controller.version");
|
const runningVersion = this.config.get("controller.version");
|
||||||
const packageJsonPath = require.resolve("@clusterio/controller/package.json");
|
const packageJsonPath = fileURLToPath(
|
||||||
|
import.meta.resolve("@clusterio/controller/package.json"),
|
||||||
|
);
|
||||||
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
|
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
|
||||||
if (runningVersion !== packageJson.version) {
|
if (runningVersion !== packageJson.version) {
|
||||||
this.config.restartRequired = true;
|
this.config.restartRequired = true;
|
||||||
@@ -644,15 +653,14 @@ export default class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
packageName = pluginInfo.npmPackage ?? pluginInfo.name;
|
packageName = pluginInfo.npmPackage ?? pluginInfo.name;
|
||||||
const pluginPackageJsonPath = require.resolve(path.posix.join(pluginInfo.requirePath, "package.json"));
|
const pluginPackageJson = JSON.parse(await fs.readFile(pluginInfo.packagePath, "utf8"));
|
||||||
const pluginPackageJson = JSON.parse(await fs.readFile(pluginPackageJsonPath, "utf8"));
|
|
||||||
if (pluginInfo.version !== pluginPackageJson.version) {
|
if (pluginInfo.version !== pluginPackageJson.version) {
|
||||||
this.config.restartRequired = true;
|
this.config.restartRequired = true;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
logger.warn(`Failed to read package json for ${packageName}:\n${err.stack ?? err.message}`);
|
logger.warn(`Failed to read package.json for ${packageName}:\n${err.stack ?? err.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@@ -661,7 +669,7 @@ export default class Controller {
|
|||||||
async checkRestartDowngrade() {
|
async checkRestartDowngrade() {
|
||||||
try {
|
try {
|
||||||
const runningVersion = this.config.get("controller.version");
|
const runningVersion = this.config.get("controller.version");
|
||||||
const packageJsonPath = require.resolve("@clusterio/controller/package.json");
|
const packageJsonPath = fileURLToPath(import.meta.resolve("@clusterio/controller/package.json"));
|
||||||
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
|
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
|
||||||
const installedVersion = packageJson.version;
|
const installedVersion = packageJson.version;
|
||||||
|
|
||||||
@@ -726,9 +734,8 @@ export default class Controller {
|
|||||||
this.modPacks.save(),
|
this.modPacks.save(),
|
||||||
this.roles.save(),
|
this.roles.save(),
|
||||||
this.users.records.save(),
|
this.users.records.save(),
|
||||||
|
this.hooks.save.invoke(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await lib.invokeHook(this.plugins, "onSaveData");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static migrateSystems(rawJson: unknown[]): Static<typeof lib.SystemInfo.jsonSchema>[] {
|
static migrateSystems(rawJson: unknown[]): Static<typeof lib.SystemInfo.jsonSchema>[] {
|
||||||
@@ -902,7 +909,7 @@ export default class Controller {
|
|||||||
// Set folder to serve static content from (the website)
|
// Set folder to serve static content from (the website)
|
||||||
const staticOptions = { immutable: true, maxAge: 1000 * 86400 * 365 };
|
const staticOptions = { immutable: true, maxAge: 1000 * 86400 * 365 };
|
||||||
app.use("/static",
|
app.use("/static",
|
||||||
express.static(path.join(__dirname, "..", "..", "web", "static"), staticOptions)
|
express.static(path.join(import.meta.dirname, "..", "..", "web", "static"), staticOptions)
|
||||||
);
|
);
|
||||||
app.use("/static", express.static("static", staticOptions)); // Used for data export files
|
app.use("/static", express.static("static", staticOptions)); // Used for data export files
|
||||||
|
|
||||||
@@ -1028,7 +1035,7 @@ export default class Controller {
|
|||||||
|
|
||||||
modPacksUpdated(modPacks: lib.ModPack[]) {
|
modPacksUpdated(modPacks: lib.ModPack[]) {
|
||||||
this.subscriptions.broadcast(new lib.ModPackUpdatesEvent(modPacks));
|
this.subscriptions.broadcast(new lib.ModPackUpdatesEvent(modPacks));
|
||||||
lib.invokeHook(this.plugins, "onModPacksUpdated", modPacks);
|
this.hooks.modPacksUpdated.invoke(modPacks);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleModPackSubscription(request: lib.SubscriptionRequest) {
|
async handleModPackSubscription(request: lib.SubscriptionRequest) {
|
||||||
@@ -1044,7 +1051,7 @@ export default class Controller {
|
|||||||
modsUpdated(mods: lib.ModInfo[]) {
|
modsUpdated(mods: lib.ModInfo[]) {
|
||||||
// ModStore sets updatedAtMs for mods
|
// ModStore sets updatedAtMs for mods
|
||||||
this.subscriptions.broadcast(new lib.ModUpdatesEvent(mods));
|
this.subscriptions.broadcast(new lib.ModUpdatesEvent(mods));
|
||||||
lib.invokeHook(this.plugins, "onModsUpdated", mods);
|
this.hooks.modsUpdated.invoke(mods);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleModSubscription(request: lib.SubscriptionRequest) {
|
async handleModSubscription(request: lib.SubscriptionRequest) {
|
||||||
@@ -1092,7 +1099,7 @@ export default class Controller {
|
|||||||
|
|
||||||
rolesUpdated(roles: lib.Role[]) {
|
rolesUpdated(roles: lib.Role[]) {
|
||||||
this.subscriptions.broadcast(new lib.RoleUpdatesEvent(roles));
|
this.subscriptions.broadcast(new lib.RoleUpdatesEvent(roles));
|
||||||
// lib.invokeHook(this.plugins, "onRolesUpdated", roles); // This doesn't exist at the moment
|
this.hooks.rolesUpdated.invoke(roles);
|
||||||
// Notify connected control clients with the given role that the permissions may have changed.
|
// Notify connected control clients with the given role that the permissions may have changed.
|
||||||
for (const role of roles) {
|
for (const role of roles) {
|
||||||
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
||||||
@@ -1122,12 +1129,15 @@ export default class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async loadPlugins() {
|
async loadPlugins() {
|
||||||
|
const context = { metrics, logger, controller: this };
|
||||||
for (let pluginInfo of this.pluginInfos) {
|
for (let pluginInfo of this.pluginInfos) {
|
||||||
try {
|
try {
|
||||||
let manifestPath = path.posix.join(pluginInfo.requirePath, "dist", "web", "manifest.json");
|
let manifestPath = path.posix.join(pluginInfo.requirePath, "dist", "web", "manifest.json");
|
||||||
pluginInfo.manifest = await Controller.loadJsonObject(require.resolve(manifestPath), true);
|
pluginInfo.manifest = await Controller.loadJsonObject(import.meta.resolve(manifestPath), true);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.warn(`Unable to load dist/web/manifest.json for plugin ${pluginInfo.name}`);
|
if (lib.pluginNeedsWebBuild(pluginInfo)) {
|
||||||
|
logger.warn(`Unable to load dist/web/manifest.json for plugin ${pluginInfo.name}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.config.get(`${pluginInfo.name}.load_plugin`)) {
|
if (!this.config.get(`${pluginInfo.name}.load_plugin`)) {
|
||||||
@@ -1139,20 +1149,16 @@ export default class Controller {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let ControllerPluginClass = BaseControllerPlugin;
|
|
||||||
try {
|
try {
|
||||||
if (pluginInfo.controllerEntrypoint) {
|
await lib.loadPlugin(
|
||||||
ControllerPluginClass = await lib.loadPluginClass(
|
pluginInfo,
|
||||||
pluginInfo.name,
|
"controller",
|
||||||
path.posix.join(pluginInfo.requirePath, pluginInfo.controllerEntrypoint),
|
context,
|
||||||
"ControllerPlugin",
|
"ControllerPlugin",
|
||||||
BaseControllerPlugin,
|
BaseControllerPlugin,
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
let controllerPlugin = new ControllerPluginClass(pluginInfo, this, metrics as any, logger);
|
this.loadedPlugins.add(pluginInfo);
|
||||||
await controllerPlugin.init();
|
|
||||||
this.plugins.set(pluginInfo.name, controllerPlugin);
|
|
||||||
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
if (err.code === "InstallationError") {
|
if (err.code === "InstallationError") {
|
||||||
@@ -1238,11 +1244,14 @@ export default class Controller {
|
|||||||
mainBundle = res.app.locals.mainBundle;
|
mainBundle = res.app.locals.mainBundle;
|
||||||
} else {
|
} else {
|
||||||
let stats = res.locals.webpack.devMiddleware.stats.stats[0];
|
let stats = res.locals.webpack.devMiddleware.stats.stats[0];
|
||||||
mainBundle = stats.toJson().assetsByChunkName["main"];
|
mainBundle = stats.toJson().assetsByChunkName["main"][0];
|
||||||
}
|
}
|
||||||
mainBundle = routes.stripStaticPrefix(mainBundle);
|
mainBundle = routes.stripStaticPrefix(mainBundle);
|
||||||
|
|
||||||
fs.readFile(path.join(__dirname, "..", "..", "..", "web", "index.html"), "utf8").then((content) => {
|
fs.readFile(
|
||||||
|
path.join(import.meta.dirname, "..", "..", "..", "web", "index.html"),
|
||||||
|
"utf8",
|
||||||
|
).then((content) => {
|
||||||
res.type("text/html");
|
res.type("text/html");
|
||||||
res.send(content
|
res.send(content
|
||||||
.replace(/__CLUSTER_NAME__/g, res.app.locals.controller.config.get("controller.name"))
|
.replace(/__CLUSTER_NAME__/g, res.app.locals.controller.config.get("controller.name"))
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import type Controller from "./Controller";
|
import type Controller from "./Controller.js";
|
||||||
import type BaseConnection from "./BaseConnection";
|
import type BaseConnection from "./BaseConnection.js";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import HostConnection from "./HostConnection";
|
import { logger } from "@clusterio/lib";
|
||||||
import ControlConnection from "./ControlConnection";
|
import HostConnection from "./HostConnection.js";
|
||||||
const { logger } = lib;
|
import ControlConnection from "./ControlConnection.js";
|
||||||
|
|
||||||
export default class ControllerRouter {
|
export default class ControllerRouter {
|
||||||
constructor(
|
constructor(
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import type Controller from "./Controller";
|
import type Controller from "./Controller.js";
|
||||||
import type WsServerConnector from "./WsServerConnector";
|
import type WsServerConnector from "./WsServerConnector.js";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = lib;
|
import { logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import BaseConnection from "./BaseConnection";
|
import BaseConnection from "./BaseConnection.js";
|
||||||
import InstanceRecord from "./InstanceRecord";
|
import InstanceRecord from "./InstanceRecord.js";
|
||||||
import HostRecord from "./HostRecord";
|
import HostRecord from "./HostRecord.js";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -47,12 +47,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
this._checkPluginVersions();
|
this._checkPluginVersions();
|
||||||
|
|
||||||
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
||||||
|
this.connector.on(event, () => this._controller.hooks.hostConnectionEvent.invoke(this, event));
|
||||||
this.connector.on(event, () => {
|
|
||||||
for (let plugin of this._controller.plugins.values()) {
|
|
||||||
plugin.onHostConnectionEvent(this, event);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.connector.on("close", () => {
|
this.connector.on("close", () => {
|
||||||
@@ -66,7 +61,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
instances.push(instance);
|
instances.push(instance);
|
||||||
let prev = instance.status;
|
let prev = instance.status;
|
||||||
instance.status = "unknown";
|
instance.status = "unknown";
|
||||||
lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
|
this._controller.hooks.instanceStatusChanged.invoke(instance, prev);
|
||||||
}
|
}
|
||||||
this._controller.instances.records.setMany(instances);
|
this._controller.instances.records.setMany(instances);
|
||||||
|
|
||||||
@@ -143,7 +138,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async prepareDisconnect() {
|
async prepareDisconnect() {
|
||||||
await lib.invokeHook(this._controller.plugins, "onPrepareHostDisconnect", this);
|
await this._controller.hooks.prepareHostDisconnect.invoke(this);
|
||||||
return await super.prepareDisconnect();
|
return await super.prepareDisconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,7 +211,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
instance.factorioVersion = request.factorioVersion;
|
instance.factorioVersion = request.factorioVersion;
|
||||||
this._controller.instances.records.set(instance);
|
this._controller.instances.records.set(instance);
|
||||||
logger.verbose(`Instance ${instance.config.get("instance.name")} State: ${instance.status}`);
|
logger.verbose(`Instance ${instance.config.get("instance.name")} State: ${instance.status}`);
|
||||||
await lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
|
await this._controller.hooks.instanceStatusChanged.invoke(instance, prev);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstancesUpdateRequest(request: lib.InstancesUpdateRequest) {
|
async handleInstancesUpdateRequest(request: lib.InstancesUpdateRequest) {
|
||||||
@@ -256,9 +251,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
instanceUpdates.push(controllerInstance);
|
instanceUpdates.push(controllerInstance);
|
||||||
logger.verbose(`Instance ${instanceConfig.get("instance.name")} State: ${instanceData.status}`);
|
logger.verbose(`Instance ${instanceConfig.get("instance.name")} State: ${instanceData.status}`);
|
||||||
await lib.invokeHook(
|
await this._controller.hooks.instanceStatusChanged.invoke(controllerInstance, prev);
|
||||||
this._controller.plugins, "onInstanceStatusChanged", controllerInstance, prev
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -274,7 +267,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
// We suppress the changes made by createInstance so we must manually make them here
|
// We suppress the changes made by createInstance so we must manually make them here
|
||||||
this._controller.instances.records.setMany(instanceUpdates);
|
this._controller.instances.records.setMany(instanceUpdates);
|
||||||
await Promise.all(instanceUpdates.flatMap(newInstance => [
|
await Promise.all(instanceUpdates.flatMap(newInstance => [
|
||||||
lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", newInstance),
|
this._controller.hooks.instanceStatusChanged.invoke(newInstance, undefined),
|
||||||
this.send(
|
this.send(
|
||||||
new lib.InstanceAssignInternalRequest(
|
new lib.InstanceAssignInternalRequest(
|
||||||
newInstance.config.get("instance.id"), newInstance.config.toRemote("host")
|
newInstance.config.get("instance.id"), newInstance.config.toRemote("host")
|
||||||
@@ -350,7 +343,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
user.saveRecord();
|
user.saveRecord();
|
||||||
|
|
||||||
let instance = this._controller.instances.get(instanceId)!;
|
let instance = this._controller.instances.get(instanceId)!;
|
||||||
await lib.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
|
await this._controller.hooks.playerEvent.invoke(instance, {
|
||||||
type: event.type,
|
type: event.type,
|
||||||
name: event.name,
|
name: event.name,
|
||||||
reason: event.reason,
|
reason: event.reason,
|
||||||
@@ -367,7 +360,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
user.set("isAdmin", event.admin);
|
user.set("isAdmin", event.admin);
|
||||||
|
|
||||||
const instance = this._controller.instances.get(src.id)!;
|
const instance = this._controller.instances.get(src.id)!;
|
||||||
await lib.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
|
await this._controller.hooks.playerEvent.invoke(instance, {
|
||||||
type: event.admin ? "promote" : "demote" as lib.PlayerEvent["type"],
|
type: event.admin ? "promote" : "demote" as lib.PlayerEvent["type"],
|
||||||
name: event.name,
|
name: event.name,
|
||||||
stats: user.instanceStats.get(src.id)!,
|
stats: user.instanceStats.get(src.id)!,
|
||||||
@@ -385,11 +378,11 @@ export default class HostConnection extends BaseConnection {
|
|||||||
user.saveRecord();
|
user.saveRecord();
|
||||||
|
|
||||||
const instance = this._controller.instances.get(src.id)!;
|
const instance = this._controller.instances.get(src.id)!;
|
||||||
await lib.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
|
await this._controller.hooks.playerEvent.invoke(instance, {
|
||||||
type: event.banned ? "ban" : "unban" as lib.PlayerEvent["type"],
|
type: event.banned ? "ban" : "unban" as lib.PlayerEvent["type"],
|
||||||
name: event.name,
|
name: event.name,
|
||||||
stats: user.instanceStats.get(src.id)!,
|
stats: user.instanceStats.get(src.id)!,
|
||||||
resaon: event.reason,
|
reason: event.reason,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,7 +395,7 @@ export default class HostConnection extends BaseConnection {
|
|||||||
user.set("isWhitelisted", event.whitelisted);
|
user.set("isWhitelisted", event.whitelisted);
|
||||||
|
|
||||||
const instance = this._controller.instances.get(src.id)!;
|
const instance = this._controller.instances.get(src.id)!;
|
||||||
await lib.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
|
await this._controller.hooks.playerEvent.invoke(instance, {
|
||||||
type: event.whitelisted ? "whitelisted" : "unwhitelisted" as lib.PlayerEvent["type"],
|
type: event.whitelisted ? "whitelisted" : "unwhitelisted" as lib.PlayerEvent["type"],
|
||||||
name: event.name,
|
name: event.name,
|
||||||
stats: user.instanceStats.get(src.id)!,
|
stats: user.instanceStats.get(src.id)!,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import type Controller from "./Controller";
|
import type Controller from "./Controller.js";
|
||||||
import type HostConnection from "./HostConnection";
|
import type HostConnection from "./HostConnection.js";
|
||||||
import InstanceRecord from "./InstanceRecord";
|
import InstanceRecord from "./InstanceRecord.js";
|
||||||
|
|
||||||
export default class InstanceManager {
|
export default class InstanceManager {
|
||||||
private static readonly DefaultFactorioSettings = {
|
private static readonly DefaultFactorioSettings = {
|
||||||
@@ -83,12 +83,7 @@ export default class InstanceManager {
|
|||||||
instance: InstanceRecord,
|
instance: InstanceRecord,
|
||||||
prev?: lib.InstanceStatus,
|
prev?: lib.InstanceStatus,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await lib.invokeHook(
|
await this._controller.hooks.instanceStatusChanged.invoke(instance, prev);
|
||||||
this._controller.plugins,
|
|
||||||
"onInstanceStatusChanged",
|
|
||||||
instance,
|
|
||||||
prev,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async _notifyConfigFieldChanged(
|
private async _notifyConfigFieldChanged(
|
||||||
@@ -97,14 +92,7 @@ export default class InstanceManager {
|
|||||||
curr: unknown,
|
curr: unknown,
|
||||||
prev: unknown,
|
prev: unknown,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await lib.invokeHook(
|
await this._controller.hooks.instanceConfigFieldChanged.invoke(instance, field, curr, prev);
|
||||||
this._controller.plugins,
|
|
||||||
"onInstanceConfigFieldChanged",
|
|
||||||
instance,
|
|
||||||
field,
|
|
||||||
curr,
|
|
||||||
prev,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
IUser, Role, SubscribableDatastore,
|
IUser, Role, SubscribableDatastore,
|
||||||
PermissionError, permissions,
|
PermissionError, PermissionName, permissions,
|
||||||
} from "@clusterio/lib";
|
} from "@clusterio/lib";
|
||||||
|
|
||||||
import UserRecord from "./UserRecord";
|
import UserRecord from "./UserRecord.js";
|
||||||
import { Static } from "@sinclair/typebox";
|
import { Static } from "@sinclair/typebox";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -126,7 +126,7 @@ export default class User extends UserRecord implements IUser {
|
|||||||
this.saveRecord();
|
this.saveRecord();
|
||||||
}
|
}
|
||||||
|
|
||||||
checkPermission(permission: string) {
|
checkPermission(permission: PermissionName) {
|
||||||
if (!permissions.has(permission)) {
|
if (!permissions.has(permission)) {
|
||||||
throw new Error(`permission ${permission} does not exist`);
|
throw new Error(`permission ${permission} does not exist`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import jwt from "jsonwebtoken";
|
|||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import User from "./User";
|
import User from "./User.js";
|
||||||
import UserRecord from "./UserRecord";
|
import UserRecord from "./UserRecord.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Access layer for users on the controller.
|
* Access layer for users on the controller.
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import type { IncomingMessage } from "http";
|
import type { IncomingMessage } from "http";
|
||||||
import type { Duplex } from "stream";
|
import type { Duplex } from "stream";
|
||||||
import type Controller from "./Controller";
|
import type Controller from "./Controller.js";
|
||||||
|
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import WebSocket, { WebSocketServer } from "ws";
|
import WebSocket, { WebSocketServer } from "ws";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = lib;
|
import { logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import ControlConnection from "./ControlConnection";
|
import ControlConnection from "./ControlConnection.js";
|
||||||
import HostConnection from "./HostConnection";
|
import HostConnection from "./HostConnection.js";
|
||||||
import WsServerConnector from "./WsServerConnector";
|
import WsServerConnector from "./WsServerConnector.js";
|
||||||
|
|
||||||
import { version as packageVersion } from "../package.json";
|
import packageConfig from "../package.json" with { type: "json" };
|
||||||
|
|
||||||
const wsMessageCounter = new lib.Counter(
|
const wsMessageCounter = new lib.Counter(
|
||||||
"clusterio_controller_websocket_message_total",
|
"clusterio_controller_websocket_message_total",
|
||||||
@@ -45,12 +45,12 @@ export default class WsServer {
|
|||||||
sessionAud: string = `session-${Date.now()}`;
|
sessionAud: string = `session-${Date.now()}`;
|
||||||
nextSessionId: number = 1;
|
nextSessionId: number = 1;
|
||||||
nextControlId: number = 1;
|
nextControlId: number = 1;
|
||||||
wss: WebSocket.Server;
|
wss: WebSocketServer;
|
||||||
|
|
||||||
constructor(controller: Controller) {
|
constructor(controller: Controller) {
|
||||||
this.controller = controller;
|
this.controller = controller;
|
||||||
|
|
||||||
this.wss = new WebSocket.Server({
|
this.wss = new WebSocketServer({
|
||||||
noServer: true,
|
noServer: true,
|
||||||
path: "/api/socket",
|
path: "/api/socket",
|
||||||
});
|
});
|
||||||
@@ -135,11 +135,11 @@ export default class WsServer {
|
|||||||
|
|
||||||
// Start connection handshake.
|
// Start connection handshake.
|
||||||
let loadedPlugins: {[key:string]: string} = {};
|
let loadedPlugins: {[key:string]: string} = {};
|
||||||
for (let [name, plugin] of this.controller.plugins) {
|
for (const plugin of this.controller.loadedPlugins) {
|
||||||
loadedPlugins[name] = plugin.info.version;
|
loadedPlugins[plugin.name] = plugin.version;
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.send(JSON.stringify(new lib.MessageHello(new lib.HelloData(packageVersion, loadedPlugins))));
|
socket.send(JSON.stringify(new lib.MessageHello(new lib.HelloData(packageConfig.version, loadedPlugins))));
|
||||||
this.attachHandler(socket, req);
|
this.attachHandler(socket, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -287,10 +287,11 @@ ${err.stack}`
|
|||||||
logger.info(
|
logger.info(
|
||||||
`WsServer | registered host ${data.id} using version ${data.version}`
|
`WsServer | registered host ${data.id} using version ${data.version}`
|
||||||
);
|
);
|
||||||
if (data.version !== packageVersion) {
|
if (data.version !== packageConfig.version) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
`Host ${data.id} connected using version ${data.version} which does not match the ` +
|
`Host ${data.id} connected using version ${data.version} which does not match the ` +
|
||||||
`version of the controller is currently running (${packageVersion}). It may not work as expected.`
|
`version of the controller is currently running (${packageConfig.version}). ` +
|
||||||
|
"It may not work as expected."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import type WebSocket from "ws";
|
import { type WebSocket } from "ws";
|
||||||
|
|
||||||
import events from "events";
|
import events from "events";
|
||||||
import assert from "assert/strict";
|
import assert from "assert/strict";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = lib;
|
import { logger } from "@clusterio/lib";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -49,7 +49,7 @@ export default class WsServerConnector extends lib.WebSocketBaseConnector {
|
|||||||
* @param account - account data to provide to control connection
|
* @param account - account data to provide to control connection
|
||||||
*/
|
*/
|
||||||
ready(
|
ready(
|
||||||
socket: WebSocket.WebSocket,
|
socket: WebSocket,
|
||||||
src: lib.Address,
|
src: lib.Address,
|
||||||
sessionToken: string,
|
sessionToken: string,
|
||||||
account: lib.AccountDetails | undefined
|
account: lib.AccountDetails | undefined
|
||||||
@@ -80,7 +80,7 @@ export default class WsServerConnector extends lib.WebSocketBaseConnector {
|
|||||||
* @param lastSeq - The last message the client received.
|
* @param lastSeq - The last message the client received.
|
||||||
*/
|
*/
|
||||||
continue(
|
continue(
|
||||||
socket: WebSocket.WebSocket,
|
socket: WebSocket,
|
||||||
lastSeq: number
|
lastSeq: number
|
||||||
) {
|
) {
|
||||||
|
|
||||||
@@ -106,6 +106,9 @@ export default class WsServerConnector extends lib.WebSocketBaseConnector {
|
|||||||
this._state = "connected";
|
this._state = "connected";
|
||||||
this._attachSocketHandlers();
|
this._attachSocketHandlers();
|
||||||
this._dropSendBufferSeq(lastSeq);
|
this._dropSendBufferSeq(lastSeq);
|
||||||
|
logger.verbose(
|
||||||
|
`Connector | resuming session with ${this.dst}, resending ${this._sendBuffer.length} buffered messages`
|
||||||
|
);
|
||||||
for (let message of this._sendBuffer) {
|
for (let message of this._sendBuffer) {
|
||||||
this._socket.send(JSON.stringify(message));
|
this._socket.send(JSON.stringify(message));
|
||||||
}
|
}
|
||||||
@@ -113,7 +116,7 @@ export default class WsServerConnector extends lib.WebSocketBaseConnector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_timedOut() {
|
_timedOut() {
|
||||||
logger.verbose("Connector | Connection timed out");
|
logger.verbose(`Connector | Connection to ${this.dst} timed out`);
|
||||||
this._close();
|
this._close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { Application, Request, Response } from "express";
|
import type { Application, Request, Response } from "express";
|
||||||
import Controller from "./Controller";
|
import Controller from "./Controller.js";
|
||||||
|
|
||||||
import busboy from "busboy";
|
import busboy from "busboy";
|
||||||
import crypto from "crypto";
|
import crypto from "crypto";
|
||||||
@@ -12,7 +12,7 @@ import nodeStream from "stream";
|
|||||||
import util from "util";
|
import util from "util";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = lib;
|
import { logger } from "@clusterio/lib";
|
||||||
|
|
||||||
const finished = util.promisify(nodeStream.finished);
|
const finished = util.promisify(nodeStream.finished);
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ async function getMetrics(req: Request, res: Response, next: any) {
|
|||||||
const controller: Controller = req.app.locals.controller;
|
const controller: Controller = req.app.locals.controller;
|
||||||
|
|
||||||
let results: lib.CollectorResult[] = [];
|
let results: lib.CollectorResult[] = [];
|
||||||
let pluginResults = await lib.invokeHook(controller.plugins, "onMetrics");
|
let pluginResults = await controller.hooks.metrics.collect();
|
||||||
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);
|
||||||
@@ -117,8 +117,8 @@ function getPlugins(req: Request, res: Response) {
|
|||||||
let plugins: lib.PluginWebApi[] = [];
|
let plugins: lib.PluginWebApi[] = [];
|
||||||
for (let pluginInfo of req.app.locals.controller.pluginInfos) {
|
for (let pluginInfo of req.app.locals.controller.pluginInfos) {
|
||||||
let name = pluginInfo.name;
|
let name = pluginInfo.name;
|
||||||
let loaded = req.app.locals.controller.plugins.has(name);
|
const loaded = req.app.locals.controller.loadedPlugins.has(pluginInfo);
|
||||||
let enabled = loaded && req.app.locals.controller.config.get(`${pluginInfo.name}.load_plugin`);
|
const enabled = loaded && req.app.locals.controller.config.get(`${pluginInfo.name}.load_plugin`);
|
||||||
// Note: Cast through unknown is needed because load_plugin is
|
// Note: Cast through unknown is needed because load_plugin is
|
||||||
// defined at runtime and no other fields in the controller config
|
// defined at runtime and no other fields in the controller config
|
||||||
// currently have the boolean type.
|
// currently have the boolean type.
|
||||||
@@ -126,13 +126,13 @@ function getPlugins(req: Request, res: Response) {
|
|||||||
let devPlugins = req.app.locals.devPlugins;
|
let devPlugins = req.app.locals.devPlugins;
|
||||||
if (devPlugins && devPlugins.has(name)) {
|
if (devPlugins && devPlugins.has(name)) {
|
||||||
let stats = res.locals.webpack.devMiddleware.stats.stats[devPlugins.get(name)!];
|
let stats = res.locals.webpack.devMiddleware.stats.stats[devPlugins.get(name)!];
|
||||||
web.main = stats.toJson().assetsByChunkName[name];
|
web.main = stats.toJson().assetsByChunkName[name][0];
|
||||||
} else if (pluginInfo.manifest) {
|
} else if (pluginInfo.manifest) {
|
||||||
web.main = pluginInfo.manifest[`${pluginInfo.name}.js`];
|
web.main = pluginInfo.manifest[`${pluginInfo.name}.js`];
|
||||||
if (!web.main) {
|
if (!web.main) {
|
||||||
web.error = `Missing ${pluginInfo.name}.js entry in manifest.json`;
|
web.error = `Missing ${pluginInfo.name}.js entry in manifest.json`;
|
||||||
}
|
}
|
||||||
} else {
|
} else if (lib.pluginNeedsWebBuild(pluginInfo)) {
|
||||||
web.error = "Missing dist/web/manifest.json";
|
web.error = "Missing dist/web/manifest.json";
|
||||||
}
|
}
|
||||||
if (web.main === "remoteEntry.js") {
|
if (web.main === "remoteEntry.js") {
|
||||||
|
|||||||
File renamed without changes.
+20
-21
@@ -1,20 +1,19 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
"use strict";
|
import child_process from "node:child_process";
|
||||||
const child_process = require("child_process");
|
import fs from "node:fs/promises";
|
||||||
const fs = require("node:fs/promises");
|
import inquirer from "inquirer";
|
||||||
const inquirer = require("inquirer");
|
import os from "node:os";
|
||||||
const os = require("os");
|
import path from "node:path";
|
||||||
const path = require("path");
|
import stream from "node:stream";
|
||||||
const stream = require("stream");
|
import util from "node:util";
|
||||||
const util = require("util");
|
import yargs from "yargs";
|
||||||
const yargs = require("yargs");
|
|
||||||
|
|
||||||
const { levels, logger, setLogLevel } = require("./logging");
|
import { levels, logger, setLogLevel } from "./logging.js";
|
||||||
const { copyPluginTemplates } = require("./template");
|
import { copyPluginTemplates } from "./template.js";
|
||||||
let dev = false;
|
let dev = false;
|
||||||
const scriptExt = process.platform === "win32" ? ".cmd" : "";
|
const scriptExt = process.platform === "win32" ? ".cmd" : "";
|
||||||
const { escapeArg } = require("./escape_arg");
|
import { escapeArg } from "./escape_arg.js";
|
||||||
|
|
||||||
// I hate this, there is a bug with rl.close on windows that was meant to have been fixed in Node14.4
|
// I hate this, there is a bug with rl.close on windows that was meant to have been fixed in Node14.4
|
||||||
// See nodejs/node#21771 and nodejs/node#30701 for the apparent fix that was applied
|
// See nodejs/node#21771 and nodejs/node#30701 for the apparent fix that was applied
|
||||||
@@ -147,21 +146,21 @@ async function execFile(cmd, args) {
|
|||||||
|
|
||||||
async function execController(args) {
|
async function execController(args) {
|
||||||
if (dev) {
|
if (dev) {
|
||||||
return await execFile("node", [path.join(__dirname, "..", "controller"), ...args]);
|
return await execFile("node", [path.join(import.meta.dirname, "..", "controller"), ...args]);
|
||||||
}
|
}
|
||||||
return await execFile(path.join("node_modules", ".bin", `clusteriocontroller${scriptExt}`), args);
|
return await execFile(path.join("node_modules", ".bin", `clusteriocontroller${scriptExt}`), args);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function execHost(args) {
|
async function execHost(args) {
|
||||||
if (dev) {
|
if (dev) {
|
||||||
return await execFile("node", [path.join(__dirname, "..", "host"), ...args]);
|
return await execFile("node", [path.join(import.meta.dirname, "..", "host"), ...args]);
|
||||||
}
|
}
|
||||||
return await execFile(path.join("node_modules", ".bin", `clusteriohost${scriptExt}`), args);
|
return await execFile(path.join("node_modules", ".bin", `clusteriohost${scriptExt}`), args);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function execCtl(args) {
|
async function execCtl(args) {
|
||||||
if (dev) {
|
if (dev) {
|
||||||
return await execFile("node", [path.join(__dirname, "..", "ctl"), ...args]);
|
return await execFile("node", [path.join(import.meta.dirname, "..", "ctl"), ...args]);
|
||||||
}
|
}
|
||||||
return await execFile(path.join("node_modules", ".bin", `clusterioctl${scriptExt}`), args);
|
return await execFile(path.join("node_modules", ".bin", `clusterioctl${scriptExt}`), args);
|
||||||
}
|
}
|
||||||
@@ -235,7 +234,7 @@ async function migrateRename(args) {
|
|||||||
if (await pathExists(source) && !await pathExists(destination)) {
|
if (await pathExists(source) && !await pathExists(destination)) {
|
||||||
await safeOutputFile(destination, JSON.stringify(
|
await safeOutputFile(destination, JSON.stringify(
|
||||||
renameConfig(JSON.parse(await fs.readFile(source))), null, "\t"
|
renameConfig(JSON.parse(await fs.readFile(source))), null, "\t"
|
||||||
));
|
), { mode: 0o600 });
|
||||||
logger.info(`Migrated ${source} to ${destination}`);
|
logger.info(`Migrated ${source} to ${destination}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -408,7 +407,7 @@ async function installClusterio(mode, plugins) {
|
|||||||
for (let plugin of plugins) {
|
for (let plugin of plugins) {
|
||||||
if (!pluginList.has(plugin)) {
|
if (!pluginList.has(plugin)) {
|
||||||
|
|
||||||
let pluginInfo = require(require.resolve(plugin, { paths: [process.cwd()] })).plugin;
|
let pluginInfo = (await import(plugin)).plugin;
|
||||||
pluginList.set(pluginInfo.name, plugin);
|
pluginList.set(pluginInfo.name, plugin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -750,7 +749,7 @@ async function inquirerMissingArgs(args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
let args = yargs
|
let yarg = yargs(process.argv.slice(2))
|
||||||
.option("log-level", {
|
.option("log-level", {
|
||||||
nargs: 1, describe: "Log level to print to stdout", default: "info",
|
nargs: 1, describe: "Log level to print to stdout", default: "info",
|
||||||
choices: ["none"].concat(Object.keys(levels)), type: "string",
|
choices: ["none"].concat(Object.keys(levels)), type: "string",
|
||||||
@@ -805,14 +804,14 @@ async function main() {
|
|||||||
;
|
;
|
||||||
|
|
||||||
if (process.platform === "linux") {
|
if (process.platform === "linux") {
|
||||||
args = args
|
yarg = yarg
|
||||||
.option("allow-install-as-root", {
|
.option("allow-install-as-root", {
|
||||||
nargs: 0, describe: "(Linux only) Allow installing as root (not recommended)", type: "boolean",
|
nargs: 0, describe: "(Linux only) Allow installing as root (not recommended)", type: "boolean",
|
||||||
})
|
})
|
||||||
;
|
;
|
||||||
}
|
}
|
||||||
|
|
||||||
args = args.argv;
|
const args = yarg.parse();
|
||||||
|
|
||||||
setLogLevel(args.logLevel === "none" ? -1 : levels[args.logLevel]);
|
setLogLevel(args.logLevel === "none" ? -1 : levels[args.logLevel]);
|
||||||
dev = args.dev;
|
dev = args.dev;
|
||||||
@@ -900,7 +899,7 @@ async function main() {
|
|||||||
/* eslint-enable no-console */
|
/* eslint-enable no-console */
|
||||||
}
|
}
|
||||||
|
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
main().catch(err => {
|
main().catch(err => {
|
||||||
if (err instanceof InstallError) {
|
if (err instanceof InstallError) {
|
||||||
logger.error(err.message);
|
logger.error(err.message);
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
"use strict";
|
export function escapeArg(arg) {
|
||||||
|
|
||||||
function escapeArg(arg) {
|
|
||||||
// When shell: true is used execFile does not escaping of arguments, they are
|
// When shell: true is used execFile does not escaping of arguments, they are
|
||||||
// simply joined by space and then passed to the shell.
|
// simply joined by space and then passed to the shell.
|
||||||
|
|
||||||
@@ -56,7 +54,3 @@ function escapeArg(arg) {
|
|||||||
}
|
}
|
||||||
return `"${arg.replace(/[$`"\\]/g, "\\$&")}"`;
|
return `"${arg.replace(/[$`"\\]/g, "\\$&")}"`;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
escapeArg,
|
|
||||||
};
|
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
/* eslint-disable no-console */
|
/* eslint-disable no-console */
|
||||||
"use strict";
|
import chalk from "chalk";
|
||||||
const chalk = require("chalk");
|
|
||||||
|
|
||||||
const levels = Object.freeze({
|
export const levels = Object.freeze({
|
||||||
fatal: 0,
|
fatal: 0,
|
||||||
error: 1,
|
error: 1,
|
||||||
warn: 2,
|
warn: 2,
|
||||||
@@ -11,7 +10,7 @@ const levels = Object.freeze({
|
|||||||
verbose: 6,
|
verbose: 6,
|
||||||
});
|
});
|
||||||
|
|
||||||
const colors = {
|
export const colors = {
|
||||||
fatal: "inverse red",
|
fatal: "inverse red",
|
||||||
error: "bold redBright",
|
error: "bold redBright",
|
||||||
warn: "bold yellowBright",
|
warn: "bold yellowBright",
|
||||||
@@ -21,7 +20,7 @@ const colors = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let maxLogLevel = levels.info;
|
let maxLogLevel = levels.info;
|
||||||
const logger = {};
|
export const logger = {};
|
||||||
for (let [name, level] of Object.entries(levels)) {
|
for (let [name, level] of Object.entries(levels)) {
|
||||||
// eslint-disable-next-line no-loop-func
|
// eslint-disable-next-line no-loop-func
|
||||||
logger[name] = message => {
|
logger[name] = message => {
|
||||||
@@ -42,10 +41,6 @@ for (let [name, level] of Object.entries(levels)) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
export function setLogLevel(level) {
|
||||||
colors,
|
maxLogLevel = level;
|
||||||
levels,
|
}
|
||||||
setLogLevel: (level) => { maxLogLevel = level; },
|
|
||||||
logger,
|
|
||||||
};
|
|
||||||
|
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"type": "module",
|
||||||
"main": "create.js",
|
"main": "create.js",
|
||||||
"bin": {
|
"bin": {
|
||||||
"clusteriocreate": "./create.js"
|
"clusteriocreate": "./create.js"
|
||||||
|
|||||||
+11
-13
@@ -1,9 +1,8 @@
|
|||||||
"use strict";
|
import { logger } from "./logging.js";
|
||||||
const { logger } = require("./logging");
|
import fs from "node:fs/promises";
|
||||||
const fs = require("node:fs/promises");
|
import path from "node:path";
|
||||||
const path = require("path");
|
|
||||||
|
|
||||||
const _package = require("./package.json");
|
import _package from "./package.json" with { type: "json" };
|
||||||
|
|
||||||
async function copyTemplateFile(src, dst, properties) {
|
async function copyTemplateFile(src, dst, properties) {
|
||||||
logger.verbose(`Writing ${dst} from template ${src}`);
|
logger.verbose(`Writing ${dst} from template ${src}`);
|
||||||
@@ -79,7 +78,7 @@ async function copyTemplateFile(src, dst, properties) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function copyPluginTemplates(pluginName, templates) {
|
export async function copyPluginTemplates(pluginName, templates) {
|
||||||
logger.info(`Please wait, coping templates for ${templates.join(", ")}`);
|
logger.info(`Please wait, coping templates for ${templates.join(", ")}`);
|
||||||
const files = new Map();
|
const files = new Map();
|
||||||
const prepare = [];
|
const prepare = [];
|
||||||
@@ -96,8 +95,11 @@ async function copyPluginTemplates(pluginName, templates) {
|
|||||||
|
|
||||||
// Get the file extension and path to the templates
|
// Get the file extension and path to the templates
|
||||||
const ext = javascriptOnly ? "js" : "ts";
|
const ext = javascriptOnly ? "js" : "ts";
|
||||||
const templatePath = path.resolve(__dirname, javascriptOnly ? "./templates/plugin-js" : "./templates/plugin-ts");
|
const templatePath = path.resolve(
|
||||||
const commonPath = path.resolve(__dirname, "./templates/common");
|
import.meta.dirname,
|
||||||
|
javascriptOnly ? "./templates/plugin-js" : "./templates/plugin-ts"
|
||||||
|
);
|
||||||
|
const commonPath = path.resolve(import.meta.dirname, "./templates/common");
|
||||||
|
|
||||||
// Files included in all templates
|
// Files included in all templates
|
||||||
files.set(".gitignore", path.join(commonPath, "template.gitignore"));
|
files.set(".gitignore", path.join(commonPath, "template.gitignore"));
|
||||||
@@ -119,7 +121,7 @@ async function copyPluginTemplates(pluginName, templates) {
|
|||||||
// Files and dependences to support webpack
|
// Files and dependences to support webpack
|
||||||
if (webpack) {
|
if (webpack) {
|
||||||
prepare.push("webpack-cli --mode production");
|
prepare.push("webpack-cli --mode production");
|
||||||
files.set("webpack.config.js", path.join(commonPath, "webpack.config.js"));
|
files.set("webpack.config.cjs", path.join(commonPath, "webpack.config.cjs"));
|
||||||
if (templates.includes("web")) {
|
if (templates.includes("web")) {
|
||||||
files.set(`web/index.${ext}x`, path.join(templatePath, `web/plugin.${ext}x`));
|
files.set(`web/index.${ext}x`, path.join(templatePath, `web/plugin.${ext}x`));
|
||||||
pluginContexts += 1;
|
pluginContexts += 1;
|
||||||
@@ -202,7 +204,3 @@ async function copyPluginTemplates(pluginName, templates) {
|
|||||||
await Promise.all(writes);
|
await Promise.all(writes);
|
||||||
logger.info("Successfully wrote all template files");
|
logger.info("Successfully wrote all template files");
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
copyPluginTemplates,
|
|
||||||
};
|
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "__plugin_name__",
|
"name": "__plugin_name__",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "Example Description. Package. Change me in package.json",
|
"description": "Example Description. Package. Change me in package.json",
|
||||||
|
"type": "module",
|
||||||
//%if typescript
|
//%if typescript
|
||||||
"main": "dist/node/index.js",
|
"main": "dist/node/index.js",
|
||||||
//%endif
|
//%endif
|
||||||
@@ -18,9 +19,6 @@
|
|||||||
//%if controller
|
//%if controller
|
||||||
"@clusterio/controller": "^__clusterio_version__",
|
"@clusterio/controller": "^__clusterio_version__",
|
||||||
//%endif
|
//%endif
|
||||||
//%if webpack
|
|
||||||
"@clusterio/web_ui": "^__clusterio_version__",
|
|
||||||
//%endif
|
|
||||||
//%if host
|
//%if host
|
||||||
"@clusterio/host": "^__clusterio_version__",
|
"@clusterio/host": "^__clusterio_version__",
|
||||||
//%endif
|
//%endif
|
||||||
@@ -29,6 +27,31 @@
|
|||||||
//%endif
|
//%endif
|
||||||
"@clusterio/lib": "^__clusterio_version__"
|
"@clusterio/lib": "^__clusterio_version__"
|
||||||
},
|
},
|
||||||
|
//%if controller | host | ctl
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
//%endif
|
||||||
|
//%if controller
|
||||||
|
"@clusterio/controller": {
|
||||||
|
"optional": true
|
||||||
|
//%endif
|
||||||
|
//%if controller & host | controller & ctl
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
|
//%if host
|
||||||
|
"@clusterio/host": {
|
||||||
|
"optional": true
|
||||||
|
//%endif
|
||||||
|
//%if host & ctl
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
|
//%if ctl
|
||||||
|
"@clusterio/ctl": {
|
||||||
|
"optional": true
|
||||||
|
//%endif
|
||||||
|
//%if controller | host | ctl
|
||||||
|
}
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
//%// Typescript and type declarations
|
//%// Typescript and type declarations
|
||||||
//%if typescript
|
//%if typescript
|
||||||
|
|||||||
File renamed without changes.
@@ -1,85 +1,66 @@
|
|||||||
"use strict";
|
import * as lib from "@clusterio/lib";
|
||||||
const lib = require("@clusterio/lib");
|
|
||||||
const { BaseControllerPlugin } = require("@clusterio/controller");
|
|
||||||
//%if multi_context // Messages requires multi context
|
//%if multi_context // Messages requires multi context
|
||||||
|
|
||||||
const {
|
import {
|
||||||
PluginExampleEvent, PluginExampleRequest,
|
PluginExampleEvent, PluginExampleRequest,
|
||||||
//%endif
|
//%endif
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
ExampleSubscribableUpdate, ExampleSubscribableValue,
|
ExampleSubscribableUpdate, ExampleSubscribableValue,
|
||||||
//%endif
|
//%endif
|
||||||
//%if multi_context // Messages requires multi context
|
//%if multi_context // Messages requires multi context
|
||||||
} = require("./messages");
|
} from "./messages.js";
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
class ControllerPlugin extends BaseControllerPlugin {
|
export default async function loadControllerPlugin(context) {
|
||||||
|
const { controller, logger, plugin } = context;
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
exampleDatabase;
|
// If needed, replace with loading from database file such as lib.Datastore
|
||||||
storageDirty = false;
|
const exampleDatabase = new Map([["foo", new ExampleSubscribableValue("foo", 0, false)]]);
|
||||||
|
|
||||||
//%endif
|
|
||||||
//%if multi_context // Subscribing requires multi context
|
|
||||||
async init() {
|
|
||||||
this.controller.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
|
|
||||||
this.controller.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
|
|
||||||
//%endif
|
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
|
||||||
this.controller.subscriptions.handle(ExampleSubscribableUpdate, this.handleExampleSubscription.bind(this));
|
|
||||||
// If needed, replace with loading from database file such as lib.Datastore
|
|
||||||
this.exampleDatabase = new Map([["foo", new ExampleSubscribableValue("foo", 0, false)]]);
|
|
||||||
//%endif
|
|
||||||
//%if multi_context // Subscribing requires multi context
|
|
||||||
}
|
|
||||||
//%endif
|
//%endif
|
||||||
|
//%if multi_context // Messages requires multi context
|
||||||
|
|
||||||
async onControllerConfigFieldChanged(field, curr, prev) {
|
controller.handle(PluginExampleEvent, async (event) => {
|
||||||
this.logger.info(`controller::onControllerConfigFieldChanged ${field}`);
|
logger.info(JSON.stringify(event));
|
||||||
}
|
});
|
||||||
//%if instance
|
|
||||||
|
|
||||||
async onInstanceConfigFieldChanged(instance, field, curr, prev) {
|
controller.handle(PluginExampleRequest, async (request) => {
|
||||||
this.logger.info(`controller::onInstanceConfigFieldChanged ${instance.id} ${field}`);
|
logger.info(JSON.stringify(request));
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
|
|
||||||
async onSaveData() {
|
|
||||||
this.logger.info("controller::onSaveData");
|
|
||||||
}
|
|
||||||
|
|
||||||
async onShutdown() {
|
|
||||||
this.logger.info("controller::onShutdown");
|
|
||||||
}
|
|
||||||
|
|
||||||
async onPlayerEvent(instance, event) {
|
|
||||||
this.logger.info(`controller::onPlayerEvent ${instance.id} ${JSON.stringify(event)}`);
|
|
||||||
}
|
|
||||||
//%if multi_context
|
|
||||||
|
|
||||||
async handlePluginExampleEvent(event) {
|
|
||||||
this.logger.info(JSON.stringify(event));
|
|
||||||
}
|
|
||||||
|
|
||||||
async handlePluginExampleRequest(request) {
|
|
||||||
this.logger.info(JSON.stringify(request));
|
|
||||||
return {
|
return {
|
||||||
myResponseString: request.myString,
|
myResponseString: request.myString,
|
||||||
myResponseNumbers: request.myNumberArray,
|
myResponseNumbers: request.myNumberArray,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
|
|
||||||
async handleExampleSubscription(request) {
|
controller.subscriptions.handle(ExampleSubscribableUpdate, async (request) => {
|
||||||
this.logger.info(JSON.stringify(request));
|
logger.info(JSON.stringify(request));
|
||||||
const values = [...this.exampleDatabase.values()].filter(
|
const values = [...exampleDatabase.values()].filter(
|
||||||
value => value.updatedAtMs > request.lastRequestTimeMs,
|
value => value.updatedAtMs > request.lastRequestTimeMs,
|
||||||
);
|
);
|
||||||
return values.length ? new ExampleSubscribableUpdate(values) : null;
|
return values.length ? new ExampleSubscribableUpdate(values) : null;
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
controller.hooks.controllerConfigFieldChanged.attach(plugin.name, async (field, curr, prev) => {
|
||||||
ControllerPlugin,
|
logger.info(`controller::controllerConfigFieldChanged ${field}`);
|
||||||
};
|
});
|
||||||
|
//%if instance
|
||||||
|
|
||||||
|
controller.hooks.instanceConfigFieldChanged.attach(plugin.name, async (instance, field, curr, prev) => {
|
||||||
|
logger.info(`controller::instanceConfigFieldChanged ${instance.id} ${field}`);
|
||||||
|
});
|
||||||
|
//%endif
|
||||||
|
|
||||||
|
controller.hooks.save.attach(plugin.name, async () => {
|
||||||
|
logger.info("controller::save");
|
||||||
|
});
|
||||||
|
|
||||||
|
controller.hooks.shutdown.attach(plugin.name, async () => {
|
||||||
|
logger.info("controller::shutdown");
|
||||||
|
});
|
||||||
|
|
||||||
|
controller.hooks.playerEvent.attach(plugin.name, async (instance, event) => {
|
||||||
|
logger.info(`controller::playerEvent ${instance.id} ${JSON.stringify(event)}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
"use strict";
|
import { CommandTree, Command } from "@clusterio/lib";
|
||||||
const { BaseCtlPlugin } = require("@clusterio/ctl");
|
|
||||||
const { CommandTree, Command } = require("@clusterio/lib");
|
|
||||||
//%// We do not check for multi context here because it doesn't make sense to have a ctl without messages
|
//%// We do not check for multi context here because it doesn't make sense to have a ctl without messages
|
||||||
const { PluginExampleEvent, PluginExampleRequest } = require("./messages");
|
import { PluginExampleEvent, PluginExampleRequest } from "./messages.js";
|
||||||
/* eslint-disable no-console */
|
/* eslint-disable no-console */
|
||||||
|
|
||||||
const pluginCommands = new CommandTree({
|
const pluginCommands = new CommandTree({
|
||||||
@@ -21,12 +19,8 @@ pluginCommands.add(new Command({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
/* eslint-enable no-console */
|
/* eslint-enable no-console */
|
||||||
class CtlPlugin extends BaseCtlPlugin {
|
export default async function loadCtlPlugin(context) {
|
||||||
async addCommands(rootCommand) {
|
context.hooks.addCommands.attach(context.plugin.name, async (rootCommand) => {
|
||||||
rootCommand.add(pluginCommands);
|
rootCommand.add(pluginCommands);
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
CtlPlugin,
|
|
||||||
};
|
|
||||||
@@ -1,41 +1,30 @@
|
|||||||
"use strict";
|
import * as lib from "@clusterio/lib";
|
||||||
const lib = require("@clusterio/lib");
|
|
||||||
const { BaseHostPlugin } = require("@clusterio/host");
|
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
const { PluginExampleEvent, PluginExampleRequest } = require("./messages");
|
import { PluginExampleEvent, PluginExampleRequest } from "./messages.js";
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
class HostPlugin extends BaseHostPlugin {
|
export default async function loadHostPlugin(context) {
|
||||||
//%if multi_context
|
const { host, logger, plugin } = context;
|
||||||
async init() {
|
|
||||||
this.host.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
|
|
||||||
this.host.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
|
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
|
|
||||||
async onHostConfigFieldChanged(field, curr, prev) {
|
|
||||||
this.logger.info(`host::onInstanceConfigFieldChanged ${field}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async onShutdown() {
|
|
||||||
this.logger.info("host::onShutdown");
|
|
||||||
}
|
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
|
|
||||||
async handlePluginExampleEvent(event) {
|
host.handle(PluginExampleEvent, async (event) => {
|
||||||
this.logger.info(JSON.stringify(event));
|
logger.info(JSON.stringify(event));
|
||||||
}
|
});
|
||||||
|
|
||||||
async handlePluginExampleRequest(request) {
|
host.handle(PluginExampleRequest, async (request) => {
|
||||||
this.logger.info(JSON.stringify(request));
|
logger.info(JSON.stringify(request));
|
||||||
return {
|
return {
|
||||||
myResponseString: request.myString,
|
myResponseString: request.myString,
|
||||||
myResponseNumbers: request.myNumberArray,
|
myResponseNumbers: request.myNumberArray,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
host.hooks.hostConfigFieldChanged.attach(plugin.name, async (field, curr, prev) => {
|
||||||
HostPlugin,
|
logger.info(`host::hostConfigFieldChanged ${field}`);
|
||||||
};
|
});
|
||||||
|
|
||||||
|
host.hooks.shutdown.attach(plugin.name, async () => {
|
||||||
|
logger.info("host::shutdown");
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,42 +1,9 @@
|
|||||||
"use strict";
|
import * as lib from "@clusterio/lib";
|
||||||
const lib = require("@clusterio/lib");
|
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
const Messages = require("./messages");
|
import * as Messages from "./messages.js";
|
||||||
|
|
||||||
lib.definePermission({
|
|
||||||
name: "__plugin_name__.example.permission.event",
|
|
||||||
title: "Example permission event",
|
|
||||||
description: "Example Description. Event. Change me in index.js",
|
|
||||||
grantByDefault: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
lib.definePermission({
|
|
||||||
name: "__plugin_name__.example.permission.request",
|
|
||||||
title: "Example permission request",
|
|
||||||
description: "Example Description. Request. Change me in index.js",
|
|
||||||
grantByDefault: true,
|
|
||||||
});
|
|
||||||
//%endif
|
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
|
||||||
|
|
||||||
lib.definePermission({
|
|
||||||
name: "__plugin_name__.example.permission.subscribe",
|
|
||||||
title: "Example permission subscribe",
|
|
||||||
description: "Example Description. Subscribe. Change me in index.js",
|
|
||||||
grantByDefault: true,
|
|
||||||
});
|
|
||||||
//%endif
|
|
||||||
//%if web
|
|
||||||
|
|
||||||
lib.definePermission({
|
|
||||||
name: "__plugin_name__.page.view",
|
|
||||||
title: "Example page view permission",
|
|
||||||
description: "Example Description. View. Change me in index.js",
|
|
||||||
grantByDefault: true,
|
|
||||||
});
|
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
const plugin = {
|
export const plugin = {
|
||||||
name: "__plugin_name__",
|
name: "__plugin_name__",
|
||||||
title: "__plugin_name__",
|
title: "__plugin_name__",
|
||||||
description: "Example Description. Plugin. Change me in index.js",
|
description: "Example Description. Plugin. Change me in index.js",
|
||||||
@@ -44,7 +11,7 @@ const plugin = {
|
|||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if controller
|
//%if controller
|
||||||
controllerEntrypoint: "./dist/node/controller",
|
controllerEntrypoint: "./dist/node/controller.js",
|
||||||
//%endif
|
//%endif
|
||||||
//%if controller & config
|
//%if controller & config
|
||||||
controllerConfigFields: {
|
controllerConfigFields: {
|
||||||
@@ -60,7 +27,7 @@ const plugin = {
|
|||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if host
|
//%if host
|
||||||
hostEntrypoint: "./dist/node/host",
|
hostEntrypoint: "./dist/node/host.js",
|
||||||
//%endif
|
//%endif
|
||||||
//%if host & config
|
//%if host & config
|
||||||
hostConfigFields: {
|
hostConfigFields: {
|
||||||
@@ -76,7 +43,7 @@ const plugin = {
|
|||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if instance | module // Modules load an empty instance plugin
|
//%if instance | module // Modules load an empty instance plugin
|
||||||
instanceEntrypoint: "./dist/node/instance",
|
instanceEntrypoint: "./dist/node/instance.js",
|
||||||
//%endif
|
//%endif
|
||||||
//%if instance & config
|
//%if instance & config
|
||||||
instanceConfigFields: {
|
instanceConfigFields: {
|
||||||
@@ -92,7 +59,7 @@ const plugin = {
|
|||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if ctl
|
//%if ctl
|
||||||
ctlEntrypoint: "./dist/node/ctl",
|
ctlEntrypoint: "./dist/node/ctl.js",
|
||||||
//%endif
|
//%endif
|
||||||
//%if ctl & config
|
//%if ctl & config
|
||||||
controlConfigFields: {
|
controlConfigFields: {
|
||||||
@@ -116,6 +83,43 @@ const plugin = {
|
|||||||
//%if multi_context // Subscribing requires multi context
|
//%if multi_context // Subscribing requires multi context
|
||||||
],
|
],
|
||||||
//%endif
|
//%endif
|
||||||
|
//%if multi_context | web
|
||||||
|
|
||||||
|
permissions: [
|
||||||
|
//%endif
|
||||||
|
//%if multi_context
|
||||||
|
{
|
||||||
|
name: "__plugin_name__.example.permission.event",
|
||||||
|
title: "Example permission event",
|
||||||
|
description: "Example Description. Event. Change me in index.js",
|
||||||
|
grantByDefault: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "__plugin_name__.example.permission.request",
|
||||||
|
title: "Example permission request",
|
||||||
|
description: "Example Description. Request. Change me in index.js",
|
||||||
|
grantByDefault: true,
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
|
{
|
||||||
|
name: "__plugin_name__.example.permission.subscribe",
|
||||||
|
title: "Example permission subscribe",
|
||||||
|
description: "Example Description. Subscribe. Change me in index.js",
|
||||||
|
grantByDefault: true,
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
|
//%if web
|
||||||
|
{
|
||||||
|
name: "__plugin_name__.page.view",
|
||||||
|
title: "Example page view permission",
|
||||||
|
description: "Example Description. View. Change me in index.js",
|
||||||
|
grantByDefault: true,
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
|
//%if multi_context | web
|
||||||
|
],
|
||||||
|
//%endif
|
||||||
//%if web // Web content template has an example route which is the plugin name
|
//%if web // Web content template has an example route which is the plugin name
|
||||||
|
|
||||||
webEntrypoint: "./web",
|
webEntrypoint: "./web",
|
||||||
@@ -124,7 +128,3 @@ const plugin = {
|
|||||||
],
|
],
|
||||||
//%endif
|
//%endif
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
plugin,
|
|
||||||
};
|
|
||||||
@@ -1,74 +1,56 @@
|
|||||||
"use strict";
|
import * as lib from "@clusterio/lib";
|
||||||
const lib = require("@clusterio/lib");
|
|
||||||
const { BaseInstancePlugin } = require("@clusterio/host");
|
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
const { PluginExampleEvent, PluginExampleRequest } = require("./messages");
|
import { PluginExampleEvent, PluginExampleRequest } from "./messages.js";
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
class InstancePlugin extends BaseInstancePlugin {
|
export default async function loadInstancePlugin(context) {
|
||||||
//%if multi_context | module
|
const { instance, logger, plugin } = context;
|
||||||
async init() {
|
|
||||||
//%if multi_context
|
|
||||||
this.instance.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
|
|
||||||
this.instance.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
|
|
||||||
//%endif
|
|
||||||
//%if module
|
|
||||||
this.instance.server.handle("__plugin_name__-plugin_example_ipc", this.handlePluginExampleIPC.bind(this));
|
|
||||||
//%endif
|
|
||||||
//%if multi_context | module
|
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
|
|
||||||
async onInstanceConfigFieldChanged(field, curr, prev) {
|
|
||||||
this.logger.info(`instance::onInstanceConfigFieldChanged ${field}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async onStart() {
|
|
||||||
// Called once rcon becomes available
|
|
||||||
this.logger.info("instance::onStart");
|
|
||||||
}
|
|
||||||
|
|
||||||
async onStop() {
|
|
||||||
// Called during normal exits before rcon becomes unavailable
|
|
||||||
this.logger.info("instance::onStop");
|
|
||||||
}
|
|
||||||
|
|
||||||
onExit() {
|
|
||||||
// Called during all exits, including crashes and init failures, rcon is not available
|
|
||||||
this.logger.info("instance::onExit");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async onPlayerEvent(event) {
|
|
||||||
this.logger.info(`onPlayerEvent::onPlayerEvent ${JSON.stringify(event)}`);
|
|
||||||
//%if module
|
|
||||||
if (this.instance.status === "running") {
|
|
||||||
await this.sendRcon("/sc __plugin_name__.foo()");
|
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
}
|
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
|
|
||||||
async handlePluginExampleEvent(event) {
|
instance.handle(PluginExampleEvent, async (event) => {
|
||||||
this.logger.info(JSON.stringify(event));
|
logger.info(JSON.stringify(event));
|
||||||
}
|
});
|
||||||
|
|
||||||
async handlePluginExampleRequest(request) {
|
instance.handle(PluginExampleRequest, async (request) => {
|
||||||
this.logger.info(JSON.stringify(request));
|
logger.info(JSON.stringify(request));
|
||||||
return {
|
return {
|
||||||
myResponseString: request.myString,
|
myResponseString: request.myString,
|
||||||
myResponseNumbers: request.myNumberArray,
|
myResponseNumbers: request.myNumberArray,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
//%if module
|
//%if module
|
||||||
|
|
||||||
async handlePluginExampleIPC(event) {
|
instance.server.handle("__plugin_name__-plugin_example_ipc", async (event) => {
|
||||||
this.logger.info(JSON.stringify(event));
|
logger.info(JSON.stringify(event));
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
instance.hooks.instanceConfigFieldChanged.attach(plugin.name, async (field, curr, prev) => {
|
||||||
InstancePlugin,
|
logger.info(`instance::instanceConfigFieldChanged ${field}`);
|
||||||
};
|
});
|
||||||
|
|
||||||
|
instance.hooks.start.attach(plugin.name, async () => {
|
||||||
|
// Called once rcon becomes available
|
||||||
|
logger.info("instance::start");
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.hooks.stop.attach(plugin.name, async () => {
|
||||||
|
// Called during normal exits before rcon becomes unavailable
|
||||||
|
logger.info("instance::stop");
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.hooks.exit.attach(plugin.name, () => {
|
||||||
|
// Called during all exits, including crashes and init failures, rcon is not available
|
||||||
|
logger.info("instance::exit");
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.hooks.playerEvent.attach(plugin.name, async (event) => {
|
||||||
|
logger.info(`instance::playerEvent ${JSON.stringify(event)}`);
|
||||||
|
//%if module
|
||||||
|
if (instance.status === "running") {
|
||||||
|
await instance.sendRcon("/sc __plugin_name__.foo()", false, plugin.name);
|
||||||
|
}
|
||||||
|
//%endif
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,11 +1,3 @@
|
|||||||
"use strict";
|
// This entrypoint is empty because an instance entrypoint must be defined for a module to be injected
|
||||||
const { BaseInstancePlugin } = require("@clusterio/host");
|
// This requirement may change in the future to allow for standalone modules
|
||||||
|
export default async function loadInstancePlugin(context) { }
|
||||||
class InstancePlugin extends BaseInstancePlugin {
|
|
||||||
// This class is empty because an instance plugin must be defined for a module to be injected
|
|
||||||
// This requirement may change in the future to allow for standalone modules
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
InstancePlugin,
|
|
||||||
};
|
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
"use strict";
|
import { plainJson, jsonArray, JsonBoolean, JsonNumber, JsonString, StringEnum } from "@clusterio/lib";
|
||||||
const { plainJson, jsonArray, JsonBoolean, JsonNumber, JsonString, StringEnum } = require("@clusterio/lib");
|
import { Type } from "@sinclair/typebox";
|
||||||
const { Type } = require("@sinclair/typebox");
|
|
||||||
|
|
||||||
class PluginExampleEvent {
|
export class PluginExampleEvent {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = ["host", "control"];
|
static src = ["host", "control"];
|
||||||
static dst = ["controller", "host", "instance"];
|
static dst = ["controller", "host", "instance"];
|
||||||
@@ -24,7 +23,7 @@ class PluginExampleEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class PluginExampleRequest {
|
export class PluginExampleRequest {
|
||||||
static type = "request";
|
static type = "request";
|
||||||
static src = ["host", "control"];
|
static src = ["host", "control"];
|
||||||
static dst = ["controller", "host", "instance"];
|
static dst = ["controller", "host", "instance"];
|
||||||
@@ -52,7 +51,7 @@ class PluginExampleRequest {
|
|||||||
}
|
}
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
|
|
||||||
class ExampleSubscribableValue {
|
export class ExampleSubscribableValue {
|
||||||
constructor(id, updatedAtMs, isDeleted) {
|
constructor(id, updatedAtMs, isDeleted) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.updatedAtMs = updatedAtMs;
|
this.updatedAtMs = updatedAtMs;
|
||||||
@@ -70,7 +69,7 @@ class ExampleSubscribableValue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ExampleSubscribableUpdate {
|
export class ExampleSubscribableUpdate {
|
||||||
static type = "event";
|
static type = "event";
|
||||||
static src = "controller";
|
static src = "controller";
|
||||||
static dst = "control";
|
static dst = "control";
|
||||||
@@ -90,12 +89,3 @@ class ExampleSubscribableUpdate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
PluginExampleEvent,
|
|
||||||
PluginExampleRequest,
|
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
|
||||||
ExampleSubscribableValue,
|
|
||||||
ExampleSubscribableUpdate,
|
|
||||||
//%endif
|
|
||||||
};
|
|
||||||
@@ -10,7 +10,7 @@ import React, {
|
|||||||
// } from "antd";
|
// } from "antd";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
BaseWebPlugin, PageLayout, PageHeader, Control, ControlContext, notifyErrorHandler,
|
PageLayout, PageHeader, Control, ControlContext, notifyErrorHandler,
|
||||||
} from "@clusterio/web_ui";
|
} from "@clusterio/web_ui";
|
||||||
//%if multi_context // Messages requires multi context
|
//%if multi_context // Messages requires multi context
|
||||||
|
|
||||||
@@ -21,16 +21,26 @@ import {
|
|||||||
ExampleSubscribableUpdate, ExampleSubscribableValue,
|
ExampleSubscribableUpdate, ExampleSubscribableValue,
|
||||||
//%endif
|
//%endif
|
||||||
//%if multi_context // Messages requires multi context
|
//%if multi_context // Messages requires multi context
|
||||||
} from "../messages";
|
} from "../messages.js";
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
//%if controller // Subscribing requires web content and the controller
|
||||||
|
|
||||||
|
// Created when the plugin is loaded, before any page is rendered
|
||||||
|
let exampleSubscriber;
|
||||||
|
|
||||||
|
function useSubscribableData() {
|
||||||
|
const control = useContext(ControlContext);
|
||||||
|
const subscribe = useCallback((callback) => exampleSubscriber.subscribe(callback), [control]);
|
||||||
|
return useSyncExternalStore(subscribe, () => exampleSubscriber.getSnapshot());
|
||||||
|
}
|
||||||
|
//%endif
|
||||||
|
|
||||||
function MyTemplatePage() {
|
function MyTemplatePage() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
//%if controller // Subscribing requires web content and the controller
|
//%if controller // Subscribing requires web content and the controller
|
||||||
const plugin = control.plugins.get("__plugin_name__");
|
const [subscribableData, synced] = useSubscribableData();
|
||||||
const [subscribableData, synced] = plugin.useSubscribableData();
|
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
return <PageLayout nav={[{ name: "__plugin_name__" }]}>
|
return <PageLayout nav={[{ name: "__plugin_name__" }]}>
|
||||||
@@ -41,53 +51,39 @@ function MyTemplatePage() {
|
|||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WebPlugin extends BaseWebPlugin {
|
export default async function loadWebPlugin(context) {
|
||||||
|
const { control, logger, plugin } = context;
|
||||||
//%if controller // Subscribing requires web content and the controller
|
//%if controller // Subscribing requires web content and the controller
|
||||||
subscribableData = new lib.EventSubscriber(ExampleSubscribableUpdate, this.control);
|
exampleSubscriber = new lib.MapSubscriber(ExampleSubscribableUpdate, control);
|
||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
async init() {
|
|
||||||
this.pages = [
|
control.hooks.pages.attach(plugin.name, () => [
|
||||||
{
|
{
|
||||||
path: "/__plugin_name__",
|
path: "/__plugin_name__",
|
||||||
sidebarName: "__plugin_name__",
|
sidebarName: "__plugin_name__",
|
||||||
// This permission is client side only, so it must match the permission string of a resource request to be secure
|
// This permission is client side only, so it must match the permission string of a resource request to be secure
|
||||||
// An undefined value means that the page will always be visible
|
// An undefined value means that the page will always be visible
|
||||||
//%if controller // Subscribing requires web content and the controller
|
//%if controller // Subscribing requires web content and the controller
|
||||||
permission: "__plugin_name__.example.permission.subscribe",
|
permission: "__plugin_name__.example.permission.subscribe",
|
||||||
//%endif
|
//%endif
|
||||||
//%if !controller
|
//%if !controller
|
||||||
permission: "__plugin_name__.example.permission.view",
|
permission: "__plugin_name__.page.view",
|
||||||
//%endif
|
//%endif
|
||||||
content: <MyTemplatePage/>,
|
content: <MyTemplatePage/>,
|
||||||
},
|
},
|
||||||
];
|
]);
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
|
|
||||||
this.control.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
|
control.handle(PluginExampleEvent, async (event) => {
|
||||||
this.control.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
|
logger.info(JSON.stringify(event));
|
||||||
//%endif
|
});
|
||||||
}
|
|
||||||
//%if controller// Subscribing requires web content and the controller
|
|
||||||
|
|
||||||
useSubscribableData() {
|
control.handle(PluginExampleRequest, async (request) => {
|
||||||
const control = useContext(ControlContext);
|
logger.info(JSON.stringify(request));
|
||||||
const subscribe = useCallback((callback) => this.subscribableData.subscribe(callback), [control]);
|
|
||||||
return useSyncExternalStore(subscribe, () => this.subscribableData.getSnapshot());
|
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
//%if multi_context
|
|
||||||
|
|
||||||
async handlePluginExampleEvent(event) {
|
|
||||||
this.logger.info(JSON.stringify(event));
|
|
||||||
}
|
|
||||||
|
|
||||||
async handlePluginExampleRequest(request) {
|
|
||||||
this.logger.info(JSON.stringify(request));
|
|
||||||
return {
|
return {
|
||||||
myResponseString: request.myString,
|
myResponseString: request.myString,
|
||||||
myResponseNumbers: request.myNumberArray,
|
myResponseNumbers: request.myNumberArray,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { BaseControllerPlugin, InstanceRecord } from "@clusterio/controller";
|
import type { ControllerPluginContext, InstanceRecord } from "@clusterio/controller";
|
||||||
//%if multi_context // Messages requires multi context
|
//%if multi_context // Messages requires multi context
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -9,72 +9,61 @@ import {
|
|||||||
ExampleSubscribableUpdate, ExampleSubscribableValue,
|
ExampleSubscribableUpdate, ExampleSubscribableValue,
|
||||||
//%endif
|
//%endif
|
||||||
//%if multi_context // Messages requires multi context
|
//%if multi_context // Messages requires multi context
|
||||||
} from "./messages";
|
} from "./messages.js";
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
export class ControllerPlugin extends BaseControllerPlugin {
|
export default async function loadControllerPlugin(context: ControllerPluginContext) {
|
||||||
|
const { controller, logger, plugin } = context;
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
exampleDatabase!: Map<string, ExampleSubscribableValue>;
|
// If needed, replace with loading from database file such as lib.Datastore
|
||||||
storageDirty = false;
|
const exampleDatabase = new Map([["foo", new ExampleSubscribableValue("foo", 0, false)]]);
|
||||||
|
|
||||||
//%endif
|
|
||||||
//%if multi_context // Subscribing requires multi context
|
|
||||||
async init() {
|
|
||||||
this.controller.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
|
|
||||||
this.controller.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
|
|
||||||
//%endif
|
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
|
||||||
this.controller.subscriptions.handle(ExampleSubscribableUpdate, this.handleExampleSubscription.bind(this));
|
|
||||||
// If needed, replace with loading from database file such as lib.Datastore
|
|
||||||
this.exampleDatabase = new Map([["foo", new ExampleSubscribableValue("foo", 0, false)]]);
|
|
||||||
//%endif
|
|
||||||
//%if multi_context // Subscribing requires multi context
|
|
||||||
}
|
|
||||||
//%endif
|
//%endif
|
||||||
|
//%if multi_context // Messages requires multi context
|
||||||
|
|
||||||
async onControllerConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
|
controller.handle(PluginExampleEvent, async (event: PluginExampleEvent) => {
|
||||||
this.logger.info(`controller::onControllerConfigFieldChanged ${field}`);
|
logger.info(JSON.stringify(event));
|
||||||
}
|
});
|
||||||
//%if instance
|
|
||||||
|
|
||||||
async onInstanceConfigFieldChanged(instance: InstanceRecord, field: string, curr: unknown, prev: unknown) {
|
controller.handle(PluginExampleRequest, async (request: PluginExampleRequest) => {
|
||||||
this.logger.info(`controller::onInstanceConfigFieldChanged ${instance.id} ${field}`);
|
logger.info(JSON.stringify(request));
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
|
|
||||||
async onSaveData() {
|
|
||||||
this.logger.info("controller::onSaveData");
|
|
||||||
}
|
|
||||||
|
|
||||||
async onShutdown() {
|
|
||||||
this.logger.info("controller::onShutdown");
|
|
||||||
}
|
|
||||||
|
|
||||||
async onPlayerEvent(instance: InstanceRecord, event: lib.PlayerEvent) {
|
|
||||||
this.logger.info(`controller::onPlayerEvent ${instance.id} ${JSON.stringify(event)}`);
|
|
||||||
}
|
|
||||||
//%if multi_context
|
|
||||||
|
|
||||||
async handlePluginExampleEvent(event: PluginExampleEvent) {
|
|
||||||
this.logger.info(JSON.stringify(event));
|
|
||||||
}
|
|
||||||
|
|
||||||
async handlePluginExampleRequest(request: PluginExampleRequest) {
|
|
||||||
this.logger.info(JSON.stringify(request));
|
|
||||||
return {
|
return {
|
||||||
myResponseString: request.myString,
|
myResponseString: request.myString,
|
||||||
myResponseNumbers: request.myNumberArray,
|
myResponseNumbers: request.myNumberArray,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
|
|
||||||
async handleExampleSubscription(request: lib.SubscriptionRequest) {
|
controller.subscriptions.handle(ExampleSubscribableUpdate, async (request: lib.SubscriptionRequest) => {
|
||||||
this.logger.info(JSON.stringify(request));
|
logger.info(JSON.stringify(request));
|
||||||
const values = [...this.exampleDatabase.values()].filter(
|
const values = [...exampleDatabase.values()].filter(
|
||||||
value => value.updatedAtMs > request.lastRequestTimeMs,
|
value => value.updatedAtMs > request.lastRequestTimeMs,
|
||||||
);
|
);
|
||||||
return values.length ? new ExampleSubscribableUpdate(values) : null;
|
return values.length ? new ExampleSubscribableUpdate(values) : null;
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
|
controller.hooks.controllerConfigFieldChanged.attach(plugin.name, async (field, curr, prev) => {
|
||||||
|
logger.info(`controller::controllerConfigFieldChanged ${field}`);
|
||||||
|
});
|
||||||
|
//%if instance
|
||||||
|
|
||||||
|
controller.hooks.instanceConfigFieldChanged.attach(
|
||||||
|
plugin.name, async (instance: InstanceRecord, field, curr, prev) => {
|
||||||
|
logger.info(`controller::instanceConfigFieldChanged ${instance.id} ${field}`);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
//%endif
|
||||||
|
|
||||||
|
controller.hooks.save.attach(plugin.name, async () => {
|
||||||
|
logger.info("controller::save");
|
||||||
|
});
|
||||||
|
|
||||||
|
controller.hooks.shutdown.attach(plugin.name, async () => {
|
||||||
|
logger.info("controller::shutdown");
|
||||||
|
});
|
||||||
|
|
||||||
|
controller.hooks.playerEvent.attach(plugin.name, async (instance: InstanceRecord, event: lib.PlayerEvent) => {
|
||||||
|
logger.info(`controller::playerEvent ${instance.id} ${JSON.stringify(event)}`);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { BaseCtlPlugin, type Control } from "@clusterio/ctl";
|
import type { Control, CtlPluginContext } from "@clusterio/ctl";
|
||||||
import { CommandTree, Command } from "@clusterio/lib";
|
import { CommandTree, Command } from "@clusterio/lib";
|
||||||
//%// We do not check for multi context here because it doesn't make sense to have a ctl without messages
|
//%// We do not check for multi context here because it doesn't make sense to have a ctl without messages
|
||||||
import { PluginExampleEvent, PluginExampleRequest } from "./messages";
|
import { PluginExampleEvent, PluginExampleRequest } from "./messages.js";
|
||||||
/* eslint-disable no-console */
|
/* eslint-disable no-console */
|
||||||
|
|
||||||
const pluginCommands = new CommandTree({
|
const pluginCommands = new CommandTree({
|
||||||
@@ -20,8 +20,8 @@ pluginCommands.add(new Command({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
/* eslint-enable no-console */
|
/* eslint-enable no-console */
|
||||||
export class CtlPlugin extends BaseCtlPlugin {
|
export default async function loadCtlPlugin(context: CtlPluginContext) {
|
||||||
async addCommands(rootCommand: CommandTree) {
|
context.hooks.addCommands.attach(context.plugin.name, async (rootCommand) => {
|
||||||
rootCommand.add(pluginCommands);
|
rootCommand.add(pluginCommands);
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
@@ -1,36 +1,30 @@
|
|||||||
import * as lib from "@clusterio/lib";
|
import type { HostPluginContext } from "@clusterio/host";
|
||||||
import { BaseHostPlugin } from "@clusterio/host";
|
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
import { PluginExampleEvent, PluginExampleRequest } from "./messages";
|
import { PluginExampleEvent, PluginExampleRequest } from "./messages.js";
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
export class HostPlugin extends BaseHostPlugin {
|
export default async function loadHostPlugin(context: HostPluginContext) {
|
||||||
//%if multi_context
|
const { host, logger, plugin } = context;
|
||||||
async init() {
|
|
||||||
this.host.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
|
|
||||||
this.host.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
|
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
|
|
||||||
async onHostConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
|
|
||||||
this.logger.info(`host::onInstanceConfigFieldChanged ${field}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async onShutdown() {
|
|
||||||
this.logger.info("host::onShutdown");
|
|
||||||
}
|
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
|
|
||||||
async handlePluginExampleEvent(event: PluginExampleEvent) {
|
host.handle(PluginExampleEvent, async (event: PluginExampleEvent) => {
|
||||||
this.logger.info(JSON.stringify(event));
|
logger.info(JSON.stringify(event));
|
||||||
}
|
});
|
||||||
|
|
||||||
async handlePluginExampleRequest(request: PluginExampleRequest) {
|
host.handle(PluginExampleRequest, async (request: PluginExampleRequest) => {
|
||||||
this.logger.info(JSON.stringify(request));
|
logger.info(JSON.stringify(request));
|
||||||
return {
|
return {
|
||||||
myResponseString: request.myString,
|
myResponseString: request.myString,
|
||||||
myResponseNumbers: request.myNumberArray,
|
myResponseNumbers: request.myNumberArray,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
|
host.hooks.hostConfigFieldChanged.attach(plugin.name, async (field, curr, prev) => {
|
||||||
|
logger.info(`host::hostConfigFieldChanged ${field}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
host.hooks.shutdown.attach(plugin.name, async () => {
|
||||||
|
logger.info("host::shutdown");
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -1,40 +1,8 @@
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
import * as Messages from "./messages";
|
import * as Messages from "./messages.js";
|
||||||
|
|
||||||
lib.definePermission({
|
|
||||||
name: "__plugin_name__.example.permission.event",
|
|
||||||
title: "Example permission event",
|
|
||||||
description: "Example Description. Event. Change me in index.ts",
|
|
||||||
grantByDefault: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
lib.definePermission({
|
|
||||||
name: "__plugin_name__.example.permission.request",
|
|
||||||
title: "Example permission request",
|
|
||||||
description: "Example Description. Request. Change me in index.ts",
|
|
||||||
grantByDefault: true,
|
|
||||||
});
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if controller & web // Subscribing requires web content and the controller
|
//%if config | multi_context | web
|
||||||
|
|
||||||
lib.definePermission({
|
|
||||||
name: "__plugin_name__.example.permission.subscribe",
|
|
||||||
title: "Example permission subscribe",
|
|
||||||
description: "Example Description. Subscribe. Change me in index.ts",
|
|
||||||
grantByDefault: true,
|
|
||||||
});
|
|
||||||
//%endif
|
|
||||||
//%if web
|
|
||||||
|
|
||||||
lib.definePermission({
|
|
||||||
name: "__plugin_name__.page.view",
|
|
||||||
title: "Example page view permission",
|
|
||||||
description: "Example Description. View. Change me in index.ts",
|
|
||||||
grantByDefault: true,
|
|
||||||
});
|
|
||||||
//%endif
|
|
||||||
//%if config
|
|
||||||
|
|
||||||
declare module "@clusterio/lib" {
|
declare module "@clusterio/lib" {
|
||||||
//%endif
|
//%endif
|
||||||
@@ -58,7 +26,23 @@ declare module "@clusterio/lib" {
|
|||||||
"__plugin_name__.myControlField": string;
|
"__plugin_name__.myControlField": string;
|
||||||
}
|
}
|
||||||
//%endif
|
//%endif
|
||||||
//%if config
|
//%if multi_context | web
|
||||||
|
export interface Permissions {
|
||||||
|
//%endif
|
||||||
|
//%if multi_context
|
||||||
|
"__plugin_name__.example.permission.event": never;
|
||||||
|
"__plugin_name__.example.permission.request": never;
|
||||||
|
//%endif
|
||||||
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
|
"__plugin_name__.example.permission.subscribe": never;
|
||||||
|
//%endif
|
||||||
|
//%if web
|
||||||
|
"__plugin_name__.page.view": never;
|
||||||
|
//%endif
|
||||||
|
//%if multi_context | web
|
||||||
|
}
|
||||||
|
//%endif
|
||||||
|
//%if config | multi_context | web
|
||||||
}
|
}
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
@@ -71,7 +55,7 @@ export const plugin: lib.PluginDeclaration = {
|
|||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if controller
|
//%if controller
|
||||||
controllerEntrypoint: "./dist/node/controller",
|
controllerEntrypoint: "./dist/node/controller.js",
|
||||||
//%endif
|
//%endif
|
||||||
//%if controller & config
|
//%if controller & config
|
||||||
controllerConfigFields: {
|
controllerConfigFields: {
|
||||||
@@ -87,7 +71,7 @@ export const plugin: lib.PluginDeclaration = {
|
|||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if host
|
//%if host
|
||||||
hostEntrypoint: "./dist/node/host",
|
hostEntrypoint: "./dist/node/host.js",
|
||||||
//%endif
|
//%endif
|
||||||
//%if host & config
|
//%if host & config
|
||||||
hostConfigFields: {
|
hostConfigFields: {
|
||||||
@@ -103,7 +87,7 @@ export const plugin: lib.PluginDeclaration = {
|
|||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if instance | module // Modules load an empty instance plugin
|
//%if instance | module // Modules load an empty instance plugin
|
||||||
instanceEntrypoint: "./dist/node/instance",
|
instanceEntrypoint: "./dist/node/instance.js",
|
||||||
//%endif
|
//%endif
|
||||||
//%if instance & config
|
//%if instance & config
|
||||||
instanceConfigFields: {
|
instanceConfigFields: {
|
||||||
@@ -119,7 +103,7 @@ export const plugin: lib.PluginDeclaration = {
|
|||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
//%if ctl
|
//%if ctl
|
||||||
ctlEntrypoint: "./dist/node/ctl",
|
ctlEntrypoint: "./dist/node/ctl.js",
|
||||||
//%endif
|
//%endif
|
||||||
//%if ctl & config
|
//%if ctl & config
|
||||||
controlConfigFields: {
|
controlConfigFields: {
|
||||||
@@ -143,6 +127,43 @@ export const plugin: lib.PluginDeclaration = {
|
|||||||
//%if multi_context // Subscribing requires multi context
|
//%if multi_context // Subscribing requires multi context
|
||||||
],
|
],
|
||||||
//%endif
|
//%endif
|
||||||
|
//%if multi_context | web
|
||||||
|
|
||||||
|
permissions: [
|
||||||
|
//%endif
|
||||||
|
//%if multi_context
|
||||||
|
{
|
||||||
|
name: "__plugin_name__.example.permission.event",
|
||||||
|
title: "Example permission event",
|
||||||
|
description: "Example Description. Event. Change me in index.ts",
|
||||||
|
grantByDefault: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "__plugin_name__.example.permission.request",
|
||||||
|
title: "Example permission request",
|
||||||
|
description: "Example Description. Request. Change me in index.ts",
|
||||||
|
grantByDefault: true,
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
|
//%if controller & web // Subscribing requires web content and the controller
|
||||||
|
{
|
||||||
|
name: "__plugin_name__.example.permission.subscribe",
|
||||||
|
title: "Example permission subscribe",
|
||||||
|
description: "Example Description. Subscribe. Change me in index.ts",
|
||||||
|
grantByDefault: true,
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
|
//%if web
|
||||||
|
{
|
||||||
|
name: "__plugin_name__.page.view",
|
||||||
|
title: "Example page view permission",
|
||||||
|
description: "Example Description. View. Change me in index.ts",
|
||||||
|
grantByDefault: true,
|
||||||
|
},
|
||||||
|
//%endif
|
||||||
|
//%if multi_context | web
|
||||||
|
],
|
||||||
|
//%endif
|
||||||
//%if web // Web content template has an example route which is the plugin name
|
//%if web // Web content template has an example route which is the plugin name
|
||||||
|
|
||||||
webEntrypoint: "./web",
|
webEntrypoint: "./web",
|
||||||
|
|||||||
@@ -1,76 +1,64 @@
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { BaseInstancePlugin } from "@clusterio/host";
|
import type { InstancePluginContext } from "@clusterio/host";
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
import { PluginExampleEvent, PluginExampleRequest } from "./messages";
|
import { PluginExampleEvent, PluginExampleRequest } from "./messages.js";
|
||||||
//%endif
|
//%endif
|
||||||
//%if module
|
//%if module
|
||||||
|
|
||||||
type PuginExampleIPC = {
|
type PluginExampleIPC = {
|
||||||
tick: number,
|
tick: number,
|
||||||
player_name: string,
|
player_name: string,
|
||||||
};
|
};
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
export class InstancePlugin extends BaseInstancePlugin {
|
export default async function loadInstancePlugin(context: InstancePluginContext) {
|
||||||
//%if multi_context | module
|
const { instance, logger, plugin } = context;
|
||||||
async init() {
|
|
||||||
//%endif
|
|
||||||
//%if multi_context
|
|
||||||
this.instance.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
|
|
||||||
this.instance.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
|
|
||||||
//%endif
|
|
||||||
//%if module
|
|
||||||
this.instance.server.handle("__plugin_name__-plugin_example_ipc", this.handlePluginExampleIPC.bind(this));
|
|
||||||
//%endif
|
|
||||||
//%if multi_context | module
|
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
|
|
||||||
async onInstanceConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
|
|
||||||
this.logger.info(`instance::onInstanceConfigFieldChanged ${field}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async onStart() {
|
|
||||||
// Called once rcon becomes available
|
|
||||||
this.logger.info("instance::onStart");
|
|
||||||
}
|
|
||||||
|
|
||||||
async onStop() {
|
|
||||||
// Called during normal exits before rcon becomes unavailable
|
|
||||||
this.logger.info("instance::onStop");
|
|
||||||
}
|
|
||||||
|
|
||||||
onExit() {
|
|
||||||
// Called during all exits, including crashes and init failures, rcon is not available
|
|
||||||
this.logger.info("instance::onExit");
|
|
||||||
}
|
|
||||||
|
|
||||||
async onPlayerEvent(event: lib.PlayerEvent) {
|
|
||||||
this.logger.info(`onPlayerEvent::onPlayerEvent ${JSON.stringify(event)}`);
|
|
||||||
//%if module
|
|
||||||
if (this.instance.status === "running") {
|
|
||||||
await this.sendRcon("/sc __plugin_name__.foo()");
|
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
}
|
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
|
|
||||||
async handlePluginExampleEvent(event: PluginExampleEvent) {
|
instance.handle(PluginExampleEvent, async (event: PluginExampleEvent) => {
|
||||||
this.logger.info(JSON.stringify(event));
|
logger.info(JSON.stringify(event));
|
||||||
}
|
});
|
||||||
|
|
||||||
async handlePluginExampleRequest(request: PluginExampleRequest) {
|
instance.handle(PluginExampleRequest, async (request: PluginExampleRequest) => {
|
||||||
this.logger.info(JSON.stringify(request));
|
logger.info(JSON.stringify(request));
|
||||||
return {
|
return {
|
||||||
myResponseString: request.myString,
|
myResponseString: request.myString,
|
||||||
myResponseNumbers: request.myNumberArray,
|
myResponseNumbers: request.myNumberArray,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
//%if module
|
//%if module
|
||||||
|
|
||||||
async handlePluginExampleIPC(event: PuginExampleIPC) {
|
instance.server.handle("__plugin_name__-plugin_example_ipc", async (event: PluginExampleIPC) => {
|
||||||
this.logger.info(JSON.stringify(event));
|
logger.info(JSON.stringify(event));
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
|
instance.hooks.instanceConfigFieldChanged.attach(plugin.name, async (field, curr, prev) => {
|
||||||
|
logger.info(`instance::instanceConfigFieldChanged ${field}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.hooks.start.attach(plugin.name, async () => {
|
||||||
|
// Called once rcon becomes available
|
||||||
|
logger.info("instance::start");
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.hooks.stop.attach(plugin.name, async () => {
|
||||||
|
// Called during normal exits before rcon becomes unavailable
|
||||||
|
logger.info("instance::stop");
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.hooks.exit.attach(plugin.name, () => {
|
||||||
|
// Called during all exits, including crashes and init failures, rcon is not available
|
||||||
|
logger.info("instance::exit");
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.hooks.playerEvent.attach(plugin.name, async (event: lib.PlayerEvent) => {
|
||||||
|
logger.info(`instance::playerEvent ${JSON.stringify(event)}`);
|
||||||
|
//%if module
|
||||||
|
if (instance.status === "running") {
|
||||||
|
await instance.sendRcon("/sc __plugin_name__.foo()", false, plugin.name);
|
||||||
|
}
|
||||||
|
//%endif
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
import * as lib from "@clusterio/lib";
|
import type { InstancePluginContext } from "@clusterio/host";
|
||||||
import { BaseInstancePlugin } from "@clusterio/host";
|
|
||||||
|
|
||||||
export class InstancePlugin extends BaseInstancePlugin {
|
// This entrypoint is empty because an instance entrypoint must be defined for a module to be injected
|
||||||
// This class is empty because an instance plugin must be defined for a module to be injected
|
// This requirement may change in the future to allow for standalone modules
|
||||||
// This requirement may change in the future to allow for standalone modules
|
export default async function loadInstancePlugin(context: InstancePluginContext) { }
|
||||||
}
|
|
||||||
@@ -9,5 +9,5 @@
|
|||||||
"noEmitOnError": true,
|
"noEmitOnError": true,
|
||||||
"outDir": "${configDir}/dist/browser",
|
"outDir": "${configDir}/dist/browser",
|
||||||
},
|
},
|
||||||
"include": [ "web/**/*.tsx", "web/**/*.ts", "messages.ts", "package.json" ],
|
"include": [ "web/**/*.tsx", "web/**/*.ts", "index.ts", "messages.ts", "package.json" ],
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,8 @@ import React, {
|
|||||||
// } from "antd";
|
// } from "antd";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
BaseWebPlugin, PageLayout, PageHeader, Control, ControlContext, notifyErrorHandler,
|
PageLayout, PageHeader, Control, ControlContext, notifyErrorHandler,
|
||||||
|
type WebPluginContext,
|
||||||
} from "@clusterio/web_ui";
|
} from "@clusterio/web_ui";
|
||||||
//%if multi_context // Messages requires multi context
|
//%if multi_context // Messages requires multi context
|
||||||
|
|
||||||
@@ -21,16 +22,26 @@ import {
|
|||||||
ExampleSubscribableUpdate, ExampleSubscribableValue,
|
ExampleSubscribableUpdate, ExampleSubscribableValue,
|
||||||
//%endif
|
//%endif
|
||||||
//%if multi_context // Messages requires multi context
|
//%if multi_context // Messages requires multi context
|
||||||
} from "../messages";
|
} from "../messages.js";
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
//%if controller // Subscribing requires web content and the controller
|
||||||
|
|
||||||
|
// Created when the plugin is loaded, before any page is rendered
|
||||||
|
let exampleSubscriber: lib.MapSubscriber<ExampleSubscribableUpdate>;
|
||||||
|
|
||||||
|
function useSubscribableData() {
|
||||||
|
const control = useContext(ControlContext);
|
||||||
|
const subscribe = useCallback((callback: () => void) => exampleSubscriber.subscribe(callback), [control]);
|
||||||
|
return useSyncExternalStore(subscribe, () => exampleSubscriber.getSnapshot());
|
||||||
|
}
|
||||||
|
//%endif
|
||||||
|
|
||||||
function MyTemplatePage() {
|
function MyTemplatePage() {
|
||||||
const control = useContext(ControlContext);
|
const control = useContext(ControlContext);
|
||||||
//%if controller // Subscribing requires web content and the controller
|
//%if controller // Subscribing requires web content and the controller
|
||||||
const plugin = control.plugins.get("__plugin_name__") as WebPlugin;
|
const [subscribableData, synced] = useSubscribableData();
|
||||||
const [subscribableData, synced] = plugin.useSubscribableData();
|
|
||||||
//%endif
|
//%endif
|
||||||
|
|
||||||
return <PageLayout nav={[{ name: "__plugin_name__" }]}>
|
return <PageLayout nav={[{ name: "__plugin_name__" }]}>
|
||||||
@@ -41,53 +52,39 @@ function MyTemplatePage() {
|
|||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WebPlugin extends BaseWebPlugin {
|
export default async function loadWebPlugin(context: WebPluginContext) {
|
||||||
|
const { control, logger, plugin } = context;
|
||||||
//%if controller // Subscribing requires web content and the controller
|
//%if controller // Subscribing requires web content and the controller
|
||||||
subscribableData = new lib.EventSubscriber(ExampleSubscribableUpdate, this.control);
|
exampleSubscriber = new lib.MapSubscriber(ExampleSubscribableUpdate, control);
|
||||||
|
|
||||||
//%endif
|
//%endif
|
||||||
async init() {
|
|
||||||
this.pages = [
|
control.hooks.pages.attach(plugin.name, () => [
|
||||||
{
|
{
|
||||||
path: "/__plugin_name__",
|
path: "/__plugin_name__",
|
||||||
sidebarName: "__plugin_name__",
|
sidebarName: "__plugin_name__",
|
||||||
// This permission is client side only, so it must match the permission string of a resource request to be secure
|
// This permission is client side only, so it must match the permission string of a resource request to be secure
|
||||||
// An undefined value means that the page will always be visible
|
// An undefined value means that the page will always be visible
|
||||||
//%if controller // Subscribing requires web content and the controller
|
//%if controller // Subscribing requires web content and the controller
|
||||||
permission: "__plugin_name__.example.permission.subscribe",
|
permission: "__plugin_name__.example.permission.subscribe",
|
||||||
//%endif
|
//%endif
|
||||||
//%if !controller
|
//%if !controller
|
||||||
permission: "__plugin_name__.example.permission.view",
|
permission: "__plugin_name__.page.view",
|
||||||
//%endif
|
//%endif
|
||||||
content: <MyTemplatePage/>,
|
content: <MyTemplatePage/>,
|
||||||
},
|
},
|
||||||
];
|
]);
|
||||||
//%if multi_context
|
//%if multi_context
|
||||||
|
|
||||||
this.control.handle(PluginExampleEvent, this.handlePluginExampleEvent.bind(this));
|
control.handle(PluginExampleEvent, async (event: PluginExampleEvent) => {
|
||||||
this.control.handle(PluginExampleRequest, this.handlePluginExampleRequest.bind(this));
|
logger.info(JSON.stringify(event));
|
||||||
//%endif
|
});
|
||||||
}
|
|
||||||
//%if controller // Subscribing requires web content and the controller
|
|
||||||
|
|
||||||
useSubscribableData() {
|
control.handle(PluginExampleRequest, async (request: PluginExampleRequest) => {
|
||||||
const control = useContext(ControlContext);
|
logger.info(JSON.stringify(request));
|
||||||
const subscribe = useCallback((callback: () => void) => this.subscribableData.subscribe(callback), [control]);
|
|
||||||
return useSyncExternalStore(subscribe, () => this.subscribableData.getSnapshot());
|
|
||||||
}
|
|
||||||
//%endif
|
|
||||||
//%if multi_context
|
|
||||||
|
|
||||||
async handlePluginExampleEvent(event: PluginExampleEvent) {
|
|
||||||
this.logger.info(JSON.stringify(event));
|
|
||||||
}
|
|
||||||
|
|
||||||
async handlePluginExampleRequest(request: PluginExampleRequest) {
|
|
||||||
this.logger.info(JSON.stringify(request));
|
|
||||||
return {
|
return {
|
||||||
myResponseString: request.myString,
|
myResponseString: request.myString,
|
||||||
myResponseNumbers: request.myNumberArray,
|
myResponseNumbers: request.myNumberArray,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
//%endif
|
//%endif
|
||||||
}
|
}
|
||||||
+24
-33
@@ -7,16 +7,16 @@
|
|||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import yargs, { type Argv } from "yargs";
|
import yargs, { type Argv } from "yargs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import { version } from "./package.json";
|
import packageConfig from "./package.json" with { type: "json" };
|
||||||
import { strict as assert } from "assert";
|
import { strict as assert } from "assert";
|
||||||
|
|
||||||
// Reduce startup time by lazy compiling schemas.
|
// Reduce startup time by lazy compiling schemas.
|
||||||
(global as any).lazySchemaCompilation = true;
|
import "./src/set_lazy_schema_compliation.js";
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import * as commands from "./src/commands";
|
import * as commands from "./src/commands.js";
|
||||||
import BaseCtlPlugin from "./src/BaseCtlPlugin";
|
import { BaseCtlPlugin, CtlHooks } from "./src/BaseCtlPlugin.js";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,7 +37,7 @@ class ControlConnector extends lib.WebSocketClientConnector {
|
|||||||
new lib.MessageRegisterControl(
|
new lib.MessageRegisterControl(
|
||||||
new lib.RegisterControlData(
|
new lib.RegisterControlData(
|
||||||
this._token,
|
this._token,
|
||||||
version,
|
packageConfig.version,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -53,19 +53,15 @@ class ControlConnector extends lib.WebSocketClientConnector {
|
|||||||
export class Control extends lib.Link {
|
export class Control extends lib.Link {
|
||||||
/** Control config used for connecting to the controller. */
|
/** Control config used for connecting to the controller. */
|
||||||
config: lib.ControlConfig;
|
config: lib.ControlConfig;
|
||||||
/** Mapping of plugin names to their instance for loaded plugins. */
|
|
||||||
plugins: Map<string, BaseCtlPlugin>;
|
|
||||||
/** Keep the control connection alive after the command completes. */
|
/** Keep the control connection alive after the command completes. */
|
||||||
keepOpen = false;
|
keepOpen = false;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
connector: ControlConnector,
|
connector: ControlConnector,
|
||||||
controlConfig: lib.ControlConfig,
|
controlConfig: lib.ControlConfig,
|
||||||
ctlPlugins: Map<string, BaseCtlPlugin>
|
|
||||||
) {
|
) {
|
||||||
super(connector);
|
super(connector);
|
||||||
this.config = controlConfig;
|
this.config = controlConfig;
|
||||||
this.plugins = ctlPlugins;
|
|
||||||
|
|
||||||
this.handle(lib.LogMessageEvent, this.handleLogMessageEvent.bind(this));
|
this.handle(lib.LogMessageEvent, this.handleLogMessageEvent.bind(this));
|
||||||
this.handle(lib.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
|
this.handle(lib.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
|
||||||
@@ -105,27 +101,23 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadPlugins(pluginList: Map<string, string>) {
|
async function loadPlugins(pluginList: Map<string, string>, hooks: CtlHooks) {
|
||||||
let pluginInfos = await lib.loadPluginInfos(pluginList);
|
let pluginInfos = await lib.loadPluginInfos(pluginList);
|
||||||
lib.registerPluginMessages(pluginInfos);
|
lib.registerPluginMessages(pluginInfos);
|
||||||
|
lib.registerPluginPermissions(pluginInfos);
|
||||||
lib.addPluginConfigFields(pluginInfos);
|
lib.addPluginConfigFields(pluginInfos);
|
||||||
|
|
||||||
let ctlPlugins = new Map<string, BaseCtlPlugin>();
|
const ctlPlugins = new Set<lib.PluginNodeEnvInfo>();
|
||||||
for (let pluginInfo of pluginInfos) {
|
for (let pluginInfo of pluginInfos) {
|
||||||
if (!pluginInfo.ctlEntrypoint) {
|
if (!pluginInfo.ctlEntrypoint) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let CtlPlugin = await lib.loadPluginClass(
|
const context = { hooks, logger, plugin: pluginInfo };
|
||||||
pluginInfo.name,
|
await lib.loadPlugin(pluginInfo, "ctl", context, "CtlPlugin", BaseCtlPlugin);
|
||||||
path.posix.join(pluginInfo.requirePath, pluginInfo.ctlEntrypoint),
|
ctlPlugins.add(pluginInfo);
|
||||||
"CtlPlugin",
|
|
||||||
BaseCtlPlugin,
|
|
||||||
);
|
|
||||||
let ctlPlugin = new CtlPlugin(pluginInfo, logger);
|
|
||||||
ctlPlugins.set(pluginInfo.name, ctlPlugin);
|
|
||||||
await ctlPlugin.init();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return ctlPlugins;
|
return ctlPlugins;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,14 +133,14 @@ interface CtlArguments {
|
|||||||
interface InitializeParameters {
|
interface InitializeParameters {
|
||||||
args: CtlArguments;
|
args: CtlArguments;
|
||||||
shouldRun: boolean;
|
shouldRun: boolean;
|
||||||
ctlPlugins?: Map<string, BaseCtlPlugin>;
|
ctlHooks: CtlHooks;
|
||||||
rootCommands?: lib.CommandTree;
|
rootCommands?: lib.CommandTree;
|
||||||
controlConfig?: lib.ControlConfig;
|
controlConfig?: lib.ControlConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function initialize(
|
export async function initialize(
|
||||||
argv: string | string[],
|
argv: string | string[],
|
||||||
ctlPlugins?: Map<string, BaseCtlPlugin>,
|
ctlHooks: CtlHooks = new CtlHooks(logger),
|
||||||
noLoggerTransport?: boolean,
|
noLoggerTransport?: boolean,
|
||||||
): Promise<InitializeParameters> {
|
): Promise<InitializeParameters> {
|
||||||
// Build a fresh, isolated yargs parser each time this function is called.
|
// Build a fresh, isolated yargs parser each time this function is called.
|
||||||
@@ -207,23 +199,23 @@ export async function initialize(
|
|||||||
lib.handleUnhandledErrors();
|
lib.handleUnhandledErrors();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Discover and load plugins. This check exists to allow tests to inject plugins.
|
// Discover and load plugins. ctlHooks.size check exists to allow tests to inject plugins.
|
||||||
if (!ctlPlugins || args._[0] === "plugin") {
|
if (ctlHooks.addCommands.size === 0 || args._[0] === "plugin") {
|
||||||
logger.verbose(`Loading available plugins from ${args.pluginList}`);
|
logger.verbose(`Loading available plugins from ${args.pluginList}`);
|
||||||
const pluginList = await lib.loadPluginList(args.pluginList);
|
const pluginList = await lib.loadPluginList(args.pluginList);
|
||||||
|
|
||||||
// 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 lib.handlePluginCommand(args, pluginList, args.pluginList);
|
await lib.handlePluginCommand(args, pluginList, args.pluginList);
|
||||||
return { args, shouldRun: false };
|
return { args, ctlHooks, shouldRun: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.verbose("Loading Plugins");
|
logger.verbose("Loading Plugins");
|
||||||
ctlPlugins = await loadPlugins(pluginList);
|
await loadPlugins(pluginList, ctlHooks);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add all commands including from plugins and reparse with help and strict checking.
|
// Add all commands including from plugins and reparse with help and strict checking.
|
||||||
const rootCommands = await commands.registerCommands(ctlPlugins, parser);
|
const rootCommands = await commands.registerCommands(ctlHooks, parser);
|
||||||
args = parser
|
args = parser
|
||||||
.help()
|
.help()
|
||||||
.strict()
|
.strict()
|
||||||
@@ -260,10 +252,10 @@ export async function initialize(
|
|||||||
// 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 lib.handleConfigCommand(args, controlConfig, controlConfigLock);
|
await lib.handleConfigCommand(args, controlConfig, controlConfigLock);
|
||||||
return { args, controlConfig, ctlPlugins, rootCommands, shouldRun: false };
|
return { args, controlConfig, ctlHooks, rootCommands, shouldRun: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { args, controlConfig, ctlPlugins, rootCommands, shouldRun: true };
|
return { args, controlConfig, ctlHooks, rootCommands, shouldRun: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function selectTargetCommand(args: CtlArguments, rootCommands: lib.CommandTree): lib.Command {
|
export function selectTargetCommand(args: CtlArguments, rootCommands: lib.CommandTree): lib.Command {
|
||||||
@@ -280,11 +272,10 @@ async function startControl() {
|
|||||||
const {
|
const {
|
||||||
args,
|
args,
|
||||||
shouldRun,
|
shouldRun,
|
||||||
ctlPlugins,
|
|
||||||
rootCommands,
|
rootCommands,
|
||||||
controlConfig,
|
controlConfig,
|
||||||
} = await initialize(process.argv.slice(2));
|
} = await initialize(process.argv.slice(2));
|
||||||
if (!shouldRun || !ctlPlugins || !rootCommands || !controlConfig) {
|
if (!shouldRun || !rootCommands || !controlConfig) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -300,7 +291,7 @@ async function startControl() {
|
|||||||
controlConfig.get("control.controller_token")!,
|
controlConfig.get("control.controller_token")!,
|
||||||
);
|
);
|
||||||
|
|
||||||
let control = new Control(controlConnector, controlConfig, ctlPlugins);
|
let control = new Control(controlConnector, controlConfig);
|
||||||
try {
|
try {
|
||||||
await controlConnector.connect();
|
await controlConnector.connect();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -377,6 +368,6 @@ ${err.stack}`
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
bootstrap();
|
bootstrap();
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { bootstrap } from "./ctl";
|
import { bootstrap } from "./ctl.js";
|
||||||
export * from "./ctl";
|
export * from "./ctl.js";
|
||||||
export { default as BaseCtlPlugin } from "./src/BaseCtlPlugin";
|
export { BaseCtlPlugin, CtlHooks, type CtlPluginContext } from "./src/BaseCtlPlugin.js";
|
||||||
|
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
bootstrap();
|
bootstrap();
|
||||||
}
|
}
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"type": "module",
|
||||||
"main": "dist/node/index.js",
|
"main": "dist/node/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "tsc --build",
|
"prepare": "tsc --build",
|
||||||
|
|||||||
@@ -1,38 +1,18 @@
|
|||||||
import type { CommandTree, Logger, PluginNodeEnvInfo } from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
|
export type CtlPluginContext = lib.PluginLoadContext<{
|
||||||
|
hooks: CtlHooks
|
||||||
|
}>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base class for clusterioctl plugins
|
* Collection of clusterioctl plugin hooks
|
||||||
*
|
|
||||||
* Ctl plugins are subclasses of this class which get instantiated by
|
|
||||||
* clusterioctl in order to extend its functionallity. To be discovered the
|
|
||||||
* class must be exported under the name `CtlPlugin` in the module
|
|
||||||
* specified by the `ctlEntrypoint` in the plugin's `plugin` export.
|
|
||||||
*/
|
*/
|
||||||
export default class BaseCtlPlugin {
|
export class CtlHooks extends lib.AsyncHookCollection {
|
||||||
/**
|
constructor(logger: lib.Logger) {
|
||||||
* Logger for this plugin
|
super(logger);
|
||||||
*
|
this.addCommands = this.newHook();
|
||||||
* Instance of winston Logger for sending log messages from this
|
|
||||||
* plugin. Supported methods and their corresponding log levels are
|
|
||||||
* `error`, `warn`, `audit`, `info` and `verbose`.
|
|
||||||
*/
|
|
||||||
logger: Logger;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
/**
|
|
||||||
* The plugin's own info module
|
|
||||||
*/
|
|
||||||
public info: PluginNodeEnvInfo,
|
|
||||||
logger: Logger,
|
|
||||||
) {
|
|
||||||
this.logger = logger.child({ plugin: this.info.name }) as unknown as Logger;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Called immediately after the class is instantiated
|
|
||||||
*/
|
|
||||||
async init() { }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called to add commands to the command line interface.
|
* Called to add commands to the command line interface.
|
||||||
*
|
*
|
||||||
@@ -43,5 +23,47 @@ export default class BaseCtlPlugin {
|
|||||||
* @param rootCommand -
|
* @param rootCommand -
|
||||||
* Root of the clusterioctl command tree.
|
* Root of the clusterioctl command tree.
|
||||||
*/
|
*/
|
||||||
async addCommands(rootCommand: CommandTree) { }
|
readonly addCommands: lib.AsyncHook<[rootCommand: lib.CommandTree]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||||
|
export interface BaseCtlPlugin {
|
||||||
|
addCommands?(rootCommand: lib.CommandTree): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for clusterioctl plugins
|
||||||
|
*
|
||||||
|
* Ctl plugins are subclasses of this class which get instantiated by
|
||||||
|
* clusterioctl in order to extend its functionallity. To be discovered the
|
||||||
|
* class must be exported under the name `CtlPlugin` in the module
|
||||||
|
* specified by the `ctlEntrypoint` in the plugin's `plugin` export.
|
||||||
|
*/
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||||
|
export class BaseCtlPlugin {
|
||||||
|
constructor(
|
||||||
|
/**
|
||||||
|
* The plugin's own info module
|
||||||
|
*/
|
||||||
|
public info: lib.PluginNodeEnvInfo,
|
||||||
|
public logger: lib.Logger,
|
||||||
|
private hooks: CtlHooks,
|
||||||
|
) {
|
||||||
|
if (this.addCommands) {
|
||||||
|
hooks.addCommands.attach(info.name, this.addCommands.bind(this));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromContext(context: CtlPluginContext) {
|
||||||
|
return new this(context.plugin, context.logger, context.hooks);
|
||||||
|
}
|
||||||
|
|
||||||
|
detachHooks() {
|
||||||
|
this.hooks.detachAll(this.info.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called immediately after the class is instantiated
|
||||||
|
*/
|
||||||
|
async init() {}
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,19 @@
|
|||||||
import type { Argv } from "yargs";
|
import type { Argv } from "yargs";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import type BaseCtlPlugin from "./BaseCtlPlugin";
|
import { controllerCommands } from "./commands_controller.js";
|
||||||
import { controllerCommands } from "./commands_controller";
|
import { hostCommands } from "./commands_host.js";
|
||||||
import { hostCommands } from "./commands_host";
|
import { instanceCommands } from "./commands_instance.js";
|
||||||
import { instanceCommands } from "./commands_instance";
|
import { modPackCommands } from "./commands_mod_pack.js";
|
||||||
import { modPackCommands } from "./commands_mod_pack";
|
import { modCommands } from "./commands_mod.js";
|
||||||
import { modCommands } from "./commands_mod";
|
import { permissionCommands } from "./commands_permission.js";
|
||||||
import { permissionCommands } from "./commands_permission";
|
import { roleCommands } from "./commands_role.js";
|
||||||
import { roleCommands } from "./commands_role";
|
import { userCommands } from "./commands_user.js";
|
||||||
import { userCommands } from "./commands_user";
|
import { logCommands } from "./commands_log.js";
|
||||||
import { logCommands } from "./commands_log";
|
import { debugCommands } from "./commands_debug.js";
|
||||||
import { debugCommands } from "./commands_debug";
|
import type { CtlHooks } from "./BaseCtlPlugin.js";
|
||||||
|
|
||||||
export async function registerCommands(ctlPlugins: Map<string, BaseCtlPlugin>, yargs: Argv) {
|
export async function registerCommands(ctlHooks: CtlHooks, yargs: Argv) {
|
||||||
const rootCommands = new lib.CommandTree({ name: "clusterioctl", description: "Manage cluster" });
|
const rootCommands = new lib.CommandTree({ name: "clusterioctl", description: "Manage cluster" });
|
||||||
rootCommands.add(controllerCommands);
|
rootCommands.add(controllerCommands);
|
||||||
rootCommands.add(hostCommands);
|
rootCommands.add(hostCommands);
|
||||||
@@ -26,9 +26,7 @@ export async function registerCommands(ctlPlugins: Map<string, BaseCtlPlugin>, y
|
|||||||
rootCommands.add(logCommands);
|
rootCommands.add(logCommands);
|
||||||
rootCommands.add(debugCommands);
|
rootCommands.add(debugCommands);
|
||||||
|
|
||||||
for (let controlPlugin of ctlPlugins.values()) {
|
await ctlHooks.addCommands.invoke(rootCommands);
|
||||||
await controlPlugin.addCommands(rootCommands);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let [name, command] of rootCommands.subCommands) {
|
for (let [name, command] of rootCommands.subCommands) {
|
||||||
if (name === command.name) {
|
if (name === command.name) {
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ import os from "os";
|
|||||||
import child_process from "child_process";
|
import child_process from "child_process";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
import { print } from "./command_ops";
|
import { print } from "./command_ops.js";
|
||||||
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops";
|
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
|
||||||
|
|
||||||
const asTable = asTableModule.configure({ delimiter: " | " });
|
const asTable = asTableModule.configure({ delimiter: " | " });
|
||||||
|
|
||||||
@@ -28,9 +28,14 @@ controllerCommands.add(new lib.Command({
|
|||||||
controllerCommands.add(new lib.Command({
|
controllerCommands.add(new lib.Command({
|
||||||
definition: ["update", "Update the controller", (yargs) => {
|
definition: ["update", "Update the controller", (yargs) => {
|
||||||
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
|
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
|
||||||
|
yargs.option("all", { alias: "a", type: "boolean", description: "Also update all plugins" });
|
||||||
}],
|
}],
|
||||||
handler: async function(args: { restart: boolean }, control: Control) {
|
handler: async function(args: { restart: boolean, all: boolean }, control: Control) {
|
||||||
await control.send(new lib.ControllerUpdateRequest());
|
if (args.all) {
|
||||||
|
await control.send(new lib.UpdateAllRequest());
|
||||||
|
} else {
|
||||||
|
await control.send(new lib.ControllerUpdateRequest());
|
||||||
|
}
|
||||||
if (args.restart) {
|
if (args.restart) {
|
||||||
await control.send(new lib.ControllerRestartRequest());
|
await control.send(new lib.ControllerRestartRequest());
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
|
|
||||||
export const debugCommands = new lib.CommandTree({ name: "debug", description: "Debugging utilities" });
|
export const debugCommands = new lib.CommandTree({ name: "debug", description: "Debugging utilities" });
|
||||||
debugCommands.add(new lib.Command({
|
debugCommands.add(new lib.Command({
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ import child_process from "child_process";
|
|||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { logger } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
import { print } from "./command_ops";
|
import { print } from "./command_ops.js";
|
||||||
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops";
|
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
|
||||||
|
|
||||||
const asTable = asTableModule.configure({ delimiter: " | " });
|
const asTable = asTableModule.configure({ delimiter: " | " });
|
||||||
|
|
||||||
@@ -87,7 +87,7 @@ hostCommands.add(new lib.Command({
|
|||||||
} else {
|
} else {
|
||||||
logger.info(`Writing ${args.output}`);
|
logger.info(`Writing ${args.output}`);
|
||||||
try {
|
try {
|
||||||
await fs.writeFile(args.output, content, { flag: "wx" });
|
await fs.writeFile(args.output, content, { flag: "wx", mode: 0o600 });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
if (err.code === "EEXIST") {
|
if (err.code === "EEXIST") {
|
||||||
throw new lib.CommandError(`File ${args.output} already exists`);
|
throw new lib.CommandError(`File ${args.output} already exists`);
|
||||||
@@ -101,10 +101,15 @@ hostCommands.add(new lib.Command({
|
|||||||
definition: ["update <host>", "Update the host", (yargs) => {
|
definition: ["update <host>", "Update the host", (yargs) => {
|
||||||
yargs.positional("host", { describe: "Host to update", type: "string" });
|
yargs.positional("host", { describe: "Host to update", type: "string" });
|
||||||
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
|
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
|
||||||
|
yargs.option("all", { alias: "a", type: "boolean", description: "Also update all plugins" });
|
||||||
}],
|
}],
|
||||||
handler: async function(args: { host: string, restart: boolean }, control: Control) {
|
handler: async function(args: { host: string, restart: boolean, all: boolean }, control: Control) {
|
||||||
let hostId = await lib.resolveHost(control, args.host);
|
let hostId = await lib.resolveHost(control, args.host);
|
||||||
await control.sendTo({ hostId }, new lib.HostUpdateRequest());
|
if (args.all) {
|
||||||
|
await control.sendTo({ hostId }, new lib.UpdateAllRequest());
|
||||||
|
} else {
|
||||||
|
await control.sendTo({ hostId }, new lib.HostUpdateRequest());
|
||||||
|
}
|
||||||
if (args.restart) {
|
if (args.restart) {
|
||||||
await control.sendTo({ hostId }, new lib.HostRestartRequest());
|
await control.sendTo({ hostId }, new lib.HostRestartRequest());
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ import util from "util";
|
|||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { logger } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
import { print } from "./command_ops";
|
import { print } from "./command_ops.js";
|
||||||
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops";
|
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
|
||||||
|
|
||||||
const asTable = asTableModule.configure({ delimiter: " | " });
|
const asTable = asTableModule.configure({ delimiter: " | " });
|
||||||
const finished = util.promisify(stream.finished);
|
const finished = util.promisify(stream.finished);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import winston from "winston";
|
|||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
|
|
||||||
export const logCommands = new lib.CommandTree({ name: "log", description: "Log inspection" });
|
export const logCommands = new lib.CommandTree({ name: "log", description: "Log inspection" });
|
||||||
logCommands.add(new lib.Command({
|
logCommands.add(new lib.Command({
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ import util from "util";
|
|||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { logger } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
import { print } from "./command_ops";
|
import { print } from "./command_ops.js";
|
||||||
|
|
||||||
const asTable = asTableModule.configure({ delimiter: " | " });
|
const asTable = asTableModule.configure({ delimiter: " | " });
|
||||||
const finished = util.promisify(stream.finished);
|
const finished = util.promisify(stream.finished);
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ import asTableModule from "as-table";
|
|||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { logger } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
import { print } from "./command_ops";
|
import { print } from "./command_ops.js";
|
||||||
|
|
||||||
const asTable = asTableModule.configure({ delimiter: " | " });
|
const asTable = asTableModule.configure({ delimiter: " | " });
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import asTableModule from "as-table";
|
import asTableModule from "as-table";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
import { print } from "./command_ops";
|
import { print } from "./command_ops.js";
|
||||||
|
|
||||||
const asTable = asTableModule.configure({ delimiter: " | " });
|
const asTable = asTableModule.configure({ delimiter: " | " });
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ import asTableModule from "as-table";
|
|||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { logger } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
import { print } from "./command_ops";
|
import { print } from "./command_ops.js";
|
||||||
|
|
||||||
const asTable = asTableModule.configure({ delimiter: " | " });
|
const asTable = asTableModule.configure({ delimiter: " | " });
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import asTableModule from "as-table";
|
|||||||
import path from "path";
|
import path from "path";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import type { Control } from "../ctl";
|
import type { Control } from "../ctl.js";
|
||||||
import { print } from "./command_ops";
|
import { print } from "./command_ops.js";
|
||||||
|
|
||||||
const asTable = asTableModule.configure({ delimiter: " | " });
|
const asTable = asTableModule.configure({ delimiter: " | " });
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
// This needs to be a separate file due to ECMAScript Modules evaluating code in
|
||||||
|
// imported modules before any code in the file that imports it.
|
||||||
|
(global as any).lazySchemaCompilation = true;
|
||||||
@@ -80,9 +80,10 @@ Shows the value for a single config entry.
|
|||||||
|
|
||||||
### `create-scenario <output>`
|
### `create-scenario <output>`
|
||||||
|
|
||||||
Create a scenario with the Clusterio modules patched into it and write it to the `output` directory.
|
Create a scenario with the Clusterio modules patched into it and write it to `output`.
|
||||||
This is the same patching that is applied to saves when an instance starts, see docs/how-it-works.md in the main repository.
|
This is the same patching that is applied to saves when an instance starts, see docs/how-it-works.md in the main repository.
|
||||||
The result can be used as a regular scenario outside of Clusterio by copying it to the `scenarios` folder of Factorio or into a mod.
|
The result can be used as a regular scenario outside of Clusterio by copying it to the `scenarios` folder of Factorio or into a mod.
|
||||||
|
The IPC between the game and the host is not available outside of Clusterio, so modules that depend on it will not work as expected.
|
||||||
|
|
||||||
By default the freeplay scenario from the latest Factorio install in `host.factorio_directory` is patched with the modules from all plugins that are enabled in the host config.
|
By default the freeplay scenario from the latest Factorio install in `host.factorio_directory` is patched with the modules from all plugins that are enabled in the host config.
|
||||||
|
|
||||||
@@ -94,6 +95,9 @@ By default the freeplay scenario from the latest Factorio install in `host.facto
|
|||||||
|
|
||||||
* `--plugins <name>...` Only patch in modules from the given plugins.
|
* `--plugins <name>...` Only patch in modules from the given plugins.
|
||||||
|
|
||||||
|
* `--zip` Write the scenario as a zip file instead of a directory.
|
||||||
|
Factorio does not load zipped scenarios, extract it before use.
|
||||||
|
|
||||||
For example, creating a scenario with only the inventory_sync module:
|
For example, creating a scenario with only the inventory_sync module:
|
||||||
|
|
||||||
npx clusteriohost create-scenario ~/.factorio/scenarios/inventory_sync --plugins inventory_sync
|
npx clusteriohost create-scenario ~/.factorio/scenarios/inventory_sync --plugins inventory_sync
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import yargs from "yargs";
|
import yargs from "yargs";
|
||||||
import { version } from "./package.json";
|
import packageConfig from "./package.json" with { type: "json" };
|
||||||
import winston from "winston";
|
import winston from "winston";
|
||||||
import "winston-daily-rotate-file";
|
import "winston-daily-rotate-file";
|
||||||
|
|
||||||
@@ -23,8 +23,8 @@ import "winston-daily-rotate-file";
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import Host from "./src/Host";
|
import Host from "./src/Host.js";
|
||||||
import { createScenarioCommand, handleCreateScenarioCommand } from "./src/create_scenario";
|
import { createScenarioCommand, handleCreateScenarioCommand } from "./src/create_scenario.js";
|
||||||
|
|
||||||
let host: Host | undefined;
|
let host: Host | undefined;
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ export class HostConnector extends lib.WebSocketClientConnector {
|
|||||||
new lib.MessageRegisterHost(
|
new lib.MessageRegisterHost(
|
||||||
new lib.RegisterHostData(
|
new lib.RegisterHostData(
|
||||||
this.hostConfig.get("host.controller_token"),
|
this.hostConfig.get("host.controller_token"),
|
||||||
version,
|
packageConfig.version,
|
||||||
this.hostConfig.get("host.id"),
|
this.hostConfig.get("host.id"),
|
||||||
plugins,
|
plugins,
|
||||||
)
|
)
|
||||||
@@ -83,7 +83,7 @@ export class HostConnector extends lib.WebSocketClientConnector {
|
|||||||
async function startHost() {
|
async function startHost() {
|
||||||
// argument parsing
|
// argument parsing
|
||||||
// eslint-disable-next-line node/no-sync
|
// eslint-disable-next-line node/no-sync
|
||||||
const args = yargs
|
const args = yargs(process.argv.slice(2))
|
||||||
.scriptName("host")
|
.scriptName("host")
|
||||||
.usage("$0 <command> [options]")
|
.usage("$0 <command> [options]")
|
||||||
.option("log-level", {
|
.option("log-level", {
|
||||||
@@ -151,7 +151,7 @@ async function startHost() {
|
|||||||
|
|
||||||
let command = args._[0];
|
let command = args._[0];
|
||||||
if (command === "run") {
|
if (command === "run") {
|
||||||
logger.info(`Starting Clusterio host ${version}`);
|
logger.info(`Starting Clusterio host ${packageConfig.version}`);
|
||||||
if (args.recovery) {
|
if (args.recovery) {
|
||||||
logger.warn("Host recovery mode enabled. Some features will be disabled.");
|
logger.warn("Host recovery mode enabled. Some features will be disabled.");
|
||||||
}
|
}
|
||||||
@@ -169,6 +169,7 @@ async function startHost() {
|
|||||||
logger.info("Loading Plugin info");
|
logger.info("Loading Plugin info");
|
||||||
let pluginInfos = await lib.loadPluginInfos(pluginList);
|
let pluginInfos = await lib.loadPluginInfos(pluginList);
|
||||||
lib.registerPluginMessages(pluginInfos);
|
lib.registerPluginMessages(pluginInfos);
|
||||||
|
lib.registerPluginPermissions(pluginInfos);
|
||||||
lib.addPluginConfigFields(pluginInfos);
|
lib.addPluginConfigFields(pluginInfos);
|
||||||
|
|
||||||
const hostConfigPath = args.config;
|
const hostConfigPath = args.config;
|
||||||
@@ -193,7 +194,7 @@ async function startHost() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
hostConfig.set("host.version", version); // Allows tracking last loaded version
|
hostConfig.set("host.version", packageConfig.version); // Allows tracking last loaded version
|
||||||
|
|
||||||
if (command === "config") {
|
if (command === "config") {
|
||||||
await lib.handleConfigCommand(args, hostConfig, hostConfigLock);
|
await lib.handleConfigCommand(args, hostConfig, hostConfigLock);
|
||||||
@@ -319,6 +320,6 @@ ${err.stack}`
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
bootstrap();
|
bootstrap();
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { bootstrap } from "./host";
|
import { bootstrap } from "./host.js";
|
||||||
export { default as BaseHostPlugin } from "./src/BaseHostPlugin";
|
export { BaseHostPlugin, HostHooks, type HostPluginContext } from "./src/BaseHostPlugin.js";
|
||||||
export { default as BaseInstancePlugin } from "./src/BaseInstancePlugin";
|
export { BaseInstancePlugin, InstanceHooks, type InstancePluginContext } from "./src/BaseInstancePlugin.js";
|
||||||
export { default as Host, HostRouter } from "./src/Host";
|
export { default as Host, HostRouter } from "./src/Host.js";
|
||||||
export { default as Instance } from "./src/Instance";
|
export { default as Instance } from "./src/Instance.js";
|
||||||
export { default as InstanceConnection } from "./src/InstanceConnection";
|
export { default as InstanceConnection } from "./src/InstanceConnection.js";
|
||||||
|
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
bootstrap();
|
bootstrap();
|
||||||
}
|
}
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"type": "module",
|
||||||
"main": "dist/node/index.js",
|
"main": "dist/node/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "tsc --build",
|
"prepare": "tsc --build",
|
||||||
|
|||||||
@@ -1,45 +1,24 @@
|
|||||||
import type {
|
import type Host from "./Host.js";
|
||||||
CollectorResult, Logger, ParsedFactorioOutput, PlayerEvent, PluginNodeEnvInfo,
|
|
||||||
} from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import type Host from "./Host";
|
|
||||||
|
export type HostPluginContext = lib.PluginLoadContext<{
|
||||||
|
host: Host;
|
||||||
|
}>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base class for host plugins
|
* Collection of host plugin hooks
|
||||||
*
|
|
||||||
* Host plugins are subclasses of this class which get instantiated by
|
|
||||||
* the host when it starts up with the plugin enabled in the config. To be
|
|
||||||
* discovered the class must be exported under the name `HostPlugin` in the
|
|
||||||
* module specified by the `hostEntrypoint` in the plugin's `plugin` export.
|
|
||||||
*/
|
*/
|
||||||
export default class BaseHostPlugin {
|
export class HostHooks extends lib.AsyncHookCollection {
|
||||||
/**
|
constructor(logger: lib.Logger) {
|
||||||
* Logger for this plugin
|
super(logger);
|
||||||
*
|
this.metrics = this.newHook();
|
||||||
* Instance of winston Logger for sending log messages from this
|
this.shutdown = this.newHook();
|
||||||
* plugin. Supported methods and their corresponding log levels are
|
this.hostConfigFieldChanged = this.newHook();
|
||||||
* `error`, `warn`, `audit`, `info` and `verbose`.
|
this.controllerConnectionEvent = this.newHook();
|
||||||
*/
|
this.prepareControllerDisconnect = this.newHook();
|
||||||
logger: Logger;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
/**
|
|
||||||
* The plugin's own info module
|
|
||||||
*/
|
|
||||||
public info: PluginNodeEnvInfo,
|
|
||||||
/**
|
|
||||||
* Host the plugin started for
|
|
||||||
*/
|
|
||||||
public host: Host,
|
|
||||||
logger: Logger,
|
|
||||||
) {
|
|
||||||
this.logger = logger.child({ plugin: this.info.name }) as unknown as Logger;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Called immediately after the class is instantiated
|
|
||||||
*/
|
|
||||||
async init() { }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the value of a host config field changed.
|
* Called when the value of a host config field changed.
|
||||||
*
|
*
|
||||||
@@ -50,7 +29,7 @@ export default class BaseHostPlugin {
|
|||||||
* @param curr - The current value of the field.
|
* @param curr - The current value of the field.
|
||||||
* @param prev - The previous value of the field.
|
* @param prev - The previous value of the field.
|
||||||
*/
|
*/
|
||||||
async onHostConfigFieldChanged(field: string, curr: unknown, prev: unknown) { }
|
readonly hostConfigFieldChanged: lib.AsyncHook<[field: string, curr: unknown, prev: unknown]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called before collecting Prometheus metrics
|
* Called before collecting Prometheus metrics
|
||||||
@@ -67,12 +46,12 @@ export default class BaseHostPlugin {
|
|||||||
*
|
*
|
||||||
* @returns an async iterator of prometheus metric results or undefined.
|
* @returns an async iterator of prometheus metric results or undefined.
|
||||||
*/
|
*/
|
||||||
async onMetrics(): Promise<void | AsyncIterable<CollectorResult>> { }
|
readonly metrics: lib.AsyncHook<[], AsyncIterable<lib.CollectorResult>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the host is shutting down
|
* Called when the host is shutting down
|
||||||
*/
|
*/
|
||||||
async onShutdown() { }
|
readonly shutdown: lib.AsyncHook<[]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when an event on the controller connection happens
|
* Called when an event on the controller connection happens
|
||||||
@@ -108,7 +87,7 @@ export default class BaseHostPlugin {
|
|||||||
*
|
*
|
||||||
* @param event - one of connect, drop, resume and close
|
* @param event - one of connect, drop, resume and close
|
||||||
*/
|
*/
|
||||||
onControllerConnectionEvent(event: "connect" | "drop" | "resume" | "close") { }
|
readonly controllerConnectionEvent: lib.AsyncHook<[event: "connect" | "drop" | "resume" | "close"]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the controller is preparing to disconnect from the host
|
* Called when the controller is preparing to disconnect from the host
|
||||||
@@ -123,5 +102,60 @@ export default class BaseHostPlugin {
|
|||||||
* @param connection -
|
* @param connection -
|
||||||
* The connection to the host preparing to disconnect.
|
* The connection to the host preparing to disconnect.
|
||||||
*/
|
*/
|
||||||
async onPrepareControllerDisconnect(connection: Host) { }
|
readonly prepareControllerDisconnect: lib.AsyncHook<[connection: Host]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||||
|
export interface BaseHostPlugin {
|
||||||
|
onHostConfigFieldChanged?(field: string, curr: unknown, prev: unknown): Promise<void>;
|
||||||
|
onMetrics?(): Promise<void | AsyncIterable<lib.CollectorResult>>;
|
||||||
|
onShutdown?(): Promise<void>;
|
||||||
|
onControllerConnectionEvent?(event: "connect" | "drop" | "resume" | "close"): void;
|
||||||
|
onPrepareControllerDisconnect?(connection: Host): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for host plugins
|
||||||
|
*
|
||||||
|
* Host plugins are subclasses of this class which get instantiated by
|
||||||
|
* the host when it starts up with the plugin enabled in the config. To be
|
||||||
|
* discovered the class must be exported under the name `HostPlugin` in the
|
||||||
|
* module specified by the `hostEntrypoint` in the plugin's `plugin` export.
|
||||||
|
*/
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||||
|
export class BaseHostPlugin {
|
||||||
|
constructor(
|
||||||
|
public info: lib.PluginNodeEnvInfo,
|
||||||
|
public host: Host,
|
||||||
|
public logger: lib.Logger,
|
||||||
|
) {
|
||||||
|
const attach = <Args extends unknown[], Return>(
|
||||||
|
hook: lib.AsyncHook<Args, Return>,
|
||||||
|
fn?: lib.HookHandler<Args, Return>,
|
||||||
|
) => {
|
||||||
|
if (fn) {
|
||||||
|
hook.attach(info.name, fn.bind(this));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
attach(host.hooks.hostConfigFieldChanged, this.onHostConfigFieldChanged);
|
||||||
|
attach(host.hooks.metrics, this.onMetrics);
|
||||||
|
attach(host.hooks.shutdown, this.onShutdown);
|
||||||
|
attach(host.hooks.controllerConnectionEvent, this.onControllerConnectionEvent);
|
||||||
|
attach(host.hooks.prepareControllerDisconnect, this.onPrepareControllerDisconnect);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromContext(context: HostPluginContext): BaseHostPlugin {
|
||||||
|
const plugin = new this(context.plugin, context.host, context.logger);
|
||||||
|
return plugin;
|
||||||
|
}
|
||||||
|
|
||||||
|
detachHooks() {
|
||||||
|
this.host.hooks.detachAll(this.info.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called immediately after the class is instantiated
|
||||||
|
*/
|
||||||
|
async init() {}
|
||||||
}
|
}
|
||||||
@@ -1,69 +1,30 @@
|
|||||||
import type {
|
import type Instance from "./Instance.js";
|
||||||
CollectorResult, Logger, ParsedFactorioOutput, PlayerEvent, PluginNodeEnvInfo,
|
import type Host from "./Host.js";
|
||||||
} from "@clusterio/lib";
|
|
||||||
import type Instance from "./Instance";
|
import * as lib from "@clusterio/lib";
|
||||||
import type Host from "./Host";
|
|
||||||
|
export type InstancePluginContext = lib.PluginLoadContext<{
|
||||||
|
host: Host;
|
||||||
|
instance: Instance;
|
||||||
|
}>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base class for instance plugins
|
* Collection of instance plugin hooks
|
||||||
*
|
|
||||||
* Instance plugins are subclasses of this class which get instantiated by
|
|
||||||
* the host when it brings up an instance with the plugin enabled in the
|
|
||||||
* config. To be discovered the class must be exported under the name
|
|
||||||
* `InstancePlugin` in the module specified by the `instanceEntrypoint` in
|
|
||||||
* the plugin's `plugin` export.
|
|
||||||
*
|
|
||||||
* Instances may be started and stopped many times, and many instances may
|
|
||||||
* be running at the same time, each of which will have their own instance
|
|
||||||
* of the InstancePlugin class.
|
|
||||||
*/
|
*/
|
||||||
export default class BaseInstancePlugin {
|
export class InstanceHooks extends lib.AsyncHookCollection {
|
||||||
/**
|
constructor(logger: lib.Logger) {
|
||||||
* Logger for this plugin
|
super(logger);
|
||||||
*
|
this.metrics = this.newHook();
|
||||||
* Instance of winston Logger for sending log messages from this
|
this.start = this.newHook();
|
||||||
* plugin. Supported methods and their corresponding log levels are
|
this.stop = this.newHook();
|
||||||
* `error`, `warn`, `audit`, `info` and `verbose`.
|
this.exit = this.newHook();
|
||||||
*/
|
this.output = this.newHook();
|
||||||
logger: Logger;
|
this.instanceConfigFieldChanged = this.newHook();
|
||||||
|
this.controllerConnectionEvent = this.newHook();
|
||||||
private _pendingRconMessages: {
|
this.prepareControllerDisconnect = this.newHook();
|
||||||
resolve: (result: string) => void,
|
this.playerEvent = this.newHook();
|
||||||
reject: (err: Error) => void,
|
|
||||||
message: string,
|
|
||||||
expectEmpty: boolean,
|
|
||||||
}[] = [];
|
|
||||||
|
|
||||||
private _sendingRconMessages = false;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
/**
|
|
||||||
* The plugin's own info module
|
|
||||||
*/
|
|
||||||
public info: PluginNodeEnvInfo,
|
|
||||||
/**
|
|
||||||
* Instance the plugin started for
|
|
||||||
*/
|
|
||||||
public instance: Instance,
|
|
||||||
/**
|
|
||||||
* Host running the instance
|
|
||||||
*
|
|
||||||
* With the exepction of accessing the host's config you should
|
|
||||||
* avoid ineracting with the host object directly.
|
|
||||||
*/
|
|
||||||
public host: Host,
|
|
||||||
) {
|
|
||||||
this.logger = instance.logger.child({ plugin: this.info.name }) as unknown as Logger;
|
|
||||||
|
|
||||||
this._pendingRconMessages = [];
|
|
||||||
this._sendingRconMessages = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Called immediately after the class is instantiated
|
|
||||||
*/
|
|
||||||
async init() { }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the value of a config field changed.
|
* Called when the value of a config field changed.
|
||||||
*
|
*
|
||||||
@@ -74,7 +35,7 @@ export default class BaseInstancePlugin {
|
|||||||
* @param curr - The current value of the field.
|
* @param curr - The current value of the field.
|
||||||
* @param prev - The previous value of the field.
|
* @param prev - The previous value of the field.
|
||||||
*/
|
*/
|
||||||
async onInstanceConfigFieldChanged(field: string, curr: unknown, prev: unknown) { }
|
readonly instanceConfigFieldChanged: lib.AsyncHook<[field: string, curr: unknown, prev: unknown]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called before collecting Prometheus metrics
|
* Called before collecting Prometheus metrics
|
||||||
@@ -91,12 +52,12 @@ export default class BaseInstancePlugin {
|
|||||||
*
|
*
|
||||||
* @returns an async iterator of prometheus metric results or undefined.
|
* @returns an async iterator of prometheus metric results or undefined.
|
||||||
*/
|
*/
|
||||||
async onMetrics(): Promise<void | AsyncIterable<CollectorResult>> { }
|
readonly metrics: lib.AsyncHook<[], AsyncIterable<lib.CollectorResult>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called after the Factorio server is started
|
* Called after the Factorio server is started
|
||||||
*/
|
*/
|
||||||
async onStart() { }
|
readonly start: lib.AsyncHook<[]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called before the Factorio server is stopped
|
* Called before the Factorio server is stopped
|
||||||
@@ -104,7 +65,7 @@ export default class BaseInstancePlugin {
|
|||||||
* This will not be called if for example the Factorio server crashes or
|
* This will not be called if for example the Factorio server crashes or
|
||||||
* is killed.
|
* is killed.
|
||||||
*/
|
*/
|
||||||
async onStop() { }
|
readonly stop: lib.AsyncHook<[]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the instance exits
|
* Called when the instance exits
|
||||||
@@ -113,7 +74,7 @@ export default class BaseInstancePlugin {
|
|||||||
* has been called if an error occurs during startup. Note that if
|
* has been called if an error occurs during startup. Note that if
|
||||||
* the plugin's init() throws this method will still be invoked.
|
* the plugin's init() throws this method will still be invoked.
|
||||||
*/
|
*/
|
||||||
onExit() { }
|
readonly exit: lib.AsyncHook<[]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the Factorio outputs a line
|
* Called when the Factorio outputs a line
|
||||||
@@ -125,7 +86,7 @@ export default class BaseInstancePlugin {
|
|||||||
* @param parsed - parsed server output.
|
* @param parsed - parsed server output.
|
||||||
* @param line - raw line of server output.
|
* @param line - raw line of server output.
|
||||||
*/
|
*/
|
||||||
async onOutput(parsed: ParsedFactorioOutput, line: string) { }
|
readonly output: lib.AsyncHook<[parsed: lib.ParsedFactorioOutput, line: string]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when an event on the controller connection happens
|
* Called when an event on the controller connection happens
|
||||||
@@ -161,7 +122,7 @@ export default class BaseInstancePlugin {
|
|||||||
*
|
*
|
||||||
* @param event - one of connect, drop, resume and close
|
* @param event - one of connect, drop, resume and close
|
||||||
*/
|
*/
|
||||||
onControllerConnectionEvent(event: "connect" | "drop" | "resume" | "close") { }
|
readonly controllerConnectionEvent: lib.AsyncHook<[event: "connect" | "drop" | "resume" | "close"]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when the controller is preparing to disconnect from the host
|
* Called when the controller is preparing to disconnect from the host
|
||||||
@@ -176,7 +137,7 @@ export default class BaseInstancePlugin {
|
|||||||
* @param connection -
|
* @param connection -
|
||||||
* The connection to the host preparing to disconnect.
|
* The connection to the host preparing to disconnect.
|
||||||
*/
|
*/
|
||||||
async onPrepareControllerDisconnect(connection: Instance) { }
|
readonly prepareControllerDisconnect: lib.AsyncHook<[connection: Instance]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called when a player joins or leaves the game
|
* Called when a player joins or leaves the game
|
||||||
@@ -185,7 +146,96 @@ export default class BaseInstancePlugin {
|
|||||||
*
|
*
|
||||||
* @param event - Information about the event.
|
* @param event - Information about the event.
|
||||||
*/
|
*/
|
||||||
async onPlayerEvent(event: PlayerEvent) { }
|
readonly playerEvent: lib.AsyncHook<[event: lib.PlayerEvent]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||||
|
export interface BaseInstancePlugin {
|
||||||
|
onInstanceConfigFieldChanged?(field: string, curr: unknown, prev: unknown): Promise<void>;
|
||||||
|
onMetrics?(): Promise<void | AsyncIterable<lib.CollectorResult>>;
|
||||||
|
onStart?(): Promise<void>;
|
||||||
|
onStop?(): Promise<void>;
|
||||||
|
onExit?(): void;
|
||||||
|
onOutput?(parsed: lib.ParsedFactorioOutput, line: string): Promise<void>;
|
||||||
|
onControllerConnectionEvent?(event: "connect" | "drop" | "resume" | "close"): void;
|
||||||
|
onPrepareControllerDisconnect?(connection: Instance): Promise<void>;
|
||||||
|
onPlayerEvent?(event: lib.PlayerEvent): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for instance plugins
|
||||||
|
*
|
||||||
|
* Instance plugins are subclasses of this class which get instantiated by
|
||||||
|
* the host when it brings up an instance with the plugin enabled in the
|
||||||
|
* config. To be discovered the class must be exported under the name
|
||||||
|
* `InstancePlugin` in the module specified by the `instanceEntrypoint` in
|
||||||
|
* the plugin's `plugin` export.
|
||||||
|
*
|
||||||
|
* Instances may be started and stopped many times, and many instances may
|
||||||
|
* be running at the same time, each of which will have their own instance
|
||||||
|
* of the InstancePlugin class.
|
||||||
|
*/
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||||
|
export class BaseInstancePlugin {
|
||||||
|
private _pendingRconMessages: {
|
||||||
|
resolve: (result: string) => void,
|
||||||
|
reject: (err: Error) => void,
|
||||||
|
message: string,
|
||||||
|
expectEmpty: boolean,
|
||||||
|
}[] = [];
|
||||||
|
|
||||||
|
private _sendingRconMessages = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
/**
|
||||||
|
* The plugin's own info module
|
||||||
|
*/
|
||||||
|
public info: lib.PluginNodeEnvInfo,
|
||||||
|
/**
|
||||||
|
* Instance the plugin started for
|
||||||
|
*/
|
||||||
|
public instance: Instance,
|
||||||
|
/**
|
||||||
|
* Host running the instance
|
||||||
|
*
|
||||||
|
* With the exepction of accessing the host's config you should
|
||||||
|
* avoid ineracting with the host object directly.
|
||||||
|
*/
|
||||||
|
public host: Host,
|
||||||
|
public logger: lib.Logger,
|
||||||
|
) {
|
||||||
|
const attach = <Args extends unknown[], Return>(
|
||||||
|
hook: lib.AsyncHook<Args, Return>,
|
||||||
|
fn?: lib.HookHandler<Args, Return>,
|
||||||
|
) => {
|
||||||
|
if (fn) {
|
||||||
|
hook.attach(info.name, fn.bind(this));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
attach(instance.hooks.instanceConfigFieldChanged, this.onInstanceConfigFieldChanged);
|
||||||
|
attach(instance.hooks.metrics, this.onMetrics);
|
||||||
|
attach(instance.hooks.start, this.onStart);
|
||||||
|
attach(instance.hooks.stop, this.onStop);
|
||||||
|
attach(instance.hooks.exit, this.onExit);
|
||||||
|
attach(instance.hooks.output, this.onOutput);
|
||||||
|
attach(instance.hooks.controllerConnectionEvent, this.onControllerConnectionEvent);
|
||||||
|
attach(instance.hooks.prepareControllerDisconnect, this.onPrepareControllerDisconnect);
|
||||||
|
attach(instance.hooks.playerEvent, this.onPlayerEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromContext(context: InstancePluginContext) {
|
||||||
|
return new this(context.plugin, context.instance, context.host, context.logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
detachHooks() {
|
||||||
|
this.instance.hooks.detachAll(this.info.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called immediately after the class is instantiated
|
||||||
|
*/
|
||||||
|
async init() {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send RCON message to instance
|
* Send RCON message to instance
|
||||||
|
|||||||
+39
-34
@@ -1,22 +1,20 @@
|
|||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import events from "events";
|
|
||||||
import pidusage from "pidusage";
|
import pidusage from "pidusage";
|
||||||
import semver from "semver";
|
import semver from "semver";
|
||||||
import setBlocking from "set-blocking";
|
import setBlocking from "set-blocking";
|
||||||
import stream from "stream";
|
import stream from "stream";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
import util from "util";
|
import util from "util";
|
||||||
|
|
||||||
// internal libraries
|
// internal libraries
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { logger } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import type { HostConnector } from "../host";
|
import type { HostConnector } from "../host.js";
|
||||||
import Instance from "./Instance";
|
import Instance from "./Instance.js";
|
||||||
import InstanceConnection from "./InstanceConnection";
|
import InstanceConnection from "./InstanceConnection.js";
|
||||||
import BaseHostPlugin from "./BaseHostPlugin";
|
import { BaseHostPlugin, HostHooks } from "./BaseHostPlugin.js";
|
||||||
|
|
||||||
const finished = util.promisify(stream.finished);
|
|
||||||
|
|
||||||
|
|
||||||
function checkRequestSaveName(name: string) {
|
function checkRequestSaveName(name: string) {
|
||||||
@@ -272,8 +270,10 @@ export default class Host extends lib.Link {
|
|||||||
pluginInfos: lib.PluginNodeEnvInfo[];
|
pluginInfos: lib.PluginNodeEnvInfo[];
|
||||||
config: lib.HostConfig;
|
config: lib.HostConfig;
|
||||||
|
|
||||||
/** Mapping of plugin name to loaded plugin */
|
/** Hooks which plugins can attach to */
|
||||||
plugins: Map<string, BaseHostPlugin> = new Map();
|
hooks = new HostHooks(logger);
|
||||||
|
/** Plugins which are currently loaded */
|
||||||
|
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
||||||
|
|
||||||
/** A map from instance id to instance connection. Only present when instance is running. */
|
/** A map from instance id to instance connection. Only present when instance is running. */
|
||||||
instanceConnections = new Map<number, InstanceConnection>();
|
instanceConnections = new Map<number, InstanceConnection>();
|
||||||
@@ -332,7 +332,7 @@ export default class Host extends lib.Link {
|
|||||||
if (name === "host.name" || name === "host.public_address") {
|
if (name === "host.name" || name === "host.public_address") {
|
||||||
this.sendHostUpdate();
|
this.sendHostUpdate();
|
||||||
}
|
}
|
||||||
lib.invokeHook(this.plugins, "onHostConfigFieldChanged", name, curr, prev);
|
this.hooks.hostConfigFieldChanged.invoke(name, curr, prev);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.connector.on("hello", data => {
|
this.connector.on("hello", data => {
|
||||||
@@ -384,9 +384,7 @@ export default class Host extends lib.Link {
|
|||||||
for (let instanceConnection of this.instanceConnections.values()) {
|
for (let instanceConnection of this.instanceConnections.values()) {
|
||||||
instanceConnection.send(message);
|
instanceConnection.send(message);
|
||||||
}
|
}
|
||||||
for (let plugin of this.plugins.values()) {
|
this.hooks.controllerConnectionEvent.invoke(event);
|
||||||
plugin.onControllerConnectionEvent(event);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -403,6 +401,7 @@ export default class Host extends lib.Link {
|
|||||||
this.handle(lib.PluginListRequest, this.handlePluginListRequest.bind(this));
|
this.handle(lib.PluginListRequest, this.handlePluginListRequest.bind(this));
|
||||||
this.handle(lib.PluginUpdateRequest, this.handlePluginUpdateRequest.bind(this));
|
this.handle(lib.PluginUpdateRequest, this.handlePluginUpdateRequest.bind(this));
|
||||||
this.handle(lib.PluginInstallRequest, this.handlePluginInstallRequest.bind(this));
|
this.handle(lib.PluginInstallRequest, this.handlePluginInstallRequest.bind(this));
|
||||||
|
this.handle(lib.UpdateAllRequest, this.handleUpdateAllRequest.bind(this));
|
||||||
|
|
||||||
this.snoopEvent(lib.InstanceAdminlistUpdateEvent, this.handleAdminlistUpdateEvent.bind(this));
|
this.snoopEvent(lib.InstanceAdminlistUpdateEvent, this.handleAdminlistUpdateEvent.bind(this));
|
||||||
this.snoopEvent(lib.InstanceBanlistUpdateEvent, this.handleBanlistUpdateEvent.bind(this));
|
this.snoopEvent(lib.InstanceBanlistUpdateEvent, this.handleBanlistUpdateEvent.bind(this));
|
||||||
@@ -423,6 +422,7 @@ export default class Host extends lib.Link {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async loadPlugins() {
|
async loadPlugins() {
|
||||||
|
const context = { logger, host: this };
|
||||||
for (let pluginInfo of this.pluginInfos) {
|
for (let pluginInfo of this.pluginInfos) {
|
||||||
if (
|
if (
|
||||||
!pluginInfo.hostEntrypoint && !pluginInfo.instanceEntrypoint
|
!pluginInfo.hostEntrypoint && !pluginInfo.instanceEntrypoint
|
||||||
@@ -436,20 +436,16 @@ export default class Host extends lib.Link {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let HostPluginClass = BaseHostPlugin;
|
|
||||||
try {
|
try {
|
||||||
if (pluginInfo.hostEntrypoint) {
|
await lib.loadPlugin(
|
||||||
HostPluginClass = await lib.loadPluginClass(
|
pluginInfo,
|
||||||
pluginInfo.name,
|
"host",
|
||||||
path.posix.join(pluginInfo.requirePath, pluginInfo.hostEntrypoint),
|
context,
|
||||||
"HostPlugin",
|
"HostPlugin",
|
||||||
BaseHostPlugin,
|
BaseHostPlugin,
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
let hostPlugin = new HostPluginClass(pluginInfo, this, logger);
|
this.loadedPlugins.add(pluginInfo);
|
||||||
await hostPlugin.init();
|
|
||||||
this.plugins.set(pluginInfo.name, hostPlugin);
|
|
||||||
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
if (err.code === "InstallationError") {
|
if (err.code === "InstallationError") {
|
||||||
@@ -859,7 +855,7 @@ export default class Host extends lib.Link {
|
|||||||
try {
|
try {
|
||||||
// First check the clusterio version
|
// First check the clusterio version
|
||||||
const runningVersion = this.config.get("host.version");
|
const runningVersion = this.config.get("host.version");
|
||||||
const packageJsonPath = require.resolve("@clusterio/host/package.json");
|
const packageJsonPath = fileURLToPath(import.meta.resolve("@clusterio/host/package.json"));
|
||||||
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
|
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
|
||||||
if (runningVersion !== packageJson.version) {
|
if (runningVersion !== packageJson.version) {
|
||||||
this.config.restartRequired = true;
|
this.config.restartRequired = true;
|
||||||
@@ -876,15 +872,14 @@ export default class Host extends lib.Link {
|
|||||||
}
|
}
|
||||||
|
|
||||||
packageName = pluginInfo.npmPackage ?? pluginInfo.name;
|
packageName = pluginInfo.npmPackage ?? pluginInfo.name;
|
||||||
const pluginPackageJsonPath = require.resolve(path.posix.join(pluginInfo.requirePath, "package.json"));
|
const pluginPackageJson = JSON.parse(await fs.readFile(pluginInfo.packagePath, "utf8"));
|
||||||
const pluginPackageJson = JSON.parse(await fs.readFile(pluginPackageJsonPath, "utf8"));
|
|
||||||
if (pluginInfo.version !== pluginPackageJson.version) {
|
if (pluginInfo.version !== pluginPackageJson.version) {
|
||||||
this.config.restartRequired = true;
|
this.config.restartRequired = true;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
logger.warn(`Failed to read package json for ${packageName}:\n${err.stack ?? err.message}`);
|
logger.warn(`Failed to read package.json for ${packageName}:\n${err.stack ?? err.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@@ -893,7 +888,7 @@ export default class Host extends lib.Link {
|
|||||||
async checkRestartDowngrade() {
|
async checkRestartDowngrade() {
|
||||||
try {
|
try {
|
||||||
const runningVersion = this.config.get("host.version");
|
const runningVersion = this.config.get("host.version");
|
||||||
const packageJsonPath = require.resolve("@clusterio/host/package.json");
|
const packageJsonPath = fileURLToPath(import.meta.resolve("@clusterio/host/package.json"));
|
||||||
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
|
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
|
||||||
const installedVersion = packageJson.version;
|
const installedVersion = packageJson.version;
|
||||||
|
|
||||||
@@ -922,7 +917,7 @@ export default class Host extends lib.Link {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let results = [];
|
let results = [];
|
||||||
let pluginResults = await lib.invokeHook(this.plugins, "onMetrics");
|
let pluginResults = await this.hooks.metrics.collect();
|
||||||
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);
|
||||||
@@ -1151,10 +1146,20 @@ export default class Host extends lib.Link {
|
|||||||
return await lib.handlePluginInstall(request.pluginPackage);
|
return await lib.handlePluginInstall(request.pluginPackage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async handleUpdateAllRequest(request: lib.UpdateAllRequest) {
|
||||||
|
if (!this.config.get("host.allow_remote_updates")) {
|
||||||
|
throw new lib.RequestError("Remote updates are disabled on this machine");
|
||||||
|
}
|
||||||
|
if (!this.config.get("host.allow_plugin_updates")) {
|
||||||
|
throw new lib.RequestError("Plugin updates are disabled on this machine");
|
||||||
|
}
|
||||||
|
return await lib.handleUpdateAll("@clusterio/host", this.pluginInfos);
|
||||||
|
}
|
||||||
|
|
||||||
async handlePluginListRequest(request: lib.PluginListRequest) {
|
async handlePluginListRequest(request: lib.PluginListRequest) {
|
||||||
return this.pluginInfos.map(pluginInfo => lib.PluginDetails.fromNodeEnvInfo(
|
return this.pluginInfos.map(pluginInfo => lib.PluginDetails.fromNodeEnvInfo(
|
||||||
pluginInfo,
|
pluginInfo,
|
||||||
this.plugins.has(pluginInfo.name),
|
this.loadedPlugins.has(pluginInfo),
|
||||||
this.config.get(`${pluginInfo.name}.load_plugin`),
|
this.config.get(`${pluginInfo.name}.load_plugin`),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -1215,7 +1220,7 @@ export default class Host extends lib.Link {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async prepareDisconnect() {
|
async prepareDisconnect() {
|
||||||
await lib.invokeHook(this.plugins, "onPrepareControllerDisconnect", this);
|
await this.hooks.prepareControllerDisconnect.invoke(this);
|
||||||
for (let instanceConnection of this.instanceConnections.values()) {
|
for (let instanceConnection of this.instanceConnections.values()) {
|
||||||
await instanceConnection.send(new lib.PrepareControllerDisconnectRequest());
|
await instanceConnection.send(new lib.PrepareControllerDisconnectRequest());
|
||||||
}
|
}
|
||||||
@@ -1232,7 +1237,7 @@ export default class Host extends lib.Link {
|
|||||||
}
|
}
|
||||||
this._shuttingDown = true;
|
this._shuttingDown = true;
|
||||||
|
|
||||||
await lib.invokeHook(this.plugins, "onShutdown");
|
await this.hooks.shutdown.invoke();
|
||||||
|
|
||||||
for (let instanceConnection of this.instanceConnections.values()) {
|
for (let instanceConnection of this.instanceConnections.values()) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ const execAsync = util.promisify(exec);
|
|||||||
// internal libraries
|
// internal libraries
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { FactorioServer } from "./server";
|
import { FactorioServer } from "./server.js";
|
||||||
import { loadModules, patch } from "./patch";
|
import { loadModules, patch } from "./patch.js";
|
||||||
import { exportData } from "./export";
|
import { exportData } from "./export.js";
|
||||||
import type Host from "./Host";
|
import type Host from "./Host.js";
|
||||||
import BaseInstancePlugin from "./BaseInstancePlugin";
|
import { BaseInstancePlugin, InstanceHooks } from "./BaseInstancePlugin.js";
|
||||||
|
|
||||||
const scriptCommands = [
|
const scriptCommands = [
|
||||||
"/cheat", "/editor",
|
"/cheat", "/editor",
|
||||||
@@ -140,7 +140,6 @@ export default class Instance extends lib.Link {
|
|||||||
* ID of this instance, equivalenet to `instance.config.get("instance.id")`.
|
* ID of this instance, equivalenet to `instance.config.get("instance.id")`.
|
||||||
*/
|
*/
|
||||||
readonly id: number;
|
readonly id: number;
|
||||||
plugins: Map<string, BaseInstancePlugin>;
|
|
||||||
config: lib.InstanceConfig;
|
config: lib.InstanceConfig;
|
||||||
logger: lib.Logger;
|
logger: lib.Logger;
|
||||||
server: FactorioServer;
|
server: FactorioServer;
|
||||||
@@ -156,6 +155,10 @@ export default class Instance extends lib.Link {
|
|||||||
* Players currently online on the instance.
|
* Players currently online on the instance.
|
||||||
*/
|
*/
|
||||||
playersOnline: Set<string> = new Set();
|
playersOnline: Set<string> = new Set();
|
||||||
|
/** Hooks which plugins can attach to */
|
||||||
|
hooks: InstanceHooks;
|
||||||
|
/** Plugins which are currently loaded */
|
||||||
|
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
||||||
|
|
||||||
|
|
||||||
_host: Host;
|
_host: Host;
|
||||||
@@ -179,7 +182,6 @@ export default class Instance extends lib.Link {
|
|||||||
this._host = host;
|
this._host = host;
|
||||||
this._dir = dir;
|
this._dir = dir;
|
||||||
|
|
||||||
this.plugins = new Map();
|
|
||||||
this.config = instanceConfig;
|
this.config = instanceConfig;
|
||||||
|
|
||||||
this.id = this.config.get("instance.id");
|
this.id = this.config.get("instance.id");
|
||||||
@@ -189,8 +191,10 @@ export default class Instance extends lib.Link {
|
|||||||
instance_name: this.name,
|
instance_name: this.name,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.hooks = new InstanceHooks(this.logger);
|
||||||
|
|
||||||
this._configFieldChanged = (field: string, curr: unknown, prev: unknown) => {
|
this._configFieldChanged = (field: string, curr: unknown, prev: unknown) => {
|
||||||
let hook = () => lib.invokeHook(this.plugins, "onInstanceConfigFieldChanged", field, curr, prev);
|
let hook = () => this.hooks.instanceConfigFieldChanged.invoke(field, curr, prev);
|
||||||
|
|
||||||
if (field === "factorio.shutdown_timeout") {
|
if (field === "factorio.shutdown_timeout") {
|
||||||
this.server.shutdownTimeoutMs = curr as number * 1000;
|
this.server.shutdownTimeoutMs = curr as number * 1000;
|
||||||
@@ -231,7 +235,7 @@ export default class Instance extends lib.Link {
|
|||||||
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 });
|
||||||
|
|
||||||
lib.invokeHook(this.plugins, "onOutput", parsed, line);
|
this.hooks.output.invoke(parsed, line);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.server.on("error", err => {
|
this.server.on("error", err => {
|
||||||
@@ -398,7 +402,7 @@ export default class Instance extends lib.Link {
|
|||||||
stats,
|
stats,
|
||||||
};
|
};
|
||||||
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("join", name, stats));
|
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("join", name, stats));
|
||||||
lib.invokeHook(this.plugins, "onPlayerEvent", event);
|
this.hooks.playerEvent.invoke(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
_recordPlayerLeave(name: string, reason: string) {
|
_recordPlayerLeave(name: string, reason: string) {
|
||||||
@@ -419,7 +423,7 @@ export default class Instance extends lib.Link {
|
|||||||
stats,
|
stats,
|
||||||
};
|
};
|
||||||
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("leave", name, stats, reason));
|
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("leave", name, stats, reason));
|
||||||
lib.invokeHook(this.plugins, "onPlayerEvent", event);
|
this.hooks.playerEvent.invoke(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceExtractPlayersRequest() {
|
async handleInstanceExtractPlayersRequest() {
|
||||||
@@ -450,7 +454,7 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
stats,
|
stats,
|
||||||
};
|
};
|
||||||
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("import", name, stats));
|
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("import", name, stats));
|
||||||
lib.invokeHook(this.plugins, "onPlayerEvent", event);
|
this.hooks.playerEvent.invoke(event);
|
||||||
count += 1;
|
count += 1;
|
||||||
}
|
}
|
||||||
this.logger.info(`Extracted data for ${count} player(s)`);
|
this.logger.info(`Extracted data for ${count} player(s)`);
|
||||||
@@ -588,9 +592,7 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Notify plugins of exit
|
// Notify plugins of exit
|
||||||
for (let pluginInstance of this.plugins.values()) {
|
this.hooks.exit.invoke();
|
||||||
pluginInstance.onExit();
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let player of this.playersOnline) {
|
for (let player of this.playersOnline) {
|
||||||
this._recordPlayerLeave(player, "server_quit");
|
this._recordPlayerLeave(player, "server_quit");
|
||||||
@@ -598,21 +600,6 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
this._saveStats().catch(err => this.logger.error(`Error saving stats:\n${err.stack}`));
|
this._saveStats().catch(err => this.logger.error(`Error saving stats:\n${err.stack}`));
|
||||||
}
|
}
|
||||||
|
|
||||||
async _loadPlugin(pluginInfo: lib.PluginNodeEnvInfo, host: Host) {
|
|
||||||
let pluginLoadStartedMs = Date.now();
|
|
||||||
let InstancePluginClass = await lib.loadPluginClass(
|
|
||||||
pluginInfo.name,
|
|
||||||
path.posix.join(pluginInfo.requirePath, pluginInfo.instanceEntrypoint!),
|
|
||||||
"InstancePlugin",
|
|
||||||
BaseInstancePlugin,
|
|
||||||
);
|
|
||||||
let instancePlugin = new InstancePluginClass(pluginInfo, this, host);
|
|
||||||
this.plugins.set(pluginInfo.name, instancePlugin);
|
|
||||||
await instancePlugin.init();
|
|
||||||
|
|
||||||
this.logger.info(`Loaded plugin ${pluginInfo.name} in ${Date.now() - pluginLoadStartedMs}ms`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async _loadStats() {
|
async _loadStats() {
|
||||||
let instanceStats;
|
let instanceStats;
|
||||||
try {
|
try {
|
||||||
@@ -667,6 +654,7 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
|
|
||||||
// load plugins
|
// load plugins
|
||||||
|
const plugins: Record<string, string> = {};
|
||||||
for (let pluginInfo of pluginInfos) {
|
for (let pluginInfo of pluginInfos) {
|
||||||
if (
|
if (
|
||||||
!pluginInfo.instanceEntrypoint
|
!pluginInfo.instanceEntrypoint
|
||||||
@@ -682,7 +670,18 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this._loadPlugin(pluginInfo, this._host);
|
let pluginLoadStartedMs = Date.now();
|
||||||
|
await lib.loadPlugin(
|
||||||
|
pluginInfo,
|
||||||
|
"instance",
|
||||||
|
{ logger: this.logger, host: this._host, instance: this },
|
||||||
|
"InstancePlugin",
|
||||||
|
BaseInstancePlugin,
|
||||||
|
);
|
||||||
|
|
||||||
|
this.loadedPlugins.add(pluginInfo);
|
||||||
|
plugins[pluginInfo.name] = pluginInfo.version;
|
||||||
|
this.logger.info(`Loaded plugin ${pluginInfo.name} in ${Date.now() - pluginLoadStartedMs}ms`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.notifyExit();
|
this.notifyExit();
|
||||||
await this.sendSaveListUpdate();
|
await this.sendSaveListUpdate();
|
||||||
@@ -690,10 +689,6 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let plugins: Record<string, string> = {};
|
|
||||||
for (let [name, plugin] of this.plugins) {
|
|
||||||
plugins[name] = plugin.info.version;
|
|
||||||
}
|
|
||||||
this.send(new lib.InstanceInitialisedEvent(plugins));
|
this.send(new lib.InstanceInitialisedEvent(plugins));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -796,6 +791,7 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
} else {
|
} else {
|
||||||
modPack = await this.sendTo("controller", new lib.ModPackGetRequest(modPackId));
|
modPack = await this.sendTo("controller", new lib.ModPackGetRequest(modPackId));
|
||||||
}
|
}
|
||||||
|
this.checkModPackVersion(modPack);
|
||||||
this.activeModPack = modPack;
|
this.activeModPack = modPack;
|
||||||
|
|
||||||
const mods = await this._host.fetchMods(modPack.mods.values(), modPack.factorioVersion);
|
const mods = await this._host.fetchMods(modPack.mods.values(), modPack.factorioVersion);
|
||||||
@@ -847,6 +843,25 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
await fs.writeFile(this.path("mods", "mod-settings.dat"), this.activeModPack.toModSettingsDat());
|
await fs.writeFile(this.path("mods", "mod-settings.dat"), this.activeModPack.toModSettingsDat());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check that the mod pack does not target a newer Factorio than the server
|
||||||
|
*
|
||||||
|
* The mod pack's Factorio version is written into mod-settings.dat and
|
||||||
|
* Factorio refuses to read it if it is newer than the game. It then
|
||||||
|
* loads default settings instead, which can corrupt the save.
|
||||||
|
*
|
||||||
|
* @throws {lib.RequestError} if the mod pack version is higher than the server version.
|
||||||
|
*/
|
||||||
|
checkModPackVersion(modPack: lib.ModPack) {
|
||||||
|
const serverVersion = this.server.version;
|
||||||
|
if (serverVersion && modPack.integerFactorioVersion > lib.integerFullVersion(serverVersion)) {
|
||||||
|
throw new lib.RequestError(
|
||||||
|
`Mod pack ${modPack.name} is for Factorio ${modPack.factorioVersion} ` +
|
||||||
|
`which is newer than the Factorio ${serverVersion} this instance runs`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prepare instance for starting
|
* Prepare instance for starting
|
||||||
*
|
*
|
||||||
@@ -951,7 +966,7 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
// Patch save with lua modules from plugins
|
// Patch save with lua modules from plugins
|
||||||
this.logger.verbose("Patching save");
|
this.logger.verbose("Patching save");
|
||||||
|
|
||||||
let modules = await loadModules([...this.plugins.values()].map(plugin => plugin.info));
|
let modules = await loadModules(this.loadedPlugins);
|
||||||
await patch(this.path("saves", saveName), [...modules.values()]);
|
await patch(this.path("saves", saveName), [...modules.values()]);
|
||||||
return saveName;
|
return saveName;
|
||||||
}
|
}
|
||||||
@@ -986,7 +1001,7 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
|
|
||||||
await this.sendSaveListUpdate();
|
await this.sendSaveListUpdate();
|
||||||
await lib.invokeHook(this.plugins, "onStart");
|
await this.hooks.start.invoke();
|
||||||
|
|
||||||
this.notifyStatus("running");
|
this.notifyStatus("running");
|
||||||
}
|
}
|
||||||
@@ -1011,7 +1026,7 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
await this.server.startScenario(scenario, seed, mapGenSettings, mapSettings);
|
await this.server.startScenario(scenario, seed, mapGenSettings, mapSettings);
|
||||||
this._watchServerLogActions();
|
this._watchServerLogActions();
|
||||||
|
|
||||||
await lib.invokeHook(this.plugins, "onStart");
|
await this.hooks.start.invoke();
|
||||||
|
|
||||||
this.notifyStatus("running");
|
this.notifyStatus("running");
|
||||||
}
|
}
|
||||||
@@ -1147,7 +1162,7 @@ end`.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 lib.invokeHook(this.plugins, "onStop");
|
await this.hooks.stop.invoke();
|
||||||
await this.server.stop();
|
await this.server.stop();
|
||||||
await this.sendSaveListUpdate();
|
await this.sendSaveListUpdate();
|
||||||
} else if (
|
} else if (
|
||||||
@@ -1166,17 +1181,17 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleControllerConnectionEvent(event: lib.ControllerConnectionEvent) {
|
async handleControllerConnectionEvent(event: lib.ControllerConnectionEvent) {
|
||||||
await lib.invokeHook(this.plugins, "onControllerConnectionEvent", event.event);
|
await this.hooks.controllerConnectionEvent.invoke(event.event);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handlePrepareControllerDisconnectRequest() {
|
async handlePrepareControllerDisconnectRequest() {
|
||||||
await lib.invokeHook(this.plugins, "onPrepareControllerDisconnect", this);
|
await this.hooks.prepareControllerDisconnect.invoke(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceMetricsRequest() {
|
async handleInstanceMetricsRequest() {
|
||||||
let results: ReturnType<typeof lib.serializeResult>[] = [];
|
let results: ReturnType<typeof lib.serializeResult>[] = [];
|
||||||
if (!["stopped", "stopping"].includes(this._status)) {
|
if (!["stopped", "stopping"].includes(this._status)) {
|
||||||
let pluginResults = await lib.invokeHook(this.plugins, "onMetrics");
|
let pluginResults = await this.hooks.metrics.collect();
|
||||||
for (let metricIterator of pluginResults) {
|
for (let metricIterator of pluginResults) {
|
||||||
for await (let metric of metricIterator) {
|
for await (let metric of metricIterator) {
|
||||||
results.push(lib.serializeResult(metric));
|
results.push(lib.serializeResult(metric));
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import type Host from "./Host";
|
import type Host from "./Host.js";
|
||||||
import type Instance from "./Instance";
|
import type Instance from "./Instance.js";
|
||||||
|
|
||||||
|
|
||||||
export default class InstanceConnection extends lib.Link {
|
export default class InstanceConnection extends lib.Link {
|
||||||
|
|||||||
@@ -7,24 +7,35 @@ import path from "path";
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { logger } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
|
|
||||||
import { loadModules, patch, SaveModule } from "./patch";
|
import { loadModules, patch, SaveModule } from "./patch.js";
|
||||||
import { findVersion } from "./server";
|
import { findVersion } from "./server.js";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a scenario patched with the given modules
|
* Create a scenario patched with the given modules
|
||||||
*
|
*
|
||||||
* Runs the save patching on the scenario at scenarioPath and writes the
|
* Runs the save patching on the scenario at scenarioPath and writes the
|
||||||
* result to the directory at outputPath. The scenario can be a directory,
|
* result to outputPath. The scenario can be a directory, a zipped
|
||||||
* a zipped scenario or a save.
|
* scenario or a save.
|
||||||
*
|
*
|
||||||
* @param scenarioPath - Path to the scenario to patch.
|
* @param scenarioPath - Path to the scenario to patch.
|
||||||
* @param outputPath - Directory to write the patched scenario to.
|
* @param outputPath - Path to write the patched scenario to.
|
||||||
* @param modules - Description of the modules to patch.
|
* @param modules - Description of the modules to patch.
|
||||||
|
* @param zip - Write a zip file instead of a directory.
|
||||||
*/
|
*/
|
||||||
export async function createScenario(scenarioPath: string, outputPath: string, modules: SaveModule[]) {
|
export async function createScenario(
|
||||||
if (await fs.access(outputPath).then(() => true, () => false)) {
|
scenarioPath: string,
|
||||||
|
outputPath: string,
|
||||||
|
modules: SaveModule[],
|
||||||
|
zip = false,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
await fs.stat(outputPath);
|
||||||
throw new Error(`${outputPath} already exists`);
|
throw new Error(`${outputPath} already exists`);
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err.code !== "ENOENT") {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-scenario-"));
|
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-scenario-"));
|
||||||
@@ -37,7 +48,12 @@ export async function createScenario(scenarioPath: string, outputPath: string, m
|
|||||||
}
|
}
|
||||||
|
|
||||||
await patch(tempPath, modules);
|
await patch(tempPath, modules);
|
||||||
await extractZip(tempPath, outputPath);
|
if (zip) {
|
||||||
|
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
||||||
|
await fs.copyFile(tempPath, outputPath);
|
||||||
|
} else {
|
||||||
|
await extractZip(tempPath, outputPath);
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
await fs.rm(tempDir, { recursive: true, force: true });
|
await fs.rm(tempDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
@@ -83,12 +99,18 @@ async function extractZip(zipPath: string, dirPath: string) {
|
|||||||
export function createScenarioCommand(yargs: any) {
|
export function createScenarioCommand(yargs: any) {
|
||||||
yargs
|
yargs
|
||||||
.positional("output", {
|
.positional("output", {
|
||||||
describe: "Directory to write the scenario to",
|
describe: "Path to write the scenario to",
|
||||||
type: "string",
|
type: "string",
|
||||||
})
|
})
|
||||||
|
.option("zip", {
|
||||||
|
type: "boolean", nargs: 0, default: false,
|
||||||
|
describe: "Write the scenario as a zip file instead of a directory",
|
||||||
|
})
|
||||||
.option("scenario", {
|
.option("scenario", {
|
||||||
nargs: 1,
|
nargs: 1,
|
||||||
describe: "Scenario directory, zipped scenario or save to patch, defaults to freeplay",
|
describe:
|
||||||
|
"Path to a scenario directory, zipped scenario or save to patch. " +
|
||||||
|
"Defaults to the freeplay scenario of the Factorio install in host.factorio_directory",
|
||||||
type: "string",
|
type: "string",
|
||||||
})
|
})
|
||||||
.option("factorio-version", {
|
.option("factorio-version", {
|
||||||
@@ -144,6 +166,6 @@ export async function handleCreateScenarioCommand(
|
|||||||
|
|
||||||
const modules = await loadModules(selected);
|
const modules = await loadModules(selected);
|
||||||
logger.info(`Patching ${scenarioPath} with modules ${[...modules.keys()].join(", ")}`);
|
logger.info(`Patching ${scenarioPath} with modules ${[...modules.keys()].join(", ")}`);
|
||||||
await createScenario(scenarioPath, args.output as string, [...modules.values()]);
|
await createScenario(scenarioPath, args.output as string, [...modules.values()], Boolean(args.zip));
|
||||||
logger.info(`Created scenario ${args.output}`);
|
logger.info(`Created scenario ${args.output}`);
|
||||||
}
|
}
|
||||||
@@ -5,9 +5,9 @@ import { Jimp, JimpMime, type JimpInstance } from "jimp";
|
|||||||
import JSZip from "jszip";
|
import JSZip from "jszip";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import * as libBuildMod from "@clusterio/lib/dist/node/build_mod";
|
import * as libBuildMod from "@clusterio/lib/dist/node/build_mod.js";
|
||||||
import type { FactorioServer } from "./server";
|
import type { FactorioServer } from "./server.js";
|
||||||
import { definesPrototypesFallback } from "./export_fallback";
|
import { definesPrototypesFallback } from "./export_fallback.js";
|
||||||
|
|
||||||
interface SimpleIconSpecification {
|
interface SimpleIconSpecification {
|
||||||
icons?: never;
|
icons?: never;
|
||||||
@@ -56,7 +56,7 @@ async function generateExportMod(server: FactorioServer) {
|
|||||||
clean: false,
|
clean: false,
|
||||||
build: true,
|
build: true,
|
||||||
pack: true,
|
pack: true,
|
||||||
sourceDir: path.join(__dirname, "..", "..", "..", "lua", "export"),
|
sourceDir: path.join(import.meta.dirname, "..", "..", "..", "lua", "export"),
|
||||||
outputDir: server.writePath("mods"),
|
outputDir: server.writePath("mods"),
|
||||||
bumpPatch: false,
|
bumpPatch: false,
|
||||||
factorioVersion: server.version?.replace(/\.\d+$/, ""),
|
factorioVersion: server.version?.replace(/\.\d+$/, ""),
|
||||||
|
|||||||
@@ -9,9 +9,6 @@ import { Type, Static } from "@sinclair/typebox";
|
|||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import BaseInstancePlugin from "./BaseInstancePlugin";
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Describes a module that can be patched into a save
|
* Describes a module that can be patched into a save
|
||||||
*/
|
*/
|
||||||
@@ -90,13 +87,8 @@ export class SaveModule {
|
|||||||
return module;
|
return module;
|
||||||
}
|
}
|
||||||
|
|
||||||
static async fromPlugin(plugin: BaseInstancePlugin) {
|
static async fromPluginInfo(pluginInfo: lib.PluginNodeEnvInfo) {
|
||||||
return SaveModule.fromPluginInfo(plugin.info);
|
let moduleDirectory = path.join(path.dirname(pluginInfo.packagePath), "module");
|
||||||
}
|
|
||||||
|
|
||||||
static async fromPluginInfo(info: lib.PluginNodeEnvInfo) {
|
|
||||||
let pluginPackagePath = require.resolve(path.posix.join(info.requirePath, "package.json"));
|
|
||||||
let moduleDirectory = path.join(path.dirname(pluginPackagePath), "module");
|
|
||||||
try {
|
try {
|
||||||
await fs.access(moduleDirectory);
|
await fs.access(moduleDirectory);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -107,17 +99,17 @@ export class SaveModule {
|
|||||||
let moduleJson;
|
let moduleJson;
|
||||||
try {
|
try {
|
||||||
moduleJson = {
|
moduleJson = {
|
||||||
name: info.name,
|
name: pluginInfo.name,
|
||||||
version: info.version,
|
version: pluginInfo.version,
|
||||||
dependencies: { "clusterio": "*" },
|
dependencies: { "clusterio": "*" },
|
||||||
...JSON.parse(await fs.readFile(moduleJsonPath, "utf8")),
|
...JSON.parse(await fs.readFile(moduleJsonPath, "utf8")),
|
||||||
};
|
};
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
throw new Error(`Loading module/module.json in plugin ${info.name} failed: ${err.message}`);
|
throw new Error(`Loading module/module.json in plugin ${pluginInfo.name} failed: ${err.message}`);
|
||||||
}
|
}
|
||||||
if (!lib.ModuleInfo.validate(moduleJson)) {
|
if (!lib.ModuleInfo.validate(moduleJson)) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`module/module.json in plugin ${info.name} failed validation:\n` +
|
`module/module.json in plugin ${pluginInfo.name} failed validation:\n` +
|
||||||
`${JSON.stringify(lib.ModuleInfo.validate.errors, null, "\t")}`
|
`${JSON.stringify(lib.ModuleInfo.validate.errors, null, "\t")}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -174,7 +166,7 @@ export async function loadModules(pluginInfos: Iterable<lib.PluginNodeEnvInfo>)
|
|||||||
|
|
||||||
// Find stand alone modules to load
|
// Find stand alone modules to load
|
||||||
// XXX for now only the included clusterio module is loaded
|
// XXX for now only the included clusterio module is loaded
|
||||||
let modulesDirectory = path.join(__dirname, "..", "..", "..", "modules");
|
let modulesDirectory = path.join(import.meta.dirname, "..", "..", "..", "modules");
|
||||||
for (let entry of await fs.readdir(modulesDirectory, { withFileTypes: true })) {
|
for (let entry of await fs.readdir(modulesDirectory, { withFileTypes: true })) {
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
if (modules.has(entry.name)) {
|
if (modules.has(entry.name)) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
export * from "./src/api";
|
export * from "./src/api";
|
||||||
|
export * from "./src/AsyncHook";
|
||||||
export * from "./src/config";
|
export * from "./src/config";
|
||||||
export * from "./src/data";
|
export * from "./src/data";
|
||||||
export * from "./src/errors";
|
export * from "./src/errors";
|
||||||
@@ -10,14 +11,14 @@ export * from "./src/link";
|
|||||||
export * from "./src/lua_tools";
|
export * from "./src/lua_tools";
|
||||||
export * from "./src/logging";
|
export * from "./src/logging";
|
||||||
export * from "./src/permissions";
|
export * from "./src/permissions";
|
||||||
export * from "./src/plugin";
|
export * from "./src/loadPlugin";
|
||||||
export * from "./src/schema";
|
export * from "./src/schema";
|
||||||
export * from "./src/subscriptions";
|
export * from "./src/subscriptions";
|
||||||
|
|
||||||
export { default as ExponentialBackoff } from "./src/ExponentialBackoff";
|
export { default as ExponentialBackoff } from "./src/ExponentialBackoff";
|
||||||
export { default as RateLimiter } from "./src/RateLimiter";
|
export { default as RateLimiter } from "./src/RateLimiter";
|
||||||
export { default as ValueCache } from "./src/ValueCache";
|
export { default as ValueCache } from "./src/ValueCache";
|
||||||
export { default as isDeepStrictEqual } from "./src/is_deep_strict_equal";
|
export { default as isDeepStrictEqual } from "#is_deep_strict_equal";
|
||||||
|
|
||||||
import { checkSingletonImport } from "./src/check_singleton_import";
|
import { checkSingletonImport } from "./src/check_singleton_import";
|
||||||
checkSingletonImport(import.meta.url);
|
checkSingletonImport(import.meta.url);
|
||||||
+10
-15
@@ -1,11 +1,10 @@
|
|||||||
/* eslint-disable no-console */
|
/* eslint-disable no-console */
|
||||||
"use strict";
|
import fs from "node:fs/promises";
|
||||||
const fs = require("node:fs/promises");
|
import JSZip from "jszip";
|
||||||
const JSZip = require("jszip");
|
import path from "node:path";
|
||||||
const path = require("path");
|
import stream from "node:stream";
|
||||||
const stream = require("stream");
|
import util from "node:util";
|
||||||
const util = require("util");
|
import yargs from "yargs";
|
||||||
const yargs = require("yargs");
|
|
||||||
|
|
||||||
const finished = util.promisify(stream.finished);
|
const finished = util.promisify(stream.finished);
|
||||||
|
|
||||||
@@ -79,7 +78,7 @@ async function buildMod(args, info, modName) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function build(args) {
|
export async function build(args) {
|
||||||
let info = JSON.parse(await fs.readFile(path.join(args.sourceDir, "info.json")));
|
let info = JSON.parse(await fs.readFile(path.join(args.sourceDir, "info.json")));
|
||||||
|
|
||||||
if (args.factorioVersion) {
|
if (args.factorioVersion) {
|
||||||
@@ -121,7 +120,7 @@ async function build(args) {
|
|||||||
|
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const args = yargs
|
const args = yargs(process.argv.slice(2))
|
||||||
.scriptName("build")
|
.scriptName("build")
|
||||||
.options({
|
.options({
|
||||||
"clean": { describe: "Remove previous builds", type: "boolean", default: false },
|
"clean": { describe: "Remove previous builds", type: "boolean", default: false },
|
||||||
@@ -144,16 +143,12 @@ async function main() {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
.strict()
|
.strict()
|
||||||
.argv
|
.parse()
|
||||||
;
|
;
|
||||||
|
|
||||||
await build(args);
|
await build(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (module === require.main) {
|
if (import.meta.main) {
|
||||||
main().catch(err => { console.log(err); });
|
main().catch(err => { console.log(err); });
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
build,
|
|
||||||
};
|
|
||||||
+41
-39
@@ -2,44 +2,46 @@
|
|||||||
* Shared library for Clusterio
|
* Shared library for Clusterio
|
||||||
* @module lib
|
* @module lib
|
||||||
*/
|
*/
|
||||||
export * from "./build_mod";
|
export * from "./build_mod.js";
|
||||||
export * from "./src/api";
|
export * from "./src/api.js";
|
||||||
export * from "./src/command";
|
export * from "./src/command.js";
|
||||||
export * from "./src/config";
|
export * from "./src/config/index.js";
|
||||||
export * from "./src/data";
|
export * from "./src/data/index.js";
|
||||||
export * from "./src/database";
|
export * from "./src/database.js";
|
||||||
export * from "./src/errors";
|
export * from "./src/errors.js";
|
||||||
export * from "./src/export";
|
export * from "./src/export.js";
|
||||||
export * from "./src/external";
|
export * from "./src/external/index.js";
|
||||||
export * from "./src/factorio";
|
export * from "./src/factorio/index.js";
|
||||||
export * from "./src/file_ops";
|
export * from "./src/file_ops.js";
|
||||||
export * from "./src/hash";
|
export * from "./src/hash.js";
|
||||||
export * from "./src/helpers";
|
export * from "./src/helpers.js";
|
||||||
export * from "./src/ini";
|
export * from "./src/ini.js";
|
||||||
export * from "./src/link";
|
export * from "./src/link/index.js";
|
||||||
export * from "./src/logging";
|
export * from "./src/logging.js";
|
||||||
export * from "./src/logging_utils";
|
export * from "./src/logging_utils.js";
|
||||||
export * from "./src/lua_tools";
|
export * from "./src/lua_tools.js";
|
||||||
export * from "./src/permissions";
|
export * from "./src/permissions.js";
|
||||||
export * from "./src/plugin";
|
export * from "./src/plugin.js";
|
||||||
export * from "./src/plugin_loader";
|
export * from "./src/plugin_loader.js";
|
||||||
export * from "./src/prometheus";
|
export * from "./src/loadPlugin.js";
|
||||||
export * from "./src/schema";
|
export * from "./src/prometheus.js";
|
||||||
export * from "./src/shared_commands";
|
export * from "./src/schema.js";
|
||||||
export * from "./src/stream";
|
export * from "./src/shared_commands.js";
|
||||||
export * from "./src/system_collectors";
|
export * from "./src/stream.js";
|
||||||
export * from "./src/zip_ops";
|
export * from "./src/system_collectors.js";
|
||||||
export * from "./src/subscriptions";
|
export * from "./src/zip_ops.js";
|
||||||
export * from "./src/datastore";
|
export * from "./src/subscriptions.js";
|
||||||
export * from "./src/load_plugin_list";
|
export * from "./src/datastore.js";
|
||||||
export * from "./src/rce_ops";
|
export * from "./src/load_plugin_list.js";
|
||||||
export * from "./src/LockFile";
|
export * from "./src/rce_ops.js";
|
||||||
|
export * from "./src/LockFile.js";
|
||||||
|
export * from "./src/AsyncHook.js";
|
||||||
|
|
||||||
export { default as ExponentialBackoff } from "./src/ExponentialBackoff";
|
export { default as ExponentialBackoff } from "./src/ExponentialBackoff.js";
|
||||||
export { default as ModStore } from "./src/ModStore";
|
export { default as ModStore } from "./src/ModStore.js";
|
||||||
export { default as RateLimiter } from "./src/RateLimiter";
|
export { default as RateLimiter } from "./src/RateLimiter.js";
|
||||||
export { default as ValueCache } from "./src/ValueCache";
|
export { default as ValueCache } from "./src/ValueCache.js";
|
||||||
export { default as isDeepStrictEqual } from "./src/is_deep_strict_equal";
|
export { default as isDeepStrictEqual } from "#is_deep_strict_equal";
|
||||||
|
|
||||||
import { checkSingletonImport } from "./src/check_singleton_import";
|
import { checkSingletonImport } from "./src/check_singleton_import.js";
|
||||||
checkSingletonImport(__filename);
|
checkSingletonImport(import.meta.filename);
|
||||||
@@ -22,6 +22,17 @@
|
|||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"type": "module",
|
||||||
|
"imports": {
|
||||||
|
"#WebSocket": {
|
||||||
|
"node": "./src/link/WebSocket.node.ts",
|
||||||
|
"import": "./src/link/WebSocket.browser.ts"
|
||||||
|
},
|
||||||
|
"#is_deep_strict_equal": {
|
||||||
|
"node": "./src/is_deep_strict_equal.node.ts",
|
||||||
|
"import": "./src/is_deep_strict_equal.browser.ts"
|
||||||
|
}
|
||||||
|
},
|
||||||
"browser": "browser.ts",
|
"browser": "browser.ts",
|
||||||
"main": "dist/node/index.js",
|
"main": "dist/node/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
"use strict";
|
import fs from "node:fs";
|
||||||
const fs = require("node:fs");
|
import path from "node:path";
|
||||||
const path = require("path");
|
import Ajv from "ajv";
|
||||||
const Ajv = require("ajv");
|
import standaloneCode from "ajv/dist/standalone/index.js";
|
||||||
const standaloneCode = require("ajv/dist/standalone").default;
|
|
||||||
|
|
||||||
/* eslint-disable node/no-sync */
|
/* eslint-disable node/no-sync */
|
||||||
|
|
||||||
// Provide an empty file for message_core to load
|
// Provide an empty file for message_core to load
|
||||||
fs.writeFileSync(path.join(__dirname, "../dist/node/src/data/message_validate.js"), "");
|
fs.writeFileSync(path.join(import.meta.dirname, "../dist/node/src/data/message_validate.js"), "export default {};");
|
||||||
|
|
||||||
const { Message } = require("../dist/node/src/data/messages_core");
|
const { Message } = await import("../dist/node/src/data/messages_core.js");
|
||||||
|
|
||||||
const ajv = new Ajv({
|
const ajv = new Ajv({
|
||||||
allowUnionTypes: true,
|
allowUnionTypes: true,
|
||||||
@@ -18,13 +17,14 @@ const ajv = new Ajv({
|
|||||||
verbose: true,
|
verbose: true,
|
||||||
code: {
|
code: {
|
||||||
source: true,
|
source: true,
|
||||||
|
esm: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const validate = ajv.compile(Message.jsonSchema);
|
const validate = ajv.compile(Message.jsonSchema);
|
||||||
let moduleCode = standaloneCode(ajv, validate);
|
let moduleCode = standaloneCode(ajv, validate);
|
||||||
function write(output) {
|
function write(output) {
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
path.join(__dirname, output),
|
path.join(import.meta.dirname, output),
|
||||||
`// generated by scripts/compile_validator.js\n// @ts-nocheck\n/* eslint-disable */\n${moduleCode}`
|
`// generated by scripts/compile_validator.js\n// @ts-nocheck\n/* eslint-disable */\n${moduleCode}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import { logger } from "./logging.js";
|
||||||
|
import * as libHelpers from "./helpers.js";
|
||||||
|
|
||||||
|
export type HookHandler<Args extends unknown[], Result = void> = (...args: Args) => Result | Promise<Result>;
|
||||||
|
|
||||||
|
export class AsyncHook<
|
||||||
|
Args extends unknown[],
|
||||||
|
Result = void,
|
||||||
|
> {
|
||||||
|
private static readonly _timeoutToken = Symbol("timeout");
|
||||||
|
private _handlers = new Map<string, HookHandler<Args, Result>>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private _logger = logger,
|
||||||
|
private _timeoutMs = 15_000,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
get size() {
|
||||||
|
return this._handlers.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
get attached() {
|
||||||
|
return this._handlers.keys();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stable event listener reference bound to this hook instance.
|
||||||
|
*
|
||||||
|
* This function is pre-bound and guaranteed to remain referentially stable
|
||||||
|
* for the lifetime of the hook instance. It can safely be passed directly
|
||||||
|
* into event emitters (e.g. EventEmitter.on / off) without losing context
|
||||||
|
* or requiring re-binding.
|
||||||
|
*
|
||||||
|
* Example:
|
||||||
|
* `eventEmitter.on("change", hook.listener);`
|
||||||
|
*/
|
||||||
|
readonly listener = this.invoke.bind(this);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attach a handler to this hook.
|
||||||
|
*
|
||||||
|
* An error is thrown if another handler with the same name is already attached.
|
||||||
|
*/
|
||||||
|
attach(
|
||||||
|
name: string,
|
||||||
|
handler: HookHandler<Args, Result>,
|
||||||
|
) {
|
||||||
|
if (this._handlers.has(name)) {
|
||||||
|
throw new Error(`Handler with name ${name} is already attached`);
|
||||||
|
}
|
||||||
|
this._handlers.set(name, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a previously attached handler.
|
||||||
|
*
|
||||||
|
* If no handler exists, then no action is performed.
|
||||||
|
*/
|
||||||
|
detach(name: string) {
|
||||||
|
this._handlers.delete(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove all attached handlers.
|
||||||
|
*/
|
||||||
|
clear() {
|
||||||
|
this._handlers.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async _invokeHandler(
|
||||||
|
name: string,
|
||||||
|
handler: HookHandler<Args, Result>,
|
||||||
|
args: Args,
|
||||||
|
): Promise<Result | undefined> {
|
||||||
|
try {
|
||||||
|
const result = await libHelpers.timeout<
|
||||||
|
Result | typeof AsyncHook._timeoutToken
|
||||||
|
>(
|
||||||
|
Promise.resolve(handler(...args)),
|
||||||
|
this._timeoutMs,
|
||||||
|
AsyncHook._timeoutToken,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result === AsyncHook._timeoutToken) {
|
||||||
|
throw new Error(`Hook ${name} timed out after ${this._timeoutMs}ms`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
|
||||||
|
} catch (err: any) {
|
||||||
|
this._logger.error(`Ignoring error in hook "${name}":\n${err?.stack ?? err}`);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invoke all handlers attached to this hook.
|
||||||
|
*
|
||||||
|
* Any return values are discarded.
|
||||||
|
*/
|
||||||
|
async invoke(...args: Args): Promise<void> {
|
||||||
|
await Promise.all(
|
||||||
|
[...this._handlers.entries()].map(
|
||||||
|
([name, handler]) => this._invokeHandler(name, handler, args)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invoke all handlers attached to this hook.
|
||||||
|
*
|
||||||
|
* Returns all successful results.
|
||||||
|
*/
|
||||||
|
async collect(...args: Args): Promise<Result[]> {
|
||||||
|
const results = await Promise.all(
|
||||||
|
[...this._handlers.entries()].map(
|
||||||
|
([name, handler]) => this._invokeHandler(name, handler, args)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
return results.filter(
|
||||||
|
(result): result is Awaited<Result> => result !== undefined
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invoke all handlers attached to this hook.
|
||||||
|
*
|
||||||
|
* Returns all successful results and their source.
|
||||||
|
*/
|
||||||
|
async collectEntries(...args: Args): Promise<[string, Result][]> {
|
||||||
|
const results = await Promise.all(
|
||||||
|
[...this._handlers.entries()].map(async ([name, handler]) => {
|
||||||
|
const result = await this._invokeHandler(name, handler, args);
|
||||||
|
return result !== undefined ? [name, result] as [string, Result] : undefined;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return results.filter(
|
||||||
|
(entry): entry is [string, Result] => entry !== undefined
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AsyncHookCollection {
|
||||||
|
private hooks: AsyncHook<any[], any>[] = [];
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private _logger = logger,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
protected newHook<
|
||||||
|
Args extends unknown[],
|
||||||
|
Result = void,
|
||||||
|
> (
|
||||||
|
_logger = this._logger
|
||||||
|
) {
|
||||||
|
const hook = new AsyncHook<Args, Result>(_logger);
|
||||||
|
this.hooks.push(hook);
|
||||||
|
return hook;
|
||||||
|
}
|
||||||
|
|
||||||
|
get size() {
|
||||||
|
const attached = new Set(this.hooks.flatMap(hook => [...hook.attached]));
|
||||||
|
return attached.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
get attached() {
|
||||||
|
const attached = new Set(this.hooks.flatMap(hook => [...hook.attached]));
|
||||||
|
return attached.values();
|
||||||
|
}
|
||||||
|
|
||||||
|
detachAll(name: string) {
|
||||||
|
for (const hook of this.hooks) {
|
||||||
|
hook.detach(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
clearAll() {
|
||||||
|
for (const hook of this.hooks) {
|
||||||
|
hook.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,10 +2,10 @@ import fs from "node:fs/promises";
|
|||||||
import path from "path";
|
import path from "path";
|
||||||
import events from "events";
|
import events from "events";
|
||||||
import { Static } from "@sinclair/typebox";
|
import { Static } from "@sinclair/typebox";
|
||||||
import { logger } from "./logging";
|
import { logger } from "./logging.js";
|
||||||
import { downloadFile, safeOutputFile } from "./file_ops";
|
import { downloadFile, safeOutputFile } from "./file_ops.js";
|
||||||
import { ModPortalReleaseSchema, ModPortalDetailsSchema, ModNameVersionPair } from "./data/messages_mod";
|
import { ModPortalReleaseSchema, ModPortalDetailsSchema, ModNameVersionPair } from "./data/messages_mod.js";
|
||||||
import { ModInfo, ModPack, MajorMinorVersion, ModVersionEquality, SourceVersion } from "./data";
|
import { ModInfo, ModPack, MajorMinorVersion, ModVersionEquality, SourceVersion } from "./data/index.js";
|
||||||
|
|
||||||
export interface ModStoreEvents {
|
export interface ModStoreEvents {
|
||||||
/** A stored mod was created, updated or deleted */
|
/** A stored mod was created, updated or deleted */
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ export type PluginWebApi = {
|
|||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
loaded: boolean;
|
loaded: boolean;
|
||||||
web: {
|
web: {
|
||||||
main: string;
|
/** Path to the web bundle, not present if the plugin has no web build. */
|
||||||
|
main?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { InstallationError } from "./errors";
|
import { InstallationError } from "./errors.js";
|
||||||
declare global {
|
declare global {
|
||||||
// eslint-disable-next-line vars-on-top
|
// eslint-disable-next-line vars-on-top
|
||||||
var _clusterioLibImportedFrom: string;
|
var _clusterioLibImportedFrom: string;
|
||||||
|
|||||||
+34
-72
@@ -6,9 +6,9 @@
|
|||||||
* @author Hornwitser
|
* @author Hornwitser
|
||||||
* @module lib/command
|
* @module lib/command
|
||||||
*/
|
*/
|
||||||
import * as libData from "./data";
|
import * as libData from "./data/index.js";
|
||||||
import * as libErrors from "./errors";
|
import * as libErrors from "./errors.js";
|
||||||
import type { Link } from "./link";
|
import type { Link } from "./link/index.js";
|
||||||
import type { Argv } from "yargs";
|
import type { Argv } from "yargs";
|
||||||
|
|
||||||
export type CommandHandler = (args: any, control: any) => Promise<void>;
|
export type CommandHandler = (args: any, control: any) => Promise<void>;
|
||||||
@@ -146,6 +146,22 @@ export class CommandTree {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a string with either an id or a name to the id of an entry
|
||||||
|
*
|
||||||
|
* An integer like string is treated as an id if an entry with that id
|
||||||
|
* exists, otherwise it is looked up as a name.
|
||||||
|
*/
|
||||||
|
function resolveId(entries: { id: number, name: string }[], idOrName: string) {
|
||||||
|
if (/^-?\d+$/.test(idOrName)) {
|
||||||
|
const id = parseInt(idOrName, 10);
|
||||||
|
if (entries.some(entry => entry.id === id)) {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries.find(entry => entry.name === idOrName)?.id;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve a string into a host ID
|
* Resolve a string into a host ID
|
||||||
*
|
*
|
||||||
@@ -157,23 +173,11 @@ export class CommandTree {
|
|||||||
* @returns host ID.
|
* @returns host ID.
|
||||||
*/
|
*/
|
||||||
export async function resolveHost(client: Link, hostName: string) {
|
export async function resolveHost(client: Link, hostName: string) {
|
||||||
let hostId: number | undefined;
|
const hosts = await client.sendTo("controller", new libData.HostListRequest());
|
||||||
if (/^-?\d+$/.test(hostName)) {
|
const hostId = resolveId(hosts, hostName);
|
||||||
hostId = parseInt(hostName, 10);
|
if (hostId === undefined) {
|
||||||
} else {
|
throw new libErrors.CommandError(`No host named ${hostName}`);
|
||||||
let hosts = await client.sendTo("controller", new libData.HostListRequest());
|
|
||||||
for (let host of hosts) {
|
|
||||||
if (host.name === hostName) {
|
|
||||||
hostId = host.id;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hostId === undefined) {
|
|
||||||
throw new libErrors.CommandError(`No host named ${hostName}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return hostId;
|
return hostId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,23 +192,11 @@ export async function resolveHost(client: Link, hostName: string) {
|
|||||||
* @returns instance ID.
|
* @returns instance ID.
|
||||||
*/
|
*/
|
||||||
export async function resolveInstance(client: Link, instanceName: string) {
|
export async function resolveInstance(client: Link, instanceName: string) {
|
||||||
let instanceId: number | undefined;
|
const instances = await client.sendTo("controller", new libData.InstanceDetailsListRequest());
|
||||||
if (/^-?\d+$/.test(instanceName)) {
|
const instanceId = resolveId(instances, instanceName);
|
||||||
instanceId = parseInt(instanceName, 10);
|
if (instanceId === undefined) {
|
||||||
} else {
|
throw new libErrors.CommandError(`No instance named ${instanceName}`);
|
||||||
let instances = await client.sendTo("controller", new libData.InstanceDetailsListRequest());
|
|
||||||
for (let instance of instances) {
|
|
||||||
if (instance.name === instanceName) {
|
|
||||||
instanceId = instance.id;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (instanceId === undefined) {
|
|
||||||
throw new libErrors.CommandError(`No instance named ${instanceName}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return instanceId;
|
return instanceId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,23 +212,11 @@ export async function resolveInstance(client: Link, instanceName: string) {
|
|||||||
* @returns mod pack ID.
|
* @returns mod pack ID.
|
||||||
*/
|
*/
|
||||||
export async function resolveModPack(client: Link, modPackName: string) {
|
export async function resolveModPack(client: Link, modPackName: string) {
|
||||||
let modPackId: number | undefined;
|
const modPacks = await client.sendTo("controller", new libData.ModPackListRequest());
|
||||||
if (/^-?\d+/.test(modPackName)) {
|
const modPackId = resolveId(modPacks, modPackName);
|
||||||
modPackId = parseInt(modPackName, 10);
|
if (modPackId === undefined) {
|
||||||
} else {
|
throw new libErrors.CommandError(`No mod pack named ${modPackName}`);
|
||||||
let modPacks = await client.sendTo("controller", new libData.ModPackListRequest());
|
|
||||||
for (let modPack of modPacks) {
|
|
||||||
if (modPack.name === modPackName) {
|
|
||||||
modPackId = modPack.id;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (modPackId === undefined) {
|
|
||||||
throw new libErrors.CommandError(`No mod pack named ${modPackName}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return modPackId;
|
return modPackId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,27 +231,9 @@ export async function resolveModPack(client: Link, modPackName: string) {
|
|||||||
* @returns Role info.
|
* @returns Role info.
|
||||||
*/
|
*/
|
||||||
export async function retrieveRole(client: Link, roleName: string) {
|
export async function retrieveRole(client: Link, roleName: string) {
|
||||||
let roles = await client.sendTo("controller", new libData.RoleListRequest());
|
const roles = await client.sendTo("controller", new libData.RoleListRequest());
|
||||||
|
const roleId = resolveId(roles, roleName);
|
||||||
let resolvedRole: libData.Role | undefined;
|
const resolvedRole = roles.find(role => role.id === roleId);
|
||||||
if (/^-?\d+$/.test(roleName)) {
|
|
||||||
let roleId = parseInt(roleName, 10);
|
|
||||||
for (let role of roles) {
|
|
||||||
if (role.id === roleId) {
|
|
||||||
resolvedRole = role;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
for (let role of roles) {
|
|
||||||
if (role.name === roleName) {
|
|
||||||
resolvedRole = role;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!resolvedRole) {
|
if (!resolvedRole) {
|
||||||
throw new libErrors.CommandError(`No role named ${roleName}`);
|
throw new libErrors.CommandError(`No role named ${roleName}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ import { Type, Static } from "@sinclair/typebox";
|
|||||||
import * as fs from "node:fs/promises";
|
import * as fs from "node:fs/promises";
|
||||||
import events from "events";
|
import events from "events";
|
||||||
|
|
||||||
import isDeepStrictEqual from "../is_deep_strict_equal";
|
import isDeepStrictEqual from "#is_deep_strict_equal";
|
||||||
import { basicType } from "../helpers";
|
import { basicType } from "../helpers.js";
|
||||||
import * as libSchema from "../schema";
|
import * as libSchema from "../schema.js";
|
||||||
import { StringEnum } from "../data/composites";
|
import { StringEnum } from "../data/composites.js";
|
||||||
import { safeOutputFile } from "../file_ops";
|
import { safeOutputFile } from "../file_ops.js";
|
||||||
import * as validators from "./validators";
|
import * as validators from "./validators.js";
|
||||||
import { RequestError } from "../errors";
|
import { RequestError } from "../errors.js";
|
||||||
|
|
||||||
const ConfigLocation = StringEnum(["controller", "host", "control"]);
|
const ConfigLocation = StringEnum(["controller", "host", "control"]);
|
||||||
export type ConfigLocation = Static<typeof ConfigLocation>;
|
export type ConfigLocation = Static<typeof ConfigLocation>;
|
||||||
@@ -468,7 +468,7 @@ export class Config<
|
|||||||
if (!this.filepath) {
|
if (!this.filepath) {
|
||||||
throw new Error("Cannot save config which has no filepath");
|
throw new Error("Cannot save config which has no filepath");
|
||||||
}
|
}
|
||||||
await safeOutputFile(this.filepath, JSON.stringify(this, null, "\t"));
|
await safeOutputFile(this.filepath, JSON.stringify(this, null, "\t"), { mode: 0o600 });
|
||||||
this.dirty = false;
|
this.dirty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// Core definitions for the configuration system
|
// Core definitions for the configuration system
|
||||||
import * as classes from "./classes";
|
import * as classes from "./classes.js";
|
||||||
import * as validators from "./validators";
|
import * as validators from "./validators.js";
|
||||||
import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin";
|
import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin.js";
|
||||||
import { Static } from "@sinclair/typebox";
|
import { Static } from "@sinclair/typebox";
|
||||||
import { isTargetVersion } from "../data/version";
|
import { isTargetVersion } from "../data/version.js";
|
||||||
|
|
||||||
type configFromJSON<T> = (...args: Parameters<typeof classes.Config.fromJSON>) => T;
|
type configFromJSON<T> = (...args: Parameters<typeof classes.Config.fromJSON>) => T;
|
||||||
type configFromFile<T> = (...args: Parameters<typeof classes.Config.fromFile>) => Promise<T>;
|
type configFromFile<T> = (...args: Parameters<typeof classes.Config.fromFile>) => Promise<T>;
|
||||||
|
|||||||
@@ -3,5 +3,5 @@
|
|||||||
* @author Hornwitser
|
* @author Hornwitser
|
||||||
* @module lib/config
|
* @module lib/config
|
||||||
*/
|
*/
|
||||||
export * from "./classes";
|
export * from "./classes.js";
|
||||||
export * from "./definitions";
|
export * from "./definitions.js";
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Static, Type } from "@sinclair/typebox";
|
import { Static, Type } from "@sinclair/typebox";
|
||||||
import { StringEnum } from "./composites";
|
import { StringEnum } from "./composites.js";
|
||||||
import { TargetVersion, TargetVersionSchema } from "./version";
|
import { TargetVersion, TargetVersionSchema } from "./version.js";
|
||||||
|
|
||||||
export const InstanceStatus = StringEnum([
|
export const InstanceStatus = StringEnum([
|
||||||
"unknown",
|
"unknown",
|
||||||
|
|||||||
@@ -2,16 +2,16 @@ import fs from "node:fs/promises";
|
|||||||
import JSZip from "jszip";
|
import JSZip from "jszip";
|
||||||
import { Type, Static } from "@sinclair/typebox";
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
|
|
||||||
import * as libHash from "../hash";
|
import * as libHash from "../hash.js";
|
||||||
import * as libSchema from "../schema";
|
import * as libSchema from "../schema.js";
|
||||||
import { findRoot } from "../zip_ops";
|
import { findRoot } from "../zip_ops.js";
|
||||||
import { ModRecord } from "./ModPack";
|
import { ModRecord } from "./ModPack.js";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
MajorMinorVersion, MajorMinorVersionSchema, normaliseMajorMinorVersion, integerMajorMinorVersion,
|
MajorMinorVersion, MajorMinorVersionSchema, normaliseMajorMinorVersion, integerMajorMinorVersion,
|
||||||
SourceVersion, SourceVersionSchema, isSourceVersion, normaliseSourceVersion, integerSourceVersion,
|
SourceVersion, SourceVersionSchema, isSourceVersion, normaliseSourceVersion, integerSourceVersion,
|
||||||
ModVersionEquality,
|
ModVersionEquality,
|
||||||
} from "./version";
|
} from "./version.js";
|
||||||
|
|
||||||
|
|
||||||
type ModDependencyType = "incompatible" | "optional" | "hidden" | "unordered" | "required" | "recommended";
|
type ModDependencyType = "incompatible" | "optional" | "hidden" | "unordered" | "required" | "recommended";
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
import zlib from "zlib";
|
import zlib from "zlib";
|
||||||
import { Type, Static } from "@sinclair/typebox";
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
|
|
||||||
import * as libSchema from "../schema";
|
import * as libSchema from "../schema.js";
|
||||||
import * as libLuaTools from "../lua_tools";
|
import * as libLuaTools from "../lua_tools.js";
|
||||||
|
|
||||||
import ExportManifest from "./ExportManifest";
|
import ExportManifest from "./ExportManifest.js";
|
||||||
import type { ExportSettings } from "../export";
|
import type { ExportSettings } from "../export.js";
|
||||||
import type { Logger } from "../logging";
|
import type { Logger } from "../logging.js";
|
||||||
|
|
||||||
import ModInfo, { ModDependencyUnsatisfiedReason } from "./ModInfo";
|
import ModInfo, { ModDependencyUnsatisfiedReason } from "./ModInfo.js";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
PartialVersion, PartialVersionSchema, integerPartialVersion,
|
PartialVersion, PartialVersionSchema, integerPartialVersion,
|
||||||
SourceVersion, SourceVersionSchema, normaliseFullVersion, integerSourceVersion,
|
SourceVersion, SourceVersionSchema, normaliseFullVersion, integerSourceVersion,
|
||||||
} from "./version";
|
} from "./version.js";
|
||||||
|
|
||||||
|
|
||||||
export const ModSettingColor = Type.Object({
|
export const ModSettingColor = Type.Object({
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Type, Static } from "@sinclair/typebox";
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
import { compile } from "../schema";
|
import { compile } from "../schema.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Information about a module stored in its module.json file
|
* Information about a module stored in its module.json file
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Static, Type } from "@sinclair/typebox";
|
import { Static, Type } from "@sinclair/typebox";
|
||||||
import { permissions as globalPermissions } from "../permissions";
|
import { permissions as globalPermissions } from "../permissions.js";
|
||||||
|
|
||||||
interface RoleCollection {
|
interface RoleCollection {
|
||||||
get(id: number): Role;
|
get(id: number): Role;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Static, Type } from "@sinclair/typebox";
|
import { Static, Type } from "@sinclair/typebox";
|
||||||
|
import type { PermissionName } from "../permissions.js";
|
||||||
import PlayerStats from "./PlayerStats";
|
import PlayerStats from "./PlayerStats.js";
|
||||||
|
|
||||||
/** Represents a user in the cluster */
|
/** Represents a user in the cluster */
|
||||||
export default class UserDetails {
|
export default class UserDetails {
|
||||||
@@ -164,5 +164,5 @@ export interface IUser extends UserDetails {
|
|||||||
* @throws {Error} If the given permission does not exist.
|
* @throws {Error} If the given permission does not exist.
|
||||||
* @throws {libErrors.PermissionError} if the user does noh have the given permission.
|
* @throws {libErrors.PermissionError} if the user does noh have the given permission.
|
||||||
*/
|
*/
|
||||||
checkPermission(permission: string): void
|
checkPermission(permission: PermissionName): void
|
||||||
}
|
}
|
||||||
@@ -3,26 +3,26 @@
|
|||||||
* @module lib/data
|
* @module lib/data
|
||||||
* @author Hornwitser
|
* @author Hornwitser
|
||||||
*/
|
*/
|
||||||
export { default as ExportManifest } from "./ExportManifest";
|
export { default as ExportManifest } from "./ExportManifest.js";
|
||||||
export { default as ModInfo, ModDependency } from "./ModInfo";
|
export { default as ModInfo, ModDependency } from "./ModInfo.js";
|
||||||
export { ModSettingColor, getInstalledModUpdates, applyModRecordAdvisories } from "./ModPack";
|
export { ModSettingColor, getInstalledModUpdates, applyModRecordAdvisories } from "./ModPack.js";
|
||||||
export type { ModSetting, ModRecord, ModRecordAdvisory } from "./ModPack";
|
export type { ModSetting, ModRecord, ModRecordAdvisory } from "./ModPack.js";
|
||||||
export { default as ModPack } from "./ModPack";
|
export { default as ModPack } from "./ModPack.js";
|
||||||
export { default as ModuleInfo } from "./ModuleInfo";
|
export { default as ModuleInfo } from "./ModuleInfo.js";
|
||||||
export { default as Permission } from "./Permission";
|
export { default as Permission } from "./Permission.js";
|
||||||
export { default as PlayerStats } from "./PlayerStats";
|
export { default as PlayerStats } from "./PlayerStats.js";
|
||||||
export { default as Role } from "./Role";
|
export { default as Role } from "./Role.js";
|
||||||
export { default as InstanceDetails, InstanceStatus } from "./InstanceDetails";
|
export { default as InstanceDetails, InstanceStatus } from "./InstanceDetails.js";
|
||||||
export { default as HostDetails } from "./HostDetails";
|
export { default as HostDetails } from "./HostDetails.js";
|
||||||
export { default as UserDetails } from "./UserDetails";
|
export { default as UserDetails } from "./UserDetails.js";
|
||||||
export type { IUser } from "./UserDetails";
|
export type { IUser } from "./UserDetails.js";
|
||||||
export * from "./composites";
|
export * from "./composites.js";
|
||||||
export * from "./messages_core";
|
export * from "./messages_core.js";
|
||||||
export * from "./messages_controller";
|
export * from "./messages_controller.js";
|
||||||
export * from "./messages_host";
|
export * from "./messages_host.js";
|
||||||
export * from "./messages_instance";
|
export * from "./messages_instance.js";
|
||||||
export * from "./messages_mod";
|
export * from "./messages_mod.js";
|
||||||
export * from "./messages_user";
|
export * from "./messages_user.js";
|
||||||
export * from "./messages_role";
|
export * from "./messages_role.js";
|
||||||
export * from "./messages_plugin";
|
export * from "./messages_plugin.js";
|
||||||
export * from "./version";
|
export * from "./version.js";
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
import type { ValidateFunction } from "ajv";
|
import type { ValidateFunction } from "ajv";
|
||||||
import type { Message } from "./messages_core";
|
import type { Message } from "./messages_core.js";
|
||||||
const message_validate: ValidateFunction<Message>;
|
const message_validate: ValidateFunction<Message>;
|
||||||
export default message_validate;
|
export default message_validate;
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Type, Static } from "@sinclair/typebox";
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
import { JsonString, StringEnum, StringKey, plainJson } from "./composites";
|
import { JsonString, StringEnum, StringKey, plainJson } from "./composites.js";
|
||||||
import { levels } from "../logging";
|
import { levels } from "../logging.js";
|
||||||
import { ControllerConfig, HostConfig } from "../config";
|
import { ControllerConfig, HostConfig } from "../config/index.js";
|
||||||
import { ExternalFactorioVersionSchema, LatestReleasesSchema } from "../external";
|
import { ExternalFactorioVersionSchema, LatestReleasesSchema } from "../external/index.js";
|
||||||
|
|
||||||
export class ControllerStopRequest {
|
export class ControllerStopRequest {
|
||||||
declare ["constructor"]: typeof ControllerStopRequest;
|
declare ["constructor"]: typeof ControllerStopRequest;
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
// Note: Run compile_validator script after making changes to this file.
|
// Note: Run compile_validator script after making changes to this file.
|
||||||
import { TSchema, Type, Static } from "@sinclair/typebox";
|
import { TSchema, Type, Static } from "@sinclair/typebox";
|
||||||
|
|
||||||
import messageValidate from "./message_validate"; // generated file
|
import messageValidate from "./message_validate.js"; // generated file
|
||||||
import { StringEnum } from "./composites";
|
import { StringEnum } from "./composites.js";
|
||||||
|
|
||||||
export type AddressType = "controller" | "host" | "instance" | "control" | "broadcast";
|
export type AddressType = "controller" | "host" | "instance" | "control" | "broadcast";
|
||||||
export type AddressShorthand =
|
export type AddressShorthand =
|
||||||
|
|||||||
Loaded 100 of 297 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user