Skip to content

Commit

Permalink
Small saveserver changes (#1101)
Browse files Browse the repository at this point in the history
- Adds a saveguard to the current profile being saved to prevent it from
being called again for a save if one is already underway, this is only
ever possible in my testing to happen on certain race conditions where a
user might quit the game at the same time as the server is saving, none
the less it's better if this is only processed one-time
- Wraps current timed saves in a try-catch so that if one profile errors
out during saving this does not completely stop the method from running.
  • Loading branch information
chompDev authored Jan 31, 2025
2 parents 554159e + 7f2f270 commit a460470
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions project/src/servers/SaveServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { inject, injectAll, injectable } from "tsyringe";
export class SaveServer {
protected profileFilepath = "user/profiles/";
protected profiles: Map<string, ISptProfile> = new Map();
protected profilesBeingSaved: Set<string> = new Set();
protected onBeforeSaveCallbacks: Map<string, (profile: ISptProfile) => Promise<ISptProfile>> = new Map();
protected saveSHA1: { [key: string]: string } = {};

Expand Down Expand Up @@ -71,12 +72,19 @@ export class SaveServer {
*/
public async save(): Promise<void> {
const timer = new Timer();
let savedProfiles = 0;

for (const [sessionId] of this.profiles) {
await this.saveProfile(sessionId);
try {
await this.saveProfile(sessionId);
savedProfiles++;
} catch (error) {
this.logger.error(`Could not save profile ${sessionId} | ${error}`);
}
}
const profileCount = this.profiles.size;

this.logger.debug(
`Saving ${profileCount} profile${profileCount > 1 ? "s" : ""} took ${timer.getTime("ms")}ms`,
`Saving ${savedProfiles} profile${savedProfiles > 1 ? "s" : ""} took ${timer.getTime("ms")}ms`,
false,
);
}
Expand Down Expand Up @@ -184,6 +192,12 @@ export class SaveServer {
throw new Error(`Profile ${sessionID} does not exist! Unable to save this profile!`);
}

if (this.profilesBeingSaved.has(sessionID)) {
throw new Error(`Profile ${sessionID} is already being saved!`);
}

this.profilesBeingSaved.add(sessionID);

const filePath = `${this.profileFilepath}${sessionID}.json`;

// Run pre-save callbacks before we save into json
Expand All @@ -201,12 +215,16 @@ export class SaveServer {
this.profiles.get(sessionID),
!this.configServer.getConfig<ICoreConfig>(ConfigTypes.CORE).features.compressProfile,
);

const sha1 = await this.hashUtil.generateSha1ForDataAsync(jsonProfile);

if (typeof this.saveSHA1[sessionID] !== "string" || this.saveSHA1[sessionID] !== sha1) {
this.saveSHA1[sessionID] = sha1;
// save profile to disk
await this.fileSystem.write(filePath, jsonProfile);
}

this.profilesBeingSaved.delete(sessionID);
}

/**
Expand Down

0 comments on commit a460470

Please sign in to comment.