Convert subspace_storage 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:47 +00:00
1 parent 1ca0c658b9
commit 60dbb461e7
5 files changed
+363 -277

No files matched your search

+92 -95
View File
@@ -1,5 +1,5 @@
import * as lib from "@clusterio/lib";
import { BaseInstancePlugin } from "@clusterio/host";
import type { InstancePluginContext } from "@clusterio/host";
import {
PlaceEvent,
@@ -11,127 +11,124 @@ import {
type IpcItems = [name: string, count: number, quality: string][];
export class InstancePlugin extends BaseInstancePlugin {
pendingTasks!: Set<any>;
pingId?: ReturnType<typeof setTimeout>;
timeUpdateId?: ReturnType<typeof setInterval>;
cachedInventoryItems: Item[] = [];
export default async function(context: InstancePluginContext) {
const { instance, host, logger, plugin } = context;
const pendingTasks = new Set<Promise<unknown>>();
let pingId: ReturnType<typeof setInterval> | undefined;
let timeUpdateId: ReturnType<typeof setInterval> | undefined;
let cachedInventoryItems: Item[] = [];
unexpectedError(err: Error) {
this.logger.error(`Unexpected error:\n${err.stack}`);
}
async init() {
this.pendingTasks = new Set();
this.instance.server.on("ipc-subspace_storage:output", (output: IpcItems) => {
this.logger.info("Received output items:");
this.logger.info(JSON.stringify(output));
this.provideItems(output).catch(err => this.unexpectedError(err));
});
this.instance.server.on("ipc-subspace_storage:orders", (orders: IpcItems) => {
if (this.instance.status !== "running" || !this.host.connected) {
return;
}
let task = this.requestItems(orders).catch(err => this.unexpectedError(err));
this.pendingTasks.add(task);
task.finally(() => { this.pendingTasks.delete(task); });
});
this.instance.handle(UpdateStorageEvent, this.handleUpdateStorageEvent.bind(this));
}
async onStart() {
this.pingId = setInterval(() => {
if (!this.host.connected) {
return; // Only ping if we are actually connected to the controller.
}
this.sendRcon(
"/sc __subspace_storage__ global.ticksSinceMasterPinged = 0", true
).catch(err => this.unexpectedError(err));
}, 5000);
let items = await this.instance.sendTo("controller", new GetStorageRequest());
// Cache items for periodic time updates
this.cachedInventoryItems = items;
// Ensure a payload with updated time is sent every second
this.timeUpdateId = setInterval(() => {
if (this.instance.status !== "running") {
return;
}
const payloadItems = [
...this.cachedInventoryItems,
new Item("signal-unixtime", Math.floor(Date.now() / 1000), "normal"),
];
const payloadJson = lib.escapeString(JSON.stringify(payloadItems));
const task = this.sendRcon(`/sc __subspace_storage__ UpdateInvData("${payloadJson}")`, true)
.catch(err => this.unexpectedError(err));
this.pendingTasks.add(task);
task.finally(() => { this.pendingTasks.delete(task); });
}, 1000);
}
async onStop() {
clearInterval(this.pingId);
clearInterval(this.timeUpdateId);
await Promise.all(this.pendingTasks);
}
onExit() {
clearInterval(this.pingId);
clearInterval(this.timeUpdateId);
function unexpectedError(err: Error) {
logger.error(`Unexpected error:\n${err.stack}`);
}
// provide items --------------------------------------------------------------
async provideItems(items: IpcItems) {
if (!this.host.connector.hasSession) {
async function provideItems(items: IpcItems) {
if (!host.connector.hasSession) {
// For now the items are voided if the controller connection is
// down, which is no different from the previous behaviour.
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
this.logger.verbose("Voided the following items:");
this.logger.verbose(JSON.stringify(items));
if (instance.config.get("subspace_storage.log_item_transfers")) {
logger.verbose("Voided the following items:");
logger.verbose(JSON.stringify(items));
}
return;
}
const fromIpcItems = items.map(item => new Item(item[0], item[1], item[2]));
this.instance.sendTo("controller", new PlaceEvent(fromIpcItems));
instance.sendTo("controller", new PlaceEvent(fromIpcItems));
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
this.logger.verbose("Exported the following to controller:");
this.logger.verbose(JSON.stringify(items));
if (instance.config.get("subspace_storage.log_item_transfers")) {
logger.verbose("Exported the following to controller:");
logger.verbose(JSON.stringify(items));
}
}
// request items --------------------------------------------------------------
async requestItems(requestItems: IpcItems) {
this.logger.info(`Requesting items: ${JSON.stringify(requestItems)}`);
async function requestItems(orders: IpcItems) {
logger.info(`Requesting items: ${JSON.stringify(orders)}`);
// Request the items all at once
const fromIpcItems = requestItems.map(item => new Item(item[0], item[1], item[2]));
let items = await this.instance.sendTo("controller", new RemoveRequest(fromIpcItems));
const fromIpcItems = orders.map(item => new Item(item[0], item[1], item[2]));
let items = await instance.sendTo("controller", new RemoveRequest(fromIpcItems));
if (!items.length) {
return;
}
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
this.logger.verbose("Imported following from controller:");
this.logger.verbose(JSON.stringify(items));
if (instance.config.get("subspace_storage.log_item_transfers")) {
logger.verbose("Imported following from controller:");
logger.verbose(JSON.stringify(items));
}
let itemsJson = lib.escapeString(JSON.stringify(items));
await this.sendRcon(`/sc __subspace_storage__ Import("${itemsJson}")`, true);
await instance.sendRcon(`/sc __subspace_storage__ Import("${itemsJson}")`, true, plugin.name);
}
// combinator signals ---------------------------------------------------------
async handleUpdateStorageEvent(event: UpdateStorageEvent) {
if (this.instance.status !== "running") {
instance.server.on("ipc-subspace_storage:output", (output: IpcItems) => {
logger.info("Received output items:");
logger.info(JSON.stringify(output));
provideItems(output).catch(err => unexpectedError(err));
});
instance.server.on("ipc-subspace_storage:orders", (orders: IpcItems) => {
if (instance.status !== "running" || !host.connected) {
return;
}
// Cache latest inventory from controller
this.cachedInventoryItems = event.items;
}
let task = requestItems(orders).catch(err => unexpectedError(err));
pendingTasks.add(task);
task.finally(() => { pendingTasks.delete(task); });
});
// combinator signals ---------------------------------------------------------
instance.handle(UpdateStorageEvent, async (event: UpdateStorageEvent) => {
if (instance.status !== "running") {
return;
}
// Cache latest inventory from controller
cachedInventoryItems = event.items;
});
instance.hooks.start.attach(plugin.name, async () => {
pingId = setInterval(() => {
if (!host.connected) {
return; // Only ping if we are actually connected to the controller.
}
instance.sendRcon(
"/sc __subspace_storage__ global.ticksSinceMasterPinged = 0", true, plugin.name
).catch(err => unexpectedError(err));
}, 5000);
let items = await instance.sendTo("controller", new GetStorageRequest());
// Cache items for periodic time updates
cachedInventoryItems = items;
// Ensure a payload with updated time is sent every second
timeUpdateId = setInterval(() => {
if (instance.status !== "running") {
return;
}
const payloadItems = [
...cachedInventoryItems,
new Item("signal-unixtime", Math.floor(Date.now() / 1000), "normal"),
];
const payloadJson = lib.escapeString(JSON.stringify(payloadItems));
const task = instance.sendRcon(
`/sc __subspace_storage__ UpdateInvData("${payloadJson}")`, true, plugin.name
).catch(err => unexpectedError(err));
pendingTasks.add(task);
task.finally(() => { pendingTasks.delete(task); });
}, 1000);
});
instance.hooks.stop.attach(plugin.name, async () => {
clearInterval(pingId);
clearInterval(timeUpdateId);
await Promise.all(pendingTasks);
});
instance.hooks.exit.attach(plugin.name, () => {
clearInterval(pingId);
clearInterval(timeUpdateId);
});
}