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

+184
View File
@@ -0,0 +1,184 @@
import { logger } from "./logging.js";
import * as libHelpers from "./helpers.js";
export type HookHandler<Args extends unknown[], Result = void> = (...args: Args) => Result | Promise<Result>;
export class AsyncHook<
Args extends unknown[],
Result = void,
> {
private static readonly _timeoutToken = Symbol("timeout");
private _handlers = new Map<string, HookHandler<Args, Result>>();
constructor(
private _logger = logger,
private _timeoutMs = 15_000,
) { }
get size() {
return this._handlers.size;
}
get attached() {
return this._handlers.keys();
}
/**
* Stable event listener reference bound to this hook instance.
*
* This function is pre-bound and guaranteed to remain referentially stable
* for the lifetime of the hook instance. It can safely be passed directly
* into event emitters (e.g. EventEmitter.on / off) without losing context
* or requiring re-binding.
*
* Example:
* `eventEmitter.on("change", hook.listener);`
*/
readonly listener = this.invoke.bind(this);
/**
* Attach a handler to this hook.
*
* An error is thrown if another handler with the same name is already attached.
*/
attach(
name: string,
handler: HookHandler<Args, Result>,
) {
if (this._handlers.has(name)) {
throw new Error(`Handler with name ${name} is already attached`);
}
this._handlers.set(name, handler);
}
/**
* Remove a previously attached handler.
*
* If no handler exists, then no action is performed.
*/
detach(name: string) {
this._handlers.delete(name);
}
/**
* Remove all attached handlers.
*/
clear() {
this._handlers.clear();
}
private async _invokeHandler(
name: string,
handler: HookHandler<Args, Result>,
args: Args,
): Promise<Result | undefined> {
try {
const result = await libHelpers.timeout<
Result | typeof AsyncHook._timeoutToken
>(
Promise.resolve(handler(...args)),
this._timeoutMs,
AsyncHook._timeoutToken,
);
if (result === AsyncHook._timeoutToken) {
throw new Error(`Hook ${name} timed out after ${this._timeoutMs}ms`);
}
return result;
} catch (err: any) {
this._logger.error(`Ignoring error in hook "${name}":\n${err?.stack ?? err}`);
return undefined;
}
}
/**
* Invoke all handlers attached to this hook.
*
* Any return values are discarded.
*/
async invoke(...args: Args): Promise<void> {
await Promise.all(
[...this._handlers.entries()].map(
([name, handler]) => this._invokeHandler(name, handler, args)
)
);
}
/**
* Invoke all handlers attached to this hook.
*
* Returns all successful results.
*/
async collect(...args: Args): Promise<Result[]> {
const results = await Promise.all(
[...this._handlers.entries()].map(
([name, handler]) => this._invokeHandler(name, handler, args)
)
);
return results.filter(
(result): result is Awaited<Result> => result !== undefined
);
}
/**
* Invoke all handlers attached to this hook.
*
* Returns all successful results and their source.
*/
async collectEntries(...args: Args): Promise<[string, Result][]> {
const results = await Promise.all(
[...this._handlers.entries()].map(async ([name, handler]) => {
const result = await this._invokeHandler(name, handler, args);
return result !== undefined ? [name, result] as [string, Result] : undefined;
})
);
return results.filter(
(entry): entry is [string, Result] => entry !== undefined
);
}
}
export class AsyncHookCollection {
private hooks: AsyncHook<any[], any>[] = [];
constructor(
private _logger = logger,
) {}
protected newHook<
Args extends unknown[],
Result = void,
> (
_logger = this._logger
) {
const hook = new AsyncHook<Args, Result>(_logger);
this.hooks.push(hook);
return hook;
}
get size() {
const attached = new Set(this.hooks.flatMap(hook => [...hook.attached]));
return attached.size;
}
get attached() {
const attached = new Set(this.hooks.flatMap(hook => [...hook.attached]));
return attached.values();
}
detachAll(name: string) {
for (const hook of this.hooks) {
hook.detach(name);
}
}
clearAll() {
for (const hook of this.hooks) {
hook.clear();
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { Type, Static } from "@sinclair/typebox";
import { jsonArray } from "./composites.js";
import { PluginNodeEnvInfo } from "../plugin.js";
import type { PluginNodeEnvInfo } from "../plugin.js";
/* This is similar to other plugin definitions but with lots removed */
export class PluginDetails {
+54
View File
@@ -0,0 +1,54 @@
// 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`);
}
await init(context);
}
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>;
}
+21 -40
View File
@@ -2,7 +2,6 @@
* Plugin interfaces and utilities.
* @module lib/plugin
*/
import * as libHelpers from "./helpers.js";
import type { Logger } from "./logging.js";
import type { FieldDefinition } from "./config/index.js";
import type { PermissionDefinition } from "./permissions.js";
@@ -90,42 +89,24 @@ export interface PlayerEvent {
stats: PlayerStats,
}
/**
* Invokes the given hook on all plugins
*
* @param plugins -
* Mapping of plugin names to plugins to invoke the hook on.
* @param hook - Name of hook to invoke.
* @param args - Arguments to pass on to the hook.
* @returns Non-undefined return values from the hooks.
*/
export async function invokeHook<
Hook extends string,
R,
Args extends [...any],
Plugin extends { logger: Logger } & Record<Hook, (...hookArgs: Args) => R | Promise<R>>
>(
plugins: Map<string, Plugin>,
hook: Hook,
...args: Args
): Promise<Exclude<Awaited<ReturnType<Plugin[Hook]>>, void>[]> {
let results: any[] = [];
for (let [name, plugin] of plugins) {
try {
const timeout = Symbol("timeout-token");
let result = await libHelpers.timeout<R | typeof timeout>(
plugin[hook](...args) as Promise<R>,
15000,
timeout
);
if (result === timeout) {
throw new Error(`Invoking hook ${hook} timed out for plugin ${name}`);
} else if (result !== undefined) {
results.push(result);
}
} catch (err: any) {
plugin.logger.error(`Ignoring error from plugin ${name} in ${hook}:\n${err.stack}`);
}
}
return results;
}
export type PluginLoadContext<
Context extends object,
Info extends PluginDeclaration = PluginNodeEnvInfo
> = Context & {
logger: Logger;
plugin: Info;
};
export type PluginClass<
Context extends object,
Info extends PluginDeclaration,
> = {
new (...args: any[]): any;
fromContext(context: PluginLoadContext<Context, Info>): {
init(): Promise<void>;
detachHooks(): void;
};
};
export type PluginType =
Extract<keyof PluginDeclaration, `${string}Entrypoint`> extends `${infer P}Entrypoint` ? P : never;
+37 -17
View File
@@ -8,7 +8,8 @@ import fs from "node:fs/promises";
import { fileURLToPath, pathToFileURL } from "node:url";
import * as libErrors from "./errors.js";
import * as libPlugin from "./plugin.js";
import { logger } from "./logging.js";
import { type Logger, logger } from "./logging.js";
import { loadPluginEntrypoint, loadPluginClass } from "./loadPlugin.js";
/**
@@ -88,22 +89,41 @@ export async function loadPluginInfos(pluginList: Map<string, string>) {
return plugins;
}
export async function loadPluginClass<Class extends { new (...args: any): any }>(
pluginName: string,
requirePath: string,
className: string,
pluginClass: Class,
): Promise<Class> {
let entrypoint = await import(pathToFileURL(requirePath).href);
if (!entrypoint[className]) {
throw new libErrors.PluginError(pluginName,
new Error(`Expected ${requirePath} to export a class named ${className}`)
);
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;
}
if (!(entrypoint[className].prototype instanceof pluginClass)) {
throw new libErrors.PluginError(pluginName,
new Error(`Expected ${className} exported from ${requirePath} to be a subclass of ${pluginClass.name}`)
);
const module = await import(pathToFileURL(path.posix.join(pluginInfo.requirePath, requirePath)).href);
const pluginContext: libPlugin.PluginLoadContext<Context> = {
...context,
plugin: pluginInfo,
logger: context.logger.child({ plugin: pluginInfo.name }),
};
if (typeof module.default === "function") {
await loadPluginEntrypoint(pluginInfo, pluginType, pluginContext, module);
return;
}
return entrypoint[className];
// migrate: accept plugins which export classes
if (module[exportName]) {
pluginContext.logger.warn(`Plugin ${pluginInfo.name} is using deprecated class export`);
await loadPluginClass(pluginInfo, pluginType, pluginContext, module, exportName, baseClass);
return;
}
throw new Error(`Plugin ${pluginInfo.name} must export either a default function or ${exportName} class`);
}
+1 -1
View File
@@ -3,7 +3,7 @@ import path from "path";
import { exec } from "child_process";
import { logger } from "./logging.js";
import { RequestError } from "./errors.js";
import { PluginNodeEnvInfo } from "./plugin.js";
import type { PluginNodeEnvInfo } from "./plugin.js";
const execAsync = util.promisify(exec);
function isDev() {