diff --git a/rollbar-android/src/main/java/com/rollbar/android/notifier/sender/ConnectionAwareSenderFailureStrategy.java b/rollbar-android/src/main/java/com/rollbar/android/notifier/sender/ConnectionAwareSenderFailureStrategy.java index 3479d1a5..060bd7df 100644 --- a/rollbar-android/src/main/java/com/rollbar/android/notifier/sender/ConnectionAwareSenderFailureStrategy.java +++ b/rollbar-android/src/main/java/com/rollbar/android/notifier/sender/ConnectionAwareSenderFailureStrategy.java @@ -8,6 +8,7 @@ import com.rollbar.notifier.util.ObjectsUtils; import java.net.SocketException; +import java.net.SocketTimeoutException; import java.net.UnknownHostException; /** @@ -148,7 +149,10 @@ private NetworkStatus getNetworkStatus(Throwable error) { return NetworkStatus.OK; } - if (error instanceof SocketException || error instanceof UnknownHostException) { + // SocketTimeoutException is not a SocketException. It's what a connection that stops + // answering throws once the sender's timeouts expire, so it has to be listed on its own. + if (error instanceof SocketException || error instanceof SocketTimeoutException + || error instanceof UnknownHostException) { if (detector.isNetworkAvailable()) { return NetworkStatus.UNKNOWN_NETWORK_ISSUE; } else { diff --git a/rollbar-android/src/test/java/com/rollbar/android/notifier/sender/ConnectionAwareSenderFailureStrategyTest.java b/rollbar-android/src/test/java/com/rollbar/android/notifier/sender/ConnectionAwareSenderFailureStrategyTest.java index 29c1965e..b5d86a80 100644 --- a/rollbar-android/src/test/java/com/rollbar/android/notifier/sender/ConnectionAwareSenderFailureStrategyTest.java +++ b/rollbar-android/src/test/java/com/rollbar/android/notifier/sender/ConnectionAwareSenderFailureStrategyTest.java @@ -2,6 +2,7 @@ import com.rollbar.api.payload.Payload; import com.rollbar.notifier.sender.SenderFailureStrategy; +import com.rollbar.notifier.sender.exception.SenderException; import com.rollbar.notifier.sender.result.Response; import org.junit.Before; import org.junit.Test; @@ -10,6 +11,7 @@ import org.mockito.ArgumentCaptor; import java.net.ConnectException; +import java.net.SocketTimeoutException; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -105,6 +107,48 @@ public void ifTheNetworkIsUpSendingShouldBeSuspendedFor1SecAndPayloadRetried() { } } + public static class GivenATimeoutErrorTest extends ConnectionAwareSenderFailureStrategyTest { + // Wrapped the same way the sender reports it to the listeners. + private final SenderException exception = + new SenderException(new SocketTimeoutException("connect timed out")); + + @Test + public void ifTheNetworkIsDownSendingShouldBeSuspendedFor5MinutesAndPayloadRetried() { + when(connectivityDetector.isNetworkAvailable()).thenReturn(false); + + SenderFailureStrategy.PayloadAction action = sut.getAction(payload, exception); + + assertThat(action, equalTo(SenderFailureStrategy.PayloadAction.CAN_BE_RETRIED)); + assertThat(sut.isSendingSuspended(), is(true)); + + moveTimeForward(299999); + + assertThat(sut.isSendingSuspended(), is(true)); + + moveTimeForward(1); + + assertThat(sut.isSendingSuspended(), is(false)); + } + + @Test + public void ifTheNetworkIsUpSendingShouldBeSuspendedFor1SecAndPayloadRetried() { + when(connectivityDetector.isNetworkAvailable()).thenReturn(true); + + SenderFailureStrategy.PayloadAction action = sut.getAction(payload, exception); + + assertThat(action, equalTo(SenderFailureStrategy.PayloadAction.CAN_BE_RETRIED)); + assertThat(sut.isSendingSuspended(), is(true)); + + moveTimeForward(999); + + assertThat(sut.isSendingSuspended(), is(true)); + + moveTimeForward(1); + + assertThat(sut.isSendingSuspended(), is(false)); + } + } + public static class GivenAnUnrecognizedError extends ConnectionAwareSenderFailureStrategyTest { private final IllegalStateException exception = new IllegalStateException("Something unexpected"); diff --git a/rollbar-java/src/main/java/com/rollbar/notifier/config/Config.java b/rollbar-java/src/main/java/com/rollbar/notifier/config/Config.java index b154f7cc..8d4c4312 100644 --- a/rollbar-java/src/main/java/com/rollbar/notifier/config/Config.java +++ b/rollbar-java/src/main/java/com/rollbar/notifier/config/Config.java @@ -2,7 +2,7 @@ import com.rollbar.notifier.Rollbar; import com.rollbar.notifier.sender.Sender; -import com.rollbar.notifier.sender.json.JsonSerializer; +import com.rollbar.notifier.sender.SyncSender; import java.net.Proxy; @@ -24,6 +24,26 @@ public interface Config extends CommonConfig { */ Proxy proxy(); + /** + * Time in milliseconds the default sender waits while connecting to the Rollbar API. + * Ignored when a custom {@link #sender() sender} is configured. + * + * @return the connect timeout in milliseconds. + */ + default int connectTimeoutMillis() { + return SyncSender.DEFAULT_CONNECT_TIMEOUT_MILLIS; + } + + /** + * Time in milliseconds the default sender waits for data from the Rollbar API once connected. + * Ignored when a custom {@link #sender() sender} is configured. + * + * @return the read timeout in milliseconds. + */ + default int readTimeoutMillis() { + return SyncSender.DEFAULT_READ_TIMEOUT_MILLIS; + } + /** *
* If set to true (the default), a JVM shutdown hook is registered that flushes any payloads diff --git a/rollbar-java/src/main/java/com/rollbar/notifier/config/ConfigBuilder.java b/rollbar-java/src/main/java/com/rollbar/notifier/config/ConfigBuilder.java index 2fc772cc..6a637d40 100644 --- a/rollbar-java/src/main/java/com/rollbar/notifier/config/ConfigBuilder.java +++ b/rollbar-java/src/main/java/com/rollbar/notifier/config/ConfigBuilder.java @@ -103,6 +103,10 @@ public class ConfigBuilder { protected boolean compressPayload; + protected int connectTimeoutMillis = SyncSender.DEFAULT_CONNECT_TIMEOUT_MILLIS; + + protected int readTimeoutMillis = SyncSender.DEFAULT_READ_TIMEOUT_MILLIS; + protected boolean flushOnShutdown; protected long shutdownTimeoutMillis; @@ -166,6 +170,8 @@ private ConfigBuilder(Config config) { this.defaultLevels = new DefaultLevels(config); this.truncateLargePayloads = config.truncateLargePayloads(); this.compressPayload = config.compressPayload(); + this.connectTimeoutMillis = config.connectTimeoutMillis(); + this.readTimeoutMillis = config.readTimeoutMillis(); this.flushOnShutdown = config.flushOnShutdown(); this.shutdownTimeoutMillis = config.shutdownTimeoutMillis(); this.maximumTelemetryData = config.maximumTelemetryData(); @@ -527,6 +533,27 @@ public ConfigBuilder compressPayload(boolean compress) { return this; } + /** + *
+ * Time in milliseconds the default sender waits while connecting to the Rollbar API. + * Default: {@value SyncSender#DEFAULT_CONNECT_TIMEOUT_MILLIS}. Zero means wait forever, which + * is not recommended. + *
+ *+ * Only applies when this builder creates the default sender. It has no effect when a custom + * {@link #sender(Sender) sender} is set, or when the builder starts from an existing + * configuration, for example through {@code Rollbar.configure}, because that configuration's + * sender is reused. + *
+ * @param connectTimeoutMillis the connect timeout in milliseconds. + * @return the builder instance. + * @throws IllegalArgumentException if the timeout is negative. + */ + public ConfigBuilder connectTimeoutMillis(int connectTimeoutMillis) { + this.connectTimeoutMillis = requireNonNegative(connectTimeoutMillis, "connectTimeoutMillis"); + return this; + } + /** ** If set to true (the default), a JVM shutdown hook is registered that flushes any payloads @@ -552,6 +579,34 @@ public ConfigBuilder flushOnShutdown(boolean flushOnShutdown) { return this; } + /** + *
+ * Time in milliseconds the default sender waits for data from the Rollbar API once connected. + * Default: {@value SyncSender#DEFAULT_READ_TIMEOUT_MILLIS}. Zero means wait forever, which is + * not recommended. + *
+ *+ * Only applies when this builder creates the default sender. It has no effect when a custom + * {@link #sender(Sender) sender} is set, or when the builder starts from an existing + * configuration, for example through {@code Rollbar.configure}, because that configuration's + * sender is reused. + *
+ * @param readTimeoutMillis the read timeout in milliseconds. + * @return the builder instance. + * @throws IllegalArgumentException if the timeout is negative. + */ + public ConfigBuilder readTimeoutMillis(int readTimeoutMillis) { + this.readTimeoutMillis = requireNonNegative(readTimeoutMillis, "readTimeoutMillis"); + return this; + } + + private static int requireNonNegative(int value, String name) { + if (value < 0) { + throw new IllegalArgumentException(name + " must not be negative: " + value); + } + return value; + } + /** ** The maximum time, in milliseconds, that the shutdown hook will spend flushing buffered @@ -658,7 +713,9 @@ public Config build() { new SyncSender.Builder(this.endpoint) .accessToken(accessToken) .proxy(proxy) - .compressPayload(this.compressPayload); + .compressPayload(this.compressPayload) + .connectTimeoutMillis(this.connectTimeoutMillis) + .readTimeoutMillis(this.readTimeoutMillis); if (this.jsonSerializer != null) { innerSender.jsonSerializer(this.jsonSerializer); } @@ -735,6 +792,10 @@ private static class ConfigImpl implements Config { private final boolean compressPayload; + private final int connectTimeoutMillis; + + private final int readTimeoutMillis; + private final boolean flushOnShutdown; private final long shutdownTimeoutMillis; @@ -782,6 +843,8 @@ private static class ConfigImpl implements Config { this.defaultLevels = builder.defaultLevels; this.truncateLargePayloads = builder.truncateLargePayloads; this.compressPayload = builder.compressPayload; + this.connectTimeoutMillis = builder.connectTimeoutMillis; + this.readTimeoutMillis = builder.readTimeoutMillis; this.flushOnShutdown = builder.flushOnShutdown; this.shutdownTimeoutMillis = builder.shutdownTimeoutMillis; this.maximumTelemetryData = builder.maximumTelemetryData; @@ -943,6 +1006,16 @@ public boolean compressPayload() { return this.compressPayload; } + @Override + public int connectTimeoutMillis() { + return this.connectTimeoutMillis; + } + + @Override + public int readTimeoutMillis() { + return this.readTimeoutMillis; + } + @Override public boolean flushOnShutdown() { return this.flushOnShutdown; diff --git a/rollbar-java/src/main/java/com/rollbar/notifier/sender/SenderShutdownHook.java b/rollbar-java/src/main/java/com/rollbar/notifier/sender/SenderShutdownHook.java index b5acfbae..a1a26428 100644 --- a/rollbar-java/src/main/java/com/rollbar/notifier/sender/SenderShutdownHook.java +++ b/rollbar-java/src/main/java/com/rollbar/notifier/sender/SenderShutdownHook.java @@ -17,11 +17,12 @@ *
* *- * The hook is bounded by a timeout. Flushing performs blocking network I/O, and the sender does - * not impose a socket timeout of its own, so an unbounded flush would be able to stall JVM - * shutdown for as long as the remote end kept the connection open. Instead the flush runs on a - * separate daemon thread and this hook waits for it for at most {@code timeoutMillis}; once that - * elapses shutdown continues regardless, and the daemon thread is torn down with the JVM. + * The hook is bounded by a timeout. Flushing performs blocking network I/O, and the sender's + * socket timeouts (30 s by default) are much longer than this hook's budget, so an unbounded + * flush could stall JVM shutdown for that long, or forever if the timeouts are set to zero. + * Instead the flush runs on a separate daemon thread and this hook waits for it for at most + * {@code timeoutMillis}; once that elapses shutdown continues regardless, and the daemon thread + * is torn down with the JVM. *
* *
diff --git a/rollbar-java/src/main/java/com/rollbar/notifier/sender/SyncSender.java b/rollbar-java/src/main/java/com/rollbar/notifier/sender/SyncSender.java
index 2a8f0cb3..634c6d24 100755
--- a/rollbar-java/src/main/java/com/rollbar/notifier/sender/SyncSender.java
+++ b/rollbar-java/src/main/java/com/rollbar/notifier/sender/SyncSender.java
@@ -26,6 +26,16 @@ public class SyncSender extends AbstractSender {
public static final String UTF_8 = "UTF-8";
+ /**
+ * Default time in milliseconds to wait while establishing a connection to the Rollbar API.
+ */
+ public static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 30_000;
+
+ /**
+ * Default time in milliseconds to wait for data from the Rollbar API once connected.
+ */
+ public static final int DEFAULT_READ_TIMEOUT_MILLIS = 30_000;
+
private final URL url;
private final JsonSerializer jsonSerializer;
@@ -36,12 +46,18 @@ public class SyncSender extends AbstractSender {
private final boolean compressPayload;
+ private final int connectTimeoutMillis;
+
+ private final int readTimeoutMillis;
+
SyncSender(Builder builder) {
this.url = builder.url;
this.jsonSerializer = builder.jsonSerializer;
this.accessToken = builder.accessToken;
this.proxy = builder.proxy != null ? builder.proxy : Proxy.NO_PROXY;
this.compressPayload = builder.compressPayload;
+ this.connectTimeoutMillis = builder.connectTimeoutMillis;
+ this.readTimeoutMillis = builder.readTimeoutMillis;
}
@Override
@@ -66,6 +82,11 @@ private HttpURLConnection getConnection() throws IOException {
// By default, this will use the HTTPS Rollbar API URL defined in DEFAULT_API_ENDPOINT.
HttpURLConnection connection = (HttpURLConnection) url.openConnection(this.proxy);
+ // Without these calls HttpURLConnection never times out, which could block the sender
+ // thread forever.
+ connection.setConnectTimeout(connectTimeoutMillis);
+ connection.setReadTimeout(readTimeoutMillis);
+
if (accessToken != null && !"".equals(accessToken)) {
connection.setRequestProperty("x-rollbar-access-token", accessToken);
}
@@ -144,6 +165,10 @@ public static final class Builder {
private boolean compressPayload = true;
+ private int connectTimeoutMillis = DEFAULT_CONNECT_TIMEOUT_MILLIS;
+
+ private int readTimeoutMillis = DEFAULT_READ_TIMEOUT_MILLIS;
+
public Builder() {
this(DEFAULT_API_ENDPOINT);
}
@@ -218,6 +243,32 @@ public Builder compressPayload(boolean compress) {
return this;
}
+ /**
+ * Time in milliseconds to wait while establishing a connection to the Rollbar API.
+ * Default: {@value SyncSender#DEFAULT_CONNECT_TIMEOUT_MILLIS}. Zero means wait forever, which
+ * is not recommended: a single unresponsive connection would stop all reporting.
+ * @param connectTimeoutMillis the connect timeout in milliseconds.
+ * @return the builder instance.
+ * @throws IllegalArgumentException if the timeout is negative.
+ */
+ public Builder connectTimeoutMillis(int connectTimeoutMillis) {
+ this.connectTimeoutMillis = requireNonNegative(connectTimeoutMillis, "connectTimeoutMillis");
+ return this;
+ }
+
+ /**
+ * Time in milliseconds to wait for data from the Rollbar API once connected.
+ * Default: {@value SyncSender#DEFAULT_READ_TIMEOUT_MILLIS}. Zero means wait forever, which
+ * is not recommended: a single unresponsive connection would stop all reporting.
+ * @param readTimeoutMillis the read timeout in milliseconds.
+ * @return the builder instance.
+ * @throws IllegalArgumentException if the timeout is negative.
+ */
+ public Builder readTimeoutMillis(int readTimeoutMillis) {
+ this.readTimeoutMillis = requireNonNegative(readTimeoutMillis, "readTimeoutMillis");
+ return this;
+ }
+
/**
* Builds the {@link SyncSender sync sender}.
*
@@ -227,6 +278,13 @@ public SyncSender build() {
return new SyncSender(this);
}
+ private static int requireNonNegative(int value, String name) {
+ if (value < 0) {
+ throw new IllegalArgumentException(name + " must not be negative: " + value);
+ }
+ return value;
+ }
+
private static URL parseUrl(String url) {
try {
URL result = new URL(url);
diff --git a/rollbar-java/src/test/java/com/rollbar/notifier/config/ConfigBuilderTest.java b/rollbar-java/src/test/java/com/rollbar/notifier/config/ConfigBuilderTest.java
index b8199ee7..65f586db 100644
--- a/rollbar-java/src/test/java/com/rollbar/notifier/config/ConfigBuilderTest.java
+++ b/rollbar-java/src/test/java/com/rollbar/notifier/config/ConfigBuilderTest.java
@@ -6,7 +6,11 @@
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import com.rollbar.api.payload.Payload;
import com.rollbar.api.payload.data.Client;
import com.rollbar.api.payload.data.Level;
import com.rollbar.api.payload.data.Notifier;
@@ -19,12 +23,19 @@
import com.rollbar.notifier.provider.notifier.NotifierProvider;
import com.rollbar.notifier.sender.BufferedSender;
import com.rollbar.notifier.sender.Sender;
+import com.rollbar.notifier.sender.SyncSender;
+import com.rollbar.notifier.sender.exception.SenderException;
+import com.rollbar.notifier.sender.listener.SenderListener;
import com.rollbar.notifier.transformer.Transformer;
import com.rollbar.notifier.uuid.UuidGenerator;
+import java.net.InetAddress;
import java.net.Proxy;
+import java.net.ServerSocket;
+import java.net.SocketTimeoutException;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
@@ -97,6 +108,8 @@ public void shouldBuildConfigurationWithDefaults() {
assertThat(config.handleUncaughtErrors(), is(true));
assertThat(config.isEnabled(), is(true));
assertThat(config.proxy(), is(nullValue()));
+ assertThat(config.connectTimeoutMillis(), is(SyncSender.DEFAULT_CONNECT_TIMEOUT_MILLIS));
+ assertThat(config.readTimeoutMillis(), is(SyncSender.DEFAULT_READ_TIMEOUT_MILLIS));
assertThat(config.defaultMessageLevel(), equalTo(Level.WARNING));
assertThat(config.defaultThrowableLevel(), equalTo(Level.ERROR));
@@ -204,4 +217,57 @@ public void shouldBuildWithConfig() {
assertThat(config.isEnabled(), is(copy.isEnabled()));
assertThat(config.maximumTelemetryData(), is(maximumTelemetryData));
}
+
+ @Test
+ public void shouldBuildWithTimeoutsAndCopyThem() {
+ Config config = ConfigBuilder.withAccessToken(ACCESS_TOKEN)
+ .connectTimeoutMillis(1234)
+ .readTimeoutMillis(5678)
+ .build();
+
+ Config copy = withConfig(config).build();
+
+ assertThat(config.connectTimeoutMillis(), is(1234));
+ assertThat(config.readTimeoutMillis(), is(5678));
+ assertThat(copy.connectTimeoutMillis(), is(1234));
+ assertThat(copy.readTimeoutMillis(), is(5678));
+ }
+
+ @Test(timeout = 10_000)
+ public void shouldApplyReadTimeoutToTheDefaultSender() throws Exception {
+ // Accepts the connection (via the backlog) but never responds. If the configured timeout did
+ // not reach the sender, it would wait for the 30 s default and this test would time out.
+ String host = "127.0.0.1";
+ try (ServerSocket silentServer = new ServerSocket(0, 1, InetAddress.getByName(host))) {
+ Config config = ConfigBuilder.withAccessToken(ACCESS_TOKEN)
+ .endpoint("http://" + host + ":" + silentServer.getLocalPort() + "/api/1/item/")
+ .readTimeoutMillis(200)
+ .build();
+ try {
+ Sender defaultSender = ((BufferedSender) config.sender()).sender();
+ assertThat(defaultSender, is(instanceOf(SyncSender.class)));
+ SenderListener listener = mock(SenderListener.class);
+ defaultSender.addListener(listener);
+ Payload payload = new Payload("{}");
+
+ defaultSender.send(payload);
+
+ ArgumentCaptor