arcature 0.1.2

Arcature: an opinionated full-stack Rust web framework. One package, batteries included.
Documentation
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! The thing that actually delivers.

use std::fmt;

use crate::mail::{Email, EmailError, Mail, Mailable, lettre::Message};

#[cfg(feature = "notifications-broadcast")]
use super::broadcast::BroadcastNotifications;
use super::channel::{Channel, NotificationError};
use super::notification::{BroadcastContent, DatabaseContent, MailContent, Notification};
#[cfg(feature = "notifications-queue")]
use super::queue::{NotificationQueue, QueuedMail};
use super::recipient::Notifiable;
#[cfg(feature = "notifications-db")]
use super::store::DatabaseNotifications;

/// Which channels a notification actually reached.
///
/// Returned rather than discarded because "delivered to nothing" is a real
/// outcome and an invisible one: a notification whose `to_mail` returns
/// `None` for everybody is indistinguishable from a working one unless the
/// caller can ask.
/// A channel a notification was *handed to* rather than delivered over is
/// reported separately, because the two are different promises. A channel in
/// [`Delivery::channels`] has run: the message left the process. A channel in
/// [`Delivery::queued`] has been written down and will run later, or will
/// not, and the caller finds out from the queue rather than from here.
///
/// Folding the two together would make [`Delivery::reached`] say yes to a job
/// row -- which is the one answer nobody would want it to give.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct Delivery {
    channels: Vec<Channel>,
    queued: Vec<Channel>,
}

impl Delivery {
    /// The channels that delivered, in the order they were tried.
    #[must_use]
    pub fn channels(&self) -> &[Channel] {
        &self.channels
    }

    /// Whether a particular channel delivered.
    #[must_use]
    pub fn reached(&self, channel: Channel) -> bool {
        self.channels.contains(&channel)
    }

    /// The channels that were handed to the queue instead of run inline.
    ///
    /// Only [`Notifier::queue`] populates this; a plain
    /// [`send`](Notifier::send) always leaves it empty.
    #[must_use]
    pub fn queued(&self) -> &[Channel] {
        &self.queued
    }

    /// Whether a particular channel was queued rather than delivered.
    #[must_use]
    pub fn is_queued(&self, channel: Channel) -> bool {
        self.queued.contains(&channel)
    }

    /// Whether the notification neither reached anybody nor was queued for
    /// anybody.
    ///
    /// A queued channel counts as not-empty. The question this answers is
    /// "did asking to notify this person amount to nothing", and a job row
    /// waiting to be run is not nothing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.channels.is_empty() && self.queued.is_empty()
    }
}

/// Delivers notifications over the channels it has been given.
///
/// A notifier holds one backing per channel and knows nothing about any
/// particular notification. It is cheap to clone and is meant to live in
/// application state.
///
/// # Failure is loud
///
/// If a notification renders content for a channel this notifier was not
/// built with, [`Notifier::send`] returns
/// [`NotificationError::NotConfigured`] rather than skipping it. Skipping
/// would turn a missing `.with_mail(..)` at startup into mail that silently
/// never arrives -- discovered, if ever, by a user who did not get their
/// password reset.
///
/// # Example
///
/// ```
/// use arcature::mail::{Mail, Mailer};
/// use arcature::notifications::{Channel, MailContent, Notification, Notifier, Recipient};
///
/// struct PasswordChanged;
///
/// impl Notification for PasswordChanged {
///     fn to_mail(&self, recipient: &Recipient) -> Option<MailContent> {
///         recipient.email_address()?;
///         Some(MailContent::new(
///             "Your password was changed",
///             "If this was not you, reset it immediately.",
///         ))
///     }
/// }
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // `capture_ok` accepts every message and sends nothing: what a test wants.
/// let mailer = Mailer::capture_ok();
/// let notifier = Notifier::new()
///     .with_mail(Mail::new(mailer.clone(), "noreply@example.com".parse()?));
///
/// let ada = Recipient::new("user:42").email("ada@example.com");
/// let delivery = notifier.send(&ada, &PasswordChanged).await?;
///
/// assert!(delivery.reached(Channel::Mail));
/// assert_eq!(mailer.captured().await.unwrap().len(), 1);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct Notifier {
    mail: Option<Mail>,
    #[cfg(feature = "notifications-db")]
    database: Option<DatabaseNotifications>,
    #[cfg(feature = "notifications-broadcast")]
    broadcast: Option<BroadcastNotifications>,
    #[cfg(feature = "notifications-queue")]
    queue: Option<NotificationQueue>,
}

