Acta. Durable execution for .NET

learn actawait for people, events, and time

How to hold a sign-up until the email is confirmed

The job is the pending sign-up: Acta stores its input, a signal confirms it, and a deadline ends it with no account to clean up.

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

Checked every release learn/200-durable-execution/221-pending-signup
Read as

1Wait for the confirmation, with a deadline

The wait is a row with its deadline stored in the database, so no process has to stay alive for it. When nobody confirms in time, the job cancels itself: no user was ever written, so there is nothing to undo. CancelAsync ends the handler there, so the lines after it run only for a confirmed sign-up.

pending-signup.csexcerpt
var confirmed = await ctx.WaitSignalAsync<EmailConfirmed>("email-confirmed", input.ConfirmWithin, ct);
if (confirmed.TimedOut)
{
    Console.WriteLine($"[{input.Email}] not confirmed in time");
    await ctx.CancelAsync("not confirmed in time", ct);
}

2Create the user only after the confirmation

Only now does the sign-up become a real user. The insert is keyed by the email, so a repeat of the step adds nothing.

pending-signup.csexcerpt
await ctx.RunStepAsync(
    "create-user",
    _ =>
    {
        users.CreateIfAbsent(input.Email, input.DisplayName);
        Console.WriteLine($"[{input.Email}] user created");
        return Task.CompletedTask;
    },
    ct
);

3Start the job when the form is submitted

The input is the pending sign-up, so there is no table of pending users. The one-time code also goes into the link of the email. Ada gets a day to confirm; Sam gets two seconds, so the program can show a sign-up that expires.

pending-signup.csexcerpt
using var host = builder.Build();
await host.StartAsync();

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

var ada = await jobs.EnqueueAsync(new RegisterUser("[email protected]", "Ada", "c0ffee", TimeSpan.FromHours(24)));
var sam = await jobs.EnqueueAsync(new RegisterUser("[email protected]", "Sam", "decade", TimeSpan.FromSeconds(2)));

4Confirm it from the link in the email

A raise proves nothing about who sent it, so the code from the link is compared with the one stored in the job before the signal is raised. The raise answers what it did.

pending-signup.csexcerpt
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
while ((await jobs.GetAsync(ada, timeout.Token))?.Status != JobStatusCode.Suspended)
{
    await Task.Delay(50, timeout.Token);
}

var pending = await jobs.GetInputAsync<RegisterUser>(ada);
if (pending.Code == "c0ffee")
{
    var raised = await jobs.RaiseSignalAsync(ada, "email-confirmed", new EmailConfirmed("c0ffee"));
    Console.WriteLine($"ada's click: {raised.Action}");
}

await ada.WaitAsync();
await sam.WaitAsync();
Console.WriteLine($"[email protected]: {(await jobs.GetAsync(ada))!.Status}");
Console.WriteLine($"[email protected]: {(await jobs.GetAsync(sam))!.Status}");
Console.WriteLine($"users: {string.Join(", ", users.Emails)}");

5Run it and check the output

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

Terminal
dotnet run --project learn/200-durable-execution/221-pending-signup
Its output must contain
ada's click: Applied
[[email protected]] user created
[[email protected]] not confirmed in time
[email protected]: Cancelled
users: [email protected]
sam's late click: Rejected

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

Remember

  • Nothing real exists until create-user runs. An unconfirmed sign-up ends as a cancelled job and leaves no half-made account behind.
  • The deadline is stored once, as database time plus the timeout. Restarts and downtime never make it longer.
  • The handler runs from the top after the confirmation. The email is not sent again, because the step that sends it already has a recorded outcome.
  • Make create-user safe to repeat: insert only when the address is absent. A crash right after the insert runs the step again, and two submits of the form end as one account.
  • A finished job is kept with its input for its retention period: ninety days by default, seven here, through [Job("register-user", JobRetention = "7d")]. Keep the input to what the work needs when it holds personal data.
  • In a web app the confirm link opens a page with a Confirm button that posts: mail scanners fetch the links they see, and a fetch must not confirm anything.

Check yourself

The app is redeployed twelve hours after the sign-up. What happens to the pending registration?

Show the answer

Nothing: it is a suspended job, and the link still works. The wait is a row with its deadline stored in the database. No process had to stay alive for it, and the email step is not repeated.

Nobody opens the link. What is left when the deadline has passed?

Show the answer

A cancelled job with its timeline, and no user. The wait times out, the handler cancels the job, and create-user never runs. The job row stays for its retention period as the record of what happened.

The whole program

