| | | 1 | | /******************************************************************************** |
| | | 2 | | * ApiGatewayV2Router.cs * |
| | | 3 | | * * |
| | | 4 | | * Author: Denes Solti * |
| | | 5 | | ********************************************************************************/ |
| | | 6 | | using System; |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using System.Net; |
| | | 9 | | using System.Net.Http; |
| | | 10 | | using System.Net.Http.Headers; |
| | | 11 | | using System.Text.Json; |
| | | 12 | | using System.Threading; |
| | | 13 | | using System.Threading.Tasks; |
| | | 14 | | |
| | | 15 | | using Amazon.Lambda.APIGatewayEvents; |
| | | 16 | | using Amazon.Lambda.Core; |
| | | 17 | | |
| | | 18 | | namespace 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, _) => 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) |
| | 1 | 39 | | { |
| | 1 | 40 | | if (!Uri.TryCreate($"{Config.RequestScheme}://{Config.RequestDomain ?? request.RequestContext.DomainName}", |
| | 1 | 41 | | throw new InvalidOperationException(Resources.ERR_UNKNOWN_URI); |
| | | 42 | | |
| | 1 | 43 | | UriBuilder uriBuilder = new(baseUri) |
| | 1 | 44 | | { |
| | 1 | 45 | | Path = request.RawPath is { Length: > 0 } path ? path : "/", |
| | 1 | 46 | | Query = request.RawQueryString is { Length: > 0 } query ? query : null |
| | 1 | 47 | | }; |
| | | 48 | | |
| | 1 | 49 | | HttpRequestMessage requestMessage = new |
| | 1 | 50 | | ( |
| | 1 | 51 | | HttpMethod.For(request.RequestContext.Http.Method), |
| | 1 | 52 | | uriBuilder.Uri |
| | 1 | 53 | | ) |
| | 1 | 54 | | { |
| | 1 | 55 | | Content = request switch |
| | 1 | 56 | | { |
| | 1 | 57 | | { IsBase64Encoded: false } and { Body.Length: > 0 } => new StringContent(request.Body), |
| | 1 | 58 | | { IsBase64Encoded: true } and { Body.Length: > 0 } => new StreamContent |
| | 1 | 59 | | ( |
| | 1 | 60 | | new Base64BodyReaderStream(request.Body) |
| | 1 | 61 | | ), |
| | 1 | 62 | | _ => null |
| | 1 | 63 | | } |
| | 1 | 64 | | }; |
| | | 65 | | |
| | 1 | 66 | | requestMessage.Content?.Headers.Clear(); |
| | | 67 | | |
| | 1 | 68 | | HttpHeaders |
| | 1 | 69 | | requestHeaders = requestMessage.Headers, |
| | 1 | 70 | | contentHeaders = requestMessage.Content?.Headers!; |
| | | 71 | | |
| | 1 | 72 | | foreach (KeyValuePair<string, string> header in request.Headers) |
| | 1 | 73 | | { |
| | 1 | 74 | | HttpHeaders headers = contentHeaders is not null && HttpRequestMessage.ContentHeaders.Contains(header.Ke |
| | 1 | 75 | | ? contentHeaders |
| | 1 | 76 | | : requestHeaders; |
| | | 77 | | |
| | 1 | 78 | | headers.TryAddWithoutValidation(header.Key, header.Value); |
| | 1 | 79 | | } |
| | | 80 | | |
| | 1 | 81 | | requestMessage.OriginalRequest = request; |
| | 1 | 82 | | requestMessage.TraceId = request.RequestContext.RequestId; |
| | | 83 | | |
| | 1 | 84 | | return requestMessage; |
| | 1 | 85 | | } |
| | | 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 | | |
| | 1 | 151 | | private ApiGatewayV2Router(RouteScopeBuilder routes, ApiGatewayV2RouterConfig config) : base(routes, config) |
| | 1 | 152 | | { |
| | 1 | 153 | | } |
| | | 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<ApiGatewayV2Router, ApiGatewayV2RouterConfig> builder = ApiGatewayV2Router.CreateBuilder |
| | | 163 | | /// </code> |
| | | 164 | | /// </example> |
| | 1 | 165 | | 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 | | } |