-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathReceivingAmqpLink.cs
1284 lines (1127 loc) · 49.6 KB
/
ReceivingAmqpLink.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.Amqp
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Amqp.Framing;
using Microsoft.Azure.Amqp.Transaction;
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "Uses custom scheme for cleanup")]
public sealed class ReceivingAmqpLink : AmqpLink
{
// Workaround for TimeSpan.Zero server wait timeout. Consider supporting this with drain
static readonly TimeSpan MinReceiveTimeout = TimeSpan.FromSeconds(10);
// To support non-prefetch mode with multiple BeginReceive calls
const int MaxCreditForOnDemandReceive = 200;
const int CreditBatchThreshold = 20; // after this we will batch credit to minimize flows
const int PendingReceiversThreshold = 20; // after this we will batch credit to minimize flows
Action<AmqpMessage> messageListener;
SizeBasedFlowQueue messageQueue;
WorkCollection<ArraySegment<byte>, DisposeAsyncResult, DeliveryState> pendingDispositions;
AmqpMessage currentMessage;
LinkedList<ReceiveAsyncResult> waiterList;
HashSet<DrainAsyncResult> drainTasks;
public ReceivingAmqpLink(AmqpLinkSettings settings)
: this(null, settings)
{
}
public ReceivingAmqpLink(AmqpSession session, AmqpLinkSettings settings) :
base("receiver", session, settings)
{
}
public long? TotalCacheSizeInBytes
{
get
{
return this.Settings.TotalCacheSizeInBytes;
}
}
internal int MessageQueueCount
{
get
{
SizeBasedFlowQueue queue = this.messageQueue;
return queue != null ? queue.Count : 0;
}
}
internal long AvgMessageSize
{
get
{
SizeBasedFlowQueue queue = this.messageQueue;
return queue != null ? queue.AverageMessageSizeInBytes : 0;
}
}
internal long MessageQueueSize
{
get
{
SizeBasedFlowQueue queue = this.messageQueue;
if (queue != null && queue.IsPrefetchingBySize)
{
long totalSize = 0;
if (this.TotalCacheSizeInBytes.HasValue)
{
totalSize = this.TotalCacheSizeInBytes.Value;
}
return totalSize - queue.CacheSizeCredit;
}
return 0;
}
}
public void SetCacheSizeInBytes(long? cacheSizeInBytes)
{
if (cacheSizeInBytes != this.Settings.TotalCacheSizeInBytes)
{
this.Settings.TotalCacheSizeInBytes = cacheSizeInBytes;
SizeBasedFlowQueue queue = this.messageQueue;
if (queue != null)
{
queue.SetLinkCreditUsingTotalCacheSize();
}
}
}
public void RegisterMessageListener(Action<AmqpMessage> messageListener)
{
if (Interlocked.Exchange(ref this.messageListener, messageListener) != null)
{
throw new InvalidOperationException(CommonResources.MessageListenerAlreadyRegistered);
}
}
public IAsyncResult BeginReceiveRemoteMessages(int messageCount, TimeSpan batchWaitTimeout, TimeSpan timeout, AsyncCallback callback, object state)
{
// If the caller expects some messages and pass TimeSpan.Zero, we wait to mimic a service call
if (timeout == TimeSpan.Zero && !this.Settings.AutoSendFlow)
{
timeout = MinReceiveTimeout;
}
return this.BeginReceiveMessages(messageCount, batchWaitTimeout, timeout, CancellationToken.None, callback, state);
}
public Task<AmqpMessage> ReceiveMessageAsync(TimeSpan timeout)
{
return this.ReceiveMessageAsync(timeout, CancellationToken.None);
}
public Task<AmqpMessage> ReceiveMessageAsync(CancellationToken cancellationToken)
{
return this.ReceiveMessageAsync(this.OperationTimeout, cancellationToken);
}
public Task<AmqpMessage> ReceiveMessageAsync(TimeSpan timeout, CancellationToken cancellationToken)
{
return Task.Factory.FromAsync(
(t, k, c, s) => ((ReceivingAmqpLink)s).BeginReceiveMessages(1, TimeSpan.Zero, t, k, c, s),
r =>
{
((ReceivingAmqpLink)r.AsyncState).EndReceiveMessages(r, out var messages);
return messages.FirstOrDefault();
},
timeout,
cancellationToken,
this);
}
public Task<IEnumerable<AmqpMessage>> ReceiveMessagesAsync(int messageCount, TimeSpan batchWaitTimeout)
{
return this.ReceiveMessagesAsync(messageCount, batchWaitTimeout, this.OperationTimeout, CancellationToken.None);
}
public Task<IEnumerable<AmqpMessage>> ReceiveMessagesAsync(int messageCount, TimeSpan batchWaitTimeout, CancellationToken cancellationToken)
{
return this.ReceiveMessagesAsync(messageCount, batchWaitTimeout, this.OperationTimeout, cancellationToken);
}
public Task<IEnumerable<AmqpMessage>> ReceiveMessagesAsync(int messageCount, TimeSpan batchWaitTimeout, TimeSpan timeout, CancellationToken cancellationToken)
{
return Task.Factory.FromAsync(
(p, c, s) => ((ReceivingAmqpLink)s).BeginReceiveMessages(p.MessageCount, p.BatchWaitTime, p.Timeout, p.CancellationToken, c, s),
r => { ((ReceivingAmqpLink)r.AsyncState).EndReceiveMessages(r, out var messages); return messages; },
new ReceiveParam(messageCount, batchWaitTimeout, timeout, cancellationToken),
this);
}
public IAsyncResult BeginReceiveMessage(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.BeginReceiveMessages(1, TimeSpan.Zero, timeout, CancellationToken.None, callback, state);
}
public bool EndReceiveMessage(IAsyncResult result, out AmqpMessage message)
{
if (result is ReceiveAsyncResult)
{
IEnumerable<AmqpMessage> messages;
bool retValue = ReceiveAsyncResult.End(result, out messages);
message = messages.FirstOrDefault();
return retValue;
}
message = CompletedAsyncResult<IEnumerable<AmqpMessage>>.End(result).FirstOrDefault();
return true;
}
public IAsyncResult BeginReceiveMessages(int messageCount, TimeSpan timeout, AsyncCallback callback, object state)
{
return BeginReceiveMessages(messageCount, TimeSpan.Zero, timeout, CancellationToken.None, callback, state);
}
IAsyncResult BeginReceiveMessages(int messageCount, TimeSpan batchWaitTimeout, TimeSpan timeout, CancellationToken cancellationToken, AsyncCallback callback, object state)
{
this.ThrowIfClosed();
List<AmqpMessage> messages = new List<AmqpMessage>();
lock (this.SyncRoot)
{
if (this.messageQueue != null && this.messageQueue.Count > 0)
{
for (int i = 0; i < messageCount && this.messageQueue.Count > 0; i++)
{
messages.Add(this.messageQueue.Dequeue());
}
}
}
if (messages.Count == 0 && timeout > TimeSpan.Zero)
{
ReceiveAsyncResult waiter = new ReceiveAsyncResult(this, messageCount, batchWaitTimeout, timeout, callback, state);
bool completeWaiter = true;
lock (this.SyncRoot)
{
if (this.messageQueue == null)
{
// closed, so return null message immediately
}
else if (this.messageQueue.Count > 0)
{
for (int i = 0; i < messageCount && this.messageQueue.Count > 0; i++)
{
messages.Add(this.messageQueue.Dequeue());
}
}
else
{
LinkedListNode<ReceiveAsyncResult> node = this.waiterList.AddLast(waiter);
waiter.Initialize(node, cancellationToken);
completeWaiter = false;
// If no auto-flow, trigger a flow to get messages.
int creditToIssue = this.Settings.AutoSendFlow ? 0 : this.GetOnDemandReceiveCredit();
if (creditToIssue > 0)
{
// Before the credit is issued, waiters could be completed already. In this case, we will queue the incoming
// messages and wait for the next receive calls.
this.IssueCredit((uint)creditToIssue, false, AmqpConstants.NullBinary);
}
}
}
if (completeWaiter)
{
waiter.Signal(messages, true);
}
return waiter;
}
return new CompletedAsyncResult<IEnumerable<AmqpMessage>>(messages, callback, state);
}
protected override void OnReceiveStateOpenSent(Attach attach)
{
// If we uses prefetchBySize logic, then we need to
// Update link credit based on Gateway's return max message size
lock (this.SyncRoot)
{
var queue = this.messageQueue as SizeBasedFlowQueue;
if (queue != null)
{
queue.SetLinkCreditUsingTotalCacheSize();
}
}
}
public bool EndReceiveMessages(IAsyncResult result, out IEnumerable<AmqpMessage> messages)
{
if (result is ReceiveAsyncResult)
{
return ReceiveAsyncResult.End(result, out messages);
}
messages = CompletedAsyncResult<IEnumerable<AmqpMessage>>.End(result);
return true;
}
public Task DrainAsyc(CancellationToken cancellationToken)
{
return Task.Factory.FromAsync(
(thisPtr, k, c, s) => new DrainAsyncResult(thisPtr, thisPtr.OperationTimeout, k, c, s),
r => DrainAsyncResult.End(r),
this,
cancellationToken,
this);
}
public Task<Outcome> DisposeMessageAsync(ArraySegment<byte> deliveryTag, Outcome outcome, bool batchable, TimeSpan timeout)
{
return this.DisposeMessageAsync(deliveryTag, AmqpConstants.NullBinary, outcome, batchable, timeout);
}
public Task<Outcome> DisposeMessageAsync(ArraySegment<byte> deliveryTag, ArraySegment<byte> txnId, Outcome outcome, bool batchable, TimeSpan timeout)
{
return Task.Factory.FromAsync(
(p, t, k, c, s) => ((ReceivingAmqpLink)s).BeginDisposeMessage(p.DeliveryTag, p.TxnId, p.Outcome, p.Batchable, t, k, c, s),
r => ((ReceivingAmqpLink)r.AsyncState).EndDisposeMessage(r),
new DisposeParam(deliveryTag, txnId, outcome, batchable),
timeout,
CancellationToken.None,
this);
}
public Task<Outcome> DisposeMessageAsync(ArraySegment<byte> deliveryTag, Outcome outcome, bool batchable, CancellationToken cancellationToken)
{
return this.DisposeMessageAsync(deliveryTag, AmqpConstants.NullBinary, outcome, batchable, cancellationToken);
}
public Task<Outcome> DisposeMessageAsync(ArraySegment<byte> deliveryTag, ArraySegment<byte> txnId, Outcome outcome, bool batchable, CancellationToken cancellationToken)
{
return Task.Factory.FromAsync(
(p, t, k, c, s) => ((ReceivingAmqpLink)s).BeginDisposeMessage(p.DeliveryTag, p.TxnId, p.Outcome, p.Batchable, t, k, c, s),
r => ((ReceivingAmqpLink)r.AsyncState).EndDisposeMessage(r),
new DisposeParam(deliveryTag, txnId, outcome, batchable),
this.OperationTimeout,
cancellationToken,
this);
}
public IAsyncResult BeginDisposeMessage(ArraySegment<byte> deliveryTag, Outcome outcome, bool batchable, TimeSpan timeout, AsyncCallback callback, object state)
{
return this.BeginDisposeMessage(deliveryTag, AmqpConstants.NullBinary, outcome, batchable, timeout, CancellationToken.None, callback, state);
}
public IAsyncResult BeginDisposeMessage(ArraySegment<byte> deliveryTag, ArraySegment<byte> txnId, Outcome outcome, bool batchable, TimeSpan timeout, AsyncCallback callback, object state)
{
return this.BeginDisposeMessage(deliveryTag, txnId, outcome, batchable, timeout, CancellationToken.None, callback, state);
}
public Outcome EndDisposeMessage(IAsyncResult result)
{
return DisposeAsyncResult.End(result);
}
public void AcceptMessage(AmqpMessage message, bool batchable)
{
bool settled = this.Settings.SettleType != SettleMode.SettleOnDispose;
this.AcceptMessage(message, settled, batchable);
}
public void AcceptMessage(AmqpMessage message, bool settled, bool batchable)
{
this.DisposeMessage(message, AmqpConstants.AcceptedOutcome, settled, batchable);
}
public void RejectMessage(AmqpMessage message, Exception exception)
{
Rejected rejected = new Rejected();
rejected.Error = Error.FromException(exception);
this.DisposeMessage(message, rejected, true, false);
}
public void ReleaseMessage(AmqpMessage message)
{
this.DisposeMessage(message, AmqpConstants.ReleasedOutcome, true, false);
}
public void ModifyMessage(AmqpMessage message, bool deliveryFailed, bool deliverElseWhere, Fields messageAttributes)
{
Modified modified = new Modified();
modified.DeliveryFailed = deliveryFailed;
modified.UndeliverableHere = deliverElseWhere;
modified.MessageAnnotations = messageAttributes;
this.DisposeMessage(message, modified, true, false);
}
public void DisposeMessage(AmqpMessage message, DeliveryState state, bool settled, bool batchable)
{
this.ThrowIfClosed();
message.Batchable = batchable;
this.DisposeDelivery(message, settled, state);
}
public override bool CreateDelivery(Transfer transfer, out Delivery delivery)
{
if (this.currentMessage != null)
{
delivery = this.currentMessage;
return false;
}
else
{
delivery = this.currentMessage = AmqpMessage.CreateReceivedMessage();
return true;
}
}
protected override bool OpenInternal()
{
this.messageQueue = new SizeBasedFlowQueue(this);
this.waiterList = new LinkedList<ReceiveAsyncResult>();
this.pendingDispositions = new WorkCollection<ArraySegment<byte>, DisposeAsyncResult, DeliveryState>(ByteArrayComparer.Instance);
bool syncComplete = base.OpenInternal();
if (this.LinkCredit > 0)
{
this.SendFlow(false);
}
return syncComplete;
}
protected override void OnDisposeDeliveryInternal(Delivery delivery)
{
// This happens when the sender sends a disposition after the receiver's disposition
// in the EO delivery scenario, and also in transaction case.
AmqpTrace.Provider.AmqpDispose(this, delivery.DeliveryId.Value, delivery.Settled, delivery.State);
DeliveryState deliveryState = delivery.State;
if (deliveryState != null)
{
this.pendingDispositions.CompleteWork(delivery.DeliveryTag, false, deliveryState);
}
}
protected override void OnProcessTransfer(Delivery delivery, Transfer transfer, Frame frame)
{
Fx.Assert(delivery == null || delivery == this.currentMessage, "The delivery must be null or must be the same as the current message.");
if (this.Settings.MaxMessageSize.HasValue && this.Settings.MaxMessageSize.Value > 0)
{
ulong size = (ulong)(this.currentMessage.BytesTransfered + frame.Payload.Count);
if (size > this.Settings.MaxMessageSize.Value)
{
if (this.IsClosing())
{
// The closing sequence has been started, so any
// transfer is meaningless, so we can treat them as no-op
return;
}
throw new AmqpException(AmqpErrorCode.MessageSizeExceeded,
AmqpResources.GetString(AmqpResources.AmqpMessageSizeExceeded, this.currentMessage.DeliveryId.Value, size, this.Settings.MaxMessageSize.Value));
}
}
Fx.Assert(this.currentMessage != null, "Current message must have been created!");
ArraySegment<byte> payload = frame.Payload;
frame.RawByteBuffer.AdjustPosition(payload.Offset, payload.Count);
frame.RawByteBuffer.AddReference(); // Message also owns the buffer from now on
this.currentMessage.AddPayload(frame.RawByteBuffer, !transfer.More());
if (!transfer.More())
{
AmqpMessage message = this.currentMessage;
this.currentMessage = null;
AmqpTrace.Provider.AmqpReceiveMessage(this, message.DeliveryId.Value, message.RawByteBuffers.Count);
this.OnReceiveMessage(message);
}
}
protected override void OnCreditAvailable(int session, uint link, bool drain, ArraySegment<byte> txnId)
{
}
protected override void AbortInternal()
{
Queue<AmqpMessage> messages = null;
this.CancelPendingOperations(true, out messages);
if (messages != null)
{
foreach (AmqpMessage message in messages)
{
message.Dispose();
}
}
AmqpMessage temp = this.currentMessage;
if (temp != null)
{
temp.Dispose();
}
base.AbortInternal();
}
protected override bool CloseInternal()
{
Queue<AmqpMessage> messages = null;
this.CancelPendingOperations(false, out messages);
if (messages != null)
{
foreach (AmqpMessage message in messages)
{
this.DisposeDelivery(message, true, AmqpConstants.ReleasedOutcome);
message.Dispose();
}
}
AmqpMessage temp = this.currentMessage;
if (temp != null)
{
temp.Dispose();
}
return base.CloseInternal();
}
protected override void OnReceiveFlow(Flow flow)
{
bool draining = this.Drain;
base.OnReceiveFlow(flow);
if (draining && this.LinkCredit == 0)
{
HashSet<DrainAsyncResult> pendingTasks = null;
lock (this.SyncRoot)
{
pendingTasks = this.drainTasks;
this.drainTasks = null;
}
if (pendingTasks != null)
{
foreach (var task in pendingTasks)
{
task.Signal(false);
}
}
}
}
IAsyncResult BeginDisposeMessage(ArraySegment<byte> deliveryTag, ArraySegment<byte> txnId, Outcome outcome, bool batchable,
TimeSpan timeout, CancellationToken cancellationToken, AsyncCallback callback, object state)
{
this.ThrowIfClosed();
return new DisposeAsyncResult(this, deliveryTag, txnId, outcome, batchable, timeout, cancellationToken, callback, state);
}
void CancelPendingOperations(bool aborted, out Queue<AmqpMessage> messagesToRelease)
{
messagesToRelease = null;
LinkedList<ReceiveAsyncResult> waiters = null;
lock (this.SyncRoot)
{
messagesToRelease = this.messageQueue;
waiters = this.waiterList;
this.messageQueue = null;
this.waiterList = null;
}
if (waiters != null)
{
ActionItem.Schedule(o =>
{
var state = (Tuple<LinkedList<ReceiveAsyncResult>, bool>)o;
LinkedList<ReceiveAsyncResult> waitersToCancel = state.Item1;
foreach (ReceiveAsyncResult waiter in waitersToCancel)
{
if (state.Item2)
{
waiter.Cancel();
}
else
{
waiter.Signal(false, null);
}
}
},
new Tuple<LinkedList<ReceiveAsyncResult>, bool>(waiters, aborted));
}
if (this.pendingDispositions != null)
{
this.pendingDispositions.Abort();
}
}
void OnReceiveMessage(AmqpMessage message)
{
if (this.messageListener != null)
{
this.messageListener(message);
}
else
{
ReceiveAsyncResult waiter = null;
int creditToIssue = 0;
bool releaseMessage = false;
lock (this.SyncRoot)
{
if (this.waiterList != null && this.waiterList.Count > 0)
{
var firstWaiter = this.waiterList.First.Value;
if (this.messageQueue.IsPrefetchingBySize)
{
if (this.messageQueue.UpdateCreditToIssue(message))
{
this.SetTotalLinkCredit(this.messageQueue.BoundedTotalLinkCredit, true);
}
}
firstWaiter.Add(message);
if (firstWaiter.RequestedMessageCount == 1 || firstWaiter.MessageCount >= firstWaiter.RequestedMessageCount)
{
this.waiterList.RemoveFirst();
firstWaiter.OnRemoved();
creditToIssue = this.Settings.AutoSendFlow ? 0 : this.GetOnDemandReceiveCredit();
waiter = firstWaiter;
}
}
else if (!this.Settings.AutoSendFlow && this.Settings.SettleType != SettleMode.SettleOnSend)
{
releaseMessage = true;
}
else if (this.messageQueue != null)
{
this.messageQueue.Enqueue(message);
AmqpTrace.Provider.AmqpCacheMessage(
this,
message.DeliveryId.Value,
this.messageQueue.Count,
this.messageQueue.IsPrefetchingBySize,
this.TotalCacheSizeInBytes ?? 0,
this.Settings == null ? 0 : this.Settings.TotalLinkCredit,
this.LinkCredit);
}
}
if (releaseMessage)
{
this.ReleaseMessage(message);
message.Dispose();
}
if (creditToIssue > 0)
{
this.IssueCredit((uint)creditToIssue, false, AmqpConstants.NullBinary);
}
if (waiter != null)
{
// Schedule the completion on another thread so we don't block the I/O thread
ActionItem.Schedule(o => { var w = (ReceiveAsyncResult)o; w.Signal(false); }, waiter);
}
}
}
// Must be called with lock held
int GetOnDemandReceiveCredit()
{
Fx.Assert(!this.Settings.AutoSendFlow, "This is only valid when auto-flow is false");
int credit = 0;
int currentCredit = (int)this.LinkCredit;
int totalRequestedMessageCount = 0;
foreach (var waiter in this.waiterList)
{
totalRequestedMessageCount += waiter.RequestedMessageCount;
}
if (this.waiterList.Count == totalRequestedMessageCount)
{
if (this.waiterList.Count > currentCredit &&
currentCredit < MaxCreditForOnDemandReceive)
{
int needCredit = Math.Min(this.waiterList.Count, MaxCreditForOnDemandReceive) - currentCredit;
if (this.waiterList.Count <= CreditBatchThreshold ||
currentCredit == 0 ||
needCredit % CreditBatchThreshold == 0)
{
credit = currentCredit + needCredit;
}
}
}
else
{
if (totalRequestedMessageCount > currentCredit)
{
int needCredit = totalRequestedMessageCount - currentCredit;
if (this.waiterList.Count <= PendingReceiversThreshold ||
currentCredit == 0 ||
this.waiterList.Count % PendingReceiversThreshold == 0)
{
credit = currentCredit + needCredit;
}
}
}
return credit;
}
struct ReceiveParam
{
public ReceiveParam(int messageCount, TimeSpan batchWaitTime, TimeSpan timeout, CancellationToken cancellationToken)
{
this.MessageCount = messageCount;
this.BatchWaitTime = batchWaitTime;
this.Timeout = timeout;
this.CancellationToken = cancellationToken;
}
public readonly int MessageCount;
public readonly TimeSpan BatchWaitTime;
public readonly TimeSpan Timeout;
public readonly CancellationToken CancellationToken;
}
struct DisposeParam
{
public DisposeParam(ArraySegment<byte> deliveryTag, ArraySegment<byte> txnId, Outcome outcome, bool batchable)
{
this.DeliveryTag = deliveryTag;
this.TxnId = txnId;
this.Outcome = outcome;
this.Batchable = batchable;
}
public readonly ArraySegment<byte> DeliveryTag;
public readonly ArraySegment<byte> TxnId;
public readonly Outcome Outcome;
public readonly bool Batchable;
}
sealed class ReceiveAsyncResult : AsyncResult
{
readonly ReceivingAmqpLink parent;
readonly int requestedMessageCount;
readonly TimeSpan batchWaitTimeout;
readonly TimeSpan timeout;
CancellationTokenRegistration cancellationTokenRegistration;
Timer timer;
LinkedListNode<ReceiveAsyncResult> node;
int completed; // 1: signaled, 2: timeout
List<AmqpMessage> messages;
public ReceiveAsyncResult(ReceivingAmqpLink parent, int requestedMessageCount, TimeSpan batchWaitTimeout,
TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.parent = parent;
this.batchWaitTimeout = batchWaitTimeout;
this.requestedMessageCount = requestedMessageCount;
Fx.Assert(timeout > TimeSpan.Zero, "must have a non-zero timeout");
this.timeout = timeout;
}
public int RequestedMessageCount
{
get
{
return this.requestedMessageCount;
}
}
public int MessageCount
{
get
{
return this.messages != null ? this.messages.Count : 0;
}
}
public void Initialize(LinkedListNode<ReceiveAsyncResult> node, CancellationToken cancellationToken)
{
this.node = node;
if (this.timeout != TimeSpan.MaxValue)
{
this.timer = new Timer(s => OnTimer(s), this, this.timeout, Timeout.InfiniteTimeSpan);
}
if (cancellationToken.CanBeCanceled)
{
this.cancellationTokenRegistration = cancellationToken.Register(o =>
{
ReceiveAsyncResult result = (ReceiveAsyncResult)o;
RemoveFromWaiterList(result);
result.Signal(false, new TaskCanceledException());
}, this);
}
}
// Needs caller to hold lock to ReceivingAmqpLink.SyncRoot
public void Add(AmqpMessage message)
{
if (this.messages == null)
{
this.messages = new List<AmqpMessage>();
this.messages.Add(message);
if (this.requestedMessageCount > 1 && this.batchWaitTimeout != TimeSpan.MaxValue)
{
this.timer.Change(this.batchWaitTimeout, Timeout.InfiniteTimeSpan);
}
}
else
{
this.messages.Add(message);
}
}
public static bool End(IAsyncResult result, out IEnumerable<AmqpMessage> messages)
{
ReceiveAsyncResult thisPtr = AsyncResult.End<ReceiveAsyncResult>(result);
messages = thisPtr.messages != null ? thisPtr.messages : AmqpConstants.EmptyMessages;
return thisPtr.completed == 1;
}
// Ensure the lock is held when calling this function
public void OnRemoved()
{
this.node = null;
}
public void Cancel()
{
if (this.parent.TerminalException != null)
{
this.Signal(false, new OperationCanceledException(this.parent.TerminalException.Message, this.parent.TerminalException));
}
else
{
this.Signal(false, new OperationCanceledException());
}
}
public void Signal(bool syncComplete)
{
this.Signal(syncComplete, null);
}
public void Signal(List<AmqpMessage> messages, bool syncComplete)
{
if (this.messages != null)
{
this.messages.AddRange(messages);
}
else
{
this.messages = messages;
}
this.Signal(syncComplete, null);
}
public void Signal(bool syncComplete, Exception exception)
{
this.CompleteInternal(syncComplete, 1, exception);
}
void CompleteInternal(bool syncComplete, int code, Exception exception)
{
Timer t = this.timer;
if (t != null)
{
t.Dispose();
}
this.cancellationTokenRegistration.Dispose();
if (Interlocked.CompareExchange(ref this.completed, code, 0) == 0)
{
if (this.messages == null)
{
this.messages = new List<AmqpMessage>();
}
if (exception != null)
{
this.Complete(syncComplete, exception);
}
else
{
this.Complete(syncComplete);
}
}
}
internal static void OnTimer(object state)
{
ReceiveAsyncResult thisPtr = (ReceiveAsyncResult)state;
RemoveFromWaiterList(thisPtr);
thisPtr.CompleteInternal(false, thisPtr.MessageCount > 0 ? 1 : 2, null); // 1: signaled, 2: timeout
}
private static void RemoveFromWaiterList(ReceiveAsyncResult result)
{
lock (result.parent.SyncRoot)
{
if (result.parent.waiterList == null || result.node == null)
{
return;
}
result.parent.waiterList.Remove(result.node);
result.node = null;
}
}
}
sealed class DrainAsyncResult : TimeoutAsyncResult<string>
{
readonly ReceivingAmqpLink link;
public DrainAsyncResult(ReceivingAmqpLink link,
TimeSpan timeout,
CancellationToken cancellationToken,
AsyncCallback callback,
object state)
: base(timeout, cancellationToken, callback, state)
{
this.link = link;
this.Start();
}
public static void End(IAsyncResult result)
{
AsyncResult.End<DrainAsyncResult>(result);
}
public void Signal(bool isSynchronous)
{
this.CompleteSelf(isSynchronous);
}
public override void Cancel(bool isSynchronous)
{
if (this.Remove())
{
this.CompleteSelf(isSynchronous, new TaskCanceledException());
}
}
protected override string Target
{
get { return "drain"; }
}
protected override void CompleteOnTimer()
{
if (this.Remove())
{
base.CompleteOnTimer();
}
}
void Start()
{
lock (this.link.SyncRoot)
{
if (this.link.drainTasks == null)
{
this.link.drainTasks = new HashSet<DrainAsyncResult>();
}
this.link.drainTasks.Add(this);
if (!this.link.Drain)
{
this.link.SendFlow(false, true, null);
}
}
this.StartTracking();
}
bool Remove()
{
lock (this.link.SyncRoot)
{
if (this.link.drainTasks == null || !this.link.drainTasks.Remove(this))
{
return false;
}
if (this.link.drainTasks.Count == 0)
{
this.link.drainTasks = null;
}
}
return true;
}
}
sealed class DisposeAsyncResult : TimeoutAsyncResult<string>, IWork<DeliveryState>
{
readonly ReceivingAmqpLink link;
readonly ArraySegment<byte> deliveryTag;
readonly bool batchable;
Outcome outcome;
ArraySegment<byte> txnId;
public DisposeAsyncResult(
ReceivingAmqpLink link,
ArraySegment<byte> deliveryTag,
ArraySegment<byte> txnId,
Outcome outcome,
bool batchable,
TimeSpan timeout,
CancellationToken cancellationToken,
AsyncCallback callback,
object state)
: base(timeout, cancellationToken, callback, state)
{
this.link = link;
this.deliveryTag = deliveryTag;
this.batchable = batchable;
this.outcome = outcome;
this.txnId = txnId;
this.link.pendingDispositions.StartWork(deliveryTag, this);
}
public static Outcome End(IAsyncResult result)
{
return AsyncResult.End<DisposeAsyncResult>(result).outcome;