mirror of
https://github.com/ajayyy/SponsorBlockServer.git
synced 2025-12-09 13:07:02 +03:00
Add retry logic to postgres requests
Maybe solves https://github.com/ajayyy/SponsorBlockServer/issues/487
This commit is contained in:
@@ -32,6 +32,8 @@ export class Postgres implements IDatabase {
|
|||||||
private poolRead: Pool;
|
private poolRead: Pool;
|
||||||
private lastPoolReadFail = 0;
|
private lastPoolReadFail = 0;
|
||||||
|
|
||||||
|
private maxTries = 3;
|
||||||
|
|
||||||
constructor(private config: DatabaseConfig) {}
|
constructor(private config: DatabaseConfig) {}
|
||||||
|
|
||||||
async init(): Promise<void> {
|
async init(): Promise<void> {
|
||||||
@@ -94,27 +96,36 @@ export class Postgres implements IDatabase {
|
|||||||
|
|
||||||
Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`);
|
Logger.debug(`prepare (postgres): type: ${type}, query: ${query}, params: ${params}`);
|
||||||
|
|
||||||
try {
|
let tries = 0;
|
||||||
const queryResult = await this.getPool(type, options).query({ text: query, values: params });
|
do {
|
||||||
|
tries++;
|
||||||
|
|
||||||
switch (type) {
|
try {
|
||||||
case "get": {
|
const queryResult = await this.getPool(type, options).query({ text: query, values: params });
|
||||||
const value = queryResult.rows[0];
|
|
||||||
Logger.debug(`result (postgres): ${JSON.stringify(value)}`);
|
switch (type) {
|
||||||
return value;
|
case "get": {
|
||||||
|
const value = queryResult.rows[0];
|
||||||
|
Logger.debug(`result (postgres): ${JSON.stringify(value)}`);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
case "all": {
|
||||||
|
const values = queryResult.rows;
|
||||||
|
Logger.debug(`result (postgres): ${JSON.stringify(values)}`);
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
case "run": {
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case "all": {
|
} catch (err) {
|
||||||
const values = queryResult.rows;
|
if (err instanceof Error && err.message.includes("terminating connection due to conflict with recovery")) {
|
||||||
Logger.debug(`result (postgres): ${JSON.stringify(values)}`);
|
options.useReplica = false;
|
||||||
return values;
|
|
||||||
}
|
|
||||||
case "run": {
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Logger.error(`prepare (postgres) try ${tries}: ${err}`);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} while ((type === "get" || type === "all") && tries < this.maxTries);
|
||||||
Logger.error(`prepare (postgres): ${err}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private getPool(type: string, options: QueryOption): Pool {
|
private getPool(type: string, options: QueryOption): Pool {
|
||||||
|
|||||||
Reference in New Issue
Block a user