mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-12 07:04:52 +09:00
Complete rework of the inventory synchronization to reduce the number of times the inventory has to be downloaded and the possibilities for item loss/duplication. The basic concept is to acquire exclusive access to the player data before downloading the data. This prevents the player from logging in to two servers at the same time and getting the synced inventory twice. The acquisition will in most cases execute faster than the player can provide input to the game on login, and if the player data on the master isn't what was previously uploaded then the player inventory is deleted and the player is turned into a spectator while the updated inventory is being transferred into the game. This model allows for the downloading of the synced inventory to be skipped in the case the player joins the same server they left from. The synced data is expanded to include more than just the character and inventory to properly handle sync of dead players. If the player leaves dead on one server this state will be saved and when the player joins another server they continue off as dead. The ghost, god, and spectator controllers are supported, while the cutscene and editor controllers are not. For players in a cutscene when joining the acquisition will be attempted immediately, but the scenario waits until the player is out of the cutscene before acting upon the response to the acquisition. For players in the editor mode the scenario toggles them out of the mode before syncing data. Since uploads to the master can fail handling of this is also added. The scenario will retry uploading the player data at exponentially increasing intervals until it gets the message back that the upload succeeded. Since it's possible for servers to go down and stay down for a long time the exclusive access held by these servers are released after a timeout. This means that a player could be playing and or have uploaded newer data by the time the instance comes back online and tries to upload the inventory, in this case the master will report the upload succeeded but discard the data. Instances may also upload old data if they load back to an earlier save, which will also be discarded by the master. Other small improvements made by this rework: - Add a retry button to the failed download dialog - Update the existing progress dialog instead of destroying and recreating it every time. - Automatically stuff the items from the temporary inventory into the synced inventory if they fit. - Move player back to the position they started the download from if they were turned into a spectator for the download. - Ensure the player has a character if the stored data is wiped. - Add error checking of the RCON commands sent by the instance.
162 lines
5.0 KiB
JavaScript
162 lines
5.0 KiB
JavaScript
/**
|
|
* @module
|
|
*/
|
|
"use strict";
|
|
const libErrors = require("@clusterio/lib/errors");
|
|
const libPlugin = require("@clusterio/lib/plugin");
|
|
const libLuaTools = require("@clusterio/lib/lua_tools");
|
|
|
|
/**
|
|
* 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}`)));
|
|
}
|
|
|
|
onPrepareMasterDisconnect() {
|
|
this.disconnecting = true;
|
|
}
|
|
|
|
onMasterConnectionEvent(event) {
|
|
if (event === "connect") {
|
|
this.disconnecting = false;
|
|
(async () => {
|
|
for (let player_name of this.playersToRelease) {
|
|
if (!this.slave.connector.connected || this.disconnecting) {
|
|
return;
|
|
}
|
|
this.playersToRelease.delete(player);
|
|
await this.info.messages.release.send(this.instance, {
|
|
instance_id: this.instance.id,
|
|
player_name,
|
|
});
|
|
}
|
|
})().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: "Master is temporarily unavailable",
|
|
};
|
|
|
|
if (this.slave.connector.connected && !this.disconnecting) {
|
|
try {
|
|
response = {
|
|
player_name: request.player_name,
|
|
...await this.info.messages.acquire.send(this.instance, {
|
|
instance_id: this.instance.id,
|
|
player_name: request.player_name,
|
|
}),
|
|
};
|
|
} 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.slave.connector.connected) {
|
|
this.playersToRelease.set(request.player_name);
|
|
}
|
|
|
|
try {
|
|
await this.info.messages.release.send(this.instance, {
|
|
instance_id: this.instance.id,
|
|
player_name: request.player_name,
|
|
});
|
|
} 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.slave.connector.connected || this.disconnecting) {
|
|
return;
|
|
}
|
|
|
|
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,
|
|
});
|
|
|
|
} 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 player_name = request.player_name;
|
|
this.logger.verbose(`Downloading ${player_name}`);
|
|
|
|
let response = await this.info.messages.download.send(this.instance, {
|
|
instance_id: this.instance.id,
|
|
player_name,
|
|
});
|
|
|
|
if (!response.player_data) {
|
|
await this.sendRcon(`/sc inventory_sync.download_inventory('${player_name}',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`);
|
|
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})`,
|
|
true
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
InstancePlugin,
|
|
};
|