Beispiel #1
0
        public async Task HandleAsync(JObject jObject, CancellationToken cancellationToken)
        {
            var @event = jObject.ToObject <OrderProcessedEvent>();

            var isnew       = tracer.CurrentTransaction == null;
            var transaction = isnew
                ? tracer.StartTransaction("OrderProcessedEventHandler", "event-subscriber")
                              .WithLabel("data", jObject.ToString())
                              .WithLabel("event name", "OrderProcessedEvent")

                : tracer.CurrentTransaction;

            logger.Information(@event);
            var currentQuantity = await repository.GetAvailableQuantityAsync(@event.Product, cancellationToken);

            await repository.UpdateAsync(@event.Product, @event.Quantity, cancellationToken);

            messageProducer.SendMessage(new InventoryUpdatedEvent
            {
                Product  = @event.Product,
                Quantity = currentQuantity - @event.Quantity
            });

            if (isnew)
            {
                transaction.End();
            }
        }
Beispiel #2
0
        public async Task <IActionResult> NewAsync([FromBody] Customer customer)
        {
            var isnew       = tracer.CurrentTransaction == null;
            var transaction = isnew
                ? tracer.StartTransaction($"NewCustomer", "post")
                              .WithLabel("customer: id", customer.Id.ToString())
                              .WithLabel("customer: name", customer.Name)
                : tracer.CurrentTransaction;

            if (customer == default)
            {
                return(BadRequest("Body empty or null"));
            }

            customer.Id = Guid.NewGuid();

            await repository.NewAsync(customer, CancellationToken.None);

            messageProducer.SendMessage(new CustomerCreatedEvent
            {
                CustomerId = customer.Id
            });

            if (isnew)
            {
                transaction.End();
            }
            return(Ok());
        }
Beispiel #3
0
        public async Task <IActionResult> NewAsync([FromBody] Contracts.Inventory inventory)
        {
            var isnew       = tracer.CurrentTransaction == null;
            var transaction = isnew
                ? tracer.StartTransaction($"NewInventory", "post")
                              .WithLabel("inventory: product", inventory.Product)
                              .WithLabel("inventory: quantity", inventory.Quantity.ToString())
                : tracer.CurrentTransaction;

            if (inventory == default(Contracts.Inventory))
            {
                return(BadRequest("Body empty or null"));
            }

            inventory.Id = Guid.NewGuid();

            await repository.NewAsync(inventory, CancellationToken.None);

            messageProducer.SendMessage(new InventoryAddedEvent
            {
                Product  = inventory.Product,
                Quantity = inventory.Quantity
            });

            if (isnew)
            {
                transaction.End();
            }
            return(Ok());
        }
        public async Task <Customer> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
        {
            var customer = await _customerRepository.AddAsync(request.Customer);

            var customerMessage = new CustomerMessage(_serviceId, customer);

            _messageProducer.SendMessage(_queueName, customerMessage);
            _logger.Log(LogLevel.Information, $"{DateTime.Now} - Enviada mensagem pelo ServiceId: {customerMessage.ServiceId} com RequestId: {customerMessage.RequestId}");
            return(await Task.FromResult(customer));
        }
Beispiel #5
0
        public bool Publish(TransportMessage message, IEnumerable <Type> eventTypes)
        {
            var eventType = eventTypes.First(); //we route on the first event for now

            var topic = topicEvaluator.GetTopicFromMessageType(eventType);

            messageProducer.SendMessage(message, topic, "topic://");

            return(true);
        }
