mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 11:46:53 +00:00
Implement FoundationDbMessageStream#acknowledgeMessage
This commit is contained in:
1 parent
68a5e4e8ee
commit
defbc1c853
7 files changed
+414
-101
No files matched your search
+15
-21
@@ -23,7 +23,9 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
@@ -34,7 +36,6 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
/// NOTE: most of the happy-path test cases are already covered in {@link FoundationDbMessageStoreTest}, this test
|
||||
@@ -42,7 +43,6 @@ import reactor.test.StepVerifier;
|
||||
class FoundationDbMessagePublisherTest {
|
||||
|
||||
private Database database;
|
||||
private MessageGuidCodec messageGuidCodec;
|
||||
private List<FoundationDbMessagePublisher.State> stateTransitions;
|
||||
|
||||
private static final AciServiceIdentifier SERVICE_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
@@ -53,6 +53,8 @@ class FoundationDbMessagePublisherTest {
|
||||
private static final byte[] MESSAGES_AVAILABLE_WATCH_KEY =
|
||||
FoundationDbMessageStore.getMessagesAvailableWatchKey(SERVICE_IDENTIFIER);
|
||||
|
||||
private static final Supplier<Consumer<Transaction>> NOOP_ON_PAGE_FETCH = () -> _ -> {};
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
database = mock(Database.class);
|
||||
@@ -60,10 +62,6 @@ class FoundationDbMessagePublisherTest {
|
||||
|
||||
final byte[] messageGuidCodecKey = new byte[16];
|
||||
new SecureRandom().nextBytes(messageGuidCodecKey);
|
||||
|
||||
messageGuidCodec = new MessageGuidCodec(SERVICE_IDENTIFIER.uuid(),
|
||||
Device.PRIMARY_ID,
|
||||
new VersionstampUUIDCipher(0, messageGuidCodecKey));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -99,10 +97,10 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
database,
|
||||
messageGuidCodec,
|
||||
2, // With 3 messages and batch size set to 2, we'll need to grab 2 batches.
|
||||
null,
|
||||
(_, newState) -> stateTransitions.add(newState)
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
);
|
||||
|
||||
StepVerifier.create(finitePublisher.getMessages())
|
||||
@@ -125,7 +123,7 @@ class FoundationDbMessagePublisherTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "resource"})
|
||||
void infinitePublisher() throws InvalidProtocolBufferException {
|
||||
void infinitePublisher() {
|
||||
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message3 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
@@ -170,7 +168,6 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
database,
|
||||
messageGuidCodec,
|
||||
2,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(oldState, newState) -> {
|
||||
@@ -187,7 +184,8 @@ class FoundationDbMessagePublisherTest {
|
||||
watchFuture2.complete(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
);
|
||||
|
||||
StepVerifier.create(infinitePublisher.getMessages())
|
||||
@@ -252,7 +250,6 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
database,
|
||||
messageGuidCodec,
|
||||
2,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(oldState, newState) -> {
|
||||
@@ -267,7 +264,8 @@ class FoundationDbMessagePublisherTest {
|
||||
.count() == 1) {
|
||||
watchFuture1.complete(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
);
|
||||
|
||||
StepVerifier.create(infinitePublisher.getMessages())
|
||||
@@ -298,9 +296,9 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterThan(SUBSPACE_RANGE.end),
|
||||
database,
|
||||
messageGuidCodec,
|
||||
100,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY);
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
() -> _ -> {});
|
||||
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final Transaction transaction = mock(Transaction.class);
|
||||
final KeyValue keyValue = mockKeyValue((byte) 5, message);
|
||||
@@ -326,12 +324,8 @@ class FoundationDbMessagePublisherTest {
|
||||
verify(watchFuture).cancel(true);
|
||||
}
|
||||
|
||||
private MessageStreamEntry.Envelope getExpectedMessageStreamEntry(final KeyValue keyValue)
|
||||
throws InvalidProtocolBufferException {
|
||||
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(keyValue.getValue())
|
||||
.toBuilder()
|
||||
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()))))
|
||||
.build());
|
||||
private FoundationDbMessageStreamEntry.Message getExpectedMessageStreamEntry(final KeyValue keyValue) {
|
||||
return new FoundationDbMessageStreamEntry.Message(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()), keyValue.getValue());
|
||||
}
|
||||
|
||||
private static KeyValue mockKeyValue(final byte key, final MessageProtos.Envelope message) {
|
||||
|
||||
+87
-4
@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
@@ -31,9 +32,11 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -56,8 +59,10 @@ import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.test.StepVerifier;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class FoundationDbMessageStoreTest {
|
||||
@@ -404,7 +409,8 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device, batchSize);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device, batchSize,
|
||||
Util.NOOP);
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
@@ -550,6 +556,82 @@ class FoundationDbMessageStoreTest {
|
||||
.verifyTimeout(Duration.ofSeconds(3));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void acknowledgeMessages(final int numMessages, final Set<Integer> unacknowledgedMessages)
|
||||
throws InterruptedException {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
|
||||
final List<Versionstamp> versionstamps = IntStream.range(0, numMessages)
|
||||
.mapToObj(
|
||||
_ -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join()
|
||||
.get(Device.PRIMARY_ID)
|
||||
.versionstamp()
|
||||
.orElseThrow())
|
||||
.toList();
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
latch::countDown);
|
||||
final List<CompletableFuture<Void>> acknowledgeFutures = new ArrayList<>();
|
||||
final AtomicInteger messageCounter = new AtomicInteger(0);
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.doOnNext(entry -> {
|
||||
final int messageNum = messageCounter.getAndIncrement();
|
||||
if (!unacknowledgedMessages.contains(messageNum) && entry instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) {
|
||||
acknowledgeFutures.add(messageStream.acknowledgeMessage(message));
|
||||
}
|
||||
}))
|
||||
.expectNextCount(numMessages)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofSeconds(1));
|
||||
|
||||
CompletableFuture.allOf(acknowledgeFutures.toArray(CompletableFuture[]::new)).join();
|
||||
final List<Versionstamp> expectedDeletedVersionstamps = IntStream.range(0, numMessages)
|
||||
.filter(i -> !unacknowledgedMessages.contains(i))
|
||||
.mapToObj(versionstamps::get)
|
||||
.toList();
|
||||
// Clean up can take a bit after subscription cancellation, so wait for the countdown latch to complete
|
||||
if (!expectedDeletedVersionstamps.isEmpty()) {
|
||||
assertTrue(latch.await(1, TimeUnit.SECONDS));
|
||||
expectedDeletedVersionstamps.forEach(
|
||||
versionstamp -> assertNull(getMessageByVersionstamp(aci, Device.PRIMARY_ID, versionstamp)));
|
||||
}
|
||||
|
||||
// Expect that the unacknowledged messages are re-delivered when we connect again.
|
||||
final List<Versionstamp> expectedRedeliveredVersionstamps = IntStream.range(0, numMessages)
|
||||
.filter(unacknowledgedMessages::contains)
|
||||
.mapToObj(versionstamps::get)
|
||||
.toList();
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
.expectNextCount(expectedRedeliveredVersionstamps.size())
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofSeconds(1));
|
||||
|
||||
assertEquals(expectedRedeliveredVersionstamps, retrievedEntries.stream()
|
||||
.filter(e -> e instanceof MessageStreamEntry.Envelope)
|
||||
.map(e -> messageGuidCodec.decodeMessageGuid(UUIDUtil.fromByteString(((MessageStreamEntry.Envelope) e).message().getServerGuidBinary())))
|
||||
.toList());
|
||||
|
||||
}
|
||||
|
||||
static Stream<Arguments> acknowledgeMessages() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Single acknowledged message", 1, Collections.emptySet()),
|
||||
Arguments.argumentSet("Multiple messages, all acknowledged", 16, Collections.emptySet()),
|
||||
Arguments.argumentSet("Multiple messages, single unacknowledged", 16, Set.of(3)),
|
||||
Arguments.argumentSet("Multiple messages with range-breakers", 16, Set.of(3, 7, 8, 9, 12))
|
||||
);
|
||||
}
|
||||
|
||||
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
|
||||
return generateRandomMessage(ephemeral, 16);
|
||||
}
|
||||
@@ -561,10 +643,11 @@ class FoundationDbMessageStoreTest {
|
||||
.build();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci, final byte deviceId,
|
||||
final Versionstamp versionstamp) {
|
||||
return foundationDbMessageStore.getShardForAci(aci).read(transaction -> {
|
||||
final byte[] key = foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId)
|
||||
final byte[] key = FoundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId)
|
||||
.pack(Tuple.from(versionstamp));
|
||||
return transaction.get(key);
|
||||
}).join();
|
||||
@@ -572,7 +655,7 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
private Optional<Versionstamp> getMessagesAvailableWatch(final AciServiceIdentifier aci) {
|
||||
return foundationDbMessageStore.getShardForAci(aci)
|
||||
.read(transaction -> transaction.get(foundationDbMessageStore.getMessagesAvailableWatchKey(aci))
|
||||
.read(transaction -> transaction.get(FoundationDbMessageStore.getMessagesAvailableWatchKey(aci))
|
||||
.thenApply(value -> value == null ? null : Tuple.fromBytes(value).getVersionstamp(0))
|
||||
.thenApply(Optional::ofNullable))
|
||||
.join();
|
||||
@@ -609,7 +692,7 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
private List<KeyValue> getItemsInDeviceQueue(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return foundationDbMessageStore.getShardForAci(aci).readAsync(transaction -> AsyncUtil.collect(transaction.getRange(
|
||||
foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId).range()))).join();
|
||||
FoundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId).range()))).join();
|
||||
}
|
||||
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
class FoundationDbMessageStreamTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void computeFlushableRanges(final List<Integer> versionstampsSent, final List<Integer> versionstampsAcknowledged,
|
||||
final List<Pair<Integer, Integer>> expectedRanges) {
|
||||
final FoundationDbMessageStream foundationDbMessageStream = new FoundationDbMessageStream(
|
||||
mock(Subspace.class),
|
||||
new byte[]{0},
|
||||
mock(Database.class),
|
||||
mock(MessageGuidCodec.class),
|
||||
100,
|
||||
Util.NOOP
|
||||
);
|
||||
|
||||
versionstampsSent.forEach(
|
||||
versionstamp -> foundationDbMessageStream.onVersionstampSent(versionstampFromInt(versionstamp)));
|
||||
versionstampsAcknowledged.forEach(
|
||||
versionstamp -> foundationDbMessageStream.handleAcknowledged(versionstampFromInt(versionstamp)));
|
||||
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = foundationDbMessageStream.computeFlushableRanges();
|
||||
assertEquals(expectedRanges
|
||||
.stream()
|
||||
.map(range -> new Pair<>(versionstampFromInt(range.first()), versionstampFromInt(range.second())))
|
||||
.toList(),
|
||||
flushableRanges);
|
||||
}
|
||||
|
||||
static Stream<Arguments> computeFlushableRanges() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Single acknowledged message range", List.of(1, 2, 3), List.of(1),
|
||||
List.of(new Pair<>(1, 1))),
|
||||
Arguments.argumentSet("No acknowledged messages", List.of(1, 2, 3), Collections.emptyList(),
|
||||
Collections.emptyList()),
|
||||
Arguments.argumentSet("Fully acknowledged message range", List.of(1, 2, 3, 4),
|
||||
List.of(1, 2, 3, 4), List.of(new Pair<>(1, 4))),
|
||||
Arguments.argumentSet("Not all messages acknowledged", List.of(1, 2, 3, 4),
|
||||
List.of(1, 2, 3), List.of(new Pair<>(1, 3))),
|
||||
Arguments.argumentSet("Out-of-order acknowledged ranges", List.of(1, 2, 3, 4, 5, 6, 7, 8),
|
||||
List.of(1, 3, 4, 5, 7, 8), List.of(new Pair<>(1, 1), new Pair<>(3, 5), new Pair<>(7, 8))),
|
||||
Arguments.argumentSet("Out-of-order acknowledged single messages", List.of(1, 2, 3, 4, 5, 6, 7, 8),
|
||||
List.of(1, 3, 5), List.of(new Pair<>(1, 1), new Pair<>(3, 3), new Pair<>(5, 5)))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private static Versionstamp versionstampFromInt(final int version) {
|
||||
final ByteBuffer buf = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN);
|
||||
buf.putLong(version); // 8 bytes: transaction version
|
||||
buf.putShort((short) 2); // 2 bytes: batch order within transaction
|
||||
return Versionstamp.complete(buf.array());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user