Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbConnectionEvents.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbConnectionEvents.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Tracing;
namespace redb.Route.Tests.AzureServiceBus;
///
/// Counts, in this process, the peeks of the Service Bus client (its Azure-Messaging-ServiceBus event source)
/// and the AMQP connections opened and closed under it (the Microsoft-Azure-Amqp event source), and keeps each
/// of them with its time on the given clock. The counts start when the listener is made and stop when it is disposed.
///
internal sealed class AsbConnectionEvents : EventListener
{
private readonly Stopwatch? _clock;
private readonly ConcurrentQueue _timeline = new();
private int _peeksStarted;
private int _peeksCompleted;
private int _connectionsOpened;
private int _connectionsClosed;
/// The clock the timeline is kept on.
public AsbConnectionEvents(Stopwatch clock)
{
_clock = clock;
}
/// The peeks the client started.
public int PeeksStarted => Volatile.Read(ref _peeksStarted);
/// The peeks the namespace answered.
public int PeeksCompleted => Volatile.Read(ref _peeksCompleted);
/// The AMQP connections opened.
public int ConnectionsOpened => Volatile.Read(ref _connectionsOpened);
/// The AMQP connections closed.
public int ConnectionsClosed => Volatile.Read(ref _connectionsClosed);
/// The counted events in order, each with its second on the clock.
public string Timeline => string.Join(", ", _timeline);
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name is "Azure-Messaging-ServiceBus" or "Microsoft-Azure-Amqp")
EnableEvents(eventSource, EventLevel.Verbose, EventKeywords.All);
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
switch (eventData.EventName)
{
case "PeekMessageStart":
Interlocked.Increment(ref _peeksStarted);
break;
case "PeekMessageComplete":
Interlocked.Increment(ref _peeksCompleted);
break;
case "AmqpOpenConnection":
Interlocked.Increment(ref _connectionsOpened);
break;
case "AmqpCloseConnection":
Interlocked.Increment(ref _connectionsClosed);
break;
default:
return;
}
// The base constructor enables the sources before this one has run.
if (_clock is not null)
_timeline.Enqueue($"{eventData.EventName} {_clock.Elapsed.TotalSeconds:0.0}");
}
}