Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replays: Implement retry mechanism for database operations #10799

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion server/replays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,27 @@ export const Replays = new class {
return replayData;
}

async retry<T>(fn: () => Promise<T>, retries = 3, delayMs = 1000): Promise<T> {
let lastError: any;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt < retries) {
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 this.retry(() => replays.insert(replayData), 3, 1000);
for (const playerName of replay.players) {
await replayPlayers.insert({
playerid: toID(playerName),
Expand Down
Loading