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

+96 -124
View File
@@ -1,6 +1,6 @@
import * as lib from "@clusterio/lib";
import * as path from "node:path";
import type { Controller, ControllerPluginContext } from "@clusterio/controller";
import type { ControllerPluginContext } from "@clusterio/controller";
import { RoleMetaRecord } from "@expcluster/roles";
import { GroupRecord, GroupPermissions, RoleMappingRecord } from "@expcluster/permission-groups";
import { ControllerPlugin as RolesPlugin } from "@expcluster/roles/dist/node/controller.js";
@@ -9,149 +9,55 @@ import * as messages from "./messages.js";
import { features, pruneFeatureValues, validateFeatureValues } from "./features.js";
import { SeedRole, SeedGroup, seedRoles, seedGroups, flattenSeedPermissions } from "./seed.js";
export class ControllerPlugin {
private constructor(
public controller: Controller,
public logger: lib.Logger,
public name: string,
public features: lib.SubscribableDatastore<messages.FeatureRecord>,
) {}
static async fromContext(context: ControllerPluginContext) {
const controller = context.controller;
const databaseDirectory = controller.config.get("controller.database_directory");
const features = new lib.SubscribableDatastore(
...await new lib.JsonIdDatastoreProvider(
path.join(databaseDirectory, "exp_scenario", "features.json"),
messages.FeatureRecord.fromJSON.bind(messages.FeatureRecord),
).bootstrap()
);
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, features);
plugin.reconcileFeatures();
controller.subscriptions.handle(messages.FeatureUpdatedEvent, plugin.handleFeatureSubscription.bind(plugin));
features.on("update", plugin.featuresUpdated.bind(plugin));
controller.handle(messages.SeedRequest, plugin.handleSeedRequest.bind(plugin));
controller.handle(messages.FeatureListRequest, plugin.handleFeatureListRequest.bind(plugin));
controller.handle(messages.FeatureUpdateRequest, plugin.handleFeatureUpdateRequest.bind(plugin));
controller.hooks.shutdown.attach(plugin.name, plugin.onShutdown.bind(plugin));
return plugin;
}
async onShutdown() {
await this.features.save();
}
export default async function (context: ControllerPluginContext) {
const { controller, logger, plugin } = context;
const databaseDirectory = controller.config.get("controller.database_directory");
const featureStore = new lib.SubscribableDatastore(
...await new lib.JsonIdDatastoreProvider(
path.join(databaseDirectory, "exp_scenario", "features.json"),
messages.FeatureRecord.fromJSON.bind(messages.FeatureRecord),
).bootstrap()
);
/** Add new features, delete removed ones, and drop stored values which no longer fit a field */
reconcileFeatures() {
function reconcileFeatures() {
const declared = new Map(features.map(feature => [feature.name, feature]));
for (const record of this.features.values()) {
for (const record of featureStore.values()) {
const feature = declared.get(record.id);
if (!feature) {
this.logger.warn(`Dropping stored config of removed feature ${record.id}`);
this.features.delete(record);
logger.warn(`Dropping stored config of removed feature ${record.id}`);
featureStore.delete(record);
continue;
}
const { kept, dropped } = pruneFeatureValues(feature, record.values);
if (dropped.length) {
this.logger.warn(`Dropping stored values of ${record.id} which no longer match a setting: ${dropped.join(", ")}`);
this.features.set(new messages.FeatureRecord(record.id, record.enabled, kept));
logger.warn(`Dropping stored values of ${record.id} which no longer match a setting: ${dropped.join(", ")}`);
featureStore.set(new messages.FeatureRecord(record.id, record.enabled, kept));
}
}
const missing = features.filter(feature => !this.features.has(feature.name));
const missing = features.filter(feature => !featureStore.has(feature.name));
if (missing.length) {
this.features.setMany(missing.map(feature => new messages.FeatureRecord(feature.name, true)));
featureStore.setMany(missing.map(feature => new messages.FeatureRecord(feature.name, true)));
}
}
featuresUpdated(updates: messages.FeatureRecord[]) {
this.controller.subscriptions.broadcast(new messages.FeatureUpdatedEvent(updates));
}
async handleFeatureSubscription(request: lib.SubscriptionRequest) {
const updates = [...this.features.values()].filter(feature => feature.updatedAtMs > request.lastRequestTimeMs);
return updates.length ? new messages.FeatureUpdatedEvent(updates) : null;
}
async handleFeatureListRequest() {
return [...this.features.values()];
}
async handleFeatureUpdateRequest(request: messages.FeatureUpdateRequest) {
let values;
try {
values = validateFeatureValues(request.id, request.values);
} catch (err: any) {
throw new lib.RequestError(err.message);
}
const feature = new messages.FeatureRecord(request.id, request.enabled, values);
this.features.set(feature);
return feature;
}
/**
* Create the roles and permission groups the scenario shipped with.
*
* Roles which already exist by name are reused and only gain the seed
* permissions, groups which already exist by name are reset to the seed.
*/
async handleSeedRequest() {
const rolesPlugin = RolesPlugin.get(this.controller);
const groupsPlugin = GroupsPlugin.get(this.controller);
if (!rolesPlugin || !groupsPlugin) {
throw new lib.RequestError("Seeding requires the exp_roles and exp_groups plugins");
}
const roleIds = new Map<string, number>();
for (const [index, seedRole] of seedRoles.entries()) {
const role = this.seedRole(seedRole);
if (!role) {
continue;
}
roleIds.set(seedRole.name, role.id);
rolesPlugin.roleMeta.set(new RoleMetaRecord(
role.id,
index + 1,
seedRole.priority ?? 0,
seedRole.shortHand,
"",
seedRole.color,
seedRole.autoAssignHours === undefined ? null : seedRole.autoAssignHours * 3600000,
seedRole.blockAutoAssign ?? false,
));
}
const groupIds = new Map<string, number>();
for (const seedGroup of seedGroups) {
groupIds.set(seedGroup.name, this.seedGroup(groupsPlugin, seedGroup).id);
}
this.seedRoleMappings(groupsPlugin, roleIds, groupIds);
this.logger.info(`Seeded ${roleIds.size} roles and ${groupIds.size} permission groups`);
}
/** Find or create the clusterio role for a seed role, returns undefined if it has no role to use. */
seedRole(seedRole: SeedRole) {
const roles = this.controller.roles;
function ensureRole(seedRole: SeedRole) {
const roles = controller.roles;
if (seedRole.isAdmin) {
return roles.get(lib.Role.DefaultAdminRoleId);
}
if (seedRole.isDefault) {
const defaultRoleId = this.controller.config.get("controller.default_role_id");
const defaultRoleId = controller.config.get("controller.default_role_id");
return defaultRoleId !== null ? roles.get(defaultRoleId) : undefined;
}
const permissions = flattenSeedPermissions(seedRole);
for (const permission of permissions) {
if (!lib.permissions.has(permission)) {
this.logger.warn(`Seed role ${seedRole.name} grants unknown permission ${permission}`);
logger.warn(`Seed role ${seedRole.name} grants unknown permission ${permission}`);
}
}
@@ -163,19 +69,19 @@ export class ControllerPlugin {
} else {
const id = Math.max(5, ...[...roles.keys()].map(other => other + 1));
role = new lib.Role(id, seedRole.name, "", permissions);
this.logger.info(`Created role ${seedRole.name}`);
logger.info(`Created role ${seedRole.name}`);
}
roles.set(role);
return role;
}
/** Find or create the permission group for a seed group. */
seedGroup(groupsPlugin: GroupsPlugin, seedGroup: SeedGroup) {
function ensureGroup(groupsPlugin: GroupsPlugin, seedGroup: SeedGroup) {
const permissions = new GroupPermissions(seedGroup.isBlacklist, [...seedGroup.inputActions]);
const existing = [...groupsPlugin.groups.values()].find(other => other.name === seedGroup.name);
const group = new GroupRecord(existing?.id ?? newId(groupsPlugin.groups), seedGroup.name, permissions);
if (!existing) {
this.logger.info(`Created permission group ${seedGroup.name}`);
logger.info(`Created permission group ${seedGroup.name}`);
}
groupsPlugin.groups.set(group);
return group;
@@ -188,7 +94,7 @@ export class ControllerPlugin {
* priorities follow how exp_roles picks a player's highest role: role
* priority first, then the role order.
*/
seedRoleMappings(groupsPlugin: GroupsPlugin, roleIds: Map<string, number>, groupIds: Map<string, number>) {
function seedRoleMappings(groupsPlugin: GroupsPlugin, roleIds: Map<string, number>, groupIds: Map<string, number>) {
// Lowest role first, so the mapping priority rises with the role
const ranked = seedRoles
.filter(seedRole => seedRole.group !== undefined && roleIds.has(seedRole.name))
@@ -227,12 +133,78 @@ export class ControllerPlugin {
}
groupsPlugin.roleMappings.setMany(mappings);
return mappings;
}
}
export default async function (context: ControllerPluginContext) {
await ControllerPlugin.fromContext(context);
reconcileFeatures();
controller.subscriptions.handle(messages.FeatureUpdatedEvent, async request => {
const updates = [...featureStore.values()].filter(feature => feature.updatedAtMs > request.lastRequestTimeMs);
return updates.length ? new messages.FeatureUpdatedEvent(updates) : null;
});
featureStore.on("update", updates => {
controller.subscriptions.broadcast(new messages.FeatureUpdatedEvent(updates));
});
/**
* Create the roles and permission groups the scenario shipped with.
*
* Roles which already exist by name are reused and only gain the seed
* permissions, groups which already exist by name are reset to the seed.
*/
controller.handle(messages.SeedRequest, async () => {
const rolesPlugin = RolesPlugin.get(controller);
const groupsPlugin = GroupsPlugin.get(controller);
if (!rolesPlugin || !groupsPlugin) {
throw new lib.RequestError("Seeding requires the exp_roles and exp_groups plugins");
}
const roleIds = new Map<string, number>();
for (const [index, seed] of seedRoles.entries()) {
const role = ensureRole(seed);
if (!role) {
continue;
}
roleIds.set(seed.name, role.id);
rolesPlugin.roleMeta.set(new RoleMetaRecord(
role.id,
index + 1,
seed.priority ?? 0,
seed.shortHand,
"",
seed.color,
seed.autoAssignHours === undefined ? null : seed.autoAssignHours * 3600000,
seed.blockAutoAssign ?? false,
));
}
const groupIds = new Map<string, number>();
for (const seed of seedGroups) {
groupIds.set(seed.name, ensureGroup(groupsPlugin, seed).id);
}
seedRoleMappings(groupsPlugin, roleIds, groupIds);
logger.info(`Seeded ${roleIds.size} roles and ${groupIds.size} permission groups`);
});
controller.handle(messages.FeatureListRequest, async () => [...featureStore.values()]);
controller.handle(messages.FeatureUpdateRequest, async (request: messages.FeatureUpdateRequest) => {
let values;
try {
values = validateFeatureValues(request.id, request.values);
} catch (err: any) {
throw new lib.RequestError(err.message);
}
const feature = new messages.FeatureRecord(request.id, request.enabled, values);
featureStore.set(feature);
return feature;
});
controller.hooks.shutdown.attach(plugin.name, async () => {
await featureStore.save();
});
}
function newId(datastore: { has(id: number): boolean }) {
+31 -51
View File
@@ -1,63 +1,25 @@
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";
import { features, FeatureValue } from "./features.js";
/** Sends feature config to the lua side, see module/features.lua. */
export class InstancePlugin {
export default async function (context: InstancePluginContext) {
const { instance, plugin } = context;
/** Rcon is up and the lua side can take updates */
started = false;
private constructor(
public instance: Instance,
public logger: lib.Logger,
public name: string,
) {}
static async fromContext(context: InstancePluginContext) {
const instance = context.instance;
const plugin = new InstancePlugin(instance, context.logger, context.plugin.name);
instance.handle(messages.FeatureUpdatedEvent, plugin.handleFeatureUpdatedEvent.bind(plugin));
instance.hooks.start.attach(plugin.name, plugin.onStart.bind(plugin));
instance.hooks.exit.attach(plugin.name, plugin.onExit.bind(plugin));
instance.hooks.controllerConnectionEvent.attach(plugin.name, plugin.onControllerConnectionEvent.bind(plugin));
return plugin;
}
async onStart() {
this.started = true;
await this.syncFeatures();
}
async onExit() {
this.started = false;
}
/** A new session means the controller restarted and forgot the subscription. */
async onControllerConnectionEvent(event: "connect" | "drop" | "resume" | "close") {
if (event === "connect" && this.started) {
await this.syncFeatures();
}
}
let started = false;
/** Subscribe, then send every feature */
async syncFeatures() {
await this.instance.sendTo("controller", new lib.SubscriptionRequest(
async function syncFeatures() {
await instance.sendTo("controller", new lib.SubscriptionRequest(
`exp_scenario:${messages.FeatureUpdatedEvent.name}`, "subscribe", Date.now(),
));
const features = await this.instance.sendTo("controller", new messages.FeatureListRequest());
await this.luaSendFeatures(features);
}
async handleFeatureUpdatedEvent(event: messages.FeatureUpdatedEvent) {
if (this.started) {
await this.luaSendFeatures(event.updates.filter(feature => !feature.isDeleted));
}
const records = await instance.sendTo("controller", new messages.FeatureListRequest());
await luaSendFeatures(records);
}
/** Every value of each feature is sent, so the lua side sets them all */
async luaSendFeatures(records: messages.FeatureRecord[]) {
async function luaSendFeatures(records: messages.FeatureRecord[]) {
if (!records.length) {
return;
}
@@ -75,12 +37,30 @@ export class InstancePlugin {
while (json.includes(`]${level}]`)) {
level += "=";
}
await this.instance.sendRcon(
await instance.sendRcon(
`/sc exp_scenario.features.receive_update(helpers.json_to_table[${level}[${json}]${level}])`, true,
);
}
}
export default async function (context: InstancePluginContext) {
await InstancePlugin.fromContext(context);
instance.handle(messages.FeatureUpdatedEvent, async event => {
if (started) {
await luaSendFeatures(event.updates.filter(feature => !feature.isDeleted));
}
});
instance.hooks.start.attach(plugin.name, async () => {
started = true;
await syncFeatures();
});
instance.hooks.exit.attach(plugin.name, async () => {
started = false;
});
// A new session means the controller restarted and forgot the subscription
instance.hooks.controllerConnectionEvent.attach(plugin.name, async event => {
if (event === "connect" && started) {
await syncFeatures();
}
});
}
+84 -50
View File
@@ -1,7 +1,8 @@
import t from "tap";
import path from "node:path";
import * as lib from "@clusterio/lib";
import { Controller } from "@clusterio/controller";
import { ControllerPlugin } from "../dist/node/controller.js";
import entrypoint from "../dist/node/controller.js";
import * as messages from "../dist/node/messages.js";
import { seedRoles, seedGroups } from "../dist/node/seed.js";
import { features } from "../dist/node/features.js";
@@ -29,7 +30,7 @@ t.after(() => {
lib.logger.silent = false;
});
/** Build the plugin around a real controller, which is side effect free while not started. */
/** Run the plugin on a real controller, which is side effect free while not started, returns the handlers it registered. */
async function startPlugin(t2, { withPlugins = true, databaseDirectory = t2.testdir() } = {}) {
const controllerConfig = new lib.ControllerConfig("controller", {
"controller.database_directory": databaseDirectory,
@@ -45,42 +46,74 @@ async function startPlugin(t2, { withPlugins = true, databaseDirectory = t2.test
}
}
const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_scenario" }, controller, logger });
return { plugin, controller };
const handlers = new Map();
const handle = controller.handle.bind(controller);
controller.handle = (Class, handler) => {
handlers.set(Class, handler);
handle(Class, handler);
};
const subscriptionHandle = controller.subscriptions.handle.bind(controller.subscriptions);
controller.subscriptions.handle = (Class, handler) => {
handlers.set(Class, handler);
subscriptionHandle(Class, handler);
};
await entrypoint({ plugin: { name: "exp_scenario" }, controller, logger });
return {
controller,
seed: () => handlers.get(messages.SeedRequest)(new messages.SeedRequest()),
listFeatures: () => handlers.get(messages.FeatureListRequest)(new messages.FeatureListRequest()),
updateFeature: request => handlers.get(messages.FeatureUpdateRequest)(request),
featureSubscription: request => handlers.get(messages.FeatureUpdatedEvent)(request),
shutdown: () => controller.hooks.shutdown.invoke(),
};
}
/** Write the stored features as a previous run would have left them. */
async function storeFeatures(databaseDirectory, records) {
await new lib.JsonIdDatastoreProvider(
path.join(databaseDirectory, "exp_scenario", "features.json"),
messages.FeatureRecord.fromJSON.bind(messages.FeatureRecord),
).save(new Map(records.map(record => [record.id, record])));
}
/** The feature record with the given id. */
async function getFeature(listFeatures, id) {
return (await listFeatures()).find(record => record.id === id);
}
const byName = (datastore, name) => [...datastore.values()].find(other => other.name === name);
t.test("class ControllerPlugin", t2 => {
t2.test(".handleSeedRequest() throws when the seeded plugins are missing", async t3 => {
const { plugin } = await startPlugin(t3, { withPlugins: false });
t.test("controller plugin", t2 => {
t2.test("SeedRequest throws when the seeded plugins are missing", async t3 => {
const { seed } = await startPlugin(t3, { withPlugins: false });
await t3.rejects(
plugin.handleSeedRequest(),
seed(),
{ message: "Seeding requires the exp_roles and exp_groups plugins" },
"the request is rejected",
);
});
t2.test(".handleSeedRequest() creates the roles and reuses them by name", async t3 => {
const { plugin, controller } = await startPlugin(t3);
t2.test("SeedRequest creates the roles and reuses them by name", async t3 => {
const { seed, controller } = await startPlugin(t3);
const rolesPlugin = RolesPlugin.get(controller);
await plugin.handleSeedRequest();
await seed();
t3.strictSame(controller.roles.size, seedRoles.length, "every seed role exists");
const moderator = byName(controller.roles, "Moderator");
t3.ok(moderator.permissions.has("exp_scenario.command.jail"), "parent permissions are flattened in");
t3.strictSame(rolesPlugin.roleMeta.get(moderator.id).shortHand, "Mod", "the role properties match the seed");
await plugin.handleSeedRequest();
await seed();
t3.strictSame(controller.roles.size, seedRoles.length, "seeding again reuses the roles");
});
t2.test(".handleSeedRequest() creates the groups and resets them by name", async t3 => {
const { plugin, controller } = await startPlugin(t3);
t2.test("SeedRequest creates the groups and resets them by name", async t3 => {
const { seed, controller } = await startPlugin(t3);
const groupsPlugin = GroupsPlugin.get(controller);
await plugin.handleSeedRequest();
await seed();
t3.strictSame(groupsPlugin.groups.size, seedGroups.length, "every seed group exists");
const restricted = byName(groupsPlugin.groups, "Restricted");
@@ -89,7 +122,7 @@ t.test("class ControllerPlugin", t2 => {
const admin = byName(groupsPlugin.groups, "Admin");
groupsPlugin.groups.set(new GroupRecord(admin.id, admin.name, new GroupPermissions(true, [])));
await plugin.handleSeedRequest();
await seed();
t3.strictSame(groupsPlugin.groups.size, seedGroups.length, "seeding again reuses the groups");
t3.ok(
byName(groupsPlugin.groups, "Admin").permissions.permissions.includes("toggle_map_editor"),
@@ -97,11 +130,11 @@ t.test("class ControllerPlugin", t2 => {
);
});
t2.test(".handleSeedRequest() maps each role onto its group by rank", async t3 => {
const { plugin, controller } = await startPlugin(t3);
t2.test("SeedRequest maps each role onto its group by rank", async t3 => {
const { seed, controller } = await startPlugin(t3);
const groupsPlugin = GroupsPlugin.get(controller);
await plugin.handleSeedRequest();
await seed();
const mapped = seedRoles.filter(role => role.group !== undefined);
t3.strictSame(groupsPlugin.roleMappings.size, mapped.length, "every role with a group is mapped");
@@ -119,74 +152,75 @@ t.test("class ControllerPlugin", t2 => {
t3.strictSame(priorities.length, new Set(priorities).size, "priorities are unique");
});
t2.test(".handleSeedRequest() reuses mappings and keeps clear of other mappings", async t3 => {
const { plugin, controller } = await startPlugin(t3);
t2.test("SeedRequest reuses mappings and keeps clear of other mappings", async t3 => {
const { seed, controller } = await startPlugin(t3);
const groupsPlugin = GroupsPlugin.get(controller);
groupsPlugin.roleMappings.set(new RoleMappingRecord(99, new Set([0, 1]), 5, 2, true));
await plugin.handleSeedRequest();
await seed();
const first = new Map([...groupsPlugin.roleMappings.values()].map(mapping => [mapping.id, mapping.priority]));
await plugin.handleSeedRequest();
await seed();
const second = new Map([...groupsPlugin.roleMappings.values()].map(mapping => [mapping.id, mapping.priority]));
t3.strictSame(second, first, "seeding again reuses the mappings");
t3.strictSame(groupsPlugin.roleMappings.get(99).priority, 2, "other mappings are left alone");
t3.notOk([...first.values()].filter(priority => priority === 2).length > 1, "seed priorities skip taken ones");
});
t2.test(".fromContext() adds every feature with its defaults", async t3 => {
const { plugin } = await startPlugin(t3, { withPlugins: false });
const records = await plugin.handleFeatureListRequest();
t2.test("startup adds every feature with its defaults", async t3 => {
const { listFeatures } = await startPlugin(t3, { withPlugins: false });
const records = await listFeatures();
t3.strictSame(records.map(record => record.id), features.map(feature => feature.name), "one record per feature");
t3.ok(records.every(record => record.enabled && !Object.keys(record.values).length), "enabled with no overrides");
});
t2.test(".reconcileFeatures() drops stored values and features which no longer exist", async t3 => {
t2.test("startup drops stored values and features which no longer exist", async t3 => {
const databaseDirectory = t3.testdir();
const { plugin } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
plugin.features.set(new messages.FeatureRecord("afk_kick", false, { afk_minutes: 5, trust_time: 600 }));
plugin.features.set(new messages.FeatureRecord("gone", true, {}));
await plugin.onShutdown();
await storeFeatures(databaseDirectory, [
new messages.FeatureRecord("afk_kick", false, { afk_minutes: 5, trust_time: 600 }),
new messages.FeatureRecord("gone", true, {}),
]);
const { plugin: restarted } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
const record = restarted.features.get("afk_kick");
const { listFeatures } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
const record = await getFeature(listFeatures, "afk_kick");
t3.strictSame([record.enabled, record.values], [false, { afk_minutes: 5 }], "the stale value is dropped, the rest kept");
t3.notOk(restarted.features.has("gone"), "the removed feature is deleted");
t3.ok(features.every(feature => restarted.features.has(feature.name)), "every declared feature still has a record");
const ids = new Set((await listFeatures()).map(other => other.id));
t3.notOk(ids.has("gone"), "the removed feature is deleted");
t3.ok(features.every(feature => ids.has(feature.name)), "every declared feature still has a record");
});
t2.test(".handleFeatureUpdateRequest() stores the values which differ from the default", async t3 => {
const { plugin } = await startPlugin(t3, { withPlugins: false });
t2.test("FeatureUpdateRequest stores the values which differ from the default", async t3 => {
const { controller, listFeatures, updateFeature, featureSubscription } = await startPlugin(t3, { withPlugins: false });
const broadcasts = [];
plugin.controller.subscriptions.broadcast = event => broadcasts.push(event);
controller.subscriptions.broadcast = event => broadcasts.push(event);
const record = await plugin.handleFeatureUpdateRequest(new messages.FeatureUpdateRequest(
const record = await updateFeature(new messages.FeatureUpdateRequest(
"death_markers", false, { show_map_markers: false, collect_corpses: true },
));
t3.strictSame(record.values, { show_map_markers: false }, "the default value is dropped");
t3.equal(plugin.features.get("death_markers").enabled, false, "the feature is disabled");
t3.equal((await getFeature(listFeatures, "death_markers")).enabled, false, "the feature is disabled");
t3.strictSame(broadcasts.map(event => event.updates.map(update => update.id)), [["death_markers"]], "the update is broadcast");
const subscription = await plugin.handleFeatureSubscription({ lastRequestTimeMs: record.updatedAtMs - 1 });
const subscription = await featureSubscription({ lastRequestTimeMs: record.updatedAtMs - 1 });
t3.strictSame(subscription.updates.map(update => update.id), ["death_markers"], "subscribers catch up on the change");
});
t2.test(".handleFeatureUpdateRequest() rejects invalid values", async t3 => {
const { plugin } = await startPlugin(t3, { withPlugins: false });
t2.test("FeatureUpdateRequest rejects invalid values", async t3 => {
const { updateFeature } = await startPlugin(t3, { withPlugins: false });
await t3.rejects(
plugin.handleFeatureUpdateRequest(new messages.FeatureUpdateRequest("death_markers", true, { unknown: 1 })),
updateFeature(new messages.FeatureUpdateRequest("death_markers", true, { unknown: 1 })),
{ message: "Feature death_markers has no setting unknown" },
);
});
t2.test(".fromContext() keeps stored features across restarts", async t3 => {
t2.test("stored features are kept across restarts", async t3 => {
const databaseDirectory = t3.testdir();
const { plugin } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
await plugin.handleFeatureUpdateRequest(new messages.FeatureUpdateRequest("afk_kick", false, { afk_minutes: 5 }));
await plugin.onShutdown();
const { updateFeature, shutdown } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
await updateFeature(new messages.FeatureUpdateRequest("afk_kick", false, { afk_minutes: 5 }));
await shutdown();
const { plugin: restarted } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
const record = restarted.features.get("afk_kick");
const { listFeatures } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
const record = await getFeature(listFeatures, "afk_kick");
t3.strictSame([record.enabled, record.values], [false, { afk_minutes: 5 }], "the stored record is loaded");
});
+37 -24
View File
@@ -1,7 +1,7 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { Instance } from "@clusterio/host";
import { InstancePlugin } from "../dist/node/instance.js";
import entrypoint from "../dist/node/instance.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js";
import * as messages from "../dist/node/messages.js";
import { features } from "../dist/node/features.js";
@@ -24,7 +24,7 @@ class TestConnector extends lib.BaseConnector {
send() {}
}
/** Build a plugin around a real instance with spies on what leaves it. */
/** Run the plugin on a real instance with spies on what leaves it, returns the event handler it registered. */
async function startPlugin(t2, features = [new messages.FeatureRecord("death_markers", false, { show_map_markers: false })]) {
const instanceConfig = new lib.InstanceConfig("host");
instanceConfig.set("instance.id", 1);
@@ -47,8 +47,18 @@ async function startPlugin(t2, features = [new messages.FeatureRecord("death_mar
return request instanceof messages.FeatureListRequest ? features : undefined;
};
const plugin = await InstancePlugin.fromContext({ plugin: { name: "exp_scenario" }, instance, host: {}, logger });
return { plugin, instance, state };
const handlers = new Map();
instance.handle = (Event, handler) => handlers.set(Event, handler);
await entrypoint({ plugin: { name: "exp_scenario" }, instance, host: {}, logger });
const hooks = instance.hooks;
return {
state,
start: () => hooks.start.invoke(),
exit: () => hooks.exit.invoke(),
connectionEvent: event => hooks.controllerConnectionEvent.invoke(event),
featureUpdated: handlers.get(messages.FeatureUpdatedEvent),
};
}
/** The payload of a recorded rcon command. */
@@ -57,10 +67,10 @@ function decodeRcon(command) {
return JSON.parse(match[2]);
}
t.test("class InstancePlugin", t2 => {
t2.test(".onStart() subscribes and sends every feature to lua", async t3 => {
const { plugin, state } = await startPlugin(t3);
await plugin.onStart();
t.test("instance plugin", t2 => {
t2.test("start subscribes and sends every feature to lua", async t3 => {
const { start, state } = await startPlugin(t3);
await start();
t3.ok(state.sent[0] instanceof lib.SubscriptionRequest, "subscribes to updates first");
t3.ok(state.sent[1] instanceof messages.FeatureListRequest, "then lists the features");
@@ -72,49 +82,52 @@ t.test("class InstancePlugin", t2 => {
t3.equal(Object.keys(update.values).length, deathMarkers.fields.length + 1, "every field and enabled");
});
t2.test(".handleFeatureUpdatedEvent() only sends while the game is up", async t3 => {
const { plugin, state } = await startPlugin(t3);
t2.test("FeatureUpdatedEvent only sends while the game is up", async t3 => {
const { start, exit, featureUpdated, state } = await startPlugin(t3);
const event = new messages.FeatureUpdatedEvent([
new messages.FeatureRecord("afk_kick", true, { afk_minutes: 5 }),
new messages.FeatureRecord("removed", true, {}, 0, true),
]);
await plugin.handleFeatureUpdatedEvent(event);
await featureUpdated(event);
t3.strictSame(state.rcons, [], "nothing is sent before start");
await plugin.onStart();
await start();
state.rcons.length = 0;
await plugin.handleFeatureUpdatedEvent(event);
await featureUpdated(event);
const updates = decodeRcon(state.rcons[0]);
t3.strictSame(updates.map(update => update.name), ["afk_kick"], "deleted features are left out");
t3.strictSame([updates[0].values.enabled, updates[0].values.afk_minutes], [true, 5]);
await plugin.onExit();
await exit();
state.rcons.length = 0;
await plugin.handleFeatureUpdatedEvent(event);
await featureUpdated(event);
t3.strictSame(state.rcons, [], "nothing is sent after exit");
});
t2.test(".onControllerConnectionEvent() syncs again after the controller restarts", async t3 => {
const { plugin, state } = await startPlugin(t3);
await plugin.onControllerConnectionEvent("connect");
t2.test("a new controller connection syncs again after the controller restarts", async t3 => {
const { start, connectionEvent, state } = await startPlugin(t3);
await connectionEvent("connect");
t3.strictSame(state.sent, [], "nothing happens before start");
await plugin.onStart();
await start();
state.sent.length = 0;
state.rcons.length = 0;
await plugin.onControllerConnectionEvent("resume");
await connectionEvent("resume");
t3.strictSame(state.sent, [], "a resumed session keeps its subscription");
await plugin.onControllerConnectionEvent("connect");
await connectionEvent("connect");
t3.ok(state.sent[0] instanceof lib.SubscriptionRequest, "subscribes again");
t3.equal(state.rcons.length, 1, "and sends every feature");
});
t2.test(".luaSendFeatures() picks a long bracket the values do not close", async t3 => {
const { plugin, state } = await startPlugin(t3);
t2.test("feature updates pick a long bracket the values do not close", async t3 => {
const { start, featureUpdated, state } = await startPlugin(t3, []);
await start();
const name = "a]=]b]==]c";
await plugin.luaSendFeatures([new messages.FeatureRecord("station_auto_name", true, { station_name: name })]);
await featureUpdated(new messages.FeatureUpdatedEvent([
new messages.FeatureRecord("station_auto_name", true, { station_name: name }),
]));
t3.match(state.rcons[0], "json_to_table[===[", "uses a level not found in the json");
t3.strictSame(decodeRcon(state.rcons[0])[0].values.station_name, name);
});