< Summary

Information
Class: NanoRoute.AwsLambda.ApiGatewayV2Router
Assembly: NanoRoute.AwsLambda.dll
File(s): /home/runner/work/nanoroute/nanoroute/Src/NanoRoute.AwsLambda/Public/ApiGatewayV2Router.cs
Line coverage
100%
Covered lines: 43
Uncovered lines: 0
Coverable lines: 43
Total lines: 237
Line coverage: 100%
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

MethodBlocks covered Blocks not covered
CreateRequestMessage(...)780
ApiGatewayV2Router(...)20
CreateBuilder()50

File(s)

/home/runner/work/nanoroute/nanoroute/Src/NanoRoute.AwsLambda/Public/ApiGatewayV2Router.cs

#LineLine coverage
 1/********************************************************************************
 2* ApiGatewayV2Router.cs                                                         *
 3*                                                                               *
 4* Author: Denes Solti                                                           *
 5********************************************************************************/
 6using System;
 7using System.Collections.Generic;
 8using System.Net;
 9using System.Net.Http;
 10using System.Net.Http.Headers;
 11using System.Text.Json;
 12using System.Threading;
 13using System.Threading.Tasks;
 14
 15using Amazon.Lambda.APIGatewayEvents;
 16using Amazon.Lambda.Core;
 17
 18namespace NanoRoute.AwsLambda
 19{
 20    using Properties;
 21
 22    /// <summary>
 23    /// Routes API Gateway HTTP API and Lambda Function URL <see cref="APIGatewayHttpApiV2ProxyRequest"/> instances thro
 24    /// </summary>
 25    /// <example>
 26    /// <code>
 27    /// ApiGatewayV2Router router = ApiGatewayV2Router
 28    ///     .CreateBuilder()
 29    ///     .AddJsonErrorDetails()
 30    ///     .AddDefaultValueParsers()
 31    ///     .AddHandler("GET", "/health/", (context, _) =&gt; HttpResponseMessage.Json(new { status = "ok" }))
 32    ///     .CreateRouter();
 33    /// </code>
 34    /// </example>
 35    public sealed class ApiGatewayV2Router : RouterBase<ApiGatewayV2RouterConfig>
 36    {
 37        #region Private
 38        internal HttpRequestMessage CreateRequestMessage(APIGatewayHttpApiV2ProxyRequest request)
 139        {
 140            if (!Uri.TryCreate($"{Config.RequestScheme}://{Config.RequestDomain ?? request.RequestContext.DomainName}", 
 141                throw new InvalidOperationException(Resources.ERR_UNKNOWN_URI);
 42
 143            UriBuilder uriBuilder = new(baseUri)
 144            {
 145                Path = request.RawPath is { Length: > 0 } path ? path : "/",
 146                Query = request.RawQueryString is { Length: > 0 } query ? query : null
 147            };
 48
 149            HttpRequestMessage requestMessage = new
 150            (
 151                HttpMethod.For(request.RequestContext.Http.Method),
 152                uriBuilder.Uri
 153            )
 154            {
 155                Content = request switch
 156                {
 157                    { IsBase64Encoded: false } and { Body.Length: > 0 } => new StringContent(request.Body),
 158                    { IsBase64Encoded: true } and { Body.Length: > 0 } => new StreamContent
 159                    (
 160                        new Base64BodyReaderStream(request.Body)
 161                    ),
 162                    _ => null
 163                }
 164            };
 65
 166            requestMessage.Content?.Headers.Clear();
 67
 168            HttpHeaders
 169                requestHeaders = requestMessage.Headers,
 170                contentHeaders = requestMessage.Content?.Headers!;
 71
 172            foreach (KeyValuePair<string, string> header in request.Headers)
 173            {
 174                HttpHeaders headers = contentHeaders is not null && HttpRequestMessage.ContentHeaders.Contains(header.Ke
 175                    ? contentHeaders
 176                    : requestHeaders;
 77
 178                headers.TryAddWithoutValidation(header.Key, header.Value);
 179            }
 80
 181            requestMessage.OriginalRequest = request;
 182            requestMessage.TraceId = request.RequestContext.RequestId;
 83
 184            return requestMessage;
 185        }
 86
 87        internal static async Task<APIGatewayHttpApiV2ProxyResponse> CreateResponse(HttpResponseMessage responseMessage)
 88        {
 89            Dictionary<string, string> headers = new(StringComparer.OrdinalIgnoreCase);
 90            List<string> cookies = new();
 91
 92            APIGatewayHttpApiV2ProxyResponse response = new()
 93            {
 94                StatusCode = (int) responseMessage.StatusCode
 95            };
 96
 97            CopyHeaders(responseMessage.Headers, headers, cookies);
 98
 99            if (responseMessage.Content is { } content)
 100            {
 101                CopyHeaders(content.Headers, headers, cookies);
 102
 103                switch (content)
 104                {
 105                    case StringContent stringContent:
 106                    {
 107                        if (await stringContent.ReadAsStringAsync().ConfigureAwait(false) is { Length: > 0 } body)
 108                            response.Body = body;
 109                        break;
 110                    }
 111                    default:
 112                    {
 113                        using Base64BodyWriterStream destination = new();
 114
 115                        await content.CopyToAsync(destination).ConfigureAwait(false);
 116
 117                        if (destination.GetBody() is { Length: > 0 } body)
 118                        {
 119                            response.Body = body;
 120                            response.IsBase64Encoded = true;
 121                        }
 122
 123                        break;
 124                    }
 125                }
 126            }
 127
 128            response.Headers = headers;
 129            response.Cookies = cookies.ToArray();
 130
 131            return response;
 132
 133            static void CopyHeaders(HttpHeaders source, Dictionary<string, string> headers, List<string> cookies)
 134            {
 135                foreach (KeyValuePair<string, IEnumerable<string>> header in source)
 136                {
 137                    if (string.Equals(header.Key, "Set-Cookie", StringComparison.OrdinalIgnoreCase))
 138                    {
 139                        cookies.AddRange(header.Value);
 140                        continue;
 141                    }
 142
 143                    foreach (string value in header.Value)
 144                        headers[header.Key] = headers.TryGetValue(header.Key, out string? existing)
 145                            ? $"{existing},{value}"
 146                            : value;
 147                }
 148            }
 149        }
 150
 1151        private ApiGatewayV2Router(RouteScopeBuilder routes, ApiGatewayV2RouterConfig config) : base(routes, config)
 1152        {
 1153        }
 154        #endregion
 155
 156        /// <summary>
 157        /// Creates a strongly typed builder for <see cref="ApiGatewayV2Router"/>.
 158        /// </summary>
 159        /// <returns>A builder that can register handlers, value parsers, and router configuration.</returns>
 160        /// <example>
 161        /// <code>
 162        /// RouterBuilder&lt;ApiGatewayV2Router, ApiGatewayV2RouterConfig&gt; builder = ApiGatewayV2Router.CreateBuilder
 163        /// </code>
 164        /// </example>
 1165        public static RouterBuilder<ApiGatewayV2Router, ApiGatewayV2RouterConfig> CreateBuilder() => new(static (routes,
 166
 167        /// <summary>
 168        /// Routes an API Gateway HTTP API or Lambda Function URL payload-format-2.0 request and returns the correspondi
 169        /// </summary>
 170        /// <param name="request">The API Gateway v2 request event.</param>
 171        /// <param name="services">The service provider exposed to handlers through <see cref="RequestContext.Services"/
 172        /// <param name="context">
 173        /// The Lambda invocation context used to derive the cancellation deadline from <see cref="ILambdaContext.Remain
 174        /// </param>
 175        /// <returns>The API Gateway v2 proxy response generated by NanoRoute.</returns>
 176        /// <exception cref="ArgumentNullException">
 177        /// Thrown when <paramref name="request"/>, <paramref name="services"/>, or <paramref name="context"/> is
 178        /// <see langword="null"/>.
 179        /// </exception>
 180        /// <exception cref="InvalidOperationException">Thrown when the request uses an unsupported HTTP method.</except
 181        /// <exception cref="InvalidOperationException">Thrown when the API Gateway request does not contain a recogniza
 182        /// <exception cref="HttpRequestException">
 183        /// Thrown when no handler matches the request path or a matched handler signals an HTTP failure that is not
 184        /// translated by middleware.
 185        /// </exception>
 186        /// <example>
 187        /// <code>
 188        /// APIGatewayHttpApiV2ProxyResponse response = await router.Route(request, services, context);
 189        /// </code>
 190        /// </example>
 191        public async Task<APIGatewayHttpApiV2ProxyResponse> Route(APIGatewayHttpApiV2ProxyRequest request, IServiceProvi
 192        {
 193            ArgumentNullException.ThrowIfNull(request);
 194            ArgumentNullException.ThrowIfNull(services);
 195            ArgumentNullException.ThrowIfNull(context);
 196
 197            TimeSpan cancellationDelay = context.RemainingTime - Config.LambdaTimeoutBuffer;
 198            if (cancellationDelay <= TimeSpan.Zero)
 199                return Timeout();
 200
 201            using CancellationTokenSource cts = new();
 202            cts.CancelAfter(cancellationDelay);
 203
 204            using HttpRequestMessage requestMessage = CreateRequestMessage(request);
 205
 206            try
 207            {
 208                using HttpResponseMessage responseMessage = await Route(requestMessage, services, cts.Token).ConfigureAw
 209
 210                return await CreateResponse(responseMessage).ConfigureAwait(false);
 211            }
 212            catch (OperationCanceledException)
 213            {
 214                return Timeout();
 215            }
 216
 217            APIGatewayHttpApiV2ProxyResponse Timeout() => new()
 218            {
 219                StatusCode = (int) HttpStatusCode.GatewayTimeout,
 220                Body = JsonSerializer.Serialize
 221                (
 222                    new ErrorDetails
 223                    {
 224                        Status = HttpStatusCode.GatewayTimeout,
 225                        Title = "Gateway Timeout",
 226                        TraceId = request.RequestContext.RequestId
 227                    },
 228                    ErrorDetails.JsonTypeInfo
 229                ),
 230                Headers = new Dictionary<string, string>
 231                {
 232                    ["Content-Type"] = "application/json"
 233                }
 234            };
 235        }
 236    }
 237}