private async Task OnMessageReceived(Message message, CancellationToken cancelToken) { logger.LogInformation($"Processing message [{message.MessageId}]..."); if (cancelToken.IsCancellationRequested) { logger.LogWarning($"Cancellation requested. Abandoning message [{message.MessageId}]..."); await subscriptionClient.AbandonAsync(message.SystemProperties.LockToken); } else { try { var messageJson = Encoding.UTF8.GetString(message.Body); var executionRequest = JsonConvert.DeserializeObject <ExecutionRequest>(messageJson); logger.LogInformation($"Processing execution request [{executionRequest.ExecutionId}]..."); await requestRouter.RouteRequestAsync(executionRequest, cancelToken); logger.LogInformation($"Execution request [{executionRequest.ExecutionId}] successfully processed."); await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); } catch (Exception ex) { logger.LogError($"An error occurred while processing message [{message.MessageId}]: [{ex.Message}]. " + $"Abandoning message [{message.MessageId}]..."); await subscriptionClient.AbandonAsync(message.SystemProperties.LockToken); } } }
private async Task ReceiveMessage(Message message, CancellationToken cancellationToken) { if (message != null && _nodeId != null) { _logger?.LogDebug(Resources.AzureServiceBus_Debug_MessageReceived, _topicName, _nodeId, message.MessageId); try { if (message.UserProperties.ContainsKey(SubscriptionPingPropertyName)) { ProcessSubscriptionIsAliveMessage(message); } else { var nodeMessage = MessageConverter.ConvertToNodeMessage(message); _observableMessages.OnNext(nodeMessage); } await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); _logger?.LogInformation(Resources.AzureServiceBus_Info_MessageProcessed, _topicName, _nodeId, message.MessageId); } catch (Exception ex) { _logger?.LogError(ex, Resources.AzureServiceBus_Error_MessageError, _topicName, _nodeId, message.MessageId); await _subscriptionClient.AbandonAsync(message.SystemProperties.LockToken); } } }
private static async Task ReceiveMessages_FromTopicDeadLetterSubscriptions(MessageSender sender, SubscriptionClient client, CancellationToken token, ConsoleColor color) { var doneReceiving = new TaskCompletionSource <bool>(); token.Register( async() => { await client.CloseAsync(); doneReceiving.SetResult(true); }); client.RegisterMessageHandler( async(message, token1) => { try { var resubmitMessage = message.Clone(); resubmitMessage.MessageId = $"{resubmitMessage.MessageId}|{Guid.NewGuid()}"; await sender.SendAsync(resubmitMessage); await client.CompleteAsync(message.SystemProperties.LockToken); Utils.ConsoleWrite($"[{message.MessageId}] -- Placed back in topic.\n", ConsoleColor.Blue, color); } catch (Exception ex) { Log.Error($"[{message.MessageId}] -- {ex.Message}"); await client.AbandonAsync(message.SystemProperties.LockToken); } }, GetDefaultMessageHandlingOptions()); await doneReceiving.Task; }
private async Task ProcessMessagesAsync(Message message, CancellationToken token) { // Deserialize the message to get the original json sent to the producer api var simpleMessage = JsonConvert.DeserializeObject <SimpleMessage>(Encoding.UTF8.GetString(message.Body)); //await _processData.Process(simpleMessage); // decide what to communicate back to the service bus switch (simpleMessage.MessageType) { case SimpleMessageType.Complete: await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); telemetryClient.TrackTrace($"Message with id {message.MessageId} successfully processed"); break; case SimpleMessageType.SendToDlq: await subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken); telemetryClient.TrackTrace($"Message with id {message.MessageId} sent to DLQ"); break; case SimpleMessageType.Error: // increments the delivery count throw new InvalidOperationException("Cannot process message"); default: // increments the delivery count await subscriptionClient.AbandonAsync(message.SystemProperties.LockToken); telemetryClient.TrackTrace($"Message with id {message.MessageId} abandoned. Retrying shortly..."); break; } }
private async Task OnMessageAsync(Message message, CancellationToken cancellationToken, IMediator mediator) { try { var payload = JObject.Parse(Encoding.UTF8.GetString(message.Body)); var command = MapEvent(message.Label, payload); if (command != null) { if (command is IRequest) { await mediator.Send((IRequest)command, cancellationToken); } else if (command is IRequest <int> ) { await mediator.Send((IRequest <int>) command, cancellationToken); } else { logger.LogWarning($"Unsupported command type: {command.GetType()}"); } } await client.CompleteAsync(message.SystemProperties.LockToken); } catch (BusinessException ex) { logger.LogError($"Business exception occurred processing integration event. Details: {ex}"); await client.CompleteAsync(message.SystemProperties.LockToken); } catch (Exception ex) { logger.LogError($"Unexpected error occurred processing integration event. Details: {ex}"); await client.AbandonAsync(message.SystemProperties.LockToken); } }
private void RegisterSubscriptionClientMessageHandler(SubscriptionClient subscriptionClient) { subscriptionClient.RegisterMessageHandler( async(message, token) => { _log.Trace($"Received Message {message.MessageId} {message.Label} for {subscriptionClient.ServiceBusConnection.Endpoint}"); if (!token.IsCancellationRequested && !subscriptionClient.IsClosedOrClosing) { await OnMessageReceived(message); // Complete the message so that it is not received again. await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); } else { _log.Warn($"SubscriptionClient MessageReceived CancellationRequested or IsClosedOrClosing"); await subscriptionClient.AbandonAsync(message.SystemProperties.LockToken); } }, new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 20, AutoComplete = false, MaxAutoRenewDuration = TimeSpan.FromSeconds(60) }); }
/// <summary> /// This message is registered on the subscription client and is called in a separate thread. /// </summary> /// <param name="message"></param> /// <param name="token"></param> /// <returns></returns> private async Task OnMessageCallback(BrokeredMessage brokeredMessage, CancellationToken token) { if (brokeredMessage != null) { IMessage message = null; try { var data = Encoding.UTF8.GetString(brokeredMessage.Body); message = new Message { Payload = (brokeredMessage.ContentType == null) ? data : (object)_serializationUtility.Deserialize <TType>(data), Metadata = new MessageMetadata { MessageId = brokeredMessage.MessageId, DeadLetterErrorDescription = brokeredMessage.UserProperties["DeadLetterErrorDescription"].ToString(), DeadLetterReason = brokeredMessage.UserProperties["DeadLetterReason"].ToString() }, Success = !token.IsCancellationRequested }; OnMessageCallback(message); } catch (Exception ex) { Console.WriteLine(ex.Message); } // If this subscription is peek only then don't give up any of the peek locks so the next message will be processed. if (!_peekOnly) { if (message?.Success == true) { await _subscriptionClient.CompleteAsync(brokeredMessage.SystemProperties.LockToken); } else { await _subscriptionClient.AbandonAsync(brokeredMessage.SystemProperties.LockToken); } } // TODO: Add dead letter? } }
private async Task MessageReceived(Microsoft.Azure.ServiceBus.Message message, CancellationToken cancelationToken) { try { using (var compressedStream = new MemoryStream(message.Body)) using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress)) { using (var decompressedStream = new MemoryStream()) { decompressorStream.CopyTo(decompressedStream); /* * it is possible that this may not be the client that asked for the RPC request * but it could be the one that consumed the message. If this is the case the * asyn coupler will say, nope I didn't ask for this and will not processe it. * return it back to the pool to see if another client can handle it. */ if ((await ReceiveAsync(new Response(decompressedStream.ToArray()))).Successful) { await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); } else { await _subscriptionClient.AbandonAsync(message.SystemProperties.LockToken); } } } } catch (Exception ex) { message.Label = ex.Message; await _subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken, ex.GetType().FullName, ex.Message); throw; } }
public async Task AbandonMessageAsync(string connectionString, string topic, string subscription, Guid lockToken) { SubscriptionClient subscribeClient = ServiceBusConnectionsFactory.GetAckClient(connectionString, topic, subscription); await subscribeClient.AbandonAsync(lockToken); }
public override void Abort() { azureSubscription.AbandonAsync(innerMessage.SystemProperties.LockToken).Wait(); }