impl fmt::Debug for Notifier {
    /// Reports which channels are wired, not what is behind them: a
    /// `Mailer` holds SMTP credentials and a pool holds a database URL, and a
    /// `Debug` that printed either would put it in the first log line that
    /// formats application state.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = f.debug_struct("Notifier");
        out.field("mail", &self.mail.is_some());
        #[cfg(feature = "notifications-db")]
        out.field("database", &self.database.is_some());
        #[cfg(feature = "notifications-broadcast")]
        out.field("broadcast", &self.broadcast.is_some());
        #[cfg(feature = "notifications-queue")]
        out.field("queue", &self.queue.is_some());
        out.finish()
    }
}

impl Notifier {
    /// A notifier with no channels. Every notification it is given will fail
    /// with [`NotificationError::NotConfigured`] until one is added.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable the mail channel.
    #[must_use]
    pub fn with_mail(mut self, mail: Mail) -> Self {
        self.mail = Some(mail);
        self
    }

    /// Whether the mail channel is wired.
    #[must_use]
    pub fn has_mail(&self) -> bool {
        self.mail.is_some()
    }

    /// Enable the in-app inbox channel.
    ///
    /// The store does not create its own table. Call
    /// [`DatabaseNotifications::migrate`] once at startup, or run the
    /// migration alongside the application's own.
    #[cfg(feature = "notifications-db")]
    #[must_use]
    pub fn with_database(mut self, database: DatabaseNotifications) -> Self {
        self.database = Some(database);
        self
    }

    /// Whether the in-app inbox channel is wired.
    #[cfg(feature = "notifications-db")]
    #[must_use]
    pub fn has_database(&self) -> bool {
        self.database.is_some()
    }

    /// Enable the live push channel.
    ///
    /// Wiring it says the application *can* push, not that anyone is
    /// listening. A recipient with no open connection is the ordinary case,
    /// and a push to them succeeds having reached nobody.
    #[cfg(feature = "notifications-broadcast")]
    #[must_use]
    pub fn with_broadcast(mut self, broadcast: BroadcastNotifications) -> Self {
        self.broadcast = Some(broadcast);
        self
    }

    /// Whether the live push channel is wired.
    #[cfg(feature = "notifications-broadcast")]
    #[must_use]
    pub fn has_broadcast(&self) -> bool {
        self.broadcast.is_some()
    }

    /// Enable [`Notifier::queue`].
    ///
    /// Wiring a queue changes nothing about [`Notifier::send`], which still
    /// talks to the SMTP server inline. The two are separate methods so that
    /// a handler asking to defer is saying so, rather than finding out from
    /// whether startup happened to call this.
    #[cfg(feature = "notifications-queue")]
    #[must_use]
    pub fn with_queue(mut self, queue: NotificationQueue) -> Self {
        self.queue = Some(queue);
        self
    }

    /// Whether a queue is wired.
    #[cfg(feature = "notifications-queue")]
    #[must_use]
    pub fn has_queue(&self) -> bool {
        self.queue.is_some()
    }

