Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusConnectionWatch.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/redb.Route.AzureServiceBus/AzureServiceBusConnectionWatch.cs ---- using System.Net.Sockets; using Azure.Messaging.ServiceBus; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace redb.Route.AzureServiceBus; /// /// The connection of one Service Bus consumer as its endpoint's health sees it. The client reconnects by itself and /// reports each failed receive, but it has no "connection back" event. So an error of the connection goes to a /// (health shows the loss; it is not counted as a failed message), and the recovery /// comes from the next successful receive or from a read-only probe on the supervisor's schedule, whichever is first. The /// probe peeks the entity's dead-letter queue through the consumer's own client: it needs only the Listen right the /// consumer has, locks nothing, and works on a session entity too (its dead-letter queue has no sessions). It runs only /// while the connection is lost. While connected, any other error (an entity that does not exist, a refused claim) is /// recorded on the endpoint as before: it is not a connection being retried. While lost, every error of a receive is the /// loss's and shows as its reason. /// internal sealed class AzureServiceBusConnectionWatch { /// How long one probe waits for the namespace's answer. internal static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(10); private readonly AzureServiceBusEndpoint _endpoint; private readonly ILogger? _logger; private readonly ConnectionSupervisor _supervisor; private readonly Func? _probe; private readonly string? _subscription; private readonly CancellationTokenSource _stop = new(); private int _probing; /// The endpoint whose health shows the connection. /// The consumer's client: the probe peeks through it. /// The subscription a topic consumer reads; null for a queue. /// The consumer's logger. /// /// Whether to probe while lost. A consumer that receives in its own loop (the batch receiver) learns of the /// recovery from that loop and needs none. /// public AzureServiceBusConnectionWatch(AzureServiceBusEndpoint endpoint, ServiceBusClient client, string? subscription, ILogger? logger, bool probe) { _endpoint = endpoint; _logger = logger; _subscription = subscription; _supervisor = endpoint.Supervise($"asb:{endpoint.EntityName} consumer", logger); if (probe) _probe = ct => PeekDeadLetterAsync(client, ct); } /// The supervisor of the connection. public ConnectionSupervisor Supervisor => _supervisor; /// /// Whether is the connection's, not a message's or a refusal: a communication problem the /// client reports, or a socket or I/O failure under it. /// public static bool IsConnectionError(Exception error) { if (error is ServiceBusException { Reason: ServiceBusFailureReason.ServiceCommunicationProblem }) return true; if (error is ServiceBusException) return false; for (var e = error; e is not null; e = e.InnerException) { if (e is SocketException or IOException) return true; } return false; } /// /// Takes an error of the client: a connection error goes to the supervisor (the first shows the loss and starts the /// probe, the later ones are attempts that failed) and true is returned. While the connection is lost, any /// error of a receive belongs to the loss too (a session lock dies with the connection; a namespace that is coming /// back may not serve the entity yet): it becomes the reason health shows, not a failed message. Once connected, any /// other error is left to the caller (false), which records it on the endpoint. A lost session lock is neither: /// the session processor accepts a session again by itself, and a message it cut short is counted where it failed. /// public bool Report(Exception error) { if (error is ServiceBusException { Reason: ServiceBusFailureReason.SessionLockLost }) { if (_supervisor.State != ConnectionState.Connected) _supervisor.Lost(error); return true; } if (!IsConnectionError(error)) { if (_supervisor.State == ConnectionState.Connected) return false; if (_probe is null) _supervisor.Failed(error); else _supervisor.Lost(error); return true; } if (_supervisor.Lost(error)) { StartProbe(); } else if (_probe is null) { // No probe makes the attempts: the client's own failed receive is one. _supervisor.Failed(error); } return true; } /// A receive succeeded, so the connection is there. Cheap while connected. public void Traffic() { if (_supervisor.State != ConnectionState.Connected) _supervisor.Restored(); } /// Ends a running probe and stops reporting to the endpoint. public void Stop() { _stop.Cancel(); _endpoint.Unsupervise(_supervisor); } private void StartProbe() { if (_probe is null || Interlocked.CompareExchange(ref _probing, 1, 0) != 0) return; var stop = _stop.Token; _ = Task.Run(async () => { try { await _supervisor.ReconnectAsync(ProbeAsync, stop).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogDebug(ex, "ASB consumer on {Entity}: the probe ended", _endpoint.EntityName); } finally { Volatile.Write(ref _probing, 0); } }, CancellationToken.None); } // Asks nothing once the connection is back: a receive restored it meanwhile. private Task ProbeAsync(CancellationToken ct) => _supervisor.State == ConnectionState.Connected ? Task.CompletedTask : _supervisor.AttemptAsync(async c => { await _probe!(c).ConfigureAwait(false); return true; }, static _ => { }, ct); private async Task PeekDeadLetterAsync(ServiceBusClient client, CancellationToken ct) { using var bounded = CancellationTokenSource.CreateLinkedTokenSource(ct); bounded.CancelAfter(ProbeTimeout); var options = new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter }; await using var receiver = _endpoint.IsTopic ? client.CreateReceiver(_endpoint.EntityName, _subscription, options) : client.CreateReceiver(_endpoint.EntityName, options); try { await receiver.PeekMessageAsync(cancellationToken: bounded.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { throw new TimeoutException( $"asb:{_endpoint.EntityName}: the namespace did not answer a peek within {ProbeTimeout.TotalSeconds:0} s."); } } }