public async Task Consume(ConsumeContext <PersonSearchOrdered> context) { try { _logger.LogInformation($"Successfully handling new search request [{context.Message.Person}]"); _logger.LogWarning("Sample Adapter, do not use in PRODUCTION."); if (await ValidatePersonSearch(context)) { count++; if (string.Equals(context.Message.Person.FirstName, "exception", StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Exception from Sample Adapter, Your name is no exception"); } _logger.LogInformation(count.ToString()); await context.Publish(FakePersonBuilder.BuildFakePersonSearchCompleted(context.Message.SearchRequestId, context.Message.SearchRequestKey, context.Message.Person.FirstName, context.Message.Person.LastName, (DateTime)context.Message.Person.DateOfBirth, _profile)); } } catch (Exception ex) { if (context.GetRetryAttempt() == _retryConfigration.RetryTimes) { await context.Publish(FakePersonBuilder.BuildFakePersonFailed(_profile, context.Message.SearchRequestId, context.Message.SearchRequestKey, ex.Message)); } else { throw new Exception(ex.Message); } } }
public async Task Consume(ConsumeContext <NewDataAvailable> context) { var msg = context.Message; await Console.Out.WriteLineAsync($"\r\n{context.MessageId} - {context.ConversationId} - Received NewDataAvailable: {msg.Text}"); if (msg.Text.Contains('e')) { await context.Publish <SomethingNoteworthyHappened>( new { Text = $"There is an 'e' in: {msg.Text}" }); } if (State.EnableFail && msg.Text.Contains('f')) { var redeliveryAttempt = context.Headers.Get <int>("MT-Redelivery-Count", 0).Value; var retryAttempt = context.GetRetryAttempt(); if (msg.Text.Contains("ok") && retryAttempt > 1) { Console.Out.WriteLine($"{context.MessageId} - {context.ConversationId} --- Retry {retryAttempt}, 2LR {redeliveryAttempt}, will treat as ok."); } else if (msg.Text.Contains("2lr") && redeliveryAttempt > 1 && retryAttempt > 1) { Console.Out.WriteLine($"{context.MessageId} - {context.ConversationId} --- Retry {retryAttempt}, 2LR {redeliveryAttempt}, will treat as ok."); } else { Console.Out.WriteLine($"{context.MessageId} - {context.ConversationId} --- Retry {retryAttempt}, 2LR {redeliveryAttempt}, will THROW."); throw new ApplicationException($"Subscriber throws for text: {msg.Text}"); } } await context.Publish <InitialProcessingCompleted>(new { Text = msg.Text }); }
public Task Consume(ConsumeContext <Message> context) { Console.WriteLine("receive at (" + context.GetRetryAttempt() + "): " + DateTime.Now.ToLongTimeString()); throw new Exception("foo"); //return Console.Out.WriteLineAsync($"receiving: { JsonConvert.SerializeObject(context.Message) }"); }
public Task Consume(ConsumeContext <PingMessage> context) { Interlocked.Increment(ref Attempts); LastAttempt = context.GetRetryAttempt(); LastCount = context.GetRetryCount(); throw new IntentionalTestException(); }
bool IsReadyToDeliver(ConsumeContext context) { if (context.GetRetryAttempt() > 0) { return(true); } return(_messages.Count == _messageLimit); }
public async Task Consume(ConsumeContext <YourMessage> context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var retryCount = context.GetRetryAttempt(); await Console.Out.WriteLineAsync("Consumer: " + context.Message.Text); }
public async Task Consume(ConsumeContext <ISimpleMessage> context) { var retryAttempt = context.GetRetryAttempt(); var retryCount = context.GetRetryCount(); var redeliveryCount = context.GetRedeliveryCount(); logger.LogInformation("Message: {0} CreationDateTime: {1}", context.Message.Message, context.Message.CreationDateTime); logger.LogInformation("RetryAttempt: {0} RetryCount: {1} RedeliveryCount: {2}", retryAttempt, retryCount, redeliveryCount); if (context.Message.Message.Contains("error", StringComparison.InvariantCultureIgnoreCase)) { throw new ApplicationException("Invalid message content!"); } }
async Task <BatchConsumer <TConsumer, TMessage> > Add(ConsumeContext <TMessage> context) { if (_currentConsumer != null) { if (context.GetRetryAttempt() > 0) { await _currentConsumer.ForceComplete().ConfigureAwait(false); } } if (_currentConsumer == null || _currentConsumer.IsCompleted) { _currentConsumer = new BatchConsumer <TConsumer, TMessage>(_messageLimit, _timeLimit, _collector, _dispatcher, _consumerFactory, _consumerPipe); } await _currentConsumer.Add(context).ConfigureAwait(false); return(_currentConsumer); }
public async Task Consume(ConsumeContext <SubmitClaim> context) { var retryAttempt = context.GetRetryAttempt(); var message = context.Message; _logger.LogInformation("SubmitClaim 처리시작 : {OrderId} (RetryAttempt = {RetryAttempt}", message.OrderId, retryAttempt); if (retryAttempt < message.DegreeOfHardness) { _logger.LogWarning("SubmitClaim 처리중 너무 어려운 Claim을 만났네요. 고심중...(RetryAttempt = {RetryAttempt})", retryAttempt); await Task.Delay(10000 *(retryAttempt + 1)); throw new TooHardClaimException($"너무 어려운 Claim. 난이도={message.DegreeOfHardness}"); } await Task.Delay(1000); _logger.LogInformation("SubmitClaim 처리완료 : {OrderId}", message.OrderId); }
BatchConsumer <TConsumer, TMessage> Add(ConsumeContext <TMessage> context) { if (_currentConsumer != null) { if (context.GetRetryAttempt() > 0) { _currentConsumer.ForceComplete(); } } if (_currentConsumer == null || _currentConsumer.IsCompleted) { _currentConsumer = new BatchConsumer <TConsumer, TMessage>(_messageLimit, _timeLimit, _scheduler, _consumerFactory, _consumerPipe); } _currentConsumer.Add(context); BatchConsumer <TConsumer, TMessage> consumer = _currentConsumer; return(consumer); }
public Task Consume(ConsumeContext <NotifySomethingHappened> context) { var id = $"[happeningId:{context.Message.HappeningId}]"; var hap = $"[whatHappened:{context.Message.WhatHappened}]"; var redC = $"[redeliveryCount:{context.GetRedeliveryCount()}]"; var retA = $"[retryAttempt:{context.GetRetryAttempt()}]"; var retC = $"[retryCount:{context.GetRetryCount()}]"; var ten = $"[tenantId:{context.Headers.Get<string>("tenant-id")}]"; _logger.LogInformation($"Consuming NotifySomethingHappened {id}{hap}{ten}{redC}{retA}{retC}"); if (string.IsNullOrWhiteSpace(context.Message.WhatHappened)) { throw new Exception("No happening"); } if (context.Message.WhatHappened.Contains("redeliver")) { throw new CanNotCurrentlyProcessException(context.Message.WhatHappened); } return(Task.CompletedTask); }
public static void MeasureConsume <T>(ConsumeContext <T> context, TimeSpan duration, string consumerType, Exception exception = default) where T : class { var messageType = GetMessageTypeLabel <T>(); var cleanConsumerType = GetConsumerTypeLabel(consumerType); _consumeTotal.Labels(_serviceLabel, messageType, cleanConsumerType).Inc(); _consumeDuration.Labels(_serviceLabel, messageType, cleanConsumerType).Observe(duration.TotalSeconds); if (exception != null) { var exceptionType = exception.GetType().Name; _consumeFaultTotal.Labels(_serviceLabel, messageType, cleanConsumerType, exceptionType).Inc(); } var retryAttempt = context.GetRetryAttempt(); if (retryAttempt > 0) { _consumeRetryTotal.Inc(retryAttempt); } if (!context.SentTime.HasValue) { return; } var deliveryDuration = DateTime.UtcNow - context.SentTime.Value; if (deliveryDuration < TimeSpan.Zero) { deliveryDuration = TimeSpan.Zero; } _deliveryDuration.Labels(_serviceLabel, messageType, cleanConsumerType).Observe(deliveryDuration.TotalSeconds); }
Task IConsumeObserver.PreConsume <T>(ConsumeContext <T> context) { // called before the consumer's Consume method is called _log.LogInformation($"{context.Message.GetType().Name}: {JsonConvert.SerializeObject(context.Message, Formatting.Indented)} - Attempt no. {context.GetRetryAttempt()}"); return(Task.CompletedTask); }
private async Task HandleEvent <TEvent>(EventReceived <TEvent> eventHandler, ConsumeContext <TEvent> context) where TEvent : class, IEvent { EventMessage <TEvent> message = _options.ContextManager.CreateEventMessage(context); _logger.LogVerbose(new { @event = message.Event.ToString(), eventType = typeof(TEvent).FullName, correlationId = message.CorrelationId, retryCount = context.GetRetryAttempt() }, arg => $"Received event of type {arg.eventType} with correlationId {arg.correlationId}. (Try n. {arg.retryCount}). Event: {arg.@event}"); try { await eventHandler.Invoke(message).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(new { eventType = typeof(TEvent).FullName, correlationId = message.CorrelationId, retryCount = context.GetRetryAttempt(), @event = context.Message.ToString() }, ex, (arg, e) => $"Error while processing event of type {arg.eventType} with correlationId {arg.correlationId}. (Try n. {arg.retryCount}). Event: {arg.@event}. Error: {e.Message}"); throw; } }
private async Task HandleCommand <TCommand>(CommandReceived <TCommand> commandHandler, ConsumeContext <TCommand> context) where TCommand : class, ICommand { CommandMessage <TCommand> message = _options.ContextManager.CreateCommandMessage(context); _logger.LogVerbose(new { commandType = typeof(TCommand).FullName, correlationId = message.CorrelationId, retryCount = context.GetRetryAttempt(), command = message.Command.ToString() }, arg => $"Received command of type {arg.commandType} with correlationId {arg.correlationId}. (Try n. {arg.retryCount}). Command: {arg.command}"); try { await commandHandler.Invoke(message).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(new { commandType = typeof(TCommand).FullName, correlationId = message.CorrelationId, retryCount = context.GetRetryAttempt(), command = context.Message.ToString() }, ex, (arg, e) => $"Error while processing event of type {arg.commandType} with correlationId {arg.correlationId}. (Try n. {arg.retryCount}). Command: {arg.command}. Error: {e.Message}"); throw; } }
public async Task Consume(ConsumeContext <FulfillOrder> context) { // precheck 예시 if (context.Message.CustomerNumber.StartsWith("INVALID")) { throw new InvalidOperationException("😥 노력은 했지만, 고객번호가 유효하지 않네요."); } if (context.Message.CustomerNumber.StartsWith("MAYBE")) { var retryCount = context.GetRetryAttempt(); //context.GetRetryCount(); _logger.LogInformation("@@@@@@@@ MAYBE 고객번호 재시도 횟수 : {RetryCount}", retryCount); if (retryCount < 2) { _logger.LogWarning("@@@@@@@ MAYBE 고객은 처리시간이 좀 걸립니다."); await Task.Delay(TimeSpan.FromSeconds(10)); throw new ApplicationException("😐 어오. 한두번 해서는 고객번호 인증이 안될껀데요."); } _logger.LogInformation("@@@@@@@@ MAYBE 고객번호 인증됨"); } var trackingNumber = NewId.NextGuid(); var builder = new RoutingSlipBuilder(trackingNumber); // Warehouse.Contract.AllocateInventory 형에 대한 아무런 참조가 없이 완전 loose coupled 된 상태로 // 연동하기 위해, // - 문자열로 된 Activity 타입명 // - 문자열로 된 execute address // - dynamic 객체로 Activity Argument를 구성. // // "queue:allocate-inventory_execute" ..는 Masstransit 6.x 부터 지원되는 short address // (https://masstransit-project.com/usage/producers.html#send) // Activity 작업 #1 : 재고할당하기. builder.AddActivity("AllocateInventory", new Uri("queue:allocate-inventory_execute"), new { // OrderId = context.Message.OrderId, // 아래에 Variable 로 전달해봄. ItemNumber = "ITEM123", Quantity = 10.0m // Argument로 MessageData<T> 를 쓸 수 있다고 함. }); // ... Activity 를 여러개 생성할 수 있음. // Activity 작업 #2 : 결재하기. builder.AddActivity("Payment", new Uri("queue:payment_execute"), new { //OrderId = context.Message.OrderId, // 아래 Variable 로 전달된다?! Amount = 99.95m, //PaymentCardNumber = "5999-1234-5000-4321", // 실패 할 경우 (5999 로 시작) PaymentCardNumber = context.Message.PaymentCardNumber, }); // 분산처리중 필요한 "변수"를 추가. builder.AddVariable("OrderId", context.Message.OrderId); await builder.AddSubscription( context.SourceAddress, RoutingSlipEvents.Faulted | RoutingSlipEvents.Supplemental, // Supplemental 은 문서를 참고. :-( RoutingSlipEventContents.None, // 회람쪽지 내역 전체를 보낼 필요는 없다(덩치도 크다고 한다) endpoint => endpoint.Send <OrderFulfillmentFaulted>(new { OrderId = context.Message.OrderId, Timestamp = InVar.Timestamp, FaultReason = "Fault원인은 ???" // Fault된 Exception 을 어떻게 가져오지??? }) ); await builder.AddSubscription( context.SourceAddress, RoutingSlipEvents.Completed | RoutingSlipEvents.Supplemental, // Supplemental 은 문서를 참고. :-( RoutingSlipEventContents.None, // 회람쪽지 내역 전체를 보낼 필요는 없다(덩치도 크다고 한다) endpoint => endpoint.Send <OrderFulfillmentCompleted>(new { OrderId = context.Message.OrderId, Timestamp = InVar.Timestamp, }) ); await builder.AddSubscription( context.SourceAddress, RoutingSlipEvents.Completed, RoutingSlipEventContents.None, endpoint => { Console.WriteLine("@**@ RoutingSlip DONE "); return(Task.CompletedTask); } ); var routingSlip = builder.Build(); await context.Execute(routingSlip); }
public async Task Consume(ConsumeContext <SearchRequestOrdered> context) { using (LogContext.PushProperty("RequestRef", $"{context.Message?.Person?.Agency?.RequestId}")) using (LogContext.PushProperty("AgencyCode", $"{context.Message?.Person?.Agency?.Code}")) { try { _logger.LogInformation("get the searchRequestOrdered message."); await _searchRequestNotifier.NotifySearchRequestEventAsync(context.Message.RequestId, context.Message, CancellationToken.None, context.GetRetryAttempt(), _retryConfig.Value.RetryTimes); } catch (Exception e) { _logger.LogError(e, "SearchRequestOrdered {requestRef} is put into error queue.", context.Message?.RequestId); throw; } } }
public async Task Consume(ConsumeContext <NotificationAcknowledged> context) { using (LogContext.PushProperty("RequestRef", $"{context.Message?.RequestId}")) using (LogContext.PushProperty("AgencyCode", $"{context.Message?.ProviderProfile?.Name}")) { try { _logger.LogInformation("get the NotificationAcknowledged message."); var cts = new CancellationTokenSource(); await _searchRequestNotifier.NotifySearchRequestEventAsync(context.Message.RequestId, context.Message, cts.Token, context.GetRetryAttempt(), _retryConfig.Value.RetryTimes); }catch (Exception e) { _logger.LogError(e, "NotificationAcknowledged {requestRef} is put into error queue.", context.Message?.RequestId); throw; } } }
public async Task Consume(ConsumeContext <SendDocketLinkNotificationRequest> context) { await Console.Out.WriteLineAsync($"{nameof(SendDocketLinkNotificationRequest)}: Intento:{context.GetRetryAttempt()} DocketId: {context.Message.DocketId} {DateTime.Now.ToString("hh:mm:ss:ms")} ThreadID:{System.Threading.Thread.CurrentThread.ManagedThreadId}"); throw new Exception("Error"); }