forked from Azure/azure-sdk-for-java
/
CoreMessageReceiver.java
1523 lines (1389 loc) · 66 KB
/
CoreMessageReceiver.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. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package com.microsoft.azure.servicebus.primitives;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedInteger;
import org.apache.qpid.proton.amqp.messaging.Accepted;
import org.apache.qpid.proton.amqp.messaging.AmqpValue;
import org.apache.qpid.proton.amqp.messaging.Modified;
import org.apache.qpid.proton.amqp.messaging.Outcome;
import org.apache.qpid.proton.amqp.messaging.Rejected;
import org.apache.qpid.proton.amqp.messaging.Released;
import org.apache.qpid.proton.amqp.messaging.Source;
import org.apache.qpid.proton.amqp.messaging.Target;
import org.apache.qpid.proton.amqp.transport.DeliveryState;
import org.apache.qpid.proton.amqp.transport.ErrorCondition;
import org.apache.qpid.proton.amqp.transport.ReceiverSettleMode;
import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
import org.apache.qpid.proton.engine.BaseHandler;
import org.apache.qpid.proton.engine.Connection;
import org.apache.qpid.proton.engine.Delivery;
import org.apache.qpid.proton.engine.EndpointState;
import org.apache.qpid.proton.engine.Receiver;
import org.apache.qpid.proton.engine.Session;
import org.apache.qpid.proton.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microsoft.azure.servicebus.amqp.DispatchHandler;
import com.microsoft.azure.servicebus.amqp.IAmqpReceiver;
import com.microsoft.azure.servicebus.amqp.ReceiveLinkHandler;
import com.microsoft.azure.servicebus.amqp.SessionHandler;
/*
* Common Receiver that abstracts all amqp related details
* translates event-driven reactor model into async receive Api
*/
// TODO Take a re-look at the choice of collections used. Some of them are overkill may be.
public class CoreMessageReceiver extends ClientEntity implements IAmqpReceiver, IErrorContextProvider
{
private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(CoreMessageReceiver.class);
private static final Duration LINK_REOPEN_TIMEOUT = Duration.ofMinutes(5); // service closes link long before this timeout expires
private static final Duration RETURN_MESSAGES_DAEMON_WAKE_UP_INTERVAL = Duration.ofMillis(1); // Wakes up every 1 millisecond
private static final Duration UPDATE_STATE_REQUESTS_DAEMON_WAKE_UP_INTERVAL = Duration.ofMillis(500); // Wakes up every 500 milliseconds
private static final Duration ZERO_TIMEOUT_APPROXIMATION = Duration.ofMillis(200);
private static final int CREDIT_FLOW_BATCH_SIZE = 50;// Arbitrarily chosen 50 to avoid sending too many flows in case prefetch count is large
private final Object requestResonseLinkCreationLock = new Object();
private final ConcurrentLinkedQueue<ReceiveWorkItem> pendingReceives;
private final ConcurrentHashMap<String, UpdateStateWorkItem> pendingUpdateStateRequests;
private final ConcurrentHashMap<String, Delivery> tagsToDeliveriesMap;
private final MessagingFactory underlyingFactory;
private final String receivePath;
private final String sasTokenAudienceURI;
private final Duration operationTimeout;
private final CompletableFuture<Void> linkClose;
private final Object prefetchCountSync;
private final SettleModePair settleModePair;
private final RetryPolicy retryPolicy;
private int prefetchCount;
private String sessionId;
private boolean isSessionReceiver;
private boolean isBrowsableSession;
private Instant sessionLockedUntilUtc;
private boolean isSessionLockLost;
private ConcurrentLinkedQueue<MessageWithDeliveryTag> prefetchedMessages;
private Receiver receiveLink;
private RequestResponseLink requestResponseLink;
private WorkItem<CoreMessageReceiver> linkOpen;
private Duration factoryRceiveTimeout;
private Exception lastKnownLinkError;
private Instant lastKnownErrorReportedAt;
private final AtomicInteger creditToFlow;
private final AtomicInteger creditNeededtoServePendingReceives;
private final AtomicInteger currentPrefetechedMessagesCount; // size() on concurrentlinkedqueue is o(n) operation
private ScheduledFuture<?> sasTokenRenewTimerFuture;
private CompletableFuture<Void> requestResponseLinkCreationFuture;
private CompletableFuture<Void> receiveLinkReopenFuture;
private final Runnable timedOutUpdateStateRequestsDaemon;
private final Runnable returnMesagesLoopDaemon;
private final ScheduledFuture<?> updateStateRequestsTimeoutChecker;
private final ScheduledFuture<?> returnMessagesLoopRunner;
// TODO Change onReceiveComplete to handle empty deliveries. Change onError to retry updateState requests.
private CoreMessageReceiver(final MessagingFactory factory,
final String name,
final String recvPath,
final String sessionId,
final int prefetchCount,
final SettleModePair settleModePair)
{
super(name, factory);
this.underlyingFactory = factory;
this.operationTimeout = factory.getOperationTimeout();
this.receivePath = recvPath;
this.sasTokenAudienceURI = String.format(ClientConstants.SAS_TOKEN_AUDIENCE_FORMAT, factory.getHostName(), recvPath);
this.sessionId = sessionId;
this.isSessionReceiver = false;
this.isBrowsableSession = false;
this.prefetchCount = prefetchCount;
this.settleModePair = settleModePair;
this.prefetchedMessages = new ConcurrentLinkedQueue<MessageWithDeliveryTag>();
this.linkClose = new CompletableFuture<Void>();
this.lastKnownLinkError = null;
this.factoryRceiveTimeout = factory.getOperationTimeout();
this.prefetchCountSync = new Object();
this.retryPolicy = factory.getRetryPolicy();
this.pendingReceives = new ConcurrentLinkedQueue<ReceiveWorkItem>();
this.pendingUpdateStateRequests = new ConcurrentHashMap<>();
this.tagsToDeliveriesMap = new ConcurrentHashMap<>();
this.lastKnownErrorReportedAt = Instant.now();
this.receiveLinkReopenFuture = null;
this.creditToFlow = new AtomicInteger();
this.creditNeededtoServePendingReceives = new AtomicInteger();
this.currentPrefetechedMessagesCount = new AtomicInteger();
this.timedOutUpdateStateRequestsDaemon = new Runnable() {
@Override
public void run() {
try
{
TRACE_LOGGER.trace("Starting '{}' core message receiver's internal loop to complete timed out update state requests.", CoreMessageReceiver.this.receivePath);
for(Map.Entry<String, UpdateStateWorkItem> entry : CoreMessageReceiver.this.pendingUpdateStateRequests.entrySet())
{
Duration remainingTime = entry.getValue().getTimeoutTracker().remaining();
if(remainingTime.isZero() || remainingTime.isNegative())
{
CoreMessageReceiver.this.pendingUpdateStateRequests.remove(entry.getKey());
Exception exception = entry.getValue().getLastKnownException();
if(exception == null)
{
exception = new TimeoutException("Request timed out.");
}
TRACE_LOGGER.error("UpdateState request timed out. Delivery:{}", entry.getKey(), exception);
entry.getValue().getWork().completeExceptionally(exception);
}
}
TRACE_LOGGER.trace("'{}' core message receiver's internal loop to complete timed out update state requests stopped.", CoreMessageReceiver.this.receivePath);
}
catch(Throwable e)
{
// Shouldn't throw any exception for the executor to run multiple times.. Should never come here
}
}
};
// CONTRACT: message should be delivered to the caller of MessageReceiver.receive() only from prefetched messages
this.returnMesagesLoopDaemon = new Runnable() {
@Override
public void run() {
try
{
TRACE_LOGGER.trace("Starting '{}' core message receiver's internal loop to return messages to waiting clients.", CoreMessageReceiver.this.receivePath);
while(!CoreMessageReceiver.this.prefetchedMessages.isEmpty())
{
ReceiveWorkItem currentReceive = CoreMessageReceiver.this.pendingReceives.poll();
if (currentReceive != null)
{
if(!currentReceive.getWork().isDone())
{
TRACE_LOGGER.debug("Returning the message received from '{}' to a pending receive request", CoreMessageReceiver.this.receivePath);
currentReceive.cancelTimeoutTask(false);
List<MessageWithDeliveryTag> messages = CoreMessageReceiver.this.receiveCore(currentReceive.getMaxMessageCount());
CoreMessageReceiver.this.reduceCreditForCompletedReceiveRequest(currentReceive.getMaxMessageCount());
AsyncUtil.completeFuture(currentReceive.getWork(), messages);
}
}
else
{
break;
}
}
TRACE_LOGGER.trace("'{}' core message receiver's internal loop to return messages to waiting clients stopped.", CoreMessageReceiver.this.receivePath);
}
catch(Throwable e)
{
// Shouldn't throw any exception for the executor to run multiple times.. Should never come here
}
}
};
// As all update state requests have the same timeout, one timer is better than having one timer per request
this.updateStateRequestsTimeoutChecker = Timer.schedule(timedOutUpdateStateRequestsDaemon, CoreMessageReceiver.UPDATE_STATE_REQUESTS_DAEMON_WAKE_UP_INTERVAL, TimerType.RepeatRun);
// Scheduling it as a separate thread that wakes up at regular very short intervals.. Doesn't wait on incoming receive requests from callers or incoming deliveries from reactor
this.returnMessagesLoopRunner = Timer.schedule(returnMesagesLoopDaemon, CoreMessageReceiver.RETURN_MESSAGES_DAEMON_WAKE_UP_INTERVAL, TimerType.RepeatRun);
}
// Connection has to be associated with Reactor before Creating a receiver on it.
public static CompletableFuture<CoreMessageReceiver> create(
final MessagingFactory factory,
final String name,
final String recvPath,
final int prefetchCount,
final SettleModePair settleModePair)
{
TRACE_LOGGER.info("Creating core message receiver to '{}'", recvPath);
CoreMessageReceiver msgReceiver = new CoreMessageReceiver(
factory,
name,
recvPath,
null,
prefetchCount,
settleModePair);
return msgReceiver.createLink();
}
public static CompletableFuture<CoreMessageReceiver> create(
final MessagingFactory factory,
final String name,
final String recvPath,
final String sessionId,
final boolean isBrowsableSession,
final int prefetchCount,
final SettleModePair settleModePair)
{
TRACE_LOGGER.info("Creating core session receiver to '{}', sessionId '{}', browseonly session '{}'", recvPath, sessionId, isBrowsableSession);
CoreMessageReceiver msgReceiver = new CoreMessageReceiver(
factory,
name,
recvPath,
sessionId,
prefetchCount,
settleModePair);
msgReceiver.isSessionReceiver = true;
msgReceiver.isBrowsableSession = isBrowsableSession;
return msgReceiver.createLink();
}
private CompletableFuture<CoreMessageReceiver> createLink()
{
this.linkOpen = new WorkItem<CoreMessageReceiver>(new CompletableFuture<CoreMessageReceiver>(), this.operationTimeout);
this.scheduleLinkOpenTimeout(this.linkOpen.getTimeoutTracker());
this.sendSASTokenAndSetRenewTimer(false).handleAsync((v, sasTokenEx) -> {
if(sasTokenEx != null)
{
Throwable cause = ExceptionUtil.extractAsyncCompletionCause(sasTokenEx);
TRACE_LOGGER.error("Sending SAS Token failed. ReceivePath:{}", this.receivePath, cause);
AsyncUtil.completeFutureExceptionally(this.linkOpen.getWork(), cause);
}
else
{
try
{
this.underlyingFactory.scheduleOnReactorThread(new DispatchHandler()
{
@Override
public void onEvent()
{
CoreMessageReceiver.this.createReceiveLink();
}
});
}
catch (IOException ioException)
{
this.cancelSASTokenRenewTimer();
AsyncUtil.completeFutureExceptionally(this.linkOpen.getWork(), new ServiceBusException(false, "Failed to create Receiver, see cause for more details.", ioException));
}
}
return null;
});
return this.linkOpen.getWork();
}
private CompletableFuture<Void> createRequestResponseLinkAsync()
{
synchronized (this.requestResonseLinkCreationLock) {
if(this.requestResponseLinkCreationFuture == null)
{
this.requestResponseLinkCreationFuture = new CompletableFuture<Void>();
this.underlyingFactory.obtainRequestResponseLinkAsync(this.receivePath).handleAsync((rrlink, ex) ->
{
if(ex == null)
{
this.requestResponseLink = rrlink;
this.requestResponseLinkCreationFuture.complete(null);
}
else
{
Throwable cause = ExceptionUtil.extractAsyncCompletionCause(ex);
this.requestResponseLinkCreationFuture.completeExceptionally(cause);
// Set it to null so next call will retry rr link creation
synchronized (this.requestResonseLinkCreationLock)
{
this.requestResponseLinkCreationFuture = null;
}
}
return null;
});
}
return this.requestResponseLinkCreationFuture;
}
}
private void closeRequestResponseLink()
{
synchronized (this.requestResonseLinkCreationLock)
{
if(this.requestResponseLinkCreationFuture != null)
{
this.requestResponseLinkCreationFuture.thenRun(() -> {
this.underlyingFactory.releaseRequestResponseLink(this.receivePath);
this.requestResponseLink = null;
});
this.requestResponseLinkCreationFuture = null;
}
}
}
private void createReceiveLink()
{
TRACE_LOGGER.info("Creating receive link to '{}'", this.receivePath);
Connection connection = this.underlyingFactory.getConnection();
final Session session = connection.session();
session.setIncomingCapacity(Integer.MAX_VALUE);
session.open();
BaseHandler.setHandler(session, new SessionHandler(this.receivePath));
final String receiveLinkNamePrefix = StringUtil.getShortRandomString();
final String receiveLinkName = !StringUtil.isNullOrEmpty(connection.getRemoteContainer()) ?
receiveLinkNamePrefix.concat(TrackingUtil.TRACKING_ID_TOKEN_SEPARATOR).concat(connection.getRemoteContainer()) :
receiveLinkNamePrefix;
final Receiver receiver = session.receiver(receiveLinkName);
Source source = new Source();
source.setAddress(receivePath);
Map<Symbol, Object> linkProperties = new HashMap<>();
// ServiceBus expects timeout to be of type unsignedint
linkProperties.put(ClientConstants.LINK_TIMEOUT_PROPERTY, UnsignedInteger.valueOf(Util.adjustServerTimeout(this.underlyingFactory.getOperationTimeout()).toMillis()));
if(this.isSessionReceiver)
{
HashMap filterMap = new HashMap();
filterMap.put(ClientConstants.SESSION_FILTER, this.sessionId);
source.setFilter(filterMap);
linkProperties.put(ClientConstants.LINK_PEEKMODE_PROPERTY, this.isBrowsableSession);
}
receiver.setSource(source);
receiver.setTarget(new Target());
// Set settle modes
TRACE_LOGGER.debug("Receive link settle mode '{}'", this.settleModePair);
receiver.setSenderSettleMode(this.settleModePair.getSenderSettleMode());
receiver.setReceiverSettleMode(this.settleModePair.getReceiverSettleMode());
receiver.setProperties(linkProperties);
final ReceiveLinkHandler handler = new ReceiveLinkHandler(this);
BaseHandler.setHandler(receiver, handler);
this.underlyingFactory.registerForConnectionError(receiver);
receiver.open();
if (this.receiveLink != null)
{
this.underlyingFactory.deregisterForConnectionError(this.receiveLink);
}
this.receiveLink = receiver;
}
CompletableFuture<Void> sendSASTokenAndSetRenewTimer(boolean retryOnFailure)
{
if(this.getIsClosingOrClosed())
{
return CompletableFuture.completedFuture(null);
}
else
{
CompletableFuture<ScheduledFuture<?>> sendTokenFuture = this.underlyingFactory.sendSASTokenAndSetRenewTimer(this.sasTokenAudienceURI, retryOnFailure, () -> this.sendSASTokenAndSetRenewTimer(true));
return sendTokenFuture.thenAccept((f) -> {this.sasTokenRenewTimerFuture = f;TRACE_LOGGER.debug("Sent SAS Token and set renew timer");});
}
}
private void throwIfInUnusableState()
{
if(this.isSessionReceiver && this.isSessionLockLost)
{
throw new IllegalStateException("Session lock lost and cannot be used. Close this session and accept another session.");
}
this.throwIfClosed(this.lastKnownLinkError);
}
private void cancelSASTokenRenewTimer()
{
if(this.sasTokenRenewTimerFuture != null && !this.sasTokenRenewTimerFuture.isDone())
{
this.sasTokenRenewTimerFuture.cancel(true);
TRACE_LOGGER.debug("Cancelled SAS Token renew timer");
}
}
private List<MessageWithDeliveryTag> receiveCore(int messageCount)
{
List<MessageWithDeliveryTag> returnMessages = null;
MessageWithDeliveryTag currentMessage = this.prefetchedMessages.poll();
int returnedMessageCount = 0;
while (currentMessage != null)
{
this.currentPrefetechedMessagesCount.decrementAndGet();
if (returnMessages == null)
{
returnMessages = new LinkedList<MessageWithDeliveryTag>();
}
returnMessages.add(currentMessage);
if (++returnedMessageCount >= messageCount)
{
break;
}
currentMessage = this.prefetchedMessages.poll();
}
return returnMessages;
}
public int getPrefetchCount()
{
synchronized (this.prefetchCountSync)
{
return this.prefetchCount;
}
}
public String getSessionId()
{
return this.sessionId;
}
public Instant getSessionLockedUntilUtc()
{
if(this.isSessionReceiver)
{
return this.sessionLockedUntilUtc;
}
else
{
throw new RuntimeException("Object is not a session receiver");
}
}
public void setPrefetchCount(final int value) throws ServiceBusException
{
if(value < 0)
{
throw new IllegalArgumentException("Prefetch count cannot be negative.");
}
this.throwIfInUnusableState();
final int deltaPrefetchCount;
synchronized (this.prefetchCountSync)
{
deltaPrefetchCount = value - this.prefetchCount;
this.prefetchCount = value;
TRACE_LOGGER.info("Setting prefetch count to '{}' on recieve link to '{}'", value, this.receivePath);
}
if(deltaPrefetchCount > 0)
{
try
{
this.underlyingFactory.scheduleOnReactorThread(new DispatchHandler()
{
@Override
public void onEvent()
{
sendFlow(deltaPrefetchCount);
}
});
}
catch (IOException ioException)
{
throw new ServiceBusException(false, "Setting prefetch count failed, see cause for more details", ioException);
}
}
}
public CompletableFuture<Collection<MessageWithDeliveryTag>> receiveAsync(final int maxMessageCount, Duration timeout)
{
this.throwIfInUnusableState();
if (maxMessageCount <= 0)
{
throw new IllegalArgumentException("parameter 'maxMessageCount' should be a positive number");
}
TRACE_LOGGER.debug("Receiving maximum of '{}' messages from '{}'", maxMessageCount, this.receivePath);
CompletableFuture<Collection<MessageWithDeliveryTag>> onReceive = new CompletableFuture<Collection<MessageWithDeliveryTag>>();
final ReceiveWorkItem receiveWorkItem = new ReceiveWorkItem(onReceive, timeout, maxMessageCount);
this.creditNeededtoServePendingReceives.addAndGet(maxMessageCount);
this.pendingReceives.add(receiveWorkItem);
// ZERO timeout is special case in SBMP clients where the timeout is sent to the service along with request. It meant 'give me messages you already have, but don't wait'.
// As we don't send timeout to service in AMQP, treating this as a special case and using a very short timeout
if(timeout == Duration.ZERO)
{
timeout = ZERO_TIMEOUT_APPROXIMATION;
}
Timer.schedule(
new Runnable()
{
public void run()
{
if( CoreMessageReceiver.this.pendingReceives.remove(receiveWorkItem))
{
CoreMessageReceiver.this.reduceCreditForCompletedReceiveRequest(receiveWorkItem.getMaxMessageCount());
TRACE_LOGGER.warn("No messages received from '{}'. Pending receive request timed out. Returning null to the client.", CoreMessageReceiver.this.receivePath);
receiveWorkItem.getWork().complete(null);
}
}
},
timeout,
TimerType.OneTimeRun);
this.ensureLinkIsOpen().thenRunAsync(() -> {this.addCredit(receiveWorkItem);});
return onReceive;
}
@Override
public void onOpenComplete(Exception exception)
{
if (exception == null)
{
TRACE_LOGGER.info("Receive link to '{}' opened.", this.receivePath);
if(this.isSessionReceiver)
{
Map remoteSourceFilter = ((Source)this.receiveLink.getRemoteSource()).getFilter();
if(remoteSourceFilter != null && remoteSourceFilter.containsKey(ClientConstants.SESSION_FILTER))
{
String remoteSessionId = (String)remoteSourceFilter.get(ClientConstants.SESSION_FILTER);
this.sessionId = remoteSessionId;
if(this.receiveLink.getRemoteProperties() != null && this.receiveLink.getRemoteProperties().containsKey(ClientConstants.LOCKED_UNTIL_UTC))
{
this.sessionLockedUntilUtc = Util.convertDotNetTicksToInstant((long)this.receiveLink.getRemoteProperties().get(ClientConstants.LOCKED_UNTIL_UTC));
}
else
{
TRACE_LOGGER.warn("Accepted a session with id '{}', from '{}' which didn't set '{}' property on the receive link.", this.sessionId, this.receivePath, ClientConstants.LOCKED_UNTIL_UTC);
this.sessionLockedUntilUtc = Instant.ofEpochMilli(0);
}
TRACE_LOGGER.info("Accepted session with id '{}', lockedUntilUtc '{}' from '{}'.", this.sessionId, this.sessionLockedUntilUtc, this.receivePath);
}
else
{
exception = new ServiceBusException(false, "SessionId filter not set on the remote source.");
}
}
}
if (exception == null)
{
if (this.linkOpen != null && !this.linkOpen.getWork().isDone())
{
AsyncUtil.completeFuture(this.linkOpen.getWork(), this);
}
if(this.receiveLinkReopenFuture != null && !this.receiveLinkReopenFuture.isDone())
{
AsyncUtil.completeFuture(this.receiveLinkReopenFuture, null);
this.receiveLinkReopenFuture = null;
}
this.lastKnownLinkError = null;
this.underlyingFactory.getRetryPolicy().resetRetryCount(this.underlyingFactory.getClientId());
this.sendFlow(this.prefetchCount - this.currentPrefetechedMessagesCount.get());
TRACE_LOGGER.debug("receiverPath:{}, linkname:{}, updated-link-credit:{}, sentCredits:{}",
this.receivePath, this.receiveLink.getName(), this.receiveLink.getCredit(), this.prefetchCount);
}
else
{
TRACE_LOGGER.error("Opening receive link to '{}' failed.", this.receivePath, exception);
this.cancelSASTokenRenewTimer();
if (this.linkOpen != null && !this.linkOpen.getWork().isDone())
{
this.setClosed();
ExceptionUtil.completeExceptionally(this.linkOpen.getWork(), exception, this, true);
}
if(this.receiveLinkReopenFuture != null && !this.receiveLinkReopenFuture.isDone())
{
AsyncUtil.completeFutureExceptionally(this.receiveLinkReopenFuture, exception);
this.receiveLinkReopenFuture = null;
if(this.isSessionReceiver && (exception instanceof SessionLockLostException || exception instanceof SessionCannotBeLockedException))
{
// No point in retrying to establish a link.. SessionLock is lost
TRACE_LOGGER.warn("SessionId '{}' lock lost. Closing receiver.", this.sessionId);
this.isSessionLockLost = true;
this.closeAsync();
}
}
this.lastKnownLinkError = exception;
}
}
@Override
public void onReceiveComplete(Delivery delivery)
{
this.underlyingFactory.getRetryPolicy().resetRetryCount(this.getClientId());
byte[] deliveryTag = delivery.getTag();
String deliveryTagAsString = StringUtil.convertBytesToString(delivery.getTag());
TRACE_LOGGER.debug("Received a delivery '{}' from '{}'", deliveryTagAsString, this.receivePath);
if(deliveryTag == null || deliveryTag.length == 0 || !this.tagsToDeliveriesMap.containsKey(deliveryTagAsString))
{
TRACE_LOGGER.debug("Received a message from '{}'. Adding to prefecthed messages.", this.receivePath);
try
{
Message message = Util.readMessageFromDelivery(receiveLink, delivery);
if(this.settleModePair.getSenderSettleMode() == SenderSettleMode.SETTLED)
{
// No op. Delivery comes settled from the sender
delivery.disposition(Accepted.getInstance());
delivery.settle();
}
else
{
this.tagsToDeliveriesMap.put(StringUtil.convertBytesToString(delivery.getTag()), delivery);
receiveLink.advance();
}
// Accuracy of count is not that important. So not making those two operations atomic
this.currentPrefetechedMessagesCount.incrementAndGet();
this.prefetchedMessages.add(new MessageWithDeliveryTag(message, delivery.getTag()));
}
catch(Exception e)
{
TRACE_LOGGER.error("Reading message from delivery '{}' from '{}', session '{}' failed with unexpected exception.", deliveryTagAsString, this.receivePath, this.sessionId, e);
delivery.disposition(Released.getInstance());
delivery.settle();
return;
}
}
else
{
DeliveryState remoteState = delivery.getRemoteState();
TRACE_LOGGER.debug("Received a delivery '{}' with state '{}' from '{}'", deliveryTagAsString, remoteState, this.receivePath);
if(remoteState instanceof Outcome)
{
Outcome remoteOutcome = (Outcome)remoteState;
UpdateStateWorkItem matchingUpdateStateWorkItem = this.pendingUpdateStateRequests.get(deliveryTagAsString);
if(matchingUpdateStateWorkItem != null)
{
// This comparison is ugly. Using it for the lack of equals operation on Outcome classes
if(remoteOutcome.getClass().getName().equals(matchingUpdateStateWorkItem.outcome.getClass().getName()))
{
TRACE_LOGGER.debug("Completing a pending updateState operation for delivery '{}' from '{}'", deliveryTagAsString, this.receivePath);
this.completePendingUpdateStateWorkItem(delivery, deliveryTagAsString, matchingUpdateStateWorkItem, null);
}
else
{
// if(matchingUpdateStateWorkItem.expectedOutcome instanceof Accepted)
// {
TRACE_LOGGER.warn("Received delivery '{}' state '{}' doesn't match expected state '{}'", deliveryTagAsString, remoteState, matchingUpdateStateWorkItem.outcome);
// Complete requests
if(remoteOutcome instanceof Rejected)
{
Rejected rejected = (Rejected) remoteOutcome;
ErrorCondition error = rejected.getError();
Exception exception = ExceptionUtil.toException(error);
if (ExceptionUtil.isGeneralError(error.getCondition()))
{
this.lastKnownLinkError = exception;
this.lastKnownErrorReportedAt = Instant.now();
}
Duration retryInterval = this.retryPolicy.getNextRetryInterval(this.getClientId(), exception, matchingUpdateStateWorkItem.getTimeoutTracker().remaining());
if (retryInterval == null)
{
TRACE_LOGGER.error("Completing pending updateState operation for delivery '{}' with exception", deliveryTagAsString, exception);
this.completePendingUpdateStateWorkItem(delivery, deliveryTagAsString, matchingUpdateStateWorkItem, exception);
}
else
{
matchingUpdateStateWorkItem.setLastKnownException(exception);
// Retry after retry interval
TRACE_LOGGER.debug("Pending updateState operation for delivery '{}' will be retried after '{}'", deliveryTagAsString, retryInterval);
try
{
this.underlyingFactory.scheduleOnReactorThread((int) retryInterval.toMillis(),
new DispatchHandler()
{
@Override
public void onEvent()
{
delivery.disposition((DeliveryState)matchingUpdateStateWorkItem.getOutcome());
}
});
}
catch (IOException ioException)
{
this.completePendingUpdateStateWorkItem(delivery, deliveryTagAsString, matchingUpdateStateWorkItem,
new ServiceBusException(false, "Operation failed while scheduling a retry on Reactor, see cause for more details.", ioException));
}
}
}
else if (remoteOutcome instanceof Released)
{
Exception exception = new OperationCancelledException(remoteOutcome.toString());
TRACE_LOGGER.error("Completing pending updateState operation for delivery '{}' with exception", deliveryTagAsString, exception);
this.completePendingUpdateStateWorkItem(delivery, deliveryTagAsString, matchingUpdateStateWorkItem, exception);
}
else
{
Exception exception = new ServiceBusException(false, remoteOutcome.toString());
TRACE_LOGGER.error("Completing pending updateState operation for delivery '{}' with exception", deliveryTagAsString, exception);
this.completePendingUpdateStateWorkItem(delivery, deliveryTagAsString, matchingUpdateStateWorkItem, exception);
}
// }
}
}
else
{
// Should not happen. Ignore it
}
}
else
{
//Ignore it. we are only interested in terminal delivery states
}
}
}
public void onError(ErrorCondition error)
{
Exception completionException = ExceptionUtil.toException(error);
this.onError(completionException);
}
@Override
public void onError(Exception exception)
{
this.creditToFlow.set(0);
this.cancelSASTokenRenewTimer();
if(this.settleModePair.getSenderSettleMode() == SenderSettleMode.UNSETTLED)
{
this.prefetchedMessages.clear();
this.currentPrefetechedMessagesCount.set(0);
this.tagsToDeliveriesMap.clear();
}
if (this.getIsClosingOrClosed())
{
TRACE_LOGGER.info("Receive link to '{}', sessionId '{}' closed", this.receivePath, this.sessionId);
AsyncUtil.completeFuture(this.linkClose, null);
this.clearAllPendingWorkItems(exception);
}
else
{
TRACE_LOGGER.error("Receive link to '{}', sessionId '{}' closed with error.", this.receivePath, this.sessionId, exception);
this.lastKnownLinkError = exception;
if ((this.linkOpen != null && !this.linkOpen.getWork().isDone()) ||
(this.receiveLinkReopenFuture !=null && !receiveLinkReopenFuture.isDone()))
{
this.onOpenComplete(exception);
}
else
{
if (exception != null &&
(!(exception instanceof ServiceBusException) || !((ServiceBusException) exception).getIsTransient()))
{
this.clearAllPendingWorkItems(exception);
if(this.isSessionReceiver && (exception instanceof SessionLockLostException || exception instanceof SessionCannotBeLockedException))
{
// No point in retrying to establish a link.. SessionLock is lost
TRACE_LOGGER.warn("SessionId '{}' lock lost. Closing receiver.", this.sessionId);
this.isSessionLockLost = true;
this.closeAsync();
}
}
else
{
// TODO Why recreating link needs to wait for retry interval of pending receive?
ReceiveWorkItem workItem = this.pendingReceives.peek();
if (workItem != null && workItem.getTimeoutTracker() != null)
{
Duration nextRetryInterval = this.underlyingFactory.getRetryPolicy()
.getNextRetryInterval(this.getClientId(), exception, workItem.getTimeoutTracker().remaining());
if (nextRetryInterval != null)
{
TRACE_LOGGER.error("Receive link to '{}', sessionId '{}' will be reopened after '{}'", this.receivePath, this.sessionId, nextRetryInterval);
Timer.schedule(() -> {CoreMessageReceiver.this.ensureLinkIsOpen();}, nextRetryInterval, TimerType.OneTimeRun);
}
}
}
}
}
}
private void reduceCreditForCompletedReceiveRequest(int maxCreditCountOfReceiveRequest)
{
this.creditNeededtoServePendingReceives.updateAndGet((c) -> {
int updatedCredit = c - maxCreditCountOfReceiveRequest;
return (updatedCredit > 0) ? updatedCredit : 0;
});
}
private void addCredit(ReceiveWorkItem receiveWorkItem)
{
// Timed out receive requests and batch receive requests completed with less than maxCount messages might have sent more credit
// than consumed by the receiver resulting in excess credit at the service endpoint.
int creditToFlowForWorkItem = this.creditNeededtoServePendingReceives.get() - (this.receiveLink.getCredit() + this.currentPrefetechedMessagesCount.get() + this.creditToFlow.get()) + this.prefetchCount;
if(creditToFlowForWorkItem > 0)
{
int currentTotalCreditToSend = this.creditToFlow.addAndGet(creditToFlowForWorkItem);
if(currentTotalCreditToSend >= this.prefetchCount || currentTotalCreditToSend >= CREDIT_FLOW_BATCH_SIZE)
{
try
{
this.underlyingFactory.scheduleOnReactorThread(new DispatchHandler()
{
@Override
public void onEvent()
{
// Send credit accumulated so far to make it less chat-ty
int accumulatedCredit = CoreMessageReceiver.this.creditToFlow.getAndSet(0);
sendFlow(accumulatedCredit);
}
});
}
catch (IOException ioException)
{
this.pendingReceives.remove(receiveWorkItem);
this.reduceCreditForCompletedReceiveRequest(receiveWorkItem.getMaxMessageCount());
AsyncUtil.completeFutureExceptionally(receiveWorkItem.getWork(), generateDispatacherSchedulingFailedException("completeMessage", ioException));
receiveWorkItem.cancelTimeoutTask(false);
}
}
}
}
private void sendFlow(int credits)
{
if(!this.isBrowsableSession && credits > 0)
{
this.receiveLink.flow(credits);
TRACE_LOGGER.debug("Sent flow to the service. receiverPath:{}, linkname:{}, updated-link-credit:{}, sentCredits:{}",
this.receivePath, this.receiveLink.getName(), this.receiveLink.getCredit(), credits);
}
}
private void scheduleLinkOpenTimeout(final TimeoutTracker timeout)
{
// timer to signal a timeout if exceeds the operationTimeout on MessagingFactory
Timer.schedule(
new Runnable()
{
public void run()
{
if (!linkOpen.getWork().isDone())
{
CoreMessageReceiver.this.closeInternals(false);
CoreMessageReceiver.this.setClosed();
Exception operationTimedout = new TimeoutException(
String.format(Locale.US, "%s operation on ReceiveLink(%s) to path(%s) timed out at %s.", "Open", CoreMessageReceiver.this.receiveLink.getName(), CoreMessageReceiver.this.receivePath, ZonedDateTime.now()),
CoreMessageReceiver.this.lastKnownLinkError);
TRACE_LOGGER.warn(operationTimedout.getMessage());
ExceptionUtil.completeExceptionally(linkOpen.getWork(), operationTimedout, CoreMessageReceiver.this, false);
}
}
}
, timeout.remaining()
, TimerType.OneTimeRun);
}
private void scheduleLinkCloseTimeout(final TimeoutTracker timeout)
{
// timer to signal a timeout if exceeds the operationTimeout on MessagingFactory
Timer.schedule(
new Runnable()
{
public void run()
{
if (!linkClose.isDone())
{
Exception operationTimedout = new TimeoutException(String.format(Locale.US, "%s operation on Receive Link(%s) timed out at %s", "Close", CoreMessageReceiver.this.receiveLink.getName(), ZonedDateTime.now()));
TRACE_LOGGER.warn(operationTimedout.getMessage());
ExceptionUtil.completeExceptionally(linkClose, operationTimedout, CoreMessageReceiver.this, false);
}
}
}
, timeout.remaining()
, TimerType.OneTimeRun);
}
@Override
public void onClose(ErrorCondition condition)
{
if (condition == null)
{
this.onError(new ServiceBusException(true,
String.format(Locale.US, "Closing the link. LinkName(%s), EntityPath(%s)", this.receiveLink.getName(), this.receivePath)));
}
else
{
this.onError(condition);
}
}
@Override
public ErrorContext getContext()
{
final boolean isLinkOpened = this.linkOpen != null && this.linkOpen.getWork().isDone();
final String referenceId = this.receiveLink != null && this.receiveLink.getRemoteProperties() != null && this.receiveLink.getRemoteProperties().containsKey(ClientConstants.TRACKING_ID_PROPERTY)
? this.receiveLink.getRemoteProperties().get(ClientConstants.TRACKING_ID_PROPERTY).toString()
: ((this.receiveLink != null) ? this.receiveLink.getName(): null);
ReceiverErrorContext errorContext = new ReceiverErrorContext(this.underlyingFactory != null ? this.underlyingFactory.getHostName() : null,
this.receivePath,
referenceId,
isLinkOpened ? this.prefetchCount : null,
isLinkOpened && this.receiveLink != null ? this.receiveLink.getCredit(): null,
this.currentPrefetechedMessagesCount.get());
return errorContext;
}
@Override
protected CompletableFuture<Void> onClose()
{
this.closeInternals(true);
return this.linkClose;
}
private void closeInternals(boolean waitForCloseCompletion)
{
if (!this.getIsClosed())
{
if (this.receiveLink != null && this.receiveLink.getLocalState() != EndpointState.CLOSED)
{
try {
this.underlyingFactory.scheduleOnReactorThread(new DispatchHandler() {
@Override
public void onEvent() {
if (CoreMessageReceiver.this.receiveLink != null && CoreMessageReceiver.this.receiveLink.getLocalState() != EndpointState.CLOSED)
{
TRACE_LOGGER.info("Closing receive link to '{}'", CoreMessageReceiver.this.receivePath);
CoreMessageReceiver.this.receiveLink.close();
CoreMessageReceiver.this.underlyingFactory.deregisterForConnectionError(CoreMessageReceiver.this.receiveLink);
if(waitForCloseCompletion)
{
CoreMessageReceiver.this.scheduleLinkCloseTimeout(TimeoutTracker.create(CoreMessageReceiver.this.operationTimeout));
}
else
{
AsyncUtil.completeFuture(CoreMessageReceiver.this.linkClose, null);
}
}
}
});
} catch (IOException e) {
AsyncUtil.completeFutureExceptionally(this.linkClose, e);