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
49 changes: 49 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: CI

on:
push:
branches:
- main
- dev

jobs:
build-and-test:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: |
10.0.x

- name: Build
run: dotnet build src/Max.BotClient/Max.BotClient.csproj -c Release

- name: Test
run: dotnet test tests/Max.BotClient.Tests/Max.BotClient.Tests.csproj -c Release --no-build

publish:
runs-on: ubuntu-latest
needs: build-and-test
if: github.ref == 'refs/heads/main'
environment: main

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: |
10.0.x

- name: Pack
run: dotnet pack src/Max.BotClient/Max.BotClient.csproj -c Release -o ./artifacts

- name: Push to NuGet
run: dotnet nuget push ./artifacts/*.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
13 changes: 13 additions & 0 deletions src/Max.BotClient/Max.BotClient.ApiExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,18 @@ public static async Task ProcessApi<TParams>(
ApiRequestBinder.Bind(createParams(), basePath, out var path, out var body);
await botClient.SendRequest<object>(method, path, body, cancellationToken);
}

internal static async Task<TResult> PollingProcessApi<TParams, TDto, TResult>(
this IBotClientInternal botClient,
HttpMethod method,
string basePath,
Func<TParams> createParams,
CancellationToken cancellationToken = default
) where TParams : class
{
ApiRequestBinder.Bind(createParams(), basePath, out var path, out var body);
var dto = await botClient.PollingSendRequest<TDto>(method, path, body, cancellationToken);
return dto.ToResult<TDto, TResult>();
}
}
}
22 changes: 21 additions & 1 deletion src/Max.BotClient/Max.BotClient.ApiMethods.Subscriptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,25 @@ public static async Task<SubscribeResult> Unsubscribe(

return (response.Updates, response.Marker);
}

private static async Task<(Update[], long?)> GetUpdatesFromPolling(
this IBotClientInternal botClient,
int? limit = null,
int? timeout = null,
long? marker = null,
Types.UpdateType[]? types = null,
CancellationToken cancellationToken = default
)
{
var response = await botClient.PollingProcessApi<GetUpdatesParams, DTOs.GetUpdatesResponse, Types.GetUpdatesResponse>(
HttpMethod.Get,
"/updates",
() => new GetUpdatesParams
{ Limit = limit, Timeout = timeout, Marker = marker, UpdateTypes = types },
cancellationToken
);

return (response.Updates, response.Marker);
}
}
}
}
44 changes: 44 additions & 0 deletions src/Max.BotClient/Max.BotClient.DependencyInjection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#if NET10_0_OR_GREATER
using System;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Max.BotClient
{
public static class BotClientServiceCollectionExtensions
{
/// <summary>
/// Регистрирует <see cref="BotClient"/> и <see cref="IBotClient"/> в DI-контейнере.
/// </summary>
/// <param name="services">Коллекция сервисов.</param>
/// <param name="token">Токен бота.</param>
/// <param name="configure">Дополнительная настройка параметров (RetryCount, RetryDelaySeconds и др.).</param>
public static IServiceCollection AddMaxBotClient(
this IServiceCollection services,
string token,
Action<BotClientOptions>? configure = null)
{
ArgumentNullException.ThrowIfNull(services);

var options = new BotClientOptions(token);
configure?.Invoke(options);

services.TryAddSingleton(options);

services.AddHttpClient("MaxBotClient");

services.TryAddSingleton<IBotClient>(sp =>
{
var factory = sp.GetRequiredService<IHttpClientFactory>();
var httpClient = factory.CreateClient("MaxBotClient");
return new BotClient(options, httpClient);
});

services.TryAddSingleton<BotClient>(sp => (BotClient)sp.GetRequiredService<IBotClient>());

return services;
}
}
}
#endif
94 changes: 76 additions & 18 deletions src/Max.BotClient/Max.BotClient.Polling.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,19 @@ public static partial class BotClientApiMethods
/// <param name="errorHandler">Обработчик ошибок (необязательно).</param>
/// <param name="options">Опции polling.</param>
/// <param name="cancellationToken">Токен отмены.</param>
public static void StartReceiving(
public static Task StartReceiving(
this IBotClient botClient,
Func<IBotClient, Update, CancellationToken, Task> updateHandler,
Func<IBotClient, Exception, CancellationToken, Task>? errorHandler = null,
ReceiverOptions? options = null,
CancellationToken cancellationToken = default
) => Task.Run(() =>
) => Task.Run(() =>
botClient.ReceiveAsync(
updateHandler,
errorHandler,
options,
updateHandler,
errorHandler,
options,
cancellationToken
),
),
cancellationToken
);

Expand Down Expand Up @@ -83,7 +83,7 @@ public static async Task ReceiveAsync(
{
try
{
var (_, newMarker) = await botClient.GetUpdates(
var (_, newMarker) = await botClient.Update(
limit: 1,
timeout: 0,
marker: null,
Expand All @@ -92,14 +92,21 @@ public static async Task ReceiveAsync(
);
marker = newMarker;
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
if (errorHandler != null)
await errorHandler(botClient, ex, cancellationToken);
try
{
if (errorHandler != null)
await errorHandler(botClient, ex, cancellationToken);
}
catch
{
// Не позволяем errorHandler убить polling loop
}
}
}

Expand All @@ -109,7 +116,7 @@ public static async Task ReceiveAsync(

try
{
var result = await botClient.GetUpdates(
var result = await botClient.Update(
limit: options.Limit,
timeout: options.Timeout,
marker: marker,
Expand All @@ -120,14 +127,31 @@ public static async Task ReceiveAsync(
updates = result.Item1;
marker = result.Item2 ?? marker;
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
if (errorHandler != null)
await errorHandler(botClient, ex, cancellationToken);
try
{
if (errorHandler != null)
await errorHandler(botClient, ex, cancellationToken);
}
catch
{
// Не позволяем errorHandler убить polling loop
}

// Backoff перед повторной попыткой, чтобы не забивать API при длительном сбое
try
{
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
}
catch (OperationCanceledException)
{
break;
}

continue;
}
Expand All @@ -138,17 +162,51 @@ public static async Task ReceiveAsync(
{
await updateHandler(botClient, update, cancellationToken);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
if (errorHandler != null)
await errorHandler(botClient, ex, cancellationToken);
try
{
if (errorHandler != null)
await errorHandler(botClient, ex, cancellationToken);
}
catch
{
// Не позволяем errorHandler убить polling loop
}
}
}
}
}

private static Task<(Update[], long?)> Update(
this IBotClient botClient,
int? limit = null,
int? timeout = null,
long? marker = null,
Types.UpdateType[]? types = null,
CancellationToken cancellationToken = default
)
{
if (botClient is IBotClientInternal internalBotClient)
return internalBotClient.GetUpdatesFromPolling(
limit,
timeout,
marker,
types,
cancellationToken
);

return botClient.GetUpdates(
limit,
timeout,
marker,
types,
cancellationToken
);
}
}
}
}
55 changes: 53 additions & 2 deletions src/Max.BotClient/Max.BotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,23 @@ Task<TResponse> SendRequest<TResponse>(
);
}

public partial class BotClient : IBotClient
internal interface IBotClientInternal : IBotClient
{
Task<TResponse> PollingSendRequest<TResponse>(
HttpMethod method,
string path,
object? body = null,
CancellationToken cancellationToken = default
);
}

public partial class BotClient : IBotClientInternal, IDisposable
{
private readonly BotClientOptions _options;
private readonly HttpClient _httpClient;
private readonly bool _ownsHttpClient;
private HttpClient? _pollingHttpClient;
private bool _disposed;

public string Token => _options.Token;
public CancellationToken GlobalCancelToken { get; }
Expand All @@ -36,6 +49,7 @@ public BotClient(
_options = options ?? throw new ArgumentNullException(nameof(options));
GlobalCancelToken = cancellationToken;

_ownsHttpClient = httpClient == null;
_httpClient = httpClient ?? new HttpClient();
_httpClient.BaseAddress = new Uri(_options.ApiUrl);
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", _options.Token);
Expand All @@ -54,6 +68,34 @@ public async Task<TResponse> SendRequest<TResponse>(
string path,
object? body = null,
CancellationToken cancellationToken = default
) => await SendRequestCore<TResponse>(_httpClient, method, path, body, cancellationToken);

async Task<TResponse> IBotClientInternal.PollingSendRequest<TResponse>(
HttpMethod method,
string path,
object? body,
CancellationToken cancellationToken
)
{
if (_pollingHttpClient == null)
{
_pollingHttpClient = new HttpClient
{
BaseAddress = new Uri(_options.ApiUrl),
Timeout = Timeout.InfiniteTimeSpan
};
_pollingHttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", _options.Token);
}

return await SendRequestCore<TResponse>(_pollingHttpClient, method, path, body, cancellationToken);
}

private async Task<TResponse> SendRequestCore<TResponse>(
HttpClient httpClient,
HttpMethod method,
string path,
object? body,
CancellationToken cancellationToken
)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(GlobalCancelToken, cancellationToken);
Expand All @@ -78,7 +120,7 @@ public async Task<TResponse> SendRequest<TResponse>(
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}

using var response = await _httpClient.SendAsync(request, token);
using var response = await httpClient.SendAsync(request, token);
var responseBody = await response.Content.ReadAsStringAsync();

if (response.IsSuccessStatusCode)
Expand All @@ -98,5 +140,14 @@ public async Task<TResponse> SendRequest<TResponse>(

throw lastException!;
}

public void Dispose()
{
if (_disposed) return;
_disposed = true;

_pollingHttpClient?.Dispose();
if (_ownsHttpClient) _httpClient.Dispose();
}
}
}
Loading
Loading