protected override async Task <Stream> OnGetStateAsync() { try { AmqpRequestMessage amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.GetSessionStateOperation, this.OperationTimeout, null); amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionId; AmqpResponseMessage amqpResponseMessage = await this.InnerMessageReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); Stream sessionState = null; if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK) { if (amqpResponseMessage.Map[ManagementConstants.Properties.SessionState] != null) { sessionState = new BufferListStream(new[] { amqpResponseMessage.GetValue <ArraySegment <byte> >(ManagementConstants.Properties.SessionState) }); } } return(sessionState); } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } }
public static Exception ToMessagingContractException(this AmqpMessage responseMessage, AmqpResponseStatusCode statusCode) { AmqpSymbol errorCondition = AmqpExceptionHelper.GetResponseErrorCondition(responseMessage, statusCode); var statusDescription = responseMessage.ApplicationProperties.Map[ManagementConstants.Response.StatusDescription] as string ?? errorCondition.Value; return(AmqpExceptionHelper.ToMessagingContractException(errorCondition.Value, statusDescription)); }
public async Task OnAddRuleAsync(RuleDescription description) { try { var amqpRequestMessage = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.AddRuleOperation, this.ServiceBusConnection.OperationTimeout, null); amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = description.Name; amqpRequestMessage.Map[ManagementConstants.Properties.RuleDescription] = AmqpMessageConverter.GetRuleDescriptionMap(description); AmqpResponseMessage response = await ((AmqpMessageReceiver)this.InnerReceiver).ExecuteRequestResponseAsync(amqpRequestMessage) .ConfigureAwait(false); if (response.StatusCode != AmqpResponseStatusCode.OK) { throw response.ToMessagingContractException(); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception); } }
protected override async Task <DateTime> OnRenewLockAsync(string lockToken) { DateTime lockedUntilUtc = DateTime.MinValue; try { // Create an AmqpRequest Message to renew lock AmqpRequestMessage requestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.RenewLockOperation, this.OperationTimeout, null); requestMessage.Map[ManagementConstants.Properties.LockTokens] = new[] { new Guid(lockToken) }; AmqpResponseMessage response = await this.ExecuteRequestResponseAsync(requestMessage).ConfigureAwait(false); if (response.StatusCode == AmqpResponseStatusCode.OK) { IEnumerable <DateTime> lockedUntilUtcTimes = response.GetValue <IEnumerable <DateTime> >(ManagementConstants.Properties.Expirations); lockedUntilUtc = lockedUntilUtcTimes.First(); } else { throw response.ToMessagingContractException(); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception); } return(lockedUntilUtc); }
protected override async Task OnSendAsync(IEnumerable <BrokeredMessage> brokeredMessages) { TimeoutHelper timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); using (AmqpMessage amqpMessage = AmqpMessageConverter.BrokeredMessagesToAmqpMessage(brokeredMessages, true)) { SendingAmqpLink amqpLink = await this.SendLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); if (amqpLink.Settings.MaxMessageSize.HasValue) { ulong size = (ulong)amqpMessage.SerializedMessageSize; if (size > amqpLink.Settings.MaxMessageSize.Value) { // TODO: Add MessageSizeExceededException throw new NotImplementedException("MessageSizeExceededException: " + Resources.AmqpMessageSizeExceeded.FormatForUser(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value)); ////throw Fx.Exception.AsError(new MessageSizeExceededException( ////Resources.AmqpMessageSizeExceeded.FormatForUser(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value))); } } Outcome outcome = await amqpLink.SendMessageAsync(amqpMessage, this.GetNextDeliveryTag(), AmqpConstants.NullBinary, timeoutHelper.RemainingTime()).ConfigureAwait(false); if (outcome.DescriptorCode != Accepted.Code) { Rejected rejected = (Rejected)outcome; throw Fx.Exception.AsError(AmqpExceptionHelper.ToMessagingContract(rejected.Error)); } } }
protected override async Task <MessageSession> OnAcceptMessageSessionAsync(string sessionId, TimeSpan serverWaitTime) { AmqpMessageReceiver receiver = new AmqpMessageReceiver( this.SubscriptionPath, MessagingEntityType.Subscriber, this.Mode, this.ServiceBusConnection.PrefetchCount, this.ServiceBusConnection, this.CbsTokenProvider, sessionId, true); try { await receiver.GetSessionReceiverLinkAsync(serverWaitTime).ConfigureAwait(false); } catch (Exception exception) { await receiver.CloseAsync().ConfigureAwait(false); throw AmqpExceptionHelper.GetClientException(exception); } MessageSession session = new AmqpMessageSession(receiver.SessionId, receiver.LockedUntilUtc, receiver); return(session); }
protected override async Task OnSetStateAsync(Stream sessionState) { try { if (sessionState != null && sessionState.CanSeek && sessionState.Position != 0) { throw new InvalidOperationException("CannotSerializeSessionStateWithPartiallyConsumedStream"); } AmqpRequestMessage amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.SetSessionStateOperation, this.OperationTimeout, null); amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionId; if (sessionState != null) { BufferListStream buffer = BufferListStream.Create(sessionState, AmqpConstants.SegmentSize); ArraySegment <byte> value = buffer.ReadBytes((int)buffer.Length); amqpRequestMessage.Map[ManagementConstants.Properties.SessionState] = value; } else { amqpRequestMessage.Map[ManagementConstants.Properties.SessionState] = null; } await this.InnerMessageReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } }
public async Task <Tuple <AmqpObject, DateTime> > CreateAndOpenAmqpLinkAsync() { var timeoutHelper = new TimeoutHelper(this.serviceBusConnection.OperationTimeout); MessagingEventSource.Log.AmqpGetOrCreateConnectionStart(); var amqpConnection = await this.serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); MessagingEventSource.Log.AmqpGetOrCreateConnectionStop(this.entityPath, amqpConnection.ToString(), amqpConnection.State.ToString()); // Authenticate over CBS var cbsLink = amqpConnection.Extensions.Find <AmqpCbsLink>(); var resource = this.endpointAddress.AbsoluteUri; MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(this.endpointAddress, resource, resource, this.requiredClaims); var cbsTokenExpiresAtUtc = await cbsLink.SendTokenAsync(this.cbsTokenProvider, this.endpointAddress, resource, resource, this.requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false); MessagingEventSource.Log.AmqpSendAuthenticationTokenStop(); AmqpSession session = null; try { // Create Session var amqpSessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = amqpConnection.CreateSession(amqpSessionSettings); await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } catch (Exception exception) { MessagingEventSource.Log.AmqpSessionCreationException(this.entityPath, amqpConnection, exception); session?.Abort(); throw AmqpExceptionHelper.GetClientException(exception, null, session.GetInnerException()); } AmqpObject link = null; try { // Create Link link = this.OnCreateAmqpLink(amqpConnection, this.amqpLinkSettings, session); await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); return(new Tuple <AmqpObject, DateTime>(link, cbsTokenExpiresAtUtc)); } catch (Exception exception) { MessagingEventSource.Log.AmqpLinkCreationException( this.entityPath, session, amqpConnection, exception); session.SafeClose(exception); throw AmqpExceptionHelper.GetClientException(exception, null, link?.GetInnerException(), session.IsClosing()); } }
protected override async Task <IList <Message> > OnPeekAsync(long fromSequenceNumber, int messageCount = 1) { try { AmqpRequestMessage requestMessage = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.PeekMessageOperation, this.OperationTimeout, null); requestMessage.Map[ManagementConstants.Properties.FromSequenceNumber] = fromSequenceNumber; requestMessage.Map[ManagementConstants.Properties.MessageCount] = messageCount; if (!string.IsNullOrWhiteSpace(this.sessionId)) { requestMessage.Map[ManagementConstants.Properties.SessionId] = this.sessionId; } List <Message> messages = new List <Message>(); AmqpResponseMessage response = await this.ExecuteRequestResponseAsync(requestMessage).ConfigureAwait(false); if (response.StatusCode == AmqpResponseStatusCode.OK) { Message message = null; var messageList = response.GetListValue <AmqpMap>(ManagementConstants.Properties.Messages); foreach (AmqpMap entry in messageList) { var payload = (ArraySegment <byte>)entry[ManagementConstants.Properties.Message]; AmqpMessage amqpMessage = AmqpMessage.CreateAmqpStreamMessage(new BufferListStream(new[] { payload }), true); message = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); messages.Add(message); } if (message != null) { this.LastPeekedSequenceNumber = message.SystemProperties.SequenceNumber; } return(messages); } else if (response.StatusCode == AmqpResponseStatusCode.NoContent || (response.StatusCode == AmqpResponseStatusCode.NotFound && Equals(AmqpClientConstants.MessageNotFoundError, response.GetResponseErrorCondition()))) { return(messages); } else { throw response.ToMessagingContractException(); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception); } }
public async Task <IMessageSession> AcceptMessageSessionAsync(string sessionId, TimeSpan serverWaitTime) { MessagingEventSource.Log.AmqpSessionClientAcceptMessageSessionStart( this.ClientId, this.EntityPath, this.ReceiveMode, this.PrefetchCount, sessionId); AmqpMessageReceiver receiver = new AmqpMessageReceiver( this.EntityPath, this.EntityType, this.ReceiveMode, this.PrefetchCount, this.ServiceBusConnection, this.CbsTokenProvider, sessionId, this.RetryPolicy, true); try { await this.RetryPolicy.RunOperation( async() => { await receiver.GetSessionReceiverLinkAsync(serverWaitTime).ConfigureAwait(false); }, serverWaitTime) .ConfigureAwait(false); } catch (Exception exception) { MessagingEventSource.Log.AmqpSessionClientAcceptMessageSessionException( this.ClientId, this.EntityPath, exception); await receiver.CloseAsync().ConfigureAwait(false); throw AmqpExceptionHelper.GetClientException(exception); } MessageSession session = new AmqpMessageSession(receiver.SessionId, receiver.LockedUntilUtc, receiver, this.RetryPolicy); MessagingEventSource.Log.AmqpSessionClientAcceptMessageSessionStop( this.ClientId, this.EntityPath, session.SessionId); return(session); }
protected override async Task <IList <BrokeredMessage> > OnPeekAsync(long fromSequenceNumber, int messageCount = 1) { try { AmqpRequestMessage requestMessage = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.PeekMessageOperation, this.OperationTimeout, null); requestMessage.Map[ManagementConstants.Properties.FromSequenceNumber] = fromSequenceNumber; requestMessage.Map[ManagementConstants.Properties.MessageCount] = messageCount; if (!string.IsNullOrWhiteSpace(this.sessionId)) { requestMessage.Map[ManagementConstants.Properties.SessionId] = this.sessionId; } List <BrokeredMessage> messages = new List <BrokeredMessage>(); AmqpResponseMessage response = await this.ExecuteRequestResponseAsync(requestMessage); if (response.StatusCode == AmqpResponseStatusCode.OK) { BrokeredMessage brokeredMessage = null; var messageList = response.GetListValue <AmqpMap>(ManagementConstants.Properties.Messages); foreach (AmqpMap entry in messageList) { var payload = (ArraySegment <byte>)entry[ManagementConstants.Properties.Message]; AmqpMessage amqpMessage = AmqpMessage.CreateAmqpStreamMessage(new BufferListStream(new[] { payload }), true); brokeredMessage = AmqpMessageConverter.ClientGetMessage(amqpMessage); messages.Add(brokeredMessage); } if (brokeredMessage != null) { this.LastPeekedSequenceNumber = brokeredMessage.SequenceNumber; } return(messages); } } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } return(null); }
protected override async Task <IList <BrokeredMessage> > OnReceiveAsync(int maxMessageCount, TimeSpan serverWaitTime) { ReceivingAmqpLink receiveLink = null; try { TimeoutHelper timeoutHelper = new TimeoutHelper(serverWaitTime, true); receiveLink = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); IEnumerable <AmqpMessage> amqpMessages = null; bool hasMessages = await Task.Factory.FromAsync( (c, s) => receiveLink.BeginReceiveRemoteMessages(maxMessageCount, AmqpMessageReceiver.DefaultBatchFlushInterval, timeoutHelper.RemainingTime(), c, s), a => receiveLink.EndReceiveMessages(a, out amqpMessages), this).ConfigureAwait(false); if (receiveLink.TerminalException != null) { throw receiveLink.TerminalException; } if (hasMessages && amqpMessages != null) { IList <BrokeredMessage> brokeredMessages = null; foreach (var amqpMessage in amqpMessages) { if (brokeredMessages == null) { brokeredMessages = new List <BrokeredMessage>(); } if (this.ReceiveMode == ReceiveMode.ReceiveAndDelete) { receiveLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome); } BrokeredMessage brokeredMessage = AmqpMessageConverter.ClientGetMessage(amqpMessage); brokeredMessage.Receiver = this; // Associate the Message with this Receiver. brokeredMessages.Add(brokeredMessage); } return(brokeredMessages); } return(null); } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception, receiveLink?.GetTrackingId()); } }
async Task DisposeMessageRequestResponseAsync(IEnumerable <Guid> lockTokens, DispositionStatus dispositionStatus) { try { // Create an AmqpRequest Message to update disposition AmqpRequestMessage requestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.UpdateDispositionOperation, this.OperationTimeout, null); requestMessage.Map[ManagementConstants.Properties.LockTokens] = lockTokens.ToArray(); requestMessage.Map[ManagementConstants.Properties.DispositionStatus] = dispositionStatus.ToString().ToLowerInvariant(); await this.ExecuteRequestResponseAsync(requestMessage); } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } }
protected override async Task <MessageSession> OnAcceptMessageSessionAsync(string sessionId) { AmqpMessageReceiver receiver = new AmqpMessageReceiver(this.SubscriptionPath, MessagingEntityType.Subscriber, this.Mode, this.ServiceBusConnection.PrefetchCount, this.ServiceBusConnection, this.CbsTokenProvider, sessionId, true); try { await receiver.GetSessionReceiverLinkAsync().ConfigureAwait(false); } catch (AmqpException exception) { // ToDo: Abort the Receiver here AmqpExceptionHelper.ToMessagingContract(exception.Error, false); } MessageSession session = new AmqpMessageSession(receiver.SessionId, receiver.LockedUntilUtc, receiver); return(session); }
protected override async Task OnAbandonAsync(IEnumerable <Guid> lockTokens) { try { if (lockTokens.Any((lt) => this.requestResponseLockedMessages.Contains(lt))) { await this.DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Abandoned).ConfigureAwait(false); } else { await this.DisposeMessagesAsync(lockTokens, new Modified()).ConfigureAwait(false); } } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } }
protected override async Task OnDeadLetterAsync(IEnumerable <Guid> lockTokens) { try { if (lockTokens.Any((lt) => this.requestResponseLockedMessages.Contains(lt))) { await this.DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Suspended).ConfigureAwait(false); } else { await this.DisposeMessagesAsync(lockTokens, AmqpConstants.RejectedOutcome).ConfigureAwait(false); } } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } }
protected override async Task <IList <BrokeredMessage> > OnReceiveBySequenceNumberAsync(IEnumerable <long> sequenceNumbers) { List <BrokeredMessage> messages = new List <BrokeredMessage>(); try { AmqpRequestMessage requestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.ReceiveBySequenceNumberOperation, this.OperationTimeout, null); requestMessage.Map[ManagementConstants.Properties.SequenceNumbers] = sequenceNumbers.ToArray(); requestMessage.Map[ManagementConstants.Properties.ReceiverSettleMode] = (uint)(this.ReceiveMode == ReceiveMode.ReceiveAndDelete ? 0 : 1); AmqpResponseMessage response = await this.ExecuteRequestResponseAsync(requestMessage).ConfigureAwait(false); if (response.StatusCode == AmqpResponseStatusCode.OK) { IEnumerable <AmqpMap> amqpMapList = response.GetListValue <AmqpMap>(ManagementConstants.Properties.Messages); foreach (AmqpMap entry in amqpMapList) { ArraySegment <byte> payload = (ArraySegment <byte>)entry[ManagementConstants.Properties.Message]; AmqpMessage amqpMessage = AmqpMessage.CreateAmqpStreamMessage(new BufferListStream(new[] { payload }), true); BrokeredMessage brokeredMessage = AmqpMessageConverter.ClientGetMessage(amqpMessage); brokeredMessage.Receiver = this; // Associate the Message with this Receiver. Guid lockToken; if (entry.TryGetValue(ManagementConstants.Properties.LockToken, out lockToken)) { brokeredMessage.LockToken = lockToken; this.requestResponseLockedMessages.AddOrUpdate(lockToken, brokeredMessage.LockedUntilUtc); } messages.Add(brokeredMessage); } } else { throw response.ToMessagingContractException(); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception); } return(messages); }
protected override async Task OnRenewLockAsync() { try { AmqpRequestMessage amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.RenewSessionLockOperation, this.OperationTimeout, null); amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionId; AmqpResponseMessage amqpResponseMessage = await this.InnerMessageReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK) { this.LockedUntilUtc = amqpResponseMessage.GetValue <DateTime>(ManagementConstants.Properties.Expiration); } } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } }
async Task RollbackAsync(SinglePhaseEnlistment singlePhaseEnlistment) { try { var faultTolerantController = this.serviceBusConnection.TransactionController; var controller = await faultTolerantController.GetOrCreateAsync(this.serviceBusConnection.OperationTimeout).ConfigureAwait(false); await controller.DischargeAsync(this.AmqpTransactionId, fail : true).ConfigureAwait(false); singlePhaseEnlistment.Aborted(); MessagingEventSource.Log.AmqpTransactionDischarged(this.transactionId, this.AmqpTransactionId, true); } catch (Exception e) { Exception exception = AmqpExceptionHelper.GetClientException(e, true, null); MessagingEventSource.Log.AmqpTransactionDischargeException(this.transactionId, this.AmqpTransactionId, exception); singlePhaseEnlistment.Aborted(exception); } }
async Task DisposeMessageRequestResponseAsync(IEnumerable <Guid> lockTokens, DispositionStatus dispositionStatus) { try { // Create an AmqpRequest Message to update disposition AmqpRequestMessage requestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.UpdateDispositionOperation, this.OperationTimeout, null); requestMessage.Map[ManagementConstants.Properties.LockTokens] = lockTokens.ToArray(); requestMessage.Map[ManagementConstants.Properties.DispositionStatus] = dispositionStatus.ToString().ToLowerInvariant(); AmqpResponseMessage amqpResponseMessage = await this.ExecuteRequestResponseAsync(requestMessage).ConfigureAwait(false); if (amqpResponseMessage.StatusCode != AmqpResponseStatusCode.OK) { throw amqpResponseMessage.ToMessagingContractException(); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception); } }
protected override async Task OnRemoveRuleAsync(string ruleName) { try { var amqpRequestMessage = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.RemoveRuleOperation, this.ServiceBusConnection.OperationTimeout, null); amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = ruleName; var response = await((AmqpMessageReceiver)this.InnerReceiver).ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (response.StatusCode != AmqpResponseStatusCode.OK) { throw response.ToMessagingContractException(); } } catch (Exception exception) { throw AmqpExceptionHelper.GetClientException(exception); } }
async Task DisposeMessagesAsync(IEnumerable <Guid> lockTokens, Outcome outcome) { TimeoutHelper timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); IList <ArraySegment <byte> > deliveryTags = this.ConvertLockTokensToDeliveryTags(lockTokens); ReceivingAmqpLink receiveLink = null; try { receiveLink = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); Task <Outcome>[] disposeMessageTasks = new Task <Outcome> [deliveryTags.Count]; int i = 0; foreach (ArraySegment <byte> deliveryTag in deliveryTags) { disposeMessageTasks[i++] = Task.Factory.FromAsync( (c, s) => receiveLink.BeginDisposeMessage(deliveryTag, outcome, true, timeoutHelper.RemainingTime(), c, s), a => receiveLink.EndDisposeMessage(a), this); } Outcome[] outcomes = await Task.WhenAll(disposeMessageTasks).ConfigureAwait(false); Error error = null; foreach (Outcome item in outcomes) { var disposedOutcome = item.DescriptorCode == Rejected.Code && ((error = ((Rejected)item).Error) != null) ? item : null; if (disposedOutcome != null) { if (error.Condition.Equals(AmqpErrorCode.NotFound)) { if (this.isSessionReceiver) { throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession); } else { throw new MessageLockLostException(Resources.MessageLockLost); } } throw AmqpExceptionHelper.ToMessagingContractException(error); } } } catch (Exception exception) { if (exception is OperationCanceledException && receiveLink != null && receiveLink.State != AmqpObjectState.Opened) { if (this.isSessionReceiver) { throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession); } else { throw new MessageLockLostException(Resources.MessageLockLost); } } throw AmqpExceptionHelper.GetClientException(exception); } }
public async Task <Tuple <AmqpObject, DateTime> > CreateAndOpenAmqpLinkAsync() { var timeoutHelper = new TimeoutHelper(this.serviceBusConnection.OperationTimeout, true); MessagingEventSource.Log.AmqpGetOrCreateConnectionStart(); var amqpConnection = await this.serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); MessagingEventSource.Log.AmqpGetOrCreateConnectionStop(this.entityPath, amqpConnection.ToString(), amqpConnection.State.ToString()); // Authenticate over CBS var cbsLink = amqpConnection.Extensions.Find <AmqpCbsLink>(); DateTime cbsTokenExpiresAtUtc = DateTime.MaxValue; foreach (var resource in this.audience) { MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(this.endpointAddress, resource, resource, this.requiredClaims); cbsTokenExpiresAtUtc = TimeoutHelper.Min( cbsTokenExpiresAtUtc, await cbsLink.SendTokenAsync(this.cbsTokenProvider, this.endpointAddress, resource, resource, this.requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false)); MessagingEventSource.Log.AmqpSendAuthenticationTokenStop(); } AmqpSession session = null; try { // Create Session var amqpSessionSettings = new AmqpSessionSettings { Properties = new Fields() }; if (this.amqpLinkSettings.IsReceiver()) { // This is the maximum number of unsettled transfers across all receive links on this session. // This will allow the session to accept unlimited number of transfers, even if the recevier(s) // are not settling any of the deliveries. amqpSessionSettings.IncomingWindow = uint.MaxValue; } session = amqpConnection.CreateSession(amqpSessionSettings); await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } catch (Exception exception) { MessagingEventSource.Log.AmqpSessionCreationException(this.entityPath, amqpConnection, exception); session?.Abort(); throw AmqpExceptionHelper.GetClientException(exception, null, session.GetInnerException(), amqpConnection.IsClosing()); } AmqpObject link = null; try { // Create Link link = this.OnCreateAmqpLink(amqpConnection, this.amqpLinkSettings, session); await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); return(new Tuple <AmqpObject, DateTime>(link, cbsTokenExpiresAtUtc)); } catch (Exception exception) { MessagingEventSource.Log.AmqpLinkCreationException( this.entityPath, session, amqpConnection, exception); session.SafeClose(exception); throw AmqpExceptionHelper.GetClientException(exception, null, link?.GetInnerException(), amqpConnection.IsClosing()); } }