Skip to content

Commit

Permalink
Replays: Implement retry mechanism for database operations
Browse files Browse the repository at this point in the history
Add retry logic to handle transient database errors in the Replays module.

This update introduces a retry mechanism for database insert operations within the `Replays` class to enhance stability and prevent crashes caused by transient issues such as network interruptions or temporary database unavailability.

By implementing this retry logic, the system can recover from intermittent errors without requiring manual intervention.
  • Loading branch information
DieterReinert authored Jan 6, 2025
1 parent 392ab2d commit 80eb1ac
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion server/replays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,28 @@ export const Replays = new class {
return replayData;
}

export async function retry<T>(fn: () => Promise<T>, retries: number = 3, delayMs: number = 1000): Promise<T> {
let lastError: any;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt < retries) {
console.warn(`Attempt ${attempt} failed. Retrying in ${delayMs}ms...`);
await new Promise(res => setTimeout(res, delayMs));
}
}
}
throw lastError;
}

async add(replay: Replay) {
// obviously upsert exists but this is the easiest way when multiple things need to be changed
const replayData = this.toReplayRow(replay);
try {
await replays.insert(replayData);
// Retry the insert operation up to 3 times with a 1-second delay between attempts
await retry(() => replays.insert(replayData), 3, 1000);
for (const playerName of replay.players) {
await replayPlayers.insert({
playerid: toID(playerName),
Expand Down

0 comments on commit 80eb1ac

Please sign in to comment.