Interface ILeaderElection
- Namespace
- Excalibur.Dispatch.LeaderElection
- Assembly
- Excalibur.Dispatch.LeaderElection.Abstractions.dll
Provides leader election capabilities for distributed systems.
public interface ILeaderElection : IAsyncDisposable
- Inherited Members
- Extension Methods
Properties
CandidateId
Gets the unique identifier for this election participant.
string CandidateId { get; }
Property Value
- string
the unique identifier for this election participant.
CurrentLeaderId
Gets the identifier of the instance currently believed to hold leadership, on a best-effort basis.
string? CurrentLeaderId { get; }
Property Value
Remarks
Guaranteed non-null only while this instance is itself the leader. When another instance holds leadership, whether this property can name it depends on the provider's arbitration primitive, and callers must treat null as "unknown", never as "there is no leader".
A provider that arbitrates through a primitive carrying no owner identity — a Postgres session-level advisory lock, for example, which answers only true or false to the instance attempting it — has nothing to report to a follower and returns null there. A provider that arbitrates through a claims row or lease record can name the holder to every instance. Both are conforming: leader discovery is an optional capability, and its absence does not weaken the mutual-exclusion guarantee, which every provider must uphold.
Never use this for a leadership decision. It is a diagnostic and a convenience for logging or surfacing topology. The authoritative, atomic check is CurrentLeadership, which carries the fencing token for the tenure; a non-null value here says nothing about whether the named instance still holds leadership by the time the caller acts on it.
CurrentLeadership
Gets the current leadership tenure, or null if this instance is not currently the leader.
Leadership? CurrentLeadership { get; }
Property Value
- Leadership?
The current Leadership snapshot, or null if not leading.
Remarks
INVARIANT, binding on every implementation: a reported tenure carries a usable fencing token whenever fencing is configured. FencingToken is null if and only if the deployment configured no fencing. An implementation that cannot obtain a usable token does not report a tenure — it RELINQUISHES, releasing whatever claim it holds so another candidate can take it, and reports the failed acquisition instead.
That invariant is what lets a downstream guard treat a null token as a deliberate opt-out rather than as an unknown, so it must hold on EVERY path that declares a tenure — not only on acquisition. A tenure can also be concluded from a store read: a recovery after a write whose response was lost, or a poll that confirms this candidate still holds the claim. Those paths cannot see the acquisition path's checks and must make the same decision themselves.
The structurally safer shape is to pass the token as a PARAMETER to whatever declares leadership, rather than to derive leadership from state and set the token separately. Where the token is an argument, a tenure cannot be declared without one. Where leadership is derived — for example from a cached holder identity that a background poll assigns — every assignment to that state is a second declaration of leadership, and each one needs the check.
This is the authoritative, atomic check for leadership: it is non-null if and only if this instance currently considers itself the leader, and the returned Leadership carries the fencing token minted for the current tenure alongside the instant it began. Read once per tenure and pin the returned value — see the Leadership remarks.
IsLeader
Gets a value indicating whether this instance is currently the leader.
bool IsLeader { get; }
Property Value
Remarks
This is an advisory convenience derived from the same underlying state as
CurrentLeadership. For a single atomic read of leadership state that also carries the
fencing token, prefer CurrentLeadership is not null — it is the authoritative check.
NotificationsCompleted
Gets this instance's permanent notification-completion task.
Task NotificationsCompleted { get; }
Property Value
Remarks
The same task is returned from construction through disposal. Stop and restart do not complete it. It settles only after permanent disposal seals all producers and every admitted synchronous event invocation returns. A retained first notification failure faults this task independently of resource disposal. Async-void continuations and consumer-spawned tasks are not included. Dispose does not await this task, and consumers must not await it from one of this instance's own callbacks.
Methods
StartAsync(CancellationToken)
Starts participating in leader election.
Task StartAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenCancellation token.
Returns
- Task
A task that represents the asynchronous start operation.
Remarks
When the returned task completes, exactly one acquisition attempt has been made and resolved: this candidate either holds the resource — in which case CurrentLeadership is already non-null — or has observed that it does not. A renewal loop is armed either way.
Notifications for the transition are enqueued, not delivered. The BecameLeader, LostLeadership, LeaderChanged and AcquisitionFailed handlers are dispatched on the election's own notification worker, so a handler may not have run by the time this task completes, and a slow handler delays only the notifications — never the acquisition. Do not infer leadership from a flag maintained by those handlers: read CurrentLeadership, which is authoritative and self-expiring.
Calling this method again on an instance that already participates is a no-op and raises no second notification. It may not be called from inside one of this instance's own event handlers.
Exceptions
- ObjectDisposedException
This instance has been disposed.
- InvalidOperationException
A previous StopAsync(CancellationToken) has not yet reached quiescence, or this call was made from inside one of this instance's own event handlers.
- OperationCanceledException
cancellationTokenwas canceled.- TimeoutException
A provider whose coordination backend bounds its own requests timed out while attempting the acquisition. Not every provider can raise this.
StopAsync(CancellationToken)
Stops participating in leader election and relinquishes leadership if held.
Task StopAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenCancellation token.
Returns
- Task
A task that represents the asynchronous stop operation.
Events
AcquisitionFailed
Event raised when this instance fails to acquire leadership, either by losing the acquisition race to another candidate or because an error occurred during the attempt.
event EventHandler<LeaderElectionAcquisitionFailedEventArgs>? AcquisitionFailed
Event Type
Remarks
Raised from the observation tier, so consecutive pending failures are coalesced into one and only the most recent reason and cause survive the merge. This event makes contention and connectivity problems visible; it is not a counter of attempts, and a consumer deriving a failure rate from it will under-count. Use it as a signal, and take counts from metrics instead.
BecameLeader
Event raised when this instance becomes the leader.
event EventHandler<LeaderElectionEventArgs>? BecameLeader
Event Type
Remarks
Delivered on the election's notification worker, so it may run after the call that caused the transition has already returned. A local transition is queued and never discarded: it is delayed, not dropped. Arrival is not permission to write — the tenure may already have ended by the time a handler runs, so read CurrentLeadership and fence the resource rather than treating this event as authority.
LeaderChanged
Event raised when the leader changes (any instance).
event EventHandler<LeaderChangedEventArgs>? LeaderChanged
Event Type
Remarks
This event has two delivery tiers and they differ in whether an occurrence can be lost. Raised from this instance's own leadership transition, it is queued and never discarded. Raised from an observation of a remote holder, consecutive pending occurrences are coalesced: the merge keeps the earliest previous holder and the most recent current one, so a succession A to B to C can surface as a single A to C and the intermediate holder is never reported.
So the net change is reliable and the sequence is not. Do not count these to count leadership changes, and do not treat the absence of one as evidence that no change occurred.
LostLeadership
Event raised when this instance loses leadership.
event EventHandler<LeaderElectionEventArgs>? LostLeadership
Event Type
Remarks
Delivered on the election's notification worker. A local transition is queued and never discarded, so this is delayed rather than dropped — but a handler that blocks delays every later notification behind it, and a flag maintained by these handlers can therefore read "leader" for an unbounded interval after the tenure ended. Do not derive a leadership decision from one.