diff --git a/CHANGELOG.md b/CHANGELOG.md index e352adc..da5b5b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.8.1-alpha] - 2026-11-02 + +### Fixed + +- **Polling shutdown**: при остановке бота `UpdatePoller` логировал `Network error while polling updates` с `MaxNetworkException`, внутри которого был `TaskCanceledException`: `FetchUpdatesAsync` заворачивал отмену long-polling запроса в сетевую ошибку. Теперь отмена пробрасывается как есть, и поллер завершается без предупреждений. Спасибо @diquoks! +- **HTTP client cancellation**: `MaxHttpClient` считал отмену токеном вызывающего кода сбоем — писал `HTTP request failed on attempt …` / `HTTP request retry attempts failed` и пытался повторить запрос. Отмена теперь сразу пробрасывается; таймаут `HttpClient` (токен не отменён) по-прежнему повторяется. +- **Handler cancellation**: если обработчик завершался `OperationCanceledException` из-за остановки поллера или отмены webhook-запроса, это логировалось как `Update handler threw an exception`. Теперь отмена пробрасывается без ошибки в логе; прерванная пачка обновлений не сдвигает маркер и будет получена снова после перезапуска. +- **Backoff during stop**: остановка во время паузы после сетевой ошибки больше не выходит из цикла поллинга исключением, минуя ожидание запущенных обработчиков. +- **Webhook aborted by client**: если MAX закрыл соединение до ответа, `MapMaxWebhook`/`WebhookController` возвращает `499` вместо необработанного исключения. + ## [0.8.0-alpha] - 2026-10-30 Модели приведены к [OpenAPI-схеме MAX Bot API](https://github.com/max-messenger/max-bot-api-client-go/blob/main/schema.yaml): строковые и `object`-поля стали типизированными, а nullability совпадает с документацией — меньше ручного разбора и null-проверок. Спасибо @diquoks за отзыв! @@ -437,7 +447,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- -[Unreleased]: https://github.com/NanoAgents/MaxBotNet/compare/v0.8.0-alpha...HEAD +[Unreleased]: https://github.com/NanoAgents/MaxBotNet/compare/v0.8.1-alpha...HEAD +[0.8.1-alpha]: https://github.com/NanoAgents/MaxBotNet/compare/v0.8.0-alpha...v0.8.1-alpha [0.8.0-alpha]: https://github.com/NanoAgents/MaxBotNet/compare/v0.7.1-alpha...v0.8.0-alpha [0.7.1-alpha]: https://github.com/NanoAgents/MaxBotNet/compare/v0.7.0-alpha...v0.7.1-alpha [0.7.0-alpha]: https://github.com/NanoAgents/MaxBotNet/compare/v0.6.3-alpha...v0.7.0-alpha diff --git a/src/Max.Bot/Max.Bot.csproj b/src/Max.Bot/Max.Bot.csproj index aa9d9ae..46b2263 100644 --- a/src/Max.Bot/Max.Bot.csproj +++ b/src/Max.Bot/Max.Bot.csproj @@ -5,7 +5,7 @@ enable MaxMessenger.Bot - 0.8.0-alpha + 0.8.1-alpha MaxBotNet Contributors C# library for Max Messenger Bot API (.NET 10, .NET 9, .NET 8) Apache-2.0 diff --git a/src/Max.Bot/Networking/MaxHttpClient.cs b/src/Max.Bot/Networking/MaxHttpClient.cs index 795e15b..7241214 100644 --- a/src/Max.Bot/Networking/MaxHttpClient.cs +++ b/src/Max.Bot/Networking/MaxHttpClient.cs @@ -109,7 +109,7 @@ public async Task SendAsyncRaw(MaxApiRequest request, CancellationToken return await ExecuteWithResponseHandlingAsync(httpRequest, cancellationToken).ConfigureAwait(false); } - catch (Exception ex) when (ShouldRetry(ex, attempt, request) || attempt == _options.RetryCount) + catch (Exception ex) when (!IsCancelledByCaller(ex, cancellationToken) && (ShouldRetry(ex, attempt, request) || attempt == _options.RetryCount)) { lastException = ex; attempt++; @@ -170,7 +170,7 @@ public async Task SendAsyncRaw( return await ExecuteWithResponseHandlingAsync(httpRequest, cancellationToken).ConfigureAwait(false); } - catch (Exception ex) when (ShouldRetry(ex, attempt) || attempt == _options.RetryCount) + catch (Exception ex) when (!IsCancelledByCaller(ex, cancellationToken) && (ShouldRetry(ex, attempt) || attempt == _options.RetryCount)) { lastException = ex; attempt++; @@ -337,6 +337,13 @@ internal static (string? Code, string? Message) ParseErrorBody(string? responseB return null; } + /// + /// Cancellation requested by the caller is not a network failure: it is neither retried nor logged as an error. + /// A raised by (caller token not cancelled) stays retryable. + /// + private static bool IsCancelledByCaller(Exception ex, CancellationToken cancellationToken) => + ex is OperationCanceledException && cancellationToken.IsCancellationRequested; + private bool ShouldRetry(Exception ex, int attempt, MaxApiRequest? request = null) { if (attempt >= _options.RetryCount) return false; diff --git a/src/Max.Bot/Polling/UpdateHandlerExecutor.cs b/src/Max.Bot/Polling/UpdateHandlerExecutor.cs index 880c5a4..c67f178 100644 --- a/src/Max.Bot/Polling/UpdateHandlerExecutor.cs +++ b/src/Max.Bot/Polling/UpdateHandlerExecutor.cs @@ -66,6 +66,11 @@ public static async Task ExecuteAsync( logger?.LogWarning(ex, "Update handler timed out after {Timeout}. UpdateId={UpdateId}", options.Handling.HandlerTimeout, update.UpdateId); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // * Polling stopped or the webhook request was cancelled: not a handler failure, let the caller see the cancellation. + throw; + } catch (Exception ex) { if (options.Handling.PropagateHandlerExceptions) diff --git a/src/Max.Bot/Polling/UpdatePoller.cs b/src/Max.Bot/Polling/UpdatePoller.cs index 0c7bcc0..e6cb2b5 100644 --- a/src/Max.Bot/Polling/UpdatePoller.cs +++ b/src/Max.Bot/Polling/UpdatePoller.cs @@ -208,6 +208,12 @@ private async Task PollAsync(CancellationToken cancellationToken) { await DispatchAsync(update, cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // * Stopped mid-update: keep the marker so the batch is fetched again after restart. + batchCompleted = false; + break; + } catch (Exception ex) { _logger?.LogError(ex, "Failed to dispatch update {UpdateId}. Skipping.", update.UpdateId); @@ -291,6 +297,10 @@ private async Task FetchUpdatesAsync(long? marker, Cancellat { throw; // Let the caller's catch-all handle it } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; // * Stop requested: not a network error, PollAsync exits quietly + } catch (Exception ex) { throw new MaxNetworkException($"Failed to fetch updates: {ex.Message}", ex); @@ -360,7 +370,14 @@ private async Task HandleTransientErrorAsync(Exception exception, CancellationTo _consecutiveErrors++; var delay = NextBackoffDelay(); _logger?.LogWarning(exception, "{Message} Retrying in {Delay}ms.", message, delay.TotalMilliseconds); - await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + try + { + await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // * Stopped during backoff: let PollAsync leave the loop and drain in-flight handlers. + } } private TimeSpan NextBackoffDelay() diff --git a/src/Max.Bot/Polling/WebhookRequestProcessor.cs b/src/Max.Bot/Polling/WebhookRequestProcessor.cs index bcb6aa4..7f0fda5 100644 --- a/src/Max.Bot/Polling/WebhookRequestProcessor.cs +++ b/src/Max.Bot/Polling/WebhookRequestProcessor.cs @@ -78,6 +78,11 @@ public static async Task ProcessAsync( // * Answer MAX anyway: a non-2xx status would make MAX deliver the same update again. logger?.LogWarning(ex, "Webhook update handling exceeded Webhook.HandlerTimeout ({Timeout}).", handlerTimeout); } + catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) + { + // * The client (MAX) closed the connection: nobody reads the response, so this is not an error. + return StatusCodes.Status499ClientClosedRequest; + } return StatusCodes.Status200OK; } diff --git a/tests/Max.Bot.Tests/Unit/Regression/CancellationRegressionTests.cs b/tests/Max.Bot.Tests/Unit/Regression/CancellationRegressionTests.cs new file mode 100644 index 0000000..58bcffa --- /dev/null +++ b/tests/Max.Bot.Tests/Unit/Regression/CancellationRegressionTests.cs @@ -0,0 +1,227 @@ +// 📁 CancellationRegressionTests.cs - Regression tests for cancellation handling (v0.8.1-alpha) +// 🎯 Core function: Pins that stopping the bot is not reported as a network or handler error. +// 🔗 Key dependencies: UpdatePoller, MaxHttpClient, UpdateHandlerExecutor. +// 💡 Usage: Each test documents the failure scenario it guards against. + +using System.Net.Http; +using FluentAssertions; +using Max.Bot.Api; +using Max.Bot.Configuration; +using Max.Bot.Exceptions; +using Max.Bot.Networking; +using Max.Bot.Polling; +using Max.Bot.Types; +using Microsoft.Extensions.Logging; +using Moq; +using Xunit; + +namespace Max.Bot.Tests.Unit.Regression; + +public class CancellationRegressionTests +{ + private const string OneUpdateJson = """{"updates":[{"update_type":"message_created","timestamp":1,"message":{"recipient":{"chat_id":1,"chat_type":"dialog"},"timestamp":1,"body":{"mid":"m","seq":1,"text":"hi"}}}],"marker":2}"""; + + /// + /// Reported: stopping the bot logged "Network error while polling updates" with MaxNetworkException wrapping + /// TaskCanceledException, because FetchUpdatesAsync wrapped the cancellation of the long-polling request. + /// + [Fact] + public async Task StopAsync_DuringLongPollingRequest_ShouldNotLogNetworkError() + { + var requestStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var pollClient = new Mock(); + pollClient + .Setup(x => x.SendAsyncRaw(It.IsAny(), It.IsAny())) + .Returns(async (_, ct) => + { + requestStarted.TrySetResult(); + await Task.Delay(Timeout.Infinite, ct); + return "{}"; + }); + + var logger = new RecordingLogger(); + var poller = CreatePoller(pollClient.Object, logger); + + await poller.StartAsync(Mock.Of(), CancellationToken.None); + await requestStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await poller.StopAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(5)); + + logger.Entries.Should().NotContain(e => e.Level >= LogLevel.Warning); + logger.Entries.Should().Contain(e => e.Message.Contains("UpdatePoller stopped.")); + } + + [Fact] + public async Task StopAsync_DuringErrorBackoff_ShouldExitWithoutUnobservedCancellation() + { + var failed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var pollClient = new Mock(); + pollClient + .Setup(x => x.SendAsyncRaw(It.IsAny(), It.IsAny())) + .Returns((_, _) => + { + failed.TrySetResult(); + throw new HttpRequestException("network down"); + }); + + var options = CreateOptions(); + options.Polling.ErrorBackoffBase = TimeSpan.FromMinutes(1); + options.Polling.ErrorBackoffMax = TimeSpan.FromMinutes(1); + var logger = new RecordingLogger(); + var poller = CreatePoller(pollClient.Object, logger, options); + + await poller.StartAsync(Mock.Of(), CancellationToken.None); + await failed.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await poller.StopAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(5)); + + // The real network error is still reported once; stopping during the backoff adds nothing. + logger.Entries.Count(e => e.Level == LogLevel.Warning).Should().Be(1); + logger.Entries.Should().NotContain(e => e.Level >= LogLevel.Error); + } + + [Fact] + public async Task StopAsync_WhileHandlerObservesCancellation_ShouldNotLogHandlerError() + { + var handlerStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var calls = 0; + var pollClient = new Mock(); + pollClient + .Setup(x => x.SendAsyncRaw(It.IsAny(), It.IsAny())) + .Returns(async (_, ct) => + { + if (Interlocked.Increment(ref calls) == 1) + { + return OneUpdateJson; + } + + await Task.Delay(Timeout.Infinite, ct); + return "{}"; + }); + + var handler = new DelegatingUpdateHandler(onMessage: async (_, ct) => + { + handlerStarted.TrySetResult(); + await Task.Delay(Timeout.Infinite, ct); + }); + + var logger = new RecordingLogger(); + var poller = CreatePoller(pollClient.Object, logger); + + await poller.StartAsync(handler, CancellationToken.None); + await handlerStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await poller.StopAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(5)); + + logger.Entries.Should().NotContain(e => e.Level >= LogLevel.Warning); + calls.Should().Be(1, "the batch was interrupted, so the marker is not advanced and no further request is made"); + } + + [Fact] + public async Task MaxHttpClient_CancelledByCaller_ShouldNotRetryNorLogFailure() + { + using var cts = new CancellationTokenSource(); + var attempts = 0; + var handler = new CallbackHandler(async ct => + { + Interlocked.Increment(ref attempts); + cts.Cancel(); + await Task.Delay(Timeout.Infinite, ct); + return new HttpResponseMessage(); + }); + + var logger = new RecordingLogger(); + using var client = new MaxHttpClient( + new HttpClient(handler), + new MaxBotClientOptions { BaseUrl = "https://api.max.ru/bot", RetryCount = 3, RetryBaseDelay = TimeSpan.FromMilliseconds(1) }, + logger); + + var act = () => client.SendAsyncRaw(new MaxApiRequest { Method = HttpMethod.Get, Endpoint = "/me" }, cts.Token); + + await act.Should().ThrowAsync(); + attempts.Should().Be(1); + logger.Entries.Should().NotContain(e => e.Level >= LogLevel.Warning); + } + + [Fact] + public async Task MaxHttpClient_HttpClientTimeout_ShouldStillBeRetried() + { + var attempts = 0; + var handler = new CallbackHandler(_ => + { + if (Interlocked.Increment(ref attempts) == 1) + { + throw new TaskCanceledException("timeout"); + } + + return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent("{}") }); + }); + + using var client = new MaxHttpClient( + new HttpClient(handler), + new MaxBotClientOptions { BaseUrl = "https://api.max.ru/bot", RetryCount = 2, RetryBaseDelay = TimeSpan.FromMilliseconds(1) }); + + var body = await client.SendAsyncRaw(new MaxApiRequest { Method = HttpMethod.Get, Endpoint = "/me" }, CancellationToken.None); + + body.Should().Be("{}"); + attempts.Should().Be(2); + } + + [Fact] + public async Task UpdateHandlerExecutor_CancelledByCaller_ShouldPropagateCancellationWithoutErrorLog() + { + using var cts = new CancellationTokenSource(); + var handler = new DelegatingUpdateHandler(onMessage: async (_, ct) => + { + cts.Cancel(); + await Task.Delay(Timeout.Infinite, ct); + }); + var update = Max.Bot.Networking.MaxJsonSerializer.Deserialize(OneUpdateJson).Updates[0]; + var logger = new RecordingLogger(); + + var act = () => UpdateHandlerExecutor.ExecuteAsync(update, handler, CreateOptions(), Mock.Of(), logger, null, cts.Token); + + await act.Should().ThrowAsync(); + logger.Entries.Should().BeEmpty(); + } + + private static MaxBotOptions CreateOptions() => new() + { + Token = "test-token", + BaseUrl = "https://api.max.ru/bot" + }; + + private static UpdatePoller CreatePoller(IMaxHttpClient pollClient, ILogger logger, MaxBotOptions? options = null) => + new(Mock.Of(), Mock.Of(), options ?? CreateOptions(), pollClient, logger); + + private sealed class CallbackHandler(Func> send) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => send(cancellationToken); + } + + private sealed class RecordingLogger : ILogger + { + private readonly List<(LogLevel Level, string Message)> _entries = new(); + + public IReadOnlyList<(LogLevel Level, string Message)> Entries + { + get + { + lock (_entries) + { + return _entries.ToArray(); + } + } + } + + public IDisposable? BeginScope(TState state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + lock (_entries) + { + _entries.Add((logLevel, formatter(state, exception))); + } + } + } +}