Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 за отзыв!
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/Max.Bot/Max.Bot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Nullable>enable</Nullable>

<PackageId>MaxMessenger.Bot</PackageId>
<Version>0.8.0-alpha</Version>
<Version>0.8.1-alpha</Version>
<Authors>MaxBotNet Contributors</Authors>
<Description>C# library for Max Messenger Bot API (.NET 10, .NET 9, .NET 8)</Description>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
Expand Down
11 changes: 9 additions & 2 deletions src/Max.Bot/Networking/MaxHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public async Task<string> 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++;
Expand Down Expand Up @@ -170,7 +170,7 @@ public async Task<string> 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++;
Expand Down Expand Up @@ -337,6 +337,13 @@ internal static (string? Code, string? Message) ParseErrorBody(string? responseB
return null;
}

/// <summary>
/// Cancellation requested by the caller is not a network failure: it is neither retried nor logged as an error.
/// A <see cref="TaskCanceledException"/> raised by <see cref="HttpClient.Timeout"/> (caller token not cancelled) stays retryable.
/// </summary>
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;
Expand Down
5 changes: 5 additions & 0 deletions src/Max.Bot/Polling/UpdateHandlerExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
19 changes: 18 additions & 1 deletion src/Max.Bot/Polling/UpdatePoller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -291,6 +297,10 @@ private async Task<GetUpdatesResponse> 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);
Expand Down Expand Up @@ -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()
Expand Down
5 changes: 5 additions & 0 deletions src/Max.Bot/Polling/WebhookRequestProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ public static async Task<int> 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;
}
Expand Down
227 changes: 227 additions & 0 deletions tests/Max.Bot.Tests/Unit/Regression/CancellationRegressionTests.cs
Original file line number Diff line number Diff line change
@@ -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}""";

/// <summary>
/// Reported: stopping the bot logged "Network error while polling updates" with MaxNetworkException wrapping
/// TaskCanceledException, because FetchUpdatesAsync wrapped the cancellation of the long-polling request.
/// </summary>
[Fact]
public async Task StopAsync_DuringLongPollingRequest_ShouldNotLogNetworkError()
{
var requestStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var pollClient = new Mock<IMaxHttpClient>();
pollClient
.Setup(x => x.SendAsyncRaw(It.IsAny<MaxApiRequest>(), It.IsAny<CancellationToken>()))
.Returns<MaxApiRequest, CancellationToken>(async (_, ct) =>
{
requestStarted.TrySetResult();
await Task.Delay(Timeout.Infinite, ct);
return "{}";
});

var logger = new RecordingLogger<UpdatePoller>();
var poller = CreatePoller(pollClient.Object, logger);

await poller.StartAsync(Mock.Of<IUpdateHandler>(), 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<IMaxHttpClient>();
pollClient
.Setup(x => x.SendAsyncRaw(It.IsAny<MaxApiRequest>(), It.IsAny<CancellationToken>()))
.Returns<MaxApiRequest, CancellationToken>((_, _) =>
{
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<UpdatePoller>();
var poller = CreatePoller(pollClient.Object, logger, options);

await poller.StartAsync(Mock.Of<IUpdateHandler>(), 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<IMaxHttpClient>();
pollClient
.Setup(x => x.SendAsyncRaw(It.IsAny<MaxApiRequest>(), It.IsAny<CancellationToken>()))
.Returns<MaxApiRequest, CancellationToken>(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<UpdatePoller>();
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<MaxHttpClient>();
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<OperationCanceledException>();
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<GetUpdatesResponse>(OneUpdateJson).Updates[0];
var logger = new RecordingLogger<UpdatePoller>();

var act = () => UpdateHandlerExecutor.ExecuteAsync(update, handler, CreateOptions(), Mock.Of<IMaxBotApi>(), logger, null, cts.Token);

await act.Should().ThrowAsync<OperationCanceledException>();
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<UpdatePoller> logger, MaxBotOptions? options = null) =>
new(Mock.Of<IMaxBotApi>(), Mock.Of<ISubscriptionsApi>(), options ?? CreateOptions(), pollClient, logger);

private sealed class CallbackHandler(Func<CancellationToken, Task<HttpResponseMessage>> send) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => send(cancellationToken);
}

private sealed class RecordingLogger<T> : ILogger<T>
{
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>(TState state)
where TState : notnull => null;

public bool IsEnabled(LogLevel logLevel) => true;

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
lock (_entries)
{
_entries.Add((logLevel, formatter(state, exception)));
}
}
}
}
Loading