Class MonotonicFencedResourceGuard
- Namespace
- Excalibur.Dispatch.LeaderElection.Fencing
- Assembly
- Excalibur.Dispatch.LeaderElection.Abstractions.dll
A thread-safe, in-memory IFencedResource that enforces the Chubby/Lamport sequencer rule. A fencing token identifies a leadership tenure, not an individual operation, so an operation is accepted when its token is greater than or equal to the highest token previously accepted (a non-decreasing sequence), and the high-water mark advances atomically. Only a strictly lower token — presented by a superseded leader — is rejected. This admits the same leader presenting its stable per-tenure token across multiple operations, while still fencing out a stale predecessor.
public sealed class MonotonicFencedResourceGuard : IFencedResource
- Inheritance
-
MonotonicFencedResourceGuard
- Implements
- Inherited Members
- Extension Methods
Remarks
A non-positive token is refused before the comparison. The sibling contract states that every
fencing token is strictly positive and that zero is UNSET rather than a value, and that it binds
every implementation. This type previously advertised admitting "an initial token of zero" as a
feature, and did: the high-water field starts at zero, 0 < 0 is false, so a fabricated zero
was accepted and left the mark at zero — making never-guarded and guarded-at-zero the same state,
which a long cannot distinguish.
The practical consequence was narrow, and it is stated so nobody reads more into the fix than it carries: a real superseded leader holds a POSITIVE token, so this was not split-brain by itself, and admitting the first real token is correct and intended. What was wrong is that a value the family invariant says is not a token at all was admitted, by a public type a consumer instantiates directly.
This is the default fenced-resource guard for protecting an in-process resource (a cache entry, an in-memory aggregate, a connection) against stale-leader operations. Resources backed by an external store (a database row, a Redis key) typically enforce the same rule server-side instead (a conditional update keyed on a stored high-water column); this guard is for resources with no such external enforcement point.
Methods
GuardAsync(long, CancellationToken)
Guards an operation with the given fencing token, advancing the resource's high-water mark when the token is accepted.
public ValueTask GuardAsync(long fencingToken, CancellationToken cancellationToken)
Parameters
fencingTokenlongThe fencing token presented for this operation.
cancellationTokenCancellationTokenThe cancellation token to observe.
Returns
- ValueTask
A task that completes when the guard check has been evaluated.
Exceptions
- StaleFencingTokenException
Thrown when
fencingTokenis below the highest fencing token this resource has already observed — a superseded leader. A token equal to that high-water mark is the incumbent leader re-presenting its pinned per-tenure token and is accepted, not thrown on.