using System.Diagnostics; using System.Globalization; using System.Net; using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; var builder = WebApplication.CreateBuilder(args); var settings = PlantSettings.Load(builder.Configuration); builder.WebHost.ConfigureKestrel(options => options.Limits.MaxRequestBodySize = 4096); builder.Services.ConfigureHttpJsonOptions(options => { options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict; options.SerializerOptions.AllowDuplicateProperties = false; options.SerializerOptions.PropertyNameCaseInsensitive = false; }); builder.Services.AddSingleton(settings); builder.Services.AddSingleton(CallerRegistry.Load(builder.Configuration)); builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(); builder.Services.AddSingleton(); var app = builder.Build(); app.MapGet("/healthz", () => Results.Ok(new { status = "ok", catalog = "offline-fixture" })); app.MapPost("/v1/plants/find", FindPlants); app.Run(); static async Task FindPlants( HttpContext context, PlantSettings settings, CallerRegistry callers, TrafficGate gate, FixtureCatalog catalog, IOptions jsonOptions, ILogger logger) { var traceId = Activity.Current?.TraceId.ToString() ?? context.TraceIdentifier; context.Response.Headers["X-Request-Id"] = traceId; context.Response.Headers.CacheControl = "no-store"; using var scope = logger.BeginScope(new Dictionary { ["RequestId"] = traceId }); var remoteAddress = context.Connection.RemoteIpAddress; var loopback = remoteAddress is not null && IPAddress.IsLoopback( remoteAddress.IsIPv4MappedToIPv6 ? remoteAddress.MapToIPv4() : remoteAddress); if (!context.Request.IsHttps && !loopback && !settings.AllowRemoteHttp) { return Problem(403, "https_required", "HTTPS is required outside the local review."); } var subject = callers.Authenticate(context.Request.Headers); if (subject is null) { context.Response.Headers.WWWAuthenticate = "PlantFinderKey"; return Problem(401, "unauthorized", "A valid Plant Finder connection key is required."); } var key = context.Request.Headers["Idempotency-Key"]; if (key.Count != 1 || !TrafficGate.IsValidKey(key[0])) { return Problem(400, "invalid_idempotency_key", "Provide one valid Idempotency-Key header."); } if (!MediaTypeHeaderValue.TryParse(context.Request.ContentType, out var contentType) || !string.Equals(contentType.MediaType.Value, "application/json", StringComparison.OrdinalIgnoreCase) || (contentType.Charset.HasValue && !string.Equals(contentType.Charset.Value?.Trim('"'), "utf-8", StringComparison.OrdinalIgnoreCase))) { return Problem(415, "unsupported_media_type", "Send an application/json request body encoded in UTF-8."); } FindPlantsRequest? input; try { input = await JsonSerializer.DeserializeAsync( context.Request.Body, jsonOptions.Value.SerializerOptions, context.RequestAborted); } catch (JsonException) { return Problem(400, "invalid_request", "Send a JSON object containing only documented fields and types."); } catch (BadHttpRequestException error) when (error.StatusCode == StatusCodes.Status413PayloadTooLarge) { return Problem(413, "payload_too_large", "The JSON body may contain at most 4096 bytes."); } var validationMessage = input is null ? "Send a JSON object." : input.ValidationMessage(); if (validationMessage is not null) { return Problem(400, "invalid_request", validationMessage); } var admission = gate.Admit(subject, key[0]!, input!); if (admission.Denial is { } denial) { if (denial.RetryAfterSeconds is { } seconds) { context.Response.Headers.RetryAfter = seconds.ToString(CultureInfo.InvariantCulture); } return Problem(denial.Status, denial.Code, denial.Message); } var entry = admission.Entry!; if (!admission.OwnsReservation) { context.Response.Headers["Idempotency-Replayed"] = "true"; var replay = await entry.Result.WaitAsync(context.RequestAborted); logger.LogInformation("Idempotent outcome replayed ({Outcome})", replay.Response?.Kind ?? "catalog_unavailable"); return ToHttp(replay); } // Reservations count even when the catalog fails. Finish a reserved lookup if its caller disconnects. CatalogOutcome outcome; logger.LogInformation("Catalog lookup started"); try { var response = catalog.Find(input!); outcome = new CatalogOutcome(response); logger.LogInformation("Catalog lookup finished ({Outcome}, {MatchCount})", response.Kind, response.Matches.Length); } catch (Exception error) { outcome = new CatalogOutcome(null); logger.LogError("Catalog lookup failed closed ({FailureType})", error.GetType().Name); } entry.Complete(outcome); return ToHttp(outcome); IResult ToHttp(CatalogOutcome outcome) => outcome.Response is { } response ? Results.Ok(response) : Problem(503, "catalog_unavailable", "The catalog lookup failed. No recommendation was made."); IResult Problem(int status, string code, string detail) { logger.LogInformation("Plant Finder returned {Status} ({Code})", status, code); return Results.Problem( statusCode: status, title: code.Replace('_', ' '), detail: detail, extensions: new Dictionary { ["code"] = code, ["traceId"] = traceId }); } }