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
108 changes: 108 additions & 0 deletions benchmarks/Relayer.Benchmarks/SendTracingConcurrencyBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System.Diagnostics;
using System.Threading.Tasks.Sources;
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.Options;

namespace Relayer.Benchmarks;

/// <summary>
/// Measures complete warmed bursts with deterministic overlapping native sends. Totals are per burst and include
/// Activity and framework async-builder costs; SendTracingPoolTests separately isolate preparation storage.
/// </summary>
[MemoryDiagnoser]
public class SendTracingConcurrencyBenchmarks
{
private MessageTracing _tracing = null!;
private SendTracing _send = null!;
private ActivityListener _listener = null!;
private Activity _ambient = null!;
private PendingSend[] _native = null!;
private ValueTask[] _pending = null!;
private int _next;
private readonly OutgoingMessage[] _messages = [new("orders", new byte[] { 1 }), new("orders", new byte[] { 2 })];

[Params(1, 64, 128)]
public int Concurrency { get; set; }

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

[Params("Drop", "Record")]
public string Mode { get; set; } = "Drop";

[GlobalSetup]
public void Setup()
{
_tracing = new(Options.Create(new TracingOptions()), []);
_listener = new()
{
ShouldListenTo = source => ReferenceEquals(source, _tracing.Source),
Sample = (ref ActivityCreationOptions<ActivityContext> _) =>
Mode == "Drop" ? ActivitySamplingResult.None : ActivitySamplingResult.AllDataAndRecorded,
};
ActivitySource.AddActivityListener(_listener);
_ambient = new Activity("request").Start();
_native = new PendingSend[Concurrency];
_pending = new ValueTask[Concurrency];
for (var i = 0; i < _native.Length; i++) _native[i] = new();
_send = new(_tracing, new() { System = "test.native", Destination = "orders" }, SendNative, SendBatchNative);
for (var i = 0; i < 4; i++) TracedBurst();
}

[Benchmark(Baseline = true)]
public void NativeBurst()
{
Reset();
for (var i = 0; i < _pending.Length; i++)
_pending[i] = Batch ? SendBatchNative(_messages, default) : SendNative(_messages[0], default);
Complete();
}

[Benchmark]
public void TracedBurst()
{
Reset();
for (var i = 0; i < _pending.Length; i++)
_pending[i] = Batch ? _send.SendBatchAsync(_messages) : _send.SendAsync(_messages[0]);
Complete();
}

private void Reset()
{
_next = 0;
foreach (var send in _native) send.Reset();
}

private ValueTask SendNative(OutgoingMessage message, CancellationToken cancellationToken) => _native[_next++].Wait();
private ValueTask SendBatchNative(ReadOnlyMemory<OutgoingMessage> messages, CancellationToken cancellationToken) => _native[_next++].Wait();

private void Complete()
{
// Inline native completion makes each ValueTask terminal before consumption; GetResult never blocks.
for (var i = 0; i < _pending.Length; i++)
{
_native[i].Complete();
_pending[i].GetAwaiter().GetResult();
}
}

[GlobalCleanup]
public void Cleanup()
{
_ambient.Dispose();
_listener.Dispose();
_tracing.Dispose();
}

private sealed class PendingSend : IValueTaskSource
{
private ManualResetValueTaskSourceCore<bool> _completion;
internal void Reset() => _completion.Reset();
internal ValueTask Wait() => new(this, _completion.Version);
internal void Complete() => _completion.SetResult(true);
public void GetResult(short token) => _completion.GetResult(token);
public ValueTaskSourceStatus GetStatus(short token) => _completion.GetStatus(token);
public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) =>
_completion.OnCompleted(continuation, state, token, flags);
}
}
48 changes: 37 additions & 11 deletions src/Relayer/Telemetry/SendTracing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public sealed class SendTracing
private readonly Func<ReadOnlyMemory<OutgoingMessage>, CancellationToken, ValueTask> _sendBatchNative;
private readonly ILogger _logger;
private readonly HeaderNames _names;
private readonly State?[] _states = new State?[64];
private readonly PoolSegment _states = new();

/// <summary>Precomputes endpoint names and attributes supplied by the native adapter.</summary>
public SendTracing(MessageTracing tracing, MessagingEndpoint endpoint,
Expand All @@ -41,7 +41,7 @@ public SendTracing(MessageTracing tracing, MessagingEndpoint endpoint,
_sendBatchNative = sendBatch;
_logger = logger ?? NullLogger.Instance;
_names = headerNames ?? new();
_states[0] = new();
_states.Items[0] = new();
}

internal Activity? Start(ActivityContext creationContext, bool deferred) =>
Expand Down Expand Up @@ -172,23 +172,49 @@ private OutgoingMessage Prepare(State state, int index, OutgoingMessage message,

private State Rent(int count)
{
State? state = null;
for (var i = 0; i < _states.Length; i++)
if ((state = Interlocked.Exchange(ref _states[i], null)) is not null) break;
state ??= new();
state.Ensure(count);
return state;
var segment = _states;
while (true)
{
for (var i = 0; i < segment.Items.Length; i++)
{
var state = Volatile.Read(ref segment.Items[i]);
if (state is null)
{
var added = new State();
state = Interlocked.CompareExchange(ref segment.Items[i], added, null) ?? added;
}
if (Volatile.Read(ref state.InUse) != 0) continue;
if (Interlocked.CompareExchange(ref state.InUse, 1, 0) != 0) continue;
state.Ensure(count);
return state;
}
// Retain the observed concurrency high-water mark instead of dropping overflow states each burst.
var next = Volatile.Read(ref segment.Next);
if (next is null)
{
var added = new PoolSegment();
next = Interlocked.CompareExchange(ref segment.Next, added, null) ?? added;
}
segment = next;
}
}

private void Return(State state)
private static void Return(State state)
{
state.Clear();
for (var i = 0; i < _states.Length; i++)
if (Interlocked.CompareExchange(ref _states[i], state, null) is null) return;
// States stay in their slots. Publish availability only after all borrowed storage is cleared.
Volatile.Write(ref state.InUse, 0);
}

private sealed class PoolSegment
{
internal readonly State?[] Items = new State?[64];
internal PoolSegment? Next;
}

private sealed class State
{
internal int InUse;
internal OutgoingMessage[] Messages = [];
internal ActivityContext[] Contexts = [];
internal ActivityLink[] Links = [];
Expand Down
Loading
Loading