Merge branch 'feature/core-lifecycle' into main

Reconcile close reason tracking: feature branch's MarkClosed() and
ShouldSkipFlush/FlushAndCloseAsync now use main's ClientClosedReason
enum. ClosedState enum retained for forward compatibility.
This commit is contained in:
Joseph Doherty
2026-02-23 00:09:30 -05:00
12 changed files with 2745 additions and 18 deletions

View File

@@ -65,6 +65,10 @@ public sealed class NatsClient : IDisposable
public long InBytes;
public long OutBytes;
// Close reason tracking
private int _skipFlushOnClose;
public bool ShouldSkipFlush => Volatile.Read(ref _skipFlushOnClose) != 0;
// PING keepalive state
private int _pingsOut;
private long _lastIn;
@@ -174,13 +178,24 @@ public sealed class NatsClient : IDisposable
catch (OperationCanceledException)
{
_logger.LogDebug("Client {ClientId} operation cancelled", Id);
MarkClosed(ClientClosedReason.ServerShutdown);
}
catch (IOException)
{
MarkClosed(ClientClosedReason.ReadError);
}
catch (SocketException)
{
MarkClosed(ClientClosedReason.ReadError);
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Client {ClientId} connection error", Id);
MarkClosed(ClientClosedReason.ReadError);
}
finally
{
MarkClosed(ClientClosedReason.ClientClosed);
_outbound.Writer.TryComplete();
try { _socket.Shutdown(SocketShutdown.Both); }
catch (SocketException) { }
@@ -623,6 +638,57 @@ public sealed class NatsClient : IDisposable
}
}
/// <summary>
/// Marks this connection as closed with the given reason.
/// Sets skip-flush flag for error-related reasons.
/// Only the first call sets the reason (subsequent calls are no-ops).
/// </summary>
public void MarkClosed(ClientClosedReason reason)
{
if (CloseReason != ClientClosedReason.None)
return;
CloseReason = reason;
switch (reason)
{
case ClientClosedReason.ReadError:
case ClientClosedReason.WriteError:
case ClientClosedReason.SlowConsumerPendingBytes:
case ClientClosedReason.SlowConsumerWriteDeadline:
case ClientClosedReason.TlsHandshakeError:
Volatile.Write(ref _skipFlushOnClose, 1);
break;
}
_logger.LogDebug("Client {ClientId} connection closed: {CloseReason}", Id, reason);
}
/// <summary>
/// Flushes pending data (unless skip-flush is set) and closes the connection.
/// </summary>
public async Task FlushAndCloseAsync(bool minimalFlush = false)
{
if (!ShouldSkipFlush)
{
try
{
using var flushCts = new CancellationTokenSource(minimalFlush
? TimeSpan.FromMilliseconds(100)
: TimeSpan.FromSeconds(1));
await _stream.FlushAsync(flushCts.Token);
}
catch (Exception)
{
// Best effort flush — don't let it prevent close
}
}
try { _socket.Shutdown(SocketShutdown.Both); }
catch (SocketException) { }
catch (ObjectDisposedException) { }
}
public void RemoveAllSubscriptions(SubList subList)
{
foreach (var sub in _subs.Values)