using xApi.Models; using xApi.Constants; using xApi.Interfaces; using xApi.Extensions; using System.Text.Json; using System.Net.Http.Headers; namespace xApi.Providers { public class AzureServices : IAzureServices { // private readonly ILogger logger; private readonly IHttpClientFactory httpClientFactory; private readonly AzureServiceConfiguration configuration; public AzureServices( ILogger logger, IHttpClientFactory httpClientFactory, AzureServiceConfiguration configuration ) { // this.logger = logger; this.configuration = configuration; this.httpClientFactory = httpClientFactory; } /// /// Retrieve Connection Info ... /// /// /// /// public async Task GetConnectionDataAsync( CancellationToken cancellationToken = default ) { // // var json = await GetFromAzureAsync( // AzureEndpoints.ConnectionDataEndpoint, // cancellationToken: cancellationToken // ); // var json = await HandleAzureRequest( method: HttpMethod.Get, cancellationToken: cancellationToken, path: AzureEndpoints.ConnectionDataEndpoint ); // var result = json.ParseJSON(); if (result is null) { // var message = "Failed to parse Azure connection data ..."; // logger.LogError(message); throw new InvalidOperationException(message); } // return result; } public async Task GetProjectsAsync( CancellationToken cancellationToken = default ) { // // var json = await GetFromAzureAsync( // AzureEndpoints.ProjectsEndpoint, // cancellationToken: cancellationToken // ); // var json = await HandleAzureRequest( method: HttpMethod.Get, cancellationToken: cancellationToken, path: AzureEndpoints.ProjectsEndpoint ); // // var result = json.ParseJSON(); // if (result is null) // { // // // var message = "Failed to parse Azure connection data ..."; // // // logger.LogError(message); // throw new InvalidOperationException(message); // } // return json; } // #region Private ... private async Task HandleAzureRequest( string path, HttpMethod method, bool forceJsonValidation = true, IDictionary? headers = null, IDictionary? queryParams = null, IDictionary? routeParams = null, CancellationToken cancellationToken = default ) { // // Validate ... var pat = configuration.Pat; if (string.IsNullOrWhiteSpace(pat)) { // var message = "Azure PAT is not configured ..."; logger.LogError(message); throw new InvalidOperationException(message); } if (string.IsNullOrWhiteSpace(path)) { // var message = "Request Path is not configured ..."; logger.LogError(message); throw new InvalidOperationException(message); } // // Create Http Client ... var result = string.Empty; using (HttpClient client = new()) { // // Add Accept ... client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // // Add Personal Access Token ... client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String( System.Text.Encoding.ASCII.GetBytes( string.Format("{0}:{1}", "", pat)))); // // Preparing Request Path ... var url = configuration.BaseUrl; if (!url!.EndsWith('/')) { url += "/"; } if (path.StartsWith('/')) { path = path[1..]; } // // Handle Route Params ... if (routeParams is not null && routeParams.Any()) { // var exists = routeParams.Where(rp => path.Contains(rp.Key)); foreach (var irp in exists) { } } // // Finalize Url ... url = $"{url}{path}"; // // Applying Query String ... url = url .ApplyQueryString(queries: queryParams); // // Preparing Request ... var request = new HttpRequestMessage( method: method, requestUri: url ); // // Applying Headers ... if (headers is not null && headers.Any()) { // foreach (var header in headers) { // if (string.IsNullOrWhiteSpace(header.Value)) { continue; } // request.Headers.Add( name: header.Key, value: header.Value ); } } // try { // using var cts = CancellationTokenSource .CreateLinkedTokenSource(cancellationToken); cts.CancelAfter(TimeSpan.FromSeconds(20)); // // Execute Request ... var response = await client.SendAsync( request: request, cancellationToken: cts.Token ); // // Validate Request ... if (!response.IsSuccessStatusCode) { // var content = await response.Content.ReadAsStringAsync(cts.Token); // logger.LogError("Azure returned HTTP {StatusCode}. Content: {Content} ...", response.StatusCode, content); throw new HttpRequestException($"Azure returned HTTP {(int)response.StatusCode} ..."); } // // Reading Content ... result = await response.Content.ReadAsStringAsync(cts.Token); } catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException || !cancellationToken.IsCancellationRequested) { // logger.LogError(ex, "Azure request timed out. Path: {Path} ...", path); throw new TimeoutException("Azure request timed out ..."); } catch (Exception ex) { // logger.LogError(ex, "Could not connect to Azure. Path: {Path} ...", path); throw; } } // // Force Json Validation ... if (forceJsonValidation) { // // Validating JSON ... try { JsonDocument.Parse(result); } catch (JsonException ex) { // logger.LogError(ex, "Azure returned non-JSON data. Path: {Path} ...", path); throw new InvalidDataException("Azure returned non-JSON data ..."); } } // return result; } private async Task GetFromAzureAsync( string relativePath, CancellationToken cancellationToken = default ) { // // Validate PAT ... var pat = configuration.Pat; if (string.IsNullOrWhiteSpace(pat)) { // logger.LogError("Azure PAT is not configured ..."); throw new InvalidOperationException("Azure PAT is not configured ..."); } // // Create Specified Http Client ... var client = httpClientFactory.CreateClient(Params.AzureHttpClient); // // Url ... var url = $"{client.BaseAddress}{relativePath}"; logger.LogInformation("Url: {url}", url); // // Handle Request and Response ... try { // using var cts = CancellationTokenSource .CreateLinkedTokenSource(cancellationToken); cts.CancelAfter(TimeSpan.FromSeconds(20)); // var response = await client.GetAsync(relativePath, cts.Token); if (!response.IsSuccessStatusCode) { // var content = await response.Content.ReadAsStringAsync(cts.Token); logger.LogError("Azure returned HTTP {StatusCode}. Content: {Content} ...", response.StatusCode, content); throw new HttpRequestException($"Azure returned HTTP {(int)response.StatusCode} ..."); } // // Reading Content ... var json = await response.Content.ReadAsStringAsync(cts.Token); // // Validating JSON ... try { JsonDocument.Parse(json); } catch (JsonException ex) { // logger.LogError(ex, "Azure returned non-JSON data. Path: {Path} ...", relativePath); throw new InvalidDataException("Azure returned non-JSON data ..."); } // return json; } catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException || !cancellationToken.IsCancellationRequested) { // logger.LogError(ex, "Azure request timed out. Path: {Path} ...", relativePath); throw new TimeoutException("Azure request timed out ..."); } catch (Exception ex) { // logger.LogError(ex, "Could not connect to Azure. Path: {Path} ...", relativePath); throw; } } #endregion } }