Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusProducer.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.AzureServiceBus/AzureServiceBusProducer.cs
----
using System.Collections;
using System.Diagnostics;
using System.Text.Json;
using System.Transactions;
using Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using redb.Route.Transactions;
namespace redb.Route.AzureServiceBus;
///
/// Sends messages to an Azure Service Bus queue or topic.
/// Supports single send, batch send, and scheduled delivery.
///
internal sealed class AzureServiceBusProducer : ConnectableProducer
{
private readonly AzureServiceBusEndpoint _endpoint;
private readonly AzureServiceBusEndpointOptions _options;
private readonly IHeaderFilterStrategy _headerFilter;
private readonly string _batchKey = $"asb-batch-{Guid.NewGuid():N}";
private ServiceBusSender? _sender;
protected override IEndpoint ProducerEndpoint => _endpoint;
protected override string ProducerName => _endpoint.Uri.NormalizedKey;
internal AzureServiceBusProducer(AzureServiceBusEndpoint endpoint,
AzureServiceBusEndpointOptions options)
{
_endpoint = endpoint;
_options = options;
_headerFilter = endpoint.HeaderFilterStrategy;
}
protected override async Task ConnectAsync(CancellationToken ct)
{
var client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
_sender = client.CreateSender(_endpoint.EntityName);
}
protected override async Task DisconnectAsync(CancellationToken ct)
{
if (_sender is not null)
{
await _sender.DisposeAsync().ConfigureAwait(false);
_sender = null;
}
}
public override async Task Process(IExchange exchange, CancellationToken ct)
{
EnsureStarted();
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_endpoint.EntityName} send", ActivityKind.Producer,
"messaging.system", "azureservicebus",
_endpoint.Uri.NormalizedKey,
destination: _endpoint.EntityName,
operation: "send");
// A list is sent as one Service Bus batch, one message per element, as Camel's azure-servicebus sends an
// Iterable body: a list of IMessage with each element's own body and headers, a plain list with each value as
// the body under the exchange's headers.
var body = exchange.In.Body;
var elements = (IEnumerable?)ListBody.Messages(body) ?? (ListBody.IsPlainList(body) ? (IEnumerable)body! : null);
var defers = TransactedActions.Defers(exchange, _options.Transacted);
if (defers && _options.BatchCommit)
{
// The block's sends through this producer leave as one Service Bus batch when the block commits.
var messages = elements is not null ? await BuildListMessagesAsync(exchange, elements, activity).ConfigureAwait(false)
: [BuildSingle(exchange, activity)];
if (elements is not null)
exchange.In.Headers[AzureServiceBusHeaders.BatchMessageCount] = messages.Count;
TransactedActions.JoinBatch(exchange, _batchKey, () => new AzureServiceBusSendBatch(this), ProducerName)
.Add(messages);
return;
}
// The messages are built now, from the exchange as it is at this step; only the send itself waits for the
// commit when the producer joins the enclosing .Transacted() block.
var send = elements is not null
? PrepareList(exchange, await BuildListMessagesAsync(exchange, elements, activity).ConfigureAwait(false))
: PrepareSingle(exchange, activity);
if (defers)
{
TransactedActions.RegisterSend(exchange, $"asb-send-{Guid.NewGuid():N}", send, ProducerName);
return;
}
// The Service Bus client enlists a send in the ambient System.Transactions transaction on its own. A send that
// goes out at once must not: it would wait for the block's commit, and next to a database in the same block it
// would escalate the transaction to a distributed one.
using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
{
try
{
await send(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
activity.RecordFailure(ex);
throw;
}
}
}
// ── Single send ──
private Func PrepareSingle(IExchange exchange, Activity? activity)
{
var msg = BuildSingle(exchange, activity);
return async ct =>
{
await _sender!.SendMessageAsync(msg, ct).ConfigureAwait(false);
_endpoint.RecordBytesOut(msg.Body.ToMemory().Length);
};
}
private ServiceBusMessage BuildSingle(IExchange exchange, Activity? activity)
{
var msg = BuildMessage(exchange, activity);
exchange.In.Headers[AzureServiceBusHeaders.MessageId] = msg.MessageId;
return msg;
}
// ── List send ──
private Func PrepareList(IExchange exchange, List messages)
=> async ct =>
{
await SendAsOneBatchAsync(messages, "this list body", ct).ConfigureAwait(false);
exchange.In.Headers[AzureServiceBusHeaders.BatchMessageCount] = messages.Count;
};
///
/// One message per element of a list body, each built from its element's exchange ():
/// an element with its own body and headers, its own message id when it carries one; a plain
/// value with the exchange's headers and a message id of its own, so the entity's duplicate detection does not take
/// the elements for one message.
///
private async Task> BuildListMessagesAsync(IExchange exchange, IEnumerable elements, Activity? activity)
{
var messages = new List();
foreach (var element in elements)
{
var source = ListBody.ElementExchange(exchange, element);
try
{
var msg = BuildMessage(source, activity);
if (element is not IMessage)
msg.MessageId = Guid.NewGuid().ToString();
messages.Add(msg);
}
finally
{
if (source is IAsyncDisposable disposable)
await disposable.DisposeAsync().ConfigureAwait(false);
}
}
activity?.SetTag("messaging.batch.message_count", messages.Count);
return messages;
}
///
/// Sends as one Service Bus batch: the entity takes it whole or not at all. Messages that
/// do not fit in one batch fail the send before anything leaves: they used to be dropped without a word.
///
internal async Task SendAsOneBatchAsync(IReadOnlyList messages, string what, CancellationToken ct)
{
var sender = _sender ?? throw new InvalidOperationException(
$"'{ProducerName}' is stopped: the messages cannot be sent.");
using var batch = await sender.CreateMessageBatchAsync(
new CreateMessageBatchOptions { MaxSizeInBytes = _options.BatchMaxSizeBytes }, ct).ConfigureAwait(false);
foreach (var msg in messages)
{
if (!batch.TryAddMessage(msg))
throw new InvalidOperationException(
$"The {messages.Count} messages of {what} do not fit in one Service Bus batch of {batch.MaxSizeInBytes} " +
$"bytes through '{ProducerName}': nothing was sent. Raise batchMaxSizeBytes up to the entity's limit, " +
"or send less at once.");
}
if (batch.Count > 0)
{
await sender.SendMessagesAsync(batch, ct).ConfigureAwait(false);
long sent = 0;
foreach (var msg in messages)
sent += msg.Body.ToMemory().Length;
_endpoint.RecordBytesOut(sent);
}
}
// ── Message building ──
private ServiceBusMessage BuildMessage(IExchange exchange, Activity? activity)
{
var data = ResolveBodyData(exchange.In.Body
?? throw new InvalidOperationException("Body is null; cannot send an empty message."));
var msg = new ServiceBusMessage(data);
ApplyProperties(msg, exchange, activity);
return msg;
}
///
/// Maps native Service Bus properties and application properties from exchange headers/options.
/// Shared by single and batch send so batched messages carry the same metadata, the trace context of
/// included.
///
private void ApplyProperties(ServiceBusMessage msg, IExchange exchange, Activity? activity)
{
// Identity
msg.MessageId = ResolveHeader(exchange, AzureServiceBusHeaders.MessageId)
?? _options.MessageId?.Resolve(exchange)
?? Guid.NewGuid().ToString();
msg.CorrelationId = ResolveHeader(exchange, AzureServiceBusHeaders.CorrelationId) ?? "";
msg.SessionId = ResolveHeader(exchange, AzureServiceBusHeaders.SessionId)
?? _options.ProducerSessionId?.Resolve(exchange)
?? "";
var partitionKey = ResolveHeader(exchange, AzureServiceBusHeaders.PartitionKey)
?? _options.PartitionKey;
if (!string.IsNullOrEmpty(partitionKey) && string.IsNullOrEmpty(msg.SessionId))
msg.PartitionKey = partitionKey;
msg.ReplyToSessionId = ResolveHeader(exchange, AzureServiceBusHeaders.ReplyToSessionId) ?? "";
// Metadata
msg.Subject = ResolveHeader(exchange, AzureServiceBusHeaders.Subject) ?? "";
msg.ContentType = ResolveHeader(exchange, AzureServiceBusHeaders.ContentType)
?? exchange.In.ContentType ?? "";
msg.ReplyTo = ResolveHeader(exchange, AzureServiceBusHeaders.ReplyTo) ?? "";
msg.To = ResolveHeader(exchange, AzureServiceBusHeaders.To) ?? "";
// TTL
if (!string.IsNullOrEmpty(_options.TimeToLive))
msg.TimeToLive = TimeSpan.Parse(_options.TimeToLive, System.Globalization.CultureInfo.InvariantCulture);
if (ResolveHeader(exchange, AzureServiceBusHeaders.TimeToLive) is { } ttlStr
&& !string.IsNullOrEmpty(ttlStr))
msg.TimeToLive = TimeSpan.Parse(ttlStr, System.Globalization.CultureInfo.InvariantCulture);
// Scheduling
if (_options.ScheduleDelaySeconds > 0)
msg.ScheduledEnqueueTime = DateTimeOffset.UtcNow.AddSeconds(_options.ScheduleDelaySeconds);
if (exchange.In.GetHeader(AzureServiceBusHeaders.ScheduledEnqueueTime)
is { } scheduled)
msg.ScheduledEnqueueTime = scheduled;
// Application properties, as the endpoint's strategy lets the exchange headers out
foreach (var (key, value) in exchange.In.Headers)
{
if (value is null) continue;
if (_headerFilter.FilterOutgoing(key, value, exchange)) continue;
msg.ApplicationProperties[key] = value;
}
// The context of this send, over a Diagnostic-Id the header bridge copied from a received message: that one
// names the previous hop.
RouteTelemetryExtensions.InjectTraceContext(activity, msg.ApplicationProperties, AzureServiceBusTrace.Write);
}
private static BinaryData ResolveBodyData(object? body)
{
return body switch
{
byte[] bytes => BinaryData.FromBytes(bytes),
BinaryData bd => bd,
string str => BinaryData.FromString(str),
Stream stream => BinaryData.FromStream(stream),
_ => BinaryData.FromObjectAsJson(body)
};
}
private static T? ResolveHeader(IExchange exchange, string headerKey) where T : class
{
return exchange.In.GetHeader(headerKey);
}
}
///
/// The messages a Service Bus producer with batchCommit deferred in one .Transacted() block, sent as one
/// batch when the block commits.
///
internal sealed class AzureServiceBusSendBatch : ITransactedAction
{
private readonly AzureServiceBusProducer _producer;
private readonly System.Collections.Concurrent.ConcurrentQueue _messages = new();
public AzureServiceBusSendBatch(AzureServiceBusProducer producer) => _producer = producer;
public void Add(IEnumerable messages)
{
foreach (var message in messages)
_messages.Enqueue(message);
}
public Task Commit(CancellationToken ct = default) =>
_producer.SendAsOneBatchAsync(_messages.ToArray(), "this .Transacted() block", ct);
// The block rolled back before anything was sent.
public Task Rollback(CancellationToken ct = default) => Task.CompletedTask;
}