mirror of
https://github.com/ajayyy/SponsorBlockServer.git
synced 2025-12-11 05:57:04 +03:00
Switch postgres instances if there is a failure
This commit is contained in:
@@ -27,20 +27,26 @@ export interface DatabaseConfig {
|
|||||||
|
|
||||||
export class Postgres implements IDatabase {
|
export class Postgres implements IDatabase {
|
||||||
private pool: Pool;
|
private pool: Pool;
|
||||||
|
private lastPoolFail: number = 0;
|
||||||
|
|
||||||
private poolRead: Pool;
|
private poolRead: Pool;
|
||||||
|
private lastPoolReadFail: number = 0;
|
||||||
|
|
||||||
constructor(private config: DatabaseConfig) {}
|
constructor(private config: DatabaseConfig) {}
|
||||||
|
|
||||||
async init(): Promise<void> {
|
async init(): Promise<void> {
|
||||||
this.pool = new Pool(this.config.postgres);
|
this.pool = new Pool(this.config.postgres);
|
||||||
const errorHandler = (err: Error) => {
|
this.pool.on("error", (err) => {
|
||||||
Logger.error(err.stack);
|
Logger.error(err.stack);
|
||||||
};
|
this.lastPoolFail = Date.now();
|
||||||
this.pool.on("error", errorHandler);
|
});
|
||||||
|
|
||||||
if (this.config.postgresReadOnly) {
|
if (this.config.postgresReadOnly) {
|
||||||
this.poolRead = new Pool(this.config.postgresReadOnly);
|
this.poolRead = new Pool(this.config.postgresReadOnly);
|
||||||
this.poolRead.on("error", errorHandler);
|
this.poolRead.on("error", (err) => {
|
||||||
|
Logger.error(err.stack);
|
||||||
|
this.lastPoolReadFail = Date.now();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.config.readOnly) {
|
if (!this.config.readOnly) {
|
||||||
@@ -104,8 +110,11 @@ export class Postgres implements IDatabase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private getClient(type: string): Promise<PoolClient> {
|
private getClient(type: string): Promise<PoolClient> {
|
||||||
if (this.poolRead && (type === "get" || type === "all")
|
const readAvailable = this.poolRead && (type === "get" || type === "all");
|
||||||
&& Math.random() > 1 / (this.config.postgresReadOnly.weight + 1)) {
|
const ignroreReadDueToFailure = this.lastPoolReadFail < Date.now() - 1000 * 30;
|
||||||
|
const readDueToFailure = this.lastPoolFail < Date.now() - 1000 * 30;
|
||||||
|
if (readAvailable && !ignroreReadDueToFailure && (readDueToFailure ||
|
||||||
|
Math.random() > 1 / (this.config.postgresReadOnly.weight + 1))) {
|
||||||
return this.poolRead.connect();
|
return this.poolRead.connect();
|
||||||
} else {
|
} else {
|
||||||
return this.pool.connect();
|
return this.pool.connect();
|
||||||
|
|||||||
Reference in New Issue
Block a user