Acta. Durable execution for .NET

learn actawatch and control running work

How to wrap every handler in your own middleware

An IJobPipelineBehavior wraps every handler call, the way middleware wraps a request.

A how-to for Acta, durable execution for .NET. New to Acta? Run your first durable job in five minutes.

Checked every release learn/400-observability-and-alerts/401-pipeline-behavior
Read as

1Write the behavior around the call to the handler

What stands before next() runs before the handler, and what stands after it runs after.

pipeline-behavior.csexcerpt
// Wraps every handler invocation; first registered is outermost. Resolved per attempt, so it can
// take constructor dependencies (including the scoped JobContext).
public sealed class TimingBehavior : IJobPipelineBehavior
{
    public async ValueTask<JobHandlerOutput> InvokeAsync(
        object request,
        JobContext context,
        JobBehaviorDelegate next,
        CancellationToken ct
    )
    {
        var sw = Stopwatch.StartNew();
        Console.WriteLine($"-> {context.JobName} #{context.JobId} starting");
        var result = await next();
        Console.WriteLine($"<- {context.JobName} #{context.JobId} done in {sw.ElapsedMilliseconds} ms");
        return result;
    }
}

2Register the behavior

The first one registered is the outermost.

pipeline-behavior.csexcerpt
var builder = Host.CreateApplicationBuilder(args);

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);
    j.AddPipelineBehavior<TimingBehavior>();
    j.Run<PipelineBehaviorJobs>("pipeline-behavior");
});

using var host = builder.Build();
await host.StartAsync();

var jobs = host.Services.GetRequiredService<IJobs>();

await jobs.EnqueueAsync(new GreetUser("Sam"));
Console.WriteLine("Enqueued. Worker is running - press Ctrl+C to stop.");

await host.WaitForShutdownAsync();
await host.StopAsync();

3Run it and check the output

From a clone of the Acta repository, with the .NET 10 SDK:

Terminal
dotnet run --project learn/400-observability-and-alerts/401-pipeline-behavior
Its output must contain
-> greet-user #
  Hi, Sam!
<- greet-user #

Checked every release. Before each release, Acta Verify runs this program and checks that its output contains these lines.

This page shows the code. The rules it relies on, starting with the handler running again from its first line, are in the handler contract.

The whole program

Every file of learn/400-observability-and-alerts/401-pipeline-behavior, as it is compiled.

UseLocalDatabase is a helper of the Acta repository, not of the packages. In your own app, register the database with UseSqlite, UsePostgres or UseSqlServer, as in how to run your first job.

pipeline-behavior.cs67 lines
pipeline-behavior.cs
// How to wrap every handler in your own middleware
// An `IJobPipelineBehavior` wraps every handler call, the way middleware wraps a request.
using System.Diagnostics;
using Acta;
using Acta.Learn.PipelineBehavior;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);
    // learn: 2. Register the behavior
    // The first one registered is the outermost.
    j.AddPipelineBehavior<TimingBehavior>();
    // learn: end
    j.Run<PipelineBehaviorJobs>("pipeline-behavior");
});

using var host = builder.Build();
await host.StartAsync();

var jobs = host.Services.GetRequiredService<IJobs>();

await jobs.EnqueueAsync(new GreetUser("Sam"));
Console.WriteLine("Enqueued. Worker is running - press Ctrl+C to stop.");

await host.WaitForShutdownAsync();
await host.StopAsync();

namespace Acta.Learn.PipelineBehavior
{
    public sealed record GreetUser(string Name);

    public static class GreetUserJob
    {
        [Job("greet-user")]
        public static async Task Handle(GreetUser input, CancellationToken ct)
        {
            await Task.Delay(100, ct);
            Console.WriteLine($"  Hi, {input.Name}!");
        }
    }

    // Wraps every handler invocation; first registered is outermost. Resolved per attempt, so it can
    // take constructor dependencies (including the scoped JobContext).
    public sealed class TimingBehavior : IJobPipelineBehavior
    {
        public async ValueTask<JobHandlerOutput> InvokeAsync(
            object request,
            JobContext context,
            JobBehaviorDelegate next,
            CancellationToken ct
        )
        {
            // learn: 1. Write the behavior around the call to the handler
            // What stands before `next()` runs before the handler, and what stands after it runs after.
            var sw = Stopwatch.StartNew();
            Console.WriteLine($"-> {context.JobName} #{context.JobId} starting");
            var result = await next();
            Console.WriteLine($"<- {context.JobName} #{context.JobId} done in {sw.ElapsedMilliseconds} ms");
            return result;
            // learn: end
        }
    }
}

Where to go next

New to Acta?

Acta is durable execution for .NET: workflows and jobs that survive restarts, as a library inside your application with its durable state in your SQL database.