Пример #1
0
        private async Task NotifySearchRequestOrderedEvent(
            string requestId,
            SearchRequestOrdered searchRequestOrdered,
            CancellationToken cancellationToken,
            int retryTimes,
            int maxRetryTimes)
        {
            var webHookName = "SearchRequest";

            if (searchRequestOrdered == null)
            {
                throw new ArgumentNullException(nameof(SearchRequestOrdered));
            }

            string eventName = searchRequestOrdered.Action switch
            {
                RequestAction.NEW => "CreateSearchRequest",
                RequestAction.UPDATE => "UpdateSearchRequest",
                RequestAction.CANCEL => "CancelSearchRequest",
                _ => null
            };

            foreach (var webHook in _searchRequestOptions.WebHooks)
            {
                _logger.LogDebug(
                    $"The webHook {webHookName} notification is attempting to send {eventName} for {webHook.Name} webhook.");

                if (!URLHelper.TryCreateUri(webHook.Uri, eventName, $"{requestId}", out var endpoint))
                {
                    _logger.LogWarning(
                        $"The webHook {webHookName} notification uri is not established or is not an absolute Uri for {webHook.Name}. Set the WebHook.Uri value on SearchApi.WebHooks settings.");
                    throw new Exception($"The webHook {webHookName} notification uri is not established or is not an absolute Uri for {webHook.Name}.");
                }

                using var request = new HttpRequestMessage();

                try
                {
                    StringContent content = new StringContent(JsonConvert.SerializeObject(searchRequestOrdered));

                    content.Headers.ContentType =
                        System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request.Content = content;
                    request.Method  = HttpMethod.Post;
                    request.Headers.Accept.Add(
                        System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
                    request.Headers.Add("X-ApiKey", _searchRequestOptions.ApiKeyForDynadaptor);
                    request.RequestUri = endpoint;
                    var response = await _httpClient.SendAsync(request, cancellationToken);

                    if (!response.IsSuccessStatusCode)
                    {
                        if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError || response.StatusCode == System.Net.HttpStatusCode.GatewayTimeout)
                        {
                            string reason = await response.Content.ReadAsStringAsync();

                            _logger.LogError(
                                $"The webHook {webHookName} notification has not executed status {eventName} successfully for {webHook.Name} webHook. The error code is {response.StatusCode.GetHashCode()}.Reason is {reason}.");
                            throw(new Exception($"The webHook {webHookName} notification has not executed status {eventName} successfully for {webHook.Name} webHook. The error code is {response.StatusCode.GetHashCode()}."));
                        }
                        else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                        {
                            string reason = await response.Content.ReadAsStringAsync();

                            RejectReason reasonObj = JsonConvert.DeserializeObject <RejectReason>(reason);
                            if (reasonObj.ReasonCode.Equals("error", StringComparison.InvariantCultureIgnoreCase))
                            {
                                throw new Exception("should not get here. the request is wrong.");
                            }

                            await _searchRequestEventPublisher.PublishSearchRequestRejected(
                                searchRequestOrdered,
                                new List <ValidationResult>()
                            {
                                new ValidationResultData()
                                {
                                    PropertyName = reasonObj.ReasonCode, ErrorMessage = reasonObj.Message
                                }
                            });

                            return;
                        }

                        var exContent = await response.Content.ReadAsStringAsync();

                        throw new Exception($"Message Failed {response.StatusCode}, {exContent}");
                    }

                    _logger.LogInformation("get response successfully from webhook.");
                    string responseContent = await response.Content.ReadAsStringAsync();

                    var saved = JsonConvert.DeserializeObject <SearchRequestSavedEvent>(responseContent);

                    //for the new action, we changed from Dynamics push the notification to here, openshift publish notification once sr is created.
                    //for the update action, fmep needs notified and notification from dynamics.
                    if (saved.Action == RequestAction.NEW)
                    {
                        _logger.LogInformation("create sr get success, publish accepted notification");
                        var notifyEvent = new SearchRequestNotificationEvent
                        {
                            ProviderProfile     = saved.ProviderProfile,
                            NotificationType    = NotificationType.RequestSaved,
                            RequestId           = saved.RequestId,
                            SearchRequestKey    = saved.SearchRequestKey,
                            QueuePosition       = saved.QueuePosition,
                            Message             = $"Activity RequestSaved occured. ",
                            TimeStamp           = DateTime.Now,
                            EstimatedCompletion = saved.EstimatedCompletion,
                            FSOName             = null,
                            Person = null
                        };
                        await _searchRequestEventPublisher.PublishSearchRequestNotification(notifyEvent);
                    }

                    if (saved.Action == RequestAction.UPDATE)
                    {
                        _logger.LogInformation($"publish SearchRequestSaved");
                        await _searchRequestEventPublisher.PublishSearchRequestSaved(saved);

                        _logger.LogInformation("update sr get success, publish accepted notification");
                        var notifyEvent = new SearchRequestNotificationEvent
                        {
                            ProviderProfile     = saved.ProviderProfile,
                            NotificationType    = NotificationType.RequestSaved,
                            RequestId           = saved.RequestId,
                            SearchRequestKey    = saved.SearchRequestKey,
                            QueuePosition       = saved.QueuePosition,
                            Message             = $"Activity RequestSaved occured. ",
                            TimeStamp           = DateTime.Now,
                            EstimatedCompletion = saved.EstimatedCompletion,
                            FSOName             = null,
                            Person = null
                        };

                        await _searchRequestEventPublisher.PublishSearchRequestNotification(notifyEvent);
                    }

                    if (saved.Action == RequestAction.CANCEL)
                    {
                        _logger.LogInformation(
                            $"publish SearchRequestSaved");
                        await _searchRequestEventPublisher.PublishSearchRequestSaved(saved);
                    }
                }
                catch (Exception exception)
                {
                    _logger.LogError(exception, exception.Message);
                    throw;
                }
            }
        }
