Reconnect websocket with exponential backof if connection is lost

This commit is contained in:
AsamK 2021-10-15 20:00:52 +02:00
parent 5648714641
commit 4a3b0e5124

View file

@ -887,6 +887,8 @@ public class ManagerImpl implements Manager {
signalWebSocket.connect(); signalWebSocket.connect();
hasCaughtUpWithOldMessages = false; hasCaughtUpWithOldMessages = false;
var backOffCounter = 0;
final var MAX_BACKOFF_COUNTER = 9;
while (!Thread.interrupted()) { while (!Thread.interrupted()) {
SignalServiceEnvelope envelope; SignalServiceEnvelope envelope;
@ -901,6 +903,8 @@ public class ManagerImpl implements Manager {
// store message on disk, before acknowledging receipt to the server // store message on disk, before acknowledging receipt to the server
cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId); cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
}); });
backOffCounter = 0;
if (result.isPresent()) { if (result.isPresent()) {
envelope = result.get(); envelope = result.get();
logger.debug("New message received from server"); logger.debug("New message received from server");
@ -924,11 +928,24 @@ public class ManagerImpl implements Manager {
} else { } else {
throw e; throw e;
} }
} catch (WebSocketUnavailableException e) { } catch (IOException e) {
logger.debug("Pipe unexpectedly unavailable, connecting"); logger.debug("Pipe unexpectedly unavailable: {}", e.getMessage());
if (e instanceof WebSocketUnavailableException || "Connection closed!".equals(e.getMessage())) {
final var sleepMilliseconds = 100 * (long) Math.pow(2, backOffCounter);
backOffCounter = Math.min(backOffCounter + 1, MAX_BACKOFF_COUNTER);
logger.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds);
try {
Thread.sleep(sleepMilliseconds);
} catch (InterruptedException interruptedException) {
return;
}
hasCaughtUpWithOldMessages = false;
signalWebSocket.connect(); signalWebSocket.connect();
continue; continue;
}
throw e;
} catch (TimeoutException e) { } catch (TimeoutException e) {
backOffCounter = 0;
if (returnOnTimeout) return; if (returnOnTimeout) return;
continue; continue;
} }