1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//! Distributed leader election via Redis or in-process fallback.
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use tokio::sync::Notify;
/// Trait for leader election backends.
#[async_trait]
pub trait LeaderElection: Send + Sync {
/// Attempts to acquire leadership. Returns true if elected.
async fn try_acquire(&self) -> bool;
/// Releases leadership if currently held.
async fn release(&self);
/// Returns true if this instance currently holds leadership.
async fn is_leader(&self) -> bool;
}
/// In-process leader election using a shared atomic flag.
#[derive(Clone)]
pub struct InProcLeaderElection {
leader: Arc<tokio::sync::Mutex<bool>>,
notify: Arc<Notify>,
}
impl InProcLeaderElection {
pub fn new() -> Self {
Self {
leader: Arc::new(tokio::sync::Mutex::new(false)),
notify: Arc::new(Notify::new()),
}
}
}
#[async_trait]
impl LeaderElection for InProcLeaderElection {
async fn try_acquire(&self) -> bool {
let mut leader = self.leader.lock().await;
if *leader {
false
} else {
*leader = true;
true
}
}
async fn release(&self) {
let mut leader = self.leader.lock().await;
*leader = false;
self.notify.notify_waiters();
}
async fn is_leader(&self) -> bool {
*self.leader.lock().await
}
}
impl Default for InProcLeaderElection {
fn default() -> Self {
Self::new()
}
}