mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-12 07:04:52 +09:00
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.
164 lines
5.2 KiB
JavaScript
164 lines
5.2 KiB
JavaScript
/**
|
|
* @module
|
|
*/
|
|
"use strict";
|
|
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
|
|
* @param {String} string - String to split into chunks
|
|
* @returns {String[]} Chunks
|
|
*/
|
|
function chunkify(chunkSize, string) {
|
|
return string.match(new RegExp(`.{1,${chunkSize}}`, "g"));
|
|
}
|
|
|
|
class InstancePlugin extends libPlugin.BaseInstancePlugin {
|
|
async init() {
|
|
this.playersToRelease = new Set();
|
|
this.disconnecting = false;
|
|
|
|
// Handle IPC from scenario script
|
|
this.instance.server.on("ipc-inventory_sync_acquire", content => this.handleAcquire(content)
|
|
.catch(err => this.logger.error(`Error handling ipc-inventory_sync_acquire:\n${err.stack}`)));
|
|
this.instance.server.on("ipc-inventory_sync_release", content => this.handleRelease(content)
|
|
.catch(err => this.logger.error(`Error handling ipc-inventory_sync_release:\n${err.stack}`)));
|
|
this.instance.server.on("ipc-inventory_sync_upload", content => this.handleUpload(content)
|
|
.catch(err => this.logger.error(`Error handling ipc-inventory_sync_upload:\n${err.stack}`)));
|
|
this.instance.server.on("ipc-inventory_sync_download", content => this.handleDownload(content)
|
|
.catch(err => this.logger.error(`Error handling ipc-inventory_sync_download:\n${err.stack}`)));
|
|
}
|
|
|
|
onPrepareControllerDisconnect() {
|
|
this.disconnecting = true;
|
|
}
|
|
|
|
onControllerConnectionEvent(event) {
|
|
if (event === "connect") {
|
|
this.disconnecting = false;
|
|
(async () => {
|
|
for (let player_name of this.playersToRelease) {
|
|
if (!this.host.connector.connected || this.disconnecting) {
|
|
return;
|
|
}
|
|
this.playersToRelease.delete(player);
|
|
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}`)
|
|
);
|
|
}
|
|
}
|
|
|
|
async handleAcquire(request) {
|
|
let response = {
|
|
player_name: request.player_name,
|
|
status: "error",
|
|
message: "Controller is temporarily unavailable",
|
|
};
|
|
|
|
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,
|
|
status: acquireResponse.status,
|
|
generation: acquireResponse.generation,
|
|
has_data: acquireResponse.hasData,
|
|
message: acquireResponse.message,
|
|
};
|
|
} catch (err) {
|
|
if (!(err instanceof libErrors.SessionLost)) {
|
|
this.logger.error(`Unexpected error sending aquire request:\n${err.stack}`);
|
|
response.message = err.message;
|
|
}
|
|
}
|
|
}
|
|
|
|
let json = libLuaTools.escapeString(JSON.stringify(response));
|
|
await this.sendRcon(`/sc inventory_sync.acquire_response("${json}")`, true);
|
|
}
|
|
|
|
async handleRelease(request) {
|
|
if (!this.host.connector.connected) {
|
|
this.playersToRelease.set(request.player_name);
|
|
}
|
|
|
|
try {
|
|
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);
|
|
} else {
|
|
this.logger.error(`Unexpected error releasing player ${request.player_name}:\n${err.stack}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
async handleUpload(player_data) {
|
|
if (!this.host.connector.connected || this.disconnecting) {
|
|
return;
|
|
}
|
|
|
|
this.logger.verbose(`Uploading ${player_data.name} (${JSON.stringify(player_data).length / 1000}kB)`);
|
|
try {
|
|
await this.instance.sendTo(
|
|
new UploadRequest(this.instance.id, player_data.name, player_data),
|
|
"controller"
|
|
);
|
|
|
|
} catch (err) {
|
|
if (!(err instanceof libErrors.SessionLost)) {
|
|
this.logger.error(`Unexpected error uploading inventory for ${player_data.name}:\n${err.stack}`);
|
|
}
|
|
return;
|
|
}
|
|
|
|
await this.sendRcon(
|
|
`/sc inventory_sync.confirm_upload("${player_data.name}", ${player_data.generation})`, true
|
|
);
|
|
}
|
|
|
|
async handleDownload(request) {
|
|
const playerName = request.player_name;
|
|
this.logger.verbose(`Downloading ${playerName}`);
|
|
|
|
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('${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 ${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('${playerName}','${chunk}',${i + 1},${chunks.length})`,
|
|
true
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
InstancePlugin,
|
|
};
|