Path: redb-route/redb.Route.As4/As4Producer.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.As4/As4Producer.cs
----
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.As4.Compression;
using redb.Route.Configuration;
using redb.Route.As4.Messaging;
using redb.Route.As4.Mime;
using redb.Route.As4.Security;
using redb.Route.As4.Signals;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.As4;
///
/// AS4 sender (One-Way / Push, eDelivery AS4 1.16): builds the user message from the exchange and the agreement,
/// compresses, signs and encrypts the payload, posts it, and requires a signed non-repudiation receipt in the
/// response that names exactly what was signed. The outcome is on exchange.Out (InOut), as the AS2
/// producer puts its MDN there.
///
/// Failures are exceptions the route handles: when the partner refuses
/// the message, when no valid receipt proves receipt — the one to redeliver
/// on. The message id is written to redbAs4.messageId before the first attempt, so a redelivery of the
/// same exchange resends the same message.
///
///
internal sealed class As4Producer : ConnectableProducer
{
private readonly As4Endpoint _endpoint;
private readonly As4EndpointOptions _options;
private HttpClient? _http;
private StreamCacheOptions _spool = new();
public As4Producer(As4Endpoint endpoint, As4EndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
}
/// The resolved node; set when the producer has started.
internal As4Node? Node { get; private set; }
///
protected override IEndpoint ProducerEndpoint => _endpoint;
// The name reaches the started/stopped logs; a partner URL may carry userinfo no [Sensitive] reaches.
///
protected override string ProducerName => _endpoint.PartnerUrl is { } url
? $"as4:{EndpointUri.Sanitize(url)}"
: EndpointUri.Sanitize(_endpoint.Uri.NormalizedKey);
///
protected override Task ConnectAsync(CancellationToken ct)
{
var node = As4Node.Resolve(_endpoint.Context, _options.ConnectionFactory!);
_spool = As4Spool.Options(_endpoint.Context);
if (_options.Partner is not { } partner)
throw new InvalidOperationException($"AS4 send endpoint {_endpoint.Uri} requires 'partner': the Name of one of its node's partners.");
// A static partner name is checked now; an expression can only be checked per message.
if (!partner.IsDynamic)
{
var name = partner.Resolve(null!); // static: the exchange is not read
if (string.IsNullOrWhiteSpace(name) || !node.Partners.TryGetValue(name, out var agreement))
throw new InvalidOperationException(
$"AS4 send endpoint {_endpoint.Uri}: partner '{name}' is not a partner of connection factory '{node.Name}'.");
AddressOf(agreement);
}
// One client per producer, as the AS2 and HTTP producers keep.
_http = new HttpClient(CreateHandler(node.Factory))
{
Timeout = _options.Timeout > 0 ? TimeSpan.FromMilliseconds(_options.Timeout) : Timeout.InfiniteTimeSpan,
};
Node = node;
return Task.CompletedTask;
}
///
/// Reads the partner's response within : refused on a declared
/// length over it, else read as a stream that stops one byte past it. A receipt or an error is a few KB; anything
/// larger (a proxy's error page, a broken partner) is not one, and is not buffered to find out.
///
private async Task ReadBoundedAsync(HttpResponseMessage response, string messageId, CancellationToken ct)
{
var limit = _options.MaxResponseBodySize;
if (response.Content.Headers.ContentLength is { } declared && declared > limit)
throw new As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId,
$"the response declares {declared} bytes, over maxResponseBodySize {limit}.");
await using var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
using var buffer = new MemoryStream();
var chunk = new byte[81920];
int read;
while ((read = await body.ReadAsync(chunk, ct).ConfigureAwait(false)) > 0)
{
if (buffer.Length + read > limit)
throw new As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId,
$"the response is over maxResponseBodySize {limit} bytes.");
buffer.Write(chunk, 0, read);
}
return buffer.ToArray();
}
///
/// Builds the request of : each payload of the body spooled (a large one to a temporary
/// file), compressed per the agreement, signed, encrypted and written to a spool the HTTP content streams from.
///
private async Task BuildAsync(IExchange exchange, As4Node node, As4Partner partner, string messageId, CancellationToken ct)
{
var host = node.Factory.ExternalHostName;
var refToMessageId = Resolve(_options.RefToMessageId, exchange) ?? exchange.In.GetHeader(As4Headers.RefToMessageId);
var (service, serviceType, action) = BusinessValues(exchange, partner, isReply: refToMessageId is not null);
var conversationId = Resolve(_options.ConversationId, exchange)
?? exchange.In.GetHeader(As4Headers.ConversationId)
?? Guid.NewGuid().ToString("D");
var properties = MessageProperties(exchange, partner);
// One part per payload, eb:PartInfo in the order the route gave them: the first is the leading business
// document (eDelivery AS4 1.16 §3.2.3).
var parts = new List();
try
{
var partInfos = new List();
foreach (var payload in Payloads(exchange.In, partner))
{
var contentId = payload.ContentId ?? "part-" + Guid.NewGuid().ToString("N") + "@" + host;
if (parts.Any(p => p.ContentId == contentId))
throw new InvalidOperationException(
$"AS4 message to partner '{partner.Name}' has two payloads with Content-ID '{contentId}'.");
var part = new SwaPart(contentId, payload.ContentType,
await As4Spool.RunAsync(_spool, (output, token) => WritePayloadAsync(payload.Content, output, token), ct).ConfigureAwait(false));
parts.Add(part);
IReadOnlyList described = partner.CompressPayloads
? As4Compression.Compress(part, _spool)
: [new Property(As4Compression.MimeTypeProperty, part.ContentType, null)];
partInfos.Add(new PartInfo(WsSecurityNames.CidUri(contentId), [.. described, .. payload.Properties]));
}
var user = new UserMessage(
new MessageInfo(DateTimeOffset.UtcNow, messageId, refToMessageId),
new Party([new PartyId(node.Factory.OurPartyId!, node.Factory.OurPartyIdType)], partner.OurRole),
new Party([new PartyId(partner.PartyId!, partner.PartyIdType)], partner.PartnerRole),
new CollaborationInfo(
partner.AgreementRef is null ? null : new AgreementRef(partner.AgreementRef, partner.AgreementRefType, partner.PModeId),
new Service(service, serviceType), action, conversationId),
properties,
partInfos,
null);
using var message = SwaMessage.Create(MessagingWriter.CreateEnvelope(user), _spool);
foreach (var part in parts)
message.Parts.Add(part.ContentId, part);
var signed = As4SecurityEngine.Sign(message, node.Factory.SigningCertificate!, partner.KeyReference, partner.TimestampTtl, DateTimeOffset.UtcNow,
node.SigningPath);
As4SecurityEngine.Encrypt(message, partner.PartnerEncryptionCertificate!, partner.KeyReference);
string? wireType = null;
var body = As4Spool.Run(_spool, output => wireType = message.WriteTo(output));
return new As4Transmission(messageId, partner.Name!, exchange.In.Body, body, wireType!, signed);
}
finally
{
foreach (var part in parts) part.Dispose();
}
}
/// What the route asks to send as one payload: its content as the exchange gave it.
private readonly record struct OutboundPayload(string? ContentId, string ContentType, object? Content, IReadOnlyList Properties);
///
/// The payloads of the message. A body that is a list of (or one of them) is sent as that
/// many payloads in that order, each with its Content-ID and part properties; an empty list is a message without
/// payloads. Any other body is one payload with a generated Content-ID and the media type of the message.
///
private static IReadOnlyList Payloads(IMessage message, As4Partner partner)
{
IEnumerable? listed = message.Body switch
{
As4Payload one => [one],
IEnumerable many => many,
_ => null,
};
if (listed is null)
return [new OutboundPayload(null, message.ContentType ?? "application/octet-stream", message.Body, [])];
var payloads = new List();
foreach (var payload in listed)
{
if (payload is null)
throw new InvalidOperationException($"AS4 message to partner '{partner.Name}': a payload in the body list is null.");
if (payload.ContentId is { } id && (id.Length == 0 || id.Any(c => char.IsWhiteSpace(c) || c is '<' or '>')))
throw new InvalidOperationException(
$"AS4 message to partner '{partner.Name}': Content-ID '{id}' is not usable; give it without angle brackets and spaces, or null.");
if (string.IsNullOrWhiteSpace(payload.ContentType))
throw new InvalidOperationException($"AS4 message to partner '{partner.Name}': a payload has no ContentType.");
if (payload.Properties is not null && payload.Properties.TryGetValue(PayloadConsistency.CharacterSetProperty, out var characterSet)
&& !PayloadConsistency.IsCharacterSetName(characterSet))
throw new InvalidOperationException(
$"AS4 message to partner '{partner.Name}': CharacterSet '{characterSet}' is not an encoding name of XML 1.0 §4.3.3 (UTF-8, ISO-8859-1, ...).");
// MimeType and CompressionType describe what the connector does to the part; they are its own to write.
var properties = (payload.Properties ?? new Dictionary())
.Where(p => p.Key is not (As4Compression.MimeTypeProperty or As4Compression.CompressionTypeProperty) && p.Value is not null)
.Select(p => new Property(p.Key, p.Value, null))
.OrderBy(p => p.Name, StringComparer.Ordinal)
.ToList();
payloads.Add(new OutboundPayload(payload.ContentId, payload.ContentType, payload.Content, properties));
}
return payloads;
}
///
/// The HTTP handler of a sender: the TLS versions the node allows (TLS 1.2 and 1.3 by default, as Holodeck, phase4
/// and Domibus offer), and our client certificate for partners that require mutual TLS.
///
internal static HttpClientHandler CreateHandler(As4ConnectionFactory node)
{
ArgumentNullException.ThrowIfNull(node);
var handler = new HttpClientHandler { SslProtocols = node.SslProtocols };
if (node.ClientCertificate is { } clientCertificate)
handler.ClientCertificates.Add(clientCertificate);
return handler;
}
///
protected override Task DisconnectAsync(CancellationToken ct)
{
_http?.Dispose();
_http = null;
return Task.CompletedTask;
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(exchange);
var node = Node!;
var partner = ResolvePartner(exchange, node);
var address = AddressOf(partner);
var host = node.Factory.ExternalHostName;
// The id is fixed on the exchange before the first attempt: a redelivery resends the same message.
var messageId = exchange.In.GetHeader(As4Headers.MessageId);
if (string.IsNullOrWhiteSpace(messageId))
{
messageId = MessageIdFactory.New(host);
exchange.In.Headers[As4Headers.MessageId] = messageId;
}
// Pinned keys are still checked for their validity period before anything is sent, on every attempt (Domibus
// sender/receiver certificate validation on sending): a partner would refuse the message, and a receipt could not
// be trusted either.
var now = DateTimeOffset.UtcNow;
if (CertificateValidity.Problem(node.Factory.SigningCertificate!, now, $"AS4 node '{node.Name}': our signing certificate", node.Factory.Revocation) is { } ours)
throw new InvalidOperationException(ours);
if (CertificateValidity.Problem(partner.PartnerEncryptionCertificate!, now, $"AS4 partner '{partner.Name}': the encryption certificate", node.Factory.Revocation) is { } theirs)
throw new InvalidOperationException(theirs);
// A redelivery on this exchange resends the message of the first attempt, byte for byte.
if (exchange.Properties.TryGetValue(As4Transmission.Property, out var stored) && stored is As4Transmission prior
&& prior.IsFor(messageId, partner.Name!, exchange.In.Body))
{
Logger?.LogDebug("AS4 message {MessageId}: redelivery sends the transmission of the first attempt.", messageId);
}
else
{
prior = await BuildAsync(exchange, node, partner, messageId, ct).ConfigureAwait(false);
exchange.Properties[As4Transmission.Property] = prior;
ExchangeResources.ReleaseWithExchange(exchange, prior);
}
var transmission = prior;
var sent = transmission.Signed;
// The send span on the core contract (EnableTelemetry=false opens none); its context is written to the request,
// replacing one already there: HttpClient writes none of its own when the header is present.
using var activity = RouteTelemetryExtensions.StartTransportSpan(
_endpoint.Context, $"{partner.Name} send", ActivityKind.Client, "messaging.system", "as4",
_endpoint.Uri.NormalizedKey, destination: EndpointUri.Sanitize(address), operation: "send");
using var request = new HttpRequestMessage(HttpMethod.Post, address) { Content = transmission.Content() };
RouteTelemetryExtensions.InjectTraceContext(activity, request, static (r, name, value) =>
{
r.Headers.Remove(name);
r.Headers.TryAddWithoutValidation(name, value);
});
_endpoint.RecordBytesOut(transmission.Body.Length);
byte[] responseBody;
string? responseType;
SignalMessage receipt;
try
{
using var response = await ReceiptWithin(_http!.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct), messageId, partner, ct).ConfigureAwait(false);
responseBody = await ReceiptWithin(ReadBoundedAsync(response, messageId, ct), messageId, partner, ct).ConfigureAwait(false);
responseType = response.Content.Headers.ContentType?.ToString();
receipt = ReadReceipt(messageId, response, responseBody, responseType, partner, sent);
}
catch (Exception e) when (e is not OperationCanceledException)
{
// Unreachable, no receipt, an ebMS error or a receipt that does not verify: the send failed.
activity.RecordFailure(e);
throw;
}
var outMessage = new Message(responseBody) { ContentType = responseType };
outMessage.Headers[As4Headers.MessageId] = messageId;
outMessage.Headers[As4Headers.Partner] = partner.Name;
outMessage.Headers[As4Headers.ReceiptValid] = true;
outMessage.Headers[As4Headers.ReceiptMessageId] = receipt.MessageInfo.MessageId;
exchange.Out = outMessage;
exchange.Pattern = ExchangePattern.InOut;
Logger?.LogDebug("AS4 message {MessageId} sent to partner {Partner}; receipt {ReceiptId} verified.",
messageId, partner.Name, receipt.MessageInfo.MessageId);
}
// ── Receipt ──────────────────────────────────────────────────────────────
///
/// Whether the answer is an eb:SignalMessage about (or about no message) with no
/// receipt, error or pull request in it: what is left of a receipt when the receipt is taken out.
///
private static bool IsSignalWithoutReceipt(System.Xml.XmlDocument envelope, string messageId)
{
var signals = envelope.GetElementsByTagName("SignalMessage", EbmsNamespaces.Eb).OfType().ToList();
return signals.Count > 0 && signals.All(signal =>
{
var children = signal.ChildNodes.OfType().Where(c => c.NamespaceURI == EbmsNamespaces.Eb).ToList();
if (children.Any(c => c.LocalName is "Receipt" or "Error" or "PullRequest"))
return false;
var refTo = children.FirstOrDefault(c => c.LocalName == "MessageInfo")?.ChildNodes.OfType()
.FirstOrDefault(c => c.LocalName == "RefToMessageId" && c.NamespaceURI == EbmsNamespaces.Eb)?.InnerText.Trim();
return refTo is null || refTo == messageId;
});
}
///
/// The start of a textual answer that is not an ebMS signal (a proxy's or firewall's page often names who refused
/// and a support reference), for the error text: at most 160 characters, whitespace collapsed, control characters
/// dropped. Empty for a binary answer.
///
private static string AnswerExcerpt(byte[] body, string contentType)
{
if (!contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase))
return "";
var text = System.Text.Encoding.UTF8.GetString(body, 0, Math.Min(body.Length, 4096));
var excerpt = new System.Text.StringBuilder(160);
var space = false;
foreach (var c in text)
{
if (excerpt.Length >= 160) break;
if (char.IsWhiteSpace(c)) { space = excerpt.Length > 0; continue; }
if (char.IsControl(c)) continue;
if (space) { excerpt.Append(' '); space = false; }
excerpt.Append(c);
}
return excerpt.Length == 0 ? "" : $" ({contentType.Split(';')[0].Trim()}: \"{excerpt}\")";
}
///
/// The verified receipt for in the partner's response, or the exception that
/// says why there is none: the partner's own error signal, a response without a signal (missing receipt),
/// or a receipt that does not verify or does not echo what we signed (invalid receipt).
///
private SignalMessage ReadReceipt(string messageId, HttpResponseMessage response, byte[] body, string? contentType,
As4Partner partner, IReadOnlyList sent)
{
// A signal may come with any status (Holodeck answers an ebMS error with 200); only an empty body is "nothing".
if (body.Length == 0 || string.IsNullOrWhiteSpace(contentType))
throw new As4ReceiptException(As4ErrorCode.MissingReceipt, messageId,
$"the partner answered HTTP {(int)response.StatusCode} without a signal.");
SwaMessage? read = null;
SwaMessage answer;
EbmsMessaging messaging;
try
{
answer = read = SwaMessage.Read(contentType, body, _options.MaxEnvelopeCharacters);
messaging = MessagingReader.Read(answer.Envelope);
}
catch (As4ProcessingException e) when (read is not null && IsSignalWithoutReceipt(read.Envelope, messageId))
{
// A signal about our message that holds neither a receipt nor an error: no receipt came (reception awareness,
// EBMS:0301), as the conformance test driver simulates a lost receipt (AS4_CP_TA15).
throw new As4ReceiptException(As4ErrorCode.MissingReceipt, messageId,
$"the partner's HTTP {(int)response.StatusCode} answer is a signal without a receipt.", e);
}
catch (Exception e) when (e is As4ProcessingException or FormatException or System.Xml.XmlException or MimeKit.ParseException)
{
throw new As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId,
$"the partner's HTTP {(int)response.StatusCode} answer is not an ebMS signal{AnswerExcerpt(body, contentType)}.", e);
}
// Signals about our message; an error that names no message at all is about it too — a partner that could not
// parse our header cannot quote its id.
var signals = messaging.SignalMessages
.Where(s => s.MessageInfo.RefToMessageId == messageId
|| s.Errors.Any(e => e.RefToMessageInError == messageId)
|| (s.MessageInfo.RefToMessageId is null && s.Errors.Count > 0 && s.Errors.All(e => e.RefToMessageInError is null)))
.ToList();
var failure = signals.SelectMany(s => s.Errors).FirstOrDefault(e => e.Severity == As4ErrorSeverity.Failure);
if (failure is not null)
throw new As4ErrorSignalException(messageId, failure.ErrorCode, failure.ShortDescription, failure.Description, failure.ErrorDetail);
var receipt = signals.FirstOrDefault(s => s.IsReceipt)
?? throw new As4ReceiptException(As4ErrorCode.MissingReceipt, messageId,
$"the partner's HTTP {(int)response.StatusCode} answer carries no receipt for it.");
try
{
As4SecurityEngine.Verify(answer, partner.PartnerSigningCertificates.ToList(), partner.TimestampTolerance, DateTimeOffset.UtcNow,
Node!.Factory.Revocation, partner.TimestampTimeToLive, partner.PkiPathTrust);
}
catch (CryptographicException e)
{
throw new As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId, "the receipt's signature does not verify.", e);
}
if (!Receipts.ProvesReceiptOf(receipt, sent))
throw new As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId,
"the receipt's non-repudiation information does not name what was signed.");
return receipt;
}
// ── Building the message ─────────────────────────────────────────────────
private As4Partner ResolvePartner(IExchange exchange, As4Node node)
{
var name = _options.Partner!.Value.Resolve(exchange);
if (string.IsNullOrWhiteSpace(name) || !node.Partners.TryGetValue(name, out var partner))
throw new InvalidOperationException(
$"AS4 send endpoint {_endpoint.Uri}: partner '{name}' is not a partner of connection factory '{node.Name}'.");
return partner;
}
///
/// Where the message goes: the address of the send endpoint, or the partner's . Exactly
/// one of them: two would leave the reader of the route to guess which one is used.
///
private string AddressOf(As4Partner partner)
{
if (_endpoint.PartnerUrl is { } url)
{
if (partner.Address is not null)
throw new InvalidOperationException(
$"AS4 send endpoint {EndpointUri.Sanitize(_endpoint.Uri.NormalizedKey)} gives an address and partner '{partner.Name}' has " +
"one in its Address: give it in one place.");
return url;
}
return partner.Address ?? throw new InvalidOperationException(
$"AS4 send endpoint {EndpointUri.Sanitize(_endpoint.Uri.NormalizedKey)} has no address and partner '{partner.Name}' has no Address: " +
"set the partner's Address, or send to as4s://host[:port]/path.");
}
///
/// Service and action: the agreement's request leg, or its reply leg when the message answers another one
/// (Two-Way / Push-and-Push). An option or header may override them only where the agreement allows it.
///
private (string Service, string? ServiceType, string Action) BusinessValues(IExchange exchange, As4Partner partner, bool isReply)
{
string service, action;
string? serviceType;
if (isReply)
{
var leg = partner.ReplyLeg
?? throw new InvalidOperationException(
$"AS4 partner '{partner.Name}': the message answers another one (refToMessageId), but the agreement has no ReplyLeg.");
(service, serviceType, action) = (leg.Service!, leg.ServiceType, leg.Action!);
}
else
{
(service, serviceType, action) = (partner.Service!, partner.ServiceType, partner.Action!);
}
var serviceOverride = Resolve(_options.Service, exchange) ?? exchange.In.GetHeader(As4Headers.Service);
if (serviceOverride is not null && serviceOverride != service)
{
if (!partner.AllowOverrideService)
throw new InvalidOperationException(
$"AS4 partner '{partner.Name}' does not allow overriding the service ('{service}' asked to be '{serviceOverride}').");
service = serviceOverride;
}
var actionOverride = Resolve(_options.Action, exchange) ?? exchange.In.GetHeader(As4Headers.Action);
if (actionOverride is not null && actionOverride != action)
{
if (!partner.AllowOverrideAction)
throw new InvalidOperationException(
$"AS4 partner '{partner.Name}' does not allow overriding the action ('{action}' asked to be '{actionOverride}').");
action = actionOverride;
}
return (service, serviceType, action);
}
///
/// eb:MessageProperties from the exchange headers under — the only
/// exchange headers that reach the partner, each with the type a header under
/// gives it. The eDelivery four-corner properties are required unless
/// the agreement says otherwise ().
///
private static IReadOnlyList MessageProperties(IExchange exchange, As4Partner partner)
{
var headers = exchange.In.Headers;
var properties = headers
.Where(h => h.Key.StartsWith(As4Headers.PropertyPrefix, StringComparison.Ordinal) && h.Value is not null)
.Select(h =>
{
var name = h.Key[As4Headers.PropertyPrefix.Length..];
var type = headers.TryGetValue(As4Headers.PropertyTypePrefix + name, out var t) && t?.ToString() is { Length: > 0 } text ? text : null;
return new Property(name, h.Value!.ToString()!, type);
})
.OrderBy(p => p.Name, StringComparer.Ordinal)
.ToList();
if (!partner.RequireFourCornerProperties)
return properties;
foreach (var required in new[] { As4Headers.OriginalSender, As4Headers.FinalRecipient })
{
var name = required[As4Headers.PropertyPrefix.Length..];
if (!properties.Any(p => p.Name == name && p.Value.Length > 0))
throw new InvalidOperationException(
$"AS4 message to partner '{partner.Name}' has no '{name}' property: set the header '{required}' (eDelivery four-corner model).");
}
return properties;
}
///
/// Writes the body into the payload spool. A is copied, not buffered, and not closed: the
/// exchange owns it (the ownsStream rule of the stream connectors). A seekable one is read from its start,
/// so a redelivery sends the same bytes (the SttProducer precedent); a forward-only one is read once — to redeliver
/// it, the route caches it with .StreamCaching().
///
private static async Task WritePayloadAsync(object? body, Stream output, CancellationToken ct)
{
switch (body)
{
case null:
return;
case byte[] bytes:
await output.WriteAsync(bytes, ct).ConfigureAwait(false);
return;
case string text:
await output.WriteAsync(Encoding.UTF8.GetBytes(text), ct).ConfigureAwait(false);
return;
case Stream stream:
if (stream.CanSeek) stream.Position = 0;
await stream.CopyToAsync(output, ct).ConfigureAwait(false);
return;
default:
// As the AS2 and HTTP producers do: any other body is sent as its UTF-8 text.
await output.WriteAsync(Encoding.UTF8.GetBytes(BodyText.Of(body)), ct).ConfigureAwait(false);
return;
}
}
///
/// Awaits one step of the exchange with the partner. A timeout is a missing receipt, not a cancellation: the
/// engine's OnException and dead letter channel always rethrow , so an
/// unconverted timeout could never be redelivered (the McpProducer precedent). A cancelled
/// stays a cancellation.
///
private async Task ReceiptWithin(Task step, string messageId, As4Partner partner, CancellationToken ct)
{
try
{
return await step.ConfigureAwait(false);
}
catch (OperationCanceledException e) when (!ct.IsCancellationRequested)
{
throw new As4ReceiptException(As4ErrorCode.MissingReceipt, messageId,
$"no response from partner '{partner.Name}' within {_options.Timeout} ms.", e);
}
}
private static string? Resolve(DynamicValue? value, IExchange exchange) =>
value is { } v && v.Resolve(exchange) is { Length: > 0 } resolved ? resolved : null;
}