Пример #1
0
        /// <summary>
        ///   Performs the tasks needed to handle a <see cref="ProcessOrder" /> command.
        /// </summary>
        ///
        /// <param name="processOrderMessage">The brokered message containing the command to process.</param>
        ///
        public async Task HandleProcessOrderAsync([ServiceBusTrigger(TriggerQueueNames.ProcessOrderCommandQueue)] BrokeredMessage processOrderMessage)
        {
            if (processOrderMessage == null)
            {
                this.Log.Error("The {CommandType} brokered message was null.", nameof(ProcessOrder));
                throw new ArgumentNullException(nameof(processOrderMessage));
            }

            ILogger      log     = null;
            ProcessOrder command = null;

            try
            {
                // Attempt to retrieve the command from the brokered message.

                using (var bodyStream = processOrderMessage.GetBody <Stream>())
                    using (var reader = new StreamReader(bodyStream))
                        using (var jsonReader = new JsonTextReader(reader))
                        {
                            command = this.jsonSerializer.Deserialize <ProcessOrder>(jsonReader);

                            jsonReader.Close();
                            reader.Close();
                            bodyStream.Close();
                        };

                // If the body was not a proper ProcessOrder command, an empty command will be
                // returned.  Verify that the Id and OrderId are not in their default states.

                if ((command.Id == Guid.Empty) && (command.OrderId == null))
                {
                    throw new MissingDependencyException("The command could not be extracted from the brokered message");
                }

                // Process the order identified by the command.

                var correlationId = command.CorrelationId ?? processOrderMessage.CorrelationId;

                log = this.Log.WithCorrelationId(correlationId);
                log.Information("A {CommandType} command was received and is being handled.  {Command}", nameof(ProcessOrder), command);

                var result = await this.orderProcessor.ProcessOrderAsync(command.PartnerCode, command.OrderId, (IReadOnlyDictionary <string, string>) command.Assets, command.Emulation, correlationId);

                // Consider the result to complete handling.  If processing was successful, then the message should be completed to
                // ensure that it is not retried.

                if (result?.Outcome == Outcome.Success)
                {
                    await this.submitOrderForProductionPublisher.PublishAsync(command.CreateNewOrderCommand <SubmitOrderForProduction>(cmd => cmd.Emulation = command.Emulation));

                    await this.CompleteMessageAsync(processOrderMessage);

                    this.eventPublisher.TryPublishAsync(command.CreateNewOrderEvent <OrderProcessed>()).FireAndForget();
                    log.Information("A {CommandType} command was successfully handled.  The order was staged for submission with the key {CreateOrderMessageKey}.", nameof(ProcessOrder), result?.Payload);
                }
                else
                {
                    log.Warning("A {CommandType} command was successfully handled.  The order procesing was not successful, however.", nameof(ProcessOrder));

                    // Attempt to schedule the command for a retry using a backoff policy.  If scheduled, complete the current message so that it is removed
                    // from the queue.  Otherwise, throw to expose the failure to the WebJob infrastructure so that the command will be moved to the dead letter
                    // queue after retries are exhausted.

                    if (await this.ScheduleCommandForRetryIfEligibleAsync(command, this.retryThresholds, this.rng, this.clock, this.processOrderPublisher))
                    {
                        await this.CompleteMessageAsync(processOrderMessage);
                    }
                    else
                    {
                        await this.notifyOfFatalFailurePublisher.TryPublishAsync(command.CreateNewOrderCommand <NotifyOfFatalFailure>());

                        throw new FailedtoHandleCommandException();
                    }
                }
            }

            catch (Exception ex) when(!(ex is FailedtoHandleCommandException))
            {
                (log ?? this.Log).Error(ex, "An exception occurred while handling the {CommandType} comand", nameof(ProcessOrder));

                var failedEvent = (command?.CreateNewOrderEvent <OrderProcessingFailed>() ?? new OrderProcessingFailed
                {
                    Id = Guid.NewGuid(),
                    CorrelationId = processOrderMessage?.CorrelationId,
                    OccurredTimeUtc = this.clock.GetCurrentInstant().ToDateTimeUtc()
                });

                this.eventPublisher.TryPublishAsync(failedEvent).FireAndForget();

                // Attempt to schedule the command for a retry using a backoff policy.  If scheduled, complete the current message so that it is removed
                // from the queue.  Otherwise, throw to expose the failure to the WebJob infrastructure so that the command will be moved to the dead letter
                // queue after retries are exhausted.

                if (await this.ScheduleCommandForRetryIfEligibleAsync(command, this.retryThresholds, this.rng, this.clock, this.processOrderPublisher))
                {
                    await this.CompleteMessageAsync(processOrderMessage);
                }
                else
                {
                    await this.notifyOfFatalFailurePublisher.TryPublishAsync(command.CreateNewOrderCommand <NotifyOfFatalFailure>());

                    throw;
                };
            }
        }