diff --git a/service/pom.xml b/service/pom.xml
index c134025a6..a8361ed58 100644
--- a/service/pom.xml
+++ b/service/pom.xml
@@ -326,6 +326,10 @@
4.3.0
+
+ io.github.resilience4j
+ resilience4j-bulkhead
+
io.github.resilience4j
resilience4j-circuitbreaker
diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java
index e3e3a3c87..7bd1547aa 100644
--- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java
+++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java
@@ -20,6 +20,7 @@ import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFact
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
+import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
@@ -351,6 +352,9 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private Map retries = Collections.emptyMap();
+ @JsonProperty
+ private Map bulkheads = Collections.emptyMap();
+
@Valid
@NotNull
@JsonProperty
@@ -628,6 +632,10 @@ public class WhisperServerConfiguration extends Configuration {
return retries;
}
+ public Map getBulkheadConfigurations() {
+ return bulkheads;
+ }
+
public RetryConfiguration getGeneralRedisRetryConfiguration() {
return generalRedisRetry;
}
diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java
index a677b862a..e9c5ea15c 100644
--- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java
+++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java
@@ -444,6 +444,9 @@ public class WhisperServerService extends Application
ResilienceUtil.getRetryRegistry().addConfiguration(name, configuration.toRetryConfigBuilder().build()));
+ config.getBulkheadConfigurations().forEach((name, configuration) ->
+ ResilienceUtil.getBulkheadRegistry().addConfiguration(name, configuration.toBulkheadConfig().build()));
+
ResilienceUtil.setGeneralRedisRetryConfiguration(config.getGeneralRedisRetryConfiguration());
ScheduledExecutorService dynamicConfigurationExecutor = ScheduledExecutorServiceBuilder.of(environment, "dynamicConfiguration")
@@ -529,7 +532,8 @@ public class WhisperServerService extends Application T run(final Function super Transaction, T> retryable, final Context context) {
try {
concurrentTransactionCount.increment();
- return circuitBreaker.executeSupplier(() -> database.run(retryable));
+ return bulkhead.executeSupplier(() -> circuitBreaker.executeSupplier(() -> database.run(retryable)));
} catch (final Exception e) {
if (e instanceof final FDBException fdbException) {
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
@@ -70,7 +80,7 @@ public class FaultTolerantDatabase {
concurrentTransactionCount.increment();
- final CompletableFuture runAsyncFuture = circuitBreaker.executeCompletionStage(() -> database.runAsync(retryable)
+ final CompletableFuture runAsyncFuture = bulkhead.executeCompletionStage(() -> circuitBreaker.executeCompletionStage(() -> database.runAsync(retryable)
.whenComplete((_, throwable) -> {
if (throwable != null && ExceptionUtils.unwrap(throwable) instanceof final FDBException fdbException) {
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
@@ -79,7 +89,7 @@ public class FaultTolerantDatabase {
).increment();
}
})
- .thenApply(Function.identity()))
+ .thenApply(Function.identity())))
.toCompletableFuture();
runAsyncFuture.whenComplete((_, _) -> concurrentTransactionCount.decrement());
@@ -90,7 +100,7 @@ public class FaultTolerantDatabase {
public T read(final Function super ReadTransaction, T> retryable, final Context context) {
try {
concurrentTransactionCount.increment();
- return circuitBreaker.executeSupplier(() -> database.read(retryable));
+ return bulkhead.executeSupplier(() -> circuitBreaker.executeSupplier(() -> database.read(retryable)));
} catch (final Exception e) {
if (e instanceof final FDBException fdbException) {
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
@@ -110,7 +120,7 @@ public class FaultTolerantDatabase {
concurrentTransactionCount.increment();
- final CompletableFuture readAsyncFuture = circuitBreaker.executeCompletionStage(() -> database.readAsync(retryable)
+ final CompletableFuture readAsyncFuture = bulkhead.executeCompletionStage(() -> circuitBreaker.executeCompletionStage(() -> database.readAsync(retryable)
.whenComplete((_, throwable) -> {
if (throwable != null && ExceptionUtils.unwrap(throwable) instanceof final FDBException fdbException) {
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
@@ -118,7 +128,7 @@ public class FaultTolerantDatabase {
"code", String.valueOf(fdbException.getCode())
).increment();
}
- }))
+ })))
.toCompletableFuture();
readAsyncFuture.whenComplete((_, _) -> concurrentTransactionCount.decrement());
diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/util/ResilienceUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/util/ResilienceUtil.java
index 88bc8f5ac..7a123612e 100644
--- a/service/src/main/java/org/whispersystems/textsecuregcm/util/ResilienceUtil.java
+++ b/service/src/main/java/org/whispersystems/textsecuregcm/util/ResilienceUtil.java
@@ -5,6 +5,8 @@
package org.whispersystems.textsecuregcm.util;
+import io.github.resilience4j.bulkhead.Bulkhead;
+import io.github.resilience4j.bulkhead.BulkheadRegistry;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.retry.Retry;
@@ -23,6 +25,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
import org.apache.commons.lang3.RandomStringUtils;
+import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
@@ -35,15 +38,23 @@ public class ResilienceUtil {
private static final RetryRegistry RETRY_REGISTRY =
RetryRegistry.of(new RetryConfiguration().toRetryConfigBuilder().build());
+ private static final BulkheadRegistry BULKHEAD_REGISTRY =
+ BulkheadRegistry.of(new BulkheadConfiguration().toBulkheadConfig().build());
+
private static final ConcurrentMap> METER_IDS_BY_BREAKER_NAME = new ConcurrentHashMap<>();
private static final ConcurrentMap> METER_IDS_BY_RETRY_NAME = new ConcurrentHashMap<>();
+ private static final ConcurrentMap> METER_IDS_BY_BULKHEAD_NAME = new ConcurrentHashMap<>();
private static final String BREAKER_CALL_COUNTER_NAME = MetricsUtil.name(ResilienceUtil.class, "breaker", "call");
private static final String BREAKER_STATE_GAUGE_NAME = MetricsUtil.name(ResilienceUtil.class, "breaker", "state");
private static final String RETRY_CALL_COUNTER_NAME = MetricsUtil.name(ResilienceUtil.class, "retry", "call");
+ private static final String BULKHEAD_CALL_COUNTER_NAME = MetricsUtil.name(ResilienceUtil.class, "bulkhead", "call");
+ private static final String BULKHEAD_AVAILABLE_CONCURRENT_CALLS_GAUGE_NAME =
+ MetricsUtil.name(ResilienceUtil.class, "bulkhead", "availableConcurrentCalls");
private static final String BREAKER_NAME_TAG_NAME = "breakerName";
private static final String RETRY_NAME_TAG = "retryName";
+ private static final String BULKHEAD_NAME_TAG = "bulkheadName";
private static final String OUTCOME_TAG_NAME = "outcome";
// Include a random suffix to avoid accidental collisions
@@ -68,6 +79,14 @@ public class ResilienceUtil {
removeMetrics(event.getOldEntry());
addMetrics(event.getNewEntry());
});
+
+ BULKHEAD_REGISTRY.getEventPublisher()
+ .onEntryAdded(event -> addMetrics(event.getAddedEntry()))
+ .onEntryRemoved(event -> removeMetrics(event.getRemovedEntry()))
+ .onEntryReplaced(event -> {
+ removeMetrics(event.getOldEntry());
+ addMetrics(event.getNewEntry());
+ });
}
public static CircuitBreakerRegistry getCircuitBreakerRegistry() {
@@ -84,6 +103,10 @@ public class ResilienceUtil {
.build());
}
+ public static BulkheadRegistry getBulkheadRegistry() {
+ return BULKHEAD_REGISTRY;
+ }
+
/// Generates a standardized name for a `CircuitBreaker` or `Retry`.
///
/// @param clazz the class to which the circuit breaker or retry belongs
@@ -191,6 +214,39 @@ public class ResilienceUtil {
METER_IDS_BY_RETRY_NAME.put(retry.getName(), meterIds);
}
+ private static void addMetrics(final Bulkhead bulkhead) {
+ final Set meterIds = new HashSet<>();
+ final List additionalTags = toTags(bulkhead.getTags());
+
+ meterIds.add(Gauge.builder(BULKHEAD_AVAILABLE_CONCURRENT_CALLS_GAUGE_NAME, bulkhead,
+ b -> b.getMetrics().getAvailableConcurrentCalls())
+ .tag(BULKHEAD_NAME_TAG, bulkhead.getName())
+ .tags(additionalTags)
+ .register(Metrics.globalRegistry)
+ .getId());
+
+ final Counter permittedCallCounter = Counter.builder(BULKHEAD_CALL_COUNTER_NAME)
+ .tag(BULKHEAD_NAME_TAG, bulkhead.getName())
+ .tag(OUTCOME_TAG_NAME, "permitted")
+ .tags(additionalTags)
+ .register(Metrics.globalRegistry);
+
+ final Counter rejectedCallCounter = Counter.builder(BULKHEAD_CALL_COUNTER_NAME)
+ .tag(BULKHEAD_NAME_TAG, bulkhead.getName())
+ .tag(OUTCOME_TAG_NAME, "rejected")
+ .tags(additionalTags)
+ .register(Metrics.globalRegistry);
+
+ bulkhead.getEventPublisher()
+ .onCallPermitted(_ -> permittedCallCounter.increment())
+ .onCallRejected(_ -> rejectedCallCounter.increment());
+
+ meterIds.add(permittedCallCounter.getId());
+ meterIds.add(rejectedCallCounter.getId());
+
+ METER_IDS_BY_BULKHEAD_NAME.put(bulkhead.getName(), meterIds);
+ }
+
private static void removeMetrics(final CircuitBreaker circuitBreaker) {
removeMetrics(METER_IDS_BY_BREAKER_NAME.remove(circuitBreaker.getName()));
}
@@ -199,6 +255,10 @@ public class ResilienceUtil {
removeMetrics(METER_IDS_BY_RETRY_NAME.remove(retry.getName()));
}
+ private static void removeMetrics(final Bulkhead bulkhead) {
+ removeMetrics(METER_IDS_BY_BULKHEAD_NAME.remove(bulkhead.getName()));
+ }
+
private static void removeMetrics(@Nullable final Set meterIds) {
if (meterIds != null) {
meterIds.forEach(Metrics.globalRegistry::remove);
diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java
index 0da91cd14..6acbe9d83 100644
--- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java
+++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java
@@ -134,7 +134,8 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
.map(entry -> {
try {
return new FaultTolerantDatabase(entry.getValue().build(fdb), entry.getKey(),
- configuration.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
+ configuration.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName(),
+ configuration.getFoundationDbMessagesConfiguration().bulkheadConfigurationName());
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java
index 3904ebaed..c91a925b9 100644
--- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java
+++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java
@@ -179,7 +179,8 @@ public record CommandDependencies(
configuration.getFoundationDbMessagesConfiguration().transactionRetryLimit());
return new FaultTolerantDatabase(database, entry.getKey(),
- configuration.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
+ configuration.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName(),
+ configuration.getFoundationDbMessagesConfiguration().bulkheadConfigurationName());
} catch (final IOException e) {
throw new UncheckedIOException("Failed to construct FoundationDB database", e);
}
diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfigurationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfigurationTest.java
index 6e2382142..46855e1e0 100644
--- a/service/src/test/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfigurationTest.java
+++ b/service/src/test/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfigurationTest.java
@@ -30,6 +30,7 @@ class FoundationDbMessagesConfigurationTest {
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
null,
+ null,
null
).isEveryEpochClusterConfigured());
@@ -45,6 +46,7 @@ class FoundationDbMessagesConfigurationTest {
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
null,
+ null,
null
).isEveryEpochClusterConfigured());
}
@@ -63,6 +65,7 @@ class FoundationDbMessagesConfigurationTest {
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
null,
+ null,
null
).isEveryEpochFreeOfDuplicates());
@@ -78,6 +81,7 @@ class FoundationDbMessagesConfigurationTest {
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
null,
+ null,
null
).isEveryEpochFreeOfDuplicates());
}
@@ -96,6 +100,7 @@ class FoundationDbMessagesConfigurationTest {
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
null,
+ null,
null
).isActiveEpochConfigured());
@@ -111,6 +116,7 @@ class FoundationDbMessagesConfigurationTest {
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
null,
+ null,
null
).isActiveEpochConfigured());
}
@@ -129,6 +135,7 @@ class FoundationDbMessagesConfigurationTest {
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
null,
+ null,
null
).isCurrentVersionstampCipherKeyConfigured());
@@ -144,6 +151,7 @@ class FoundationDbMessagesConfigurationTest {
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
null,
+ null,
null
).isCurrentVersionstampCipherKeyConfigured());
}
diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/FoundationDbClusterExtension.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/FoundationDbClusterExtension.java
index 6f7459f06..5a1f244c1 100644
--- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/FoundationDbClusterExtension.java
+++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/FoundationDbClusterExtension.java
@@ -32,7 +32,7 @@ public class FoundationDbClusterExtension implements BeforeAllCallback, Extensio
: new TestcontainersFoundationDbDatabaseLifecycleManager();
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
databaseLifecycleManagers[i] = databaseLifecycleManager;
- databases[i] = new FaultTolerantDatabase(databaseLifecycleManager.getDatabase(), String.format("messages-%d", i), null);
+ databases[i] = new FaultTolerantDatabase(databaseLifecycleManager.getDatabase(), String.format("messages-%d", i), null, null);
}
}
diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabaseTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabaseTest.java
index 70e7ea5d2..301f587e6 100644
--- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabaseTest.java
+++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabaseTest.java
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -12,16 +13,23 @@ import static org.mockito.Mockito.when;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDBException;
+import io.github.resilience4j.bulkhead.BulkheadFullException;
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import java.time.Duration;
+import java.util.concurrent.BrokenBarrierException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CyclicBarrier;
+import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
public class FaultTolerantDatabaseTest {
private Database database;
- private FaultTolerantDatabase ftDatabase;
@BeforeEach
void setUp() {
@@ -41,8 +49,9 @@ public class FaultTolerantDatabaseTest {
ResilienceUtil.getCircuitBreakerRegistry()
.addConfiguration(circuitBreakerConfigurationName, circuitBreakerConfiguration.toCircuitBreakerConfig());
- ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "testCircuitBreaker",
- circuitBreakerConfigurationName);
+ final FaultTolerantDatabase ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "testCircuitBreaker",
+ circuitBreakerConfigurationName,
+ null);
when(database.read(any())).thenThrow(new FDBException("error", 1031));
@@ -63,4 +72,100 @@ public class FaultTolerantDatabaseTest {
assertThrows(CallNotPermittedException.class, () -> ftDatabase.read(t ->
t.get("test_key".getBytes()), FaultTolerantDatabase.Context.TEST));
}
+
+ @Test
+ void bulkhead() throws BrokenBarrierException, InterruptedException {
+ final String bulkheadConfigurationName = "testBulkhead";
+ final BulkheadConfiguration bulkheadConfiguration = new BulkheadConfiguration();
+
+ final int maxConcurrentCalls = 8;
+
+ bulkheadConfiguration.setMaxConcurrentCalls(maxConcurrentCalls);
+ bulkheadConfiguration.setMaxWaitDuration(Duration.ZERO);
+
+ ResilienceUtil.getBulkheadRegistry()
+ .addConfiguration(bulkheadConfigurationName, bulkheadConfiguration.toBulkheadConfig().build());
+
+ final FaultTolerantDatabase ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "testBulkhead",
+ null,
+ bulkheadConfigurationName);
+
+ final CyclicBarrier cyclicBarrier = new CyclicBarrier(maxConcurrentCalls + 1);
+ final CountDownLatch finishReadLatch = new CountDownLatch(1);
+
+ when(database.read(any())).thenAnswer(_ -> {
+ // Wait for all threads to be holding a permit
+ cyclicBarrier.await();
+
+ // Wait for the main thread to attempt and fail a read before exiting and yielding the permit
+ finishReadLatch.await();
+
+ return null;
+ });
+
+ final Thread[] threads = IntStream.range(0, maxConcurrentCalls)
+ .mapToObj(_ -> new Thread(() -> ftDatabase.read(_ -> null, FaultTolerantDatabase.Context.TEST)))
+ .toArray(Thread[]::new);
+
+ for (final Thread thread : threads) {
+ thread.start();
+ }
+
+ cyclicBarrier.await();
+
+ assertThrows(BulkheadFullException.class, () -> ftDatabase.read(_ -> null, FaultTolerantDatabase.Context.TEST));
+
+ finishReadLatch.countDown();
+
+ for (final Thread thread : threads) {
+ thread.join();
+ }
+ }
+
+ @Test
+ void bulkheadAsync() throws BrokenBarrierException, InterruptedException {
+ final String bulkheadConfigurationName = "testBulkhead";
+ final BulkheadConfiguration bulkheadConfiguration = new BulkheadConfiguration();
+
+ final int maxConcurrentCalls = 8;
+
+ bulkheadConfiguration.setMaxConcurrentCalls(maxConcurrentCalls);
+ bulkheadConfiguration.setMaxWaitDuration(Duration.ZERO);
+
+ ResilienceUtil.getBulkheadRegistry()
+ .addConfiguration(bulkheadConfigurationName, bulkheadConfiguration.toBulkheadConfig().build());
+
+ final FaultTolerantDatabase ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "testBulkhead",
+ null,
+ bulkheadConfigurationName);
+
+ final CyclicBarrier cyclicBarrier = new CyclicBarrier(maxConcurrentCalls + 1);
+ final CountDownLatch finishReadLatch = new CountDownLatch(1);
+
+ when(database.readAsync(any())).thenAnswer(_ -> CompletableFuture.runAsync(() -> {
+ try {
+ // Wait for all threads to be holding a permit
+ cyclicBarrier.await();
+
+ // Wait for the main thread to attempt and fail a read before exiting and yielding the permit
+ finishReadLatch.await();
+ } catch (final InterruptedException | BrokenBarrierException e) {
+ throw new RuntimeException(e);
+ }
+ }));
+
+ final CompletableFuture readFutures = CompletableFuture.allOf(IntStream.range(0, 8)
+ .mapToObj(_ -> ftDatabase.readAsync(_ -> null, FaultTolerantDatabase.Context.TEST))
+ .toArray(CompletableFuture[]::new));
+
+ cyclicBarrier.await();
+
+ final CompletionException completionException = assertThrows(CompletionException.class,
+ () -> ftDatabase.readAsync(_ -> null, FaultTolerantDatabase.Context.TEST).join());
+
+ assertInstanceOf(BulkheadFullException.class, completionException.getCause());
+
+ finishReadLatch.countDown();
+ readFutures.join();
+ }
}
diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisherTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisherTest.java
index 0bd4fb6d6..7d40dee0a 100644
--- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisherTest.java
+++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisherTest.java
@@ -81,8 +81,7 @@ class FoundationDbMessagePublisherTest {
@BeforeEach
void setUp() {
database = mock(Database.class);
- ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "-testCircuitBreaker",
- null);
+ ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "-testCircuitBreaker", null, null);
stateTransitions = new ArrayList<>();
final byte[] messageGuidCodecKey = new byte[16];