Beispiel #6
0
        protected override void OnWorkerStart(CancellationToken token)
        {
            IConfigurationObserver obs = null;

            try
            {
                obs = configurationObserverFactory.Invoke();
                obs.PropertyChanged += (o, ea) =>
                {
                    var cfgDto = new ConfigurationDto
                    {
                        Timeout          = obs.DocumentsJoinerConfiguration.Timeout,
                        BarcodeSeparator = obs.DocumentsJoinerConfiguration.BarcodeSeparatorValue
                    };
                    var cmd = new CommandMessage <ConfigurationDto>
                    {
                        CommandName = CommandMessageName.UPDATE_CONFIGURATION_COMMAND_NAME,
                        Payload     = cfgDto
                    };
                    commandsQueue.SendMessage(cmd.Serialize());
                };
                obs.Start();
                while (!token.IsCancellationRequested)
                {
                    token.WaitHandle.WaitOne(SEND_STATUS_COMMAND_PERIOD_MS);
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }

                    var statusCmd = new CommandMessage <object>
                    {
                        CommandName = CommandMessageName.SEND_STATUS_COMMAND_NAME
                    };
                    commandsQueue.SendMessage(statusCmd.Serialize());
                }
            }
            finally
            {
                obs?.Dispose();
            }
        }
        private void ControllerOnDocumentsBatchCollected(object sender, DocumentBatchEventArgs e)
        {
            Status = DocumentsJoinerStatus.BUILDING_BATCH;
            var batch  = e.DocumentBatch;
            var joiner = documentsJoinerFactory.Invoke(CancellationSource.Token);

            using (var joinedStream = joiner.Join(batch.Documents))
                using (var ms = new MemoryStream())
                {
                    joinedStream.Seek(0, SeekOrigin.Begin);
                    joinedStream.CopyTo(ms);
                    var message = ms.ToArray();
                    documentsQueue.SendMessage(message);
                }

            Status = DocumentsJoinerStatus.WAITING;
        }
 public void PublishStatusMessages()
 {
     lock (Lock)
     {
         foreach (var statusObservable in observables)
         {
             var statusWithPId          = $"{Process.GetCurrentProcess().Id}: {statusObservable.Status}";
             var configurationStatusDto = new
             {
                 ConfigurationContext.Timeout,
                 ConfigurationContext.BarcodeSeparator
             };
             var msg = $"{statusWithPId}; cfg: {configurationStatusDto}";
             statusQueue.SendMessage(DocumentsJoinerStatus.Encoding.GetBytes(msg));
         }
     }
 }
        public async Task <IActionResult> NewAsync([FromBody] Order order)
        {
            var isnew       = tracer.CurrentTransaction == null;
            var transaction = isnew
                ? tracer.StartTransaction($"NewOrder", "post")
                              .WithLabel("Order: OrderId", order.Id.ToString())
                              .WithLabel("Order: Product", order.Product)
                              .WithLabel("Order: Quantity", order.Quantity.ToString())
                              .WithLabel("Order: Customer", order.CustomerId.ToString())
                : tracer.CurrentTransaction;


            if (order == default(Order))
            {
                return(BadRequest("Body empty or null"));
            }

            order.Id = Guid.NewGuid();

            var customer = await customerRepository.GetByIdAsync(order.CustomerId, CancellationToken.None);

            if (customer == default)
            {
                return(NotFound("Customer"));
            }

            await repository.NewAsync(order, CancellationToken.None);

            messageProducer.SendMessage(new OrderCreatedEvent
            {
                OrderId  = order.Id,
                Product  = order.Product,
                Quantity = order.Quantity
            });

            var span = transaction.StartSpan($"{apis.Inventory}/{order.Product}", ApiConstants.ActionQuery, subType: ApiConstants.SubtypeHttp);
            var availableQuantity = await httpClient.GetAsync <int>($"{apis.Inventory}/{order.Product}").ConfigureAwait(false);

            span.SetLabel("Response", availableQuantity.ToString());
            span?.End();
            logger.LogInformation("inventory service {api} {RequestMethod} {data}", apis.Inventory, "GET", availableQuantity.ToString());

            if (availableQuantity >= order.Quantity)
            {
                await repository.ProcessOrderAsync(order.Id, CancellationToken.None);

                messageProducer.SendMessage(new OrderProcessedEvent
                {
                    OrderId  = order.Id,
                    Product  = order.Product,
                    Quantity = order.Quantity
                });
            }
            else
            {
                await repository.CancelOrderAsync(order.Id, CancellationToken.None);

                messageProducer.SendMessage(new OrderCancelledEvent
                {
                    OrderId = order.Id,
                    Product = order.Product
                });
            }
            if (isnew)
            {
                transaction.End();
            }
            return(Ok());
        }
 private void TimeElapsed(object sender, Timers.ElapsedEventArgs e, HelloWorldMessage helloWorldMessage)
 {
     _messageProducer.SendMessage(_queueName, helloWorldMessage);
     _logger.Log(LogLevel.Information, $"{DateTime.Now} - Enviada mensagem pelo ServiceId: {helloWorldMessage.ServiceId} com RequestId: {helloWorldMessage.RequestId}");
 }
Beispiel #11
0
 public void Send(TransportMessage message, Address address)
 {
     messageProducer.SendMessage(message, address.Queue, "queue://");
 }