GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Pubsub ordering keys (#5624) · googleapis/google-cloud-java@fe9c781

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • google-cloud-pubsub/src
    • main/java/com/google/cloud/pubsub/v1
      • MessageDispatcher.java
      • Publisher.java
      • SequentialExecutorService.java
    • test/java/com/google/cloud/pubsub/v1
      • FakePublisherServiceImpl.java
      • PublisherImplTest.java
      • SequentialExecutorServiceTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/MessageDispatcher.java‎

Copy file name to clipboardExpand all lines: google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/MessageDispatcher.java
+9-2Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ class MessageDispatcher {
6262
@InternalApi static final Duration PENDING_ACKS_SEND_DELAY = Duration.ofMillis(100);
6363

6464
private final Executor executor;
65+
private final SequentialExecutorService.AutoExecutor sequentialExecutor;
6566
private final ScheduledExecutorService systemExecutor;
6667
private final ApiClock clock;
6768

@@ -206,6 +207,7 @@ void sendAckOperations(
206207
jobLock = new ReentrantLock();
207208
messagesWaiter = new MessageWaiter();
208209
this.clock = clock;
210+
this.sequentialExecutor = new SequentialExecutorService.AutoExecutor(executor);
209211
}
210212

211213
void start() {
@@ -358,7 +360,7 @@ public void nack() {
358360
}
359361
};
360362
ApiFutures.addCallback(response, ackHandler, MoreExecutors.directExecutor());
361-
executor.execute(
363+
Runnable deliverMessageTask =
362364
new Runnable() {
363365
@Override
364366
public void run() {
@@ -379,7 +381,12 @@ public void run() {
379381
response.setException(e);
380382
}
381383
}
382-
});
384+
};
385+
if (message.getOrderingKey().isEmpty()) {
386+
executor.execute(deliverMessageTask);
387+
} else {
388+
sequentialExecutor.submit(message.getOrderingKey(), deliverMessageTask);
389+
}
383390
}
384391

385392
/** Compute the ideal deadline, set subsequent modacks to this deadline, and return it. */
Collapse file

‎google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/Publisher.java‎

