/
ServiceBusSenderAsyncClient.java
996 lines (917 loc) · 49.2 KB
/
ServiceBusSenderAsyncClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.servicebus;
import com.azure.core.amqp.AmqpRetryOptions;
import com.azure.core.amqp.AmqpRetryPolicy;
import com.azure.core.amqp.AmqpTransaction;
import com.azure.core.amqp.exception.AmqpErrorCondition;
import com.azure.core.amqp.exception.AmqpException;
import com.azure.core.amqp.implementation.AmqpSendLink;
import com.azure.core.amqp.implementation.ErrorContextProvider;
import com.azure.core.amqp.implementation.MessageSerializer;
import com.azure.core.amqp.implementation.RequestResponseChannelClosedException;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import com.azure.messaging.servicebus.implementation.MessagingEntityType;
import com.azure.messaging.servicebus.implementation.instrumentation.ServiceBusSenderInstrumentation;
import com.azure.messaging.servicebus.implementation.ServiceBusAmqpConnection;
import com.azure.messaging.servicebus.implementation.instrumentation.ServiceBusTracer;
import com.azure.messaging.servicebus.models.CreateMessageBatchOptions;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
import org.apache.qpid.proton.amqp.transaction.TransactionalState;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.StreamSupport;
import static com.azure.core.amqp.implementation.RetryUtil.getRetryPolicy;
import static com.azure.core.amqp.implementation.RetryUtil.withRetry;
import static com.azure.core.util.FluxUtil.fluxError;
import static com.azure.core.util.FluxUtil.monoError;
import static com.azure.messaging.servicebus.implementation.Messages.INVALID_OPERATION_DISPOSED_SENDER;
/**
* <p>An <b>asynchronous</b> client to send messages to a Service Bus resource.</p>
*
* <p>The examples shown in this document use a credential object named DefaultAzureCredential for authentication,
* which is appropriate for most scenarios, including local development and production environments. Additionally, we
* recommend using
* <a href="https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/">managed identity</a>
* for authentication in production environments. You can find more information on different ways of authenticating and
* their corresponding credential types in the
* <a href="https://learn.microsoft.com/java/api/overview/azure/identity-readme">Azure Identity documentation"</a>.
* </p>
*
* <p><strong>Sample: Create an instance of sender</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebusasyncsenderclient.instantiation -->
* <pre>
* TokenCredential credential = new DefaultAzureCredentialBuilder().build();
*
* // 'fullyQualifiedNamespace' will look similar to "{your-namespace}.servicebus.windows.net"
* ServiceBusSenderAsyncClient asyncSender = new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, credential)
* .sender()
* .queueName(queueName)
* .buildAsyncClient();
*
* // When users are done with the sender, they should dispose of it.
* // Clients should be long-lived objects as they require resources
* // and time to establish a connection to the service.
* asyncSender.close();
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusasyncsenderclient.instantiation -->
*
* <p><strong>Sample: Send messages to a Service Bus resource</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebusasyncsenderclient.createMessageBatch -->
* <pre>
* // `subscribe` is a non-blocking call. The program will move onto the next line of code when it starts the
* // operation. Users should use the callbacks on `subscribe` to understand the status of the send operation.
* asyncSender.createMessageBatch().flatMap(batch -> {
* batch.tryAddMessage(new ServiceBusMessage("test-1"));
* batch.tryAddMessage(new ServiceBusMessage("test-2"));
* return asyncSender.sendMessages(batch);
* }).subscribe(unused -> {
* }, error -> {
* System.err.println("Error occurred while sending batch:" + error);
* }, () -> {
* System.out.println("Send complete.");
* });
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusasyncsenderclient.createMessageBatch -->
*
* <p><strong>Sample: Send messages using a size-limited {@link ServiceBusMessageBatch} to a Service Bus resource
* </strong></p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebusasyncsenderclient.createMessageBatch#CreateMessageBatchOptionsLimitedSize -->
* <pre>
* Flux<ServiceBusMessage> telemetryMessages = Flux.just(firstMessage, secondMessage);
*
* // Setting `setMaximumSizeInBytes` when creating a batch, limits the size of that batch.
* // In this case, all the batches created with these options are limited to 256 bytes.
* CreateMessageBatchOptions options = new CreateMessageBatchOptions()
* .setMaximumSizeInBytes(256);
* AtomicReference<ServiceBusMessageBatch> currentBatch = new AtomicReference<>();
*
* // Sends the current batch if it is not null and not empty. If the current batch is null, sets it.
* // Returns the batch to work with.
* Mono<ServiceBusMessageBatch> sendBatchAndGetCurrentBatchOperation = Mono.defer(() -> {
* ServiceBusMessageBatch batch = currentBatch.get();
*
* if (batch == null) {
* return asyncSender.createMessageBatch(options);
* }
*
* if (batch.getCount() > 0) {
* return asyncSender.sendMessages(batch).then(
* asyncSender.createMessageBatch(options)
* .handle((ServiceBusMessageBatch newBatch, SynchronousSink<ServiceBusMessageBatch> sink) -> {
* // Expect that the batch we just sent is the current one. If it is not, there's a race
* // condition accessing currentBatch reference.
* if (!currentBatch.compareAndSet(batch, newBatch)) {
* sink.error(new IllegalStateException(
* "Expected that the object in currentBatch was batch. But it is not."));
* } else {
* sink.next(newBatch);
* }
* }));
* } else {
* return Mono.just(batch);
* }
* });
*
* // The sample Flux contains two messages, but it could be an infinite stream of telemetry messages.
* Flux<Void> sendMessagesOperation = telemetryMessages.flatMap(message -> {
* return sendBatchAndGetCurrentBatchOperation.flatMap(batch -> {
* if (batch.tryAddMessage(message)) {
* return Mono.empty();
* } else {
* return sendBatchAndGetCurrentBatchOperation
* .handle((ServiceBusMessageBatch newBatch, SynchronousSink<Void> sink) -> {
* if (!newBatch.tryAddMessage(message)) {
* sink.error(new IllegalArgumentException(
* "Message is too large to fit in an empty batch."));
* } else {
* sink.complete();
* }
* });
* }
* });
* });
*
* // `subscribe` is a non-blocking call. The program will move onto the next line of code when it starts the
* // operation. Users should use the callbacks on `subscribe` to understand the status of the send operation.
* Disposable disposable = sendMessagesOperation.then(sendBatchAndGetCurrentBatchOperation)
* .subscribe(batch -> {
* System.out.println("Last batch should be empty: " + batch.getCount());
* }, error -> {
* System.err.println("Error sending telemetry messages: " + error);
* }, () -> {
* System.out.println("Completed.");
*
* // Continue using the sender and finally, dispose of the sender.
* // Clients should be long-lived objects as they require resources
* // and time to establish a connection to the service.
* asyncSender.close();
* });
*
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusasyncsenderclient.createMessageBatch#CreateMessageBatchOptionsLimitedSize -->
*
* <p><strong>Sample: Sending a message to a session-enabled queue</strong></p>
*
* <p>The snippet below demonstrates sending a message to a
* <a href="https://learn.microsoft.com/azure/service-bus-messaging/message-sessions">Service Bus sessions</a>
* enabled queue. Setting {@link ServiceBusMessage#setMessageId(String)} property to "greetings" will send the message
* to a Service Bus session with an id of "greetings".</p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebussenderasyncclient.sendMessage-session -->
* <pre>
* // 'fullyQualifiedNamespace' will look similar to "{your-namespace}.servicebus.windows.net"
* ServiceBusSenderAsyncClient sender = new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, new DefaultAzureCredentialBuilder().build())
* .sender()
* .queueName(sessionEnabledQueueName)
* .buildAsyncClient();
*
* // Setting sessionId publishes that message to a specific session, in this case, "greeting".
* ServiceBusMessage message = new ServiceBusMessage("Hello world")
* .setSessionId("greetings");
*
* // `subscribe` is a non-blocking call. The program will move onto the next line of code when it starts the
* // operation. Users should use the callbacks on `subscribe` to understand the status of the send operation.
* sender.sendMessage(message).subscribe(unused -> {
* }, error -> {
* System.err.println("Error occurred publishing batch: " + error);
* }, () -> {
* System.out.println("Send complete.");
* });
*
* // Continue using the sender and finally, dispose of the sender.
* // Clients should be long-lived objects as they require resources
* // and time to establish a connection to the service.
* sender.close();
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebussenderasyncclient.sendMessage-session -->
*
* @see ServiceBusClientBuilder#sender()
* @see ServiceBusSenderClient To communicate with a Service Bus resource using a synchronous client.
*/
@ServiceClient(builder = ServiceBusClientBuilder.class, isAsync = true)
public final class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final CreateMessageBatchOptions DEFAULT_BATCH_OPTIONS = new CreateMessageBatchOptions();
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusSenderAsyncClient.class);
private final AtomicReference<String> linkName = new AtomicReference<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final MessageSerializer messageSerializer;
private final AmqpRetryOptions retryOptions;
private final AmqpRetryPolicy retryPolicy;
private final MessagingEntityType entityType;
private final Runnable onClientClose;
private final String entityName;
private final Mono<ServiceBusAmqpConnection> connectionProcessor;
private final String fullyQualifiedNamespace;
private final String viaEntityName;
private final String identifier;
private final ServiceBusSenderInstrumentation instrumentation;
private final ServiceBusTracer tracer;
private final boolean isV2;
/**
* Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to a Service Bus entity.
*/
ServiceBusSenderAsyncClient(String entityName, MessagingEntityType entityType,
ConnectionCacheWrapper connectionCacheWrapper, AmqpRetryOptions retryOptions, ServiceBusSenderInstrumentation instrumentation,
MessageSerializer messageSerializer, Runnable onClientClose, String viaEntityName, String identifier) {
// Caching the created link so we don't invoke another link creation.
this.messageSerializer = Objects.requireNonNull(messageSerializer,
"'messageSerializer' cannot be null.");
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null.");
Objects.requireNonNull(connectionCacheWrapper, "'connectionCacheWrapper' cannot be null.");
this.connectionProcessor = connectionCacheWrapper.getConnection();
this.fullyQualifiedNamespace = connectionCacheWrapper.getFullyQualifiedNamespace();
this.instrumentation = Objects.requireNonNull(instrumentation, "'instrumentation' cannot be null.");
this.tracer = instrumentation.getTracer();
this.retryPolicy = getRetryPolicy(retryOptions);
this.entityType = entityType;
this.viaEntityName = viaEntityName;
this.onClientClose = onClientClose;
this.identifier = identifier;
this.isV2 = connectionCacheWrapper.isV2();
}
/**
* Gets the fully qualified namespace.
*
* @return The fully qualified namespace.
*/
public String getFullyQualifiedNamespace() {
return fullyQualifiedNamespace;
}
/**
* Gets the name of the Service Bus resource.
*
* @return The name of the Service Bus resource.
*/
public String getEntityPath() {
return entityName;
}
/**
* Gets the identifier of the instance of {@link ServiceBusSenderAsyncClient}.
*
* @return The identifier that can identify the instance of {@link ServiceBusSenderAsyncClient}.
*/
public String getIdentifier() {
return identifier;
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
* @throws IllegalStateException if sender is already disposed.
* @throws ServiceBusException if {@code message} is larger than the maximum allowed size of a single message or
* the message could not be sent.
*/
public Mono<Void> sendMessage(ServiceBusMessage message) {
if (Objects.isNull(message)) {
return monoError(LOGGER, new NullPointerException("'message' cannot be null."));
}
return sendInternal(Flux.just(message), null);
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws IllegalStateException if sender is already disposed.
* @throws ServiceBusException if {@code message} is larger than the maximum allowed size of a single message or
* the message could not be sent.
*/
public Mono<Void> sendMessage(ServiceBusMessage message, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(Flux.just(message), transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages
* exceed the maximum size of a single batch, an exception will be triggered and the send will fail.
* By default, the message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws IllegalStateException if sender is already disposed.
* @throws ServiceBusException if the message could not be sent or {@code message} is larger than the maximum size of the {@link
* ServiceBusMessageBatch}.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendIterable(messages, transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages exceed
* the maximum size of a single batch, an exception will be triggered and the send will fail. By default, the
* message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code messages} is {@code null}.
* @throws ServiceBusException if the message could not be sent or {@code message} is larger than the maximum size of the {@link
* ServiceBusMessageBatch}.
* @throws IllegalStateException if sender is already disposed.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages) {
return sendIterable(messages, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch} is {@code null}.
* @throws ServiceBusException if the message batch could not be sent.
* @throws IllegalStateException if sender is already disposed.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch) {
return sendInternal(batch, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws ServiceBusException if the message batch could not be sent.
* @throws IllegalStateException if sender is already disposed.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(batch, transactionContext);
}
/**
* Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*
* @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
* @throws ServiceBusException if the message batch could not be created.
* @throws IllegalStateException if sender is already disposed.
*/
public Mono<ServiceBusMessageBatch> createMessageBatch() {
return createMessageBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link ServiceBusMessageBatch} configured with the options specified.
*
* @param options A set of options used to configure the {@link ServiceBusMessageBatch}.
*
* @return A new {@link ServiceBusMessageBatch} configured with the given options.
* @throws NullPointerException if {@code options} is null.
* @throws ServiceBusException if the message batch could not be created.
* @throws IllegalStateException if sender is already disposed.
* @throws IllegalArgumentException if {@link CreateMessageBatchOptions#getMaximumSizeInBytes()} is larger than
* maximum allowed size.
*/
public Mono<ServiceBusMessageBatch> createMessageBatch(CreateMessageBatchOptions options) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "createMessageBatch")));
}
if (Objects.isNull(options)) {
return monoError(LOGGER, new NullPointerException("'options' cannot be null."));
}
final int maxSize = options.getMaximumSizeInBytes();
final Mono<ServiceBusMessageBatch> createBatch = getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (maxSize > maximumLinkSize) {
return monoError(LOGGER, new IllegalArgumentException(String.format(Locale.US,
"CreateMessageBatchOptions.getMaximumSizeInBytes (%s bytes) is larger than the link size"
+ " (%s bytes).", maxSize, maximumLinkSize)));
}
final int batchSize = maxSize > 0
? maxSize
: maximumLinkSize;
return Mono.just(new ServiceBusMessageBatch(isV2, batchSize, link::getErrorContext, tracer, messageSerializer));
})).onErrorMap(RequestResponseChannelClosedException.class,
e -> {
// When the current connection is being disposed, the connectionProcessor can produce a new connection
// if downstream request. In this context, treat RequestResponseChannelClosedException from
// the RequestResponseChannel scoped to the current connection being disposed as retry-able so that retry
// can obtain new connection.
return new AmqpException(true, e.getMessage(), e, null);
});
// Similar to the companion API 'send', the 'create-batch' can also make network calls, so retry in case of transient errors.
return withRetry(createBatch, retryOptions,
String.format("entityPath[%s]: Creating batch timed out.", entityName))
.onErrorMap(this::mapError);
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message}, {@code scheduledEnqueueTime}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
* @throws ServiceBusException If the message could not be scheduled.
* @throws IllegalStateException if sender is already disposed.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return scheduleMessageInternal(message, scheduledEnqueueTime, transactionContext);
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}.
* @throws ServiceBusException If the message could not be scheduled.
* @throws IllegalStateException if sender is already disposed.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime) {
return scheduleMessageInternal(message, scheduledEnqueueTime, null);
}
/**
* Sends a batch of scheduled messages to the Azure Service Bus entity this sender is connected to. A scheduled
* message is enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param messages Messages to be sent to the Service Bus queue or topic.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*
* @return Sequence numbers of the scheduled messages which can be used to cancel the messages.
*
* @throws NullPointerException If {@code messages} or {@code scheduledEnqueueTime} is {@code null}.
* @throws ServiceBusException If the messages could not be scheduled.
* @throws IllegalStateException if sender is already disposed.
*/
public Flux<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime) {
return scheduleMessages(messages, scheduledEnqueueTime, null);
}
/**
* Sends a scheduled messages to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param messages Messages to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the messages should appear in the Service Bus queue or topic.
* @param transactionContext Transaction to associate with the operation.
*
* @return Sequence numbers of the scheduled messages which can be used to cancel the messages.
*
* @throws NullPointerException If {@code messages}, {@code scheduledEnqueueTime}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws ServiceBusException If the messages could not be scheduled or the {@code message} is larger than
* the maximum size of the {@link ServiceBusMessageBatch}.
* @throws IllegalStateException if sender is already disposed.
*/
public Flux<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return fluxError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "scheduleMessages")));
}
if (Objects.isNull(messages)) {
return fluxError(LOGGER, new NullPointerException("'messages' cannot be null."));
}
if (Objects.isNull(scheduledEnqueueTime)) {
return fluxError(LOGGER, new NullPointerException("'scheduledEnqueueTime' cannot be null."));
}
return createMessageBatch()
.map(messageBatch -> {
int index = 0;
for (ServiceBusMessage message : messages) {
if (!messageBatch.tryAddMessage(message)) {
final String error = String.format(Locale.US,
"Messages exceed max allowed size for all the messages together. "
+ "Failed to add message at index '%s'.", index);
throw LOGGER.logExceptionAsError(new IllegalArgumentException(error));
}
++index;
}
return messageBatch;
})
.flatMapMany(messageBatch ->
tracer.traceScheduleFlux("ServiceBus.scheduleMessages",
connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMapMany(managementNode -> managementNode.schedule(messageBatch.getMessages(), scheduledEnqueueTime,
messageBatch.getMaxSizeInBytes(), linkName.get(), transactionContext)),
messageBatch.getMessages())
).onErrorMap(this::mapError);
}
/**
* Cancels the enqueuing of a scheduled message, if it was not already enqueued.
*
* @param sequenceNumber of the scheduled message to cancel.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*
* @throws IllegalArgumentException if {@code sequenceNumber} is negative.
* @throws ServiceBusException If the messages could not be cancelled.
* @throws IllegalStateException if sender is already disposed.
*/
public Mono<Void> cancelScheduledMessage(long sequenceNumber) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "cancelScheduledMessage")));
}
if (sequenceNumber < 0) {
return monoError(LOGGER, new IllegalArgumentException("'sequenceNumber' cannot be negative."));
}
return tracer.traceMono("ServiceBus.cancelScheduledMessage",
connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.cancelScheduledMessages(
Collections.singletonList(sequenceNumber), linkName.get())))
.onErrorMap(this::mapError);
}
/**
* Cancels the enqueuing of an already scheduled message, if it was not already enqueued.
*
* @param sequenceNumbers of the scheduled messages to cancel.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code sequenceNumbers} is null.
* @throws IllegalStateException if sender is already disposed.
* @throws ServiceBusException if the scheduled messages cannot cancelled.
*/
public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "cancelScheduledMessages")));
}
if (Objects.isNull(sequenceNumbers)) {
return monoError(LOGGER, new NullPointerException("'messages' cannot be null."));
}
return tracer.traceMono("ServiceBus.cancelScheduledMessages",
connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.cancelScheduledMessages(sequenceNumbers, linkName.get())))
.onErrorMap(this::mapError);
}
/**
* Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along with
* {@link ServiceBusReceivedMessage} all operations that needs to be in this transaction.
*
* @return A new {@link ServiceBusTransactionContext}.
*
* @throws IllegalStateException if sender is already disposed.
* @throws ServiceBusException if a transaction cannot be created.
*
* @see ServiceBusReceiverAsyncClient#createTransaction()
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "createTransaction")));
}
return tracer.traceMono("ServiceBus.createTransaction",
connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId())))
.onErrorMap(this::mapError);
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on Service Bus resource.
*
* @throws IllegalStateException if sender is already disposed.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
* @throws ServiceBusException if the transaction could not be committed.
*
* @see ServiceBusReceiverAsyncClient#commitTransaction(ServiceBusTransactionContext)
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "commitTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return
tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId()))))
.onErrorMap(this::mapError);
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext Transaction to rollback.
*
* @return The {@link Mono} that finishes this operation on the Service Bus resource.
*
* @throws IllegalStateException if sender is already disposed.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
* @throws ServiceBusException if the transaction could not be rolled back.
*
* @see ServiceBusReceiverAsyncClient#rollbackTransaction(ServiceBusTransactionContext)
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "rollbackTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return tracer.traceMono("ServiceBus.rollbackTransaction",
connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId()))))
.onErrorMap(this::mapError);
}
/**
* Disposes of the {@link ServiceBusSenderAsyncClient}. If the client has a dedicated connection, the underlying
* connection is also closed.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
onClientClose.run();
}
private Mono<Void> sendIterable(Iterable<ServiceBusMessage> messages, ServiceBusTransactionContext transaction) {
if (Objects.isNull(messages)) {
return monoError(LOGGER, new NullPointerException("'messages' cannot be null."));
}
return createMessageBatch().flatMap(messageBatch -> {
StreamSupport.stream(messages.spliterator(), false)
.forEach(message -> messageBatch.tryAddMessage(message));
return sendInternal(messageBatch, transaction);
}).onErrorMap(this::mapError);
}
private Mono<Long> scheduleMessageInternal(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "scheduleMessage")));
}
if (Objects.isNull(message)) {
return monoError(LOGGER, new NullPointerException("'message' cannot be null."));
}
if (Objects.isNull(scheduledEnqueueTime)) {
return monoError(LOGGER, new NullPointerException("'scheduledEnqueueTime' cannot be null."));
}
return tracer.traceScheduleMono("ServiceBus.scheduleMessage",
getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> {
int maxSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.schedule(Arrays.asList(message), scheduledEnqueueTime,
maxSize, link.getLinkName(), transactionContext)
.next());
})),
message, message.getContext())
.onErrorMap(this::mapError);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*/
private Mono<Void> sendInternal(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "sendMessages")));
}
if (Objects.isNull(batch)) {
return monoError(LOGGER, new NullPointerException("'batch' cannot be null."));
}
if (batch.getMessages().isEmpty()) {
LOGGER.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
LOGGER.atInfo()
.addKeyValue("batchSize", batch.getCount())
.log("Sending batch.");
final List<org.apache.qpid.proton.message.Message> messages = Collections.synchronizedList(new ArrayList<>());
batch.getMessages().forEach(serviceBusMessage -> {
final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(serviceBusMessage);
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
message.setMessageAnnotations(messageAnnotations);
messages.add(message);
});
final Mono<Void> sendMessage = getSendLink().flatMap(link -> {
if (transactionContext != null && transactionContext.getTransactionId() != null) {
final TransactionalState deliveryState = new TransactionalState();
deliveryState.setTxnId(Binary.create(transactionContext.getTransactionId()));
return messages.size() == 1
? link.send(messages.get(0), deliveryState)
: link.send(messages, deliveryState);
} else {
return messages.size() == 1
? link.send(messages.get(0))
: link.send(messages);
}
}).onErrorMap(RequestResponseChannelClosedException.class,
e -> {
// When the current connection is being disposed, the connectionProcessor can produce a new connection
// if downstream request. In this context, treat RequestResponseChannelClosedException from
// the RequestResponseChannel scoped to the current connection being disposed as retry-able so that retry
// can obtain new connection.
return new AmqpException(true, e.getMessage(), e, null);
});
final Mono<Void> sendWithRetry = withRetry(sendMessage, retryOptions,
String.format("entityPath[%s], messages-count[%s]: Sending messages timed out.", entityName, batch.getCount()))
.onErrorMap(this::mapError);
return instrumentation.instrumentSendBatch("ServiceBus.send", sendWithRetry, batch.getMessages());
}
private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages, ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_SENDER, "sendMessage")));
}
return withRetry(getSendLink(), retryOptions, "Failed to create send link " + linkName)
.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final CreateMessageBatchOptions batchOptions = new CreateMessageBatchOptions()
.setMaximumSizeInBytes(batchSize);
return messages.collect(new AmqpMessageCollector(isV2, batchOptions, 1,
link::getErrorContext, tracer, messageSerializer));
})
.flatMap(list -> sendInternalBatch(Flux.fromIterable(list), transactionContext)))
.onErrorMap(this::mapError);
}
private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches,
ServiceBusTransactionContext transactionContext) {
return eventBatches
.flatMap(messageBatch -> sendInternal(messageBatch, transactionContext))
.then()
.doOnError(error -> LOGGER.error("Error sending batch.", error));
}
private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions,
entityName, identifier);
} else {
return connection.createSendLink(entityName, entityName, retryOptions, null, identifier);
}
})
.doOnNext(next -> linkName.compareAndSet(null, next.getLinkName()));
}
private Throwable mapError(Throwable throwable) {
if (!(throwable instanceof ServiceBusException)) {
return new ServiceBusException(throwable, ServiceBusErrorSource.SEND);
}
return throwable;
}
private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>,
List<ServiceBusMessageBatch>> {
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private final ServiceBusTracer tracer;
private final MessageSerializer serializer;
private final boolean isV2;
private volatile ServiceBusMessageBatch currentBatch;
AmqpMessageCollector(boolean isV2, CreateMessageBatchOptions options, Integer maxNumberOfBatches,
ErrorContextProvider contextProvider, ServiceBusTracer tracer, MessageSerializer serializer) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.contextProvider = contextProvider;
this.tracer = tracer;
this.serializer = serializer;
this.isV2 = isV2;
currentBatch = new ServiceBusMessageBatch(isV2, maxMessageSize, contextProvider, tracer, serializer);
}
@Override
public Supplier<List<ServiceBusMessageBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() {
return (list, event) -> {
ServiceBusMessageBatch batch = currentBatch;
if (batch.tryAddMessage(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new ServiceBusMessageBatch(isV2, maxMessageSize, contextProvider, tracer, serializer);
currentBatch.tryAddMessage(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<ServiceBusMessageBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() {
return list -> {
ServiceBusMessageBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
}