diff --git a/crates/izlek-core/src/mail.rs b/crates/izlek-core/src/mail.rs index 0a7bda3..010d3b5 100644 --- a/crates/izlek-core/src/mail.rs +++ b/crates/izlek-core/src/mail.rs @@ -31,7 +31,8 @@ use time::{Duration, OffsetDateTime}; use crate::board::Transition; use crate::detail::ActivityKind; use crate::store::{ - ActivityEvent, Audience, Event, Freeing, MailOutcome, MailRule, MailSend, SendKind, Store, + ActivityEvent, Audience, ClaimedSend, Event, Freeing, MailOutcome, MailRule, MailSend, SendKind, + Store, Trigger, }; @@ -113,6 +114,15 @@ pub const MAX_ATTEMPTS: u32 = 5; /// to see whether mail starts moving. pub const HOLD: Duration = Duration::minutes(1); +/// How long a delivery pass holds a row it is about to send, so a second pass +/// running at the same moment leaves it alone. +/// +/// It is a lease and not a removal: if this process dies between taking the +/// row and writing down what happened, the row falls due again after this and +/// the mail goes late instead of never. Long enough to cover a mail server +/// that is thinking about it, short enough that a crash is not a lost day. +pub const LEASE: Duration = Duration::minutes(5); + /// The wait before the next attempt, doubling and capped: five minutes, ten, /// twenty, forty, an hour. pub fn backoff(attempts: u32) -> Duration { @@ -524,7 +534,14 @@ impl Engine { for recipient in audience { let claimed = self .store - .claim_send(&rule.id, event.id(), task_id, &recipient.email, now) + .claim_send( + &rule.id, + event.id(), + task_id, + &recipient.email, + now, + now + LEASE, + ) .await?; match claimed { Some(send) => { @@ -567,7 +584,11 @@ impl Engine { limit: u32, ) -> crate::store::Result { let mut report = Report::default(); - for send in self.store.sends_owed(now, limit).await? { + // Claimed, not merely owed: the request that queued a mail spawns a + // pass and the same write wakes the sweep, so two passes reach the + // same row together. Each is handed only what it took, and only a + // `ClaimedSend` can be mailed. See `Store::claim_sends_owed`. + for send in self.store.claim_sends_owed(now, now + LEASE, limit).await? { // An invite and an admin's notice both owe no rule and no event: // each carries its own subject and body, composed once at mint // time. Without this arm a notice falls through to the rule path, @@ -602,7 +623,7 @@ impl Engine { /// One attempt, and the ledger line it leaves behind. async fn attempt( &self, - send: &MailSend, + send: &ClaimedSend, mail: Option, report: &mut Report, ) -> crate::store::Result<()> { diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 22b23cb..85cfd60 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -367,6 +367,39 @@ impl SendKind { } } +/// A send this delivery pass holds, and the only thing the engine will mail. +/// +/// The duplicate-invite bug was not that somebody forgot to claim a row. It +/// was that the delivery path *could* read a row and mail it without claiming +/// it — two passes did, and an invited member got two identical mails. A +/// comment saying "claim first" is a fix that lasts until the next person +/// writes the next delivery loop. +/// +/// So the reading and the claiming are one operation +/// ([`claim_sends_owed`](Store::claim_sends_owed)), and what it hands back is +/// this rather than a bare [`MailSend`]. Only the store builds one, and +/// `Engine::attempt` accepts nothing else, so a row that was merely *read* — +/// by [`sends_owed`](Store::sends_owed), by a queue screen, by a test — will +/// not compile into a mail. The rule is carried by the type instead of by +/// whoever remembers it. +#[derive(Debug, Clone)] +pub struct ClaimedSend(MailSend); + +impl ClaimedSend { + /// Built only where a row was actually taken: the store's claim. + pub(crate) fn taken(send: MailSend) -> Self { + Self(send) + } +} + +impl std::ops::Deref for ClaimedSend { + type Target = MailSend; + + fn deref(&self) -> &MailSend { + &self.0 + } +} + /// One mail a rule owes one person, or an invite that owes nobody, and what /// happened to it. `rule_id`/`event_id`/`task_id` are `None` on an invite /// send; `subject`/`body` are `None` on a rule send, which composes its own @@ -1010,6 +1043,12 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Nothing is handed to the mail server before this row exists, so a /// crash mid-send leaves a row that says pending rather than a mail /// nobody can account for. + /// + /// The row is born held until `until`, because writing it announces the + /// queue and the sweep wakes on that announcement — a row inserted due + /// now is a row the sweep can be mailing while the pass that created it + /// is also mailing it. The index stops the crossing being owed twice; the + /// lease stops the one row being sent twice. async fn claim_send( &self, rule_id: &str, @@ -1017,7 +1056,8 @@ pub trait Store: BoardReads + DetailReads + 'static { task_id: &str, recipient: &str, at: OffsetDateTime, - ) -> Result>; + until: OffsetDateTime, + ) -> Result>; /// Holds an invite mail: pending, no rule, no event, no task. async fn queue_invite( @@ -1067,8 +1107,37 @@ pub trait Store: BoardReads + DetailReads + 'static { ) -> Result<()>; /// Sends owed right now: claimed but never accepted, and due. + /// + /// This is a read, for looking: what it returns is a [`MailSend`], which + /// the engine cannot mail. Delivery goes through + /// [`claim_sends_owed`](Store::claim_sends_owed). async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result>; + /// Takes the sends owed right now for this pass, and hands back only the + /// ones it actually got. + /// + /// Two things deliver: the pass spawned off the request that queued the + /// mail, and the sweep, which the same queue write wakes. Both used to + /// read the ledger and then go to the mail server, and a row does not stop + /// looking owed until the send comes back — so both saw the same row as + /// owed and an invited member was mailed twice. + /// + /// Reading and claiming are therefore one operation. Every row returned + /// has already been moved out of the due window, in the same call, before + /// anyone can spend a network round-trip on it; a pass arriving second + /// gets a shorter list, not a duplicate. + /// + /// `until` is a lease rather than a removal, because a process that dies + /// between claiming and recording must not take the mail with it. The row + /// falls due again then, and is sent late rather than never — which is the + /// right way round for a mail nobody has received. + async fn claim_sends_owed( + &self, + now: OffsetDateTime, + until: OffsetDateTime, + limit: u32, + ) -> Result>; + /// When the next mail falls due, whether or not that is yet. /// /// The sweep asks this so it can sleep exactly that long instead of waking diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 216c4eb..2a37888 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -16,7 +16,8 @@ use ulid::Ulid; use super::secret; use super::{ ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion, - Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, MailSend, + ClaimedSend, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, + MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState, SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User, Workspace, @@ -2880,7 +2881,8 @@ impl Store for TursoStore { task_id: &str, recipient: &str, at: OffsetDateTime, - ) -> Result> { + until: OffsetDateTime, + ) -> Result> { let id = Ulid::new().to_string(); // The index is the decision. `DO NOTHING` turns the second engine run // into zero rows affected rather than an error to interpret, and the @@ -2893,7 +2895,7 @@ impl Store for TursoStore { "INSERT INTO mail_send \ (id, rule_id, event_id, task_id, recipient, state, attempts, claimed_at, \ next_attempt_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6) \ + VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?7) \ ON CONFLICT (rule_id, event_id, task_id, recipient) DO NOTHING", params![ id.clone(), @@ -2901,7 +2903,8 @@ impl Store for TursoStore { event_id, task_id, recipient, - stamp(at)? + stamp(at)?, + stamp(until)? ], ) .await @@ -2913,7 +2916,7 @@ impl Store for TursoStore { self.announce([Topic::Queue]); let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { - Some(row) => send_from(&row).map(Some), + Some(row) => send_from(&row).map(ClaimedSend::taken).map(Some), None => Err(StoreError::NotFound), } } @@ -3085,6 +3088,51 @@ impl Store for TursoStore { } } + async fn claim_sends_owed( + &self, + now: OffsetDateTime, + until: OffsetDateTime, + limit: u32, + ) -> Result> { + // One lock across the read and every claim: no second pass is inside + // this while it runs, and every path into this store goes through the + // same connection. + let conn = self.conn.lock().await; + let sql = format!( + "SELECT {SEND_COLUMNS} FROM mail_send \ + WHERE next_attempt_at IS NOT NULL AND next_attempt_at <= ?1 \ + ORDER BY next_attempt_at LIMIT ?2" + ); + let mut rows = conn + .query(&sql, params![stamp(now)?, i64::from(limit)]) + .await + .map_err(backend)?; + let mut due = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + due.push(send_from(&row)?); + } + + let mut taken = Vec::new(); + for send in due { + // The `next_attempt_at <= ?2` is the whole of the exclusion: a + // pass that gets here after this row was leased finds it pushed + // out of the window and changes nothing, so it is not returned to + // that pass either. + let moved = conn + .execute( + "UPDATE mail_send SET next_attempt_at = ?1 \ + WHERE id = ?3 AND next_attempt_at IS NOT NULL AND next_attempt_at <= ?2", + params![stamp(until)?, stamp(now)?, send.id.as_str()], + ) + .await + .map_err(backend)?; + if moved == 1 { + taken.push(ClaimedSend::taken(send)); + } + } + Ok(taken) + } + async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result> { let conn = self.conn.lock().await; let sql = format!( diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 091361f..6dec664 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -3637,7 +3637,7 @@ async fn the_index_decides_who_owns_a_send() { let now = OffsetDateTime::now_utc(); let first = scratch .store - .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now) .await .unwrap(); assert!(first.is_some(), "the first run owns the send"); @@ -3647,7 +3647,7 @@ async fn the_index_decides_who_owns_a_send() { // first: the insert loses. let second = scratch .store - .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now) .await .unwrap(); assert!(second.is_none(), "the second run owns nothing"); @@ -3683,7 +3683,7 @@ async fn a_second_crossing_is_a_second_send() { assert!( scratch .store - .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now) .await .unwrap() .is_some() @@ -3717,7 +3717,7 @@ async fn a_refused_send_is_recorded_and_owed_again() { let now = OffsetDateTime::now_utc(); let send = scratch .store - .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now) .await .unwrap() .unwrap(); @@ -3770,7 +3770,7 @@ async fn a_refused_address_is_not_retried_forever() { let now = OffsetDateTime::now_utc(); let send = scratch .store - .claim_send(&rule.id, &transition.id, &task, "gone@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "gone@izlek.sh", now, now) .await .unwrap() .unwrap(); @@ -3813,7 +3813,7 @@ async fn an_accepted_send_stops_being_owed() { let now = OffsetDateTime::now_utc(); let send = scratch .store - .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now) .await .unwrap() .unwrap(); @@ -3903,7 +3903,7 @@ async fn deleting_a_rule_takes_its_ledger_with_it() { let now = OffsetDateTime::now_utc(); scratch .store - .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now) .await .unwrap(); @@ -5006,13 +5006,13 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() { let now = OffsetDateTime::now_utc(); let pending = store - .claim_send(&rule.id, &transition.id, &task, "pending@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "pending@izlek.sh", now, now) .await .unwrap() .unwrap(); let failed = store - .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now, now) .await .unwrap() .unwrap(); @@ -5022,14 +5022,14 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() { .unwrap(); let sent = store - .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now, now) .await .unwrap() .unwrap(); store.record_send_accepted(&sent.id, now).await.unwrap(); let abandoned = store - .claim_send(&rule.id, &transition.id, &task, "abandoned@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "abandoned@izlek.sh", now, now) .await .unwrap() .unwrap(); @@ -5092,6 +5092,153 @@ async fn an_invite_mail_with_no_sender_is_held_not_failed() { let _ = std::fs::remove_dir_all(&dir); } +/// A mailer that takes its time, so a second pass has somewhere to arrive. +struct Dawdling { + sent: Mutex>, +} + +#[async_trait::async_trait] +impl Mailer for Dawdling { + async fn send(&self, mail: &Outgoing) -> Result<(), MailError> { + // The window the bug lived in: the row still looks owed for as long as + // the mail server is thinking about it. + tokio::time::sleep(std::time::Duration::from_millis(150)).await; + self.sent.lock().unwrap().push(mail.clone()); + Ok(()) + } +} + +#[tokio::test] +async fn two_passes_over_one_owed_mail_send_it_once() { + // Queueing an invite both spawns a delivery pass off the request and wakes + // the sweep, so two passes read the ledger at the same moment. Owed is not + // ownership: whoever loses the claim must not also send. Three invited + // members once arrived as six mails. + let (dir, store, _workspace, _admin) = shared().await; + let now = OffsetDateTime::now_utc(); + store + .queue_invite("newcomer@izlek.sh", "Join İzlek", "Come aboard.", now) + .await + .unwrap(); + + let mailer = Arc::new(Dawdling { + sent: Mutex::new(Vec::new()), + }); + // Two engines over one store, which is what the process actually has: the + // request's pass and the sweep's. + let request = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let sweep = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let (a, b) = tokio::join!( + request.deliver_owed(now, 10), + sweep.deliver_owed(now, 10), + ); + let (a, b) = (a.unwrap(), b.unwrap()); + + let sent = mailer.sent.lock().unwrap().len(); + assert_eq!( + sent, 1, + "one queued invite left as {sent} mails: the loser of the claim sent it too" + ); + assert_eq!( + a.sent + b.sent, + 1, + "both passes reported sending the same mail" + ); + + // The winner wrote down that it went, so the row does not come back when + // the lease runs out — the loser leaving it alone is not the same as the + // mail being dropped. + let owed = store + .sends_owed(now + izlek_core::mail::LEASE + Duration::seconds(1), 10) + .await + .unwrap(); + assert!( + owed.is_empty(), + "a mail that was sent is owed again once the lease expires" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn a_crossing_and_a_sweep_at_the_same_moment_mail_once() { + // The unique index stops a crossing being *owed* twice. It does nothing + // about the one row being *sent* twice: writing it announces the queue, + // which wakes the sweep, while the pass that wrote it is still composing. + // The row is therefore born held, and this is the test that says so. + let (dir, store, workspace, admin) = shared().await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &mate).await.unwrap(); + let _rule = a_rule(&store, &workspace, "Done", "Task completed").await; + let transition = moved_to(&store, &workspace, &task, "Backlog", "Done", &admin).await; + + let mailer = Arc::new(Dawdling { + sent: Mutex::new(Vec::new()), + }); + let crossing = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let sweep = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + + // The sweep passes run while the crossing is inside its send, which is + // exactly when the row it just wrote is sitting in the ledger. + let (crossed, _swept) = tokio::join!(crossing.on_transition(&transition), async { + for _ in 0..4 { + let _ = sweep + .deliver_owed(OffsetDateTime::now_utc(), 10) + .await + .unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(40)).await; + } + }); + crossed.unwrap(); + + let sent = mailer.sent.lock().unwrap().len(); + assert_eq!( + sent, 1, + "one crossing left as {sent} mails: the sweep sent the row the crossing was sending" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn a_lease_that_expires_gives_the_mail_back() { + // The claim is a lease, not a deletion: a process that dies between taking + // a row and writing down what happened must not take the mail with it. + let (scratch, _workspace, _admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + let invite = store + .queue_invite("newcomer@izlek.sh", "Join İzlek", "Come aboard.", now) + .await + .unwrap(); + + let mine = store + .claim_sends_owed(now, now + izlek_core::mail::LEASE, 10) + .await + .unwrap(); + assert!( + mine.iter().any(|s| s.id == invite.id), + "the first pass did not get a mail nobody holds" + ); + let theirs = store + .claim_sends_owed(now, now + izlek_core::mail::LEASE, 10) + .await + .unwrap(); + assert!( + !theirs.iter().any(|s| s.id == invite.id), + "a second pass was handed a mail that was already held" + ); + // Nobody wrote the outcome down, so once the lease is out the mail is owed + // again rather than lost. + let owed = store + .sends_owed(now + izlek_core::mail::LEASE + Duration::seconds(1), 10) + .await + .unwrap(); + assert!( + owed.iter().any(|s| s.id == invite.id), + "an abandoned lease swallowed the mail" + ); +} + #[tokio::test] async fn the_activity_feed_is_the_whole_workspace_newest_first() { let (scratch, workspace, admin) = workspace_with_admin().await; @@ -5457,12 +5604,12 @@ async fn decisions_and_sends_for_task_read_only_that_tasks_own_rows() { .await .unwrap(); let send = store - .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now) .await .unwrap() .unwrap(); store - .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now) + .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now, now) .await .unwrap(); @@ -5486,7 +5633,7 @@ async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() { let now = OffsetDateTime::now_utc(); let failed = store - .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now, now) .await .unwrap() .unwrap(); @@ -5496,7 +5643,7 @@ async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() { .unwrap(); let sent = store - .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now, now) .await .unwrap() .unwrap(); @@ -5847,6 +5994,11 @@ fn every_writing_method_announces_or_is_named_here() { "record_auth_attempt", "clear_auth_attempts", "prune_auth_attempts", + // A lease is one pass saying "mine" for the length of a send, and the + // write that follows it — accepted, refused, held — announces. Saying + // so twice would wake every open queue screen on the way past a value + // that is about to be overwritten. + "claim_sends_owed", ]; let source = include_str!("../src/store/turso_store.rs"); diff --git a/crates/izlek-web/tests/http.rs b/crates/izlek-web/tests/http.rs index 092a718..4d97fd1 100644 --- a/crates/izlek-web/tests/http.rs +++ b/crates/izlek-web/tests/http.rs @@ -5985,12 +5985,12 @@ async fn a_task_with_a_notification(app: &App, admin_cookie: &str, subject: &str .unwrap(); let send = app .store - .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now) .await .unwrap() .unwrap(); app.store.record_send_accepted(&send.id, now).await.unwrap(); - (task, send.id) + (task, send.id.clone()) } /// A task's detail page shows its notifications: the recipient and a state