mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2026-11-19 15:23:12 +09:00
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:
1 parent
26a801da5e
commit
68a964cf57
12 files changed
+709
-820
No files matched your search
+89
-117
@@ -1,122 +1,29 @@
|
||||
import type { Controller, ControllerPluginContext } from "@clusterio/controller";
|
||||
import type { ControllerPluginContext } from "@clusterio/controller";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import * as messages from "./messages.js";
|
||||
import * as path from "node:path";
|
||||
|
||||
export class ControllerPlugin {
|
||||
private constructor(
|
||||
public controller: Controller,
|
||||
public logger: lib.Logger,
|
||||
public name: string,
|
||||
public reports: lib.SubscribableDatastore<messages.ReportRecord>,
|
||||
) {}
|
||||
|
||||
static async fromContext(context: ControllerPluginContext) {
|
||||
const controller = context.controller;
|
||||
const databaseDirectory = controller.config.get("controller.database_directory");
|
||||
|
||||
const reports = new lib.SubscribableDatastore(
|
||||
...await new lib.JsonIdDatastoreProvider(
|
||||
path.join(databaseDirectory, "exp_reports", "reports.json"),
|
||||
messages.ReportRecord.fromJSON.bind(messages.ReportRecord),
|
||||
).bootstrap()
|
||||
);
|
||||
|
||||
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, reports);
|
||||
|
||||
controller.subscriptions.handle(messages.ReportUpdatedEvent, plugin.handleReportSubscription.bind(plugin));
|
||||
reports.on("update", plugin.reportsUpdated.bind(plugin));
|
||||
|
||||
controller.handle(messages.ReportListRequest, plugin.handleReportListRequest.bind(plugin));
|
||||
controller.handle(messages.ReportGetRequest, plugin.handleReportGetRequest.bind(plugin));
|
||||
controller.handle(messages.ReportCreateRequest, plugin.handleReportCreateRequest.bind(plugin));
|
||||
controller.handle(messages.ReportDeleteRequest, plugin.handleReportDeleteRequest.bind(plugin));
|
||||
|
||||
controller.hooks.shutdown.attach(plugin.name, plugin.onShutdown.bind(plugin));
|
||||
return plugin;
|
||||
}
|
||||
|
||||
async onShutdown() {
|
||||
await this.reports.save();
|
||||
}
|
||||
|
||||
/** Reports are immutable, so any update which is not a deletion is a new report. */
|
||||
reportsUpdated(reports: messages.ReportRecord[]) {
|
||||
this.controller.subscriptions.broadcast(new messages.ReportUpdatedEvent(reports));
|
||||
|
||||
for (const report of reports) {
|
||||
if (!report.isDeleted) {
|
||||
this.sendWebhooks(report);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleReportSubscription(request: lib.SubscriptionRequest) {
|
||||
const reports = [...this.reports.values()].filter(report => report.updatedAtMs > request.lastRequestTimeMs);
|
||||
return reports.length ? new messages.ReportUpdatedEvent(reports) : null;
|
||||
}
|
||||
export default async function (context: ControllerPluginContext) {
|
||||
const { controller, logger, plugin } = context;
|
||||
const databaseDirectory = controller.config.get("controller.database_directory");
|
||||
const reports = new lib.SubscribableDatastore(
|
||||
...await new lib.JsonIdDatastoreProvider(
|
||||
path.join(databaseDirectory, "exp_reports", "reports.json"),
|
||||
messages.ReportRecord.fromJSON.bind(messages.ReportRecord),
|
||||
).bootstrap()
|
||||
);
|
||||
|
||||
/** Every report, or only those against one player. */
|
||||
listReports(playerName?: string) {
|
||||
const reports = [...this.reports.values()];
|
||||
return playerName === undefined ? reports : reports.filter(report => report.playerName === playerName);
|
||||
}
|
||||
|
||||
async handleReportListRequest(request: messages.ReportListRequest) {
|
||||
return this.listReports(request.playerName);
|
||||
}
|
||||
|
||||
async handleReportGetRequest(request: messages.ReportGetRequest) {
|
||||
const report = this.reports.get(request.id);
|
||||
if (!report) {
|
||||
throw new lib.RequestError(`Report with ID ${request.id} does not exist`);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
async handleReportCreateRequest(request: messages.ReportCreateRequest, src: lib.Address) {
|
||||
let byPlayerName = request.byPlayerName;
|
||||
let instanceName = "";
|
||||
if (src.type === lib.Address.control) {
|
||||
byPlayerName = this.controller.wsServer.controlConnections.get(src.id)!.user.name;
|
||||
} else {
|
||||
const instance = this.controller.instances.get(src.id);
|
||||
instanceName = instance ? instance.config.get("instance.name") : String(src.id);
|
||||
}
|
||||
|
||||
if (!byPlayerName) {
|
||||
throw new lib.RequestError("A report needs the name of the player making it");
|
||||
}
|
||||
if (!request.reason.trim()) {
|
||||
throw new lib.RequestError("A report needs a reason");
|
||||
}
|
||||
if (this.listReports(request.playerName).some(report => report.byPlayerName === byPlayerName)) {
|
||||
throw new lib.RequestError(`${byPlayerName} has already reported ${request.playerName}`);
|
||||
}
|
||||
|
||||
let id = Math.random() * 2 ** 31 | 0;
|
||||
while (this.reports.has(id)) {
|
||||
id = Math.random() * 2 ** 31 | 0;
|
||||
}
|
||||
|
||||
const report = new messages.ReportRecord(id, request.playerName, byPlayerName, request.reason.trim(), instanceName);
|
||||
this.reports.set(report);
|
||||
return report;
|
||||
}
|
||||
|
||||
async handleReportDeleteRequest(request: messages.ReportDeleteRequest) {
|
||||
const report = this.reports.getMutable(request.id);
|
||||
if (!report) {
|
||||
throw new lib.RequestError(`Report with ID ${request.id} does not exist`);
|
||||
}
|
||||
this.reports.delete(report);
|
||||
function listReports(playerName?: string) {
|
||||
const all = [...reports.values()];
|
||||
return playerName === undefined ? all : all.filter(report => report.playerName === playerName);
|
||||
}
|
||||
|
||||
/** Post a new report to the configured webhooks, failures are logged rather than failing the report. */
|
||||
sendWebhooks(report: messages.ReportRecord) {
|
||||
const discordUrl = this.controller.config.get("exp_reports.discord_webhook_url");
|
||||
function sendWebhooks(report: messages.ReportRecord) {
|
||||
const discordUrl = controller.config.get("exp_reports.discord_webhook_url");
|
||||
if (discordUrl) {
|
||||
this.postWebhook(discordUrl, {
|
||||
postWebhook(discordUrl, {
|
||||
embeds: [{
|
||||
title: "Player reported",
|
||||
color: 0xffcc00,
|
||||
@@ -131,13 +38,13 @@ export class ControllerPlugin {
|
||||
});
|
||||
}
|
||||
|
||||
const jsonUrl = this.controller.config.get("exp_reports.json_webhook_url");
|
||||
const jsonUrl = controller.config.get("exp_reports.json_webhook_url");
|
||||
if (jsonUrl) {
|
||||
this.postWebhook(jsonUrl, { type: "report_created", report: report.toJSON() });
|
||||
postWebhook(jsonUrl, { type: "report_created", report: report.toJSON() });
|
||||
}
|
||||
}
|
||||
|
||||
async postWebhook(url: string, body: unknown) {
|
||||
async function postWebhook(url: string, body: unknown) {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
@@ -145,14 +52,79 @@ export class ControllerPlugin {
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) {
|
||||
this.logger.warn(`Webhook ${url} responded with ${response.status}`);
|
||||
logger.warn(`Webhook ${url} responded with ${response.status}`);
|
||||
}
|
||||
} catch (err: any) {
|
||||
this.logger.warn(`Webhook ${url} failed: ${err.message}`);
|
||||
logger.warn(`Webhook ${url} failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default async function (context: ControllerPluginContext) {
|
||||
await ControllerPlugin.fromContext(context);
|
||||
controller.subscriptions.handle(messages.ReportUpdatedEvent, async request => {
|
||||
const updates = [...reports.values()].filter(report => report.updatedAtMs > request.lastRequestTimeMs);
|
||||
return updates.length ? new messages.ReportUpdatedEvent(updates) : null;
|
||||
});
|
||||
|
||||
// Reports are immutable, so any update which is not a deletion is a new report
|
||||
reports.on("update", updates => {
|
||||
controller.subscriptions.broadcast(new messages.ReportUpdatedEvent(updates));
|
||||
for (const report of updates) {
|
||||
if (!report.isDeleted) {
|
||||
sendWebhooks(report);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
controller.handle(messages.ReportListRequest, async (request: messages.ReportListRequest) => (
|
||||
listReports(request.playerName)
|
||||
));
|
||||
|
||||
controller.handle(messages.ReportGetRequest, async (request: messages.ReportGetRequest) => {
|
||||
const report = reports.get(request.id);
|
||||
if (!report) {
|
||||
throw new lib.RequestError(`Report with ID ${request.id} does not exist`);
|
||||
}
|
||||
return report;
|
||||
});
|
||||
|
||||
controller.handle(messages.ReportCreateRequest, async (request: messages.ReportCreateRequest, src: lib.Address) => {
|
||||
let byPlayerName = request.byPlayerName;
|
||||
let instanceName = "";
|
||||
if (src.type === lib.Address.control) {
|
||||
byPlayerName = controller.wsServer.controlConnections.get(src.id)!.user.name;
|
||||
} else {
|
||||
const instance = controller.instances.get(src.id);
|
||||
instanceName = instance ? instance.config.get("instance.name") : String(src.id);
|
||||
}
|
||||
|
||||
if (!byPlayerName) {
|
||||
throw new lib.RequestError("A report needs the name of the player making it");
|
||||
}
|
||||
if (!request.reason.trim()) {
|
||||
throw new lib.RequestError("A report needs a reason");
|
||||
}
|
||||
if (listReports(request.playerName).some(report => report.byPlayerName === byPlayerName)) {
|
||||
throw new lib.RequestError(`${byPlayerName} has already reported ${request.playerName}`);
|
||||
}
|
||||
|
||||
let id = Math.random() * 2 ** 31 | 0;
|
||||
while (reports.has(id)) {
|
||||
id = Math.random() * 2 ** 31 | 0;
|
||||
}
|
||||
|
||||
const report = new messages.ReportRecord(id, request.playerName, byPlayerName, request.reason.trim(), instanceName);
|
||||
reports.set(report);
|
||||
return report;
|
||||
});
|
||||
|
||||
controller.handle(messages.ReportDeleteRequest, async (request: messages.ReportDeleteRequest) => {
|
||||
const report = reports.getMutable(request.id);
|
||||
if (!report) {
|
||||
throw new lib.RequestError(`Report with ID ${request.id} does not exist`);
|
||||
}
|
||||
reports.delete(report);
|
||||
});
|
||||
|
||||
controller.hooks.shutdown.attach(plugin.name, async () => {
|
||||
await reports.save();
|
||||
});
|
||||
}
|
||||
+28
-47
@@ -1,5 +1,4 @@
|
||||
import type { Instance, InstancePluginContext } from "@clusterio/host";
|
||||
import type * as lib from "@clusterio/lib";
|
||||
import type { InstancePluginContext } from "@clusterio/host";
|
||||
import * as messages from "./messages.js";
|
||||
|
||||
/** Sent by the lua side when a player reports another. */
|
||||
@@ -29,82 +28,64 @@ export type IpcReportDelete = {
|
||||
* the answer is handed back to lua once it arrives. The instance may have
|
||||
* stopped by then, in which case the answer is dropped.
|
||||
*/
|
||||
export class InstancePlugin {
|
||||
private constructor(
|
||||
public instance: Instance,
|
||||
public logger: lib.Logger,
|
||||
public name: string,
|
||||
) {}
|
||||
export default async function (context: InstancePluginContext) {
|
||||
const { instance } = context;
|
||||
|
||||
static async fromContext(context: InstancePluginContext) {
|
||||
const instance = context.instance;
|
||||
const plugin = new InstancePlugin(instance, context.logger, context.plugin.name);
|
||||
|
||||
instance.server.handle("exp_reports:create", plugin.handleCreateIPC.bind(plugin));
|
||||
instance.server.handle("exp_reports:list", plugin.handleListIPC.bind(plugin));
|
||||
instance.server.handle("exp_reports:delete", plugin.handleDeleteIPC.bind(plugin));
|
||||
return plugin;
|
||||
/** Hand an answer to lua, unless the instance stopped while it was being fetched. */
|
||||
async function luaSend(receiver: string, json: any) {
|
||||
if (instance.status !== "running") {
|
||||
return;
|
||||
}
|
||||
await instance.sendRcon(
|
||||
`/sc exp_reports.${receiver}(helpers.json_to_table[=[${JSON.stringify(json)}]=])`, true
|
||||
);
|
||||
}
|
||||
|
||||
async handleCreateIPC(event: IpcReportCreate) {
|
||||
instance.server.handle("exp_reports:create", async (event: IpcReportCreate) => {
|
||||
try {
|
||||
const report = await this.instance.sendTo("controller", new messages.ReportCreateRequest(
|
||||
const report = await instance.sendTo("controller", new messages.ReportCreateRequest(
|
||||
event.player_name, event.reason, event.by_player_name,
|
||||
));
|
||||
const reports = await this.instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
await this.luaSend("receive_created", {
|
||||
const reports = await instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
await luaSend("receive_created", {
|
||||
report: report.toJSON(),
|
||||
reports: reports.map(other => other.toJSON()),
|
||||
});
|
||||
} catch (err: any) {
|
||||
await this.luaSend("receive_error", { caller: event.by_player_name, message: err.message });
|
||||
await luaSend("receive_error", { caller: event.by_player_name, message: err.message });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async handleListIPC(event: IpcReportList) {
|
||||
instance.server.handle("exp_reports:list", async (event: IpcReportList) => {
|
||||
try {
|
||||
const reports = await this.instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
await this.luaSend("receive_list", {
|
||||
const reports = await instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
await luaSend("receive_list", {
|
||||
caller: event.caller,
|
||||
player_name: event.player_name,
|
||||
reports: reports.map(report => report.toJSON()),
|
||||
});
|
||||
} catch (err: any) {
|
||||
await this.luaSend("receive_error", { caller: event.caller, message: err.message });
|
||||
await luaSend("receive_error", { caller: event.caller, message: err.message });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async handleDeleteIPC(event: IpcReportDelete) {
|
||||
instance.server.handle("exp_reports:delete", async (event: IpcReportDelete) => {
|
||||
try {
|
||||
let reports = await this.instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
let reports = await instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
if (event.by_player_name !== undefined) {
|
||||
reports = reports.filter(report => report.byPlayerName === event.by_player_name);
|
||||
}
|
||||
for (const report of reports) {
|
||||
await this.instance.sendTo("controller", new messages.ReportDeleteRequest(report.id));
|
||||
await instance.sendTo("controller", new messages.ReportDeleteRequest(report.id));
|
||||
}
|
||||
await this.luaSend("receive_deleted", {
|
||||
await luaSend("receive_deleted", {
|
||||
caller: event.caller,
|
||||
player_name: event.player_name,
|
||||
by_player_name: event.by_player_name,
|
||||
count: reports.length,
|
||||
});
|
||||
} catch (err: any) {
|
||||
await this.luaSend("receive_error", { caller: event.caller, message: err.message });
|
||||
await luaSend("receive_error", { caller: event.caller, message: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
/** Hand an answer to lua, unless the instance stopped while it was being fetched. */
|
||||
async luaSend(receiver: string, json: any) {
|
||||
if (this.instance.status !== "running") {
|
||||
return;
|
||||
}
|
||||
await this.instance.sendRcon(
|
||||
`/sc exp_reports.${receiver}(helpers.json_to_table[=[${JSON.stringify(json)}]=])`, true
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default async function (context: InstancePluginContext) {
|
||||
await InstancePlugin.fromContext(context);
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import t from "tap";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { Controller, InstanceRecord } from "@clusterio/controller";
|
||||
import entrypoint, { ControllerPlugin } from "../dist/node/controller.js";
|
||||
import entrypoint from "../dist/node/controller.js";
|
||||
import * as messages from "../dist/node/messages.js";
|
||||
import { plugin as pluginDeclaration } from "../dist/node/index.js";
|
||||
|
||||
@@ -24,7 +24,7 @@ const fromInstance = lib.Address.fromShorthand({ instanceId: 1 });
|
||||
const fromUnknownInstance = lib.Address.fromShorthand({ instanceId: 9 });
|
||||
const fromControl = lib.Address.fromShorthand({ controlId: 7 });
|
||||
|
||||
/** 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, { config = {} } = {}) {
|
||||
const controllerConfig = new lib.ControllerConfig("controller", {
|
||||
"controller.database_directory": t2.testdir(),
|
||||
@@ -46,12 +46,45 @@ async function startPlugin(t2, { config = {} } = {}) {
|
||||
broadcast(event);
|
||||
};
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (url, init) => {
|
||||
state.posts.push({ url, body: JSON.parse(init.body) });
|
||||
return state.fetchResult();
|
||||
};
|
||||
state.fetchResult = () => ({ ok: true, status: 200 });
|
||||
t2.teardown(() => { globalThis.fetch = realFetch; });
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
const pluginLogger = { ...logger, warn: message => state.warnings.push(message) };
|
||||
const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_reports" }, controller, logger: pluginLogger });
|
||||
plugin.postWebhook = async (url, body) => { state.posts.push({ url, body }); };
|
||||
return { plugin, controller, state };
|
||||
await entrypoint({ plugin: { name: "exp_reports" }, controller, logger: pluginLogger });
|
||||
const request = (Request, ...args) => handlers.get(Request)(new Request(...args), fromInstance);
|
||||
return {
|
||||
controller,
|
||||
state,
|
||||
create: (playerName, reason, byPlayerName, src = fromInstance) => handlers.get(messages.ReportCreateRequest)(
|
||||
new messages.ReportCreateRequest(playerName, reason, byPlayerName), src,
|
||||
),
|
||||
list: playerName => request(messages.ReportListRequest, playerName),
|
||||
get: id => request(messages.ReportGetRequest, id),
|
||||
remove: id => request(messages.ReportDeleteRequest, id),
|
||||
subscription: lastRequestTimeMs => handlers.get(messages.ReportUpdatedEvent)({ lastRequestTimeMs }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Let the webhook posts which are not awaited finish. */
|
||||
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
t.test("entrypoint", async t2 => {
|
||||
const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() });
|
||||
const controller = new Controller(logger, [], controllerConfig);
|
||||
@@ -62,108 +95,102 @@ t.test("entrypoint", async t2 => {
|
||||
await controller.hooks.shutdown.invoke();
|
||||
});
|
||||
|
||||
t.test("class ControllerPlugin", t2 => {
|
||||
t2.test(".handleReportCreateRequest() from an instance records the instance and the reporter", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
const report = await plugin.handleReportCreateRequest(
|
||||
new messages.ReportCreateRequest("bob", " griefing ", "alice"), fromInstance,
|
||||
);
|
||||
t.test("controller plugin", t2 => {
|
||||
t2.test("ReportCreateRequest from an instance records the instance and the reporter", async t3 => {
|
||||
const { create, list } = await startPlugin(t3);
|
||||
const report = await create("bob", " griefing ", "alice", fromInstance);
|
||||
|
||||
t3.strictSame(report.playerName, "bob");
|
||||
t3.strictSame(report.byPlayerName, "alice", "the reporter comes from the request");
|
||||
t3.strictSame(report.reason, "griefing", "the reason is trimmed");
|
||||
t3.strictSame(report.instanceName, "EXP", "the instance is named");
|
||||
t3.ok(report.updatedAtMs > 0, "the report is timestamped");
|
||||
t3.strictSame(plugin.listReports(), [report], "the report is stored");
|
||||
t3.strictSame(await list(), [report], "the report is stored");
|
||||
|
||||
const unknown = await plugin.handleReportCreateRequest(
|
||||
new messages.ReportCreateRequest("carol", "spam", "alice"), fromUnknownInstance,
|
||||
);
|
||||
const unknown = await create("carol", "spam", "alice", fromUnknownInstance);
|
||||
t3.strictSame(unknown.instanceName, "9", "an unknown instance is named by its id");
|
||||
});
|
||||
|
||||
t2.test(".handleReportCreateRequest() from the web ui uses the user of the connection", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
const report = await plugin.handleReportCreateRequest(
|
||||
new messages.ReportCreateRequest("bob", "griefing", "someone-else"), fromControl,
|
||||
);
|
||||
t2.test("ReportCreateRequest from the web ui uses the user of the connection", async t3 => {
|
||||
const { create } = await startPlugin(t3);
|
||||
const report = await create("bob", "griefing", "someone-else", fromControl);
|
||||
|
||||
t3.strictSame(report.byPlayerName, "admin", "the reporter is the connected user");
|
||||
t3.strictSame(report.instanceName, "", "there is no instance");
|
||||
});
|
||||
|
||||
t2.test(".handleReportCreateRequest() rejects reports which can not be stored", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
t2.test("ReportCreateRequest rejects reports which can not be stored", async t3 => {
|
||||
const { create, list } = await startPlugin(t3);
|
||||
await create("bob", "griefing", "alice", fromInstance);
|
||||
|
||||
await t3.rejects(
|
||||
plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "again", "alice"), fromInstance),
|
||||
create("bob", "again", "alice", fromInstance),
|
||||
{ message: "alice has already reported bob" },
|
||||
"a player can only report another once",
|
||||
);
|
||||
await t3.rejects(
|
||||
plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", " ", "carol"), fromInstance),
|
||||
create("bob", " ", "carol", fromInstance),
|
||||
{ message: "A report needs a reason" },
|
||||
"a reason is required",
|
||||
);
|
||||
await t3.rejects(
|
||||
plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "spam", ""), fromInstance),
|
||||
create("bob", "spam", "", fromInstance),
|
||||
{ message: "A report needs the name of the player making it" },
|
||||
"an instance must name the reporter",
|
||||
);
|
||||
t3.strictSame(plugin.listReports().length, 1, "nothing else was stored");
|
||||
t3.strictSame((await list()).length, 1, "nothing else was stored");
|
||||
});
|
||||
|
||||
t2.test(".handleReportListRequest() and .handleReportGetRequest() find reports", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
const first = await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("carol", "spam", "alice"), fromInstance);
|
||||
t2.test("ReportListRequest and ReportGetRequest find reports", async t3 => {
|
||||
const { create, list, get } = await startPlugin(t3);
|
||||
const first = await create("bob", "griefing", "alice", fromInstance);
|
||||
await create("carol", "spam", "alice", fromInstance);
|
||||
|
||||
t3.strictSame((await plugin.handleReportListRequest(new messages.ReportListRequest())).length, 2, "everything is listed");
|
||||
t3.strictSame((await list()).length, 2, "everything is listed");
|
||||
t3.strictSame(
|
||||
await plugin.handleReportListRequest(new messages.ReportListRequest("bob")), [first],
|
||||
await list("bob"), [first],
|
||||
"a player's reports are listed",
|
||||
);
|
||||
t3.strictSame(await plugin.handleReportGetRequest(new messages.ReportGetRequest(first.id)), first);
|
||||
t3.strictSame(await get(first.id), first);
|
||||
await t3.rejects(
|
||||
plugin.handleReportGetRequest(new messages.ReportGetRequest(123)),
|
||||
get(123),
|
||||
{ message: "Report with ID 123 does not exist" },
|
||||
);
|
||||
});
|
||||
|
||||
t2.test(".handleReportDeleteRequest() removes the report and broadcasts the deletion", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
const report = await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
t2.test("ReportDeleteRequest removes the report and broadcasts the deletion", async t3 => {
|
||||
const { create, list, remove, state } = await startPlugin(t3);
|
||||
const report = await create("bob", "griefing", "alice", fromInstance);
|
||||
|
||||
state.broadcasts.length = 0;
|
||||
await plugin.handleReportDeleteRequest(new messages.ReportDeleteRequest(report.id));
|
||||
t3.strictSame(plugin.listReports(), [], "the report is gone");
|
||||
await remove(report.id);
|
||||
t3.strictSame(await list(), [], "the report is gone");
|
||||
t3.ok(
|
||||
state.broadcasts.some(event => event instanceof messages.ReportUpdatedEvent && event.updates[0].isDeleted),
|
||||
"subscribers are told it was deleted",
|
||||
);
|
||||
await t3.rejects(
|
||||
plugin.handleReportDeleteRequest(new messages.ReportDeleteRequest(report.id)),
|
||||
remove(report.id),
|
||||
{ message: `Report with ID ${report.id} does not exist` },
|
||||
);
|
||||
});
|
||||
|
||||
t2.test(".handleReportSubscription() replays only newer records", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
const report = await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
t2.test("subscribing replays only newer records", async t3 => {
|
||||
const { create, subscription } = await startPlugin(t3);
|
||||
const report = await create("bob", "griefing", "alice", fromInstance);
|
||||
|
||||
const all = await plugin.handleReportSubscription({ lastRequestTimeMs: 0 });
|
||||
const all = await subscription(0);
|
||||
t3.strictSame(all.updates, [report], "everything is replayed from the start");
|
||||
const none = await plugin.handleReportSubscription({ lastRequestTimeMs: report.updatedAtMs });
|
||||
const none = await subscription(report.updatedAtMs);
|
||||
t3.strictSame(none, null, "nothing is replayed when up to date");
|
||||
});
|
||||
|
||||
t2.test(".sendWebhooks() posts new reports to the configured hooks", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3, { config: {
|
||||
t2.test("new reports are posted to the configured hooks", async t3 => {
|
||||
const { create, remove, state } = await startPlugin(t3, { config: {
|
||||
"exp_reports.discord_webhook_url": "https://discord.example/hook",
|
||||
"exp_reports.json_webhook_url": "https://json.example/hook",
|
||||
} });
|
||||
const report = await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
const report = await create("bob", "griefing", "alice", fromInstance);
|
||||
|
||||
t3.strictSame(state.posts.map(post => post.url), ["https://discord.example/hook", "https://json.example/hook"]);
|
||||
const embed = state.posts[0].body.embeds[0];
|
||||
@@ -171,29 +198,29 @@ t.test("class ControllerPlugin", t2 => {
|
||||
t3.strictSame(state.posts[1].body, { type: "report_created", report: report.toJSON() }, "the json hook gets the record");
|
||||
|
||||
state.posts.length = 0;
|
||||
await plugin.handleReportDeleteRequest(new messages.ReportDeleteRequest(report.id));
|
||||
await remove(report.id);
|
||||
t3.strictSame(state.posts, [], "deletions are not posted");
|
||||
});
|
||||
|
||||
t2.test(".sendWebhooks() does nothing without hooks", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
t2.test("nothing is posted without hooks", async t3 => {
|
||||
const { create, state } = await startPlugin(t3);
|
||||
await create("bob", "griefing", "alice", fromInstance);
|
||||
t3.strictSame(state.posts, []);
|
||||
});
|
||||
|
||||
t2.test(".postWebhook() logs rather than throws when the hook fails", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
plugin.postWebhook = ControllerPlugin.prototype.postWebhook;
|
||||
t2.test("webhooks log rather than throw when the hook fails", async t3 => {
|
||||
const { create, state } = await startPlugin(t3, { config: {
|
||||
"exp_reports.json_webhook_url": "https://down.example/hook",
|
||||
} });
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => { throw new Error("connection refused"); };
|
||||
t3.teardown(() => { globalThis.fetch = realFetch; });
|
||||
|
||||
await plugin.postWebhook("https://down.example/hook", {});
|
||||
state.fetchResult = () => { throw new Error("connection refused"); };
|
||||
await create("bob", "griefing", "alice");
|
||||
await settle();
|
||||
t3.strictSame(state.warnings, ["Webhook https://down.example/hook failed: connection refused"]);
|
||||
|
||||
globalThis.fetch = async () => ({ ok: false, status: 404 });
|
||||
await plugin.postWebhook("https://down.example/hook", {});
|
||||
state.fetchResult = () => ({ ok: false, status: 404 });
|
||||
await create("bob", "griefing", "carol");
|
||||
await settle();
|
||||
t3.strictSame(state.warnings[1], "Webhook https://down.example/hook responded with 404");
|
||||
});
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -25,7 +25,7 @@ class TestConnector extends lib.BaseConnector {
|
||||
|
||||
const report = (id, playerName, byPlayerName) => new messages.ReportRecord(id, playerName, byPlayerName, "griefing", "EXP", 1000);
|
||||
|
||||
/** Build a plugin around a real running instance with spies on what leaves it. */
|
||||
/** Run the plugin on a real running instance with spies on what leaves it, returns the IPC handlers it registered. */
|
||||
async function startPlugin(t2, { reports = [report(1, "bob", "alice"), report(2, "bob", "carol")] } = {}) {
|
||||
const instanceConfig = new lib.InstanceConfig("host");
|
||||
instanceConfig.set("instance.id", 1);
|
||||
@@ -37,8 +37,9 @@ async function startPlugin(t2, { reports = [report(1, "bob", "alice"), report(2,
|
||||
|
||||
// Spies which record the messages and commands leaving the instance
|
||||
const state = { sent: [], rcons: [], failNext: null };
|
||||
const ipc = new Map();
|
||||
instance.server = {
|
||||
handle: () => {},
|
||||
handle: (name, handler) => ipc.set(name, handler),
|
||||
sendRcon: async command => {
|
||||
state.rcons.push(command);
|
||||
return "";
|
||||
@@ -63,8 +64,14 @@ async function startPlugin(t2, { reports = [report(1, "bob", "alice"), report(2,
|
||||
instance.notifyStatus("running");
|
||||
state.sent.length = 0;
|
||||
|
||||
const plugin = await InstancePlugin.fromContext({ plugin: { name: "exp_reports" }, instance, host: {}, logger });
|
||||
return { plugin, instance, state };
|
||||
await entrypoint({ plugin: { name: "exp_reports" }, instance, host: {}, logger });
|
||||
return {
|
||||
instance,
|
||||
state,
|
||||
createIPC: event => ipc.get("exp_reports:create")(event),
|
||||
listIPC: event => ipc.get("exp_reports:list")(event),
|
||||
deleteIPC: event => ipc.get("exp_reports:delete")(event),
|
||||
};
|
||||
}
|
||||
|
||||
/** The lua receiver and payload of a recorded rcon command. */
|
||||
@@ -73,10 +80,10 @@ function decodeRcon(command) {
|
||||
return { receiver: match[1], payload: JSON.parse(match[2]) };
|
||||
}
|
||||
|
||||
t.test("class InstancePlugin", t2 => {
|
||||
t2.test(".handleCreateIPC() creates the report and hands it to lua with the others against the player", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
await plugin.handleCreateIPC({ player_name: "bob", by_player_name: "dave", reason: "griefing" });
|
||||
t.test("instance plugin", t2 => {
|
||||
t2.test("exp_reports:create creates the report and hands it to lua with the others against the player", async t3 => {
|
||||
const { state, createIPC } = await startPlugin(t3);
|
||||
await createIPC({ player_name: "bob", by_player_name: "dave", reason: "griefing" });
|
||||
|
||||
const create = state.sent.find(request => request instanceof messages.ReportCreateRequest);
|
||||
t3.strictSame([create.playerName, create.byPlayerName, create.reason], ["bob", "dave", "griefing"]);
|
||||
@@ -89,20 +96,20 @@ t.test("class InstancePlugin", t2 => {
|
||||
t3.strictSame(payload.reports.map(other => other.by_player_name), ["alice", "carol"], "along with the existing ones");
|
||||
});
|
||||
|
||||
t2.test(".handleCreateIPC() prints a refusal to the reporter", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
t2.test("exp_reports:create prints a refusal to the reporter", async t3 => {
|
||||
const { state, createIPC } = await startPlugin(t3);
|
||||
state.failNext = new lib.RequestError("dave has already reported bob");
|
||||
await plugin.handleCreateIPC({ player_name: "bob", by_player_name: "dave", reason: "griefing" });
|
||||
await createIPC({ player_name: "bob", by_player_name: "dave", reason: "griefing" });
|
||||
|
||||
const { receiver, payload } = decodeRcon(state.rcons[0]);
|
||||
t3.strictSame(receiver, "receive_error");
|
||||
t3.strictSame(payload, { caller: "dave", message: "dave has already reported bob" });
|
||||
});
|
||||
|
||||
t2.test(".handleListIPC() lists the reports for the caller", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
await plugin.handleListIPC({ caller: "admin", player_name: "bob" });
|
||||
await plugin.handleListIPC({ caller: "admin", player_name: undefined });
|
||||
t2.test("exp_reports:list lists the reports for the caller", async t3 => {
|
||||
const { state, listIPC } = await startPlugin(t3);
|
||||
await listIPC({ caller: "admin", player_name: "bob" });
|
||||
await listIPC({ caller: "admin", player_name: undefined });
|
||||
|
||||
const forPlayer = decodeRcon(state.rcons[0]);
|
||||
t3.strictSame(forPlayer.receiver, "receive_list");
|
||||
@@ -113,9 +120,9 @@ t.test("class InstancePlugin", t2 => {
|
||||
t3.strictSame(forAll.payload.player_name, undefined, "no player when listing everyone");
|
||||
});
|
||||
|
||||
t2.test(".handleDeleteIPC() deletes only the matching reports", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
await plugin.handleDeleteIPC({ caller: "admin", player_name: "bob", by_player_name: "carol" });
|
||||
t2.test("exp_reports:delete deletes only the matching reports", async t3 => {
|
||||
const { state, deleteIPC } = await startPlugin(t3);
|
||||
await deleteIPC({ caller: "admin", player_name: "bob", by_player_name: "carol" });
|
||||
|
||||
const deletes = state.sent.filter(request => request instanceof messages.ReportDeleteRequest);
|
||||
t3.strictSame(deletes.map(request => request.id), [2], "only carol's report is deleted");
|
||||
@@ -124,17 +131,17 @@ t.test("class InstancePlugin", t2 => {
|
||||
t3.strictSame(payload, { caller: "admin", player_name: "bob", by_player_name: "carol", count: 1 });
|
||||
|
||||
state.sent.length = 0;
|
||||
await plugin.handleDeleteIPC({ caller: "admin", player_name: "bob", by_player_name: undefined });
|
||||
await deleteIPC({ caller: "admin", player_name: "bob", by_player_name: undefined });
|
||||
t3.strictSame(
|
||||
state.sent.filter(request => request instanceof messages.ReportDeleteRequest).length, 2,
|
||||
"every report is deleted without a reporter",
|
||||
);
|
||||
});
|
||||
|
||||
t2.test(".luaSend() drops answers once the instance has stopped", async t3 => {
|
||||
const { plugin, instance, state } = await startPlugin(t3);
|
||||
t2.test("answers are dropped once the instance has stopped", async t3 => {
|
||||
const { instance, state, listIPC } = await startPlugin(t3);
|
||||
instance.notifyStatus("stopped");
|
||||
await plugin.handleListIPC({ caller: "admin", player_name: undefined });
|
||||
await listIPC({ caller: "admin", player_name: undefined });
|
||||
t3.strictSame(state.rcons, [], "nothing is sent to a stopped instance");
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user