mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 11:46:53 +00:00
Add gRPC message retrieval
This commit is contained in:
1 parent
329d229ac7
commit
b6317a1b43
12 files changed
+1367
-44
No files matched your search
+260
@@ -0,0 +1,260 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.signal.chat.messages.GetMessagesRequest;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.Sinks;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.test.publisher.TestPublisher;
|
||||
|
||||
@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class MessageDispatcherIntegrationTest {
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.MESSAGES);
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private static ExecutorService sharedExecutorService;
|
||||
private static Scheduler messageDeliveryScheduler;
|
||||
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private ReportMessageManager reportMessageManager;
|
||||
private Account account;
|
||||
private Device device;
|
||||
private ClientReleaseManager clientReleaseManager;
|
||||
private MessageDispatcher messageDispatcher;
|
||||
|
||||
private long serialTimestamp = System.currentTimeMillis();
|
||||
|
||||
@BeforeAll
|
||||
static void beforeAll() {
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), Clock.systemUTC());
|
||||
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7),
|
||||
sharedExecutorService);
|
||||
redisMessageAvailabilityManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
sharedExecutorService, sharedExecutorService);
|
||||
reportMessageManager = mock(ReportMessageManager.class);
|
||||
account = mock(Account.class);
|
||||
device = mock(Device.class);
|
||||
clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID());
|
||||
when(device.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
|
||||
redisMessageAvailabilityManager.start();
|
||||
|
||||
messageDispatcher = new MessageDispatcher(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, reportMessageManager,
|
||||
sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
clientReleaseManager);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
redisMessageAvailabilityManager.stop();
|
||||
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void afterAll() throws InterruptedException {
|
||||
sharedExecutorService.shutdown();
|
||||
final Mono<Void> schedulerShutdownMono = messageDeliveryScheduler.disposeGracefully();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
sharedExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
schedulerShutdownMono.timeout(Duration.ofSeconds(2))
|
||||
.onErrorResume(TimeoutException.class, _ -> Mono.fromRunnable(() -> messageDeliveryScheduler.dispose()))
|
||||
.block();
|
||||
}
|
||||
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"207, 173",
|
||||
"323, 0",
|
||||
"0, 221",
|
||||
})
|
||||
void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount);
|
||||
final Sinks.Many<UUID> acks = Sinks.many().unicast().onBackpressureBuffer();
|
||||
final List<Envelope> receivedMessages = messageDispatcher
|
||||
.getMessages(true, null, account, device, acks.asFlux())
|
||||
.takeWhile(response -> !response.hasQueueEmpty())
|
||||
.doOnNext(response -> acks.tryEmitNext(UUIDUtil.fromByteString(response.getEnvelope().getServerGuid())))
|
||||
.map(GetMessagesResponse::getEnvelope)
|
||||
.collectList()
|
||||
.block(Duration.ofSeconds(15));
|
||||
assertEquals(expectedMessages, receivedMessages);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessStoredMessagesMultipleSegments() {
|
||||
final int persistedMessageCount = 77;
|
||||
final int cachedMessageCount = 104;
|
||||
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount);
|
||||
final AtomicInteger remainingMessages = new AtomicInteger(persistedMessageCount + cachedMessageCount);
|
||||
final int additionalMessageCount = 67;
|
||||
|
||||
final Sinks.Many<UUID> acks = Sinks.many().unicast().onBackpressureBuffer();
|
||||
final List<Envelope> receivedMessages = messageDispatcher
|
||||
.getMessages(true, null, account, device, acks.asFlux())
|
||||
.filter(response -> !response.hasQueueEmpty())
|
||||
.map(GetMessagesResponse::getEnvelope)
|
||||
.doOnNext(envelope -> {
|
||||
acks.tryEmitNext(UUIDUtil.fromByteString(envelope.getServerGuid()));
|
||||
if (remainingMessages.addAndGet(-1) == 60) {
|
||||
sharedExecutorService
|
||||
.submit(() -> expectedMessages.addAll(fillRandomMessages(0, additionalMessageCount)));
|
||||
}
|
||||
})
|
||||
.take(persistedMessageCount + cachedMessageCount + additionalMessageCount)
|
||||
.collectList()
|
||||
.block(Duration.ofSeconds(15));
|
||||
assertEquals(expectedMessages.size(), receivedMessages.size());
|
||||
assertEquals(expectedMessages, receivedMessages);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessStoredMessagesClientClosed() {
|
||||
final int persistedMessageCount = 207;
|
||||
final int cachedMessageCount = 173;
|
||||
|
||||
final Set<Envelope> receivedMessages = Collections.newSetFromMap(new ConcurrentHashMap<Envelope, Boolean>());
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount);
|
||||
final TestPublisher<UUID> acks = TestPublisher.create();
|
||||
final Exception thrown = assertThrows(Exception.class, () -> messageDispatcher
|
||||
.getMessages(true, null, account, device, acks.flux())
|
||||
.doOnNext(response -> {
|
||||
assertTrue(redisMessageAvailabilityManager.isLocallyPresent(account.getIdentifier(IdentityType.ACI),
|
||||
device.getId()));
|
||||
receivedMessages.add(response.getEnvelope());
|
||||
acks.error(new IOException("test exception"));
|
||||
})
|
||||
.collectList()
|
||||
.block());
|
||||
assertInstanceOf(IOException.class, thrown.getCause());
|
||||
assertTrue(expectedMessages.containsAll(receivedMessages));
|
||||
assertFalse(redisMessageAvailabilityManager.isLocallyPresent(account.getIdentifier(IdentityType.ACI), device.getId()));
|
||||
}
|
||||
|
||||
private List<Envelope> fillRandomMessages(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
|
||||
final List<Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
for (int i = 0; i < persistedMessageCount; i++) {
|
||||
final Envelope envelope = generateRandomMessage(UUID.randomUUID());
|
||||
expectedMessages.add(envelope);
|
||||
}
|
||||
messagesDynamoDb.store(expectedMessages, account.getIdentifier(IdentityType.ACI), device);
|
||||
|
||||
for (int i = 0; i < cachedMessageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final Envelope envelope = generateRandomMessage(messageGuid);
|
||||
|
||||
messagesCache.insert(messageGuid, account.getIdentifier(IdentityType.ACI), device.getId(), envelope).join();
|
||||
expectedMessages.add(envelope);
|
||||
}
|
||||
return expectedMessages;
|
||||
}
|
||||
|
||||
private Envelope generateRandomMessage(final UUID messageGuid) {
|
||||
final long timestamp = serialTimestamp++;
|
||||
|
||||
return Envelope.newBuilder()
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(timestamp)
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(new AciServiceIdentifier(messageGuid).toCompactByteString())
|
||||
.setDestinationServiceId(new AciServiceIdentifier(UUID.randomUUID()).toCompactByteString())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ConflictingMessageConsumerException;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.StepVerifier;
|
||||
import reactor.test.publisher.TestPublisher;
|
||||
|
||||
class MessageDispatcherTest {
|
||||
|
||||
private static final GetMessagesResponse QUEUE_EMPTY =
|
||||
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
|
||||
private static final GetMessagesResponse REQUIRES_REAUTH = GetMessagesResponse.newBuilder()
|
||||
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
|
||||
.setReauthenticationRequired(Empty.getDefaultInstance())
|
||||
.build())
|
||||
.build();
|
||||
private static final GetMessagesResponse CONFLICTING_STREAM = GetMessagesResponse.newBuilder()
|
||||
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
|
||||
.setConflictingStream(Empty.getDefaultInstance())
|
||||
.build())
|
||||
.build();
|
||||
|
||||
private static final UUID ACI = UUID.randomUUID();
|
||||
private static final byte DEVICE_ID = 2;
|
||||
private static final int SOURCE_DEVICE_ID = 1;
|
||||
private static final String TEST_UA = "test-user-agent";
|
||||
|
||||
private Account account;
|
||||
private Device device;
|
||||
private MessagesManager messagesManager;
|
||||
private ReceiptSender receiptSender;
|
||||
private PushNotificationManager pushNotificationManager;
|
||||
private MessageDispatcher dispatcher;
|
||||
private DisconnectionRequestManager disconnectionRequestManager;
|
||||
private PushNotificationScheduler pushNotificationScheduler;
|
||||
private MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACI);
|
||||
when(account.getUuid()).thenReturn(ACI);
|
||||
|
||||
device = mock(Device.class);
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
receiptSender = mock(ReceiptSender.class);
|
||||
pushNotificationManager = mock(PushNotificationManager.class);
|
||||
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
|
||||
pushNotificationScheduler = mock(PushNotificationScheduler.class);
|
||||
messageDeliveryLoopMonitor = mock(MessageDeliveryLoopMonitor.class);
|
||||
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
when(device.isPrimary()).thenReturn(true);
|
||||
|
||||
dispatcher = new MessageDispatcher(
|
||||
receiptSender,
|
||||
messagesManager,
|
||||
new MessageMetrics(),
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
messageDeliveryLoopMonitor,
|
||||
disconnectionRequestManager,
|
||||
mock(ClientReleaseManager.class));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void drainSingleMessage(final boolean mayHaveMoreMessages) {
|
||||
final ServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final long timestamp = 17;
|
||||
|
||||
final Envelope message = createMessage(sourceServiceId, ACI, timestamp, "hello");
|
||||
mockMessages(message);
|
||||
|
||||
final Flux<GetMessagesResponse> responses =
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, Flux.never());
|
||||
final Envelope expectedEnvelope = message.toBuilder().clearEphemeral().build();
|
||||
|
||||
when(messagesManager.mayHaveMessages(any(), any())).thenReturn(
|
||||
CompletableFuture.completedFuture(mayHaveMoreMessages));
|
||||
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).build())
|
||||
.then(() -> verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), any()))
|
||||
.thenCancel()
|
||||
.verify(Duration.ofSeconds(5));
|
||||
|
||||
verify(messageDeliveryLoopMonitor, times(1))
|
||||
.recordDeliveryAttempt(ACI, DEVICE_ID, UUIDUtil.fromByteString(message.getServerGuid()), TEST_UA, "grpc");
|
||||
verify(disconnectionRequestManager).removeListener(eq(ACI), eq(DEVICE_ID), any());
|
||||
verify(pushNotificationManager).handleMessagesRetrieved(account, device, TEST_UA);
|
||||
verify(messagesManager).mayHaveMessages(ACI, device);
|
||||
verify(pushNotificationScheduler, times(mayHaveMoreMessages ? 1 : 0))
|
||||
.scheduleDelayedNotification(account, device, MessageDispatcher.CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
|
||||
verifyNoInteractions(receiptSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ackMessages() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.toList();
|
||||
final List<UUID> guids = messages.stream().map(Envelope::getServerGuid).map(UUIDUtil::fromByteString).toList();
|
||||
final List<Long> timestamps = messages.stream().map(Envelope::getServerTimestamp).toList();
|
||||
final List<GetMessagesResponse> expectedMessages = messages.stream()
|
||||
.map(e -> e.toBuilder().clearEphemeral().build())
|
||||
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).build())
|
||||
.toList();
|
||||
|
||||
final MessageStream messageStream = mockMessages(messages);
|
||||
|
||||
final TestPublisher<UUID> acks = TestPublisher.create();
|
||||
|
||||
final Flux<GetMessagesResponse> responses =
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
|
||||
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Sending an ack should allow another message to come back
|
||||
.then(() -> acks.next(guids.get(0)))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES))
|
||||
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(0), timestamps.get(0)))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Send another one
|
||||
.then(() -> acks.next(guids.get(1)))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES + 1))
|
||||
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(1), timestamps.get(1)))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
.thenCancel()
|
||||
.verify(Duration.ofSeconds(5));
|
||||
|
||||
verify(receiptSender, times(1))
|
||||
.sendReceipt(new AciServiceIdentifier(ACI), DEVICE_ID, sourceServiceId, 0);
|
||||
verify(receiptSender, times(1))
|
||||
.sendReceipt(new AciServiceIdentifier(ACI), DEVICE_ID, sourceServiceId, 1);
|
||||
verifyNoMoreInteractions(receiptSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxOutstandingAllowsGaps() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
final int totalMessages = MessageDispatcher.MAX_UNACKED_MESSAGES * 2;
|
||||
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, totalMessages)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.toList();
|
||||
final List<UUID> ackRequests = messages.stream()
|
||||
.map(Envelope::getServerGuid).map(UUIDUtil::fromByteString)
|
||||
.toList();
|
||||
final List<GetMessagesResponse> expectedMessages = messages.stream()
|
||||
.map(e -> e.toBuilder().clearEphemeral().build())
|
||||
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).build())
|
||||
.toList();
|
||||
|
||||
mockMessages(messages);
|
||||
final TestPublisher<UUID> acks = TestPublisher.create();
|
||||
|
||||
final Flux<GetMessagesResponse> responses =
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
|
||||
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> {
|
||||
for (int i = 0; i < MessageDispatcher.MAX_UNACKED_MESSAGES; i++) {
|
||||
if (i != 2) {
|
||||
acks.next(ackRequests.get(i));
|
||||
}
|
||||
}
|
||||
})
|
||||
.expectNext(expectedMessages.subList(MessageDispatcher.MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> acks.next(ackRequests.get(2)))
|
||||
.expectNext(expectedMessages.get(totalMessages - 1))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> {
|
||||
for (int i = MessageDispatcher.MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
|
||||
acks.next(ackRequests.get(i));
|
||||
}
|
||||
})
|
||||
.expectNext(QUEUE_EMPTY)
|
||||
.thenCancel()
|
||||
.verify(Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateAckIgnored() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.toList();
|
||||
|
||||
final List<UUID> ackRequests = messages.stream()
|
||||
.map(Envelope::getServerGuid).map(UUIDUtil::fromByteString)
|
||||
.toList();
|
||||
final TestPublisher<UUID> acks = TestPublisher.create();
|
||||
|
||||
mockMessages(messages);
|
||||
|
||||
StepVerifier
|
||||
.create(dispatcher.getMessages(true, TEST_UA, account, device, acks.flux()))
|
||||
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Ack a message, we should then get a new message
|
||||
.then(() -> acks.next(ackRequests.get(0)))
|
||||
.expectNextCount(1)
|
||||
|
||||
// Ack the same message again, there should be no additional message (or error)
|
||||
.then(() -> acks.next(ackRequests.get(0)))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Ack a different message, we should get a message back
|
||||
.then(() -> acks.next(ackRequests.get(1)))
|
||||
.expectNextCount(1)
|
||||
.thenCancel()
|
||||
.verify(Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void disconnectionRequest() {
|
||||
final ServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final long timestamp = 17;
|
||||
|
||||
final Envelope message = createMessage(sourceServiceId, ACI, timestamp, "hello");
|
||||
final Envelope expectedEnvelope = message.toBuilder().clearEphemeral().build();
|
||||
mockMessages(message);
|
||||
|
||||
final Flux<GetMessagesResponse> responses =
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, Flux.never());
|
||||
ArgumentCaptor<DisconnectionRequestListener> listener = ArgumentCaptor.forClass(DisconnectionRequestListener.class);
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).build())
|
||||
.then(() -> {
|
||||
verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), listener.capture());
|
||||
listener.getValue().handleDisconnectionRequest();
|
||||
})
|
||||
.expectNext(REQUIRES_REAUTH)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void conflictingConsumer() {
|
||||
mockMessages(Flux.error(new ConflictingMessageConsumerException()));
|
||||
final Flux<GetMessagesResponse> responses =
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, Flux.never());
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(CONFLICTING_STREAM)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void conflictingConsumerWhileWaitingForAcks() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<MessageStreamEntry.Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.map(MessageStreamEntry.Envelope::new)
|
||||
.toList();
|
||||
|
||||
final TestPublisher<MessageStreamEntry> source = TestPublisher.create();
|
||||
mockMessages(source.flux());
|
||||
|
||||
StepVerifier
|
||||
.create(dispatcher.getMessages(true, TEST_UA, account, device, Flux.never()))
|
||||
.then(() -> messages.forEach(source::next))
|
||||
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
// The error should make it to us immediately even though there are max-unacked messages outstanding
|
||||
.then(() -> source.error(new ConflictingMessageConsumerException()))
|
||||
.expectNext(CONFLICTING_STREAM)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
/// Set envelopes to return when a message stream is created. A [MessageStreamEntry.QueueEmpty] will be emitted after
|
||||
/// the provided messages
|
||||
private MessageStream mockMessages(final List<MessageProtos.Envelope> messages) {
|
||||
return mockMessages(messages.toArray(MessageProtos.Envelope[]::new));
|
||||
}
|
||||
|
||||
/// Set envelopes to return when a message stream is created. A [MessageStreamEntry.QueueEmpty] will be emitted after
|
||||
/// the provided messages
|
||||
private MessageStream mockMessages(final MessageProtos.Envelope... messages) {
|
||||
return mockMessages(Flux.concat(
|
||||
Flux.fromStream(Arrays.stream(messages).map(MessageStreamEntry.Envelope::new)),
|
||||
Flux.just(new MessageStreamEntry.QueueEmpty())));
|
||||
}
|
||||
|
||||
private MessageStream mockMessages(final Flux<MessageStreamEntry> messages) {
|
||||
final MessageStream mockMessageStream = mock(MessageStream.class);
|
||||
when(mockMessageStream.getMessages()).thenReturn(JdkFlowAdapter.publisherToFlowPublisher(messages));
|
||||
when(mockMessageStream.acknowledgeMessage(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(messagesManager.getMessages(ACI, device)).thenReturn(mockMessageStream);
|
||||
return mockMessageStream;
|
||||
}
|
||||
|
||||
private static Envelope createMessage(final ServiceIdentifier sourceId,
|
||||
final UUID destinationUuid,
|
||||
final long clientTimestamp,
|
||||
final String content) {
|
||||
|
||||
final UUID serverGuid = UUID.randomUUID();
|
||||
return Envelope.newBuilder()
|
||||
.setServerGuid(UUIDUtil.toByteString(serverGuid))
|
||||
.setType(Envelope.Type.CIPHERTEXT)
|
||||
.setClientTimestamp(clientTimestamp)
|
||||
.setServerTimestamp(0)
|
||||
.setSourceServiceId(sourceId.toCompactByteString())
|
||||
.setSourceDevice(SOURCE_DEVICE_ID)
|
||||
.setDestinationServiceId(new AciServiceIdentifier(destinationUuid).toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(content.getBytes(StandardCharsets.UTF_8)))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+118
-16
@@ -6,11 +6,15 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -20,7 +24,11 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.Channel;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusException;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.grpc.stub.BlockingClientCall;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
@@ -29,18 +37,30 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.messages.ChallengeRequired;
|
||||
import org.signal.chat.messages.GetMessagesRequest;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.signal.chat.messages.IndividualRecipientMessageBundle;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.chat.messages.MessagesGrpc;
|
||||
import org.signal.chat.messages.MismatchedDevices;
|
||||
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
|
||||
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.chat.messages.SendSyncMessageRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
@@ -62,11 +82,16 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.publisher.TestPublisher;
|
||||
|
||||
class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, MessagesGrpc.MessagesBlockingStub> {
|
||||
class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, MessagesGrpc.MessagesBlockingV2Stub> {
|
||||
|
||||
@Mock
|
||||
private AccountsManager accountsManager;
|
||||
@@ -98,6 +123,9 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
@Mock
|
||||
private Device secondLinkedDevice;
|
||||
|
||||
@Mock
|
||||
private MessageDispatcher messageDispatcher;
|
||||
|
||||
private static final int AUTHENTICATED_REGISTRATION_ID = 7;
|
||||
|
||||
private static final byte LINKED_DEVICE_ID = AUTHENTICATED_DEVICE_ID + 1;
|
||||
@@ -108,6 +136,11 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.now());
|
||||
|
||||
@Override
|
||||
protected MessagesGrpc.MessagesBlockingV2Stub createStub(final Channel channel) {
|
||||
return MessagesGrpc.newBlockingV2Stub(channel);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MessagesGrpcService createServiceBeforeEachTest() {
|
||||
return new MessagesGrpcService(accountsManager,
|
||||
@@ -115,11 +148,14 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
messageSender,
|
||||
messageByteLimitEstimator,
|
||||
spamChecker,
|
||||
messageDispatcher,
|
||||
CLOCK);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
CLOCK.pin(Instant.now());
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
|
||||
|
||||
when(rateLimiters.getInboundMessageBytes()).thenReturn(rateLimiter);
|
||||
@@ -130,6 +166,8 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
|
||||
when(authenticatedDevice.getId()).thenReturn(AUTHENTICATED_DEVICE_ID);
|
||||
when(authenticatedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(AUTHENTICATED_REGISTRATION_ID);
|
||||
when(authenticatedDevice.getLastSeen()).thenReturn(CLOCK.instant().toEpochMilli());
|
||||
when(authenticatedDevice.isPrimary()).thenReturn(true);
|
||||
|
||||
when(linkedDevice.getId()).thenReturn(LINKED_DEVICE_ID);
|
||||
when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(LINKED_DEVICE_REGISTRATION_ID);
|
||||
@@ -144,9 +182,12 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
when(authenticatedAccount.getDevice(LINKED_DEVICE_ID)).thenReturn(Optional.of(linkedDevice));
|
||||
when(authenticatedAccount.getDevice(SECOND_LINKED_DEVICE_ID)).thenReturn(Optional.of(secondLinkedDevice));
|
||||
when(authenticatedAccount.getDevices()).thenReturn(List.of(authenticatedDevice, linkedDevice, secondLinkedDevice));
|
||||
when(authenticatedAccount.getPrimaryDevice()).thenReturn(authenticatedDevice);
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI)))
|
||||
.thenReturn(Optional.of(authenticatedAccount));
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(authenticatedAccount));
|
||||
}
|
||||
|
||||
@Nested
|
||||
@@ -157,7 +198,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean includeReportSpamToken)
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
|
||||
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final int registrationId = 7;
|
||||
@@ -252,7 +293,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
.build());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub()
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub()
|
||||
.sendMessage(generateRequest(serviceIdentifier, false, true, messages)));
|
||||
|
||||
verifyNoInteractions(messageSender);
|
||||
@@ -260,7 +301,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
|
||||
@Test
|
||||
void mismatchedDevices()
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
|
||||
final byte missingDeviceId = Device.PRIMARY_ID;
|
||||
final byte extraDeviceId = missingDeviceId + 1;
|
||||
final byte staleDeviceId = extraDeviceId + 1;
|
||||
@@ -298,7 +339,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
|
||||
@Test
|
||||
void destinationNotFound()
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
|
||||
@@ -343,7 +384,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
.build());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertRateLimitExceeded(retryDuration,
|
||||
assertRateLimitExceeded(retryDuration,
|
||||
() -> authenticatedServiceStub().sendMessage(
|
||||
generateRequest(serviceIdentifier, false, true, messages)));
|
||||
|
||||
@@ -374,7 +415,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
|
||||
assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> authenticatedServiceStub().sendMessage(
|
||||
generateRequest(serviceIdentifier, false, true, messages)));
|
||||
}
|
||||
@@ -407,7 +448,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
Optional.empty()));
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
|
||||
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED, () -> authenticatedServiceStub()
|
||||
assertStatusException(Status.RESOURCE_EXHAUSTED, () -> authenticatedServiceStub()
|
||||
.sendMessage(generateRequest(serviceIdentifier, false, true, messages)));
|
||||
|
||||
verify(spamChecker).checkForIndividualRecipientSpamGrpc(MessageType.INDIVIDUAL_IDENTIFIED_SENDER,
|
||||
@@ -420,7 +461,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
|
||||
@Test
|
||||
void spamWithResponse()
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final int registrationId = 7;
|
||||
|
||||
@@ -489,7 +530,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
|
||||
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
|
||||
assertStatusException(Status.UNAVAILABLE,
|
||||
() -> authenticatedServiceStub().sendMessage(generateRequest(serviceIdentifier, false, false, messages)));
|
||||
}
|
||||
|
||||
@@ -520,7 +561,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
void sendMessage(@CartesianTest.Enum(mode = CartesianTest.Enum.Mode.EXCLUDE, names = {"UNSPECIFIED", "UNRECOGNIZED", "UNIDENTIFIED_SENDER"}) final SendMessageType messageType,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean includeReportSpamToken)
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
|
||||
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(AUTHENTICATED_ACI);
|
||||
final byte[] payload = TestRandomUtil.nextBytes(128);
|
||||
@@ -604,7 +645,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
|
||||
@Test
|
||||
void mismatchedDevices()
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
|
||||
final byte missingDeviceId = Device.PRIMARY_ID;
|
||||
final byte extraDeviceId = missingDeviceId + 1;
|
||||
final byte staleDeviceId = extraDeviceId + 1;
|
||||
@@ -650,7 +691,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
.build());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertRateLimitExceeded(retryDuration, () ->
|
||||
assertRateLimitExceeded(retryDuration, () ->
|
||||
authenticatedServiceStub().sendSyncMessage(generateRequest(true, messages)));
|
||||
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
@@ -680,7 +721,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub()
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub()
|
||||
.sendSyncMessage( generateRequest( true, messages)));
|
||||
}
|
||||
|
||||
@@ -707,7 +748,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
|
||||
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
|
||||
assertStatusException(Status.UNAVAILABLE,
|
||||
() -> authenticatedServiceStub().sendSyncMessage(generateRequest(false, messages)));
|
||||
}
|
||||
|
||||
@@ -727,4 +768,65 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
|
||||
return requestBuilder.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Timeout(value = 1, unit = TimeUnit.MINUTES, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
@Nested
|
||||
class Retrieval {
|
||||
|
||||
@Test
|
||||
public void invalidFirstRequest() throws InterruptedException, StatusException {
|
||||
final BlockingClientCall<GetMessagesRequest, GetMessagesResponse> blockingCall = authenticatedServiceStub().getMessages();
|
||||
blockingCall.write(GetMessagesRequest.newBuilder().setServerGuidAck(UUIDUtil.toByteString(UUID.randomUUID())).build());
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> blockingCall.read());
|
||||
}
|
||||
|
||||
|
||||
static Stream<Arguments> invalidAckMessages() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Includes initial stream configuration", GetMessagesRequest.newBuilder()
|
||||
.setOptions(GetMessagesRequest.GetMessageOptions.getDefaultInstance())
|
||||
.build()),
|
||||
Arguments.argumentSet("Missing ack guid", GetMessagesRequest.getDefaultInstance())
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void invalidAckMessages(final GetMessagesRequest request)
|
||||
throws StatusException, InterruptedException, TimeoutException {
|
||||
doAnswer(invocation -> {
|
||||
Flux<UUID> ackArg = invocation.getArgument(4);
|
||||
// use mapNotNull instead of `then` because there is an interaction between the blocking client and
|
||||
// simple-grpc where losing the per-request demand (that is, requesting an item on every delivery) prevents
|
||||
// the blocking write channel from accepting writes.
|
||||
return ackArg.mapNotNull(_ -> null).cast(GetMessagesResponse.class);
|
||||
}).when(messageDispatcher).getMessages(anyBoolean(), any(), any(), any(), any());
|
||||
|
||||
final BlockingClientCall<GetMessagesRequest, GetMessagesResponse> blockingCall = authenticatedServiceStub().getMessages();
|
||||
final CompletableFuture<StatusException> reader = CompletableFuture.supplyAsync(() -> assertThrows(StatusException.class, () -> blockingCall.read()));
|
||||
|
||||
blockingCall.write(GetMessagesRequest.newBuilder().setOptions(GetMessagesRequest.GetMessageOptions.getDefaultInstance()).build());
|
||||
blockingCall.write(request);
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), reader.join().getStatus().getCode());
|
||||
}
|
||||
}
|
||||
|
||||
private static Executable convertStatusException(final Executable serviceCall) {
|
||||
return () -> {
|
||||
try {
|
||||
serviceCall.execute();
|
||||
} catch (final StatusException e) {
|
||||
throw new StatusRuntimeException(e.getStatus(), e.getTrailers());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static StatusRuntimeException assertStatusException(final Status expected, final Executable serviceCall) {
|
||||
return GrpcTestUtils.assertStatusException(expected, convertStatusException(serviceCall));
|
||||
}
|
||||
|
||||
private static void assertRateLimitExceeded(final Duration expectedRetryAfter, final Executable serviceCall) {
|
||||
GrpcTestUtils.assertRateLimitExceeded(expectedRetryAfter, convertStatusException(serviceCall));
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -273,7 +273,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
when(successResponse.getStatus()).thenReturn(200);
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any()))
|
||||
.thenAnswer(_ -> {
|
||||
if (remainingMessages.addAndGet(-1) == 60) {
|
||||
if (remainingMessages.decrementAndGet() == 60) {
|
||||
sharedExecutorService.submit(() -> {
|
||||
for (int i = 0; i < additionalMessageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
|
||||
Reference in new issue
Block a user