Path: redb-route/redb.Route/Core/ConnectableProducer.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/Core/ConnectableProducer.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Core; /// /// Base class for connection-based producers. /// Handles: started guard, logger resolution, Start/Stop lifecycle. /// Subclasses implement and optionally override . /// public abstract class ConnectableProducer : IProducer { private int _started; // 0 = stopped, 1 = fully started (ConnectAsync completed) private readonly object _startLock = new(); private Task? _startTask; private ILogger? _logger; /// The endpoint this producer sends to. protected abstract IEndpoint ProducerEndpoint { get; } /// Display name for logging (e.g. "http:https://api.example.com", "kafka:orders"). protected abstract string ProducerName { get; } /// Logger resolved from the component. protected ILogger? Logger => _logger ??= (ProducerEndpoint.Component as ComponentBase)?.Logger; /// Whether the producer has been started. public bool IsStarted => Volatile.Read(ref _started) == 1; // ── IProducer lifecycle ── /// public Task Start(CancellationToken ct = default) { // Single-flight: the first caller creates the start task; concurrent callers await the SAME // task rather than each starting their own. Crucially, IsStarted flips to true only AFTER // ConnectAsync completes (see StartCoreAsync), so a racing Process()/EnsureStarted() can never // observe a half-initialised producer (e.g. a Redis producer whose _db is not yet assigned). lock (_startLock) { return _startTask ??= StartCoreAsync(ct); } } private async Task StartCoreAsync(CancellationToken ct) { try { await ConnectAsync(ct).ConfigureAwait(false); Volatile.Write(ref _started, 1); // observable as started ONLY now that resources are ready Logger?.LogInformation("{Producer} started.", EndpointUri.ForLog(ProducerName, Logger)); } catch { // Let a later Start() retry a failed cold start instead of caching the failure forever. lock (_startLock) { _startTask = null; } throw; } } /// public async Task Stop(CancellationToken ct = default) { Task? startInFlight; lock (_startLock) { startInFlight = _startTask; _startTask = null; } if (startInFlight is null) return; // never started // Let a concurrent start settle before tearing down (ignore its failure — nothing connected). try { await startInFlight.ConfigureAwait(false); } catch { /* start failed */ } if (Interlocked.CompareExchange(ref _started, 0, 1) != 1) return; // A reconnect in flight finishes first, so a connection it opens is closed here rather than left open after the // stop; a send that waits for one finds the producer stopped. await _reconnectLock.WaitAsync(CancellationToken.None).ConfigureAwait(false); try { await DisconnectAsync(ct).ConfigureAwait(false); } finally { _reconnectLock.Release(); } ReleaseSupervisor(); Logger?.LogInformation("{Producer} stopped.", EndpointUri.ForLog(ProducerName, Logger)); } // ── Lost connection ── private ConnectionSupervisor? _supervisor; private readonly object _supervisorLock = new(); private readonly SemaphoreSlim _reconnectLock = new(1, 1); /// /// The supervisor of this producer's connection, created on first use with the context's reconnect options /// (RedbRoute:Reconnect) and registered with the endpoint, so a lost connection shows in the endpoint's health. /// A producer that never calls behaves as before; a stop removes the supervisor. /// protected ConnectionSupervisor Supervisor { get { lock (_supervisorLock) { return _supervisor ??= ProducerEndpoint is ISupervisingEndpoint endpoint ? endpoint.Supervise(ProducerName, Logger) : new ConnectionSupervisor(ProducerName, new Configuration.ReconnectOptions(), Logger); } } } /// /// Reports that the connection is lost: from a send, a reply loop, a transacted action's commit or a client callback. /// The first report of a loss calls , so the producer fails what waits on the connection /// once; the next reconnects. Nothing is sent again: a send that failed this way may /// or may not have arrived. /// protected internal void MarkConnectionLost(Exception cause) { if (Supervisor.Lost(cause)) OnConnectionLost(cause); } /// Fails what waits on the lost connection, such as pending request-reply calls. Default: nothing. protected virtual void OnConnectionLost(Exception cause) { } /// /// Called by before it sends: when the connection was marked lost, either fails at once while /// the next attempt is not due yet ("the next reconnect attempt is due in N s"), or runs /// and again, one caller at a time; concurrent sends wait for that attempt. A failed attempt /// grows the pause; a successful one reports the connection restored. Returns at once while connected. /// protected async Task EnsureConnectedAsync(CancellationToken ct) { var supervisor = Volatile.Read(ref _supervisor); if (supervisor is null || supervisor.State == ConnectionState.Connected) return; await _reconnectLock.WaitAsync(ct).ConfigureAwait(false); try { EnsureStarted(); // stopped while this send waited: no reconnect behind the stop if (supervisor.State == ConnectionState.Connected) return; var dueIn = supervisor.DueIn; if (dueIn > TimeSpan.Zero) throw new InvalidOperationException( $"{ProducerName}: the connection was lost; the next reconnect attempt is due in {ConnectionSupervisor.FormatDuration(dueIn)}." + (supervisor.LastFailure is { Length: > 0 } failure ? $" Last failure: {failure}" : string.Empty)); await DisconnectAsync(CancellationToken.None).ConfigureAwait(false); try { await ConnectAsync(ct).ConfigureAwait(false); } catch (Exception ex) { await DisconnectAsync(CancellationToken.None).ConfigureAwait(false); if (ex is not OperationCanceledException || !ct.IsCancellationRequested) supervisor.Failed(ex); throw; } supervisor.Restored(); } finally { _reconnectLock.Release(); } } private void ReleaseSupervisor() { ConnectionSupervisor? supervisor; lock (_supervisorLock) { supervisor = _supervisor; _supervisor = null; } if (supervisor is not null && ProducerEndpoint is ISupervisingEndpoint endpoint) endpoint.Unsupervise(supervisor); } // ── Abstract / virtual hooks ── /// /// Set up connection/resources. Awaited by Start() to completion before IsStarted flips to /// true, so subclasses may assign their fields here knowing no Process() can run until it returns. /// protected abstract Task ConnectAsync(CancellationToken ct); /// Tear down connection/resources. Called from Stop() after the started flag is cleared. protected virtual Task DisconnectAsync(CancellationToken ct) => Task.CompletedTask; /// public abstract Task Process(IExchange exchange, CancellationToken ct = default); /// Throws if the producer has not been started. protected void EnsureStarted() { if (!IsStarted) throw new InvalidOperationException($"{ProducerName} has not been started. Call Start() first."); } }