mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 06:56:47 +00:00
Discard ephemeral messages from the finite publisher in FoundationDB
This commit is contained in:
1 parent
d9c39cc12b
commit
b93da1323b
4 files changed
+71
-65
No files matched your search
+11
@@ -99,4 +99,15 @@ class AcknowledgedMessageBuffer {
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
|
||||
/// Acknowledges a stale ephemeral message for cleanup from FoundationDB.
|
||||
/// Ephemeral messages are only delivered when the recipient has an active message stream, so any ephemeral message
|
||||
/// read from the finite publisher is stale by definition and can be immediately acknowledged and discarded.
|
||||
///
|
||||
/// @param versionstamp The versionstamp to acknowledge
|
||||
public synchronized void acknowledgeStaleEphemeralMessage(final Versionstamp versionstamp) {
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
}
|
||||
+1
-2
@@ -275,8 +275,7 @@ public class FoundationDbMessageStore {
|
||||
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
|
||||
maxMessagesPerScan,
|
||||
maxUnacknowledgedMessages,
|
||||
doAfterCleanup,
|
||||
clock);
|
||||
doAfterCleanup);
|
||||
}
|
||||
|
||||
static Versionstamp getVersionstamp(final byte[] messageKey) {
|
||||
|
||||
+17
-23
@@ -16,6 +16,8 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.function.Consumer;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
@@ -27,6 +29,8 @@ import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
/// A [MessageStream] implementation that fetches messages from FoundationDB
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
@@ -38,12 +42,9 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final int maxMessagesPerScan;
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
private final Runnable doAfterCleanup;
|
||||
private final Clock clock;
|
||||
|
||||
private final AcknowledgedMessageBuffer acknowledgedMessageBuffer;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
|
||||
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
|
||||
name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
|
||||
@VisibleForTesting
|
||||
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
|
||||
@@ -56,14 +57,12 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup,
|
||||
final Clock clock) {
|
||||
final Runnable doAfterCleanup) {
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.database = database;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.clock = clock;
|
||||
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
|
||||
this.doAfterCleanup = doAfterCleanup;
|
||||
|
||||
@@ -81,7 +80,6 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// @implNote turns the stream of [FoundationDbMessageStreamEntry] into [MessageStreamEntry], but taps into the stream
|
||||
/// first to keep track of versionstamps sent to the client.
|
||||
private Flux<MessageStreamEntry> createMessagePublisher() {
|
||||
final long earliestAllowedEphemeralTimestamp = clock.instant().minus(MAX_EPHEMERAL_MESSAGE_DELAY).toEpochMilli();
|
||||
return createFoundationDbMessagePublisher()
|
||||
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
|
||||
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
|
||||
@@ -96,14 +94,6 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
sink.next(messageStreamEntry);
|
||||
})
|
||||
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
|
||||
.<MessageStreamEntry>handle((messageStreamEntry, sink) -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)
|
||||
&& isStaleEphemeralMessage(message, earliestAllowedEphemeralTimestamp)) {
|
||||
acknowledgeMessage(message);
|
||||
return;
|
||||
}
|
||||
sink.next(messageStreamEntry);
|
||||
})
|
||||
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
|
||||
}
|
||||
|
||||
@@ -126,7 +116,16 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive, database, maxMessagesPerScan, this::clearAcknowledgedMessages).getMessages())
|
||||
.orElseGet(Flux::empty);
|
||||
.orElseGet(Flux::empty)
|
||||
.handle((fdbMessageStreamEntry, sink) -> {
|
||||
// Ephemeral messages from the finite stream are considered stale and automatically discarded
|
||||
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
|
||||
acknowledgedMessageBuffer.acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
|
||||
staleEphemeralMessagesCounter.increment();
|
||||
return;
|
||||
}
|
||||
sink.next(fdbMessageStreamEntry);
|
||||
});
|
||||
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
|
||||
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
|
||||
final Flux<FoundationDbMessageStreamEntry.Message> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
@@ -196,9 +195,4 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
|
||||
}
|
||||
|
||||
private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message,
|
||||
final long earliestAllowableTimestamp) {
|
||||
return message.getEphemeral() && message.getClientTimestamp() < earliestAllowableTimestamp;
|
||||
}
|
||||
}
|
||||
+42
-40
@@ -37,7 +37,6 @@ 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;
|
||||
import java.util.stream.IntStream;
|
||||
@@ -649,57 +648,60 @@ class FoundationDbMessageStoreTest {
|
||||
.verify();
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void discardStaleEphemeralMessages(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean isStale,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral) {
|
||||
@Test
|
||||
void discardStaleEphemeralMessages() 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 long messageTimestamp;
|
||||
if (isStale) {
|
||||
messageTimestamp = CLOCK.instant().minus(FoundationDbMessageStream.MAX_EPHEMERAL_MESSAGE_DELAY.plus(Duration.ofMillis(1))).toEpochMilli();
|
||||
} else {
|
||||
messageTimestamp = CLOCK.instant().toEpochMilli();
|
||||
}
|
||||
|
||||
final Versionstamp expectedVersionstamp = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(ephemeral, messageTimestamp)))
|
||||
// Insert an ephemeral message that will be read by the finite publisher and immediately acknowledged and discarded
|
||||
final Versionstamp acknowledgedVersionstamp = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(true)))
|
||||
.join()
|
||||
.get(Device.PRIMARY_ID)
|
||||
.versionstamp()
|
||||
.orElseThrow();
|
||||
|
||||
final CountDownLatch cleanUpLatch = new CountDownLatch(1);
|
||||
final CountDownLatch queueEmptyLatch = new CountDownLatch(1);
|
||||
final MessageProtos.Envelope freshEphemeralMessage = generateRandomMessage(true);
|
||||
final CompletableFuture<Versionstamp> deliveredUnacknowledgedVersionstamp = new CompletableFuture<>();
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
// Wait until queue is empty to publish a "fresh" ephemeral message
|
||||
assertTrue(queueEmptyLatch.await(1000, TimeUnit.MILLISECONDS));
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, freshEphemeralMessage))
|
||||
.thenAccept(result -> {
|
||||
result.get(Device.PRIMARY_ID)
|
||||
.versionstamp()
|
||||
.ifPresentOrElse(deliveredUnacknowledgedVersionstamp::complete,
|
||||
() -> deliveredUnacknowledgedVersionstamp.completeExceptionally(new RuntimeException("versionstamp absent")));
|
||||
});
|
||||
} catch (final InterruptedException e) {
|
||||
fail(e);
|
||||
}
|
||||
});
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
|
||||
if (isStale && ephemeral) {
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofSeconds(1));
|
||||
assertEquals(1, retrievedEntries.size());
|
||||
} else {
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
.expectNextCount(1)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofSeconds(1));
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
cleanUpLatch::countDown);
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
// We should have discarded the already-inserted ephemeral message
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.then(queueEmptyLatch::countDown)
|
||||
.expectNextMatches(entry -> entry.equals(new MessageStreamEntry.Envelope(freshEphemeralMessage
|
||||
.toBuilder()
|
||||
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(deliveredUnacknowledgedVersionstamp.join())))
|
||||
.build())))
|
||||
.verifyTimeout(Duration.ofSeconds(3));
|
||||
|
||||
assertEquals(2, retrievedEntries.size());
|
||||
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
|
||||
final MessageStreamEntry.Envelope envelopeEntry =
|
||||
assertInstanceOf(MessageStreamEntry.Envelope.class, retrievedEntries.getFirst());
|
||||
assertEquals(expectedVersionstamp,
|
||||
messageGuidCodec.decodeMessageGuid(UUIDUtil.fromByteString(envelopeEntry.message().getServerGuidBinary())));
|
||||
}
|
||||
}
|
||||
|
||||
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final long timestamp) {
|
||||
return generateRandomMessage(ephemeral, 16, timestamp);
|
||||
assertTrue(cleanUpLatch.await(1, TimeUnit.SECONDS));
|
||||
assertNull(getMessageByVersionstamp(aci, Device.PRIMARY_ID, acknowledgedVersionstamp));
|
||||
assertNotNull(getMessageByVersionstamp(aci, Device.PRIMARY_ID, deliveredUnacknowledgedVersionstamp.join()));
|
||||
}
|
||||
|
||||
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
|
||||
|
||||
Reference in new issue
Block a user