diff --git a/src/anchor.rs b/src/anchor.rs index 2fe042c..d3773d2 100644 --- a/src/anchor.rs +++ b/src/anchor.rs @@ -319,12 +319,16 @@ pub async fn run_daily(cfg: &Config, db: &PgPool, now: DateTime) -> Result< if cfg.mail.is_none() { return Ok(None); } - // one server sends: the lock keeps two runs from both sending + // one server sends: the lock keeps two runs from both sending. Every + // way out ends the transaction itself: a dropped one is only rolled + // back when its connection is used again, and until then it keeps the + // lock, so the next run would find it taken and skip the day. let mut tx = db.begin().await?; let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(7464530001)") .fetch_one(&mut *tx) .await?; if !locked { + tx.rollback().await?; return Ok(None); } let today = now.with_timezone(&dates::bangkok()).date_naive(); @@ -334,11 +338,12 @@ pub async fn run_daily(cfg: &Config, db: &PgPool, now: DateTime) -> Result< .fetch_all(db) .await?; if !due(now, &rows) { + tx.rollback().await?; return Ok(None); } - let out = send(cfg, db, true, "daily anchor", now).await?; - tx.commit().await?; - Ok(Some(out)) + let out = send(cfg, db, true, "daily anchor", now).await; + tx.rollback().await?; + Ok(Some(out?)) } /// Checks every ten minutes whether the day's anchor is due. diff --git a/tests/notifications.rs b/tests/notifications.rs index 61e4775..c13c820 100644 --- a/tests/notifications.rs +++ b/tests/notifications.rs @@ -289,6 +289,19 @@ async fn the_journal_anchor_goes_out_daily_and_checks_later(pool: PgPool) { .unwrap() .is_none() ); + // a run that sends nothing lets go of its lock before it returns, as a + // connection of its own (another run's) sees it + let mut other = ::connect_with(&pool.connect_options()) + .await + .unwrap(); + let held: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' \ + AND database = (SELECT oid FROM pg_database WHERE datname = current_database())", + ) + .fetch_one(&mut other) + .await + .unwrap(); + assert_eq!(held, 0, "the anchor's lock is still held"); let out = visa::anchor::run_daily(&cfg, &pool, cm(0, 7, 5)) .await .unwrap();