Acta. Durable execution for .NET

learn actasplit work across child jobs

How to find the child job that handles one item

A child's name on the reads is its deduplication key, {map}/{key} for a child that a map started. List the parent's children and pick the one that carries the item's key.

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/222-find-child-job
Read as

1Start each child under the item's own key

itemKey names each child after its item. The name is stored as the child's deduplication key, and it is how a replay of the parent and a reader from outside find the same child.

find-child-job.csexcerpt
public sealed class InvoiceJobs
{
    [Job("send-invoices")]
    public async Task Handle(SendInvoices batch, JobContext ctx, CancellationToken ct)
    {
        var sent = await ctx.MapAsync("invoice", batch.InvoiceIds, itemKey: id => id, child: id => new SendInvoice(id), ct);
        Console.WriteLine($"{sent.Items.Count(item => item.Outcome.Succeeded)} of {batch.InvoiceIds.Length} invoices sent");
    }

    [Job("send-invoice")]
    public async Task Send(SendInvoice invoice, JobContext ctx, CancellationToken ct)
    {
        // FailAsync ends the job there, Failed with no retry, so only the other invoices print as sent.
        if (invoice.InvoiceId == 7)
        {
            await ctx.FailAsync("the customer's address bounced", ct);
        }
        Console.WriteLine($"invoice {invoice.InvoiceId} sent");
    }
}

2List the parent's children

Parent restricts the job list to the children of one job. Each child shows the name it was started under.

find-child-job.csexcerpt
var jobs = host.Services.GetRequiredService<IJobs>();
var operations = host.Services.GetRequiredService<IActaOperations>();

var parent = await jobs.EnqueueAsync(new SendInvoices([5, 6, 7]));
await parent.WaitAsync();

var children = await operations.Ledger.ListJobsAsync(new ListJobsQuery(Parent: parent));
foreach (var child in children.Items.OrderBy(child => child.DeduplicationKey, StringComparer.Ordinal))
{
    Console.WriteLine($"{child.DeduplicationKey}: {child.Status.Code}");
}

var invoice7 = children.Items.Single(child => child.DeduplicationKey == "invoice/7");
var why = (await jobs.ExplainAsync(invoice7.JobRef))!;
Console.WriteLine($"invoice 7: {why.Headline} {why.Reason}");

await host.StopAsync();

3Pick the child that carries the item's key

The key is the one the map was given for that item, so a page that shows invoice 7 gets from the invoice to its job, and from there to what the job did.

find-child-job.csexcerpt
var children = await operations.Ledger.ListJobsAsync(new ListJobsQuery(Parent: parent));
foreach (var child in children.Items.OrderBy(child => child.DeduplicationKey, StringComparer.Ordinal))
{
    Console.WriteLine($"{child.DeduplicationKey}: {child.Status.Code}");
}

var invoice7 = children.Items.Single(child => child.DeduplicationKey == "invoice/7");
var why = (await jobs.ExplainAsync(invoice7.JobRef))!;
Console.WriteLine($"invoice 7: {why.Headline} {why.Reason}");

await host.StopAsync();

4Run 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/222-find-child-job
Its output must contain
2 of 3 invoices sent
invoice/5: succeeded
invoice/7: failed
invoice 7: Failed. the customer's address bounced

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

Remember

  • A child's name on the job reads is its DeduplicationKey: the call's name for EnqueueChildAsync, {map}/{key} for a map's child.
  • Keys keep their case: Invoice/7 and invoice/7 are two keys, so build the key the same way where you start the child and where you look for it.
  • The list answers a page at a time, fifty jobs unless PageSize says otherwise and a hundred at most. A parent with more children is read page by page, as in list and page through jobs.
  • A failed child does not fail its parent by itself, so a parent that reads succeeded can still have a child that failed. Handle child jobs that fail shows the parent's side.

Check yourself

A parent mapped invoices 5, 6 and 7 under the name invoice. Which deduplication key does the child for invoice 6 carry?

Show the answer

invoice/6. The name the map was given comes first, then the item's key. The job's own name, send-invoice, is not part of it.

The whole program

Every file of learn/200-durable-execution/222-find-child-job, 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.

find-child-job.cs81 lines
find-child-job.cs
// How to find the child job that handles one item
// A child's name on the reads is its deduplication key, `{map}/{key}` for a child that a map started. List the
// parent's children and pick the one that carries the item's key.
using Acta;
using Acta.Learn.FindChildJob;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);
    j.Run<FindChildJobJobs>("find-child-job");
});

// One invoice fails on purpose; quiet the framework's warning for it.
builder.Logging.AddFilter("Acta", LogLevel.Error);

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

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

var parent = await jobs.EnqueueAsync(new SendInvoices([5, 6, 7]));
await parent.WaitAsync();

// learn: 2. List the parent's children
// `Parent` restricts the job list to the children of one job. Each child shows the name it was started under.
var children = await operations.Ledger.ListJobsAsync(new ListJobsQuery(Parent: parent));
foreach (var child in children.Items.OrderBy(child => child.DeduplicationKey, StringComparer.Ordinal))
{
    Console.WriteLine($"{child.DeduplicationKey}: {child.Status.Code}");
}

// learn: end

// learn: 3. Pick the child that carries the item's key
// The key is the one the map was given for that item, so a page that shows invoice 7 gets from the invoice to its
// job, and from there to what the job did.
var invoice7 = children.Items.Single(child => child.DeduplicationKey == "invoice/7");
var why = (await jobs.ExplainAsync(invoice7.JobRef))!;
Console.WriteLine($"invoice 7: {why.Headline} {why.Reason}");

// learn: end

await host.StopAsync();

namespace Acta.Learn.FindChildJob
{
    public sealed record SendInvoices(int[] InvoiceIds);

    public sealed record SendInvoice(int InvoiceId);

    public sealed class InvoiceJobs
    {
        [Job("send-invoices")]
        public async Task Handle(SendInvoices batch, JobContext ctx, CancellationToken ct)
        {
            // learn: 1. Start each child under the item's own key
            // `itemKey` names each child after its item. The name is stored as the child's deduplication key, and it
            // is how a replay of the parent and a reader from outside find the same child.
            var sent = await ctx.MapAsync("invoice", batch.InvoiceIds, itemKey: id => id, child: id => new SendInvoice(id), ct);
            // learn: end
            Console.WriteLine($"{sent.Items.Count(item => item.Outcome.Succeeded)} of {batch.InvoiceIds.Length} invoices sent");
        }

        [Job("send-invoice")]
        public async Task Send(SendInvoice invoice, JobContext ctx, CancellationToken ct)
        {
            // FailAsync ends the job there, Failed with no retry, so only the other invoices print as sent.
            if (invoice.InvoiceId == 7)
            {
                await ctx.FailAsync("the customer's address bounced", ct);
            }
            Console.WriteLine($"invoice {invoice.InvoiceId} sent");
        }
    }
}

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.