Skip to content

Advanced Topics ​

Job Filters ​

Job filters intercept the execution pipeline, providing cross-cutting concerns like logging, metrics, and auditing.

Implementing a Filter ​

csharp
using GrydJobs.Core.Abstractions;

public class LoggingJobFilter : IJobFilter
{
    public int Order => 0; // Lower = executes first

    private readonly ILogger<LoggingJobFilter> _logger;

    public LoggingJobFilter(ILogger<LoggingJobFilter> logger)
        => _logger = logger;

    public Task OnBeforeExecutionAsync(JobExecutionContext context, CancellationToken ct)
    {
        _logger.LogInformation("Starting job {JobType} (ID: {JobId})",
            context.JobType, context.JobId);
        return Task.CompletedTask;
    }

    public Task OnAfterExecutionAsync(JobExecutionContext context, JobExecutionResult result,
        CancellationToken ct)
    {
        _logger.LogInformation("Job {JobType} completed with success={IsSuccess} in {Duration}ms",
            context.JobType, result.IsSuccess, result.Duration.TotalMilliseconds);
        return Task.CompletedTask;
    }

    public Task OnErrorAsync(JobExecutionContext context, Exception exception, CancellationToken ct)
    {
        _logger.LogError(exception, "Failed job {JobType} (ID: {JobId})",
            context.JobType, context.JobId);
        return Task.CompletedTask;
    }
}

Registering Filters ​

Filters are registered in DI and resolved automatically:

csharp
builder.Services.AddTransient<IJobFilter, LoggingJobFilter>();
builder.Services.AddTransient<IJobFilter, MetricsJobFilter>();

Filters run for typed and dynamically resolved jobs, including one-off and recurring executions. They are resolved after the trusted tenant context is established and run in ascending Order. OnBeforeExecutionAsync runs before the job is resolved; OnAfterExecutionAsync runs after success, and OnErrorAsync runs before OnAfterExecutionAsync when execution fails. Failures in the before hook, job, or success-after hook enter the common failure handling and follow the same retry and lifecycle persistence rules as other job failures. Exceptions from OnErrorAsync and failure OnAfterExecutionAsync are logged without replacing the original exception. If a success after hook fails, all hooks receive the subsequent failure notifications, including hooks that already received a success notification.

Execution identity and cancellation ​

For recurring jobs, JobExecutionContext.JobId is the registered recurring key. Each actual provider run has a separate ExecutionId, and each processing attempt has an ExecutionAttemptId. Use those execution identifiers when correlating lifecycle records; a recurring key identifies the schedule, not one run.

Execution deadlines cancel the job's token cooperatively while user job work is running. Pass the token to database, network, and other long-running operations, and stop when cancellation is requested. GrydJobs awaits the job task before disposing its dependency scope or allowing a retry. Filter hooks receive the provider cancellation token. Provider shutdown cancellation is recorded separately and skips normal failure persistence; a job deadline is reported as a timeout after cooperative cancellation of user work.

Relational persistence tests ​

The Jobs infrastructure tests include PostgreSQL repository coverage against the production EF Core migrations and schema. They check SQL filtering and pagination, string-mapped enum ordering, execution duration aggregates, tenant visibility, database constraints, schedule queries, and dead-letter retry and purge state. These tests verify persisted metadata and repository behavior; they do not exercise provider replay.

Run the relational coverage with Docker available:

bash
dotnet test tests/Modules/Jobs/GrydJobs.Infrastructure.Tests/GrydJobs.Infrastructure.Tests.csproj \
  -c Release --filter "FullyQualifiedName~PostgresTests"

Each test creates and drops its own database in the shared PostgreSQL test container.

Observability ​

Metrics ​

GrydJobs emits these metrics through the Core meter. gryd_jobs_enqueued_total counts an individual Hangfire invocation after provider creation succeeds. This includes delayed jobs, continuations, replays, and individual recurring ticks. Registering or updating a recurring schedule is not an invocation.

MetricTypeDescription
gryd_jobs_enqueued_totalCounterProvider-created individual invocations
gryd_jobs_executed_totalCounterNewly committed successful attempts
gryd_jobs_failed_totalCounterNewly committed failed attempts, including retryable failures
gryd_jobs_deadlettered_totalCounterNewly committed terminal attempts moved to the DLQ
gryd_jobs_retry_scheduled_totalCounterProvider state transitions scheduled for another attempt
gryd_jobs_retry_attempts_totalCounterCommitted outcomes for attempts after attempt zero
gryd_jobs_execution_duration_msHistogram, millisecondsDuration of each newly committed success or failed attempt

