| | | 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 | | /// <summary> |
| | | 10 | | /// Receives Telegram updates through getUpdates, preserves acknowledgement ordering, and applies explicit schema decode |
| | | 11 | | /// </summary> |
| | | 12 | | public sealed partial class TelegramLongPollingClient : ITelegramLongPollingClient |
| | | 13 | | { |
| | | 14 | | private readonly ITelegramUpdateBatchReceiver _batchReceiver; |
| | | 15 | | private readonly ITelegramUpdateDecodeFailurePolicy _decodeFailurePolicy; |
| | | 16 | | private readonly TimeProvider _timeProvider; |
| | | 17 | | private readonly ILogger<TelegramLongPollingClient> _logger; |
| | | 18 | | |
| | | 19 | | public TelegramLongPollingClient( |
| | | 20 | | ITelegramClient telegramClient, |
| | | 21 | | TimeProvider timeProvider, |
| | | 22 | | ILoggerFactory loggerFactory) |
| | 7 | 23 | | : this( |
| | 7 | 24 | | new TypedTelegramUpdateBatchReceiver(telegramClient), |
| | 7 | 25 | | StopTelegramUpdateDecodeFailurePolicy.Instance, |
| | 7 | 26 | | timeProvider, |
| | 7 | 27 | | loggerFactory) |
| | | 28 | | { |
| | 7 | 29 | | } |
| | | 30 | | |
| | | 31 | | internal TelegramLongPollingClient( |
| | | 32 | | ITelegramUpdateBatchReceiver batchReceiver, |
| | | 33 | | ITelegramUpdateDecodeFailurePolicy decodeFailurePolicy, |
| | | 34 | | TimeProvider timeProvider, |
| | | 35 | | ILoggerFactory loggerFactory) |
| | | 36 | | { |
| | 31 | 37 | | ArgumentNullException.ThrowIfNull(batchReceiver); |
| | 31 | 38 | | ArgumentNullException.ThrowIfNull(decodeFailurePolicy); |
| | 31 | 39 | | ArgumentNullException.ThrowIfNull(timeProvider); |
| | 31 | 40 | | ArgumentNullException.ThrowIfNull(loggerFactory); |
| | | 41 | | |
| | 31 | 42 | | _batchReceiver = batchReceiver; |
| | 31 | 43 | | _decodeFailurePolicy = decodeFailurePolicy; |
| | 31 | 44 | | _timeProvider = timeProvider; |
| | 31 | 45 | | _logger = loggerFactory.CreateLogger<TelegramLongPollingClient>(); |
| | 31 | 46 | | } |
| | | 47 | | |
| | | 48 | | public async Task RunAsync( |
| | | 49 | | Func<Update, CancellationToken, Task> updateHandler, |
| | | 50 | | TelegramRawLongPollingOptions? options = null, |
| | | 51 | | CancellationToken cancellationToken = default) |
| | | 52 | | { |
| | 10 | 53 | | ArgumentNullException.ThrowIfNull(updateHandler); |
| | | 54 | | |
| | 10 | 55 | | options ??= new TelegramRawLongPollingOptions(); |
| | 10 | 56 | | TelegramRawLongPollingOptionsValidator.Validate(options); |
| | | 57 | | |
| | 8 | 58 | | long? offset = null; |
| | 8 | 59 | | var backoff = new TelegramRawLongPollingBackoff(options.Backoff); |
| | 8 | 60 | | var allowedUpdates = CopyAllowedUpdates(options.AllowedUpdates); |
| | 8 | 61 | | var connected = false; |
| | 8 | 62 | | var recoveringFromPollingFailure = false; |
| | | 63 | | |
| | 8 | 64 | | LogStart(options, allowedUpdates); |
| | | 65 | | |
| | 15 | 66 | | while (!cancellationToken.IsCancellationRequested) |
| | | 67 | | { |
| | 11 | 68 | | var updates = await GetUpdatesBatchAsync( |
| | 11 | 69 | | offset, |
| | 11 | 70 | | options, |
| | 11 | 71 | | allowedUpdates, |
| | 11 | 72 | | backoff, |
| | 11 | 73 | | () => |
| | 11 | 74 | | { |
| | 11 | 75 | | if (!connected) |
| | 11 | 76 | | { |
| | 8 | 77 | | LogConnected(_logger); |
| | 8 | 78 | | connected = true; |
| | 11 | 79 | | } |
| | 11 | 80 | | |
| | 11 | 81 | | if (recoveringFromPollingFailure) |
| | 11 | 82 | | { |
| | 2 | 83 | | LogGetUpdatesRecovered(_logger); |
| | 2 | 84 | | recoveringFromPollingFailure = false; |
| | 11 | 85 | | } |
| | 11 | 86 | | }, |
| | 3 | 87 | | () => recoveringFromPollingFailure = true, |
| | 11 | 88 | | cancellationToken).ConfigureAwait(false); |
| | | 89 | | |
| | 40 | 90 | | for (var index = 0; index < updates.Count; index++) |
| | | 91 | | { |
| | 13 | 92 | | var item = updates[index]; |
| | 13 | 93 | | if (!item.IsSuccess) |
| | | 94 | | { |
| | 4 | 95 | | await HandleDecodeFailureAsync(item, cancellationToken).ConfigureAwait(false); |
| | 1 | 96 | | offset = item.UpdateId + 1; |
| | 1 | 97 | | continue; |
| | | 98 | | } |
| | | 99 | | |
| | 9 | 100 | | var update = item.Update!; |
| | | 101 | | |
| | 9 | 102 | | if (_logger.IsEnabled(LogLevel.Debug)) |
| | | 103 | | { |
| | 0 | 104 | | var updateType = TelegramRawLongPollingLogFormatter.GetUpdateType(update); |
| | 0 | 105 | | var processingStarted = _timeProvider.GetTimestamp(); |
| | | 106 | | |
| | 0 | 107 | | LogUpdateReceived( |
| | 0 | 108 | | _logger, |
| | 0 | 109 | | update.UpdateId, |
| | 0 | 110 | | updateType, |
| | 0 | 111 | | index + 1, |
| | 0 | 112 | | updates.Count); |
| | | 113 | | |
| | 0 | 114 | | await updateHandler(update, cancellationToken).ConfigureAwait(false); |
| | 0 | 115 | | offset = update.UpdateId + 1; |
| | | 116 | | |
| | 0 | 117 | | LogUpdateAcknowledgedByHandler( |
| | 0 | 118 | | _logger, |
| | 0 | 119 | | update.UpdateId, |
| | 0 | 120 | | updateType, |
| | 0 | 121 | | GetElapsedMilliseconds(processingStarted)); |
| | 0 | 122 | | continue; |
| | | 123 | | } |
| | | 124 | | |
| | 9 | 125 | | await updateHandler(update, cancellationToken).ConfigureAwait(false); |
| | 8 | 126 | | offset = update.UpdateId + 1; |
| | 8 | 127 | | } |
| | 7 | 128 | | } |
| | 4 | 129 | | } |
| | | 130 | | |
| | | 131 | | public async IAsyncEnumerable<TelegramPolledUpdate> GetUpdatesAsync( |
| | | 132 | | TelegramRawLongPollingOptions? options = null, |
| | | 133 | | [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| | | 134 | | { |
| | 19 | 135 | | options ??= new TelegramRawLongPollingOptions(); |
| | 19 | 136 | | TelegramRawLongPollingOptionsValidator.Validate(options); |
| | | 137 | | |
| | 19 | 138 | | long? offset = null; |
| | 19 | 139 | | var backoff = new TelegramRawLongPollingBackoff(options.Backoff); |
| | 19 | 140 | | var allowedUpdates = CopyAllowedUpdates(options.AllowedUpdates); |
| | 19 | 141 | | var connected = false; |
| | 19 | 142 | | var recoveringFromPollingFailure = false; |
| | | 143 | | |
| | 19 | 144 | | LogStart(options, allowedUpdates); |
| | | 145 | | |
| | 38 | 146 | | while (!cancellationToken.IsCancellationRequested) |
| | | 147 | | { |
| | 24 | 148 | | var updates = await GetUpdatesBatchAsync( |
| | 24 | 149 | | offset, |
| | 24 | 150 | | options, |
| | 24 | 151 | | allowedUpdates, |
| | 24 | 152 | | backoff, |
| | 24 | 153 | | () => |
| | 24 | 154 | | { |
| | 23 | 155 | | if (!connected) |
| | 24 | 156 | | { |
| | 18 | 157 | | LogConnected(_logger); |
| | 18 | 158 | | connected = true; |
| | 24 | 159 | | } |
| | 24 | 160 | | |
| | 23 | 161 | | if (recoveringFromPollingFailure) |
| | 24 | 162 | | { |
| | 4 | 163 | | LogGetUpdatesRecovered(_logger); |
| | 4 | 164 | | recoveringFromPollingFailure = false; |
| | 24 | 165 | | } |
| | 23 | 166 | | }, |
| | 5 | 167 | | () => recoveringFromPollingFailure = true, |
| | 24 | 168 | | cancellationToken).ConfigureAwait(false); |
| | | 169 | | |
| | 82 | 170 | | for (var index = 0; index < updates.Count; index++) |
| | | 171 | | { |
| | 22 | 172 | | var item = updates[index]; |
| | 22 | 173 | | if (!item.IsSuccess) |
| | | 174 | | { |
| | 0 | 175 | | await HandleDecodeFailureAsync(item, cancellationToken).ConfigureAwait(false); |
| | 0 | 176 | | offset = item.UpdateId + 1; |
| | 0 | 177 | | continue; |
| | | 178 | | } |
| | | 179 | | |
| | 22 | 180 | | var update = item.Update!; |
| | 22 | 181 | | var polledUpdate = new TelegramPolledUpdate(update, index + 1, updates.Count); |
| | | 182 | | |
| | 22 | 183 | | var debugEnabled = _logger.IsEnabled(LogLevel.Debug); |
| | 22 | 184 | | var updateType = debugEnabled |
| | 22 | 185 | | ? TelegramRawLongPollingLogFormatter.GetUpdateType(update) |
| | 22 | 186 | | : string.Empty; |
| | | 187 | | |
| | 22 | 188 | | if (debugEnabled) |
| | | 189 | | { |
| | 2 | 190 | | LogStreamUpdateReceived( |
| | 2 | 191 | | _logger, |
| | 2 | 192 | | update.UpdateId, |
| | 2 | 193 | | updateType); |
| | | 194 | | } |
| | | 195 | | |
| | 22 | 196 | | yield return polledUpdate; |
| | | 197 | | |
| | 19 | 198 | | if (!polledUpdate.IsAcknowledged) |
| | | 199 | | { |
| | 1 | 200 | | throw new InvalidOperationException( |
| | 1 | 201 | | "Telegram polled updates must be acknowledged with AcknowledgeAsync before requesting the next u |
| | | 202 | | } |
| | | 203 | | |
| | 18 | 204 | | offset = update.UpdateId + 1; |
| | | 205 | | |
| | 18 | 206 | | if (debugEnabled) |
| | | 207 | | { |
| | 1 | 208 | | LogStreamUpdateAcknowledged( |
| | 1 | 209 | | _logger, |
| | 1 | 210 | | update.UpdateId, |
| | 1 | 211 | | updateType); |
| | | 212 | | } |
| | 18 | 213 | | } |
| | 19 | 214 | | } |
| | 17 | 215 | | } |
| | | 216 | | |
| | | 217 | | private async Task<IReadOnlyList<TelegramUpdateDecodeResult>> GetUpdatesBatchAsync( |
| | | 218 | | long? offset, |
| | | 219 | | TelegramRawLongPollingOptions options, |
| | | 220 | | IReadOnlyList<string>? allowedUpdates, |
| | | 221 | | TelegramRawLongPollingBackoff backoff, |
| | | 222 | | Action onSuccess, |
| | | 223 | | Action onTransientFailure, |
| | | 224 | | CancellationToken cancellationToken) |
| | | 225 | | { |
| | | 226 | | while (true) |
| | | 227 | | { |
| | | 228 | | try |
| | | 229 | | { |
| | 43 | 230 | | var updates = await _batchReceiver.ReceiveAsync( |
| | 43 | 231 | | new GetUpdates |
| | 43 | 232 | | { |
| | 43 | 233 | | Offset = offset, |
| | 43 | 234 | | Limit = options.Limit, |
| | 43 | 235 | | Timeout = options.TimeoutSeconds, |
| | 43 | 236 | | AllowedUpdates = allowedUpdates |
| | 43 | 237 | | }, |
| | 43 | 238 | | cancellationToken).ConfigureAwait(false); |
| | | 239 | | |
| | 34 | 240 | | onSuccess(); |
| | 34 | 241 | | backoff.Reset(); |
| | 34 | 242 | | return updates; |
| | | 243 | | } |
| | 9 | 244 | | catch (Exception exception) when (IsPollingTransient(exception) && !cancellationToken.IsCancellationRequeste |
| | | 245 | | { |
| | 8 | 246 | | var delay = GetPollingRetryDelay(exception, backoff); |
| | 8 | 247 | | onTransientFailure(); |
| | | 248 | | |
| | 8 | 249 | | LogGetUpdatesFailed( |
| | 8 | 250 | | _logger, |
| | 8 | 251 | | exception, |
| | 8 | 252 | | delay); |
| | | 253 | | |
| | 8 | 254 | | await DelayAsync(delay, cancellationToken).ConfigureAwait(false); |
| | 8 | 255 | | } |
| | | 256 | | } |
| | 34 | 257 | | } |
| | | 258 | | |
| | | 259 | | private void LogStart( |
| | | 260 | | TelegramRawLongPollingOptions options, |
| | | 261 | | IReadOnlyList<string>? allowedUpdates) |
| | | 262 | | { |
| | 27 | 263 | | if (!_logger.IsEnabled(LogLevel.Information)) |
| | | 264 | | { |
| | 25 | 265 | | return; |
| | | 266 | | } |
| | | 267 | | |
| | 2 | 268 | | LogStarting( |
| | 2 | 269 | | _logger, |
| | 2 | 270 | | TelegramRawLongPollingLogFormatter.FormatAllowedUpdates(allowedUpdates), |
| | 2 | 271 | | options.TimeoutSeconds, |
| | 2 | 272 | | options.Limit); |
| | 2 | 273 | | } |
| | | 274 | | |
| | | 275 | | private double GetElapsedMilliseconds(long startingTimestamp) |
| | | 276 | | { |
| | 0 | 277 | | return _timeProvider.GetElapsedTime(startingTimestamp).TotalMilliseconds; |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | private ValueTask DelayAsync(TimeSpan delay, CancellationToken cancellationToken) |
| | | 281 | | { |
| | 8 | 282 | | return delay <= TimeSpan.Zero |
| | 8 | 283 | | ? ValueTask.CompletedTask |
| | 8 | 284 | | : new ValueTask(Task.Delay(delay, _timeProvider, cancellationToken)); |
| | | 285 | | } |
| | | 286 | | |
| | | 287 | | private async ValueTask HandleDecodeFailureAsync( |
| | | 288 | | TelegramUpdateDecodeResult item, |
| | | 289 | | CancellationToken cancellationToken) |
| | | 290 | | { |
| | 4 | 291 | | var exception = item.Exception |
| | 4 | 292 | | ?? throw new InvalidOperationException("A failed Telegram update decode result did not contain an exception. |
| | 4 | 293 | | var failure = new TelegramUpdateDecodeFailure( |
| | 4 | 294 | | TelegramUpdateTransport.LongPolling, |
| | 4 | 295 | | item.UpdateId, |
| | 4 | 296 | | item.RawPayloadJson |
| | 4 | 297 | | ?? throw new InvalidOperationException("A failed Telegram update decode result did not contain raw paylo |
| | 4 | 298 | | item.PayloadSha256 |
| | 4 | 299 | | ?? throw new InvalidOperationException("A failed Telegram update decode result did not contain a payload |
| | 4 | 300 | | exception); |
| | | 301 | | |
| | 4 | 302 | | var decision = await _decodeFailurePolicy |
| | 4 | 303 | | .DecideAsync(failure, cancellationToken) |
| | 4 | 304 | | .ConfigureAwait(false); |
| | | 305 | | |
| | | 306 | | switch (decision) |
| | | 307 | | { |
| | | 308 | | case TelegramUpdateDecodeFailureDecision.Stop: |
| | 1 | 309 | | LogUpdateDecodeStopped( |
| | 1 | 310 | | _logger, |
| | 1 | 311 | | exception, |
| | 1 | 312 | | item.UpdateId, |
| | 1 | 313 | | exception.JsonPath, |
| | 1 | 314 | | exception.PayloadSha256); |
| | 1 | 315 | | throw exception; |
| | | 316 | | case TelegramUpdateDecodeFailureDecision.Skip: |
| | 1 | 317 | | LogUpdateDecodeSkipped( |
| | 1 | 318 | | _logger, |
| | 1 | 319 | | item.UpdateId, |
| | 1 | 320 | | exception.JsonPath, |
| | 1 | 321 | | exception.PayloadSha256); |
| | 1 | 322 | | return; |
| | | 323 | | default: |
| | 0 | 324 | | throw new InvalidOperationException( |
| | 0 | 325 | | $"Unsupported Telegram update decode failure decision '{decision}'."); |
| | | 326 | | } |
| | 1 | 327 | | } |
| | | 328 | | |
| | | 329 | | private static string[]? CopyAllowedUpdates(IReadOnlyList<string>? allowedUpdates) |
| | | 330 | | { |
| | 27 | 331 | | return allowedUpdates is null ? null : allowedUpdates.ToArray(); |
| | | 332 | | } |
| | | 333 | | |
| | | 334 | | private static bool IsPollingTransient(Exception exception) |
| | | 335 | | { |
| | 9 | 336 | | return exception is TelegramNetworkException or |
| | 9 | 337 | | TelegramServerException or |
| | 9 | 338 | | TelegramRetryAfterException; |
| | | 339 | | } |
| | | 340 | | |
| | | 341 | | private static TimeSpan GetPollingRetryDelay(Exception exception, TelegramRawLongPollingBackoff backoff) |
| | | 342 | | { |
| | 8 | 343 | | return exception is TelegramRetryAfterException { RetryAfter: { } retryAfter } |
| | 8 | 344 | | ? retryAfter |
| | 8 | 345 | | : backoff.NextDelay(); |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | [LoggerMessage( |
| | | 349 | | EventId = 1, |
| | | 350 | | Level = LogLevel.Information, |
| | | 351 | | Message = "Starting raw Telegram long polling. allowed_updates={AllowedUpdates}, timeout={TimeoutSeconds}s, limi |
| | | 352 | | private static partial void LogStarting( |
| | | 353 | | ILogger logger, |
| | | 354 | | string allowedUpdates, |
| | | 355 | | int timeoutSeconds, |
| | | 356 | | int limit); |
| | | 357 | | |
| | | 358 | | [LoggerMessage( |
| | | 359 | | EventId = 2, |
| | | 360 | | Level = LogLevel.Information, |
| | | 361 | | Message = "Raw Telegram long polling connected.")] |
| | | 362 | | private static partial void LogConnected(ILogger logger); |
| | | 363 | | |
| | | 364 | | [LoggerMessage( |
| | | 365 | | EventId = 3, |
| | | 366 | | Level = LogLevel.Information, |
| | | 367 | | Message = "Raw Telegram long polling getUpdates recovered after transient failures.")] |
| | | 368 | | private static partial void LogGetUpdatesRecovered(ILogger logger); |
| | | 369 | | |
| | | 370 | | [LoggerMessage( |
| | | 371 | | EventId = 4, |
| | | 372 | | Level = LogLevel.Debug, |
| | | 373 | | Message = "Raw Telegram update received. update_id={UpdateId}, type={UpdateType}, batch_index={BatchIndex}/{Batc |
| | | 374 | | private static partial void LogUpdateReceived( |
| | | 375 | | ILogger logger, |
| | | 376 | | long updateId, |
| | | 377 | | string updateType, |
| | | 378 | | int batchIndex, |
| | | 379 | | int batchCount); |
| | | 380 | | |
| | | 381 | | [LoggerMessage( |
| | | 382 | | EventId = 5, |
| | | 383 | | Level = LogLevel.Debug, |
| | | 384 | | Message = "Raw Telegram update acknowledged by handler. update_id={UpdateId}, type={UpdateType}, total_ms={Total |
| | | 385 | | private static partial void LogUpdateAcknowledgedByHandler( |
| | | 386 | | ILogger logger, |
| | | 387 | | long updateId, |
| | | 388 | | string updateType, |
| | | 389 | | double totalElapsedMilliseconds); |
| | | 390 | | |
| | | 391 | | [LoggerMessage( |
| | | 392 | | EventId = 6, |
| | | 393 | | Level = LogLevel.Debug, |
| | | 394 | | Message = "Raw Telegram update received. update_id={UpdateId}, type={UpdateType}.")] |
| | | 395 | | private static partial void LogStreamUpdateReceived( |
| | | 396 | | ILogger logger, |
| | | 397 | | long updateId, |
| | | 398 | | string updateType); |
| | | 399 | | |
| | | 400 | | [LoggerMessage( |
| | | 401 | | EventId = 7, |
| | | 402 | | Level = LogLevel.Debug, |
| | | 403 | | Message = "Raw Telegram update acknowledged. update_id={UpdateId}, type={UpdateType}.")] |
| | | 404 | | private static partial void LogStreamUpdateAcknowledged( |
| | | 405 | | ILogger logger, |
| | | 406 | | long updateId, |
| | | 407 | | string updateType); |
| | | 408 | | |
| | | 409 | | [LoggerMessage( |
| | | 410 | | EventId = 8, |
| | | 411 | | Level = LogLevel.Warning, |
| | | 412 | | Message = "Raw Telegram long polling getUpdates failed. Retrying in {Delay}.")] |
| | | 413 | | private static partial void LogGetUpdatesFailed( |
| | | 414 | | ILogger logger, |
| | | 415 | | Exception exception, |
| | | 416 | | TimeSpan delay); |
| | | 417 | | |
| | | 418 | | [LoggerMessage( |
| | | 419 | | EventId = 9, |
| | | 420 | | Level = LogLevel.Error, |
| | | 421 | | Message = "Telegram update decoding failed and polling was stopped. update_id={UpdateId}, json_path={JsonPath}, |
| | | 422 | | private static partial void LogUpdateDecodeStopped( |
| | | 423 | | ILogger logger, |
| | | 424 | | Exception exception, |
| | | 425 | | long updateId, |
| | | 426 | | string? jsonPath, |
| | | 427 | | string payloadSha256); |
| | | 428 | | |
| | | 429 | | [LoggerMessage( |
| | | 430 | | EventId = 10, |
| | | 431 | | Level = LogLevel.Warning, |
| | | 432 | | Message = "Telegram update decoding failed and the update was skipped by application policy. update_id={UpdateId |
| | | 433 | | private static partial void LogUpdateDecodeSkipped( |
| | | 434 | | ILogger logger, |
| | | 435 | | long updateId, |
| | | 436 | | string? jsonPath, |
| | | 437 | | string payloadSha256); |
| | | 438 | | } |