Implement autosaving of data held in memory

Add controller.autosave_interval config that specifies the frequency
which controller config, hosts, instances, users, mod packs and plugin
specific data which is held in memory should be automatically flushed to
disk if they have changed since the last time they were saved.  This
prevents data loss in the event of a server crash.

Plugins can use the onSaveData hook to save its own data at the same
time as the controller does and this obsoletes making an autosave
interval in the plugin.

Resolves #523.
This commit is contained in:
Hornwitser committed 2023-11-29 20:18:50 +01:00
1 parent faadf873fb
commit ffe5040644
14 files changed
+168 -57

No files matched your search

+7 -9
View File
@@ -38,16 +38,11 @@ async function saveDatabase(
export class ControllerPlugin extends BaseControllerPlugin {
acquiredPlayers!: Map<string, { instanceId: number, expires?: number }>;
playerDatastore!: Map<string, IpcPlayerData>;
autosaveId!: ReturnType<typeof setInterval>;
playerDatastoreDirty = false;
async init() {
this.acquiredPlayers = new Map();
this.playerDatastore = await loadDatabase(this.controller.config, this.logger);
this.autosaveId = setInterval(() => {
saveDatabase(this.controller.config, this.playerDatastore, this.logger).catch(err => {
this.logger.error(`Unexpected error autosaving player data:\n${err.stack}`);
});
}, this.controller.config.get("inventory_sync.autosave_interval") as number * 1000);
this.controller.handle(msg.AcquireRequest, this.handleAcquireRequest.bind(this));
this.controller.handle(msg.ReleaseRequest, this.handleReleaseRequest.bind(this));
@@ -161,6 +156,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
if (store) {
this.logger.verbose(`Received player data for ${playerName} from ${instanceName}`);
this.playerDatastore.set(playerName, playerData);
this.playerDatastoreDirty = true;
}
}
@@ -179,9 +175,11 @@ export class ControllerPlugin extends BaseControllerPlugin {
return new msg.DownloadRequest.Response(this.playerDatastore.get(playerName) || null);
}
async onShutdown() {
clearInterval(this.autosaveId);
await saveDatabase(this.controller.config, this.playerDatastore, this.logger);
async onSaveData() {
if (this.playerDatastoreDirty) {
this.playerDatastoreDirty = false;
await saveDatabase(this.controller.config, this.playerDatastore, this.logger);
}
}
async handleDatabaseStatsRequest() {