< Summary

Information
Class: MyNet.Http.ApiParameter
Assembly: MyNet.Http
File(s): https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Http/WebApiService.cs
Tag: 342_31701152804
Line coverage
50%
Covered lines: 2
Uncovered lines: 2
Coverable lines: 4
Total lines: 462
Line coverage: 50%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
op_Implicit(...)100%210%
op_Implicit(...)100%11100%
ToApiParameter(...)100%11100%
ToValueTuple(...)100%210%

File(s)

https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.Http/WebApiService.cs

#LineLine coverage
 1// -----------------------------------------------------------------------
 2// <copyright file="WebApiService.cs" company="Stéphane ANDRE">
 3// Copyright (c) Stéphane ANDRE. All rights reserved.
 4// </copyright>
 5// -----------------------------------------------------------------------
 6
 7using System;
 8using System.Collections.Generic;
 9using System.Diagnostics.CodeAnalysis;
 10using System.Globalization;
 11using System.IO;
 12using System.Linq;
 13using System.Net;
 14using System.Net.Http;
 15using System.Net.Http.Headers;
 16using System.Text;
 17using System.Text.Json;
 18using System.Text.Json.Nodes;
 19using System.Threading;
 20using System.Threading.Tasks;
 21using MyNet.Http.Exceptions;
 22using MyNet.Text;
 23
 24namespace MyNet.Http;
 25
 26/// <summary>
 27/// Provides methods to interact with web APIs using HTTP requests. The <see cref="WebApiService"/> class allows sending
 28/// </summary>
 29public sealed class WebApiService : IWebApiService
 30{
 31    private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true };
 32
 33    private readonly HttpClient _client;
 34    private readonly bool _disposeClient;
 35    private readonly TimeSpan _timeout;
 36    private readonly Func<object?, Exception>? _toException;
 37
 38    /// <summary>
 39    /// Initializes a new instance of the <see cref="WebApiService"/> class.
 40    /// </summary>
 41    /// <param name="serverUrl">Target server URL.</param>
 42    /// <param name="timeout">Maximum request timeout duration.</param>
 43    /// <param name="headers">Custom HTTP headers.</param>
 44    /// <param name="toException">Function to convert a response to an exception.</param>
 45    public WebApiService(Uri? serverUrl = null, TimeSpan timeout = default, Dictionary<string, string>? headers = null, 
 46        : this(CreateHttpClient(serverUrl, headers), timeout, toException, disposeClient: true)
 47    {
 48    }
 49
 50    /// <summary>
 51    /// Initializes a new instance of the <see cref="WebApiService"/> class with a custom <see cref="HttpClient"/>.
 52    /// </summary>
 53    /// <param name="client">Configured HTTP client.</param>
 54    /// <param name="timeout">Maximum request timeout duration.</param>
 55    /// <param name="toException">Function to convert a response to an exception.</param>
 56    /// <param name="disposeClient">Indicates whether this service should dispose the HTTP client.</param>
 57    public WebApiService(HttpClient client, TimeSpan timeout = default, Func<object?, Exception>? toException = null, bo
 58    {
 59        ArgumentNullException.ThrowIfNull(client);
 60
 61        _client = client;
 62        _disposeClient = disposeClient;
 63        _toException = toException;
 64        _timeout = timeout != TimeSpan.Zero ? timeout : TimeSpan.FromMilliseconds(Timeout.Infinite);
 65
 66        // We enforce timeouts per request via CancellationTokenSource.CancelAfter.
 67        _client.Timeout = Timeout.InfiniteTimeSpan;
 68    }
 69
 70    /// <inheritdoc/>
 71    public Task<Stream> GetStreamAsync(string str) => GetStreamAsync(new Uri(str, UriKind.RelativeOrAbsolute), Cancellat
 72
 73    /// <inheritdoc/>
 74    public Task<T> GetDataAsync<T>(string str, CancellationToken cancellationToken, params ApiParameter[] parameters) =>
 75
 76    /// <inheritdoc/>
 77    public Task<T> GetDataAsync<T>(Uri uri, CancellationToken cancellationToken = default) => SendRequestAsync<T>(HttpMe
 78
 79    /// <inheritdoc/>
 80    public Task<TReturn> PostDataAsync<TParam, TReturn>(string str, TParam value, CancellationToken cancellationToken, p
 81
 82    /// <inheritdoc/>
 83    public Task<T> PostDataAsync<TParam, T>(Uri uri, TParam value, CancellationToken cancellationToken = default) => Sen
 84
 85    /// <inheritdoc/>
 86    public Task PostDataAsync<TParam>(string str, TParam value, CancellationToken cancellationToken, params ApiParameter
 87
 88    /// <inheritdoc/>
 89    public Task PostDataAsync<TParam>(Uri uri, TParam value, CancellationToken cancellationToken = default) => SendReque
 90
 91    /// <inheritdoc/>
 92    public Task PostDataAsync(string str, CancellationToken cancellationToken, params ApiParameter[] parameters) => Post
 93
 94    /// <inheritdoc/>
 95    public Task PostDataAsync(Uri uri, CancellationToken cancellationToken = default) => SendRequestAsync(HttpMethod.Pos
 96
 97    /// <inheritdoc/>
 98    public Task<TReturn> PutDataAsync<TParam, TReturn>(string str, TParam value, CancellationToken cancellationToken, pa
 99
 100    /// <inheritdoc/>
 101    public Task<T> PutDataAsync<TParam, T>(Uri uri, TParam value, CancellationToken cancellationToken = default) => Send
 102
 103    /// <inheritdoc/>
 104    public Task<TReturn> PatchDataAsync<TParam, TReturn>(string str, TParam value, CancellationToken cancellationToken, 
 105
 106    /// <inheritdoc/>
 107    public Task<T> PatchDataAsync<TParam, T>(Uri uri, TParam value, CancellationToken cancellationToken = default) => Se
 108
 109    /// <inheritdoc/>
 110    public Task DeleteDataAsync(string str, CancellationToken cancellationToken, params ApiParameter[] parameters) => De
 111
 112    /// <inheritdoc/>
 113    public Task DeleteDataAsync(Uri uri, CancellationToken cancellationToken = default) => SendRequestAsync(HttpMethod.D
 114
 115    /// <inheritdoc/>
 116    public Task<TReturn> DeleteDataAsync<TParam, TReturn>(string str, TParam value, CancellationToken cancellationToken,
 117
 118    /// <inheritdoc/>
 119    public Task<T> DeleteDataAsync<TParam, T>(Uri uri, TParam value, CancellationToken cancellationToken = default) => S
 120
 121    /// <inheritdoc/>
 122    public Task DeleteDataAsync<TParam>(string str, TParam value, CancellationToken cancellationToken, params ApiParamet
 123
 124    /// <inheritdoc/>
 125    public Task DeleteDataAsync<TParam>(Uri uri, TParam value, CancellationToken cancellationToken = default) => SendReq
 126
 127    /// <inheritdoc/>
 128    public void Dispose()
 129    {
 130        if (_disposeClient)
 131        {
 132            _client.Dispose();
 133        }
 134    }
 135
 136    /// <inheritdoc/>
 137    public async Task SendRequestAsync(HttpMethod method, Uri uri, HttpContent? content = null, CancellationToken cancel
 138    {
 139        using var request = CreateRequest(method, uri, content);
 140        using var linkedCancellationToken = CreateLinkedTimeoutTokenSource(request, cancellationToken, out var tokenSour
 141
 142        HttpResponseMessage? response = null;
 143        try
 144        {
 145            response = await _client.SendAsync(request, HttpCompletionOption.ResponseContentRead, linkedCancellationToke
 146
 147            if (response.IsSuccessStatusCode)
 148            {
 149                return;
 150            }
 151
 152            throw await GetExceptionAsync(response, linkedCancellationToken.Token).ConfigureAwait(false);
 153        }
 154        catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
 155        {
 156            throw new TimeoutException();
 157        }
 158        finally
 159        {
 160            response?.Dispose();
 161            tokenSource.Dispose();
 162        }
 163    }
 164
 165    /// <inheritdoc/>
 166    public async Task<T> SendRequestAsync<T>(HttpMethod method, Uri uri, HttpContent? content = null, CancellationToken 
 167    {
 168        using var request = CreateRequest(method, uri, content);
 169        using var linkedCancellationToken = CreateLinkedTimeoutTokenSource(request, cancellationToken, out var tokenSour
 170
 171        HttpResponseMessage? response = null;
 172        try
 173        {
 174            response = await _client.SendAsync(request, HttpCompletionOption.ResponseContentRead, linkedCancellationToke
 175            return !response.IsSuccessStatusCode
 176                ? throw await GetExceptionAsync(response, linkedCancellationToken.Token).ConfigureAwait(false)
 177                : await ReadResponseAsync<T>(response, linkedCancellationToken.Token).ConfigureAwait(false);
 178        }
 179        catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
 180        {
 181            throw new TimeoutException();
 182        }
 183        finally
 184        {
 185            response?.Dispose();
 186            tokenSource.Dispose();
 187        }
 188    }
 189
 190    private static HttpClient CreateHttpClient(Uri? serverUrl, Dictionary<string, string>? headers)
 191    {
 192        var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip, CheckCertificateRevoca
 193
 194        var client = new HttpClient(handler) { BaseAddress = serverUrl };
 195
 196        client.DefaultRequestHeaders.Accept.Clear();
 197        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 198        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/problem+json"));
 199        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
 200        client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip"));
 201        ApplyHeaders(client.DefaultRequestHeaders, headers);
 202
 203        return client;
 204    }
 205
 206    private async Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken)
 207    {
 208        using var request = CreateRequest(HttpMethod.Get, uri);
 209        using var linkedCancellationToken = CreateLinkedTimeoutTokenSource(request, cancellationToken, out var tokenSour
 210
 211        HttpResponseMessage? response = null;
 212        try
 213        {
 214            response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, linkedCancellationToke
 215
 216            if (!response.IsSuccessStatusCode)
 217                throw await GetExceptionAsync(response, linkedCancellationToken.Token).ConfigureAwait(false);
 218            var stream = await response.Content.ReadAsStreamAsync(linkedCancellationToken.Token).ConfigureAwait(false);
 219            var responseToReturn = response;
 220            response = null;
 221
 222            return new ResponseStream(stream, responseToReturn);
 223        }
 224        catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
 225        {
 226            throw new TimeoutException();
 227        }
 228        finally
 229        {
 230            response?.Dispose();
 231            tokenSource.Dispose();
 232        }
 233    }
 234
 235    [SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1204:Static members should appear before non-static members", J
 236    private static void ApplyHeaders(HttpRequestHeaders headers, Dictionary<string, string>? customHeaders)
 237    {
 238        if (customHeaders is null)
 239        {
 240            return;
 241        }
 242
 243        foreach (var (key, value) in customHeaders)
 244        {
 245            if (string.Equals(key, "Authorization", StringComparison.OrdinalIgnoreCase))
 246            {
 247                headers.Authorization = AuthenticationHeaderValue.Parse(value);
 248                continue;
 249            }
 250
 251            if (!headers.TryAddWithoutValidation(key, value))
 252            {
 253                throw new InvalidOperationException($"Unable to add HTTP header '{key}'.");
 254            }
 255        }
 256    }
 257
 258    private static HttpRequestMessage CreateRequest(HttpMethod method, Uri uri, HttpContent? content = null)
 259    {
 260        var request = new HttpRequestMessage(method, uri) { Content = content };
 261
 262        request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(CultureInfo.CurrentCulture.Name));
 263        return request;
 264    }
 265
 266    private CancellationTokenSource CreateLinkedTimeoutTokenSource(HttpRequestMessage request, CancellationToken cancell
 267    {
 268        tokenSource = new CancellationTokenSource();
 269        var linked = CancellationTokenSource.CreateLinkedTokenSource(tokenSource.Token, cancellationToken);
 270        var effectiveTimeout = request.GetTimeout() ?? _timeout;
 271
 272        if (effectiveTimeout != Timeout.InfiniteTimeSpan)
 273        {
 274            tokenSource.CancelAfter(effectiveTimeout);
 275        }
 276
 277        return linked;
 278    }
 279
 280    [SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1204:Static members should appear before non-static members", J
 281    private static StringContent CreateContent<TParam>(TParam value) => new(JsonSerializer.Serialize(value, JsonOptions)
 282
 283    private static Uri ToWebUri(string str, ApiParameter[] parameters)
 284        => parameters.Length == 0 && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out var uri)
 285            ? uri
 286            : str.ToWebUri([.. parameters.Select(x => (x.Key, x.Value))]);
 287
 288    [SuppressMessage("Reliability", "CA2007:Appeler ConfigureAwait sur la tâche attendue", Justification = "Library code
 289    private static async Task<T> ReadResponseAsync<T>(HttpResponseMessage response, CancellationToken cancellationToken)
 290    {
 291        if (typeof(T) == typeof(string))
 292        {
 293            return (T)(object)await response.Content
 294                .ReadAsStringAsync(cancellationToken)
 295                .ConfigureAwait(false);
 296        }
 297
 298        await using var stream = await response.Content
 299            .ReadAsStreamAsync(cancellationToken)
 300            .ConfigureAwait(false);
 301
 302        if (stream.Length == 0)
 303        {
 304            throw new JsonException($"Response body is empty and cannot be deserialized to '{typeof(T)}'.");
 305        }
 306
 307        var result = await JsonSerializer.DeserializeAsync<T>(stream, JsonOptions, cancellationToken).ConfigureAwait(fal
 308        return result ?? throw new JsonException($"Unable to deserialize response body to '{typeof(T)}'.");
 309    }
 310
 311    private Task<Exception> GetExceptionAsync(HttpResponseMessage response, CancellationToken cancellationToken) => GetE
 312
 313    private async Task<Exception> GetExceptionAsync(HttpStatusCode statusCode, string? reasonPhrase, HttpContent content
 314    {
 315        string? text = null;
 316        try
 317        {
 318            text = await content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
 319        }
 320        catch
 321        {
 322            // ignore read failures: we still want to throw a meaningful exception.
 323        }
 324
 325        var problemException = ProblemDetailsParser.TryParseException(text);
 326        if (problemException is not null)
 327        {
 328            return problemException;
 329        }
 330
 331        object? payload = null;
 332        if (string.IsNullOrWhiteSpace(text))
 333            return _toException?.Invoke(payload) ?? new WebApiException(statusCode, reasonPhrase, text, payload);
 334        try
 335        {
 336            payload = JsonNode.Parse(text);
 337        }
 338        catch (JsonException)
 339        {
 340            payload = text;
 341        }
 342
 343        return _toException?.Invoke(payload) ?? new WebApiException(statusCode, reasonPhrase, text, payload);
 344    }
 345
 346    /// <summary>
 347    /// A stream wrapper that ensures the underlying HTTP response is disposed when the stream is disposed. This is nece
 348    /// </summary>
 349    /// <param name="inner">The inner stream to wrap.</param>
 350    /// <param name="response">The HTTP response message associated with the stream.</param>
 351    private sealed class ResponseStream(Stream inner, HttpResponseMessage response) : Stream
 352    {
 353        /// <inheritdoc/>
 354        public override bool CanRead => inner.CanRead;
 355
 356        /// <inheritdoc/>
 357        public override bool CanSeek => inner.CanSeek;
 358
 359        /// <inheritdoc/>
 360        public override bool CanWrite => inner.CanWrite;
 361
 362        /// <inheritdoc/>
 363        public override long Length => inner.Length;
 364
 365        /// <inheritdoc/>
 366        public override long Position
 367        {
 368            get => inner.Position;
 369            set => inner.Position = value;
 370        }
 371
 372        /// <inheritdoc/>
 373        public override void Flush() => inner.Flush();
 374
 375        /// <inheritdoc/>
 376        public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count);
 377
 378        /// <inheritdoc/>
 379        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =
 380
 381        /// <inheritdoc/>
 382        public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) => 
 383
 384        /// <inheritdoc/>
 385        public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);
 386
 387        /// <inheritdoc/>
 388        public override void SetLength(long value) => inner.SetLength(value);
 389
 390        /// <inheritdoc/>
 391        public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count);
 392
 393        /// <inheritdoc/>
 394        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => in
 395
 396        /// <inheritdoc/>
 397        public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
 398
 399        /// <inheritdoc/>
 400        protected override void Dispose(bool disposing)
 401        {
 402            if (disposing)
 403            {
 404                inner.Dispose();
 405                response.Dispose();
 406            }
 407
 408            base.Dispose(disposing);
 409        }
 410
 411        /// <inheritdoc/>
 412        public override async ValueTask DisposeAsync()
 413        {
 414            try
 415            {
 416                await inner.DisposeAsync().ConfigureAwait(false);
 417            }
 418            finally
 419            {
 420                response.Dispose();
 421            }
 422
 423            await base.DisposeAsync().ConfigureAwait(false);
 424        }
 425    }
 426}
 427
 428/// <summary>
 429/// Represents a key-value pair for API parameters, such as query parameters or form data. This struct provides implicit
 430/// </summary>
 431/// <param name="Key">The key of the API parameter.</param>
 432/// <param name="Value">The value of the API parameter.</param>
 433public record struct ApiParameter(string Key, string Value)
 434{
 435    /// <summary>
 436    /// Defines an implicit conversion from an <see cref="ApiParameter"/> to a tuple of (string Key, string Value). This
 437    /// </summary>
 438    /// <param name="value">The <see cref="ApiParameter"/> instance to convert.</param>
 0439    public static implicit operator (string Key, string Value)(ApiParameter value) => ToValueTuple(value);
 440
 441    /// <summary>
 442    /// Defines an implicit conversion from a tuple of (string Key, string Value) to an <see cref="ApiParameter"/>. This
 443    /// </summary>
 444    /// <param name="value">The tuple representing the API parameter.</param>
 445    /// <returns>A new <see cref="ApiParameter"/> instance with the specified Key and Value.</returns>
 3446    public static implicit operator ApiParameter((string Key, string Value) value) => ToApiParameter(value);
 447
 448    /// <summary>
 449    /// Converts a tuple of (string Key, string Value) to an <see cref="ApiParameter"/>. This method is used by the impl
 450    /// </summary>
 451    /// <param name="value">The tuple representing the API parameter.</param>
 452    /// <returns>A new <see cref="ApiParameter"/> instance with the specified Key and Value.</returns>
 3453    public static ApiParameter ToApiParameter((string Key, string Value) value) => new(value.Key, value.Value);
 454
 455    /// <summary>
 456    /// Converts an <see cref="ApiParameter"/> to a tuple of (string Key, string Value). This method is used by the impl
 457    /// </summary>
 458    /// <param name="value">The <see cref="ApiParameter"/> instance to convert.</param>
 459    /// <returns>A tuple containing the Key and Value of the <see cref="ApiParameter"/> instance.</returns>
 0460    public static (string Key, string Value) ToValueTuple(ApiParameter value) => (value.Key, value.Value);
 461}
 462