mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-23 00:13:13 +09:00
Load all plugin types through one short lived PluginLoader
PluginLoader.load takes the plugin type, context, export name and base class as options and is used by the controller, host, instance, ctl, web interface and migrations. Module imports go through #plugin_module so the node variant stays out of the web bundle. loadPlugin.ts and the loading half of plugin_loader.ts are merged into it. The loader lives for one load. Plugins reach it through context.plugins, with waitFor(name, timeoutMs) and checkInstalled(name), replacing the waitForPlugin methods. Waiting on a plugin that is not in the load list or failed to load settles right away, as loading can't finish while the waiting entrypoint is still running. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7f688d2ed0
commit
c1ea4d470b
20 files changed
+490
-512
No files matched your search
@@ -206,6 +206,9 @@ The context has the following properties:
|
|||||||
**logger**:
|
**logger**:
|
||||||
Logger for this plugin, see [Logging Messages](#logging-messages).
|
Logger for this plugin, see [Logging Messages](#logging-messages).
|
||||||
|
|
||||||
|
**plugins**:
|
||||||
|
The other plugins loaded alongside this one, see [Depending on other plugins](#depending-on-other-plugins).
|
||||||
|
|
||||||
**controller**, **host**, **instance**, **hooks** or **control**:
|
**controller**, **host**, **instance**, **hooks** or **control**:
|
||||||
The object the entrypoint is loaded for.
|
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`.
|
Controller entrypoints get `controller`, host entrypoints get `host`, instance entrypoints get both `instance` and `host`, clusterioctl entrypoints get `hooks` and web entrypoints get `control`.
|
||||||
@@ -219,14 +222,13 @@ For TypeScript the context types are exported as `ControllerPluginContext`, `Hos
|
|||||||
### Depending on other plugins
|
### Depending on other plugins
|
||||||
|
|
||||||
Plugins are loaded at the same time, so there is no order between them.
|
Plugins are loaded at the same time, so there is no order between them.
|
||||||
A plugin that uses another plugin can wait for it with `waitForPlugin(waiter, name, timeoutMs)` on the controller, host or instance it is loaded for.
|
A plugin that uses another plugin can wait for it with `plugins.waitFor(name, timeoutMs)` from its context, `timeoutMs` defaults to 30 seconds.
|
||||||
`waiter` is the name of the plugin waiting, `name` is the plugin to wait for, and `timeoutMs` defaults to 30 seconds.
|
It resolves to the value returned by the other plugin's entrypoint for the same controller, host, instance, clusterioctl or web interface, so a plugin that offers an API to other plugins should return it from its entrypoint.
|
||||||
It resolves to the value returned by the other plugin's entrypoint for the same controller, host or instance, so a plugin that offers an API to other plugins should return it from its entrypoint.
|
|
||||||
For deprecated class based plugins it resolves to the plugin instance.
|
For deprecated class based plugins it resolves to the plugin instance.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
export default async function({ controller, plugin }) {
|
export default async function({ plugins }) {
|
||||||
const other = await controller.waitForPlugin(plugin.name, "other_plugin");
|
const other = await plugins.waitFor("other_plugin");
|
||||||
if (other) {
|
if (other) {
|
||||||
other.doSomething();
|
other.doSomething();
|
||||||
}
|
}
|
||||||
@@ -234,9 +236,10 @@ export default async function({ controller, plugin }) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
If the plugin is already loaded it resolves right away.
|
If the plugin is already loaded it resolves right away.
|
||||||
If the plugin is not installed, has load_plugin set to false, or plugins are disabled by recovery mode, it resolves to undefined once all plugins have loaded.
|
If the plugin is not installed, has load_plugin set to false, is disabled by recovery mode, or fails to load, it resolves to undefined right away.
|
||||||
If it times out it resolves to undefined.
|
If it times out it resolves to undefined.
|
||||||
In both cases a warning naming both plugins is logged.
|
In both cases a warning naming both plugins is logged.
|
||||||
|
`plugins.checkInstalled(name)` tells if a plugin is installed, use it to avoid the warning for optional plugins.
|
||||||
|
|
||||||
Startup does not continue until every entrypoint has returned.
|
Startup does not continue until every entrypoint has returned.
|
||||||
Two plugins awaiting each other in their entrypoints hold up startup until one of them times out.
|
Two plugins awaiting each other in their entrypoints hold up startup until one of them times out.
|
||||||
|
|||||||
@@ -77,7 +77,6 @@ export default class Controller {
|
|||||||
hooks = new ControllerHooks(logger);
|
hooks = new ControllerHooks(logger);
|
||||||
/** Plugins which are currently loaded */
|
/** Plugins which are currently loaded */
|
||||||
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
||||||
private _pluginLoader = new lib.PluginLoader(logger);
|
|
||||||
/** Latest versions of plugins on npm, as shown on the plugins page */
|
/** Latest versions of plugins on npm, as shown on the plugins page */
|
||||||
pluginLatestVersionCache: lib.LatestVersionCache = new Map();
|
pluginLatestVersionCache: lib.LatestVersionCache = new Map();
|
||||||
|
|
||||||
@@ -1580,20 +1579,6 @@ export default class Controller {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Wait for another plugin to load
|
|
||||||
*
|
|
||||||
* @param waiter - Name of the plugin waiting, used in warnings.
|
|
||||||
* @param name - Name of the plugin to wait for.
|
|
||||||
* @param timeoutMs - Time to wait before giving up.
|
|
||||||
* @returns
|
|
||||||
* What the plugin's entrypoint returned, or undefined with a
|
|
||||||
* warning logged if it did not load.
|
|
||||||
*/
|
|
||||||
waitForPlugin<T = unknown>(waiter: string, name: string, timeoutMs?: number) {
|
|
||||||
return this._pluginLoader.waitFor<T>(waiter, name, timeoutMs);
|
|
||||||
}
|
|
||||||
|
|
||||||
async loadPlugins() {
|
async loadPlugins() {
|
||||||
const toLoad: lib.PluginNodeEnvInfo[] = [];
|
const toLoad: lib.PluginNodeEnvInfo[] = [];
|
||||||
for (let pluginInfo of this.pluginInfos) {
|
for (let pluginInfo of this.pluginInfos) {
|
||||||
@@ -1621,29 +1606,16 @@ export default class Controller {
|
|||||||
toLoad.push(pluginInfo);
|
toLoad.push(pluginInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
const context = { metrics, logger, controller: this };
|
const { loaded } = await lib.PluginLoader.load({
|
||||||
await this._pluginLoader.load(toLoad, async pluginInfo => {
|
type: "controller",
|
||||||
let api;
|
context: { metrics, controller: this },
|
||||||
try {
|
logger,
|
||||||
api = await lib.loadPlugin(
|
installed: this.pluginInfos,
|
||||||
pluginInfo,
|
load: toLoad,
|
||||||
"controller",
|
exportName: "ControllerPlugin",
|
||||||
context,
|
baseClass: BaseControllerPlugin,
|
||||||
"ControllerPlugin",
|
|
||||||
BaseControllerPlugin,
|
|
||||||
);
|
|
||||||
} catch (err: any) {
|
|
||||||
if (err.code === "InstallationError") {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
throw new lib.PluginError(pluginInfo.name, err);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`Loaded plugin ${pluginInfo.name}`);
|
|
||||||
return api;
|
|
||||||
});
|
});
|
||||||
|
for (const pluginInfo of loaded.keys()) {
|
||||||
for (const pluginInfo of toLoad) {
|
|
||||||
this.loadedPlugins.add(pluginInfo);
|
this.loadedPlugins.add(pluginInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-11
@@ -118,17 +118,16 @@ async function loadPlugins(pluginList: Map<string, string>, hooks: CtlHooks) {
|
|||||||
lib.registerPluginPermissions(pluginInfos);
|
lib.registerPluginPermissions(pluginInfos);
|
||||||
lib.addPluginConfigFields(pluginInfos);
|
lib.addPluginConfigFields(pluginInfos);
|
||||||
|
|
||||||
const ctlPlugins = new Set<lib.PluginNodeEnvInfo>();
|
const { loaded } = await lib.PluginLoader.load({
|
||||||
for (let pluginInfo of pluginInfos) {
|
type: "ctl",
|
||||||
if (!pluginInfo.ctlEntrypoint) {
|
context: { hooks },
|
||||||
continue;
|
logger,
|
||||||
}
|
installed: pluginInfos,
|
||||||
|
load: pluginInfos.filter(pluginInfo => pluginInfo.ctlEntrypoint),
|
||||||
const context = { hooks, logger, plugin: pluginInfo };
|
exportName: "CtlPlugin",
|
||||||
await lib.loadPlugin(pluginInfo, "ctl", context, "CtlPlugin", BaseCtlPlugin);
|
baseClass: BaseCtlPlugin,
|
||||||
ctlPlugins.add(pluginInfo);
|
});
|
||||||
}
|
const ctlPlugins = new Set(loaded.keys());
|
||||||
|
|
||||||
return ctlPlugins;
|
return ctlPlugins;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -331,7 +331,6 @@ export default class Host extends lib.Link {
|
|||||||
hooks = new HostHooks(logger);
|
hooks = new HostHooks(logger);
|
||||||
/** Plugins which are currently loaded */
|
/** Plugins which are currently loaded */
|
||||||
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
||||||
private _pluginLoader = new lib.PluginLoader(logger);
|
|
||||||
|
|
||||||
/** 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>();
|
||||||
@@ -488,20 +487,6 @@ export default class Host extends lib.Link {
|
|||||||
this.handle(lib.InstanceDeleteInternalRequest, this.handleInstanceDeleteInternalRequest.bind(this));
|
this.handle(lib.InstanceDeleteInternalRequest, this.handleInstanceDeleteInternalRequest.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Wait for another host plugin to load
|
|
||||||
*
|
|
||||||
* @param waiter - Name of the plugin waiting, used in warnings.
|
|
||||||
* @param name - Name of the plugin to wait for.
|
|
||||||
* @param timeoutMs - Time to wait before giving up.
|
|
||||||
* @returns
|
|
||||||
* What the plugin's host entrypoint returned, or undefined with
|
|
||||||
* a warning logged if it did not load.
|
|
||||||
*/
|
|
||||||
waitForPlugin<T = unknown>(waiter: string, name: string, timeoutMs?: number) {
|
|
||||||
return this._pluginLoader.waitFor<T>(waiter, name, timeoutMs);
|
|
||||||
}
|
|
||||||
|
|
||||||
async loadPlugins() {
|
async loadPlugins() {
|
||||||
const toLoad: lib.PluginNodeEnvInfo[] = [];
|
const toLoad: lib.PluginNodeEnvInfo[] = [];
|
||||||
for (let pluginInfo of this.pluginInfos) {
|
for (let pluginInfo of this.pluginInfos) {
|
||||||
@@ -520,29 +505,16 @@ export default class Host extends lib.Link {
|
|||||||
toLoad.push(pluginInfo);
|
toLoad.push(pluginInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
const context = { logger, host: this };
|
const { loaded } = await lib.PluginLoader.load({
|
||||||
await this._pluginLoader.load(toLoad, async pluginInfo => {
|
type: "host",
|
||||||
let api;
|
context: { host: this },
|
||||||
try {
|
logger,
|
||||||
api = await lib.loadPlugin(
|
installed: this.pluginInfos,
|
||||||
pluginInfo,
|
load: toLoad,
|
||||||
"host",
|
exportName: "HostPlugin",
|
||||||
context,
|
baseClass: BaseHostPlugin,
|
||||||
"HostPlugin",
|
|
||||||
BaseHostPlugin,
|
|
||||||
);
|
|
||||||
} catch (err: any) {
|
|
||||||
if (err.code === "InstallationError") {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
throw new lib.PluginError(pluginInfo.name, err);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`Loaded plugin ${pluginInfo.name}`);
|
|
||||||
return api;
|
|
||||||
});
|
});
|
||||||
|
for (const pluginInfo of loaded.keys()) {
|
||||||
for (const pluginInfo of toLoad) {
|
|
||||||
this.loadedPlugins.add(pluginInfo);
|
this.loadedPlugins.add(pluginInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -181,7 +181,6 @@ export default class Instance extends lib.Link {
|
|||||||
hooks: InstanceHooks;
|
hooks: InstanceHooks;
|
||||||
/** Plugins which are currently loaded */
|
/** Plugins which are currently loaded */
|
||||||
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
loadedPlugins: Set<lib.PluginNodeEnvInfo> = new Set();
|
||||||
private _pluginLoader: lib.PluginLoader;
|
|
||||||
|
|
||||||
|
|
||||||
_host: Host;
|
_host: Host;
|
||||||
@@ -212,7 +211,6 @@ export default class Instance extends lib.Link {
|
|||||||
this.id = this.config.get("instance.id");
|
this.id = this.config.get("instance.id");
|
||||||
|
|
||||||
this.logger = instanceLogger(instanceConfig);
|
this.logger = instanceLogger(instanceConfig);
|
||||||
this._pluginLoader = new lib.PluginLoader(this.logger);
|
|
||||||
|
|
||||||
this.hooks = new InstanceHooks(this.logger);
|
this.hooks = new InstanceHooks(this.logger);
|
||||||
|
|
||||||
@@ -768,20 +766,6 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Wait for another instance plugin to load
|
|
||||||
*
|
|
||||||
* @param waiter - Name of the plugin waiting, used in warnings.
|
|
||||||
* @param name - Name of the plugin to wait for.
|
|
||||||
* @param timeoutMs - Time to wait before giving up.
|
|
||||||
* @returns
|
|
||||||
* What the plugin's instance entrypoint returned, or undefined with
|
|
||||||
* a warning logged if it did not load.
|
|
||||||
*/
|
|
||||||
waitForPlugin<T = unknown>(waiter: string, name: string, timeoutMs?: number) {
|
|
||||||
return this._pluginLoader.waitFor<T>(waiter, name, timeoutMs);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load the instance plugins and report the instance as initialised
|
* Load the instance plugins and report the instance as initialised
|
||||||
*
|
*
|
||||||
@@ -806,19 +790,17 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
toLoad.push(pluginInfo);
|
toLoad.push(pluginInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let loaded;
|
||||||
try {
|
try {
|
||||||
await this._pluginLoader.load(toLoad, async pluginInfo => {
|
({ loaded } = await lib.PluginLoader.load({
|
||||||
let pluginLoadStartedMs = Date.now();
|
type: "instance",
|
||||||
const api = await lib.loadPlugin(
|
context: { host: this._host, instance: this },
|
||||||
pluginInfo,
|
logger: this.logger,
|
||||||
"instance",
|
installed: pluginInfos,
|
||||||
{ logger: this.logger, host: this._host, instance: this },
|
load: toLoad,
|
||||||
"InstancePlugin",
|
exportName: "InstancePlugin",
|
||||||
BaseInstancePlugin,
|
baseClass: BaseInstancePlugin,
|
||||||
);
|
}));
|
||||||
this.logger.info(`Loaded plugin ${pluginInfo.name} in ${Date.now() - pluginLoadStartedMs}ms`);
|
|
||||||
return api;
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.notifyExit();
|
this.notifyExit();
|
||||||
await this.sendSaveListUpdate();
|
await this.sendSaveListUpdate();
|
||||||
@@ -826,7 +808,7 @@ end`.replace(/\r?\n/g, " ");
|
|||||||
}
|
}
|
||||||
|
|
||||||
const plugins: Record<string, string> = {};
|
const plugins: Record<string, string> = {};
|
||||||
for (const pluginInfo of toLoad) {
|
for (const pluginInfo of loaded.keys()) {
|
||||||
this.loadedPlugins.add(pluginInfo);
|
this.loadedPlugins.add(pluginInfo);
|
||||||
plugins[pluginInfo.name] = pluginInfo.version;
|
plugins[pluginInfo.name] = pluginInfo.version;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ 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/loadPlugin";
|
export * from "./src/PluginLoader";
|
||||||
export * from "./src/schema";
|
export * from "./src/schema";
|
||||||
export * from "./src/subscriptions";
|
export * from "./src/subscriptions";
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ export * from "./src/permissions.js";
|
|||||||
export * from "./src/plugin.js";
|
export * from "./src/plugin.js";
|
||||||
export * from "./src/plugin_loader.js";
|
export * from "./src/plugin_loader.js";
|
||||||
export * from "./src/PluginLoader.js";
|
export * from "./src/PluginLoader.js";
|
||||||
export * from "./src/loadPlugin.js";
|
|
||||||
export * from "./src/prometheus.js";
|
export * from "./src/prometheus.js";
|
||||||
export * from "./src/schema.js";
|
export * from "./src/schema.js";
|
||||||
export * from "./src/shared_commands.js";
|
export * from "./src/shared_commands.js";
|
||||||
|
|||||||
@@ -38,6 +38,13 @@
|
|||||||
},
|
},
|
||||||
"import": "./src/zlib_sync.browser.ts"
|
"import": "./src/zlib_sync.browser.ts"
|
||||||
},
|
},
|
||||||
|
"#plugin_module": {
|
||||||
|
"node": {
|
||||||
|
"types": "./src/plugin_module.node.ts",
|
||||||
|
"default": "./dist/node/src/plugin_module.node.js"
|
||||||
|
},
|
||||||
|
"import": "./src/plugin_module.browser.ts"
|
||||||
|
},
|
||||||
"#is_deep_strict_equal": {
|
"#is_deep_strict_equal": {
|
||||||
"node": {
|
"node": {
|
||||||
"types": "./src/is_deep_strict_equal.node.ts",
|
"types": "./src/is_deep_strict_equal.node.ts",
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { logger as defaultLogger, type Logger } from "./logging.js";
|
// Shared by node and the web interface, node specifics go in #plugin_module
|
||||||
import type { PluginNodeEnvInfo } from "./plugin.js";
|
import importPluginModule from "#plugin_module";
|
||||||
|
import { PluginError } from "./errors.js";
|
||||||
|
import type { Logger } from "./logging.js";
|
||||||
|
import type { PluginClass, PluginDeclaration, PluginLoadContext, PluginRegistry, PluginType } from "./plugin.js";
|
||||||
|
|
||||||
type Waiter = {
|
type Waiter = {
|
||||||
resolve: (api: unknown) => void,
|
resolve: (api: unknown) => void,
|
||||||
@@ -7,80 +10,164 @@ type Waiter = {
|
|||||||
waiter: string,
|
waiter: string,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type PluginLoadOptions<Context extends object, Info extends PluginDeclaration> = {
|
||||||
|
/** Entrypoint to load, e.g. controller loads controllerEntrypoint */
|
||||||
|
type: PluginType,
|
||||||
|
/** Context passed to each plugin, plugin, logger and plugins are added per plugin */
|
||||||
|
context: Context | ((pluginInfo: Info) => Context),
|
||||||
|
/** Logger for warnings, plugins get a child of it */
|
||||||
|
logger: Logger,
|
||||||
|
/** All installed plugins, used by checkInstalled */
|
||||||
|
installed: Info[],
|
||||||
|
/** Plugins to load */
|
||||||
|
load: Info[],
|
||||||
|
/** Name of the deprecated class export, class exports are not accepted if unset */
|
||||||
|
exportName?: string,
|
||||||
|
baseClass?: PluginClass<any, any>,
|
||||||
|
/** Return failed plugins instead of throwing the first error */
|
||||||
|
continueOnError?: boolean,
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PluginLoadResult<Info> = {
|
||||||
|
/** What each loaded plugin's entrypoint returned, in load order */
|
||||||
|
loaded: Map<Info, unknown>,
|
||||||
|
failed: Map<Info, Error>,
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads plugins concurrently and lets them wait for each other
|
* Loads plugins concurrently and lets them wait for each other
|
||||||
*
|
*
|
||||||
* Owned by the object plugins are loaded into (controller, host or
|
* Created for one load of plugins with {@link PluginLoader.load}.
|
||||||
* instance).
|
|
||||||
*/
|
*/
|
||||||
export class PluginLoader {
|
export class PluginLoader<Context extends object, Info extends PluginDeclaration> {
|
||||||
private _apis = new Map<string, unknown>();
|
private _apis = new Map<string, unknown>();
|
||||||
private _waiters = new Map<string, Waiter[]>();
|
private _waiters = new Map<string, Waiter[]>();
|
||||||
private _finished = false;
|
private _installed: Set<string>;
|
||||||
|
/** Plugins still loading */
|
||||||
|
private _pending: Set<string>;
|
||||||
|
|
||||||
constructor(
|
private constructor(
|
||||||
private _logger: Logger = defaultLogger,
|
private _options: PluginLoadOptions<Context, Info>,
|
||||||
) {}
|
) {
|
||||||
|
this._installed = new Set(_options.installed.map(pluginInfo => pluginInfo.name));
|
||||||
|
this._pending = new Set(_options.load.map(pluginInfo => pluginInfo.name));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load plugins concurrently
|
* Load plugins concurrently
|
||||||
*
|
*
|
||||||
* Waits for all loads to settle, then throws the error of the first
|
* Waits for all plugins to settle, then throws the error of the first
|
||||||
* plugin in the list that failed.
|
* plugin in the list that failed unless continueOnError is set.
|
||||||
|
* Errors are wrapped in PluginError.
|
||||||
*
|
*
|
||||||
* @param pluginInfos - Plugins to load.
|
* @param options - What to load and how.
|
||||||
* @param loadPlugin - Loads one plugin and returns what its entrypoint returned.
|
* @returns Loaded and failed plugins.
|
||||||
*/
|
*/
|
||||||
async load(pluginInfos: PluginNodeEnvInfo[], loadPlugin: (pluginInfo: PluginNodeEnvInfo) => Promise<unknown>) {
|
static async load<Context extends object, Info extends PluginDeclaration>(
|
||||||
try {
|
options: PluginLoadOptions<Context, Info>
|
||||||
const results = await Promise.allSettled(pluginInfos.map(async pluginInfo => {
|
): Promise<PluginLoadResult<Info>> {
|
||||||
this._loaded(pluginInfo.name, await loadPlugin(pluginInfo));
|
return await new PluginLoader(options)._load();
|
||||||
}));
|
|
||||||
const failed = results.find(result => result.status === "rejected");
|
|
||||||
if (failed) {
|
|
||||||
throw failed.reason;
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
this._finish();
|
private async _load() {
|
||||||
|
const results = await Promise.allSettled(this._options.load.map(async pluginInfo => {
|
||||||
|
const startedMs = Date.now();
|
||||||
|
try {
|
||||||
|
const api = await this._loadPlugin(pluginInfo);
|
||||||
|
if (this._options.type !== "migration" && pluginInfo[`${this._options.type}Entrypoint`]) {
|
||||||
|
this._options.logger.info(`Loaded plugin ${pluginInfo.name} in ${Date.now() - startedMs}ms`);
|
||||||
|
}
|
||||||
|
this._settle(pluginInfo.name, true, api);
|
||||||
|
return api;
|
||||||
|
} catch (err) {
|
||||||
|
this._settle(pluginInfo.name, false);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
const loaded = new Map<Info, unknown>();
|
||||||
|
const failed = new Map<Info, Error>();
|
||||||
|
for (const [index, result] of results.entries()) {
|
||||||
|
const pluginInfo = this._options.load[index];
|
||||||
|
if (result.status === "fulfilled") {
|
||||||
|
loaded.set(pluginInfo, result.value);
|
||||||
|
} else {
|
||||||
|
failed.set(pluginInfo, result.reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (failed.size && !this._options.continueOnError) {
|
||||||
|
throw failed.values().next().value;
|
||||||
|
}
|
||||||
|
return { loaded, failed };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async _loadPlugin(pluginInfo: Info) {
|
||||||
|
const { type, exportName, baseClass } = this._options;
|
||||||
|
const entrypoint = pluginInfo[`${type}Entrypoint`];
|
||||||
|
if (!entrypoint) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = this._options;
|
||||||
|
const context = typeof options.context === "function" ? options.context(pluginInfo) : options.context;
|
||||||
|
const pluginContext: PluginLoadContext<Context, Info> = {
|
||||||
|
...context,
|
||||||
|
plugin: pluginInfo,
|
||||||
|
logger: options.logger.child({ plugin: pluginInfo.name }),
|
||||||
|
plugins: this._registry(pluginInfo.name),
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const module = await importPluginModule(pluginInfo, entrypoint);
|
||||||
|
if (typeof module.default === "function") {
|
||||||
|
return await module.default(pluginContext) as unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
// migrate: accept plugins which export classes
|
||||||
|
if (exportName && baseClass && module[exportName]) {
|
||||||
|
pluginContext.logger.warn(`Plugin ${pluginInfo.name} is using deprecated class export`);
|
||||||
|
return await loadPluginClass(pluginInfo, pluginContext, module[exportName], exportName, baseClass);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(exportName
|
||||||
|
? `Plugin ${pluginInfo.name} must export either a default function or ${exportName} class`
|
||||||
|
: `Expected ${type} plugin ${pluginInfo.name} to export a default function`
|
||||||
|
);
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err.code === "InstallationError") {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
throw new PluginError(pluginInfo.name, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private _loaded(name: string, api: unknown) {
|
private _registry(waiter: string): PluginRegistry {
|
||||||
|
return {
|
||||||
|
waitFor: (name, timeoutMs) => this._waitFor(waiter, name, timeoutMs),
|
||||||
|
checkInstalled: name => this._installed.has(name),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private _settle(name: string, loaded: boolean, api?: unknown) {
|
||||||
|
this._pending.delete(name);
|
||||||
|
if (loaded) {
|
||||||
this._apis.set(name, api);
|
this._apis.set(name, api);
|
||||||
|
}
|
||||||
for (const entry of this._waiters.get(name) ?? []) {
|
for (const entry of this._waiters.get(name) ?? []) {
|
||||||
clearTimeout(entry.timeout);
|
clearTimeout(entry.timeout);
|
||||||
|
if (!loaded) {
|
||||||
|
this._warnNotLoaded(entry.waiter, name);
|
||||||
|
}
|
||||||
entry.resolve(api);
|
entry.resolve(api);
|
||||||
}
|
}
|
||||||
this._waiters.delete(name);
|
this._waiters.delete(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
private _finish() {
|
private _waitFor<T>(waiter: string, name: string, timeoutMs = 30_000): Promise<T | undefined> {
|
||||||
this._finished = true;
|
|
||||||
for (const [name, entries] of this._waiters) {
|
|
||||||
for (const entry of entries) {
|
|
||||||
clearTimeout(entry.timeout);
|
|
||||||
this._warnNotLoaded(entry.waiter, name);
|
|
||||||
entry.resolve(undefined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this._waiters.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wait for a plugin to load
|
|
||||||
*
|
|
||||||
* @param waiter - Name of the plugin waiting, used in warnings.
|
|
||||||
* @param name - Name of the plugin to wait for.
|
|
||||||
* @param timeoutMs - Time to wait before giving up.
|
|
||||||
* @returns
|
|
||||||
* What the plugin's entrypoint returned, or undefined with a
|
|
||||||
* warning logged if it did not load.
|
|
||||||
*/
|
|
||||||
waitFor<T = unknown>(waiter: string, name: string, timeoutMs = 30_000): Promise<T | undefined> {
|
|
||||||
if (this._apis.has(name)) {
|
if (this._apis.has(name)) {
|
||||||
return Promise.resolve(this._apis.get(name) as T);
|
return Promise.resolve(this._apis.get(name) as T);
|
||||||
}
|
}
|
||||||
if (this._finished) {
|
if (!this._pending.has(name)) {
|
||||||
this._warnNotLoaded(waiter, name);
|
this._warnNotLoaded(waiter, name);
|
||||||
return Promise.resolve(undefined);
|
return Promise.resolve(undefined);
|
||||||
}
|
}
|
||||||
@@ -92,7 +179,9 @@ export class PluginLoader {
|
|||||||
timeout: setTimeout(() => {
|
timeout: setTimeout(() => {
|
||||||
const entries = this._waiters.get(name)!;
|
const entries = this._waiters.get(name)!;
|
||||||
entries.splice(entries.indexOf(entry), 1);
|
entries.splice(entries.indexOf(entry), 1);
|
||||||
this._logger.warn(`Plugin ${waiter} timed out after ${timeoutMs}ms waiting for plugin ${name}`);
|
this._options.logger.warn(
|
||||||
|
`Plugin ${waiter} timed out after ${timeoutMs}ms waiting for plugin ${name}`
|
||||||
|
);
|
||||||
resolve(undefined);
|
resolve(undefined);
|
||||||
}, timeoutMs),
|
}, timeoutMs),
|
||||||
};
|
};
|
||||||
@@ -106,6 +195,32 @@ export class PluginLoader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _warnNotLoaded(waiter: string, name: string) {
|
private _warnNotLoaded(waiter: string, name: string) {
|
||||||
this._logger.warn(`Plugin ${waiter} waited for plugin ${name} which is not loaded`);
|
this._options.logger.warn(`Plugin ${waiter} waited for plugin ${name} which is not loaded`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadPluginClass(
|
||||||
|
pluginInfo: PluginDeclaration,
|
||||||
|
context: PluginLoadContext<object, any>,
|
||||||
|
pluginClass: unknown,
|
||||||
|
exportName: string,
|
||||||
|
baseClass: PluginClass<any, any>,
|
||||||
|
) {
|
||||||
|
if (typeof pluginClass !== "function") {
|
||||||
|
throw new Error(`Expected plugin ${pluginInfo.name} to export a class named ${exportName}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(pluginClass.prototype instanceof baseClass)) {
|
||||||
|
throw new Error(`Expected ${exportName} exported from ${pluginInfo.name} to extend ${baseClass.name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const plugin = (pluginClass as PluginClass<any, any>).fromContext(context);
|
||||||
|
try {
|
||||||
|
await plugin.init();
|
||||||
|
} catch (err) {
|
||||||
|
plugin.detachHooks();
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
return plugin;
|
||||||
|
}
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
// Contained in its own file to allow use within web build
|
|
||||||
import type { PluginDeclaration, PluginType, PluginLoadContext, PluginClass } from "./plugin.js";
|
|
||||||
|
|
||||||
|
|
||||||
export async function loadPluginEntrypoint<
|
|
||||||
Context extends object,
|
|
||||||
Info extends PluginDeclaration
|
|
||||||
>(
|
|
||||||
pluginInfo: Info,
|
|
||||||
pluginType: PluginType,
|
|
||||||
context: PluginLoadContext<Context, Info>,
|
|
||||||
module: Record<string, unknown>
|
|
||||||
) {
|
|
||||||
const init = module.default;
|
|
||||||
|
|
||||||
if (typeof init !== "function") {
|
|
||||||
throw new Error(`Expected ${pluginType} plugin ${pluginInfo.name} to export a default function`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await init(context) as unknown;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadPluginClass<
|
|
||||||
Context extends object,
|
|
||||||
Class extends PluginClass<Context, Info>,
|
|
||||||
Info extends PluginDeclaration
|
|
||||||
>(
|
|
||||||
pluginInfo: Info,
|
|
||||||
pluginType: PluginType,
|
|
||||||
context: PluginLoadContext<Context, Info>,
|
|
||||||
module: Record<string, unknown>,
|
|
||||||
exportName: string,
|
|
||||||
baseClass: Class
|
|
||||||
) {
|
|
||||||
const pluginClass = module[exportName];
|
|
||||||
|
|
||||||
if (typeof pluginClass !== "function") {
|
|
||||||
throw new Error(`Expected ${pluginType} plugin ${pluginInfo.name} to export a class named ${exportName}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!(pluginClass.prototype instanceof baseClass)) {
|
|
||||||
throw new Error(`Expected ${exportName} exported from ${pluginInfo.name} to extend ${baseClass.name}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const plugin = (pluginClass as Class).fromContext(context);
|
|
||||||
try {
|
|
||||||
await plugin.init();
|
|
||||||
} catch (err) {
|
|
||||||
plugin.detachHooks();
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
return plugin as InstanceType<Class>;
|
|
||||||
}
|
|
||||||
@@ -142,12 +142,29 @@ export interface PlayerEvent {
|
|||||||
stats: PlayerStats,
|
stats: PlayerStats,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Access to the other plugins loaded alongside a plugin */
|
||||||
|
export interface PluginRegistry {
|
||||||
|
/**
|
||||||
|
* Wait for another plugin to load
|
||||||
|
*
|
||||||
|
* @param name - Name of the plugin to wait for.
|
||||||
|
* @param timeoutMs - Time to wait before giving up, defaults to 30 seconds.
|
||||||
|
* @returns
|
||||||
|
* What the plugin's entrypoint returned, or undefined with a
|
||||||
|
* warning logged if it did not load.
|
||||||
|
*/
|
||||||
|
waitFor<T = unknown>(name: string, timeoutMs?: number): Promise<T | undefined>;
|
||||||
|
/** Check if a plugin is installed, it may still be disabled */
|
||||||
|
checkInstalled(name: string): boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export type PluginLoadContext<
|
export type PluginLoadContext<
|
||||||
Context extends object,
|
Context extends object,
|
||||||
Info extends PluginDeclaration = PluginNodeEnvInfo
|
Info extends PluginDeclaration = PluginNodeEnvInfo
|
||||||
> = Context & {
|
> = Context & {
|
||||||
logger: Logger;
|
logger: Logger;
|
||||||
plugin: Info;
|
plugin: Info;
|
||||||
|
plugins: PluginRegistry;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Hooks for migrating data that Clusterio stores on behalf of plugins */
|
/** Hooks for migrating data that Clusterio stores on behalf of plugins */
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import fs from "node:fs/promises";
|
|||||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||||
import * as libErrors from "./errors.js";
|
import * as libErrors from "./errors.js";
|
||||||
import * as libPlugin from "./plugin.js";
|
import * as libPlugin from "./plugin.js";
|
||||||
import { type Logger, logger } from "./logging.js";
|
import { logger } from "./logging.js";
|
||||||
import { loadPluginEntrypoint, loadPluginClass } from "./loadPlugin.js";
|
import { PluginLoader } from "./PluginLoader.js";
|
||||||
import { Config } from "./config/classes.js";
|
import { Config } from "./config/classes.js";
|
||||||
import { ControllerConfig, HostConfig, InstanceConfig } from "./config/definitions.js";
|
import { ControllerConfig, HostConfig, InstanceConfig } from "./config/definitions.js";
|
||||||
import Role from "./data/Role.js";
|
import Role from "./data/Role.js";
|
||||||
@@ -217,59 +217,12 @@ export async function loadPluginMigrations(pluginInfos: libPlugin.PluginNodeEnvI
|
|||||||
|
|
||||||
for (const pluginInfo of pluginInfos) {
|
for (const pluginInfo of pluginInfos) {
|
||||||
Config.pluginVersions.set(pluginInfo.name, pluginInfo.version);
|
Config.pluginVersions.set(pluginInfo.name, pluginInfo.version);
|
||||||
if (!pluginInfo.migrationEntrypoint) {
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
await PluginLoader.load({
|
||||||
try {
|
type: "migration",
|
||||||
const module = await import(pathToFileURL(
|
context: { hooks },
|
||||||
path.join(path.dirname(pluginInfo.packagePath), pluginInfo.migrationEntrypoint)
|
logger,
|
||||||
).href);
|
installed: pluginInfos,
|
||||||
const context: libPlugin.MigrationContext = {
|
load: pluginInfos,
|
||||||
hooks,
|
});
|
||||||
plugin: pluginInfo,
|
|
||||||
logger: logger.child({ plugin: pluginInfo.name }),
|
|
||||||
};
|
|
||||||
await loadPluginEntrypoint(pluginInfo, "migration", context, module);
|
|
||||||
} catch (err: any) {
|
|
||||||
throw new libErrors.PluginError(pluginInfo.name, err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadPlugin<
|
|
||||||
Context extends { logger: Logger },
|
|
||||||
Class extends libPlugin.PluginClass<Context, libPlugin.PluginNodeEnvInfo>,
|
|
||||||
> (
|
|
||||||
pluginInfo: libPlugin.PluginNodeEnvInfo,
|
|
||||||
pluginType: libPlugin.PluginType,
|
|
||||||
context: Context,
|
|
||||||
exportName: `${string}Plugin`,
|
|
||||||
baseClass: Class,
|
|
||||||
) {
|
|
||||||
const entrypoint = `${pluginType}Entrypoint` as const;
|
|
||||||
const requirePath = pluginInfo[entrypoint];
|
|
||||||
|
|
||||||
if (!requirePath) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const module = await import(pathToFileURL(path.join(path.dirname(pluginInfo.packagePath), requirePath)).href);
|
|
||||||
const pluginContext: libPlugin.PluginLoadContext<Context> = {
|
|
||||||
...context,
|
|
||||||
plugin: pluginInfo,
|
|
||||||
logger: context.logger.child({ plugin: pluginInfo.name }),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (typeof module.default === "function") {
|
|
||||||
return await loadPluginEntrypoint(pluginInfo, pluginType, pluginContext, module);
|
|
||||||
}
|
|
||||||
|
|
||||||
// migrate: accept plugins which export classes
|
|
||||||
if (module[exportName]) {
|
|
||||||
pluginContext.logger.warn(`Plugin ${pluginInfo.name} is using deprecated class export`);
|
|
||||||
return await loadPluginClass(pluginInfo, pluginType, pluginContext, module, exportName, baseClass);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`Plugin ${pluginInfo.name} must export either a default function or ${exportName} class`);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import type { PluginDeclaration, PluginWebEnvInfo } from "./plugin";
|
||||||
|
|
||||||
|
export default async function importPluginModule(
|
||||||
|
pluginInfo: PluginDeclaration, entrypoint: string
|
||||||
|
): Promise<Record<string, any>> {
|
||||||
|
return await (pluginInfo as PluginWebEnvInfo).container.get(entrypoint);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import path from "node:path";
|
||||||
|
import { pathToFileURL } from "node:url";
|
||||||
|
import type { PluginDeclaration, PluginNodeEnvInfo } from "./plugin.js";
|
||||||
|
|
||||||
|
export default async function importPluginModule(
|
||||||
|
pluginInfo: PluginDeclaration, entrypoint: string
|
||||||
|
): Promise<Record<string, any>> {
|
||||||
|
const packagePath = (pluginInfo as PluginNodeEnvInfo).packagePath;
|
||||||
|
return await import(pathToFileURL(path.join(path.dirname(packagePath), entrypoint)).href);
|
||||||
|
}
|
||||||
@@ -25,7 +25,8 @@
|
|||||||
"./src/logging.ts",
|
"./src/logging.ts",
|
||||||
"./src/permissions.ts",
|
"./src/permissions.ts",
|
||||||
"./src/prometheus.ts",
|
"./src/prometheus.ts",
|
||||||
"./src/loadPlugin.ts",
|
"./src/PluginLoader.ts",
|
||||||
|
"./src/plugin_module.browser.ts",
|
||||||
"./src/plugin.ts",
|
"./src/plugin.ts",
|
||||||
"./src/schema.ts",
|
"./src/schema.ts",
|
||||||
"./src/subscriptions.ts",
|
"./src/subscriptions.ts",
|
||||||
|
|||||||
@@ -69,49 +69,36 @@ async function loadPlugins(
|
|||||||
pluginInfos: lib.PluginWebEnvInfo[],
|
pluginInfos: lib.PluginWebEnvInfo[],
|
||||||
control: Control
|
control: Control
|
||||||
) {
|
) {
|
||||||
const plugins = new Map<string, WebPlugin.BaseWebPlugin>();
|
const { loaded, failed } = await lib.PluginLoader.load({
|
||||||
|
type: "web",
|
||||||
for (const pluginInfo of pluginInfos) {
|
context: (pluginInfo: lib.PluginWebEnvInfo) => ({
|
||||||
if (!pluginInfo.enabled || !pluginInfo.webEntrypoint) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const webModule = await pluginInfo.container.get(pluginInfo.webEntrypoint);
|
|
||||||
|
|
||||||
const pluginContext: WebPlugin.WebPluginContext = {
|
|
||||||
control,
|
control,
|
||||||
plugin: pluginInfo,
|
|
||||||
container: pluginInfo.container,
|
container: pluginInfo.container,
|
||||||
package: pluginInfo.package,
|
package: pluginInfo.package,
|
||||||
logger: logger.child({ plugin: pluginInfo.name }),
|
}),
|
||||||
};
|
logger,
|
||||||
|
installed: pluginInfos,
|
||||||
|
load: pluginInfos.filter(pluginInfo => pluginInfo.enabled && pluginInfo.webEntrypoint),
|
||||||
|
exportName: "WebPlugin",
|
||||||
|
baseClass: WebPlugin.BaseWebPlugin,
|
||||||
|
continueOnError: true,
|
||||||
|
});
|
||||||
|
|
||||||
if (typeof webModule.default === "function") {
|
for (const [pluginInfo, err] of failed) {
|
||||||
await lib.loadPluginEntrypoint(pluginInfo, "web", pluginContext, webModule);
|
const cause = err instanceof lib.PluginError ? err.original : err;
|
||||||
continue;
|
pluginInfo.error = `Error loading plugin: ${cause.message}`;
|
||||||
}
|
|
||||||
|
|
||||||
// migrate: accept plugins which export classes
|
|
||||||
if (webModule.WebPlugin) {
|
|
||||||
logger.warn(`Plugin ${pluginInfo.name} is using deprecated class hooks`);
|
|
||||||
plugins.set(pluginInfo.name, await lib.loadPluginClass(
|
|
||||||
pluginInfo, "web", pluginContext, webModule, "WebPlugin", WebPlugin.BaseWebPlugin
|
|
||||||
));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`Plugin ${pluginInfo.name} must export either a default function or WebPlugin`);
|
|
||||||
|
|
||||||
} catch (err: any) {
|
|
||||||
pluginInfo.error = `Error loading plugin: ${err.message}`;
|
|
||||||
logger.error(`Failed to load plugin ${pluginInfo.name}`);
|
logger.error(`Failed to load plugin ${pluginInfo.name}`);
|
||||||
if (err.stack) {
|
if (cause.stack) {
|
||||||
logger.error(err.stack);
|
logger.error(cause.stack);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const plugins = new Map<string, WebPlugin.BaseWebPlugin>();
|
||||||
|
for (const [pluginInfo, api] of loaded) {
|
||||||
|
if (api instanceof WebPlugin.BaseWebPlugin) {
|
||||||
|
plugins.set(pluginInfo.name, api);
|
||||||
|
}
|
||||||
|
}
|
||||||
return plugins;
|
return plugins;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -239,15 +239,16 @@ describe("controller/src/Controller", function() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe(".waitForPlugin()", function() {
|
describe(".loadPlugins()", function() {
|
||||||
const names = ["wait_early", "wait_late", "wait_off"];
|
const names = ["wait_early", "wait_late", "wait_off"];
|
||||||
let dir;
|
let dir;
|
||||||
before(async function() {
|
before(async function() {
|
||||||
addPluginConfigFields(names.map(name => ({ name, version: "1.0.0", controllerEntrypoint: "x" })));
|
addPluginConfigFields(names.map(name => ({ name, version: "1.0.0", controllerEntrypoint: "x" })));
|
||||||
dir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-wait-"));
|
dir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-wait-"));
|
||||||
const entrypoints = {
|
const entrypoints = {
|
||||||
wait_early: `export default async function({ controller, plugin }) {
|
wait_early: `export default async function({ controller, plugins }) {
|
||||||
controller.lateApi = await controller.waitForPlugin(plugin.name, "wait_late");
|
controller.lateApi = await plugins.waitFor("wait_late");
|
||||||
|
controller.offApi = await plugins.waitFor("wait_off", 60_000);
|
||||||
}`,
|
}`,
|
||||||
wait_late: "export default function() { return { late: true }; }",
|
wait_late: "export default function() { return { late: true }; }",
|
||||||
wait_off: "export default function() { return { off: true }; }",
|
wait_off: "export default function() { return { off: true }; }",
|
||||||
@@ -278,25 +279,17 @@ describe("controller/src/Controller", function() {
|
|||||||
}));
|
}));
|
||||||
return new Controller({}, infos, config, false, recoveryMode);
|
return new Controller({}, infos, config, false, recoveryMode);
|
||||||
}
|
}
|
||||||
it("should resolve to what a plugin later in the list returned", async function() {
|
it("should let plugins wait for each other", async function() {
|
||||||
const pluginsController = pluginController();
|
const pluginsController = pluginController();
|
||||||
await pluginsController.loadPlugins();
|
await pluginsController.loadPlugins();
|
||||||
assert.deepEqual(pluginsController.lateApi, { late: true });
|
assert.deepEqual(pluginsController.lateApi, { late: true });
|
||||||
assert.deepEqual(await pluginsController.waitForPlugin("test", "wait_late"), { late: true });
|
assert.equal(pluginsController.offApi, undefined);
|
||||||
|
assert.deepEqual([...pluginsController.loadedPlugins].map(p => p.name), ["wait_early", "wait_late"]);
|
||||||
});
|
});
|
||||||
it("should resolve undefined once loading finishes for plugins not loaded", async function() {
|
it("should load nothing in recovery mode", async function() {
|
||||||
const pluginsController = pluginController();
|
|
||||||
const off = pluginsController.waitForPlugin("test", "wait_off", 60_000);
|
|
||||||
const missing = pluginsController.waitForPlugin("test", "missing", 60_000);
|
|
||||||
await pluginsController.loadPlugins();
|
|
||||||
assert.equal(await off, undefined);
|
|
||||||
assert.equal(await missing, undefined);
|
|
||||||
});
|
|
||||||
it("should resolve undefined once loading finishes in recovery mode", async function() {
|
|
||||||
const pluginsController = pluginController(true);
|
const pluginsController = pluginController(true);
|
||||||
const late = pluginsController.waitForPlugin("test", "wait_late", 60_000);
|
|
||||||
await pluginsController.loadPlugins();
|
await pluginsController.loadPlugins();
|
||||||
assert.equal(await late, undefined);
|
assert.equal(pluginsController.loadedPlugins.size, 0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe(".validateExports()", function() {
|
describe(".validateExports()", function() {
|
||||||
|
|||||||
@@ -251,7 +251,7 @@ describe("host/src/Host", function() {
|
|||||||
assert.equal(host.config.restartRequired, true);
|
assert.equal(host.config.restartRequired, true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe(".waitForPlugin()", function() {
|
describe(".loadPlugins()", function() {
|
||||||
let dir;
|
let dir;
|
||||||
before(async function() {
|
before(async function() {
|
||||||
lib.addPluginConfigFields([
|
lib.addPluginConfigFields([
|
||||||
@@ -259,8 +259,8 @@ describe("host/src/Host", function() {
|
|||||||
{ name: "host_wait_late", version: "1.0.0", hostEntrypoint: "x" },
|
{ name: "host_wait_late", version: "1.0.0", hostEntrypoint: "x" },
|
||||||
]);
|
]);
|
||||||
dir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-host-wait-"));
|
dir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-host-wait-"));
|
||||||
await fs.writeFile(path.join(dir, "early.js"), `export default async function({ host, plugin }) {
|
await fs.writeFile(path.join(dir, "early.js"), `export default async function({ host, plugins }) {
|
||||||
host.lateApi = await host.waitForPlugin(plugin.name, "host_wait_late");
|
host.lateApi = await plugins.waitFor("host_wait_late");
|
||||||
}`);
|
}`);
|
||||||
await fs.writeFile(path.join(dir, "late.js"), "export default function() { return { late: true }; }");
|
await fs.writeFile(path.join(dir, "late.js"), "export default function() { return { late: true }; }");
|
||||||
});
|
});
|
||||||
@@ -272,7 +272,7 @@ describe("host/src/Host", function() {
|
|||||||
}
|
}
|
||||||
await fs.rm(dir, { recursive: true, force: true });
|
await fs.rm(dir, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
it("should resolve to what a host plugin later in the list returned", async function() {
|
it("should let plugins wait for each other", async function() {
|
||||||
const pluginInfos = [["host_wait_early", "early.js"], ["host_wait_late", "late.js"]].map(
|
const pluginInfos = [["host_wait_early", "early.js"], ["host_wait_late", "late.js"]].map(
|
||||||
([name, hostEntrypoint]) => ({
|
([name, hostEntrypoint]) => ({
|
||||||
name, hostEntrypoint, packagePath: path.resolve(dir, "package.json"),
|
name, hostEntrypoint, packagePath: path.resolve(dir, "package.json"),
|
||||||
@@ -280,10 +280,9 @@ describe("host/src/Host", function() {
|
|||||||
);
|
);
|
||||||
const hostConfig = new lib.HostConfig("host");
|
const hostConfig = new lib.HostConfig("host");
|
||||||
const host = new Host(new HostConnector(hostConfig, pluginInfos), hostConfig, pluginInfos);
|
const host = new Host(new HostConnector(hostConfig, pluginInfos), hostConfig, pluginInfos);
|
||||||
const missing = host.waitForPlugin("test", "missing", 60_000);
|
|
||||||
await host.loadPlugins();
|
await host.loadPlugins();
|
||||||
assert.deepEqual(host.lateApi, { late: true });
|
assert.deepEqual(host.lateApi, { late: true });
|
||||||
assert.equal(await missing, undefined);
|
assert.deepEqual([...host.loadedPlugins].map(p => p.name), ["host_wait_early", "host_wait_late"]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe(".assignFreeGamePort()", function() {
|
describe(".assignFreeGamePort()", function() {
|
||||||
|
|||||||
+181
-54
@@ -1,72 +1,199 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
|
import fs from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import * as mock from "../mock.js";
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
import { BaseControllerPlugin } from "@clusterio/controller";
|
||||||
|
|
||||||
describe("lib/PluginLoader", function() {
|
describe("lib/PluginLoader", function() {
|
||||||
|
let dir;
|
||||||
let logger;
|
let logger;
|
||||||
let loader;
|
let controller;
|
||||||
beforeEach(function() {
|
before(async function() {
|
||||||
logger = { warnings: [], warn(msg) { this.warnings.push(msg); } };
|
// Inside the repo so the class entrypoints can import @clusterio/controller
|
||||||
loader = new lib.PluginLoader(logger);
|
dir = path.resolve("temp", "test", "plugin_loader");
|
||||||
});
|
await fs.mkdir(dir, { recursive: true });
|
||||||
const infos = (...names) => names.map(name => ({ name }));
|
const entrypoints = {
|
||||||
|
"function.js": `export default async function(context) {
|
||||||
it("should let a plugin await a plugin later in the list while loading", async function() {
|
context.controller.loadedWith = context;
|
||||||
const apis = { b: { b: true } };
|
return { api: true };
|
||||||
await loader.load(infos("a", "b"), async ({ name }) => {
|
}`,
|
||||||
if (name === "a") {
|
"class.js": `import { BaseControllerPlugin } from "@clusterio/controller";
|
||||||
apis.a = { gotB: await loader.waitFor("a", "b") };
|
export class ControllerPlugin extends BaseControllerPlugin {
|
||||||
|
async init() { this.controller.loadedWith = this; }
|
||||||
|
async onSaveData() { }
|
||||||
|
}`,
|
||||||
|
"throwing_class.js": `import { BaseControllerPlugin } from "@clusterio/controller";
|
||||||
|
export class ControllerPlugin extends BaseControllerPlugin {
|
||||||
|
async init() { throw new Error("init failed"); }
|
||||||
|
async onSaveData() { }
|
||||||
|
}`,
|
||||||
|
"empty.js": "",
|
||||||
|
"wrong_parent.js": "export class ControllerPlugin {};\n",
|
||||||
|
"throwing.js": `export default async function({ plugin }) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, plugin.delay ?? 0));
|
||||||
|
throw new Error(\`\${plugin.name} failed\`);
|
||||||
|
}`,
|
||||||
|
// Waits for the plugin named in plugin.waitFor and returns what it got
|
||||||
|
"waiting.js": `export default async function({ plugin, plugins }) {
|
||||||
|
const got = plugin.waitFor ? await plugins.waitFor(plugin.waitFor, plugin.timeoutMs) : undefined;
|
||||||
|
return { name: plugin.name, got };
|
||||||
|
}`,
|
||||||
|
};
|
||||||
|
for (const [file, content] of Object.entries(entrypoints)) {
|
||||||
|
await fs.writeFile(path.join(dir, file), content);
|
||||||
}
|
}
|
||||||
return apis[name];
|
|
||||||
});
|
});
|
||||||
assert.deepEqual(apis.a, { gotB: { b: true } });
|
after(async function() {
|
||||||
assert.equal(await loader.waitFor("c", "a"), apis.a);
|
await fs.rm(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
beforeEach(function() {
|
||||||
|
controller = new mock.MockController();
|
||||||
|
logger = new mock.MockLogger();
|
||||||
|
logger.warnings = [];
|
||||||
|
logger.warn = msg => logger.warnings.push(msg);
|
||||||
|
});
|
||||||
|
|
||||||
|
function info(name, entrypoint, extra = {}) {
|
||||||
|
return { name, packagePath: path.join(dir, "package.json"), controllerEntrypoint: entrypoint, ...extra };
|
||||||
|
}
|
||||||
|
function load(pluginInfos, options = {}) {
|
||||||
|
return lib.PluginLoader.load({
|
||||||
|
type: "controller",
|
||||||
|
context: { controller },
|
||||||
|
logger,
|
||||||
|
installed: pluginInfos,
|
||||||
|
load: pluginInfos,
|
||||||
|
exportName: "ControllerPlugin",
|
||||||
|
baseClass: BaseControllerPlugin,
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function loadOne(pluginInfo) {
|
||||||
|
const { loaded } = await load([pluginInfo]);
|
||||||
|
return loaded.get(pluginInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("loading", function() {
|
||||||
|
it("should load plugins without the entrypoint as undefined", async function() {
|
||||||
|
const pluginInfo = { name: "test" };
|
||||||
|
const { loaded } = await load([pluginInfo]);
|
||||||
|
assert.deepEqual([...loaded], [[pluginInfo, undefined]]);
|
||||||
|
assert.equal(controller.loadedWith, undefined);
|
||||||
|
});
|
||||||
|
it("should call the default export with the load context", async function() {
|
||||||
|
const pluginInfo = info("test", "function.js");
|
||||||
|
assert.deepEqual(await loadOne(pluginInfo), { api: true });
|
||||||
|
assert.equal(controller.loadedWith.controller, controller);
|
||||||
|
assert.equal(controller.loadedWith.plugin, pluginInfo);
|
||||||
|
assert.equal(controller.loadedWith.logger, logger);
|
||||||
|
assert.equal(typeof controller.loadedWith.plugins.waitFor, "function");
|
||||||
assert.deepEqual(logger.warnings, []);
|
assert.deepEqual(logger.warnings, []);
|
||||||
});
|
});
|
||||||
it("should resolve undefined with a warning once loading finishes without the plugin", async function() {
|
it("should build the context per plugin when given a function", async function() {
|
||||||
const result = loader.waitFor("a", "b");
|
const pluginInfo = info("test", "function.js");
|
||||||
await loader.load(infos("c"), async () => ({}));
|
await load([pluginInfo], { context: p => ({ controller, name: p.name }) });
|
||||||
assert.equal(await result, undefined);
|
assert.equal(controller.loadedWith.name, "test");
|
||||||
assert.equal(await loader.waitFor("a", "d"), undefined);
|
|
||||||
assert.deepEqual(logger.warnings, [
|
|
||||||
"Plugin a waited for plugin b which is not loaded",
|
|
||||||
"Plugin a waited for plugin d which is not loaded",
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
it("should resolve undefined with a warning on timeout", async function() {
|
it("should load a deprecated class export", async function() {
|
||||||
const result = loader.waitFor("a", "b", 10);
|
const pluginInfo = info("test", "class.js");
|
||||||
const other = loader.waitFor("c", "b");
|
assert.equal(await loadOne(pluginInfo), controller.loadedWith);
|
||||||
assert.equal(await result, undefined);
|
assert(controller.loadedWith instanceof BaseControllerPlugin);
|
||||||
assert.deepEqual(logger.warnings, ["Plugin a timed out after 10ms waiting for plugin b"]);
|
assert.equal(controller.loadedWith.info, pluginInfo);
|
||||||
await loader.load(infos("b"), async () => "api");
|
assert.deepEqual([...controller.hooks.save.attached], ["test"]);
|
||||||
assert.equal(await other, "api");
|
assert.deepEqual(logger.warnings, ["Plugin test is using deprecated class export"]);
|
||||||
});
|
});
|
||||||
it("should break a wait cycle with the timeout", async function() {
|
it("should not accept class exports without exportName", async function() {
|
||||||
const got = {};
|
await assert.rejects(
|
||||||
await loader.load(infos("a", "b"), async ({ name }) => {
|
load([info("test", "class.js")], { exportName: undefined }),
|
||||||
got[name] = await loader.waitFor(name, name === "a" ? "b" : "a", name === "a" ? 10 : 1000);
|
{ message: "PluginError: Expected controller plugin test to export a default function" },
|
||||||
return name;
|
);
|
||||||
});
|
});
|
||||||
assert.deepEqual(got, { a: undefined, b: "a" });
|
it("should detach hooks if init throws", async function() {
|
||||||
assert.deepEqual(logger.warnings, ["Plugin a timed out after 10ms waiting for plugin b"]);
|
await assert.rejects(
|
||||||
|
loadOne(info("test", "throwing_class.js")),
|
||||||
|
err => err instanceof lib.PluginError && err.original.message === "init failed",
|
||||||
|
);
|
||||||
|
assert.equal(controller.hooks.size, 0);
|
||||||
|
});
|
||||||
|
it("should throw if neither a function nor a class is exported", async function() {
|
||||||
|
await assert.rejects(
|
||||||
|
loadOne(info("test", "empty.js")),
|
||||||
|
{ message: "PluginError: Plugin test must export either a default function or ControllerPlugin class" },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it("should throw if the class is not a subclass of the base class", async function() {
|
||||||
|
await assert.rejects(
|
||||||
|
loadOne(info("test", "wrong_parent.js")),
|
||||||
|
{ message: "PluginError: Expected ControllerPlugin exported from test to extend BaseControllerPlugin" },
|
||||||
|
);
|
||||||
});
|
});
|
||||||
it("should finish loading the rest before throwing the first error in list order", async function() {
|
it("should finish loading the rest before throwing the first error in list order", async function() {
|
||||||
const loaded = [];
|
const ok = info("ok", "function.js");
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
loader.load(infos("a", "b", "c"), async ({ name }) => {
|
load([info("a", "throwing.js", { delay: 10 }), info("b", "throwing.js"), ok]),
|
||||||
if (name === "a") {
|
err => err instanceof lib.PluginError && err.pluginName === "a",
|
||||||
await new Promise(resolve => setTimeout(resolve, 10));
|
|
||||||
throw new Error("a failed");
|
|
||||||
}
|
|
||||||
if (name === "b") {
|
|
||||||
throw new Error("b failed");
|
|
||||||
}
|
|
||||||
loaded.push(name);
|
|
||||||
return name;
|
|
||||||
}),
|
|
||||||
{ message: "a failed" },
|
|
||||||
);
|
);
|
||||||
assert.deepEqual(loaded, ["c"]);
|
assert.equal(controller.loadedWith.plugin, ok);
|
||||||
assert.equal(await loader.waitFor("x", "a"), undefined);
|
});
|
||||||
assert.deepEqual(logger.warnings, ["Plugin x waited for plugin a which is not loaded"]);
|
it("should return failures with continueOnError", async function() {
|
||||||
|
const a = info("a", "throwing.js");
|
||||||
|
const ok = info("ok", "function.js");
|
||||||
|
const { loaded, failed } = await load([a, ok], { continueOnError: true });
|
||||||
|
assert.deepEqual([...loaded.keys()], [ok]);
|
||||||
|
assert.deepEqual([...failed.keys()], [a]);
|
||||||
|
assert(failed.get(a) instanceof lib.PluginError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("plugins.waitFor()", function() {
|
||||||
|
it("should resolve to what a plugin later in the list returned", async function() {
|
||||||
|
const { loaded } = await load([info("a", "waiting.js", { waitFor: "b" }), info("b", "waiting.js")]);
|
||||||
|
const b = { name: "b", got: undefined };
|
||||||
|
assert.deepEqual([...loaded.values()], [{ name: "a", got: b }, b]);
|
||||||
|
assert.deepEqual(logger.warnings, []);
|
||||||
|
});
|
||||||
|
it("should resolve after loading finished", async function() {
|
||||||
|
const pluginInfo = info("test", "function.js");
|
||||||
|
await load([pluginInfo, info("b", "waiting.js")]);
|
||||||
|
const { plugins } = controller.loadedWith;
|
||||||
|
assert.deepEqual(await plugins.waitFor("b"), { name: "b", got: undefined });
|
||||||
|
assert.equal(await plugins.waitFor("missing"), undefined);
|
||||||
|
assert.deepEqual(logger.warnings, ["Plugin test waited for plugin missing which is not loaded"]);
|
||||||
|
});
|
||||||
|
it("should resolve undefined with a warning once loading finishes without the plugin", async function() {
|
||||||
|
const installed = [info("off", "function.js")];
|
||||||
|
const waiting = info("a", "waiting.js", { waitFor: "off", timeoutMs: 60_000 });
|
||||||
|
const { loaded } = await load([waiting], { installed });
|
||||||
|
assert.deepEqual(loaded.get(waiting), { name: "a", got: undefined });
|
||||||
|
assert.deepEqual(logger.warnings, ["Plugin a waited for plugin off which is not loaded"]);
|
||||||
|
});
|
||||||
|
it("should resolve undefined with a warning if the plugin failed", async function() {
|
||||||
|
const waiting = info("a", "waiting.js", { waitFor: "b", timeoutMs: 60_000 });
|
||||||
|
const { loaded } = await load([waiting, info("b", "throwing.js")], { continueOnError: true });
|
||||||
|
assert.deepEqual(loaded.get(waiting), { name: "a", got: undefined });
|
||||||
|
assert.deepEqual(logger.warnings, ["Plugin a waited for plugin b which is not loaded"]);
|
||||||
|
});
|
||||||
|
it("should break a wait cycle with the timeout", async function() {
|
||||||
|
const { loaded } = await load([
|
||||||
|
info("a", "waiting.js", { waitFor: "b", timeoutMs: 10 }),
|
||||||
|
info("b", "waiting.js", { waitFor: "a", timeoutMs: 60_000 }),
|
||||||
|
]);
|
||||||
|
const a = { name: "a", got: undefined };
|
||||||
|
assert.deepEqual([...loaded.values()], [a, { name: "b", got: a }]);
|
||||||
|
assert.deepEqual(logger.warnings, ["Plugin a timed out after 10ms waiting for plugin b"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("plugins.checkInstalled()", function() {
|
||||||
|
it("should check the installed list", async function() {
|
||||||
|
const pluginInfo = info("test", "function.js");
|
||||||
|
await load([pluginInfo], { installed: [pluginInfo, { name: "off" }] });
|
||||||
|
const { plugins } = controller.loadedWith;
|
||||||
|
assert.equal(plugins.checkInstalled("test"), true);
|
||||||
|
assert.equal(plugins.checkInstalled("off"), true);
|
||||||
|
assert.equal(plugins.checkInstalled("missing"), false);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
+7
-118
@@ -5,7 +5,6 @@ import { pathToFileURL } from "node:url";
|
|||||||
|
|
||||||
import * as mock from "../mock.js";
|
import * as mock from "../mock.js";
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import { BaseControllerPlugin } from "@clusterio/controller";
|
|
||||||
import { computePluginStatuses, planUpdate } from "../../packages/web_ui/src/util/plugin_status.ts";
|
import { computePluginStatuses, planUpdate } from "../../packages/web_ui/src/util/plugin_status.ts";
|
||||||
|
|
||||||
|
|
||||||
@@ -105,10 +104,13 @@ describe("lib/plugin_loader", function() {
|
|||||||
assert.equal(pluginInfo.packagePath, path.join(packageDir, "package.json"));
|
assert.equal(pluginInfo.packagePath, path.join(packageDir, "package.json"));
|
||||||
|
|
||||||
const controller = new mock.MockController();
|
const controller = new mock.MockController();
|
||||||
await lib.loadPlugin(
|
await lib.PluginLoader.load({
|
||||||
pluginInfo, "controller", { controller, metrics: {}, logger: new mock.MockLogger() },
|
type: "controller",
|
||||||
"ControllerPlugin", BaseControllerPlugin,
|
context: { controller },
|
||||||
);
|
logger: new mock.MockLogger(),
|
||||||
|
installed: [pluginInfo],
|
||||||
|
load: [pluginInfo],
|
||||||
|
});
|
||||||
assert.equal(controller.loadedNpmPlugin, true);
|
assert.equal(controller.loadedNpmPlugin, true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -165,119 +167,6 @@ describe("lib/plugin_loader", function() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe("loadPlugin()", function() {
|
|
||||||
const baseDir = path.join("temp", "test", "plugin");
|
|
||||||
const functionPlugin = path.resolve(baseDir, "function_plugin");
|
|
||||||
const classPlugin = path.resolve(baseDir, "class_plugin");
|
|
||||||
const throwingClassPlugin = path.resolve(baseDir, "throwing_class_plugin");
|
|
||||||
const missingClassPlugin = path.resolve(baseDir, "missing_class_plugin");
|
|
||||||
const wrongParentClassPlugin = path.resolve(baseDir, "wrong_parent_class_plugin");
|
|
||||||
let controller;
|
|
||||||
let logger;
|
|
||||||
let context;
|
|
||||||
|
|
||||||
before(async function() {
|
|
||||||
async function writeEntrypoint(pluginPath, content) {
|
|
||||||
await fs.mkdir(pluginPath, { recursive: true });
|
|
||||||
await fs.writeFile(path.join(pluginPath, "controller.js"), content);
|
|
||||||
}
|
|
||||||
|
|
||||||
await writeEntrypoint(functionPlugin, `
|
|
||||||
export default async function(context) {
|
|
||||||
context.controller.loadedWith = context;
|
|
||||||
return { api: true };
|
|
||||||
}
|
|
||||||
`);
|
|
||||||
await writeEntrypoint(classPlugin, `
|
|
||||||
import { BaseControllerPlugin } from "@clusterio/controller";
|
|
||||||
export class ControllerPlugin extends BaseControllerPlugin {
|
|
||||||
async init() { this.controller.loadedWith = this; }
|
|
||||||
async onSaveData() { }
|
|
||||||
}
|
|
||||||
`);
|
|
||||||
await writeEntrypoint(throwingClassPlugin, `
|
|
||||||
import { BaseControllerPlugin } from "@clusterio/controller";
|
|
||||||
export class ControllerPlugin extends BaseControllerPlugin {
|
|
||||||
async init() { throw new Error("init failed"); }
|
|
||||||
async onSaveData() { }
|
|
||||||
}
|
|
||||||
`);
|
|
||||||
await writeEntrypoint(missingClassPlugin, "");
|
|
||||||
await writeEntrypoint(wrongParentClassPlugin, "export class ControllerPlugin {};\n");
|
|
||||||
});
|
|
||||||
|
|
||||||
beforeEach(function() {
|
|
||||||
controller = new mock.MockController();
|
|
||||||
logger = new mock.MockLogger();
|
|
||||||
logger.warnings = [];
|
|
||||||
logger.warn = msg => logger.warnings.push(msg);
|
|
||||||
context = { controller, metrics: {}, logger };
|
|
||||||
});
|
|
||||||
|
|
||||||
function info(requirePath, entrypoint = "controller.js") {
|
|
||||||
return {
|
|
||||||
name: "test",
|
|
||||||
requirePath,
|
|
||||||
packagePath: path.join(requirePath, "package.json"),
|
|
||||||
controllerEntrypoint: entrypoint,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
it("should do nothing when the entrypoint is not set", async function() {
|
|
||||||
await lib.loadPlugin(
|
|
||||||
{ name: "test", requirePath: missingClassPlugin }, "controller", context,
|
|
||||||
"ControllerPlugin", BaseControllerPlugin,
|
|
||||||
);
|
|
||||||
assert.equal(controller.loadedWith, undefined);
|
|
||||||
});
|
|
||||||
it("should call the default export with the load context", async function() {
|
|
||||||
const pluginInfo = info(functionPlugin);
|
|
||||||
const result = await lib.loadPlugin(
|
|
||||||
pluginInfo, "controller", context, "ControllerPlugin", BaseControllerPlugin,
|
|
||||||
);
|
|
||||||
assert.deepEqual(result, { api: true });
|
|
||||||
assert.equal(controller.loadedWith.controller, controller);
|
|
||||||
assert.equal(controller.loadedWith.plugin, pluginInfo);
|
|
||||||
assert.equal(controller.loadedWith.logger, logger);
|
|
||||||
assert.deepEqual(logger.warnings, []);
|
|
||||||
});
|
|
||||||
it("should load a deprecated class export", async function() {
|
|
||||||
const pluginInfo = info(classPlugin);
|
|
||||||
const result = await lib.loadPlugin(
|
|
||||||
pluginInfo, "controller", context, "ControllerPlugin", BaseControllerPlugin,
|
|
||||||
);
|
|
||||||
assert.equal(result, controller.loadedWith);
|
|
||||||
assert(controller.loadedWith instanceof BaseControllerPlugin);
|
|
||||||
assert.equal(controller.loadedWith.info, pluginInfo);
|
|
||||||
assert.deepEqual([...controller.hooks.save.attached], ["test"]);
|
|
||||||
assert.deepEqual(logger.warnings, ["Plugin test is using deprecated class export"]);
|
|
||||||
});
|
|
||||||
it("should detach hooks if init throws", async function() {
|
|
||||||
await assert.rejects(
|
|
||||||
lib.loadPlugin(
|
|
||||||
info(throwingClassPlugin), "controller", context, "ControllerPlugin", BaseControllerPlugin
|
|
||||||
),
|
|
||||||
new Error("init failed")
|
|
||||||
);
|
|
||||||
assert.equal(controller.hooks.size, 0);
|
|
||||||
});
|
|
||||||
it("should throw if neither a function nor a class is exported", async function() {
|
|
||||||
await assert.rejects(
|
|
||||||
lib.loadPlugin(
|
|
||||||
info(missingClassPlugin), "controller", context, "ControllerPlugin", BaseControllerPlugin
|
|
||||||
),
|
|
||||||
new Error("Plugin test must export either a default function or ControllerPlugin class")
|
|
||||||
);
|
|
||||||
});
|
|
||||||
it("should throw if the class is not a subclass of the base class", async function() {
|
|
||||||
await assert.rejects(
|
|
||||||
lib.loadPlugin(
|
|
||||||
info(wrongParentClassPlugin), "controller", context, "ControllerPlugin", BaseControllerPlugin
|
|
||||||
),
|
|
||||||
new Error("Expected ControllerPlugin exported from test to extend BaseControllerPlugin")
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
describe("loadPluginList()", async function() {
|
describe("loadPluginList()", async function() {
|
||||||
const old_cwd = process.cwd();
|
const old_cwd = process.cwd();
|
||||||
const baseDir = path.join("temp", "test", "plugin_list");
|
const baseDir = path.join("temp", "test", "plugin_list");
|
||||||
|
|||||||
Reference in new issue
Block a user