Skip to content

Commit

Permalink
[#52317] android-client: Add exponential backoff to management WS rec…
Browse files Browse the repository at this point in the history
…onnections
  • Loading branch information
lkedziora committed Dec 8, 2023
1 parent 1a4b9f9 commit 7fcb4c1
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.antmicro.update.rdfm.Utils;
import com.antmicro.update.rdfm.exceptions.DeviceUnauthorizedException;
import com.antmicro.update.rdfm.exceptions.ServerConnectionException;
import com.antmicro.update.rdfm.utilities.BackoffCounter;
import com.antmicro.update.rdfm.utilities.HttpUtils;

import java.util.HashMap;
Expand All @@ -22,6 +23,8 @@

public final class ManagementClient extends WebSocketListener {
private static final String TAG = "ManagementWS";
private static final long MIN_RECONNECT_INTERVAL_MILLIS = 1_000;
private static final long MAX_RECONNECT_INTERVAL_MILLIS = 120_000;
private final String mServerAddress;
private final int mMaxShellCount;
private final IDeviceTokenProvider mTokenProvider;
Expand Down Expand Up @@ -122,11 +125,15 @@ public void onFailure(WebSocket webSocket, Throwable t, Response response) {
}

private void reconnectThread() {
BackoffCounter counter = new BackoffCounter(MIN_RECONNECT_INTERVAL_MILLIS, MAX_RECONNECT_INTERVAL_MILLIS);
while (true) {
long sleepDurationMillis = counter.next();
Log.i(TAG, "Reconnecting in " + sleepDurationMillis + "ms..");

// Delay until reconnection
while (true) {
try {
Thread.sleep(5000);
Thread.sleep(sleepDurationMillis);
break;
} catch (InterruptedException e) {
// empty
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.antmicro.update.rdfm.utilities;

public class BackoffCounter {
private long mCurrent;
private final long mInitialValue;
private final long mMaxValue;

public BackoffCounter(long initialValue, long maxValue) {
if (initialValue > maxValue) {
throw new IllegalArgumentException("initialValue is larger than maxValue");
}
mCurrent = initialValue;
mInitialValue = initialValue;
mMaxValue = maxValue;
}

/**
* Advance the backoff counter and return the new value.
*
* @return new backoff value
*/
public long next() {
mCurrent = Math.multiplyExact(mCurrent, 2L);
if (mCurrent > mMaxValue) {
mCurrent = mMaxValue;
}
return mCurrent;
}

/**
* Reset the counter to its initial value
*/
public void reset() {
mCurrent = mInitialValue;
}


}

0 comments on commit 7fcb4c1

Please sign in to comment.