Path: redb-route/redb.Route.As2/Fluent/As2.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.As2/Fluent/As2.cs
----
using System.Text;
namespace redb.Route.As2.Fluent;
///
/// Entry point for the AS2 fluent DSL.
///
/// // Receive server (consumer)
/// From(As2.Receive("/inbound/orders").Host("0.0.0.0").Port(4080).ConnectionFactory("walmart"))
/// .To("direct://process-edi");
///
/// // Send to partner (producer)
/// From("direct://outbound")
/// .To(As2.Send("https://partner.example.com/as2").ConnectionFactory("walmart"));
///
///
public static class As2
{
/// AS2 receive server on the given HTTP path.
public static As2Builder Receive(string path) => new(As2Mode.Receive, path);
/// AS2 async-MDN receiver on the given HTTP path (correlates receipts posted back by partners).
public static As2Builder ReceiveMdn(string path) => new(As2Mode.Receive, path) { AsMdnReceiver = true };
/// AS2 producer that POSTs to the given partner URL.
public static As2Builder Send(string url) => new(As2Mode.Send, url);
}
/// Which side of the AS2 exchange a builder produces.
internal enum As2Mode
{
/// Receive server (consumer).
Receive,
/// Send client (producer).
Send,
}
///
/// Fluent builder for AS2 endpoint URIs. Builds a string consumed by .
///
/// Receive: as2:/path?host=..&port=.. — host/port as query, the path kept intact (no first-segment
/// truncation, mirroring the Http listener fix). Send: as2[s]://host[:port]/path — HTTPS maps to the
/// as2s scheme.
///
///
public sealed class As2Builder
{
private readonly As2Mode _mode;
private readonly string _target;
private string? _host;
private int? _port;
private string? _connectionFactory;
private bool _useTls;
private string? _sslCertPath;
private string? _sslCertPassword;
private int? _maxConcurrentRequests;
private int? _requestQueueLimit;
private int? _rejectStatusCode;
private int? _retryAfterSeconds;
private long? _maxRequestBodySize;
private long? _maxDecompressedSize;
private int? _asyncMdnPoolSize;
private int? _inFlightClaimTimeout;
private int? _asyncMdnAttempts;
private int? _asyncMdnRetryDelay;
private string? _idempotentRepository;
private bool _streamBody;
private long? _maxResponseBodySize;
/// When set, this receive endpoint accepts async MDN receipts (mode=mdn).
internal bool AsMdnReceiver { get; init; }
internal As2Builder(As2Mode mode, string target)
{
_mode = mode;
_target = target ?? throw new ArgumentNullException(nameof(target));
}
/// Bind host for the receive server (consumer only).
public As2Builder Host(string host) { _host = host; return this; }
/// Listen port for the receive server (consumer only).
public As2Builder Port(int port) { _port = port; return this; }
/// Reference a named from the registry instead of inline config.
public As2Builder ConnectionFactory(string name) { _connectionFactory = name; return this; }
///
/// Serve the receive endpoint over TLS. The certificate is the one presented to the trading
/// partner on the connection — not the S/MIME key that signs the payload. Omit it here to take
/// the certificate from the named connection factory or from the host default; a TLS receiver
/// that finds none anywhere refuses to bind.
///
public As2Builder Tls(string? certPath = null, string? certPassword = null)
{
_useTls = true;
_sslCertPath = certPath;
_sslCertPassword = certPassword;
return this;
}
///
/// Admission limit (receive endpoint): at most concurrent pipeline
/// executions (default 32, 0 = unlimited); overflow beyond the FIFO (not given: 32 while
/// limits) is shed with 503 + Retry-After before any MIME/crypto work.
///
public As2Builder MaxConcurrentRequests(int max, int? queue = null)
{
_maxConcurrentRequests = max;
_requestQueueLimit = queue;
return this;
}
/// Status code of a refused request: shed, or every asynchronous MDN slot taken (default 503).
public As2Builder RejectStatusCode(int statusCode) { _rejectStatusCode = statusCode; return this; }
/// Retry-After value of a refused request in seconds; 0 = do not send (default 30).
public As2Builder RetryAfterSeconds(int seconds) { _retryAfterSeconds = seconds; return this; }
///
/// Receive endpoint: how many asynchronous MDNs are handled at once (default 20); a message asking for one when
/// every slot is taken is refused before any work.
///
public As2Builder AsyncMdnPoolSize(int size) { _asyncMdnPoolSize = size; return this; }
///
/// Receive endpoint: an asynchronous MDN is posted at most times (default 3), the first
/// retry after milliseconds (default 5000), doubled for each one after it.
///
public As2Builder AsyncMdnRetry(int attempts, int delayMs)
{
_asyncMdnAttempts = attempts;
_asyncMdnRetryDelay = delayMs;
return this;
}
/// Receive endpoint: a named IIdempotentRepository that remembers received Message-IDs, so a resend is not delivered twice.
public As2Builder IdempotentRepository(string name) { _idempotentRepository = name; return this; }
///
/// Receive endpoint, with an idempotent repository: milliseconds after which an unconfirmed claim of a Message-ID is
/// taken over (default 600000); a copy arriving while a younger claim is in flight is refused as busy.
///
public As2Builder InFlightClaimTimeout(int milliseconds) { _inFlightClaimTimeout = milliseconds; return this; }
/// Receive endpoint: hand the payload to the route as a spooled Stream instead of byte[].
public As2Builder StreamBody(bool streamBody = true) { _streamBody = streamBody; return this; }
/// Receive endpoint: the largest request body accepted, in bytes (default 100 MB); larger is answered 413.
public As2Builder MaxRequestBodySize(long bytes) { _maxRequestBodySize = bytes; return this; }
///
/// Receive endpoint: the most bytes a compressed message may inflate to; past it the message is refused with
/// decompression-failed. Unset: .
///
public As2Builder MaxDecompressedSize(long bytes) { _maxDecompressedSize = bytes; return this; }
/// Send endpoint: the largest response (synchronous MDN) read, in bytes (default 4 MB).
public As2Builder MaxResponseBodySize(long bytes) { _maxResponseBodySize = bytes; return this; }
/// Builds the AS2 URI string.
public string Build() => _mode == As2Mode.Receive ? BuildReceive() : BuildSend();
private string BuildReceive()
{
// Keep the path intact incl. its leading slash — the first segment must NOT be dropped
// (see the Http ConsumerPath fix). host/port travel as query parameters.
var path = _target.StartsWith('/') ? _target : "/" + _target;
var sb = new StringBuilder("as2:").Append(path);
var sep = '?';
void Add(string k, string v) { sb.Append(sep).Append(k).Append('=').Append(Uri.EscapeDataString(v)); sep = '&'; }
if (_host is not null) Add("host", _host);
if (_port is not null) Add("port", _port.Value.ToString());
if (_connectionFactory is not null) Add("connectionFactory", _connectionFactory);
if (_useTls) Add("useTls", "true");
if (_sslCertPath is not null) Add("sslCertPath", _sslCertPath);
if (_sslCertPassword is not null) Add("sslCertPassword", _sslCertPassword);
if (_maxConcurrentRequests is { } max) Add("maxConcurrentRequests", max.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_requestQueueLimit is { } queue) Add("requestQueueLimit", queue.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_rejectStatusCode is { } rsc) Add("rejectStatusCode", rsc.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_retryAfterSeconds is { } ras) Add("retryAfterSeconds", ras.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_maxRequestBodySize is { } mrb) Add("maxRequestBodySize", mrb.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_maxDecompressedSize is { } mds) Add("maxDecompressedSize", mds.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_asyncMdnPoolSize is { } amp) Add("asyncMdnPoolSize", amp.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_asyncMdnAttempts is { } ama) Add("asyncMdnAttempts", ama.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_asyncMdnRetryDelay is { } amd) Add("asyncMdnRetryDelay", amd.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_streamBody) Add("streamBody", "true");
if (_idempotentRepository is not null) Add("idempotentRepository", _idempotentRepository);
if (_inFlightClaimTimeout is { } ict) Add("inFlightClaimTimeout", ict.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (AsMdnReceiver) Add("mode", "mdn");
return sb.ToString();
}
private string BuildSend()
{
// Map the partner URL scheme onto as2/as2s so the component is selected; TLS is carried by the scheme.
var scheme = "as2";
var rest = _target;
if (rest.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { scheme = "as2s"; rest = rest["https://".Length..]; }
else if (rest.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { rest = rest["http://".Length..]; }
else if (rest.StartsWith("as2s://", StringComparison.OrdinalIgnoreCase)) { scheme = "as2s"; rest = rest["as2s://".Length..]; }
else if (rest.StartsWith("as2://", StringComparison.OrdinalIgnoreCase)) { rest = rest["as2://".Length..]; }
var sb = new StringBuilder(scheme).Append("://").Append(rest);
var sep = rest.Contains('?') ? '&' : '?';
void Add(string k, string v) { sb.Append(sep).Append(k).Append('=').Append(Uri.EscapeDataString(v)); sep = '&'; }
if (_connectionFactory is not null) Add("connectionFactory", _connectionFactory);
if (_maxResponseBodySize is { } mrs) Add("maxResponseBodySize", mrs.ToString(System.Globalization.CultureInfo.InvariantCulture));
return sb.ToString();
}
/// Allows passing the builder directly to From()/To() without calling Build().
public static implicit operator string(As2Builder builder) => builder.Build();
///
public override string ToString() => Build();
}