From 572b6b044678b812367ed4acd3cebbefbca4f8c7 Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Fri, 13 Nov 2026 18:57:01 +0000
Subject: [PATCH] Align transport API naming and borrowed SQS access (#623)
---
... => ServiceBusMessageBindingBenchmarks.cs} | 8 +--
.../ServiceBusSendBenchmarks.cs | 2 +-
docs/design.md | 4 +-
.../AmazonSqsTransportOptions.cs | 4 --
src/Relayer.AmazonSqs/SqsDelivery.cs | 23 ++++++-
src/Relayer.AmazonSqs/SqsHostedService.cs | 2 +-
.../AspireConnectionExtensions.cs | 4 +-
.../ServiceBusBuilderExtensions.cs | 6 +-
.../ServiceBusConsumer.cs | 2 +-
.../ServiceBusHostedService.cs | 4 +-
...Binding.cs => ServiceBusMessageBinding.cs} | 10 +--
.../ServiceBusSendTransport.cs | 4 +-
.../ServiceBusSettlement.cs | 4 +-
.../ServiceBusTopology.cs | 2 +-
.../ServiceBusTopologyExporter.cs | 10 +--
...tions.cs => ServiceBusTransportOptions.cs} | 2 +-
src/Relayer.Kafka/KafkaBuilderExtensions.cs | 4 ++
tests/Relayer.AotSmoke/Program.cs | 6 +-
.../AspireRegistrationTests.cs | 2 +-
tests/Relayer.Kafka.Tests/KafkaSendTests.cs | 4 +-
tests/Relayer.Tests/RequestResponseTests.cs | 2 +-
.../ServiceBusConformanceTests.cs | 12 ++--
... ServiceBusMessageBindingEmulatorTests.cs} | 4 +-
...ts.cs => ServiceBusMessageBindingTests.cs} | 30 ++++-----
.../ServiceBusReceiveTopologyTests.cs | 4 +-
.../ServiceBusSendDurationTests.cs | 2 +-
.../ServiceBusSendEmulatorTests.cs | 6 +-
tests/Relayer.Tests/ServiceBusSendTests.cs | 6 +-
.../ServiceBusTopologyExportTests.cs | 16 ++---
tests/Relayer.Tests/SqsReceiveTests.cs | 36 ++++++++++
website/docs/guides/topology.md | 2 +-
website/docs/transports/amazon-sqs.md | 4 +-
website/docs/transports/authoring.md | 66 ++++++++++++++++++-
website/docs/transports/kafka.md | 8 +++
.../docs/transports/service-bus-receive.md | 6 +-
website/docs/transports/service-bus.md | 7 ++
36 files changed, 226 insertions(+), 92 deletions(-)
rename benchmarks/Relayer.Benchmarks/{ServiceBusBindingBenchmarks.cs => ServiceBusMessageBindingBenchmarks.cs} (83%)
rename src/Relayer.AzureServiceBus/{ServiceBusBinding.cs => ServiceBusMessageBinding.cs} (87%)
rename src/Relayer.AzureServiceBus/{AzureServiceBusTransportOptions.cs => ServiceBusTransportOptions.cs} (97%)
rename tests/Relayer.Tests/{ServiceBusBindingEmulatorTests.cs => ServiceBusMessageBindingEmulatorTests.cs} (97%)
rename tests/Relayer.Tests/{ServiceBusBindingTests.cs => ServiceBusMessageBindingTests.cs} (91%)
diff --git a/benchmarks/Relayer.Benchmarks/ServiceBusBindingBenchmarks.cs b/benchmarks/Relayer.Benchmarks/ServiceBusMessageBindingBenchmarks.cs
similarity index 83%
rename from benchmarks/Relayer.Benchmarks/ServiceBusBindingBenchmarks.cs
rename to benchmarks/Relayer.Benchmarks/ServiceBusMessageBindingBenchmarks.cs
index 0db0b766a..19801e3b5 100644
--- a/benchmarks/Relayer.Benchmarks/ServiceBusBindingBenchmarks.cs
+++ b/benchmarks/Relayer.Benchmarks/ServiceBusMessageBindingBenchmarks.cs
@@ -6,7 +6,7 @@ namespace Relayer.Benchmarks;
/// Compares receive projection with equivalent direct, zero-copy native AMQP property reads.
[MemoryDiagnoser]
-public class ServiceBusBindingBenchmarks
+public class ServiceBusMessageBindingBenchmarks
{
private ProcessMessageEventArgs _incoming = null!;
@@ -31,9 +31,9 @@ public int NativeAmqpProjection()
[Benchmark]
public int RelayerBindingProjection()
{
- var body = ServiceBusBinding.GetBody(_incoming);
- ServiceBusBinding.TryGetHeader(_incoming, "cloudEvents:type", out var type);
- return checked((int)body.Length) + type.Text!.Length + ServiceBusBinding.GetDeliveryCount(_incoming)!.Value;
+ var body = ServiceBusMessageBinding.GetBody(_incoming);
+ ServiceBusMessageBinding.TryGetHeader(_incoming, "cloudEvents:type", out var type);
+ return checked((int)body.Length) + type.Text!.Length + ServiceBusMessageBinding.GetDeliveryCount(_incoming)!.Value;
}
private sealed class BenchmarkReceiver : ServiceBusReceiver;
diff --git a/benchmarks/Relayer.Benchmarks/ServiceBusSendBenchmarks.cs b/benchmarks/Relayer.Benchmarks/ServiceBusSendBenchmarks.cs
index 41f3efa7f..d47cb5f5b 100644
--- a/benchmarks/Relayer.Benchmarks/ServiceBusSendBenchmarks.cs
+++ b/benchmarks/Relayer.Benchmarks/ServiceBusSendBenchmarks.cs
@@ -80,7 +80,7 @@ public async Task Setup()
await _admin.CreateQueueAsync(queueOptions);
_client = new(connection);
_raw = _client.CreateSender(_queue);
- var options = new AzureServiceBusTransportOptions { Client = _client };
+ var options = new ServiceBusTransportOptions { Client = _client };
options.Queues.Add(new(_queue));
_transport = new("benchmark", _client, false, options, [_queue], TopologyMode.None, tracing: _tracing);
_body = "{\"orderId\":42,\"customer\":\"customer-1\"}"u8.ToArray();
diff --git a/docs/design.md b/docs/design.md
index 69c603952..3fc39b901 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -121,7 +121,7 @@ public interface IMessageBinding
}
// Azure Service Bus: TIncoming is whatever the native receive callback hands over.
-public readonly struct ServiceBusBinding : IMessageBinding { … }
+public readonly struct ServiceBusMessageBinding : IMessageBinding { … }
```
`WireString` is a struct that holds a header value as the native client stores it: a UTF-16 `string` (ASB, SQS) or UTF-8 bytes (Kafka, RabbitMQ). The core compares and parses it in place, and converts it to a `string` only when user code asks. Header names come from the transport's `HeaderNames`, which encodes its CloudEvents protocol binding (`ce_` for Kafka, `cloudEvents:` for AMQP). Relayer's own attributes, such as the attempt count and error metadata, are CloudEvents extensions, so they follow the same binding.
@@ -129,7 +129,7 @@ public readonly struct ServiceBusBinding : IMessageBinding(consumer); // once, at startup
+var pipeline = pipelines.Create(consumer); // once, at startup
processor.ProcessMessageAsync += async args =>
{
diff --git a/src/Relayer.AmazonSqs/AmazonSqsTransportOptions.cs b/src/Relayer.AmazonSqs/AmazonSqsTransportOptions.cs
index c5ca09db7..1b102c8fe 100644
--- a/src/Relayer.AmazonSqs/AmazonSqsTransportOptions.cs
+++ b/src/Relayer.AmazonSqs/AmazonSqsTransportOptions.cs
@@ -1,4 +1,3 @@
-using Amazon.SimpleNotificationService;
using Amazon.SQS;
using Amazon.SQS.Model;
@@ -15,7 +14,4 @@ public sealed class AmazonSqsTransportOptions
/// Native SQS client configuration.
public AmazonSQSConfig Sqs { get; set; } = new();
-
- /// Native SNS client configuration.
- public AmazonSimpleNotificationServiceConfig Sns { get; set; } = new();
}
diff --git a/src/Relayer.AmazonSqs/SqsDelivery.cs b/src/Relayer.AmazonSqs/SqsDelivery.cs
index 2d88531bf..f72b6876f 100644
--- a/src/Relayer.AmazonSqs/SqsDelivery.cs
+++ b/src/Relayer.AmazonSqs/SqsDelivery.cs
@@ -9,7 +9,7 @@
namespace Relayer.AmazonSqs;
-/// A borrowed native SQS delivery, valid only until its handler and settlement complete.
+/// Receiver-owned SQS storage for transport authors. Applications use the borrowed SqsMessageContext view.
public sealed class SqsDelivery : IDisposable
{
private byte[] _buffer = [];
@@ -117,5 +117,24 @@ public static void EnrichActivity(Activity activity, SqsDelivery message)
public static class AmazonSqsMessageContextExtensions
{
/// Returns borrowed SQS native features for this delivery.
- public static SqsDelivery AmazonSqs(this MessageContext context) => context.Features.GetRequired>().Message;
+ public static SqsMessageContext AmazonSqs(this MessageContext context) =>
+ new(context.Features.GetRequired>().Message);
+}
+
+/// A borrowed native SQS view, valid only while this message is being processed.
+/// Do not retain this view or its native objects after processing. The receiver owns delivery storage and the native client lifetime.
+public readonly struct SqsMessageContext
+{
+ private readonly SqsDelivery _delivery;
+
+ internal SqsMessageContext(SqsDelivery delivery) => _delivery = delivery;
+
+ /// The unchanged native message.
+ public Message Message => _delivery.Message;
+ /// The native client, owned by the transport or caller.
+ public IAmazonSQS Client => _delivery.Client;
+ /// The resolved native queue URL.
+ public string QueueUrl => _delivery.QueueUrl;
+ /// The request identifier of the native receive.
+ public string? RequestId => _delivery.RequestId;
}
diff --git a/src/Relayer.AmazonSqs/SqsHostedService.cs b/src/Relayer.AmazonSqs/SqsHostedService.cs
index 573116011..d59ff16fb 100644
--- a/src/Relayer.AmazonSqs/SqsHostedService.cs
+++ b/src/Relayer.AmazonSqs/SqsHostedService.cs
@@ -54,7 +54,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
internal static OutgoingMessage Copy(MessageContext context, string sourceIdentityHeader = "ce_id", string deadIdentityHeader = "ce_id")
{
- var delivery = context.AmazonSqs();
+ var delivery = context.Features.GetRequired>().Message;
var attributes = delivery.Message.MessageAttributes;
var fifo = delivery.QueueUrl.EndsWith(".fifo", StringComparison.Ordinal);
var headers = new List>(attributes?.Count ?? 0);
diff --git a/src/Relayer.AzureServiceBus/AspireConnectionExtensions.cs b/src/Relayer.AzureServiceBus/AspireConnectionExtensions.cs
index c8a7421bd..6d33d3af9 100644
--- a/src/Relayer.AzureServiceBus/AspireConnectionExtensions.cs
+++ b/src/Relayer.AzureServiceBus/AspireConnectionExtensions.cs
@@ -8,8 +8,8 @@ public static class AspireConnectionExtensions
{
/// Sets a Relayer-owned Service Bus client's native connection string from ConnectionStrings:connectionName.
/// Native ClientOptions are unchanged. Do not also configure a caller-owned Client. Values are captured at registration.
- public static TransportBuilder UseAspireConnection(
- this TransportBuilder builder,
+ public static TransportBuilder UseAspireConnection(
+ this TransportBuilder builder,
IConfiguration configuration, string connectionName)
{
ArgumentNullException.ThrowIfNull(builder);
diff --git a/src/Relayer.AzureServiceBus/ServiceBusBuilderExtensions.cs b/src/Relayer.AzureServiceBus/ServiceBusBuilderExtensions.cs
index 5dd2a1890..81b3de8a3 100644
--- a/src/Relayer.AzureServiceBus/ServiceBusBuilderExtensions.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusBuilderExtensions.cs
@@ -15,12 +15,12 @@ public static class ServiceBusBuilderExtensions
{
/// Declares native queue/topic sending and queue or subscription processors.
public static IRelayerBuilder ServiceBus(this IRelayerBuilder builder, string name,
- Action> configure)
+ Action> configure)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(configure);
builder.Services.TryAddSingleton();
- builder.AddTransport(name, transport =>
+ builder.AddTransport(name, transport =>
{
transport.SendDefaults = new() { HeaderNames = new("cloudEvents:") };
configure(transport);
@@ -29,7 +29,7 @@ public static IRelayerBuilder ServiceBus(this IRelayerBuilder builder, string na
{
var configuration = provider.GetRequiredService();
var definition = configuration.Transports.Single(item => item.Name == name);
- var options = provider.GetRequiredService>().Get(name);
+ var options = provider.GetRequiredService>().Get(name);
if ((options.Client is null) == string.IsNullOrWhiteSpace(options.ConnectionString))
throw new InvalidOperationException($"Service Bus transport '{name}': configure exactly one of Client or ConnectionString.");
ArgumentNullException.ThrowIfNull(options.ClientOptions);
diff --git a/src/Relayer.AzureServiceBus/ServiceBusConsumer.cs b/src/Relayer.AzureServiceBus/ServiceBusConsumer.cs
index d45e01e6a..70b976943 100644
--- a/src/Relayer.AzureServiceBus/ServiceBusConsumer.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusConsumer.cs
@@ -58,7 +58,7 @@ internal ServiceBusConsumer(IConsumerDefinition declaration, ServiceBusSessionPr
processor.ProcessErrorAsync += ErrorAsync;
}
- internal static void ValidateDeclaration(string name, AzureServiceBusTransportOptions transport,
+ internal static void ValidateDeclaration(string name, ServiceBusTransportOptions transport,
ConsumerDefinition consumer)
{
var options = consumer.Options;
diff --git a/src/Relayer.AzureServiceBus/ServiceBusHostedService.cs b/src/Relayer.AzureServiceBus/ServiceBusHostedService.cs
index 18ee96262..d475201b0 100644
--- a/src/Relayer.AzureServiceBus/ServiceBusHostedService.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusHostedService.cs
@@ -53,7 +53,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
ServiceBusConsumer receiver;
if (consumer.Options.SessionProcessorOptions is { } sessionOptions)
{
- var receive = new ReceivePipeline(composed,
+ var receive = new ReceivePipeline(composed,
new("cloudEvents:"), consumer.Concurrency);
var native = consumer.Options.Subscription is { } sub
? _transport.Client.CreateSessionProcessor(consumer.Source, sub, sessionOptions)
@@ -62,7 +62,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
}
else
{
- var receive = new ReceivePipeline(composed,
+ var receive = new ReceivePipeline(composed,
new("cloudEvents:"), consumer.Concurrency);
var native = consumer.Options.Subscription is { } sub
? _transport.Client.CreateProcessor(consumer.Source, sub, consumer.Options.ProcessorOptions)
diff --git a/src/Relayer.AzureServiceBus/ServiceBusBinding.cs b/src/Relayer.AzureServiceBus/ServiceBusMessageBinding.cs
similarity index 87%
rename from src/Relayer.AzureServiceBus/ServiceBusBinding.cs
rename to src/Relayer.AzureServiceBus/ServiceBusMessageBinding.cs
index 0815a87de..c21f4d476 100644
--- a/src/Relayer.AzureServiceBus/ServiceBusBinding.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusMessageBinding.cs
@@ -6,7 +6,7 @@
namespace Relayer.AzureServiceBus;
/// Reads a native processor delivery without enumerating its headers.
-public readonly struct ServiceBusBinding : IMessageBinding
+public readonly struct ServiceBusMessageBinding : IMessageBinding
{
///
///
@@ -67,14 +67,14 @@ internal static void EnrichActivity(Activity activity, ServiceBusReceivedMessage
}
/// Reads the unchanged native session processor delivery through the same lazy Service Bus binding.
-public readonly struct ServiceBusSessionBinding : IMessageBinding
+public readonly struct ServiceBusSessionMessageBinding : IMessageBinding
{
///
- public static ReadOnlySequence GetBody(ProcessSessionMessageEventArgs message) => ServiceBusBinding.GetBody(message.Message);
+ public static ReadOnlySequence GetBody(ProcessSessionMessageEventArgs message) => ServiceBusMessageBinding.GetBody(message.Message);
///
public static int? GetDeliveryCount(ProcessSessionMessageEventArgs message) => message.Message.DeliveryCount;
///
- public static bool TryGetHeader(ProcessSessionMessageEventArgs message, string name, out WireString value) => ServiceBusBinding.TryGetHeader(message.Message, name, out value);
+ public static bool TryGetHeader(ProcessSessionMessageEventArgs message, string name, out WireString value) => ServiceBusMessageBinding.TryGetHeader(message.Message, name, out value);
///
- public static void EnrichActivity(Activity activity, ProcessSessionMessageEventArgs message) => ServiceBusBinding.EnrichActivity(activity, message.Message);
+ public static void EnrichActivity(Activity activity, ProcessSessionMessageEventArgs message) => ServiceBusMessageBinding.EnrichActivity(activity, message.Message);
}
diff --git a/src/Relayer.AzureServiceBus/ServiceBusSendTransport.cs b/src/Relayer.AzureServiceBus/ServiceBusSendTransport.cs
index ed2974b8f..5a45c6d47 100644
--- a/src/Relayer.AzureServiceBus/ServiceBusSendTransport.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusSendTransport.cs
@@ -22,7 +22,7 @@ internal sealed class ServiceBusSendTransport : ITransport, ITransportSendTracin
internal List Consumers { get; } = [];
internal bool HealthTracking { get; set; }
- internal static void ValidateDeclarations(string name, AzureServiceBusTransportOptions options, IEnumerable destinations)
+ internal static void ValidateDeclarations(string name, ServiceBusTransportOptions options, IEnumerable destinations)
{
var entities = new HashSet(StringComparer.Ordinal);
foreach (var queue in options.Queues)
@@ -48,7 +48,7 @@ internal static void ValidateDeclarations(string name, AzureServiceBusTransportO
}
internal ServiceBusSendTransport(string name, ServiceBusClient client, bool ownsClient,
- AzureServiceBusTransportOptions options, IEnumerable destinations, TopologyMode mode,
+ ServiceBusTransportOptions options, IEnumerable destinations, TopologyMode mode,
ServiceBusAdministrationClient? administration = null, MessageTracing? tracing = null, ILoggerFactory? logging = null, IReadOnlyList? consumers = null)
{
Name = name;
diff --git a/src/Relayer.AzureServiceBus/ServiceBusSettlement.cs b/src/Relayer.AzureServiceBus/ServiceBusSettlement.cs
index be042f1d6..f5c299991 100644
--- a/src/Relayer.AzureServiceBus/ServiceBusSettlement.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusSettlement.cs
@@ -81,8 +81,8 @@ internal async ValueTask ExecuteAsync(ServiceBusDelivery delivery, ServiceBusDis
using var activity = tracing.Start();
if (activity is { IsAllDataRequested: true })
{
- ServiceBusBinding.EnrichActivity(activity, delivery.Message);
- activity.SetTag("messaging.message.id", ServiceBusBinding.TryGetHeader(delivery.Message, "cloudEvents:id", out var id)
+ ServiceBusMessageBinding.EnrichActivity(activity, delivery.Message);
+ activity.SetTag("messaging.message.id", ServiceBusMessageBinding.TryGetHeader(delivery.Message, "cloudEvents:id", out var id)
? id.ToString() : delivery.Message.MessageId);
if (_subscription is not null) activity.SetTag("messaging.destination.subscription.name", _subscription);
activity.SetTag("messaging.servicebus.disposition_status", operation switch
diff --git a/src/Relayer.AzureServiceBus/ServiceBusTopology.cs b/src/Relayer.AzureServiceBus/ServiceBusTopology.cs
index c028b5052..81758602f 100644
--- a/src/Relayer.AzureServiceBus/ServiceBusTopology.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusTopology.cs
@@ -6,7 +6,7 @@
namespace Relayer.AzureServiceBus;
internal sealed class ServiceBusTopology(string name, ServiceBusClient client,
- AzureServiceBusTransportOptions options, ServiceBusAdministrationClient? administration,
+ ServiceBusTransportOptions options, ServiceBusAdministrationClient? administration,
IReadOnlyList? consumers = null, IReadOnlyCollection? destinations = null)
{
internal async ValueTask ApplyAsync(TopologyMode mode, CancellationToken cancellationToken)
diff --git a/src/Relayer.AzureServiceBus/ServiceBusTopologyExporter.cs b/src/Relayer.AzureServiceBus/ServiceBusTopologyExporter.cs
index b86dd5c73..64922b84b 100644
--- a/src/Relayer.AzureServiceBus/ServiceBusTopologyExporter.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusTopologyExporter.cs
@@ -20,10 +20,10 @@ public enum ServiceBusTopologyFormat
public sealed class ServiceBusTopologyExporter
{
private readonly ITopology _topology;
- private readonly IOptionsMonitor _options;
+ private readonly IOptionsMonitor _options;
/// Uses the existing topology and its named native options, without resolving runtime transports.
- public ServiceBusTopologyExporter(ITopology topology, IOptionsMonitor options)
+ public ServiceBusTopologyExporter(ITopology topology, IOptionsMonitor options)
{
ArgumentNullException.ThrowIfNull(topology);
ArgumentNullException.ThrowIfNull(options);
@@ -44,7 +44,7 @@ public void Export(string transportName, Stream destination, ServiceBusTopologyF
throw new ArgumentOutOfRangeException(nameof(format), "Choose Bicep or Terraform for Service Bus topology export.");
var declaration = _topology.Transports.SingleOrDefault(item => item.Name == transportName)
?? throw new InvalidOperationException($"No transport named '{transportName}' is declared.");
- if (declaration.OptionsType != typeof(AzureServiceBusTransportOptions))
+ if (declaration.OptionsType != typeof(ServiceBusTransportOptions))
throw new InvalidOperationException($"Transport '{transportName}' is not a Service Bus transport. Select a Service Bus declaration or use its transport's exporter.");
var options = _options.Get(transportName);
ServiceBusSendTransport.ValidateDeclarations(transportName, options, declaration.Routes.Select(route => route.Destination));
@@ -56,7 +56,7 @@ public void Export(string transportName, Stream destination, ServiceBusTopologyF
writer.Write(text);
}
- private static void ValidateConsumers(TransportDefinition transport, AzureServiceBusTransportOptions options)
+ private static void ValidateConsumers(TransportDefinition transport, ServiceBusTransportOptions options)
{
foreach (var consumer in transport.Consumers)
{
@@ -70,7 +70,7 @@ private static void ValidateConsumers(TransportDefinition transport, AzureServic
}
}
- private static List Build(AzureServiceBusTransportOptions options)
+ private static List Build(ServiceBusTransportOptions options)
{
var resources = new List();
var topics = new Dictionary(StringComparer.Ordinal);
diff --git a/src/Relayer.AzureServiceBus/AzureServiceBusTransportOptions.cs b/src/Relayer.AzureServiceBus/ServiceBusTransportOptions.cs
similarity index 97%
rename from src/Relayer.AzureServiceBus/AzureServiceBusTransportOptions.cs
rename to src/Relayer.AzureServiceBus/ServiceBusTransportOptions.cs
index f8e5c6190..f5da6b590 100644
--- a/src/Relayer.AzureServiceBus/AzureServiceBusTransportOptions.cs
+++ b/src/Relayer.AzureServiceBus/ServiceBusTransportOptions.cs
@@ -4,7 +4,7 @@
namespace Relayer.AzureServiceBus;
/// Options for the AzureServiceBus transport. Native client configuration is passed through unchanged (docs/decisions.md D1).
-public sealed class AzureServiceBusTransportOptions
+public sealed class ServiceBusTransportOptions
{
/// Connection string for a client owned and disposed by Relayer. Do not also set Client.
public string? ConnectionString { get; set; }
diff --git a/src/Relayer.Kafka/KafkaBuilderExtensions.cs b/src/Relayer.Kafka/KafkaBuilderExtensions.cs
index fd08b21e8..d3239107b 100644
--- a/src/Relayer.Kafka/KafkaBuilderExtensions.cs
+++ b/src/Relayer.Kafka/KafkaBuilderExtensions.cs
@@ -12,6 +12,10 @@ namespace Relayer.Kafka;
/// Registers named Kafka transports backed by Dekaf.
public static class KafkaBuilderExtensions
{
+ /// Customizes native Kafka headers immediately before single or batch sending.
+ public static SendOptions Kafka(this SendOptions options, Action configure) =>
+ options.ConfigureNative(configure);
+
/// Declares Kafka send routes and serial consumers with durable dead-letter copies.
public static IRelayerBuilder Kafka(this IRelayerBuilder builder, string name,
Action> configure)
diff --git a/tests/Relayer.AotSmoke/Program.cs b/tests/Relayer.AotSmoke/Program.cs
index 72712b0c0..84162d7f2 100644
--- a/tests/Relayer.AotSmoke/Program.cs
+++ b/tests/Relayer.AotSmoke/Program.cs
@@ -97,9 +97,9 @@ static void AssertSendAllocation(Relayer.TestFixtures.SendTracingCompletionFixtu
var serviceBusMessage = ServiceBusModelFactory.ServiceBusReceivedMessage(new BinaryData(new byte[] { 42 }),
properties: new Dictionary { ["cloudEvents:type"] = "smoke;v=1" }, deliveryCount: 2);
var serviceBusArgs = new ProcessMessageEventArgs(serviceBusMessage, new SmokeServiceBusReceiver(), "aot", default);
-if (ServiceBusBinding.GetBody(serviceBusArgs).First.Span[0] != 42 ||
- ServiceBusBinding.GetDeliveryCount(serviceBusArgs) != 2 ||
- !ServiceBusBinding.TryGetHeader(serviceBusArgs, "cloudEvents:type", out var serviceBusType) || serviceBusType.Text != "smoke;v=1")
+if (ServiceBusMessageBinding.GetBody(serviceBusArgs).First.Span[0] != 42 ||
+ ServiceBusMessageBinding.GetDeliveryCount(serviceBusArgs) != 2 ||
+ !ServiceBusMessageBinding.TryGetHeader(serviceBusArgs, "cloudEvents:type", out var serviceBusType) || serviceBusType.Text != "smoke;v=1")
throw new InvalidOperationException("Service Bus binding failed under Native AOT.");
var postgresConnectionString = Environment.GetEnvironmentVariable("RELAYER_AOT_POSTGRES_CONNECTION");
diff --git a/tests/Relayer.Aspire.Tests/AspireRegistrationTests.cs b/tests/Relayer.Aspire.Tests/AspireRegistrationTests.cs
index 9601b7269..9a73794e0 100644
--- a/tests/Relayer.Aspire.Tests/AspireRegistrationTests.cs
+++ b/tests/Relayer.Aspire.Tests/AspireRegistrationTests.cs
@@ -41,7 +41,7 @@ public async Task References_can_use_different_connection_and_transport_names_wi
var kafka = provider.GetRequiredService>().Get("events");
await Assert.That(kafka.BootstrapServers.ToArray()).IsEquivalentTo(new[] { "first:9092", "[::1]:9093" });
await Assert.That(kafka.ConfigureConsumer).IsSameReferenceAs(nativeConsumer);
- var bus = provider.GetRequiredService>().Get("commands");
+ var bus = provider.GetRequiredService>().Get("commands");
await Assert.That(bus.ConnectionString).IsEqualTo("native-connection");
await Assert.That(bus.ClientOptions).IsSameReferenceAs(nativeOptions);
await Assert.That(provider.GetRequiredService>().Get("other").BootstrapServers.Count).IsEqualTo(0);
diff --git a/tests/Relayer.Kafka.Tests/KafkaSendTests.cs b/tests/Relayer.Kafka.Tests/KafkaSendTests.cs
index 3f89cf613..64ce189ea 100644
--- a/tests/Relayer.Kafka.Tests/KafkaSendTests.cs
+++ b/tests/Relayer.Kafka.Tests/KafkaSendTests.cs
@@ -51,7 +51,7 @@ public async Task Borrows_utf8_memory_encodes_text_and_clears_native_headers_bet
var state = new KafkaSendState();
byte[] bytes = [1, 2, 3];
KeyValuePair[] headers = [new("bytes", new(bytes)), new("text", new("héllo"))];
- var options = new SendOptions().ConfigureNative(static native => native.Add("custom", "yes"));
+ var options = new SendOptions().Kafka(static native => native.Add("custom", "yes"));
state.Prepare(new("orders", bytes, headers, new WireString(bytes), options: options));
await Assert.That(state.Key!.Value.Utf8.Equals(bytes.AsMemory())).IsTrue();
await Assert.That(state.Headers[0].Value.Equals(bytes.AsMemory())).IsTrue();
@@ -101,7 +101,7 @@ public async Task Warm_send_preparation_and_native_serialization_allocate_zero_b
public async Task Native_callback_errors_and_mismatches_do_not_leak_prepared_headers()
{
var state = new KafkaSendState();
- var options = new SendOptions().ConfigureNative(static headers =>
+ var options = new SendOptions().Kafka(static headers =>
{
headers.Add("failed", "value");
throw new InvalidOperationException("callback failure");
diff --git a/tests/Relayer.Tests/RequestResponseTests.cs b/tests/Relayer.Tests/RequestResponseTests.cs
index 24cff6610..77f07f380 100644
--- a/tests/Relayer.Tests/RequestResponseTests.cs
+++ b/tests/Relayer.Tests/RequestResponseTests.cs
@@ -190,7 +190,7 @@ public async Task Native_Service_Bus_application_properties_correlate_a_reply()
["cloudEvents:id"] = "native-reply", ["cloudEvents:type"] = "tests.rpc.response;v=1",
["cloudEvents:correlationid"] = correlation,
});
- var receive = new ReceivePipeline(
+ var receive = new ReceivePipeline(
fixture.Pipeline(new ReplyDescriptor()), fixture.Names);
await receive.ProcessAsync(new ProcessMessageEventArgs(native, new Receiver(), "rpc", default));
await Assert.That((await request).Value).IsEqualTo(5);
diff --git a/tests/Relayer.Tests/ServiceBusConformanceTests.cs b/tests/Relayer.Tests/ServiceBusConformanceTests.cs
index 8d0019b8a..c28496447 100644
--- a/tests/Relayer.Tests/ServiceBusConformanceTests.cs
+++ b/tests/Relayer.Tests/ServiceBusConformanceTests.cs
@@ -19,7 +19,7 @@ public async Task Provision_restores_an_administration_created_queue_lost_on_emu
var queue = "reprovision-" + Guid.NewGuid().ToString("N");
await using var client = new ServiceBusClient(broker.ConnectionString);
var admin = new ServiceBusAdministrationClient(broker.AdministrationConnectionString);
- var options = new AzureServiceBusTransportOptions { Client = client };
+ var options = new ServiceBusTransportOptions { Client = client };
options.Queues.Add(new(queue) { DefaultMessageTimeToLive = TimeSpan.FromHours(1),
MaxSizeInMegabytes = 100, DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10) });
await using var transport = new ServiceBusSendTransport("reprovision", client, false, options,
@@ -53,7 +53,7 @@ public async Task Service_bus_emulator_passes_queue_and_session_transport_contra
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(8));
var token = timeout.Token;
var destination = "";
- var queues = new TransportConformanceSuite(
+ var queues = new TransportConformanceSuite(
(tracing, cancellation) => ServiceBusConformanceFixture.CreateAsync(broker, tracing, false, destination, cancellation),
TimeSpan.FromMinutes(2));
foreach (var scenario in destinations.Keys)
@@ -67,7 +67,7 @@ public async Task Service_bus_emulator_passes_queue_and_session_transport_contra
}
else await Assert.That(result.Skipped).IsFalse();
}
- var sessions = new TransportConformanceSuite(
+ var sessions = new TransportConformanceSuite(
(tracing, cancellation) => ServiceBusConformanceFixture.CreateAsync(broker, tracing, true, sessionDestination, cancellation),
TimeSpan.FromMinutes(2));
await Assert.That((await sessions.RunAsync(TransportConformanceCase.OrderingByKey, token)).Skipped).IsFalse();
@@ -83,14 +83,14 @@ public async Task Service_bus_graceful_stop_drains_native_processor(bool session
sessions ? [] : [destination], sessions ? [destination] : []);
if (sessions)
{
- var suite = new TransportConformanceSuite(
+ var suite = new TransportConformanceSuite(
(tracing, token) => ServiceBusConformanceFixture.CreateAsync(broker, tracing, true, destination, token),
TimeSpan.FromMinutes(2));
await Assert.That((await suite.RunAsync(TransportConformanceCase.CleanShutdown)).Skipped).IsFalse();
}
else
{
- var suite = new TransportConformanceSuite(
+ var suite = new TransportConformanceSuite(
(tracing, token) => ServiceBusConformanceFixture.CreateAsync(broker, tracing, false, destination, token),
TimeSpan.FromMinutes(2));
await Assert.That((await suite.RunAsync(TransportConformanceCase.CleanShutdown)).Skipped).IsFalse();
@@ -138,7 +138,7 @@ private ServiceBusConformanceFixture(ServiceBusReceiveBroker broker, MessageTrac
var options = new ServiceBusConsumerOptions();
if (sessions) options.SessionProcessorOptions = new() { AutoCompleteMessages = false, MaxConcurrentSessions = 1 };
_declaration = new(Destination, options, [], 1, 1, TimeSpan.FromMilliseconds(100));
- var native = new AzureServiceBusTransportOptions { Client = _client };
+ var native = new ServiceBusTransportOptions { Client = _client };
native.Queues.Add(new(Destination) { RequiresSession = sessions, DefaultMessageTimeToLive = TimeSpan.FromHours(1) });
_transport = new("conformance", _client, true, native, [Destination], TopologyMode.Provision, _admin, tracing, _logs,
consumers: [_declaration]);
diff --git a/tests/Relayer.Tests/ServiceBusBindingEmulatorTests.cs b/tests/Relayer.Tests/ServiceBusMessageBindingEmulatorTests.cs
similarity index 97%
rename from tests/Relayer.Tests/ServiceBusBindingEmulatorTests.cs
rename to tests/Relayer.Tests/ServiceBusMessageBindingEmulatorTests.cs
index 0a44ea52b..5f367b6f9 100644
--- a/tests/Relayer.Tests/ServiceBusBindingEmulatorTests.cs
+++ b/tests/Relayer.Tests/ServiceBusMessageBindingEmulatorTests.cs
@@ -10,7 +10,7 @@
namespace Relayer.Tests;
-public partial class ServiceBusBindingTests
+public partial class ServiceBusMessageBindingTests
{
[Test]
[Arguments(false)]
@@ -56,7 +56,7 @@ public async Task Native_settlement_round_trips_against_service_bus_emulator(boo
await Assert.That(context.ServiceBus().Message.ApplicationProperties.ContainsKey("content-type")).IsFalse();
await Assert.That(context.Headers.TryGetValue("content-type", out var contentType)).IsTrue();
await Assert.That(contentType.Text).IsEqualTo(outgoing.ContentType);
- await Assert.That(ServiceBusBinding.GetBody(context.ServiceBus().Callback).First.Span[0]).IsEqualTo((byte)42);
+ await Assert.That(ServiceBusMessageBinding.GetBody(context.ServiceBus().Callback).First.Span[0]).IsEqualTo((byte)42);
await Settle(context.ServiceBus(), operation, properties);
};
var args = new ProcessMessageEventArgs(incoming, receiver, "emulator", token);
diff --git a/tests/Relayer.Tests/ServiceBusBindingTests.cs b/tests/Relayer.Tests/ServiceBusMessageBindingTests.cs
similarity index 91%
rename from tests/Relayer.Tests/ServiceBusBindingTests.cs
rename to tests/Relayer.Tests/ServiceBusMessageBindingTests.cs
index 8a572328f..2fd7a329f 100644
--- a/tests/Relayer.Tests/ServiceBusBindingTests.cs
+++ b/tests/Relayer.Tests/ServiceBusMessageBindingTests.cs
@@ -9,7 +9,7 @@
namespace Relayer.Tests;
-public partial class ServiceBusBindingTests
+public partial class ServiceBusMessageBindingTests
{
[Test]
public async Task Binding_preserves_sdk_multi_section_body_conversion()
@@ -17,7 +17,7 @@ public async Task Binding_preserves_sdk_multi_section_body_conversion()
var message = Args(new RecordingReceiver()).Message;
message.GetRawAmqpMessage().Body = AmqpMessageBody.FromData(new ReadOnlyMemory[] { new byte[] { 1, 2 }, new byte[] { 3 } });
var args = new ProcessMessageEventArgs(message, new RecordingReceiver(), "multi-section", default);
- await Assert.That(ServiceBusBinding.GetBody(args).ToArray().AsSpan().SequenceEqual(message.Body.ToMemory().Span)).IsTrue();
+ await Assert.That(ServiceBusMessageBinding.GetBody(args).ToArray().AsSpan().SequenceEqual(message.Body.ToMemory().Span)).IsTrue();
}
[Test]
@@ -34,19 +34,19 @@ public async Task Binding_borrows_native_body_and_reads_only_requested_text_or_b
});
var args = new ProcessMessageEventArgs(message, new RecordingReceiver(), "test", default);
- await Assert.That(ServiceBusBinding.GetBody(args).First.Equals(body.ToMemory())).IsTrue();
- await Assert.That(ServiceBusBinding.GetDeliveryCount(args)).IsEqualTo(7);
- await Assert.That(ServiceBusBinding.TryGetHeader(args, "cloudEvents:type", out var value)).IsTrue();
+ await Assert.That(ServiceBusMessageBinding.GetBody(args).First.Equals(body.ToMemory())).IsTrue();
+ await Assert.That(ServiceBusMessageBinding.GetDeliveryCount(args)).IsEqualTo(7);
+ await Assert.That(ServiceBusMessageBinding.TryGetHeader(args, "cloudEvents:type", out var value)).IsTrue();
await Assert.That(value.Text).IsSameReferenceAs(text);
foreach (var name in new[] { "binary", "memory", "segment" })
{
- await Assert.That(ServiceBusBinding.TryGetHeader(args, name, out value)).IsTrue();
+ await Assert.That(ServiceBusMessageBinding.TryGetHeader(args, name, out value)).IsTrue();
await Assert.That(value.Text).IsNull();
await Assert.That(value.Utf8.Equals((ReadOnlyMemory)binary)).IsTrue();
}
- await Assert.That(ServiceBusBinding.TryGetHeader(args, "missing", out value)).IsFalse();
+ await Assert.That(ServiceBusMessageBinding.TryGetHeader(args, "missing", out value)).IsFalse();
await Assert.That(value.IsEmpty).IsTrue();
- await Assert.That(ServiceBusBinding.TryGetHeader(args, "number", out _)).IsFalse();
+ await Assert.That(ServiceBusMessageBinding.TryGetHeader(args, "number", out _)).IsFalse();
await Assert.That(message.ApplicationProperties["number"]).IsEqualTo(42);
}
@@ -63,11 +63,11 @@ public async Task Binding_reads_native_content_type_before_application_property(
var message = ServiceBusModelFactory.ServiceBusReceivedMessage(contentType: native, properties: properties);
var args = new ProcessMessageEventArgs(message, new RecordingReceiver(), "content-type", default);
- var found = ServiceBusBinding.TryGetHeader(args, "content-type", out var value);
+ var found = ServiceBusMessageBinding.TryGetHeader(args, "content-type", out var value);
var expected = native ?? fallback;
await Assert.That(found).IsEqualTo(expected is not null);
await Assert.That(value.Text).IsSameReferenceAs(expected);
- await Assert.That(ServiceBusBinding.TryGetHeader(args, "other", out value)).IsTrue();
+ await Assert.That(ServiceBusMessageBinding.TryGetHeader(args, "other", out value)).IsTrue();
await Assert.That(value.Text).IsEqualTo("unchanged");
await Assert.That(message.ContentType).IsEqualTo(native);
await Assert.That(message.ApplicationProperties.ContainsKey("content-type")).IsEqualTo(fallback is not null);
@@ -106,10 +106,10 @@ public async Task Binding_does_not_allocate_after_warmup(bool nativeContentType)
static void Read(ProcessMessageEventArgs args)
{
- _ = ServiceBusBinding.GetBody(args);
- _ = ServiceBusBinding.GetDeliveryCount(args);
- if (!ServiceBusBinding.TryGetHeader(args, "cloudEvents:type", out _)) throw new InvalidOperationException();
- if (!ServiceBusBinding.TryGetHeader(args, "content-type", out _)) throw new InvalidOperationException();
+ _ = ServiceBusMessageBinding.GetBody(args);
+ _ = ServiceBusMessageBinding.GetDeliveryCount(args);
+ if (!ServiceBusMessageBinding.TryGetHeader(args, "cloudEvents:type", out _)) throw new InvalidOperationException();
+ if (!ServiceBusMessageBinding.TryGetHeader(args, "content-type", out _)) throw new InvalidOperationException();
}
}
@@ -228,7 +228,7 @@ private static ServiceProvider Provider()
return services.BuildServiceProvider();
}
- private static ReceivePipeline Pipeline(ServiceProvider provider)
+ private static ReceivePipeline Pipeline(ServiceProvider provider)
{
var consumer = new ConsumePipelineBuilder(provider.GetRequiredService(),
provider.GetRequiredService(), new Serializer(), static (_, error, _) => ValueTask.FromException(error))
diff --git a/tests/Relayer.Tests/ServiceBusReceiveTopologyTests.cs b/tests/Relayer.Tests/ServiceBusReceiveTopologyTests.cs
index 093bff823..906fbef8e 100644
--- a/tests/Relayer.Tests/ServiceBusReceiveTopologyTests.cs
+++ b/tests/Relayer.Tests/ServiceBusReceiveTopologyTests.cs
@@ -11,7 +11,7 @@ public sealed class ServiceBusReceiveTopologyTests
public async Task Receive_only_validation_uses_Listen_peeks_without_opening_Send_links()
{
var client = new ListenClient();
- var options = new AzureServiceBusTransportOptions { Client = client };
+ var options = new ServiceBusTransportOptions { Client = client };
options.Queues.Add(new("orders"));
options.Topics.Add(new("events"));
options.Subscriptions.Add(new("events", "audit"));
@@ -30,7 +30,7 @@ public async Task Receive_only_validation_uses_Listen_peeks_without_opening_Send
public async Task Trusted_session_subscription_still_validates_a_declared_consumers_Listen_link()
{
var client = new ListenClient();
- var options = new AzureServiceBusTransportOptions { Client = client };
+ var options = new ServiceBusTransportOptions { Client = client };
options.Topics.Add(new("events"));
options.Subscriptions.Add(new("events", "audit") { RequiresSession = true });
options.TrustedSessionEntities.Add("events/Subscriptions/audit");
diff --git a/tests/Relayer.Tests/ServiceBusSendDurationTests.cs b/tests/Relayer.Tests/ServiceBusSendDurationTests.cs
index 8b7a17cb9..21bba3880 100644
--- a/tests/Relayer.Tests/ServiceBusSendDurationTests.cs
+++ b/tests/Relayer.Tests/ServiceBusSendDurationTests.cs
@@ -209,7 +209,7 @@ public ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellation
private static ServiceBusSendTransport Transport(ServiceBusSendTests.NativeClient client, MessageTracing tracing)
{
- var options = new AzureServiceBusTransportOptions { Client = client };
+ var options = new ServiceBusTransportOptions { Client = client };
options.Queues.Add(new("orders"));
options.Topics.Add(new("events"));
return new("bus", client, false, options, ["orders", "events"], TopologyMode.None, tracing: tracing);
diff --git a/tests/Relayer.Tests/ServiceBusSendEmulatorTests.cs b/tests/Relayer.Tests/ServiceBusSendEmulatorTests.cs
index 992e8cdcd..d15ac45a1 100644
--- a/tests/Relayer.Tests/ServiceBusSendEmulatorTests.cs
+++ b/tests/Relayer.Tests/ServiceBusSendEmulatorTests.cs
@@ -35,7 +35,7 @@ public async Task Native_sends_batches_sessions_scheduling_and_topology_round_tr
using var capture = new SendDurationCapture(instrumentation);
await using var client = new ServiceBusClient(emulator.GetConnectionString());
var admin = new ServiceBusAdministrationClient(emulator.GetHttpConnectionString());
- var options = new AzureServiceBusTransportOptions { Client = client, AdministrationClient = admin };
+ var options = new ServiceBusTransportOptions { Client = client, AdministrationClient = admin };
// Match the emulator's documented TTL/size quotas and its duplicate-window default.
options.Queues.Add(new("send-orders") { DefaultMessageTimeToLive = TimeSpan.FromHours(1), MaxSizeInMegabytes = 100, DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10) });
options.Queues.Add(new("send-sessions") { RequiresSession = true, DefaultMessageTimeToLive = TimeSpan.FromHours(1), MaxSizeInMegabytes = 100, DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10) });
@@ -109,7 +109,7 @@ await Assert.That(capture.Values.All(value => value.Seconds > 0 &&
// Externally managed session queues work with least-privilege topology modes.
foreach (var mode in new[] { TopologyMode.Validate, TopologyMode.None })
{
- var trustedOptions = new AzureServiceBusTransportOptions { Client = client };
+ var trustedOptions = new ServiceBusTransportOptions { Client = client };
trustedOptions.Queues.Add(new("send-sessions") { RequiresSession = true });
trustedOptions.TrustedSessionEntities.Add("send-sessions");
await using var trusted = new ServiceBusSendTransport("trusted", client, false, trustedOptions,
@@ -124,7 +124,7 @@ await Assert.That(capture.Values.All(value => value.Seconds > 0 &&
await Assert.That(received.SessionId).IsEqualTo(key);
await trustedSession.CompleteMessageAsync(received, token);
- var untrustedOptions = new AzureServiceBusTransportOptions { Client = client };
+ var untrustedOptions = new ServiceBusTransportOptions { Client = client };
untrustedOptions.Queues.Add(new("send-sessions") { RequiresSession = true });
await using var untrusted = new ServiceBusSendTransport("untrusted", client, false, untrustedOptions,
["send-sessions"], mode);
diff --git a/tests/Relayer.Tests/ServiceBusSendTests.cs b/tests/Relayer.Tests/ServiceBusSendTests.cs
index f6228301f..73208dbb4 100644
--- a/tests/Relayer.Tests/ServiceBusSendTests.cs
+++ b/tests/Relayer.Tests/ServiceBusSendTests.cs
@@ -34,7 +34,7 @@ public async Task Named_registration_preserves_native_options_and_caller_ownersh
});
await using (var provider = services.BuildServiceProvider())
{
- var options = provider.GetRequiredService>();
+ var options = provider.GetRequiredService>();
await Assert.That(options.Get("first").ClientOptions).IsSameReferenceAs(nativeOptions);
await Assert.That(options.Get("second").Client).IsSameReferenceAs(second);
var transports = provider.GetServices().ToArray();
@@ -436,9 +436,9 @@ public async Task Invalid_ownership_undeclared_entities_and_consumers_fail_befor
await Assert.That(client.Senders.Count).IsEqualTo(0);
}
- internal static AzureServiceBusTransportOptions Options(ServiceBusClient client, bool sessions = false)
+ internal static ServiceBusTransportOptions Options(ServiceBusClient client, bool sessions = false)
{
- var options = new AzureServiceBusTransportOptions { Client = client };
+ var options = new ServiceBusTransportOptions { Client = client };
options.Queues.Add(new("orders") { RequiresSession = sessions });
options.Topics.Add(new("events"));
return options;
diff --git a/tests/Relayer.Tests/ServiceBusTopologyExportTests.cs b/tests/Relayer.Tests/ServiceBusTopologyExportTests.cs
index 2e6632f69..1cda5822e 100644
--- a/tests/Relayer.Tests/ServiceBusTopologyExportTests.cs
+++ b/tests/Relayer.Tests/ServiceBusTopologyExportTests.cs
@@ -234,7 +234,7 @@ public async Task Missing_native_consumer_entity_is_not_silently_dropped(bool su
{
var definition = new ConsumerDefinition("missing", new() { Subscription = subscription ? "sub" : null },
[], 1, 1, TimeSpan.FromMilliseconds(100));
- var topology = new DeclarationTopology(new("bus", typeof(AzureServiceBusTransportOptions), [], [definition], null, (_, _) => { }));
+ var topology = new DeclarationTopology(new("bus", typeof(ServiceBusTransportOptions), [], [definition], null, (_, _) => { }));
var exporter = new ServiceBusTopologyExporter(topology, new OptionsMonitor(new()));
using var stream = new MemoryStream();
await Assert.That(() => exporter.Export("bus", stream, ServiceBusTopologyFormat.Bicep)).Throws();
@@ -244,11 +244,11 @@ public async Task Missing_native_consumer_entity_is_not_silently_dropped(bool su
[Test]
public async Task Consumer_subscription_and_queue_entities_export_without_runtime_processors()
{
- var options = new AzureServiceBusTransportOptions();
+ var options = new ServiceBusTransportOptions();
options.Queues.Add(new("queue"));
options.Topics.Add(new("topic"));
options.Subscriptions.Add(new("topic", "sub"));
- var topology = new DeclarationTopology(new("bus", typeof(AzureServiceBusTransportOptions), [],
+ var topology = new DeclarationTopology(new("bus", typeof(ServiceBusTransportOptions), [],
[new ConsumerDefinition("queue", new(), [], 1, 1, TimeSpan.FromMilliseconds(100)),
new ConsumerDefinition("topic", new() { Subscription = "sub" }, [], 1, 1, TimeSpan.FromMilliseconds(100))],
null, (_, _) => { }));
@@ -256,7 +256,7 @@ public async Task Consumer_subscription_and_queue_entities_export_without_runtim
await Assert.That(output).Contains("name: 'sub'");
}
- private static ServiceProvider Provider(Action configure)
+ private static ServiceProvider Provider(Action configure)
{
var services = new ServiceCollection();
services.AddRelayer(builder =>
@@ -286,11 +286,11 @@ private static string ResourceBody(string document, string symbol, ServiceBusTop
return end < 0 ? document[start..] : document[start..end];
}
- private sealed class OptionsMonitor(AzureServiceBusTransportOptions options) : IOptionsMonitor
+ private sealed class OptionsMonitor(ServiceBusTransportOptions options) : IOptionsMonitor
{
- public AzureServiceBusTransportOptions CurrentValue => options;
- public AzureServiceBusTransportOptions Get(string? name) => options;
- public IDisposable? OnChange(Action listener) => null;
+ public ServiceBusTransportOptions CurrentValue => options;
+ public ServiceBusTransportOptions Get(string? name) => options;
+ public IDisposable? OnChange(Action listener) => null;
}
private sealed class DeclarationTopology(TransportDefinition declaration) : ITopology
diff --git a/tests/Relayer.Tests/SqsReceiveTests.cs b/tests/Relayer.Tests/SqsReceiveTests.cs
index fad5f7b62..4e86ed8e8 100644
--- a/tests/Relayer.Tests/SqsReceiveTests.cs
+++ b/tests/Relayer.Tests/SqsReceiveTests.cs
@@ -37,6 +37,42 @@ public async Task Binding_reuses_body_and_native_objects_and_combines_copy_and_r
await Assert.That(retries.ToString()).IsEqualTo("0");
}
+ [Test]
+ public async Task Context_borrows_native_objects_without_exposing_receiver_ownership()
+ {
+ using var client = new ReceiveClient();
+ using var delivery = new SqsDelivery(client, "url");
+ var message = Message("body", 1);
+ delivery.Prepare(message, TimeProvider.System.GetTimestamp(), "request");
+ var context = new NativeContext();
+ context.Features.Set(new NativeMessage { Message = delivery });
+
+ SqsMessageContext view = context.AmazonSqs();
+ await Assert.That(view.Message).IsSameReferenceAs(message);
+ await Assert.That(view.Client).IsSameReferenceAs(client);
+ await Assert.That(view.QueueUrl).IsEqualTo("url");
+ await Assert.That(view.RequestId).IsEqualTo("request");
+ await Assert.That((object)view is IDisposable).IsFalse();
+
+ // Processing a later message must still be able to reuse receiver-owned storage.
+ delivery.Clear();
+ var next = Message("next", 1);
+ delivery.Prepare(next, TimeProvider.System.GetTimestamp(), null);
+ await Assert.That(context.AmazonSqs().Message).IsSameReferenceAs(next);
+ await Assert.That(context.AmazonSqs().RequestId).IsNull();
+ }
+
+ private sealed class NativeContext : MessageContext
+ {
+ public override string MessageId => "id";
+ public override MessageType MessageType => default;
+ public override MessageHeaders Headers => MessageHeaders.Empty;
+ public override int Attempt => 1;
+ public override IServiceProvider Services => throw new NotSupportedException();
+ public override MessageFeatures Features { get; } = new();
+ public override CancellationToken CancellationToken => default;
+ }
+
[Test]
public async Task Receive_errors_retry_without_permanently_losing_worker()
{
diff --git a/website/docs/guides/topology.md b/website/docs/guides/topology.md
index 1046ed7db..4bbce008b 100644
--- a/website/docs/guides/topology.md
+++ b/website/docs/guides/topology.md
@@ -47,7 +47,7 @@ JSON export uses schema version 1, transport declaration order, effective modes,
## Service Bus infrastructure export
-`Relayer.AzureServiceBus` provides `ServiceBusTopologyExporter` for **one explicitly selected named Service Bus transport**. It reads `ITopology` and the same named `AzureServiceBusTransportOptions` used by the application, including native `CreateQueueOptions`, `CreateTopicOptions` and `CreateSubscriptionOptions`. It does not create clients, resolve runtime adapters, start the host, connect to Azure or provision anything. Other named transports are outside this selection; exporting one of them through this exporter fails.
+`Relayer.AzureServiceBus` provides `ServiceBusTopologyExporter` for **one explicitly selected named Service Bus transport**. It reads `ITopology` and the same named `ServiceBusTransportOptions` used by the application, including native `CreateQueueOptions`, `CreateTopicOptions` and `CreateSubscriptionOptions`. It does not create clients, resolve runtime adapters, start the host, connect to Azure or provision anything. Other named transports are outside this selection; exporting one of them through this exporter fails.
Here is a standalone export application. Create a .NET 10 console project, add `Relayer.AzureServiceBus` and `Microsoft.Extensions.DependencyInjection`, and replace `Program.cs` with:
diff --git a/website/docs/transports/amazon-sqs.md b/website/docs/transports/amazon-sqs.md
index 9e5ccf70d..420d592f9 100644
--- a/website/docs/transports/amazon-sqs.md
+++ b/website/docs/transports/amazon-sqs.md
@@ -76,7 +76,7 @@ Each worker owns one reusable native `ReceiveMessageRequest`, receives one messa
FIFO ordering comes from SQS's invisible-message-group semantics, including across application instances. No group dispatcher is added. Set native visibility long enough for all durable work and in-process retries: this adapter does not renew visibility automatically, and native expiration can cause duplicate delivery and release the group. Graceful stop cancels polls while draining active work; the host's drain deadline cancels processing. An aborted drain requires a new host. The SDK owns request retries. Workers issue another poll after any exhausted native request failure, with cancellable exponential backoff from one to thirty seconds, reset by a successful poll. This also allows recovery after credentials, permissions or queue availability change; persistent configuration errors remain visible in warning logs.
-`context.AmazonSqs()` exposes the borrowed native `Message`, `IAmazonSQS`, queue URL and receive request ID. Keep these references within the handler lifetime. Use the portable settlement feature for completion, retry or dead-letter decisions so settlement follows durable work.
+`context.AmazonSqs()` returns a readonly `SqsMessageContext` view exposing the borrowed native `Message`, `IAmazonSQS`, queue URL and receive request ID. Keep these references within the handler lifetime. The view has no disposal API; the receiver owns and reuses the underlying delivery storage. Use the portable settlement feature for completion, retry or dead-letter decisions so settlement follows durable work.
Consumers use the default `ce_` CloudEvents headers. For a custom send binding such as `new HeaderNames("event_")`, set `consumer.Options.HeaderNames` to the same binding. The receiver uses it for envelope decoding and preserves those attributes in failure copies.
@@ -157,7 +157,7 @@ Native request, entry and attribute containers are pooled per concurrent operati
## SNS topic publishing
-Use the same package and sender API with an explicit SNS transport and native topic declarations:
+Use the same package and sender API with an explicit SNS transport and native topic declarations. Configure SNS through `AmazonSnsTransportOptions.Sns`; SQS transport options configure only SQS and do not contain an SNS client configuration:
```csharp
relayer.AmazonSns("events", sns =>
diff --git a/website/docs/transports/authoring.md b/website/docs/transports/authoring.md
index 94b6a79be..ed9057c31 100644
--- a/website/docs/transports/authoring.md
+++ b/website/docs/transports/authoring.md
@@ -31,6 +31,70 @@ Generated code accesses message/handler/upcaster registries through `builder.Inf
`SendOptions.ConfigureNative` remains application-facing. Adapters import `Relayer.Transports` to call `options.ApplyNative(native)` and persistence integrations call `options.HasNativeConfigurators()`; neither is an application-facing instance member. Prefer `OutgoingMessage.ApplyNative` and `ValidateForOutbox` when working with an outgoing message. Consumer pipeline composition and serializer resolution use `Relayer.Pipeline.ConsumerPipelineExtensions.ConfigureConsumer` and `Relayer.Transports.TransportServiceProviderExtensions.GetMessageSerializer`.
+## Naming and borrowed native access
+
+Use the transport's application name followed by the concept: `KafkaTransportOptions`,
+`ServiceBusTransportOptions`, `AmazonSqsTransportOptions` and `RabbitMqTransportOptions`.
+Consumer settings use `ConsumerOptions`; an `IMessageBinding` implementation uses
+`MessageBinding` (`ServiceBusMessageBinding`, for example). `RabbitMqBinding` represents a
+native exchange-to-queue topology binding, so its name describes a different concept.
+Keep native product spelling on fluent extensions (`RabbitMQ`) and normal .NET casing on types (`RabbitMq`).
+
+`relayer.Kafka(...)`, `relayer.ServiceBus(...)`, `relayer.AmazonSqs(...)` and
+`relayer.RabbitMQ(...)` declare a transport. `UseJsonSerializer` selects a serializer on a
+builder; `services.AddRelayerTenancy` and `services.AddRelayerHarness` register services.
+These verbs describe different operations and are not aliases for transport registration.
+
+Kafka, Service Bus, SQS and RabbitMQ `context.()` accessors return borrowed readonly struct views. The view
+exposes native objects unchanged; it never transfers their ownership. Keep the view,
+messages, body memory, callbacks and native clients within the processing lifetime. A
+struct copy does not extend that lifetime. Receiver storage such as `SqsDelivery` is an
+authoring detail; application handlers use `SqsMessageContext`, which has no disposal API.
+
+```csharp
+var kafkaRecord = context.Kafka().ConsumeResult;
+var serviceBusMessage = context.ServiceBus().Message;
+var sqsMessage = context.AmazonSqs().Message;
+var rabbitDelivery = context.RabbitMQ().Message;
+```
+
+Each line belongs in a handler for that transport. Wrong-transport access fails instead
+of returning an empty substitute. Native settlement remains transport-specific: Service
+Bus exposes callback operations through its view; other transports retain their existing
+native settlement contracts. Prefer portable settlement when the pipeline must perform
+durable work before acknowledging.
+
+For native per-send customization, expose `SendOptions.(Action)`
+only when the adapter actually applies that native type:
+
+```csharp
+var kafka = new SendOptions().Kafka(headers => headers.Add("source", "billing"));
+var serviceBus = new SendOptions().ServiceBus(message => message.Subject = "invoice");
+var sqs = new SendOptions().AmazonSqs(request => request.DelaySeconds = 5);
+var rabbit = new SendOptions().RabbitMQ(properties => properties.Priority = 3);
+```
+
+These callbacks run before the native send; they cannot be persisted in an outbox.
+Native capabilities still differ. Kafka exposes its native `Dekaf.Serialization.Headers`
+through this seam, not an entire producer record.
+[Dekaf 1.27.0](https://github.com/thomhurst/Dekaf/blob/48edcaa1065edf0ff76bc35b9a7f174e43a3bb6b/src/Dekaf/Producer/IKafkaProducer.cs#L522-L554) supports `ProducerMessage.Partition` and `Timestamp`, but Relayer's current
+producer path uses its allocation-free key/value overload. A future Kafka seam must wrap
+that existing native support and preserve the send-path performance contract; do not
+promise those settings through the current API or emulate partition selection. This
+separate runtime feature is tracked in [#738](https://github.com/thomhurst/Relayer/issues/738).
+
+Transport `Options` is a named `OptionsBuilder` for client-level configuration.
+Consumer `Options` is the declaration's own mutable options instance, captured at startup.
+It can still bind from configuration with `configuration.GetSection("OrdersConsumer").Bind(consumer.Options)`
+when the application's configuration binder is enabled; this does not add reload to an
+already composed consumer. Do not replace native client configuration types with portable copies.
+
+`BackgroundService` versus `IHostedService` is an implementation choice driven by the
+native client's polling or callback lifecycle, not an application contract. Likewise,
+dead-letter management and circuit pause/resume are advertised only by adapters that
+implement them with native facilities. Do not synthesize missing broker features to
+make a capability table look uniform.
+
## Registration
`RelayerInfrastructureExtensions.AddTransport` is the core seam for a transport package's typed registration extension. It declares routes and consumers; it does not substitute for a native client or start a broker receive loop. The application-side call site is in [Configuration](../guides/configuration.md), with executable coverage in `BuilderTests`.
@@ -118,7 +182,7 @@ The seam borrows prepared headers and batch memory until the native delegate com
Each endpoint retains send preparation and continuation storage up to its observed concurrency high-water mark, including workloads above 64 overlapping single or batch sends. Prepared headers and batch memory stay exclusive until the native delegate completes, including failure or cancellation. The continuation slot stays reserved until the caller consumes its returned `ValueTask`, so await each send exactly once. Native completion on a different thread does not discard warmed continuation storage. Initial concurrency growth and larger batches can allocate; repeated bursts at the warmed concurrency and batch size reuse that storage without per-message locks. Each slot retains its largest preparation arrays and header buffers for the endpoint lifetime, so a temporary concurrency or batch-size spike can increase retained memory. `System.Diagnostics` activity allocations remain separate. Run `SendTracingConcurrencyBenchmarks` for complete burst costs with dropped and recorded spans, and `SendTracingCompletionBenchmarks` for cross-thread native completion with a synchronous outer caller. `SendTracingPoolTests` also verifies asynchronously awaited callers.
-`InMemoryTransport` implements this seam. DI registration supplies `MessageTracing` automatically. For a standalone instance, pass `tracing:` to its constructor. Its homogeneous batches use one batch span; mixed-destination batches retain native input order and use one single-message span per message. The Kafka producer adapter also implements this seam. Other broker adapters must provide this integration when implemented.
+`InMemoryTransport` implements this seam. DI registration supplies `MessageTracing` automatically. For a standalone instance, pass `tracing:` to its constructor. Its homogeneous batches use one batch span; mixed-destination batches retain native input order and use one single-message span per message. The Kafka, Service Bus, SQS/SNS and RabbitMQ adapters also implement this seam. New adapters must provide this integration.
Run the reusable [transport conformance suite](conformance.md) against the real broker or emulator before shipping an adapter.
diff --git a/website/docs/transports/kafka.md b/website/docs/transports/kafka.md
index e4d8b971a..546a3b72f 100644
--- a/website/docs/transports/kafka.md
+++ b/website/docs/transports/kafka.md
@@ -319,3 +319,11 @@ Use the same native TLS/SASL settings on all three builders when the cluster req
`Relayer.AspNetCore` exposes this named Kafka manager through the [shared HTTP management endpoints](service-bus.md#optional-http-management). Pass the Kafka transport's registered name to `MapRelayerDeadLetters`, and use a configured dead-letter topic as `source`. Apply the application's authentication and authorization policy as shown there; mapping alone does not secure inspection or destructive operations.
The HTTP API returns message IDs and base64-encoded body bytes, without native feature objects. A tombstone and an empty body both appear as empty bytes; use `IDeadLetterManager` directly to inspect `KafkaDeadLetterFeature.Record.Value`. HTTP redrive preserves tombstones and follows the same group-offset and filter rules above, and HTTP purge permanently deletes partition prefixes for all groups.
+
+## Native per-send headers
+
+Use `new SendOptions().Kafka(headers => headers.Add("source", "billing"))` to customize
+native `Dekaf.Serialization.Headers` before sending. This wraps the existing native
+header callback seam and works for single and batch sends. Native callbacks cannot be
+persisted in an outbox. Partition and timestamp overrides are not exposed per send;
+the configured Dekaf producer still chooses the partition using its native partitioner.
diff --git a/website/docs/transports/service-bus-receive.md b/website/docs/transports/service-bus-receive.md
index 500f1f4ad..6b5681eaf 100644
--- a/website/docs/transports/service-bus-receive.md
+++ b/website/docs/transports/service-bus-receive.md
@@ -3,7 +3,7 @@ title: Service Bus receive primitives
description: "Use the native Service Bus callback with Relayer's receive pipeline and manual settlement view."
---
-`Relayer.AzureServiceBus` provides `ServiceBusBinding` for `ProcessMessageEventArgs`, `ServiceBusSessionBinding` for `ProcessSessionMessageEventArgs`, and a borrowed `context.ServiceBus()` view. These are low-level building blocks for applications that already own an Azure SDK processor. Most applications can use [named native processors](service-bus.md#register-receiving), which compose failure handling, settlement, telemetry and lifecycle automatically.
+`Relayer.AzureServiceBus` provides `ServiceBusMessageBinding` for `ProcessMessageEventArgs`, `ServiceBusSessionMessageBinding` for `ProcessSessionMessageEventArgs`, and a borrowed `context.ServiceBus()` view. These are low-level building blocks for applications that already own an Azure SDK processor. Most applications can use [named native processors](service-bus.md#register-receiving), which compose failure handling, settlement, telemetry and lifecycle automatically.
Compose a [consume pipeline](consume-pipeline.md) with generated handlers, serialization and an explicit durable failure delegate. Then adapt your existing native processor:
@@ -13,7 +13,7 @@ using Relayer.AzureServiceBus;
using Relayer.Transports;
// consumerPipeline is the composed ConsumePipeline, built once at startup.
-var receive = new ReceivePipeline(
+var receive = new ReceivePipeline(
consumerPipeline, new HeaderNames("cloudEvents:"), contextPoolCapacity: 8);
await using var processor = client.CreateProcessor("orders", new ServiceBusProcessorOptions
@@ -57,6 +57,6 @@ await native.DeferAsync();
`Callback` exposes `ProcessMessageEventArgs` for other native operations, including lock renewal. For session deliveries, `SessionCallback` exposes the unchanged `ProcessSessionMessageEventArgs`, including session state and session lock operations; `Callback` fails explicitly on a session delivery. The common `Message` and settlement helpers work with either callback kind. If you settle directly through a callback, set the corresponding `NativeMessage` or `NativeMessage` disposition to `Disposition.SettledByHandler` after success. The view, callback, message, body and header storage are borrowed for the current processing call; never retain them after it returns.
-`ServiceBusBinding` reads only the requested header. The logical `content-type` header comes from the native `ServiceBusReceivedMessage.ContentType` property, as required by the CloudEvents AMQP binding. When the native property is absent, the binding falls back to an application property named `content-type`; when both exist, the native property wins. Other headers come from AMQP application properties. Text stays text; binary values stay borrowed UTF-8 memory. Missing properties and other native value types return `false`; access numeric and other typed values through `native.Message.ApplicationProperties`. CloudEvents attributes use the `cloudEvents:` prefix; creation context remains in `traceparent` and `tracestate`. No SDK tracing header is substituted for the creation context.
+`ServiceBusMessageBinding` reads only the requested header. The logical `content-type` header comes from the native `ServiceBusReceivedMessage.ContentType` property, as required by the CloudEvents AMQP binding. When the native property is absent, the binding falls back to an application property named `content-type`; when both exist, the native property wins. Other headers come from AMQP application properties. Text stays text; binary values stay borrowed UTF-8 memory. Missing properties and other native value types return `false`; access numeric and other typed values through `native.Message.ApplicationProperties`. CloudEvents attributes use the `cloudEvents:` prefix; creation context remains in `traceparent` and `tracestate`. No SDK tracing header is substituted for the creation context.
For an indexed single AMQP data section, the binding borrows the original body memory and creates no allocation. Other body layouts use the SDK's `Body` conversion, preserving native behavior; that conversion may allocate and join multiple sections. Header reads use the raw AMQP property dictionary to avoid the SDK's per-access read-only dictionary wrapper.
diff --git a/website/docs/transports/service-bus.md b/website/docs/transports/service-bus.md
index 557d8517d..3acdf6611 100644
--- a/website/docs/transports/service-bus.md
+++ b/website/docs/transports/service-bus.md
@@ -274,3 +274,10 @@ Set `consumer.Options.CircuitBreaker` to `ConsumerCircuitOptions` to stop queue
Abandoning a failed delivery and allowing a rejected delivery's lock to expire both consume native delivery attempts. During a prolonged outage, Service Bus can dead-letter messages at `MaxDeliveryCount` even while the circuit is open. Size `BreakDuration` together with the queue or subscription's `MaxDeliveryCount` and expected outage duration; circuit retention does not override broker limits or message expiry.
If a native circuit stop or recovery start fails, consumption stops and the failure is logged and retained for shutdown. With `AddRelayerServiceBusHealthProviders` and `AddRelayerHealthChecks` registered, consumer health reports the failure as unhealthy. Recreate the application host to resume consumption.
+
+## API naming
+
+The transport's client options are `ServiceBusTransportOptions`, matching
+`relayer.ServiceBus(...)` and `ServiceBusConsumerOptions`. The receive binding is
+`ServiceBusMessageBinding` (or `ServiceBusSessionMessageBinding` for sessions). These replace the former `AzureServiceBusTransportOptions`
+`ServiceBusBinding` and `ServiceBusSessionBinding` names; update explicit type references when upgrading.