    /// Render `notification` for `to` and deliver it on every channel it
    /// produced content for.
    ///
    /// # Errors
    ///
    /// - [`NotificationError::NotConfigured`] if the notification wants a
    ///   channel this notifier has no backing for.
    /// - [`NotificationError::NoAddress`] if it wants the mail channel for a
    ///   recipient with no email address.
    /// - [`NotificationError::Mail`] if the transport refuses the message.
    /// - [`NotificationError::Database`] if the inbox row cannot be written.
    /// - [`NotificationError::Encode`] if a broadcast payload cannot be
    ///   serialised.
    ///
    /// Delivery stops at the first failing channel, and the order the channels
    /// run in is therefore part of the contract: **inbox, then live push, then
    /// mail** -- the durable local record first, then the local push, then the
    /// one thing that leaves this process. The inbox cannot fail for a reason
    /// outside the application, so writing it first means an SMTP server that
    /// is down leaves the notification visible in the application rather than
    /// losing it along with the email. The reverse order would trade a
    /// recoverable failure for an unrecoverable one.
    ///
    /// The [`Delivery`] a successful call returns is the record of what did go
    /// out. [`Channel::Broadcast`] appears in it only when at least one
    /// connection received the push: a recipient who is not connected is not
    /// an error, and recording the channel as delivered when nobody was
    /// listening would make the record say something it does not know.
    pub async fn send<N>(
        &self,
        to: &impl Notifiable,
        notification: &N,
    ) -> Result<Delivery, NotificationError>
    where
        N: Notification + ?Sized,
    {
        let recipient = to.recipient();
        let mut channels = Vec::new();

        if let Some(content) = notification.to_database(&recipient) {
            self.deliver_database(recipient.key(), &content).await?;
            channels.push(Channel::Database);
        }

        if let Some(content) = notification.to_broadcast(&recipient)
            && self.deliver_broadcast(recipient.key(), &content)? > 0
        {
            channels.push(Channel::Broadcast);
        }

        if let Some(content) = notification.to_mail(&recipient) {
            let mail = self.mail.as_ref().ok_or(NotificationError::NotConfigured {
                channel: Channel::Mail,
            })?;
            let address =
                recipient
                    .email_address()
                    .ok_or_else(|| NotificationError::NoAddress {
                        key: recipient.key().to_owned(),
                    })?;

            mail.to(address).send(&AsMailable(&content)).await?;
            channels.push(Channel::Mail);
        }

        Ok(Delivery {
            channels,
            queued: Vec::new(),
        })
    }

    /// Like [`send`](Notifier::send), but hand the email to the job queue
    /// instead of waiting for the SMTP server.
    ///
    /// The inbox row and the live push still run inline, in the same order
    /// [`send`](Notifier::send) runs them. Only the mail moves, because only
    /// the mail leaves the machine -- see the [module
    /// docs](crate::notifications) and [`queue`](super::queue) for why
    /// deferring the other two would be dropping them rather than delaying
    /// them.
    ///
    /// The returned [`Delivery`] reports the mail channel under
    /// [`Delivery::queued`], never [`Delivery::channels`]. A job row is not a
    /// delivery, and the two accessors keep saying exactly one thing each.
    ///
    /// # Duplicates are possible
    ///
    /// [`crate::jobs`] is at-least-once, so a worker that dies between
    /// handing the message to the SMTP server and marking the job complete
    /// leaves a job another worker will run -- and the recipient gets the
    /// email twice. This is inherent to writing across two systems, not a gap
    /// here; a notification whose second copy is harmful should not be sent
    /// this way.
    ///
    /// # Errors
    ///
    /// - [`NotificationError::QueueNotConfigured`] if the notification
    ///   renders mail and no queue was wired. Loud rather than silently
    ///   falling back to an inline send, because the fallback would take the
    ///   latency the caller asked to avoid and only under load, which is when
    ///   it is least affordable and hardest to see.
    /// - [`NotificationError::NoAddress`] if the notification renders mail
    ///   for a recipient with no email address. Checked here rather than in
    ///   the worker: an address that does not exist is not going to appear by
    ///   the time the job runs, and failing now puts the error in the request
    ///   that caused it instead of in a dead job row.
    /// - [`NotificationError::Queue`] if the row cannot be written.
    /// - The same inbox and broadcast errors [`send`](Notifier::send)
    ///   returns, from the channels that still run inline.
    #[cfg(feature = "notifications-queue")]
    pub async fn queue<N>(
        &self,
        to: &impl Notifiable,
        notification: &N,
    ) -> Result<Delivery, NotificationError>
    where
        N: Notification + ?Sized,
    {
        let recipient = to.recipient();
        let mut channels = Vec::new();
        let mut queued = Vec::new();

        if let Some(content) = notification.to_database(&recipient) {
            self.deliver_database(recipient.key(), &content).await?;
            channels.push(Channel::Database);
        }

        if let Some(content) = notification.to_broadcast(&recipient)
            && self.deliver_broadcast(recipient.key(), &content)? > 0
        {
            channels.push(Channel::Broadcast);
        }

        if let Some(content) = notification.to_mail(&recipient) {
            let queue = self
                .queue
                .as_ref()
                .ok_or(NotificationError::QueueNotConfigured)?;
            let address =
                recipient
                    .email_address()
                    .ok_or_else(|| NotificationError::NoAddress {
                        key: recipient.key().to_owned(),
                    })?;

            queue.enqueue(&QueuedMail::new(address, &content)).await?;
            queued.push(Channel::Mail);
        }

        Ok(Delivery { channels, queued })
    }

