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

fix: reconnect on connection issues #165

Merged
merged 1 commit into from
Dec 7, 2023
Merged
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
98 changes: 58 additions & 40 deletions src/clients/sql.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { Pool, PoolClient, PoolConfig, QueryArrayResult, QueryResult } from "pg";
import { Pool, PoolClient, PoolConfig, QueryArrayResult } from "pg";
import AdminClient from "./admin";
import CloudClient from "./cloud";
import { Profile } from "../context/config";
import AsyncContext from "../context/asyncContext";
import { Errors, ExtensionError } from "../utilities/error";

export default class SqlClient {
private pool: Promise<Pool>;
Expand All @@ -12,6 +11,7 @@
private cloudClient: CloudClient;
private context: AsyncContext;
private profile: Profile;
private ended: boolean;

constructor(
adminClient: AdminClient,
Expand All @@ -23,45 +23,61 @@
this.cloudClient = cloudClient;
this.profile = profile;
this.context = context;
this.ended = false;
this.pool = this.buildPool();
this.privateClient = this.buildPrivateClient();
this.handleReconnection();
}

this.pool = new Promise((res, rej) => {
const asyncOp = async () => {
try {
console.log("[SqlClient]", "Building config.");
const config = await this.buildPoolConfig();
const pool = new Pool(config);
console.log("[SqlClient]", "Connecting pool.");

pool.connect().then(() => {
console.log("[SqlClient]", "Pool successfully connected.");
res(pool);
}).catch((err) => {
console.error(err);
rej(new ExtensionError(Errors.poolConnectionFailure, err));
});
} catch (err) {
console.error("[SqlClient]", "Error creating pool: ", err);
rej(new ExtensionError(Errors.poolCreationFailure, err));
}
};

asyncOp();
});
private async handleReconnection() {
let reconnecting = false;

const reconnect = (err: Error) => {
console.error("[SqlClient]", "Unexpected error: ", err);
console.log("[SqlClient]", "Reconnecting.");
if (reconnecting === false && this.ended === false) {
reconnecting = true;
const interval = setInterval(async () => {
try {
const pool = await this.pool;
pool.end();
} catch (err) {
console.error("[SqlClient]", "Error awaiting pool to end. It is ok it the pool connection failed.");
} finally {
this.pool = this.buildPool();
this.privateClient = this.buildPrivateClient();
this.handleReconnection();
reconnecting = false;
clearInterval(interval);
}
}, 5000);
}
};

this.privateClient = new Promise((res, rej) => {
const asyncOp = async () => {
try {
const pool = await this.pool;
const client = await pool.connect();
res(client);
} catch (err) {
console.error("[SqlClient]", "Error awaiting the pool: ", err);
rej(err);
}
};

asyncOp();
});
try {
const pool = await this.pool;
pool.on("error", reconnect);

try {
const client = await this.privateClient;
client.on("error", reconnect);
} catch (err) {
reconnect(err as Error);
console.error("[SqlClient]", "Unexpected error on client: ", err);
}
} catch (err) {
reconnect(err as Error);
console.error("[SqlClient]", "Unexpected error on pool: ", err);
}
}

private async buildPrivateClient(): Promise<PoolClient> {
const pool = await this.pool;
return pool.connect();
}

private async buildPool(): Promise<Pool> {
return new Pool(await this.buildPoolConfig());
}

async connectErr() {
Expand Down Expand Up @@ -124,7 +140,7 @@
* @param values
* @returns query results
*/
async internalQuery(statement: string, values?: Array<any>): Promise<QueryArrayResult<any>> {
async internalQuery(statement: string, values?: Array<string | number>): Promise<QueryArrayResult<any>> {

Check warning on line 143 in src/clients/sql.ts

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Unexpected any. Specify a different type
const pool = await this.pool;
const results = await pool.query(statement, values);

Expand All @@ -145,7 +161,7 @@
* @param values
* @returns query results
*/
async privateQuery(statement: string, values?: Array<any>): Promise<QueryArrayResult<any>> {

Check warning on line 164 in src/clients/sql.ts

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Unexpected any. Specify a different type

Check warning on line 164 in src/clients/sql.ts

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Unexpected any. Specify a different type
const client = await this.privateClient;
// Row mode is a must.
// Otherwise when two columns have the same name, one is dropped
Expand All @@ -163,6 +179,8 @@
* Shut down cleanly the pool.
*/
async end() {
this.ended = true;

try {
const pool = await this.pool;
await pool.end();
Expand Down
Loading