| | | 1 | | using System.Diagnostics.CodeAnalysis; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using TeleFlow.Framework.Updates; |
| | | 4 | | using TeleFlow.Telegram.Internal.Handlers; |
| | | 5 | | |
| | | 6 | | namespace TeleFlow.Telegram.Internal; |
| | | 7 | | |
| | | 8 | | [SuppressMessage( |
| | | 9 | | "Performance", |
| | | 10 | | "CA1812:Avoid uninstantiated internal classes", |
| | | 11 | | Justification = "The type is instantiated by dependency injection through AddLongPolling.")] |
| | | 12 | | internal sealed partial class TelegramLongPollingUpdateSource : IUpdateSource |
| | | 13 | | { |
| | | 14 | | private readonly ITelegramLongPollingClient _pollingClient; |
| | | 15 | | private readonly ITelegramClient _bot; |
| | | 16 | | private readonly TelegramBotIdentity _botIdentity; |
| | | 17 | | private readonly TelegramLongPollingOptions _options; |
| | | 18 | | private readonly TimeProvider _timeProvider; |
| | | 19 | | private readonly ILogger<TelegramLongPollingUpdateSource> _logger; |
| | | 20 | | private readonly IReadOnlyList<TelegramHandlerDescriptor> _handlerDescriptors; |
| | | 21 | | |
| | | 22 | | public TelegramLongPollingUpdateSource( |
| | | 23 | | ITelegramLongPollingClient pollingClient, |
| | | 24 | | ITelegramClient bot, |
| | | 25 | | TelegramBotIdentity botIdentity, |
| | | 26 | | TelegramLongPollingOptions options, |
| | | 27 | | TimeProvider timeProvider, |
| | | 28 | | ILoggerFactory loggerFactory, |
| | | 29 | | IEnumerable<TelegramHandlerDescriptor> handlerDescriptors) |
| | | 30 | | { |
| | 17 | 31 | | ArgumentNullException.ThrowIfNull(pollingClient); |
| | 17 | 32 | | ArgumentNullException.ThrowIfNull(bot); |
| | 17 | 33 | | ArgumentNullException.ThrowIfNull(botIdentity); |
| | 17 | 34 | | ArgumentNullException.ThrowIfNull(options); |
| | 17 | 35 | | ArgumentNullException.ThrowIfNull(timeProvider); |
| | 17 | 36 | | ArgumentNullException.ThrowIfNull(loggerFactory); |
| | 17 | 37 | | ArgumentNullException.ThrowIfNull(handlerDescriptors); |
| | | 38 | | |
| | 17 | 39 | | _pollingClient = pollingClient; |
| | 17 | 40 | | _bot = bot; |
| | 17 | 41 | | _botIdentity = botIdentity; |
| | 17 | 42 | | _options = options; |
| | 17 | 43 | | _timeProvider = timeProvider; |
| | 17 | 44 | | _logger = loggerFactory.CreateLogger<TelegramLongPollingUpdateSource>(); |
| | 17 | 45 | | _handlerDescriptors = handlerDescriptors.ToArray(); |
| | 17 | 46 | | } |
| | | 47 | | |
| | | 48 | | public async Task StartAsync( |
| | | 49 | | Func<IUpdatePayload, CancellationToken, Task> updateHandler, |
| | | 50 | | CancellationToken cancellationToken = default) |
| | | 51 | | { |
| | 16 | 52 | | ArgumentNullException.ThrowIfNull(updateHandler); |
| | | 53 | | |
| | 16 | 54 | | await _botIdentity.EnsureResolvedAsync(_bot, cancellationToken).ConfigureAwait(false); |
| | | 55 | | |
| | 16 | 56 | | var allowedUpdates = TelegramAllowedUpdatesResolver.Resolve(_options.AllowedUpdates, _handlerDescriptors, _logge |
| | 16 | 57 | | var rawOptions = CreateRawOptions(allowedUpdates); |
| | 16 | 58 | | var connected = false; |
| | | 59 | | |
| | 16 | 60 | | LogStarting( |
| | 16 | 61 | | _logger, |
| | 16 | 62 | | TelegramUpdateLogFormatter.FormatAllowedUpdates(allowedUpdates), |
| | 16 | 63 | | _options.TimeoutSeconds, |
| | 16 | 64 | | _options.Limit); |
| | | 65 | | |
| | | 66 | | try |
| | | 67 | | { |
| | 68 | 68 | | await foreach (var item in _pollingClient.GetUpdatesAsync(rawOptions, cancellationToken).ConfigureAwait(fals |
| | | 69 | | { |
| | 19 | 70 | | if (!connected) |
| | | 71 | | { |
| | 16 | 72 | | LogConnected(_logger); |
| | 16 | 73 | | connected = true; |
| | | 74 | | } |
| | | 75 | | |
| | 19 | 76 | | var update = item.Update; |
| | 19 | 77 | | var informationEnabled = _logger.IsEnabled(LogLevel.Information); |
| | 19 | 78 | | var errorEnabled = _logger.IsEnabled(LogLevel.Error); |
| | 19 | 79 | | var debugEnabled = _logger.IsEnabled(LogLevel.Debug); |
| | 19 | 80 | | string? updateType = null; |
| | 4 | 81 | | string GetUpdateType() => updateType ??= TelegramUpdateLogFormatter.GetUpdateType(update); |
| | 19 | 82 | | var processingStarted = debugEnabled ? _timeProvider.GetTimestamp() : 0; |
| | | 83 | | |
| | 19 | 84 | | if (informationEnabled) |
| | | 85 | | { |
| | 2 | 86 | | LogUpdateReceived( |
| | 2 | 87 | | _logger, |
| | 2 | 88 | | update.UpdateId, |
| | 2 | 89 | | GetUpdateType(), |
| | 2 | 90 | | item.BatchIndex, |
| | 2 | 91 | | item.BatchCount); |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | try |
| | | 95 | | { |
| | 19 | 96 | | await updateHandler(new TelegramUpdatePayload(update), cancellationToken).ConfigureAwait(false); |
| | 17 | 97 | | } |
| | 2 | 98 | | catch (Exception exception) when (!IsUpdateCancellation(exception, cancellationToken)) |
| | | 99 | | { |
| | 1 | 100 | | if (errorEnabled) |
| | | 101 | | { |
| | 0 | 102 | | if (debugEnabled) |
| | | 103 | | { |
| | 0 | 104 | | LogUpdateProcessingFailedWithTiming( |
| | 0 | 105 | | _logger, |
| | 0 | 106 | | exception, |
| | 0 | 107 | | update.UpdateId, |
| | 0 | 108 | | GetUpdateType(), |
| | 0 | 109 | | GetElapsedMilliseconds(processingStarted)); |
| | | 110 | | } |
| | | 111 | | else |
| | | 112 | | { |
| | 0 | 113 | | LogUpdateProcessingFailed( |
| | 0 | 114 | | _logger, |
| | 0 | 115 | | exception, |
| | 0 | 116 | | update.UpdateId, |
| | 0 | 117 | | GetUpdateType()); |
| | | 118 | | } |
| | | 119 | | } |
| | | 120 | | |
| | 1 | 121 | | throw; |
| | | 122 | | } |
| | | 123 | | |
| | 17 | 124 | | await item.AcknowledgeAsync(CancellationToken.None).ConfigureAwait(false); |
| | | 125 | | |
| | 17 | 126 | | if (informationEnabled) |
| | | 127 | | { |
| | 1 | 128 | | LogUpdateProcessed( |
| | 1 | 129 | | _logger, |
| | 1 | 130 | | update.UpdateId, |
| | 1 | 131 | | GetUpdateType()); |
| | | 132 | | } |
| | | 133 | | |
| | 17 | 134 | | if (debugEnabled) |
| | | 135 | | { |
| | 1 | 136 | | LogUpdateProcessedWithTiming( |
| | 1 | 137 | | _logger, |
| | 1 | 138 | | update.UpdateId, |
| | 1 | 139 | | GetUpdateType(), |
| | 1 | 140 | | GetElapsedMilliseconds(processingStarted)); |
| | | 141 | | } |
| | 17 | 142 | | } |
| | 14 | 143 | | } |
| | | 144 | | finally |
| | | 145 | | { |
| | 16 | 146 | | if (cancellationToken.IsCancellationRequested) |
| | | 147 | | { |
| | 15 | 148 | | LogStopped(_logger); |
| | | 149 | | } |
| | | 150 | | } |
| | 14 | 151 | | } |
| | | 152 | | |
| | | 153 | | private TelegramRawLongPollingOptions CreateRawOptions(IReadOnlyList<string>? allowedUpdates) |
| | | 154 | | { |
| | 16 | 155 | | return new TelegramRawLongPollingOptions |
| | 16 | 156 | | { |
| | 16 | 157 | | TimeoutSeconds = _options.TimeoutSeconds, |
| | 16 | 158 | | Limit = _options.Limit, |
| | 16 | 159 | | AllowedUpdates = allowedUpdates, |
| | 16 | 160 | | Backoff = new TelegramRawLongPollingBackoffOptions |
| | 16 | 161 | | { |
| | 16 | 162 | | Enabled = _options.Backoff.Enabled, |
| | 16 | 163 | | MinDelay = _options.Backoff.MinDelay, |
| | 16 | 164 | | MaxDelay = _options.Backoff.MaxDelay, |
| | 16 | 165 | | Factor = _options.Backoff.Factor, |
| | 16 | 166 | | Jitter = _options.Backoff.Jitter |
| | 16 | 167 | | } |
| | 16 | 168 | | }; |
| | | 169 | | } |
| | | 170 | | |
| | | 171 | | private double GetElapsedMilliseconds(long startingTimestamp) |
| | | 172 | | { |
| | 1 | 173 | | return _timeProvider.GetElapsedTime(startingTimestamp).TotalMilliseconds; |
| | | 174 | | } |
| | | 175 | | |
| | | 176 | | private static bool IsUpdateCancellation(Exception exception, CancellationToken cancellationToken) |
| | | 177 | | { |
| | 2 | 178 | | return exception is OperationCanceledException && cancellationToken.IsCancellationRequested; |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | [LoggerMessage( |
| | | 182 | | EventId = 1, |
| | | 183 | | Level = LogLevel.Information, |
| | | 184 | | Message = "Starting Telegram long polling. allowed_updates={AllowedUpdates}, timeout={TimeoutSeconds}s, limit={L |
| | | 185 | | private static partial void LogStarting( |
| | | 186 | | ILogger logger, |
| | | 187 | | string allowedUpdates, |
| | | 188 | | int timeoutSeconds, |
| | | 189 | | int limit); |
| | | 190 | | |
| | | 191 | | [LoggerMessage( |
| | | 192 | | EventId = 2, |
| | | 193 | | Level = LogLevel.Information, |
| | | 194 | | Message = "Telegram long polling connected.")] |
| | | 195 | | private static partial void LogConnected(ILogger logger); |
| | | 196 | | |
| | | 197 | | [LoggerMessage( |
| | | 198 | | EventId = 3, |
| | | 199 | | Level = LogLevel.Information, |
| | | 200 | | Message = "Telegram update received. update_id={UpdateId}, type={UpdateType}, batch_index={BatchIndex}/{BatchCou |
| | | 201 | | private static partial void LogUpdateReceived( |
| | | 202 | | ILogger logger, |
| | | 203 | | long updateId, |
| | | 204 | | string updateType, |
| | | 205 | | int batchIndex, |
| | | 206 | | int batchCount); |
| | | 207 | | |
| | | 208 | | [LoggerMessage( |
| | | 209 | | EventId = 4, |
| | | 210 | | Level = LogLevel.Error, |
| | | 211 | | Message = "Telegram update processing failed. update_id={UpdateId}, type={UpdateType}.")] |
| | | 212 | | private static partial void LogUpdateProcessingFailed( |
| | | 213 | | ILogger logger, |
| | | 214 | | Exception exception, |
| | | 215 | | long updateId, |
| | | 216 | | string updateType); |
| | | 217 | | |
| | | 218 | | [LoggerMessage( |
| | | 219 | | EventId = 4, |
| | | 220 | | Level = LogLevel.Error, |
| | | 221 | | Message = "Telegram update processing failed. update_id={UpdateId}, type={UpdateType}, total_ms={TotalElapsedMil |
| | | 222 | | private static partial void LogUpdateProcessingFailedWithTiming( |
| | | 223 | | ILogger logger, |
| | | 224 | | Exception exception, |
| | | 225 | | long updateId, |
| | | 226 | | string updateType, |
| | | 227 | | double totalElapsedMilliseconds); |
| | | 228 | | |
| | | 229 | | [LoggerMessage( |
| | | 230 | | EventId = 5, |
| | | 231 | | Level = LogLevel.Information, |
| | | 232 | | Message = "Telegram update processed. update_id={UpdateId}, type={UpdateType}.")] |
| | | 233 | | private static partial void LogUpdateProcessed( |
| | | 234 | | ILogger logger, |
| | | 235 | | long updateId, |
| | | 236 | | string updateType); |
| | | 237 | | |
| | | 238 | | [LoggerMessage( |
| | | 239 | | EventId = 5, |
| | | 240 | | Level = LogLevel.Debug, |
| | | 241 | | Message = "Telegram update processed. update_id={UpdateId}, type={UpdateType}, total_ms={TotalElapsedMillisecond |
| | | 242 | | private static partial void LogUpdateProcessedWithTiming( |
| | | 243 | | ILogger logger, |
| | | 244 | | long updateId, |
| | | 245 | | string updateType, |
| | | 246 | | double totalElapsedMilliseconds); |
| | | 247 | | |
| | | 248 | | [LoggerMessage( |
| | | 249 | | EventId = 6, |
| | | 250 | | Level = LogLevel.Information, |
| | | 251 | | Message = "Telegram long polling stopped.")] |
| | | 252 | | private static partial void LogStopped(ILogger logger); |
| | | 253 | | } |