The bounded tags are job.mode (fire_and_forget, delayed, continuation, recurring, unknown), job.outcome (success, failure), and job.reason (exception, timeout, cancelled). Retry scheduling is observed after the provider applies its Scheduled state; it is a separate provider transition from the worker's committed attempt outcome. retry_attempts_total counts a committed outcome only when the worker retry count is greater than zero, so a scheduled retry that has not run does not count as an executed retry attempt. Provider transitions and lifecycle commits are separate transactions and do not imply exactly-once observations. A tag is present only where it describes that metric. Job type, queue, tenant, arguments, and exception messages are not metric tags.

The queue-depth and active-job gauges are unavailable because this module has no real sampler for them. Attempt outcomes are emitted after the corresponding lifecycle transaction commits and duplicate or terminal callbacks do not add another attempt observation. These metrics are operational observations, not a durable accounting ledger; a process failure or exporter outage can lose observations. Provider shutdown cancellation is excluded because it does not commit a failed attempt. A committed timeout or job cancellation remains a failed attempt and uses its bounded reason; a terminal one also contributes one dead-letter observation.

Distributed Tracing ​

GrydJobs creates spans through the Core activity source:

SpanKindDescription
gryd.jobs.submitProducerProvider submission operation
gryd.jobs.executeConsumerOne worker attempt

Spans use the bounded job.mode tag. Worker spans also include the provider job.id and job.retry_count; successful and failed executions set job.outcome. Failures set only the exception type, never the message or job arguments.

For an individual invocation, the trusted scheduling envelope stores the producer span's W3C traceparent and optional tracestate. The worker uses that context as its parent and does not persist or propagate baggage. Missing or malformed W3C context starts a new root while restoring any unrelated ambient activity after the worker span. Recurring registration clears trace context so later ticks do not all inherit the registration trace. A one-shot recurring invocation uses its captured W3C parent; an automatic tick with no captured parent starts an independent root, even if unrelated ambient activity or baggage exists.

Enable the Core exporter to collect the Jobs meter and source:

csharp
using Gryd.Observability.Abstractions;
using Gryd.Observability.OpenTelemetry.Extensions;
using GrydJobs;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("Jobs")!;

builder.Services.AddGrydOpenTelemetry(new ObservabilityOptions
{
    ServiceName = "orders-worker",
    OpenTelemetry = new OpenTelemetryOptions
    {
        Enabled = true,
        Exporter = "console"
    }
});

builder.Services.AddGrydJobs(options =>
{
    options.ConnectionString = connectionString;
});

Jobs also supplies the Core collector and activity source when registered alone. Explicit host registrations take precedence, including scoped custom services.

Testing ​

Unit Testing Jobs ​

csharp
[Fact]
public async Task SendEmailJob_SendsEmail()
{
    var sender = Substitute.For<IEmailSender>();
    var job = new SendEmailJob(sender);
    var context = new JobExecutionContext
    {
        JobId = "test-123",
        JobType = nameof(SendEmailJob)
    };

    await job.ExecuteAsync(
        new SendEmailArgs("user@test.com", "Test", "Body"),
        context,
        CancellationToken.None);

    await sender.Received(1).SendAsync(
        "user@test.com", "Test", "Body", Arg.Any<CancellationToken>());
}

Testing with Mocked Scheduler ​

csharp
[Fact]
public async Task OrderService_EnqueuesConfirmationEmail()
{
    var scheduler = Substitute.For<IJobScheduler>();
    var service = new OrderService(scheduler);

    await service.PlaceOrderAsync(new Order { Email = "test@test.com" });

    await scheduler.Received(1).EnqueueAsync<SendEmailJob, SendEmailArgs>(
        Arg.Is<SendEmailArgs>(a => a.To == "test@test.com"),
        Arg.Any<CancellationToken>());
}

In-Memory Provider for Testing ​

For integration tests, you can create an in-memory IJobScheduler:

csharp
public class InMemoryJobScheduler : IJobScheduler
{
    public List<(Type JobType, object Args)> EnqueuedJobs { get; } = [];

    public Task<string> EnqueueAsync<TJob, TArgs>(TArgs args, CancellationToken ct)
        where TJob : IJob<TArgs> where TArgs : class
    {
        EnqueuedJobs.Add((typeof(TJob), args));
        return Task.FromResult(Guid.NewGuid().ToString());
    }
    // ... implement other methods as needed
}

Idempotency ​

For jobs that must not execute more than once (e.g., payment processing), implement idempotency guards:

csharp
public class ProcessPaymentJob : IJob<PaymentArgs>
{
    private readonly IPaymentStore _store;

    public async Task ExecuteAsync(
        PaymentArgs args,
        JobExecutionContext context,
        CancellationToken ct)
    {
        // Check if already processed
        if (await _store.IsProcessedAsync(args.PaymentId, ct))
        {
            return; // Idempotent — skip duplicate execution
        }

        await _store.ProcessAsync(args.PaymentId, ct);
        await _store.MarkProcessedAsync(args.PaymentId, ct);
    }
}

Released under the MIT License.