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
|
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Runtime;
using System.Threading;
using System.Xml;
delegate IAsyncResult BeginSendHandler(MessageAttemptInfo attemptInfo, TimeSpan timeout, bool maskUnhandledException, AsyncCallback asyncCallback, object state);
delegate void EndSendHandler(IAsyncResult result);
delegate void SendHandler(MessageAttemptInfo attemptInfo, TimeSpan timeout, bool maskUnhandledException);
delegate void ComponentFaultedHandler(Exception faultException, WsrmFault fault);
delegate void ComponentExceptionHandler(Exception exception);
delegate void RetryHandler(MessageAttemptInfo attemptInfo);
sealed class ReliableOutputConnection
{
BeginSendHandler beginSendHandler;
OperationWithTimeoutBeginCallback beginSendAckRequestedHandler;
bool closed = false;
EndSendHandler endSendHandler;
OperationEndCallback endSendAckRequestedHandler;
UniqueId id;
MessageVersion messageVersion;
object mutex = new Object();
static AsyncCallback onSendRetriesComplete = Fx.ThunkCallback(new AsyncCallback(OnSendRetriesComplete));
static AsyncCallback onSendRetryComplete = Fx.ThunkCallback(new AsyncCallback(OnSendRetryComplete));
ReliableMessagingVersion reliableMessagingVersion;
Guard sendGuard = new Guard(Int32.MaxValue);
SendHandler sendHandler;
OperationWithTimeoutCallback sendAckRequestedHandler;
static Action<object> sendRetries = new Action<object>(SendRetries);
TimeSpan sendTimeout;
InterruptibleWaitObject shutdownHandle = new InterruptibleWaitObject(false);
TransmissionStrategy strategy;
bool terminated = false;
public ReliableOutputConnection(UniqueId id,
int maxTransferWindowSize,
MessageVersion messageVersion,
ReliableMessagingVersion reliableMessagingVersion,
TimeSpan initialRtt,
bool requestAcks,
TimeSpan sendTimeout)
{
this.id = id;
this.messageVersion = messageVersion;
this.reliableMessagingVersion = reliableMessagingVersion;
this.sendTimeout = sendTimeout;
this.strategy = new TransmissionStrategy(reliableMessagingVersion, initialRtt, maxTransferWindowSize,
requestAcks, id);
this.strategy.RetryTimeoutElapsed = OnRetryTimeoutElapsed;
this.strategy.OnException = RaiseOnException;
}
public ComponentFaultedHandler Faulted;
public ComponentExceptionHandler OnException;
MessageVersion MessageVersion
{
get
{
return this.messageVersion;
}
}
public BeginSendHandler BeginSendHandler
{
set
{
this.beginSendHandler = value;
}
}
public OperationWithTimeoutBeginCallback BeginSendAckRequestedHandler
{
set
{
this.beginSendAckRequestedHandler = value;
}
}
public bool Closed
{
get
{
return this.closed;
}
}
public EndSendHandler EndSendHandler
{
set
{
this.endSendHandler = value;
}
}
public OperationEndCallback EndSendAckRequestedHandler
{
set
{
this.endSendAckRequestedHandler = value;
}
}
public Int64 Last
{
get
{
return this.strategy.Last;
}
}
public SendHandler SendHandler
{
set
{
this.sendHandler = value;
}
}
public OperationWithTimeoutCallback SendAckRequestedHandler
{
set
{
this.sendAckRequestedHandler = value;
}
}
public TransmissionStrategy Strategy
{
get
{
return this.strategy;
}
}
object ThisLock
{
get { return this.mutex; }
}
public void Abort(ChannelBase channel)
{
this.sendGuard.Abort();
this.shutdownHandle.Abort(channel);
this.strategy.Abort(channel);
}
void CompleteTransfer(TimeSpan timeout)
{
if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
{
Message message = Message.CreateMessage(this.MessageVersion, WsrmFeb2005Strings.LastMessageAction);
message.Properties.AllowOutputBatching = false;
// Return value ignored.
this.InternalAddMessage(message, timeout, null, true);
}
else if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
{
if (this.strategy.SetLast())
{
this.shutdownHandle.Set();
}
else
{
this.sendAckRequestedHandler(timeout);
}
}
else
{
throw Fx.AssertAndThrow("Unsupported version.");
}
}
public bool AddMessage(Message message, TimeSpan timeout, object state)
{
return this.InternalAddMessage(message, timeout, state, false);
}
public IAsyncResult BeginAddMessage(Message message, TimeSpan timeout, object state, AsyncCallback callback, object asyncState)
{
return new AddAsyncResult(message, false, timeout, state, this, callback, asyncState);
}
public bool EndAddMessage(IAsyncResult result)
{
return AddAsyncResult.End(result);
}
IAsyncResult BeginCompleteTransfer(TimeSpan timeout, AsyncCallback callback, object state)
{
if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
{
Message message = Message.CreateMessage(this.MessageVersion, WsrmFeb2005Strings.LastMessageAction);
message.Properties.AllowOutputBatching = false;
return new AddAsyncResult(message, true, timeout, null, this, callback, state);
}
else if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
{
if (this.strategy.SetLast())
{
this.shutdownHandle.Set();
return new AlreadyCompletedTransferAsyncResult(callback, state);
}
else
{
return this.beginSendAckRequestedHandler(timeout, callback, state);
}
}
else
{
throw Fx.AssertAndThrow("Unsupported version.");
}
}
void EndCompleteTransfer(IAsyncResult result)
{
if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
{
AddAsyncResult.End(result);
}
else if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
{
AlreadyCompletedTransferAsyncResult completedResult = result as AlreadyCompletedTransferAsyncResult;
if (completedResult != null)
{
completedResult.End();
}
else
{
this.endSendAckRequestedHandler(result);
}
}
else
{
throw Fx.AssertAndThrow("Unsupported version.");
}
}
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
bool completeTransfer = false;
lock (this.ThisLock)
{
completeTransfer = !this.closed;
this.closed = true;
}
OperationWithTimeoutBeginCallback[] beginCallbacks;
OperationEndCallback[] endCallbacks;
beginCallbacks = new OperationWithTimeoutBeginCallback[] {
completeTransfer ? this.BeginCompleteTransfer : default(OperationWithTimeoutBeginCallback),
this.shutdownHandle.BeginWait,
this.sendGuard.BeginClose,
this.beginSendAckRequestedHandler };
endCallbacks = new OperationEndCallback[] {
completeTransfer ? this.EndCompleteTransfer : default(OperationEndCallback),
this.shutdownHandle.EndWait,
this.sendGuard.EndClose,
this.endSendAckRequestedHandler };
return OperationWithTimeoutComposer.BeginComposeAsyncOperations(timeout, beginCallbacks, endCallbacks, callback, state);
}
public bool CheckForTermination()
{
return this.strategy.DoneTransmitting;
}
public void Close(TimeSpan timeout)
{
bool completeTransfer = false;
lock (this.ThisLock)
{
completeTransfer = !this.closed;
this.closed = true;
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (completeTransfer)
{
this.CompleteTransfer(timeoutHelper.RemainingTime());
}
this.shutdownHandle.Wait(timeoutHelper.RemainingTime());
this.sendGuard.Close(timeoutHelper.RemainingTime());
this.strategy.Close();
}
void CompleteSendRetries(IAsyncResult result)
{
while (true)
{
this.endSendHandler(result);
this.sendGuard.Exit();
this.strategy.DequeuePending();
if (this.sendGuard.Enter())
{
MessageAttemptInfo attemptInfo = this.strategy.GetMessageInfoForRetry(true);
if (attemptInfo.Message == null)
{
break;
}
else
{
result = this.beginSendHandler(attemptInfo, this.sendTimeout, true, onSendRetriesComplete, this);
if (!result.CompletedSynchronously)
{
return;
}
}
}
else
{
return;
}
}
// We are here if there are no more messages to retry.
this.sendGuard.Exit();
this.OnTransferComplete();
}
void CompleteSendRetry(IAsyncResult result)
{
try
{
this.endSendHandler(result);
}
finally
{
this.sendGuard.Exit();
}
}
public void EndClose(IAsyncResult result)
{
OperationWithTimeoutComposer.EndComposeAsyncOperations(result);
this.strategy.Close();
}
public void Fault(ChannelBase channel)
{
this.sendGuard.Abort();
this.shutdownHandle.Fault(channel);
this.strategy.Fault(channel);
}
bool InternalAddMessage(Message message, TimeSpan timeout, object state, bool isLast)
{
MessageAttemptInfo attemptInfo;
TimeoutHelper helper = new TimeoutHelper(timeout);
try
{
if (isLast)
{
if (state != null)
{
throw Fx.AssertAndThrow("The isLast overload does not take a state.");
}
attemptInfo = this.strategy.AddLast(message, helper.RemainingTime(), null);
}
else if (!this.strategy.Add(message, helper.RemainingTime(), state, out attemptInfo))
{
return false;
}
}
catch (TimeoutException)
{
if (isLast)
this.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.id, SR.GetString(SR.SequenceTerminatedAddLastToWindowTimedOut), null));
// else - RM does not fault the channel based on a timeout exception trying to add a sequenced message to the window.
throw;
}
catch (Exception e)
{
if (!Fx.IsFatal(e))
this.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.id, SR.GetString(SR.SequenceTerminatedUnknownAddToWindowError), null));
throw;
}
if (sendGuard.Enter())
{
try
{
this.sendHandler(attemptInfo, helper.RemainingTime(), false);
}
catch (QuotaExceededException)
{
this.RaiseFault(null, SequenceTerminatedFault.CreateQuotaExceededFault(this.id));
throw;
}
finally
{
this.sendGuard.Exit();
}
}
return true;
}
public bool IsFinalAckConsistent(SequenceRangeCollection ranges)
{
return this.strategy.IsFinalAckConsistent(ranges);
}
void OnRetryTimeoutElapsed(MessageAttemptInfo attemptInfo)
{
if (this.sendGuard.Enter())
{
IAsyncResult result = this.beginSendHandler(attemptInfo, this.sendTimeout, true, onSendRetryComplete, this);
if (result.CompletedSynchronously)
{
this.CompleteSendRetry(result);
}
}
}
static void OnSendRetryComplete(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ReliableOutputConnection outputConnection = (ReliableOutputConnection)result.AsyncState;
try
{
outputConnection.CompleteSendRetry(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
outputConnection.RaiseOnException(e);
}
}
}
static void OnSendRetriesComplete(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ReliableOutputConnection outputConnection = (ReliableOutputConnection)result.AsyncState;
try
{
outputConnection.CompleteSendRetries(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
outputConnection.RaiseOnException(e);
}
}
}
void OnTransferComplete()
{
this.strategy.DequeuePending();
if (this.strategy.DoneTransmitting)
Terminate();
}
public void ProcessTransferred(Int64 transferred, SequenceRangeCollection ranges, int quotaRemaining)
{
if (transferred < 0)
{
throw Fx.AssertAndThrow("Argument transferred must be a valid sequence number or 0 for protocol messages.");
}
bool invalidAck;
// ignored, TransmissionStrategy is being used to keep track of what must be re-sent.
// In the Request-Reply case this state may not align with acks.
bool inconsistentAck;
this.strategy.ProcessAcknowledgement(ranges, out invalidAck, out inconsistentAck);
invalidAck = (invalidAck || ((transferred != 0) && !ranges.Contains(transferred)));
if (!invalidAck)
{
if ((transferred > 0) && this.strategy.ProcessTransferred(transferred, quotaRemaining))
{
ActionItem.Schedule(sendRetries, this);
}
else
{
this.OnTransferComplete();
}
}
else
{
WsrmFault fault = new InvalidAcknowledgementFault(this.id, ranges);
RaiseFault(fault.CreateException(), fault);
}
}
public void ProcessTransferred(SequenceRangeCollection ranges, int quotaRemaining)
{
bool invalidAck;
bool inconsistentAck;
this.strategy.ProcessAcknowledgement(ranges, out invalidAck, out inconsistentAck);
if (!invalidAck && !inconsistentAck)
{
if (this.strategy.ProcessTransferred(ranges, quotaRemaining))
{
ActionItem.Schedule(sendRetries, this);
}
else
{
this.OnTransferComplete();
}
}
else
{
WsrmFault fault = new InvalidAcknowledgementFault(this.id, ranges);
RaiseFault(fault.CreateException(), fault);
}
}
void RaiseFault(Exception faultException, WsrmFault fault)
{
ComponentFaultedHandler handler = this.Faulted;
if (handler != null)
handler(faultException, fault);
}
void RaiseOnException(Exception exception)
{
ComponentExceptionHandler handler = this.OnException;
if (handler != null)
handler(exception);
}
void SendRetries()
{
IAsyncResult result = null;
if (this.sendGuard.Enter())
{
MessageAttemptInfo attemptInfo = this.strategy.GetMessageInfoForRetry(false);
if (attemptInfo.Message != null)
{
result = this.beginSendHandler(attemptInfo, this.sendTimeout, true, onSendRetriesComplete, this);
}
if (result != null)
{
if (result.CompletedSynchronously)
{
this.CompleteSendRetries(result);
}
}
else
{
this.sendGuard.Exit();
this.OnTransferComplete();
}
}
}
static void SendRetries(object state)
{
ReliableOutputConnection outputConnection = (ReliableOutputConnection)state;
try
{
outputConnection.SendRetries();
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
outputConnection.RaiseOnException(e);
}
}
public void Terminate()
{
lock (this.ThisLock)
{
if (this.terminated)
return;
this.terminated = true;
}
this.shutdownHandle.Set();
}
sealed class AddAsyncResult : AsyncResult
{
static AsyncCallback addCompleteStatic = Fx.ThunkCallback(new AsyncCallback(AddComplete));
ReliableOutputConnection connection;
bool isLast;
static AsyncCallback sendCompleteStatic = Fx.ThunkCallback(new AsyncCallback(SendComplete));
TimeoutHelper timeoutHelper;
bool validAdd;
public AddAsyncResult(Message message, bool isLast, TimeSpan timeout, object state,
ReliableOutputConnection connection, AsyncCallback callback, object asyncState)
: base(callback, asyncState)
{
this.connection = connection;
this.timeoutHelper = new TimeoutHelper(timeout);
this.isLast = isLast;
bool complete = false;
IAsyncResult result;
try
{
if (isLast)
{
if (state != null)
{
throw Fx.AssertAndThrow("The isLast overload does not take a state.");
}
result = this.connection.strategy.BeginAddLast(message, this.timeoutHelper.RemainingTime(), state, addCompleteStatic, this);
}
else
{
result = this.connection.strategy.BeginAdd(message, this.timeoutHelper.RemainingTime(), state, addCompleteStatic, this);
}
}
catch (TimeoutException)
{
if (isLast)
this.connection.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.connection.id, SR.GetString(SR.SequenceTerminatedAddLastToWindowTimedOut), null));
// else - RM does not fault the channel based on a timeout exception trying to add a sequenced message to the window.
throw;
}
catch (Exception e)
{
if (!Fx.IsFatal(e))
this.connection.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.connection.id, SR.GetString(SR.SequenceTerminatedUnknownAddToWindowError), null));
throw;
}
if (result.CompletedSynchronously)
complete = this.CompleteAdd(result);
if (complete)
this.Complete(true);
}
static void AddComplete(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
AddAsyncResult addResult = (AddAsyncResult)result.AsyncState;
bool complete = false;
Exception completeException = null;
try
{
complete = addResult.CompleteAdd(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
completeException = e;
}
if (complete || completeException != null)
addResult.Complete(false, completeException);
}
}
bool CompleteAdd(IAsyncResult result)
{
MessageAttemptInfo attemptInfo = default(MessageAttemptInfo);
this.validAdd = true;
try
{
if (this.isLast)
{
attemptInfo = this.connection.strategy.EndAddLast(result);
}
else if (!this.connection.strategy.EndAdd(result, out attemptInfo))
{
this.validAdd = false;
return true;
}
}
catch (TimeoutException)
{
if (this.isLast)
this.connection.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.connection.id, SR.GetString(SR.SequenceTerminatedAddLastToWindowTimedOut), null));
// else - RM does not fault the channel based on a timeout exception trying to add a sequenced message to the window.
throw;
}
catch (Exception e)
{
if (!Fx.IsFatal(e))
this.connection.RaiseFault(null, SequenceTerminatedFault.CreateCommunicationFault(this.connection.id, SR.GetString(SR.SequenceTerminatedUnknownAddToWindowError), null));
throw;
}
if (this.connection.sendGuard.Enter())
{
bool throwing = true;
try
{
result = this.connection.beginSendHandler(attemptInfo, this.timeoutHelper.RemainingTime(), false, sendCompleteStatic, this);
throwing = false;
}
catch (QuotaExceededException)
{
this.connection.RaiseFault(null, SequenceTerminatedFault.CreateQuotaExceededFault(this.connection.id));
throw;
}
finally
{
if (throwing)
this.connection.sendGuard.Exit();
}
}
else
{
return true;
}
if (result.CompletedSynchronously)
{
this.CompleteSend(result);
return true;
}
else
{
return false;
}
}
void CompleteSend(IAsyncResult result)
{
try
{
this.connection.endSendHandler(result);
}
catch (QuotaExceededException)
{
this.connection.RaiseFault(null, SequenceTerminatedFault.CreateQuotaExceededFault(this.connection.id));
throw;
}
finally
{
this.connection.sendGuard.Exit();
}
}
static void SendComplete(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
AddAsyncResult addResult = (AddAsyncResult)result.AsyncState;
Exception completeException = null;
try
{
addResult.CompleteSend(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
completeException = e;
}
addResult.Complete(false, completeException);
}
}
public static bool End(IAsyncResult result)
{
AsyncResult.End<AddAsyncResult>(result);
return ((AddAsyncResult)result).validAdd;
}
}
class AlreadyCompletedTransferAsyncResult : CompletedAsyncResult
{
public AlreadyCompletedTransferAsyncResult(AsyncCallback callback, object state)
: base(callback, state)
{
}
public void End()
{
AsyncResult.End<AlreadyCompletedTransferAsyncResult>(this);
}
}
}
}
|