| | | 1 | | using System.Runtime.CompilerServices; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using TeleFlow.Telegram.Internal; |
| | | 4 | | using TeleFlow.Telegram.Schema.Methods; |
| | | 5 | | using TeleFlow.Telegram.Schema.Types; |
| | | 6 | | |
| | | 7 | | namespace TeleFlow.Telegram; |
| | | 8 | | |
| | | 9 | | public sealed partial class TelegramLongPollingClient : ITelegramLongPollingClient |
| | | 10 | | { |
| | | 11 | | private readonly ITelegramClient _telegramClient; |
| | | 12 | | private readonly TimeProvider _timeProvider; |
| | | 13 | | private readonly ILogger<TelegramLongPollingClient> _logger; |
| | | 14 | | |
| | | 15 | | public TelegramLongPollingClient( |
| | | 16 | | ITelegramClient telegramClient, |
| | | 17 | | TimeProvider timeProvider, |
| | | 18 | | ILoggerFactory loggerFactory) |
| | | 19 | | { |
| | 25 | 20 | | ArgumentNullException.ThrowIfNull(telegramClient); |
| | 25 | 21 | | ArgumentNullException.ThrowIfNull(timeProvider); |
| | 25 | 22 | | ArgumentNullException.ThrowIfNull(loggerFactory); |
| | | 23 | | |
| | 25 | 24 | | _telegramClient = telegramClient; |
| | 25 | 25 | | _timeProvider = timeProvider; |
| | 25 | 26 | | _logger = loggerFactory.CreateLogger<TelegramLongPollingClient>(); |
| | 25 | 27 | | } |
| | | 28 | | |
| | | 29 | | public async Task RunAsync( |
| | | 30 | | Func<Update, CancellationToken, Task> updateHandler, |
| | | 31 | | TelegramRawLongPollingOptions? options = null, |
| | | 32 | | CancellationToken cancellationToken = default) |
| | | 33 | | { |
| | 6 | 34 | | ArgumentNullException.ThrowIfNull(updateHandler); |
| | | 35 | | |
| | 6 | 36 | | options ??= new TelegramRawLongPollingOptions(); |
| | 6 | 37 | | TelegramRawLongPollingOptionsValidator.Validate(options); |
| | | 38 | | |
| | 4 | 39 | | long? offset = null; |
| | 4 | 40 | | var backoff = new TelegramRawLongPollingBackoff(options.Backoff); |
| | 4 | 41 | | var allowedUpdates = CopyAllowedUpdates(options.AllowedUpdates); |
| | 4 | 42 | | var connected = false; |
| | 4 | 43 | | var recoveringFromPollingFailure = false; |
| | | 44 | | |
| | 4 | 45 | | LogStart(options, allowedUpdates); |
| | | 46 | | |
| | 9 | 47 | | while (!cancellationToken.IsCancellationRequested) |
| | | 48 | | { |
| | 6 | 49 | | var updates = await GetUpdatesBatchAsync( |
| | 6 | 50 | | offset, |
| | 6 | 51 | | options, |
| | 6 | 52 | | allowedUpdates, |
| | 6 | 53 | | backoff, |
| | 6 | 54 | | () => |
| | 6 | 55 | | { |
| | 6 | 56 | | if (!connected) |
| | 6 | 57 | | { |
| | 4 | 58 | | LogConnected(_logger); |
| | 4 | 59 | | connected = true; |
| | 6 | 60 | | } |
| | 6 | 61 | | |
| | 6 | 62 | | if (recoveringFromPollingFailure) |
| | 6 | 63 | | { |
| | 2 | 64 | | LogGetUpdatesRecovered(_logger); |
| | 2 | 65 | | recoveringFromPollingFailure = false; |
| | 6 | 66 | | } |
| | 6 | 67 | | }, |
| | 3 | 68 | | () => recoveringFromPollingFailure = true, |
| | 6 | 69 | | cancellationToken).ConfigureAwait(false); |
| | | 70 | | |
| | 20 | 71 | | for (var index = 0; index < updates.Count; index++) |
| | | 72 | | { |
| | 5 | 73 | | var update = updates[index]; |
| | | 74 | | |
| | 5 | 75 | | if (_logger.IsEnabled(LogLevel.Debug)) |
| | | 76 | | { |
| | 0 | 77 | | var updateType = TelegramRawLongPollingLogFormatter.GetUpdateType(update); |
| | 0 | 78 | | var processingStarted = _timeProvider.GetTimestamp(); |
| | | 79 | | |
| | 0 | 80 | | LogUpdateReceived( |
| | 0 | 81 | | _logger, |
| | 0 | 82 | | update.UpdateId, |
| | 0 | 83 | | updateType, |
| | 0 | 84 | | index + 1, |
| | 0 | 85 | | updates.Count); |
| | | 86 | | |
| | 0 | 87 | | await updateHandler(update, cancellationToken).ConfigureAwait(false); |
| | 0 | 88 | | offset = update.UpdateId + 1; |
| | | 89 | | |
| | 0 | 90 | | LogUpdateAcknowledgedByHandler( |
| | 0 | 91 | | _logger, |
| | 0 | 92 | | update.UpdateId, |
| | 0 | 93 | | updateType, |
| | 0 | 94 | | GetElapsedMilliseconds(processingStarted)); |
| | 0 | 95 | | continue; |
| | | 96 | | } |
| | | 97 | | |
| | 5 | 98 | | await updateHandler(update, cancellationToken).ConfigureAwait(false); |
| | 4 | 99 | | offset = update.UpdateId + 1; |
| | 4 | 100 | | } |
| | 5 | 101 | | } |
| | 3 | 102 | | } |
| | | 103 | | |
| | | 104 | | public async IAsyncEnumerable<TelegramPolledUpdate> GetUpdatesAsync( |
| | | 105 | | TelegramRawLongPollingOptions? options = null, |
| | | 106 | | [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| | | 107 | | { |
| | 18 | 108 | | options ??= new TelegramRawLongPollingOptions(); |
| | 18 | 109 | | TelegramRawLongPollingOptionsValidator.Validate(options); |
| | | 110 | | |
| | 18 | 111 | | long? offset = null; |
| | 18 | 112 | | var backoff = new TelegramRawLongPollingBackoff(options.Backoff); |
| | 18 | 113 | | var allowedUpdates = CopyAllowedUpdates(options.AllowedUpdates); |
| | 18 | 114 | | var connected = false; |
| | 18 | 115 | | var recoveringFromPollingFailure = false; |
| | | 116 | | |
| | 18 | 117 | | LogStart(options, allowedUpdates); |
| | | 118 | | |
| | 37 | 119 | | while (!cancellationToken.IsCancellationRequested) |
| | | 120 | | { |
| | 23 | 121 | | var updates = await GetUpdatesBatchAsync( |
| | 23 | 122 | | offset, |
| | 23 | 123 | | options, |
| | 23 | 124 | | allowedUpdates, |
| | 23 | 125 | | backoff, |
| | 23 | 126 | | () => |
| | 23 | 127 | | { |
| | 23 | 128 | | if (!connected) |
| | 23 | 129 | | { |
| | 18 | 130 | | LogConnected(_logger); |
| | 18 | 131 | | connected = true; |
| | 23 | 132 | | } |
| | 23 | 133 | | |
| | 23 | 134 | | if (recoveringFromPollingFailure) |
| | 23 | 135 | | { |
| | 4 | 136 | | LogGetUpdatesRecovered(_logger); |
| | 4 | 137 | | recoveringFromPollingFailure = false; |
| | 23 | 138 | | } |
| | 23 | 139 | | }, |
| | 5 | 140 | | () => recoveringFromPollingFailure = true, |
| | 23 | 141 | | cancellationToken).ConfigureAwait(false); |
| | | 142 | | |
| | 82 | 143 | | for (var index = 0; index < updates.Count; index++) |
| | | 144 | | { |
| | 22 | 145 | | var update = updates[index]; |
| | 22 | 146 | | var polledUpdate = new TelegramPolledUpdate(update, index + 1, updates.Count); |
| | | 147 | | |
| | 22 | 148 | | var debugEnabled = _logger.IsEnabled(LogLevel.Debug); |
| | 22 | 149 | | var updateType = debugEnabled |
| | 22 | 150 | | ? TelegramRawLongPollingLogFormatter.GetUpdateType(update) |
| | 22 | 151 | | : string.Empty; |
| | | 152 | | |
| | 22 | 153 | | if (debugEnabled) |
| | | 154 | | { |
| | 2 | 155 | | LogStreamUpdateReceived( |
| | 2 | 156 | | _logger, |
| | 2 | 157 | | update.UpdateId, |
| | 2 | 158 | | updateType); |
| | | 159 | | } |
| | | 160 | | |
| | 22 | 161 | | yield return polledUpdate; |
| | | 162 | | |
| | 19 | 163 | | if (!polledUpdate.IsAcknowledged) |
| | | 164 | | { |
| | 1 | 165 | | throw new InvalidOperationException( |
| | 1 | 166 | | "Telegram polled updates must be acknowledged with AcknowledgeAsync before requesting the next u |
| | | 167 | | } |
| | | 168 | | |
| | 18 | 169 | | offset = update.UpdateId + 1; |
| | | 170 | | |
| | 18 | 171 | | if (debugEnabled) |
| | | 172 | | { |
| | 1 | 173 | | LogStreamUpdateAcknowledged( |
| | 1 | 174 | | _logger, |
| | 1 | 175 | | update.UpdateId, |
| | 1 | 176 | | updateType); |
| | | 177 | | } |
| | 18 | 178 | | } |
| | 19 | 179 | | } |
| | 17 | 180 | | } |
| | | 181 | | |
| | | 182 | | private async Task<IReadOnlyList<Update>> GetUpdatesBatchAsync( |
| | | 183 | | long? offset, |
| | | 184 | | TelegramRawLongPollingOptions options, |
| | | 185 | | IReadOnlyList<string>? allowedUpdates, |
| | | 186 | | TelegramRawLongPollingBackoff backoff, |
| | | 187 | | Action onSuccess, |
| | | 188 | | Action onTransientFailure, |
| | | 189 | | CancellationToken cancellationToken) |
| | | 190 | | { |
| | | 191 | | while (true) |
| | | 192 | | { |
| | | 193 | | try |
| | | 194 | | { |
| | 37 | 195 | | var updates = await _telegramClient.SendAsync( |
| | 37 | 196 | | new GetUpdates |
| | 37 | 197 | | { |
| | 37 | 198 | | Offset = offset, |
| | 37 | 199 | | Limit = options.Limit, |
| | 37 | 200 | | Timeout = options.TimeoutSeconds, |
| | 37 | 201 | | AllowedUpdates = allowedUpdates |
| | 37 | 202 | | }, |
| | 37 | 203 | | cancellationToken).ConfigureAwait(false); |
| | | 204 | | |
| | 29 | 205 | | onSuccess(); |
| | 29 | 206 | | backoff.Reset(); |
| | 29 | 207 | | return updates; |
| | | 208 | | } |
| | 8 | 209 | | catch (Exception exception) when (IsPollingTransient(exception) && !cancellationToken.IsCancellationRequeste |
| | | 210 | | { |
| | 8 | 211 | | var delay = GetPollingRetryDelay(exception, backoff); |
| | 8 | 212 | | onTransientFailure(); |
| | | 213 | | |
| | 8 | 214 | | LogGetUpdatesFailed( |
| | 8 | 215 | | _logger, |
| | 8 | 216 | | exception, |
| | 8 | 217 | | delay); |
| | | 218 | | |
| | 8 | 219 | | await DelayAsync(delay, cancellationToken).ConfigureAwait(false); |
| | 8 | 220 | | } |
| | | 221 | | } |
| | 29 | 222 | | } |
| | | 223 | | |
| | | 224 | | private void LogStart( |
| | | 225 | | TelegramRawLongPollingOptions options, |
| | | 226 | | IReadOnlyList<string>? allowedUpdates) |
| | | 227 | | { |
| | 22 | 228 | | if (!_logger.IsEnabled(LogLevel.Information)) |
| | | 229 | | { |
| | 20 | 230 | | return; |
| | | 231 | | } |
| | | 232 | | |
| | 2 | 233 | | LogStarting( |
| | 2 | 234 | | _logger, |
| | 2 | 235 | | TelegramRawLongPollingLogFormatter.FormatAllowedUpdates(allowedUpdates), |
| | 2 | 236 | | options.TimeoutSeconds, |
| | 2 | 237 | | options.Limit); |
| | 2 | 238 | | } |
| | | 239 | | |
| | | 240 | | private double GetElapsedMilliseconds(long startingTimestamp) |
| | | 241 | | { |
| | 0 | 242 | | return _timeProvider.GetElapsedTime(startingTimestamp).TotalMilliseconds; |
| | | 243 | | } |
| | | 244 | | |
| | | 245 | | private ValueTask DelayAsync(TimeSpan delay, CancellationToken cancellationToken) |
| | | 246 | | { |
| | 8 | 247 | | return delay <= TimeSpan.Zero |
| | 8 | 248 | | ? ValueTask.CompletedTask |
| | 8 | 249 | | : new ValueTask(Task.Delay(delay, _timeProvider, cancellationToken)); |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | private static string[]? CopyAllowedUpdates(IReadOnlyList<string>? allowedUpdates) |
| | | 253 | | { |
| | 22 | 254 | | return allowedUpdates is null ? null : allowedUpdates.ToArray(); |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | private static bool IsPollingTransient(Exception exception) |
| | | 258 | | { |
| | 8 | 259 | | return exception is TelegramNetworkException or |
| | 8 | 260 | | TelegramServerException or |
| | 8 | 261 | | TelegramDecodeException or |
| | 8 | 262 | | TelegramRetryAfterException; |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | private static TimeSpan GetPollingRetryDelay(Exception exception, TelegramRawLongPollingBackoff backoff) |
| | | 266 | | { |
| | 8 | 267 | | return exception is TelegramRetryAfterException { RetryAfter: { } retryAfter } |
| | 8 | 268 | | ? retryAfter |
| | 8 | 269 | | : backoff.NextDelay(); |
| | | 270 | | } |
| | | 271 | | |
| | | 272 | | [LoggerMessage( |
| | | 273 | | EventId = 1, |
| | | 274 | | Level = LogLevel.Information, |
| | | 275 | | Message = "Starting raw Telegram long polling. allowed_updates={AllowedUpdates}, timeout={TimeoutSeconds}s, limi |
| | | 276 | | private static partial void LogStarting( |
| | | 277 | | ILogger logger, |
| | | 278 | | string allowedUpdates, |
| | | 279 | | int timeoutSeconds, |
| | | 280 | | int limit); |
| | | 281 | | |
| | | 282 | | [LoggerMessage( |
| | | 283 | | EventId = 2, |
| | | 284 | | Level = LogLevel.Information, |
| | | 285 | | Message = "Raw Telegram long polling connected.")] |
| | | 286 | | private static partial void LogConnected(ILogger logger); |
| | | 287 | | |
| | | 288 | | [LoggerMessage( |
| | | 289 | | EventId = 3, |
| | | 290 | | Level = LogLevel.Information, |
| | | 291 | | Message = "Raw Telegram long polling getUpdates recovered after transient failures.")] |
| | | 292 | | private static partial void LogGetUpdatesRecovered(ILogger logger); |
| | | 293 | | |
| | | 294 | | [LoggerMessage( |
| | | 295 | | EventId = 4, |
| | | 296 | | Level = LogLevel.Debug, |
| | | 297 | | Message = "Raw Telegram update received. update_id={UpdateId}, type={UpdateType}, batch_index={BatchIndex}/{Batc |
| | | 298 | | private static partial void LogUpdateReceived( |
| | | 299 | | ILogger logger, |
| | | 300 | | long updateId, |
| | | 301 | | string updateType, |
| | | 302 | | int batchIndex, |
| | | 303 | | int batchCount); |
| | | 304 | | |
| | | 305 | | [LoggerMessage( |
| | | 306 | | EventId = 5, |
| | | 307 | | Level = LogLevel.Debug, |
| | | 308 | | Message = "Raw Telegram update acknowledged by handler. update_id={UpdateId}, type={UpdateType}, total_ms={Total |
| | | 309 | | private static partial void LogUpdateAcknowledgedByHandler( |
| | | 310 | | ILogger logger, |
| | | 311 | | long updateId, |
| | | 312 | | string updateType, |
| | | 313 | | double totalElapsedMilliseconds); |
| | | 314 | | |
| | | 315 | | [LoggerMessage( |
| | | 316 | | EventId = 6, |
| | | 317 | | Level = LogLevel.Debug, |
| | | 318 | | Message = "Raw Telegram update received. update_id={UpdateId}, type={UpdateType}.")] |
| | | 319 | | private static partial void LogStreamUpdateReceived( |
| | | 320 | | ILogger logger, |
| | | 321 | | long updateId, |
| | | 322 | | string updateType); |
| | | 323 | | |
| | | 324 | | [LoggerMessage( |
| | | 325 | | EventId = 7, |
| | | 326 | | Level = LogLevel.Debug, |
| | | 327 | | Message = "Raw Telegram update acknowledged. update_id={UpdateId}, type={UpdateType}.")] |
| | | 328 | | private static partial void LogStreamUpdateAcknowledged( |
| | | 329 | | ILogger logger, |
| | | 330 | | long updateId, |
| | | 331 | | string updateType); |
| | | 332 | | |
| | | 333 | | [LoggerMessage( |
| | | 334 | | EventId = 8, |
| | | 335 | | Level = LogLevel.Warning, |
| | | 336 | | Message = "Raw Telegram long polling getUpdates failed. Retrying in {Delay}.")] |
| | | 337 | | private static partial void LogGetUpdatesFailed( |
| | | 338 | | ILogger logger, |
| | | 339 | | Exception exception, |
| | | 340 | | TimeSpan delay); |
| | | 341 | | } |