Table of Contents

Class FencingTokenMiddleware

Namespace
Excalibur.Dispatch.LeaderElection.Fencing
Assembly
Excalibur.Dispatch.LeaderElection.Abstractions.dll

Middleware that validates fencing tokens on incoming messages to prevent stale leader operations in leader election scenarios.

[AppliesTo(MessageKinds.Action|MessageKinds.Event)]
public sealed class FencingTokenMiddleware : IDispatchMiddleware
Inheritance
FencingTokenMiddleware
Implements
Inherited Members
Extension Methods

Remarks

This middleware checks for a fencing token in the message context's Items dictionary (key: FencingToken) and validates it against the current token for the resource (identified by FencingResourceId in Items).

If the token is stale (lower than the current token), the message is rejected with a failed result.

Validation faults and cancellation propagate without invoking the next delegate. They are not converted to a stale-token result: an unavailable authority is not proof of staleness, and preserving the original failure allows outer retry/classification and cancellation policies to act on it.

THIS IS A PRE-FLIGHT CHECK AND IT DOES NOT FENCE THE HANDLER'S WRITES. Read this before relying on it. The validation happens, and then the handler runs. A successor can advance the high-water mark in the interval between the check returning and the handler's write, so a message admitted here can still be processed by a superseded leader. That is not a defect in this middleware, it is what a check-then-act sequence is: the validation describes an instant that has already passed by the time the handler executes, and no comparison performed here can change that.

What it DOES establish, which is worth having: a message whose token was ALREADY superseded at the moment of the check is refused before the handler runs at all, which turns a stale delivery into a reported failure instead of a silent reprocessing. It narrows the window; it does not close it, and it cannot prevent split-brain on its own.

What closes it is enforcement inside the write: a conditional update in the handler's own store, predicated on a stored high-water column, so the store either applies the write or rejects it in one step. Only the store holding the data can make that atomic with the write, so it is outside this framework. A handler whose correctness depends on not being superseded must do that, with this middleware as a cheap early rejection rather than as the guarantee.

Fencing tokens are strictly positive. A context item that is present but holds a non-positive value is not a token -- it is either an unset value or an item of the wrong type -- and the message is rejected rather than validated. Zero in particular must never reach validation: against a provider whose own high-water mark is unset, a token >= mark comparison would admit it.

Constructors

FencingTokenMiddleware(IFencingTokenProvider, ILogger<FencingTokenMiddleware>)

Middleware that validates fencing tokens on incoming messages to prevent stale leader operations in leader election scenarios.

public FencingTokenMiddleware(IFencingTokenProvider provider, ILogger<FencingTokenMiddleware> logger)

Parameters

provider IFencingTokenProvider

The fencing token provider for validation.

logger ILogger<FencingTokenMiddleware>

The logger for diagnostic output.

Remarks

This middleware checks for a fencing token in the message context's Items dictionary (key: FencingToken) and validates it against the current token for the resource (identified by FencingResourceId in Items).

If the token is stale (lower than the current token), the message is rejected with a failed result.

Validation faults and cancellation propagate without invoking the next delegate. They are not converted to a stale-token result: an unavailable authority is not proof of staleness, and preserving the original failure allows outer retry/classification and cancellation policies to act on it.

THIS IS A PRE-FLIGHT CHECK AND IT DOES NOT FENCE THE HANDLER'S WRITES. Read this before relying on it. The validation happens, and then the handler runs. A successor can advance the high-water mark in the interval between the check returning and the handler's write, so a message admitted here can still be processed by a superseded leader. That is not a defect in this middleware, it is what a check-then-act sequence is: the validation describes an instant that has already passed by the time the handler executes, and no comparison performed here can change that.

What it DOES establish, which is worth having: a message whose token was ALREADY superseded at the moment of the check is refused before the handler runs at all, which turns a stale delivery into a reported failure instead of a silent reprocessing. It narrows the window; it does not close it, and it cannot prevent split-brain on its own.

What closes it is enforcement inside the write: a conditional update in the handler's own store, predicated on a stored high-water column, so the store either applies the write or rejects it in one step. Only the store holding the data can make that atomic with the write, so it is outside this framework. A handler whose correctness depends on not being superseded must do that, with this middleware as a cheap early rejection rather than as the guarantee.

Fencing tokens are strictly positive. A context item that is present but holds a non-positive value is not a token -- it is either an unset value or an item of the wrong type -- and the message is rejected rather than validated. Zero in particular must never reach validation: against a provider whose own high-water mark is unset, a token >= mark comparison would admit it.

Fields

FencingResourceIdKey

The context item key for the fencing resource identifier.

public const string FencingResourceIdKey = "FencingResourceId"

Field Value

string

FencingTokenKey

The context item key for the fencing token value.

public const string FencingTokenKey = "FencingToken"

Field Value

string

Properties

ApplicableMessageKinds

Gets the message kinds that this middleware applies.

public MessageKinds ApplicableMessageKinds { get; }

Property Value

MessageKinds

The set of message kinds this middleware applies to.

Remarks

Specifies which types of messages this middleware should process. The pipeline filters middleware based on these flags, ensuring only relevant middleware processes each message. This improves performance and allows middleware to specialize in handling specific message types. If not implemented, defaults to All for backward compatibility.

Stage

Gets the pipeline stage where this middleware should execute.

public DispatchMiddlewareStage? Stage { get; }

Property Value

DispatchMiddlewareStage?

The pipeline stage for this middleware.

Remarks

The stage determines the execution order of middleware in the pipeline. If null, the middleware will be registered at the end of the pipeline. Stages are processed in numeric order, allowing fine-grained control over middleware execution sequence.

Methods

InvokeAsync(IDispatchMessage, IMessageContext, DispatchRequestDelegate, CancellationToken)

Processes the message within the middleware pipeline.

public ValueTask<IMessageResult> InvokeAsync(IDispatchMessage message, IMessageContext context, DispatchRequestDelegate nextDelegate, CancellationToken cancellationToken)

Parameters

message IDispatchMessage

The message being processed.

context IMessageContext

The message context containing metadata and processing state.

nextDelegate DispatchRequestDelegate

The delegate to invoke the next middleware in the pipeline.

cancellationToken CancellationToken

The cancellation token to observe.

Returns

ValueTask<IMessageResult>

A ValueTask<TResult> representing the result of message processing, potentially modified by this middleware. ValueTask can avoid allocating a Task for a synchronously completed result; other dispatch work can still allocate.

Remarks

Implementations can execute logic before calling nextDelegate, after calling it, or both. To short-circuit the pipeline, don't call nextDelegate and return an appropriate result. The context can be used to share data between middleware components. Respect the cancellation token to support timeouts and graceful shutdown.

Exceptions

ArgumentNullException

Thrown when message, context, or nextDelegate is null.

OperationCanceledException

Thrown when the operation is cancelled.