This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/matrix/net/Reconnector.ts

196 lines
7.4 KiB
TypeScript
Raw Normal View History

2020-08-05 22:08:55 +05:30
/*
Copyright 2020 Bruno Windels <bruno@windels.cloud>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2021-09-30 06:00:21 +05:30
import {ObservableValue} from "../../observable/ObservableValue";
2021-11-22 15:16:46 +05:30
import type {ExponentialRetryDelay} from "./ExponentialRetryDelay";
import type {TimeMeasure} from "../../platform/web/dom/Clock.js";
import type {OnlineStatus} from "../../platform/web/dom/OnlineStatus.js";
import type {IVersionResponse} from "./types/response";
import type {HomeServerApi} from "./HomeServerApi.js";
2020-04-19 22:32:10 +05:30
2021-11-22 15:16:46 +05:30
export enum ConnectionStatus {
2020-04-19 22:32:10 +05:30
"Waiting",
"Reconnecting",
"Online"
2021-11-22 15:16:46 +05:30
};
2020-04-19 22:32:10 +05:30
export class Reconnector {
2021-11-22 15:16:46 +05:30
private readonly _retryDelay: ExponentialRetryDelay;
private readonly _createTimeMeasure: () => TimeMeasure;
private readonly _onlineStatus: OnlineStatus;
private readonly _state: ObservableValue<ConnectionStatus>;
private _isReconnecting: boolean;
private _versionsResponse?: IVersionResponse = undefined;
private _stateSince: TimeMeasure;
constructor({retryDelay, createMeasure, onlineStatus}: {retryDelay: ExponentialRetryDelay, createMeasure: () => TimeMeasure, onlineStatus: OnlineStatus}) {
2020-04-19 22:32:10 +05:30
this._onlineStatus = onlineStatus;
this._retryDelay = retryDelay;
this._createTimeMeasure = createMeasure;
// assume online, and do our thing when something fails
this._state = new ObservableValue(ConnectionStatus.Online);
this._isReconnecting = false;
}
2021-11-22 15:16:46 +05:30
get lastVersionsResponse(): IVersionResponse | undefined {
2020-04-19 22:32:10 +05:30
return this._versionsResponse;
}
2021-11-22 15:16:46 +05:30
get connectionStatus(): ObservableValue<ConnectionStatus> {
2020-04-19 22:32:10 +05:30
return this._state;
}
2021-11-22 15:16:46 +05:30
get retryIn(): number {
2020-04-19 22:32:10 +05:30
if (this._state.get() === ConnectionStatus.Waiting) {
return this._retryDelay.nextValue - this._stateSince.measure();
}
return 0;
}
2021-11-22 15:16:46 +05:30
async onRequestFailed(hsApi: HomeServerApi): Promise<void> {
2020-05-07 00:28:48 +05:30
if (!this._isReconnecting) {
this._isReconnecting = true;
2020-04-19 22:32:10 +05:30
const onlineStatusSubscription = this._onlineStatus && this._onlineStatus.subscribe(online => {
if (online) {
this.tryNow();
}
});
try {
await this._reconnectLoop(hsApi);
} catch (err) {
// nothing is catching the error above us,
// so just log here
console.error(err);
} finally {
if (onlineStatusSubscription) {
// unsubscribe from this._onlineStatus
onlineStatusSubscription();
}
2020-05-07 00:28:48 +05:30
this._isReconnecting = false;
2020-04-19 22:32:10 +05:30
}
}
}
2021-11-22 15:16:46 +05:30
tryNow(): void {
2020-04-19 22:32:10 +05:30
if (this._retryDelay) {
// this will interrupt this._retryDelay.waitForRetry() in _reconnectLoop
this._retryDelay.abort();
}
}
2021-11-22 15:16:46 +05:30
_setState(state: ConnectionStatus): void {
2020-04-19 22:32:10 +05:30
if (state !== this._state.get()) {
if (state === ConnectionStatus.Waiting) {
this._stateSince = this._createTimeMeasure();
} else {
this._stateSince = null;
}
this._state.set(state);
}
}
2021-11-22 15:16:46 +05:30
async _reconnectLoop(hsApi: HomeServerApi): Promise<void> {
this._versionsResponse = undefined;
2020-04-19 22:32:10 +05:30
this._retryDelay.reset();
while (!this._versionsResponse) {
try {
this._setState(ConnectionStatus.Reconnecting);
// use 30s timeout, as a tradeoff between not giving up
// too quickly on a slow server, and not waiting for
2020-04-19 22:32:10 +05:30
// a stale connection when we just came online again
const versionsRequest = hsApi.versions({timeout: 30000});
2020-04-19 22:32:10 +05:30
this._versionsResponse = await versionsRequest.response();
this._setState(ConnectionStatus.Online);
} catch (err) {
if (err.name === "ConnectionError") {
2020-04-19 22:32:10 +05:30
this._setState(ConnectionStatus.Waiting);
await this._retryDelay.waitForRetry();
2020-04-19 22:32:10 +05:30
} else {
throw err;
}
}
}
}
}
import {Clock as MockClock} from "../../mocks/Clock.js";
2021-11-22 15:16:46 +05:30
import {ExponentialRetryDelay as _ExponentialRetryDelay} from "./ExponentialRetryDelay";
import {ConnectionError} from "../error.js"
2020-04-19 22:32:10 +05:30
export function tests() {
function createHsApiMock(remainingFailures) {
return {
versions() {
return {
response() {
if (remainingFailures) {
remainingFailures -= 1;
2020-04-19 22:35:12 +05:30
return Promise.reject(new ConnectionError());
2020-04-19 22:32:10 +05:30
} else {
return Promise.resolve(42);
}
}
};
}
}
}
return {
"test reconnecting with 1 failure": async assert => {
const clock = new MockClock();
const {createMeasure} = clock;
const onlineStatus = new ObservableValue(false);
2021-11-22 15:16:46 +05:30
const retryDelay = new _ExponentialRetryDelay(clock.createTimeout);
2020-04-19 22:32:10 +05:30
const reconnector = new Reconnector({retryDelay, onlineStatus, createMeasure});
const {connectionStatus} = reconnector;
2021-11-22 15:16:46 +05:30
const statuses: ConnectionStatus[] = [];
2020-04-19 22:32:10 +05:30
const subscription = reconnector.connectionStatus.subscribe(s => {
statuses.push(s);
});
reconnector.onRequestFailed(createHsApiMock(1));
await connectionStatus.waitFor(s => s === ConnectionStatus.Waiting).promise;
clock.elapse(2000);
await connectionStatus.waitFor(s => s === ConnectionStatus.Online).promise;
assert.deepEqual(statuses, [
ConnectionStatus.Reconnecting,
ConnectionStatus.Waiting,
ConnectionStatus.Reconnecting,
ConnectionStatus.Online
]);
assert.strictEqual(reconnector.lastVersionsResponse, 42);
subscription();
},
"test reconnecting with onlineStatus": async assert => {
const clock = new MockClock();
const {createMeasure} = clock;
const onlineStatus = new ObservableValue(false);
2021-11-22 15:16:46 +05:30
const retryDelay = new _ExponentialRetryDelay(clock.createTimeout);
2020-04-19 22:32:10 +05:30
const reconnector = new Reconnector({retryDelay, onlineStatus, createMeasure});
const {connectionStatus} = reconnector;
reconnector.onRequestFailed(createHsApiMock(1));
await connectionStatus.waitFor(s => s === ConnectionStatus.Waiting).promise;
onlineStatus.set(true); //skip waiting
await connectionStatus.waitFor(s => s === ConnectionStatus.Online).promise;
assert.equal(connectionStatus.get(), ConnectionStatus.Online);
assert.strictEqual(reconnector.lastVersionsResponse, 42);
},
}
}