Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/Sentry.Hangfire/GlobalConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ public static IGlobalConfiguration UseSentry(this IGlobalConfiguration configura
}

/// <summary>
/// Adds the Sentry filter that captures check-ins for jobs marked with <see cref="SentryMonitorSlugAttribute"/>.
/// Adds the Sentry filter that captures check-ins for jobs marked with <see cref="SentryMonitorSlugAttribute"/>,
/// or for every recurring job when <see cref="SentryHangfireOptions.MonitorAllRecurringJobs"/> is enabled.
/// </summary>
/// <param name="configuration">The Hangfire configuration.</param>
/// <param name="configureOptions">Configures the Sentry Hangfire integration.</param>
Expand All @@ -44,10 +45,12 @@ public static IGlobalConfiguration UseSentry(this IGlobalConfiguration configura
/// <param name="configuration"></param>
/// <param name="hub"></param>
/// <param name="logger"></param>
/// <param name="options"></param>
/// <returns></returns>
internal static IGlobalConfiguration UseSentry(this IGlobalConfiguration configuration, IHub hub, IDiagnosticLogger logger)
internal static IGlobalConfiguration UseSentry(this IGlobalConfiguration configuration, IHub hub, IDiagnosticLogger logger,
SentryHangfireOptions? options = null)
{
configuration.UseFilter(new SentryServerFilter(hub, logger));
configuration.UseFilter(new SentryServerFilter(hub, logger, options));
return configuration;
}
}
1 change: 1 addition & 0 deletions src/Sentry.Hangfire/Sentry.Hangfire.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<ItemGroup>
<!-- Sentry's internals aren't visible here because this assembly isn't strong-named -->
<Compile Include="..\Sentry\Internal\CrontabValidator.cs" Link="Internal\CrontabValidator.cs" />
<Compile Include="..\Sentry\Internal\MonitorSlug.cs" Link="Internal\MonitorSlug.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
46 changes: 46 additions & 0 deletions src/Sentry.Hangfire/SentryHangfireOptions.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using Sentry.Internal;

namespace Sentry.Hangfire;

/// <summary>
Expand All @@ -23,4 +25,48 @@ public class SentryHangfireOptions
/// </para>
/// </remarks>
public bool SendMonitorConfig { get; set; } = true;

/// <summary>
/// When enabled, every recurring job sends check-ins, not only jobs marked with
/// <see cref="SentryMonitorSlugAttribute"/>. The monitor slug is the recurring job ID, normalized the way Sentry
/// normalizes monitor slugs: lowercased, accents removed, spaces and dashes turned into <c>-</c>, other characters
/// dropped, and cut to 50 characters. Defaults to <c>false</c>.
/// </summary>
/// <remarks>
/// Jobs marked with <see cref="SentryMonitorSlugAttribute"/> keep their monitor slug.
/// Use <see cref="ExcludedRecurringJobs"/> to leave out some recurring jobs.
/// </remarks>
public bool MonitorAllRecurringJobs { get; set; }

/// <summary>
/// Recurring jobs that <see cref="MonitorAllRecurringJobs"/> doesn't send check-ins for. A string matches a
/// recurring job whose ID is equal to it, and a regular expression a recurring job whose ID it matches.
/// </summary>
/// <remarks>
/// Jobs marked with <see cref="SentryMonitorSlugAttribute"/> still send check-ins.
/// </remarks>
public IList<StringOrRegex> ExcludedRecurringJobs { get; set; } = new List<StringOrRegex>();

internal string? GetRecurringJobSlug(string recurringJobId)
Comment thread
wedamija marked this conversation as resolved.
Resolved
{
if (!MonitorAllRecurringJobs || IsExcluded(recurringJobId))
{
return null;
}

return MonitorSlug.From(recurringJobId);
}

