diff --git a/src/Sentry.Hangfire/GlobalConfigurationExtensions.cs b/src/Sentry.Hangfire/GlobalConfigurationExtensions.cs
index fee90a9359..20738e519d 100644
--- a/src/Sentry.Hangfire/GlobalConfigurationExtensions.cs
+++ b/src/Sentry.Hangfire/GlobalConfigurationExtensions.cs
@@ -20,7 +20,8 @@ public static IGlobalConfiguration UseSentry(this IGlobalConfiguration configura
}
///
- /// Adds the Sentry filter that captures check-ins for jobs marked with .
+ /// Adds the Sentry filter that captures check-ins for jobs marked with ,
+ /// or for every recurring job when is enabled.
///
/// The Hangfire configuration.
/// Configures the Sentry Hangfire integration.
@@ -44,10 +45,12 @@ public static IGlobalConfiguration UseSentry(this IGlobalConfiguration configura
///
///
///
+ ///
///
- 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;
}
}
diff --git a/src/Sentry.Hangfire/Sentry.Hangfire.csproj b/src/Sentry.Hangfire/Sentry.Hangfire.csproj
index ff3b319e63..d3c8dfb1aa 100644
--- a/src/Sentry.Hangfire/Sentry.Hangfire.csproj
+++ b/src/Sentry.Hangfire/Sentry.Hangfire.csproj
@@ -22,6 +22,7 @@
+
diff --git a/src/Sentry.Hangfire/SentryHangfireOptions.cs b/src/Sentry.Hangfire/SentryHangfireOptions.cs
index fc5419a84d..d8d72018d2 100644
--- a/src/Sentry.Hangfire/SentryHangfireOptions.cs
+++ b/src/Sentry.Hangfire/SentryHangfireOptions.cs
@@ -1,3 +1,5 @@
+using Sentry.Internal;
+
namespace Sentry.Hangfire;
///
@@ -23,4 +25,48 @@ public class SentryHangfireOptions
///
///
public bool SendMonitorConfig { get; set; } = true;
+
+ ///
+ /// When enabled, every recurring job sends check-ins, not only jobs marked with
+ /// . The monitor slug is the recurring job ID, normalized the way Sentry
+ /// normalizes monitor slugs: lowercased, accents removed, spaces and dashes turned into -, other characters
+ /// dropped, and cut to 50 characters. Defaults to false.
+ ///
+ ///
+ /// Jobs marked with keep their monitor slug.
+ /// Use to leave out some recurring jobs.
+ ///
+ public bool MonitorAllRecurringJobs { get; set; }
+
+ ///
+ /// Recurring jobs that 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.
+ ///
+ ///
+ /// Jobs marked with still send check-ins.
+ ///
+ public IList ExcludedRecurringJobs { get; set; } = new List();
+
+ internal string? GetRecurringJobSlug(string recurringJobId)
+ {
+ 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;
+ }
}
diff --git a/src/Sentry.Hangfire/SentryServerFilter.cs b/src/Sentry.Hangfire/SentryServerFilter.cs
index fed803cc24..2ca302bf73 100644
--- a/src/Sentry.Hangfire/SentryServerFilter.cs
+++ b/src/Sentry.Hangfire/SentryServerFilter.cs
@@ -41,7 +41,7 @@ internal SentryServerFilter(IHub? hub, IDiagnosticLogger? logger, SentryHangfire
public void OnPerforming(PerformingContext context)
{
- var monitorSlug = context.GetJobParameter(SentryMonitorSlugKey);
+ var monitorSlug = GetMonitorSlug(context);
if (monitorSlug is null)
{
var jobType = context.BackgroundJob.Job.Type;
@@ -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(SentryMonitorSlugKey);
+ if (monitorSlug is not null || !_options.MonitorAllRecurringJobs)
+ {
+ return monitorSlug;
+ }
+
+ try
+ {
+ var recurringJobId = context.GetJobParameter(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)
@@ -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;
}
@@ -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>();
var ids = new HashSet();
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;
}
@@ -295,8 +317,7 @@ static int ToNumber(string value) =>
public void OnPerformed(PerformedContext context)
{
- var monitorSlug = context.GetJobParameter(SentryMonitorSlugKey);
- if (monitorSlug is null)
+ if (!context.Items.TryGetValue(SentryMonitorSlugKey, out var monitorSlugObject) || monitorSlugObject is not string monitorSlug)
{
return;
}
diff --git a/src/Sentry.Quartz/Core/JobMonitor.cs b/src/Sentry.Quartz/Core/JobMonitor.cs
index 430c243af0..a73d79dfe0 100644
--- a/src/Sentry.Quartz/Core/JobMonitor.cs
+++ b/src/Sentry.Quartz/Core/JobMonitor.cs
@@ -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);
@@ -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)
diff --git a/src/Sentry.Quartz/Core/SentryMonitorSlugAttribute.cs b/src/Sentry.Quartz/Core/SentryMonitorSlugAttribute.cs
index c21f4eb13a..0aead11422 100644
--- a/src/Sentry.Quartz/Core/SentryMonitorSlugAttribute.cs
+++ b/src/Sentry.Quartz/Core/SentryMonitorSlugAttribute.cs
@@ -8,8 +8,8 @@ namespace Sentry.Quartz;
/// Jobs without this attribute are not monitored.
///
///
-/// 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: reports.DailyEmail 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: reports.DailyEmail becomes
/// reports-dailyemail, and DEFAULT.Cleanup becomes cleanup. Set in the
/// job's or trigger's JobDataMap to use a different slug for that job or trigger.
///
diff --git a/src/Sentry/Internal/MonitorSlug.cs b/src/Sentry/Internal/MonitorSlug.cs
new file mode 100644
index 0000000000..080058b095
--- /dev/null
+++ b/src/Sentry/Internal/MonitorSlug.cs
@@ -0,0 +1,62 @@
+using System.Text;
+
+namespace Sentry.Internal;
+
+///
+/// Builds monitor slugs the way Sentry's slugify_monitor_slug does, so Sentry shows the same slug.
+///
+///
+/// Also compiled into Sentry.Hangfire, which can't see Sentry's internals because it isn't strong-named.
+///
+internal static class MonitorSlug
+{
+ private const int MaxLength = 50;
+
+ ///
+ /// Returns the slug of , or null when nothing usable is left.
+ ///
+ 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;
+ }
+}
diff --git a/src/Sentry/StringOrRegex.cs b/src/Sentry/StringOrRegex.cs
index c8e316f8e8..40cf266acc 100644
--- a/src/Sentry/StringOrRegex.cs
+++ b/src/Sentry/StringOrRegex.cs
@@ -16,6 +16,11 @@ public class StringOrRegex
///
public bool IsRegex => _regex is Regex;
+ ///
+ /// The regular expression, or null when this instance contains a plain string.
+ ///
+ public Regex? Regex => _regex;
+
///
/// Constructs a instance.
///
diff --git a/test/Sentry.Hangfire.Tests/HangfireFixture.cs b/test/Sentry.Hangfire.Tests/HangfireFixture.cs
index 3b9f5cd0f9..8176bc7dc2 100644
--- a/test/Sentry.Hangfire.Tests/HangfireFixture.cs
+++ b/test/Sentry.Hangfire.Tests/HangfireFixture.cs
@@ -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();
public IDiagnosticLogger Logger { get; }
private readonly BackgroundJobServer _server;
@@ -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();
}
diff --git a/test/Sentry.Hangfire.Tests/HangfireTests.cs b/test/Sentry.Hangfire.Tests/HangfireTests.cs
index 2efbc1a391..12fa595fa7 100644
--- a/test/Sentry.Hangfire.Tests/HangfireTests.cs
+++ b/test/Sentry.Hangfire.Tests/HangfireTests.cs
@@ -58,7 +58,8 @@ public async Task ExecuteJobWithoutAttribute_DoesNotCapturesCheckInButLogs()
await _fixture.Enqueue(job => job.ExecuteJobWithoutAttribute());
_fixture.Hub.DidNotReceive().CaptureCheckIn(Arg.Any(), Arg.Any(), Arg.Is(id => id == sentryId));
- _fixture.Logger.Received(1).Log(SentryLevel.Debug, Arg.Is(message => message.Contains("Skipping creating a check-in for")), null, Arg.Any(), Arg.Any());
+ _fixture.Logger.Received(1).Log(SentryLevel.Debug, Arg.Is(message => message.Contains("Skipping creating a check-in for")), null, Arg.Any(),
+ Arg.Is(method => method.Name == nameof(TestJob.ExecuteJobWithoutAttribute)));
}
[SkippableFact]
@@ -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("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(duration => duration != null), Arg.Any());
+ }
+
+ [Fact]
+ public async Task ExecuteRecurringJobWithoutAttribute_Excluded_DoesNotCaptureCheckIn()
+ {
+ await _fixture.TriggerRecurringJob(HangfireFixture.ExcludedRecurringJobId,
+ job => job.ExecuteRecurringJobWithoutAttribute(), "0 3 * * *", TimeZoneInfo.Utc);
+
+ _fixture.Hub.DidNotReceive().CaptureCheckIn("excluded-recurring-job", Arg.Any(), Arg.Any(),
+ Arg.Any(), Arg.Any(), Arg.Any?>());
+ }
+
// 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()
@@ -127,4 +152,7 @@ public void ExecuteJobWithoutAttribute()
[SentryMonitorSlug("test-recurring-job")]
public void ExecuteRecurringJob()
{ }
+
+ public void ExecuteRecurringJobWithoutAttribute()
+ { }
}
diff --git a/test/Sentry.Hangfire.Tests/ServerFilterTests.cs b/test/Sentry.Hangfire.Tests/ServerFilterTests.cs
index 172432aa64..9f34a1a366 100644
--- a/test/Sentry.Hangfire.Tests/ServerFilterTests.cs
+++ b/test/Sentry.Hangfire.Tests/ServerFilterTests.cs
@@ -241,6 +241,7 @@ public void OnPerforming_ClassSlugSharedByMethodsWithDifferentCron_SendsCheckInW
var fixture = new RecurringJobFixture
{
Slug = SlugOnClassJob.Slug,
+ AttributeSlug = SlugOnClassJob.Slug,
Cron = "0 2 * * *",
Job = Job.FromExpression(job => job.First())
};
@@ -340,6 +341,178 @@ public void OnPerforming_ReadingAllRecurringJobsThrows_SendsCheckInWithoutMonito
fixture.AssertCheckInSentWithoutMonitorConfig();
}
+ [Fact]
+ public void OnPerforming_MonitorAllRecurringJobs_UsesSlugifiedRecurringJobId()
+ {
+ // Arrange
+ var fixture = new RecurringJobFixture
+ {
+ RecurringJobId = "Reports: Nightly Run",
+ AttributeSlug = null,
+ Slug = "reports-nightly-run",
+ Options = { MonitorAllRecurringJobs = true }
+ };
+ var filter = fixture.GetSut();
+
+ // Act
+ filter.OnPerforming(fixture.PerformingContext);
+ filter.OnPerformed(new PerformedContext(fixture.PerformingContext, null, false, null));
+
+ // Assert
+ fixture.GetSentMonitorConfig()!.Value.GetProperty("schedule").GetProperty("value").GetString().Should().Be(fixture.Cron);
+ var checkInId = fixture.Hub.ReceivedInProgressCheckInId("reports-nightly-run");
+ fixture.Hub.Received(1).CaptureCheckIn("reports-nightly-run", CheckInStatus.Ok, checkInId, Arg.Any());
+ }
+
+ [Fact]
+ public void OnPerforming_MonitorAllRecurringJobsWithAttribute_KeepsAttributeSlug()
+ {
+ // Arrange
+ var fixture = new RecurringJobFixture { Options = { MonitorAllRecurringJobs = true } };
+ var filter = fixture.GetSut();
+
+ // Act
+ filter.OnPerforming(fixture.PerformingContext);
+
+ // Assert
+ fixture.GetSentMonitorConfig().Should().NotBeNull();
+ fixture.Hub.DidNotReceive().CaptureCheckIn("test-recurring-job", Arg.Any(), Arg.Any(),
+ Arg.Any(), Arg.Any(), Arg.Any?>());
+ }
+
+ [Theory]
+ [InlineData(false, new string[0])]
+ [InlineData(true, new[] { "test-recurring-job" })]
+ public void OnPerforming_RecurringJobNotMonitored_DoesNotCaptureCheckIn(bool monitorAll, string[] excluded)
+ {
+ // Arrange
+ var fixture = new RecurringJobFixture { AttributeSlug = null };
+ fixture.Options.MonitorAllRecurringJobs = monitorAll;
+ foreach (var id in excluded)
+ {
+ fixture.Options.ExcludedRecurringJobs.Add(id);
+ }
+ var filter = fixture.GetSut();
+
+ // Act
+ filter.OnPerforming(fixture.PerformingContext);
+ filter.OnPerformed(new PerformedContext(fixture.PerformingContext, null, false, null));
+
+ // Assert
+ fixture.Hub.DidNotReceiveWithAnyArgs().CaptureCheckIn(default!, default);
+ fixture.PerformingContext.Items.Should().NotContainKey(SentryServerFilter.SentryCheckInIdKey);
+ }
+
+ [Fact]
+ public void OnPerforming_ExcludedRecurringJobWithAttribute_CapturesCheckIn()
+ {
+ // Arrange
+ var fixture = new RecurringJobFixture
+ {
+ Options = { MonitorAllRecurringJobs = true, ExcludedRecurringJobs = { "test-recurring-job" } }
+ };
+ var filter = fixture.GetSut();
+
+ // Act
+ filter.OnPerforming(fixture.PerformingContext);
+
+ // Assert
+ fixture.GetSentMonitorConfig().Should().NotBeNull();
+ }
+
+ [Fact]
+ public void OnPerforming_MonitorAllRecurringJobsIdsShareSlugWithDifferentCron_SendsCheckInWithoutMonitorConfig()
+ {
+ // Arrange
+ var fixture = new RecurringJobFixture
+ {
+ RecurringJobId = "Cleanup",
+ AttributeSlug = null,
+ Slug = "cleanup",
+ Cron = "0 2 * * *",
+ Job = Job.FromExpression(job => job.Run()),
+ Options = { MonitorAllRecurringJobs = true }
+ };
+ fixture.OtherRecurringJobs.Add(("cleanup", "0 8 * * *", null, Job.FromExpression(job => job.Run())));
+ var filter = fixture.GetSut();
+
+ // Act
+ filter.OnPerforming(fixture.PerformingContext);
+
+ // Assert
+ fixture.AssertCheckInSentWithoutMonitorConfig();
+ }
+
+ [Fact]
+ public void OnPerforming_MonitorAllRecurringJobsExcludedIdWithSameSlug_SendsMonitorConfig()
+ {
+ // Arrange
+ var fixture = new RecurringJobFixture
+ {
+ RecurringJobId = "Cleanup",
+ AttributeSlug = null,
+ Slug = "cleanup",
+ Cron = "0 2 * * *",
+ Job = Job.FromExpression(job => job.Run()),
+ Options = { MonitorAllRecurringJobs = true, ExcludedRecurringJobs = { "cleanup" } }
+ };
+ fixture.OtherRecurringJobs.Add(("cleanup", "0 8 * * *", null, Job.FromExpression(job => job.Run())));
+ var filter = fixture.GetSut();
+
+ // Act
+ filter.OnPerforming(fixture.PerformingContext);
+
+ // Assert
+ fixture.GetSentMonitorConfig().Should().NotBeNull();
+ }
+
+ [Theory]
+ [InlineData("nightly", "nightly")]
+ [InlineData("Reports: Nightly Run", "reports-nightly-run")]
+ [InlineData("!!!", null)]
+ public void GetRecurringJobSlug_RecurringJobId_ReturnsSlug(string recurringJobId, string? expected)
+ {
+ var options = new SentryHangfireOptions { MonitorAllRecurringJobs = true };
+
+ options.GetRecurringJobSlug(recurringJobId).Should().Be(expected);
+ }
+
+ [Theory]
+ [InlineData("nightly", true)]
+ [InlineData("Nightly", false)]
+ [InlineData("nightly-2", false)]
+ public void GetRecurringJobSlug_ExcludedString_MatchesIdExactly(string recurringJobId, bool excluded)
+ {
+ var options = new SentryHangfireOptions
+ {
+ MonitorAllRecurringJobs = true,
+ ExcludedRecurringJobs = { "nightly" }
+ };
+
+ (options.GetRecurringJobSlug(recurringJobId) is null).Should().Be(excluded);
+ }
+
+ [Theory]
+ [InlineData("cleanup-eu", true)]
+ [InlineData("Cleanup-US", true)]
+ [InlineData("nightly-cleanup", false)]
+ public void GetRecurringJobSlug_ExcludedRegex_MatchesId(string recurringJobId, bool excluded)
+ {
+ var options = new SentryHangfireOptions
+ {
+ MonitorAllRecurringJobs = true,
+ ExcludedRecurringJobs = { new Regex("^cleanup-", RegexOptions.IgnoreCase) }
+ };
+
+ (options.GetRecurringJobSlug(recurringJobId) is null).Should().Be(excluded);
+ }
+
+ public class PlainJob
+ {
+ public void Run()
+ { }
+ }
+
private static Job ReportJob(string region) => Job.FromExpression(job => job.Run(region));
[Theory]
@@ -425,12 +598,17 @@ private class RecurringJobFixture
public SentryId CheckInId { get; set; } = SentryId.Create();
public PerformingContext PerformingContext { get; private set; } = null!;
+ public SentryHangfireOptions Options { get; set; } = new();
+
public SentryServerFilter GetSut(bool? sendMonitorConfig = null)
{
Logger.IsEnabled(Arg.Any()).Returns(true);
Clock.GetUtcNow().Returns(Now);
- Connection.GetJobParameter(JobId, SentryServerFilter.SentryMonitorSlugKey)
- .Returns(SerializationHelper.Serialize(Slug));
+ if (AttributeSlug is not null)
+ {
+ Connection.GetJobParameter(JobId, SentryServerFilter.SentryMonitorSlugKey)
+ .Returns(SerializationHelper.Serialize(AttributeSlug));
+ }
var recurringJobIds = new HashSet(OtherRecurringJobs.Select(job => job.Id));
if (RecurringJobId is not null)
{
@@ -458,20 +636,22 @@ public SentryServerFilter GetSut(bool? sendMonitorConfig = null)
Arg.Any?>())
.Returns(CheckInId);
- var backgroundJob = new BackgroundJob(JobId, null, DateTime.Now);
+ var backgroundJob = new BackgroundJob(JobId, Job ?? Job.FromExpression(job => job.Run()), DateTime.Now);
var performContext = new PerformContext(null, Connection, backgroundJob, Substitute.For());
PerformingContext = new PerformingContext(performContext);
- var options = new SentryHangfireOptions();
if (sendMonitorConfig is { } send)
{
- options.SendMonitorConfig = send;
+ Options.SendMonitorConfig = send;
}
- return new SentryServerFilter(Hub, Logger, options, Clock);
+ return new SentryServerFilter(Hub, Logger, Options, Clock);
}
public string Slug { get; set; } = MonitorSlug;
+ // The slug the job was created with; null for a job without SentryMonitorSlugAttribute
+ public string? AttributeSlug { get; set; } = MonitorSlug;
+
private static Dictionary RecurringJobHash(string cron, string? timeZoneId, Job? job)
{
var hash = new Dictionary { ["Cron"] = cron };
diff --git a/test/Sentry.Quartz.Tests/Core/JobMonitorTests.cs b/test/Sentry.Quartz.Tests/Core/JobMonitorTests.cs
index 4151331442..2de81ac9c6 100644
--- a/test/Sentry.Quartz.Tests/Core/JobMonitorTests.cs
+++ b/test/Sentry.Quartz.Tests/Core/JobMonitorTests.cs
@@ -627,19 +627,6 @@ public void GetMonitorSlug_Job_ReturnsSlug(
JobMonitor.GetMonitorSlug(_fixture.GetContext(), attribute).Should().Be(expected);
}
- [Theory]
- [InlineData("Nightly Report", "nightly-report")]
- [InlineData("Billing.Invoices/Send!", "billing-invoices-send")]
- [InlineData("_queue__drain_", "queue__drain")]
- [InlineData("-a.-b-", "a-b")]
- [InlineData("日本語", null)]
- [InlineData("a234567890b234567890c234567890d234567890e234567890f234567890", "a234567890b234567890c234567890d234567890e234567890")]
- [InlineData("a234567890b234567890c234567890d234567890e23456789-f234567890", "a234567890b234567890c234567890d234567890e23456789")]
- public void ToSlug_Value_ReturnsSlugSentryLeavesUnchanged(string value, string? expected)
- {
- JobMonitor.ToSlug(value).Should().Be(expected);
- }
-
private static ITrigger CronTrigger(
string cronExpression,
IJobDetail? job = null,
diff --git a/test/Sentry.Tests/ApiApprovalTests.Run.DotNet10_0.verified.txt b/test/Sentry.Tests/ApiApprovalTests.Run.DotNet10_0.verified.txt
index 2a3833e84f..dcb5151b83 100644
--- a/test/Sentry.Tests/ApiApprovalTests.Run.DotNet10_0.verified.txt
+++ b/test/Sentry.Tests/ApiApprovalTests.Run.DotNet10_0.verified.txt
@@ -1367,6 +1367,7 @@ namespace Sentry
public StringOrRegex(System.Text.RegularExpressions.Regex regex) { }
public StringOrRegex(string stringOrRegex) { }
public bool IsRegex { get; }
+ public System.Text.RegularExpressions.Regex? Regex { get; }
public override bool Equals(object? obj) { }
public override int GetHashCode() { }
public override string ToString() { }
diff --git a/test/Sentry.Tests/ApiApprovalTests.Run.DotNet8_0.verified.txt b/test/Sentry.Tests/ApiApprovalTests.Run.DotNet8_0.verified.txt
index 2a3833e84f..dcb5151b83 100644
--- a/test/Sentry.Tests/ApiApprovalTests.Run.DotNet8_0.verified.txt
+++ b/test/Sentry.Tests/ApiApprovalTests.Run.DotNet8_0.verified.txt
@@ -1367,6 +1367,7 @@ namespace Sentry
public StringOrRegex(System.Text.RegularExpressions.Regex regex) { }
public StringOrRegex(string stringOrRegex) { }
public bool IsRegex { get; }
+ public System.Text.RegularExpressions.Regex? Regex { get; }
public override bool Equals(object? obj) { }
public override int GetHashCode() { }
public override string ToString() { }
diff --git a/test/Sentry.Tests/ApiApprovalTests.Run.DotNet9_0.verified.txt b/test/Sentry.Tests/ApiApprovalTests.Run.DotNet9_0.verified.txt
index 2a3833e84f..dcb5151b83 100644
--- a/test/Sentry.Tests/ApiApprovalTests.Run.DotNet9_0.verified.txt
+++ b/test/Sentry.Tests/ApiApprovalTests.Run.DotNet9_0.verified.txt
@@ -1367,6 +1367,7 @@ namespace Sentry
public StringOrRegex(System.Text.RegularExpressions.Regex regex) { }
public StringOrRegex(string stringOrRegex) { }
public bool IsRegex { get; }
+ public System.Text.RegularExpressions.Regex? Regex { get; }
public override bool Equals(object? obj) { }
public override int GetHashCode() { }
public override string ToString() { }
diff --git a/test/Sentry.Tests/ApiApprovalTests.Run.Net4_8.verified.txt b/test/Sentry.Tests/ApiApprovalTests.Run.Net4_8.verified.txt
index 28b4f8cea8..832e96b3db 100644
--- a/test/Sentry.Tests/ApiApprovalTests.Run.Net4_8.verified.txt
+++ b/test/Sentry.Tests/ApiApprovalTests.Run.Net4_8.verified.txt
@@ -1348,6 +1348,7 @@ namespace Sentry
public StringOrRegex(System.Text.RegularExpressions.Regex regex) { }
public StringOrRegex(string stringOrRegex) { }
public bool IsRegex { get; }
+ public System.Text.RegularExpressions.Regex? Regex { get; }
public override bool Equals(object? obj) { }
public override int GetHashCode() { }
public override string ToString() { }
diff --git a/test/Sentry.Tests/Internals/MonitorSlugTests.cs b/test/Sentry.Tests/Internals/MonitorSlugTests.cs
new file mode 100644
index 0000000000..ef3645fb53
--- /dev/null
+++ b/test/Sentry.Tests/Internals/MonitorSlugTests.cs
@@ -0,0 +1,30 @@
+namespace Sentry.Tests.Internals;
+
+public class MonitorSlugTests
+{
+ // Expected values come from Relay's slugify_monitor_slug tests
+ [Theory]
+ [InlineData("my-monitor", "my-monitor")]
+ [InlineData("My Monitor", "my-monitor")]
+ [InlineData("my_job", "my_job")]
+ [InlineData(" leading and trailing ", "leading-and-trailing")]
+ [InlineData("a - ! - b", "a-b")]
+ [InlineData("--a--b--", "a-b")]
+ [InlineData("_-_a_-_", "a")]
+ [InlineData("a\tb\nc", "a-b-c")]
+ [InlineData("a\u001cb", "a-b")]
+ [InlineData("Café Crème", "cafe-creme")]
+ [InlineData("straße", "strae")]
+ [InlineData("file", "file")]
+ [InlineData("Hello, World!", "hello-world")]
+ [InlineData("a.b.c", "abc")]
+ [InlineData("ÀÉÎÕÜ", "aeiou")]
+ [InlineData("日本語", null)]
+ [InlineData("!!!", null)]
+ [InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-b", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")]
+ [InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_b", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_")]
+ public void From_Value_MatchesRelay(string value, string expected)
+ {
+ MonitorSlug.From(value).Should().Be(expected);
+ }
+}