feat: add flush-before-close for graceful client shutdown
This commit is contained in:
@@ -563,6 +563,31 @@ public sealed class NatsClient : IDisposable
|
||||
_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)
|
||||
|
||||
@@ -86,11 +86,14 @@ public sealed class NatsServer : IMessageRouter, ISubListAccess, IDisposable
|
||||
// Wait for accept loop to exit
|
||||
await _acceptLoopExited.Task.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
|
||||
|
||||
// Close all client connections
|
||||
// Close all client connections — flush first, then mark closed
|
||||
var flushTasks = new List<Task>();
|
||||
foreach (var client in _clients.Values)
|
||||
{
|
||||
client.MarkClosed(ClosedState.ServerShutdown);
|
||||
flushTasks.Add(client.FlushAndCloseAsync(minimalFlush: true));
|
||||
}
|
||||
await Task.WhenAll(flushTasks).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
|
||||
|
||||
// Wait for active client tasks to drain (with timeout)
|
||||
if (Volatile.Read(ref _activeClientCount) > 0)
|
||||
|
||||
Reference in New Issue
Block a user