Convert global_chat, research_sync and statistics_exporter to entrypoint functions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-10-08 05:15:00 +00:00
1 parent bd609c3c54
commit cfeb4b6a4a
7 files changed
+231 -237

No files matched your search

+62 -73
View File
@@ -1,6 +1,6 @@
import fs from "node:fs/promises";
import path from "path";
import { BaseControllerPlugin } from "@clusterio/controller";
import type { ControllerPluginContext } from "@clusterio/controller";
import { Static } from "@sinclair/typebox";
import * as lib from "@clusterio/lib";
@@ -49,61 +49,39 @@ async function saveTechnologies(
await lib.safeOutputFile(filePath, JSON.stringify([...technologies.entries()], null, "\t"));
}
export class ControllerPlugin extends BaseControllerPlugin {
technologies!: Map<string, Technology>;
technologiesDirty = true;
progressRateLimiter!: lib.RateLimiter;
progressBroadcastId!: ReturnType<typeof setInterval> | null;
progressToBroadcast!: Set<string>;
export default async function(context: ControllerPluginContext) {
const { controller, logger, plugin } = context;
const technologies = await loadTechnologies(controller.config, logger);
let technologiesDirty = true;
const progressToBroadcast = new Set<string>();
async init() {
this.technologies = await loadTechnologies(this.controller.config, this.logger);
this.progressRateLimiter = new RateLimiter({
maxRate: 1,
action: () => this.broadcastProgress(),
});
this.progressBroadcastId = null;
this.progressToBroadcast = new Set();
this.controller.handle(ContributionEvent, this.handleContributionEvent.bind(this));
this.controller.handle(FinishedEvent, this.handleFinishedEvent.bind(this));
this.controller.handle(SyncTechnologiesRequest, this.handleSyncTechnologiesRequest.bind(this));
}
async onSaveData() {
if (this.technologiesDirty) {
this.technologiesDirty = false;
await saveTechnologies(this.controller.config, this.technologies, this.logger);
}
}
async onShutdown() {
this.progressRateLimiter.cancel();
}
broadcastProgress() {
function broadcastProgress() {
let techs = [];
for (let name of this.progressToBroadcast) {
let tech = this.technologies.get(name);
for (let name of progressToBroadcast) {
let tech = technologies.get(name);
if (tech && tech.progress) {
techs.push(new TechnologyProgress(name, tech.level, tech.progress));
}
}
this.progressToBroadcast.clear();
progressToBroadcast.clear();
if (techs.length) {
this.controller.sendTo("allInstances", new ProgressEvent(techs));
controller.sendTo("allInstances", new ProgressEvent(techs));
}
}
async handleContributionEvent(event: ContributionEvent) {
const progressRateLimiter = new RateLimiter({
maxRate: 1,
action: broadcastProgress,
});
controller.handle(ContributionEvent, async (event: ContributionEvent) => {
let { name, level, contribution } = event;
let tech = this.technologies.get(name);
let tech = technologies.get(name);
if (!tech) {
tech = { level, progress: 0, researched: false };
this.technologies.set(name, tech);
this.technologiesDirty = true;
technologies.set(name, tech);
technologiesDirty = true;
// Ignore contribution to already researched technologies
} else if (tech.level > level || tech.level === level && tech.researched) {
@@ -124,31 +102,31 @@ export class ControllerPlugin extends BaseControllerPlugin {
let newProgress = tech.progress! + contribution;
if (newProgress < 1) {
tech.progress = newProgress;
this.progressToBroadcast.add(name);
this.progressRateLimiter!.activate();
progressToBroadcast.add(name);
progressRateLimiter.activate();
} else {
tech.researched = true;
tech.progress = null;
this.progressToBroadcast.delete(name);
progressToBroadcast.delete(name);
this.controller.sendTo("allInstances", new FinishedEvent(name, tech.level));
controller.sendTo("allInstances", new FinishedEvent(name, tech.level));
}
this.technologiesDirty = true;
}
technologiesDirty = true;
});
async handleFinishedEvent(event: FinishedEvent) {
controller.handle(FinishedEvent, async (event: FinishedEvent) => {
let { name, level } = event;
let tech = this.technologies.get(name);
let tech = technologies.get(name);
if (!tech || tech.level <= level) {
this.controller.sendTo("allInstances", event);
this.progressToBroadcast.delete(name);
this.technologies.set(name, { level, progress: null, researched: true });
this.technologiesDirty = true;
controller.sendTo("allInstances", event);
progressToBroadcast.delete(name);
technologies.set(name, { level, progress: null, researched: true });
technologiesDirty = true;
}
}
});
async handleSyncTechnologiesRequest(request: SyncTechnologiesRequest): Promise<TechnologySync[]> {
controller.handle(SyncTechnologiesRequest, async (request: SyncTechnologiesRequest): Promise<TechnologySync[]> => {
function baseLevel(name: string): number {
let match = /-(\d+)$/.exec(name);
if (!match) {
@@ -159,14 +137,14 @@ export class ControllerPlugin extends BaseControllerPlugin {
for (let instanceTech of request.technologies) {
let { name, level, progress, researched } = instanceTech;
let tech = this.technologies.get(name);
let tech = technologies.get(name);
if (!tech) {
this.technologies.set(name, { level, progress, researched });
this.technologiesDirty = true;
technologies.set(name, { level, progress, researched });
technologiesDirty = true;
if (progress) {
this.progressToBroadcast.add(name);
progressToBroadcast.add(name);
} else if (researched || baseLevel(name) !== level) {
this.controller.sendTo("allInstances", new FinishedEvent(name, level));
controller.sendTo("allInstances", new FinishedEvent(name, level));
}
} else {
@@ -177,33 +155,44 @@ export class ControllerPlugin extends BaseControllerPlugin {
if (tech.level < level || researched) {
// Send update if the unlocked level is greater
if (level - Number(!researched) > tech.level - Number(!tech.researched)) {
this.controller.sendTo("allInstances", new FinishedEvent(name, level - Number(!researched)));
controller.sendTo("allInstances", new FinishedEvent(name, level - Number(!researched)));
}
tech.level = level;
tech.progress = progress;
tech.researched = researched;
if (progress) {
this.progressToBroadcast.add(name);
progressToBroadcast.add(name);
} else {
this.progressToBroadcast.delete(name);
progressToBroadcast.delete(name);
}
this.technologiesDirty = true;
technologiesDirty = true;
} else if (tech.progress && progress && tech.progress < progress) {
tech.progress = progress;
this.progressToBroadcast.add(name);
this.technologiesDirty = true;
progressToBroadcast.add(name);
technologiesDirty = true;
}
}
}
this.progressRateLimiter.activate();
progressRateLimiter.activate();
let technologies = [];
for (let [name, tech] of this.technologies) {
technologies.push(new TechnologySync(name, tech.level, tech.progress, tech.researched));
let result = [];
for (let [name, tech] of technologies) {
result.push(new TechnologySync(name, tech.level, tech.progress, tech.researched));
}
return technologies;
}
return result;
});
controller.hooks.save.attach(plugin.name, async () => {
if (technologiesDirty) {
technologiesDirty = false;
await saveTechnologies(controller.config, technologies, logger);
}
});
controller.hooks.shutdown.attach(plugin.name, async () => {
progressRateLimiter.cancel();
});
}
+39 -36
View File
@@ -1,5 +1,5 @@
import * as lib from "@clusterio/lib";
import { BaseInstancePlugin } from "@clusterio/host";
import type { InstancePluginContext } from "@clusterio/host";
import {
ContributionEvent,
ProgressEvent,
@@ -19,54 +19,57 @@ type IpcFinished = {
level: number,
};
export class InstancePlugin extends BaseInstancePlugin {
syncStarted!: boolean;
export default async function(context: InstancePluginContext) {
const { instance, logger, plugin } = context;
let syncStarted = false;
unexpectedError(err: Error) {
this.logger.error(`Unexpected error:\n${err.stack}`);
// Commands are sent one at a time so they execute in order
let rconQueue: Promise<unknown> = Promise.resolve();
function sendOrderedRcon(message: string, expectEmpty = false) {
const result = rconQueue.then(() => instance.sendRcon(message, expectEmpty, plugin.name));
rconQueue = result.catch(() => {});
return result;
}
async init() {
this.instance.server.on("ipc-research_sync:contribution", (tech: IpcContribution) => {
this.researchContribution(tech).catch(err => this.unexpectedError(err));
});
this.instance.server.on("ipc-research_sync:finished", (tech: IpcFinished) => {
this.researchFinished(tech).catch(err => this.unexpectedError(err));
});
this.syncStarted = false;
this.instance.handle(ProgressEvent, this.handleProgressEvent.bind(this));
this.instance.handle(FinishedEvent, this.handleFinishedEvent.bind(this));
function unexpectedError(err: Error) {
logger.error(`Unexpected error:\n${err.stack}`);
}
async researchContribution(tech: IpcContribution) {
this.instance.sendTo("controller", new ContributionEvent(tech.name, tech.level, tech.contribution));
async function researchContribution(tech: IpcContribution) {
instance.sendTo("controller", new ContributionEvent(tech.name, tech.level, tech.contribution));
}
async handleProgressEvent(event: ProgressEvent) {
if (!this.syncStarted || !["starting", "running"].includes(this.instance.status)) {
async function researchFinished(tech: IpcFinished) {
instance.sendTo("controller", new FinishedEvent(tech.name, tech.level));
}
instance.server.on("ipc-research_sync:contribution", (tech: IpcContribution) => {
researchContribution(tech).catch(err => unexpectedError(err));
});
instance.server.on("ipc-research_sync:finished", (tech: IpcFinished) => {
researchFinished(tech).catch(err => unexpectedError(err));
});
instance.handle(ProgressEvent, async (event: ProgressEvent) => {
if (!syncStarted || !["starting", "running"].includes(instance.status)) {
return;
}
let techsJson = lib.escapeString(JSON.stringify(event.technologies));
await this.sendOrderedRcon(`/sc research_sync.update_progress("${techsJson}")`, true);
}
await sendOrderedRcon(`/sc research_sync.update_progress("${techsJson}")`, true);
});
async researchFinished(tech: IpcFinished) {
this.instance.sendTo("controller", new FinishedEvent(tech.name, tech.level));
}
async handleFinishedEvent(event: FinishedEvent) {
if (!this.syncStarted || !["starting", "running"].includes(this.instance.status)) {
instance.handle(FinishedEvent, async (event: FinishedEvent) => {
if (!syncStarted || !["starting", "running"].includes(instance.status)) {
return;
}
let { name, level } = event;
await this.sendOrderedRcon(
await sendOrderedRcon(
`/sc research_sync.research_technology("${lib.escapeString(name)}", ${level})`, true
);
}
});
async onStart() {
let dumpJson = await this.sendOrderedRcon("/sc research_sync.dump_technologies()");
instance.hooks.start.attach(plugin.name, async () => {
let dumpJson = await sendOrderedRcon("/sc research_sync.dump_technologies()");
let techsToSend = [];
let instanceTechs = new Map();
for (let tech of JSON.parse(dumpJson)) {
@@ -79,8 +82,8 @@ export class InstancePlugin extends BaseInstancePlugin {
instanceTechs.set(tech.name, tech);
}
let controllerTechs = await this.instance.sendTo("controller", new SyncTechnologiesRequest(techsToSend));
this.syncStarted = true;
let controllerTechs = await instance.sendTo("controller", new SyncTechnologiesRequest(techsToSend));
syncStarted = true;
let techsToSync = [];
for (let controllerTech of controllerTechs) {
let { name, level, progress, researched } = controllerTech;
@@ -97,7 +100,7 @@ export class InstancePlugin extends BaseInstancePlugin {
if (techsToSync.length) {
let syncJson = lib.escapeString(JSON.stringify(techsToSync));
await this.sendOrderedRcon(`/sc research_sync.sync_technologies("${syncJson}")`, true);
await sendOrderedRcon(`/sc research_sync.sync_technologies("${syncJson}")`, true);
}
}
});
}