Acta. Durable execution for .NET

learn actaget told when something breaks

How to raise an alert from a handler

AlertAsync in a handler raises an alert for the people who operate the system, and operations.Alerts reads it back.

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/402-alerts
Read as

1Raise the alert from the handler

No channel name routes to the implicit "default" channel (log transport). The database stores only the channel name; delivery configuration comes from worker startup.

alerts.csexcerpt
[Job("verify-backup")]
public async Task Handle(VerifyBackup input, JobContext context, CancellationToken ct)
{
    await Task.Delay(50, ct);

    if (!input.Healthy)
    {
        await context.AlertAsync(
            title: $"Backup verification failed: {input.FolderName}",
            message: $"The nightly backup of '{input.FolderName}' is missing or corrupt.",
            severityCode: AlertSeverityCode.Error,
            deduplicationKey: $"backup-failed:{input.FolderName}",
            ct: ct
        );
        Console.WriteLine($"[{input.FolderName}] backup is bad - alert raised");
        return;
    }

    Console.WriteLine($"[{input.FolderName}] backup verified OK");
}

2Read the alerts back

An alert is a row: the list answers its severity, its channel, and whether it was delivered.

alerts.csexcerpt
// Handler raises an operator alert; read it back through the read-only operator query surface.
await jobs.EnqueueAsync(new VerifyBackup("photos", Healthy: false));
await Task.Delay(800);

var queries = host.Services.GetRequiredService<IActaOperations>();

var alerts = await queries.Alerts.ListAsync(new ListAlertsQuery(JobNamespace: "alerts"));
foreach (var alert in alerts.Items)
{
    Console.WriteLine($"alert [{alert.Severity}] {alert.Title} -> channel '{alert.ChannelName}', delivery {alert.DeliveryStatus}");
}

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/402-alerts
Its output must contain
[photos] backup is bad - alert raised
alert [Error] Backup verification failed: photos -> channel 'default'

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

Remember

  • The AlertAsync call is a bare line, so it runs again on every re-entry of the handler: without a deduplicationKey each run inserts another alert. Raise it in a step, or give it a key.
  • AlertAsync answers its AlertRef, and acta.Alerts.ResolveAsync(alertRef) resolves it. An alert raised with a key resolves with ctx.ResolveAlertAsync(key, ct).
  • The row is written at once; delivery to the channel runs on the sys.alerts pass, within about a minute.

The whole program

Every file of learn/400-observability-and-alerts/402-alerts, 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.

alerts.cs71 lines
alerts.cs
// How to raise an alert from a handler
// `AlertAsync` in a handler raises an alert for the people who operate the system, and `operations.Alerts` reads it
// back.
using Acta;
using Acta.Learn.Alerts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);
    j.Run<AlertsJobs>("alerts");
});

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

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

// Handler raises an operator alert; read it back through the read-only operator query surface.
await jobs.EnqueueAsync(new VerifyBackup("photos", Healthy: false));
await Task.Delay(800);

var queries = host.Services.GetRequiredService<IActaOperations>();

// learn: 2. Read the alerts back
// An alert is a row: the list answers its severity, its channel, and whether it was delivered.
var alerts = await queries.Alerts.ListAsync(new ListAlertsQuery(JobNamespace: "alerts"));

// learn: end
foreach (var alert in alerts.Items)
{
    Console.WriteLine($"alert [{alert.Severity}] {alert.Title} -> channel '{alert.ChannelName}', delivery {alert.DeliveryStatus}");
}

await host.StopAsync();

namespace Acta.Learn.Alerts
{
    public sealed record VerifyBackup(string FolderName, bool Healthy);

    public sealed class VerifyBackupJob
    {
        [Job("verify-backup")]
        public async Task Handle(VerifyBackup input, JobContext context, CancellationToken ct)
        {
            await Task.Delay(50, ct);

            if (!input.Healthy)
            {
                // learn: 1. Raise the alert from the handler
                // No channel name routes to the implicit "default" channel (log transport). The
                // database stores only the channel name; delivery configuration comes from worker startup.
                await context.AlertAsync(
                    title: $"Backup verification failed: {input.FolderName}",
                    message: $"The nightly backup of '{input.FolderName}' is missing or corrupt.",
                    severityCode: AlertSeverityCode.Error,
                    deduplicationKey: $"backup-failed:{input.FolderName}",
                    ct: ct
                );
                // learn: end
                Console.WriteLine($"[{input.FolderName}] backup is bad - alert raised");
                return;
            }

            Console.WriteLine($"[{input.FolderName}] backup verified OK");
        }
    }
}

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.