Skip to content
New issue

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

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

Already on GitHub? # to your account

Force a reconnect in case a heartbeat is missing #569

Merged
merged 1 commit into from
Jan 26, 2024
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
46 changes: 21 additions & 25 deletions src/lib/requests/client/GraphQLClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,37 +157,33 @@ export class GraphQLClient extends BaseClient<
}

protected createClient() {
const heartbeatInterval = 1000 * 20;

this.wsClient = createClient({
url: () => this.getBaseUrl().replace(/http(|s)/g, 'ws'),
keepAlive: 20000,
keepAlive: heartbeatInterval,
retryAttempts: Infinity,
retryWait: async (retries) => {
const getDelayInMS = () => {
if (retries < 10) {
return 1000 * 5;
}

if (retries < 50) {
return 1000 * 10;
}

if (retries < 500) {
return 1000 * 30;
}

if (retries < 1000) {
return 1000 * 60;
}

return 1000 * 60 * 5;
};
});

await new Promise((resolve) => {
setTimeout(resolve, getDelayInMS());
});
},
let lastHeartbeat: number = 0;
this.wsClient.on('connected', () => {
lastHeartbeat = Date.now();
});
this.wsClient.on('pong', () => {
lastHeartbeat = Date.now();
});

const checkHeartbeatInterval = heartbeatInterval + 1000 * 10;
// for some reason "this.wsClient" is undefined in the "setInterval" callback
const { wsClient } = this;
setInterval(() => {
const isHeartbeatMissing = Date.now() - lastHeartbeat > checkHeartbeatInterval * 1.1;
if (isHeartbeatMissing) {
// force a reconnect
wsClient.terminate();
}
}, checkHeartbeatInterval);

this.client = new ApolloClient({
cache: new InMemoryCache({
// for whatever reason there is some weird TypeError complaining that
Expand Down
Loading