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(api-client): socket reconnect after coming back from sleep #6287

Merged
merged 5 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
21 changes: 13 additions & 8 deletions packages/api-client/src/tcp/ReconnectingWebsocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {TimeUtil} from '@wireapp/commons';

import * as buffer from '../shims/node/buffer';
import {WebSocketNode} from '../shims/node/websocket';
import {onBackFromSleep} from '../utils/BackFromSleepHandler';

export enum CloseEventCode {
NORMAL_CLOSURE = 1000,
Expand Down Expand Up @@ -82,6 +83,16 @@ export class ReconnectingWebsocket {
}

this.hasUnansweredPing = false;

onBackFromSleep({
callback: () => {
if (this.socket) {
this.logger.debug('Back from sleep, reconnecting WebSocket');
this.socket?.reconnect();
}
},
isDisconnected: () => this.getState() === WEBSOCKET_STATE.CLOSED,
Comment on lines +93 to +100
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wasn't the ping/pong mechanism enough to detect that the connection was closed?
Is there some kind of timer that runs to check if a message has been received in a certain amount of time?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we have the mechanism for that, but it's a ping every 20 seconds, which doesn't seem to be efficient enough to reconnect immediately after coming back from sleep. From what I was testing, it was the 20s that we had to wait for the weboscket to reconnect after coming back from sleep.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Humm that makes sense, 20s is, indeed, pretty long time.

Then your solution seems solid to me 😎

});
}

private readonly internalOnError = (error: ErrorEvent) => {
Expand Down Expand Up @@ -173,16 +184,10 @@ export class ReconnectingWebsocket {
return this.socket ? this.socket.readyState : WEBSOCKET_STATE.CLOSED;
}

public disconnect(reason = 'Closed by client', keepClosed = true): void {
public disconnect(reason = 'Closed by client'): void {
if (this.socket) {
this.logger.info(`Disconnecting from WebSocket (reason: "${reason}")`);
// TODO: 'any' can be removed once this issue is resolved:
// https://github.com/pladaria/reconnecting-websocket/issues/44
(this.socket as any).close(CloseEventCode.NORMAL_CLOSURE, reason, {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method does not accept the 3rd (options) parameter any more.

delay: 0,
fastClose: true,
keepClosed,
});
this.socket.close(CloseEventCode.NORMAL_CLOSURE, reason);
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/api-client/src/tcp/WebSocketClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,9 @@ export class WebSocketClient extends EventEmitter {
}
}

public disconnect(reason?: string, keepClosed = true): void {
public disconnect(reason?: string): void {
if (this.socket) {
this.socket.disconnect(reason, keepClosed);
this.socket.disconnect(reason);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* Wire
* Copyright (C) 2024 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/

import {onBackFromSleep} from './BackFromSleepHandler';

const CHECK_INTERVAL = 2000;
const TOLERANCE = CHECK_INTERVAL * 2;

jest.useFakeTimers();

describe('onBackFromSleep', () => {
let originalDateNow: () => number;
let now: number;

beforeEach(() => {
originalDateNow = Date.now;
now = Date.now();
jest.spyOn(global, 'Date').mockImplementation(
() =>
({
getTime: () => now,
}) as unknown as Date,
);
});

afterEach(() => {
jest.clearAllTimers();
global.Date.now = originalDateNow;
});

it('should call the callback when system wakes up from sleep', () => {
const callback = jest.fn();
onBackFromSleep({callback});

// Simulate system sleep
now += TOLERANCE + 1;
jest.advanceTimersByTime(CHECK_INTERVAL);

expect(callback).toHaveBeenCalledTimes(1);
});

it('should not call the callback for small delays', () => {
const callback = jest.fn();
onBackFromSleep({callback});

// Simulate small delay
now += TOLERANCE - 1;
jest.advanceTimersByTime(CHECK_INTERVAL);

expect(callback).not.toHaveBeenCalled();
});

it('should call the callback if disconnected during sleep', () => {
const callback = jest.fn();
const isDisconnected = jest.fn().mockReturnValue(true);

onBackFromSleep({callback, isDisconnected});

// Simulate system sleep
now += TOLERANCE + 1;
jest.advanceTimersByTime(CHECK_INTERVAL);

expect(callback).toHaveBeenCalledTimes(1);
});

it('should not call the callback if not disconnected during sleep', () => {
const callback = jest.fn();
const isDisconnected = jest.fn().mockReturnValue(false);

onBackFromSleep({callback, isDisconnected});

// Simulate system sleep
now += TOLERANCE + 1;
jest.advanceTimersByTime(CHECK_INTERVAL);

expect(callback).not.toHaveBeenCalled();
});

it('should call the callback only once after sleep', () => {
const callback = jest.fn();
onBackFromSleep({callback});

// Simulate system sleep and wake up
now += TOLERANCE + 1;
jest.advanceTimersByTime(CHECK_INTERVAL);

expect(callback).toHaveBeenCalledTimes(1);

// Simulate more intervals
jest.advanceTimersByTime(CHECK_INTERVAL * 10);

expect(callback).toHaveBeenCalledTimes(1);
});

it('should stop checking when returned function is called', () => {
const callback = jest.fn();
const stop = onBackFromSleep({callback});

// Stop the interval
stop();

// Simulate system sleep
now += TOLERANCE + 1;
jest.advanceTimersByTime(CHECK_INTERVAL);

expect(callback).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Wire
* Copyright (C) 2024 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/

const CHECK_INTERVAL = 2000;
const TOLERANCE = CHECK_INTERVAL * 2;

/**
* This function will call the callback when the system has very likely woken up from sleep.
* It will ignore small delays and will only call the callback if the system was disconnected during sleep.
* @param callback - the function to call when the system wakes up
* @param isDisconnected - (optional) a function to make sure the connection was lost, to reduce the chance of false positives
* @returns a function to stop the interval
* @example
* ```typescript
* const stop = onBackFromSleep({
* callback: () => {
* console.log('Woke up from sleep');
* },
* isDisconnected: () => {
* return !navigator.onLine;
* }
* });
* ```
*/
export const onBackFromSleep = ({
callback,
isDisconnected: isDisconnectedCallback,
}: {
callback: () => void;
isDisconnected?: () => boolean;
}) => {
let lastTime = new Date().getTime();
let wasDisconnected = false;

const tid = setInterval(() => {
const currentTime = new Date().getTime();

// The interval did not run for a while, so we assume the system was sleeping
const wasAsleep = currentTime > lastTime + TOLERANCE;

lastTime = currentTime;

if (isDisconnectedCallback && isDisconnectedCallback()) {
wasDisconnected = true;
}

if (wasAsleep) {
if (!isDisconnectedCallback || wasDisconnected) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't be like that? 🤔

Suggested change
if (!isDisconnectedCallback || wasDisconnected) {
if (!isDisconnectedCallback?.() || wasDisconnected) {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, if the check callback is not provided at all we want to always run the callback

wasDisconnected = false;
callback();
}
}
}, CHECK_INTERVAL);

return () => clearInterval(tid);
};
20 changes: 20 additions & 0 deletions packages/api-client/src/utils/BackFromSleepHandler/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Wire
* Copyright (C) 2024 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/

export * from './BackFromSleepHandler';
Loading