| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using TeleFlow.Framework.Dispatching; |
| | | 3 | | using TeleFlow.Framework.States; |
| | | 4 | | using TeleFlow.Framework.Updates; |
| | | 5 | | using TeleFlow.Telegram.Internal; |
| | | 6 | | |
| | | 7 | | namespace TeleFlow.Telegram.Internal.Handlers; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Selects and invokes the Telegram handler for a single update payload. |
| | | 11 | | /// </summary> |
| | | 12 | | internal sealed partial class TelegramHandlerDispatcher : IUpdateDispatcher |
| | | 13 | | { |
| | | 14 | | private readonly TelegramHandlerSelector _selector; |
| | | 15 | | private readonly TelegramErrorHandlerIndex _errorHandlerIndex; |
| | | 16 | | private readonly TimeProvider _timeProvider; |
| | | 17 | | private readonly TelegramAutoAnswerCallbackDescriptor? _globalAutoAnswerCallback; |
| | | 18 | | private readonly ILogger<TelegramHandlerDispatcher> _logger; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Creates a dispatcher from registered handler descriptors and framework services. |
| | | 22 | | /// </summary> |
| | | 23 | | public TelegramHandlerDispatcher( |
| | | 24 | | IEnumerable<TelegramHandlerDescriptor> descriptors, |
| | | 25 | | IEnumerable<TelegramErrorHandlerDescriptor> errorHandlers, |
| | | 26 | | IEnumerable<TelegramAutoAnswerCallbackOptions> autoAnswerCallbackOptions, |
| | | 27 | | TelegramBotIdentity botIdentity, |
| | | 28 | | TimeProvider timeProvider, |
| | | 29 | | ILoggerFactory loggerFactory) |
| | | 30 | | { |
| | 202 | 31 | | ArgumentNullException.ThrowIfNull(descriptors); |
| | 202 | 32 | | ArgumentNullException.ThrowIfNull(errorHandlers); |
| | 202 | 33 | | ArgumentNullException.ThrowIfNull(autoAnswerCallbackOptions); |
| | 202 | 34 | | ArgumentNullException.ThrowIfNull(botIdentity); |
| | 202 | 35 | | ArgumentNullException.ThrowIfNull(timeProvider); |
| | 202 | 36 | | ArgumentNullException.ThrowIfNull(loggerFactory); |
| | | 37 | | |
| | 202 | 38 | | var table = new TelegramHandlerTable(descriptors); |
| | | 39 | | |
| | 201 | 40 | | _selector = new TelegramHandlerSelector(table, botIdentity, loggerFactory); |
| | 201 | 41 | | _errorHandlerIndex = new TelegramErrorHandlerIndex(errorHandlers); |
| | 201 | 42 | | _timeProvider = timeProvider; |
| | 201 | 43 | | _globalAutoAnswerCallback = CreateGlobalAutoAnswerDescriptor(autoAnswerCallbackOptions.LastOrDefault()); |
| | 201 | 44 | | _logger = loggerFactory.CreateLogger<TelegramHandlerDispatcher>(); |
| | 201 | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Dispatches one update through handler selection, invocation, error handlers, and callback auto-answering. |
| | | 49 | | /// </summary> |
| | | 50 | | public async Task DispatchAsync(UpdateContext context, CancellationToken cancellationToken = default) |
| | | 51 | | { |
| | 344 | 52 | | ArgumentNullException.ThrowIfNull(context); |
| | | 53 | | |
| | 344 | 54 | | if (context.Payload is not TelegramUpdatePayload payload) |
| | | 55 | | { |
| | 0 | 56 | | return; |
| | | 57 | | } |
| | | 58 | | |
| | 344 | 59 | | var routeLoggingEnabled = _logger.IsEnabled(LogLevel.Information); |
| | 344 | 60 | | var debugEnabled = _logger.IsEnabled(LogLevel.Debug); |
| | 344 | 61 | | string? updateType = null; |
| | 31 | 62 | | string GetUpdateType() => updateType ??= TelegramUpdateLogFormatter.GetUpdateType(payload.Update); |
| | | 63 | | |
| | 344 | 64 | | var effectiveCancellationToken = cancellationToken.CanBeCanceled |
| | 344 | 65 | | ? cancellationToken |
| | 344 | 66 | | : context.CancellationToken; |
| | 344 | 67 | | var currentState = _selector.HasStatefulHandlers |
| | 344 | 68 | | ? await GetCurrentStateAsync(context, effectiveCancellationToken).ConfigureAwait(false) |
| | 344 | 69 | | : null; |
| | 344 | 70 | | var matchStarted = debugEnabled ? _timeProvider.GetTimestamp() : 0; |
| | 344 | 71 | | TelegramRouteSelection? selection = null; |
| | 344 | 72 | | TelegramUpdateContext? telegramContext = null; |
| | | 73 | | |
| | 344 | 74 | | if (payload.Update.Message is not null) |
| | | 75 | | { |
| | 258 | 76 | | var messageContext = context.GetMessageContext(); |
| | 258 | 77 | | selection = await _selector.SelectMessageHandlerAsync( |
| | 258 | 78 | | messageContext, |
| | 258 | 79 | | currentState, |
| | 258 | 80 | | effectiveCancellationToken).ConfigureAwait(false); |
| | 256 | 81 | | telegramContext = messageContext; |
| | 256 | 82 | | } |
| | | 83 | | |
| | 342 | 84 | | if (selection is null && payload.Update.CallbackQuery is not null) |
| | | 85 | | { |
| | 72 | 86 | | var callbackContext = context.GetCallbackQueryContext(); |
| | 72 | 87 | | selection = await _selector.SelectCallbackHandlerAsync( |
| | 72 | 88 | | callbackContext, |
| | 72 | 89 | | currentState, |
| | 72 | 90 | | effectiveCancellationToken).ConfigureAwait(false); |
| | 70 | 91 | | telegramContext = callbackContext; |
| | 70 | 92 | | } |
| | | 93 | | |
| | 340 | 94 | | if (selection is null && (payload.Update.ChatMember is not null || payload.Update.MyChatMember is not null)) |
| | | 95 | | { |
| | 14 | 96 | | var chatMemberContext = context.GetChatMemberUpdatedContext(); |
| | 14 | 97 | | var routeKind = payload.Update.ChatMember is not null |
| | 14 | 98 | | ? TelegramRouteKind.ChatMemberUpdated |
| | 14 | 99 | | : TelegramRouteKind.MyChatMemberUpdated; |
| | 14 | 100 | | selection = await _selector.SelectChatMemberHandlerAsync( |
| | 14 | 101 | | chatMemberContext, |
| | 14 | 102 | | routeKind, |
| | 14 | 103 | | currentState, |
| | 14 | 104 | | effectiveCancellationToken).ConfigureAwait(false); |
| | 14 | 105 | | telegramContext = chatMemberContext; |
| | 14 | 106 | | } |
| | | 107 | | |
| | 340 | 108 | | var matchElapsedMilliseconds = debugEnabled ? GetElapsedMilliseconds(matchStarted) : 0; |
| | | 109 | | |
| | 340 | 110 | | if (selection is null || telegramContext is null) |
| | | 111 | | { |
| | 18 | 112 | | if (debugEnabled) |
| | | 113 | | { |
| | 1 | 114 | | LogNoHandlerMatchedWithTiming( |
| | 1 | 115 | | _logger, |
| | 1 | 116 | | payload.Update.UpdateId, |
| | 1 | 117 | | GetUpdateType(), |
| | 1 | 118 | | matchElapsedMilliseconds); |
| | | 119 | | } |
| | 17 | 120 | | else if (routeLoggingEnabled) |
| | | 121 | | { |
| | 1 | 122 | | LogNoHandlerMatched( |
| | 1 | 123 | | _logger, |
| | 1 | 124 | | payload.Update.UpdateId, |
| | 1 | 125 | | GetUpdateType()); |
| | | 126 | | } |
| | | 127 | | |
| | 18 | 128 | | return; |
| | | 129 | | } |
| | | 130 | | |
| | 322 | 131 | | string? handlerName = null; |
| | 322 | 132 | | string? routeName = null; |
| | 29 | 133 | | string GetHandlerName() => handlerName ??= TelegramUpdateLogFormatter.FormatHandler(selection.Handler); |
| | 29 | 134 | | string GetRouteName() => routeName ??= TelegramUpdateLogFormatter.FormatRoute(selection.Route); |
| | | 135 | | |
| | 322 | 136 | | if (debugEnabled) |
| | | 137 | | { |
| | 10 | 138 | | LogHandlerMatchedWithTiming( |
| | 10 | 139 | | _logger, |
| | 10 | 140 | | payload.Update.UpdateId, |
| | 10 | 141 | | GetUpdateType(), |
| | 10 | 142 | | GetHandlerName(), |
| | 10 | 143 | | GetRouteName(), |
| | 10 | 144 | | selection.Handler.ModuleName ?? string.Empty, |
| | 10 | 145 | | selection.Handler.SceneName ?? string.Empty, |
| | 10 | 146 | | matchElapsedMilliseconds); |
| | | 147 | | } |
| | 312 | 148 | | else if (routeLoggingEnabled) |
| | | 149 | | { |
| | 6 | 150 | | LogHandlerMatched( |
| | 6 | 151 | | _logger, |
| | 6 | 152 | | payload.Update.UpdateId, |
| | 6 | 153 | | GetUpdateType(), |
| | 6 | 154 | | GetHandlerName(), |
| | 6 | 155 | | GetRouteName(), |
| | 6 | 156 | | selection.Handler.ModuleName ?? string.Empty, |
| | 6 | 157 | | selection.Handler.SceneName ?? string.Empty); |
| | | 158 | | } |
| | | 159 | | |
| | 322 | 160 | | var handlerTimingEnabled = debugEnabled; |
| | 322 | 161 | | var handlerStarted = handlerTimingEnabled ? _timeProvider.GetTimestamp() : 0; |
| | 322 | 162 | | using var requestTimingScope = handlerTimingEnabled |
| | 322 | 163 | | ? TelegramHandlerRequestTimingScope.Begin() |
| | 322 | 164 | | : null; |
| | | 165 | | |
| | | 166 | | try |
| | | 167 | | { |
| | 322 | 168 | | await TelegramHandlerInvoker.InvokeAsync( |
| | 322 | 169 | | selection, |
| | 322 | 170 | | telegramContext, |
| | 322 | 171 | | effectiveCancellationToken).ConfigureAwait(false); |
| | | 172 | | |
| | 297 | 173 | | await AutoAnswerCallbackAsync( |
| | 297 | 174 | | selection.Handler, |
| | 297 | 175 | | telegramContext, |
| | 297 | 176 | | effectiveCancellationToken).ConfigureAwait(false); |
| | 295 | 177 | | } |
| | 27 | 178 | | catch (Exception exception) when (!IsUpdateCancellation(exception, effectiveCancellationToken)) |
| | | 179 | | { |
| | 26 | 180 | | RouteExecutionFailureLogContext? logContext = null; |
| | | 181 | | RouteExecutionFailureLogContext GetLogContext() |
| | | 182 | | { |
| | 6 | 183 | | logContext ??= new RouteExecutionFailureLogContext( |
| | 6 | 184 | | payload.Update.UpdateId, |
| | 6 | 185 | | GetUpdateType(), |
| | 6 | 186 | | GetHandlerName(), |
| | 6 | 187 | | GetRouteName(), |
| | 6 | 188 | | selection.Handler.ModuleName ?? string.Empty, |
| | 6 | 189 | | selection.Handler.SceneName ?? string.Empty, |
| | 6 | 190 | | exception.GetType().FullName ?? exception.GetType().Name); |
| | | 191 | | |
| | 6 | 192 | | return logContext.Value; |
| | | 193 | | } |
| | | 194 | | |
| | 26 | 195 | | if (_logger.IsEnabled(LogLevel.Error)) |
| | | 196 | | { |
| | 5 | 197 | | LogRouteExecutionFailure( |
| | 5 | 198 | | exception, |
| | 5 | 199 | | GetLogContext(), |
| | 5 | 200 | | handlerTimingEnabled, |
| | 5 | 201 | | handlerStarted, |
| | 5 | 202 | | requestTimingScope); |
| | | 203 | | } |
| | | 204 | | |
| | 26 | 205 | | if (_errorHandlerIndex.HasHandlers && |
| | 26 | 206 | | await TryHandleErrorAsync( |
| | 26 | 207 | | selection, |
| | 26 | 208 | | telegramContext, |
| | 26 | 209 | | exception, |
| | 26 | 210 | | debugEnabled ? GetLogContext() : null, |
| | 26 | 211 | | effectiveCancellationToken).ConfigureAwait(false)) |
| | | 212 | | { |
| | 18 | 213 | | return; |
| | | 214 | | } |
| | | 215 | | |
| | 7 | 216 | | throw; |
| | | 217 | | } |
| | | 218 | | |
| | 295 | 219 | | if (!handlerTimingEnabled) |
| | | 220 | | { |
| | 287 | 221 | | return; |
| | | 222 | | } |
| | | 223 | | |
| | 8 | 224 | | var completedHandlerElapsed = _timeProvider.GetElapsedTime(handlerStarted); |
| | 8 | 225 | | var completedTiming = requestTimingScope!.CreateSummary(_timeProvider, completedHandlerElapsed); |
| | | 226 | | |
| | 8 | 227 | | LogRouteExecutionCompleted( |
| | 8 | 228 | | _logger, |
| | 8 | 229 | | payload.Update.UpdateId, |
| | 8 | 230 | | GetUpdateType(), |
| | 8 | 231 | | GetHandlerName(), |
| | 8 | 232 | | GetRouteName(), |
| | 8 | 233 | | completedHandlerElapsed.TotalMilliseconds, |
| | 8 | 234 | | completedTiming.RequestCount, |
| | 8 | 235 | | completedTiming.RequestElapsedMilliseconds, |
| | 8 | 236 | | completedTiming.HandlerLogicElapsedMilliseconds); |
| | 331 | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <summary> |
| | | 240 | | /// Reads current state only when the selector contains stateful handlers. |
| | | 241 | | /// </summary> |
| | | 242 | | private static async ValueTask<string?> GetCurrentStateAsync( |
| | | 243 | | UpdateContext context, |
| | | 244 | | CancellationToken cancellationToken) |
| | | 245 | | { |
| | 81 | 246 | | return context.TryGetState(out var state) |
| | 81 | 247 | | ? await state.GetAsync(cancellationToken).ConfigureAwait(false) |
| | 81 | 248 | | : null; |
| | 81 | 249 | | } |
| | | 250 | | |
| | | 251 | | /// <summary> |
| | | 252 | | /// Returns elapsed milliseconds from a timestamp captured by the dispatcher time provider. |
| | | 253 | | /// </summary> |
| | | 254 | | private double GetElapsedMilliseconds(long startingTimestamp) |
| | | 255 | | { |
| | 11 | 256 | | return _timeProvider.GetElapsedTime(startingTimestamp).TotalMilliseconds; |
| | | 257 | | } |
| | | 258 | | |
| | | 259 | | /// <summary> |
| | | 260 | | /// Sends the configured callback answer after a callback handler when the handler did not answer it explicitly. |
| | | 261 | | /// </summary> |
| | | 262 | | private async Task AutoAnswerCallbackAsync( |
| | | 263 | | TelegramHandlerDescriptor handler, |
| | | 264 | | TelegramUpdateContext context, |
| | | 265 | | CancellationToken cancellationToken) |
| | | 266 | | { |
| | 297 | 267 | | if (context is not CallbackQueryContext callbackContext || |
| | 297 | 268 | | callbackContext.IsCallbackQueryAnswered) |
| | | 269 | | { |
| | 234 | 270 | | return; |
| | | 271 | | } |
| | | 272 | | |
| | 63 | 273 | | var autoAnswer = handler.AutoAnswerCallback ?? _globalAutoAnswerCallback; |
| | | 274 | | |
| | 63 | 275 | | if (autoAnswer is not { Enabled: true }) |
| | | 276 | | { |
| | 57 | 277 | | return; |
| | | 278 | | } |
| | | 279 | | |
| | 6 | 280 | | await callbackContext.Callback.AnswerAsync( |
| | 6 | 281 | | autoAnswer.Text, |
| | 6 | 282 | | autoAnswer.ShowAlert ? true : null, |
| | 6 | 283 | | cancellationToken).ConfigureAwait(false); |
| | 295 | 284 | | } |
| | | 285 | | |
| | | 286 | | /// <summary> |
| | | 287 | | /// Tries registered Telegram error handlers in deterministic priority order. |
| | | 288 | | /// </summary> |
| | | 289 | | private async ValueTask<bool> TryHandleErrorAsync( |
| | | 290 | | TelegramRouteSelection selection, |
| | | 291 | | TelegramUpdateContext telegramContext, |
| | | 292 | | Exception exception, |
| | | 293 | | RouteExecutionFailureLogContext? logContext, |
| | | 294 | | CancellationToken cancellationToken) |
| | | 295 | | { |
| | 21 | 296 | | var errorContext = new TelegramErrorContext( |
| | 21 | 297 | | exception, |
| | 21 | 298 | | telegramContext, |
| | 21 | 299 | | selection.Handler.HandlerType, |
| | 21 | 300 | | selection.Handler.MethodName, |
| | 21 | 301 | | selection.Handler.ModuleName, |
| | 21 | 302 | | selection.Handler.SceneName, |
| | 21 | 303 | | selection.RouteValues); |
| | | 304 | | |
| | 67 | 305 | | foreach (var errorHandler in _errorHandlerIndex.GetCandidates(selection, telegramContext, exception)) |
| | | 306 | | { |
| | 22 | 307 | | var result = await TelegramErrorHandlerInvoker.InvokeAsync( |
| | 22 | 308 | | errorHandler, |
| | 22 | 309 | | errorContext, |
| | 22 | 310 | | telegramContext, |
| | 22 | 311 | | exception, |
| | 22 | 312 | | selection.RouteValues, |
| | 22 | 313 | | cancellationToken).ConfigureAwait(false); |
| | 21 | 314 | | var handled = result == TelegramErrorHandlingResult.Handled; |
| | | 315 | | |
| | 21 | 316 | | if (logContext is { } context) |
| | | 317 | | { |
| | 1 | 318 | | LogErrorHandlerCompleted( |
| | 1 | 319 | | _logger, |
| | 1 | 320 | | context.UpdateId, |
| | 1 | 321 | | context.UpdateType, |
| | 1 | 322 | | context.Handler, |
| | 1 | 323 | | context.Route, |
| | 1 | 324 | | context.ModuleName, |
| | 1 | 325 | | context.SceneName, |
| | 1 | 326 | | context.ExceptionType, |
| | 1 | 327 | | FormatErrorHandler(errorHandler), |
| | 1 | 328 | | handled); |
| | | 329 | | } |
| | | 330 | | |
| | 21 | 331 | | if (handled) |
| | | 332 | | { |
| | 18 | 333 | | return true; |
| | | 334 | | } |
| | 3 | 335 | | } |
| | | 336 | | |
| | 2 | 337 | | return false; |
| | 20 | 338 | | } |
| | | 339 | | |
| | | 340 | | /// <summary> |
| | | 341 | | /// Determines whether an exception represents cancellation requested for the current update. |
| | | 342 | | /// </summary> |
| | | 343 | | private static bool IsUpdateCancellation(Exception exception, CancellationToken cancellationToken) |
| | | 344 | | { |
| | 27 | 345 | | return exception is OperationCanceledException && cancellationToken.IsCancellationRequested; |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | /// <summary> |
| | | 349 | | /// Formats an error handler name for diagnostic logs. |
| | | 350 | | /// </summary> |
| | | 351 | | private static string FormatErrorHandler(TelegramErrorHandlerDescriptor handler) |
| | | 352 | | { |
| | 1 | 353 | | return $"{handler.HandlerType.Name}.{handler.MethodName}"; |
| | | 354 | | } |
| | | 355 | | |
| | | 356 | | /// <summary> |
| | | 357 | | /// Converts global callback auto-answer options to the descriptor used by the dispatcher. |
| | | 358 | | /// </summary> |
| | | 359 | | private static TelegramAutoAnswerCallbackDescriptor? CreateGlobalAutoAnswerDescriptor( |
| | | 360 | | TelegramAutoAnswerCallbackOptions? options) |
| | | 361 | | { |
| | 201 | 362 | | return options is null |
| | 201 | 363 | | ? null |
| | 201 | 364 | | : new TelegramAutoAnswerCallbackDescriptor(options.Enabled, options.Text, options.ShowAlert); |
| | | 365 | | } |
| | | 366 | | |
| | | 367 | | } |