Copy file name to clipboardExpand all lines: google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/Publisher.java
+153-28Lines changed: 153 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,12 @@
4949
import com.google.pubsub.v1.TopicNames;
5050
import java.io.IOException;
5151
import java.util.ArrayList;
52+
import java.util.HashMap;
5253
import java.util.Iterator;
5354
import java.util.LinkedList;
5455
import java.util.List;
56+
import java.util.Map;
57+
import java.util.concurrent.Callable;
5558
import java.util.concurrent.ScheduledExecutorService;
5659
import java.util.concurrent.ScheduledFuture;
5760
import java.util.concurrent.TimeUnit;
@@ -85,15 +88,20 @@ public class Publisher {
8588
private final String topicName;
8689

8790
private final BatchingSettings batchingSettings;
91+
private final boolean enableMessageOrdering;
8892

8993
private final Lock messagesBatchLock;
90-
private MessagesBatch messagesBatch;
94+
95+
private final Map<String, MessagesBatch> messagesBatches;
9196

9297
private final AtomicBoolean activeAlarm;
9398

9499
private final PublisherStub publisherStub;
95100

96101
private final ScheduledExecutorService executor;
102+
103+
private final SequentialExecutorService.CallbackExecutor sequentialExecutor;
104+
97105
private final AtomicBoolean shutdown;
98106
private final BackgroundResource backgroundResources;
99107
private final MessageWaiter messagesWaiter;
@@ -114,22 +122,33 @@ private Publisher(Builder builder) throws IOException {
114122
topicName = builder.topicName;
115123

116124
this.batchingSettings = builder.batchingSettings;
125+
this.enableMessageOrdering = builder.enableMessageOrdering;
117126
this.messageTransform = builder.messageTransform;
118127

119-
messagesBatch = new MessagesBatch(batchingSettings);
128+
messagesBatches = new HashMap<>();
120129
messagesBatchLock = new ReentrantLock();
121130
activeAlarm = new AtomicBoolean(false);
122131
executor = builder.executorProvider.getExecutor();
132+
sequentialExecutor = new SequentialExecutorService.CallbackExecutor(executor);
123133
List<BackgroundResource> backgroundResourceList = new ArrayList<>();
124134
if (builder.executorProvider.shouldAutoClose()) {
125135
backgroundResourceList.add(new ExecutorAsBackgroundResource(executor));
126136
}
127137

128138
// Publisher used to take maxAttempt == 0 to mean infinity, but to GAX it means don't retry.
129139
// We post-process this here to keep backward-compatibility.
130-
RetrySettings retrySettings = builder.retrySettings;
131-
if (retrySettings.getMaxAttempts() == 0) {
132-
retrySettings = retrySettings.toBuilder().setMaxAttempts(Integer.MAX_VALUE).build();
140+
// Also, if "message ordering" is enabled, the publisher should retry sending the failed
141+
// message infinitely rather than sending the next one.
142+
RetrySettings.Builder retrySettingsBuilder = builder.retrySettings.toBuilder();
143+
if (retrySettingsBuilder.getMaxAttempts() == 0) {
144+
retrySettingsBuilder.setMaxAttempts(Integer.MAX_VALUE);
145+
}
146+
if (enableMessageOrdering) {
147+
// TODO: is there a way to have the default retry settings for requests without an ordering
148+
// key?
149+
retrySettingsBuilder
150+
.setMaxAttempts(Integer.MAX_VALUE)
151+
.setTotalTimeout(Duration.ofNanos(Long.MAX_VALUE));
133152
}
134153

135154
PublisherStubSettings.Builder stubSettings =
@@ -147,7 +166,7 @@ private Publisher(Builder builder) throws IOException {
147166
StatusCode.Code.RESOURCE_EXHAUSTED,
148167
StatusCode.Code.UNKNOWN,
149168
StatusCode.Code.UNAVAILABLE)
150-
.setRetrySettings(retrySettings)
169+
.setRetrySettings(retrySettingsBuilder.build())
151170
.setBatchingSettings(BatchingSettings.newBuilder().setIsEnabled(false).build());
152171
this.publisherStub = GrpcPublisherStub.create(stubSettings.build());
153172
backgroundResourceList.add(publisherStub);
@@ -194,38 +213,71 @@ public String getTopicNameString() {
194213
public ApiFuture<String> publish(PubsubMessage message) {
195214
Preconditions.checkState(!shutdown.get(), "Cannot publish on a shut-down publisher.");
196215

216+
final String orderingKey = message.getOrderingKey();
217+
Preconditions.checkState(
218+
orderingKey.isEmpty() || enableMessageOrdering,
219+
"Cannot publish a message with an ordering key when message ordering is not enabled.");
220+
197221
final OutstandingPublish outstandingPublish =
198222
new OutstandingPublish(messageTransform.apply(message));
199223
List<OutstandingBatch> batchesToSend;
200224
messagesBatchLock.lock();
201225
try {
226+
MessagesBatch messagesBatch = messagesBatches.get(orderingKey);
227+
if (messagesBatch == null) {
228+
messagesBatch = new MessagesBatch(batchingSettings, orderingKey);
229+
messagesBatches.put(orderingKey, messagesBatch);
230+
}
231+
202232
batchesToSend = messagesBatch.add(outstandingPublish);
233+
if (!batchesToSend.isEmpty() && messagesBatch.isEmpty()) {
234+
messagesBatches.remove(orderingKey);
235+
}
203236
// Setup the next duration based delivery alarm if there are messages batched.
204237
setupAlarm();
238+
// For messages with an ordering key, we need to publish with messagesBatchLock held in order
239+
// to ensure another publish doesn't slip in and send a batch before these batches we already
240+
// want to send.
241+
if (!batchesToSend.isEmpty() && !orderingKey.isEmpty()) {
242+
for (final OutstandingBatch batch : batchesToSend) {
243+
logger.log(Level.FINER, "Scheduling a batch for immediate sending.");
244+
publishOutstandingBatch(batch);
245+
}
246+
}
205247
} finally {
206248
messagesBatchLock.unlock();
207249
}
208250

209251
messagesWaiter.incrementPendingMessages(1);
210252

211-
if (!batchesToSend.isEmpty()) {
253+
// For messages without ordering keys, it is okay to send batches without holding
254+
// messagesBatchLock.
255+
if (!batchesToSend.isEmpty() && orderingKey.isEmpty()) {
212256
for (final OutstandingBatch batch : batchesToSend) {
213257
logger.log(Level.FINER, "Scheduling a batch for immediate sending.");
214-
executor.execute(
215-
new Runnable() {
216-
@Override
217-
public void run() {
218-
publishOutstandingBatch(batch);
219-
}
220-
});
258+
publishOutstandingBatch(batch);
221259
}
222260
}
223261

224262
return outstandingPublish.publishResult;
225263
}
226264

265+
/**
266+
* There may be non-recoverable problems with a request for an ordering key. In that case, all
267+
* subsequent requests will fail until this method is called. If the key is not currently paused,
268+
* calling this method will be a no-op.
269+
*
270+
* @param key The key for which to resume publishing.
271+
*/
272+
// TODO: make this public when Ordering keys is live
273+
@BetaApi
274+
void resumePublish(String key) {
275+
Preconditions.checkState(!shutdown.get(), "Cannot publish on a shut-down publisher.");
276+
sequentialExecutor.resumePublish(key);
277+
}
278+
227279
private void setupAlarm() {
228-
if (!messagesBatch.isEmpty()) {
280+
if (!messagesBatches.isEmpty()) {
229281
if (!activeAlarm.getAndSet(true)) {
230282
long delayThresholdMs = getBatchingSettings().getDelayThreshold().toMillis();
231283
logger.log(Level.FINER, "Setting up alarm for the next {0} ms.", delayThresholdMs);
@@ -236,7 +288,7 @@ private void setupAlarm() {
236288
public void run() {
237289
logger.log(Level.FINER, "Sending messages based on schedule.");
238290
activeAlarm.getAndSet(false);
239-
publishAllOutstanding();
291+
publishAllWithoutInflight();
240292
}
241293
},
242294
delayThresholdMs,
@@ -256,17 +308,61 @@ public void run() {
256308
* futures returned from {@code publish}.
257309
*/
258310
public void publishAllOutstanding() {
311+
OutstandingBatch unorderedOutstandingBatch = null;
312+
messagesBatchLock.lock();
313+
try {
314+
for (MessagesBatch batch : messagesBatches.values()) {
315+
if (!batch.isEmpty()) {
316+
if (!batch.orderingKey.isEmpty()) {
317+
// For messages with an ordering key, we need to publish with messagesBatchLock held in
318+
// order to ensure another publish doesn't slip in and send a batch before these batches
319+
// we already want to send.
320+
publishOutstandingBatch(batch.popOutstandingBatch());
321+
} else {
322+
unorderedOutstandingBatch = batch.popOutstandingBatch();
323+
}
324+
}
325+
}
326+
messagesBatches.clear();
327+
} finally {
328+
messagesBatchLock.unlock();
329+
}
330+
if (unorderedOutstandingBatch != null) {
331+
publishOutstandingBatch(unorderedOutstandingBatch);
332+
}
333+
}
334+
335+
/**
336+
* Publish any outstanding batches if non-empty and there are no other batches in flight. This
337+
* method sends buffered messages, but does not wait for the send operations to complete. To wait
338+
* for messages to send, call {@code get} on the futures returned from {@code publish}.
339+
*/
340+
private void publishAllWithoutInflight() {
341+
OutstandingBatch unorderedOutstandingBatch = null;
259342
messagesBatchLock.lock();
260-
OutstandingBatch batchToSend;
261343
try {
262-
if (messagesBatch.isEmpty()) {
263-
return;
344+
Iterator<Map.Entry<String, MessagesBatch>> it = messagesBatches.entrySet().iterator();
345+
while (it.hasNext()) {
346+
Map.Entry<String, MessagesBatch> entry = it.next();
347+
MessagesBatch batch = entry.getValue();
348+
String key = entry.getKey();
349+
if (batch.isEmpty()) {
350+
it.remove();
351+
} else if (key.isEmpty()) {
352+
// We will publish the batch with no ordering key outside messagesBatchLock.
353+
unorderedOutstandingBatch = batch.popOutstandingBatch();
354+
it.remove();
355+
} else if (!sequentialExecutor.hasTasksInflight(key)) {
356+
publishOutstandingBatch(batch.popOutstandingBatch());
357+
it.remove();
358+
}
264359
}
265-
batchToSend = messagesBatch.popOutstandingBatch();
266360
} finally {
267361
messagesBatchLock.unlock();
268362
}
269-
publishOutstandingBatch(batchToSend);
363+
if (unorderedOutstandingBatch != null) {
364+
publishOutstandingBatch(unorderedOutstandingBatch);
365+
}
270366
}
271367

272368
private ApiFuture<PublishResponse> publishCall(OutstandingBatch outstandingBatch) {
@@ -280,12 +376,12 @@ private ApiFuture<PublishResponse> publishCall(OutstandingBatch outstandingBatch
280376
}
281377

282378
private void publishOutstandingBatch(final OutstandingBatch outstandingBatch) {
283-
ApiFutureCallback<PublishResponse> futureCallback =
379+
final ApiFutureCallback<PublishResponse> futureCallback =
284380
new ApiFutureCallback<PublishResponse>() {
285381
@Override
286382
public void onSuccess(PublishResponse result) {
287383
try {
288-
if (result.getMessageIdsCount() != outstandingBatch.size()) {
384+
if (result == null || result.getMessageIdsCount() != outstandingBatch.size()) {
289385
outstandingBatch.onFailure(
290386
new IllegalStateException(
291387
String.format(
@@ -311,20 +407,37 @@ public void onFailure(Throwable t) {
311407
}
312408
};
313409

314-
ApiFutures.addCallback(publishCall(outstandingBatch), futureCallback, directExecutor());
410+
ApiFuture<PublishResponse> future;
411+
if (outstandingBatch.orderingKey == null || outstandingBatch.orderingKey.isEmpty()) {
412+
future = publishCall(outstandingBatch);
413+
} else {
414+
// If ordering key is specified, publish the batch using the sequential executor.
415+
future =
416+
sequentialExecutor.submit(
417+
outstandingBatch.orderingKey,
418+
new Callable<ApiFuture<PublishResponse>>() {
419+
public ApiFuture<PublishResponse> call() {
420+
return publishCall(outstandingBatch);
421+
}
422+
});
423+
}
424+
ApiFutures.addCallback(future, futureCallback, directExecutor());
315425
}
316426

317427
private static final class OutstandingBatch {
318428
final List<OutstandingPublish> outstandingPublishes;
319429
final long creationTime;
320430
int attempt;
321431
int batchSizeBytes;
432+
final String orderingKey;
322433

323-
OutstandingBatch(List<OutstandingPublish> outstandingPublishes, int batchSizeBytes) {
434+
OutstandingBatch(
435+
List<OutstandingPublish> outstandingPublishes, int batchSizeBytes, String orderingKey) {
324436
this.outstandingPublishes = outstandingPublishes;
325437
attempt = 1;
326438
creationTime = System.currentTimeMillis();
327439
this.batchSizeBytes = batchSizeBytes;
440+
this.orderingKey = orderingKey;
328441
}
329442

330443
int size() {
@@ -468,7 +581,7 @@ public static final class Builder {
468581
.setRpcTimeoutMultiplier(2)
469582
.setMaxRpcTimeout(DEFAULT_RPC_TIMEOUT)
470583
.build();
471-
584+
static final boolean DEFAULT_ENABLE_MESSAGE_ORDERING = false;
472585
private static final int THREADS_PER_CPU = 5;
473586
static final ExecutorProvider DEFAULT_EXECUTOR_PROVIDER =
474587
InstantiatingExecutorProvider.newBuilder()
@@ -482,6 +595,8 @@ public static final class Builder {
482595

483596
RetrySettings retrySettings = DEFAULT_RETRY_SETTINGS;
484597

598+
private boolean enableMessageOrdering = DEFAULT_ENABLE_MESSAGE_ORDERING;
599+
485600
private TransportChannelProvider channelProvider =
486601
TopicAdminSettings.defaultGrpcTransportProviderBuilder().setChannelsPerCpu(1).build();
487602

@@ -576,6 +691,14 @@ public Builder setRetrySettings(RetrySettings retrySettings) {
576691
return this;
577692
}
578693

694+
/** Sets the message ordering option. */
695+
// TODO: make this public when Ordering keys is live
696+
@BetaApi
697+
Builder setEnableMessageOrdering(boolean enableMessageOrdering) {
698+
this.enableMessageOrdering = enableMessageOrdering;
699+
return this;
700+
}
701+
579702
/** Gives the ability to set a custom executor to be used by the library. */
580703
public Builder setExecutorProvider(ExecutorProvider executorProvider) {
581704
this.executorProvider = Preconditions.checkNotNull(executorProvider);
@@ -601,15 +724,17 @@ public Publisher build() throws IOException {
601724
private static class MessagesBatch {
602725
private List<OutstandingPublish> messages;
603726
private int batchedBytes;
727+
private String orderingKey;
604728
private final BatchingSettings batchingSettings;
605729

606-
public MessagesBatch(BatchingSettings batchingSettings) {
730+
private MessagesBatch(BatchingSettings batchingSettings, String orderingKey) {
607731
this.batchingSettings = batchingSettings;
732+
this.orderingKey = orderingKey;
608733
reset();
609734
}
610735

611736
private OutstandingBatch popOutstandingBatch() {
612-
OutstandingBatch batch = new OutstandingBatch(messages, batchedBytes);
737+
OutstandingBatch batch = new OutstandingBatch(messages, batchedBytes, orderingKey);
613738
reset();
614739
return batch;
615740
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.