Acta. Durable execution for .NET

learn actaget told when something breaks

How to send alerts to your own channel

AddAlertChannel declares where alerts go, under a name of your choice, and an alert names the channel it is for.

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/403-alert-channel
Read as

1Declare the channel on the worker

w is the worker builder of j.Run("alert-channel", w => { w.AddManifest<AlertChannelJobs>(); ... }), the form of Run that takes more than a manifest. Alert channels declare process-local delivery configuration. Alert rows persist only the selected channel name; endpoints and secrets stay in app configuration. MinSeverity = Warning suppresses lower-severity alerts at delivery.

alert-channel.csexcerpt
w.AddManifest<AlertChannelJobs>();

w.AddAlertChannel(
    "ops",
    AlertTransportKinds.Log,
    endpoint: "ops", // the log transport ignores the endpoint; a Slack channel passes its URL here
    o =>
    {
        o.MinSeverity = AlertSeverityCode.Warning;
    }
);

2Name the channel when you raise the alert

Route to the "ops" channel instead of the default.

alert-channel.csexcerpt
await context.AlertAsync(
    title: $"Low disk space on {input.Server}",
    message: $"Only {input.FreePercent}% free on {input.Server}.",
    severityCode: AlertSeverityCode.Error,
    channelName: "ops",
    deduplicationKey: $"disk:{input.Server}",
    ct: ct
);
Console.WriteLine($"[{input.Server}] low disk - alerted ops ({input.FreePercent}% free)");
return;

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/403-alert-channel
Its output must contain
[db-server] low disk - alerted ops (4% free)
alert [Error] Low disk space on db-server -> channel 'ops'

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/403-alert-channel, 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.

alert-channel.cs87 lines
alert-channel.cs
// How to send alerts to your own channel
// `AddAlertChannel` declares where alerts go, under a name of your choice, and an alert names the channel it is for.
using Acta;
using Acta.Learn.AlertChannel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);

    // Use the namespace-plus-configure worker registration form so alert channels can be declared
    // through the worker builder.
    j.Run("alert-channel", w =>
    {
        w.AddManifest<AlertChannelJobs>();

        // learn: 1. Declare the channel on the worker
        // `w` is the worker builder of `j.Run("alert-channel", w => { w.AddManifest<AlertChannelJobs>(); ... })`,
        // the form of `Run` that takes more than a manifest.
        // Alert channels declare process-local delivery configuration. Alert rows persist only
        // the selected channel name; endpoints and secrets stay in app configuration.
        // MinSeverity = Warning suppresses lower-severity alerts at delivery.
        w.AddAlertChannel(
            "ops",
            AlertTransportKinds.Log,
            endpoint: "ops", // the log transport ignores the endpoint; a Slack channel passes its URL here
            o =>
            {
                o.MinSeverity = AlertSeverityCode.Warning;
            }
        );
        // learn: end
    });
});

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

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

await jobs.EnqueueAsync(new CheckDiskSpace("db-server", FreePercent: 4));
await Task.Delay(800);

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

await host.StopAsync();

namespace Acta.Learn.AlertChannel
{
    public sealed record CheckDiskSpace(string Server, int FreePercent);

    public sealed class CheckDiskSpaceJob
    {
        [Job("check-disk-space")]
        public async Task Handle(CheckDiskSpace input, JobContext context, CancellationToken ct)
        {
            await Task.Delay(50, ct);

            if (input.FreePercent < 10)
            {
                // learn: 2. Name the channel when you raise the alert
                // Route to the "ops" channel instead of the default.
                await context.AlertAsync(
                    title: $"Low disk space on {input.Server}",
                    message: $"Only {input.FreePercent}% free on {input.Server}.",
                    severityCode: AlertSeverityCode.Error,
                    channelName: "ops",
                    deduplicationKey: $"disk:{input.Server}",
                    ct: ct
                );
                // learn: end
                Console.WriteLine($"[{input.Server}] low disk - alerted ops ({input.FreePercent}% free)");
                return;
            }

            Console.WriteLine($"[{input.Server}] disk OK ({input.FreePercent}% free)");
        }
    }
}

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.