Every file of learn/200-durable-execution/221-pending-signup, 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.

pending-signup.cs123 lines
pending-signup.cs
// How to hold a sign-up until the email is confirmed
// The job is the pending sign-up: Acta stores its input, a signal confirms it, and a deadline ends it with no account
// to clean up.
using System.Collections.Concurrent;
using Acta;
using Acta.Learn.PendingSignup;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<UserStore>();

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);
    j.Run<PendingSignupJobs>("pending-signup");
});

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

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

// learn: 3. Start the job when the form is submitted
// The input is the pending sign-up, so there is no table of pending users. The one-time code also goes into the
// link of the email. Ada gets a day to confirm; Sam gets two seconds, so the program can show a sign-up that expires.
var ada = await jobs.EnqueueAsync(new RegisterUser("[email protected]", "Ada", "c0ffee", TimeSpan.FromHours(24)));

// learn: end
var sam = await jobs.EnqueueAsync(new RegisterUser("[email protected]", "Sam", "decade", TimeSpan.FromSeconds(2)));

using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
while ((await jobs.GetAsync(ada, timeout.Token))?.Status != JobStatusCode.Suspended)
{
    await Task.Delay(50, timeout.Token);
}

// learn: 4. Confirm it from the link in the email
// A raise proves nothing about who sent it, so the code from the link is compared with the one stored in the job
// before the signal is raised. The raise answers what it did.
var pending = await jobs.GetInputAsync<RegisterUser>(ada);
if (pending.Code == "c0ffee")
{
    var raised = await jobs.RaiseSignalAsync(ada, "email-confirmed", new EmailConfirmed("c0ffee"));
    Console.WriteLine($"ada's click: {raised.Action}");
}

// learn: end

await ada.WaitAsync();
await sam.WaitAsync();
Console.WriteLine($"[email protected]: {(await jobs.GetAsync(ada))!.Status}");
Console.WriteLine($"[email protected]: {(await jobs.GetAsync(sam))!.Status}");
Console.WriteLine($"users: {string.Join(", ", users.Emails)}");

// A click on Sam's link after his sign-up has ended: the answer is not Applied, so the page must not say "confirmed".
var late = await jobs.RaiseSignalAsync(sam, "email-confirmed", new EmailConfirmed("decade"));
Console.WriteLine($"sam's late click: {late.Action}");

await host.StopAsync();

namespace Acta.Learn.PendingSignup
{
    public sealed record RegisterUser(string Email, string DisplayName, string Code, TimeSpan ConfirmWithin);

    public sealed record EmailConfirmed(string Code);

    /// <summary>The application's own users. Nothing reaches it before a sign-up is confirmed.</summary>
    public sealed class UserStore
    {
        private readonly ConcurrentDictionary<string, string> _users = new();

        public IEnumerable<string> Emails => _users.Keys.Order();

        public void CreateIfAbsent(string email, string displayName) => _users.TryAdd(email, displayName);
    }

    public sealed class RegistrationJobs(UserStore users)
    {
        // The finished job is kept with its input for seven days, not the default ninety.
        [Job("register-user", JobRetention = "7d")]
        public async Task Handle(RegisterUser input, JobContext ctx, CancellationToken ct)
        {
            await ctx.RunStepAsync(
                "send-confirmation",
                _ =>
                {
                    Console.WriteLine($"[{input.Email}] confirmation email sent");
                    return Task.CompletedTask;
                },
                ct
            );

            // learn: 1. Wait for the confirmation, with a deadline
            // The wait is a row with its deadline stored in the database, so no process has to stay alive for it. When
            // nobody confirms in time, the job cancels itself: no user was ever written, so there is nothing to undo.
            // `CancelAsync` ends the handler there, so the lines after it run only for a confirmed sign-up.
            var confirmed = await ctx.WaitSignalAsync<EmailConfirmed>("email-confirmed", input.ConfirmWithin, ct);
            if (confirmed.TimedOut)
            {
                Console.WriteLine($"[{input.Email}] not confirmed in time");
                await ctx.CancelAsync("not confirmed in time", ct);
            }
            // learn: end

            // learn: 2. Create the user only after the confirmation
            // Only now does the sign-up become a real user. The insert is keyed by the email, so a repeat of the step
            // adds nothing.
            await ctx.RunStepAsync(
                "create-user",
                _ =>
                {
                    users.CreateIfAbsent(input.Email, input.DisplayName);
                    Console.WriteLine($"[{input.Email}] user created");
                    return Task.CompletedTask;
                },
                ct
            );
            // 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.