Path: redb-route/redb.Route.Http/HttpConsumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Http/HttpConsumer.cs
----
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using System.Diagnostics;
using System.Linq;
namespace redb.Route.Http;
///
/// HTTP consumer. Uses SharedHttpServerManager to register routes on a shared
/// Kestrel server instance per (host, port). Multiple consumers can serve
/// different routes on the same port.
/// Supports configurable bind address, CORS, allowed methods, HTTPS/TLS,
/// request body streaming, and InOut exchange patterns for synchronous responses.
///
public class HttpConsumer : IConsumer
{
private readonly HttpEndpoint _endpoint;
public IEndpoint Endpoint => _endpoint;
private readonly IProcessor _processor;
private readonly HttpEndpointOptions _options;
private readonly redb.Route.Abstractions.IHeaderFilterStrategy _headerFilter;
private readonly SharedHttpServerManager _serverManager;
private ILogger? _logger;
private RouteRegistration? _registration;
private long _processedCount;
// Unregistering the route only stops NEW requests from reaching it. When another route still
// holds the port, the listener stays up and nobody waits for the ones already in the pipeline,
// so a deploy that removes one route cuts its requests mid-flight. Same guard every broker
// consumer uses.
private readonly InflightDrainGuard _drain = new();
/// Creates an HTTP consumer.
public HttpConsumer(HttpEndpoint endpoint, IProcessor processor, HttpEndpointOptions options, SharedHttpServerManager serverManager)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_options = options ?? throw new ArgumentNullException(nameof(options));
_serverManager = serverManager ?? throw new ArgumentNullException(nameof(serverManager));
_logger = (endpoint.Component as ComponentBase)?.Logger;
_headerFilter = endpoint.HeaderFilterStrategy(EndpointRole.Consumer);
}
/// The inbound check (inboundAuth); null when the endpoint accepts every caller.
internal HttpInboundAuthenticator? Authenticator { get; init; }
// Each request header exactly as received (the object put on the exchange), so the response can tell a value the
// client sent from one the route wrote under the same name.
private const string RequestHeaderValuesKey = "redbHttp.RequestHeaderValues";
/// Number of requests successfully processed.
public long ProcessedCount => Interlocked.Read(ref _processedCount);
/// The base URL the server is listening on. Available after Start().
public string? BaseUrl { get; private set; }
///
public async Task Start(CancellationToken ct = default)
{
_drain.Start(ct);
var host = _options.Host;
var port = _options.Port;
var path = _endpoint.ConsumerPath;
var ssl = _options.Ssl;
// Translate the per-endpoint CORS knobs into a per-route CORS policy. The shared server
// installs ONE CORS dispatch middleware per (host, port) which selects the policy by
// the matched route, so different endpoints on the same port may declare different
// policies (resolves the legacy "first-wins" gotcha; see SharedHttpServerManager).
RouteCorsOptions? corsOptions = null;
if (_options.Cors)
{
// Validation in HttpEndpointOptions.Validate guarantees that at least one of
// CorsOrigins / CorsOriginsResolver is supplied here -- no implicit "*" fallback.
corsOptions = new RouteCorsOptions(
AllowedOrigins: _options.CorsOrigins,
AllowedMethods: _options.Methods,
AllowCredentials: _options.CorsCredentials,
OriginsResolver: _options.CorsOriginsResolver);
}
_registration = _serverManager.RegisterRoute(
host, port, path, _options.Methods, HandleRequest,
ssl, _options.SslCertPath, _options.SslCertPassword,
corsOptions, _options.MaxRequestBodySize, _options.Protocol,
concurrencyLimit: ConcurrencyLimitOptions.FromEndpoint(
_options.MaxConcurrentRequests, _options.RequestQueueLimit,
_options.RejectStatusCode, _options.RetryAfterSeconds,
onRejected: _endpoint.RecordRejected));
try
{
await _serverManager.EnsureStarted(host, port, ct).ConfigureAwait(false);
}
catch
{
// The listener did not come up (a port still taken): the route leaves it, so a later Start registers
// once and does not find a stale registration of its own.
await Stop(CancellationToken.None).ConfigureAwait(false);
throw;
}
BaseUrl = _serverManager.GetBaseUrl(host, port);
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("HTTP consumer started: {Url}", BaseUrl + path);
}
///
public async Task Stop(CancellationToken ct = default)
{
if (_registration is not null)
{
var host = _options.Host;
var port = _options.Port;
_serverManager.UnregisterRoute(_registration);
_registration = null;
// New requests can no longer reach this route; the ones inside it still can finish.
await _drain.DrainAsync(ct, _logger, $"http://{host}:{port}{_endpoint.ConsumerPath}").ConfigureAwait(false);
await _serverManager.StopIfEmpty(host, port, ct).ConfigureAwait(false);
}
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("HTTP consumer stopped: {Host}:{Port}", _options.Host, _options.Port);
}
private async Task HandleRequest(HttpContext httpContext)
{
// The server span of the request, as every inbound transport opens one: the caller's trace goes on from
// traceparent, or from the host's own span when ASP.NET Core instrumentation opened it, and the route's spans
// sit under this one. It covers the whole request, the refused ones too.
using var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{httpContext.Request.Method} {_endpoint.ConsumerPath}", ActivityKind.Server,
"http.method", httpContext.Request.Method, _endpoint.Uri.NormalizedKey,
httpContext.Request.Headers, static (headers, name) => headers.TryGetValue(name, out var value) ? value.ToString() : null,
InboundParent.HostRequest);
try
{
await HandleTracedRequest(httpContext, span.Activity).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !httpContext.RequestAborted.IsCancellationRequested)
{
span.Activity.RecordFailure(ex);
throw;
}
finally
{
if (span.Activity is { } activity)
{
var status = httpContext.Response.StatusCode;
if (activity.IsAllDataRequested)
activity.SetTag("http.response.status_code", status);
// A server span is an error for a 5xx only: a 4xx is the caller's mistake, answered correctly.
if (status >= 500 && activity.Status != ActivityStatusCode.Error)
activity.SetStatus(ActivityStatusCode.Error);
}
}
}
private async Task HandleTracedRequest(HttpContext httpContext, Activity? span)
{
// The inbound check comes first: a refused request is answered with 401 and no exchange is built for it.
System.Security.Claims.ClaimsPrincipal? authenticated = null;
if (Authenticator is not null)
{
authenticated = await Authenticator.AuthenticateAsync(httpContext).ConfigureAwait(false);
if (authenticated is null)
return;
}
// Build exchange from HTTP request
var exchange = await BuildExchange(httpContext).ConfigureAwait(false);
if (authenticated is not null)
{
// The credentials stop at the check: a route that logs, forwards or echoes its headers must not carry them on.
exchange.In.Headers.Remove(HeaderNames.Authorization);
if (exchange.Properties.TryGetValue("redbHttp.RequestHeaderNames", out var names) && names is ISet requestHeaders)
requestHeaders.Remove(HeaderNames.Authorization);
ExchangePrincipal.Set(exchange, authenticated);
}
// Set exchange pattern
exchange.Pattern = _options.InOut ? ExchangePattern.InOut : ExchangePattern.InOnly;
_drain.Increment();
try
{
// Process through the route pipeline
try
{
await _processor.Process(exchange, httpContext.RequestAborted).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !httpContext.RequestAborted.IsCancellationRequested)
{
_logger?.LogError(ex, "HTTP request processing failed: {Method} {Path}",
httpContext.Request.Method, httpContext.Request.Path);
exchange.Exception ??= ex;
}
// Check for exceptions
if (exchange.Exception is not null && !exchange.ExceptionHandled)
{
// The exception's own text goes to the log, never to the caller: it is written by
// whoever threw it and routinely carries a file path, a connection string or the name
// of an inner service (BR-4). The caller gets the exchange id to quote instead — the
// same id the log line above carries, so an operator can find the real reason.
_logger?.LogError(exchange.Exception,
"Route failed for {Method} {Path} (exchange {ExchangeId})",
httpContext.Request.Method, httpContext.Request.Path, exchange.ExchangeId);
span.RecordFailure(exchange.Exception);
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
httpContext.Response.ContentType = "text/plain; charset=utf-8";
await httpContext.Response.WriteAsync(
$"An unexpected error occurred while processing the request (ref: {exchange.ExchangeId}).",
httpContext.RequestAborted).ConfigureAwait(false);
return;
}
// Build HTTP response from exchange
try
{
await WriteResponse(httpContext, exchange).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger?.LogError(ex,
"HTTP response writing failed: {Method} {Path}, route={RouteId}, statusStarted={Started}",
httpContext.Request.Method, httpContext.Request.Path, exchange.RouteId, httpContext.Response.HasStarted);
throw;
}
Interlocked.Increment(ref _processedCount);
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
_drain.Decrement();
}
}
private async Task BuildExchange(HttpContext httpContext)
{
var request = httpContext.Request;
// Read request body
object? body = null;
if (request.ContentLength > 0 || request.ContentType is not null)
{
if (_options.StreamRequest)
{
// Stream passthrough — body stays as HttpRequest.Body stream.
// Exchange.DisposeAsync does NOT own this stream (Kestrel does),
// but the stream remains valid until WriteResponse completes.
body = request.Body;
}
else
{
using var ms = new MemoryStream();
await request.Body.CopyToAsync(ms, httpContext.RequestAborted).ConfigureAwait(false);
body = ms.ToArray();
}
}
var message = new Message(body);
// Set ContentType from HTTP request
if (!string.IsNullOrEmpty(request.ContentType))
message.ContentType = request.ContentType;
// Map HTTP request headers to exchange headers
message.Headers[HttpHeaders.Method] = request.Method;
message.Headers[HttpHeaders.Path] = request.Path.Value ?? "/";
message.Headers[HttpHeaders.Url] = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
message.Headers[HttpHeaders.Port] = _options.Port;
if (request.QueryString.HasValue)
{
message.Headers[HttpHeaders.Query] = request.QueryString.Value?.TrimStart('?') ?? string.Empty;
// Extract individual query parameters as redbHttp.QueryParam.*
foreach (var qp in request.Query)
{
message.Headers[$"{HttpHeaders.QueryParamPrefix}{qp.Key}"] = qp.Value.Count switch
{
0 => string.Empty,
1 => (object)qp.Value[0]!,
_ => string.Join(",", qp.Value!)
};
}
}
// Extract route template parameters as redbHttp.RouteParam.*
if (httpContext.Items.TryGetValue("__redbRouteValues", out var rvObj) && rvObj is RouteValueDictionary routeValues)
{
foreach (var (key, value) in routeValues)
{
if (value is not null)
message.Headers[$"{HttpHeaders.RouteParamPrefix}{key}"] = value;
}
}
if (httpContext.Connection.RemoteIpAddress is not null)
{
message.Headers[HttpHeaders.RemoteAddress] = httpContext.Connection.RemoteIpAddress.ToString();
}
// The exchange the header filter strategy is asked about; the headers below go into its message.
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
// Copy all HTTP headers to exchange, and remember which ones came from
// the request so they are not accidentally echoed in the response.
var requestHeaderNames = new HashSet(StringComparer.OrdinalIgnoreCase);
var requestHeaderValues = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var header in request.Headers)
{
// Skip pseudo-headers
if (header.Key.StartsWith(':')) continue;
// Transport-owned headers are set above from the connection itself, and processors trust
// them: redbHttp.RemoteAddress drives rate limiting, brute-force lockout and audit. This copy
// runs AFTER those assignments, so without the guard a caller sending a header literally
// named "redbHttp.RemoteAddress" (a valid HTTP token) would overwrite the socket address and
// pick its own throttle bucket.
if (HttpHeaders.IsRedbHeader(header.Key)) continue;
// A response field in a request is dropped here, at the transport: the route never sees a client's value
// under a name it may later write for the response (Set-Cookie, Location, WWW-Authenticate, ...).
if (HttpHeaders.ResponseOnlyHeaders.Contains(header.Key)) continue;
var received = header.Value.Count switch
{
0 => string.Empty,
1 => (object)header.Value[0]!,
_ => string.Join(", ", header.Value!)
};
if (_headerFilter.FilterIncoming(header.Key, received, exchange)) continue;
requestHeaderNames.Add(header.Key);
message.Headers[header.Key] = received;
requestHeaderValues[header.Key] = received;
}
exchange.Properties["redbHttp.RequestHeaderNames"] = requestHeaderNames;
exchange.Properties[RequestHeaderValuesKey] = requestHeaderValues;
ExchangePrincipal.Set(exchange, SharedHttpServerManager.GetResolvedPrincipal(httpContext));
return exchange;
}
private async Task WriteResponse(Microsoft.AspNetCore.Http.HttpContext httpContext, IExchange exchange)
{
// Pick the response message: Out if set, otherwise In (pipeline merges Out→In)
var responseMsg = exchange.HasOut ? exchange.Out! : exchange.In;
// Determine status code: header override > fallback > options default
var statusCode = _options.ResponseCode;
if (responseMsg.Headers.TryGetValue(HttpHeaders.ResponseCode, out var rc))
{
if (rc is int code) statusCode = code;
else if (rc is string codeStr && int.TryParse(codeStr, out var parsed)) statusCode = parsed;
}
else if (responseMsg.Headers.TryGetValue("status.code", out var sc))
{
// Fallback: controller dispatchers set "status.code" for transport-agnostic status
if (sc is int code2) statusCode = code2;
else if (sc is string scStr && int.TryParse(scStr, out var parsed2)) statusCode = parsed2;
}
httpContext.Response.StatusCode = statusCode;
// Set Content-Type
var responseContentType = responseMsg.ContentType ?? _options.ContentType;
if (responseMsg.Headers.TryGetValue(HttpHeaders.ResponseContentType, out var rct) && rct is string rctStr)
{
responseContentType = rctStr;
}
// InOut pattern — propagate headers and (optionally) body.
// NOTE: headers MUST be copied even when Body is null. Otherwise body-less
// responses (HTTP 302 redirects, 204 No Content, Set-Cookie-only replies)
// silently drop Location / Set-Cookie / etc. See repo memory
// 'http-redirect-headers-bug' for the symptom history.
if (_options.InOut)
{
httpContext.Response.ContentType = responseContentType;
// Copy response headers (always, regardless of body presence).
// When the response message is exchange.In, it still contains the original request headers. Never echo
// those back — but only a value that is still the one the client sent. Matching by name let a client
// suppress a header the route wrote: a request carrying Cache-Control removed the route's no-store.
var requestHeaderValues =
exchange.Properties.TryGetValue(RequestHeaderValuesKey, out var valuesObj)
&& valuesObj is Dictionary received
? received
: null;
foreach (var (key, value) in responseMsg.Headers)
{
if (requestHeaderValues is not null && requestHeaderValues.TryGetValue(key, out var sent)
&& ReferenceEquals(sent, value)) continue;
// The protocol fields and the component's own namespace are the transport's, whatever the strategy says.
if (HttpHeaders.ProtocolHeaders.Contains(key)) continue;
if (HttpHeaders.IsRedbHeader(key)) continue;
if (_headerFilter.FilterOutgoing(key, value, exchange)) continue;
if (value is null) continue;
// Headers like Set-Cookie can carry multiple values. Use StringValues so
// ASP.NET emits one header line per entry instead of stringifying the array.
Microsoft.Extensions.Primitives.StringValues sv = value switch
{
string s => s,
string[] arr => arr,
System.Collections.IEnumerable seq when value is not string =>
seq.Cast