This repository has been archived by the owner on Oct 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathMessageReceiver.cs
1697 lines (1487 loc) · 81.4 KB
/
MessageReceiver.cs
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.
namespace Microsoft.Azure.ServiceBus.Core
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.Azure.Amqp;
using Microsoft.Azure.Amqp.Encoding;
using Microsoft.Azure.Amqp.Framing;
using Microsoft.Azure.ServiceBus.Amqp;
using Microsoft.Azure.ServiceBus.Primitives;
/// <summary>
/// The MessageReceiver can be used to receive messages from Queues and Subscriptions and acknowledge them.
/// </summary>
/// <example>
/// Create a new MessageReceiver to receive a message from a Subscription
/// <code>
/// IMessageReceiver messageReceiver = new MessageReceiver(
/// namespaceConnectionString,
/// EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName),
/// ReceiveMode.PeekLock);
/// </code>
///
/// Receive a message from the Subscription.
/// <code>
/// var message = await messageReceiver.ReceiveAsync();
/// await messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
/// </code>
/// </example>
/// <remarks>
/// The MessageReceiver provides advanced functionality that is not found in the
/// <see cref="QueueClient" /> or <see cref="SubscriptionClient" />. For instance,
/// <see cref="ReceiveAsync()"/>, which allows you to receive messages on demand, but also requires
/// you to manually renew locks using <see cref="RenewLockAsync(Message)"/>.
/// It uses AMQP protocol to communicate with service.
/// </remarks>
public class MessageReceiver : ClientEntity, IMessageReceiver
{
private static readonly TimeSpan DefaultBatchFlushInterval = TimeSpan.FromMilliseconds(20);
readonly ConcurrentExpiringSet<Guid> requestResponseLockedMessages;
readonly bool isSessionReceiver;
readonly object messageReceivePumpSyncLock;
readonly ActiveClientLinkManager clientLinkManager;
readonly ServiceBusDiagnosticSource diagnosticSource;
int prefetchCount;
long lastPeekedSequenceNumber;
MessageReceivePump receivePump;
CancellationTokenSource receivePumpCancellationTokenSource;
/// <summary>
/// Creates a new MessageReceiver from a <see cref="ServiceBusConnectionStringBuilder"/>.
/// </summary>
/// <param name="connectionStringBuilder">The <see cref="ServiceBusConnectionStringBuilder"/> having entity level connection details.</param>
/// <param name="receiveMode">The <see cref="ServiceBus.ReceiveMode"/> used to specify how messages are received. Defaults to PeekLock mode.</param>
/// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/>.</param>
/// <param name="prefetchCount">The <see cref="PrefetchCount"/> that specifies the upper limit of messages this receiver
/// will actively receive regardless of whether a receive operation is pending. Defaults to 0.</param>
/// <remarks>Creates a new connection to the entity, which is opened during the first operation.</remarks>
public MessageReceiver(
ServiceBusConnectionStringBuilder connectionStringBuilder,
ReceiveMode receiveMode = ReceiveMode.PeekLock,
RetryPolicy retryPolicy = null,
int prefetchCount = Constants.DefaultClientPrefetchCount)
: this(connectionStringBuilder?.GetNamespaceConnectionString(), connectionStringBuilder?.EntityPath, receiveMode, retryPolicy, prefetchCount)
{
}
/// <summary>
/// Creates a new MessageReceiver from a specified connection string and entity path.
/// </summary>
/// <param name="connectionString">Namespace connection string used to communicate with Service Bus. Must not contain Entity details.</param>
/// <param name="entityPath">The path of the entity for this receiver. For Queues this will be the name, but for Subscriptions this will be the path.
/// You can use <see cref="EntityNameHelper.FormatSubscriptionPath(string, string)"/>, to help create this path.</param>
/// <param name="receiveMode">The <see cref="ServiceBus.ReceiveMode"/> used to specify how messages are received. Defaults to PeekLock mode.</param>
/// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/></param>
/// <param name="prefetchCount">The <see cref="PrefetchCount"/> that specifies the upper limit of messages this receiver
/// will actively receive regardless of whether a receive operation is pending. Defaults to 0.</param>
/// <remarks>Creates a new connection to the entity, which is opened during the first operation.</remarks>
public MessageReceiver(
string connectionString,
string entityPath,
ReceiveMode receiveMode = ReceiveMode.PeekLock,
RetryPolicy retryPolicy = null,
int prefetchCount = Constants.DefaultClientPrefetchCount)
: this(entityPath, null, receiveMode, new ServiceBusConnection(connectionString), null, retryPolicy, prefetchCount)
{
if (string.IsNullOrWhiteSpace(connectionString))
{
throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString);
}
this.OwnsConnection = true;
}
/// <summary>
/// Creates a new MessageReceiver from a specified endpoint, entity path, and token provider.
/// </summary>
/// <param name="endpoint">Fully qualified domain name for Service Bus. Most likely, {yournamespace}.servicebus.windows.net</param>
/// <param name="entityPath">Queue path.</param>
/// <param name="tokenProvider">Token provider which will generate security tokens for authorization.</param>
/// <param name="transportType">Transport type.</param>
/// <param name="receiveMode">Mode of receive of messages. Defaults to <see cref="ReceiveMode"/>.PeekLock.</param>
/// <param name="retryPolicy">Retry policy for queue operations. Defaults to <see cref="RetryPolicy.Default"/></param>
/// <param name="prefetchCount">The <see cref="PrefetchCount"/> that specifies the upper limit of messages this receiver
/// will actively receive regardless of whether a receive operation is pending. Defaults to 0.</param>
/// <remarks>Creates a new connection to the entity, which is opened during the first operation.</remarks>
public MessageReceiver(
string endpoint,
string entityPath,
ITokenProvider tokenProvider,
TransportType transportType = TransportType.Amqp,
ReceiveMode receiveMode = ReceiveMode.PeekLock,
RetryPolicy retryPolicy = null,
int prefetchCount = Constants.DefaultClientPrefetchCount)
: this(entityPath, null, receiveMode, new ServiceBusConnection(endpoint, transportType, retryPolicy) {TokenProvider = tokenProvider}, null, retryPolicy, prefetchCount)
{
this.OwnsConnection = true;
}
/// <summary>
/// Creates a new AMQP MessageReceiver on a given <see cref="ServiceBusConnection"/>
/// </summary>
/// <param name="serviceBusConnection">Connection object to the service bus namespace.</param>
/// <param name="entityPath">The path of the entity for this receiver. For Queues this will be the name, but for Subscriptions this will be the path.
/// You can use <see cref="EntityNameHelper.FormatSubscriptionPath(string, string)"/>, to help create this path.</param>
/// <param name="receiveMode">The <see cref="ServiceBus.ReceiveMode"/> used to specify how messages are received. Defaults to PeekLock mode.</param>
/// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/></param>
/// <param name="prefetchCount">The <see cref="PrefetchCount"/> that specifies the upper limit of messages this receiver
/// will actively receive regardless of whether a receive operation is pending. Defaults to 0.</param>
public MessageReceiver(
ServiceBusConnection serviceBusConnection,
string entityPath,
ReceiveMode receiveMode = ReceiveMode.PeekLock,
RetryPolicy retryPolicy = null,
int prefetchCount = Constants.DefaultClientPrefetchCount)
: this(entityPath, null, receiveMode, serviceBusConnection, null, retryPolicy, prefetchCount)
{
this.OwnsConnection = false;
}
internal MessageReceiver(
string entityPath,
MessagingEntityType? entityType,
ReceiveMode receiveMode,
ServiceBusConnection serviceBusConnection,
ICbsTokenProvider cbsTokenProvider,
RetryPolicy retryPolicy,
int prefetchCount = Constants.DefaultClientPrefetchCount,
string sessionId = null,
bool isSessionReceiver = false)
: base(nameof(MessageReceiver), entityPath, retryPolicy ?? RetryPolicy.Default)
{
MessagingEventSource.Log.MessageReceiverCreateStart(serviceBusConnection?.Endpoint.Authority, entityPath, receiveMode.ToString());
if (string.IsNullOrWhiteSpace(entityPath))
{
throw Fx.Exception.ArgumentNullOrWhiteSpace(entityPath);
}
this.ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection));
this.ReceiveMode = receiveMode;
this.Path = entityPath;
this.EntityType = entityType;
this.ServiceBusConnection.ThrowIfClosed();
if (cbsTokenProvider != null)
{
this.CbsTokenProvider = cbsTokenProvider;
}
else if (this.ServiceBusConnection.TokenProvider != null)
{
this.CbsTokenProvider = new TokenProviderAdapter(this.ServiceBusConnection.TokenProvider, this.ServiceBusConnection.OperationTimeout);
}
else
{
throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider");
}
this.SessionIdInternal = sessionId;
this.isSessionReceiver = isSessionReceiver;
this.ReceiveLinkManager = new FaultTolerantAmqpObject<ReceivingAmqpLink>(this.CreateLinkAsync, CloseSession);
this.RequestResponseLinkManager = new FaultTolerantAmqpObject<RequestResponseAmqpLink>(this.CreateRequestResponseLinkAsync, CloseRequestResponseSession);
this.requestResponseLockedMessages = new ConcurrentExpiringSet<Guid>();
this.PrefetchCount = prefetchCount;
this.messageReceivePumpSyncLock = new object();
this.clientLinkManager = new ActiveClientLinkManager(this, this.CbsTokenProvider);
this.diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint);
MessagingEventSource.Log.MessageReceiverCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, this.ClientId);
}
/// <summary>
/// Gets a list of currently registered plugins.
/// </summary>
public override IList<ServiceBusPlugin> RegisteredPlugins { get; } = new List<ServiceBusPlugin>();
/// <summary>
/// Gets the <see cref="ServiceBus.ReceiveMode"/> of the current receiver.
/// </summary>
public ReceiveMode ReceiveMode { get; protected set; }
/// <summary>
/// Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when and before the application asks for one using Receive.
/// Setting a non-zero value prefetches PrefetchCount number of messages.
/// Setting the value to zero turns prefetch off.
/// Defaults to 0.
/// </summary>
/// <remarks>
/// <para>
/// When Prefetch is enabled, the receiver will quietly acquire more messages, up to the PrefetchCount limit, than what the application
/// immediately asks for. A single initial Receive/ReceiveAsync call will therefore acquire a message for immediate consumption
/// that will be returned as soon as available, and the client will proceed to acquire further messages to fill the prefetch buffer in the background.
/// </para>
/// <para>
/// While messages are available in the prefetch buffer, any subsequent ReceiveAsync calls will be immediately satisfied from the buffer, and the buffer is
/// replenished in the background as space becomes available.If there are no messages available for delivery, the receive operation will drain the
/// buffer and then wait or block as expected.
/// </para>
/// <para>Prefetch also works equivalently with the <see cref="RegisterMessageHandler(Func{Message,CancellationToken,Task}, Func{ExceptionReceivedEventArgs, Task})"/> APIs.</para>
/// <para>Updates to this value take effect on the next receive call to the service.</para>
/// </remarks>
public int PrefetchCount
{
get => this.prefetchCount;
set
{
if (value < 0)
{
throw Fx.Exception.ArgumentOutOfRange(nameof(this.PrefetchCount), value, "Value cannot be less than 0.");
}
this.prefetchCount = value;
if (this.ReceiveLinkManager.TryGetOpenedObject(out var link))
{
link.SetTotalLinkCredit((uint)value, true, true);
}
}
}
/// <summary>Gets the sequence number of the last peeked message.</summary>
/// <seealso cref="PeekAsync()"/>
public long LastPeekedSequenceNumber
{
get => this.lastPeekedSequenceNumber;
internal set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(this.LastPeekedSequenceNumber), value.ToString());
}
this.lastPeekedSequenceNumber = value;
}
}
/// <summary>The path of the entity for this receiver. For Queues this will be the name, but for Subscriptions this will be the path.</summary>
public override string Path { get; }
/// <summary>
/// Duration after which individual operations will timeout.
/// </summary>
public override TimeSpan OperationTimeout {
get => this.ServiceBusConnection.OperationTimeout;
set => this.ServiceBusConnection.OperationTimeout = value;
}
/// <summary>
/// Connection object to the service bus namespace.
/// </summary>
public override ServiceBusConnection ServiceBusConnection { get; }
/// <summary>
/// Gets the DateTime that the current receiver is locked until. This is only applicable when Sessions are used.
/// </summary>
internal DateTime LockedUntilUtcInternal { get; set; }
/// <summary>
/// Gets the SessionId of the current receiver. This is only applicable when Sessions are used.
/// </summary>
internal string SessionIdInternal { get; set; }
internal MessagingEntityType? EntityType { get; }
Exception LinkException { get; set; }
ICbsTokenProvider CbsTokenProvider { get; }
internal FaultTolerantAmqpObject<ReceivingAmqpLink> ReceiveLinkManager { get; }
FaultTolerantAmqpObject<RequestResponseAmqpLink> RequestResponseLinkManager { get; }
/// <summary>
/// Receive a message from the entity defined by <see cref="Path"/> using <see cref="ReceiveMode"/> mode.
/// </summary>
/// <returns>The message received. Returns null if no message is found.</returns>
/// <remarks>Operation will time out after duration of <see cref="ClientEntity.OperationTimeout"/></remarks>
public Task<Message> ReceiveAsync()
{
return this.ReceiveAsync(this.OperationTimeout);
}
/// <summary>
/// Receive a message from the entity defined by <see cref="Path"/> using <see cref="ReceiveMode"/> mode.
/// </summary>
/// <param name="operationTimeout">The time span the client waits for receiving a message before it times out.</param>
/// <returns>The message received. Returns null if no message is found.</returns>
/// <remarks>
/// The parameter <paramref name="operationTimeout"/> includes the time taken by the receiver to establish a connection
/// (either during the first receive or when connection needs to be re-established). If establishing the connection
/// times out, this will throw <see cref="ServiceBusTimeoutException"/>.
/// </remarks>
public async Task<Message> ReceiveAsync(TimeSpan operationTimeout)
{
var messages = await this.ReceiveAsync(1, operationTimeout).ConfigureAwait(false);
if (messages != null && messages.Count > 0)
{
return messages[0];
}
return null;
}
/// <summary>
/// Receives a maximum of <paramref name="maxMessageCount"/> messages from the entity defined by <see cref="Path"/> using <see cref="ReceiveMode"/> mode.
/// </summary>
/// <param name="maxMessageCount">The maximum number of messages that will be received.</param>
/// <returns>List of messages received. Returns null if no message is found.</returns>
/// <remarks>Receiving less than <paramref name="maxMessageCount"/> messages is not an indication of empty entity.</remarks>
public Task<IList<Message>> ReceiveAsync(int maxMessageCount)
{
return this.ReceiveAsync(maxMessageCount, this.OperationTimeout);
}
/// <summary>
/// Receives a maximum of <paramref name="maxMessageCount"/> messages from the entity defined by <see cref="Path"/> using <see cref="ReceiveMode"/> mode.
/// </summary>
/// <param name="maxMessageCount">The maximum number of messages that will be received.</param>
/// <param name="operationTimeout">The time span the client waits for receiving a message before it times out.</param>
/// <returns>List of messages received. Returns null if no message is found.</returns>
/// <remarks>Receiving less than <paramref name="maxMessageCount"/> messages is not an indication of empty entity.
/// The parameter <paramref name="operationTimeout"/> includes the time taken by the receiver to establish a connection
/// (either during the first receive or when connection needs to be re-established). If establishing the connection
/// times out, this will throw <see cref="ServiceBusTimeoutException"/>.
/// </remarks>
public async Task<IList<Message>> ReceiveAsync(int maxMessageCount, TimeSpan operationTimeout)
{
this.ThrowIfClosed();
if (operationTimeout <= TimeSpan.Zero)
{
throw Fx.Exception.ArgumentOutOfRange(nameof(operationTimeout), operationTimeout, Resources.TimeoutMustBePositiveNonZero.FormatForUser(nameof(operationTimeout), operationTimeout));
}
MessagingEventSource.Log.MessageReceiveStart(this.ClientId, maxMessageCount);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.ReceiveStart(maxMessageCount) : null;
Task receiveTask = null;
IList<Message> unprocessedMessageList = null;
try
{
receiveTask = this.RetryPolicy.RunOperation(
async () =>
{
unprocessedMessageList = await this.OnReceiveAsync(maxMessageCount, operationTimeout)
.ConfigureAwait(false);
}, operationTimeout);
await receiveTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessageReceiveException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.ReceiveStop(activity, maxMessageCount, receiveTask?.Status, unprocessedMessageList);
}
MessagingEventSource.Log.MessageReceiveStop(this.ClientId, unprocessedMessageList?.Count ?? 0);
if (unprocessedMessageList == null)
{
return unprocessedMessageList;
}
return await this.ProcessMessages(unprocessedMessageList).ConfigureAwait(false);
}
/// <summary>
/// Receives a specific deferred message identified by <paramref name="sequenceNumber"/>.
/// </summary>
/// <param name="sequenceNumber">The sequence number of the message that will be received.</param>
/// <returns>Message identified by sequence number <paramref name="sequenceNumber"/>. Returns null if no such message is found.
/// Throws if the message has not been deferred.</returns>
/// <seealso cref="DeferAsync"/>
public async Task<Message> ReceiveDeferredMessageAsync(long sequenceNumber)
{
var messages = await this.ReceiveDeferredMessageAsync(new[] { sequenceNumber }).ConfigureAwait(false);
if (messages != null && messages.Count > 0)
{
return messages[0];
}
return null;
}
/// <summary>
/// Receives a <see cref="IList{Message}"/> of deferred messages identified by <paramref name="sequenceNumbers"/>.
/// </summary>
/// <param name="sequenceNumbers">An <see cref="IEnumerable{T}"/> containing the sequence numbers to receive.</param>
/// <returns>Messages identified by sequence number are returned. Returns null if no messages are found.
/// Throws if the messages have not been deferred.</returns>
/// <seealso cref="DeferAsync"/>
public async Task<IList<Message>> ReceiveDeferredMessageAsync(IEnumerable<long> sequenceNumbers)
{
this.ThrowIfClosed();
this.ThrowIfNotPeekLockMode();
if (sequenceNumbers == null)
{
throw Fx.Exception.ArgumentNull(nameof(sequenceNumbers));
}
var sequenceNumberList = sequenceNumbers.ToArray();
if (sequenceNumberList.Length == 0)
{
throw Fx.Exception.ArgumentNull(nameof(sequenceNumbers));
}
MessagingEventSource.Log.MessageReceiveDeferredMessageStart(this.ClientId, sequenceNumberList.Length, sequenceNumberList);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.ReceiveDeferredStart(sequenceNumberList) : null;
Task receiveTask = null;
IList<Message> messages = null;
try
{
receiveTask = this.RetryPolicy.RunOperation(
async () =>
{
messages = await this.OnReceiveDeferredMessageAsync(sequenceNumberList).ConfigureAwait(false);
}, this.OperationTimeout);
await receiveTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessageReceiveDeferredMessageException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.ReceiveDeferredStop(activity, sequenceNumberList, receiveTask?.Status, messages);
}
MessagingEventSource.Log.MessageReceiveDeferredMessageStop(this.ClientId, messages?.Count ?? 0);
return messages;
}
/// <summary>
/// Completes a <see cref="Message"/> using its lock token. This will delete the message from the service.
/// </summary>
/// <param name="lockToken">The lock token of the corresponding message to complete.</param>
/// <remarks>
/// A lock token can be found in <see cref="Message.SystemPropertiesCollection.LockToken"/>,
/// only when <see cref="ReceiveMode"/> is set to <see cref="ServiceBus.ReceiveMode.PeekLock"/>.
/// This operation can only be performed on messages that were received by this receiver.
/// </remarks>
public Task CompleteAsync(string lockToken)
{
return this.CompleteAsync(new[] { lockToken });
}
/// <summary>
/// Completes a series of <see cref="Message"/> using a list of lock tokens. This will delete the message from the service.
/// </summary>
/// <remarks>
/// A lock token can be found in <see cref="Message.SystemPropertiesCollection.LockToken"/>,
/// only when <see cref="ReceiveMode"/> is set to <see cref="ServiceBus.ReceiveMode.PeekLock"/>.
/// This operation can only be performed on messages that were received by this receiver.
/// </remarks>
/// <param name="lockTokens">An <see cref="IEnumerable{T}"/> containing the lock tokens of the corresponding messages to complete.</param>
public async Task CompleteAsync(IEnumerable<string> lockTokens)
{
this.ThrowIfClosed();
this.ThrowIfNotPeekLockMode();
if (lockTokens == null)
{
throw Fx.Exception.ArgumentNull(nameof(lockTokens));
}
var lockTokenList = lockTokens.ToList();
if (lockTokenList.Count == 0)
{
throw Fx.Exception.Argument(nameof(lockTokens), Resources.ListOfLockTokensCannotBeEmpty);
}
MessagingEventSource.Log.MessageCompleteStart(this.ClientId, lockTokenList.Count, lockTokenList);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.CompleteStart(lockTokenList) : null;
Task completeTask = null;
try
{
completeTask =
this.RetryPolicy.RunOperation(() => this.OnCompleteAsync(lockTokenList), this.OperationTimeout);
await completeTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessageCompleteException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.CompleteStop(activity, lockTokenList, completeTask?.Status);
}
MessagingEventSource.Log.MessageCompleteStop(this.ClientId);
}
/// <summary>
/// Abandons a <see cref="Message"/> using a lock token. This will make the message available again for processing.
/// </summary>
/// <param name="lockToken">The lock token of the corresponding message to abandon.</param>
/// <param name="propertiesToModify">The properties of the message to modify while abandoning the message.</param>
/// <remarks>A lock token can be found in <see cref="Message.SystemPropertiesCollection.LockToken"/>,
/// only when <see cref="ReceiveMode"/> is set to <see cref="ServiceBus.ReceiveMode.PeekLock"/>.
/// Abandoning a message will increase the delivery count on the message.
/// This operation can only be performed on messages that were received by this receiver.
/// </remarks>
public async Task AbandonAsync(string lockToken, IDictionary<string, object> propertiesToModify = null)
{
this.ThrowIfClosed();
this.ThrowIfNotPeekLockMode();
MessagingEventSource.Log.MessageAbandonStart(this.ClientId, 1, lockToken);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("Abandon", lockToken) : null;
Task abandonTask = null;
try
{
abandonTask = this.RetryPolicy.RunOperation(() => this.OnAbandonAsync(lockToken, propertiesToModify),
this.OperationTimeout);
await abandonTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessageAbandonException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.DisposeStop(activity, lockToken, abandonTask?.Status);
}
MessagingEventSource.Log.MessageAbandonStop(this.ClientId);
}
/// <summary>Indicates that the receiver wants to defer the processing for the message.</summary>
/// <param name="lockToken">The lock token of the <see cref="Message" />.</param>
/// <param name="propertiesToModify">The properties of the message to modify while deferring the message.</param>
/// <remarks>
/// A lock token can be found in <see cref="Message.SystemPropertiesCollection.LockToken"/>,
/// only when <see cref="ReceiveMode"/> is set to <see cref="ServiceBus.ReceiveMode.PeekLock"/>.
/// In order to receive this message again in the future, you will need to save the <see cref="Message.SystemPropertiesCollection.SequenceNumber"/>
/// and receive it using <see cref="ReceiveDeferredMessageAsync(long)"/>.
/// Deferring messages does not impact message's expiration, meaning that deferred messages can still expire.
/// This operation can only be performed on messages that were received by this receiver.
/// </remarks>
public async Task DeferAsync(string lockToken, IDictionary<string, object> propertiesToModify = null)
{
this.ThrowIfClosed();
this.ThrowIfNotPeekLockMode();
MessagingEventSource.Log.MessageDeferStart(this.ClientId, 1, lockToken);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("Defer", lockToken) : null;
Task deferTask = null;
try
{
deferTask = this.RetryPolicy.RunOperation(() => this.OnDeferAsync(lockToken, propertiesToModify),
this.OperationTimeout);
await deferTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessageDeferException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.DisposeStop(activity, lockToken, deferTask?.Status);
}
MessagingEventSource.Log.MessageDeferStop(this.ClientId);
}
/// <summary>
/// Moves a message to the deadletter sub-queue.
/// </summary>
/// <param name="lockToken">The lock token of the corresponding message to deadletter.</param>
/// <param name="propertiesToModify">The properties of the message to modify while moving to sub-queue.</param>
/// <remarks>
/// A lock token can be found in <see cref="Message.SystemPropertiesCollection.LockToken"/>,
/// only when <see cref="ReceiveMode"/> is set to <see cref="ServiceBus.ReceiveMode.PeekLock"/>.
/// In order to receive a message from the deadletter queue, you will need a new <see cref="IMessageReceiver"/>, with the corresponding path.
/// You can use <see cref="EntityNameHelper.FormatDeadLetterPath(string)"/> to help with this.
/// This operation can only be performed on messages that were received by this receiver.
/// </remarks>
public async Task DeadLetterAsync(string lockToken, IDictionary<string, object> propertiesToModify = null)
{
this.ThrowIfClosed();
this.ThrowIfNotPeekLockMode();
MessagingEventSource.Log.MessageDeadLetterStart(this.ClientId, 1, lockToken);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("DeadLetter", lockToken) : null;
Task deadLetterTask = null;
try
{
deadLetterTask = this.RetryPolicy.RunOperation(() => this.OnDeadLetterAsync(lockToken, propertiesToModify),
this.OperationTimeout);
await deadLetterTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessageDeadLetterException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status);
}
MessagingEventSource.Log.MessageDeadLetterStop(this.ClientId);
}
/// <summary>
/// Moves a message to the deadletter sub-queue.
/// </summary>
/// <param name="lockToken">The lock token of the corresponding message to deadletter.</param>
/// <param name="deadLetterReason">The reason for deadlettering the message.</param>
/// <param name="deadLetterErrorDescription">The error description for deadlettering the message.</param>
/// <remarks>
/// A lock token can be found in <see cref="Message.SystemPropertiesCollection.LockToken"/>,
/// only when <see cref="ReceiveMode"/> is set to <see cref="ServiceBus.ReceiveMode.PeekLock"/>.
/// In order to receive a message from the deadletter queue, you will need a new <see cref="IMessageReceiver"/>, with the corresponding path.
/// You can use <see cref="EntityNameHelper.FormatDeadLetterPath(string)"/> to help with this.
/// This operation can only be performed on messages that were received by this receiver.
/// </remarks>
public async Task DeadLetterAsync(string lockToken, string deadLetterReason, string deadLetterErrorDescription = null)
{
this.ThrowIfClosed();
this.ThrowIfNotPeekLockMode();
MessagingEventSource.Log.MessageDeadLetterStart(this.ClientId, 1, lockToken);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("DeadLetter", lockToken) : null;
Task deadLetterTask = null;
try
{
deadLetterTask =
this.RetryPolicy.RunOperation(
() => this.OnDeadLetterAsync(lockToken, null, deadLetterReason, deadLetterErrorDescription),
this.OperationTimeout);
await deadLetterTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessageDeadLetterException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status);
}
MessagingEventSource.Log.MessageDeadLetterStop(this.ClientId);
}
/// <summary>
/// Renews the lock on the message specified by the lock token. The lock will be renewed based on the setting specified on the queue.
/// </summary>
/// <remarks>
/// When a message is received in <see cref="ServiceBus.ReceiveMode.PeekLock"/> mode, the message is locked on the server for this
/// receiver instance for a duration as specified during the Queue/Subscription creation (LockDuration).
/// If processing of the message requires longer than this duration, the lock needs to be renewed.
/// For each renewal, it resets the time the message is locked by the LockDuration set on the Entity.
/// </remarks>
public async Task RenewLockAsync(Message message)
{
message.SystemProperties.LockedUntilUtc = await RenewLockAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
}
/// <summary>
/// Renews the lock on the message. The lock will be renewed based on the setting specified on the queue.
/// <returns>New lock token expiry date and time in UTC format.</returns>
/// </summary>
/// <param name="lockToken">Lock token associated with the message.</param>
/// <remarks>
/// When a message is received in <see cref="ServiceBus.ReceiveMode.PeekLock"/> mode, the message is locked on the server for this
/// receiver instance for a duration as specified during the Queue/Subscription creation (LockDuration).
/// If processing of the message requires longer than this duration, the lock needs to be renewed.
/// For each renewal, it resets the time the message is locked by the LockDuration set on the Entity.
/// </remarks>
public async Task<DateTime> RenewLockAsync(string lockToken)
{
this.ThrowIfClosed();
this.ThrowIfNotPeekLockMode();
MessagingEventSource.Log.MessageRenewLockStart(this.ClientId, 1, lockToken);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.RenewLockStart(lockToken) : null;
Task renewTask = null;
var lockedUntilUtc = DateTime.MinValue;
try
{
renewTask = this.RetryPolicy.RunOperation(
async () => lockedUntilUtc = await this.OnRenewLockAsync(lockToken).ConfigureAwait(false),
this.OperationTimeout);
await renewTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessageRenewLockException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.RenewLockStop(activity, lockToken, renewTask?.Status, lockedUntilUtc);
}
MessagingEventSource.Log.MessageRenewLockStop(this.ClientId);
return lockedUntilUtc;
}
/// <summary>
/// Fetches the next active message without changing the state of the receiver or the message source.
/// </summary>
/// <remarks>
/// The first call to <see cref="PeekAsync()"/> fetches the first active message for this receiver. Each subsequent call
/// fetches the subsequent message in the entity.
/// Unlike a received message, peeked message will not have lock token associated with it, and hence it cannot be Completed/Abandoned/Deferred/Deadlettered/Renewed.
/// Also, unlike <see cref="ReceiveAsync()"/>, this method will fetch even Deferred messages (but not Deadlettered message)
/// </remarks>
/// <returns>The <see cref="Message" /> that represents the next message to be read. Returns null when nothing to peek.</returns>
public Task<Message> PeekAsync()
{
return this.PeekBySequenceNumberAsync(this.lastPeekedSequenceNumber + 1);
}
/// <summary>
/// Fetches the next batch of active messages without changing the state of the receiver or the message source.
/// </summary>
/// <remarks>
/// The first call to <see cref="PeekAsync()"/> fetches the first active message for this receiver. Each subsequent call
/// fetches the subsequent message in the entity.
/// Unlike a received message, peeked message will not have lock token associated with it, and hence it cannot be Completed/Abandoned/Deferred/Deadlettered/Renewed.
/// Also, unlike <see cref="ReceiveAsync()"/>, this method will fetch even Deferred messages (but not Deadlettered message)
/// </remarks>
/// <returns>List of <see cref="Message" /> that represents the next message to be read. Returns null when nothing to peek.</returns>
public Task<IList<Message>> PeekAsync(int maxMessageCount)
{
return this.PeekBySequenceNumberAsync(this.lastPeekedSequenceNumber + 1, maxMessageCount);
}
/// <summary>
/// Asynchronously reads the next message without changing the state of the receiver or the message source.
/// </summary>
/// <param name="fromSequenceNumber">The sequence number from where to read the message.</param>
/// <returns>The asynchronous operation that returns the <see cref="Message" /> that represents the next message to be read.</returns>
public async Task<Message> PeekBySequenceNumberAsync(long fromSequenceNumber)
{
var messages = await this.PeekBySequenceNumberAsync(fromSequenceNumber, 1).ConfigureAwait(false);
return messages?.FirstOrDefault();
}
/// <summary>Peeks a batch of messages.</summary>
/// <param name="fromSequenceNumber">The starting point from which to browse a batch of messages.</param>
/// <param name="messageCount">The number of messages to retrieve.</param>
/// <returns>A batch of messages peeked.</returns>
public async Task<IList<Message>> PeekBySequenceNumberAsync(long fromSequenceNumber, int messageCount)
{
this.ThrowIfClosed();
IList<Message> messages = null;
MessagingEventSource.Log.MessagePeekStart(this.ClientId, fromSequenceNumber, messageCount);
bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled();
Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.PeekStart(fromSequenceNumber, messageCount) : null;
Task peekTask = null;
try
{
peekTask = this.RetryPolicy.RunOperation(
async () =>
{
messages = await this.OnPeekAsync(fromSequenceNumber, messageCount).ConfigureAwait(false);
}, this.OperationTimeout);
await peekTask.ConfigureAwait(false);
}
catch (Exception exception)
{
if (isDiagnosticSourceEnabled)
{
this.diagnosticSource.ReportException(exception);
}
MessagingEventSource.Log.MessagePeekException(this.ClientId, exception);
throw;
}
finally
{
this.diagnosticSource.PeekStop(activity, fromSequenceNumber, messageCount, peekTask?.Status, messages);
}
MessagingEventSource.Log.MessagePeekStop(this.ClientId, messages?.Count ?? 0);
return messages;
}
/// <summary>
/// Receive messages continuously from the entity. Registers a message handler and begins a new thread to receive messages.
/// This handler(<see cref="Func{Message, CancellationToken, Task}"/>) is awaited on every time a new message is received by the receiver.
/// </summary>
/// <param name="handler">A <see cref="Func{T1, T2, TResult}"/> that processes messages.</param>
/// <param name="exceptionReceivedHandler">A <see cref="Func{T1, TResult}"/> that is used to notify exceptions.</param>
public void RegisterMessageHandler(Func<Message, CancellationToken, Task> handler, Func<ExceptionReceivedEventArgs, Task> exceptionReceivedHandler)
{
this.RegisterMessageHandler(handler, new MessageHandlerOptions(exceptionReceivedHandler));
}
/// <summary>
/// Receive messages continuously from the entity. Registers a message handler and begins a new thread to receive messages.
/// This handler(<see cref="Func{Message, CancellationToken, Task}"/>) is awaited on every time a new message is received by the receiver.
/// </summary>
/// <param name="handler">A <see cref="Func{Message, CancellationToken, Task}"/> that processes messages.</param>
/// <param name="messageHandlerOptions">The <see cref="MessageHandlerOptions"/> options used to configure the settings of the pump.</param>
/// <remarks>Enable prefetch to speed up the receive rate.</remarks>
public void RegisterMessageHandler(Func<Message, CancellationToken, Task> handler, MessageHandlerOptions messageHandlerOptions)
{
this.ThrowIfClosed();
this.OnMessageHandler(messageHandlerOptions, handler);
}
/// <summary>
/// Registers a <see cref="ServiceBusPlugin"/> to be used with this receiver.
/// </summary>
public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin)
{
this.ThrowIfClosed();
if (serviceBusPlugin == null)
{
throw new ArgumentNullException(nameof(serviceBusPlugin), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPlugin)));
}
if (this.RegisteredPlugins.Any(p => p.Name == serviceBusPlugin.Name))
{
throw new ArgumentException(nameof(serviceBusPlugin), Resources.PluginAlreadyRegistered.FormatForUser(serviceBusPlugin.Name));
}
this.RegisteredPlugins.Add(serviceBusPlugin);
}
/// <summary>
/// Unregisters a <see cref="ServiceBusPlugin"/>.
/// </summary>
/// <param name="serviceBusPluginName">The <see cref="ServiceBusPlugin.Name"/> of the plugin to be unregistered.</param>
public override void UnregisterPlugin(string serviceBusPluginName)
{
this.ThrowIfClosed();
if (this.RegisteredPlugins == null)
{
return;
}
if (string.IsNullOrWhiteSpace(serviceBusPluginName))
{
throw new ArgumentNullException(nameof(serviceBusPluginName), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPluginName)));
}
if (this.RegisteredPlugins.Any(p => p.Name == serviceBusPluginName))
{
var plugin = this.RegisteredPlugins.First(p => p.Name == serviceBusPluginName);
this.RegisteredPlugins.Remove(plugin);
}
}
internal async Task GetSessionReceiverLinkAsync(TimeSpan serverWaitTime)
{
var timeoutHelper = new TimeoutHelper(serverWaitTime, true);
var receivingAmqpLink = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
var source = (Source)receivingAmqpLink.Settings.Source;
if (!source.FilterSet.TryGetValue<string>(AmqpClientConstants.SessionFilterName, out var tempSessionId))
{
receivingAmqpLink.Session.SafeClose();
throw new ServiceBusException(true, Resources.SessionFilterMissing);
}
if (string.IsNullOrWhiteSpace(tempSessionId))
{
receivingAmqpLink.Session.SafeClose();
throw new ServiceBusException(true, Resources.AmqpFieldSessionId);
}
receivingAmqpLink.Closed += this.OnSessionReceiverLinkClosed;
this.SessionIdInternal = tempSessionId;
this.LockedUntilUtcInternal = receivingAmqpLink.Settings.Properties.TryGetValue<long>(AmqpClientConstants.LockedUntilUtc, out var lockedUntilUtcTicks)
? new DateTime(lockedUntilUtcTicks, DateTimeKind.Utc)
: DateTime.MinValue;
}
internal async Task<AmqpResponseMessage> ExecuteRequestResponseAsync(AmqpRequestMessage amqpRequestMessage)
{
var amqpMessage = amqpRequestMessage.AmqpMessage;
if (this.isSessionReceiver)
{
this.ThrowIfSessionLockLost();
}
var timeoutHelper = new TimeoutHelper(this.OperationTimeout, true);
ArraySegment<byte> transactionId = AmqpConstants.NullBinary;
var ambientTransaction = Transaction.Current;
if (ambientTransaction != null)
{
transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, this.ServiceBusConnection).ConfigureAwait(false);
}
if (!this.RequestResponseLinkManager.TryGetOpenedObject(out var requestResponseAmqpLink))
{
MessagingEventSource.Log.CreatingNewLink(this.ClientId, this.isSessionReceiver, this.SessionIdInternal, true, this.LinkException);
requestResponseAmqpLink = await this.RequestResponseLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
}
var responseAmqpMessage = await Task.Factory.FromAsync(
(c, s) => requestResponseAmqpLink.BeginRequest(amqpMessage, transactionId, timeoutHelper.RemainingTime(), c, s),
(a) => requestResponseAmqpLink.EndRequest(a),
this).ConfigureAwait(false);
return AmqpResponseMessage.CreateResponse(responseAmqpMessage);
}
protected override async Task OnClosingAsync()
{
this.clientLinkManager.Close();
lock (this.messageReceivePumpSyncLock)