| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
use crate::Shared; |
| 20 |
use std::collections::BTreeSet; |
| 21 |
use std::future::Future; |
| 22 |
use std::sync::Mutex; |
| 23 |
use std::time::Duration; |
| 24 |
|
| 25 |
|
| 26 |
pub const RETRY: Duration = Duration::from_secs(2); |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
pub const CHECK: Duration = Duration::from_secs(2); |
| 31 |
|
| 32 |
|
| 33 |
#[derive(Default)] |
| 34 |
pub struct Leader { |
| 35 |
|
| 36 |
tasks: Mutex<BTreeSet<&'static str>>, |
| 37 |
|
| 38 |
leading: Mutex<BTreeSet<&'static str>>, |
| 39 |
|
| 40 |
contenders: Mutex<Vec<tokio::task::AbortHandle>>, |
| 41 |
#[cfg(feature = "postgres")] |
| 42 |
session: pg::Session, |
| 43 |
} |
| 44 |
|
| 45 |
impl Leader { |
| 46 |
|
| 47 |
pub fn tasks(&self) -> Vec<&'static str> { |
| 48 |
self.tasks.lock().unwrap_or_else(|p| p.into_inner()).iter().copied().collect() |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
pub fn leading(&self) -> Vec<&'static str> { |
| 53 |
self.leading.lock().unwrap_or_else(|p| p.into_inner()).iter().copied().collect() |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
pub fn note(&self, name: &'static str) { |
| 58 |
self.tasks.lock().unwrap_or_else(|p| p.into_inner()).insert(name); |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
pub async fn resign(&self) { |
| 64 |
for c in self.contenders.lock().unwrap_or_else(|p| p.into_inner()).drain(..) { |
| 65 |
c.abort(); |
| 66 |
} |
| 67 |
#[cfg(feature = "postgres")] |
| 68 |
self.session.close().await; |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
#[cfg(feature = "postgres")] |
| 74 |
pub async fn session_pid(&self) -> Option<i32> { |
| 75 |
self.session.pid().await |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
#[cfg(feature = "postgres")] |
| 82 |
impl Leader { |
| 83 |
|
| 84 |
|
| 85 |
async fn acquire(&self, app: &Shared, name: &'static str) -> Option<u64> { |
| 86 |
self.session.acquire(&app.db, name).await |
| 87 |
} |
| 88 |
|
| 89 |
|
| 90 |
async fn held(&self, term: u64) -> bool { |
| 91 |
self.session.held(term).await |
| 92 |
} |
| 93 |
|
| 94 |
|
| 95 |
async fn release(&self, name: &'static str, term: u64) { |
| 96 |
self.session.release(name, term).await |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
#[cfg(not(feature = "postgres"))] |
| 101 |
impl Leader { |
| 102 |
async fn acquire(&self, _app: &Shared, _name: &'static str) -> Option<u64> { |
| 103 |
Some(0) |
| 104 |
} |
| 105 |
|
| 106 |
async fn held(&self, _term: u64) -> bool { |
| 107 |
true |
| 108 |
} |
| 109 |
|
| 110 |
async fn release(&self, _name: &'static str, _term: u64) {} |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
struct Leading<'a>(&'a Leader, &'static str); |
| 116 |
|
| 117 |
impl<'a> Leading<'a> { |
| 118 |
fn new(leader: &'a Leader, name: &'static str) -> Self { |
| 119 |
leader.leading.lock().unwrap_or_else(|p| p.into_inner()).insert(name); |
| 120 |
Leading(leader, name) |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
impl Drop for Leading<'_> { |
| 125 |
fn drop(&mut self) { |
| 126 |
self.0.leading.lock().unwrap_or_else(|p| p.into_inner()).remove(self.1); |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
pub fn run<F, Fut>(app: &Shared, name: &'static str, task: F) |
| 135 |
where |
| 136 |
F: Fn(Shared) -> Fut + Send + 'static, |
| 137 |
Fut: Future<Output = ()> + Send + 'static, |
| 138 |
{ |
| 139 |
app.leader.note(name); |
| 140 |
let handle = tokio::spawn(contend(app.clone(), name, task)); |
| 141 |
app.leader.contenders.lock().unwrap_or_else(|p| p.into_inner()).push(handle.abort_handle()); |
| 142 |
} |
| 143 |
|
| 144 |
async fn contend<F, Fut>(app: Shared, name: &'static str, task: F) |
| 145 |
where |
| 146 |
F: Fn(Shared) -> Fut, |
| 147 |
Fut: Future<Output = ()>, |
| 148 |
{ |
| 149 |
let leader = &app.leader; |
| 150 |
let mut waiting = false; |
| 151 |
loop { |
| 152 |
let Some(term) = leader.acquire(&app, name).await else { |
| 153 |
if !waiting { |
| 154 |
tracing::info!("leader: {name} runs elsewhere; standing by"); |
| 155 |
waiting = true; |
| 156 |
} |
| 157 |
tokio::time::sleep(RETRY).await; |
| 158 |
continue; |
| 159 |
}; |
| 160 |
if waiting { |
| 161 |
tracing::info!("leader: took over {name}"); |
| 162 |
waiting = false; |
| 163 |
} |
| 164 |
let _leading = Leading::new(leader, name); |
| 165 |
let work = task(app.clone()); |
| 166 |
tokio::pin!(work); |
| 167 |
let finished = loop { |
| 168 |
tokio::select! { |
| 169 |
_ = &mut work => break true, |
| 170 |
_ = tokio::time::sleep(CHECK) => { |
| 171 |
if !leader.held(term).await { |
| 172 |
break false; |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
}; |
| 177 |
if finished { |
| 178 |
leader.release(name, term).await; |
| 179 |
return; |
| 180 |
} |
| 181 |
|
| 182 |
tracing::warn!("leader: lost the lock for {name}; stopped it, contending again"); |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
#[cfg(feature = "postgres")] |
| 187 |
mod pg { |
| 188 |
use super::CHECK; |
| 189 |
use crate::db::Pool; |
| 190 |
use sqlx::postgres::PgConnection; |
| 191 |
use sqlx::Connection; |
| 192 |
use std::time::Instant; |
| 193 |
|
| 194 |
|
| 195 |
struct Conn { |
| 196 |
conn: PgConnection, |
| 197 |
|
| 198 |
|
| 199 |
schema: String, |
| 200 |
pid: i32, |
| 201 |
|
| 202 |
checked: Instant, |
| 203 |
} |
| 204 |
|
| 205 |
#[derive(Default)] |
| 206 |
pub(super) struct Session { |
| 207 |
conn: tokio::sync::Mutex<Option<Conn>>, |
| 208 |
|
| 209 |
|
| 210 |
term: std::sync::atomic::AtomicU64, |
| 211 |
closed: std::sync::atomic::AtomicBool, |
| 212 |
} |
| 213 |
|
| 214 |
|
| 215 |
pub(super) fn key(schema: &str, name: &str) -> i64 { |
| 216 |
let h = blake3::hash(format!("oxygenhub leader\0{schema}\0{name}").as_bytes()); |
| 217 |
i64::from_le_bytes(h.as_bytes()[..8].try_into().expect("eight bytes")) |
| 218 |
} |
| 219 |
|
| 220 |
impl Session { |
| 221 |
fn term(&self) -> u64 { |
| 222 |
self.term.load(std::sync::atomic::Ordering::SeqCst) |
| 223 |
} |
| 224 |
|
| 225 |
|
| 226 |
fn lose(&self, slot: &mut Option<Conn>) { |
| 227 |
if slot.take().is_some() { |
| 228 |
self.term.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
async fn connect(db: &Pool) -> anyhow::Result<Conn> { |
| 233 |
let options = db.connect_options(); |
| 234 |
let mut conn = PgConnection::connect_with(&options).await?; |
| 235 |
let (schema, pid): (String, i32) = |
| 236 |
sqlx::query_as("SELECT CAST(current_schema() AS TEXT), pg_backend_pid()").fetch_one(&mut conn).await?; |
| 237 |
Ok(Conn { conn, schema, pid, checked: Instant::now() }) |
| 238 |
} |
| 239 |
|
| 240 |
pub(super) async fn acquire(&self, db: &Pool, name: &'static str) -> Option<u64> { |
| 241 |
let mut slot = self.conn.lock().await; |
| 242 |
if self.closed.load(std::sync::atomic::Ordering::SeqCst) { |
| 243 |
return None; |
| 244 |
} |
| 245 |
if slot.is_none() { |
| 246 |
match tokio::time::timeout(CHECK * 5, Self::connect(db)).await { |
| 247 |
Ok(Ok(c)) => *slot = Some(c), |
| 248 |
Ok(Err(e)) => { |
| 249 |
tracing::warn!("leader: connecting for {name}'s lock: {e}"); |
| 250 |
return None; |
| 251 |
} |
| 252 |
Err(_) => { |
| 253 |
tracing::warn!("leader: connecting for {name}'s lock: timed out"); |
| 254 |
return None; |
| 255 |
} |
| 256 |
} |
| 257 |
} |
| 258 |
let term = self.term(); |
| 259 |
let c = slot.as_mut()?; |
| 260 |
let ask = sqlx::query_scalar::<_, bool>("SELECT pg_try_advisory_lock($1)").bind(key(&c.schema, name)); |
| 261 |
match tokio::time::timeout(CHECK, ask.fetch_one(&mut c.conn)).await { |
| 262 |
Ok(Ok(got)) => { |
| 263 |
c.checked = Instant::now(); |
| 264 |
got.then_some(term) |
| 265 |
} |
| 266 |
Ok(Err(e)) => { |
| 267 |
tracing::warn!("leader: asking for {name}'s lock: {e}"); |
| 268 |
self.lose(&mut slot); |
| 269 |
None |
| 270 |
} |
| 271 |
Err(_) => { |
| 272 |
tracing::warn!("leader: asking for {name}'s lock: timed out"); |
| 273 |
self.lose(&mut slot); |
| 274 |
None |
| 275 |
} |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
pub(super) async fn held(&self, term: u64) -> bool { |
| 280 |
let mut slot = self.conn.lock().await; |
| 281 |
if self.term() != term { |
| 282 |
return false; |
| 283 |
} |
| 284 |
let Some(c) = slot.as_mut() else { return false }; |
| 285 |
|
| 286 |
if c.checked.elapsed() < CHECK / 2 { |
| 287 |
return true; |
| 288 |
} |
| 289 |
let ping = sqlx::query_scalar::<_, i32>("SELECT 1").fetch_one(&mut c.conn); |
| 290 |
match tokio::time::timeout(CHECK, ping).await { |
| 291 |
Ok(Ok(_)) => { |
| 292 |
c.checked = Instant::now(); |
| 293 |
true |
| 294 |
} |
| 295 |
_ => { |
| 296 |
tracing::warn!("leader: the connection holding the locks is gone"); |
| 297 |
self.lose(&mut slot); |
| 298 |
false |
| 299 |
} |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
pub(super) async fn release(&self, name: &'static str, term: u64) { |
| 304 |
let mut slot = self.conn.lock().await; |
| 305 |
if self.term() != term { |
| 306 |
return; |
| 307 |
} |
| 308 |
let Some(c) = slot.as_mut() else { return }; |
| 309 |
let unlock = sqlx::query_scalar::<_, bool>("SELECT pg_advisory_unlock($1)").bind(key(&c.schema, name)); |
| 310 |
if !matches!(tokio::time::timeout(CHECK, unlock.fetch_one(&mut c.conn)).await, Ok(Ok(_))) { |
| 311 |
self.lose(&mut slot); |
| 312 |
} |
| 313 |
} |
| 314 |
|
| 315 |
pub(super) async fn close(&self) { |
| 316 |
self.closed.store(true, std::sync::atomic::Ordering::SeqCst); |
| 317 |
let mut slot = self.conn.lock().await; |
| 318 |
if let Some(c) = slot.take() { |
| 319 |
self.term.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 320 |
let _ = c.conn.close().await; |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
pub(super) async fn pid(&self) -> Option<i32> { |
| 325 |
self.conn.lock().await.as_ref().map(|c| c.pid) |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
#[cfg(test)] |
| 330 |
mod tests { |
| 331 |
#[test] |
| 332 |
fn keys_are_stable_and_per_schema() { |
| 333 |
assert_eq!(super::key("hub_a", "flow.scheduler"), super::key("hub_a", "flow.scheduler")); |
| 334 |
assert_ne!(super::key("hub_a", "flow.scheduler"), super::key("hub_b", "flow.scheduler")); |
| 335 |
assert_ne!(super::key("hub_a", "flow.scheduler"), super::key("hub_a", "flow.reaper")); |
| 336 |
} |
| 337 |
} |
| 338 |
} |