Write plugins without state shared elsewhere as functions (#492)

The instance plugins of exp_groups, exp_reports, exp_roles, exp_scenario
and exp_server_ups, and the controller plugins of exp_reports and
exp_scenario, were classes only to hold their handlers. They are now
init functions with closures, like clusterio's own plugins.

The exp_roles and exp_groups controller plugins stay classes because
exp_scenario reaches their datastores through get(controller).
AutoRestart stays a class because its tests step check() with a fake
clock.

Tests spy on handle() and the hooks to call the handlers. The reports
webhook tests stub fetch instead of replacing postWebhook, and the
feature reconcile test writes the stored records to disk before start.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
BastiaanandClaude Opus 5.5 authored and GitHub committed 2026-10-13 21:50:15 +01:00
1 parent 26a801da5e
commit 68a964cf57
12 files changed
+709 -820

No files matched your search

+54 -90
View File
@@ -1,4 +1,4 @@
import type { Instance, InstancePluginContext } from "@clusterio/host";
import type { InstancePluginContext } from "@clusterio/host";
import * as lib from "@clusterio/lib";
import * as messages from "./messages.js";
@@ -9,118 +9,82 @@ export type IpcAssignmentUpdate = {
unassign: number[] | undefined,
};
export class InstancePlugin {
private constructor(
public instance: Instance,
public logger: lib.Logger,
public name: string,
) {}
export default async function (context: InstancePluginContext) {
const { instance, logger, plugin } = context;
const syncMode = () => instance.config.get("exp_roles.sync_mode");
static async fromContext(context: InstancePluginContext) {
const instance = context.instance;
const plugin = new InstancePlugin(instance, context.logger, context.plugin.name);
instance.handle(messages.RoleUpdatedEvent, plugin.handleRoleUpdatedEvent.bind(plugin));
instance.handle(messages.AssignmentUpdatedEvent, plugin.handleAssignmentUpdatedEvent.bind(plugin));
instance.server.handle("exp_roles:assignment_update", plugin.handleAssignmentUpdateIPC.bind(plugin));
const hooks = instance.hooks;
hooks.instanceConfigFieldChanged.attach(plugin.name, plugin.onInstanceConfigFieldChanged.bind(plugin));
hooks.start.attach(plugin.name, plugin.onStart.bind(plugin));
return plugin;
async function luaSend(receiver: string, json: any) {
await instance.sendRcon(
`/sc exp_roles.${receiver}(helpers.json_to_table[=[${JSON.stringify(json)}]=])`, true
);
}
get syncMode() {
return this.instance.config.get("exp_roles.sync_mode");
}
async onInstanceConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
switch (field) {
case "exp_roles.sync_mode":
await this.luaSetEmitEvents(curr === "bidirectional");
break;
instance.handle(messages.RoleUpdatedEvent, async event => {
if (syncMode() !== "disabled") {
await luaSend("receive_role_updates", event.updates.map(role => role.toJSON()));
}
}
});
async onStart() {
if (this.syncMode === "disabled") {
instance.handle(messages.AssignmentUpdatedEvent, async event => {
if (syncMode() !== "disabled") {
await luaSend("receive_assignment_updates", event.updates.map(a => a.toJSON()));
}
});
instance.server.handle("exp_roles:assignment_update", async (event: IpcAssignmentUpdate) => {
if (syncMode() !== "bidirectional") {
return;
}
const assign = event.assign ?? [];
try {
await instance.sendTo("controller", new messages.AssignmentUpdateRequest(
event.name, assign, event.unassign ?? [],
));
} catch (err: any) {
// The roles were already applied in game, so they have to be taken
// back off again now that the controller has refused them
logger.warn(`Role change for ${event.name} was rejected: ${err.message}`);
if (assign.length) {
await luaSend("reject_assignment", { name: event.name, role_ids: assign });
}
}
});
instance.hooks.instanceConfigFieldChanged.attach(plugin.name, async (field, curr) => {
if (field === "exp_roles.sync_mode") {
await luaSend("set_emit_events", curr === "bidirectional");
}
});
instance.hooks.start.attach(plugin.name, async () => {
if (syncMode() === "disabled") {
return;
}
// Date.now() is used because the lua state is initialised from the full
// list below, so only updates made after this point are of interest
const subscribedAtMs = Date.now();
await this.instance.sendTo("controller", new lib.SubscriptionRequest(
await instance.sendTo("controller", new lib.SubscriptionRequest(
`exp_roles:${messages.RoleUpdatedEvent.name}`, true, subscribedAtMs
));
await this.instance.sendTo("controller", new lib.SubscriptionRequest(
await instance.sendTo("controller", new lib.SubscriptionRequest(
`exp_roles:${messages.AssignmentUpdatedEvent.name}`, true, subscribedAtMs
));
const [roles, assignments] = await Promise.all([
this.instance.sendTo("controller", new messages.RoleListRequest()),
this.instance.sendTo("controller", new messages.AssignmentListRequest()),
instance.sendTo("controller", new messages.RoleListRequest()),
instance.sendTo("controller", new messages.AssignmentListRequest()),
]);
if (!roles.some(role => role.isDefault)) {
this.logger.warn("No default role is set on the controller, players will hold no roles in game");
logger.warn("No default role is set on the controller, players will hold no roles in game");
}
await this.luaSend("initialise", {
await luaSend("initialise", {
...messages.encodeRolesForLua(roles),
assignments: assignments.map(assignment => assignment.toJSON()),
});
await this.luaSetEmitEvents(this.syncMode === "bidirectional");
}
async handleRoleUpdatedEvent(event: messages.RoleUpdatedEvent) {
if (this.syncMode === "disabled") {
return;
}
await this.luaSend("receive_role_updates", event.updates.map(role => role.toJSON()));
}
async handleAssignmentUpdatedEvent(event: messages.AssignmentUpdatedEvent) {
if (this.syncMode === "disabled") {
return;
}
await this.luaSend("receive_assignment_updates", event.updates.map(a => a.toJSON()));
}
async handleAssignmentUpdateIPC(event: IpcAssignmentUpdate) {
if (this.syncMode !== "bidirectional") {
return;
}
const assign = event.assign ?? [];
try {
await this.instance.sendTo("controller", new messages.AssignmentUpdateRequest(
event.name, assign, event.unassign ?? [],
));
} catch (err: any) {
// The roles were already applied in game, so they have to be taken
// back off again now that the controller has refused them
this.logger.warn(`Role change for ${event.name} was rejected: ${err.message}`);
if (assign.length) {
await this.luaSend("reject_assignment", { name: event.name, role_ids: assign });
}
return;
}
}
async luaSetEmitEvents(emitEvents: boolean) {
await this.luaSend("set_emit_events", emitEvents);
}
async luaSend(receiver: string, json: any) {
await this.instance.sendRcon(
`/sc exp_roles.${receiver}(helpers.json_to_table[=[${JSON.stringify(json)}]=])`, true
);
}
}
export default async function (context: InstancePluginContext) {
await InstancePlugin.fromContext(context);
await luaSend("set_emit_events", syncMode() === "bidirectional");
});
}