Path: redb-route/redb.Route.Http/HttpProducer.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/HttpProducer.cs
----
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using SysHttpMethod = System.Net.Http.HttpMethod;
namespace redb.Route.Http;
///
/// HTTP producer. Sends HTTP requests using .
/// Supports all HTTP methods, header bridging, Basic/Bearer authentication,
/// configurable timeouts, and automatic error handling.
///
public class HttpProducer : ConnectableProducer
{
private readonly HttpEndpoint _endpoint;
private readonly HttpEndpointOptions _options;
private HttpClient? _httpClient;
private HttpClientHandler? _handler;
private readonly redb.Route.Abstractions.IHeaderFilterStrategy _headerFilter;
/// Creates an HTTP producer.
public HttpProducer(HttpEndpoint endpoint, HttpEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_headerFilter = endpoint.HeaderFilterStrategy(EndpointRole.Producer);
}
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
// The name is logged as "producer started", so it goes through the same redaction as every
// other URI at a logging boundary: [Sensitive] option names cover the query parameters, and
// Sanitize additionally masks a userinfo password, which lives in the authority and therefore
// cannot be reached by any attribute.
protected override string ProducerName => $"http:{EndpointUri.Sanitize(_endpoint.BuildProducerUrl())}";
/// The logged producer name, so a test can pin the redaction.
internal string DiagnosticName => ProducerName;
///
protected override Task ConnectAsync(CancellationToken ct)
{
_handler = new HttpClientHandler
{
AllowAutoRedirect = _options.FollowRedirects,
MaxAutomaticRedirections = _options.MaxRedirects
};
_httpClient = new HttpClient(_handler)
{
Timeout = _options.Timeout > 0
? TimeSpan.FromMilliseconds(_options.Timeout)
: System.Threading.Timeout.InfiniteTimeSpan
};
// Set default auth header
ConfigureAuthentication(_httpClient);
return Task.CompletedTask;
}
///
protected override Task DisconnectAsync(CancellationToken ct)
{
_httpClient?.Dispose();
_httpClient = null;
_handler?.Dispose();
_handler = null;
return Task.CompletedTask;
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
var url = ResolveUrl(exchange);
var method = ResolveMethod(exchange);
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"HTTP {method.Method}", ActivityKind.Client,
"http.method", method.Method,
_endpoint.Uri.NormalizedKey,
destination: url);
using var request = new HttpRequestMessage(method, url);
// Set body for methods that support it
if (HasBody(method))
{
SetRequestBody(request, exchange);
}
// Exchange headers to request headers, as the header filter strategy lets them (skipRequestHeaders: none).
if (!_options.SkipRequestHeaders)
{
BridgeExchangeHeaders(request, exchange);
}
// preserveHostHeader=true: the reverse-proxy case - the target sees the ORIGINAL
// request's Host. Off (default): the target sees its own host, like any plain client.
// Host is excluded from the header bridge, so this explicit set is the only path.
// Independent of skipRequestHeaders, like in camel-http.
if (_options.PreserveHostHeader
&& exchange.In.Headers.TryGetValue("Host", out var originalHost)
&& originalHost?.ToString() is { Length: > 0 } hostValue)
{
request.Headers.TryAddWithoutValidation("Host", hostValue);
}
// Set per-request auth if using dynamic token
ConfigurePerRequestAuth(request, exchange);
// The context of this send, over a traceparent the header bridge copied from the incoming request: that one
// names the previous hop, and HttpClient does not overwrite a trace header already on the request.
RouteTelemetryExtensions.InjectTraceContext(activity, request, static (r, name, value) =>
{
r.Headers.Remove(name);
r.Headers.TryAddWithoutValidation(name, value);
});
HttpResponseMessage response;
try
{
// Send request
response = await _httpClient!.SendAsync(request, ct).ConfigureAwait(false);
}
catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct))
{
Logger?.LogError(ex, "HTTP {Method} to {Url} failed. Timeout={Timeout}ms, auth={Auth}",
method.Method, EndpointUri.Sanitize(url), _options.Timeout, _options.AuthScheme);
activity.RecordFailure(ex);
// The producer owns its deadline: name the timeout as one here, with the exact method and URL,
// so a direct (non-EIP) caller of Process is on the same contract too. The EIP layer
// (RouteCancellation.Normalize) would name it anyway; a real cancellation is untouched. The
// message carries only the sanitized URL — never the body or credentials (BR-4).
if (RouteCancellation.IsOwnedTimeout(ex, ct))
throw new TimeoutException(
$"HTTP {method.Method} {EndpointUri.Sanitize(url)} timed out after {_options.Timeout} ms.", ex);
throw;
}
if (activity is not null)
{
if (activity.IsAllDataRequested)
activity.SetTag("http.response.status_code", (int)response.StatusCode);
// A client span is an error for any 4xx or 5xx: the call did not do what it asked.
if ((int)response.StatusCode >= 400)
activity.SetStatus(ActivityStatusCode.Error);
}
// When StreamResponse is enabled, the response stream is set as exchange body.
// Disposing the HttpResponseMessage would close that stream, so we skip Dispose()
// and let Exchange.DisposeAsync() close the body stream instead (equivalent effect).
if (_options.StreamResponse)
{
await MapResponse(exchange, response, ct).ConfigureAwait(false);
if (_options.ThrowOnError && !response.IsSuccessStatusCode)
{
response.Dispose();
var body = exchange.HasOut ? exchange.Out!.Body?.ToString() : null;
throw new HttpRequestException(
$"HTTP {(int)response.StatusCode} {response.ReasonPhrase}: {body}",
inner: null,
statusCode: response.StatusCode);
}
}
else
{
using (response)
{
// Map response back to exchange
await MapResponse(exchange, response, ct).ConfigureAwait(false);
// Throw on error if configured
if (_options.ThrowOnError && !response.IsSuccessStatusCode)
{
var body = exchange.HasOut ? exchange.Out!.Body?.ToString() : null;
throw new HttpRequestException(
$"HTTP {(int)response.StatusCode} {response.ReasonPhrase}: {body}",
inner: null,
statusCode: response.StatusCode);
}
}
}
}
private string ResolveUrl(IExchange exchange)
{
// Base URL from endpoint — ${...} expressions resolved per message
var baseUrl = _options.ResolveOption(_endpoint.BuildProducerUrl(), exchange)
?? _endpoint.BuildProducerUrl();
// Resolve {name} named parameters from .Param() bindings
baseUrl = ResolveNamedParams(baseUrl, exchange);
// Check for query string parameters in exchange headers (a control header: skipControlHeaders ignores it)
if (!_options.SkipControlHeaders && exchange.In.Headers.TryGetValue(HttpHeaders.Query, out var query) && query is string qs && qs.Length > 0)
{
var separator = baseUrl.Contains('?') ? "&" : "?";
return $"{baseUrl}{separator}{qs}";
}
return baseUrl;
}
private string ResolveNamedParams(string url, IExchange exchange)
{
var parameters = _options.ExplicitParameters;
if (parameters.Count == 0) return url;
foreach (var (name, valueTemplate) in parameters)
{
var placeholder = $"{{{name}}}";
if (!url.Contains(placeholder, StringComparison.Ordinal)) continue;
// Resolve ${...} expressions inside the param value first
var resolved = valueTemplate.Contains("${")
? (_options.ResolveOption(valueTemplate, exchange) ?? valueTemplate)
: valueTemplate;
url = url.Replace(placeholder, Uri.EscapeDataString(resolved), StringComparison.Ordinal);
}
return url;
}
private SysHttpMethod ResolveMethod(IExchange exchange)
{
// Allow override from exchange header (a control header: skipControlHeaders ignores it)
if (!_options.SkipControlHeaders && exchange.In.Headers.TryGetValue(HttpHeaders.Method, out var hm) && hm is string methodStr)
{
return new SysHttpMethod(methodStr.ToUpperInvariant());
}
return _options.Method switch
{
HttpMethod.GET => SysHttpMethod.Get,
HttpMethod.POST => SysHttpMethod.Post,
HttpMethod.PUT => SysHttpMethod.Put,
HttpMethod.DELETE => SysHttpMethod.Delete,
HttpMethod.PATCH => SysHttpMethod.Patch,
HttpMethod.HEAD => SysHttpMethod.Head,
HttpMethod.OPTIONS => SysHttpMethod.Options,
_ => SysHttpMethod.Get
};
}
private static bool HasBody(SysHttpMethod method)
{
return method == SysHttpMethod.Post ||
method == SysHttpMethod.Put ||
method == SysHttpMethod.Patch;
}
private void SetRequestBody(HttpRequestMessage request, IExchange exchange)
{
var body = exchange.HasOut ? exchange.Out!.Body : exchange.In.Body;
if (body is null) return;
HttpContent content;
if (body is byte[] bytes)
{
content = new ByteArrayContent(bytes);
}
else if (body is Stream stream)
{
content = new StreamContent(stream);
}
else
{
var text = BodyText.Of(body);
content = new StringContent(text, Encoding.UTF8);
}
// Set content type
var contentType = exchange.In.ContentType ?? _options.ContentType;
if (exchange.In.Headers.TryGetValue(HttpHeaders.ContentType, out var ct) && ct is string ctStr)
{
contentType = ctStr;
}
if (MediaTypeHeaderValue.TryParse(contentType, out var mediaType))
{
content.Headers.ContentType = mediaType;
}
request.Content = content;
}
private void BridgeExchangeHeaders(HttpRequestMessage request, IExchange exchange)
{
foreach (var (key, value) in exchange.In.Headers)
{
// The protocol fields are the transport's, whatever the strategy says.
if (HttpHeaders.ProtocolHeaders.Contains(key)) continue;
if (_headerFilter.FilterOutgoing(key, value, exchange)) continue;
var strValue = value?.ToString() ?? string.Empty;
// Try to add as request header (some headers may already be set)
if (!request.Headers.TryAddWithoutValidation(key, strValue))
{
// Try content headers if request has content
request.Content?.Headers.TryAddWithoutValidation(key, strValue);
}
}
}
private void ConfigureAuthentication(HttpClient client)
{
switch (_options.AuthScheme)
{
case HttpAuthScheme.Basic:
var credentials = Convert.ToBase64String(
Encoding.ASCII.GetBytes($"{_options.Username}:{_options.Password}"));
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", credentials);
break;
case HttpAuthScheme.Bearer when _options.AuthToken.HasValue && !_options.AuthToken.Value.IsDynamic:
// Static token — set once on client
var token = _options.AuthToken.Value.Resolve(null!);
if (!string.IsNullOrEmpty(token))
{
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
}
break;
}
}
private void ConfigurePerRequestAuth(HttpRequestMessage request, IExchange exchange)
{
// Dynamic bearer token — resolve per-request
if (_options.AuthScheme == HttpAuthScheme.Bearer &&
_options.AuthToken.HasValue && _options.AuthToken.Value.IsDynamic)
{
var token = _options.AuthToken.Value.Resolve(exchange);
if (!string.IsNullOrEmpty(token))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
}
}
private async Task MapResponse(IExchange exchange, HttpResponseMessage response, CancellationToken ct)
{
// Read response body
object? responseBody;
if (_options.StreamResponse)
{
responseBody = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
}
else
{
var bytes = await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
responseBody = bytes.Length > 0 ? bytes : null;
}
// Set Out message with response body
var outMessage = new Message(responseBody);
exchange.Out = outMessage;
// Set standard response headers
outMessage.Headers[HttpHeaders.StatusCode] = (int)response.StatusCode;
outMessage.Headers[HttpHeaders.StatusText] = response.ReasonPhrase ?? string.Empty;
outMessage.Headers[HttpHeaders.Url] = response.RequestMessage?.RequestUri?.ToString() ?? string.Empty;
// Response headers to the exchange, as the header filter strategy lets them (skipResponseHeaders: none)
if (!_options.SkipResponseHeaders)
{
foreach (var header in response.Headers)
{
var value = string.Join(", ", header.Value);
if (_headerFilter.FilterIncoming(header.Key, value, exchange)) continue;
outMessage.Headers[header.Key] = value;
}
if (response.Content.Headers.ContentType is not null)
{
outMessage.Headers[HttpHeaders.ContentType] = response.Content.Headers.ContentType.ToString();
outMessage.ContentType = response.Content.Headers.ContentType.MediaType;
}
if (response.Content.Headers.ContentLength is not null)
{
outMessage.Headers[HttpHeaders.ContentLength] = response.Content.Headers.ContentLength.Value;
}
}
}
}