< Summary

Information
Class: OzonOrdersWeb.Observability.HangfireFailureTelegramFilter
Assembly: OzonOrdersWeb
File(s): /home/runner/work/Studio2Prod/Studio2Prod/OzonOrdersWeb/Observability/HangfireFailureTelegramFilter.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 29
Coverable lines: 29
Total lines: 67
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 28
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)0%620%
.cctor()100%210%
OnPerforming(...)100%210%
OnPerformed(...)0%342180%
ShouldSend(...)0%7280%

File(s)

/home/runner/work/Studio2Prod/Studio2Prod/OzonOrdersWeb/Observability/HangfireFailureTelegramFilter.cs

#LineLine coverage
 1using System.Collections.Concurrent;
 2using Hangfire.Common;
 3using Hangfire.Server;
 4using Services.ApiServices.TelegramBotApi;
 5
 6namespace OzonOrdersWeb.Observability;
 7
 8/// <summary>
 9/// Отправляет в Telegram необработанные исключения Hangfire-джобов. Отмена и остановка сервера ошибкой не считаются.
 10/// Повторы одной и той же джобы глушатся на <see cref="Cooldown"/>, чтобы падающий каждую минуту recurring не заспамил 
 11/// </summary>
 012public sealed class HangfireFailureTelegramFilter(IServiceProvider services, TimeSpan? cooldown = null) : JobFilterAttri
 13{
 014    private static readonly ConcurrentDictionary<string, DateTime> LastSentUtc = new();
 015    private readonly TimeSpan Cooldown = cooldown ?? TimeSpan.FromMinutes(30);
 16
 17    public void OnPerforming(PerformingContext filterContext)
 18    {
 019    }
 20
 21    public void OnPerformed(PerformedContext filterContext)
 22    {
 023        var ex = filterContext.Exception;
 024        if (ex is null || filterContext.ExceptionHandled) return;
 025        if (ex is OperationCanceledException ||
 026            (ex is AggregateException agg && agg.InnerExceptions.All(e => e is OperationCanceledException))) return;
 27
 028        var job = filterContext.BackgroundJob.Job;
 029        var jobName = $"{job.Type.Name}.{job.Method.Name}";
 030        if (!ShouldSend(jobName, DateTime.UtcNow)) return;
 31
 32        try
 33        {
 034            var notifier = services.GetService<ITelegramNotifier>();
 035            if (notifier is not { IsConfigured: true }) return;
 36
 037            var retry = filterContext.GetJobParameter<int>("RetryCount");
 038            var message = TelegramMessageFactory.Exception($"Hangfire: {jobName}", ex,
 039                new Dictionary<string, string?>
 040                {
 041                    ["Job Id"] = filterContext.BackgroundJob.Id,
 042                    ["Попытка"] = retry > 0 ? (retry + 1).ToString() : null
 043                });
 44            // Не ждём Telegram: воркер освобождается сразу. SendAsync исключений не бросает.
 045            _ = notifier.SendAsync(message);
 046        }
 047        catch
 48        {
 49            // Уведомление не должно влиять на выполнение джобов.
 050        }
 051    }
 52
 53    private bool ShouldSend(string jobName, DateTime nowUtc)
 54    {
 55        while (true)
 56        {
 057            if (!LastSentUtc.TryGetValue(jobName, out var last))
 58            {
 059                if (LastSentUtc.TryAdd(jobName, nowUtc)) return true;
 60                continue;
 61            }
 62
 063            if (nowUtc - last < Cooldown) return false;
 064            if (LastSentUtc.TryUpdate(jobName, nowUtc, last)) return true;
 65        }
 66    }
 67}