    /// Write one inbox row.
    #[cfg(feature = "notifications-db")]
    async fn deliver_database(
        &self,
        key: &str,
        content: &DatabaseContent,
    ) -> Result<(), NotificationError> {
        let database = self
            .database
            .as_ref()
            .ok_or(NotificationError::NotConfigured {
                channel: Channel::Database,
            })?;
        database.store(key, content).await?;
        Ok(())
    }

    /// Without the `notifications-db` feature there is no store to write to,
    /// so every attempt is the wiring error -- the same one a notifier built
    /// without `.with_database(..)` gives. A notification that renders inbox
    /// content in a build that cannot deliver it is a mistake either way, and
    /// it says so on the first send instead of on the day somebody notices the
    /// inbox has been empty.
    #[cfg(not(feature = "notifications-db"))]
    #[expect(
        clippy::unused_async,
        reason = "matches the feature-on signature, which awaits the database"
    )]
    async fn deliver_database(
        &self,
        key: &str,
        content: &DatabaseContent,
    ) -> Result<(), NotificationError> {
        let _ = (key, content);
        Err(NotificationError::NotConfigured {
            channel: Channel::Database,
        })
    }

    /// Push once, and report how many connections received it.
    ///
    /// Not `async`: a `tokio::sync::broadcast` send neither waits nor blocks,
    /// so awaiting here would only add a suspension point that never yields.
    #[cfg(feature = "notifications-broadcast")]
    fn deliver_broadcast(
        &self,
        key: &str,
        content: &BroadcastContent,
    ) -> Result<usize, NotificationError> {
        let broadcast = self
            .broadcast
            .as_ref()
            .ok_or(NotificationError::NotConfigured {
                channel: Channel::Broadcast,
            })?;
        broadcast.push(key, content)
    }

    /// Without the `notifications-broadcast` feature there is nothing to push
    /// through, so every attempt is the wiring error -- the same reasoning as
    /// [`deliver_database`](Self::deliver_database). Note that this is *not*
    /// the same case as a recipient with no open connection, which succeeds
    /// having reached nobody: that is a fact about the recipient, this is a
    /// fact about the build.
    #[cfg(not(feature = "notifications-broadcast"))]
    fn deliver_broadcast(
        &self,
        key: &str,
        content: &BroadcastContent,
    ) -> Result<usize, NotificationError> {
        let _ = (key, content);
        Err(NotificationError::NotConfigured {
            channel: Channel::Broadcast,
        })
    }
}

/// Adapts a [`MailContent`] to the [`Mailable`] the mail transport takes.
///
/// Going through `Mail::to(..).send(..)` rather than building a `Message`
/// here means address parsing, the `From` header, and the transport's own
/// error mapping stay in one place instead of being reimplemented with
/// slightly different edge cases.
///
/// Visible to the rest of the module so [`queue`](super::queue) sends a
/// deferred email through this same adapter. Two spellings of "turn content
/// into a message" would eventually disagree about something small -- a
/// missing HTML part, a different encoding -- and the disagreement would only
/// show up in whichever path had no test for it.
pub(super) struct AsMailable<'a>(pub(super) &'a MailContent);

