From 658ba33f7f3d6f94523cb42d0ba7a12a953a2ae9 Mon Sep 17 00:00:00 2001 From: "savage@savage.za.org" Date: Thu, 22 Oct 2026 08:07:58 +0200 Subject: [PATCH 1/4] Fix broad exception handling and resource cleanup --- .../ProviderAccountConfigurationService.cs | 3 +- .../ArticleWork/ArticleWorkConsumerService.cs | 15 ++-- .../ArticleWork/ArticleWorkConsumerSession.cs | 5 +- .../ArticleWorkDeliveryPipeline.cs | 5 +- .../ArticleWorkResponsePublisher.cs | 16 +++-- .../ArticleWork/ArticleWorkSettlementLease.cs | 3 +- .../ArticleWork/ProviderArticleWorkHandler.cs | 3 +- .../BackFillerOptionsValidator.cs | 3 +- .../Core/ApplicationServiceManager.cs | 4 +- .../Hosting/Systemd/SystemdNotifyBridge.cs | 7 +- .../Hosting/Systemd/SystemdWatchdogService.cs | 5 +- .../Listener/CacheListenerEndpoints.cs | 8 +-- .../Listener/CacheListenerService.cs | 10 +-- .../Listener/ICacheListenerTransport.cs | 8 ++- .../Nntp/NntpArticleRetriever.cs | 3 +- .../Nntp/NntpProtocolIo.cs | 5 +- .../Nntp/NntpProviderRegistry.cs | 7 +- .../Nntp/NntpProviderSession.cs | 3 +- .../Nntp/NntpSessionPool.cs | 14 ++-- .../Nntp/NntpTlsClient.cs | 10 ++- .../Nntp/TcpNntpTransportFactory.cs | 8 ++- src/VectorNNTPD.BackFillerService/Program.cs | 15 ++-- .../Retention/ArticleRetentionAuthority.cs | 3 +- .../Acme/AcmeCertificateService.cs | 7 +- .../Acme/AcmeExclusiveFileLock.cs | 14 ++-- src/VectorNNTPD.Common/Acme/AcmeIssuer.cs | 3 +- src/VectorNNTPD.Common/Acme/AtomicFile.cs | 10 ++- src/VectorNNTPD.Common/Acme/Dns01Solver.cs | 10 +-- .../Acme/Protocol/AcmeAccountKey.cs | 7 +- .../Articles/ArticleRecordFactory.cs | 3 +- .../Articles/CanonicalArticleBuffer.cs | 3 +- .../NntpArticleCanonicalMaterializer.cs | 3 +- .../Cloudflare/CloudflareDnsReconciler.cs | 3 +- .../CloudflareDnsReconciliationService.cs | 3 +- .../Core/ApplicationLifecycle.cs | 14 ++-- .../Core/ApplicationServiceManager.cs | 8 +-- .../Dns/ZoneApexNameserverDiscovery.cs | 5 +- .../Logging/PeriodicFileFlushSink.cs | 13 ++-- ...abbitMqClientAsyncConfirmPublishChannel.cs | 3 +- .../RabbitMq/RabbitMqClientConnection.cs | 3 +- .../RabbitMqClientConnectionFactory.cs | 13 ++-- .../RabbitMqClientManualAckChannel.cs | 5 +- .../RabbitMq/RabbitMqClientPublishChannel.cs | 3 +- .../Messaging/RabbitMq/RabbitMqService.cs | 6 +- .../TlsCertificateContextProvider.cs | 3 +- .../NntpDb/MySqlNntpDbConnectionFactory.cs | 13 ++-- .../NntpDb/NntpDbService.cs | 4 +- .../Nntp/NntpShutdownDeadlineTests.cs | 5 +- .../Nntp/NntpStartTlsTests.cs | 5 +- .../TestDoubles/ScriptedNntpTransport.cs | 3 +- .../Acme/AcmeExclusiveFileLockTests.cs | 24 +++++-- .../NntpMessageIdValidationTests.cs | 3 +- .../Core/ExceptionHelpersTests.cs | 71 +++++++++++++++++++ 53 files changed, 288 insertions(+), 145 deletions(-) create mode 100644 tests/VectorNNTPD.Common.Tests/Core/ExceptionHelpersTests.cs diff --git a/src/VectorNNTPD.BackFillerService/Accounts/ProviderAccountConfigurationService.cs b/src/VectorNNTPD.BackFillerService/Accounts/ProviderAccountConfigurationService.cs index eb0e3e4f..8b758c79 100644 --- a/src/VectorNNTPD.BackFillerService/Accounts/ProviderAccountConfigurationService.cs +++ b/src/VectorNNTPD.BackFillerService/Accounts/ProviderAccountConfigurationService.cs @@ -5,6 +5,7 @@ using VectorNNTPD.Common.Messaging.RabbitMq; using VectorNNTPD.Common.NntpDb; using VectorNNTPD.Common.Acme; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Accounts { @@ -329,7 +330,7 @@ private async Task RefreshAsync(bool required, CancellationToken cancellat { throw; } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (required && !_hadSuccessfulSnapshot) { diff --git a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkConsumerService.cs b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkConsumerService.cs index 34d37315..fca20c5c 100644 --- a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkConsumerService.cs +++ b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkConsumerService.cs @@ -4,6 +4,7 @@ using VectorNNTPD.BackFillerService.Nntp; using VectorNNTPD.BackFillerService.RabbitMq; using VectorNNTPD.Common.Messaging.RabbitMq; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.ArticleWork @@ -240,7 +241,7 @@ public async Task StartAsync(CancellationToken cancellationToken) await ReconcileSessionsAsync(cancellationToken).ConfigureAwait(false); _reconcileLoop = RunReconcileLoopAsync(_reconcileCts.Token); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { _connections.ConnectionReplaced -= OnConnectionReplaced; _capacity.SnapshotPublished -= OnCapacitySnapshotPublished; @@ -431,7 +432,7 @@ private async Task ShutdownAsync(CancellationToken cancellationToken) await replace.ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] A background reconcile or replacement failure must be logged without faulting an unobserved task. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ArticleWorkLogMessages.ConsumerReplaceFailed(_logger, ex.Message); } @@ -498,7 +499,7 @@ private async Task RunReconcileLoopAsync(CancellationToken cancellationToken) throw; } // codeql[cs/catch-of-all-exceptions] A reconcile fault must stay inside this loop so membership recovery continues. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { Interlocked.Increment(ref _unexpectedReconcileFaults); ArticleWorkLogMessages.ConsumerReconcileFailed(_logger, ex.Message); @@ -582,7 +583,7 @@ private async Task ReconcileObservedAsync() await ReconcileAsync(CancellationToken.None).ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] A background reconcile or replacement failure must be logged without faulting an unobserved task. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ArticleWorkLogMessages.ConsumerReplaceFailed(_logger, ex.Message); } @@ -687,7 +688,7 @@ private async Task ReconcileSessionsAsync(CancellationToken cance started.Add(session); } } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { foreach (var session in started) { @@ -1129,7 +1130,7 @@ private async Task FinishAcquiredReplacementAsync( await ReconcileSessionsAsync(CancellationToken.None).ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] A background reconcile or replacement failure must be logged without faulting an unobserved task. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ArticleWorkLogMessages.ConsumerReplaceFailed(_logger, ex.Message); } @@ -1158,7 +1159,7 @@ private async Task FinishQueuedReplacementAsync(Task replaceGateWait, Task start await RunReplacementBodyAsync().ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] A background reconcile or replacement failure must be logged without faulting an unobserved task. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ArticleWorkLogMessages.ConsumerReplaceFailed(_logger, ex.Message); } diff --git a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkConsumerSession.cs b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkConsumerSession.cs index 37304b69..b81106c3 100644 --- a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkConsumerSession.cs +++ b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkConsumerSession.cs @@ -2,6 +2,7 @@ using VectorNNTPD.BackFillerService.Logging; using VectorNNTPD.BackFillerService.RabbitMq; using VectorNNTPD.Common.Messaging.RabbitMq; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.ArticleWork { @@ -346,7 +347,7 @@ internal async Task StartAsync(CancellationToken cancellationToken) "Channel closed during consumer start.")); } } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ArticleWorkLogMessages.ConsumerStartFailed(_logger, _backbone, _queue, ex.Message); if (channel is not null) @@ -582,7 +583,7 @@ await ArticleWorkSettlementLease.RunExclusiveAsync( return true; } // codeql[cs/catch-of-all-exceptions] A session failure must be observed here so the consumer loop stays owned. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { return false; } diff --git a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkDeliveryPipeline.cs b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkDeliveryPipeline.cs index 06046423..9830ff08 100644 --- a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkDeliveryPipeline.cs +++ b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkDeliveryPipeline.cs @@ -1,5 +1,6 @@ using VectorNNTPD.Common.Messaging.RabbitMq; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.ArticleWork { @@ -209,7 +210,7 @@ internal async Task ProcessAsync( error = null; } // codeql[cs/catch-of-all-exceptions] A delivery failure must be settled or logged by this pipeline boundary. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { outcome = ArticleWorkOutcome.UnexpectedFailure; error = ex.GetType().Name; @@ -414,7 +415,7 @@ await _publisher.PublishAsync( return ArticleWorkPublishAttempt.Cancelled; } // codeql[cs/catch-of-all-exceptions] A delivery failure must be settled or logged by this pipeline boundary. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { return ArticleWorkPublishAttempt.Failed; } diff --git a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkResponsePublisher.cs b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkResponsePublisher.cs index 3eaa7627..91201e7b 100644 --- a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkResponsePublisher.cs +++ b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkResponsePublisher.cs @@ -163,7 +163,7 @@ public async Task StartAsync(CancellationToken cancellationToken) ArticleWorkLogMessages.PublisherRunning(_logger, Generation); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ArticleWorkLogMessages.PublisherStartFailed(_logger, ex.Message); _connections.ConnectionReplaced -= OnConnectionReplaced; @@ -229,7 +229,7 @@ public async ValueTask DisposeAsync() await replace.ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] A publish or replacement failure must not escape this publisher boundary. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ArticleWorkLogMessages.PublisherReplaceFailed(_logger, ex.Message); } @@ -536,7 +536,7 @@ private async Task RebuildPublishChannelAsync() await ReplaceChannelAsync(startup: false, _runCts.Token).ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] A publish or replacement failure must not escape this publisher boundary. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ArticleWorkLogMessages.PublisherReplaceFailed(_logger, ex.Message); } @@ -615,6 +615,7 @@ private async Task ReplaceChannelAsync(bool startup, CancellationToken cancellat var channel = await handle.Connection .CreatePublishChannelAsync(handle.Generation, cancellationToken) .ConfigureAwait(false); + IAsyncDisposable? pendingDispose = channel; try { if (!handle.IsCurrent || channel.Generation != handle.Generation) @@ -623,11 +624,14 @@ private async Task ReplaceChannelAsync(bool startup, CancellationToken cancellat } await InstallPublishChannelAsync(channel).ConfigureAwait(false); + pendingDispose = null; } - catch + finally { - await channel.DisposeAsync().ConfigureAwait(false); - throw; + if (pendingDispose is not null) + { + await pendingDispose.DisposeAsync().ConfigureAwait(false); + } } } diff --git a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkSettlementLease.cs b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkSettlementLease.cs index dbce8a35..24ebe5bb 100644 --- a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkSettlementLease.cs +++ b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkSettlementLease.cs @@ -1,5 +1,6 @@ using System.Runtime.CompilerServices; using VectorNNTPD.Common.Messaging.RabbitMq; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.ArticleWork { @@ -110,7 +111,7 @@ await _channel.BasicRejectAsync(_deliveryTag, disposition.Requeue, CancellationT return true; } // codeql[cs/catch-of-all-exceptions] Settlement cleanup must finish even when an unexpected exception is thrown. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { return false; } diff --git a/src/VectorNNTPD.BackFillerService/ArticleWork/ProviderArticleWorkHandler.cs b/src/VectorNNTPD.BackFillerService/ArticleWork/ProviderArticleWorkHandler.cs index 5d31fbf8..bfcdbe06 100644 --- a/src/VectorNNTPD.BackFillerService/ArticleWork/ProviderArticleWorkHandler.cs +++ b/src/VectorNNTPD.BackFillerService/ArticleWork/ProviderArticleWorkHandler.cs @@ -10,6 +10,7 @@ using System.Text; using VectorNNTPD.Common.Configuration; using NntpArticleIdentity = VectorNNTPD.Common.Articles.Processing.NntpArticleIdentity; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.ArticleWork { @@ -323,7 +324,7 @@ public async ValueTask HandleAsync( cancellationToken) .ConfigureAwait(false); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { LogArticleProcessed(item, OutcomeFailed, string.Empty, CommandTimestamp(ex)); if (ex is OperationCanceledException && cancellationToken.IsCancellationRequested) diff --git a/src/VectorNNTPD.BackFillerService/Configuration/BackFillerOptionsValidator.cs b/src/VectorNNTPD.BackFillerService/Configuration/BackFillerOptionsValidator.cs index 2667cbba..987ed8e6 100644 --- a/src/VectorNNTPD.BackFillerService/Configuration/BackFillerOptionsValidator.cs +++ b/src/VectorNNTPD.BackFillerService/Configuration/BackFillerOptionsValidator.cs @@ -3,6 +3,7 @@ using VectorNNTPD.BackFillerService.Networking; using VectorNNTPD.Common.Messaging.RabbitMq; using VectorNNTPD.Common.Configuration; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Configuration { @@ -416,7 +417,7 @@ private void ValidateArticleRetention(BackFillerOptions options, List fa totalPhysicalMemoryBytes = _physicalMemoryProvider.GetTotalPhysicalMemoryBytes(); } // codeql[cs/catch-of-all-exceptions] Validation must report every rejected value and continue checking the remaining options. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { failures.Add( $"The host must have at least {BackFillerArticleRetentionOptions.MinimumPhysicalMemoryGibibytes} GiB ({BackFillerArticleRetentionOptions.MinimumPhysicalMemoryBytes} bytes) of physical RAM, but total physical memory could not be determined."); diff --git a/src/VectorNNTPD.BackFillerService/Core/ApplicationServiceManager.cs b/src/VectorNNTPD.BackFillerService/Core/ApplicationServiceManager.cs index 0e281460..d3022f26 100644 --- a/src/VectorNNTPD.BackFillerService/Core/ApplicationServiceManager.cs +++ b/src/VectorNNTPD.BackFillerService/Core/ApplicationServiceManager.cs @@ -311,7 +311,7 @@ internal async Task StopAsync(CancellationToken cancellationToken) ApplicationServiceManagerLogMessages.ServiceStopAbortedAfterBudget(_logger, service.Name); } } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ApplicationServiceManagerLogMessages.ServiceStopFailed(_logger, ex, service.Name); failures.Add(ex); @@ -383,7 +383,7 @@ private async Task RollbackStartedAsync(CancellationToken cancellationToken) await service.StopAsync(timeoutCts.Token).ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] A service start or stop failure must be recorded without abandoning the remaining services. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ApplicationServiceManagerLogMessages.ServiceRollbackFailed(_logger, ex, service.Name); } diff --git a/src/VectorNNTPD.BackFillerService/Hosting/Systemd/SystemdNotifyBridge.cs b/src/VectorNNTPD.BackFillerService/Hosting/Systemd/SystemdNotifyBridge.cs index 8ba1e123..194a40cf 100644 --- a/src/VectorNNTPD.BackFillerService/Hosting/Systemd/SystemdNotifyBridge.cs +++ b/src/VectorNNTPD.BackFillerService/Hosting/Systemd/SystemdNotifyBridge.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Hosting.Systemd; using Serilog.Debugging; using VectorNNTPD.BackFillerService.Logging; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Hosting.Systemd { @@ -113,21 +114,21 @@ private void Notify(ServiceState state, string label) SystemdLogMessages.NotificationSent(_logger, label); } // codeql[cs/catch-of-all-exceptions] A notification or diagnostic failure must not escape the notifier. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { try { SystemdLogMessages.NotificationFailed(_logger, ex, label); } // codeql[cs/catch-of-all-exceptions] A notification or diagnostic failure must not escape the notifier. - catch (Exception logFailure) + catch (Exception logFailure) when (!ExceptionHelpers.IsFatal(logFailure)) { try { SelfLog.WriteLine("systemd notification failure log failed: {0}", logFailure); } // codeql[cs/catch-of-all-exceptions] A notification or diagnostic failure must not escape the notifier. - catch (Exception) + catch (Exception selfLogFailure) when (!ExceptionHelpers.IsFatal(selfLogFailure)) { // Notification and its diagnostic log are both best-effort. } diff --git a/src/VectorNNTPD.BackFillerService/Hosting/Systemd/SystemdWatchdogService.cs b/src/VectorNNTPD.BackFillerService/Hosting/Systemd/SystemdWatchdogService.cs index a200a011..f363ae81 100644 --- a/src/VectorNNTPD.BackFillerService/Hosting/Systemd/SystemdWatchdogService.cs +++ b/src/VectorNNTPD.BackFillerService/Hosting/Systemd/SystemdWatchdogService.cs @@ -1,6 +1,7 @@ using VectorNNTPD.BackFillerService.Configuration; using VectorNNTPD.BackFillerService.Logging; using Microsoft.Extensions.Options; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Hosting.Systemd { @@ -171,7 +172,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) SystemdLogMessages.WatchdogKeepAliveSent(_logger); } // codeql[cs/catch-of-all-exceptions] A watchdog notify failure must be logged and must not stop the process. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // Unlike NNTPD, notify failures must not stop BackFiller. Missing // keep-alives still trip systemd when WatchdogSec is configured. @@ -183,7 +184,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { SystemdLogMessages.WatchdogDeactivated(_logger); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { SystemdLogMessages.WatchdogLoopFailed(_logger, ex); Interlocked.Exchange(ref _active, 0); diff --git a/src/VectorNNTPD.BackFillerService/Listener/CacheListenerEndpoints.cs b/src/VectorNNTPD.BackFillerService/Listener/CacheListenerEndpoints.cs index a7343f77..e3a3239c 100644 --- a/src/VectorNNTPD.BackFillerService/Listener/CacheListenerEndpoints.cs +++ b/src/VectorNNTPD.BackFillerService/Listener/CacheListenerEndpoints.cs @@ -1,4 +1,3 @@ - using System.Net; using System.Net.Sockets; using VectorNNTPD.Common.Networking.Listeners; @@ -43,16 +42,17 @@ private static Socket CreateBoundListenSocket(IPEndPoint endpoint, bool dualMode socket.DualMode = dualMode; } + Socket? pendingDispose = socket; try { socket.Bind(endpoint); socket.Listen(512); + pendingDispose = null; return socket; } - catch + finally { - socket.Dispose(); - throw; + pendingDispose?.Dispose(); } } } diff --git a/src/VectorNNTPD.BackFillerService/Listener/CacheListenerService.cs b/src/VectorNNTPD.BackFillerService/Listener/CacheListenerService.cs index 6759766c..c9745512 100644 --- a/src/VectorNNTPD.BackFillerService/Listener/CacheListenerService.cs +++ b/src/VectorNNTPD.BackFillerService/Listener/CacheListenerService.cs @@ -340,7 +340,7 @@ public async Task StartAsync(CancellationToken cancellationToken) _journal.Record(BackFillerStartupStages.ListenerStarted); _acceptTask = AcceptAllAsync(_runCts.Token); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { CacheListenerLogMessages.StartFailed(_logger, ex.Message); await DisposeBoundResourcesAsync().ConfigureAwait(false); @@ -822,7 +822,7 @@ private async Task ProcessAsync(Socket accepted, string remote, CancellationToke CacheListenerLogMessages.ConnectionIoClosed(_logger, remote, ex.GetType().Name); } // codeql[cs/catch-of-all-exceptions] One connection failure must be logged and must not leave the accept loop with an unobserved task fault. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { CacheListenerLogMessages.ConnectionFailed(_logger, remote, ex.GetType().Name); } @@ -940,14 +940,14 @@ private async Task DrainConnectionsAsync() await Task.WhenAll(tasks).ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] A connection-task fault during drain must not skip the remaining listener cleanup. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { try { CacheListenerLogMessages.ConnectionDrainFailed(_logger, ex.GetBaseException().GetType().Name); } // codeql[cs/catch-of-all-exceptions] A connection-task fault during drain must not skip the remaining listener cleanup. - catch (Exception logFailure) + catch (Exception logFailure) when (!ExceptionHelpers.IsFatal(logFailure)) { try { @@ -956,7 +956,7 @@ private async Task DrainConnectionsAsync() logFailure); } // codeql[cs/catch-of-all-exceptions] A connection-task fault during drain must not skip the remaining listener cleanup. - catch (Exception) + catch (Exception selfLogFailure) when (!ExceptionHelpers.IsFatal(selfLogFailure)) { // Drain logging is best-effort. Remaining dispose work still runs. } diff --git a/src/VectorNNTPD.BackFillerService/Listener/ICacheListenerTransport.cs b/src/VectorNNTPD.BackFillerService/Listener/ICacheListenerTransport.cs index ac6ec12b..f0b0cc66 100644 --- a/src/VectorNNTPD.BackFillerService/Listener/ICacheListenerTransport.cs +++ b/src/VectorNNTPD.BackFillerService/Listener/ICacheListenerTransport.cs @@ -1,3 +1,5 @@ +using VectorNNTPD.Common.Core; + namespace VectorNNTPD.BackFillerService.Listener { /// @@ -149,7 +151,7 @@ public ValueTask ReadAsync(Memory buffer, CancellationToken cancellat ThrowTranslatedCancellation(cancellationToken, operation: "read"); throw; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { Disarm(); throw; @@ -201,7 +203,7 @@ public ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken ThrowTranslatedCancellation(cancellationToken, operation: "write"); throw; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { Disarm(); throw; @@ -334,7 +336,7 @@ private CancellationToken Arm(CancellationToken cancellationToken) retired?.Dispose(); return token; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { retired?.Dispose(); Disarm(); diff --git a/src/VectorNNTPD.BackFillerService/Nntp/NntpArticleRetriever.cs b/src/VectorNNTPD.BackFillerService/Nntp/NntpArticleRetriever.cs index 7a8fdeac..0c46625f 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/NntpArticleRetriever.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/NntpArticleRetriever.cs @@ -1,5 +1,6 @@ using VectorNNTPD.BackFillerService.ArticleWork; using VectorNNTPD.Common.Articles; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Nntp { @@ -129,7 +130,7 @@ public async Task RetrieveAsync( return result; } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { RememberCommandTimestamp(ex, lease.Session.ArticleCommandStartedTimestamp); throw; diff --git a/src/VectorNNTPD.BackFillerService/Nntp/NntpProtocolIo.cs b/src/VectorNNTPD.BackFillerService/Nntp/NntpProtocolIo.cs index 7ba5a653..4a5274c5 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/NntpProtocolIo.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/NntpProtocolIo.cs @@ -1,5 +1,6 @@ using System.Buffers; using System.Text; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Nntp { @@ -417,7 +418,7 @@ internal async Task ReadLineAsync(int maxBytes, TimeSpan timeout, Cancellat { await ReadByteAfterPendingCarriageReturnAsync(timeoutCts.Token).ConfigureAwait(false); } - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { _offset = 0; _count = 0; @@ -747,7 +748,7 @@ private void EnsurePayloadCapacity(int needed, int maxBytes) _payloadScratch.AsSpan(0, _payloadCount).CopyTo(next); } } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { _payloadPool.Return(next); throw; diff --git a/src/VectorNNTPD.BackFillerService/Nntp/NntpProviderRegistry.cs b/src/VectorNNTPD.BackFillerService/Nntp/NntpProviderRegistry.cs index 7bafad7c..5f7b17e1 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/NntpProviderRegistry.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/NntpProviderRegistry.cs @@ -2,6 +2,7 @@ using VectorNNTPD.BackFillerService.Accounts; using VectorNNTPD.BackFillerService.ArticleWork; using VectorNNTPD.BackFillerService.Configuration; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Nntp { @@ -509,14 +510,14 @@ private async Task ReconcileConsumersObservedAsync() NntpLogMessages.SessionReplenishFailed(_logger, "consumers", ex.Message); } // codeql[cs/catch-of-all-exceptions] An observed reconcile task must log every failure, including a failure of that log. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { try { NntpLogMessages.SessionReplenishFailed(_logger, "consumers", ex.Message); } // codeql[cs/catch-of-all-exceptions] An observed reconcile task must log every failure, including a failure of that log. - catch (Exception logFailure) + catch (Exception logFailure) when (!ExceptionHelpers.IsFatal(logFailure)) { try { @@ -525,7 +526,7 @@ private async Task ReconcileConsumersObservedAsync() logFailure); } // codeql[cs/catch-of-all-exceptions] An observed reconcile task must log every failure, including a failure of that log. - catch (Exception) + catch (Exception selfLogFailure) when (!ExceptionHelpers.IsFatal(selfLogFailure)) { // The reconcile task is unobserved. Its failure must not become an unhandled task exception. } diff --git a/src/VectorNNTPD.BackFillerService/Nntp/NntpProviderSession.cs b/src/VectorNNTPD.BackFillerService/Nntp/NntpProviderSession.cs index 056c7e21..c46b70da 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/NntpProviderSession.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/NntpProviderSession.cs @@ -7,6 +7,7 @@ using VectorNNTPD.Common.Articles; using System.Buffers; using System.Text; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Nntp { @@ -1114,7 +1115,7 @@ await WriteCommandAsync("STARTTLS", NntpProtocolIo.StartTlsCommand, cancellation NntpLogMessages.WireTlsHandshakeStarting(_logger, _wireIdentity); } - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { try { diff --git a/src/VectorNNTPD.BackFillerService/Nntp/NntpSessionPool.cs b/src/VectorNNTPD.BackFillerService/Nntp/NntpSessionPool.cs index e1016b80..e7f9d439 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/NntpSessionPool.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/NntpSessionPool.cs @@ -830,7 +830,7 @@ internal async Task AcquireAsync(CancellationToken cancellatio continue; } } - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { try { @@ -1151,7 +1151,7 @@ private async Task DisposeCoreAsync( ShutdownObservations.Canceled(_logger, "session replenish"); } // codeql[cs/catch-of-all-exceptions] Keepalive and replenishment failures must retire or log the session and must not escape the background task. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { NntpLogMessages.SessionReplenishFailed(_logger, _provider.Backbone, ex.Message); } @@ -1398,7 +1398,7 @@ private async Task AcquirePermitAsync(CancellationToken cancellationToken) await _leases.WaitAsync(cancellationToken).ConfigureAwait(false); } - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { try { @@ -1726,7 +1726,7 @@ private async Task CreateReadySessionAsync(CancellationToke { connectionNumber = AllocateConnectionNumber(); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { Interlocked.Decrement(ref _created); throw; @@ -1737,7 +1737,7 @@ private async Task CreateReadySessionAsync(CancellationToke { session = new NntpProviderSession(_provider, _options, _logger, connectionNumber); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ReleaseUnregisteredReservation(connectionNumber); throw; @@ -1783,7 +1783,7 @@ private async Task CreateReadySessionAsync(CancellationToke failure?.Reason ?? "NNTP connect failed."); } // codeql[cs/catch-of-all-exceptions] Failed creation must release its own reservation for every exception type and must not leave the session in the live set. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (registered && ex is not NntpProviderConnectException) { @@ -2284,7 +2284,7 @@ await RetireFromKeepAliveAsync(session, registration, "DATE keepalive failed") ShutdownObservations.Canceled(_logger, "DATE keepalive"); } // codeql[cs/catch-of-all-exceptions] Keepalive and replenishment failures must retire or log the session and must not escape the background task. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // The loop still owns the session only while its registration is the published one and the session remains idle. // A dequeue that already took it, or a replacement keepalive, retires or keeps it. diff --git a/src/VectorNNTPD.BackFillerService/Nntp/NntpTlsClient.cs b/src/VectorNNTPD.BackFillerService/Nntp/NntpTlsClient.cs index 84b176e7..9e35b72f 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/NntpTlsClient.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/NntpTlsClient.cs @@ -76,6 +76,7 @@ internal static async Task AuthenticateAsClientAsync( { ArgumentNullException.ThrowIfNull(inner); var ssl = streamFactory?.Invoke(inner) ?? new SslStream(inner, leaveInnerStreamOpen: false); + SslStream? pendingDispose = ssl; try { using var tlsCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -84,12 +85,15 @@ await ssl.AuthenticateAsClientAsync( CreateClientOptions(host, serverCertificateValidationCallback), tlsCts.Token) .ConfigureAwait(false); + pendingDispose = null; return ssl; } - catch + finally { - await ssl.DisposeAsync().ConfigureAwait(false); - throw; + if (pendingDispose is not null) + { + await pendingDispose.DisposeAsync().ConfigureAwait(false); + } } } } diff --git a/src/VectorNNTPD.BackFillerService/Nntp/TcpNntpTransportFactory.cs b/src/VectorNNTPD.BackFillerService/Nntp/TcpNntpTransportFactory.cs index eea18e76..84c28d2d 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/TcpNntpTransportFactory.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/TcpNntpTransportFactory.cs @@ -44,6 +44,7 @@ public async Task ConnectAsync( ArgumentNullException.ThrowIfNull(options); var client = new TcpClient(); + TcpClient? pendingClient = client; try { @@ -66,6 +67,7 @@ public async Task ConnectAsync( Stream stream = client.GetStream(); if (!provider.UseTls) { + pendingClient = null; return new TcpOwnedStream(client, stream); } @@ -76,12 +78,12 @@ public async Task ConnectAsync( options.ServerCertificateValidationCallback, cancellationToken) .ConfigureAwait(false); + pendingClient = null; return new TcpOwnedStream(client, ssl); } - catch + finally { - client.Dispose(); - throw; + pendingClient?.Dispose(); } } diff --git a/src/VectorNNTPD.BackFillerService/Program.cs b/src/VectorNNTPD.BackFillerService/Program.cs index e56f5a4e..0a3ed9bd 100644 --- a/src/VectorNNTPD.BackFillerService/Program.cs +++ b/src/VectorNNTPD.BackFillerService/Program.cs @@ -4,6 +4,7 @@ using VectorNNTPD.BackFillerService.Logging; using VectorNNTPD.BackFillerService.Configuration; using VectorNNTPD.Common.Configuration; +using VectorNNTPD.Common.Core; /// Process entry point. Builds the Generic Host from the entry-assembly directory and runs it. internal class Program @@ -77,7 +78,7 @@ private static async Task Main(string[] args) } } // codeql[cs/catch-of-all-exceptions] The process boundary must log every host failure and still return the documented exit code. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { exitCode = BackFillerProcessBoundary.ObserveHostFailure(ex); } @@ -134,14 +135,14 @@ internal static int ObserveHostFailure(Exception exception, Action lo logFatal(exception); } // codeql[cs/catch-of-all-exceptions] The process boundary must log every host failure and still return the documented exit code. - catch (Exception logFailure) + catch (Exception logFailure) when (!ExceptionHelpers.IsFatal(logFailure)) { try { SelfLog.WriteLine("BackFiller host failure log failed: {0}", logFailure); } // codeql[cs/catch-of-all-exceptions] The process boundary must log every host failure and still return the documented exit code. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // The process boundary must still return the failure exit code. } @@ -179,7 +180,7 @@ internal static async Task FinishAsync(int exitCode, Func closeAndFlu await closeAndFlush().ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] Logger shutdown must not replace the process result or skip console restoration. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ObserveShutdownFailure(exitCode, ex); } @@ -190,14 +191,14 @@ internal static async Task FinishAsync(int exitCode, Func closeAndFlu restoreConsole(); } // codeql[cs/catch-of-all-exceptions] Console restoration must not replace the process result. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { try { SelfLog.WriteLine("BackFiller console restore failed: {0}", ex); } // codeql[cs/catch-of-all-exceptions] Console restoration must not replace the process result. - catch (Exception) + catch (Exception selfLogFailure) when (!ExceptionHelpers.IsFatal(selfLogFailure)) { // The process boundary must still return the chosen exit code. } @@ -226,7 +227,7 @@ private static void ObserveShutdownFailure(int exitCode, Exception exception) SelfLog.WriteLine(message, exception); } // codeql[cs/catch-of-all-exceptions] A secondary shutdown diagnostic must not replace the process result. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // The chosen exit code remains the process result. } diff --git a/src/VectorNNTPD.BackFillerService/Retention/ArticleRetentionAuthority.cs b/src/VectorNNTPD.BackFillerService/Retention/ArticleRetentionAuthority.cs index cf4cba99..d4a70083 100644 --- a/src/VectorNNTPD.BackFillerService/Retention/ArticleRetentionAuthority.cs +++ b/src/VectorNNTPD.BackFillerService/Retention/ArticleRetentionAuthority.cs @@ -5,6 +5,7 @@ using CanonicalBufferLease = VectorNNTPD.Common.Articles.CanonicalArticleBuffer.CanonicalBufferLease; using VectorNNTPD.Common.Articles.Parsing; using NntpArticleIdentity = VectorNNTPD.Common.Articles.Processing.NntpArticleIdentity; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Retention { @@ -496,7 +497,7 @@ public ArticleRetentionResult RetainCanonical( ArticleRetentionLogMessages.Retained(_logger, identity.ArticleIdHex, record.ArtSize, _retainedBytes); return result; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (entry is not null) { diff --git a/src/VectorNNTPD.Common/Acme/AcmeCertificateService.cs b/src/VectorNNTPD.Common/Acme/AcmeCertificateService.cs index f901a2b1..7cab90f1 100644 --- a/src/VectorNNTPD.Common/Acme/AcmeCertificateService.cs +++ b/src/VectorNNTPD.Common/Acme/AcmeCertificateService.cs @@ -1,4 +1,5 @@ using VectorNNTPD.Common.Configuration; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Acme { @@ -207,7 +208,7 @@ internal async Task StopAsync(CancellationToken cancellationToken) { // Expected on cancel. } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { AcmeLogMessages.RenewalLoopStopError(_logger, ex); } @@ -285,7 +286,7 @@ private async Task RunRenewalLoopAsync(CancellationToken cancellationToken) break; } // codeql[cs/catch-of-all-exceptions] Certificate renewal must record every failure and continue the documented recovery path. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { AcmeLogMessages.RenewalCheckFailed(_logger, AcmeFailureSanitizer.Sanitize(ex)); ObserveFailure(); @@ -341,7 +342,7 @@ private void ObserveFailure() _observation.OnObserved(_manager.EvaluateExisting(_time.GetUtcNow()), renewalReplacedCertificate: false); } // codeql[cs/catch-of-all-exceptions] An unreadable certificate must be reported without ending the renewal loop. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { _observation.OnUnreadable(ex); } diff --git a/src/VectorNNTPD.Common/Acme/AcmeExclusiveFileLock.cs b/src/VectorNNTPD.Common/Acme/AcmeExclusiveFileLock.cs index 2f7e6f67..3f7c1db3 100644 --- a/src/VectorNNTPD.Common/Acme/AcmeExclusiveFileLock.cs +++ b/src/VectorNNTPD.Common/Acme/AcmeExclusiveFileLock.cs @@ -127,19 +127,21 @@ internal static bool TryAcquireOnce( return false; } - // Open succeeded: dispose on initialization failure, otherwise transfer ownership - // to the returned lock. A finally/null pattern is avoided so initialization errors - // cannot be mistaken for open-time contention retries. + // Open succeeded: dispose on any initialization failure, otherwise transfer ownership + // to the returned lock. Ownership-transfer finally keeps cleanup on every failure path + // (including process-integrity failures) without a catch-all, and never returns false + // here — so init errors cannot be mistaken for open-time contention retries. + FileStream? pendingDispose = stream; try { InitializeLockFile(stream); acquired = new AcmeExclusiveFileLock(stream); + pendingDispose = null; return true; } - catch + finally { - stream.Dispose(); - throw; + pendingDispose?.Dispose(); } } diff --git a/src/VectorNNTPD.Common/Acme/AcmeIssuer.cs b/src/VectorNNTPD.Common/Acme/AcmeIssuer.cs index ae71991d..04421831 100644 --- a/src/VectorNNTPD.Common/Acme/AcmeIssuer.cs +++ b/src/VectorNNTPD.Common/Acme/AcmeIssuer.cs @@ -2,6 +2,7 @@ using System.Security.Cryptography.X509Certificates; using VectorNNTPD.Common.Acme.Protocol; using VectorNNTPD.Common.Configuration; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Acme { @@ -507,7 +508,7 @@ private async Task BestEffortDnsCleanupAsync(CancellationToken cancellationToken { // Ignore clean-up cancel during best-effort. } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // Best-effort. } diff --git a/src/VectorNNTPD.Common/Acme/AtomicFile.cs b/src/VectorNNTPD.Common/Acme/AtomicFile.cs index 3feb33f7..2706f8fa 100644 --- a/src/VectorNNTPD.Common/Acme/AtomicFile.cs +++ b/src/VectorNNTPD.Common/Acme/AtomicFile.cs @@ -23,6 +23,7 @@ internal static void WriteBytes(string path, ReadOnlySpan data) directory ?? ".", $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp"); + var committed = false; try { using (var stream = new FileStream( @@ -38,11 +39,14 @@ internal static void WriteBytes(string path, ReadOnlySpan data) } File.Move(tempPath, path, overwrite: true); + committed = true; } - catch + finally { - TryDelete(tempPath); - throw; + if (!committed) + { + TryDelete(tempPath); + } } } diff --git a/src/VectorNNTPD.Common/Acme/Dns01Solver.cs b/src/VectorNNTPD.Common/Acme/Dns01Solver.cs index 445e828b..7049f743 100644 --- a/src/VectorNNTPD.Common/Acme/Dns01Solver.cs +++ b/src/VectorNNTPD.Common/Acme/Dns01Solver.cs @@ -1,3 +1,5 @@ +using VectorNNTPD.Common.Core; + namespace VectorNNTPD.Common.Acme { /// One DNS-01 challenge to publish as a TXT record. @@ -129,7 +131,7 @@ internal async Task RecoverAsync(CancellationToken cancellationToken) { throw; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { failures++; } @@ -216,7 +218,7 @@ internal async Task WaitPropagatedAsync( { throw; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { continue; } @@ -271,7 +273,7 @@ await DeleteOwnedRecordAsync(item.ZoneId, item.RecordId, cancellationToken) { throw; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { remaining.Add(item); } @@ -466,7 +468,7 @@ private async Task BestEffortCleanupAsync(CancellationToken cancellationToken) { throw; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // Logged by callers via category. } diff --git a/src/VectorNNTPD.Common/Acme/Protocol/AcmeAccountKey.cs b/src/VectorNNTPD.Common/Acme/Protocol/AcmeAccountKey.cs index 007a9756..1ed1ec45 100644 --- a/src/VectorNNTPD.Common/Acme/Protocol/AcmeAccountKey.cs +++ b/src/VectorNNTPD.Common/Acme/Protocol/AcmeAccountKey.cs @@ -66,6 +66,7 @@ internal static AcmeAccountKey ImportPkcs8Der(ReadOnlySpan pkcs8Der) } RSA rsa = RSA.Create(); + RSA? pendingDispose = rsa; try { rsa.ImportPkcs8PrivateKey(pkcs8Der, out int bytesRead); @@ -75,12 +76,12 @@ internal static AcmeAccountKey ImportPkcs8Der(ReadOnlySpan pkcs8Der) $"PKCS#8 import consumed {bytesRead} of {pkcs8Der.Length} bytes."); } + pendingDispose = null; return new AcmeAccountKey(rsa); } - catch + finally { - rsa.Dispose(); - throw; + pendingDispose?.Dispose(); } } diff --git a/src/VectorNNTPD.Common/Articles/ArticleRecordFactory.cs b/src/VectorNNTPD.Common/Articles/ArticleRecordFactory.cs index f653aca0..2f523571 100644 --- a/src/VectorNNTPD.Common/Articles/ArticleRecordFactory.cs +++ b/src/VectorNNTPD.Common/Articles/ArticleRecordFactory.cs @@ -5,6 +5,7 @@ using VectorNNTPD.Common.Articles.Processing; using VectorNNTPD.Common.Articles.Validation; using VectorNNTPD.Common.Transport.ArticleTransfer; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Articles { @@ -131,7 +132,7 @@ internal static ArticleRecordCreateResult TryCreate( buffer = null; return ArticleRecordCreateResult.Accepted(record, parse.SelectedDateHeaderName); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (buffer is not null) { diff --git a/src/VectorNNTPD.Common/Articles/CanonicalArticleBuffer.cs b/src/VectorNNTPD.Common/Articles/CanonicalArticleBuffer.cs index dffcafb5..1846ea03 100644 --- a/src/VectorNNTPD.Common/Articles/CanonicalArticleBuffer.cs +++ b/src/VectorNNTPD.Common/Articles/CanonicalArticleBuffer.cs @@ -1,5 +1,6 @@ using System.Buffers; using System.Threading; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Articles { @@ -218,7 +219,7 @@ internal static bool TryCreate( lease = new CanonicalBufferLease(buffer); return true; } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { buffer.ReleaseConsumer(); throw; diff --git a/src/VectorNNTPD.Common/Articles/Processing/NntpArticleCanonicalMaterializer.cs b/src/VectorNNTPD.Common/Articles/Processing/NntpArticleCanonicalMaterializer.cs index ce75214c..cff65672 100644 --- a/src/VectorNNTPD.Common/Articles/Processing/NntpArticleCanonicalMaterializer.cs +++ b/src/VectorNNTPD.Common/Articles/Processing/NntpArticleCanonicalMaterializer.cs @@ -1,5 +1,6 @@ using System.Buffers; using VectorNNTPD.Common.Articles.Parsing; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Articles.Processing { @@ -369,7 +370,7 @@ internal static NntpArticleCanonicalMaterializeResult Materialize( ? NntpArticleCanonicalMaterializeResult.Accepted(destination) : NntpArticleCanonicalMaterializeResult.Accepted(destination, finalLength); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ReturnRented(rentFrom, destination, ref returned); throw; diff --git a/src/VectorNNTPD.Common/Cloudflare/CloudflareDnsReconciler.cs b/src/VectorNNTPD.Common/Cloudflare/CloudflareDnsReconciler.cs index 7b1984fb..c1f4cbbc 100644 --- a/src/VectorNNTPD.Common/Cloudflare/CloudflareDnsReconciler.cs +++ b/src/VectorNNTPD.Common/Cloudflare/CloudflareDnsReconciler.cs @@ -2,6 +2,7 @@ using System.Net.Sockets; using VectorNNTPD.Common.Networking; using VectorNNTPD.Common.Configuration; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Cloudflare { @@ -781,7 +782,7 @@ await DeleteRecordsAsync(zoneId, fqdn, CloudflareDnsRecordTypes.AAAA, planAaaa.R // Stage 6: re-read and verify the exact final sets. await VerifyAsync(zoneId, fqdn, desiredV4, desiredV6, cancellationToken).ConfigureAwait(false); } - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (!_deletedPreExistingDuringLastReconcile) { diff --git a/src/VectorNNTPD.Common/Cloudflare/CloudflareDnsReconciliationService.cs b/src/VectorNNTPD.Common/Cloudflare/CloudflareDnsReconciliationService.cs index fd53eaa0..9f9572b7 100644 --- a/src/VectorNNTPD.Common/Cloudflare/CloudflareDnsReconciliationService.cs +++ b/src/VectorNNTPD.Common/Cloudflare/CloudflareDnsReconciliationService.cs @@ -1,5 +1,6 @@ using VectorNNTPD.Common.Networking; using VectorNNTPD.Common.Configuration; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Cloudflare { @@ -357,7 +358,7 @@ await _reconciler fqdn, FailedStartCleanupTimeout); } - catch (Exception cleanupEx) + catch (Exception cleanupEx) when (!ExceptionHelpers.IsFatal(cleanupEx)) { CloudflareLogMessages.PostFailureCleanupFailed(_logger, cleanupEx, fqdn); } diff --git a/src/VectorNNTPD.Common/Core/ApplicationLifecycle.cs b/src/VectorNNTPD.Common/Core/ApplicationLifecycle.cs index dc1659f0..a2ce53a5 100644 --- a/src/VectorNNTPD.Common/Core/ApplicationLifecycle.cs +++ b/src/VectorNNTPD.Common/Core/ApplicationLifecycle.cs @@ -195,7 +195,7 @@ internal async Task StartAsync(CancellationToken cancellationToken) throw new TimeoutException( $"Application startup timed out after {_options.StartupTimeout}."); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { LifecycleLogMessages.StartupFailed(_logger, ex, sw.ElapsedMilliseconds); await FailStartupCleanupAsync().ConfigureAwait(false); @@ -310,7 +310,7 @@ public async ValueTask DisposeAsync() // Complete graceful stop before marking disposed. await StopAsync(CancellationToken.None).ConfigureAwait(false); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { shutdownFailure = ex; LifecycleLogMessages.DisposalShutdownFailure(_logger, ex); @@ -363,7 +363,7 @@ private async Task AwaitExistingStopAsync() { await stop.ConfigureAwait(false); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // The original stop/dispose caller observes the failure; subsequent dispose awaits are idempotent. } @@ -373,7 +373,7 @@ private async Task AwaitExistingStopAsync() { await _disposeCompleted.Task.ConfigureAwait(false); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // Idempotent subsequent dispose: do not rethrow the original failure. } @@ -425,7 +425,7 @@ private async Task StopCoreAsync(CancellationToken cancellationToken) _stoppedTcs.TrySetResult(); throw; } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { LifecycleLogMessages.ShutdownFailed(_logger, ex, sw.ElapsedMilliseconds); Transition(ApplicationState.Stopped); @@ -481,7 +481,7 @@ private async Task FailStartupCleanupAsync() await _serviceManager.StopAsync(CancellationToken.None).ConfigureAwait(false); } } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { LifecycleLogMessages.StartupFailureCleanupError(_logger, ex); } @@ -542,7 +542,7 @@ private void RaiseStateChanged(ApplicationState from, ApplicationState to) { StateChanged?.Invoke(this, new ApplicationStateChangedEventArgs(from, to)); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { LifecycleLogMessages.StateChangedHandlerFailed(_logger, ex, from, to); } diff --git a/src/VectorNNTPD.Common/Core/ApplicationServiceManager.cs b/src/VectorNNTPD.Common/Core/ApplicationServiceManager.cs index 756702b8..ea537058 100644 --- a/src/VectorNNTPD.Common/Core/ApplicationServiceManager.cs +++ b/src/VectorNNTPD.Common/Core/ApplicationServiceManager.cs @@ -143,7 +143,7 @@ internal async Task StartAsync(CancellationToken cancellationToken) await RollbackStartedAsync(CancellationToken.None).ConfigureAwait(false); throw; } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ServiceManagerLogMessages.ServiceStartupFailed( _logger, @@ -353,7 +353,7 @@ internal async Task StopAsync(CancellationToken cancellationToken) _started.Remove(service); } } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ServiceManagerLogMessages.ServiceShutdownFailed( _logger, @@ -440,7 +440,7 @@ private async Task RollbackStartedAsync(CancellationToken cancellationToken) await service.StopAsync(timeoutCts.Token).ConfigureAwait(false); ServiceManagerLogMessages.ServiceRolledBack(_logger, service.Name); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ServiceManagerLogMessages.ServiceRollbackFailed(_logger, ex, service.Name); } @@ -594,7 +594,7 @@ private async Task StopExecutionMonitoringAsync() { // Expected. } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ServiceManagerLogMessages.ExecutionMonitorExceptionDuringShutdown(_logger, ex); } diff --git a/src/VectorNNTPD.Common/Dns/ZoneApexNameserverDiscovery.cs b/src/VectorNNTPD.Common/Dns/ZoneApexNameserverDiscovery.cs index d7ba1262..cf7f3e9e 100644 --- a/src/VectorNNTPD.Common/Dns/ZoneApexNameserverDiscovery.cs +++ b/src/VectorNNTPD.Common/Dns/ZoneApexNameserverDiscovery.cs @@ -2,6 +2,7 @@ using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Dns { @@ -163,7 +164,7 @@ private static IPAddress[] ResolveRecursiveResolvers() return [.. servers]; } } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { s_recursiveResolverDiscoveryException = ex; } @@ -359,7 +360,7 @@ private static async Task> ResolveHostAddressesAsync( { throw; } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (logger is not null && logger.IsEnabled(LogLevel.Debug)) { diff --git a/src/VectorNNTPD.Common/Logging/PeriodicFileFlushSink.cs b/src/VectorNNTPD.Common/Logging/PeriodicFileFlushSink.cs index bcc1be9a..0823d088 100644 --- a/src/VectorNNTPD.Common/Logging/PeriodicFileFlushSink.cs +++ b/src/VectorNNTPD.Common/Logging/PeriodicFileFlushSink.cs @@ -2,6 +2,7 @@ using Serilog.Debugging; using Serilog.Events; using Serilog.Sinks.File; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Logging { @@ -99,7 +100,7 @@ public void Dispose() FlushRequired(); } // codeql[cs/catch-of-all-exceptions] A flush, dispose, or diagnostic failure must not escape this sink or skip the remaining cleanup. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ReportDiagnostic("Periodic file flush failed during disposal.", ex); } @@ -110,7 +111,7 @@ public void Dispose() (_sink as IDisposable)?.Dispose(); } // codeql[cs/catch-of-all-exceptions] A flush, dispose, or diagnostic failure must not escape this sink or skip the remaining cleanup. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ReportDiagnostic("Periodic file sink disposal failed.", ex); } @@ -120,7 +121,7 @@ public void Dispose() _timer.Dispose(); } // codeql[cs/catch-of-all-exceptions] A flush, dispose, or diagnostic failure must not escape this sink or skip the remaining cleanup. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ReportDiagnostic("Periodic file flush timer disposal failed.", ex); } @@ -150,7 +151,7 @@ private void OnTick(object? state) } } // codeql[cs/catch-of-all-exceptions] A flush, dispose, or diagnostic failure must not escape this sink or skip the remaining cleanup. - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { ReportDiagnostic("Periodic file flush timer callback failed.", ex); } @@ -167,7 +168,7 @@ private static void ReportDiagnostic(string message, Exception exception) SelfLog.WriteLine("{0} {1}", message, exception); } // codeql[cs/catch-of-all-exceptions] A flush, dispose, or diagnostic failure must not escape this sink or skip the remaining cleanup. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // The diagnostic channel is best-effort. It must not recurse into this sink or fault the timer thread. } @@ -191,7 +192,7 @@ private void FlushRequired() { _flushable.FlushToDisk(); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // A failed checkpoint must stay pending for the next tick and for disposal. Interlocked.Exchange(ref _flushRequired, 1); diff --git a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientAsyncConfirmPublishChannel.cs b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientAsyncConfirmPublishChannel.cs index 2b803db9..de0127cc 100644 --- a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientAsyncConfirmPublishChannel.cs +++ b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientAsyncConfirmPublishChannel.cs @@ -1,6 +1,7 @@ using System.Globalization; using RabbitMQ.Client; using RabbitMQ.Client.Events; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Messaging.RabbitMq { @@ -110,7 +111,7 @@ public async ValueTask DisposeAsync() await _channel.CloseAsync().ConfigureAwait(false); } } - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { } diff --git a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnection.cs b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnection.cs index 52ee40a1..ca464639 100644 --- a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnection.cs +++ b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnection.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Messaging.RabbitMq { @@ -193,7 +194,7 @@ public async ValueTask DisposeAsync() { await _connection.CloseAsync().ConfigureAwait(false); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { RabbitMqLogMessages.ConnectionCloseFailed(_logger, ex); } diff --git a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnectionFactory.cs b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnectionFactory.cs index ebe29705..a026cd21 100644 --- a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnectionFactory.cs +++ b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnectionFactory.cs @@ -50,14 +50,19 @@ public async Task ConnectAsync( // across endpoints, so failover would reuse Hosts[0] as SNI for every dial. var endpoints = CreateAmqpTcpEndpoints(runtime); var connection = await factory.CreateConnectionAsync(endpoints, cancellationToken).ConfigureAwait(false); + IAsyncDisposable? pendingDispose = connection; try { - return new RabbitMqClientConnection(connection, runtime.VirtualHost, _logger); + var wrapped = new RabbitMqClientConnection(connection, runtime.VirtualHost, _logger); + pendingDispose = null; + return wrapped; } - catch + finally { - await connection.DisposeAsync().ConfigureAwait(false); - throw; + if (pendingDispose is not null) + { + await pendingDispose.DisposeAsync().ConfigureAwait(false); + } } } diff --git a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientManualAckChannel.cs b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientManualAckChannel.cs index e692a048..3d4e96db 100644 --- a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientManualAckChannel.cs +++ b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientManualAckChannel.cs @@ -4,6 +4,7 @@ using RabbitMQ.Client.Events; using RabbitMQ.Client.Exceptions; using Serilog.Debugging; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Messaging.RabbitMq { @@ -186,7 +187,7 @@ public async Task BasicConsumeAsync( _consumer = consumer; return consumerTag; } - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { _onDelivery = null; DetachConsumerHandlers(consumer); @@ -262,7 +263,7 @@ async Task MarkDisposedAsync() await exclusiveDispose(MarkDisposedAsync).ConfigureAwait(false); } } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { // The hook runs the mark inside the caller's gate. A throw after that mark used to // skip the client close, and a later dispose saw the channel as already marked and diff --git a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientPublishChannel.cs b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientPublishChannel.cs index 62a2996f..ef4cb831 100644 --- a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientPublishChannel.cs +++ b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientPublishChannel.cs @@ -1,6 +1,7 @@ using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Client.Exceptions; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Messaging.RabbitMq { @@ -136,7 +137,7 @@ public async ValueTask DisposeAsync() await _channel.CloseAsync().ConfigureAwait(false); } } - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { } diff --git a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqService.cs b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqService.cs index 941138d5..2af4aa6a 100644 --- a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqService.cs +++ b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqService.cs @@ -348,7 +348,7 @@ private async Task RecoverAsync(CancellationToken cancellationToken) { throw; } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (attempt == 1) { @@ -447,7 +447,7 @@ private async Task ConnectAndInstallAsync( return live.Current.Generation; } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (!installed && connection is not null) { @@ -880,7 +880,7 @@ private async Task DisposeConnectionQuietlyAsync(IRabbitMqConnection connection) { await connection.DisposeAsync().ConfigureAwait(false); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { RabbitMqLogMessages.ConnectionDisposeFailed(_logger, ex); } diff --git a/src/VectorNNTPD.Common/Networking/Certificates/TlsCertificateContextProvider.cs b/src/VectorNNTPD.Common/Networking/Certificates/TlsCertificateContextProvider.cs index c5c2ab8c..d240c455 100644 --- a/src/VectorNNTPD.Common/Networking/Certificates/TlsCertificateContextProvider.cs +++ b/src/VectorNNTPD.Common/Networking/Certificates/TlsCertificateContextProvider.cs @@ -2,6 +2,7 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using VectorNNTPD.Common.Acme; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Networking.Certificates { @@ -339,7 +340,7 @@ internal static TlsCertificateHolder CreateFromPfx(ReadOnlySpan pfxBytes, var generation = Interlocked.Increment(ref s_generation); return new TlsCertificateHolder(context, leaf, collection, generation); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { foreach (var cert in collection) { diff --git a/src/VectorNNTPD.Common/NntpDb/MySqlNntpDbConnectionFactory.cs b/src/VectorNNTPD.Common/NntpDb/MySqlNntpDbConnectionFactory.cs index 2adf96a5..e4aa60ca 100644 --- a/src/VectorNNTPD.Common/NntpDb/MySqlNntpDbConnectionFactory.cs +++ b/src/VectorNNTPD.Common/NntpDb/MySqlNntpDbConnectionFactory.cs @@ -15,32 +15,33 @@ public sealed class MySqlNntpDbConnectionFactory : INntpDbConnectionFactory public async Task OpenAsync(string connectionString, CancellationToken cancellationToken) { var connection = CreateConnection(connectionString); + MySqlConnection? pendingDispose = connection; try { await connection.OpenAsync(cancellationToken).ConfigureAwait(false); + pendingDispose = null; return new MySqlNntpDbSession(connection); } catch (MySqlException ex) when (IsAuthenticationFailure(ex)) { - await connection.DisposeAsync().ConfigureAwait(false); throw new NntpDbAuthenticationException("MySQL authentication failed.", ex); } catch (ArgumentException ex) { - await connection.DisposeAsync().ConfigureAwait(false); throw new NntpDbConfigurationException(ex.Message, ex); } catch (Exception ex) when (ex is not OperationCanceledException and not NntpDbAuthenticationException and not NntpDbConfigurationException) { - await connection.DisposeAsync().ConfigureAwait(false); throw new NntpDbUnavailableException("MySQL connection failed.", ex); } - catch + finally { - await connection.DisposeAsync().ConfigureAwait(false); - throw; + if (pendingDispose is not null) + { + await pendingDispose.DisposeAsync().ConfigureAwait(false); + } } } diff --git a/src/VectorNNTPD.Common/NntpDb/NntpDbService.cs b/src/VectorNNTPD.Common/NntpDb/NntpDbService.cs index 4f275759..5d02573e 100644 --- a/src/VectorNNTPD.Common/NntpDb/NntpDbService.cs +++ b/src/VectorNNTPD.Common/NntpDb/NntpDbService.cs @@ -112,7 +112,7 @@ public async Task StartAsync(CancellationToken cancellationToken) await ConnectWithStartupBudgetAsync(_options.Value, cancellationToken).ConfigureAwait(false); Volatile.Write(ref _accepting, 1); } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (ex is NntpDbConfigurationException configuration) { @@ -216,7 +216,7 @@ private async Task ConnectWithStartupBudgetAsync(NntpDbOptions options, Cancella { throw; } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { if (_timeProvider.GetUtcNow() >= deadline) { diff --git a/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpShutdownDeadlineTests.cs b/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpShutdownDeadlineTests.cs index e590d639..5e323934 100644 --- a/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpShutdownDeadlineTests.cs +++ b/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpShutdownDeadlineTests.cs @@ -4,6 +4,7 @@ using VectorNNTPD.BackFillerService.Accounts; using VectorNNTPD.BackFillerService.Nntp; using VectorNNTPD.BackFillerService.Tests.TestDoubles; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Tests.Nntp { @@ -665,7 +666,7 @@ await registry.ApplySnapshotAsync( await dispose.WaitAsync(TimeSpan.FromSeconds(2)); elapsed = Stopwatch.GetElapsedTime(started); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { Release(poolServers); await dispose.WaitAsync(TimeSpan.FromSeconds(5)); @@ -934,7 +935,7 @@ private static async Task MeasureAsync(Func shutdown, IReadOnlyL await dispose.WaitAsync(MeasureHangTimeout); return Stopwatch.GetElapsedTime(started); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { Release(servers); await dispose.WaitAsync(TimeSpan.FromSeconds(5)); diff --git a/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpStartTlsTests.cs b/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpStartTlsTests.cs index 06f1fb64..787f96e2 100644 --- a/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpStartTlsTests.cs +++ b/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpStartTlsTests.cs @@ -9,6 +9,7 @@ using VectorNNTPD.BackFillerService.Tests.TestDoubles; using System.Net; using System.Text; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Tests.Nntp { @@ -489,7 +490,7 @@ public async Task ConnectAsync( await client.ConnectAsync(provider.Host, provider.Port, connectCts.Token).ConfigureAwait(false); return new DisposeCountingStream(client, () => Interlocked.Increment(ref _disposeCalls)); } - catch + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { client.Dispose(); throw; @@ -696,7 +697,7 @@ public async ValueTask DisposeAsync() await _accept.WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } // codeql[cs/catch-of-all-exceptions] Stopping the listener can fault the accept task with any transport exception. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { /* Disposal still releases the listener and the cancellation source. */ } diff --git a/tests/VectorNNTPD.BackFillerService.Tests/TestDoubles/ScriptedNntpTransport.cs b/tests/VectorNNTPD.BackFillerService.Tests/TestDoubles/ScriptedNntpTransport.cs index 60d9cb90..6822bf03 100644 --- a/tests/VectorNNTPD.BackFillerService.Tests/TestDoubles/ScriptedNntpTransport.cs +++ b/tests/VectorNNTPD.BackFillerService.Tests/TestDoubles/ScriptedNntpTransport.cs @@ -4,6 +4,7 @@ using VectorNNTPD.BackFillerService.Nntp; using System.Net.Sockets; using System.Text; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Tests.TestDoubles { @@ -579,7 +580,7 @@ private async Task RunServerAsync() } } // codeql[cs/catch-of-all-exceptions] The scripted peer must finish the pipe after any read or command failure. - catch (Exception) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { /* The caller observes the closed pipe rather than this task. */ } diff --git a/tests/VectorNNTPD.Common.Tests/Acme/AcmeExclusiveFileLockTests.cs b/tests/VectorNNTPD.Common.Tests/Acme/AcmeExclusiveFileLockTests.cs index 9eebe03a..7571f8a4 100644 --- a/tests/VectorNNTPD.Common.Tests/Acme/AcmeExclusiveFileLockTests.cs +++ b/tests/VectorNNTPD.Common.Tests/Acme/AcmeExclusiveFileLockTests.cs @@ -86,8 +86,10 @@ public void Unrelated_io_failures_are_not_lock_contention() /// An initialization failure after a successful open propagates immediately, does not enter the /// contention retry loop, and disposes the opened stream. /// - [Fact] - public void Initialization_failure_propagates_and_disposes_stream() + /// Operational or programming failure thrown during lock-file initialization. + [Theory] + [MemberData(nameof(InitializationFailures))] + public void Initialization_failure_propagates_and_disposes_stream(Exception failure) { using var dir = new TempStateDir(); var path = Path.Join(dir.Path, "init-fail.lock"); @@ -99,13 +101,12 @@ public void Initialization_failure_propagates_and_disposes_stream() Interlocked.Increment(ref openCount); return new TrackingFileStream(p, () => Interlocked.Increment(ref disposed)); }; - AcmeExclusiveFileLock.InitializeLockFileForTests = _ => - throw new IOException("simulated metadata write failure", unchecked((int)0x80070070)); + AcmeExclusiveFileLock.InitializeLockFileForTests = _ => throw failure; try { - var ex = Assert.Throws(() => AcmeExclusiveFileLock.Acquire(path, CancellationToken.None)); - Assert.Equal("simulated metadata write failure", ex.Message); + var ex = Assert.Throws(failure.GetType(), () => AcmeExclusiveFileLock.Acquire(path, CancellationToken.None)); + Assert.Same(failure, ex); Assert.Equal(1, Volatile.Read(ref openCount)); Assert.Equal(1, Volatile.Read(ref disposed)); } @@ -116,6 +117,17 @@ public void Initialization_failure_propagates_and_disposes_stream() } } + /// + /// Representative initialization failures that must dispose the open stream and must not become + /// contention retries (ownership-transfer finally, not a filtered catch-all). + /// + public static TheoryData InitializationFailures() => + [ + new IOException("simulated metadata write failure", unchecked((int)0x80070070)), + new InvalidOperationException("simulated programming failure during lock init"), + new UnauthorizedAccessException("simulated access denied during lock init"), + ]; + /// /// Synchronous and asynchronous issuance-lock acquisition classify a directory path the same way. /// diff --git a/tests/VectorNNTPD.Common.Tests/Articles/Validation/NntpMessageIdValidationTests.cs b/tests/VectorNNTPD.Common.Tests/Articles/Validation/NntpMessageIdValidationTests.cs index ee6a5e43..5bddabdc 100644 --- a/tests/VectorNNTPD.Common.Tests/Articles/Validation/NntpMessageIdValidationTests.cs +++ b/tests/VectorNNTPD.Common.Tests/Articles/Validation/NntpMessageIdValidationTests.cs @@ -1,6 +1,7 @@ using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using VectorNNTPD.Common.Articles.Validation; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Tests.Articles.Validation { @@ -149,7 +150,7 @@ public void Vector_scan_terminates_when_the_first_lane_does_not_match() Assert.Equal(expected[i], NntpMessageIdValidation.IsValidMessageId(tokens[i])); } } - catch (Exception ex) + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) { error = ex; } diff --git a/tests/VectorNNTPD.Common.Tests/Core/ExceptionHelpersTests.cs b/tests/VectorNNTPD.Common.Tests/Core/ExceptionHelpersTests.cs new file mode 100644 index 00000000..5e4b40f7 --- /dev/null +++ b/tests/VectorNNTPD.Common.Tests/Core/ExceptionHelpersTests.cs @@ -0,0 +1,71 @@ +using VectorNNTPD.Common.Core; + +namespace VectorNNTPD.Common.Tests.Core +{ + /// Regresses process-integrity classification used by intentional catch filters. + public sealed class ExceptionHelpersTests + { + /// Operational failures are not treated as process-integrity failures. + /// Representative non-fatal exception. + [Theory] + [MemberData(nameof(NonFatalExceptions))] + public void IsFatal_returns_false_for_operational_failures(Exception exception) + { + Assert.False(ExceptionHelpers.IsFatal(exception)); + } + + /// Process-integrity failures must propagate past best-effort containment. + /// Representative fatal exception. + [Theory] + [MemberData(nameof(FatalExceptions))] + public void IsFatal_returns_true_for_process_integrity_failures(Exception exception) + { + Assert.True(ExceptionHelpers.IsFatal(exception)); + } + + /// + /// A containment boundary that filters with absorbs operational + /// failures and rethrows process-integrity failures. + /// + [Fact] + public void Containment_filter_absorbs_operational_failures_and_rethrows_fatal_ones() + { + Assert.Equal("contained", Contain(new IOException("disk full"))); + Assert.Throws(() => Contain(new OutOfMemoryException())); + } + + /// Non-fatal samples for classification. + public static TheoryData NonFatalExceptions() => + [ + new IOException("io"), + new InvalidOperationException("invalid"), + new TimeoutException("timeout"), + new OperationCanceledException(), + new ArgumentException("arg"), + new Exception("base"), + ]; + + /// Fatal samples for classification. + public static TheoryData FatalExceptions() => + [ + new OutOfMemoryException(), + new StackOverflowException(), + new AccessViolationException(), + new AppDomainUnloadedException(), + new BadImageFormatException(), + new CannotUnloadAppDomainException(), + ]; + + private static string Contain(Exception failure) + { + try + { + throw failure; + } + catch (Exception ex) when (!ExceptionHelpers.IsFatal(ex)) + { + return "contained"; + } + } + } +} From f815710a882651e6810a765be93f94ec895ec6d0 Mon Sep 17 00:00:00 2001 From: "savage@savage.za.org" Date: Thu, 22 Oct 2026 08:38:44 +0200 Subject: [PATCH 2/4] Fix disposable ownership transfer and cleanup --- .../ArticleWorkResponsePublisher.cs | 24 +-- .../Listener/CacheListenerEndpoints.cs | 20 +-- .../Nntp/NntpTlsClient.cs | 12 +- .../Nntp/TcpNntpTransportFactory.cs | 71 ++++----- .../Acme/AcmeExclusiveFileLock.cs | 45 ++++-- .../Acme/Protocol/AcmeAccountKey.cs | 13 +- .../Core/DisposableOwnership.cs | 107 +++++++++++++ .../RabbitMqClientConnectionFactory.cs | 19 +-- .../NntpDb/MySqlNntpDbConnectionFactory.cs | 16 +- .../Acme/OwnedAcmeProtocolTests.cs | 28 ++++ .../Core/DisposableOwnershipTests.cs | 140 ++++++++++++++++++ 11 files changed, 373 insertions(+), 122 deletions(-) create mode 100644 src/VectorNNTPD.Common/Core/DisposableOwnership.cs create mode 100644 tests/VectorNNTPD.Common.Tests/Core/DisposableOwnershipTests.cs diff --git a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkResponsePublisher.cs b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkResponsePublisher.cs index 91201e7b..43511665 100644 --- a/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkResponsePublisher.cs +++ b/src/VectorNNTPD.BackFillerService/ArticleWork/ArticleWorkResponsePublisher.cs @@ -615,24 +615,16 @@ private async Task ReplaceChannelAsync(bool startup, CancellationToken cancellat var channel = await handle.Connection .CreatePublishChannelAsync(handle.Generation, cancellationToken) .ConfigureAwait(false); - IAsyncDisposable? pendingDispose = channel; - try - { - if (!handle.IsCurrent || channel.Generation != handle.Generation) - { - throw new InvalidOperationException("RabbitMQ publish channel generation is no longer current."); - } - - await InstallPublishChannelAsync(channel).ConfigureAwait(false); - pendingDispose = null; - } - finally + await using var ownership = new AsyncDisposableOwnership(channel); + if (!handle.IsCurrent || ownership.Resource.Generation != handle.Generation) { - if (pendingDispose is not null) - { - await pendingDispose.DisposeAsync().ConfigureAwait(false); - } + throw new InvalidOperationException("RabbitMQ publish channel generation is no longer current."); } + + // Install either stores the channel or disposes it as stale; Transfer after success + // so this ownership does not dispose again. + await InstallPublishChannelAsync(ownership.Resource).ConfigureAwait(false); + ownership.Transfer(); } /// Clears and disposes the installed publication channel. diff --git a/src/VectorNNTPD.BackFillerService/Listener/CacheListenerEndpoints.cs b/src/VectorNNTPD.BackFillerService/Listener/CacheListenerEndpoints.cs index e3a3239c..09867bde 100644 --- a/src/VectorNNTPD.BackFillerService/Listener/CacheListenerEndpoints.cs +++ b/src/VectorNNTPD.BackFillerService/Listener/CacheListenerEndpoints.cs @@ -1,5 +1,6 @@ using System.Net; using System.Net.Sockets; +using VectorNNTPD.Common.Core; using VectorNNTPD.Common.Networking.Listeners; namespace VectorNNTPD.BackFillerService.Listener @@ -35,25 +36,18 @@ internal static Socket CreateBoundListenSocket(ListenBinding binding) private static Socket CreateBoundListenSocket(IPEndPoint endpoint, bool dualMode = false) { ArgumentNullException.ThrowIfNull(endpoint); - var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + using var ownership = new DisposableOwnership( + new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)); + var socket = ownership.Resource; if (endpoint.AddressFamily == AddressFamily.InterNetworkV6) { socket.DualMode = dualMode; } - Socket? pendingDispose = socket; - try - { - socket.Bind(endpoint); - socket.Listen(512); - pendingDispose = null; - return socket; - } - finally - { - pendingDispose?.Dispose(); - } + socket.Bind(endpoint); + socket.Listen(512); + return ownership.Transfer(); } } } diff --git a/src/VectorNNTPD.BackFillerService/Nntp/NntpTlsClient.cs b/src/VectorNNTPD.BackFillerService/Nntp/NntpTlsClient.cs index 9e35b72f..c957c05e 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/NntpTlsClient.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/NntpTlsClient.cs @@ -75,18 +75,22 @@ internal static async Task AuthenticateAsClientAsync( Func? streamFactory = null) { ArgumentNullException.ThrowIfNull(inner); - var ssl = streamFactory?.Invoke(inner) ?? new SslStream(inner, leaveInnerStreamOpen: false); - SslStream? pendingDispose = ssl; + // Ownership transfer uses DisposeAsync (not sync Dispose) so STARTTLS teardown matches + // SslStream's async dispose path. cs/missed-using-statement targets IDisposable.Dispose + // in finally; DisposeAsync here is intentional and preserves handshake-cancel cleanup. + SslStream? pendingDispose = + streamFactory?.Invoke(inner) ?? new SslStream(inner, leaveInnerStreamOpen: false); try { using var tlsCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); tlsCts.CancelAfter(timeout); - await ssl.AuthenticateAsClientAsync( + await pendingDispose.AuthenticateAsClientAsync( CreateClientOptions(host, serverCertificateValidationCallback), tlsCts.Token) .ConfigureAwait(false); + var authenticated = pendingDispose; pendingDispose = null; - return ssl; + return authenticated; } finally { diff --git a/src/VectorNNTPD.BackFillerService/Nntp/TcpNntpTransportFactory.cs b/src/VectorNNTPD.BackFillerService/Nntp/TcpNntpTransportFactory.cs index 84c28d2d..61bd801d 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/TcpNntpTransportFactory.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/TcpNntpTransportFactory.cs @@ -1,5 +1,6 @@ using System.Net.Sockets; using VectorNNTPD.BackFillerService.Networking; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.BackFillerService.Nntp { @@ -43,48 +44,38 @@ public async Task ConnectAsync( ArgumentNullException.ThrowIfNull(provider); ArgumentNullException.ThrowIfNull(options); - var client = new TcpClient(); - TcpClient? pendingClient = client; - - try + using var ownership = new DisposableOwnership(new TcpClient()); + var client = ownership.Resource; + var keepAlive = options.EffectiveTcpKeepAlive; + TcpSocketOptions.Apply( + client.Client, + options.TcpSendBufferBytes, + options.TcpReceiveBufferBytes, + keepAlive); + using var connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + connectCts.CancelAfter(options.ConnectTimeout); + await client.ConnectAsync(provider.Host, provider.Port, connectCts.Token).ConfigureAwait(false); + // ConnectAsync(string) can replace the socket when the resolved address family differs. + // Re-apply on the connected socket before the first TLS or NNTP byte. + TcpSocketOptions.Apply( + client.Client, + options.TcpSendBufferBytes, + options.TcpReceiveBufferBytes, + keepAlive); + Stream stream = client.GetStream(); + if (!provider.UseTls) { - var keepAlive = options.EffectiveTcpKeepAlive; - TcpSocketOptions.Apply( - client.Client, - options.TcpSendBufferBytes, - options.TcpReceiveBufferBytes, - keepAlive); - using var connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - connectCts.CancelAfter(options.ConnectTimeout); - await client.ConnectAsync(provider.Host, provider.Port, connectCts.Token).ConfigureAwait(false); - // ConnectAsync(string) can replace the socket when the resolved address family differs. - // Re-apply on the connected socket before the first TLS or NNTP byte. - TcpSocketOptions.Apply( - client.Client, - options.TcpSendBufferBytes, - options.TcpReceiveBufferBytes, - keepAlive); - Stream stream = client.GetStream(); - if (!provider.UseTls) - { - pendingClient = null; - return new TcpOwnedStream(client, stream); - } - - var ssl = await NntpTlsClient.AuthenticateAsClientAsync( - stream, - provider.Host, - options.ConnectTimeout, - options.ServerCertificateValidationCallback, - cancellationToken) - .ConfigureAwait(false); - pendingClient = null; - return new TcpOwnedStream(client, ssl); - } - finally - { - pendingClient?.Dispose(); + return new TcpOwnedStream(ownership.Transfer(), stream); } + + var ssl = await NntpTlsClient.AuthenticateAsClientAsync( + stream, + provider.Host, + options.ConnectTimeout, + options.ServerCertificateValidationCallback, + cancellationToken) + .ConfigureAwait(false); + return new TcpOwnedStream(ownership.Transfer(), ssl); } /// diff --git a/src/VectorNNTPD.Common/Acme/AcmeExclusiveFileLock.cs b/src/VectorNNTPD.Common/Acme/AcmeExclusiveFileLock.cs index 3f7c1db3..fd3c75ad 100644 --- a/src/VectorNNTPD.Common/Acme/AcmeExclusiveFileLock.cs +++ b/src/VectorNNTPD.Common/Acme/AcmeExclusiveFileLock.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Acme { @@ -35,17 +36,39 @@ internal sealed class AcmeExclusiveFileLock : IDisposable /// Non-zero after has run. private int _disposed; + /// + /// Async-local test seam that replaces construction. + /// Scoped per async flow so parallel tests cannot observe another test's hook. + /// Production code leaves this . + /// + private static readonly AsyncLocal?> CreateStreamForTestsLocal = new(); + + /// + /// Async-local test seam that replaces lock-file metadata initialization after open. + /// Scoped per async flow so parallel tests cannot observe another test's hook. + /// Production code leaves this . + /// + private static readonly AsyncLocal?> InitializeLockFileForTestsLocal = new(); + /// /// Optional test seam that replaces construction. /// Production code leaves this . /// - internal static Func? CreateStreamForTests { get; set; } + internal static Func? CreateStreamForTests + { + get => CreateStreamForTestsLocal.Value; + set => CreateStreamForTestsLocal.Value = value; + } /// /// Optional test seam that replaces lock-file metadata initialization after open. /// Production code leaves this . /// - internal static Action? InitializeLockFileForTests { get; set; } + internal static Action? InitializeLockFileForTests + { + get => InitializeLockFileForTestsLocal.Value; + set => InitializeLockFileForTestsLocal.Value = value; + } /// Takes ownership of an already exclusive . /// Lock stream. Disposed by . @@ -128,21 +151,15 @@ internal static bool TryAcquireOnce( } // Open succeeded: dispose on any initialization failure, otherwise transfer ownership - // to the returned lock. Ownership-transfer finally keeps cleanup on every failure path - // (including process-integrity failures) without a catch-all, and never returns false - // here — so init errors cannot be mistaken for open-time contention retries. - FileStream? pendingDispose = stream; - try + // to the returned lock. using + Transfer keeps cleanup on every failure path without a + // catch-all or dispose-in-finally, and never returns false here — so init errors cannot + // be mistaken for open-time contention retries. + using (var ownership = new DisposableOwnership(stream)) { - InitializeLockFile(stream); - acquired = new AcmeExclusiveFileLock(stream); - pendingDispose = null; + InitializeLockFile(ownership.Resource); + acquired = new AcmeExclusiveFileLock(ownership.Transfer()); return true; } - finally - { - pendingDispose?.Dispose(); - } } /// diff --git a/src/VectorNNTPD.Common/Acme/Protocol/AcmeAccountKey.cs b/src/VectorNNTPD.Common/Acme/Protocol/AcmeAccountKey.cs index 1ed1ec45..4c81fb59 100644 --- a/src/VectorNNTPD.Common/Acme/Protocol/AcmeAccountKey.cs +++ b/src/VectorNNTPD.Common/Acme/Protocol/AcmeAccountKey.cs @@ -1,5 +1,6 @@ using System.Security.Cryptography; using System.Text; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Acme.Protocol { @@ -65,10 +66,9 @@ internal static AcmeAccountKey ImportPkcs8Der(ReadOnlySpan pkcs8Der) throw new CryptographicException("PKCS#8 DER account key is empty."); } - RSA rsa = RSA.Create(); - RSA? pendingDispose = rsa; - try + using (var ownership = new DisposableOwnership(RSA.Create())) { + var rsa = ownership.Resource; rsa.ImportPkcs8PrivateKey(pkcs8Der, out int bytesRead); if (bytesRead != pkcs8Der.Length) { @@ -76,12 +76,7 @@ internal static AcmeAccountKey ImportPkcs8Der(ReadOnlySpan pkcs8Der) $"PKCS#8 import consumed {bytesRead} of {pkcs8Der.Length} bytes."); } - pendingDispose = null; - return new AcmeAccountKey(rsa); - } - finally - { - pendingDispose?.Dispose(); + return new AcmeAccountKey(ownership.Transfer()); } } diff --git a/src/VectorNNTPD.Common/Core/DisposableOwnership.cs b/src/VectorNNTPD.Common/Core/DisposableOwnership.cs new file mode 100644 index 00000000..d1a19d34 --- /dev/null +++ b/src/VectorNNTPD.Common/Core/DisposableOwnership.cs @@ -0,0 +1,107 @@ +namespace VectorNNTPD.Common.Core +{ + /// + /// Holds an until moves ownership, or cleans it up. + /// + /// Resource type. + /// + /// + /// Use with a using statement: on success call before the using ends; + /// on failure the using disposes the resource. Avoids manual dispose-in-finally while keeping + /// explicit ownership transfer. + /// + /// + /// Intended for single-threaded ownership within one method. and + /// use atomic exchange so a concurrent dispose cannot dispose a resource that was already transferred, and + /// a second transfer fails. Concurrent access with transfer/dispose is not supported. + /// A throw from the resource's propagates; when that happens inside a + /// using that is already unwinding for another exception, the runtime may replace the primary exception + /// (standard using behaviour). + /// + /// + public sealed class DisposableOwnership : IDisposable + where T : class, IDisposable + { + private T? _resource; + + /// Takes ownership of until transfer or dispose. + /// Resource to hold. Must not be null. + public DisposableOwnership(T resource) + { + ArgumentNullException.ThrowIfNull(resource); + _resource = resource; + } + + /// Gets the held resource before transfer. + /// The resource was already transferred or disposed. + public T Resource => + _resource ?? throw new ObjectDisposedException(nameof(DisposableOwnership)); + + /// + /// Releases ownership to the caller without disposing. Subsequent is a no-op. + /// + /// The held resource. + /// The resource was already transferred or disposed. + public T Transfer() + { + var resource = Interlocked.Exchange(ref _resource, null); + return resource ?? throw new ObjectDisposedException(nameof(DisposableOwnership)); + } + + /// + public void Dispose() + { + var resource = Interlocked.Exchange(ref _resource, null); + resource?.Dispose(); + } + } + + /// + /// Holds an until moves ownership, or + /// cleans it up. + /// + /// Resource type. + /// + /// Same single-owner contract as . awaits + /// the resource dispose and is not fire-and-forget. + /// + public sealed class AsyncDisposableOwnership : IAsyncDisposable + where T : class, IAsyncDisposable + { + private T? _resource; + + /// Takes ownership of until transfer or dispose. + /// Resource to hold. Must not be null. + public AsyncDisposableOwnership(T resource) + { + ArgumentNullException.ThrowIfNull(resource); + _resource = resource; + } + + /// Gets the held resource before transfer. + /// The resource was already transferred or disposed. + public T Resource => + _resource ?? throw new ObjectDisposedException(nameof(AsyncDisposableOwnership)); + + /// + /// Releases ownership to the caller without disposing. Subsequent is a no-op. + /// + /// The held resource. + /// The resource was already transferred or disposed. + public T Transfer() + { + var resource = Interlocked.Exchange(ref _resource, null); + return resource ?? throw new ObjectDisposedException(nameof(AsyncDisposableOwnership)); + } + + /// + public async ValueTask DisposeAsync() + { + var resource = Interlocked.Exchange(ref _resource, null); + if (resource is not null) + { + await resource.DisposeAsync().ConfigureAwait(false); + } + } + } +} diff --git a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnectionFactory.cs b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnectionFactory.cs index a026cd21..9ee462af 100644 --- a/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnectionFactory.cs +++ b/src/VectorNNTPD.Common/Messaging/RabbitMq/RabbitMqClientConnectionFactory.cs @@ -4,6 +4,7 @@ using System.Security.Authentication; using RabbitMQ.Client; using VectorNNTPD.Common.Configuration; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.Messaging.RabbitMq { @@ -50,20 +51,10 @@ public async Task ConnectAsync( // across endpoints, so failover would reuse Hosts[0] as SNI for every dial. var endpoints = CreateAmqpTcpEndpoints(runtime); var connection = await factory.CreateConnectionAsync(endpoints, cancellationToken).ConfigureAwait(false); - IAsyncDisposable? pendingDispose = connection; - try - { - var wrapped = new RabbitMqClientConnection(connection, runtime.VirtualHost, _logger); - pendingDispose = null; - return wrapped; - } - finally - { - if (pendingDispose is not null) - { - await pendingDispose.DisposeAsync().ConfigureAwait(false); - } - } + await using var ownership = new AsyncDisposableOwnership(connection); + var wrapped = new RabbitMqClientConnection(ownership.Resource, runtime.VirtualHost, _logger); + ownership.Transfer(); + return wrapped; } /// diff --git a/src/VectorNNTPD.Common/NntpDb/MySqlNntpDbConnectionFactory.cs b/src/VectorNNTPD.Common/NntpDb/MySqlNntpDbConnectionFactory.cs index e4aa60ca..61660772 100644 --- a/src/VectorNNTPD.Common/NntpDb/MySqlNntpDbConnectionFactory.cs +++ b/src/VectorNNTPD.Common/NntpDb/MySqlNntpDbConnectionFactory.cs @@ -1,4 +1,5 @@ using MySqlConnector; +using VectorNNTPD.Common.Core; namespace VectorNNTPD.Common.NntpDb { @@ -14,13 +15,11 @@ public sealed class MySqlNntpDbConnectionFactory : INntpDbConnectionFactory /// public async Task OpenAsync(string connectionString, CancellationToken cancellationToken) { - var connection = CreateConnection(connectionString); - MySqlConnection? pendingDispose = connection; + await using var ownership = new AsyncDisposableOwnership(CreateConnection(connectionString)); try { - await connection.OpenAsync(cancellationToken).ConfigureAwait(false); - pendingDispose = null; - return new MySqlNntpDbSession(connection); + await ownership.Resource.OpenAsync(cancellationToken).ConfigureAwait(false); + return new MySqlNntpDbSession(ownership.Transfer()); } catch (MySqlException ex) when (IsAuthenticationFailure(ex)) { @@ -36,13 +35,6 @@ and not NntpDbAuthenticationException { throw new NntpDbUnavailableException("MySQL connection failed.", ex); } - finally - { - if (pendingDispose is not null) - { - await pendingDispose.DisposeAsync().ConfigureAwait(false); - } - } } /// diff --git a/tests/VectorNNTPD.Common.Tests/Acme/OwnedAcmeProtocolTests.cs b/tests/VectorNNTPD.Common.Tests/Acme/OwnedAcmeProtocolTests.cs index c5cc3de6..54436c92 100644 --- a/tests/VectorNNTPD.Common.Tests/Acme/OwnedAcmeProtocolTests.cs +++ b/tests/VectorNNTPD.Common.Tests/Acme/OwnedAcmeProtocolTests.cs @@ -28,6 +28,34 @@ public void AccountKey_DerImportExport_PreservesRsaMaterial() Assert.Contains("\"kty\":\"RSA\"", key.Jwk, StringComparison.Ordinal); } + /// Empty PKCS#8 input fails closed without returning a key. + [Fact] + public void AccountKey_EmptyDer_Throws() + { + Assert.Throws(() => AcmeAccountKey.ImportPkcs8Der(ReadOnlySpan.Empty)); + } + + /// Malformed PKCS#8 input fails closed without returning a key. + [Fact] + public void AccountKey_MalformedDer_Throws() + { + Assert.ThrowsAny(() => AcmeAccountKey.ImportPkcs8Der([0x30, 0x03, 0x01, 0x02, 0x03])); + } + + /// PKCS#8 that does not consume the full buffer fails closed. + [Fact] + public void AccountKey_TrailingBytes_Throws() + { + using var rsa = RSA.Create(2048); + byte[] der = rsa.ExportPkcs8PrivateKey(); + var withTrailer = new byte[der.Length + 1]; + der.CopyTo(withTrailer, 0); + withTrailer[^1] = 0x00; + + var ex = Assert.Throws(() => AcmeAccountKey.ImportPkcs8Der(withTrailer)); + Assert.Contains("consumed", ex.Message, StringComparison.OrdinalIgnoreCase); + } + /// /// is unpadded base64url, and /// is the token, a dot, and the key thumbprint. diff --git a/tests/VectorNNTPD.Common.Tests/Core/DisposableOwnershipTests.cs b/tests/VectorNNTPD.Common.Tests/Core/DisposableOwnershipTests.cs new file mode 100644 index 00000000..32f4708a --- /dev/null +++ b/tests/VectorNNTPD.Common.Tests/Core/DisposableOwnershipTests.cs @@ -0,0 +1,140 @@ +using VectorNNTPD.Common.Core; + +namespace VectorNNTPD.Common.Tests.Core +{ + /// Regresses ownership-transfer helpers used to avoid dispose-in-finally patterns. + public sealed class DisposableOwnershipTests + { + /// Transfer clears ownership so dispose does not dispose the resource. + [Fact] + public void Transfer_prevents_subsequent_dispose_from_disposing_the_resource() + { + var resource = new TrackingDisposable(); + TrackingDisposable transferred; + using (var ownership = new DisposableOwnership(resource)) + { + transferred = ownership.Transfer(); + } + + Assert.Same(resource, transferred); + Assert.Equal(0, resource.DisposeCount); + transferred.Dispose(); + Assert.Equal(1, resource.DisposeCount); + } + + /// Without transfer, using disposes the held resource. + [Fact] + public void Dispose_without_transfer_disposes_the_resource() + { + var resource = new TrackingDisposable(); + using (var ownership = new DisposableOwnership(resource)) + { + Assert.Same(resource, ownership.Resource); + } + + Assert.Equal(1, resource.DisposeCount); + } + + /// A second transfer after the first fails closed. + [Fact] + public void Second_transfer_throws_and_does_not_dispose() + { + var resource = new TrackingDisposable(); + using var ownership = new DisposableOwnership(resource); + Assert.Same(resource, ownership.Transfer()); + Assert.Throws(() => ownership.Transfer()); + Assert.Equal(0, resource.DisposeCount); + resource.Dispose(); + } + + /// Resource access after transfer fails closed. + [Fact] + public void Resource_after_transfer_throws() + { + var resource = new TrackingDisposable(); + using var ownership = new DisposableOwnership(resource); + _ = ownership.Transfer(); + Assert.Throws(() => _ = ownership.Resource); + resource.Dispose(); + } + + /// Repeated dispose is a no-op after the first release. + [Fact] + public void Repeated_dispose_is_safe() + { + var resource = new TrackingDisposable(); + var ownership = new DisposableOwnership(resource); + ownership.Dispose(); + ownership.Dispose(); + Assert.Equal(1, resource.DisposeCount); + } + + /// Null construction is rejected before any ownership is taken. + [Fact] + public void Null_resource_is_rejected() + { + Assert.Throws(() => new DisposableOwnership(null!)); + } + + /// Async transfer clears ownership so dispose does not dispose the resource. + /// A task that completes after async ownership is released. + [Fact] + public async Task Async_transfer_prevents_subsequent_dispose_from_disposing_the_resource() + { + var resource = new TrackingAsyncDisposable(); + TrackingAsyncDisposable transferred; + await using (var ownership = new AsyncDisposableOwnership(resource)) + { + transferred = ownership.Transfer(); + } + + Assert.Same(resource, transferred); + Assert.Equal(0, resource.DisposeCount); + await transferred.DisposeAsync(); + Assert.Equal(1, resource.DisposeCount); + } + + /// Async dispose without transfer awaits resource disposal once. + /// A task that completes after disposal. + [Fact] + public async Task Async_dispose_without_transfer_disposes_once() + { + var resource = new TrackingAsyncDisposable(); + var ownership = new AsyncDisposableOwnership(resource); + await ownership.DisposeAsync(); + await ownership.DisposeAsync(); + Assert.Equal(1, resource.DisposeCount); + } + + /// A second async transfer after the first fails closed. + /// A task that completes after the failed second transfer. + [Fact] + public async Task Async_second_transfer_throws() + { + var resource = new TrackingAsyncDisposable(); + await using var ownership = new AsyncDisposableOwnership(resource); + Assert.Same(resource, ownership.Transfer()); + Assert.Throws(() => ownership.Transfer()); + Assert.Equal(0, resource.DisposeCount); + await resource.DisposeAsync(); + } + + private sealed class TrackingDisposable : IDisposable + { + public int DisposeCount { get; private set; } + + public void Dispose() => DisposeCount++; + } + + private sealed class TrackingAsyncDisposable : IAsyncDisposable + { + public int DisposeCount { get; private set; } + + public ValueTask DisposeAsync() + { + DisposeCount++; + return ValueTask.CompletedTask; + } + } + } +} From b786b1c2204ae70a4c1bb1503717e34ede3c6f43 Mon Sep 17 00:00:00 2001 From: "savage@savage.za.org" Date: Thu, 22 Oct 2026 16:38:16 +0200 Subject: [PATCH 3/4] Harden readiness concurrency tests and disposal assertions --- .../Systemd/SystemdLifecycleNotifierTests.cs | 51 +++++++++--- .../Core/DisposableOwnershipTests.cs | 82 +++++++++++++------ 2 files changed, 97 insertions(+), 36 deletions(-) diff --git a/tests/VectorNNTPD.BackFillerService.Tests/Hosting/Systemd/SystemdLifecycleNotifierTests.cs b/tests/VectorNNTPD.BackFillerService.Tests/Hosting/Systemd/SystemdLifecycleNotifierTests.cs index 172c1bf4..42ca4777 100644 --- a/tests/VectorNNTPD.BackFillerService.Tests/Hosting/Systemd/SystemdLifecycleNotifierTests.cs +++ b/tests/VectorNNTPD.BackFillerService.Tests/Hosting/Systemd/SystemdLifecycleNotifierTests.cs @@ -247,12 +247,20 @@ public async Task Readiness_RepeatedHealthCallbacks_DoNotDuplicateReady() } /// Concurrent readiness triggers share the send gate and produce one successful READY. + /// + /// Workers are armed on dedicated threads and must reach the start gate before release so the + /// assertion does not race the thread pool under CI load (Linux suite flake: ReadyAttempted timeout). + /// After release, readiness is raced against Task.WhenAll(workers) so a worker fault before + /// NotifyReady surfaces immediately instead of waiting out the ReadyAttempted safety bound. + /// [Fact] public async Task Readiness_ConcurrentTriggers_DoNotDuplicateReady() { + const int workerCount = 8; var notify = new FakeSystemdNotifyBridge(); using var gate = new ManualResetEventSlim(false); using var start = new ManualResetEventSlim(false); + using var workersArmed = new CountdownEvent(workerCount); notify.BlockReadyUntil = gate; var lifetime = new TestHostApplicationLifetime(); var health = new BackFillerApplicationHealth(); @@ -266,23 +274,46 @@ public async Task Readiness_ConcurrentTriggers_DoNotDuplicateReady() lifetime.SignalStarted(); Assert.Equal(0, notify.ReadyCount); - workers = Enumerable.Range(0, 8) - .Select(_ => Task.Run(() => - { - start.Wait(); - health.MarkCertificateAvailable(); - })) + // LongRunning avoids thread-pool starvation while workers block on start/gate. + workers = Enumerable.Range(0, workerCount) + .Select(_ => Task.Factory.StartNew( + () => + { + workersArmed.Signal(); + start.Wait(); + health.MarkCertificateAvailable(); + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default)) .ToArray(); + if (!workersArmed.Wait(TimeSpan.FromSeconds(30))) + { + throw new TimeoutException("Concurrent readiness workers did not reach the start gate."); + } + start.Set(); - await notify.ReadyAttempted.Task.WaitAsync(TimeSpan.FromSeconds(2)); + + // Race readiness against worker completion so a fault before NotifyReady is not + // reported as a ReadyAttempted timeout after the full safety wait. + var workersCompleted = Task.WhenAll(workers); + var first = await Task.WhenAny(notify.ReadyAttempted.Task, workersCompleted) + .WaitAsync(TimeSpan.FromSeconds(30)); + if (ReferenceEquals(first, workersCompleted)) + { + await workersCompleted; + throw new InvalidOperationException( + "Concurrent readiness workers finished before any READY attempt was observed."); + } + Assert.Equal(1, notify.ReadyAttemptCount); Assert.Equal(0, notify.ReadyCount); gate.Set(); - await Task.WhenAll(workers).WaitAsync(TimeSpan.FromSeconds(2)); + await workersCompleted.WaitAsync(TimeSpan.FromSeconds(30)); workers = null; - await notify.ReadySent.Task.WaitAsync(TimeSpan.FromSeconds(2)); + await notify.ReadySent.Task.WaitAsync(TimeSpan.FromSeconds(30)); Assert.Equal(1, notify.ReadyCount); Assert.True(notify.ReadyAttemptCount >= 1); @@ -295,7 +326,7 @@ public async Task Readiness_ConcurrentTriggers_DoNotDuplicateReady() notify.BlockReadyUntil = null; if (workers is not null) { - await Task.WhenAll(workers).WaitAsync(TimeSpan.FromSeconds(2)); + await Task.WhenAll(workers).WaitAsync(TimeSpan.FromSeconds(30)); } } } diff --git a/tests/VectorNNTPD.Common.Tests/Core/DisposableOwnershipTests.cs b/tests/VectorNNTPD.Common.Tests/Core/DisposableOwnershipTests.cs index 32f4708a..6bb56c4d 100644 --- a/tests/VectorNNTPD.Common.Tests/Core/DisposableOwnershipTests.cs +++ b/tests/VectorNNTPD.Common.Tests/Core/DisposableOwnershipTests.cs @@ -16,9 +16,13 @@ public void Transfer_prevents_subsequent_dispose_from_disposing_the_resource() transferred = ownership.Transfer(); } - Assert.Same(resource, transferred); - Assert.Equal(0, resource.DisposeCount); - transferred.Dispose(); + // Transferred resource must be disposed even when an assertion fails. + using (transferred) + { + Assert.Same(resource, transferred); + Assert.Equal(0, resource.DisposeCount); + } + Assert.Equal(1, resource.DisposeCount); } @@ -41,10 +45,14 @@ public void Second_transfer_throws_and_does_not_dispose() { var resource = new TrackingDisposable(); using var ownership = new DisposableOwnership(resource); - Assert.Same(resource, ownership.Transfer()); - Assert.Throws(() => ownership.Transfer()); - Assert.Equal(0, resource.DisposeCount); - resource.Dispose(); + using (var transferred = ownership.Transfer()) + { + Assert.Same(resource, transferred); + Assert.Throws(() => ownership.Transfer()); + Assert.Equal(0, resource.DisposeCount); + } + + Assert.Equal(1, resource.DisposeCount); } /// Resource access after transfer fails closed. @@ -53,9 +61,13 @@ public void Resource_after_transfer_throws() { var resource = new TrackingDisposable(); using var ownership = new DisposableOwnership(resource); - _ = ownership.Transfer(); - Assert.Throws(() => _ = ownership.Resource); - resource.Dispose(); + using (ownership.Transfer()) + { + Assert.Throws(() => _ = ownership.Resource); + Assert.Equal(0, resource.DisposeCount); + } + + Assert.Equal(1, resource.DisposeCount); } /// Repeated dispose is a no-op after the first release. @@ -63,7 +75,7 @@ public void Resource_after_transfer_throws() public void Repeated_dispose_is_safe() { var resource = new TrackingDisposable(); - var ownership = new DisposableOwnership(resource); + using var ownership = new DisposableOwnership(resource); ownership.Dispose(); ownership.Dispose(); Assert.Equal(1, resource.DisposeCount); @@ -88,9 +100,12 @@ public async Task Async_transfer_prevents_subsequent_dispose_from_disposing_the_ transferred = ownership.Transfer(); } - Assert.Same(resource, transferred); - Assert.Equal(0, resource.DisposeCount); - await transferred.DisposeAsync(); + await using (transferred) + { + Assert.Same(resource, transferred); + Assert.Equal(0, resource.DisposeCount); + } + Assert.Equal(1, resource.DisposeCount); } @@ -100,10 +115,12 @@ public async Task Async_transfer_prevents_subsequent_dispose_from_disposing_the_ public async Task Async_dispose_without_transfer_disposes_once() { var resource = new TrackingAsyncDisposable(); - var ownership = new AsyncDisposableOwnership(resource); - await ownership.DisposeAsync(); - await ownership.DisposeAsync(); - Assert.Equal(1, resource.DisposeCount); + await using (var ownership = new AsyncDisposableOwnership(resource)) + { + await ownership.DisposeAsync(); + await ownership.DisposeAsync(); + Assert.Equal(1, resource.DisposeCount); + } } /// A second async transfer after the first fails closed. @@ -113,26 +130,39 @@ public async Task Async_second_transfer_throws() { var resource = new TrackingAsyncDisposable(); await using var ownership = new AsyncDisposableOwnership(resource); - Assert.Same(resource, ownership.Transfer()); - Assert.Throws(() => ownership.Transfer()); - Assert.Equal(0, resource.DisposeCount); - await resource.DisposeAsync(); + await using (var transferred = ownership.Transfer()) + { + Assert.Same(resource, transferred); + Assert.Throws(() => ownership.Transfer()); + Assert.Equal(0, resource.DisposeCount); + } + + Assert.Equal(1, resource.DisposeCount); } + /// + /// Test disposable that counts every entry so ownership helpers + /// cannot silently double-dispose under overlapping using scopes. + /// private sealed class TrackingDisposable : IDisposable { - public int DisposeCount { get; private set; } + private int _disposeCount; + + public int DisposeCount => Volatile.Read(ref _disposeCount); - public void Dispose() => DisposeCount++; + public void Dispose() => Interlocked.Increment(ref _disposeCount); } + /// Async counterpart of . private sealed class TrackingAsyncDisposable : IAsyncDisposable { - public int DisposeCount { get; private set; } + private int _disposeCount; + + public int DisposeCount => Volatile.Read(ref _disposeCount); public ValueTask DisposeAsync() { - DisposeCount++; + Interlocked.Increment(ref _disposeCount); return ValueTask.CompletedTask; } } From 302ae26293551f5e3216e99e5b234e40b1ec2b11 Mon Sep 17 00:00:00 2001 From: "savage@savage.za.org" Date: Thu, 22 Oct 2026 17:29:59 +0200 Subject: [PATCH 4/4] Fix NNTP shutdown grace-period timing under load --- .../Nntp/NntpSessionPool.cs | 29 ++++++++++++-- .../Nntp/NntpShutdownDeadlineTests.cs | 40 ++++++++++++++++++- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/src/VectorNNTPD.BackFillerService/Nntp/NntpSessionPool.cs b/src/VectorNNTPD.BackFillerService/Nntp/NntpSessionPool.cs index e7f9d439..c59e43f2 100644 --- a/src/VectorNNTPD.BackFillerService/Nntp/NntpSessionPool.cs +++ b/src/VectorNNTPD.BackFillerService/Nntp/NntpSessionPool.cs @@ -1068,15 +1068,20 @@ internal Task DrainAndDisposeAsync(CancellationToken cancellationToken, NntpShut /// /// A task that completes after remaining sessions have been retired or their cleanup fault has been observed. /// - /// The deadline is captured at this call and released when the method returns. Keepalive drain, lease drain, and QUIT all use its shared token. + /// Shutdown cancel and the replenish-supervisor await run first so waiting for that loop to observe cancel does not + /// consume the grace budget. The deadline is then captured for keepalive drain, lease drain, and every graceful QUIT. /// A grace timeout does not abandon remaining sessions. Sessions that cannot start QUIT before the deadline aborts the transport. /// A second call returns immediately. An unexpected retirement fault is thrown after the other sessions have been attempted /// and after the pool semaphores are disposed. /// public async ValueTask DisposeAsync() { - using var deadline = NntpShutdownDeadline.FromBudget(_shutdownGrace); - await DisposeCoreAsync(forceAfterGrace: true, CancellationToken.None, deadline).ConfigureAwait(false); + await DisposeCoreAsync( + forceAfterGrace: true, + CancellationToken.None, + NntpShutdownDeadline.None, + armGraceAfterReplenish: true) + .ConfigureAwait(false); } /// @@ -1094,6 +1099,12 @@ public async ValueTask DisposeAsync() /// /// Absolute shutdown instant. is a replacement drain. /// Retirement then captures one deadline instead of giving each session its own QUIT allowance. + /// When is , this value is ignored and a grace deadline is + /// captured after the replenish supervisor has observed shutdown cancel. + /// + /// + /// for : capture after replenish cancel so + /// waiting for that supervisor does not burn the keepalive/lease/QUIT budget under scheduling load. /// /// /// The disposed flag is published under before is snapshotted under . @@ -1122,7 +1133,8 @@ public async ValueTask DisposeAsync() private async Task DisposeCoreAsync( bool forceAfterGrace, CancellationToken cancellationToken, - NntpShutdownDeadline deadline) + NntpShutdownDeadline deadline, + bool armGraceAfterReplenish = false) { TaskCompletionSource drained; lock (_idleGate) @@ -1157,6 +1169,15 @@ private async Task DisposeCoreAsync( } } + // DisposeAsync arms grace here so replenish-cancel latency cannot exhaust QUIT budget before retirement. + using var armedGrace = armGraceAfterReplenish + ? NntpShutdownDeadline.FromBudget(_shutdownGrace) + : NntpShutdownDeadline.None; + if (armGraceAfterReplenish) + { + deadline = armedGrace; + } + await AwaitKeepAlivesAsync(deadline, cancellationToken).ConfigureAwait(false); if (_beforeLeaseDrainWait is { } beforeDrain) { diff --git a/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpShutdownDeadlineTests.cs b/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpShutdownDeadlineTests.cs index 5e323934..a5e1bfef 100644 --- a/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpShutdownDeadlineTests.cs +++ b/tests/VectorNNTPD.BackFillerService.Tests/Nntp/NntpShutdownDeadlineTests.cs @@ -12,13 +12,14 @@ namespace VectorNNTPD.BackFillerService.Tests.Nntp /// Shared shutdown deadline across stalled sessions, providers, and one replacement drain. /// /// - /// Scale pools use (500 ms) and keepAliveSeconds: 0, so replacement + /// Scale pools use and keepAliveSeconds: 0, so replacement /// spends essentially one shared /// retirement deadline on stalled QUITs (keepalive drain is empty). A correct run finishes near that budget /// plus scheduling. Regressing to per-session QuitAllowance (2 s) with /// yields about two serial waves (~4 s) and also starts a QUIT on /// every session. rejects the QuitAllowance stack; quitStarted bounds /// reject per-session independent budgets that still finish under the ceiling. + /// arms grace after replenish cancel so that wait cannot exhaust QUIT budget. /// is only hang detection for and does not replace /// . /// @@ -77,7 +78,7 @@ public void Deadline_cap_is_local_to_the_value_that_was_captured() /// Later sessions do not each receive a fresh two-second QUIT allowance. /// /// - /// The budget is 500 milliseconds and the accepted ceiling is 1500 milliseconds (below one QuitAllowance). + /// The shared budget and the accepted ceiling stay below one QuitAllowance. /// Eight independent two-second QUIT attempts would exceed that ceiling. /// At most writes can be in progress. /// The shared deadline token cancels that wave, and a later session observes the same token before it can start QUIT. @@ -115,6 +116,41 @@ public async Task Many_stalled_sessions_share_one_shutdown_budget() } } + /// + /// When the shared grace is already cancelled before retirement, idle sessions skip QUIT and still dispose the transport. + /// + /// + /// Documents the production contract behind a Linux CI quitStarted=0 failure: budget spent before + /// reaches the write must not be confused with a + /// missing shared-deadline gate. burns the budget after + /// grace is armed so replenish cancel is not the consumer. + /// + [Fact] + public async Task Shared_budget_exhausted_before_retirement_skips_quit() + { + const int sessions = 4; + var factory = new ScriptedNntpTransportFactory(); + var servers = EnqueueStalledQuitServers(factory, sessions); + var pool = NntpSessionPoolTests.CreatePool(factory, max: sessions, shutdownGrace: SharedBudget); + pool.BeforeLeaseDrainWait = async _ => await Task.Delay(SharedBudget + TimeSpan.FromMilliseconds(100)); + try + { + await pool.EnsureDesiredSessionsAsync(CancellationToken.None); + Assert.Equal(sessions, pool.ActiveSessionCount); + + await pool.DisposeAsync().AsTask().WaitAsync(MeasureHangTimeout); + + Assert.Equal(0, QuitStarts(servers)); + Assert.Equal(0, pool.LiveSessionCount); + Assert.All(servers, static server => Assert.Equal(1, server.ClientStreamDisposeCount)); + } + finally + { + Release(servers); + await pool.DisposeAsync(); + } + } + /// /// A drain deadline that expires while ARTICLE is blocked aborts that write and does not grant idle sessions a fresh QUIT budget. ///