mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-17 15:33:12 +09:00
Add typed hook system for plugins
Replace invokeHook and the per plugin on* methods with AsyncHook collections on the controller, host, instance, clusterioctl and web control objects. Plugin entrypoints export a default function that receives a load context and attaches handlers to the hooks it needs. Class exports still load through fromContext with a deprecation warning. The create templates and docs use the entrypoint function. This is clusterio/clusterio#921 recreated on top of master after the ESM migration and the PluginDeclaration permissions change. Closes #730 Co-Authored-By: Cooldude2606 <25043174+Cooldude2606@users.noreply.github.com> Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
8c03ac15ab
commit
7122cbccf8
64 files changed
+1878
-1184
No files matched your search
@@ -1,45 +1,24 @@
|
||||
import type {
|
||||
CollectorResult, Logger, ParsedFactorioOutput, PlayerEvent, PluginNodeEnvInfo,
|
||||
} from "@clusterio/lib";
|
||||
import type Host from "./Host.js";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
export type HostPluginContext = lib.PluginLoadContext<{
|
||||
host: Host;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Collection of host plugin hooks
|
||||
*/
|
||||
export default class BaseHostPlugin {
|
||||
/**
|
||||
* Logger for this plugin
|
||||
*
|
||||
* 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,
|
||||
/**
|
||||
* Host the plugin started for
|
||||
*/
|
||||
public host: Host,
|
||||
logger: Logger,
|
||||
) {
|
||||
this.logger = logger.child({ plugin: this.info.name }) as unknown as Logger;
|
||||
export class HostHooks extends lib.AsyncHookCollection {
|
||||
constructor(logger: lib.Logger) {
|
||||
super(logger);
|
||||
this.metrics = this.newHook();
|
||||
this.shutdown = this.newHook();
|
||||
this.hostConfigFieldChanged = this.newHook();
|
||||
this.controllerConnectionEvent = this.newHook();
|
||||
this.prepareControllerDisconnect = this.newHook();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called immediately after the class is instantiated
|
||||
*/
|
||||
async init() { }
|
||||
|
||||
/**
|
||||
* 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 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
|
||||
@@ -67,12 +46,12 @@ export default class BaseHostPlugin {
|
||||
*
|
||||
* @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
|
||||
*/
|
||||
async onShutdown() { }
|
||||
*/
|
||||
readonly shutdown: lib.AsyncHook<[]>;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
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
|
||||
@@ -123,5 +102,60 @@ export default class BaseHostPlugin {
|
||||
* @param connection -
|
||||
* 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 {
|
||||
CollectorResult, Logger, ParsedFactorioOutput, PlayerEvent, PluginNodeEnvInfo,
|
||||
} from "@clusterio/lib";
|
||||
import type Instance from "./Instance.js";
|
||||
import type Host from "./Host.js";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
export type InstancePluginContext = lib.PluginLoadContext<{
|
||||
host: Host;
|
||||
instance: Instance;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Collection of instance plugin hooks
|
||||
*/
|
||||
export default class BaseInstancePlugin {
|
||||
/**
|
||||
* Logger for this plugin
|
||||
*
|
||||
* 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;
|
||||
|
||||
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: 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;
|
||||
export class InstanceHooks extends lib.AsyncHookCollection {
|
||||
constructor(logger: lib.Logger) {
|
||||
super(logger);
|
||||
this.metrics = this.newHook();
|
||||
this.start = this.newHook();
|
||||
this.stop = this.newHook();
|
||||
this.exit = this.newHook();
|
||||
this.output = this.newHook();
|
||||
this.instanceConfigFieldChanged = this.newHook();
|
||||
this.controllerConnectionEvent = this.newHook();
|
||||
this.prepareControllerDisconnect = this.newHook();
|
||||
this.playerEvent = this.newHook();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called immediately after the class is instantiated
|
||||
*/
|
||||
async init() { }
|
||||
|
||||
/**
|
||||
* 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 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
|
||||
@@ -91,12 +52,12 @@ export default class BaseInstancePlugin {
|
||||
*
|
||||
* @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
|
||||
*/
|
||||
async onStart() { }
|
||||
readonly start: lib.AsyncHook<[]>;
|
||||
|
||||
/**
|
||||
* 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
|
||||
* is killed.
|
||||
*/
|
||||
async onStop() { }
|
||||
readonly stop: lib.AsyncHook<[]>;
|
||||
|
||||
/**
|
||||
* 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
|
||||
* the plugin's init() throws this method will still be invoked.
|
||||
*/
|
||||
onExit() { }
|
||||
readonly exit: lib.AsyncHook<[]>;
|
||||
|
||||
/**
|
||||
* Called when the Factorio outputs a line
|
||||
@@ -125,7 +86,7 @@ export default class BaseInstancePlugin {
|
||||
* @param parsed - parsed 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
|
||||
@@ -161,7 +122,7 @@ export default class BaseInstancePlugin {
|
||||
*
|
||||
* @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
|
||||
@@ -176,7 +137,7 @@ export default class BaseInstancePlugin {
|
||||
* @param connection -
|
||||
* 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
|
||||
@@ -185,7 +146,96 @@ export default class BaseInstancePlugin {
|
||||
*
|
||||
* @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
|
||||
|
||||
+20
-26
@@ -1,6 +1,5 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "path";
|
||||
import events from "events";
|
||||
import pidusage from "pidusage";
|
||||
import semver from "semver";
|
||||
import setBlocking from "set-blocking";
|
||||
@@ -15,9 +14,7 @@ import { logger } from "@clusterio/lib";
|
||||
import type { HostConnector } from "../host.js";
|
||||
import Instance from "./Instance.js";
|
||||
import InstanceConnection from "./InstanceConnection.js";
|
||||
import BaseHostPlugin from "./BaseHostPlugin.js";
|
||||
|
||||
const finished = util.promisify(stream.finished);
|
||||
import { BaseHostPlugin, HostHooks } from "./BaseHostPlugin.js";
|
||||
|
||||
|
||||
function checkRequestSaveName(name: string) {
|
||||
@@ -273,8 +270,10 @@ export default class Host extends lib.Link {
|
||||
pluginInfos: lib.PluginNodeEnvInfo[];
|
||||
config: lib.HostConfig;
|
||||
|
||||
/** Mapping of plugin name to loaded plugin */
|
||||
plugins: Map<string, BaseHostPlugin> = new Map();
|
||||
/** Hooks which plugins can attach to */
|
||||
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. */
|
||||
instanceConnections = new Map<number, InstanceConnection>();
|
||||
@@ -333,7 +332,7 @@ export default class Host extends lib.Link {
|
||||
if (name === "host.name" || name === "host.public_address") {
|
||||
this.sendHostUpdate();
|
||||
}
|
||||
lib.invokeHook(this.plugins, "onHostConfigFieldChanged", name, curr, prev);
|
||||
this.hooks.hostConfigFieldChanged.invoke(name, curr, prev);
|
||||
});
|
||||
|
||||
this.connector.on("hello", data => {
|
||||
@@ -385,9 +384,7 @@ export default class Host extends lib.Link {
|
||||
for (let instanceConnection of this.instanceConnections.values()) {
|
||||
instanceConnection.send(message);
|
||||
}
|
||||
for (let plugin of this.plugins.values()) {
|
||||
plugin.onControllerConnectionEvent(event);
|
||||
}
|
||||
this.hooks.controllerConnectionEvent.invoke(event);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -424,6 +421,7 @@ export default class Host extends lib.Link {
|
||||
}
|
||||
|
||||
async loadPlugins() {
|
||||
const context = { logger, host: this };
|
||||
for (let pluginInfo of this.pluginInfos) {
|
||||
if (
|
||||
!pluginInfo.hostEntrypoint && !pluginInfo.instanceEntrypoint
|
||||
@@ -437,20 +435,16 @@ export default class Host extends lib.Link {
|
||||
continue;
|
||||
}
|
||||
|
||||
let HostPluginClass = BaseHostPlugin;
|
||||
try {
|
||||
if (pluginInfo.hostEntrypoint) {
|
||||
HostPluginClass = await lib.loadPluginClass(
|
||||
pluginInfo.name,
|
||||
path.posix.join(pluginInfo.requirePath, pluginInfo.hostEntrypoint),
|
||||
"HostPlugin",
|
||||
BaseHostPlugin,
|
||||
);
|
||||
}
|
||||
await lib.loadPlugin(
|
||||
pluginInfo,
|
||||
"host",
|
||||
context,
|
||||
"HostPlugin",
|
||||
BaseHostPlugin,
|
||||
);
|
||||
|
||||
let hostPlugin = new HostPluginClass(pluginInfo, this, logger);
|
||||
await hostPlugin.init();
|
||||
this.plugins.set(pluginInfo.name, hostPlugin);
|
||||
this.loadedPlugins.add(pluginInfo);
|
||||
|
||||
} catch (err: any) {
|
||||
if (err.code === "InstallationError") {
|
||||
@@ -922,7 +916,7 @@ export default class Host extends lib.Link {
|
||||
}
|
||||
|
||||
let results = [];
|
||||
let pluginResults = await lib.invokeHook(this.plugins, "onMetrics");
|
||||
let pluginResults = await this.hooks.metrics.collect();
|
||||
for (let metricIterator of pluginResults) {
|
||||
for await (let metric of metricIterator) {
|
||||
results.push(metric);
|
||||
@@ -1154,7 +1148,7 @@ export default class Host extends lib.Link {
|
||||
async handlePluginListRequest(request: lib.PluginListRequest) {
|
||||
return this.pluginInfos.map(pluginInfo => lib.PluginDetails.fromNodeEnvInfo(
|
||||
pluginInfo,
|
||||
this.plugins.has(pluginInfo.name),
|
||||
this.loadedPlugins.has(pluginInfo),
|
||||
this.config.get(`${pluginInfo.name}.load_plugin`),
|
||||
));
|
||||
}
|
||||
@@ -1215,7 +1209,7 @@ export default class Host extends lib.Link {
|
||||
}
|
||||
|
||||
async prepareDisconnect() {
|
||||
await lib.invokeHook(this.plugins, "onPrepareControllerDisconnect", this);
|
||||
await this.hooks.prepareControllerDisconnect.invoke(this);
|
||||
for (let instanceConnection of this.instanceConnections.values()) {
|
||||
await instanceConnection.send(new lib.PrepareControllerDisconnectRequest());
|
||||
}
|
||||
@@ -1232,7 +1226,7 @@ export default class Host extends lib.Link {
|
||||
}
|
||||
this._shuttingDown = true;
|
||||
|
||||
await lib.invokeHook(this.plugins, "onShutdown");
|
||||
await this.hooks.shutdown.invoke();
|
||||
|
||||
for (let instanceConnection of this.instanceConnections.values()) {
|
||||
try {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { FactorioServer } from "./server.js";
|
||||
import { SaveModule, patch } from "./patch.js";
|
||||
import { exportData } from "./export.js";
|
||||
import type Host from "./Host.js";
|
||||
import BaseInstancePlugin from "./BaseInstancePlugin.js";
|
||||
import { BaseInstancePlugin, InstanceHooks } from "./BaseInstancePlugin.js";
|
||||
|
||||
const scriptCommands = [
|
||||
"/cheat", "/editor",
|
||||
@@ -140,7 +140,6 @@ export default class Instance extends lib.Link {
|
||||
* ID of this instance, equivalenet to `instance.config.get("instance.id")`.
|
||||
*/
|
||||
readonly id: number;
|
||||
plugins: Map<string, BaseInstancePlugin>;
|
||||
config: lib.InstanceConfig;
|
||||
logger: lib.Logger;
|
||||
server: FactorioServer;
|
||||
@@ -156,6 +155,10 @@ export default class Instance extends lib.Link {
|
||||
* Players currently online on the instance.
|
||||
*/
|
||||
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;
|
||||
@@ -179,7 +182,6 @@ export default class Instance extends lib.Link {
|
||||
this._host = host;
|
||||
this._dir = dir;
|
||||
|
||||
this.plugins = new Map();
|
||||
this.config = instanceConfig;
|
||||
|
||||
this.id = this.config.get("instance.id");
|
||||
@@ -189,8 +191,10 @@ export default class Instance extends lib.Link {
|
||||
instance_name: this.name,
|
||||
});
|
||||
|
||||
this.hooks = new InstanceHooks(this.logger);
|
||||
|
||||
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") {
|
||||
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.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 => {
|
||||
@@ -398,7 +402,7 @@ export default class Instance extends lib.Link {
|
||||
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) {
|
||||
@@ -419,7 +423,7 @@ export default class Instance extends lib.Link {
|
||||
stats,
|
||||
};
|
||||
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("leave", name, stats, reason));
|
||||
lib.invokeHook(this.plugins, "onPlayerEvent", event);
|
||||
this.hooks.playerEvent.invoke(event);
|
||||
}
|
||||
|
||||
async handleInstanceExtractPlayersRequest() {
|
||||
@@ -450,7 +454,7 @@ end`.replace(/\r?\n/g, " ");
|
||||
stats,
|
||||
};
|
||||
this.sendTo("controller", new lib.InstancePlayerUpdateEvent("import", name, stats));
|
||||
lib.invokeHook(this.plugins, "onPlayerEvent", event);
|
||||
this.hooks.playerEvent.invoke(event);
|
||||
count += 1;
|
||||
}
|
||||
this.logger.info(`Extracted data for ${count} player(s)`);
|
||||
@@ -588,9 +592,7 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
|
||||
// Notify plugins of exit
|
||||
for (let pluginInstance of this.plugins.values()) {
|
||||
pluginInstance.onExit();
|
||||
}
|
||||
this.hooks.exit.invoke();
|
||||
|
||||
for (let player of this.playersOnline) {
|
||||
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}`));
|
||||
}
|
||||
|
||||
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() {
|
||||
let instanceStats;
|
||||
try {
|
||||
@@ -667,6 +654,7 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
|
||||
// load plugins
|
||||
const plugins: Record<string, string> = {};
|
||||
for (let pluginInfo of pluginInfos) {
|
||||
if (
|
||||
!pluginInfo.instanceEntrypoint
|
||||
@@ -682,7 +670,18 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
|
||||
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) {
|
||||
this.notifyExit();
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -953,8 +948,8 @@ end`.replace(/\r?\n/g, " ");
|
||||
|
||||
// Find plugin modules to patch in
|
||||
let modules: Map<string, SaveModule> = new Map();
|
||||
for (let plugin of this.plugins.values()) {
|
||||
let module = await SaveModule.fromPlugin(plugin);
|
||||
for (const pluginInfo of this.loadedPlugins) {
|
||||
let module = await SaveModule.fromPluginInfo(pluginInfo);
|
||||
if (!module) {
|
||||
continue;
|
||||
}
|
||||
@@ -1008,7 +1003,7 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
|
||||
await this.sendSaveListUpdate();
|
||||
await lib.invokeHook(this.plugins, "onStart");
|
||||
await this.hooks.start.invoke();
|
||||
|
||||
this.notifyStatus("running");
|
||||
}
|
||||
@@ -1033,7 +1028,7 @@ end`.replace(/\r?\n/g, " ");
|
||||
await this.server.startScenario(scenario, seed, mapGenSettings, mapSettings);
|
||||
this._watchServerLogActions();
|
||||
|
||||
await lib.invokeHook(this.plugins, "onStart");
|
||||
await this.hooks.start.invoke();
|
||||
|
||||
this.notifyStatus("running");
|
||||
}
|
||||
@@ -1169,7 +1164,7 @@ end`.replace(/\r?\n/g, " ");
|
||||
|
||||
// XXX this needs more thought to it
|
||||
if (this.server._state === "running") {
|
||||
await lib.invokeHook(this.plugins, "onStop");
|
||||
await this.hooks.stop.invoke();
|
||||
await this.server.stop();
|
||||
await this.sendSaveListUpdate();
|
||||
} else if (
|
||||
@@ -1188,17 +1183,17 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
|
||||
async handleControllerConnectionEvent(event: lib.ControllerConnectionEvent) {
|
||||
await lib.invokeHook(this.plugins, "onControllerConnectionEvent", event.event);
|
||||
await this.hooks.controllerConnectionEvent.invoke(event.event);
|
||||
}
|
||||
|
||||
async handlePrepareControllerDisconnectRequest() {
|
||||
await lib.invokeHook(this.plugins, "onPrepareControllerDisconnect", this);
|
||||
await this.hooks.prepareControllerDisconnect.invoke(this);
|
||||
}
|
||||
|
||||
async handleInstanceMetricsRequest() {
|
||||
let results: ReturnType<typeof lib.serializeResult>[] = [];
|
||||
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 await (let metric of metricIterator) {
|
||||
results.push(lib.serializeResult(metric));
|
||||
|
||||
@@ -9,9 +9,6 @@ import { Type, Static } from "@sinclair/typebox";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
import BaseInstancePlugin from "./BaseInstancePlugin.js";
|
||||
|
||||
|
||||
/**
|
||||
* Describes a module that can be patched into a save
|
||||
*/
|
||||
@@ -90,8 +87,8 @@ export class SaveModule {
|
||||
return module;
|
||||
}
|
||||
|
||||
static async fromPlugin(plugin: BaseInstancePlugin) {
|
||||
let moduleDirectory = path.join(path.dirname(plugin.info.packagePath), "module");
|
||||
static async fromPluginInfo(pluginInfo: lib.PluginNodeEnvInfo) {
|
||||
let moduleDirectory = path.join(path.dirname(pluginInfo.packagePath), "module");
|
||||
try {
|
||||
await fs.access(moduleDirectory);
|
||||
} catch (err: any) {
|
||||
@@ -102,17 +99,17 @@ export class SaveModule {
|
||||
let moduleJson;
|
||||
try {
|
||||
moduleJson = {
|
||||
name: plugin.info.name,
|
||||
version: plugin.info.version,
|
||||
name: pluginInfo.name,
|
||||
version: pluginInfo.version,
|
||||
dependencies: { "clusterio": "*" },
|
||||
...JSON.parse(await fs.readFile(moduleJsonPath, "utf8")),
|
||||
};
|
||||
} catch (err: any) {
|
||||
throw new Error(`Loading module/module.json in plugin ${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)) {
|
||||
throw new Error(
|
||||
`module/module.json in plugin ${plugin.info.name} failed validation:\n` +
|
||||
`module/module.json in plugin ${pluginInfo.name} failed validation:\n` +
|
||||
`${JSON.stringify(lib.ModuleInfo.validate.errors, null, "\t")}`
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user