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:
committed 2026-09-11 22:49:09 +00:00
1 parent 8c03ac15ab
commit 7122cbccf8
64 files changed
+1878 -1184

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
import assert from "node:assert/strict";
import * as mock from "../mock.js";
import * as lib from "@clusterio/lib";
describe("lib/AsyncHook", function() {
describe("class AsyncHook", function() {
let logger;
let hook;
beforeEach(function() {
logger = new mock.MockLogger();
logger.errors = [];
logger.error = msg => logger.errors.push(msg);
hook = new lib.AsyncHook(logger);
});
it("should track attached handlers", function() {
assert.equal(hook.size, 0);
hook.attach("alpha", () => {});
hook.attach("beta", () => {});
assert.equal(hook.size, 2);
assert.deepEqual([...hook.attached], ["alpha", "beta"]);
});
it("should reject duplicate handler names", function() {
hook.attach("alpha", () => {});
assert.throws(
() => hook.attach("alpha", () => {}),
new Error("Handler with name alpha is already attached")
);
});
it("should detach handlers", async function() {
let called = false;
hook.attach("alpha", () => { called = true; });
hook.detach("alpha");
hook.detach("missing");
await hook.invoke();
assert.equal(called, false);
assert.equal(hook.size, 0);
});
it("should clear all handlers", function() {
hook.attach("alpha", () => {});
hook.attach("beta", () => {});
hook.clear();
assert.equal(hook.size, 0);
});
it("should invoke all handlers with the given arguments", async function() {
let calls = [];
hook.attach("alpha", (a, b) => { calls.push(["alpha", a, b]); });
hook.attach("beta", async (a, b) => { calls.push(["beta", a, b]); });
await hook.invoke(1, "two");
assert.deepEqual(calls, [["alpha", 1, "two"], ["beta", 1, "two"]]);
});
it("should log and ignore errors thrown by handlers", async function() {
let betaCalled = false;
hook.attach("alpha", () => { throw new Error("sync"); });
hook.attach("beta", async () => { betaCalled = true; });
hook.attach("gamma", async () => { throw new Error("async"); });
await hook.invoke();
assert(betaCalled, "beta was not called");
assert.equal(logger.errors.length, 2);
assert(logger.errors[0].startsWith('Ignoring error in hook "alpha":'), logger.errors[0]);
assert(logger.errors[1].startsWith('Ignoring error in hook "gamma":'), logger.errors[1]);
});
it("should time out handlers that never resolve", async function() {
hook = new lib.AsyncHook(logger, 10);
hook.attach("stuck", () => new Promise(() => {}));
hook.attach("fast", () => 1);
assert.deepEqual(await hook.collect(), [1]);
assert.equal(logger.errors.length, 1);
assert(logger.errors[0].includes("Hook stuck timed out after 10ms"), logger.errors[0]);
});
it("should collect results from handlers", async function() {
hook.attach("alpha", arg => arg);
hook.attach("beta", () => undefined);
hook.attach("gamma", async arg => arg * 2);
hook.attach("delta", () => { throw new Error("Test"); });
assert.deepEqual(await hook.collect(21), [21, 42]);
});
it("should collect results with their source", async function() {
hook.attach("alpha", arg => arg);
hook.attach("beta", () => undefined);
hook.attach("gamma", async arg => arg * 2);
assert.deepEqual(await hook.collectEntries(21), [["alpha", 21], ["gamma", 42]]);
});
it("should provide a stable listener bound to the hook", async function() {
let calls = [];
hook.attach("alpha", arg => { calls.push(arg); });
const { listener } = hook;
assert.equal(listener, hook.listener);
await listener("value");
assert.deepEqual(calls, ["value"]);
});
});
describe("class AsyncHookCollection", function() {
class TestHooks extends lib.AsyncHookCollection {
constructor(logger) {
super(logger);
this.first = this.newHook();
this.second = this.newHook();
}
}
let hooks;
beforeEach(function() {
hooks = new TestHooks(new mock.MockLogger());
});
it("should count each name once across hooks", function() {
hooks.first.attach("alpha", () => {});
hooks.second.attach("alpha", () => {});
hooks.second.attach("beta", () => {});
assert.equal(hooks.size, 2);
assert.deepEqual([...hooks.attached], ["alpha", "beta"]);
});
it("should detach a name from all hooks", function() {
hooks.first.attach("alpha", () => {});
hooks.second.attach("alpha", () => {});
hooks.second.attach("beta", () => {});
hooks.detachAll("alpha");
assert.equal(hooks.first.size, 0);
assert.deepEqual([...hooks.second.attached], ["beta"]);
});
it("should clear all hooks", function() {
hooks.first.attach("alpha", () => {});
hooks.second.attach("beta", () => {});
hooks.clearAll();
assert.equal(hooks.size, 0);
});
});
});
-36
View File
@@ -1,36 +0,0 @@
import assert from "node:assert/strict";
import * as mock from "../mock.js";
import * as lib from "@clusterio/lib";
describe("lib/plugin", function() {
describe("invokeHook()", function() {
let betaTestCalled = false;
let plugins = new Map([
["alpha", {
test: async function() { },
pass: async function(arg) { return arg; },
error: async function() { throw new Error("Test"); },
logger: new mock.MockLogger(),
}],
["beta", {
test: async function() { betaTestCalled = true; },
pass: async function() { },
error: async function() { },
logger: new mock.MockLogger(),
}],
]);
it("should invoke the hook on the plugin", async function() {
await lib.invokeHook(plugins, "test");
assert(betaTestCalled, "Hook was not called");
});
it("should pass and return args", async function() {
let result = await lib.invokeHook(plugins, "pass", 1234);
assert.deepEqual(result, [1234]);
});
it("should ignore errors", async function() {
await lib.invokeHook(plugins, "error");
});
});
});
+89 -35
View File
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import * as mock from "../mock.js";
import * as lib from "@clusterio/lib";
import { BaseControllerPlugin } from "@clusterio/controller";
@@ -72,51 +73,104 @@ describe("lib/plugin_loader", function() {
);
});
});
describe("loadPluginClass()", function() {
let baseDir = path.join("temp", "test", "plugin");
let missingClass = path.join(baseDir, "missing_class_plugin");
let wrongParentClass = path.join(baseDir, "wrong_parent_class_plugin");
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(missingClass, "");
await writeEntrypoint(
wrongParentClass, "export class ControllerPlugin {};\n"
await writeEntrypoint(functionPlugin, `
export default async function(context) {
context.controller.loadedWith = context;
}
`);
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, 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);
await lib.loadPlugin(pluginInfo, "controller", context, "ControllerPlugin", BaseControllerPlugin);
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);
await lib.loadPlugin(pluginInfo, "controller", context, "ControllerPlugin", BaseControllerPlugin);
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 class is missing from entrypoint", async function() {
const requirePath = path.resolve(missingClass);
it("should throw if the class is not a subclass of the base class", async function() {
await assert.rejects(
lib.loadPluginClass(
"test",
path.posix.join(requirePath, "controller.js"),
"ControllerPlugin",
BaseControllerPlugin,
lib.loadPlugin(
info(wrongParentClassPlugin), "controller", context, "ControllerPlugin", BaseControllerPlugin
),
{
message:
`PluginError: Expected ${path.posix.join(requirePath, "controller.js")} ` +
"to export a class named ControllerPlugin",
}
);
});
it("should throw if class is not a subclass of BaseControllerPlugin", async function() {
const requirePath = path.resolve(wrongParentClass);
await assert.rejects(
lib.loadPluginClass(
"test",
path.posix.join(requirePath, "controller.js"),
"ControllerPlugin",
BaseControllerPlugin,
),
{
message:
"PluginError: Expected ControllerPlugin exported from " +
`${path.posix.join(requirePath, "controller.js")} to be a subclass of BaseControllerPlugin`,
}
new Error("Expected ControllerPlugin exported from test to extend BaseControllerPlugin")
);
});
});