Increment a counter when reading the first message from a stream

This commit is contained in:
Jon Chambers authored and Jon Chambers committed 2026-11-18 15:38:08 -05:00
1 parent b3db95c3ea
commit 0100901667
5 files changed
+90 -3

No files matched your search

@@ -1,6 +1,7 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.MutationType;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.tuple.Versionstamp;
@@ -8,6 +9,8 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.InvalidProtocolBufferException;
import io.micrometer.core.instrument.Metrics;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.Clock;
import java.util.Arrays;
import java.util.Collections;
@@ -42,6 +45,8 @@ class FoundationDbMessagePublisher {
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
private final KeySelector endKeyExclusive;
private final byte[] readsSinceHeadAcknowledgedKey;
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
@Nullable private final byte[] presenceKey;
@@ -87,6 +92,12 @@ class FoundationDbMessagePublisher {
private static final int STREAM_ID_UNASSIGNED = -1;
// FoundationDB's `ADD` mutation operate on little-endian, 64-bit integers rather than on tuple-encoded integers
private static final byte[] ONE_LITTLE_ENDIAN = ByteBuffer.allocate(Long.BYTES)
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(1L)
.array();
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
private static final String WATCHES_COUNTER = MetricsUtil.name(FoundationDbMessagePublisher.class, "watches");
@@ -131,6 +142,7 @@ class FoundationDbMessagePublisher {
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final int streamId,
final byte[] readsSinceHeadAcknowledgedKey,
@Nullable final byte[] presenceKey,
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
@Nullable final byte[] messagesAvailableWatchKey,
@@ -141,6 +153,7 @@ class FoundationDbMessagePublisher {
this.beginKeyCursor = beginKeyInclusive;
this.endKeyExclusive = endKeyExclusive;
this.streamId = streamId;
this.readsSinceHeadAcknowledgedKey = readsSinceHeadAcknowledgedKey;
this.presenceKey = presenceKey;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
@@ -176,13 +189,15 @@ class FoundationDbMessagePublisher {
final FaultTolerantDatabase database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive) {
final KeySelector endKeyExclusive,
final byte[] readsSinceHeadAcknowledgedKey) {
return new FoundationDbMessagePublisher(database,
clock,
beginKeyInclusive,
endKeyExclusive,
STREAM_ID_UNASSIGNED,
readsSinceHeadAcknowledgedKey,
null,
null,
null,
@@ -198,6 +213,7 @@ class FoundationDbMessagePublisher {
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final int streamId,
final byte[] readsSinceHeadAcknowledgedKey,
final byte[] presenceKey,
final ScheduledExecutorService presenceRenewalExecutorService,
final byte[] messagesAvailableWatchKey) {
@@ -207,6 +223,7 @@ class FoundationDbMessagePublisher {
beginKeyInclusive,
endKeyExclusive,
streamId,
readsSinceHeadAcknowledgedKey,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
@@ -345,7 +362,14 @@ class FoundationDbMessagePublisher {
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessages, false, StreamingMode.EXACT).asList(),
(_, keyValues) -> keyValues)
.thenApply(keyValues -> {
if (keyValues.size() < maxMessages && !terminateOnQueueEmpty) {
final int keyValuesSize = keyValues.size();
if (keyValuesSize > 0 && !hasEmittedEntry()) {
// We're about to emit our first message; increment the "sent head of queue since last ACK" counter
incrementReadsSinceHeadAcknowledged(transaction);
}
if (keyValuesSize < maxMessages && !terminateOnQueueEmpty) {
setWatch(transaction);
}
@@ -398,6 +422,10 @@ class FoundationDbMessagePublisher {
return (int) Math.min(totalRequested - totalEmitted, Integer.MAX_VALUE);
}
private synchronized boolean hasEmittedEntry() {
return totalEmitted > 0;
}
/// Fetch and publish messages. Messages are fetched in batches to avoid excessive memory consumption. After each
/// fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading from. If the fetch
/// operation returns fewer items than the batch size, we infer that we have fetched all available messages and
@@ -426,6 +454,10 @@ class FoundationDbMessagePublisher {
return this.messagePublisher;
}
private void incrementReadsSinceHeadAcknowledged(final Transaction transaction) {
transaction.mutate(MutationType.ADD, readsSinceHeadAcknowledgedKey, ONE_LITTLE_ENDIAN);
}
private synchronized void setWatch(final Transaction transaction) {
assert messagesAvailableWatchKey != null;
if (isTerminated()) {
@@ -21,6 +21,7 @@ import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -795,6 +796,25 @@ public class FoundationDbMessageStore {
}, FaultTolerantDatabase.Context.TRIM_QUEUE);
}
/// Returns the number of times a subscriber has started reading a message queue without acknowledging the message at
/// the head of the queue. In cases where a caller's messages span multiple database shards (i.e. during a migration),
/// this method returns the maximum count across all shards.
///
/// @param aci the account identifier for which to retrieve a read-without-acknowledging-head count
/// @param deviceId the device ID for which to retrieve a read-without-acknowledging-head count
///
/// @return the number of times a subscriber has started reading messages from the identified message queue without
/// acknowledging the message at the head of the queue
@VisibleForTesting
CompletableFuture<Long> getReadsSinceHeadAcknowledged(final AciServiceIdentifier aci, final byte deviceId) {
return Flux.fromArray(getDistinctDatabasesForAci(aci))
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
transaction.get(getReadsSinceHeadAcknowledgedKey(aci, deviceId)), FaultTolerantDatabase.Context.TEST)))
.map(countBytes -> ByteBuffer.wrap(countBytes).order(ByteOrder.LITTLE_ENDIAN).getLong())
.reduce(0L, Math::max)
.toFuture();
}
@VisibleForTesting
public static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
return getAccountSubspace(MESSAGES_SUBSPACE, aci);
@@ -809,6 +829,10 @@ public class FoundationDbMessageStore {
return getAccountSubspace(aci).pack("l");
}
static byte[] getReadsSinceHeadAcknowledgedKey(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).pack("r");
}
@VisibleForTesting
static byte[] getServerId() {
return SERVER_ID;
@@ -137,7 +137,8 @@ public class FoundationDbMessageStream implements MessageStream {
database,
clock,
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive)
endOfQueueKeyExclusive,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(aciServiceIdentifier, deviceId))
.getMessages())
.orElseGet(Flux::empty)
.handle((fdbMessageStreamEntry, sink) -> {
@@ -170,6 +171,7 @@ public class FoundationDbMessageStream implements MessageStream {
infinitePublisherBeginKey,
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
NEXT_STREAM_ID.getAndIncrement(),
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(aciServiceIdentifier, deviceId),
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey).getMessages();
@@ -130,6 +130,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
null,
null,
null,
@@ -207,6 +208,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -297,6 +299,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -351,6 +354,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -399,6 +403,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterThan(SUBSPACE_RANGE.end),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY);
@@ -461,6 +466,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -527,6 +533,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
null,
null,
null,
@@ -585,6 +592,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceHeadAcknowledgedKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -1314,6 +1314,27 @@ class FoundationDbMessageStoreTest {
foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(aci, deviceId).join());
}
@Test
void getReadsSinceHeadAcknowledged() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final int messageCount = 16;
for (int i = 0; i < messageCount; i++) {
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
}
assertEquals(0, foundationDbMessageStore.getReadsSinceHeadAcknowledged(aci, Device.PRIMARY_ID).join());
for (int i = 1; i < 3; i++) {
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, Util.NOOP).getMessages())
.take(messageCount)
.then()
.block();
assertEquals(i, foundationDbMessageStore.getReadsSinceHeadAcknowledged(aci, Device.PRIMARY_ID).join());
}
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
return generateRandomMessage(ephemeral, contentSize, CLOCK.millis());
}