Bundle: redb-route / redb.Route.Http (redb.Route.Http.txt), 25 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Http/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; namespace redb.Route.Http; /// /// Extension methods for registering the HTTP component with dependency injection. /// public static class ServiceCollectionExtensions { /// /// Registers the HTTP and HTTPS components with the route context. /// public static IServiceCollection AddRedbRouteHttp(this IServiceCollection services) => AddRedbRouteHttp(services, null); /// /// Registers the HTTP and HTTPS components with global CORS configuration. /// Example: services.AddRedbRouteHttp(cors => { cors.Enabled = true; cors.Origins = "https://example.com"; }); /// /// The service collection. /// Optional action to configure global CORS defaults for all HTTP consumers. public static IServiceCollection AddRedbRouteHttp(this IServiceCollection services, Action? configureCors) { // Shared server manager — single instance across all route contexts and HTTP-based connectors. services.AddRedbRouteHttpHosting(); services.AddSingleton(sp => { var component = new HttpComponent(); component.ServerManager = sp.GetRequiredService(); configureCors?.Invoke(component.DefaultCors); return component; }); services.AddSingleton(sp => { var component = new HttpsComponent(); component.ServerManager = sp.GetRequiredService(); configureCors?.Invoke(component.DefaultCors); return component; }); // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteContextConfigurator((sp, context) => { context.AddComponent(sp.GetRequiredService()); context.AddComponent(sp.GetRequiredService()); }); return services; } } Path: redb-route/redb.Route.Http/Fluent/HttpDsl.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/Fluent/HttpDsl.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Http; /// /// Fluent API for HTTP endpoints. /// /// .To(Http.Post("api.example.com/users").ContentType("application/xml").Timeout(5000)) /// .To(Http.Get("api.example.com/data").BasicAuth("user", "pass")) /// .From(Http.Listen("/webhook").Port(8080).Cors()) /// /// public static class Http { /// HTTP GET request to the given URL path. public static HttpBuilder Get(string path) => new("http", path, "GET"); /// HTTP POST request to the given URL path. public static HttpBuilder Post(string path) => new("http", path, "POST"); /// HTTP PUT request to the given URL path. public static HttpBuilder Put(string path) => new("http", path, "PUT"); /// HTTP DELETE request to the given URL path. public static HttpBuilder Delete(string path) => new("http", path, "DELETE"); /// HTTP PATCH request to the given URL path. public static HttpBuilder Patch(string path) => new("http", path, "PATCH"); /// HTTP HEAD request to the given URL path. public static HttpBuilder Head(string path) => new("http", path, "HEAD"); /// HTTP consumer — listens for incoming requests on the given route path. public static HttpBuilder Listen(string path) => new("http", path, null); } /// /// Fluent API for HTTPS endpoints. /// /// .To(Https.Post("secure-api.com/submit").BasicAuth("user", "pass")) /// .From(Https.Listen("/secure").Port(8443).SslCert("cert.pfx", "pass")) /// /// public static class Https { /// HTTPS GET request to the given URL path. public static HttpBuilder Get(string path) => new("https", path, "GET"); /// HTTPS POST request to the given URL path. public static HttpBuilder Post(string path) => new("https", path, "POST"); /// HTTPS PUT request to the given URL path. public static HttpBuilder Put(string path) => new("https", path, "PUT"); /// HTTPS DELETE request to the given URL path. public static HttpBuilder Delete(string path) => new("https", path, "DELETE"); /// HTTPS PATCH request to the given URL path. public static HttpBuilder Patch(string path) => new("https", path, "PATCH"); /// HTTPS HEAD request to the given URL path. public static HttpBuilder Head(string path) => new("https", path, "HEAD"); /// HTTPS consumer — listens for incoming requests on the given route path. public static HttpBuilder Listen(string path) => new("https", path, null); } /// /// Fluent builder for HTTP/HTTPS endpoint URIs. /// public sealed class HttpBuilder { private readonly string _scheme; private readonly string _path; private readonly string? _method; // Common private string? _timeout; private string? _contentType; // Producer private bool? _throwOnError; private bool _skipRequestHeaders; private bool _skipControlHeaders; private string? _headerFilterStrategy; private string? _authScheme; private string? _authToken; private string? _username; private string? _password; private string? _connectionFactory; private bool? _followRedirects; private string? _maxRedirects; private bool _skipResponseHeaders; private bool _preserveHostHeader; // Query-string parameters private readonly List<(string Name, string Value)> _queryParams = []; // Host/Port (producer: embedded in URL path; consumer: query params) private string? _host; private string? _port; private string? _methods; private bool _cors; private string? _corsOrigins; private bool _corsCredentials; private string? _maxRequestBodySize; private string? _maxConcurrentRequests; private string? _requestQueueLimit; private string? _rejectStatusCode; private string? _retryAfterSeconds; private string? _protocol; private bool _ssl; private string? _sslCertPath; private string? _sslCertPassword; private string? _responseCode; private bool _inOut; private bool _streamRequest; private bool _streamResponse; internal HttpBuilder(string scheme, string path, string? method) { ArgumentException.ThrowIfNullOrWhiteSpace(path); _scheme = scheme; _path = path; _method = method; } // ── Common ──────────────────────────────────────────────────────── /// Request/response timeout in milliseconds. Default 30000. public HttpBuilder Timeout(int ms) { _timeout = ms.ToString(); return this; } /// Request/response timeout from an expression. public HttpBuilder Timeout(IExpression timeout) { _timeout = timeout.ToTemplateString(); return this; } /// Content type. Default "application/json". public HttpBuilder ContentType(string contentType) { _contentType = contentType; return this; } // ── Producer ────────────────────────────────────────────────────── /// Disable throwing on non-success HTTP status codes. Default is to throw. public HttpBuilder NoThrowOnError() { _throwOnError = false; return this; } /// Do not map exchange headers to request headers (skipRequestHeaders=true). public HttpBuilder SkipRequestHeaders() { _skipRequestHeaders = true; return this; } /// /// Do not let redbHttp.Method / redbHttp.Query on the exchange steer the request /// (skipControlHeaders=true). /// public HttpBuilder SkipControlHeaders() { _skipControlHeaders = true; return this; } /// /// The header filter strategy of the endpoint, by registry name (headerFilterStrategy=#name): an /// registered in the context. /// public HttpBuilder HeaderFilterStrategy(string registryName) { ArgumentException.ThrowIfNullOrWhiteSpace(registryName); _headerFilterStrategy = registryName.TrimStart('#'); return this; } /// Use HTTP Basic authentication. public HttpBuilder BasicAuth(IExpression username, IExpression password) { _authScheme = "Basic"; _username = username.ToTemplateString(); _password = password.ToTemplateString(); return this; } /// Use HTTP Basic authentication (template strings, support ${...}). public HttpBuilder BasicAuth(string username, string password) { _authScheme = "Basic"; _username = username; _password = password; return this; } /// Use Bearer token authentication. Token is resolved via AuthToken option at runtime. public HttpBuilder BearerAuth() { _authScheme = "Bearer"; return this; } /// /// References a named from the route registry instead of /// putting Basic/Bearer credentials or the TLS certificate password in the URI. /// public HttpBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } /// Bearer/API-key token value or expression (e.g. Property("jwt")). public HttpBuilder AuthToken(IExpression token) { _authToken = token.ToTemplateString(); return this; } /// Bearer/API-key token value (template string, supports ${...}). public HttpBuilder AuthToken(string token) { _authToken = token; return this; } /// Disable following HTTP redirects. Default is to follow. public HttpBuilder NoFollowRedirects() { _followRedirects = false; return this; } /// Maximum number of redirects to follow. Default 50. public HttpBuilder MaxRedirects(int max) { _maxRedirects = max.ToString(); return this; } /// Maximum number of redirects from an expression. public HttpBuilder MaxRedirects(IExpression max) { _maxRedirects = max.ToTemplateString(); return this; } /// Do not map response headers to exchange headers (skipResponseHeaders=true). public HttpBuilder SkipResponseHeaders() { _skipResponseHeaders = true; return this; } /// Preserve the original Host header when proxying. public HttpBuilder PreserveHostHeader() { _preserveHostHeader = true; return this; } // ── Host / Port ──────────────────────────────────────────────────── // Producer: embedded in URL (supports ${...} expressions). // Consumer: emitted as query params for Kestrel bind config. /// /// Target host. Producer: part of request URL. Consumer: Kestrel bind address. /// public HttpBuilder Host(IExpression host) { _host = host.ToTemplateString(); return this; } /// /// Target host (template string, supports ${...}). Producer: part of request URL. Consumer: Kestrel bind address. /// public HttpBuilder Host(string host) { _host = host; return this; } /// /// Target port. Producer: part of request URL. Consumer: Kestrel bind port. /// public HttpBuilder Port(int port) { _port = port.ToString(); return this; } /// /// Target port from an expression — resolved per message at runtime. /// public HttpBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; } // ── Consumer ────────────────────────────────────────────────────── /// Comma-separated HTTP methods to accept (e.g. "POST,PUT"). Default: all. public HttpBuilder Methods(string methods) { _methods = methods; return this; } /// Enable CORS with optional allowed origins. public HttpBuilder Cors(string? origins = null) { _cors = true; _corsOrigins = origins; return this; } /// Allow credentials in CORS requests. public HttpBuilder CorsCredentials() { _corsCredentials = true; return this; } /// Maximum request body size in bytes. Default 10 MB. public HttpBuilder MaxRequestBodySize(long bytes) { _maxRequestBodySize = bytes.ToString(); return this; } /// Maximum request body size from an expression. public HttpBuilder MaxRequestBodySize(IExpression bytes) { _maxRequestBodySize = bytes.ToTemplateString(); return this; } /// /// Admission limit: at most concurrent pipeline executions; overflow /// beyond the optional FIFO is shed with 429 + Retry-After before /// any pipeline work (consumer side). /// public HttpBuilder MaxConcurrentRequests(int max, int queue = 0) { _maxConcurrentRequests = max.ToString(); if (queue > 0) _requestQueueLimit = queue.ToString(); return this; } /// Status code for a shed request (default 429). public HttpBuilder RejectStatusCode(int statusCode) { _rejectStatusCode = statusCode.ToString(); return this; } /// Retry-After value for a shed request in seconds; 0 = do not send (default 1). public HttpBuilder RetryAfterSeconds(int seconds) { _retryAfterSeconds = seconds.ToString(); return this; } /// HTTP protocol version: Http1, Http2, Http1And2, Http3, Http1And2And3. public HttpBuilder Protocol(string protocol) { _protocol = protocol; return this; } /// Enable SSL/TLS with the given certificate. public HttpBuilder SslCert(IExpression certPath, IExpression? certPassword = null) { _ssl = true; _sslCertPath = certPath.ToTemplateString(); _sslCertPassword = certPassword?.ToTemplateString(); return this; } /// Enable SSL/TLS with the given certificate (template strings, support ${...}). public HttpBuilder SslCert(string certPath, string? certPassword = null) { _ssl = true; _sslCertPath = certPath; _sslCertPassword = certPassword; return this; } /// Default HTTP response status code. Default 200. public HttpBuilder ResponseCode(int code) { _responseCode = code.ToString(); return this; } /// Response status code from an expression. public HttpBuilder ResponseCode(IExpression code) { _responseCode = code.ToTemplateString(); return this; } /// Enable request-reply (InOut) exchange pattern. public HttpBuilder InOut() { _inOut = true; return this; } /// Enable request body streaming (consumer: body = Stream instead of byte[]). public HttpBuilder StreamRequest() { _streamRequest = true; return this; } /// Enable response body streaming (producer: Out body = Stream instead of byte[]). public HttpBuilder StreamResponse() { _streamResponse = true; return this; } // ── Query Parameters ────────────────────────────────────────────── /// /// Adds a query-string parameter to the HTTP request URL. /// Values containing ${...} are resolved as expressions at runtime. /// /// Parameter name. /// Constant value or expression string. public HttpBuilder Param(string name, object? value) { _queryParams.Add((name, value?.ToString() ?? "")); return this; } /// /// Adds a query-string parameter bound to an expression, resolved at runtime. /// /// Parameter name. /// Expression that produces the parameter value. public HttpBuilder Param(string name, IExpression expression) { _queryParams.Add((name, expression.ToTemplateString())); return this; } // ── Build ───────────────────────────────────────────────────────── /// Builds the HTTP/HTTPS endpoint URI string. public string Build() { var sb = new StringBuilder(); sb.Append(_scheme); sb.Append(':'); // Producer with explicit Host → embed host[:port] before path if (_method != null && _host != null) { sb.Append(_host); if (_port != null) { sb.Append(':'); sb.Append(_port); } if (_path.Length > 0 && _path[0] != '/') sb.Append('/'); sb.Append(_path); } else { sb.Append(_path); } var sep = '?'; void Append(string key, string value) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } void AppendIf(string key, string? value) { if (value != null) Append(key, value); } void AppendBool(string key, bool value) { if (value) Append(key, "true"); } void AppendBoolFalse(string key, bool? value) { if (value == false) Append(key, "false"); } // Method (producer) AppendIf("method", _method); // Common AppendIf("timeout", _timeout); AppendIf("contentType", _contentType); // Producer AppendBoolFalse("throwOnError", _throwOnError); AppendBool("skipRequestHeaders", _skipRequestHeaders); AppendBool("skipControlHeaders", _skipControlHeaders); AppendIf("headerFilterStrategy", _headerFilterStrategy); AppendIf("authScheme", _authScheme); AppendIf("authToken", _authToken); AppendIf("username", _username); AppendIf("password", _password); AppendIf("connectionFactory", _connectionFactory); AppendBoolFalse("followRedirects", _followRedirects); AppendIf("maxRedirects", _maxRedirects); AppendBool("skipResponseHeaders", _skipResponseHeaders); AppendBool("preserveHostHeader", _preserveHostHeader); // Consumer host/port as query params (producer embeds them in URL path) if (_method == null) { AppendIf("host", _host); AppendIf("port", _port); } AppendIf("methods", _methods); AppendBool("cors", _cors); AppendIf("corsOrigins", _corsOrigins); AppendBool("corsCredentials", _corsCredentials); AppendIf("maxRequestBodySize", _maxRequestBodySize); AppendIf("maxConcurrentRequests", _maxConcurrentRequests); AppendIf("requestQueueLimit", _requestQueueLimit); AppendIf("rejectStatusCode", _rejectStatusCode); AppendIf("retryAfterSeconds", _retryAfterSeconds); AppendIf("protocol", _protocol); AppendBool("ssl", _ssl); AppendIf("sslCertPath", _sslCertPath); AppendIf("sslCertPassword", _sslCertPassword); AppendIf("responseCode", _responseCode); AppendBool("inOut", _inOut); AppendBool("streamRequest", _streamRequest); AppendBool("streamResponse", _streamResponse); // Query parameters foreach (var (name, value) in _queryParams) Append($"param.{name}", value); return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(HttpBuilder b) => b.Build(); /// public override string ToString() => Build(); } Path: redb-route/redb.Route.Http/HttpComponent.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/HttpComponent.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; namespace redb.Route.Http; /// /// HTTP/HTTPS component. Schemes: "http", "https". /// Producer: HttpClient-based HTTP caller (GET/POST/PUT/DELETE/PATCH). /// Consumer: Kestrel-based embedded HTTP server (webhook receiver). /// URI format: http:host:port/path?method=POST&timeout=30000 /// URI format: https:api.example.com/orders?method=POST&throwOnError=true /// URI shorthand: http:GET:/path (method prefix before the path, consumer only) /// public class HttpComponent : ComponentBase { private readonly string _scheme; /// /// Creates the http component. A parameterless constructor of its own: the assembly scan /// (context.AddComponents, the Tsak worker's module contexts) creates components through it and skips a type /// whose only constructor has optional parameters. /// public HttpComponent() : this("http") { } /// Creates an HTTP component with the specified scheme. public HttpComponent(string scheme) { _scheme = scheme; } /// public override string Scheme => _scheme; /// /// Global CORS defaults applied to all HTTP consumers. /// Endpoint-level URI parameters (cors, corsOrigins, corsCredentials) override these. /// public HttpCorsOptions DefaultCors { get; } = new(); /// /// Shared HTTP server manager for pooling Kestrel instances by (host, port). /// Assigned by AddRedbRouteHttp(); a module host that adds components by scanning leaves /// it null and keeps the manager in the container instead — see . /// public SharedHttpServerManager? ServerManager { get; set; } /// /// The manager a consumer binds on. Resolution order: explicitly assigned → the context's DI /// singleton → refusal. There is no private fallback on purpose: an http: consumer binds a /// port, and which port it binds is the host's decision, so a missing manager stays loud (gRPC, /// AS2, SignalR, WebSocket and SOAP resolve in the same order and end with their own server). /// internal SharedHttpServerManager Server => ServerManager ?? Context.Resolve() ?? throw new InvalidOperationException( "SharedHttpServerManager is not configured. Register HTTP via AddRedbRouteHttp() in DI, " + "assign HttpComponent.ServerManager, or give the route context a service provider that holds one."); /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new HttpEndpointOptions(); options.BindFromUri(uri.RawParameters); // Resolve the named ConnectionFactory right after binding — before the path is parsed, so // host/port taken from the URI path always win — and before Validate(), which requires // Username/Password when AuthScheme=Basic. if (!string.IsNullOrEmpty(options.ConnectionFactory)) { // A set-but-unknown name fails loud -- never a silent fallback to URI params. var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory); factory.ApplyTo(options, uri); } // Support shorthand: http:GET:/path or http:POST:host:port/path var path = ExtractMethodPrefix(uri.Path, options, uri.RawParameters, out var hasMethodPrefix); // Extract host[:port] from URI path (e.g. "0.0.0.0:5088/api/demo") // Only override if not explicitly set via query parameters. ParseHostPort(path, options, uri.RawParameters); // Merge global CORS defaults for fields not explicitly set in URI ApplyCorsDefaults(options, uri.RawParameters); options.Validate(); return new HttpEndpoint(uri, this, options, path, hasMethodPrefix); } /// /// Detects an HTTP method prefix in the URI path (e.g. "GET:/connect/token") /// and strips it, applying the method to options. Query params always take priority. /// Returns the cleaned path (without the method prefix). /// internal static string ExtractMethodPrefix( string path, HttpEndpointOptions options, IReadOnlyDictionary rawParams, out bool hasMethodPrefix) { hasMethodPrefix = false; var colonIdx = path.IndexOf(':'); if (colonIdx <= 0) return path; var candidate = path[..colonIdx]; if (!Enum.TryParse(candidate, ignoreCase: true, out var method)) return path; // Method prefix found — strip it from path hasMethodPrefix = true; var cleanPath = path[(colonIdx + 1)..]; // URI query params always take priority if (!rawParams.ContainsKey("method")) options.Method = method; if (!rawParams.ContainsKey("methods")) options.Methods = candidate.ToUpperInvariant(); return cleanPath; } /// /// Extracts host and port from the URI path segment (host[:port][/path]). /// Only overrides options if not already set via query parameters. /// private static void ParseHostPort(string path, HttpEndpointOptions options, IReadOnlyDictionary rawParams) { // Path format: "host:port/path" or "host/path" or "host:port" or "host" var segment = path.TrimStart('/'); var slashIdx = segment.IndexOf('/'); var hostPort = slashIdx >= 0 ? segment[..slashIdx] : segment; var colonIdx = hostPort.LastIndexOf(':'); if (colonIdx > 0) { var hostPart = hostPort[..colonIdx]; var portPart = hostPort[(colonIdx + 1)..]; if (!rawParams.ContainsKey("host") && !string.IsNullOrEmpty(hostPart)) options.Host = hostPart; if (!rawParams.ContainsKey("port") && int.TryParse(portPart, out var port)) options.Port = port; } else if (!rawParams.ContainsKey("host") && !string.IsNullOrEmpty(hostPort)) { options.Host = hostPort; } } /// /// Applies global CORS defaults to options where the URI did not explicitly set them. /// Endpoint-level parameters always win over component-level defaults. /// private void ApplyCorsDefaults(HttpEndpointOptions options, IReadOnlyDictionary rawParams) { if (!rawParams.ContainsKey("cors")) options.Cors = DefaultCors.Enabled; if (!rawParams.ContainsKey("corsOrigins") && DefaultCors.Origins is not null) options.CorsOrigins ??= DefaultCors.Origins; if (!rawParams.ContainsKey("corsCredentials")) options.CorsCredentials = options.CorsCredentials || DefaultCors.Credentials; // Resolver delegate cannot ride in URI parameters (it is a Func, not a string), // so we propagate the global default unless the endpoint already set its own. // BUT: when the URI declared its own static whitelist (corsOrigins=...), the caller // is making an explicit "this exact origin policy" statement -- injecting a // component-wide resolver on top would override that intent silently. So we only // inject the global resolver when the endpoint did not pin its own origins. if (!rawParams.ContainsKey("corsOrigins")) options.CorsOriginsResolver ??= DefaultCors.OriginsResolver; } } /// /// HTTPS component. Behaves identically to HTTP but uses the "https" scheme. /// public class HttpsComponent : HttpComponent { /// Creates an HTTPS component. public HttpsComponent() : base("https") { } } /// /// HTTP endpoint. Creates either a producer (HTTP client) or consumer (Kestrel server). /// The path part of the URI is: host[:port]/path /// For producer: resolves to target URL. /// For consumer: path is the route to listen on. /// public class HttpEndpoint : EndpointBase { private readonly string _cleanPath; private readonly bool _hasMethodPrefix; /// Creates an HTTP endpoint. /// Original parsed URI. /// Parent HTTP component. /// Parsed endpoint options. /// Path with method prefix stripped (if any). Falls back to uri.Path. /// Whether a method prefix was stripped from the path. public HttpEndpoint(EndpointUri uri, HttpComponent component, HttpEndpointOptions options, string? cleanPath = null, bool hasMethodPrefix = false) : base(uri, component, options) { _cleanPath = cleanPath ?? uri.Path; _hasMethodPrefix = hasMethodPrefix; } private redb.Route.Core.EndpointHeaderFilter? _headerFilter; /// /// The header filter strategy of this endpoint on the given side: the one headerFilterStrategy=#name names, /// or the component's default for that side (). A name the registry does /// not hold fails here, when the producer or consumer is built. /// internal redb.Route.Abstractions.IHeaderFilterStrategy HeaderFilterStrategy(EndpointRole role) => LazyInitializer.EnsureInitialized(ref _headerFilter, () => new redb.Route.Core.EndpointHeaderFilter(this, EndpointOptions.HeaderFilterStrategy)) .Or(role == EndpointRole.Producer ? HttpHeaderFilterStrategy.Producer : HttpHeaderFilterStrategy.Consumer); /// Whether this endpoint uses HTTPS. public bool IsHttps => Uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase); /// The scheme prefix for building URLs (http:// or https://). public string SchemePrefix => IsHttps ? "https://" : "http://"; /// The endpoint options for external access. internal HttpEndpointOptions EndpointOptions => Options; /// /// Build the full target URL for the producer. /// URI path is "host:port/path" or "host/path" — we prepend scheme. /// public string BuildProducerUrl() { var path = _cleanPath.TrimStart('/'); return $"{SchemePrefix}{path}"; } /// /// The consumer listen path (the route portion after host:port). /// For "http:0.0.0.0:9090/webhook", returns "/webhook". /// For "http:0.0.0.0:9090", returns "/". /// For "http:GET:/webhook", returns "/webhook". /// public string ConsumerPath { get { var path = _cleanPath; // When method prefix was used and path starts with '/', // it IS the route directly (e.g. "GET:/connect/token" → "/connect/token"). // If it doesn't start with '/', host:port is still present (e.g. "POST:0.0.0.0:8080/api"). if (_hasMethodPrefix && path.StartsWith('/')) return path; if (path.StartsWith('/')) { // Leading-slash form. Its first segment is an embedded host only in the nonstandard // "/host:port/route" shape — recognisable because a host[:port] segment contains a ':' // (route segments never do). Then the route is everything after that segment. // Otherwise the whole path is the route — which is what the fluent DSL emits: // Http.Listen("/api/x").Host(..).Port(..) builds "http:/api/x?host=..&port=..", so the // leading-slash "/api/x" must stay "/api/x", NOT be truncated to "/x". var rest = path[1..]; var firstSlash = rest.IndexOf('/'); var firstSegment = firstSlash >= 0 ? rest[..firstSlash] : rest; if (!firstSegment.Contains(':')) return path; return firstSlash >= 0 ? rest[firstSlash..] : "/"; } // Host-first form "host[:port]/route" (or bare "host") — the route starts at the first slash. var idx = path.IndexOf('/'); return idx >= 0 ? path[idx..] : "/"; } } /// public override IProducer CreateProducer() { RefuseInboundOptionsOnProducer(); return new HttpProducer(this, Options); } /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); RefuseIgnoredInboundCredentials(); var component = (HttpComponent)Component; return new HttpConsumer(this, processor, Options, component.Server) { Authenticator = HttpInboundAuthenticator.Create(Options, component.Context), }; } /// /// inboundAuth and its companions say what a CONSUMER requires of its callers; a producer sends a request /// and checks nobody. Written on a to(...) they would look like protection and do nothing. The message names /// the parameters, never their values. /// private void RefuseInboundOptionsOnProducer() { var written = redb.Route.Core.EndpointOptions.WrittenForOtherRole(Options.GetType(), Uri, EndpointRole.Producer); if (written.Count == 0) return; throw new InvalidOperationException( $"http producer '{EndpointUri.Sanitize(Uri.NormalizedKey)}' sets {string.Join(", ", written)}: these options " + "tell a consumer which callers to accept, and a producer checks nobody. For the credentials a producer sends, " + "use authScheme with username/password or authToken."); } /// /// authScheme, username and password are what a PRODUCER sends. They share the /// options class with the consumer, so on a from(...) they used to bind and validate and then /// check nothing: the endpoint looked closed and was open, with the password sitting in the route /// key. Refused until the consumer has an inbound check of its own. Only what this URI wrote counts /// — a named connection factory may carry producer credentials beside the TLS material a consumer /// reuses it for, and that is not a statement about inbound access. The message names the /// parameters and never their values. The consumer's own check is inboundAuth. /// private void RefuseIgnoredInboundCredentials() { var written = redb.Route.Core.EndpointOptions.WrittenForOtherRole(Options.GetType(), Uri, EndpointRole.Consumer); if (written.Count == 0) return; throw new InvalidOperationException( $"http consumer '{EndpointUri.Sanitize(Uri.NormalizedKey)}' sets {string.Join(", ", written)}, but an " + "http: consumer does not check callers with them — these options are what a producer sends. As written the endpoint " + "would accept every caller while looking protected. To check callers, use inboundAuth=basic with " + "inboundUsername/inboundPassword, or inboundAuth=bearer with tokenValidator=#name."); } } Path: redb-route/redb.Route.Http/HttpConnectionFactory.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/HttpConnectionFactory.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Http; /// /// Named connection factory for HTTP. Register it in the route registry and reference it by name /// from the endpoint URI (connectionFactory=my-api) so Basic/Bearer credentials and the TLS /// certificate password never have to appear in the URI, and therefore can never reach logs, /// telemetry, or the Tsak dashboard. /// /// Note: the request/listen address (host and port) is deliberately NOT part of this factory — for /// the HTTP connector it comes from the endpoint path (http://0.0.0.0:5088/api) and stays /// there, so a factory can never silently redirect a route to a different host. /// /// /// Example: /// /// context.AddToRegistry("billing-api", new HttpConnectionFactory /// { /// AuthScheme = HttpAuthScheme.Bearer, /// AuthToken = Environment.GetEnvironmentVariable("BILLING_TOKEN") /// }); /// /// // route carries no credentials at all: /// r.To("http://billing.corp.local/invoices?connectionFactory=billing-api") /// /// /// public sealed class HttpConnectionFactory { /// Authentication scheme (None, Basic, Bearer). public HttpAuthScheme AuthScheme { get; set; } = HttpAuthScheme.None; /// Username for Basic auth. public string? Username { get; set; } /// Password for Basic auth. [Sensitive] public string? Password { get; set; } /// /// Bearer token for Bearer auth. Supports ${...} expressions exactly like the URI form /// (e.g. ${env:BILLING_TOKEN}, ${header.jwt}) — an expression is resolved per /// request, a plain value is used as-is. /// [Sensitive] public string? AuthToken { get; set; } /// Request timeout in milliseconds (default 30000). public int Timeout { get; set; } = 30_000; /// Serve/connect over TLS. public bool Ssl { get; set; } /// Path to the TLS certificate. public string? SslCertPath { get; set; } /// Password for the TLS certificate. [Sensitive] public string? SslCertPassword { get; set; } /// /// Copies this factory's authentication and TLS settings onto the endpoint options, but only /// for parameters the endpoint URI did not set explicitly — an inline URI value always wins, /// so existing routes keep their behaviour. /// internal void ApplyTo(HttpEndpointOptions options, EndpointUri uri) { var supplied = uri.RawParameters; if (!supplied.ContainsKey(nameof(options.AuthScheme))) options.AuthScheme = AuthScheme; if (!supplied.ContainsKey(nameof(options.Username))) options.Username = Username; if (!supplied.ContainsKey(nameof(options.Password))) options.Password = Password; if (!supplied.ContainsKey(nameof(options.AuthToken)) && AuthToken is not null) { // Mirror EndpointOptions.BindDynamicValue: a ${...} value becomes a per-request // expression, anything else is wrapped as a static value. options.AuthToken = AuthToken.Contains("${", StringComparison.Ordinal) ? DynamicValue.FromExpression(new StringExpression(AuthToken)) : DynamicValue.FromStatic(AuthToken); } if (!supplied.ContainsKey(nameof(options.Timeout))) options.Timeout = Timeout; if (!supplied.ContainsKey(nameof(options.Ssl))) options.Ssl = Ssl; if (!supplied.ContainsKey(nameof(options.SslCertPath))) options.SslCertPath = SslCertPath; if (!supplied.ContainsKey(nameof(options.SslCertPassword))) options.SslCertPassword = SslCertPassword; } } 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().Select(o => o?.ToString() ?? string.Empty).ToArray(), _ => value.ToString() }; if (ContainsInvalidHeaderValueCharacters(sv)) continue; httpContext.Response.Headers.TryAdd(key, sv); } var body = responseMsg.Body; // RFC 7230 §3.3.3 / RFC 9112 §6.1: 1xx, 204 and 304 responses MUST NOT contain a // message body, and Kestrel hard-throws on Body.WriteAsync for those status codes // (Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.FirstWriteAsyncInternal: // "Writing to the response body is invalid for responses with status code "). // Skip the write entirely — the header copy above already propagated whatever // Location/ETag/Set-Cookie the producer wanted to surface, which is the only // legitimate payload for these status families. Silently dropping a non-empty // body is safer than letting Kestrel kill the response mid-flight: a producer // that sets a body for a 204 has a bug to fix, but their downstream client gets // a clean RFC-shaped response instead of a torn TCP connection. var statusForbidsBody = statusCode == 204 || statusCode == 304 || (statusCode >= 100 && statusCode < 200); if (statusForbidsBody) { // Intentional no-op — see note above. We don't even check body.Length: even a // zero-length WriteAsync trips FirstWriteAsyncInternal's status guard. } else if (body is byte[] bytes) { await httpContext.Response.Body.WriteAsync(bytes, httpContext.RequestAborted).ConfigureAwait(false); } else if (body is Stream stream) { await stream.CopyToAsync(httpContext.Response.Body, httpContext.RequestAborted).ConfigureAwait(false); } else if (body is IAsyncEnumerable asyncStrings) { // Streaming body: per-yield flush, no transport buffering. // - text/event-stream → SSE framing (data: ...\n\n + final 'event: done'). // - everything else → chunked plain text (each yield = one chunk). // The framing choice is driven by the response Content-Type, which is the // canonical signal carried end-to-end (HTTP Accept ↔ Content-Type), rather // than a private header. Producers that opt-in to streaming should set // ContentType="text/event-stream" on Out (LlmProducer does this for // stream=body; stream=calls streams inside the route and hands back plain text). var useSse = responseContentType is not null && responseContentType.Contains("text/event-stream", StringComparison.OrdinalIgnoreCase); // Hint to nginx / cloud LB to not buffer the response. Cache-Control // 'no-transform' also blocks gzip middleware from buffering for compression. httpContext.Response.Headers["Cache-Control"] = "no-cache, no-transform"; httpContext.Response.Headers["X-Accel-Buffering"] = "no"; // Disable ASP.NET response buffering so per-chunk WriteAsync hits the // socket immediately. Safe to call after headers are set but before // the first body byte is written. httpContext.Features .Get() ?.DisableBuffering(); if (useSse) await WriteSseStreamAsync(httpContext, responseMsg, asyncStrings, httpContext.RequestAborted).ConfigureAwait(false); else await WriteChunkedTextStreamAsync(httpContext, asyncStrings, httpContext.RequestAborted).ConfigureAwait(false); } else if (body is not null) { await httpContext.Response.WriteAsync( body.ToString() ?? string.Empty, httpContext.RequestAborted).ConfigureAwait(false); } } } /// /// Pumps an of text chunks to the response /// as plain chunked-transfer (one yield = one chunk). Caller is responsible /// for setting Content-Type and disabling buffering. /// private static async Task WriteChunkedTextStreamAsync( Microsoft.AspNetCore.Http.HttpContext httpContext, IAsyncEnumerable source, CancellationToken ct) { await foreach (var chunk in source.WithCancellation(ct).ConfigureAwait(false)) { if (string.IsNullOrEmpty(chunk)) continue; await httpContext.Response.WriteAsync(chunk, ct).ConfigureAwait(false); await httpContext.Response.Body.FlushAsync(ct).ConfigureAwait(false); } } /// /// Pumps an of text chunks to the response /// as Server-Sent Events. Each yield becomes one data: frame; a final /// event: done carries late-bound message headers /// (llm.tokens.in, llm.tokens.out, llm.stop_reason, …) /// that the producer writes only after the stream completes. /// private static async Task WriteSseStreamAsync( Microsoft.AspNetCore.Http.HttpContext httpContext, IMessage responseMsg, IAsyncEnumerable source, CancellationToken ct) { await foreach (var chunk in source.WithCancellation(ct).ConfigureAwait(false)) { if (string.IsNullOrEmpty(chunk)) continue; // SSE spec: each line of the payload needs its own 'data: ' prefix; // a blank line terminates the event. var startIdx = 0; for (var i = 0; i < chunk.Length; i++) { if (chunk[i] != '\n') continue; var line = chunk.Substring(startIdx, i - startIdx); await httpContext.Response.WriteAsync("data: " + line + "\n", ct).ConfigureAwait(false); startIdx = i + 1; } if (startIdx < chunk.Length) { await httpContext.Response.WriteAsync( "data: " + chunk.Substring(startIdx) + "\n", ct).ConfigureAwait(false); } await httpContext.Response.WriteAsync("\n", ct).ConfigureAwait(false); await httpContext.Response.Body.FlushAsync(ct).ConfigureAwait(false); } // Final 'done' event — serialises late-bound stream-summary headers // (LlmHeaders.TokensIn/Out, StopReason, ...) that the producer set after // the IAsyncEnumerable finished iterating. var trailerJson = BuildSseTrailerJson(responseMsg); if (trailerJson is not null) { await httpContext.Response.WriteAsync("event: done\ndata: " + trailerJson + "\n\n", ct).ConfigureAwait(false); await httpContext.Response.Body.FlushAsync(ct).ConfigureAwait(false); } } /// /// Builds the JSON payload for the SSE event: done trailer. Picks up /// streaming-summary headers (anything under the llm. namespace plus /// the standard llm.tokens.* / llm.stop_reason). Returns /// null when there's nothing useful to send. /// private static string? BuildSseTrailerJson(IMessage responseMsg) { var keys = new[] { "llm.tokens.in", "llm.tokens.out", "llm.cost.usd", "llm.stop_reason", "llm.tool.iterations", "llm.model.id", "llm.provider.id" }; Dictionary? payload = null; foreach (var k in keys) { if (!responseMsg.Headers.TryGetValue(k, out var v) || v is null) continue; payload ??= new Dictionary(StringComparer.Ordinal); // Numbers and booleans go in as they are, so the serializer writes JSON numbers and // literals; everything else as invariant text. ToString() would quote a count ("7") and, // on a Russian-locale worker, write a decimal cost with a comma ("0,0123") — the Llm // documentation promises plain numbers. payload[k] = v switch { string => v, bool or byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal => v, IFormattable f => f.ToString(null, System.Globalization.CultureInfo.InvariantCulture), _ => v.ToString(), }; } return payload is null ? null : System.Text.Json.JsonSerializer.Serialize(payload); } private static bool ContainsInvalidHeaderValueCharacters(Microsoft.Extensions.Primitives.StringValues values) { foreach (var value in values) { if (value is null) continue; foreach (var ch in value) { // Kestrel rejects control chars and non-ASCII in raw header values. if (ch < 0x20 || ch > 0x7E) return true; } } return false; } } Path: redb-route/redb.Route.Http/HttpCorsOptions.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/HttpCorsOptions.cs ---- namespace redb.Route.Http; /// /// Global CORS configuration for HTTP components. /// Applied as defaults to all HTTP consumers unless overridden at the endpoint level. /// Usage: services.AddRedbRouteHttp(cors => { cors.Enabled = true; cors.Origins = "https://example.com"; }); /// public class HttpCorsOptions { /// Enable CORS for all HTTP consumers. Default: false. public bool Enabled { get; set; } /// /// Allowed origins (comma-separated). Default: * when CORS is enabled. /// Example: "https://example.com,https://app.example.com" /// public string? Origins { get; set; } /// /// Enable Access-Control-Allow-Credentials header. Default: false. /// When true, Origins must be set to a specific origin (not *). /// public bool Credentials { get; set; } /// /// Optional global per-request CORS-origin resolver applied as a default to all HTTP /// consumers that do not set their own . /// See for the contract. /// public Func? OriginsResolver { get; set; } } Path: redb-route/redb.Route.Http/HttpEndpointOptions.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/HttpEndpointOptions.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Http; /// /// Options for the HTTP endpoint. Shared by both producer and consumer. /// Use URI parameters to configure: http:host:port/path?method=POST&timeout=30000 /// [LenientProperties] public class HttpEndpointOptions : EndpointOptions { // ── Common ────────────────────────────────────────── /// HTTP method. Default: GET for producer, all methods accepted for consumer. public HttpMethod Method { get; set; } = HttpMethod.GET; /// Request/response timeout in milliseconds. Default: 30000 (30s). Producer only. public int Timeout { get; set; } = 30_000; /// Content-Type header value for outgoing requests/responses. Default: application/json. public string ContentType { get; set; } = "application/json"; // ── Producer (HttpClient) ─────────────────────────── /// Throw an exception on HTTP 4xx/5xx responses. Default: true. public bool ThrowOnError { get; set; } = true; /// /// Do not map the exchange headers to request headers at all; only the fields the producer sets itself go out. /// Default: false. Apache Camel's skipRequestHeaders. /// [EndpointRole(EndpointRole.Producer)] public bool SkipRequestHeaders { get; set; } /// /// Do not let the control headers on the exchange — redbHttp.Method, redbHttp.Query — steer the /// request; the endpoint's own options decide. Default: false. Set it on a producer whose exchange may carry /// headers of other hops (a message received from a broker keeps every header it came with). Apache Camel's /// skipControlHeaders. /// [EndpointRole(EndpointRole.Producer)] public bool SkipControlHeaders { get; set; } /// /// A registry reference (#name) to an that decides /// which headers this endpoint carries, in place of : the request and /// response headers of a producer, the request and response headers of a consumer. The protocol fields /// () and, on a consumer, received redbHttp.* and response-only /// fields are never carried, whatever the strategy says. /// [RegistryReference(typeof(IHeaderFilterStrategy))] public string? HeaderFilterStrategy { get; set; } /// Authentication scheme. Default: None. [EndpointRole(EndpointRole.Producer)] public HttpAuthScheme AuthScheme { get; set; } = HttpAuthScheme.None; /// Username for Basic auth. [EndpointRole(EndpointRole.Producer)] public string? Username { get; set; } /// Password for Basic auth. [Sensitive] [EndpointRole(EndpointRole.Producer)] public string? Password { get; set; } /// Bearer token value (or expression) for Bearer auth. [Sensitive] [EndpointRole(EndpointRole.Producer)] public DynamicValue? AuthToken { get; set; } // ── Inbound authentication (consumer only) ── /// /// Consumer only: how an inbound request proves who it is. Basic checks the Authorization header /// against / ; Bearer hands the token to the /// named by . A refused request gets 401 with /// WWW-Authenticate and never reaches the route. Default None. /// [EndpointRole(EndpointRole.Consumer)] public HttpAuthScheme InboundAuth { get; set; } = HttpAuthScheme.None; /// Consumer only: the user name inboundAuth=basic accepts. [EndpointRole(EndpointRole.Consumer)] public string? InboundUsername { get; set; } /// Consumer only: the password inboundAuth=basic accepts. Take it from configuration ({{…}}). [Sensitive] [EndpointRole(EndpointRole.Consumer)] public string? InboundPassword { get; set; } /// Consumer only: the realm named in WWW-Authenticate. Default redb. [EndpointRole(EndpointRole.Consumer)] public string InboundRealm { get; set; } = "redb"; /// Consumer only: registry name of the for inboundAuth=bearer, #name or name. [EndpointRole(EndpointRole.Consumer)] [RegistryReference(typeof(IHttpTokenValidator))] public string? TokenValidator { get; set; } /// /// Named from the route registry. Lets Basic/Bearer /// credentials and the TLS certificate password live in the registry instead of the endpoint /// URI, so they never reach logs or dashboards. /// [RegistryReference(typeof(HttpConnectionFactory))] public string? ConnectionFactory { get; set; } /// Follow HTTP redirects. Default: true. public bool FollowRedirects { get; set; } = true; /// Maximum number of automatic redirects. Default: 50. public int MaxRedirects { get; set; } = 50; /// /// Do not map the response headers to exchange headers; the status, URL and content type are still set. /// Default: false. Apache Camel's skipResponseHeaders. /// [EndpointRole(EndpointRole.Producer)] public bool SkipResponseHeaders { get; set; } /// Preserve the Host header from the original request. Default: false. public bool PreserveHostHeader { get; set; } // ── Consumer (Kestrel) ────────────────────────────── /// Bind host for the embedded HTTP server. Default: 0.0.0.0. public string Host { get; set; } = "0.0.0.0"; /// Bind port for the embedded HTTP server. Default: 8080. public int Port { get; set; } = 8080; /// /// Comma-separated list of allowed HTTP methods for the consumer. /// Default: empty (all methods accepted). /// Example: "POST,PUT" /// public string? Methods { get; set; } /// Enable CORS for all origins. Default: false. public bool Cors { get; set; } /// /// CORS allowed origins (comma-separated). Default: * when CORS is enabled. /// Example: "https://example.com,https://app.example.com" /// NOTE: browsers do NOT understand a comma-separated Access-Control-Allow-Origin /// header. When this property contains multiple origins, the consumer middleware will echo /// back the request's Origin header IF it appears in the list, otherwise the request /// is treated as not allowed (no CORS headers emitted, browser preflight fails). /// For multi-origin scenarios prefer for full control. /// public string? CorsOrigins { get; set; } /// /// Optional per-request CORS-origin resolver. When set, takes precedence over /// . The delegate receives the incoming /// and returns either: /// /// a specific origin string (e.g. "https://app.example.com") — echoed back /// in Access-Control-Allow-Origin; /// "*" — wildcard (browsers reject this combination with credentials); /// null — origin not allowed; no CORS headers will be emitted. /// /// The delegate must be cheap and thread-safe; it runs on every CORS-eligible request. /// Cannot be configured via URI parameters; set this in DI via the global /// or programmatically on the endpoint options. /// public Func? CorsOriginsResolver { get; set; } /// /// Enable Access-Control-Allow-Credentials header. Default: false. /// When true, the resolved origin must be a specific value (not *) — browsers reject /// the combination. The runtime middleware enforces this regardless of how the origin was /// resolved (static or ). /// public bool CorsCredentials { get; set; } /// Maximum request body size in bytes. Default: 10 MB (10485760). 0 = unlimited. public long MaxRequestBodySize { get; set; } = 10 * 1024 * 1024; // ── Admission limit (HTTP_CONCURRENCY_LIMITS_PLAN) ── /// /// Maximum concurrent executions of this consumer's pipeline. 0 (default) = unlimited — /// Kestrel runs as many as requests arrive. Overflow beyond the limit and /// is shed with before any /// pipeline work (load shedding, not backpressure). /// public int MaxConcurrentRequests { get; set; } /// /// How many requests over the limit WAIT for a permit (FIFO) instead of being rejected. /// 0 (default) = reject immediately once the permits are taken. /// public int RequestQueueLimit { get; set; } /// Status code for a shed request. Default 429 Too Many Requests. public int RejectStatusCode { get; set; } = 429; /// Value of the Retry-After header on a shed request; 0 = do not send it. Default 1. public int RetryAfterSeconds { get; set; } = 1; /// HTTP protocol version for the consumer. Default: Http1And2. public HttpProtocol Protocol { get; set; } = HttpProtocol.Http1And2; /// Enable HTTPS for the consumer. Default: false. public bool Ssl { get; set; } /// Path to PFX certificate file for HTTPS. Required when ssl=true. public string? SslCertPath { get; set; } /// Password for the PFX certificate. [Sensitive] public string? SslCertPassword { get; set; } /// /// Response status code for successful processing. Default: 200. /// public int ResponseCode { get; set; } = 200; /// /// If true, the consumer returns the exchange Out body as the HTTP response (InOut pattern). /// If false, returns an empty 200 OK (InOnly pattern). Default: false. /// public bool InOut { get; set; } /// /// If true, enables streaming of request body instead of buffering. /// Useful for large payloads. Default: false. /// public bool StreamRequest { get; set; } /// /// If true, the producer sets the exchange Out body to a Stream instead of byte[]. /// The stream is closed automatically by Exchange.DisposeAsync(). Default: false. /// public bool StreamResponse { get; set; } // ── Named Parameters ──────────────────────────────────────────── private IReadOnlyDictionary? _explicitParameters; /// /// Named parameter bindings from .Param() calls. /// Extracted from URI parameters with param. prefix. /// Used to resolve {name} placeholders in the URL path at runtime. /// Values may contain ${...} expressions resolved before substitution. /// internal IReadOnlyDictionary ExplicitParameters => _explicitParameters ??= ParseExplicitParameters(); private IReadOnlyDictionary ParseExplicitParameters() { var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var (key, value) in UnmappedParameters) { if (key.StartsWith("param.", StringComparison.OrdinalIgnoreCase)) dict[key["param.".Length..]] = value; } return dict; } /// Inbound authentication must be complete and unambiguous: a half-declared check would look closed and be open. private void ValidateInboundAuth() { switch (InboundAuth) { case HttpAuthScheme.None: if (InboundUsername is not null || InboundPassword is not null || TokenValidator is not null) throw new ArgumentException( "inboundUsername, inboundPassword and tokenValidator take effect only with inboundAuth=basic or " + "inboundAuth=bearer; without it the endpoint would accept every caller while looking protected."); break; case HttpAuthScheme.Basic: if (string.IsNullOrEmpty(InboundUsername) || string.IsNullOrEmpty(InboundPassword)) throw new ArgumentException("inboundAuth=basic needs inboundUsername and inboundPassword."); if (TokenValidator is not null) throw new ArgumentException("tokenValidator checks bearer tokens; inboundAuth=basic does not use it."); break; case HttpAuthScheme.Bearer: if (string.IsNullOrWhiteSpace(TokenValidator)) throw new ArgumentException("inboundAuth=bearer needs tokenValidator=#name, a registered IHttpTokenValidator."); if (InboundUsername is not null || InboundPassword is not null) throw new ArgumentException("inboundUsername and inboundPassword belong to inboundAuth=basic."); break; } // The realm is written into a quoted-string of WWW-Authenticate. if (string.IsNullOrEmpty(InboundRealm) || InboundRealm.Any(c => c is '"' or '\\' || char.IsControl(c))) throw new ArgumentException("inboundRealm must be non-empty, without quotes, backslashes or control characters."); } /// /// Options renamed to Apache Camel's names, with the meaning reversed. The HTTP options take parameters they have /// no property for (), so an old name would be dropped without a word and /// its endpoint would quietly do the opposite of what it says: it is refused instead. /// private static readonly Dictionary RenamedOptions = new(StringComparer.OrdinalIgnoreCase) { ["bridgeHeaders"] = "'bridgeHeaders' is replaced by Apache Camel's 'skipRequestHeaders', with the meaning reversed: " + "bridgeHeaders=false is skipRequestHeaders=true; bridgeHeaders=true is the default and needs no option.", ["copyResponseHeaders"] = "'copyResponseHeaders' is replaced by Apache Camel's 'skipResponseHeaders', with the meaning " + "reversed: copyResponseHeaders=false is skipResponseHeaders=true; copyResponseHeaders=true " + "is the default and needs no option.", }; /// public override void Validate() { foreach (var key in UnmappedParameters.Keys) { if (RenamedOptions.TryGetValue(key, out var replacement)) throw new ArgumentException(replacement, key); } if (Timeout < 0) throw new ArgumentException("Timeout must be >= 0."); if (Port is < 0 or > 65535) throw new ArgumentException("Port must be between 0 and 65535."); if (MaxRedirects < 0) throw new ArgumentException("MaxRedirects must be >= 0."); if (MaxRequestBodySize < 0) throw new ArgumentException("MaxRequestBodySize must be >= 0."); ConcurrencyLimitOptions.ValidateShape(MaxConcurrentRequests, RequestQueueLimit, RejectStatusCode, RetryAfterSeconds); if (ResponseCode is < 100 or > 599) throw new ArgumentException("ResponseCode must be between 100 and 599."); if (AuthScheme == HttpAuthScheme.Basic && (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))) throw new ArgumentException("Username and Password are required when AuthScheme=Basic."); ValidateInboundAuth(); // No SslCertPath check here on purpose. The certificate may legitimately come from a named // connection factory or from the host default (HttpHostingOptions.Tls), the way a Camel // endpoint resolves from global SSLContextParameters. The invariant "TLS asked for and no // certificate resolves" is enforced once, at the bind, by SharedHttpServerManager — the // only place that can see all three sources. // CORS configuration must be explicit. When Cors=true, the caller MUST supply either // a static whitelist (CorsOrigins, including "*" for public endpoints) or a resolver // (CorsOriginsResolver). The legacy implicit "*" fallback is a footgun that browsers // silently downgrade in combination with credentials, so we surface the misconfiguration // at startup instead. if (Cors && string.IsNullOrEmpty(CorsOrigins) && CorsOriginsResolver is null) throw new ArgumentException( "Cors=true requires CorsOrigins (use \"*\" for public endpoints) or CorsOriginsResolver to be set."); // CorsCredentials + wildcard guard: only enforceable at config time when no resolver // is set. With a resolver, the same constraint is enforced per-request inside the // CORS middleware (see HttpConsumer.Start) — the resolver may legitimately return a // specific origin even when CorsOrigins is null/empty. if (CorsCredentials && CorsOriginsResolver is null && string.IsNullOrEmpty(CorsOrigins)) throw new ArgumentException("CorsOrigins or CorsOriginsResolver must be set when CorsCredentials=true (wildcard * is not allowed by browsers in combination with credentials)."); } } Path: redb-route/redb.Route.Http/HttpEnums.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/HttpEnums.cs ---- namespace redb.Route.Http; /// /// HTTP methods supported by the component. /// public enum HttpMethod { /// HTTP GET. GET, /// HTTP POST. POST, /// HTTP PUT. PUT, /// HTTP DELETE. DELETE, /// HTTP PATCH. PATCH, /// HTTP HEAD. HEAD, /// HTTP OPTIONS. OPTIONS } // HttpProtocol moved to redb.Route.Http.Hosting (kept in the redb.Route.Http namespace) — it is shared // between the Kestrel host and the HTTP connector options. /// /// Authentication scheme: what a producer sends (authScheme) or what a consumer requires (inboundAuth). /// public enum HttpAuthScheme { /// No authentication. None, /// HTTP Basic authentication (username:password). Basic, /// Bearer token authentication. Bearer } Path: redb-route/redb.Route.Http/HttpHeaderFilterStrategy.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/HttpHeaderFilterStrategy.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Http; /// /// The default of the HTTP component, Apache Camel's HttpHeaderFilterStrategy. /// An endpoint's headerFilterStrategy=#name replaces it; derive from it to add to it. /// /// A producer () sends every exchange header but the component's control headers /// () and empty values, and takes every response header back. A consumer /// () takes every request header and answers with every exchange header but redb* and /// Camel* ones and null values. /// /// /// Whatever the strategy, the transport itself never carries the protocol fields (), /// and a consumer never takes a received redbHttp.* header (it would pose as one the transport sets, such as /// the remote address), never takes a response-only field from a request () /// and never answers with a value the request brought. /// /// public class HttpHeaderFilterStrategy : IHeaderFilterStrategy { /// The default strategy of an HTTP producer. public static HttpHeaderFilterStrategy Producer { get; } = new(EndpointRole.Producer); /// The default strategy of an HTTP consumer. public static HttpHeaderFilterStrategy Consumer { get; } = new(EndpointRole.Consumer); /// Creates the default strategy of a producer or of a consumer. /// Which side of the exchange the strategy serves. public HttpHeaderFilterStrategy(EndpointRole role) => Role = role; /// Which side of the exchange the strategy serves: a producer's request, or a consumer's response. public EndpointRole Role { get; } /// public virtual bool FilterOutgoing(string name, object? value, IExchange exchange) => Role == EndpointRole.Producer ? value is null || value.ToString() is not { Length: > 0 } || HttpHeaders.ControlHeaders.Contains(name) : value is null || name.StartsWith("redb", StringComparison.OrdinalIgnoreCase) || name.StartsWith("Camel", StringComparison.OrdinalIgnoreCase); /// public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false; } Path: redb-route/redb.Route.Http/HttpHeaders.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/HttpHeaders.cs ---- namespace redb.Route.Http; /// /// Well-known header constants used by the HTTP component. /// Exchange headers with the "redbHttp." prefix are set/read automatically. /// Standard HTTP headers (Content-Type, Authorization, etc.) are bridged as-is. /// public static class HttpHeaders { /// Common prefix for all HTTP component headers. public const string Prefix = "redbHttp."; /// HTTP response status code (int). Set by producer after response, by consumer in Out message. public const string StatusCode = "redbHttp.StatusCode"; /// HTTP response reason phrase. public const string StatusText = "redbHttp.StatusText"; /// The full request/response URL. public const string Url = "redbHttp.Url"; /// HTTP method used (GET, POST, etc.). public const string Method = "redbHttp.Method"; /// HTTP Content-Type header value. public const string ContentType = "Content-Type"; /// HTTP Content-Length header value. public const string ContentLength = "Content-Length"; /// Query string from the incoming request (consumer). Example: "param1=val1&param2=val2". public const string Query = "redbHttp.Query"; /// Raw request path (consumer). Example: "/webhook". public const string Path = "redbHttp.Path"; /// Remote IP address of the client (consumer). public const string RemoteAddress = "redbHttp.RemoteAddress"; /// Server port the request was received on (consumer). public const string Port = "redbHttp.Port"; /// Response content type override. If set, producer/consumer use this for response Content-Type. public const string ResponseContentType = "redbHttp.ResponseContentType"; /// Response status code override. If set as int, consumer uses this for response status code. public const string ResponseCode = "redbHttp.ResponseCode"; /// Authorization header value. public const string Authorization = "Authorization"; /// Accept header value. public const string Accept = "Accept"; /// User-Agent header value. public const string UserAgent = "User-Agent"; /// Prefix for route template parameters. Example: "redbHttp.RouteParam.id". public const string RouteParamPrefix = "redbHttp.RouteParam."; /// Prefix for query string parameters. Example: "redbHttp.QueryParam.sort". public const string QueryParamPrefix = "redbHttp.QueryParam."; // ── What is never carried, and what the default strategy keeps back ── /// /// The control headers of this component — the request it builds and the exchange a consumer fills. The default /// strategy of a producer () does not send them as request headers; a /// consumer never takes a received redbHttp.* header and never answers with one. /// public static readonly IReadOnlySet ControlHeaders = new HashSet(StringComparer.OrdinalIgnoreCase) { StatusCode, StatusText, Url, Method, Query, Path, RemoteAddress, Port, ResponseContentType, ResponseCode, }; /// /// Fields of the protocol, never carried between an exchange and a message whatever the header filter strategy /// says: the hop-by-hop fields, Host (only preserveHostHeader=true carries the original one) and the /// content fields, which describe the body and are set from it. /// public static readonly IReadOnlySet ProtocolHeaders = new HashSet(StringComparer.OrdinalIgnoreCase) { // Hop-by-hop HTTP headers "Connection", "Keep-Alive", "Transfer-Encoding", "TE", "Trailer", "Upgrade", "Proxy-Authorization", "Proxy-Authenticate", // Host names THIS hop's target. Bridging it verbatim turned every proxy route into an // accidental preserve-host proxy; the explicit preserveHostHeader=true is the one way // to carry the original through (the options sweep). "Host", // Content headers managed by HttpClient ContentType, ContentLength, "Content-Encoding", "Content-Language", "Content-Disposition", "Content-Range" }; /// /// Fields only a response carries (RFC 9110 §10.2 and §11, RFC 6265 Set-Cookie). A consumer drops them from an /// inbound request before the exchange is built, so neither the route nor the response ever holds a value a client /// planted under a response field's name. Stricter than Camel's inbound filter, which removes only its own /// Camel* headers: a request has no legitimate use for these, and one that sends them is probing. /// public static readonly IReadOnlySet ResponseOnlyHeaders = new HashSet(StringComparer.OrdinalIgnoreCase) { "Set-Cookie", "Location", "WWW-Authenticate", "Proxy-Authenticate", "Authentication-Info", "Proxy-Authentication-Info", "Retry-After", "Server", "Age", "ETag", "Accept-Ranges", "Vary", }; /// Returns true if the header key belongs to the HTTP component (starts with "redbHttp."). public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.Http/HttpInboundAuthenticator.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/HttpInboundAuthenticator.cs ---- using System.Security.Claims; using System.Security.Cryptography; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Serialization; namespace redb.Route.Http; /// /// The inbound check of an http: consumer (inboundAuth=basic|bearer). Runs before the exchange exists: a request /// it refuses gets 401 with WWW-Authenticate and never reaches the route. /// internal sealed class HttpInboundAuthenticator { private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private readonly HttpAuthScheme _scheme; private readonly string _realm; private readonly byte[]? _userHash; private readonly byte[]? _passwordHash; private readonly IHttpTokenValidator? _validator; private HttpInboundAuthenticator(HttpAuthScheme scheme, string realm, string? user, string? password, IHttpTokenValidator? validator) { _scheme = scheme; _realm = realm; // Hashes of equal length, so the comparison below takes the same time whatever the input. _userHash = user is null ? null : SHA256.HashData(Encoding.UTF8.GetBytes(user)); _passwordHash = password is null ? null : SHA256.HashData(Encoding.UTF8.GetBytes(password)); _validator = validator; } /// /// The authenticator the options declare, or null for inboundAuth=none. The token validator is resolved /// here, while the route starts, so a misspelt name stops the start instead of answering every request with 500. /// public static HttpInboundAuthenticator? Create(HttpEndpointOptions options, IRouteContext? context) => options.InboundAuth switch { HttpAuthScheme.Basic => new(HttpAuthScheme.Basic, options.InboundRealm, options.InboundUsername, options.InboundPassword, null), HttpAuthScheme.Bearer => new(HttpAuthScheme.Bearer, options.InboundRealm, null, null, context.GetRequiredFromRegistry( options.TokenValidator!.StartsWith('#') ? options.TokenValidator[1..] : options.TokenValidator)), _ => null, }; /// /// The principal of an accepted request; null after writing the 401 of a refused one. /// public async Task AuthenticateAsync(HttpContext httpContext) { var header = httpContext.Request.Headers.Authorization; var credentials = header.Count == 1 ? Credentials(header[0]) : null; if (_scheme == HttpAuthScheme.Basic) { var principal = credentials is null ? null : CheckBasic(credentials); if (principal is null) Refuse(httpContext, $"Basic realm=\"{_realm}\", charset=\"UTF-8\""); return principal; } if (credentials is null) { // No token at all: RFC 6750 §3.1, the challenge carries no error code. Refuse(httpContext, $"Bearer realm=\"{_realm}\""); return null; } var accepted = await _validator!.ValidateAsync(credentials, httpContext.RequestAborted).ConfigureAwait(false); if (accepted?.Identity?.IsAuthenticated == true) return accepted; Refuse(httpContext, $"Bearer realm=\"{_realm}\", error=\"invalid_token\""); return null; } /// The credentials after this authenticator's scheme name, or null when the header is another scheme. private string? Credentials(string? header) { if (string.IsNullOrEmpty(header)) return null; var space = header.IndexOf(' '); if (space <= 0) return null; var scheme = _scheme == HttpAuthScheme.Basic ? "Basic" : "Bearer"; if (!header.AsSpan(0, space).Equals(scheme, StringComparison.OrdinalIgnoreCase)) return null; var credentials = header[(space + 1)..].Trim(); return credentials.Length == 0 ? null : credentials; } private ClaimsPrincipal? CheckBasic(string encoded) { var buffer = new byte[encoded.Length]; // A credential has one spelling: non-zero unused bits in the last character are refused on every runtime. if (!Base64Text.TryDecodeCanonical(encoded, buffer, out var length)) return null; string decoded; try { decoded = StrictUtf8.GetString(buffer, 0, length); } catch (DecoderFallbackException) { // Not UTF-8 (RFC 7617 charset): not credentials this endpoint issued. return null; } var colon = decoded.IndexOf(':'); if (colon < 0) return null; var user = decoded[..colon]; var password = decoded[(colon + 1)..]; // Both halves are always compared, so the time does not tell which one was wrong. var userMatches = CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(user)), _userHash); var passwordMatches = CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(password)), _passwordHash); if (!(userMatches & passwordMatches)) return null; return new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, user)], authenticationType: "Basic")); } private static void Refuse(HttpContext httpContext, string challenge) { httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized; httpContext.Response.Headers[HeaderNames.WWWAuthenticate] = challenge; } } 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; } } } } Path: redb-route/redb.Route.Http/IHttpTokenValidator.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/IHttpTokenValidator.cs ---- using System.Security.Claims; namespace redb.Route.Http; /// /// Checks the bearer token of an inbound request for an http: consumer or a REST declaration with /// inboundAuth=bearer, registered in the route registry and named by tokenValidator=#name. /// /// The connector does not read tokens itself: JWT parsing, signing keys and their rotation, audiences and scopes belong /// to the identity provider's library (redb.Identity, or any OpenID Connect client). This interface is where it plugs in. /// /// public interface IHttpTokenValidator { /// /// The principal the token stands for, or null when the token is not accepted (the caller gets 401 with /// error="invalid_token"). A principal whose identity is not authenticated counts as not accepted. An exception /// is a failure of the validator, not of the caller, and answers 500. /// /// The token after Bearer , as the client sent it. /// Cancelled when the request is aborted. Task ValidateAsync(string token, CancellationToken ct); } Path: redb-route/redb.Route.Http/README.md 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/README.md ---- # redb.Route.Http > Documentation and articles: HTTP/HTTPS transport for redb.Route. HttpClient-based producer (outbound requests) and Kestrel-based consumer (webhook receiver) with CORS, auth, and streaming. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Http?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Http) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Http ``` ## Usage ### Fluent DSL ```csharp using redb.Route.Http; // Outbound HTTP call (producer) From("direct://send") .To(Http.Post("api.example.com/orders") .Timeout(5000) .BearerAuth() .ContentType("application/json")); // Webhook receiver (consumer) From(Http.Listen("/webhooks/orders") .Host("0.0.0.0").Port(8080) .Methods("POST") .Cors("https://app.example.com") .MaxRequestBodySize(1_048_576)) .Log("Webhook received: ${body}") .To("direct://process"); // REST methods shorthand From("direct://get-data") .To(Http.Get("api.example.com/status").NoThrowOnError()); From("direct://update") .To(Http.Put("api.example.com/orders/${header.orderId}")); From("direct://remove") .To(Http.Delete("api.example.com/orders/${header.orderId}")); // HTTPS From("direct://secure-call") .To(Https.Post("api.example.com/data") .BearerAuth() .AuthToken("${property.jwt}")); // Named parameters — {name} in URL resolved from .Param() at runtime From("direct://get-order") .To(Http.Get("api.example.com/orders/{orderId}") .Param("orderId", Header("orderId"))); // Multiple named parameters + IExpression values From("direct://user-orders") .To(Http.Get("api.example.com/users/{userId}/orders/{status}") .Param("userId", Header("userId")) .Param("status", Constant("active"))); ``` > `${...}` expressions in URL and options are resolved per message at runtime. > `{name}` placeholders are resolved from `.Param()` bindings — values are URL-encoded automatically. > In fluent DSL, pass the path **without** `http://` / `https://` — the scheme is set by `Http.` vs `Https.`. ### Raw URI (non-fluent) ```csharp // Raw URI strings include the full scheme — ${...} resolved per message From("direct://update") .To("https://api.example.com/orders/${header.orderId}?method=PUT"); // Fully dynamic URL — host, port, path all from expressions From("direct://proxy") .To("https://${header.targetHost}:${header.targetPort}/api/${header.resource}?method=POST"); ``` ## Fluent Builder API | Category | Methods | |----------|---------| | **HTTP Methods** | `Http.Get()`, `Http.Post()`, `Http.Put()`, `Http.Delete()`, `Http.Patch()`, `Http.Head()` | | **Consumer** | `Http.Listen()`, `.Host()`, `.Port()`, `.Methods()`, `.Cors()`, `.CorsCredentials()`, `.MaxRequestBodySize()`, `.Protocol()`, `.ResponseCode()`, `.InOut()`, `.StreamRequest()` | | **Auth** | `.BasicAuth(user, pass)`, `.BearerAuth()`, `.AuthToken()` | | **SSL** | `.SslCert(path, pass?)` | | **Producer** | `.Timeout()`, `.ContentType()`, `.NoThrowOnError()`, `.SkipRequestHeaders()`, `.SkipControlHeaders()`, `.HeaderFilterStrategy(name)`, `.NoFollowRedirects()`, `.MaxRedirects()`, `.SkipResponseHeaders()`, `.PreserveHostHeader()` | | **Parameters** | `.Param(name, value)`, `.Param(name, IExpression)` — bind `{name}` URL placeholders | > Most builder methods (Timeout, BasicAuth, AuthToken, MaxRedirects, Host, Port, MaxRequestBodySize, SslCert, ResponseCode) accept both constant values and `IExpression` for runtime resolution. ## Schemes Both `http` and `https` schemes are supported. Use `Https.Get(...)` / `Https.Post(...)` for TLS endpoints. ## Routing precedence (shared server) Multiple consumers can register routes on the same `(host, port)` — they share one Kestrel server. When several routes match the same request path, the most **specific** path wins, not the first one registered: 1. Concrete/literal paths (`/api/echo`) before route-parameter paths (`/api/{id}`). 2. Fewer route parameters before more. 3. Catch-all templates (`/{**path}`) are tried **last**. 4. Registration order breaks ties (first-registered wins among equal specificity). This means a concrete path and a catch-all fallback can coexist on one port — e.g. a dispatcher mounted on `/{**path}` plus a dedicated `/api/echo` route — and `/api/echo` is routed to the specific handler. The same ordering drives per-route CORS dispatch. ## REST DSL A declarative facade over the same consumer and shared host (Apache Camel `rest()` parity): ```csharp this.Rest("/api/orders", o => { o.Port = 8080; o.BindingMode = RestBindingMode.Json; }) .Get("/{id}").Produces("application/json").OutType().To("direct:get-order") // header.id, header.query.page .Post().Consumes("application/json").Type().To("direct:create-order") // 415 on another Content-Type .Put("/{id}/status").To("direct:set-status") .Delete("/{id}").Route().Process(e => e.In.Body = null); // inline steps, 204 ``` Every verb is an ordinary route `From("http://host:port/base/path?methods=GET&inOut=true")`. Path parameters arrive as `header.id`, query as `header.query.*`; the status code is the consumer's `redbHttp.ResponseCode` header; no body and no status is 204. An OpenAPI 3.0.3 document is served at `{basePath}/openapi.json` (`RestOptions.OpenApi` / `OpenApiPath`). Several `Rest(...)` declarations share a port. Route ids: a verb's route takes the id given with `.Id(...)` (`id=` in XML). Without one it gets `rest-GET-api-orders-id-1a2b3c4d`: method and path with every other character turned into `-`, then a fingerprint of the method and path, so `/{id}` and `/id` stay apart and the id is the same on every start. The OpenAPI route is `rest-openapi-api-orders-…`, and the route of a verb's inline steps is the verb's id plus `-handler`. The ids carry no `/` and no space, so the Tsak worker API and the dashboard can address them. ### Request validation Parameters are declared on the verb with `Param(...)` and always go to the OpenAPI document. They are enforced only when `ClientRequestValidation` is on (Camel's `clientRequestValidation`), for the whole declaration or per verb, so parameters written down for the document alone never start refusing requests: ```csharp this.Rest("/api/items", o => { o.Port = 8080; o.ClientRequestValidation = true; o.ErrorHandler = "#restErrors"; }) .Get("/{id}").Produces("application/json") .Param("id", RestParamType.Path, dataType: RestParamDataType.Integer) .Param("limit", RestParamType.Query, required: true, dataType: RestParamDataType.Integer, description: "Page size") .Param("X-Tenant", RestParamType.Header, required: true) .To("direct:get-item"); ``` In order, before the route runs: | Check | Answer | |---|---| | `Content-Type` against `Consumes` (runs with validation off too) | 415 | | `Accept` against `Produces`: no header admits everything; the most specific matching range decides; `q=0` refuses | 406 | | a required parameter is missing, or a value does not convert to its `dataType` (`integer`, `number`, `boolean`; invariant culture) | 400, naming the parameter | A path parameter must be a segment of the template and is always required. The refusal body is the reason as `text/plain`. `ErrorHandler` names a registered `IProcessor` that writes it instead: it finds the code, reason and parameter in the `RestErrorProperties` exchange properties, and may change the status. A name that is not registered stops the start. In Route-XML: ```xml ``` ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new HttpConnectionFactory { AuthScheme = HttpAuthScheme.Bearer, AuthToken = secrets.ApiToken, }); // http://api.internal/orders?connectionFactory=prod ``` A token from configuration or the environment is written `{{BILLING_TOKEN}}` in the route URI (`?authToken={{BILLING_TOKEN}}`) or in a `` value in markup: it reads the host's `IConfiguration`, then context properties, then the OS environment when there is no `IConfiguration`, once, when the route is built. In C# code read it yourself (`AuthToken = configuration["BILLING_TOKEN"]`). `${env:BILLING_TOKEN}` in `AuthToken`, Camel's spelling, reads the OS environment on every request. ## Credentials: outbound and inbound `authScheme`, `username`, `password` and `authToken` are what a **producer** sends. Written on a consumer URI they are refused at startup — naming the parameters, never their values — instead of starting an endpoint that looks protected and accepts everyone. A connection factory a consumer references for its TLS certificate may still carry producer credentials; only what the consumer URI writes itself is taken as intent. A **consumer** checks its callers with `inboundAuth` (refused on a producer the same way): | `inboundAuth` | Also needs | A refused request | |---|---|---| | `basic` | `inboundUsername`, `inboundPassword` (from configuration: `{{api.password}}`) | 401, `WWW-Authenticate: Basic realm="…", charset="UTF-8"` | | `bearer` | `tokenValidator=#name`, a registered `IHttpTokenValidator` | 401, `WWW-Authenticate: Bearer realm="…"`, with `error="invalid_token"` when the validator refused the token | ```csharp context.AddToRegistry("tokens", new MyTokenValidator()); // IHttpTokenValidator r.From("http://0.0.0.0:8080/orders?inboundAuth=bearer&tokenValidator=#tokens&inboundRealm=orders") .Process(e => { var who = ExchangePrincipal.Get(e)?.Identity?.Name; /* ... */ }); ``` A refused request never reaches the route. An accepted one reaches it with the principal on the exchange (`ExchangePrincipal.Get`) and **without** the `Authorization` header, so a route that logs or forwards its headers does not carry the credentials on. Basic compares both halves in constant time. `inboundRealm` (default `redb`) is the realm of the challenge. A half-declared check — credentials without `inboundAuth`, `basic` without a password, `bearer` without a validator, an unregistered validator name — stops the start. **Boundary.** The connector does not read tokens. JWT parsing, signing keys and their rotation, audiences, scopes and roles belong to the identity provider's library (redb.Identity, or any OpenID Connect client), plugged in through `IHttpTokenValidator`; access policies beyond "who is this" belong to the route. Do not add a token parser here. `Rest(...)` takes the same check for every route of the declaration (`RestOptions.InboundAuth`, `InboundUsername`, `InboundPassword`, `InboundRealm`, `TokenValidator`; in Route-XML the attributes of the same names on ``). The OpenAPI document is behind it too. ## Request headers and the response A consumer puts the request's headers on the exchange and, for `inOut=true`, writes the message's headers into the response. Three rules keep a client from shaping that response: 1. **Response fields never come in.** `Set-Cookie`, `Location`, `WWW-Authenticate`, `Proxy-Authenticate`, `Authentication-Info`, `Proxy-Authentication-Info`, `Retry-After`, `Server`, `Age`, `ETag`, `Accept-Ranges` and `Vary` in a request are dropped before the exchange is built (`HttpHeaders.ResponseOnlyHeaders`). Stricter than Camel's inbound filter, which removes only its own headers: a request has no use for them. 2. **The request is not echoed.** A header still holding the value the client sent is not written back. 3. **What the route wrote goes out.** A header the route set is written even when the client sent one with the same name: a request carrying `Cache-Control` cannot remove the route's `Cache-Control: no-store`. A processor that builds a response header from a request value — copies a header, reflects a parameter — answers for that value itself: validate or encode it before writing. Writing the request's own value back under its own name is an echo and is held back by rule 2. ## Concurrency limits Kestrel executes as many handlers as requests arrive; without a limit a route has no ceiling. The admission limit caps concurrent pipeline executions per endpoint and sheds the overflow BEFORE any pipeline work (load shedding, not backpressure): | Parameter | Default | Description | |---|---|---| | `maxConcurrentRequests` | `0` (unlimited) | Max concurrent pipeline executions | | `requestQueueLimit` | `0` | Requests over the limit that WAIT (FIFO) instead of being rejected | | `rejectStatusCode` | `429` | Status for a shed request | | `retryAfterSeconds` | `1` | `Retry-After` header value; `0` = do not send | A shed request is answered before an exchange exists: it appears in the endpoint's `Rejected` counter, not in `MessagesIn` or `Errors`. The limit is strictly per endpoint — other routes on the same listener keep their own budget. For "slow down but do not drop" semantics use `.Threads(n)` in the route instead; the two compose (the limit sheds at the door, Threads paces inside). ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`): - **Consumer.** One `Server` span per request, named `{method} {path}`, over the whole request, refused ones included. Its parent is the host's ASP.NET Core span when the application instruments ASP.NET Core, otherwise the caller's `traceparent`; without one it is a root. The caller's baggage is back on it, and the route's spans are its children. It carries `redb.route.endpoint` and `http.response.status_code`, and is an error for a 5xx. - **Producer.** One `Client` span per call, named `HTTP {method}`, with `http.response.status_code`; an error for a 4xx, a 5xx or a failed call. The request carries the context of this span: a `traceparent` the header bridge copied from an incoming request is replaced, as it names the previous hop. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. A context that came in still goes out. Path: redb-route/redb.Route.Http/Rest/OpenApiDocumentDefinition.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/Rest/OpenApiDocumentDefinition.cs ---- using System.Collections; using System.Text.Json; using System.Text.Json.Nodes; using redb.Route.Abstractions; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Http.Rest; /// /// Serves the OpenAPI 3.0.3 document of a : paths and operations from the /// verbs, path parameters from the templates, request / response schemas from Type<T>() / /// OutType<T>() (camelCase properties, shared types under components/schemas). /// Built on first request from the declarations as they are at that moment. /// public sealed class OpenApiDocumentDefinition : ProcessorDefinition { private readonly RestDefinition _rest; private readonly Lazy _document; internal OpenApiDocumentDefinition(RestDefinition rest) { _rest = rest; _document = new Lazy(() => JsonSerializer.SerializeToUtf8Bytes(Build(_rest), new JsonSerializerOptions { WriteIndented = true })); } /// public override IProcessor CreateProcessor(IRouteContext context) => new DelegateProcessor(exchange => { exchange.In.Body = _document.Value; exchange.In.ContentType = "application/json"; exchange.In.Headers[HttpHeaders.ResponseContentType] = "application/json"; }); /// Builds the document as a JSON tree (also used by tests and tooling). public static JsonObject Build(RestDefinition rest) { var schemas = new JsonObject(); var paths = new JsonObject(); foreach (var group in rest.Verbs.GroupBy(v => v.FullPath)) { var item = new JsonObject(); foreach (var verb in group) item[verb.Method.ToLowerInvariant()] = Operation(verb, rest.Options, schemas); paths[group.Key] = item; } return new JsonObject { ["openapi"] = "3.0.3", ["info"] = new JsonObject { ["title"] = rest.Options.Title, ["version"] = rest.Options.Version }, ["paths"] = paths, ["components"] = new JsonObject { ["schemas"] = schemas }, }; } private static JsonObject Operation(RestVerbDefinition verb, RestOptions options, JsonObject schemas) { var operation = new JsonObject { ["operationId"] = verb.RouteId ?? $"{verb.Method.ToLowerInvariant()}{verb.FullPath.Replace("/", "_").Replace("{", "").Replace("}", "")}", }; if (verb.Summary is not null) operation["summary"] = verb.Summary; var parameters = new JsonArray(); // Template segments first, typed by their declaration when there is one; then the declared // query and header parameters in declaration order. foreach (var name in verb.PathParameters) { var declared = verb.Parameters.FirstOrDefault(p => p.Type == RestParamType.Path && p.Name == name); parameters.Add(Parameter(declared ?? new RestParamDefinition(name, RestParamType.Path, true, RestParamDataType.String, null))); } foreach (var declared in verb.Parameters.Where(p => p.Type != RestParamType.Path)) parameters.Add(Parameter(declared)); if (parameters.Count > 0) operation["parameters"] = parameters; var consumes = verb.EffectiveConsumes(options); if (verb.RequestType is not null || consumes is not null) { var content = new JsonObject(); var media = new JsonObject(); if (verb.RequestType is not null) media["schema"] = SchemaRef(verb.RequestType, schemas); content[consumes ?? "application/json"] = media; operation["requestBody"] = new JsonObject { ["required"] = true, ["content"] = content }; } var ok = new JsonObject { ["description"] = "OK" }; var produces = verb.EffectiveProduces(options); if (verb.ResponseType is not null || produces is not null) { var media = new JsonObject(); if (verb.ResponseType is not null) media["schema"] = SchemaRef(verb.ResponseType, schemas); ok["content"] = new JsonObject { [produces ?? "application/json"] = media }; } operation["responses"] = new JsonObject { ["200"] = ok }; return operation; } private static JsonObject Parameter(RestParamDefinition parameter) { var node = new JsonObject { ["name"] = parameter.Name, ["in"] = parameter.Type switch { RestParamType.Path => "path", RestParamType.Query => "query", _ => "header", }, ["required"] = parameter.Required, ["schema"] = new JsonObject { ["type"] = parameter.DataType switch { RestParamDataType.Integer => "integer", RestParamDataType.Number => "number", RestParamDataType.Boolean => "boolean", _ => "string", }, }, }; if (parameter.Description is not null) node["description"] = parameter.Description; return node; } private static JsonNode SchemaRef(Type type, JsonObject schemas) { var inline = Primitive(type); if (inline is not null) return inline; if (type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(type)) { var element = type.IsArray ? type.GetElementType()! : type.GetGenericArguments().FirstOrDefault() ?? typeof(object); return new JsonObject { ["type"] = "array", ["items"] = SchemaRef(element, schemas) }; } var name = SchemaName(type, schemas); if (!schemas.ContainsKey(name)) { var properties = new JsonObject(); // Registered first, so cycles resolve to the $ref; x-clr-type lets a later type with the same short name get its own component. schemas[name] = new JsonObject { ["type"] = "object", ["properties"] = properties, ["x-clr-type"] = type.FullName ?? type.Name }; foreach (var property in type.GetProperties().Where(p => p.CanRead && p.GetIndexParameters().Length == 0)) properties[JsonNamingPolicy.CamelCase.ConvertName(property.Name)] = SchemaRef(property.PropertyType, schemas); } return new JsonObject { ["$ref"] = $"#/components/schemas/{name}" }; } /// /// Component name for a type: its short name, unless another type already holds it, then the /// namespace-qualified name, then a numbered one (V1.Order and V2.Order in one /// document must not share a schema). /// private static string SchemaName(Type type, JsonObject schemas) { var full = type.FullName ?? type.Name; var shortName = type.Name; var backtick = shortName.IndexOf('`'); if (backtick > 0) shortName = shortName[..backtick]; var qualified = new string(full.Select(c => char.IsLetterOrDigit(c) || c == '_' || c == '.' ? c : '_').ToArray()); foreach (var candidate in new[] { shortName, qualified }) if (IsFreeOrOwn(candidate)) return candidate; for (var i = 2; ; i++) if (IsFreeOrOwn($"{shortName}_{i}")) return $"{shortName}_{i}"; bool IsFreeOrOwn(string candidate) => schemas[candidate] is not JsonObject existing || existing["x-clr-type"]?.GetValue() == full; } private static JsonObject? Primitive(Type type) { type = Nullable.GetUnderlyingType(type) ?? type; if (type == typeof(string) || type == typeof(char) || type == typeof(Guid)) return new JsonObject { ["type"] = "string" }; if (type == typeof(bool)) return new JsonObject { ["type"] = "boolean" }; if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte)) return new JsonObject { ["type"] = "integer" }; if (type == typeof(decimal) || type == typeof(double) || type == typeof(float)) return new JsonObject { ["type"] = "number" }; if (type == typeof(DateTime) || type == typeof(DateTimeOffset)) return new JsonObject { ["type"] = "string", ["format"] = "date-time" }; if (type == typeof(object)) return new JsonObject(); if (type.IsEnum) return new JsonObject { ["type"] = "string", ["enum"] = new JsonArray(Enum.GetNames(type).Select(n => (JsonNode)n).ToArray()) }; return null; } } Path: redb-route/redb.Route.Http/Rest/RestDefinition.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/Rest/RestDefinition.cs ---- using System.Text.RegularExpressions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Http.Rest; /// /// REST DSL (Apache Camel rest() parity) on top of the HTTP consumer and the shared Kestrel host: /// every verb becomes an ordinary route From("http://host:port/base/path?methods=GET&inOut=true"), /// so path templates, method dispatch (405), CORS, TLS and everything else stay where they already are. /// The DSL adds the declarative layer: path parameters as header.id, query as header.query.page, /// Consumes / Produces with 415 on mismatch, JSON binding to CLR types, and an OpenAPI 3.0 /// document generated from the declarations. /// /// /// this.Rest("/api/orders", o => o.Port = 8080) /// .Get("/{id}").To("direct:get-order") /// .Post().Consumes("application/json").Type<Order>().To("direct:create-order") /// .Put("/{id}/status").To("direct:set-status") /// .Delete("/{id}").To("direct:cancel-order"); /// /// /// public sealed class RestDefinition { private static readonly Regex PathParameter = new(@"\{(\w+)\}", RegexOptions.Compiled); private readonly RouteBuilder _builder; private readonly List _verbs = []; private bool _openApiRegistered; internal RestDefinition(RouteBuilder builder, string basePath, RestOptions options) { _builder = builder; BasePath = "/" + basePath.Trim('/'); Options = options; } /// Common path prefix of the verbs (/api/orders). public string BasePath { get; } /// Settings of this declaration. public RestOptions Options { get; } /// Verbs declared so far (completed with To / Route). public IReadOnlyList Verbs => _verbs; /// Declares a GET operation. public RestVerbDefinition Get(string path = "") => new(this, "GET", path); /// Declares a POST operation. public RestVerbDefinition Post(string path = "") => new(this, "POST", path); /// Declares a PUT operation. public RestVerbDefinition Put(string path = "") => new(this, "PUT", path); /// Declares a DELETE operation. public RestVerbDefinition Delete(string path = "") => new(this, "DELETE", path); /// Declares a PATCH operation. public RestVerbDefinition Patch(string path = "") => new(this, "PATCH", path); /// Declares a HEAD operation. public RestVerbDefinition Head(string path = "") => new(this, "HEAD", path); /// Creates the HTTP route of a finished verb; returns the route so inline steps can follow. internal IRouteDefinition Complete(RestVerbDefinition verb) { _verbs.Add(verb); EnsureOpenApiRoute(); var key = verb.RouteId ?? $"{verb.Method} {verb.FullPath}"; var routeId = verb.RouteId ?? GeneratedId(key); var route = _builder.From(ConsumerUri(verb.FullPath, verb.Method)).RouteId(routeId); Append(route, new RestRequestDefinition(verb, Options)); if (verb.Target is not null) { route.To(verb.Target); Append(route, new RestResponseDefinition(verb, Options)); return route; } // Inline steps live in their own direct route, so the response step can still run after them. // The name carries a fingerprint (GeneratedId): sanitizing alone maps "/{id}" and "/id" to the // same text, and a direct endpoint registered twice silently keeps the last handler. var inner = $"direct://{GeneratedId(key)}"; route.To(inner); Append(route, new RestResponseDefinition(verb, Options)); return _builder.From(inner).RouteId(routeId + "-handler"); } /// Path the OpenAPI document is served at ( or {basePath}/openapi.json). public string OpenApiPath => Options.OpenApiPath ?? JoinPath(BasePath, "openapi.json"); private void EnsureOpenApiRoute() { if (_openApiRegistered || !Options.OpenApi) return; _openApiRegistered = true; var route = _builder.From(ConsumerUri(OpenApiPath, "GET")).RouteId(GeneratedId($"openapi {BasePath}")); Append(route, new OpenApiDocumentDefinition(this)); } private string ConsumerUri(string path, string method) { var uri = new System.Text.StringBuilder($"http://{Options.Host}:{Options.Port}{path}?methods={method}&inOut=true"); void Add(string key, string? value) { if (value is not null) uri.Append('&').Append(key).Append('=').Append(Uri.EscapeDataString(value)); } if (Options.InboundAuth != HttpAuthScheme.None) Add("inboundAuth", Options.InboundAuth.ToString().ToLowerInvariant()); Add("inboundUsername", Options.InboundUsername); Add("inboundPassword", Options.InboundPassword); Add("inboundRealm", Options.InboundRealm); Add("tokenValidator", Options.TokenValidator); if (!string.IsNullOrWhiteSpace(Options.ExtraConsumerOptions)) uri.Append('&').Append(Options.ExtraConsumerOptions.TrimStart('&')); return uri.ToString(); } private static void Append(IRouteDefinition route, IProcessorDefinition step) { step.Parent = route; route.Outputs.Add(step); } /// /// A generated route id: rest-GET-api-orders-id-1a2b3c4d. It carries no '/' and no space, because the worker /// API and the dashboard address a route by one path segment. The fingerprint keeps /{id} and /id /// apart, which sanitizing alone maps to the same text, and it is the same in every process, so the id survives a /// restart. /// internal static string GeneratedId(string key) => $"rest-{Sanitize(key)}-{Fingerprint(key)}"; private static string Sanitize(string routeId) => Regex.Replace(routeId, @"[^A-Za-z0-9_.-]+", "-").Trim('-'); /// Eight hex digits of the route id's SHA-256: stable across processes, distinct for ids that sanitize alike. private static string Fingerprint(string routeId) => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(routeId)))[..8].ToLowerInvariant(); internal static string JoinPath(string basePath, string path) { var tail = path.Trim('/'); return tail.Length == 0 ? basePath : $"{basePath.TrimEnd('/')}/{tail}"; } internal static IReadOnlyList PathParameterNames(string template) => PathParameter.Matches(template).Select(m => m.Groups[1].Value).ToList(); } Path: redb-route/redb.Route.Http/Rest/RestErrorProperties.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/Rest/RestErrorProperties.cs ---- namespace redb.Route.Http.Rest; /// /// Exchange properties the REST request step sets before it hands a refused request to the error /// handler named by . The handler writes the body; the status /// code is already in and may be changed by it. /// public static class RestErrorProperties { /// Status code of the refusal (int): 400, 406 or 415. public const string Code = "redbRest.ErrorCode"; /// Human-readable reason (string); the default body is this text. public const string Reason = "redbRest.ErrorReason"; /// Name of the offending parameter (string); set for 400 only. public const string Parameter = "redbRest.ErrorParameter"; } Path: redb-route/redb.Route.Http/Rest/RestOptions.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/Rest/RestOptions.cs ---- namespace redb.Route.Http.Rest; /// How request and response bodies are bound to CLR types by the REST DSL. public enum RestBindingMode { /// Bodies stay as the HTTP consumer delivers them (byte[] in, whatever the route leaves out). Off, /// A verb with Type<T>() gets its request body unmarshalled from JSON to T; a non-text response body is marshalled to JSON. Json, } /// /// Settings of one Rest(...) declaration: where the routes listen, default binding and media /// types, and the OpenAPI document. /// public sealed class RestOptions { /// Bind host of the shared HTTP server. Default 0.0.0.0. public string Host { get; set; } = "0.0.0.0"; /// Bind port. Default 8080. Several Rest(...) declarations may share a port. public int Port { get; set; } = 8080; /// Default binding mode of the verbs; a verb can override it. Default . public RestBindingMode BindingMode { get; set; } = RestBindingMode.Off; /// Default request media type expected by the verbs (application/json); a verb can override it. public string? Consumes { get; set; } /// Default response media type of the verbs; a verb can override it. public string? Produces { get; set; } /// Serve the generated OpenAPI 3.0 document. Default true. public bool OpenApi { get; set; } = true; /// Path of the OpenAPI document on the same host and port; null = {basePath}/openapi.json, so several declarations on one port do not collide. public string? OpenApiPath { get; set; } /// OpenAPI info.title. public string Title { get; set; } = "redb.Route API"; /// OpenAPI info.version. public string Version { get; set; } = "1.0.0"; /// /// Validate client requests before the route runs, like Camel's clientRequestValidation: /// an Accept that excludes the produced type is answered with 406, a missing required or /// non-convertible declared parameter with 400. A verb can override it. Default false: /// parameters declared for the OpenAPI document alone never start refusing requests. /// The 415 check of Consumes runs either way. /// public bool ClientRequestValidation { get; set; } /// /// Registry name of an that writes the body of a refused /// request (415, 406, 400), #name or name. It finds the code, reason and parameter in /// . A name that is not registered fails when the routes start. /// null = the reason as text/plain. /// public string? ErrorHandler { get; set; } /// /// How the callers of every route of this declaration prove who they are (the http: consumer's inboundAuth): /// Basic with / , Bearer with the registered /// validator named by . A refused request gets 401 before the route runs. The OpenAPI /// document is behind the same check. Default None. /// public HttpAuthScheme InboundAuth { get; set; } = HttpAuthScheme.None; /// User name InboundAuth=Basic accepts. public string? InboundUsername { get; set; } /// Password InboundAuth=Basic accepts; take it from configuration ({{…}}). public string? InboundPassword { get; set; } /// Realm named in WWW-Authenticate; null = the consumer's default. public string? InboundRealm { get; set; } /// Registry name of the for InboundAuth=Bearer. public string? TokenValidator { get; set; } /// Extra query parameters appended to every generated consumer URI ("ssl=true&sslCertPath=..."), for options the DSL does not model. public string? ExtraConsumerOptions { get; set; } } Path: redb-route/redb.Route.Http/Rest/RestParamDefinition.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/Rest/RestParamDefinition.cs ---- namespace redb.Route.Http.Rest; /// Where a declared REST parameter comes from. public enum RestParamType { /// A {name} segment of the path template. Always required. Path, /// A query string parameter. Query, /// A request header. Header, } /// The value type of a declared REST parameter, as OpenAPI names it. public enum RestParamDataType { /// Any text. String, /// A whole number (invariant culture, optional sign). Integer, /// A decimal number (invariant culture). Number, /// true or false. Boolean, } /// /// One parameter declared on a REST verb with Param(...): described in the OpenAPI document /// always, enforced only when client request validation is on. /// /// Parameter name: the template segment, the query key or the header name. /// Where the parameter comes from. /// A missing required parameter is answered with 400. /// A value that does not convert to this type is answered with 400. /// OpenAPI description. public sealed record RestParamDefinition( string Name, RestParamType Type, bool Required, RestParamDataType DataType, string? Description); Path: redb-route/redb.Route.Http/Rest/RestRequestDefinition.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/Rest/RestRequestDefinition.cs ---- using System.Globalization; using redb.Route.Abstractions; using redb.Route.Definitions; using redb.Route.Extensions; using redb.Route.Processors; namespace redb.Route.Http.Rest; /// /// First step of a REST route: path parameters become plain headers (header.id), query parameters /// header.query.*; a request whose Content-Type does not match Consumes is answered /// with 415 and stopped; with client request validation on, an Accept that excludes /// Produces is answered with 406 and a missing or non-convertible declared parameter with 400; /// under JSON binding a declared request type is unmarshalled. /// public sealed class RestRequestDefinition : ProcessorDefinition { private readonly RestVerbDefinition _verb; private readonly RestOptions _options; internal RestRequestDefinition(RestVerbDefinition verb, RestOptions options) { _verb = verb; _options = options; } /// public override IProcessor CreateProcessor(IRouteContext context) { var consumes = _verb.EffectiveConsumes(_options); var produces = _verb.EffectiveProduces(_options); var validate = _verb.EffectiveValidation(_options); var parameters = _verb.Parameters.ToArray(); var unmarshal = _verb.EffectiveBinding(_options) == RestBindingMode.Json && _verb.RequestType is not null ? context.GetService()?.GetSerializer(consumes ?? "application/json") : null; var requestType = _verb.RequestType; // Resolved here, while the routes are being built, so a misspelled name stops the start // instead of turning the first refused request into a 500. var errorHandler = _options.ErrorHandler is { } handlerName ? context.GetRequiredFromRegistry(handlerName.StartsWith('#') ? handlerName[1..] : handlerName) : null; return new DelegateProcessor(async (exchange, ct) => { var headers = exchange.In.Headers; var snapshot = headers.ToList(); // Parameters come from the request line only. A client header that happens to be named // "query.role" must not survive as if it had come from the query string, so the plain // query.* names are cleared before the real parameters are written. foreach (var (key, _) in snapshot) if (key.StartsWith("query.", StringComparison.OrdinalIgnoreCase)) headers.Remove(key); foreach (var (key, value) in snapshot) { if (key.StartsWith(HttpHeaders.RouteParamPrefix, StringComparison.Ordinal)) headers[key[HttpHeaders.RouteParamPrefix.Length..]] = value; else if (key.StartsWith(HttpHeaders.QueryParamPrefix, StringComparison.Ordinal)) headers["query." + key[HttpHeaders.QueryParamPrefix.Length..]] = value; } if (consumes is not null && exchange.In.Body is not null && !MediaTypeMatches(exchange.In.ContentType, consumes)) { await Refuse(exchange, 415, $"Unsupported Media Type: expected {consumes}", null, errorHandler, ct).ConfigureAwait(false); return; } if (validate) { if (produces is not null && !Accepts(headers.TryGetValue("Accept", out var accept) ? accept?.ToString() : null, produces)) { await Refuse(exchange, 406, $"Not Acceptable: this operation produces {produces}", null, errorHandler, ct).ConfigureAwait(false); return; } foreach (var parameter in parameters) { if (CheckParameter(exchange, parameter) is { } reason) { await Refuse(exchange, 400, reason, parameter.Name, errorHandler, ct).ConfigureAwait(false); return; } } } if (unmarshal is not null && requestType is not null && exchange.In.Body is byte[] bytes && bytes.Length > 0) exchange.In.Body = unmarshal.Deserialize(bytes, requestType); }); } private static async Task Refuse(IExchange exchange, int code, string reason, string? parameter, IProcessor? errorHandler, CancellationToken ct) { exchange.In.Headers[HttpHeaders.ResponseCode] = code; if (errorHandler is null) { exchange.In.Headers[HttpHeaders.ResponseContentType] = "text/plain"; exchange.In.ContentType = "text/plain"; exchange.In.Body = reason; } else { exchange.In.Body = null; exchange.Properties[RestErrorProperties.Code] = code; exchange.Properties[RestErrorProperties.Reason] = reason; if (parameter is not null) exchange.Properties[RestErrorProperties.Parameter] = parameter; await errorHandler.Process(exchange, ct).ConfigureAwait(false); } exchange.Stop(); } /// The reason a declared parameter refuses the request, or null when it is fine. private static string? CheckParameter(IExchange exchange, RestParamDefinition parameter) { var label = parameter.Type switch { RestParamType.Path => "Path parameter", RestParamType.Query => "Query parameter", _ => "Header", }; var raw = RawValue(exchange, parameter); if (raw is null) return parameter.Required ? $"{label} '{parameter.Name}' is required" : null; if (parameter.DataType == RestParamDataType.String) return null; // The HTTP consumer joins repeated query keys with "," and repeated headers with ", "; // every occurrence has to convert. foreach (var piece in raw.Split(',')) if (!Converts(piece.Trim(), parameter.DataType)) return $"{label} '{parameter.Name}' must be {Article(parameter.DataType)}, got '{raw}'"; return null; } private static string? RawValue(IExchange exchange, RestParamDefinition parameter) { var headers = exchange.In.Headers; switch (parameter.Type) { case RestParamType.Path: return headers.TryGetValue(HttpHeaders.RouteParamPrefix + parameter.Name, out var path) ? path?.ToString() : null; case RestParamType.Query: return headers.TryGetValue(HttpHeaders.QueryParamPrefix + parameter.Name, out var query) ? query?.ToString() : null; default: // Only a header the client actually sent counts: path parameters and the query.* names // are written into the same header map by this step. var sent = exchange.Properties.TryGetValue("redbHttp.RequestHeaderNames", out var names) && names is ISet set && set.Contains(parameter.Name); return sent && headers.TryGetValue(parameter.Name, out var header) ? header?.ToString() : null; } } private static bool Converts(string value, RestParamDataType type) => type switch { RestParamDataType.Integer => long.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out _), RestParamDataType.Number => double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) && double.IsFinite(number), RestParamDataType.Boolean => value.Equals("true", StringComparison.OrdinalIgnoreCase) || value.Equals("false", StringComparison.OrdinalIgnoreCase), _ => true, }; private static string Article(RestParamDataType type) => type switch { RestParamDataType.Integer => "an integer", RestParamDataType.Number => "a number", RestParamDataType.Boolean => "true or false", _ => "a string", }; /// /// Whether an Accept header admits (RFC 9110 §12.5.1): no header /// admits everything; otherwise the most specific matching range decides (type/subtype over /// type/* over */*) and q=0 means "not acceptable". A range whose q does /// not parse admits nothing. /// internal static bool Accepts(string? accept, string produces) { if (string.IsNullOrWhiteSpace(accept)) return true; var produced = produces.Split(';')[0].Trim(); var slash = produced.IndexOf('/'); var producedType = slash > 0 ? produced[..slash] : produced; var bestSpecificity = -1; var bestQuality = 0.0; foreach (var part in accept.Split(',')) { var segments = part.Split(';'); var range = segments[0].Trim(); if (range.Length == 0) continue; var specificity = range == "*/*" ? 0 : range.EndsWith("/*", StringComparison.Ordinal) && string.Equals(range[..^2], producedType, StringComparison.OrdinalIgnoreCase) ? 1 : string.Equals(range, produced, StringComparison.OrdinalIgnoreCase) ? 2 : -1; if (specificity < bestSpecificity || specificity < 0) continue; var quality = 1.0; foreach (var parameter in segments.Skip(1)) { var pair = parameter.Split('=', 2); if (pair.Length == 2 && pair[0].Trim().Equals("q", StringComparison.OrdinalIgnoreCase) && !double.TryParse(pair[1].Trim(), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out quality)) quality = 0; } // Equal specificity (the same range written twice): the lower weight wins, so an explicit // refusal is never overridden by a repetition. if (specificity > bestSpecificity || quality < bestQuality) { bestSpecificity = specificity; bestQuality = quality; } } return bestSpecificity >= 0 && bestQuality > 0; } internal static bool MediaTypeMatches(string? actual, string expected) { if (string.IsNullOrWhiteSpace(actual)) return false; var actualBase = actual.Split(';')[0].Trim(); var expectedBase = expected.Split(';')[0].Trim(); return string.Equals(actualBase, expectedBase, StringComparison.OrdinalIgnoreCase) || (expectedBase.EndsWith("/json", StringComparison.OrdinalIgnoreCase) && actualBase.EndsWith("+json", StringComparison.OrdinalIgnoreCase)) || (expectedBase.EndsWith("/xml", StringComparison.OrdinalIgnoreCase) && actualBase.EndsWith("+xml", StringComparison.OrdinalIgnoreCase)); } } Path: redb-route/redb.Route.Http/Rest/RestResponseDefinition.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/Rest/RestResponseDefinition.cs ---- using redb.Route.Abstractions; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Http.Rest; /// /// Last step of a REST route: writes the Produces media type, marshals a CLR object body to /// JSON under JSON binding, and answers 204 when the route left no body and set no status. /// The status code itself is the HTTP consumer's contract: header redbHttp.ResponseCode. /// public sealed class RestResponseDefinition : ProcessorDefinition { private readonly RestVerbDefinition _verb; private readonly RestOptions _options; internal RestResponseDefinition(RestVerbDefinition verb, RestOptions options) { _verb = verb; _options = options; } /// public override IProcessor CreateProcessor(IRouteContext context) { var produces = _verb.EffectiveProduces(_options); var json = _verb.EffectiveBinding(_options) == RestBindingMode.Json ? context.GetService()?.GetSerializer(produces ?? "application/json") : null; return new DelegateProcessor(exchange => { var message = exchange.Out ?? exchange.In; if (exchange.IsStopped) return; if (json is not null && message.Body is not (null or string or byte[] or Stream)) { message.Body = json.Serialize(message.Body); message.ContentType = json.ContentType; } if (produces is not null && !message.Headers.ContainsKey(HttpHeaders.ResponseContentType)) message.Headers[HttpHeaders.ResponseContentType] = produces; if (message.Body is null && !message.Headers.ContainsKey(HttpHeaders.ResponseCode)) message.Headers[HttpHeaders.ResponseCode] = 204; }); } } Path: redb-route/redb.Route.Http/Rest/RestRouteBuilderExtensions.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/Rest/RestRouteBuilderExtensions.cs ---- using redb.Route.Core; namespace redb.Route.Http.Rest; /// Entry point of the REST DSL: this.Rest("/api/orders", o => o.Port = 8080) inside a . public static class RestRouteBuilderExtensions { /// /// Starts a REST declaration under . Each verb finished with To(...) /// or Route() becomes an HTTP route on the shared Kestrel host; an OpenAPI document is served /// at (default {basePath}/openapi.json). /// public static RestDefinition Rest(this RouteBuilder builder, string basePath, Action? configure = null) { ArgumentNullException.ThrowIfNull(builder); ArgumentException.ThrowIfNullOrWhiteSpace(basePath); var options = new RestOptions(); configure?.Invoke(options); return new RestDefinition(builder, basePath, options); } } Path: redb-route/redb.Route.Http/Rest/RestVerbDefinition.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/Rest/RestVerbDefinition.cs ---- using redb.Route.Abstractions; namespace redb.Route.Http.Rest; /// /// One operation of a : method + path template, media types, binding /// types and description. Finished with (send to an endpoint) or /// (write the steps inline); both create the underlying HTTP route. /// public sealed class RestVerbDefinition { private readonly RestDefinition _rest; internal RestVerbDefinition(RestDefinition rest, string method, string path) { _rest = rest; Method = method; Path = path; } /// HTTP method (GET, POST, …). public string Method { get; } /// Path template relative to the (/{id}, /{id}/status, or empty). public string Path { get; } /// Full path template (/api/orders/{id}). public string FullPath => RestDefinition.JoinPath(_rest.BasePath, Path); /// Expected request media type; a request with another Content-Type is answered with 415. public string? ConsumesType { get; private set; } /// Response media type written to the reply. public string? ProducesType { get; private set; } /// Binding mode override for this verb. public RestBindingMode? Binding { get; private set; } /// CLR type of the request body (JSON binding and OpenAPI). public Type? RequestType { get; private set; } /// CLR type of the response body (OpenAPI). public Type? ResponseType { get; private set; } /// Human description → OpenAPI summary. public string? Summary { get; private set; } /// /// Route id; default rest-METHOD-full-path-1a2b3c4d (no '/' and no space, stable across restarts). Also the /// OpenAPI operationId. /// public string? RouteId { get; private set; } /// Target endpoint set by ; null for inline routes. public string? Target { get; private set; } /// Path parameter names in declaration order ({id} → id). public IReadOnlyList PathParameters => RestDefinition.PathParameterNames(FullPath); /// Parameters declared with , in declaration order. public IReadOnlyList Parameters => _parameters; /// Client request validation override for this verb; null = the declaration's option. public bool? Validation { get; private set; } private readonly List _parameters = []; /// /// Declares a parameter: described in OpenAPI, and when client request validation is on, a missing /// required one or a value that does not convert to is answered with 400. /// A path parameter must be a segment of the template and is always required, so /// left null means required for a path parameter and optional /// for the others. /// public RestVerbDefinition Param(string name, RestParamType type = RestParamType.Query, bool? required = null, RestParamDataType dataType = RestParamDataType.String, string? description = null) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (type == RestParamType.Path) { if (!PathParameters.Contains(name, StringComparer.Ordinal)) throw new ArgumentException( $"Path parameter '{name}' is not a segment of '{FullPath}'.", nameof(name)); if (required == false) throw new ArgumentException( $"Path parameter '{name}' cannot be optional: a path parameter is always required.", nameof(required)); } var comparer = type == RestParamType.Header ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; if (_parameters.Any(p => p.Type == type && comparer.Equals(p.Name, name))) throw new ArgumentException($"{type} parameter '{name}' is declared twice on {Method} {FullPath}.", nameof(name)); _parameters.Add(new RestParamDefinition(name, type, required ?? type == RestParamType.Path, dataType, description)); return this; } /// Switches client request validation on or off for this verb (see ). public RestVerbDefinition ClientRequestValidation(bool enabled = true) { Validation = enabled; return this; } /// Request media type this operation accepts. public RestVerbDefinition Consumes(string contentType) { ConsumesType = Required(contentType); return this; } /// Response media type this operation produces. public RestVerbDefinition Produces(string contentType) { ProducesType = Required(contentType); return this; } /// Binding mode for this operation. public RestVerbDefinition BindingMode(RestBindingMode mode) { Binding = mode; return this; } /// Request body type: unmarshalled under JSON binding, described in OpenAPI. public RestVerbDefinition Type() { RequestType = typeof(T); return this; } /// Response body type, described in OpenAPI. public RestVerbDefinition OutType() { ResponseType = typeof(T); return this; } /// Human description (OpenAPI summary). public RestVerbDefinition Description(string summary) { Summary = Required(summary); return this; } /// Route id / OpenAPI operationId. public RestVerbDefinition Id(string routeId) { RouteId = Required(routeId); return this; } /// Sends the request to (usually direct:...) and returns to the REST declaration for the next verb. public RestDefinition To(string uri) { Target = Required(uri); _rest.Complete(this); return _rest; } /// Handles the request with steps written inline; returns the route to add them to. public IRouteDefinition Route() => _rest.Complete(this); internal RestBindingMode EffectiveBinding(RestOptions options) => Binding ?? options.BindingMode; internal string? EffectiveConsumes(RestOptions options) => ConsumesType ?? options.Consumes; internal string? EffectiveProduces(RestOptions options) => ProducesType ?? options.Produces; internal bool EffectiveValidation(RestOptions options) => Validation ?? options.ClientRequestValidation; private static string Required(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); return value; } } Path: redb-route/redb.Route.Http/Rest/RestXmlContribution.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/Rest/RestXmlContribution.cs ---- using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Http.Rest; /// /// The <rest> element (the REST DSL of this package): a /// container-level contribution — it lives beside <route> and applies to the /// route BUILDER, spawning the HTTP consumer routes the fluent Rest(basePath, …) would. /// A verb child handles its request either with to= or with inline steps — one of the /// two, never both. /// public sealed class RestXmlContribution : IXmlTopLevelContribution { private static readonly string[] VerbNames = ["get", "post", "put", "delete", "patch", "head"]; /// public string Name => "rest"; /// public XmlElementKind Kind => XmlElementKind.TopLevel; /// public IReadOnlyList GeneratedUsings => ["redb.Route.Http", "redb.Route.Http.Rest"]; /// public ElementSpec Spec => new(Name, Kind, [ new AttributeSpec("path", AttributeType.String, Required: true), new AttributeSpec("host", AttributeType.String), new AttributeSpec("port", AttributeType.Int), new AttributeSpec("bindingMode", AttributeType.Enum, EnumValues: ["off", "json"]), new AttributeSpec("consumes", AttributeType.String), new AttributeSpec("produces", AttributeType.String), new AttributeSpec("openApi", AttributeType.Bool), new AttributeSpec("openApiPath", AttributeType.String), new AttributeSpec("title", AttributeType.String), new AttributeSpec("version", AttributeType.String), new AttributeSpec("clientRequestValidation", AttributeType.Bool), new AttributeSpec("errorHandler", AttributeType.String), new AttributeSpec("inboundAuth", AttributeType.Enum, EnumValues: ["none", "basic", "bearer"]), new AttributeSpec("inboundUsername", AttributeType.String), new AttributeSpec("inboundPassword", AttributeType.String), new AttributeSpec("inboundRealm", AttributeType.String), new AttributeSpec("tokenValidator", AttributeType.String), ], [.. VerbNames.Select(verb => new ElementSpec(verb, XmlElementKind.ConfigChild, [ new AttributeSpec("path", AttributeType.String), new AttributeSpec("to", AttributeType.Uri), new AttributeSpec("consumes", AttributeType.String), new AttributeSpec("produces", AttributeType.String), new AttributeSpec("type", AttributeType.TypeName), new AttributeSpec("outType", AttributeType.TypeName), new AttributeSpec("bindingMode", AttributeType.Enum, EnumValues: ["off", "json"]), new AttributeSpec("clientRequestValidation", AttributeType.Bool), ], [ParamSpec], AllowsSteps: true))]); private static readonly ElementSpec ParamSpec = new("param", XmlElementKind.ConfigChild, [ new AttributeSpec("name", AttributeType.String, Required: true), new AttributeSpec("type", AttributeType.Enum, EnumValues: ["path", "query", "header"]), new AttributeSpec("required", AttributeType.Bool), new AttributeSpec("dataType", AttributeType.Enum, EnumValues: ["string", "integer", "number", "boolean"]), new AttributeSpec("description", AttributeType.String), ], []); /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { context.AddError(element, " is a container-level element — put it beside , not inside one."); return current; } /// public void ApplyTopLevel(XElement element, RouteBuilder builder, XmlParseContext context) { var basePath = context.RequiredAttr(element, "path"); if (basePath is null) return; var rest = builder.Rest(basePath, options => { if (context.Attr(element, "host") is { } host) options.Host = host; if (context.Convert(element, "port") is { } port) options.Port = port; if (ParseBinding(element, context) is { } binding) options.BindingMode = binding; if (context.Attr(element, "consumes") is { } consumes) options.Consumes = consumes; if (context.Attr(element, "produces") is { } produces) options.Produces = produces; if (context.Convert(element, "openApi") is { } openApi) options.OpenApi = openApi; if (context.Attr(element, "openApiPath") is { } openApiPath) options.OpenApiPath = openApiPath; if (context.Attr(element, "title") is { } title) options.Title = title; if (context.Attr(element, "version") is { } version) options.Version = version; if (context.Convert(element, "clientRequestValidation") is { } validate) options.ClientRequestValidation = validate; if (context.Attr(element, "errorHandler") is { } errorHandler) options.ErrorHandler = errorHandler; if (ParseEnum(element, "inboundAuth", context, "none, basic, bearer") is { Ok: true, Value: { } inboundAuth }) options.InboundAuth = inboundAuth; if (context.Attr(element, "inboundUsername") is { } inboundUsername) options.InboundUsername = inboundUsername; if (context.Attr(element, "inboundPassword") is { } inboundPassword) options.InboundPassword = inboundPassword; if (context.Attr(element, "inboundRealm") is { } inboundRealm) options.InboundRealm = inboundRealm; if (context.Attr(element, "tokenValidator") is { } tokenValidator) options.TokenValidator = tokenValidator; }); foreach (var child in element.Elements()) { var verbName = child.Name.LocalName; if (!VerbNames.Contains(verbName)) { context.AddError(child, $" accepts only verb children ({string.Join(", ", VerbNames)}), found <{verbName}>."); continue; } var verb = verbName switch { "get" => rest.Get(context.Attr(child, "path") ?? ""), "post" => rest.Post(context.Attr(child, "path") ?? ""), "put" => rest.Put(context.Attr(child, "path") ?? ""), "delete" => rest.Delete(context.Attr(child, "path") ?? ""), "patch" => rest.Patch(context.Attr(child, "path") ?? ""), _ => rest.Head(context.Attr(child, "path") ?? ""), }; if (context.Attr(child, "consumes") is { } consumes) verb.Consumes(consumes); if (context.Attr(child, "produces") is { } produces) verb.Produces(produces); if (ParseBinding(child, context) is { } binding) verb.BindingMode(binding); if (context.Attr(child, "id") is { Length: > 0 } id) verb.Id(id); if (context.Attr(child, "description") is { Length: > 0 } description) verb.Description(description); if (context.Convert(child, "clientRequestValidation") is { } validate) verb.ClientRequestValidation(validate); if (!ApplyGenericType(child, context, "type", typeName => Closed(nameof(RestVerbDefinition.Type), typeName, verb)) || !ApplyGenericType(child, context, "outType", typeName => Closed(nameof(RestVerbDefinition.OutType), typeName, verb))) continue; if (!ApplyParams(child, verb, context)) continue; var target = context.Attr(child, "to"); var steps = child.Elements().Where(e => !IsParam(e)).ToList(); if (target is not null && steps.Count > 0) { context.AddError(child, $"<{verbName}> handles the request with to= or with inline steps — one of the two, not both."); continue; } if (target is null && steps.Count == 0) { context.AddError(child, $"<{verbName}> needs to= or at least one inline step."); continue; } if (target is not null) { context.NoteEndpointUri(child, target); verb.To(target); } else { IRouteDefinition route = verb.Route(); foreach (var step in steps) route = context.ParseStep(step, route); } } } private static bool IsParam(XElement element) => element.Name.LocalName == "param"; /// Declares the verb's <param> children; false when one was refused. private static bool ApplyParams(XElement verbElement, RestVerbDefinition verb, XmlParseContext context) { var ok = true; foreach (var param in verbElement.Elements().Where(IsParam)) { var name = context.RequiredAttr(param, "name"); var type = ParseEnum(param, "type", context, "path, query, header"); var dataType = ParseEnum(param, "dataType", context, "string, integer, number, boolean"); if (name is null || type is { Ok: false } || dataType is { Ok: false }) { ok = false; continue; } try { verb.Param(name, type.Value ?? RestParamType.Query, context.Convert(param, "required"), dataType.Value ?? RestParamDataType.String, context.Attr(param, "description")); } catch (ArgumentException ex) { // A refused declaration is a positioned schema error, collected with the rest of the pass. context.AddError(param, ex.Message); ok = false; } } return ok; } private static (bool Ok, TEnum? Value) ParseEnum(XElement element, string attribute, XmlParseContext context, string allowed) where TEnum : struct, Enum { var value = context.Attr(element, attribute); if (value is null) return (true, null); if (value.All(char.IsLetter) && Enum.TryParse(value, ignoreCase: true, out var parsed)) return (true, parsed); context.AddError(element, $"{attribute}='{value}' is not one of: {allowed}."); return (false, null); } private static RestBindingMode? ParseBinding(XElement element, XmlParseContext context) { var value = context.Attr(element, "bindingMode"); if (value is null) return null; if (Enum.TryParse(value, ignoreCase: true, out var mode)) return mode; context.AddError(element, $"'{value}' is not a binding mode (off, json)."); return null; } /// Closes Type<T>()/OutType<T>() over an XML type name (cold path). private static bool ApplyGenericType(XElement child, XmlParseContext context, string attribute, Action apply) { var typeName = context.Attr(child, attribute); if (typeName is null) return true; var resolver = context.RouteContext.GetService() ?? Components.Bean.DefaultBeanTypeResolver.Instance; var type = resolver.Resolve(typeName); if (type is null) { context.AddError(child, $"{attribute}='{typeName}' was not found in the loaded assemblies."); return false; } apply(type); return true; } private static void Closed(string methodName, Type type, RestVerbDefinition verb) => typeof(RestVerbDefinition).GetMethod(methodName)!.MakeGenericMethod(type).Invoke(verb, null); /// public void Print(XElement element, XmlCodeWriter code) { var optionLines = new List(); void Opt(string attr, Func render) { if (element.Attribute(attr)?.Value is { } value) optionLines.Add(render(value)); } Opt("host", v => $"options.Host = {XmlCodeWriter.Str(v)};"); Opt("port", v => $"options.Port = {v};"); Opt("bindingMode", v => $"options.BindingMode = RestBindingMode.{Enum.Parse(v, true)};"); Opt("consumes", v => $"options.Consumes = {XmlCodeWriter.Str(v)};"); Opt("produces", v => $"options.Produces = {XmlCodeWriter.Str(v)};"); Opt("openApi", v => $"options.OpenApi = {XmlCodeWriter.Bool(bool.Parse(v))};"); Opt("openApiPath", v => $"options.OpenApiPath = {XmlCodeWriter.Str(v)};"); Opt("title", v => $"options.Title = {XmlCodeWriter.Str(v)};"); Opt("version", v => $"options.Version = {XmlCodeWriter.Str(v)};"); Opt("clientRequestValidation", v => $"options.ClientRequestValidation = {XmlCodeWriter.Bool(bool.Parse(v))};"); Opt("errorHandler", v => $"options.ErrorHandler = {XmlCodeWriter.Str(v)};"); Opt("inboundAuth", v => $"options.InboundAuth = HttpAuthScheme.{Enum.Parse(v, true)};"); Opt("inboundUsername", v => $"options.InboundUsername = {XmlCodeWriter.Str(v)};"); Opt("inboundPassword", v => $"options.InboundPassword = {XmlCodeWriter.Str(v)};"); Opt("inboundRealm", v => $"options.InboundRealm = {XmlCodeWriter.Str(v)};"); Opt("tokenValidator", v => $"options.TokenValidator = {XmlCodeWriter.Str(v)};"); var declaration = optionLines.Count == 0 ? $"Rest({XmlCodeWriter.Str(element.Attribute("path")?.Value ?? "")})" : $"Rest({XmlCodeWriter.Str(element.Attribute("path")?.Value ?? "")}, options => {{ {string.Join(" ", optionLines)} }})"; var rest = code.PushRoot(declaration, element, "rest"); code.PopReceiver(); foreach (var child in element.Elements().Where(c => VerbNames.Contains(c.Name.LocalName))) { var verbCall = char.ToUpperInvariant(child.Name.LocalName[0]) + child.Name.LocalName[1..]; var chain = new System.Text.StringBuilder($"{rest}.{verbCall}({XmlCodeWriter.Str(child.Attribute("path")?.Value ?? "")})"); if (child.Attribute("consumes")?.Value is { } consumes) chain.Append($".Consumes({XmlCodeWriter.Str(consumes)})"); if (child.Attribute("produces")?.Value is { } produces) chain.Append($".Produces({XmlCodeWriter.Str(produces)})"); if (child.Attribute("bindingMode")?.Value is { } binding) chain.Append($".BindingMode(RestBindingMode.{Enum.Parse(binding, true)})"); if (child.Attribute("id")?.Value is { Length: > 0 } id) chain.Append($".Id({XmlCodeWriter.Str(id)})"); if (child.Attribute("description")?.Value is { Length: > 0 } description) chain.Append($".Description({XmlCodeWriter.Str(description)})"); if (child.Attribute("type")?.Value is { } requestType) chain.Append($".Type<{TypeArg(requestType)}>()"); if (child.Attribute("outType")?.Value is { } responseType) chain.Append($".OutType<{TypeArg(responseType)}>()"); if (child.Attribute("clientRequestValidation")?.Value is { } validate) chain.Append($".ClientRequestValidation({XmlCodeWriter.Bool(bool.Parse(validate))})"); foreach (var param in child.Elements().Where(IsParam)) chain.Append(PrintParam(param)); if (child.Attribute("to")?.Value is { } target) { code.MapTo(child); code.Line($"{chain}.To({XmlCodeWriter.Str(target)});"); continue; } code.MapTo(child); var route = code.PushRoot($"{chain}.Route()", child, "handler"); foreach (var step in child.Elements().Where(e => !IsParam(e))) code.PrintStep(step); code.PopReceiver(); _ = route; } } private static string PrintParam(XElement param) { var args = new List { XmlCodeWriter.Str(param.Attribute("name")?.Value ?? "") }; if (param.Attribute("type")?.Value is { } type) args.Add($"RestParamType.{Enum.Parse(type, true)}"); if (param.Attribute("required")?.Value is { } required) args.Add($"required: {XmlCodeWriter.Bool(bool.Parse(required))}"); if (param.Attribute("dataType")?.Value is { } dataType) args.Add($"dataType: RestParamDataType.{Enum.Parse(dataType, true)}"); if (param.Attribute("description")?.Value is { } description) args.Add($"description: {XmlCodeWriter.Str(description)}"); return $".Param({string.Join(", ", args)})"; } private static string TypeArg(string typeName) { var comma = typeName.IndexOf(','); return "global::" + (comma >= 0 ? typeName[..comma] : typeName).Trim(); } } Path: redb-route/redb.Route.Http/redb.Route.Http.csproj 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/redb.Route.Http.csproj ---- redb.Route.Http HTTP transport for redb.Route ESB framework. Provides HttpClient producer and Kestrel-based consumer (webhook receiver) with CORS, auth, and streaming support. esb;messaging;http;https;webhook;kestrel;rest;redb README.md