private bool IsExcluded(string recurringJobId)
{
foreach (var pattern in ExcludedRecurringJobs)
{
if (pattern.Regex is { } regex ? regex.IsMatch(recurringJobId) : pattern.ToString() == recurringJobId)
{
return true;
}
}

return false;
}
}
33 changes: 27 additions & 6 deletions src/Sentry.Hangfire/SentryServerFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ internal SentryServerFilter(IHub? hub, IDiagnosticLogger? logger, SentryHangfire

public void OnPerforming(PerformingContext context)
{
var monitorSlug = context.GetJobParameter<string>(SentryMonitorSlugKey);
var monitorSlug = GetMonitorSlug(context);
if (monitorSlug is null)
{
var jobType = context.BackgroundJob.Job.Type;
Expand All @@ -58,6 +58,27 @@ public void OnPerforming(PerformingContext context)
// then implicitly OnPerforming was called previously with the same context, but we never made it to OnPerformed
// This might happen if a Hangfire job failed at least once, with automatic retries configured.
context.Items[SentryCheckInIdKey] = checkInId;
context.Items[SentryMonitorSlugKey] = monitorSlug;
}

private string? GetMonitorSlug(PerformContext context)
{
var monitorSlug = context.GetJobParameter<string>(SentryMonitorSlugKey);
if (monitorSlug is not null || !_options.MonitorAllRecurringJobs)
{
return monitorSlug;
}

try
{
var recurringJobId = context.GetJobParameter<string>(RecurringJobIdKey);
return string.IsNullOrEmpty(recurringJobId) ? null : _options.GetRecurringJobSlug(recurringJobId!);
}
catch (Exception e)
{
_logger?.LogError(e, "Failed to read the recurring job ID of job '{0}'.", context.BackgroundJob.Id);
return null;
}
}

private SentryId CaptureInProgressCheckIn(PerformingContext context, string monitorSlug)
Expand Down Expand Up @@ -133,7 +154,7 @@ private RecurringJobSlugs GetRecurringJobSlugs(IStorageConnection connection, st
if (_recurringJobSlugs is not { } slugs || slugs.ReadAt + RecurringJobSlugsTtl <= now
|| !slugs.Contains(recurringJobId))
{
slugs = RecurringJobSlugs.Read(connection, now);
slugs = RecurringJobSlugs.Read(connection, now, _options);
_recurringJobSlugs = slugs;
}

Expand All @@ -156,14 +177,15 @@ private RecurringJobSlugs(DateTimeOffset readAt,
_ids = ids;
}

public static RecurringJobSlugs Read(IStorageConnection connection, DateTimeOffset readAt)
public static RecurringJobSlugs Read(IStorageConnection connection, DateTimeOffset readAt, SentryHangfireOptions options)
{
var jobsBySlug = new Dictionary<string, List<(string Id, string? Cron, string TimeZoneId)>>();
var ids = new HashSet<string>();
foreach (var recurringJob in connection.GetRecurringJobs())
{
ids.Add(recurringJob.Id);
if (recurringJob.Removed || recurringJob.Job is null || GetMonitorSlug(recurringJob.Job) is not { } slug)
if (recurringJob.Removed || recurringJob.Job is null
|| (GetMonitorSlug(recurringJob.Job) ?? options.GetRecurringJobSlug(recurringJob.Id)) is not { } slug)
{
continue;
}
Expand Down Expand Up @@ -295,8 +317,7 @@ static int ToNumber(string value) =>

public void OnPerformed(PerformedContext context)
{
var monitorSlug = context.GetJobParameter<string>(SentryMonitorSlugKey);
if (monitorSlug is null)
if (!context.Items.TryGetValue(SentryMonitorSlugKey, out var monitorSlugObject) || monitorSlugObject is not string monitorSlug)
{
return;
}
Expand Down
32 changes: 3 additions & 29 deletions src/Sentry.Quartz/Core/JobMonitor.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
using Quartz;
using Sentry.Extensibility;
using Sentry.Infrastructure;
using Sentry.Internal;

namespace Sentry.Quartz;

// Captures the check-ins of jobs with SentryMonitorSlugAttribute
internal sealed class JobMonitor
{
private const int MaxSlugLength = 50;

// How long the schedules of all monitored triggers are reused before they're read from the scheduler again
internal static readonly TimeSpan TriggerSchedulesTtl = TimeSpan.FromMinutes(1);

Expand Down Expand Up @@ -320,40 +319,15 @@ private static bool IsMonitored(IJobDetail job)
var key = job.Key;
if (HasIdentity(key))
{
return ToSlug(key.Group == JobKey.DefaultGroup ? key.Name : key.Group + "." + key.Name);
return MonitorSlug.From(key.Group == JobKey.DefaultGroup ? key.Name : key.Group + "-" + key.Name);
}

fromJobType = true;
return ToSlug(QuartzApi.GetJobType(job).Name);
return MonitorSlug.From(QuartzApi.GetJobType(job).Name);
}

// Quartz names a job built without an identity with a new GUID
internal static bool HasIdentity(JobKey key) => !Guid.TryParse(key.Name, out _);

// Produces a slug that Sentry's own slugify leaves unchanged
internal static string? ToSlug(string value)
{
var slug = new StringBuilder(value.Length);
foreach (var c in value.ToLowerInvariant())
{
if (c is >= 'a' and <= 'z' or >= '0' and <= '9' or '_')
{
slug.Append(c);
}
else if (slug.Length > 0 && slug[slug.Length - 1] != '-')
{
slug.Append('-');
}
}

var result = slug.ToString().Trim('-', '_');
if (result.Length > MaxSlugLength)
{
result = result.Substring(0, MaxSlugLength).Trim('-', '_');
}

return result.Length > 0 ? result : null;
}
}

internal sealed class JobCheckIn(string monitorSlug, SentryId id)
Expand Down
4 changes: 2 additions & 2 deletions src/Sentry.Quartz/Core/SentryMonitorSlugAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ namespace Sentry.Quartz;
/// Jobs without this attribute are not monitored.
/// </para>
/// <para>
/// When no monitor slug is given, the slug is the job's key, lowercased with every run of other characters replaced
/// by a hyphen. Jobs in the default group use only the job name: <c>reports.DailyEmail</c> becomes
/// When no monitor slug is given, the slug is the job's group and name joined by a hyphen, normalized the way Sentry
/// normalizes monitor slugs. Jobs in the default group use only the job name: <c>reports.DailyEmail</c> becomes
/// <c>reports-dailyemail</c>, and <c>DEFAULT.Cleanup</c> becomes <c>cleanup</c>. Set <see cref="JobDataKey"/> in the
/// job's or trigger's <c>JobDataMap</c> to use a different slug for that job or trigger.
/// </para>
Expand Down
62 changes: 62 additions & 0 deletions src/Sentry/Internal/MonitorSlug.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System.Text;

namespace Sentry.Internal;

/// <summary>
/// Builds monitor slugs the way Sentry's slugify_monitor_slug does, so Sentry shows the same slug.
/// </summary>
/// <remarks>
/// Also compiled into Sentry.Hangfire, which can't see Sentry's internals because it isn't strong-named.
/// </remarks>
internal static class MonitorSlug
{
private const int MaxLength = 50;

/// <summary>
/// Returns the slug of <paramref name="value"/>, or <c>null</c> when nothing usable is left.
/// </summary>
public static string? From(string value)
{
string normalized;
try
{
normalized = value.Normalize(NormalizationForm.FormKD);
}
catch (PlatformNotSupportedException)
{
// Invariant globalization mode can't normalize non-ASCII text
normalized = value;
}

var slug = new StringBuilder(normalized.Length);
var inSeparator = false;
foreach (var c in normalized)
{
if (c is '-' or ' ' or >= '\t' and <= '\r' or >= '\x1c' and <= '\x1f')
{
if (!inSeparator)
{
slug.Append('-');
inSeparator = true;
}
}
else if (c is >= 'a' and <= 'z' or >= '0' and <= '9' or '_')
{
slug.Append(c);
inSeparator = false;
}
else if (c is >= 'A' and <= 'Z')
{
slug.Append(char.ToLowerInvariant(c));
inSeparator = false;
}
}

var result = slug.ToString().Trim('-', '_');
if (result.Length > MaxLength)
{
result = result.Substring(0, MaxLength).TrimEnd('-');
}
return result.Length > 0 ? result : null;
}
}
5 changes: 5 additions & 0 deletions src/Sentry/StringOrRegex.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ public class StringOrRegex
/// </summary>
public bool IsRegex => _regex is Regex;

/// <summary>
/// The regular expression, or <c>null</c> when this instance contains a plain string.
/// </summary>
public Regex? Regex => _regex;

/// <summary>
/// Constructs a <see cref="StringOrRegex"/> instance.
/// </summary>
Expand Down
8 changes: 7 additions & 1 deletion test/Sentry.Hangfire.Tests/HangfireFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ namespace Sentry.Hangfire.Tests;

public class HangfireFixture : IDisposable
{
public const string ExcludedRecurringJobId = "Excluded Recurring Job";

public IHub Hub { get; set; } = Substitute.For<IHub>();
public IDiagnosticLogger Logger { get; }
private readonly BackgroundJobServer _server;
Expand All @@ -21,7 +23,11 @@ public HangfireFixture()

GlobalConfiguration.Configuration
.UseMemoryStorage()
.UseSentry(Hub, Logger);
.UseSentry(Hub, Logger, new SentryHangfireOptions
{
MonitorAllRecurringJobs = true,
ExcludedRecurringJobs = { ExcludedRecurringJobId }
});
_server = new BackgroundJobServer();
_monitoringApi = JobStorage.Current.GetMonitoringApi();
}
Expand Down
30 changes: 29 additions & 1 deletion test/Sentry.Hangfire.Tests/HangfireTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ public async Task ExecuteJobWithoutAttribute_DoesNotCapturesCheckInButLogs()
await _fixture.Enqueue<TestJob>(job => job.ExecuteJobWithoutAttribute());

_fixture.Hub.DidNotReceive().CaptureCheckIn(Arg.Any<string>(), Arg.Any<CheckInStatus>(), Arg.Is<SentryId>(id => id == sentryId));
_fixture.Logger.Received(1).Log(SentryLevel.Debug, Arg.Is<string>(message => message.Contains("Skipping creating a check-in for")), null, Arg.Any<Type>(), Arg.Any<MethodInfo>());
_fixture.Logger.Received(1).Log(SentryLevel.Debug, Arg.Is<string>(message => message.Contains("Skipping creating a check-in for")), null, Arg.Any<Type>(),
Arg.Is<MethodInfo>(method => method.Name == nameof(TestJob.ExecuteJobWithoutAttribute)));
}

[SkippableFact]
Expand All @@ -78,6 +79,30 @@ public async Task ExecuteRecurringJob_SendMonitorConfigEnabled_CapturesCheckInWi
monitorConfig.GetProperty("timezone").GetString().Should().Be("Europe/Berlin");
}

[Fact]
public async Task ExecuteRecurringJobWithoutAttribute_MonitorAllRecurringJobs_CapturesCheckInsWithJobIdSlug()
{
await _fixture.TriggerRecurringJob<TestJob>("Nightly Cleanup", job => job.ExecuteRecurringJobWithoutAttribute(),
"0 3 * * *", TimeZoneInfo.Utc);

var checkInId = _fixture.Hub.ReceivedInProgressCheckInId("nightly-cleanup");
checkInId.Should().NotBeNull().And.NotBe(SentryId.Empty);
var monitorConfig = MonitorConfigJson.Render(_fixture.Hub.ReceivedConfigureMonitorOptions("nightly-cleanup")!);
monitorConfig.GetProperty("schedule").GetProperty("value").GetString().Should().Be("0 3 * * *");
_fixture.Hub.Received(1).CaptureCheckIn("nightly-cleanup", CheckInStatus.Ok, checkInId,
Arg.Is<TimeSpan?>(duration => duration != null), Arg.Any<Scope>());
}

[Fact]
public async Task ExecuteRecurringJobWithoutAttribute_Excluded_DoesNotCaptureCheckIn()
{
await _fixture.TriggerRecurringJob<TestJob>(HangfireFixture.ExcludedRecurringJobId,
job => job.ExecuteRecurringJobWithoutAttribute(), "0 3 * * *", TimeZoneInfo.Utc);

_fixture.Hub.DidNotReceive().CaptureCheckIn("excluded-recurring-job", Arg.Any<CheckInStatus>(), Arg.Any<SentryId?>(),
Arg.Any<TimeSpan?>(), Arg.Any<Scope?>(), Arg.Any<Action<SentryMonitorOptions>?>());
}

// In this class so it runs serially with the fixture's jobs, which would also pick up the filter it adds
[Fact]
public void UseSentry_ConfigureOptions_AddsFilterWithOptions()
Expand Down Expand Up @@ -127,4 +152,7 @@ public void ExecuteJobWithoutAttribute()
[SentryMonitorSlug("test-recurring-job")]
public void ExecuteRecurringJob()
{ }

public void ExecuteRecurringJobWithoutAttribute()
{ }
}
Loading