Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion benchmarks/Relayer.Benchmarks/KafkaSendBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Diagnostics.Metrics;
using Microsoft.Extensions.Options;
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
Expand Down Expand Up @@ -27,9 +29,31 @@ public class KafkaSendBenchmarks
[Params(false, true)]
public bool Tombstone { get; set; }

private RelayerInstrumentation _instrumentation = null!;
private MessageTracing _tracing = null!;
private MeterListener? _metrics;

[Params(false, true)]
public bool Metrics { get; set; }

[GlobalSetup]
public async Task Setup()
{
_instrumentation = new();
_tracing = new(Options.Create(new TracingOptions()), [], instrumentation: _instrumentation);
if (Metrics)
{
_metrics = new()
{
InstrumentPublished = (instrument, listener) =>
{
if (ReferenceEquals(instrument.Meter.Scope, _instrumentation)) listener.EnableMeasurementEvents(instrument);
},
};
_metrics.SetMeasurementEventCallback<long>(static (_, _, _, _) => { });
_metrics.SetMeasurementEventCallback<double>(static (_, _, _, _) => { });
_metrics.Start();
}
var bootstrap = Environment.GetEnvironmentVariable("RELAYER_KAFKA_BOOTSTRAP_SERVERS")
?? throw new InvalidOperationException("Set RELAYER_KAFKA_BOOTSTRAP_SERVERS to a test Kafka broker.");
_topic = "relayer-benchmark-" + Guid.NewGuid().ToString("N");
Expand All @@ -39,7 +63,7 @@ public async Task Setup()
var producer = await new ProducerBuilder<WireString?, (ReadOnlyMemory<byte> Body, Headers Headers)?>()
.WithBootstrapServers(bootstrap).WithKeySerializer(new KafkaKeySerializer())
.WithValueSerializer(new KafkaValueSerializer()).BuildAsync();
_transport = new("benchmarks", producer, [_topic]);
_transport = new("benchmarks", producer, [_topic], _tracing);
var body = Encoding.UTF8.GetBytes("{\"orderId\":42,\"customer\":\"customer-1\"}");
var key = "customer-1"u8.ToArray();
KeyValuePair<string, WireString>[] headers = [new("ce_type", new("benchmarks.order;v=1")),
Expand Down Expand Up @@ -76,5 +100,8 @@ public async Task Cleanup()
try { if (_topic is not null) await _admin.DeleteTopicsAsync([_topic]); }
finally { await _admin.DisposeAsync(); }
}
_metrics?.Dispose();
_tracing?.Dispose();
_instrumentation?.Dispose();
}
}
30 changes: 29 additions & 1 deletion benchmarks/Relayer.Benchmarks/ServiceBusSendBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Buffers;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.Options;
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Administration;
using BenchmarkDotNet.Attributes;
Expand Down Expand Up @@ -34,9 +36,31 @@ public class ServiceBusSendBenchmarks
private readonly ServiceBusJsonOrder _order = new(42, "customer-1");
private readonly MessageEnvelope _envelope = new(new("benchmarks.servicebus-json", 1), "/", new("cloudEvents:"));

private RelayerInstrumentation _instrumentation = null!;
private MessageTracing _tracing = null!;
private MeterListener? _metrics;

[Params(false, true)]
public bool Metrics { get; set; }

