|
49 | 49 | import com.google.pubsub.v1.TopicNames; |
50 | 50 | import java.io.IOException; |
51 | 51 | import java.util.ArrayList; |
| 52 | +import java.util.HashMap; |
52 | 53 | import java.util.Iterator; |
53 | 54 | import java.util.LinkedList; |
54 | 55 | import java.util.List; |
| 56 | +import java.util.Map; |
| 57 | +import java.util.concurrent.Callable; |
55 | 58 | import java.util.concurrent.ScheduledExecutorService; |
56 | 59 | import java.util.concurrent.ScheduledFuture; |
57 | 60 | import java.util.concurrent.TimeUnit; |
@@ -85,15 +88,20 @@ public class Publisher { |
85 | 88 | private final String topicName; |
86 | 89 |
|
87 | 90 | private final BatchingSettings batchingSettings; |
| 91 | + private final boolean enableMessageOrdering; |
88 | 92 |
|
89 | 93 | private final Lock messagesBatchLock; |
90 | | - private MessagesBatch messagesBatch; |
| 94 | + |
| 95 | + private final Map<String, MessagesBatch> messagesBatches; |
91 | 96 |
|
92 | 97 | private final AtomicBoolean activeAlarm; |
93 | 98 |
|
94 | 99 | private final PublisherStub publisherStub; |
95 | 100 |
|
96 | 101 | private final ScheduledExecutorService executor; |
| 102 | + |
| 103 | + private final SequentialExecutorService.CallbackExecutor sequentialExecutor; |
| 104 | + |
97 | 105 | private final AtomicBoolean shutdown; |
98 | 106 | private final BackgroundResource backgroundResources; |
99 | 107 | private final MessageWaiter messagesWaiter; |
@@ -114,22 +122,33 @@ private Publisher(Builder builder) throws IOException { |
114 | 122 | topicName = builder.topicName; |
115 | 123 |
|
116 | 124 | this.batchingSettings = builder.batchingSettings; |
| 125 | + this.enableMessageOrdering = builder.enableMessageOrdering; |
117 | 126 | this.messageTransform = builder.messageTransform; |
118 | 127 |
|
119 | | - messagesBatch = new MessagesBatch(batchingSettings); |
| 128 | + messagesBatches = new HashMap<>(); |
120 | 129 | messagesBatchLock = new ReentrantLock(); |
121 | 130 | activeAlarm = new AtomicBoolean(false); |
122 | 131 | executor = builder.executorProvider.getExecutor(); |
| 132 | + sequentialExecutor = new SequentialExecutorService.CallbackExecutor(executor); |
123 | 133 | List<BackgroundResource> backgroundResourceList = new ArrayList<>(); |
124 | 134 | if (builder.executorProvider.shouldAutoClose()) { |
125 | 135 | backgroundResourceList.add(new ExecutorAsBackgroundResource(executor)); |
126 | 136 | } |
127 | 137 |
|
128 | 138 | // Publisher used to take maxAttempt == 0 to mean infinity, but to GAX it means don't retry. |
129 | 139 | // 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)); |
133 | 152 | } |
134 | 153 |
|
135 | 154 | PublisherStubSettings.Builder stubSettings = |
@@ -147,7 +166,7 @@ private Publisher(Builder builder) throws IOException { |
147 | 166 | StatusCode.Code.RESOURCE_EXHAUSTED, |
148 | 167 | StatusCode.Code.UNKNOWN, |
149 | 168 | StatusCode.Code.UNAVAILABLE) |
150 | | - .setRetrySettings(retrySettings) |
| 169 | + .setRetrySettings(retrySettingsBuilder.build()) |
151 | 170 | .setBatchingSettings(BatchingSettings.newBuilder().setIsEnabled(false).build()); |
152 | 171 | this.publisherStub = GrpcPublisherStub.create(stubSettings.build()); |
153 | 172 | backgroundResourceList.add(publisherStub); |
@@ -194,38 +213,71 @@ public String getTopicNameString() { |
194 | 213 | public ApiFuture<String> publish(PubsubMessage message) { |
195 | 214 | Preconditions.checkState(!shutdown.get(), "Cannot publish on a shut-down publisher."); |
196 | 215 |
|
| 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 | + |
197 | 221 | final OutstandingPublish outstandingPublish = |
198 | 222 | new OutstandingPublish(messageTransform.apply(message)); |
199 | 223 | List<OutstandingBatch> batchesToSend; |
200 | 224 | messagesBatchLock.lock(); |
201 | 225 | try { |
| 226 | + MessagesBatch messagesBatch = messagesBatches.get(orderingKey); |
| 227 | + if (messagesBatch == null) { |
| 228 | + messagesBatch = new MessagesBatch(batchingSettings, orderingKey); |
| 229 | + messagesBatches.put(orderingKey, messagesBatch); |
| 230 | + } |
| 231 | + |
202 | 232 | batchesToSend = messagesBatch.add(outstandingPublish); |
| 233 | + if (!batchesToSend.isEmpty() && messagesBatch.isEmpty()) { |
| 234 | + messagesBatches.remove(orderingKey); |
| 235 | + } |
203 | 236 | // Setup the next duration based delivery alarm if there are messages batched. |
204 | 237 | 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 | + } |
205 | 247 | } finally { |
206 | 248 | messagesBatchLock.unlock(); |
207 | 249 | } |
208 | 250 |
|
209 | 251 | messagesWaiter.incrementPendingMessages(1); |
210 | 252 |
|
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()) { |
212 | 256 | for (final OutstandingBatch batch : batchesToSend) { |
213 | 257 | 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); |
221 | 259 | } |
222 | 260 | } |
223 | 261 |
|
224 | 262 | return outstandingPublish.publishResult; |
225 | 263 | } |
226 | 264 |
|
| 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 | + |
227 | 279 | private void setupAlarm() { |
228 | | - if (!messagesBatch.isEmpty()) { |
| 280 | + if (!messagesBatches.isEmpty()) { |
229 | 281 | if (!activeAlarm.getAndSet(true)) { |
230 | 282 | long delayThresholdMs = getBatchingSettings().getDelayThreshold().toMillis(); |
231 | 283 | logger.log(Level.FINER, "Setting up alarm for the next {0} ms.", delayThresholdMs); |
@@ -236,7 +288,7 @@ private void setupAlarm() { |
236 | 288 | public void run() { |
237 | 289 | logger.log(Level.FINER, "Sending messages based on schedule."); |
238 | 290 | activeAlarm.getAndSet(false); |
239 | | - publishAllOutstanding(); |
| 291 | + publishAllWithoutInflight(); |
240 | 292 | } |
241 | 293 | }, |
242 | 294 | delayThresholdMs, |
@@ -256,17 +308,61 @@ public void run() { |
256 | 308 | * futures returned from {@code publish}. |
257 | 309 | */ |
258 | 310 | 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; |
259 | 342 | messagesBatchLock.lock(); |
260 | | - OutstandingBatch batchToSend; |
261 | 343 | 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 | + } |
264 | 359 | } |
265 | | - batchToSend = messagesBatch.popOutstandingBatch(); |
266 | 360 | } finally { |
267 | 361 | messagesBatchLock.unlock(); |
268 | 362 | } |
269 | | - publishOutstandingBatch(batchToSend); |
| 363 | + if (unorderedOutstandingBatch != null) { |
| 364 | + publishOutstandingBatch(unorderedOutstandingBatch); |
| 365 | + } |
270 | 366 | } |
271 | 367 |
|
272 | 368 | private ApiFuture<PublishResponse> publishCall(OutstandingBatch outstandingBatch) { |
@@ -280,12 +376,12 @@ private ApiFuture<PublishResponse> publishCall(OutstandingBatch outstandingBatch |
280 | 376 | } |
281 | 377 |
|
282 | 378 | private void publishOutstandingBatch(final OutstandingBatch outstandingBatch) { |
283 | | - ApiFutureCallback<PublishResponse> futureCallback = |
| 379 | + final ApiFutureCallback<PublishResponse> futureCallback = |
284 | 380 | new ApiFutureCallback<PublishResponse>() { |
285 | 381 | @Override |
286 | 382 | public void onSuccess(PublishResponse result) { |
287 | 383 | try { |
288 | | - if (result.getMessageIdsCount() != outstandingBatch.size()) { |
| 384 | + if (result == null || result.getMessageIdsCount() != outstandingBatch.size()) { |
289 | 385 | outstandingBatch.onFailure( |
290 | 386 | new IllegalStateException( |
291 | 387 | String.format( |
@@ -311,20 +407,37 @@ public void onFailure(Throwable t) { |
311 | 407 | } |
312 | 408 | }; |
313 | 409 |
|
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()); |
315 | 425 | } |
316 | 426 |
|
317 | 427 | private static final class OutstandingBatch { |
318 | 428 | final List<OutstandingPublish> outstandingPublishes; |
319 | 429 | final long creationTime; |
320 | 430 | int attempt; |
321 | 431 | int batchSizeBytes; |
| 432 | + final String orderingKey; |
322 | 433 |
|
323 | | - OutstandingBatch(List<OutstandingPublish> outstandingPublishes, int batchSizeBytes) { |
| 434 | + OutstandingBatch( |
| 435 | + List<OutstandingPublish> outstandingPublishes, int batchSizeBytes, String orderingKey) { |
324 | 436 | this.outstandingPublishes = outstandingPublishes; |
325 | 437 | attempt = 1; |
326 | 438 | creationTime = System.currentTimeMillis(); |
327 | 439 | this.batchSizeBytes = batchSizeBytes; |
| 440 | + this.orderingKey = orderingKey; |
328 | 441 | } |
329 | 442 |
|
330 | 443 | int size() { |
@@ -468,7 +581,7 @@ public static final class Builder { |
468 | 581 | .setRpcTimeoutMultiplier(2) |
469 | 582 | .setMaxRpcTimeout(DEFAULT_RPC_TIMEOUT) |
470 | 583 | .build(); |
471 | | - |
| 584 | + static final boolean DEFAULT_ENABLE_MESSAGE_ORDERING = false; |
472 | 585 | private static final int THREADS_PER_CPU = 5; |
473 | 586 | static final ExecutorProvider DEFAULT_EXECUTOR_PROVIDER = |
474 | 587 | InstantiatingExecutorProvider.newBuilder() |
@@ -482,6 +595,8 @@ public static final class Builder { |
482 | 595 |
|
483 | 596 | RetrySettings retrySettings = DEFAULT_RETRY_SETTINGS; |
484 | 597 |
|
| 598 | + private boolean enableMessageOrdering = DEFAULT_ENABLE_MESSAGE_ORDERING; |
| 599 | + |
485 | 600 | private TransportChannelProvider channelProvider = |
486 | 601 | TopicAdminSettings.defaultGrpcTransportProviderBuilder().setChannelsPerCpu(1).build(); |
487 | 602 |
|
@@ -576,6 +691,14 @@ public Builder setRetrySettings(RetrySettings retrySettings) { |
576 | 691 | return this; |
577 | 692 | } |
578 | 693 |
|
| 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 | + |
579 | 702 | /** Gives the ability to set a custom executor to be used by the library. */ |
580 | 703 | public Builder setExecutorProvider(ExecutorProvider executorProvider) { |
581 | 704 | this.executorProvider = Preconditions.checkNotNull(executorProvider); |
@@ -601,15 +724,17 @@ public Publisher build() throws IOException { |
601 | 724 | private static class MessagesBatch { |
602 | 725 | private List<OutstandingPublish> messages; |
603 | 726 | private int batchedBytes; |
| 727 | + private String orderingKey; |
604 | 728 | private final BatchingSettings batchingSettings; |
605 | 729 |
|
606 | | - public MessagesBatch(BatchingSettings batchingSettings) { |
| 730 | + private MessagesBatch(BatchingSettings batchingSettings, String orderingKey) { |
607 | 731 | this.batchingSettings = batchingSettings; |
| 732 | + this.orderingKey = orderingKey; |
608 | 733 | reset(); |
609 | 734 | } |
610 | 735 |
|
611 | 736 | private OutstandingBatch popOutstandingBatch() { |
612 | | - OutstandingBatch batch = new OutstandingBatch(messages, batchedBytes); |
| 737 | + OutstandingBatch batch = new OutstandingBatch(messages, batchedBytes, orderingKey); |
613 | 738 | reset(); |
614 | 739 | return batch; |
615 | 740 | } |
|