Пример #2
0
        public async Task NotifySearchRequestEventAsync(string requestId, SearchRequestOrdered searchRequestOrdered,
                                                        CancellationToken cancellationToken)
        {
            var webHookName = "SearchRequest";

            if (searchRequestOrdered == null)
            {
                throw new ArgumentNullException(nameof(SearchRequestOrdered));
            }

            string eventName = searchRequestOrdered.Action switch
            {
                RequestAction.NEW => "CreateSearchRequest",
                RequestAction.UPDATE => "UpdateSearchRequest",
                RequestAction.CANCEL => "CancelSearchRequest",
                _ => null
            };

            foreach (var webHook in _searchRequestOptions.WebHooks)
            {
                _logger.LogDebug(
                    $"The webHook {webHookName} notification is attempting to send {eventName} for {webHook.Name} webhook.");

                if (!URLHelper.TryCreateUri(webHook.Uri, eventName, $"{requestId}", out var endpoint))
                {
                    _logger.LogWarning(
                        $"The webHook {webHookName} notification uri is not established or is not an absolute Uri for {webHook.Name}. Set the WebHook.Uri value on SearchApi.WebHooks settings.");
                    await _searchRequestEventPublisher.PublishSearchRequestFailed(
                        searchRequestOrdered, "notification uri is not established or is not an absolute Uri."
                        );

                    return;
                }

                using var request = new HttpRequestMessage();

                try
                {
                    StringContent content = new StringContent(JsonConvert.SerializeObject(searchRequestOrdered));

                    content.Headers.ContentType =
                        System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request.Content = content;
                    request.Method  = HttpMethod.Post;
                    request.Headers.Accept.Add(
                        System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
                    request.RequestUri = endpoint;
                    var response = await _httpClient.SendAsync(request, cancellationToken);

                    if (!response.IsSuccessStatusCode)
                    {
                        if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
                        {
                            string reason = await response.Content.ReadAsStringAsync();

                            RejectReason reasonObj = JsonConvert.DeserializeObject <RejectReason>(reason);
                            _logger.LogError(
                                $"The webHook {webHookName} notification has not executed status {eventName} successfully for {webHook.Name} webHook. The error code is {response.StatusCode.GetHashCode()}.");
                            await _searchRequestEventPublisher.PublishSearchRequestRejected(
                                searchRequestOrdered,
                                new List <ValidationResult>()
                            {
                                new ValidationResultData()
                                {
                                    PropertyName = reasonObj.ReasonCode, ErrorMessage = reasonObj.Message
                                }
                            });

                            return;
                        }
                        else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                        {
                            await _searchRequestEventPublisher.PublishSearchRequestRejected(
                                searchRequestOrdered,
                                new List <ValidationResult>()
                            {
                                new ValidationResultData()
                                {
                                    PropertyName = "badRequest", ErrorMessage = await response.Content.ReadAsStringAsync()
                                }
                            });

                            return;
                        }
                        else
                        {
                            throw new Exception("failed");
                        }
                    }

                    _logger.LogInformation("get response successfully from webhook.");
                    string responseContent = await response.Content.ReadAsStringAsync();

                    var saved = JsonConvert.DeserializeObject <SearchRequestSavedEvent>(responseContent);

                    //for the new action will get Notification, only failed or rejected are got published.
                    //for the update action, fmep needs notified and notification from dynamics.
                    if (saved.Action != RequestAction.NEW)
                    {
                        _logger.LogInformation(
                            $"publish SearchRequestSaved");
                        await _searchRequestEventPublisher.PublishSearchRequestSaved(saved);
                    }
                }
                catch (Exception exception)
                {
                    await _searchRequestEventPublisher.PublishSearchRequestFailed(searchRequestOrdered, exception.Message);

                    _logger.LogError($"The webHook {webHookName} notification failed for {eventName} for {webHook.Name} webHook. [{exception.Message}]");
                }
            }
        }
    }