[GlobalSetup]
public async Task Setup()
{
_instrumentation = new();
_tracing = new(Options.Create(new TracingOptions()), [], instrumentation: _instrumentation);
if (Metrics)
{
_metrics = new()
{
InstrumentPublished = (instrument, listener) =>
{
if (ReferenceEquals(instrument.Meter.Scope, _instrumentation)) listener.EnableMeasurementEvents(instrument);
},
};
_metrics.SetMeasurementEventCallback<long>(static (_, _, _, _) => { });
_metrics.SetMeasurementEventCallback<double>(static (_, _, _, _) => { });
_metrics.Start();
}
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;
Expand All @@ -57,14 +81,15 @@ public async Task Setup()
_raw = _client.CreateSender(_queue);
var options = new AzureServiceBusTransportOptions { Client = _client };
options.Queues.Add(new(_queue));
_transport = new("benchmark", _client, false, options, [_queue], TopologyMode.None);
_transport = new("benchmark", _client, false, options, [_queue], TopologyMode.None, tracing: _tracing);
_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();
var services = new ServiceCollection();
services.AddSingleton(_instrumentation);
services.AddRelayer(builder =>
{
builder.AddMessageTypesFromThisAssembly();
Expand Down Expand Up @@ -136,6 +161,9 @@ public async Task Cleanup()
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);
_metrics?.Dispose();
_tracing?.Dispose();
_instrumentation?.Dispose();
}

private sealed class NativeHeaders : IMessageHeaderWriter<ServiceBusMessage>
Expand Down
2 changes: 1 addition & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ Instruments from the semantic conventions, with the conventions' recommended his

| Instrument | Type | Unit | Measures |
|---|---|---|---|
| `messaging.client.operation.duration` | Histogram | `s` | Each send, create and settle operation. Equals the span's duration. |
| `messaging.client.operation.duration` | Histogram | `s` | Each native send, create and settle operation, through native completion. A logical batch span can cover several native sends. |
| `messaging.process.duration` | Histogram | `s` | Each process operation, including settlement. |
| `messaging.client.sent.messages` | Counter | `{message}` | Messages that Relayer attempted to send to the broker. An outbox enqueue is not counted; its dispatch is. |
| `messaging.client.consumed.messages` | Counter | `{message}` | Messages delivered to the pipeline, counted once per delivery. |
Expand Down
20 changes: 17 additions & 3 deletions src/Relayer.AzureServiceBus/ServiceBusSendTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ internal ServiceBusSendTransport(string name, ServiceBusClient client, bool owns
// Receive features and namespace-dependent transaction/size limits are deliberately unresolved.
});
if (tracing is not null)
endpoint.Tracing = new(tracing, new() { System = "servicebus", Destination = destination },
endpoint.Tracing = new(tracing, new() { System = "servicebus", Destination = destination, ServerAddress = client.FullyQualifiedNamespace },
SendCoreAsync, SendBatchCoreAsync, logging?.CreateLogger<ServiceBusSendTransport>(), new("cloudEvents:"));
endpoints.Add(destination, endpoint);
}
Expand Down Expand Up @@ -95,7 +95,14 @@ private async ValueTask SendCoreAsync(OutgoingMessage outgoing, CancellationToke
try
{
state.Prepare(outgoing);
await endpoint.Sender.SendMessageAsync(state.Message, cancellationToken).ConfigureAwait(false);
var duration = endpoint.Tracing?.StartNativeSend() ?? default;
var failed = true;
try
{
await endpoint.Sender.SendMessageAsync(state.Message, cancellationToken).ConfigureAwait(false);
failed = false;
}
finally { duration.Complete(failed); }
}
finally { endpoint.Return(state); }
}
Expand Down Expand Up @@ -170,7 +177,14 @@ private async ValueTask SendBatchCoreAsync(ReadOnlyMemory<OutgoingMessage> messa
pending = null;
index++;
}
await endpoint.Sender.SendMessagesAsync(batch, cancellationToken).ConfigureAwait(false);
var duration = endpoint.Tracing?.StartNativeSend() ?? default;
var failed = true;
try
{
await endpoint.Sender.SendMessagesAsync(batch, cancellationToken).ConfigureAwait(false);
failed = false;
}
finally { duration.Complete(failed); }
}
finally
{
Expand Down
48 changes: 40 additions & 8 deletions src/Relayer.Kafka/KafkaProducerTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,17 @@ private async ValueTask SendCoreAsync(OutgoingMessage message, CancellationToken
{
operation.States[0].Prepare(message);
var state = operation.States[0];
if (state.Tombstone)
await _topics[message.Destination].ProduceAsync(state.Key, null, state.Headers, cancellationToken).ConfigureAwait(false);
else
await _producer.ProduceAsync(message.Destination, state.Key, (message.Body, state.Headers), cancellationToken).ConfigureAwait(false);
var duration = Endpoint(message.Destination)?.StartNativeSend() ?? default;
var failed = true;
try
{
if (state.Tombstone)
await _topics[message.Destination].ProduceAsync(state.Key, null, state.Headers, cancellationToken).ConfigureAwait(false);
else
await _producer.ProduceAsync(message.Destination, state.Key, (message.Body, state.Headers), cancellationToken).ConfigureAwait(false);
failed = false;
}
finally { duration.Complete(failed); }
}
finally { _operations.Return(operation); }
}
Expand Down Expand Up @@ -107,7 +114,16 @@ private async ValueTask SendBatchCoreAsync(ReadOnlyMemory<OutgoingMessage> messa
if (hasTombstone)
await SendNullBatchAsync(messages, operation, cancellationToken).ConfigureAwait(false);
else
await _producer.ProduceAllAsync(messages.Span[0].Destination, operation.Messages, cancellationToken).ConfigureAwait(false);
{
var duration = Endpoint(messages.Span[0].Destination)?.StartNativeSend() ?? default;
var failed = true;
try
{
await _producer.ProduceAllAsync(messages.Span[0].Destination, operation.Messages, cancellationToken).ConfigureAwait(false);
failed = false;
}
finally { duration.Complete(failed); }
}
}
finally { _operations.Return(operation); }
}
Expand All @@ -124,9 +140,7 @@ private async ValueTask SendNullBatchAsync(ReadOnlyMemory<OutgoingMessage> messa
{
var message = messages.Span[count];
var state = operation.States[count];
operation.Pending[count] = state.Tombstone
? _topics[message.Destination].ProduceAsync(state.Key, null, state.Headers, token)
: _producer.ProduceAsync(message.Destination, state.Key, (message.Body, state.Headers), token);
operation.Pending[count] = ProduceAsync(message, state, token);
}
}
catch (Exception error) { failure = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(error); }
Expand All @@ -138,6 +152,24 @@ private async ValueTask SendNullBatchAsync(ReadOnlyMemory<OutgoingMessage> messa
failure?.Throw();
}

