/
ServiceBusReceiverClient.java
851 lines (786 loc) · 44.2 KB
/
ServiceBusReceiverClient.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.servicebus;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.util.IterableStream;
import com.azure.core.util.logging.ClientLogger;
import com.azure.messaging.servicebus.ServiceBusClientBuilder.ServiceBusReceiverClientBuilder;
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.publisher.Flux;
import reactor.core.publisher.Sinks;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import static com.azure.messaging.servicebus.implementation.ServiceBusConstants.LOCK_TOKEN_KEY;
import static com.azure.messaging.servicebus.implementation.ServiceBusConstants.SESSION_ID_KEY;
import static com.azure.messaging.servicebus.implementation.ServiceBusConstants.WORK_ID_KEY;
/**
* A <b>synchronous</b> receiver responsible for receiving {@link ServiceBusReceivedMessage} from a specific queue or
* topic on Azure Service Bus.
*
* <p><strong>Create an instance of receiver</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.instantiation -->
* <pre>
* // The required parameters is connectionString, a way to authenticate with Service Bus using credentials.
* // The connectionString/queueName must be set by the application. The 'connectionString' format is shown below.
* // "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}"
* ServiceBusReceiverClient receiver = new ServiceBusClientBuilder()
* .connectionString(connectionString)
* .receiver()
* .queueName(queueName)
* .buildClient();
*
* // Use the receiver and finally close it.
* receiver.close();
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.instantiation -->
*
* @see ServiceBusClientBuilder
* @see ServiceBusReceiverAsyncClient To communicate with a Service Bus resource using an asynchronous client.
*/
@ServiceClient(builder = ServiceBusClientBuilder.class)
public final class ServiceBusReceiverClient implements AutoCloseable {
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverClient.class);
private final AtomicInteger idGenerator = new AtomicInteger();
private final ServiceBusReceiverAsyncClient asyncClient;
private final Duration operationTimeout;
private final boolean isPrefetchDisabled;
/* To hold each receive work item to be processed.*/
private final AtomicReference<SynchronousMessageSubscriber> synchronousMessageSubscriber = new AtomicReference<>();
/* To ensure synchronousMessageSubscriber is subscribed only once. */
private final AtomicBoolean syncSubscribed = new AtomicBoolean(false);
private final ServiceBusTracer tracer;
/**
* Creates a synchronous receiver given its asynchronous counterpart.
*
* @param asyncClient Asynchronous receiver.
* @param isPrefetchDisabled Indicates if the prefetch is disabled.
* @param operationTimeout Timeout to wait for operation to complete.
*/
ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient,
boolean isPrefetchDisabled,
Duration operationTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null.");
this.isPrefetchDisabled = isPrefetchDisabled;
this.tracer = asyncClient.getInstrumentation().getTracer();
}
/**
* 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 asyncClient.getFullyQualifiedNamespace();
}
/**
* Gets the Service Bus resource this client interacts with.
*
* @return The Service Bus resource this client interacts with.
*/
public String getEntityPath() {
return asyncClient.getEntityPath();
}
/**
* 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 asyncClient.getSessionId();
}
/**
* Gets the identifier of the instance of {@link ServiceBusReceiverClient}.
*
* @return The identifier that can identify the instance of {@link ServiceBusReceiverClient}.
*/
public String getIdentifier() {
return asyncClient.getIdentifier();
}
/**
* 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.
*
* @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 ServiceBusReceiverClient#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 void abandon(ServiceBusReceivedMessage message) {
asyncClient.abandon(message).block(operationTimeout);
}
/**
* Abandons a {@link ServiceBusReceivedMessage message} and 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.
*
* @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 ServiceBusReceiverClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
* @throws ServiceBusException if the message could not be abandoned.
*/
public void abandon(ServiceBusReceivedMessage message, AbandonOptions options) {
asyncClient.abandon(message, options).block(operationTimeout);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
*
* @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 ServiceBusReceiverClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
* @throws ServiceBusException if the message could not be completed.
*/
public void complete(ServiceBusReceivedMessage message) {
asyncClient.complete(message).block(operationTimeout);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. 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.
*
* @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 ServiceBusReceiverClient#peekMessage() peekMessage}.
* @throws IllegalStateException if receiver is already disposed.
* @throws IllegalArgumentException if the message has either been deleted or already settled.
* @throws ServiceBusException if the message could not be completed.
*/
public void complete(ServiceBusReceivedMessage message, CompleteOptions options) {
asyncClient.complete(message, options).block(operationTimeout);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
*
* @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 ServiceBusReceiverClient#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 void defer(ServiceBusReceivedMessage message) {
asyncClient.defer(message).block(operationTimeout);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. 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.
*
* @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 ServiceBusReceiverClient#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 void defer(ServiceBusReceivedMessage message, DeferOptions options) {
asyncClient.defer(message, options).block(operationTimeout);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
*
* @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 ServiceBusReceiverClient#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 void deadLetter(ServiceBusReceivedMessage message) {
asyncClient.deadLetter(message).block(operationTimeout);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with dead-letter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param options Options used to dead-letter the message.
*
* @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 ServiceBusReceiverClient#peekMessage() peekMessage}.
* @throws IllegalStateException if the receiver is already disposed of.
* @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 void deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) {
asyncClient.deadLetter(message, options).block(operationTimeout);
}
/**
* Gets the state of the session if this receiver is a session receiver.
*
* @return The session state or null if there is no state set for the session.
*
* @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed.
* @throws ServiceBusException if the session state could not be acquired.
*/
public byte[] getSessionState() {
return asyncClient.getSessionState().block(operationTimeout);
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peekMessage()} 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 the 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 ServiceBusReceivedMessage peekMessage() {
return this.peekMessage(asyncClient.getReceiverOptions().getSessionId());
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peekMessage()} 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 receiver is already disposed or the receiver is a non-session receiver.
* @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>
*/
ServiceBusReceivedMessage peekMessage(String sessionId) {
return asyncClient.peekMessage(sessionId).block(operationTimeout);
}
/**
* 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 the 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 ServiceBusReceivedMessage peekMessage(long sequenceNumber) {
return this.peekMessage(sequenceNumber, asyncClient.getReceiverOptions().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>
*/
ServiceBusReceivedMessage peekMessage(long sequenceNumber, String sessionId) {
return asyncClient.peekMessage(sequenceNumber, sessionId).block(operationTimeout);
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The maximum number of messages to peek.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked.
*
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @throws IllegalStateException if the 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 IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return this.peekMessages(maxMessages, asyncClient.getReceiverOptions().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 the message.
*
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (maxMessages <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages));
}
final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.peekMessages",
asyncClient.peekMessages(maxMessages, sessionId).timeout(operationTimeout));
return fromFluxAndSubscribe(messages);
}
/**
* 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 An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} peeked.
*
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @throws IllegalStateException if the 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 IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) {
return this.peekMessages(maxMessages, sequenceNumber, asyncClient.getReceiverOptions().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 the message.
*
* @see <a href="https://docs.microsoft.com/azure/service-bus-messaging/message-browsing">Message browsing</a>
*/
IterableStream<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) {
if (maxMessages <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages));
}
final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.peekMessages",
asyncClient.peekMessages(maxMessages, sequenceNumber, sessionId).timeout(operationTimeout));
return fromFluxAndSubscribe(messages);
}
/**
* Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. The
* receive operation will wait for a default 1 minute for receiving a message before it times out. You can
* override it by using {@link #receiveMessages(int, Duration)}.
*
* <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 iteration (e.g., forEach) on the {@link IterableStream} returned by the further
* invocations of receiveMessages API will throw the error to the application. Once the application receives
* this error, the application should reset the client, i.e., close the current {@link ServiceBusReceiverClient}
* and create a new client to continue receiving messages.
* </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>
*
* @param maxMessages The maximum number of messages to receive.
*
* @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity.
*
* @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value.
* @throws IllegalStateException if the receiver is already disposed.
* @throws ServiceBusException if an error occurs while receiving messages.
*
* @see <a href="https://aka.ms/azsdk/java/servicebus/sync-receive/prefetch">Synchronous receive and prefetch</a>
*/
public IterableStream<ServiceBusReceivedMessage> receiveMessages(int maxMessages) {
return receiveMessages(maxMessages, operationTimeout);
}
/**
* Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. The
* default receive mode is {@link ServiceBusReceiveMode#PEEK_LOCK } unless it is changed during creation of {@link
* ServiceBusReceiverClient} using {@link ServiceBusReceiverClientBuilder#receiveMode(ServiceBusReceiveMode)}.
*
* <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 iteration (e.g., forEach) on the {@link IterableStream} returned by the further
* invocations of receiveMessages API will throw the error to the application. Once the application receives
* this error, the application should reset the client, i.e., close the current {@link ServiceBusReceiverClient}
* and create a new client to continue receiving messages.
* </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>
*
* @param maxMessages The maximum number of messages to receive.
* @param maxWaitTime The time the client waits for receiving a message before it times out.
*
* @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity.
*
* @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value.
* @throws IllegalStateException if the receiver is already disposed.
* @throws NullPointerException if {@code maxWaitTime} is null.
* @throws ServiceBusException if an error occurs while receiving messages.
* @see <a href="https://aka.ms/azsdk/java/servicebus/sync-receive/prefetch">Synchronous receive and prefetch</a>
*/
public IterableStream<ServiceBusReceivedMessage> receiveMessages(int maxMessages, Duration maxWaitTime) {
if (maxMessages <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages));
} else if (Objects.isNull(maxWaitTime)) {
throw LOGGER.logExceptionAsError(
new NullPointerException("'maxWaitTime' cannot be null."));
} else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime));
}
// There are two subscribers to this emitter. One is the timeout between messages subscription in
// SynchronousReceiverWork.start() and the other is the IterableStream(emitter.asFlux());
// Since the subscriptions may happen at different times, we want to replay results to downstream subscribers.
final Sinks.Many<ServiceBusReceivedMessage> emitter = Sinks.many().replay().all();
queueWork(maxMessages, maxWaitTime, emitter);
final Flux<ServiceBusReceivedMessage> messagesFlux = tracer.traceSyncReceive("ServiceBus.receiveMessages", emitter.asFlux());
// messagesFlux is already a hot publisher, so it's ok to subscribe
messagesFlux.subscribe();
return new IterableStream<>(messagesFlux);
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage#getSequenceNumber() sequence number} of the
* message.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if deferred message cannot be received.
*/
public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) {
return this.receiveDeferredMessage(sequenceNumber, asyncClient.getReceiverOptions().getSessionId());
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage#getSequenceNumber() sequence number} of the
* message.
* @param sessionId Session id of the deferred message.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if deferred message cannot be received.
*/
ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) {
return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout);
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
*
* @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}.
*
* @throws NullPointerException if {@code sequenceNumbers} is null.
* @throws IllegalStateException if receiver is already disposed.
* @throws ServiceBusException if deferred messages cannot be received.
*/
public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) {
return this.receiveDeferredMessageBatch(sequenceNumbers, asyncClient.getReceiverOptions().getSessionId());
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
* @param sessionId Session id of the deferred messages. {@code null} if there is no session.
*
* @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}.
*
* @throws IllegalStateException if receiver is already disposed.
* @throws NullPointerException if {@code sequenceNumbers} is null.
* @throws ServiceBusException if deferred message cannot be received.
*/
IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers,
String sessionId) {
final Flux<ServiceBusReceivedMessage> messages = tracer.traceSyncReceive("ServiceBus.receiveDeferredMessageBatch",
asyncClient.receiveDeferredMessages(sequenceNumbers, sessionId).timeout(operationTimeout));
return fromFluxAndSubscribe(messages);
}
/**
* Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity.
* When a message is received in {@link ServiceBusReceiveMode#PEEK_LOCK} mode, the message is locked on the
* server for this receiver instance for a duration as specified during the Queue creation (LockDuration). If
* processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal,
* the lock is reset to the entity's LockDuration value.
*
* @param message The {@link ServiceBusReceivedMessage} to perform lock renewal.
*
* @return The new expiration time for the message.
*
* @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null.
* @throws UnsupportedOperationException if the receiver was opened in
* {@link ServiceBusReceiveMode#RECEIVE_AND_DELETE} mode or if the message was received from peekMessage.
* @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed.
* @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value.
*/
public OffsetDateTime renewMessageLock(ServiceBusReceivedMessage message) {
return asyncClient.renewMessageLock(message).block(operationTimeout);
}
/**
* Starts the auto lock renewal for a message with the given lock.
*
* @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
* @param onError A function to call when an error occurs during lock renewal.
*
* @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or
* {@code maxLockRenewalDuration} is null.
* @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed.
* @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value.
* @throws ServiceBusException If the message cannot be renewed.
*/
public void renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration,
Consumer<Throwable> onError) {
final String lockToken = message != null ? message.getLockToken() : "null";
final Consumer<Throwable> throwableConsumer = onError != null
? onError
: error -> LOGGER.atWarning().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Exception occurred while renewing lock token.", error);
asyncClient.renewMessageLock(message, maxLockRenewalDuration).subscribe(
v -> LOGGER.atVerbose().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Completed renewing lock token."),
throwableConsumer,
() -> LOGGER.atVerbose().addKeyValue(LOCK_TOKEN_KEY, lockToken).log("Auto message lock renewal operation completed"));
}
/**
* Sets the state of the session if this receiver is a session receiver.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed.
* @throws ServiceBusException if the session lock cannot be renewed.
*/
public OffsetDateTime renewSessionLock() {
return asyncClient.renewSessionLock().block(operationTimeout);
}
/**
* Starts the auto lock renewal for the session that this receiver works for.
*
* @param maxLockRenewalDuration Maximum duration to keep renewing the session.
* @param onError A function to call when an error occurs during lock renewal.
*
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
* @throws ServiceBusException if the session lock renewal operation cannot be started.
*/
public void renewSessionLock(Duration maxLockRenewalDuration, Consumer<Throwable> onError) {
this.renewSessionLock(asyncClient.getReceiverOptions().getSessionId(), maxLockRenewalDuration, onError);
}
/**
* Sets the state of the session if this receiver is a session receiver.
*
* @param sessionState State to set on the session.
*
* @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed.
* @throws ServiceBusException if the session state cannot be set.
*/
public void setSessionState(byte[] sessionState) {
asyncClient.setSessionState(sessionState).block(operationTimeout);
}
/**
* Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along to all
* operations that need to be in this transaction.
*
* <p><strong>Creating and using a transaction</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction#servicebustransactioncontext -->
* <pre>
* ServiceBusTransactionContext transaction = receiver.createTransaction();
*
* // Process messages and associate operations with the transaction.
* ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage(sequenceNumber);
* receiver.complete(deferredMessage, new CompleteOptions().setTransactionContext(transaction));
* receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction));
* receiver.commitTransaction(transaction);
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction#servicebustransactioncontext -->
*
* @return A new {@link ServiceBusTransactionContext}.
*
* @throws IllegalStateException if the receiver is already disposed.
* @throws ServiceBusException if a transaction cannot be created.
*/
public ServiceBusTransactionContext createTransaction() {
return asyncClient.createTransaction().block(operationTimeout);
}
/**
* Commits the transaction and all the operations associated with it.
*
* <p><strong>Creating and using a transaction</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction#servicebustransactioncontext -->
* <pre>
* ServiceBusTransactionContext transaction = receiver.createTransaction();
*
* // Process messages and associate operations with the transaction.
* ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage(sequenceNumber);
* receiver.complete(deferredMessage, new CompleteOptions().setTransactionContext(transaction));
* receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction));
* receiver.commitTransaction(transaction);
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction#servicebustransactioncontext -->
*
* @param transactionContext The transaction to be commit.
*
* @throws IllegalStateException if the receiver is already disposed.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
* @throws ServiceBusException if the transaction could not be committed.
*/
public void commitTransaction(ServiceBusTransactionContext transactionContext) {
asyncClient.commitTransaction(transactionContext).block(operationTimeout);
}
/**
* Rollbacks the transaction given and all operations associated with it.
*
* <p><strong>Creating and using a transaction</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverclient.committransaction#servicebustransactioncontext -->
* <pre>
* ServiceBusTransactionContext transaction = receiver.createTransaction();
*
* // Process messages and associate operations with the transaction.
* ServiceBusReceivedMessage deferredMessage = receiver.receiveDeferredMessage(sequenceNumber);
* receiver.complete(deferredMessage, new CompleteOptions().setTransactionContext(transaction));
* receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction));
* receiver.commitTransaction(transaction);
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebusreceiverclient.committransaction#servicebustransactioncontext -->
*
* @param transactionContext The transaction to be rollback.
*
* @throws IllegalStateException if the receiver is already disposed.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
* @throws ServiceBusException if the transaction could not be rolled back.
*/
public void rollbackTransaction(ServiceBusTransactionContext transactionContext) {
asyncClient.rollbackTransaction(transactionContext).block(operationTimeout);
}
/**
* Disposes of the consumer by closing the underlying links to the service.
*/
@Override
public void close() {
SynchronousMessageSubscriber messageSubscriber = synchronousMessageSubscriber.get();
if (messageSubscriber != null && !messageSubscriber.isDisposed()) {
messageSubscriber.dispose();
}
asyncClient.close();
}
/**
* Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus
* entity.
*/
private void queueWork(int maximumMessageCount, Duration maxWaitTime,
Sinks.Many<ServiceBusReceivedMessage> emitter) {
final long id = idGenerator.getAndIncrement();
final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter);
SynchronousMessageSubscriber messageSubscriber = synchronousMessageSubscriber.get();
if (messageSubscriber != null) {
messageSubscriber.queueWork(work);
return;
}
messageSubscriber = synchronousMessageSubscriber.updateAndGet(subscriber -> {
// Ensuring we create SynchronousMessageSubscriber only once.
if (subscriber == null) {
return new SynchronousMessageSubscriber(asyncClient,
work,
isPrefetchDisabled,
operationTimeout);
} else {
return subscriber;
}
});
// NOTE: We asynchronously send the credit to the service as soon as receiveMessage() API is called (for first
// time).
// This means that there may be messages internally buffered before users start iterating the IterableStream.
// If users do not iterate through the stream and their lock duration expires, it is possible that the
// Service Bus message's delivery count will be incremented.
if (!syncSubscribed.getAndSet(true)) {
// The 'subscribeWith' has side effects hence must not be called from
// the above updateFunction of AtomicReference::updateAndGet.
asyncClient.receiveMessagesNoBackPressure().subscribeWith(messageSubscriber);
} else {
messageSubscriber.queueWork(work);
}
LOGGER.atVerbose()
.addKeyValue(WORK_ID_KEY, work.getId())
.log("Receive request queued up.");
}
void renewSessionLock(String sessionId, Duration maxLockRenewalDuration, Consumer<Throwable> onError) {
final Consumer<Throwable> throwableConsumer = onError != null
? onError
: error -> LOGGER.atWarning().addKeyValue(SESSION_ID_KEY, sessionId).log("Exception occurred while renewing session.", error);
asyncClient.renewSessionLock(maxLockRenewalDuration).subscribe(
v -> LOGGER.atVerbose().addKeyValue(SESSION_ID_KEY, sessionId).log("Completed renewing session"),
throwableConsumer,
() -> LOGGER.atVerbose().addKeyValue(SESSION_ID_KEY, sessionId).log("Auto session lock renewal operation completed."));
}
private <T> IterableStream<T> fromFluxAndSubscribe(Flux<T> flux) {
Flux<T> cached = flux.cache();
// Subscribe to message flux so we can kick off this operation
cached.subscribe();
return new IterableStream<>(cached);
}
}