Message priority

The default behavior in Nexus is to process messages in the order that they come in; oldest first. In some cases this is not granular enough and you have some messages that needs to be prioritized over others. Nexus allows you to control this by passing a number as priority when you enqueue the message. Eg:

public class MyController(IEnqueuer<MyMessage> enqueuer)
{
    public async Task<IActionResult> Enqueue()
    {
        await enqueuer.EnqueueAsync(new MyMessage { ... }, new EnqueueContext { Priority = 10 });

        return Ok();
    }
}

With the above your message is guaranteed to be processed before any message with a lower priority than 10. For other messages with the same priority the order will be first in - first out.

Default priority

The default priority in Nexus is 0. When you enqueue messages you're encouraged to create an enum or a static class with your named priority levels rather than setting numbers like in the example above.

Note that you can have low prio messages that have a negative priority. Which means that they will be processed after any message with the default (0) priority.

Programmatically determining the priority

In some cases messages comes in through the API and you don't want to let the external party dictate the priority, but if they use the Nexus API directly to enqueue you don't get to set the priority.

For this scenario and others you can implement IMessagePriorityCalculator<TMessage> and register with IServiceCollection.

public static class MessagePriority
{
    public const int High = 100;
    public const int Low = 0;
}

public class MyMessagePriorityCalculator<MyMessage> : IMessagePriorityCalculator<MyMessage>
{
    public async Task<int?> CalculatePriorityAsync(MyMessage message)
    {
        if (message.SomeProperty == "some value")
        {
            return MessagePriority.High;
        }
        return MessagePriority.Low;
    }
}

Note that this class is only called for messages that doesn't have an explicit priority set already.