QD Actions: Reliable Background Work with H.Necessaire

Queue work, write processors, and let the QD action daemon run it with retries and a result history.

Applies to H.Necessaire 4.0.5.

A QD action (“queued action”) is a unit of work you persist now and process later: send this email, enrich this IP address, rebuild that index. H.Necessaire gives you the model, the queue API, a processor base class and a daemon that works through the queue with retries.

Install

dotnet add package H.Necessaire

The model

class QdAction : IGuidIdentity
{
    Guid ID;                 // generated
    DateTime QdAt;           // UTC, when queued
    string Type;             // routes the action to a processor
    string Payload;          // your data, typically serialized JSON
    QdActionStatus Status;   // Queued -> Running -> Succeeded | Failed
    int RunCount;
}

enum QdActionStatus { Queued = 0, Running = 100, Succeeded = 200, Failed = 500 }

Queueing work

ImAnActionQer qer = deps.Get<ImAnActionQer>();

OperationResult queued = await qer.Queue(
    QdAction.New("SendWelcomeEmail", "{\"userId\":\"42\"}")
);

Queueing just saves the action through the registered ImAStorageService<Guid, QdAction>. If no storage provider is registered, Queue returns a failed result saying it can't find a QdAction storage service.

Writing a processor

Derive from QdActionProcessorBase, declare which action types you handle, and implement one method:

public class SendWelcomeEmailProcessor : QdActionProcessorBase
{
    protected override string[] SupportedQdActionTypes { get; } = new[] { "SendWelcomeEmail" };

    protected override async Task<OperationResult> ProcessQdAction(QdAction action)
    {
        // deserialize action.Payload and do the work
        return await mailer.SendAsync(/* ... */);
    }
}

deps.Register<SendWelcomeEmailProcessor>(() => new SendWelcomeEmailProcessor());

The base class adds the boring parts: it skips actions that already succeeded, refuses actions that failed too many times, logs start and duration, and converts any thrown exception into a failed result. Your method only has to return an OperationResult.

Processors are discovered by scanning for implementations of ImAQdActionProcessor and resolving each one from the registry, so every processor must be registered. If you need custom eligibility rules, override IsEligibleFor.

The processing daemon

QdActionProcessingDaemon (an ImADaemon with Start/Stop) polls the queue on a timer. Each cycle it:

  • loads a page of actions that are Queued or Failed and still have attempts left (RunCount below the maximum),
  • re-loads each action and skips it if its persisted status shows it was already picked up,
  • marks it Running, finds a processor that says it is eligible and runs it (if none is, the attempt is saved as failed with a “No eligible QD Action Processor found” reason), then increments RunCount and saves Succeeded or Failed,
  • saves a QdActionResult (an OperationResult<QdAction> with its own ID and timestamp) so you have a history of every attempt.

Before starting the timer it validates the wireup, and if something is missing it logs a warning and does not start. Tune it with config (see the configuration reference):

KeyDefaultMeaning
QdActions.ProcessingIntervalInSeconds15Time between cycles.
QdActions.ProcessingBatchSize10Actions loaded per cycle.
QdActions.MaxProcessingAttempts3Attempts before an action is left as failed.

In a hosted app, resolve QdActionProcessingDaemon from the registry and call Start() at application startup and Stop() at shutdown, or wrap it in your own IHostedService. For tests, command line tools and one-off jobs you can skip the timer and run a single cycle yourself:

ImAQdActionQueueOnDemandRunner runner = deps.Get<ImAQdActionQueueOnDemandRunner>();
OperationResult<QdActionResult[]> cycle = await runner.RunQdActionQueueProcessingCycle();

What you need registered

  • HNecessaireDependencyGroup (or RuntimeDependencyGroup), which registers the queue, the daemon and the on-demand runner.
  • A storage provider that supplies ImAStorageService for QdAction and QdActionResult plus the QdActionFilter browser (the SQLite runtime package registers these; check that the provider you pick does too).
  • Your processors.

The Runtime package already ships two processors, IpAddressInfoProcessor and RuntimePlatformProcessor, which the runtime uses when it processes consumer identity and analytics data.

Results come from the OperationResult article; the storage article explains the services the daemon relies on.