Repository navigation
Implement Service Bus native sending, ownership and topology #147
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5d7d8b9
feat(servicebus): implement native sending and topology (#129)
thomhurst 2bd5df7
fix(servicebus): trace mixed-destination batches (#129)
thomhurst c4b5ba2
fix(servicebus): map serializer content type to AMQP property (#129)
thomhurst 0e9023b
test(servicebus): expose envelope allocation budget (#129)
thomhurst File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
79 changes: 79 additions & 0 deletions
79
benchmarks/Relayer.Benchmarks/ServiceBusHeaderBenchmarks.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| using System.Text; | ||
| using Azure.Messaging.ServiceBus; | ||
| using BenchmarkDotNet.Attributes; | ||
| using Relayer.AzureServiceBus; | ||
|
|
||
| namespace Relayer.Benchmarks; | ||
|
|
||
| /// <summary>Isolates UTF-8 envelope conversion from SDK/network allocations. IDs and times change every invocation.</summary> | ||
| [MemoryDiagnoser] | ||
| public class ServiceBusHeaderBenchmarks | ||
| { | ||
| private readonly ServiceBusSendState _relayer = new(); | ||
| private readonly ServiceBusMessage _raw = new(); | ||
| private readonly HeaderBuffer _headers = new(); | ||
| private readonly MessageEnvelope _first = new(new("benchmark.order", 1), "/orders", new("cloudEvents:")); | ||
| private readonly MessageEnvelope _second = new(new("benchmark.other", 1), "/other", new("cloudEvents:")); | ||
| private readonly DateTimeOffset _time = DateTimeOffset.UtcNow; | ||
| private long _sequence; | ||
|
|
||
| [Params(false, true)] | ||
| public bool AlternatingRoutes { get; set; } | ||
|
|
||
| [GlobalSetup] | ||
| public void Setup() | ||
| { | ||
| _relayer.Prepare(Next()); | ||
| _relayer.Clear(); | ||
| RawHeaders(); | ||
| } | ||
|
|
||
| [Benchmark(Baseline = true)] | ||
| public int RawHeaders() | ||
| { | ||
| var outgoing = Next(); | ||
| foreach (var header in outgoing.Headers.Span) | ||
| _raw.ApplicationProperties[header.Key] = header.Value.ToString(); | ||
| var count = _raw.ApplicationProperties.Count; | ||
| _raw.ApplicationProperties.Clear(); | ||
| return count; | ||
| } | ||
|
|
||
| [Benchmark] | ||
| public int RelayerHeaders() | ||
| { | ||
| _relayer.Prepare(Next()); | ||
| var count = _relayer.Message.ApplicationProperties.Count; | ||
| _relayer.Clear(); | ||
| return count; | ||
| } | ||
|
|
||
| private OutgoingMessage Next() | ||
| { | ||
| var sequence = ++_sequence; | ||
| var envelope = AlternatingRoutes && (sequence & 1) == 0 ? _second : _first; | ||
| envelope.Write<HeaderBuffer, HeaderBuffer>(_headers, | ||
| new(Guid.CreateVersion7(), _time.AddTicks(sequence), default)); | ||
| return new("orders", default, _headers.Entries); | ||
| } | ||
|
|
||
| private sealed class HeaderBuffer : IMessageHeaderWriter<HeaderBuffer> | ||
| { | ||
| internal readonly KeyValuePair<string, WireString>[] Entries = new KeyValuePair<string, WireString>[5]; | ||
| private readonly byte[][] _values = [new byte[128], new byte[128], new byte[128], new byte[128], new byte[128]]; | ||
|
|
||
| public static void SetHeader(HeaderBuffer message, string name, ReadOnlySpan<char> value) | ||
| { | ||
| for (var i = 0; i < message.Entries.Length; i++) | ||
| { | ||
| if (message.Entries[i].Key is not null && message.Entries[i].Key != name) continue; | ||
| var length = Encoding.UTF8.GetBytes(value, message._values[i]); | ||
| message.Entries[i] = new(name, new WireString(message._values[i].AsMemory(0, length))); | ||
| return; | ||
| } | ||
| throw new InvalidOperationException("Unexpected envelope header."); | ||
| } | ||
|
|
||
| public static void RemoveHeader(HeaderBuffer message, string name) { } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| using Azure.Messaging.ServiceBus; | ||
| using Azure.Messaging.ServiceBus.Administration; | ||
| using BenchmarkDotNet.Attributes; | ||
| using BenchmarkDotNet.Configs; | ||
| using Relayer.AzureServiceBus; | ||
|
|
||
| namespace Relayer.Benchmarks; | ||
|
|
||
| /// <summary>Acknowledged SDK sends to a fresh queue per case. Both paths include native message/header preparation.</summary> | ||
| [MemoryDiagnoser] | ||
| [CategoriesColumn] | ||
| [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] | ||
| public class ServiceBusSendBenchmarks | ||
| { | ||
| private ServiceBusClient _client = null!; | ||
| private ServiceBusSender _raw = null!; | ||
| private ServiceBusSendTransport _transport = null!; | ||
| private ServiceBusAdministrationClient _admin = null!; | ||
| private string _queue = null!; | ||
| private byte[] _body = null!; | ||
| private KeyValuePair<string, WireString>[] _headers = null!; | ||
| private OutgoingMessage _message; | ||
| private OutgoingMessage[] _batch = null!; | ||
|
|
||
| [GlobalSetup] | ||
| public async Task Setup() | ||
| { | ||
| var connection = Environment.GetEnvironmentVariable("RELAYER_SERVICEBUS_CONNECTION_STRING") | ||
| ?? throw new InvalidOperationException("Set RELAYER_SERVICEBUS_CONNECTION_STRING to a test Service Bus namespace."); | ||
| var administration = Environment.GetEnvironmentVariable("RELAYER_SERVICEBUS_ADMIN_CONNECTION_STRING") ?? connection; | ||
| _admin = new(administration); | ||
| _queue = "relayer-benchmark-" + Guid.NewGuid().ToString("N"); | ||
| await _admin.CreateQueueAsync(new CreateQueueOptions(_queue)); | ||
| _client = new(connection); | ||
| _raw = _client.CreateSender(_queue); | ||
| var options = new AzureServiceBusTransportOptions { Client = _client }; | ||
| options.Queues.Add(new(_queue)); | ||
| _transport = new("benchmark", _client, false, options, [_queue], TopologyMode.None); | ||
| _body = "{\"orderId\":42,\"customer\":\"customer-1\"}"u8.ToArray(); | ||
| _headers = [new("cloudEvents:type", new("benchmarks.order;v=1")), new("cloudEvents:source", new("/benchmarks")), | ||
| new("cloudEvents:specversion", new("1.0")), new("cloudEvents:id", new("019a3c1b-97c0-7000-8000-000000000001"u8.ToArray())), | ||
| new("traceparent", new("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"u8.ToArray()))]; | ||
| _message = new(_queue, _body, _headers); | ||
| _batch = Enumerable.Repeat(_message, 32).ToArray(); | ||
| await _raw.SendMessageAsync(NativeMessage()); | ||
| await _transport.SendAsync(_message, default); | ||
| } | ||
|
|
||
| private ServiceBusMessage NativeMessage() | ||
| { | ||
| var message = new ServiceBusMessage(_body); | ||
| foreach (var header in _headers) message.ApplicationProperties[header.Key] = header.Value.ToString(); | ||
| return message; | ||
| } | ||
|
|
||
| [Benchmark(Baseline = true), BenchmarkCategory("Single")] | ||
| public Task RawSingle() => _raw.SendMessageAsync(NativeMessage()); | ||
|
|
||
| [Benchmark, BenchmarkCategory("Single")] | ||
| public ValueTask RelayerSingle() => _transport.SendAsync(_message, default); | ||
|
|
||
| [Benchmark(Baseline = true, OperationsPerInvoke = 32), BenchmarkCategory("Batch")] | ||
| public async Task RawBatch() | ||
| { | ||
| using var batch = await _raw.CreateMessageBatchAsync(); | ||
| for (var i = 0; i < 32; i++) | ||
| if (!batch.TryAddMessage(NativeMessage())) throw new InvalidOperationException("The benchmark batch exceeds the native byte limit."); | ||
| await _raw.SendMessagesAsync(batch); | ||
| } | ||
|
|
||
| [Benchmark(OperationsPerInvoke = 32), BenchmarkCategory("Batch")] | ||
| public ValueTask RelayerBatch() => _transport.SendBatchAsync(_batch, default); | ||
|
|
||
| [GlobalCleanup] | ||
| public async Task Cleanup() | ||
| { | ||
| if (_transport is not null) await _transport.DisposeAsync(); | ||
| if (_raw is not null) await _raw.DisposeAsync(); | ||
| if (_client is not null) await _client.DisposeAsync(); | ||
| if (_admin is not null && _queue is not null) await _admin.DeleteQueueAsync(_queue); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
src/Relayer.AzureServiceBus/AzureServiceBusTransportOptions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,29 @@ | ||
| using Azure.Messaging.ServiceBus; | ||
| using Azure.Messaging.ServiceBus.Administration; | ||
|
|
||
| namespace Relayer.AzureServiceBus; | ||
|
|
||
| /// <summary>Options for the AzureServiceBus transport. Native client configuration is passed through unchanged (docs/decisions.md D1).</summary> | ||
| public sealed class AzureServiceBusTransportOptions | ||
| { | ||
| /// <summary>Connection string for a client owned and disposed by Relayer. Do not also set Client.</summary> | ||
| public string? ConnectionString { get; set; } | ||
|
|
||
| /// <summary>A caller-owned client, including clients constructed with TokenCredential. Relayer never disposes it.</summary> | ||
| public ServiceBusClient? Client { get; set; } | ||
|
|
||
| /// <summary>Native client options, passed straight to <see cref="ServiceBusClient"/>.</summary> | ||
| public ServiceBusClientOptions ClientOptions { get; set; } = new(); | ||
|
|
||
| /// <summary>Caller-owned administration client, used only in Provision mode. Required for caller-owned messaging clients.</summary> | ||
| public ServiceBusAdministrationClient? AdministrationClient { get; set; } | ||
|
|
||
| /// <summary>Native queue declarations. Names must match send destinations.</summary> | ||
| public IList<CreateQueueOptions> Queues { get; } = []; | ||
|
|
||
| /// <summary>Native topic declarations. Names must match send destinations.</summary> | ||
| public IList<CreateTopicOptions> Topics { get; } = []; | ||
|
|
||
| /// <summary>Native subscriptions to provision independently of receive composition.</summary> | ||
| public IList<CreateSubscriptionOptions> Subscriptions { get; } = []; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
src/Relayer.AzureServiceBus/ServiceBusBuilderExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| using Azure.Messaging.ServiceBus; | ||
| using Azure.Messaging.ServiceBus.Administration; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Hosting; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.Logging.Abstractions; | ||
| using Microsoft.Extensions.Options; | ||
| using Relayer.Transports; | ||
|
|
||
| namespace Relayer.AzureServiceBus; | ||
|
|
||
| /// <summary>Registers named Service Bus send transports with native topology declarations.</summary> | ||
| public static class ServiceBusBuilderExtensions | ||
| { | ||
| /// <summary>Declares native queue/topic sending. Complete receive composition is not implemented yet.</summary> | ||
| public static IRelayerBuilder ServiceBus(this IRelayerBuilder builder, string name, | ||
| Action<TransportBuilder<AzureServiceBusTransportOptions, ServiceBusRouteOptions, ServiceBusConsumerOptions>> configure) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(builder); | ||
| ArgumentNullException.ThrowIfNull(configure); | ||
| builder.AddTransport<AzureServiceBusTransportOptions, ServiceBusRouteOptions, ServiceBusConsumerOptions>(name, transport => | ||
| { | ||
| transport.SendDefaults = new() { HeaderNames = new("cloudEvents:") }; | ||
| configure(transport); | ||
| }); | ||
| builder.Services.AddSingleton<ITransport>(provider => | ||
| { | ||
| var configuration = provider.GetRequiredService<RelayerConfiguration>(); | ||
| var definition = configuration.Transports.Single(item => item.Name == name); | ||
| if (definition.Consumers.Count != 0) | ||
| throw new NotSupportedException($"Service Bus transport '{name}': consumer execution is not implemented yet. Use the native receive primitives or wait for complete receiver composition."); | ||
| var options = provider.GetRequiredService<IOptionsMonitor<AzureServiceBusTransportOptions>>().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); | ||
| ServiceBusSendTransport.ValidateDeclarations(name, options, definition.Routes.Select(route => route.Destination)); | ||
| var mode = definition.TopologyMode ?? configuration.TopologyMode; | ||
| var admin = options.AdministrationClient; | ||
| if (mode == TopologyMode.Provision && admin is null) | ||
| admin = options.ConnectionString is { } connection ? new ServiceBusAdministrationClient(connection) | ||
| : throw new InvalidOperationException($"Service Bus transport '{name}': Provision requires AdministrationClient when using a caller-owned Client."); | ||
| // Validate never constructs or calls an administration client. | ||
| var client = options.Client ?? new ServiceBusClient(options.ConnectionString!, options.ClientOptions); | ||
| var logging = provider.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance; | ||
| return new ServiceBusSendTransport(name, client, options.Client is null, options, | ||
| definition.Routes.Select(route => route.Destination), mode, admin, | ||
| provider.GetRequiredService<MessageTracing>(), logging); | ||
| }); | ||
| builder.Services.AddSingleton<IHostedService>(provider => new ServiceBusSendHostedService(provider, name)); | ||
| return builder; | ||
| } | ||
|
|
||
| /// <summary>Customises the native outgoing Service Bus message immediately before sending.</summary> | ||
| public static SendOptions ServiceBus(this SendOptions options, Action<ServiceBusMessage> configure) => | ||
| options.ConfigureNative(configure); | ||
| } | ||
|
|
||
| /// <summary>Service Bus send route options. Declare native entities on the named transport options.</summary> | ||
| public sealed class ServiceBusRouteOptions; | ||
|
|
||
| /// <summary>Reserved for complete native receiver composition.</summary> | ||
| public sealed class ServiceBusConsumerOptions; | ||
|
|
||
| internal sealed class ServiceBusSendHostedService(IServiceProvider provider, string name) : IHostedService | ||
| { | ||
| private ITransport Transport => provider.GetServices<ITransport>().Single(transport => transport.Name == name); | ||
| public Task StartAsync(CancellationToken cancellationToken) => Transport.StartAsync(cancellationToken); | ||
| public Task StopAsync(CancellationToken cancellationToken) => Transport.StopAsync(cancellationToken); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| using Azure.Core.Amqp; | ||
| using Azure.Messaging.ServiceBus; | ||
|
|
||
| namespace Relayer.AzureServiceBus; | ||
|
|
||
| // Retain native message containers at the concurrency high-water mark, without a lock or per-send wrapper. | ||
| internal sealed class ServiceBusPool<T>(Func<T> create) where T : class | ||
| { | ||
| private readonly Page _first = new(); | ||
|
|
||
| internal T Rent() | ||
| { | ||
| for (Page? page = _first; page is not null; page = Volatile.Read(ref page.Next)) | ||
| for (var i = 0; i < page.Slots.Length; i++) | ||
| if (Interlocked.Exchange(ref page.Slots[i], null) is { } state) return state; | ||
| return create(); | ||
| } | ||
|
|
||
| internal void Return(T state) | ||
| { | ||
| var page = _first; | ||
| while (true) | ||
| { | ||
| for (var i = 0; i < page.Slots.Length; i++) | ||
| if (Interlocked.CompareExchange(ref page.Slots[i], state, null) is null) return; | ||
| var next = Volatile.Read(ref page.Next); | ||
| if (next is null) | ||
| next = Interlocked.CompareExchange(ref page.Next, new Page(), null) ?? page.Next!; | ||
| page = next; | ||
| } | ||
| } | ||
|
|
||
| private sealed class Page | ||
| { | ||
| internal readonly T?[] Slots = new T?[64]; | ||
| internal Page? Next; | ||
| } | ||
| } | ||
|
|
||
| internal sealed class ServiceBusSendState | ||
| { | ||
| private readonly ReadOnlyMemory<byte>[] _data = new ReadOnlyMemory<byte>[1]; | ||
| private readonly AmqpMessageBody _body; | ||
| internal ServiceBusMessage Message { get; } | ||
|
|
||
| internal ServiceBusSendState() | ||
| { | ||
| _body = AmqpMessageBody.FromData(_data); | ||
| Message = new(new AmqpAnnotatedMessage(_body)); | ||
| } | ||
|
|
||
| internal void Prepare(OutgoingMessage outgoing) | ||
| { | ||
| _data[0] = outgoing.Body; | ||
| if (outgoing.OrderingKey is { } key) Message.SessionId = key.ToString(); | ||
| if (outgoing.DeliverAt is { } scheduled) Message.ScheduledEnqueueTime = scheduled; | ||
| outgoing.ApplyNative(Message); | ||
| // The original envelope and creation context take precedence over a native callback. | ||
| foreach (var header in outgoing.Headers.Span) | ||
| { | ||
| if (header.Key == "content-type") Message.ContentType = header.Value.ToString(); | ||
| else Message.ApplicationProperties[header.Key] = header.Value.ToString(); | ||
| } | ||
| } | ||
|
|
||
| internal void Clear() | ||
| { | ||
| var raw = Message.GetRawAmqpMessage(); | ||
| _data[0] = default; | ||
| raw.Body = _body; | ||
| raw.ApplicationProperties.Clear(); | ||
| raw.MessageAnnotations.Clear(); | ||
| raw.DeliveryAnnotations.Clear(); | ||
| raw.Footer.Clear(); | ||
| var header = raw.Header; | ||
| header.DeliveryCount = null; | ||
| header.Durable = null; | ||
| header.FirstAcquirer = null; | ||
| header.Priority = null; | ||
| header.TimeToLive = null; | ||
| var properties = raw.Properties; | ||
| properties.AbsoluteExpiryTime = null; | ||
| properties.ContentEncoding = null; | ||
| properties.ContentType = null; | ||
| properties.CorrelationId = null; | ||
| properties.CreationTime = null; | ||
| properties.GroupId = null; | ||
| properties.GroupSequence = null; | ||
| properties.MessageId = null; | ||
| properties.ReplyTo = null; | ||
| properties.ReplyToGroupId = null; | ||
| properties.Subject = null; | ||
| properties.To = null; | ||
| properties.UserId = null; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
On the normal CloudEvents serialization path,
MessageEnvelope.Writewrites all five envelope attributes throughSendHeaders.SetHeader, which stores UTF-8-backed values. CallingWireString.ToString()here therefore allocates five new strings per message, including for the route-constant type, source and specversion; tracing adds further conversions. These allocations occur in Relayer before the SDK call and persist after the message pool is warmed up, violating the repository's steady-state allocation contract and adding avoidable GC pressure to both single and batch sends. Preserve or cache the constant text representations rather than decoding them on every send, and address the remaining allocation budget or obtain explicit maintainer approval for the exception.AGENTS.md reference: AGENTS.md:L23-L23
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Blocking finding verified. 0e9023b adds a changing-ID/timestamp allocation probe and corrects the documentation; it does not claim to fix the allocations. Stable-head Dry and Short runs measure 312 B per message for the five UTF-8 envelope values. A bounded cache was implemented and tested locally, then rejected because it still allocated and its alternating-route result did not establish throughput neutrality (1.14 timing ratio, with noise). Runtime code is restored. The AMQP CloudEvents string ID must reach this SDK as an immutable string, so constant caching alone cannot satisfy strict zero allocation. AGENTS.md requires explicit maintainer approval for a budget exception or performance trade. The decision and alternatives are recorded at #147 (comment); #147 and #129 carry needs-human. This thread stays open while that decision is pending. No approval or exception is inferred.