impl Mailable for AsMailable<'_> {
    fn build(&self, email: Email) -> Result<Message, EmailError> {
        let email = email.subject(self.0.subject());
        match self.0.html_body() {
            Some(html) => email.alternative(self.0.text(), html),
            None => email.plain(self.0.text()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::recipient::Recipient;
    use super::*;
    use crate::mail::Mailer;

    struct Mails;
    impl Notification for Mails {
        fn to_mail(&self, _recipient: &Recipient) -> Option<MailContent> {
            Some(MailContent::new("subject", "body"))
        }
    }

    /// Renders for both channels, so a test can tell which one ran first.
    struct Filed;
    impl Notification for Filed {
        fn to_mail(&self, _recipient: &Recipient) -> Option<MailContent> {
            Some(MailContent::new("subject", "body"))
        }

        fn to_database(&self, _recipient: &Recipient) -> Option<DatabaseContent> {
            Some(DatabaseContent::new("filed", serde_json::json!({})))
        }
    }

    /// Renders for the live push and for mail, so a test can tell whether a
    /// push that reached nobody stopped the mail.
    struct Pushed;
    impl Notification for Pushed {
        fn to_mail(&self, _recipient: &Recipient) -> Option<MailContent> {
            Some(MailContent::new("subject", "body"))
        }

        fn to_broadcast(&self, _recipient: &Recipient) -> Option<BroadcastContent> {
            Some(BroadcastContent::new("pushed", serde_json::json!({})))
        }
    }

    struct Silent;
    impl Notification for Silent {}

    fn wired() -> (Mailer, Notifier) {
        let mailer = Mailer::capture_ok();
        let mail = Mail::new(mailer.clone(), "noreply@example.com".parse().unwrap());
        (mailer, Notifier::new().with_mail(mail))
    }

    #[tokio::test]
    async fn a_mail_notification_reaches_the_transport() {
        let (mailer, notifier) = wired();
        let ada = Recipient::new("user:1").email("ada@example.com");

        let delivery = notifier.send(&ada, &Mails).await.unwrap();

        assert!(delivery.reached(Channel::Mail));
        assert_eq!(delivery.channels(), [Channel::Mail]);
        assert_eq!(mailer.captured().await.unwrap().len(), 1);
    }

    #[cfg(feature = "notifications-queue")]
    #[tokio::test]
    async fn queueing_mail_with_no_queue_is_an_error_and_not_an_inline_send() {
        // The tempting fallback -- no queue, so send it inline -- would take
        // exactly the latency the caller asked to avoid, and only under the
        // load that made them ask. A wiring mistake should cost the first
        // call, not the busiest one.
        let (mailer, notifier) = wired();
        let ada = Recipient::new("user:1").email("ada@example.com");

        let error = notifier.queue(&ada, &Mails).await.unwrap_err();

        assert!(
            matches!(error, NotificationError::QueueNotConfigured),
            "got {error:?}"
        );
        assert!(
            mailer.captured().await.unwrap().is_empty(),
            "the mail must not have gone out inline instead"
        );
    }

    #[cfg(feature = "notifications-queue")]
    #[tokio::test]
    async fn a_queued_channel_is_reported_as_queued_and_not_as_reached() {
        // `Notifier::queue` needs a pool to reach, so this asserts the shape
        // of the record rather than a round trip: a job row is not a
        // delivery, and neither accessor may start saying it is.
        let queued = Delivery {
            channels: Vec::new(),
            queued: vec![Channel::Mail],
        };

        assert!(queued.is_queued(Channel::Mail));
        assert!(!queued.reached(Channel::Mail));
        assert_eq!(queued.channels(), []);
        assert!(
            !queued.is_empty(),
            "a job row waiting to run is not nothing"
        );
    }

    #[tokio::test]
    async fn a_notification_with_no_content_delivers_nothing_and_says_so() {
        let (mailer, notifier) = wired();
        let ada = Recipient::new("user:1").email("ada@example.com");

        let delivery = notifier.send(&ada, &Silent).await.unwrap();

        assert!(delivery.is_empty());
        assert!(mailer.captured().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn an_unconfigured_channel_is_an_error_and_not_a_skip() {
        // The whole point of the type: forgetting `.with_mail(..)` at startup
        // must not read as "sent successfully to zero channels".
        let ada = Recipient::new("user:1").email("ada@example.com");

        let error = Notifier::new().send(&ada, &Mails).await.unwrap_err();

        assert!(
            matches!(
                error,
                NotificationError::NotConfigured {
                    channel: Channel::Mail
                }
            ),
            "got {error:?}"
        );
    }

    #[tokio::test]
    async fn wanting_mail_for_someone_with_no_address_is_an_error() {
        let (mailer, notifier) = wired();

        let error = notifier
            .send(&Recipient::new("user:7"), &Mails)
            .await
            .unwrap_err();

        match error {
            NotificationError::NoAddress { key } => assert_eq!(key, "user:7"),
            other => panic!("got {other:?}"),
        }
        assert!(mailer.captured().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn a_transport_failure_is_reported_rather_than_swallowed() {
        let mail = Mail::new(
            Mailer::capture_error(),
            "noreply@example.com".parse().unwrap(),
        );
        let notifier = Notifier::new().with_mail(mail);
        let ada = Recipient::new("user:1").email("ada@example.com");

        let error = notifier.send(&ada, &Mails).await.unwrap_err();

        assert!(
            matches!(error, NotificationError::Mail { .. }),
            "got {error:?}"
        );
    }

    #[tokio::test]
    async fn an_invalid_recipient_address_does_not_panic() {
        // The address comes from the application's `Notifiable`, so it is not
        // attacker input -- but a typo in a column should surface as an error
        // on the send, not as a panic inside the transport.
        let (_mailer, notifier) = wired();
        let broken = Recipient::new("user:1").email("not an address");

        let error = notifier.send(&broken, &Mails).await.unwrap_err();

        assert!(
            matches!(error, NotificationError::Mail { .. }),
            "got {error:?}"
        );
    }

    #[tokio::test]
    async fn an_inbox_notification_without_a_store_is_an_error_and_not_a_skip() {
        // The same guarantee the mail channel has, and it has to hold in both
        // builds: with the feature off there is no store to wire, and with it
        // on the notifier may simply have been built without one. Either way
        // the notification asked for an inbox row and did not get one, so the
        // send fails rather than reporting a delivery to nothing.
        let (mailer, notifier) = wired();
        let ada = Recipient::new("user:1").email("ada@example.com");

        let error = notifier.send(&ada, &Filed).await.unwrap_err();

        assert!(
            matches!(
                error,
                NotificationError::NotConfigured {
                    channel: Channel::Database
                }
            ),
            "got {error:?}"
        );
        // And it failed before the mail went out: the inbox is written first
        // so that a mail failure cannot cost the durable record.
        assert!(mailer.captured().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn a_broadcast_notification_without_a_channel_source_is_an_error_and_not_a_skip() {
        // Same guarantee again, and the same reason it has to hold in both
        // builds. Distinct from the case a wired notifier reports, where a
        // recipient who is simply not connected succeeds having reached
        // nobody -- that is a fact about the recipient, this is a mistake.
        let (mailer, notifier) = wired();
        let ada = Recipient::new("user:1").email("ada@example.com");

        let error = notifier.send(&ada, &Pushed).await.unwrap_err();

        assert!(
            matches!(
                error,
                NotificationError::NotConfigured {
                    channel: Channel::Broadcast
                }
            ),
            "got {error:?}"
        );
        assert!(mailer.captured().await.unwrap().is_empty());
    }

    #[cfg(feature = "notifications-broadcast")]
    #[tokio::test]
    async fn an_unconnected_recipient_is_not_a_delivery_and_not_a_failure() {
        use super::super::broadcast::{BroadcastNotifications, PerRecipientChannels};

        let (mailer, notifier) = wired();
        let channels = PerRecipientChannels::new(8).unwrap();
        let notifier = notifier.with_broadcast(BroadcastNotifications::new(channels.clone()));
        let ada = Recipient::new("user:1").email("ada@example.com");

        // Nobody connected: the mail still goes, the push reports nothing.
        let delivery = notifier.send(&ada, &Pushed).await.unwrap();
        assert_eq!(delivery.channels(), [Channel::Mail]);

        // Connected: the push is recorded, and before the mail.
        let _connection = channels.subscribe("user:1");
        let delivery = notifier.send(&ada, &Pushed).await.unwrap();
        assert_eq!(delivery.channels(), [Channel::Broadcast, Channel::Mail]);

        assert_eq!(mailer.captured().await.unwrap().len(), 2);
    }

    #[test]
    fn debug_does_not_print_the_mailer() {
        let (_mailer, notifier) = wired();
        let rendered = format!("{notifier:?}");

        // Built rather than written out, because the field list depends on
        // three independent features and a hand-written expectation per
        // combination is eight chances to encode the wrong one.
        let mut fields = vec!["mail: true"];
        if cfg!(feature = "notifications-db") {
            fields.push("database: false");
        }
        if cfg!(feature = "notifications-broadcast") {
            fields.push("broadcast: false");
        }
        if cfg!(feature = "notifications-queue") {
            fields.push("queue: false");
        }
        assert_eq!(rendered, format!("Notifier {{ {} }}", fields.join(", ")));

        // Whatever the feature set, what is printed is which channels are
        // wired -- never a credential from behind one.
        assert!(!rendered.contains("noreply@example.com"), "{rendered}");
    }

    #[test]
    fn a_fresh_notifier_has_no_channels() {
        assert!(!Notifier::new().has_mail());
        #[cfg(feature = "notifications-db")]
        assert!(!Notifier::new().has_database());
        #[cfg(feature = "notifications-broadcast")]
        assert!(!Notifier::new().has_broadcast());
        assert!(Delivery::default().is_empty());
    }
}