/
ServiceBusReceiverAsyncClient.java
2016 lines (1870 loc) · 111 KB
/
ServiceBusReceiverAsyncClient.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
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.servicebus;
import com.azure.core.amqp.AmqpRetryPolicy;
import com.azure.core.amqp.AmqpSession;
import com.azure.core.amqp.AmqpTransaction;
import com.azure.core.amqp.exception.AmqpException;
import com.azure.core.amqp.implementation.CreditFlowMode;
import com.azure.core.amqp.implementation.MessageFlux;
import com.azure.core.amqp.implementation.MessageSerializer;
import com.azure.core.amqp.implementation.RequestResponseChannelClosedException;
import com.azure.core.amqp.implementation.RetryUtil;
import com.azure.core.amqp.implementation.StringUtil;
import com.azure.core.amqp.implementation.handler.DeliveryNotOnLinkException;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.IterableStream;
import com.azure.core.util.logging.ClientLogger;
import com.azure.messaging.servicebus.ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder;
import com.azure.messaging.servicebus.implementation.DispositionStatus;
import com.azure.messaging.servicebus.implementation.LockContainer;
import com.azure.messaging.servicebus.implementation.MessagingEntityType;
import com.azure.messaging.servicebus.implementation.ServiceBusAmqpConnection;
import com.azure.messaging.servicebus.implementation.ServiceBusReceiveLink;
import com.azure.messaging.servicebus.implementation.ServiceBusReceiveLinkProcessor;
import com.azure.messaging.servicebus.implementation.instrumentation.ServiceBusReceiverInstrumentation;
import com.azure.messaging.servicebus.implementation.instrumentation.ServiceBusTracer;
import com.azure.messaging.servicebus.models.AbandonOptions;
import com.azure.messaging.servicebus.models.CompleteOptions;
import com.azure.messaging.servicebus.models.DeadLetterOptions;
import com.azure.messaging.servicebus.models.DeferOptions;
import com.azure.messaging.servicebus.models.ServiceBusReceiveMode;
import reactor.core.Disposable;
import reactor.core.Disposables;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import static com.azure.core.amqp.implementation.ClientConstants.ENTITY_PATH_KEY;
import static com.azure.core.amqp.implementation.ClientConstants.LINK_NAME_KEY;
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_RECEIVER;
import static com.azure.messaging.servicebus.implementation.ServiceBusConstants.DISPOSITION_STATUS_KEY;
import static com.azure.messaging.servicebus.implementation.ServiceBusConstants.ENTITY_TYPE_KEY;
import static com.azure.messaging.servicebus.implementation.ServiceBusConstants.LOCK_TOKEN_KEY;
import static com.azure.messaging.servicebus.implementation.ServiceBusConstants.SEQUENCE_NUMBER_KEY;
import static com.azure.messaging.servicebus.implementation.ServiceBusConstants.SESSION_ID_KEY;
/**
* <p>An <b>asynchronous</b> receiver responsible for receiving {@link ServiceBusReceivedMessage messages} from an
* Azure Service Bus queue or topic/subscription.</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: Creating a {@link ServiceBusReceiverAsyncClient}</strong></p>
*
* <p>The following code sample demonstrates the creation of the asynchronous client
* {@link ServiceBusReceiverAsyncClient}. The {@code fullyQualifiedNamespace} is the Service Bus namespace's host name.
* It is listed under the "Essentials" panel after navigating to the Event Hubs Namespace via Azure Portal.
* The credential used is {@code DefaultAzureCredential} because it combines commonly used credentials in deployment
* and development and chooses the credential to used based on its running environment.
* {@link ServiceBusReceiveMode#PEEK_LOCK} (the default receive mode) and
* {@link ServiceBusClientBuilder.ServiceBusReceiverClientBuilder#disableAutoComplete() disableAutoComplete()} are
* <strong>strongly</strong> recommended so users have control over message settlement.</p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.instantiation -->
* <pre>
* TokenCredential credential = new DefaultAzureCredentialBuilder().build();
*
* // 'fullyQualifiedNamespace' will look similar to "{your-namespace}.servicebus.windows.net"
* // 'disableAutoComplete' indicates that users will explicitly settle their message.
* ServiceBusReceiverAsyncClient asyncReceiver = new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, credential)
* .receiver()
* .disableAutoComplete()
* .queueName(queueName)
* .buildAsyncClient();
*
* // When users are done with the receiver, dispose of the receiver.
* // Clients should be long-lived objects as they require resources
* // and time to establish a connection to the service.
* asyncReceiver.close();
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.instantiation -->
*
* <p><strong>Sample: Receive all messages from Service Bus resource</strong></p>
*
* <p>This returns an infinite stream of messages from Service Bus. The stream ends when the subscription is disposed
* or other terminal scenarios. See {@link #receiveMessages()} for more information.</p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.receiveMessages -->
* <pre>
* // Keep a reference to `subscription`. When the program is finished receiving messages, call
* // subscription.dispose(). This will stop fetching messages from the Service Bus.
* // Consider using Flux.usingWhen to scope the creation, usage, and cleanup of the receiver.
* Disposable subscription = asyncReceiver.receiveMessages()
* .flatMap(message -> {
* System.out.printf("Received Seq #: %s%n", message.getSequenceNumber());
* System.out.printf("Contents of message as string: %s%n", message.getBody());
*
* // Explicitly settle the message using complete, abandon, defer, dead-letter, etc.
* if (isMessageProcessed) {
* return asyncReceiver.complete(message);
* } else {
* return asyncReceiver.abandon(message);
* }
* })
* .subscribe(unused -> {
* }, error -> System.out.println("Error occurred: " + error),
* () -> System.out.println("Receiving complete."));
*
* // When program ends, or you're done receiving all messages, dispose of the receiver.
* // Clients should be long-lived objects as they
* // require resources and time to establish a connection to the service.
* asyncReceiver.close();
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.receiveMessages -->
*
* <p><strong>Sample: Receive messages in {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode from a Service Bus
* entity</strong></p>
*
* <p>The following code sample demonstrates the creation of the asynchronous client
* {@link ServiceBusReceiverAsyncClient} using {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE}. The
* {@code fullyQualifiedNamespace} is the Service Bus namespace's host name. It is listed under the "Essentials" panel
* after navigating to the Event Hubs Namespace via Azure Portal. The credential used is {@code DefaultAzureCredential}
* because it combines commonly used credentials in deployment and development and chooses the credential to used based
* on its running environment. See {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} docs for more information about
* receiving messages using this mode.</p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.receiveWithReceiveAndDeleteMode -->
* <pre>
* TokenCredential credential = new DefaultAzureCredentialBuilder().build();
*
* // Keep a reference to `subscription`. When the program is finished receiving messages, call
* // subscription.dispose(). This will stop fetching messages from the Service Bus.
* Disposable subscription = Flux.usingWhen(
* Mono.fromCallable(() -> {
* // Setting the receiveMode when creating the receiver enables receive and delete mode. By default,
* // peek lock mode is used. In peek lock mode, users are responsible for settling messages.
* return new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, credential)
* .receiver()
* .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE)
* .queueName(queueName)
* .buildAsyncClient();
* }), receiver -> {
* return receiver.receiveMessages();
* }, receiver -> {
* return Mono.fromRunnable(() -> receiver.close());
* })
* .subscribe(message -> {
* // Messages received in RECEIVE_AND_DELETE mode do not have to be settled because they are automatically
* // removed from the queue.
* System.out.printf("Received Seq #: %s%n", message.getSequenceNumber());
* System.out.printf("Contents of message as string: %s%n", message.getBody());
* },
* error -> System.out.println("Error occurred: " + error),
* () -> System.out.println("Receiving complete."));
*
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.receiveWithReceiveAndDeleteMode -->
*
* <p><strong>Sample: Receive messages from a specific session</strong></p>
*
* <p>To fetch messages from a specific session, switch to {@link ServiceBusSessionReceiverClientBuilder} and
* build the session receiver client. Use {@link ServiceBusSessionReceiverAsyncClient#acceptSession(String)} to create
* a session-bound {@link ServiceBusReceiverAsyncClient}. The sample assumes that Service Bus sessions were
* <a href="https://learn.microsoft.com/azure/service-bus-messaging/enable-message-sessions">enabled at the time of
* the queue creation</a>.</p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.instantiation#sessionId -->
* <pre>
* TokenCredential credential = new DefaultAzureCredentialBuilder().build();
*
* // 'fullyQualifiedNamespace' will look similar to "{your-namespace}.servicebus.windows.net"
* // 'disableAutoComplete' indicates that users will explicitly settle their message.
* ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, credential)
* .sessionReceiver()
* .disableAutoComplete()
* .queueName(sessionEnabledQueueName)
* .buildAsyncClient();
*
* // acceptSession(String) completes successfully with a receiver when "<<my-session-id>>" session is
* // successfully locked.
* // `Flux.usingWhen` is used, so we dispose of the receiver resource after `receiveMessages()` and the settlement
* // operations complete.
* // `Mono.usingWhen` can also be used if the resource closure returns a single item.
* Flux<Void> sessionMessages = Flux.usingWhen(
* sessionReceiver.acceptSession("<<my-session-id>>"),
* receiver -> {
* // Receive messages from <<my-session-id>> session.
* return receiver.receiveMessages().flatMap(message -> {
* System.out.printf("Received Sequence #: %s. Contents: %s%n", message.getSequenceNumber(),
* message.getBody());
*
* // Explicitly settle the message using complete, abandon, defer, dead-letter, etc.
* if (isMessageProcessed) {
* return receiver.complete(message);
* } else {
* return receiver.abandon(message);
* }
* });
* },
* receiver -> Mono.fromRunnable(() -> {
* // Dispose of resources.
* receiver.close();
* sessionReceiver.close();
* }));
*
* // When program ends, or you're done receiving all messages, the `subscription` can be disposed of. This code
* // is non-blocking and kicks off the operation.
* Disposable subscription = sessionMessages.subscribe(
* unused -> {
* }, error -> System.err.print("Error receiving message from session: " + error),
* () -> System.out.println("Completed receiving from session."));
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.instantiation#sessionId -->
*
* <p><strong>Sample: Receive messages from the first available session</strong></p>
*
* <p>To process messages from the first available session, switch to {@link ServiceBusSessionReceiverClientBuilder}
* and build the session receiver client. Use
* {@link ServiceBusSessionReceiverAsyncClient#acceptNextSession() acceptNextSession()} to find the first available
* session to process messages from.</p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.instantiation#nextsession -->
* <pre>
* TokenCredential credential = new DefaultAzureCredentialBuilder().build();
*
* // 'fullyQualifiedNamespace' will look similar to "{your-namespace}.servicebus.windows.net"
* // 'disableAutoComplete' indicates that users will explicitly settle their message.
* ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, credential)
* .sessionReceiver()
* .disableAutoComplete()
* .queueName(sessionEnabledQueueName)
* .buildAsyncClient();
*
* // Creates a client to receive messages from the first available session. It waits until
* // AmqpRetryOptions.getTryTimeout() elapses. If no session is available within that operation timeout, it
* // completes with a retriable error. Otherwise, a receiver is returned when a lock on the session is acquired.
* Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
*
* Flux<Void> receiveMessagesFlux = Flux.usingWhen(receiverMono,
* receiver -> receiver.receiveMessages().flatMap(message -> {
* System.out.println("Received message: " + message.getBody());
*
* // Explicitly settle the message via complete, abandon, defer, dead-letter, etc.
* if (isMessageProcessed) {
* return receiver.complete(message);
* } else {
* return receiver.abandon(message);
* }
* }),
* receiver -> Mono.fromRunnable(() -> {
* // Dispose of the receiver and sessionReceiver when done receiving messages.
* receiver.close();
* sessionReceiver.close();
* }));
*
* // This is a non-blocking call that moves onto the next line of code after setting up and starting the receive
* // operation. Customers can keep a reference to `subscription` and dispose of it when they want to stop
* // receiving messages.
* Disposable subscription = receiveMessagesFlux.subscribe(unused -> {
* }, error -> System.out.println("Error occurred: " + error),
* () -> System.out.println("Receiving complete."));
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.instantiation#nextsession -->
*
* <p><strong>Sample: Rate limiting consumption of messages from a Service Bus entity</strong></p>
*
* <p>For message receivers that need to limit the number of messages they receive at a given time, they can use
* {@link BaseSubscriber#request(long)}.</p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.receive#basesubscriber -->
* <pre>
* // This is a non-blocking call. The program will move to the next line of code after setting up the operation.
* asyncReceiver.receiveMessages().subscribe(new BaseSubscriber<ServiceBusReceivedMessage>() {
* private static final int NUMBER_OF_MESSAGES = 5;
* private final AtomicInteger currentNumberOfMessages = new AtomicInteger();
*
* @Override
* protected void hookOnSubscribe(Subscription subscription) {
* // Tell the Publisher we only want 5 message at a time.
* request(NUMBER_OF_MESSAGES);
* }
*
* @Override
* protected void hookOnNext(ServiceBusReceivedMessage message) {
* // Process the ServiceBusReceivedMessage
* // If the number of messages we have currently received is a multiple of 5, that means we have reached
* // the last message the Subscriber will provide to us. Invoking request(long) here, tells the Publisher
* // that the subscriber is ready to get more messages from upstream.
* if (currentNumberOfMessages.incrementAndGet() % 5 == 0) {
* request(NUMBER_OF_MESSAGES);
* }
* }
* });
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.receive#basesubscriber -->
*
* @see ServiceBusClientBuilder
* @see ServiceBusReceiverClient To communicate with a Service Bus resource using a synchronous client.
*/
@ServiceClient(builder = ServiceBusClientBuilder.class, isAsync = true)
public final class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final Duration EXPIRED_RENEWAL_CLEANUP_INTERVAL = Duration.ofMinutes(2);
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ConnectionCacheWrapper connectionCacheWrapper;
private final boolean isOnV2;
private final Mono<ServiceBusAmqpConnection> connectionProcessor;
private final ServiceBusReceiverInstrumentation instrumentation;
private final ServiceBusTracer tracer;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final IServiceBusSessionManager sessionManager;
private final boolean isSessionEnabled;
private final Semaphore completionLock = new Semaphore(1);
private final String identifier;
// Starting at -1 because that is before the beginning of the stream.
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
private final AutoCloseable trackSettlementSequenceNumber;
/**
* Creates a receiver that listens to a Service Bus resource.
*
* @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource.
* @param entityPath The name of the topic or queue.
* @param entityType The type of the Service Bus resource.
* @param receiverOptions Options when receiving messages.
* @param connectionCacheWrapper The AMQP connection to the Service Bus resource.
* @param instrumentation ServiceBus tracing and metrics helper
* @param messageSerializer Serializes and deserializes Service Bus messages.
* @param onClientClose Operation to run when the client completes.
*/
// Client to work with a non-session entity.
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ConnectionCacheWrapper connectionCacheWrapper, Duration cleanupInterval,
ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionCacheWrapper = Objects.requireNonNull(connectionCacheWrapper, "'connectionCacheWrapper' cannot be null.");
this.connectionProcessor = this.connectionCacheWrapper.getConnection();
this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.sessionManager = null;
if (receiverOptions.getSessionId() != null || receiverOptions.getMaxConcurrentSessions() != null) {
// Assert the internal invariant for above 'sessionManager = null' i.e, session-unaware call-sites should not set these options.
throw new IllegalStateException("Session-specific options are not expected to be present on a client for session unaware entity.");
}
this.isSessionEnabled = false;
this.isOnV2 = this.connectionCacheWrapper.isV2();
this.managementNodeLocks = new LockContainer<OffsetDateTime>(cleanupInterval);
final Consumer<LockRenewalOperation> onExpired = renewal -> {
LOGGER.atVerbose()
.addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken())
.addKeyValue("status", renewal.getStatus())
.log("Closing expired renewal operation.", renewal.getThrowable());
renewal.close();
};
this.renewalContainer = new LockContainer<LockRenewalOperation>(EXPIRED_RENEWAL_CLEANUP_INTERVAL, onExpired);
this.identifier = identifier;
this.tracer = instrumentation.getTracer();
this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber();
}
// Client to work with a session-enabled entity (client to receive from one-session (V1, V2) or receive from multiple-sessions (V1)).
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ConnectionCacheWrapper connectionCacheWrapper, Duration cleanupInterval,
ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose,
IServiceBusSessionManager sessionManager) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionCacheWrapper = Objects.requireNonNull(connectionCacheWrapper, "'connectionCacheWrapper' cannot be null.");
this.connectionProcessor = this.connectionCacheWrapper.getConnection();
this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null.");
this.isSessionEnabled = true;
this.isOnV2 = this.connectionCacheWrapper.isV2();
final boolean isV2SessionManager = this.sessionManager instanceof ServiceBusSingleSessionManager;
// Once side-by-side support for V1 is no longer needed, we'll directly use the "ServiceBusSingleSessionManager" type
// in the constructor and IServiceBusSessionManager interface will be deleted (so excuse the temporary 'I' prefix
// used to avoid type conflict with V1 ServiceBusSessionManager. The V1 ServiceBusSessionManager will also be deleted
// once side-by-side support is no longer needed).
if (isOnV2 ^ isV2SessionManager) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("For V2 Session, the manager should be ServiceBusSingleSessionManager, and ConnectionCache should be on V2."));
}
this.managementNodeLocks = new LockContainer<OffsetDateTime>(cleanupInterval);
final Consumer<LockRenewalOperation> onExpired = renewal -> {
LOGGER.atInfo()
.addKeyValue(SESSION_ID_KEY, renewal.getSessionId())
.addKeyValue("status", renewal.getStatus())
.log("Closing expired renewal operation.", renewal.getThrowable());
renewal.close();
};
this.renewalContainer = new LockContainer<LockRenewalOperation>(EXPIRED_RENEWAL_CLEANUP_INTERVAL, onExpired);
this.identifier = sessionManager.getIdentifier();
this.tracer = instrumentation.getTracer();
this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber();
}
/**
* Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to
* {@code {yournamespace}.servicebus.windows.net}.
*
* @return The fully qualified Service Bus namespace that the connection is associated with.
*/
public String getFullyQualifiedNamespace() {
return fullyQualifiedNamespace;
}
/**
* Gets the Service Bus resource this client interacts with.
*
* @return The Service Bus resource this client interacts with.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the SessionId of the session if this receiver is a session receiver.
*
* @return The SessionId or null if this is not a session receiver.
*/
public String getSessionId() {
return receiverOptions.getSessionId();
}
/**
* Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}.
*
* @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}.
*/
public String getIdentifier() {
return identifier;
}
/**
* Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing.
* Abandoning a message will increase the delivery count on the message.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
*
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from
* {@link ServiceBusReceiverAsyncClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if the message could not be abandoned.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
null, null);
}
/**
* Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the
* message available again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param options The options to set while abandoning the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
*
* @throws NullPointerException if {@code message} or {@code options} is null. Also if
* {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from
* {@link ServiceBusReceiverAsyncClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if the message could not be abandoned.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) {
if (Objects.isNull(options)) {
return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null."));
} else if (!Objects.isNull(options.getTransactionContext())
&& Objects.isNull(options.getTransactionContext().getTransactionId())) {
return monoError(LOGGER, new NullPointerException(
"'options.transactionContext.transactionId' cannot be null."));
}
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
options.getPropertiesToModify(), options.getTransactionContext());
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
*
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from
* {@link ServiceBusReceiverAsyncClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if the message could not be completed.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from
* the service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param options Options used to complete the message.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
*
* @throws NullPointerException if {@code message} or {@code options} is null. Also if
* {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from
* {@link ServiceBusReceiverAsyncClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if the message could not be completed.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) {
if (Objects.isNull(options)) {
return monoError(LOGGER, new NullPointerException("'options' cannot be null."));
} else if (!Objects.isNull(options.getTransactionContext())
&& Objects.isNull(options.getTransactionContext().getTransactionId())) {
return monoError(LOGGER, new NullPointerException(
"'options.transactionContext.transactionId' cannot be null."));
}
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, options.getTransactionContext());
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
*
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from
* {@link ServiceBusReceiverAsyncClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if the message could not be deferred.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-deferral">Message deferral</a>
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
null, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into
* the deferred sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param options Options used to defer the message.
*
* @return A {@link Mono} that completes when the defer operation finishes.
*
* @throws NullPointerException if {@code message} or {@code options} is null. Also if
* {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from
* {@link ServiceBusReceiverAsyncClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if the message could not be deferred.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-deferral">Message deferral</a>
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) {
if (Objects.isNull(options)) {
return monoError(LOGGER, new NullPointerException("'options' cannot be null."));
} else if (!Objects.isNull(options.getTransactionContext())
&& Objects.isNull(options.getTransactionContext().getTransactionId())) {
return monoError(LOGGER, new NullPointerException(
"'options.transactionContext.transactionId' cannot be null."));
}
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
options.getPropertiesToModify(), options.getTransactionContext());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
*
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from
* {@link ServiceBusReceiverAsyncClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if the message could not be dead-lettered.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
*
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/service-bus-dead-letter-queues">Dead letter
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param options Options used to dead-letter the message.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
*
* @throws NullPointerException if {@code message} or {@code options} is null. Also if
* {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from
* {@link ServiceBusReceiverAsyncClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if the message could not be dead-lettered.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
*
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/service-bus-dead-letter-queues">Dead letter
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) {
if (Objects.isNull(options)) {
return monoError(LOGGER, new NullPointerException("'options' cannot be null."));
} else if (!Objects.isNull(options.getTransactionContext())
&& Objects.isNull(options.getTransactionContext().getTransactionId())) {
return monoError(LOGGER, new NullPointerException(
"'options.transactionContext.transactionId' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(),
options.getDeadLetterErrorDescription(), options.getPropertiesToModify(),
options.getTransactionContext());
}
/**
* Gets the state of the session if this receiver is a session receiver.
*
* @return The session state or an empty Mono if there is no state set for the session.
* @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed.
* @throws ServiceBusException if the session state could not be acquired.
*/
public Mono<byte[]> getSessionState() {
return getSessionState(receiverOptions.getSessionId());
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if an error occurs while peeking at the message.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
public Mono<ServiceBusReceivedMessage> peekMessage() {
return peekMessage(receiverOptions.getSessionId());
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @throws IllegalStateException if the receiver is disposed.
* @throws ServiceBusException if an error occurs while peeking at the message.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
Mono<ServiceBusReceivedMessage> result = connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
LOGGER.atVerbose()
.addKeyValue(SEQUENCE_NUMBER_KEY, sequence)
.log("Peek message.");
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
LOGGER.atVerbose()
.addKeyValue(SEQUENCE_NUMBER_KEY, current)
.log("Updating last peeked sequence number.");
sink.next(message);
});
return tracer.traceManagementReceive("ServiceBus.peekMessage", result);
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
*
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if an error occurs while peeking at the message.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) {
return peekMessage(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if an error occurs while peeking at the message.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return tracer.traceManagementReceive("ServiceBus.peekMessage",
connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)))
.onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)));
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked.
*
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if an error occurs while peeking at messages.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return tracer.traceSyncReceive("ServiceBus.peekMessages",
peekMessages(maxMessages, receiverOptions.getSessionId()));
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if an error occurs while peeking at messages.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
if (maxMessages <= 0) {
return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive."));
}
return
connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch.");
return node
.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages)
.doOnNext(next -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, next.getSequenceNumber()));
LOGGER.atVerbose()
.addKeyValue(SEQUENCE_NUMBER_KEY, current)
.log("Last peeked sequence number in batch.");
});
})
.onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE));
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked.
*
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if an error occurs while peeking at messages.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) {
return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if an error occurs while peeking at messages.
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
if (maxMessages <= 0) {
return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive."));
}
return tracer.traceSyncReceive("ServiceBus.peekMessages",
connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages))
.onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)));
}
/**
* Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity.
* This Flux continuously receives messages from a Service Bus entity until either:
*
* <ul>
* <li>The receiver is closed.</li>
* <li>The subscription to the Flux is disposed.</li>
* <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux#take(long)} or
* {@link Flux#take(Duration)}).</li>
* <li>An {@link AmqpException} occurs that causes the receive link to stop.</li>
* </ul>
*
* <p>
* The client uses an AMQP link underneath to receive the messages; the client will transparently transition to
* a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable error
* or exhausts the retries, the Subscriber's {@link org.reactivestreams.Subscriber#onError(Throwable)} terminal handler
* will be notified with this error. No further messages will be delivered to {@link org.reactivestreams.Subscriber#onNext(Object)}
* after the terminal event; the application must create a new client to resume the receive. Re-subscribing to the Flux
* of the old client will have no effect.
* </p>
* <p>
* Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not
* exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR.
* These are certain events where the Service Bus communicates to the client that a non-retriable error occurred.
* </p>
*
* @return An <b>infinite</b> stream of messages from the Service Bus entity.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if an error occurs while receiving messages.
*/
public Flux<ServiceBusReceivedMessage> receiveMessages() {
if (isDisposed.get()) {
return fluxError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages")));
}
if (isOnV2) {
if (isSessionEnabled) {
return sessionReactiveReceiveV2();
} else {
return nonSessionReactiveReceiveV2();
}
}
// Without limitRate(), if the user calls receiveMessages().subscribe(), it will call
// ServiceBusReceiveLinkProcessor.request(long request) where request = Long.MAX_VALUE.
// We turn this one-time non-backpressure request to continuous requests with backpressure.
// If receiverOptions.prefetchCount is set to non-zero, it will be passed to ServiceBusReceiveLinkProcessor
// to auto-refill the prefetch buffer. A request will retrieve one message from this buffer.
// If receiverOptions.prefetchCount is 0 (default value),
// the request will add a link credit so one message is retrieved from the service.
return receiveMessagesNoBackPressure().limitRate(1, 0);
}
@SuppressWarnings("try")
Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() {
return receiveMessagesWithContext(0)
.handle((serviceBusMessageContext, sink) -> {
if (serviceBusMessageContext.hasError()) {
sink.error(serviceBusMessageContext.getThrowable());
return;
}
sink.next(serviceBusMessageContext.getMessage());
});
}
/**
* Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity.
* This Flux continuously receives messages from a Service Bus entity until either:
*
* <ul>
* <li>The receiver is closed.</li>
* <li>The subscription to the Flux is disposed.</li>
* <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux#take(long)} or
* {@link Flux#take(Duration)}).</li>
* <li>An {@link AmqpException} occurs that causes the receive link to stop.</li>
* </ul>
*
* @return An <b>infinite</b> stream of messages from the Service Bus entity.
*/
Flux<ServiceBusMessageContext> receiveMessagesWithContext() {
return receiveMessagesWithContext(1);
}
private Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) {
final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null