mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-16 15:30:41 +09:00
Refactor link system to JSON serialisable class pattern
Reverse the direction of the API for sending messages from
messageDefinition.send(link, { content });
to
link.send(new MessageClass(content));
and convert all message definitions to use the JSON serialisable class
pattern and explicit registration of message handlers, along with a
end-to-end based routing of messages instead of link to link.
The experience I gained from the existing way messages were defined and
sent over links was that it was difficult to understand for people
unfamiliar with the system. The automatic registration of message
handlers ment that code was being called as if by magic from nowhere
with no easy way to discover it. The manual forwarding and rules for
what can be sent where and how obscured its working.
The use of pure JSON as both input and output from message handlers made
it tedious to work with. Data had to be manually converted between the
program representation and the over the wire format, which made handler
code unplesant to write. Particularly because the over the wire format
used snake_case while the program code uses camelCase for variables.
The idea behind the decision to do it this way was to make it more clear
which data came from the wire and which from the program, and while this
worked it didn't make message handlers any nicer to write.
The direction of the API and magic registration of message handlers also
meant that a future migration to TypeScript would be troublesome. While
it may be possible to implement, the degree of TypeScript magic required
would go starkly against the principle of keep it simple stupid.
By refactoring to using the JSON serialisable class pattern most of
these issues go away. There is no longer a need to distinguish the on
wire format of messages with the program representation because the only
place that deals with the wire format of messages are the toJSON and
fromJSON methods on the classes themselves. Message handlers will work
with proper instances of classes instead of raw data, something that
makes them easier to write, and trivial to type with TypeScript.
End-to-end routing also simplifies sending messages that need to do
mulitple hops to reach the destination. And removes the need for having
all messages be specified in plugin's info module, as they can be routed
without having to be parsed completely.
The explicit registration of message handlers is something that I
thought would be tedious boilerplate code that could be automated away.
But experience now shows it to be the opposite. Allthough dull
repetition, the purpose it serves is to link together the code in a way
that humans can easily find. With explicit registration searching the
name of the message handler in the editor will show the registration that
ties it together with the type of message it handles and the kind of
registration. With implicit registration searching the name of the
message handler turns up only the handler with no clue as to what calls
it.
This commit is contained in:
1 parent
9a967a5779
commit
bcd94709d2
106 files changed
+8173
-4928
No files matched your search
@@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
const info = require("./info");
|
||||
const { ChatEvent } = require("./messages");
|
||||
const libCommand = require("@clusterio/lib/command");
|
||||
|
||||
|
||||
@@ -12,10 +12,7 @@ globalChatCommands.add(new libCommand.Command({
|
||||
yargs.positional("message", { describe: "message to send", type: "string" });
|
||||
}],
|
||||
handler: async function(args, control) {
|
||||
await info.messages.chat.send(control, {
|
||||
instance_name: "Console",
|
||||
content: args.message,
|
||||
});
|
||||
await control.sendTo(new ChatEvent("Console", args.message), "allInstances");
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"use strict";
|
||||
let { libLink } = require("@clusterio/lib");
|
||||
|
||||
module.exports = {
|
||||
name: "global_chat",
|
||||
@@ -7,17 +6,4 @@ module.exports = {
|
||||
description: "Forwards chat between instances.",
|
||||
instanceEntrypoint: "instance",
|
||||
controlEntrypoint: "control",
|
||||
|
||||
messages: {
|
||||
chat: new libLink.Event({
|
||||
type: "global_chat:chat",
|
||||
links: ["instance-host", "host-controller", "controller-host", "host-instance", "control-controller"],
|
||||
forwardTo: "controller",
|
||||
broadcastTo: "instance",
|
||||
eventProperties: {
|
||||
"instance_name": { type: "string" },
|
||||
"content": { type: "string" },
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
@@ -4,6 +4,7 @@
|
||||
"use strict";
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
||||
const { ChatEvent } = require("./messages");
|
||||
|
||||
|
||||
/**
|
||||
@@ -19,6 +20,7 @@ function removeTags(content) {
|
||||
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
async init() {
|
||||
this.messageQueue = [];
|
||||
this.instance.register(ChatEvent, this.handleChatEvent.bind(this));
|
||||
}
|
||||
|
||||
onControllerConnectionEvent(event) {
|
||||
@@ -30,17 +32,14 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
}
|
||||
}
|
||||
|
||||
async chatEventHandler(message) {
|
||||
async handleChatEvent(event) {
|
||||
// TODO check if cross server chat is enabled
|
||||
let content = `[${message.data.instance_name}] ${removeTags(message.data.content)}`;
|
||||
let content = `[${event.instanceName}] ${removeTags(event.content)}`;
|
||||
await this.sendRcon(`/sc game.print('${libLuaTools.escapeString(content)}')`, true);
|
||||
}
|
||||
|
||||
sendChat(message) {
|
||||
this.info.messages.chat.send(this.instance, {
|
||||
instance_name: this.instance.name,
|
||||
content: message,
|
||||
});
|
||||
this.instance.sendTo(new ChatEvent(this.instance.name, message), "allInstances");
|
||||
}
|
||||
|
||||
async onOutput(output) {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
|
||||
class ChatEvent {
|
||||
static type = "event";
|
||||
static src = ["control", "instance"];
|
||||
static dst = "instance";
|
||||
static plugin = "global_chat";
|
||||
|
||||
/** @type {string} */
|
||||
instanceName;
|
||||
/** @type {string} */
|
||||
content;
|
||||
|
||||
constructor(instanceName, content) {
|
||||
this.instanceName = instanceName;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["instanceName", "content"],
|
||||
properties: {
|
||||
instanceName: { type: "string" },
|
||||
content: { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.instanceName, json.content);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ChatEvent,
|
||||
};
|
||||
@@ -5,6 +5,7 @@ const mock = require("../../../test/mock");
|
||||
const lines = require("../../../test/lib/factorio/lines");
|
||||
const instance = require("../instance");
|
||||
const info = require("../info");
|
||||
const { ChatEvent } = require("../messages");
|
||||
|
||||
|
||||
describe("global_chat plugin", function() {
|
||||
@@ -28,10 +29,10 @@ describe("global_chat plugin", function() {
|
||||
await instancePlugin.init();
|
||||
});
|
||||
|
||||
describe(".chatEventHandler()", function() {
|
||||
describe(".handleChatEvent()", function() {
|
||||
it("should send received chat as command", async function() {
|
||||
instancePlugin.instance.server.rconCommands = [];
|
||||
await instancePlugin.chatEventHandler({ data: { instance_name: "test", content: "User: message" } });
|
||||
await instancePlugin.handleChatEvent(new ChatEvent("test", "User: message"));
|
||||
assert.deepEqual(
|
||||
instancePlugin.instance.server.rconCommands,
|
||||
["/sc game.print('[test] User: message')"],
|
||||
|
||||
@@ -5,6 +5,14 @@ const path = require("path");
|
||||
const libFileOps = require("@clusterio/lib/file_ops");
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
|
||||
const {
|
||||
AcquireRequest,
|
||||
ReleaseRequest,
|
||||
UploadRequest,
|
||||
DownloadRequest,
|
||||
DatabaseStatsRequest,
|
||||
} = require("./messages");
|
||||
|
||||
async function loadDatabase(config, logger) {
|
||||
let itemsPath = path.resolve(config.get("controller.database_directory"), "inventories.json");
|
||||
logger.verbose(`Loading ${itemsPath}`);
|
||||
@@ -39,6 +47,12 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
this.logger.error(`Unexpected error autosaving player data:\n${err.stack}`);
|
||||
});
|
||||
}, this.controller.config.get("inventory_sync.autosave_interval") * 1000);
|
||||
|
||||
this.controller.register(AcquireRequest, this.handleAcquireRequest.bind(this));
|
||||
this.controller.register(ReleaseRequest, this.handleReleaseRequest.bind(this));
|
||||
this.controller.register(UploadRequest, this.handleUploadRequest.bind(this));
|
||||
this.controller.register(DownloadRequest, this.handleDownloadRequest.bind(this));
|
||||
this.controller.register(DatabaseStatsRequest, this.handleDatabaseStatsRequest.bind(this));
|
||||
}
|
||||
|
||||
async onInstanceStatusChanged(instance) {
|
||||
@@ -84,10 +98,10 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
return false;
|
||||
}
|
||||
|
||||
async acquireRequestHandler(message) {
|
||||
let { instance_id, player_name } = message.data;
|
||||
if (!this.acquire(instance_id, player_name)) {
|
||||
let acquisitionRecord = this.acquiredPlayers.get(player_name);
|
||||
async handleAcquireRequest(request) {
|
||||
let { instanceId, playerName } = request;
|
||||
if (!this.acquire(instanceId, playerName)) {
|
||||
let acquisitionRecord = this.acquiredPlayers.get(playerName);
|
||||
let instance = this.controller.instances.get(acquisitionRecord.instanceId);
|
||||
return {
|
||||
status: "busy",
|
||||
@@ -95,75 +109,73 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
};
|
||||
}
|
||||
|
||||
let playerData = this.playerDatastore.get(player_name);
|
||||
return {
|
||||
status: "acquired",
|
||||
has_data: Boolean(playerData),
|
||||
generation: playerData ? playerData.generation : 0,
|
||||
};
|
||||
let playerData = this.playerDatastore.get(playerName);
|
||||
return new AcquireRequest.Response(
|
||||
"acquired",
|
||||
playerData ? playerData.generation : 0,
|
||||
Boolean(playerData),
|
||||
);
|
||||
}
|
||||
|
||||
async releaseRequestHandler(message) {
|
||||
let { instance_id, player_name } = message.data;
|
||||
let acquisitionRecord = this.acquiredPlayers.get(player_name);
|
||||
async handleReleaseRequest(request) {
|
||||
let { instanceId, playerName } = request;
|
||||
let acquisitionRecord = this.acquiredPlayers.get(playerName);
|
||||
if (!acquisitionRecord) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (acquisitionRecord.instanceId === instance_id) {
|
||||
this.acquiredPlayers.delete(player_name);
|
||||
if (acquisitionRecord.instanceId === instanceId) {
|
||||
this.acquiredPlayers.delete(playerName);
|
||||
}
|
||||
}
|
||||
|
||||
async uploadRequestHandler(message) {
|
||||
let { instance_id, player_name, player_data } = message.data;
|
||||
let instanceName = this.controller.instances.get(instance_id).config.get("instance.name");
|
||||
async handleUploadRequest(request) {
|
||||
let { instanceId, playerName, playerData } = request;
|
||||
let instanceName = this.controller.instances.get(instanceId).config.get("instance.name");
|
||||
let store = true;
|
||||
let acquisitionRecord = this.acquiredPlayers.get(player_name);
|
||||
let acquisitionRecord = this.acquiredPlayers.get(playerName);
|
||||
if (!acquisitionRecord) {
|
||||
this.logger.warn(`${instanceName} uploaded ${player_name} without an acquisition`);
|
||||
this.logger.warn(`${instanceName} uploaded ${playerName} without an acquisition`);
|
||||
// Allow upload in this case as it might come from a crashed instance that restarted and is now
|
||||
// uploading the player data for all the players that were online during the last autosave.
|
||||
|
||||
} else if (acquisitionRecord.instanceId !== instance_id) {
|
||||
this.logger.warn(`${instanceName} uploaded ${player_name} while another instance has acquired it`);
|
||||
} else if (acquisitionRecord.instanceId !== instanceId) {
|
||||
this.logger.warn(`${instanceName} uploaded ${playerName} while another instance has acquired it`);
|
||||
store = false;
|
||||
|
||||
} else {
|
||||
this.acquiredPlayers.delete(player_name);
|
||||
this.acquiredPlayers.delete(playerName);
|
||||
}
|
||||
|
||||
this.acquiredPlayers.delete(player_name);
|
||||
let oldPlayerData = this.playerDatastore.get(player_name);
|
||||
if (store && oldPlayerData && oldPlayerData.generation >= player_data.generation) {
|
||||
this.acquiredPlayers.delete(playerName);
|
||||
let oldPlayerData = this.playerDatastore.get(playerName);
|
||||
if (store && oldPlayerData && oldPlayerData.generation >= playerData.generation) {
|
||||
this.logger.warn(
|
||||
`${instanceName} uploaded generation ${player_data.generation} while the stored` +
|
||||
`generation is ${oldPlayerData.generation} for ${player_name}`
|
||||
`${instanceName} uploaded generation ${playerData.generation} while the stored` +
|
||||
`generation is ${oldPlayerData.generation} for ${playerName}`
|
||||
);
|
||||
store = false;
|
||||
}
|
||||
|
||||
if (store) {
|
||||
this.logger.verbose(`Received player data for ${player_name} from ${instanceName}`);
|
||||
this.playerDatastore.set(player_name, player_data);
|
||||
this.logger.verbose(`Received player data for ${playerName} from ${instanceName}`);
|
||||
this.playerDatastore.set(playerName, playerData);
|
||||
}
|
||||
}
|
||||
|
||||
async downloadRequestHandler(message) {
|
||||
let { instance_id, player_name } = message.data;
|
||||
let instanceName = this.controller.instances.get(instance_id).config.get("instance.name");
|
||||
async handleDownloadRequest(request) {
|
||||
let { instanceId, playerName } = request;
|
||||
let instanceName = this.controller.instances.get(instanceId).config.get("instance.name");
|
||||
|
||||
let acquisitionRecord = this.acquiredPlayers.get(player_name);
|
||||
let acquisitionRecord = this.acquiredPlayers.get(playerName);
|
||||
if (!acquisitionRecord) {
|
||||
this.logger.warn(`${instanceName} downloaded ${player_name} without an acquisition`);
|
||||
} else if (acquisitionRecord.instanceId !== instance_id) {
|
||||
this.logger.warn(`${instanceName} downloaded ${player_name} while another instance has acquired it`);
|
||||
this.logger.warn(`${instanceName} downloaded ${playerName} without an acquisition`);
|
||||
} else if (acquisitionRecord.instanceId !== instanceId) {
|
||||
this.logger.warn(`${instanceName} downloaded ${playerName} while another instance has acquired it`);
|
||||
}
|
||||
|
||||
this.logger.verbose(`Sending player data for ${player_name} to ${instanceName}`);
|
||||
return {
|
||||
player_data: this.playerDatastore.get(player_name) || null,
|
||||
};
|
||||
this.logger.verbose(`Sending player data for ${playerName} to ${instanceName}`);
|
||||
return new DownloadRequest.Response(this.playerDatastore.get(playerName) || null);
|
||||
}
|
||||
|
||||
async onShutdown() {
|
||||
@@ -171,21 +183,21 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
await saveDatabase(this.controller.config, this.playerDatastore, this.logger);
|
||||
}
|
||||
|
||||
async databaseStatsRequestHandler(message) {
|
||||
async handleDatabaseStatsRequest() {
|
||||
let playerDatastore = Array.from(this.playerDatastore.keys())
|
||||
.map(name => ({
|
||||
name,
|
||||
length: JSON.stringify(this.playerDatastore.get(name)).length,
|
||||
}))
|
||||
.sort((a, b) => a.length - b.length);
|
||||
return {
|
||||
database_size: playerDatastore.map(x => x.length).reduce((a, b) => b - a, 0),
|
||||
database_entries: playerDatastore.length,
|
||||
largest_entry: {
|
||||
.sort((a, b) => b.length - a.length);
|
||||
return new DatabaseStatsRequest.Response(
|
||||
playerDatastore.map(x => x.length).reduce((a, b) => b - a, 0),
|
||||
playerDatastore.length,
|
||||
{
|
||||
name: playerDatastore[0] && playerDatastore[0].name || "-",
|
||||
size: playerDatastore[0] && playerDatastore[0].length || 0,
|
||||
},
|
||||
};
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use strict";
|
||||
const { libConfig, libLink, libUsers } = require("@clusterio/lib");
|
||||
const { libConfig, libUsers } = require("@clusterio/lib");
|
||||
|
||||
class ControllerConfigGroup extends libConfig.PluginConfigGroup { }
|
||||
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
||||
@@ -53,70 +53,4 @@ module.exports = {
|
||||
|
||||
webEntrypoint: "./web",
|
||||
routes: ["/inventory"],
|
||||
|
||||
messages: {
|
||||
acquire: new libLink.Request({
|
||||
type: "inventory_sync:acquire",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
requestProperties: {
|
||||
"instance_id": { type: "integer" },
|
||||
"player_name": { type: "string" },
|
||||
},
|
||||
responseRequired: ["status"],
|
||||
responseProperties: {
|
||||
"status": { enum: ["acquired", "error", "busy"] },
|
||||
"generation": { type: "integer" },
|
||||
"has_data": { type: "boolean" },
|
||||
"message": { type: "string" },
|
||||
},
|
||||
}),
|
||||
release: new libLink.Request({
|
||||
type: "inventory_sync:release",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
requestProperties: {
|
||||
"instance_id": { type: "integer" },
|
||||
"player_name": { type: "string" },
|
||||
},
|
||||
}),
|
||||
upload: new libLink.Request({
|
||||
type: "inventory_sync:upload",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
requestProperties: {
|
||||
"instance_id": { type: "integer" },
|
||||
"player_name": { type: "string" },
|
||||
"player_data": { type: "object" },
|
||||
},
|
||||
}),
|
||||
download: new libLink.Request({
|
||||
type: "inventory_sync:download",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
requestProperties: {
|
||||
"instance_id": { type: "integer" },
|
||||
"player_name": { type: "string" },
|
||||
},
|
||||
responseProperties: {
|
||||
"player_data": { type: ["object", "null"] },
|
||||
},
|
||||
}),
|
||||
databaseStats: new libLink.Request({
|
||||
type: "inventory_sync:databaseStats",
|
||||
links: ["control-controller"],
|
||||
permission: "inventory_sync.inventory.view",
|
||||
responseProperties: {
|
||||
"database_size": { type: "integer" },
|
||||
"database_entries": { type: "integer" },
|
||||
"largest_entry": {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
size: { type: "number" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
@@ -6,6 +6,14 @@ const libErrors = require("@clusterio/lib/errors");
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
||||
|
||||
const {
|
||||
AcquireRequest,
|
||||
ReleaseRequest,
|
||||
UploadRequest,
|
||||
DownloadRequest,
|
||||
DatabaseStatsRequest,
|
||||
} = require("./messages");
|
||||
|
||||
/**
|
||||
* Splits string into array of strings with max of a certain length
|
||||
* @param {Number} chunkSize - Max length of each chunk
|
||||
@@ -45,10 +53,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
return;
|
||||
}
|
||||
this.playersToRelease.delete(player);
|
||||
await this.info.messages.release.send(this.instance, {
|
||||
instance_id: this.instance.id,
|
||||
player_name,
|
||||
});
|
||||
await this.instance.sendTo(new ReleaseRequest(this.instance.id, player_name), "controller");
|
||||
}
|
||||
})().catch(
|
||||
err => this.logger.error(`Unpexpected error releasing queued up players:\n${err.stack}`)
|
||||
@@ -65,12 +70,16 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
|
||||
if (this.host.connector.connected && !this.disconnecting) {
|
||||
try {
|
||||
let acquireResponse = await this.instance.sendTo(
|
||||
new AcquireRequest(this.instance.id, request.player_name),
|
||||
"controller"
|
||||
);
|
||||
response = {
|
||||
player_name: request.player_name,
|
||||
...await this.info.messages.acquire.send(this.instance, {
|
||||
instance_id: this.instance.id,
|
||||
player_name: request.player_name,
|
||||
}),
|
||||
status: acquireResponse.status,
|
||||
generation: acquireResponse.generation,
|
||||
has_data: acquireResponse.hasData,
|
||||
message: acquireResponse.message,
|
||||
};
|
||||
} catch (err) {
|
||||
if (!(err instanceof libErrors.SessionLost)) {
|
||||
@@ -90,10 +99,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
}
|
||||
|
||||
try {
|
||||
await this.info.messages.release.send(this.instance, {
|
||||
instance_id: this.instance.id,
|
||||
player_name: request.player_name,
|
||||
});
|
||||
await this.instance.sendTo(new ReleaseRequest(this.instance.id, request.player_name), "controller");
|
||||
} catch (err) {
|
||||
if (err instanceof libErrors.SessionLost) {
|
||||
this.playersToRelease.set(request.player_name);
|
||||
@@ -110,11 +116,10 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
|
||||
this.logger.verbose(`Uploading ${player_data.name} (${JSON.stringify(player_data).length / 1000}kB)`);
|
||||
try {
|
||||
await this.info.messages.upload.send(this.instance, {
|
||||
instance_id: this.instance.id,
|
||||
player_name: player_data.name,
|
||||
player_data: player_data,
|
||||
});
|
||||
await this.instance.sendTo(
|
||||
new UploadRequest(this.instance.id, player_data.name, player_data),
|
||||
"controller"
|
||||
);
|
||||
|
||||
} catch (err) {
|
||||
if (!(err instanceof libErrors.SessionLost)) {
|
||||
@@ -129,27 +134,24 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
}
|
||||
|
||||
async handleDownload(request) {
|
||||
const player_name = request.player_name;
|
||||
this.logger.verbose(`Downloading ${player_name}`);
|
||||
const playerName = request.player_name;
|
||||
this.logger.verbose(`Downloading ${playerName}`);
|
||||
|
||||
let response = await this.info.messages.download.send(this.instance, {
|
||||
instance_id: this.instance.id,
|
||||
player_name,
|
||||
});
|
||||
let response = await this.instance.sendTo(new DownloadRequest(this.instance.id, playerName), "controller");
|
||||
|
||||
if (!response.player_data) {
|
||||
await this.sendRcon(`/sc inventory_sync.download_inventory('${player_name}',nil,0,0)`, true);
|
||||
await this.sendRcon(`/sc inventory_sync.download_inventory('${playerName}',nil,0,0)`, true);
|
||||
return;
|
||||
}
|
||||
|
||||
const chunkSize = this.instance.config.get("inventory_sync.rcon_chunk_size");
|
||||
const chunks = chunkify(chunkSize, JSON.stringify(response.player_data));
|
||||
this.logger.verbose(`Sending inventory for ${player_name} in ${chunks.length} chunks`);
|
||||
this.logger.verbose(`Sending inventory for ${playerName} in ${chunks.length} chunks`);
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
// this.logger.verbose(`Sending chunk ${i+1} of ${chunks.length}`)
|
||||
const chunk = libLuaTools.escapeString(chunks[i]);
|
||||
await this.sendRcon(
|
||||
`/sc inventory_sync.download_inventory('${player_name}','${chunk}',${i + 1},${chunks.length})`,
|
||||
`/sc inventory_sync.download_inventory('${playerName}','${chunk}',${i + 1},${chunks.length})`,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
"use strict";
|
||||
|
||||
|
||||
class AcquireRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "inventory_sync";
|
||||
|
||||
/** @type {number} */
|
||||
instanceId;
|
||||
/** @type {string} */
|
||||
playerName;
|
||||
|
||||
constructor(instanceId, playerName) {
|
||||
this.instanceId = instanceId;
|
||||
this.playerName = playerName;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
"instanceId": { type: "integer" },
|
||||
"playerName": { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.instanceId, json.playerName);
|
||||
}
|
||||
}
|
||||
AcquireRequest.Response = class Response {
|
||||
/** @type {string} */
|
||||
status;
|
||||
/** @type {number} */
|
||||
generation;
|
||||
/** @type {boolean} */
|
||||
hasData;
|
||||
/** @type {string} */
|
||||
message;
|
||||
|
||||
constructor(status, generation, hasData, message) {
|
||||
this.status = status;
|
||||
if (generation !== undefined) { this.generation = generation; }
|
||||
if (hasData !== undefined) { this.hasData = hasData; }
|
||||
if (message !== undefined) { this.message = message; }
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
required: ["status"],
|
||||
properties: {
|
||||
"status": {
|
||||
type: "string",
|
||||
enum: ["acquired", "error", "busy"],
|
||||
},
|
||||
"generation": { type: "integer" },
|
||||
"hasData": { type: "boolean" },
|
||||
"message": { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.status, json.generation, json.hasData, json.message);
|
||||
}
|
||||
};
|
||||
|
||||
class ReleaseRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "inventory_sync";
|
||||
|
||||
/** @type {boolean} */
|
||||
instanceId;
|
||||
/** @type {boolean} */
|
||||
playerName;
|
||||
|
||||
constructor(instanceId, playerName) {
|
||||
this.instanceId = instanceId;
|
||||
this.playerName = playerName;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
"instanceId": { type: "integer" },
|
||||
"playerName": { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.instanceId, json.playerName);
|
||||
}
|
||||
}
|
||||
|
||||
class UploadRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "inventory_sync";
|
||||
|
||||
/** @type {boolean} */
|
||||
instanceId;
|
||||
/** @type {boolean} */
|
||||
playerName;
|
||||
/** @type {object} */
|
||||
playerData;
|
||||
|
||||
constructor(instanceId, playerName, playerData) {
|
||||
this.instanceId = instanceId;
|
||||
this.playerName = playerName;
|
||||
this.playerData = playerData;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["instanceId", "playerName", "playerData"],
|
||||
properties: {
|
||||
"instanceId": { type: "integer" },
|
||||
"playerName": { type: "string" },
|
||||
"playerData": { type: "object" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.instanceId, json.playerName, json.playerData);
|
||||
}
|
||||
}
|
||||
|
||||
class DownloadRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "inventory_sync";
|
||||
|
||||
/** @type {number} */
|
||||
instanceId;
|
||||
/** @type {string} */
|
||||
playerName;
|
||||
|
||||
constructor(instanceId, playerName) {
|
||||
this.instanceId = instanceId;
|
||||
this.playerName = playerName;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["instanceId", "playerName"],
|
||||
properties: {
|
||||
"instanceId": { type: "integer" },
|
||||
"playerName": { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.instanceId, json.playerName);
|
||||
}
|
||||
}
|
||||
DownloadRequest.Response = class Response {
|
||||
/** @type {?object} */
|
||||
playerData;
|
||||
|
||||
constructor(playerData) {
|
||||
this.playerData = playerData;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
required: ["playerData"],
|
||||
properties: {
|
||||
"playerData": { type: ["object", "null"] },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.playerData);
|
||||
}
|
||||
};
|
||||
|
||||
class DatabaseStatsRequest {
|
||||
static type = "request";
|
||||
static src = "control";
|
||||
static dst = "controller";
|
||||
static plugin = "inventory_sync";
|
||||
static permission = "inventory_sync.inventory.view";
|
||||
}
|
||||
DatabaseStatsRequest.Response = class Response {
|
||||
/** @type {boolean} */
|
||||
databaseSize;
|
||||
/** @type {boolean} */
|
||||
databaseEntries;
|
||||
/** @type {object} */
|
||||
largestEntry;
|
||||
|
||||
constructor(databaseSize, databaseEntries, largestEntry) {
|
||||
this.databaseSize = databaseSize;
|
||||
this.databaseEntries = databaseEntries;
|
||||
this.largestEntry = largestEntry;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["databaseSize", "databaseEntries", "largestEntry"],
|
||||
properties: {
|
||||
"databaseSize": { type: "integer" },
|
||||
"databaseEntries": { type: "integer" },
|
||||
"largestEntry": {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
size: { type: "number" },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.databaseSize, json.databaseEntries, json.largestEntry);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
AcquireRequest,
|
||||
ReleaseRequest,
|
||||
UploadRequest,
|
||||
DownloadRequest,
|
||||
DatabaseStatsRequest,
|
||||
};
|
||||
@@ -2,7 +2,7 @@ import React, { useContext, useEffect, useState } from "react";
|
||||
|
||||
import { libPlugin } from "@clusterio/lib";
|
||||
import { PageLayout, ControlContext } from "@clusterio/web_ui";
|
||||
import info from "../info";
|
||||
import { DatabaseStatsRequest } from "../messages";
|
||||
|
||||
import "./index.css";
|
||||
|
||||
@@ -14,16 +14,16 @@ function InventoryPage() {
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
// Get statistics
|
||||
updateStatsData(await info.messages.databaseStats.send(control, {}));
|
||||
updateStatsData(await control.send(new DatabaseStatsRequest()));
|
||||
})();
|
||||
}, []);
|
||||
|
||||
return <PageLayout nav={[{ name: "Inventory sync" }]}>
|
||||
<h2>Inventory sync</h2>
|
||||
{statsData && <>
|
||||
<p>Database size: {Math.round(statsData.database_size / 1000)}kB</p>
|
||||
<p>Database entries: {statsData.database_entries}</p>
|
||||
<p>Largest entry is {statsData.largest_entry.name} with {(statsData.largest_entry.size / 1000)}kB</p>
|
||||
<p>Database size: {Math.round(statsData.databaseSize / 1000)}kB</p>
|
||||
<p>Database entries: {statsData.databaseEntries}</p>
|
||||
<p>Largest entry is {statsData.largestEntry.name} with {(statsData.largestEntry.size / 1000)}kB</p>
|
||||
</>}
|
||||
</PageLayout>;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ const libPlugin = require("@clusterio/lib/plugin");
|
||||
const libErrors = require("@clusterio/lib/errors");
|
||||
const { basicType } = require("@clusterio/lib/helpers");
|
||||
|
||||
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("./messages");
|
||||
|
||||
|
||||
async function generateCode(length) {
|
||||
// ji1lI, 0oOQ, and 2Z are not present to ease reading.
|
||||
@@ -60,6 +62,9 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
this.controller.app.post("/api/player_auth/verify", express.json(), (req, res, next) => {
|
||||
this.handleVerify(req, res).catch(next);
|
||||
});
|
||||
|
||||
this.controller.register(FetchPlayerCodeRequest, this.handleFetchPlayerCodeRequest.bind(this));
|
||||
this.controller.register(SetVerifyCodeRequest, this.handleSetVerifyCodeRequest.bind(this));
|
||||
}
|
||||
|
||||
async handlePlayerCode(req, res) {
|
||||
@@ -159,15 +164,15 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
res.send({ error: true, message: "invalid player_code" });
|
||||
}
|
||||
|
||||
async fetchPlayerCodeRequestHandler(message) {
|
||||
async handleFetchPlayerCodeRequest(request) {
|
||||
let playerCode = await generateCode(this.controller.config.get("player_auth.code_length"));
|
||||
let expires = Date.now() + this.controller.config.get("player_auth.code_timeout") * 1000;
|
||||
this.players.set(message.data.player, { playerCode, verifyCode: null, expires });
|
||||
this.players.set(request.player, { playerCode, verifyCode: null, expires });
|
||||
return { player_code: playerCode, controller_url: this.controller.getControllerUrl() };
|
||||
}
|
||||
|
||||
async setVerifyCodeRequestHandler(message) {
|
||||
let { player, verify_code } = message.data;
|
||||
async handleSetVerifyCodeRequest(request) {
|
||||
let { player, verifyCode } = request;
|
||||
if (!this.players.has(player)) {
|
||||
throw new libErrors.RequestError("invalid player");
|
||||
}
|
||||
@@ -177,7 +182,7 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
throw new libErrors.RequestError("invalid player");
|
||||
}
|
||||
|
||||
entry.verifyCode = verify_code;
|
||||
entry.verifyCode = verifyCode;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use strict";
|
||||
let { libConfig, libLink } = require("@clusterio/lib");
|
||||
let { libConfig } = require("@clusterio/lib");
|
||||
|
||||
|
||||
class ControllerConfigGroup extends libConfig.PluginConfigGroup {}
|
||||
@@ -29,28 +29,4 @@ module.exports = {
|
||||
instanceEntrypoint: "instance",
|
||||
webEntrypoint: "./web",
|
||||
ControllerConfigGroup,
|
||||
|
||||
messages: {
|
||||
fetchPlayerCode: new libLink.Request({
|
||||
type: "player_auth:fetch_player_code",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
requestProperties: {
|
||||
"player": { type: "string" },
|
||||
},
|
||||
responseProperties: {
|
||||
"player_code": { type: "string" },
|
||||
"controller_url": { type: "string" },
|
||||
},
|
||||
}),
|
||||
setVerifyCode: new libLink.Request({
|
||||
type: "player_auth:set_verify_code",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
requestProperties: {
|
||||
"player": { type: "string" },
|
||||
"verify_code": { type: "string" },
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
@@ -4,6 +4,8 @@
|
||||
"use strict";
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
|
||||
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("./messages");
|
||||
|
||||
|
||||
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
async init() {
|
||||
@@ -25,19 +27,16 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = await this.info.messages.fetchPlayerCode.send(this.instance, { player: event.player });
|
||||
response = await this.instance.sendTo(new FetchPlayerCodeRequest(event.player), "controller");
|
||||
} catch (err) {
|
||||
await this.sendRcon(`/web-login error ${event.player} ${err.message}`);
|
||||
return;
|
||||
}
|
||||
await this.sendRcon(`/web-login open ${event.player} ${response.controller_url} ${response.player_code}`);
|
||||
await this.sendRcon(`/web-login open ${event.player} ${response.controllerUrl} ${response.playerCode}`);
|
||||
|
||||
} else if (event.type === "set_verify_code") {
|
||||
try {
|
||||
await this.info.messages.setVerifyCode.send(this.instance, {
|
||||
player: event.player,
|
||||
verify_code: event.verify_code,
|
||||
});
|
||||
await this.instance.sendTo(new SetVerifyCodeRequest(event.player, event.verify_code), "controller");
|
||||
|
||||
} catch (err) {
|
||||
await this.sendRcon(`/web-login error ${event.player} ${err.message}`);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"use strict";
|
||||
|
||||
|
||||
class FetchPlayerCodeRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "player_auth";
|
||||
|
||||
/** @type {string} */
|
||||
player;
|
||||
|
||||
constructor(player) {
|
||||
this.player = player;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["player"],
|
||||
properties: {
|
||||
"player": { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.player);
|
||||
}
|
||||
}
|
||||
FetchPlayerCodeRequest.Response = class Response {
|
||||
/** @type {string} */
|
||||
playerCode;
|
||||
/** @type {string} */
|
||||
controllerUrl;
|
||||
|
||||
constructor(playerCode, controllerUrl) {
|
||||
this.playerCode = playerCode;
|
||||
this.controllerUrl = controllerUrl;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["playerCode", "controllerUrl"],
|
||||
properties: {
|
||||
"playerCode": { type: "string" },
|
||||
"controllerUrl": { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.playerCode, json.controllerUrl);
|
||||
}
|
||||
};
|
||||
|
||||
class SetVerifyCodeRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "player_auth";
|
||||
|
||||
/** @type {string} */
|
||||
player;
|
||||
/** @type {string} */
|
||||
verifyCode;
|
||||
|
||||
constructor(player, verifyCode) {
|
||||
this.player = player;
|
||||
this.verifyCode = verifyCode;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["player", "verifyCode"],
|
||||
properties: {
|
||||
"player": { type: "string" },
|
||||
"verifyCode": { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.playerCode, json.verifyCode);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FetchPlayerCodeRequest,
|
||||
SetVerifyCodeRequest,
|
||||
};
|
||||
@@ -8,6 +8,8 @@ const mock = require("../../../test/mock");
|
||||
const controller = require("../controller");
|
||||
const instance = require("../instance");
|
||||
const info = require("../info");
|
||||
const { FetchPlayerCodeRequest, SetVerifyCodeRequest } = require("../messages");
|
||||
const libData = require("@clusterio/lib/data");
|
||||
const libErrors = require("@clusterio/lib/errors");
|
||||
|
||||
|
||||
@@ -291,9 +293,11 @@ describe("player_auth", function() {
|
||||
});
|
||||
});
|
||||
|
||||
describe(".fetchPlayerCodeRequestHandler()", function() {
|
||||
describe(".handleFetchPlayerCodeRequest()", function() {
|
||||
it("should return a code", async function() {
|
||||
let result = await controllerPlugin.fetchPlayerCodeRequestHandler({ data: { player: "test" }});
|
||||
let result = await controllerPlugin.handleFetchPlayerCodeRequest(
|
||||
new FetchPlayerCodeRequest("test")
|
||||
);
|
||||
assert(typeof result.player_code === "string", "no code returned");
|
||||
assert(result.player_code.length === 10, "incorrect code length returned");
|
||||
let expires = controllerPlugin.players.get("test").expires;
|
||||
@@ -302,11 +306,11 @@ describe("player_auth", function() {
|
||||
});
|
||||
});
|
||||
|
||||
describe(".setVerifyCodeRequestHandler()", function() {
|
||||
describe(".handleSetVerifyCodeRequest()", function() {
|
||||
it("should throw if player does not exist", async function() {
|
||||
await assert.rejects(
|
||||
controllerPlugin.setVerifyCodeRequestHandler(
|
||||
{ data: { player: "invalid", verify_code: "invalid" }}
|
||||
controllerPlugin.handleSetVerifyCodeRequest(
|
||||
new SetVerifyCodeRequest("invalid", "invalid")
|
||||
),
|
||||
new libErrors.RequestError("invalid player")
|
||||
);
|
||||
@@ -315,8 +319,8 @@ describe("player_auth", function() {
|
||||
let expires = Date.now() - 1000;
|
||||
controllerPlugin.players.set("expired", { playerCode: "expried", verifyCode: null, expires });
|
||||
await assert.rejects(
|
||||
controllerPlugin.setVerifyCodeRequestHandler(
|
||||
{ data: { player: "expired", verify_code: "expired" }}
|
||||
controllerPlugin.handleSetVerifyCodeRequest(
|
||||
new SetVerifyCodeRequest("expired", "expired")
|
||||
),
|
||||
new libErrors.RequestError("invalid player")
|
||||
);
|
||||
@@ -326,8 +330,8 @@ describe("player_auth", function() {
|
||||
describe("integration", function() {
|
||||
it("should verify a full login flow", async function() {
|
||||
let app = controllerPlugin.controller.app;
|
||||
let { player_code } = await controllerPlugin.fetchPlayerCodeRequestHandler(
|
||||
{ data: { player: "test" }}
|
||||
let { player_code } = await controllerPlugin.handleFetchPlayerCodeRequest(
|
||||
new FetchPlayerCodeRequest("test")
|
||||
);
|
||||
|
||||
let playerCodeResult = await phin({
|
||||
@@ -338,7 +342,9 @@ describe("player_auth", function() {
|
||||
});
|
||||
|
||||
let { verify_code, verify_token } = playerCodeResult.body;
|
||||
await controllerPlugin.setVerifyCodeRequestHandler({ data: { player: "test", verify_code }});
|
||||
await controllerPlugin.handleSetVerifyCodeRequest(
|
||||
new SetVerifyCodeRequest("test", verify_code)
|
||||
);
|
||||
|
||||
let verifyResult = await phin({
|
||||
url: `${controllerUrl}/api/player_auth/verify`,
|
||||
@@ -372,14 +378,11 @@ describe("player_auth", function() {
|
||||
it("should call /web-login error after error from the controller", async function() {
|
||||
instancePlugin.instance.server.reset();
|
||||
instancePlugin.instance.connector.once("send", message => {
|
||||
instancePlugin.instance.connector.emit("message", {
|
||||
seq: 1,
|
||||
type: "player_auth:fetch_player_code_response",
|
||||
data: {
|
||||
seq: message.seq,
|
||||
error: "controller error",
|
||||
},
|
||||
});
|
||||
instancePlugin.instance.connector.emit("message",
|
||||
new libData.MessageResponseError(1, message.dst, message.src,
|
||||
new libData.ResponseError("controller error")
|
||||
)
|
||||
);
|
||||
});
|
||||
await instancePlugin.handleEvent({ type: "open_dialog", player: "test" });
|
||||
let command = instancePlugin.instance.server.rconCommands[0];
|
||||
@@ -388,15 +391,11 @@ describe("player_auth", function() {
|
||||
it("should call /web-login open after a valid response from the controller", async function() {
|
||||
instancePlugin.instance.server.reset();
|
||||
instancePlugin.instance.connector.once("send", message => {
|
||||
instancePlugin.instance.connector.emit("message", {
|
||||
seq: 1,
|
||||
type: "player_auth:fetch_player_code_response",
|
||||
data: {
|
||||
seq: message.seq,
|
||||
player_code: "code",
|
||||
controller_url: "controller-url",
|
||||
},
|
||||
});
|
||||
instancePlugin.instance.connector.emit("message",
|
||||
new libData.MessageResponse(1, message.dst, message.src,
|
||||
new FetchPlayerCodeRequest.Response("code", "controller-url")
|
||||
)
|
||||
);
|
||||
});
|
||||
await instancePlugin.handleEvent({ type: "open_dialog", player: "test" });
|
||||
let command = instancePlugin.instance.server.rconCommands[0];
|
||||
@@ -407,11 +406,9 @@ describe("player_auth", function() {
|
||||
it("should call /web-login code_set after a valid response from the controller", async function() {
|
||||
instancePlugin.instance.server.reset();
|
||||
instancePlugin.instance.connector.once("send", message => {
|
||||
instancePlugin.instance.connector.emit("message", {
|
||||
seq: 1,
|
||||
type: "player_auth:set_verify_code_response",
|
||||
data: { seq: message.seq },
|
||||
});
|
||||
instancePlugin.instance.connector.emit("message",
|
||||
new libData.MessageResponse(1, message.dst, message.src)
|
||||
);
|
||||
});
|
||||
await instancePlugin.handleEvent(
|
||||
{ type: "set_verify_code", player: "test", verify_code: "verify" }
|
||||
@@ -422,11 +419,11 @@ describe("player_auth", function() {
|
||||
it("should call /web-login error after error from the controller", async function() {
|
||||
instancePlugin.instance.server.reset();
|
||||
instancePlugin.instance.connector.once("send", message => {
|
||||
instancePlugin.instance.connector.emit("message", {
|
||||
seq: 1,
|
||||
type: "player_auth:set_verify_code_response",
|
||||
data: { seq: message.seq, error: "controller error" },
|
||||
});
|
||||
instancePlugin.instance.connector.emit("message",
|
||||
new libData.MessageResponseError(1, message.dst, message.src,
|
||||
new libData.ResponseError("controller error")
|
||||
)
|
||||
);
|
||||
});
|
||||
await instancePlugin.handleEvent(
|
||||
{ type: "set_verify_code", player: "test", verify_code: "verify" }
|
||||
|
||||
@@ -6,6 +6,14 @@ const libFileOps = require("@clusterio/lib/file_ops");
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
const RateLimiter = require("@clusterio/lib/RateLimiter");
|
||||
|
||||
const {
|
||||
ContributionEvent,
|
||||
ProgressEvent,
|
||||
FinishedEvent,
|
||||
Technology,
|
||||
SyncTechnologiesRequest,
|
||||
} = require("./messages");
|
||||
|
||||
|
||||
async function loadTechnologies(controllerConfig, logger) {
|
||||
let filePath = path.join(controllerConfig.get("controller.database_directory"), "technologies.json");
|
||||
@@ -40,6 +48,10 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
this.lastProgressBroadcast = Date.now();
|
||||
this.progressBroadcastId = null;
|
||||
this.progressToBroadcast = new Set();
|
||||
|
||||
this.controller.register(ContributionEvent, this.handleContributionEvent.bind(this));
|
||||
this.controller.register(FinishedEvent, this.handleFinishedEvent.bind(this));
|
||||
this.controller.register(SyncTechnologiesRequest, this.handleSyncTechnologiesRequest.bind(this));
|
||||
}
|
||||
|
||||
async onShutdown() {
|
||||
@@ -59,12 +71,12 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
|
||||
this.lastProgressBroadcast = Date.now();
|
||||
if (techs.length) {
|
||||
this.broadcastEventToHosts(this.info.messages.progress, { technologies: techs });
|
||||
this.controller.sendTo(new ProgressEvent(techs), "allInstances");
|
||||
}
|
||||
}
|
||||
|
||||
async contributionEventHandler(message) {
|
||||
let { name, level, contribution } = message.data;
|
||||
async handleContributionEvent(event) {
|
||||
let { name, level, contribution } = event;
|
||||
let tech = this.technologies.get(name);
|
||||
if (!tech) {
|
||||
tech = { level, progress: 0, researched: false };
|
||||
@@ -97,12 +109,12 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
tech.progress = null;
|
||||
this.progressToBroadcast.delete(name);
|
||||
|
||||
this.broadcastEventToHosts(this.info.messages.finished, { name, level: tech.level });
|
||||
this.controller.sendTo(new FinishedEvent(name, tech.level), "allInstances");
|
||||
}
|
||||
}
|
||||
|
||||
async finishedEventHandler(message) {
|
||||
let { name, level } = message.data;
|
||||
async handleFinishedEvent(event) {
|
||||
let { name, level } = event;
|
||||
let tech = this.technologies.get(name);
|
||||
if (!tech || tech.level <= level) {
|
||||
this.progressToBroadcast.delete(name);
|
||||
@@ -110,7 +122,7 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
async syncTechnologiesRequestHandler(message) {
|
||||
async handleSyncTechnologiesRequest(request) {
|
||||
function baseLevel(name) {
|
||||
let match = /-(\d+)$/.exec(name);
|
||||
if (!match) {
|
||||
@@ -119,15 +131,15 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
return Number.parseInt(match[1], 10);
|
||||
}
|
||||
|
||||
for (let instanceTech of message.data.technologies) {
|
||||
let [name, level, progress, researched] = instanceTech;
|
||||
for (let instanceTech of request.technologies) {
|
||||
let { name, level, progress, researched } = instanceTech;
|
||||
let tech = this.technologies.get(name);
|
||||
if (!tech) {
|
||||
this.technologies.set(name, { level, progress, researched });
|
||||
if (progress) {
|
||||
this.progressToBroadcast.add(name);
|
||||
} else if (researched || baseLevel(name) !== level) {
|
||||
this.broadcastEventToHosts(this.info.messages.finished, { name, level });
|
||||
this.controller.sendTo(new FinishedEvent(name, tech), "allInstances");
|
||||
}
|
||||
|
||||
} else {
|
||||
@@ -138,7 +150,7 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
if (tech.level < level || researched) {
|
||||
// Send update if the unlocked level is greater
|
||||
if (level - !researched > tech.level - !tech.researched) {
|
||||
this.broadcastEventToHosts(this.info.messages.finished, { name, level: level - !researched });
|
||||
this.controller.sendTo(new FinishedEvent(name, level - !researched), "allInstances");
|
||||
}
|
||||
tech.level = level;
|
||||
tech.progress = progress;
|
||||
@@ -160,10 +172,10 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
|
||||
let technologies = [];
|
||||
for (let [name, tech] of this.technologies) {
|
||||
technologies.push([name, tech.level, tech.progress, tech.researched]);
|
||||
technologies.push(new Technology(name, tech.level, tech.progress, tech.researched));
|
||||
}
|
||||
|
||||
return { technologies };
|
||||
return technologies;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,4 @@
|
||||
"use strict";
|
||||
const { libLink } = require("@clusterio/lib");
|
||||
|
||||
|
||||
// schema used for syncing technologies to and from the controller
|
||||
const technologies = {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "array",
|
||||
minItems: 4,
|
||||
maxItems: 4,
|
||||
items: [
|
||||
{ type: "string" },
|
||||
{ type: "integer" },
|
||||
{ type: ["null", "number"] },
|
||||
{ type: "boolean" },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
name: "research_sync",
|
||||
@@ -24,57 +6,4 @@ module.exports = {
|
||||
description: "Synchronises technology research progress between instances.",
|
||||
instanceEntrypoint: "instance",
|
||||
controllerEntrypoint: "controller",
|
||||
|
||||
messages: {
|
||||
contribution: new libLink.Event({
|
||||
type: "research_sync:contribution",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
eventProperties: {
|
||||
"name": { type: "string" },
|
||||
"level": { type: "integer" },
|
||||
"contribution": { type: "number" },
|
||||
},
|
||||
}),
|
||||
progress: new libLink.Event({
|
||||
type: "research_sync:progress",
|
||||
links: ["controller-host", "host-instance"],
|
||||
broadcastTo: "instance",
|
||||
eventProperties: {
|
||||
"technologies": {
|
||||
type: "array",
|
||||
items: {
|
||||
additionalProperties: false,
|
||||
required: ["name", "level", "progress"],
|
||||
properties: {
|
||||
"name": { type: "string" },
|
||||
"level": { type: "integer" },
|
||||
"progress": { type: "number" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
finished: new libLink.Event({
|
||||
type: "research_sync:finished",
|
||||
links: ["instance-host", "host-controller", "controller-host", "host-instance"],
|
||||
forwardTo: "controller",
|
||||
broadcastTo: "instance",
|
||||
eventProperties: {
|
||||
"name": { type: "string" },
|
||||
"level": { type: "integer" },
|
||||
},
|
||||
}),
|
||||
syncTechnologies: new libLink.Request({
|
||||
type: "research_sync:sync_technologies",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
requestProperties: {
|
||||
"technologies": technologies,
|
||||
},
|
||||
responseProperties: {
|
||||
"technologies": technologies,
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,13 @@
|
||||
"use strict";
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
||||
const {
|
||||
ContributionEvent,
|
||||
ProgressEvent,
|
||||
FinishedEvent,
|
||||
Technology,
|
||||
SyncTechnologiesRequest,
|
||||
} = require("./messages");
|
||||
|
||||
|
||||
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
@@ -21,29 +28,31 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
});
|
||||
|
||||
this.syncStarted = false;
|
||||
this.instance.register(ProgressEvent, this.handleProgressEvent.bind(this));
|
||||
this.instance.register(FinishedEvent, this.handleFinishedEvent.bind(this));
|
||||
}
|
||||
|
||||
async researchContribution(tech) {
|
||||
this.info.messages.contribution.send(this.instance, tech);
|
||||
this.instance.sendTo(new ContributionEvent(tech.name, tech.level, tech.contribution), "controller");
|
||||
}
|
||||
|
||||
async progressEventHandler(message) {
|
||||
async handleProgressEvent(event) {
|
||||
if (!this.syncStarted || !["starting", "running"].includes(this.instance.status)) {
|
||||
return;
|
||||
}
|
||||
let techsJson = libLuaTools.escapeString(JSON.stringify(message.data.technologies));
|
||||
let techsJson = libLuaTools.escapeString(JSON.stringify(event.technologies));
|
||||
await this.sendOrderedRcon(`/sc research_sync.update_progress("${techsJson}")`, true);
|
||||
}
|
||||
|
||||
async researchFinished(tech) {
|
||||
this.info.messages.finished.send(this.instance, tech);
|
||||
this.instance.sendTo(new FinishedEvent(tech.name, tech.level), "allInstances");
|
||||
}
|
||||
|
||||
async finishedEventHandler(message) {
|
||||
async handleFinishedEvent(event) {
|
||||
if (!this.syncStarted || !["starting", "running"].includes(this.instance.status)) {
|
||||
return;
|
||||
}
|
||||
let { name, level } = message.data;
|
||||
let { name, level } = event;
|
||||
await this.sendOrderedRcon(
|
||||
`/sc research_sync.research_technology("${libLuaTools.escapeString(name)}", ${level})`, true
|
||||
);
|
||||
@@ -54,20 +63,20 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
let techsToSend = [];
|
||||
let instanceTechs = new Map();
|
||||
for (let tech of JSON.parse(dumpJson)) {
|
||||
techsToSend.push([
|
||||
techsToSend.push(new Technology(
|
||||
tech.name,
|
||||
tech.level,
|
||||
tech.progress || null,
|
||||
tech.researched,
|
||||
]);
|
||||
));
|
||||
instanceTechs.set(tech.name, tech);
|
||||
}
|
||||
|
||||
let response = await this.info.messages.syncTechnologies.send(this.instance, { technologies: techsToSend });
|
||||
let controllerTechs = await this.instance.sendTo(new SyncTechnologiesRequest(techsToSend), "controller");
|
||||
this.syncStarted = true;
|
||||
let techsToSync = [];
|
||||
for (let controllerTech of response.technologies) {
|
||||
let [name, level, progress, researched] = controllerTech;
|
||||
for (let controllerTech of controllerTechs) {
|
||||
let { name, level, progress, researched } = controllerTech;
|
||||
let instanceTech = instanceTechs.get(name);
|
||||
if (
|
||||
!instanceTech
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"use strict";
|
||||
const { jsonArray } = require("@clusterio/lib/data");
|
||||
|
||||
class ContributionEvent {
|
||||
static type = "event";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static json = "research_sync";
|
||||
|
||||
/** @type {string} */
|
||||
name;
|
||||
/** @type {number} */
|
||||
level;
|
||||
/** @type {number} */
|
||||
contribution;
|
||||
|
||||
constructor(name, level, contribution) {
|
||||
this.name = name;
|
||||
this.level = level;
|
||||
this.contribution = contribution;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["name", "level", "contribution"],
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
level: { type: "integer" },
|
||||
contribution: { type: "number" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.name, json.level, json.contribution);
|
||||
}
|
||||
}
|
||||
|
||||
class ProgressEvent {
|
||||
static type = "event";
|
||||
static src = "controller";
|
||||
static dst = "instance";
|
||||
static json = "research_sync";
|
||||
|
||||
/** @type {Array<>} */
|
||||
technologies;
|
||||
|
||||
constructor(technologies) {
|
||||
this.technologies = technologies;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["technologies"],
|
||||
properties: {
|
||||
technologies: {
|
||||
type: "array",
|
||||
items: {
|
||||
required: ["name", "level", "progress"],
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
level: { type: "integer" },
|
||||
progress: { type: "number" },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.technologies);
|
||||
}
|
||||
}
|
||||
|
||||
class FinishedEvent {
|
||||
static type = "event";
|
||||
static src = "instance";
|
||||
static dst = "instance";
|
||||
static json = "research_sync";
|
||||
|
||||
/** @type {string} */
|
||||
name;
|
||||
/** @type {number} */
|
||||
level;
|
||||
|
||||
constructor(name, level) {
|
||||
this.name = name;
|
||||
this.level = level;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "object",
|
||||
required: ["name", "level"],
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
level: { type: "integer" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.name, json.level);
|
||||
}
|
||||
}
|
||||
|
||||
class Technology {
|
||||
/** @type {string} */
|
||||
name;
|
||||
/** @type {number} */
|
||||
level;
|
||||
/** @type {?number} */
|
||||
progress;
|
||||
/** @type {boolean} */
|
||||
researched;
|
||||
|
||||
constructor(name, level, progress, researched) {
|
||||
this.name = name;
|
||||
this.level = level;
|
||||
this.progress = progress;
|
||||
this.researched = researched;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "array",
|
||||
minItems: 4,
|
||||
maxItems: 4,
|
||||
items: [
|
||||
{ type: "string" },
|
||||
{ type: "integer" },
|
||||
{ type: ["null", "number"] },
|
||||
{ type: "boolean" },
|
||||
],
|
||||
};
|
||||
|
||||
toJSON() {
|
||||
return [this.name, this.level, this.progress, this.researched];
|
||||
}
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json[0], json[1], json[2], json[3]);
|
||||
}
|
||||
}
|
||||
|
||||
class SyncTechnologiesRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static json = "research_sync";
|
||||
|
||||
/** @type {Array<Technology>} */
|
||||
technologies;
|
||||
|
||||
constructor(technologies) {
|
||||
this.technologies = technologies;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "array",
|
||||
items: Technology.jsonSchema,
|
||||
};
|
||||
|
||||
toJSON() {
|
||||
return this.technologies;
|
||||
}
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.map(e => Technology.fromJSON(e)));
|
||||
}
|
||||
|
||||
static Response = jsonArray(Technology);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ContributionEvent,
|
||||
ProgressEvent,
|
||||
FinishedEvent,
|
||||
Technology,
|
||||
SyncTechnologiesRequest,
|
||||
};
|
||||
@@ -11,6 +11,15 @@ const RateLimiter = require("@clusterio/lib/RateLimiter");
|
||||
const routes = require("./routes");
|
||||
const dole = require("./dole");
|
||||
|
||||
const {
|
||||
Item,
|
||||
PlaceEvent,
|
||||
RemoveRequest,
|
||||
GetStorageRequest,
|
||||
UpdateStorageEvent,
|
||||
SetStorageSubscriptionRequest,
|
||||
} = require("./messages");
|
||||
|
||||
|
||||
const exportCounter = new Counter(
|
||||
"clusterio_subspace_storage_export_total",
|
||||
@@ -87,6 +96,11 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
this.subscribedControlLinks = new Set();
|
||||
|
||||
routes.addApiRoutes(this.controller.app, this.items);
|
||||
|
||||
this.controller.register(GetStorageRequest, this.handleGetStorageRequest.bind(this));
|
||||
this.controller.register(PlaceEvent, this.handlePlaceEvent.bind(this));
|
||||
this.controller.register(RemoveRequest, this.handleRemoveRequest.bind(this));
|
||||
this.controller.register(SetStorageSubscriptionRequest, this.handleSetStorageSubscriptionRequest.bind(this));
|
||||
}
|
||||
|
||||
updateStorage() {
|
||||
@@ -107,48 +121,49 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
}
|
||||
|
||||
itemsToUpdate = [...itemsToUpdate.entries()];
|
||||
this.broadcastEventToHosts(this.info.messages.updateStorage, { items: itemsToUpdate });
|
||||
let update = new UpdateStorageEvent(itemsToUpdate);
|
||||
this.controller.sendTo(update, "allInstances");
|
||||
for (let link of this.subscribedControlLinks) {
|
||||
this.info.messages.updateStorage.send(link, { items: itemsToUpdate });
|
||||
link.send(update);
|
||||
}
|
||||
this.itemsLastUpdate = new Map(this.items._items.entries());
|
||||
}
|
||||
|
||||
async getStorageRequestHandler(message) {
|
||||
return { items: [...this.items._items.entries()] };
|
||||
async handleGetStorageRequest() {
|
||||
return [...this.items._items.entries()];
|
||||
}
|
||||
|
||||
async placeEventHandler(message) {
|
||||
let instanceId = message.data.instance_id;
|
||||
async handlePlaceEvent(request, src) {
|
||||
let instanceId = src.id;
|
||||
|
||||
for (let item of message.data.items) {
|
||||
this.items.addItem(item[0], item[1]);
|
||||
exportCounter.labels(String(instanceId), item[0]).inc(item[1]);
|
||||
for (let item of request.items) {
|
||||
this.items.addItem(item.name, item.count);
|
||||
exportCounter.labels(String(instanceId), item.name).inc(item.count);
|
||||
}
|
||||
|
||||
this.updateStorage();
|
||||
|
||||
if (this.controller.config.get("subspace_storage.log_item_transfers")) {
|
||||
this.logger.verbose(
|
||||
`Imported the following from ${message.data.instance_id}:\n${JSON.stringify(message.data.items)}`
|
||||
`Imported the following from ${instanceId}:\n${JSON.stringify(request.items)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async removeRequestHandler(message) {
|
||||
async handleRemoveRequest(request, src) {
|
||||
let method = this.controller.config.get("subspace_storage.division_method");
|
||||
let instanceId = message.data.instance_id;
|
||||
let instanceId = src.id;
|
||||
|
||||
let itemsRemoved = [];
|
||||
if (method === "simple") {
|
||||
// Give out as much items as possible until there are 0 left. This
|
||||
// might lead to one host getting all the items and the rest nothing.
|
||||
for (let item of message.data.items) {
|
||||
let count = this.items.getItemCount(item[0]);
|
||||
let toRemove = Math.min(count, item[1]);
|
||||
for (let item of request.items) {
|
||||
let count = this.items.getItemCount(item.name);
|
||||
let toRemove = Math.min(count, item.count);
|
||||
if (toRemove > 0) {
|
||||
this.items.removeItem(item[0], toRemove);
|
||||
itemsRemoved.push([item[0], toRemove]);
|
||||
this.items.removeItem(item.name, toRemove);
|
||||
itemsRemoved.push(new Item(item.name, toRemove));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,24 +173,24 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
|
||||
// use fancy neural net to calculate a "fair" dole division rate.
|
||||
if (method === "neural_dole") {
|
||||
for (let item of message.data.items) {
|
||||
let count = neuralDole.divider({ name: item[0], count: item[1], instanceId, instanceName });
|
||||
for (let item of request.items) {
|
||||
let count = neuralDole.divider({ name: item.name, count: item.count, instanceId, instanceName });
|
||||
if (count > 0) {
|
||||
itemsRemoved.push([item[0], count]);
|
||||
itemsRemoved.push(new Item(item.name, count));
|
||||
}
|
||||
}
|
||||
|
||||
// Use dole division. Makes it really slow to drain out the last little bit.
|
||||
} else if (method === "dole") {
|
||||
for (let item of message.data.items) {
|
||||
for (let item of request.items) {
|
||||
let count = dole.doleDivider({
|
||||
object: { name: item[0], count: item[1], instanceId, instanceName },
|
||||
object: { name: item.name, count: item.count, instanceId, instanceName },
|
||||
items: this.items,
|
||||
logItemTransfers: this.controller.config.get("subspace_storage.log_item_transfers"),
|
||||
logger: this.logger,
|
||||
});
|
||||
if (count > 0) {
|
||||
itemsRemoved.push([item[0], count]);
|
||||
itemsRemoved.push(new Item(item.name, count));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,7 +202,7 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
|
||||
if (itemsRemoved.length) {
|
||||
for (let item of itemsRemoved) {
|
||||
importCounter.labels(String(instanceId), item[0]).inc(item[1]);
|
||||
importCounter.labels(String(instanceId), item.name).inc(item.count);
|
||||
}
|
||||
|
||||
this.updateStorage();
|
||||
@@ -197,13 +212,12 @@ class ControllerPlugin extends libPlugin.BaseControllerPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
items: itemsRemoved,
|
||||
};
|
||||
return itemsRemoved;
|
||||
}
|
||||
|
||||
async setStorageSubscriptionRequestHandler(message, request, link) {
|
||||
if (message.data.storage) {
|
||||
async handleSetStorageSubscriptionRequest(request, src) {
|
||||
let link = this.controller.wsServer.controlConnections.get(src.id);
|
||||
if (request.storage) {
|
||||
this.subscribedControlLinks.add(link);
|
||||
} else {
|
||||
this.subscribedControlLinks.delete(link);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use strict";
|
||||
const { libConfig, libLink, libUsers } = require("@clusterio/lib");
|
||||
const { libConfig, libUsers } = require("@clusterio/lib");
|
||||
|
||||
class ControllerConfigGroup extends libConfig.PluginConfigGroup {}
|
||||
ControllerConfigGroup.defaultAccess = ["controller", "host", "control"];
|
||||
@@ -47,20 +47,6 @@ libUsers.definePermission({
|
||||
grantByDefault: true,
|
||||
});
|
||||
|
||||
// JSON schema for subspace storage items
|
||||
const items = {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "array",
|
||||
minItems: 2,
|
||||
maxItems: 2,
|
||||
items: [
|
||||
{ type: "string" },
|
||||
{ type: "integer" },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
name: "subspace_storage",
|
||||
title: "Subspace Storage",
|
||||
@@ -73,55 +59,4 @@ module.exports = {
|
||||
|
||||
webEntrypoint: "./web",
|
||||
routes: ["/storage"],
|
||||
|
||||
messages: {
|
||||
// XXX this should be a request to be reliable
|
||||
place: new libLink.Event({
|
||||
type: "subspace_storage:place",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
eventProperties: {
|
||||
"instance_id": { type: "integer" },
|
||||
"items": items,
|
||||
},
|
||||
}),
|
||||
remove: new libLink.Request({
|
||||
type: "subspace_storage:remove",
|
||||
links: ["instance-host", "host-controller"],
|
||||
forwardTo: "controller",
|
||||
requestProperties: {
|
||||
"instance_id": { type: "integer" },
|
||||
"items": items,
|
||||
},
|
||||
responseProperties: {
|
||||
"items": items,
|
||||
},
|
||||
}),
|
||||
getStorage: new libLink.Request({
|
||||
type: "subspace_storage:get_storage",
|
||||
links: ["instance-host", "host-controller", "control-controller"],
|
||||
permission: "subspace_storage.storage.view",
|
||||
forwardTo: "controller",
|
||||
responseProperties: {
|
||||
"items": items,
|
||||
},
|
||||
}),
|
||||
updateStorage: new libLink.Event({
|
||||
type: "subspace_storage:update_storage",
|
||||
links: ["controller-host", "host-instance", "controller-control"],
|
||||
broadcastTo: "instance",
|
||||
eventProperties: {
|
||||
"items": items,
|
||||
},
|
||||
}),
|
||||
|
||||
setStorageSubscription: new libLink.Request({
|
||||
type: "subspace_storage:set_storage_subscription",
|
||||
links: ["control-controller"],
|
||||
permission: "subspace_storage.storage.view",
|
||||
requestProperties: {
|
||||
"storage": { type: "boolean" },
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
@@ -2,6 +2,15 @@
|
||||
const libPlugin = require("@clusterio/lib/plugin");
|
||||
const libLuaTools = require("@clusterio/lib/lua_tools");
|
||||
|
||||
const {
|
||||
Item,
|
||||
PlaceEvent,
|
||||
RemoveRequest,
|
||||
GetStorageRequest,
|
||||
UpdateStorageEvent,
|
||||
SetStorageSubscriptionRequest,
|
||||
} = require("./messages");
|
||||
|
||||
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
unexpectedError(err) {
|
||||
this.logger.error(`Unexpected error:\n${err.stack}`);
|
||||
@@ -21,6 +30,8 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
this.pendingTasks.add(task);
|
||||
task.finally(() => { this.pendingTasks.delete(task); });
|
||||
});
|
||||
|
||||
this.instance.register(UpdateStorageEvent, this.handleUpdateStorageEvent.bind(this));
|
||||
}
|
||||
|
||||
async onStart() {
|
||||
@@ -33,9 +44,9 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
).catch(err => this.unexpectedError(err));
|
||||
}, 5000);
|
||||
|
||||
let response = await this.info.messages.getStorage.send(this.instance);
|
||||
let items = await this.instance.sendTo(new GetStorageRequest(), "controller");
|
||||
// TODO Diff with dump of invdata produce minimal command to sync
|
||||
let itemsJson = libLuaTools.escapeString(JSON.stringify(response.items));
|
||||
let itemsJson = libLuaTools.escapeString(JSON.stringify(items));
|
||||
await this.sendRcon(`/sc __subspace_storage__ UpdateInvData("${itemsJson}", true)`, true);
|
||||
}
|
||||
|
||||
@@ -60,10 +71,7 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
return;
|
||||
}
|
||||
|
||||
this.info.messages.place.send(this.instance, {
|
||||
items,
|
||||
instance_id: this.instance.id,
|
||||
});
|
||||
this.instance.sendTo(new PlaceEvent(items), "controller");
|
||||
|
||||
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
|
||||
this.logger.verbose("Exported the following to controller:");
|
||||
@@ -72,32 +80,29 @@ class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
||||
}
|
||||
|
||||
// request items --------------------------------------------------------------
|
||||
async requestItems(items) {
|
||||
async requestItems(requestItems) {
|
||||
// Request the items all at once
|
||||
let response = await this.info.messages.remove.send(this.instance, {
|
||||
instance_id: this.instance.id,
|
||||
items,
|
||||
});
|
||||
let items = await this.instance.sendTo(new RemoveRequest(requestItems), "controller");
|
||||
|
||||
if (!response.items.length) {
|
||||
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(response.items));
|
||||
this.logger.verbose(JSON.stringify(items));
|
||||
}
|
||||
|
||||
let itemsJson = libLuaTools.escapeString(JSON.stringify(response.items));
|
||||
let itemsJson = libLuaTools.escapeString(JSON.stringify(items));
|
||||
await this.sendRcon(`/sc __subspace_storage__ Import("${itemsJson}")`, true);
|
||||
}
|
||||
|
||||
// combinator signals ---------------------------------------------------------
|
||||
async updateStorageEventHandler(message) {
|
||||
async handleUpdateStorageEvent(request) {
|
||||
if (this.instance.status !== "running") {
|
||||
return;
|
||||
}
|
||||
let items = message.data.items;
|
||||
let items = request.items;
|
||||
|
||||
// XXX this should be moved to instance/clusterio api
|
||||
items.push(["signal-unixtime", Math.floor(Date.now()/1000)]);
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"use strict";
|
||||
const { jsonArray } = require("@clusterio/lib/data");
|
||||
|
||||
class Item {
|
||||
/** @type {string} */
|
||||
name;
|
||||
/** @type {number} */
|
||||
count;
|
||||
|
||||
constructor(name, count) {
|
||||
this.name = name;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
type: "array",
|
||||
minItems: 2,
|
||||
maxItems: 2,
|
||||
items: [
|
||||
{ type: "string" },
|
||||
{ type: "integer" },
|
||||
],
|
||||
};
|
||||
|
||||
toJSON() {
|
||||
return [this.name, this.count];
|
||||
}
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json[0], json[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// XXX this should be a request to be reliable
|
||||
class PlaceEvent {
|
||||
static type = "event";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "subspace_storage";
|
||||
|
||||
/** @type {Array<Item>} */
|
||||
items;
|
||||
|
||||
constructor(items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
required: ["items"],
|
||||
properties: {
|
||||
"items": {
|
||||
type: "array",
|
||||
items: Item.jsonSchema,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.items);
|
||||
}
|
||||
}
|
||||
|
||||
class RemoveRequest {
|
||||
static type = "request";
|
||||
static src = "instance";
|
||||
static dst = "controller";
|
||||
static plugin = "subspace_storage";
|
||||
|
||||
/** @type {Array<Item>} */
|
||||
items;
|
||||
|
||||
constructor(items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
required: ["items"],
|
||||
properties: {
|
||||
"items": {
|
||||
type: "array",
|
||||
items: Item.jsonSchema,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.items);
|
||||
}
|
||||
|
||||
static Response = jsonArray(Item);
|
||||
}
|
||||
|
||||
class GetStorageRequest {
|
||||
static type = "request";
|
||||
static src = ["instance", "control"];
|
||||
static dst = "controller";
|
||||
static plugin = "subspace_storage";
|
||||
static permission = "subspace_storage.storage.view";
|
||||
static Response = jsonArray(Item);
|
||||
}
|
||||
|
||||
class UpdateStorageEvent {
|
||||
static type = "request";
|
||||
static src = "controller";
|
||||
static dst = ["instance", "control"];
|
||||
static plugin = "subspace_storage";
|
||||
|
||||
/** @type {Array<Item>} */
|
||||
items;
|
||||
|
||||
constructor(items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
required: ["items"],
|
||||
properties: {
|
||||
"items": {
|
||||
type: "array",
|
||||
items: Item.jsonSchema,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.items);
|
||||
}
|
||||
}
|
||||
|
||||
class SetStorageSubscriptionRequest {
|
||||
static type = "request";
|
||||
static src = "control";
|
||||
static dst = "controller";
|
||||
static plugin = "subspace_storage";
|
||||
static permission = "subspace_storage.storage.view";
|
||||
|
||||
/** @type {boolean} */
|
||||
storage;
|
||||
|
||||
constructor(storage) {
|
||||
this.storage = storage;
|
||||
}
|
||||
|
||||
static jsonSchema = {
|
||||
required: ["storage"],
|
||||
properties: {
|
||||
"storage": { type: "boolean" },
|
||||
},
|
||||
};
|
||||
|
||||
static fromJSON(json) {
|
||||
return new this(json.storage);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Item,
|
||||
PlaceEvent,
|
||||
RemoveRequest,
|
||||
GetStorageRequest,
|
||||
UpdateStorageEvent,
|
||||
SetStorageSubscriptionRequest,
|
||||
};
|
||||
@@ -3,7 +3,7 @@ import { Input, Table, Typography } from "antd";
|
||||
|
||||
import { libPlugin } from "@clusterio/lib";
|
||||
import { notifyErrorHandler, useItemMetadata, useLocale, PageLayout, ControlContext } from "@clusterio/web_ui";
|
||||
import info from "../info";
|
||||
import { GetStorageRequest, SetStorageSubscriptionRequest } from "../messages";
|
||||
|
||||
import "./index.css";
|
||||
|
||||
@@ -135,8 +135,8 @@ export class WebPlugin extends libPlugin.BaseWebPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
async updateStorageEventHandler(message) {
|
||||
this.updateStorage(message.data.items);
|
||||
async updateStorageEventHandler(event) {
|
||||
this.updateStorage(event.items);
|
||||
}
|
||||
|
||||
onUpdate(callback) {
|
||||
@@ -159,8 +159,8 @@ export class WebPlugin extends libPlugin.BaseWebPlugin {
|
||||
}
|
||||
|
||||
updateStorage(items) {
|
||||
for (let [name, amount] of items) {
|
||||
this.storage.set(name, amount);
|
||||
for (let item of items) {
|
||||
this.storage.set(item.name, item.count);
|
||||
}
|
||||
for (let callback of this.callbacks) {
|
||||
callback();
|
||||
@@ -172,14 +172,14 @@ export class WebPlugin extends libPlugin.BaseWebPlugin {
|
||||
return;
|
||||
}
|
||||
|
||||
info.messages.setStorageSubscription.send(
|
||||
this.control, { storage: Boolean(this.callbacks.length) }
|
||||
this.control.send(
|
||||
new SetStorageSubscriptionRequest(Boolean(this.callbacks.length))
|
||||
).catch(notifyErrorHandler("Error subscribing to storage"));
|
||||
|
||||
if (this.callbacks.length) {
|
||||
info.messages.getStorage.send(this.control).then(
|
||||
result => {
|
||||
this.updateStorage(result.items);
|
||||
this.control.send(new GetStorageRequest()).then(
|
||||
items => {
|
||||
this.updateStorage(items);
|
||||
}
|
||||
).catch(notifyErrorHandler("Error updating storage"));
|
||||
} else {
|
||||
|
||||
Reference in new issue
Block a user