forge
Explore
Log in

Don't you dare go Hollow

A row that is owed is not a row that is yours

Browse files at this commit

97e905011f8bed9ad7c566b653e4474cb13ddb5dAhmet Kaan GümüşParent: c9b8984
  • fix
    • a row that is owed is not a row that is yours
Show full message
🐛 fix(mail): a row that is owed is not a row that is yours

Three invited members arrived as six mails. Queueing an invite both spawns a
delivery pass off the request and announces the queue, which wakes the sweep
— and `sends_owed` was a bare SELECT of everything due. A row keeps looking
due until the send comes back, so both passes read the same row, and each
spent its own network round-trip on it.

The reading and the claiming are now one store call. `claim_sends_owed`
moves each row out of the due window before returning it, under the single
connection every path already shares, and hands back only what it took: the
pass arriving second gets a shorter list, not a duplicate. The lease is a
lease and not a deletion, so a process that dies mid-send gives the mail
back — late beats never for a mail nobody received.

What it returns is a `ClaimedSend`, and `Engine::attempt` takes nothing
else. That is the part meant to outlive us: a row that was merely read —
by `sends_owed`, by a queue screen, by a test — will not compile into a
mail, so the next delivery loop cannot reintroduce this by forgetting a
rule written in a comment.

Making it a type immediately found the same defect a second time, in code
that looked safe: rule-driven mail claims its crossing with a unique index,
then sent the row it had just written. The index stops a crossing being
*owed* twice and says nothing about the one row being *sent* twice — and
writing that row announces the queue, which wakes the sweep while the
crossing is still composing. Rows written mid-pass are therefore born held.
Reverting just that lease turns the new crossing test red with two mails, so
this was live, not theoretical.
crates/izlek-core/src/mail.rsmodified+25 -4
@@ -31,7 +31,8 @@ use time::{Duration, OffsetDateTime};
31 use crate::board::Transition;31 use crate::board::Transition;
32 use crate::detail::ActivityKind;32 use crate::detail::ActivityKind;
33 use crate::store::{33 use crate::store::{
34- ActivityEvent, Audience, Event, Freeing, MailOutcome, MailRule, MailSend, SendKind, Store,34+ ActivityEvent, Audience, ClaimedSend, Event, Freeing, MailOutcome, MailRule, MailSend, SendKind,
35+ Store,
35 Trigger,36 Trigger,
36 };37 };
37 38
@@ -113,6 +114,15 @@ pub const MAX_ATTEMPTS: u32 = 5;
113 /// to see whether mail starts moving.114 /// to see whether mail starts moving.
114 pub const HOLD: Duration = Duration::minutes(1);115 pub const HOLD: Duration = Duration::minutes(1);
115 116
117+/// How long a delivery pass holds a row it is about to send, so a second pass
118+/// running at the same moment leaves it alone.
119+///
120+/// It is a lease and not a removal: if this process dies between taking the
121+/// row and writing down what happened, the row falls due again after this and
122+/// the mail goes late instead of never. Long enough to cover a mail server
123+/// that is thinking about it, short enough that a crash is not a lost day.
124+pub const LEASE: Duration = Duration::minutes(5);
125+
116 /// The wait before the next attempt, doubling and capped: five minutes, ten,126 /// The wait before the next attempt, doubling and capped: five minutes, ten,
117 /// twenty, forty, an hour.127 /// twenty, forty, an hour.
118 pub fn backoff(attempts: u32) -> Duration {128 pub fn backoff(attempts: u32) -> Duration {
@@ -524,7 +534,14 @@ impl Engine {
524 for recipient in audience {534 for recipient in audience {
525 let claimed = self535 let claimed = self
526 .store536 .store
527- .claim_send(&rule.id, event.id(), task_id, &recipient.email, now)537+ .claim_send(
538+ &rule.id,
539+ event.id(),
540+ task_id,
541+ &recipient.email,
542+ now,
543+ now + LEASE,
544+ )
528 .await?;545 .await?;
529 match claimed {546 match claimed {
530 Some(send) => {547 Some(send) => {
@@ -567,7 +584,11 @@ impl Engine {
567 limit: u32,584 limit: u32,
568 ) -> crate::store::Result<Report> {585 ) -> crate::store::Result<Report> {
569 let mut report = Report::default();586 let mut report = Report::default();
570- for send in self.store.sends_owed(now, limit).await? {587+ // Claimed, not merely owed: the request that queued a mail spawns a
588+ // pass and the same write wakes the sweep, so two passes reach the
589+ // same row together. Each is handed only what it took, and only a
590+ // `ClaimedSend` can be mailed. See `Store::claim_sends_owed`.
591+ for send in self.store.claim_sends_owed(now, now + LEASE, limit).await? {
571 // An invite and an admin's notice both owe no rule and no event:592 // An invite and an admin's notice both owe no rule and no event:
572 // each carries its own subject and body, composed once at mint593 // each carries its own subject and body, composed once at mint
573 // time. Without this arm a notice falls through to the rule path,594 // time. Without this arm a notice falls through to the rule path,
@@ -602,7 +623,7 @@ impl Engine {
602 /// One attempt, and the ledger line it leaves behind.623 /// One attempt, and the ledger line it leaves behind.
603 async fn attempt(624 async fn attempt(
604 &self,625 &self,
605- send: &MailSend,626+ send: &ClaimedSend,
606 mail: Option<Outgoing>,627 mail: Option<Outgoing>,
607 report: &mut Report,628 report: &mut Report,
608 ) -> crate::store::Result<()> {629 ) -> crate::store::Result<()> {
crates/izlek-core/src/store/mod.rsmodified+70 -1
@@ -367,6 +367,39 @@ impl SendKind {
367 }367 }
368 }368 }
369 369
370+/// A send this delivery pass holds, and the only thing the engine will mail.
371+///
372+/// The duplicate-invite bug was not that somebody forgot to claim a row. It
373+/// was that the delivery path *could* read a row and mail it without claiming
374+/// it — two passes did, and an invited member got two identical mails. A
375+/// comment saying "claim first" is a fix that lasts until the next person
376+/// writes the next delivery loop.
377+///
378+/// So the reading and the claiming are one operation
379+/// ([`claim_sends_owed`](Store::claim_sends_owed)), and what it hands back is
380+/// this rather than a bare [`MailSend`]. Only the store builds one, and
381+/// `Engine::attempt` accepts nothing else, so a row that was merely *read* —
382+/// by [`sends_owed`](Store::sends_owed), by a queue screen, by a test — will
383+/// not compile into a mail. The rule is carried by the type instead of by
384+/// whoever remembers it.
385+#[derive(Debug, Clone)]
386+pub struct ClaimedSend(MailSend);
387+
388+impl ClaimedSend {
389+ /// Built only where a row was actually taken: the store's claim.
390+ pub(crate) fn taken(send: MailSend) -> Self {
391+ Self(send)
392+ }
393+}
394+
395+impl std::ops::Deref for ClaimedSend {
396+ type Target = MailSend;
397+
398+ fn deref(&self) -> &MailSend {
399+ &self.0
400+ }
401+}
402+
370 /// One mail a rule owes one person, or an invite that owes nobody, and what403 /// One mail a rule owes one person, or an invite that owes nobody, and what
371 /// happened to it. `rule_id`/`event_id`/`task_id` are `None` on an invite404 /// happened to it. `rule_id`/`event_id`/`task_id` are `None` on an invite
372 /// send; `subject`/`body` are `None` on a rule send, which composes its own405 /// send; `subject`/`body` are `None` on a rule send, which composes its own
@@ -1010,6 +1043,12 @@ pub trait Store: BoardReads + DetailReads + 'static {
1010 /// Nothing is handed to the mail server before this row exists, so a1043 /// Nothing is handed to the mail server before this row exists, so a
1011 /// crash mid-send leaves a row that says pending rather than a mail1044 /// crash mid-send leaves a row that says pending rather than a mail
1012 /// nobody can account for.1045 /// nobody can account for.
1046+ ///
1047+ /// The row is born held until `until`, because writing it announces the
1048+ /// queue and the sweep wakes on that announcement — a row inserted due
1049+ /// now is a row the sweep can be mailing while the pass that created it
1050+ /// is also mailing it. The index stops the crossing being owed twice; the
1051+ /// lease stops the one row being sent twice.
1013 async fn claim_send(1052 async fn claim_send(
1014 &self,1053 &self,
1015 rule_id: &str,1054 rule_id: &str,
@@ -1017,7 +1056,8 @@ pub trait Store: BoardReads + DetailReads + 'static {
1017 task_id: &str,1056 task_id: &str,
1018 recipient: &str,1057 recipient: &str,
1019 at: OffsetDateTime,1058 at: OffsetDateTime,
1020- ) -> Result<Option<MailSend>>;1059+ until: OffsetDateTime,
1060+ ) -> Result<Option<ClaimedSend>>;
1021 1061
1022 /// Holds an invite mail: pending, no rule, no event, no task.1062 /// Holds an invite mail: pending, no rule, no event, no task.
1023 async fn queue_invite(1063 async fn queue_invite(
@@ -1067,8 +1107,37 @@ pub trait Store: BoardReads + DetailReads + 'static {
1067 ) -> Result<()>;1107 ) -> Result<()>;
1068 1108
1069 /// Sends owed right now: claimed but never accepted, and due.1109 /// Sends owed right now: claimed but never accepted, and due.
1110+ ///
1111+ /// This is a read, for looking: what it returns is a [`MailSend`], which
1112+ /// the engine cannot mail. Delivery goes through
1113+ /// [`claim_sends_owed`](Store::claim_sends_owed).
1070 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>>;1114 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>>;
1071 1115
1116+ /// Takes the sends owed right now for this pass, and hands back only the
1117+ /// ones it actually got.
1118+ ///
1119+ /// Two things deliver: the pass spawned off the request that queued the
1120+ /// mail, and the sweep, which the same queue write wakes. Both used to
1121+ /// read the ledger and then go to the mail server, and a row does not stop
1122+ /// looking owed until the send comes back — so both saw the same row as
1123+ /// owed and an invited member was mailed twice.
1124+ ///
1125+ /// Reading and claiming are therefore one operation. Every row returned
1126+ /// has already been moved out of the due window, in the same call, before
1127+ /// anyone can spend a network round-trip on it; a pass arriving second
1128+ /// gets a shorter list, not a duplicate.
1129+ ///
1130+ /// `until` is a lease rather than a removal, because a process that dies
1131+ /// between claiming and recording must not take the mail with it. The row
1132+ /// falls due again then, and is sent late rather than never — which is the
1133+ /// right way round for a mail nobody has received.
1134+ async fn claim_sends_owed(
1135+ &self,
1136+ now: OffsetDateTime,
1137+ until: OffsetDateTime,
1138+ limit: u32,
1139+ ) -> Result<Vec<ClaimedSend>>;
1140+
1072 /// When the next mail falls due, whether or not that is yet.1141 /// When the next mail falls due, whether or not that is yet.
1073 ///1142 ///
1074 /// The sweep asks this so it can sleep exactly that long instead of waking1143 /// The sweep asks this so it can sleep exactly that long instead of waking
crates/izlek-core/src/store/turso_store.rsmodified+53 -5
@@ -16,7 +16,8 @@ use ulid::Ulid;
16 use super::secret;16 use super::secret;
17 use super::{17 use super::{
18 ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion,18 ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion,
19- Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, MailSend,19+ ClaimedSend, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,
20+ MailSend,
20 NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,21 NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,
21 SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User,22 SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User,
22 Workspace,23 Workspace,
@@ -2880,7 +2881,8 @@ impl Store for TursoStore {
2880 task_id: &str,2881 task_id: &str,
2881 recipient: &str,2882 recipient: &str,
2882 at: OffsetDateTime,2883 at: OffsetDateTime,
2883- ) -> Result<Option<MailSend>> {2884+ until: OffsetDateTime,
2885+ ) -> Result<Option<ClaimedSend>> {
2884 let id = Ulid::new().to_string();2886 let id = Ulid::new().to_string();
2885 // The index is the decision. `DO NOTHING` turns the second engine run2887 // The index is the decision. `DO NOTHING` turns the second engine run
2886 // into zero rows affected rather than an error to interpret, and the2888 // into zero rows affected rather than an error to interpret, and the
@@ -2893,7 +2895,7 @@ impl Store for TursoStore {
2893 "INSERT INTO mail_send \2895 "INSERT INTO mail_send \
2894 (id, rule_id, event_id, task_id, recipient, state, attempts, claimed_at, \2896 (id, rule_id, event_id, task_id, recipient, state, attempts, claimed_at, \
2895 next_attempt_at) \2897 next_attempt_at) \
2896- VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6) \2898+ VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?7) \
2897 ON CONFLICT (rule_id, event_id, task_id, recipient) DO NOTHING",2899 ON CONFLICT (rule_id, event_id, task_id, recipient) DO NOTHING",
2898 params![2900 params![
2899 id.clone(),2901 id.clone(),
@@ -2901,7 +2903,8 @@ impl Store for TursoStore {
2901 event_id,2903 event_id,
2902 task_id,2904 task_id,
2903 recipient,2905 recipient,
2904- stamp(at)?2906+ stamp(at)?,
2907+ stamp(until)?
2905 ],2908 ],
2906 )2909 )
2907 .await2910 .await
@@ -2913,7 +2916,7 @@ impl Store for TursoStore {
2913 self.announce([Topic::Queue]);2916 self.announce([Topic::Queue]);
2914 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");2917 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");
2915 match self.one_row(&sql, params![id]).await? {2918 match self.one_row(&sql, params![id]).await? {
2916- Some(row) => send_from(&row).map(Some),2919+ Some(row) => send_from(&row).map(ClaimedSend::taken).map(Some),
2917 None => Err(StoreError::NotFound),2920 None => Err(StoreError::NotFound),
2918 }2921 }
2919 }2922 }
@@ -3085,6 +3088,51 @@ impl Store for TursoStore {
3085 }3088 }
3086 }3089 }
3087 3090
3091+ async fn claim_sends_owed(
3092+ &self,
3093+ now: OffsetDateTime,
3094+ until: OffsetDateTime,
3095+ limit: u32,
3096+ ) -> Result<Vec<ClaimedSend>> {
3097+ // One lock across the read and every claim: no second pass is inside
3098+ // this while it runs, and every path into this store goes through the
3099+ // same connection.
3100+ let conn = self.conn.lock().await;
3101+ let sql = format!(
3102+ "SELECT {SEND_COLUMNS} FROM mail_send \
3103+ WHERE next_attempt_at IS NOT NULL AND next_attempt_at <= ?1 \
3104+ ORDER BY next_attempt_at LIMIT ?2"
3105+ );
3106+ let mut rows = conn
3107+ .query(&sql, params![stamp(now)?, i64::from(limit)])
3108+ .await
3109+ .map_err(backend)?;
3110+ let mut due = Vec::new();
3111+ while let Some(row) = rows.next().await.map_err(backend)? {
3112+ due.push(send_from(&row)?);
3113+ }
3114+
3115+ let mut taken = Vec::new();
3116+ for send in due {
3117+ // The `next_attempt_at <= ?2` is the whole of the exclusion: a
3118+ // pass that gets here after this row was leased finds it pushed
3119+ // out of the window and changes nothing, so it is not returned to
3120+ // that pass either.
3121+ let moved = conn
3122+ .execute(
3123+ "UPDATE mail_send SET next_attempt_at = ?1 \
3124+ WHERE id = ?3 AND next_attempt_at IS NOT NULL AND next_attempt_at <= ?2",
3125+ params![stamp(until)?, stamp(now)?, send.id.as_str()],
3126+ )
3127+ .await
3128+ .map_err(backend)?;
3129+ if moved == 1 {
3130+ taken.push(ClaimedSend::taken(send));
3131+ }
3132+ }
3133+ Ok(taken)
3134+ }
3135+
3088 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>> {3136 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>> {
3089 let conn = self.conn.lock().await;3137 let conn = self.conn.lock().await;
3090 let sql = format!(3138 let sql = format!(
crates/izlek-core/tests/store.rsmodified+167 -15
@@ -3637,7 +3637,7 @@ async fn the_index_decides_who_owns_a_send() {
3637 let now = OffsetDateTime::now_utc();3637 let now = OffsetDateTime::now_utc();
3638 let first = scratch3638 let first = scratch
3639 .store3639 .store
3640- .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)3640+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now)
3641 .await3641 .await
3642 .unwrap();3642 .unwrap();
3643 assert!(first.is_some(), "the first run owns the send");3643 assert!(first.is_some(), "the first run owns the send");
@@ -3647,7 +3647,7 @@ async fn the_index_decides_who_owns_a_send() {
3647 // first: the insert loses.3647 // first: the insert loses.
3648 let second = scratch3648 let second = scratch
3649 .store3649 .store
3650- .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)3650+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now)
3651 .await3651 .await
3652 .unwrap();3652 .unwrap();
3653 assert!(second.is_none(), "the second run owns nothing");3653 assert!(second.is_none(), "the second run owns nothing");
@@ -3683,7 +3683,7 @@ async fn a_second_crossing_is_a_second_send() {
3683 assert!(3683 assert!(
3684 scratch3684 scratch
3685 .store3685 .store
3686- .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)3686+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now)
3687 .await3687 .await
3688 .unwrap()3688 .unwrap()
3689 .is_some()3689 .is_some()
@@ -3717,7 +3717,7 @@ async fn a_refused_send_is_recorded_and_owed_again() {
3717 let now = OffsetDateTime::now_utc();3717 let now = OffsetDateTime::now_utc();
3718 let send = scratch3718 let send = scratch
3719 .store3719 .store
3720- .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)3720+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now)
3721 .await3721 .await
3722 .unwrap()3722 .unwrap()
3723 .unwrap();3723 .unwrap();
@@ -3770,7 +3770,7 @@ async fn a_refused_address_is_not_retried_forever() {
3770 let now = OffsetDateTime::now_utc();3770 let now = OffsetDateTime::now_utc();
3771 let send = scratch3771 let send = scratch
3772 .store3772 .store
3773- .claim_send(&rule.id, &transition.id, &task, "gone@izlek.sh", now)3773+ .claim_send(&rule.id, &transition.id, &task, "gone@izlek.sh", now, now)
3774 .await3774 .await
3775 .unwrap()3775 .unwrap()
3776 .unwrap();3776 .unwrap();
@@ -3813,7 +3813,7 @@ async fn an_accepted_send_stops_being_owed() {
3813 let now = OffsetDateTime::now_utc();3813 let now = OffsetDateTime::now_utc();
3814 let send = scratch3814 let send = scratch
3815 .store3815 .store
3816- .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)3816+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now)
3817 .await3817 .await
3818 .unwrap()3818 .unwrap()
3819 .unwrap();3819 .unwrap();
@@ -3903,7 +3903,7 @@ async fn deleting_a_rule_takes_its_ledger_with_it() {
3903 let now = OffsetDateTime::now_utc();3903 let now = OffsetDateTime::now_utc();
3904 scratch3904 scratch
3905 .store3905 .store
3906- .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)3906+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now)
3907 .await3907 .await
3908 .unwrap();3908 .unwrap();
3909 3909
@@ -5006,13 +5006,13 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() {
5006 let now = OffsetDateTime::now_utc();5006 let now = OffsetDateTime::now_utc();
5007 5007
5008 let pending = store5008 let pending = store
5009- .claim_send(&rule.id, &transition.id, &task, "pending@izlek.sh", now)5009+ .claim_send(&rule.id, &transition.id, &task, "pending@izlek.sh", now, now)
5010 .await5010 .await
5011 .unwrap()5011 .unwrap()
5012 .unwrap();5012 .unwrap();
5013 5013
5014 let failed = store5014 let failed = store
5015- .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now)5015+ .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now, now)
5016 .await5016 .await
5017 .unwrap()5017 .unwrap()
5018 .unwrap();5018 .unwrap();
@@ -5022,14 +5022,14 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() {
5022 .unwrap();5022 .unwrap();
5023 5023
5024 let sent = store5024 let sent = store
5025- .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now)5025+ .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now, now)
5026 .await5026 .await
5027 .unwrap()5027 .unwrap()
5028 .unwrap();5028 .unwrap();
5029 store.record_send_accepted(&sent.id, now).await.unwrap();5029 store.record_send_accepted(&sent.id, now).await.unwrap();
5030 5030
5031 let abandoned = store5031 let abandoned = store
5032- .claim_send(&rule.id, &transition.id, &task, "abandoned@izlek.sh", now)5032+ .claim_send(&rule.id, &transition.id, &task, "abandoned@izlek.sh", now, now)
5033 .await5033 .await
5034 .unwrap()5034 .unwrap()
5035 .unwrap();5035 .unwrap();
@@ -5092,6 +5092,153 @@ async fn an_invite_mail_with_no_sender_is_held_not_failed() {
5092 let _ = std::fs::remove_dir_all(&dir);5092 let _ = std::fs::remove_dir_all(&dir);
5093 }5093 }
5094 5094
5095+/// A mailer that takes its time, so a second pass has somewhere to arrive.
5096+struct Dawdling {
5097+ sent: Mutex<Vec<Outgoing>>,
5098+}
5099+
5100+#[async_trait::async_trait]
5101+impl Mailer for Dawdling {
5102+ async fn send(&self, mail: &Outgoing) -> Result<(), MailError> {
5103+ // The window the bug lived in: the row still looks owed for as long as
5104+ // the mail server is thinking about it.
5105+ tokio::time::sleep(std::time::Duration::from_millis(150)).await;
5106+ self.sent.lock().unwrap().push(mail.clone());
5107+ Ok(())
5108+ }
5109+}
5110+
5111+#[tokio::test]
5112+async fn two_passes_over_one_owed_mail_send_it_once() {
5113+ // Queueing an invite both spawns a delivery pass off the request and wakes
5114+ // the sweep, so two passes read the ledger at the same moment. Owed is not
5115+ // ownership: whoever loses the claim must not also send. Three invited
5116+ // members once arrived as six mails.
5117+ let (dir, store, _workspace, _admin) = shared().await;
5118+ let now = OffsetDateTime::now_utc();
5119+ store
5120+ .queue_invite("newcomer@izlek.sh", "Join İzlek", "Come aboard.", now)
5121+ .await
5122+ .unwrap();
5123+
5124+ let mailer = Arc::new(Dawdling {
5125+ sent: Mutex::new(Vec::new()),
5126+ });
5127+ // Two engines over one store, which is what the process actually has: the
5128+ // request's pass and the sweep's.
5129+ let request = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5130+ let sweep = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5131+ let (a, b) = tokio::join!(
5132+ request.deliver_owed(now, 10),
5133+ sweep.deliver_owed(now, 10),
5134+ );
5135+ let (a, b) = (a.unwrap(), b.unwrap());
5136+
5137+ let sent = mailer.sent.lock().unwrap().len();
5138+ assert_eq!(
5139+ sent, 1,
5140+ "one queued invite left as {sent} mails: the loser of the claim sent it too"
5141+ );
5142+ assert_eq!(
5143+ a.sent + b.sent,
5144+ 1,
5145+ "both passes reported sending the same mail"
5146+ );
5147+
5148+ // The winner wrote down that it went, so the row does not come back when
5149+ // the lease runs out — the loser leaving it alone is not the same as the
5150+ // mail being dropped.
5151+ let owed = store
5152+ .sends_owed(now + izlek_core::mail::LEASE + Duration::seconds(1), 10)
5153+ .await
5154+ .unwrap();
5155+ assert!(
5156+ owed.is_empty(),
5157+ "a mail that was sent is owed again once the lease expires"
5158+ );
5159+ let _ = std::fs::remove_dir_all(&dir);
5160+}
5161+
5162+#[tokio::test]
5163+async fn a_crossing_and_a_sweep_at_the_same_moment_mail_once() {
5164+ // The unique index stops a crossing being *owed* twice. It does nothing
5165+ // about the one row being *sent* twice: writing it announces the queue,
5166+ // which wakes the sweep, while the pass that wrote it is still composing.
5167+ // The row is therefore born held, and this is the test that says so.
5168+ let (dir, store, workspace, admin) = shared().await;
5169+ let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
5170+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
5171+ store.assign_task(&task, &mate).await.unwrap();
5172+ let _rule = a_rule(&store, &workspace, "Done", "Task completed").await;
5173+ let transition = moved_to(&store, &workspace, &task, "Backlog", "Done", &admin).await;
5174+
5175+ let mailer = Arc::new(Dawdling {
5176+ sent: Mutex::new(Vec::new()),
5177+ });
5178+ let crossing = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5179+ let sweep = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5180+
5181+ // The sweep passes run while the crossing is inside its send, which is
5182+ // exactly when the row it just wrote is sitting in the ledger.
5183+ let (crossed, _swept) = tokio::join!(crossing.on_transition(&transition), async {
5184+ for _ in 0..4 {
5185+ let _ = sweep
5186+ .deliver_owed(OffsetDateTime::now_utc(), 10)
5187+ .await
5188+ .unwrap();
5189+ tokio::time::sleep(std::time::Duration::from_millis(40)).await;
5190+ }
5191+ });
5192+ crossed.unwrap();
5193+
5194+ let sent = mailer.sent.lock().unwrap().len();
5195+ assert_eq!(
5196+ sent, 1,
5197+ "one crossing left as {sent} mails: the sweep sent the row the crossing was sending"
5198+ );
5199+ let _ = std::fs::remove_dir_all(&dir);
5200+}
5201+
5202+#[tokio::test]
5203+async fn a_lease_that_expires_gives_the_mail_back() {
5204+ // The claim is a lease, not a deletion: a process that dies between taking
5205+ // a row and writing down what happened must not take the mail with it.
5206+ let (scratch, _workspace, _admin) = workspace_with_admin().await;
5207+ let store = &scratch.store;
5208+ let now = OffsetDateTime::now_utc();
5209+ let invite = store
5210+ .queue_invite("newcomer@izlek.sh", "Join İzlek", "Come aboard.", now)
5211+ .await
5212+ .unwrap();
5213+
5214+ let mine = store
5215+ .claim_sends_owed(now, now + izlek_core::mail::LEASE, 10)
5216+ .await
5217+ .unwrap();
5218+ assert!(
5219+ mine.iter().any(|s| s.id == invite.id),
5220+ "the first pass did not get a mail nobody holds"
5221+ );
5222+ let theirs = store
5223+ .claim_sends_owed(now, now + izlek_core::mail::LEASE, 10)
5224+ .await
5225+ .unwrap();
5226+ assert!(
5227+ !theirs.iter().any(|s| s.id == invite.id),
5228+ "a second pass was handed a mail that was already held"
5229+ );
5230+ // Nobody wrote the outcome down, so once the lease is out the mail is owed
5231+ // again rather than lost.
5232+ let owed = store
5233+ .sends_owed(now + izlek_core::mail::LEASE + Duration::seconds(1), 10)
5234+ .await
5235+ .unwrap();
5236+ assert!(
5237+ owed.iter().any(|s| s.id == invite.id),
5238+ "an abandoned lease swallowed the mail"
5239+ );
5240+}
5241+
5095 #[tokio::test]5242 #[tokio::test]
5096 async fn the_activity_feed_is_the_whole_workspace_newest_first() {5243 async fn the_activity_feed_is_the_whole_workspace_newest_first() {
5097 let (scratch, workspace, admin) = workspace_with_admin().await;5244 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() {
5457 .await5604 .await
5458 .unwrap();5605 .unwrap();
5459 let send = store5606 let send = store
5460- .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)5607+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now)
5461 .await5608 .await
5462 .unwrap()5609 .unwrap()
5463 .unwrap();5610 .unwrap();
5464 store5611 store
5465- .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now)5612+ .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now, now)
5466 .await5613 .await
5467 .unwrap();5614 .unwrap();
5468 5615
@@ -5486,7 +5633,7 @@ async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() {
5486 let now = OffsetDateTime::now_utc();5633 let now = OffsetDateTime::now_utc();
5487 5634
5488 let failed = store5635 let failed = store
5489- .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now)5636+ .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now, now)
5490 .await5637 .await
5491 .unwrap()5638 .unwrap()
5492 .unwrap();5639 .unwrap();
@@ -5496,7 +5643,7 @@ async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() {
5496 .unwrap();5643 .unwrap();
5497 5644
5498 let sent = store5645 let sent = store
5499- .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now)5646+ .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now, now)
5500 .await5647 .await
5501 .unwrap()5648 .unwrap()
5502 .unwrap();5649 .unwrap();
@@ -5847,6 +5994,11 @@ fn every_writing_method_announces_or_is_named_here() {
5847 "record_auth_attempt",5994 "record_auth_attempt",
5848 "clear_auth_attempts",5995 "clear_auth_attempts",
5849 "prune_auth_attempts",5996 "prune_auth_attempts",
5997+ // A lease is one pass saying "mine" for the length of a send, and the
5998+ // write that follows it — accepted, refused, held — announces. Saying
5999+ // so twice would wake every open queue screen on the way past a value
6000+ // that is about to be overwritten.
6001+ "claim_sends_owed",
5850 ];6002 ];
5851 6003
5852 let source = include_str!("../src/store/turso_store.rs");6004 let source = include_str!("../src/store/turso_store.rs");
crates/izlek-web/tests/http.rsmodified+2 -2
@@ -5985,12 +5985,12 @@ async fn a_task_with_a_notification(app: &App, admin_cookie: &str, subject: &str
5985 .unwrap();5985 .unwrap();
5986 let send = app5986 let send = app
5987 .store5987 .store
5988- .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)5988+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now, now)
5989 .await5989 .await
5990 .unwrap()5990 .unwrap()
5991 .unwrap();5991 .unwrap();
5992 app.store.record_send_accepted(&send.id, now).await.unwrap();5992 app.store.record_send_accepted(&send.id, now).await.unwrap();
5993- (task, send.id)5993+ (task, send.id.clone())
5994 }5994 }
5995 5995
5996 /// A task's detail page shows its notifications: the recipient and a state5996 /// A task's detail page shows its notifications: the recipient and a state