private ValueTask<RecordMetadata> ProduceAsync(OutgoingMessage message, KafkaSendState state, CancellationToken token)
{
var duration = Endpoint(message.Destination)?.StartNativeSend() ?? default;
try
{
// Preserve synchronous admission failures: stop admitting and drain earlier calls.
var pending = state.Tombstone
? _topics[message.Destination].ProduceAsync(state.Key, null, state.Headers, token)
: _producer.ProduceAsync(message.Destination, state.Key, (message.Body, state.Headers), token);
return duration.IsEnabled ? state.TrackSend(pending, duration) : pending;
}
catch
{
duration.Complete(failed: true);
throw;
}
}

[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
private async ValueTask SendMixedBatchAsync(ReadOnlyMemory<OutgoingMessage> messages, CancellationToken cancellationToken)
{
Expand Down
54 changes: 54 additions & 0 deletions src/Relayer.Kafka/KafkaSendCompletion.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System.Runtime.CompilerServices;
using System.Threading.Tasks.Sources;
using Dekaf.Producer;

namespace Relayer.Kafka;

// Retained by a send state: pooled async builders can overflow their retention cap when
// an entire tombstone batch completes concurrently, allocating again on every batch.
internal sealed class KafkaSendCompletion : IValueTaskSource<RecordMetadata>
{
private ManualResetValueTaskSourceCore<RecordMetadata> _source;
private ConfiguredValueTaskAwaitable<RecordMetadata>.ConfiguredValueTaskAwaiter _pending;
private SendTracing.NativeSendOperation _duration;
private readonly Action _complete;

internal KafkaSendCompletion() => _complete = Complete;

internal ValueTask<RecordMetadata> Track(ValueTask<RecordMetadata> pending, SendTracing.NativeSendOperation duration)
{
_pending = pending.ConfigureAwait(false).GetAwaiter();
_duration = duration;
var version = _source.Version;
if (_pending.IsCompleted) Complete();
else _pending.UnsafeOnCompleted(_complete);
return new(this, version);
}

private void Complete()
{
RecordMetadata result = default;
Exception? failure = null;
try { result = _pending.GetResult(); }
catch (Exception error) { failure = error; }
// Release the native source before publishing completion: the awaiting batch
// can immediately return this state to its pool from an inline continuation.
_pending = default;
var duration = _duration;
_duration = default;
try { duration.Complete(failure is not null); }
catch (Exception error) { failure = error; }
if (failure is null) _source.SetResult(result);
else _source.SetException(failure);
}

RecordMetadata IValueTaskSource<RecordMetadata>.GetResult(short token)
{
try { return _source.GetResult(token); }
finally { _source.Reset(); }
}

ValueTaskSourceStatus IValueTaskSource<RecordMetadata>.GetStatus(short token) => _source.GetStatus(token);
void IValueTaskSource<RecordMetadata>.OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) =>
_source.OnCompleted(continuation, state, token, flags);
}
5 changes: 5 additions & 0 deletions src/Relayer.Kafka/KafkaSendState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ internal sealed class KafkaSendState
internal const string TombstoneHeader = "relayer.internal.kafka.tombstone";
private readonly Headers _headers = new(16);
private byte[] _utf8 = [];
private KafkaSendCompletion? _completion;

internal ValueTask<Dekaf.Producer.RecordMetadata> TrackSend(ValueTask<Dekaf.Producer.RecordMetadata> pending, SendTracing.NativeSendOperation duration) =>
(_completion ??= new()).Track(pending, duration);

internal WireString? Key { get; private set; }
internal bool Tombstone { get; set; }
internal Headers Headers => _headers;
Expand Down
26 changes: 26 additions & 0 deletions src/Relayer/Telemetry/SendTracing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,32 @@ public SendTracing(MessageTracing tracing, MessagingEndpoint endpoint,
_states.Items[0] = new();
}

/// <summary>Starts timing an actual native send call, independently of tracing and logical batch composition.</summary>
/// <remarks>Complete once after native acknowledgement or failure. Do not time outbox enqueue or message preparation.</remarks>
public NativeSendOperation StartNativeSend() => new(_telemetry);

/// <summary>An allocation-free timer for one native send, including asynchronous completion.</summary>
public readonly struct NativeSendOperation
{
private readonly EndpointTelemetry? _telemetry;
private readonly long _started;

internal NativeSendOperation(EndpointTelemetry? telemetry)
{
_telemetry = telemetry;
_started = telemetry is { DurationEnabled: true } ? Stopwatch.GetTimestamp() : 0;
}

/// <summary>Whether the duration instrument had a listener when this operation started.</summary>
public bool IsEnabled => _started != 0;

/// <summary>Records one duration, with bounded error.type on failure. A default timer records nothing.</summary>
public void Complete(bool failed = false)
{
if (_started != 0) _telemetry!.RecordDuration(Stopwatch.GetElapsedTime(_started), failed);
}
}

internal Activity? Start(ActivityContext creationContext, bool deferred) =>
(deferred ? _create : _send).Start(new() { CreationContext = creationContext });

Expand Down
Loading
Loading