glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! Sending mail, as Action Mailer does: a message built from templates,
//! delivered now or (by default) from a job, through whichever service
//! the environment configures.
//!
//! ```ignore
//! pub struct ReportMailer;
//!
//! impl ReportMailer {
//!     pub fn ready(report: &Report, user: &User) -> Mail {
//!         Mail::new()
//!             .to(&user.email)
//!             .subject(format!("{} is ready", report.title))
//!             .html(views::report_mailer::Ready { report: report.clone() })
//!             .text(views::report_mailer::ReadyText { report: report.clone() })
//!     }
//! }
//!
//! // Queued with the caller's transaction, sent by a worker:
//! ReportMailer::ready(&report, &user).deliver_later().await?;
//! ```
//!
//! Delivery comes from `[mail]` in the config:
//!
//! ```toml
//! [mail]
//! from = "Reports <reports@example.com>"
//! delivery = "smtp"          # smtp, sendgrid, postmark, inbox, test or none
//!
//! [mail.smtp]
//! host = "smtp.example.com"  # port 587 and STARTTLS unless set
//! username = "apikey"
//! password = "…"             # better from GLACIER__MAIL__SMTP__PASSWORD
//! ```
//!
//! Without a `delivery`, development keeps mail in an inbox you read at
//! `/dev/mail`, tests keep it for `glacier::testing::delivered_mail()`,
//! and production refuses to send until one is configured.

mod deliveries;
pub mod preview;

use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, RwLock};

use serde::{Deserialize, Serialize};

pub use self::deliveries::{Inbox, Postmark, SendGrid, Smtp};
pub use self::preview::Previews;
use crate::config::{Config, Env};
use crate::error::{Error, Result};
use crate::jobs::Job;
use crate::view::{Rendered, Template};

/// One email: who it's to, its subject, its HTML and text parts, and
/// attachments. Build it with [`Mail::new`], then deliver it.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Mail {
    /// `"Name <address>"` or a bare address; the configured `mail.from`
    /// when not set.
    pub from: Option<String>,
    pub to: Vec<String>,
    pub cc: Vec<String>,
    pub bcc: Vec<String>,
    pub reply_to: Option<String>,
    pub subject: String,
    pub html: Option<String>,
    pub text: Option<String>,
    pub attachments: Vec<Attachment>,
    /// Extra headers, such as `List-Unsubscribe`.
    pub headers: Vec<(String, String)>,
}

/// A file sent with a mail.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Attachment {
    pub filename: String,
    pub content_type: String,
    #[serde(with = "base64_bytes")]
    pub data: Vec<u8>,
    /// For an image the HTML shows inline: `<img src="cid:logo.png">`.
    #[serde(default)]
    pub content_id: Option<String>,
}

/// A mail part: a template (`views::report_mailer::Ready { … }`), an
/// already rendered one, or text.
pub trait Body {
    fn into_body(self) -> String;
}

impl<T: Template> Body for T {
    fn into_body(self) -> String {
        self.render().to_html()
    }
}

impl Body for Rendered {
    fn into_body(self) -> String {
        self.to_html()
    }
}

impl Body for String {
    fn into_body(self) -> String {
        self
    }
}

impl Body for &str {
    fn into_body(self) -> String {
        self.to_owned()
    }
}

impl Mail {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn from(mut self, address: impl Into<String>) -> Self {
        self.from = Some(address.into());
        self
    }

    /// Adds a recipient; call it again for more.
    #[must_use]
    pub fn to(mut self, address: impl Into<String>) -> Self {
        self.to.push(address.into());
        self
    }

    #[must_use]
    pub fn cc(mut self, address: impl Into<String>) -> Self {
        self.cc.push(address.into());
        self
    }

    #[must_use]
    pub fn bcc(mut self, address: impl Into<String>) -> Self {
        self.bcc.push(address.into());
        self
    }

    #[must_use]
    pub fn reply_to(mut self, address: impl Into<String>) -> Self {
        self.reply_to = Some(address.into());
        self
    }

    #[must_use]
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = subject.into();
        self
    }

    /// The HTML part: usually a template from `src/views/<mailer>/`,
    /// which you can wrap in a mail layout yourself.
    #[must_use]
    pub fn html(mut self, body: impl Body) -> Self {
        self.html = Some(body.into_body());
        self
    }

    /// The plain-text part: a `.txt` template (`ReadyText`), whose values
    /// aren't HTML-escaped, or text.
    #[must_use]
    pub fn text(mut self, body: impl Body) -> Self {
        self.text = Some(body.into_body());
        self
    }

    /// Attaches a file: `attach("receipt.pdf", "application/pdf", bytes)`.
    #[must_use]
    pub fn attach(
        mut self,
        filename: impl Into<String>,
        content_type: impl Into<String>,
        data: impl Into<Vec<u8>>,
    ) -> Self {
        self.attachments.push(Attachment {
            filename: filename.into(),
            content_type: content_type.into(),
            data: data.into(),
            content_id: None,
        });
        self
    }

    /// Attaches an image the HTML shows in place, as `cid:<filename>`:
    /// `attach_inline("logo.png", "image/png", bytes)` for
    /// `<img src="cid:logo.png">`.
    #[must_use]
    pub fn attach_inline(
        mut self,
        filename: impl Into<String>,
        content_type: impl Into<String>,
        data: impl Into<Vec<u8>>,
    ) -> Self {
        let filename = filename.into();
        self.attachments.push(Attachment {
            content_id: Some(filename.clone()),
            filename,
            content_type: content_type.into(),
            data: data.into(),
        });
        self
    }

    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Sends it now, through the configured delivery, waiting for the
    /// service to accept it.
    ///
    /// # Errors
    ///
    /// When it has no recipient, no sender, or the service refuses it.
    pub async fn deliver_now(self) -> Result<()> {
        let mail = self.ready()?;
        let delivery = current();
        let span = tracing::info_span!(
            target: "glacier::mail",
            "mail.deliver",
            mail.to = %mail.to.join(", "),
            mail.subject = %mail.subject,
            mail.delivery = delivery.name(),
        );
        tracing::Instrument::instrument(
            async {
                delivery.deliver(&mail).await?;
                tracing::info!(
                    target: "glacier::mail",
                    to = %mail.to.join(", "),
                    subject = %mail.subject,
                    "delivered by {}",
                    delivery.name()
                );
                Ok(())
            },
            span,
        )
        .await
    }

    /// Queues it to be sent by a job worker, as Rails' `deliver_later`:
    /// inside a transaction, it's only sent if the transaction commits.
    /// Returns the job's id.
    ///
    /// # Errors
    ///
    /// When it has no recipient or sender, or can't be queued.
    pub async fn deliver_later(self) -> Result<i64> {
        DeliverMail(self.ready()?).enqueue().await
    }

    /// The mail with its sender filled in, checked for what every mail needs.
    fn ready(mut self) -> Result<Self> {
        if self.from.is_none() {
            self.from = settings().from.clone();
        }
        if self.from.is_none() {
            return Err(Error::internal(
                "the mail has no sender: set `from`, or `mail.from` in the config",
            ));
        }
        // An empty address (a user without one) isn't a recipient.
        for list in [&mut self.to, &mut self.cc, &mut self.bcc] {
            list.retain(|address| !address.trim().is_empty());
        }
        if self.to.is_empty() && self.cc.is_empty() && self.bcc.is_empty() {
            return Err(Error::internal(format!(
                "the mail `{}` has no recipients",
                self.subject
            )));
        }
        if self.html.is_none() && self.text.is_none() {
            return Err(Error::internal(format!(
                "the mail `{}` has no body: give it `html` or `text`",
                self.subject
            )));
        }
        Ok(self)
    }
}

/// The job `deliver_later` queues: the rendered mail, sent by a worker.
#[derive(Serialize, Deserialize)]
pub struct DeliverMail(pub Mail);

impl Job for DeliverMail {
    const NAME: &'static str = "glacier_deliver_mail";
    const QUEUE: &'static str = "mailers";

    async fn perform(self) -> Result<()> {
        self.0.deliver_now().await
    }
}

/// Where mail goes: SMTP, an email API, an inbox, or a test's mailbox.
/// Implement it to send through something else, and pass it to
/// `App::mail_delivery`.
pub trait Delivery: Send + Sync + 'static {
    /// A short name for logs: `smtp`, `sendgrid`, …
    fn name(&self) -> &'static str;

    fn deliver<'a>(
        &'a self,
        mail: &'a Mail,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
}

/// Refuses to send: production without a configured delivery.
struct Unconfigured;

impl Delivery for Unconfigured {
    fn name(&self) -> &'static str {
        "none"
    }

    fn deliver<'a>(
        &'a self,
        mail: &'a Mail,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        let subject = mail.subject.clone();
        Box::pin(async move {
            Err(Error::internal(format!(
                "can't send `{subject}`: no mail delivery is configured; set `mail.delivery`"
            )))
        })
    }
}

/// Drops every mail, saying so in the log: `delivery = "none"`.
struct Discard;

impl Delivery for Discard {
    fn name(&self) -> &'static str {
        "none"
    }

    fn deliver<'a>(
        &'a self,
        mail: &'a Mail,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        tracing::info!(target: "glacier::mail", subject = %mail.subject, "not sent: mail.delivery is none");
        Box::pin(async { Ok(()) })
    }
}

/// Keeps mail for `glacier::testing::delivered_mail()`: each
/// `#[glacier::test]` has a mailbox of its own.
#[derive(Default)]
pub struct TestMailbox;

impl Delivery for TestMailbox {
    fn name(&self) -> &'static str {
        "test"
    }

    fn deliver<'a>(
        &'a self,
        mail: &'a Mail,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        let mail = mail.clone();
        Box::pin(async move {
            let kept = MAILBOX
                .try_with(|mailbox| {
                    mailbox
                        .lock()
                        .unwrap_or_else(|e| e.into_inner())
                        .push(mail.clone())
                })
                .is_ok();
            if !kept {
                SHARED_MAILBOX
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .push(mail);
            }
            Ok(())
        })
    }
}

tokio::task_local! {
    /// A test's mailbox, from `#[glacier::test]`.
    static MAILBOX: Arc<Mutex<Vec<Mail>>>;
}

/// Mail a `TestMailbox` sent outside a `#[glacier::test]`.
static SHARED_MAILBOX: Mutex<Vec<Mail>> = Mutex::new(Vec::new());

/// Runs `fut` with a mailbox of its own. `#[glacier::test]` does this.
#[doc(hidden)]
pub async fn with_test_mailbox<F: Future>(fut: F) -> F::Output {
    MAILBOX.scope(Arc::default(), fut).await
}

/// The mail this test sent, oldest first.
pub(crate) fn delivered() -> Vec<Mail> {
    MAILBOX
        .try_with(|mailbox| mailbox.lock().unwrap_or_else(|e| e.into_inner()).clone())
        .unwrap_or_else(|_| {
            SHARED_MAILBOX
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .clone()
        })
}

/// Empties this test's mailbox.
pub(crate) fn clear_delivered() {
    let cleared = MAILBOX
        .try_with(|mailbox| mailbox.lock().unwrap_or_else(|e| e.into_inner()).clear())
        .is_ok();
    if !cleared {
        SHARED_MAILBOX
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
    }
}

/// The app's mail settings.
struct Settings {
    from: Option<String>,
    delivery: Arc<dyn Delivery>,
    /// Set by `App::mail_delivery`: the config doesn't replace it.
    chosen: bool,
}

static SETTINGS: RwLock<Option<Arc<Settings>>> = RwLock::new(None);

fn settings() -> Arc<Settings> {
    if let Some(settings) = SETTINGS.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
        return settings.clone();
    }
    // Nothing configured: the environment's default.
    let settings = Arc::new(Settings {
        from: None,
        delivery: default_delivery(Env::current()),
        chosen: false,
    });
    *SETTINGS.write().unwrap_or_else(|e| e.into_inner()) = Some(settings.clone());
    settings
}

/// The delivery to use: inside a `#[glacier::test]` always the test's
/// mailbox, so a test never sends real mail; otherwise the configured one.
fn current() -> Arc<dyn Delivery> {
    if MAILBOX.try_with(|_| ()).is_ok() {
        return Arc::new(TestMailbox);
    }
    settings().delivery.clone()
}

fn default_delivery(env: Env) -> Arc<dyn Delivery> {
    match env {
        Env::Development => Arc::new(Inbox),
        Env::Test => Arc::new(TestMailbox),
        Env::Production => Arc::new(Unconfigured),
    }
}

/// Reads `[mail]` from the config. `App::config` calls it.
pub(crate) fn configure(config: &Config) -> Result<()> {
    let from = config.get_opt::<String>("mail.from")?;
    let chosen = SETTINGS
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .as_ref()
        .filter(|settings| settings.chosen)
        .map(|settings| settings.delivery.clone());
    if let Some(delivery) = chosen {
        *SETTINGS.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(Settings {
            from,
            delivery,
            chosen: true,
        }));
        return Ok(());
    }
    let delivery: Arc<dyn Delivery> = match config.get_opt::<String>("mail.delivery")?.as_deref() {
        None => default_delivery(config.env()),
        Some("smtp") => Arc::new(Smtp::from_config(config)?),
        Some("sendgrid") => Arc::new(SendGrid::from_config(config)?),
        Some("postmark") => Arc::new(Postmark::from_config(config)?),
        Some("inbox") => Arc::new(Inbox),
        Some("test") => Arc::new(TestMailbox),
        Some("none") => Arc::new(Discard),
        Some(other) => {
            return Err(Error::internal(format!(
                "mail.delivery `{other}`: expected smtp, sendgrid, postmark, inbox, test or none"
            )));
        }
    };
    *SETTINGS.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(Settings {
        from,
        delivery,
        chosen: false,
    }));
    Ok(())
}

/// Replaces the delivery (`App::mail_delivery`), keeping `mail.from`,
/// whether it's called before or after `App::config`. One per process.
pub(crate) fn set_delivery(delivery: Arc<dyn Delivery>) {
    let from = settings().from.clone();
    *SETTINGS.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(Settings {
        from,
        delivery,
        chosen: true,
    }));
}

/// Splits `"Name <address>"` into its name and address.
pub(crate) fn split_address(address: &str) -> (Option<&str>, &str) {
    match (address.rfind('<'), address.rfind('>')) {
        (Some(open), Some(close)) if open < close => {
            let name = address[..open].trim().trim_matches('"').trim();
            (
                (!name.is_empty()).then_some(name),
                address[open + 1..close].trim(),
            )
        }
        _ => (None, address.trim()),
    }
}

mod base64_bytes {
    use base64::Engine as _;
    use base64::engine::general_purpose::STANDARD;
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&STANDARD.encode(bytes))
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
        let text = String::deserialize(d)?;
        STANDARD.decode(text).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn splits_addresses() {
        assert_eq!(
            split_address("Ada <ada@example.com>"),
            (Some("Ada"), "ada@example.com")
        );
        assert_eq!(
            split_address("\"Ada L\" <ada@example.com>"),
            (Some("Ada L"), "ada@example.com")
        );
        assert_eq!(split_address("ada@example.com"), (None, "ada@example.com"));
    }

    #[test]
    fn mail_survives_a_job_round_trip() {
        let mail = Mail::new()
            .to("ada@example.com")
            .subject("Hi")
            .text("Hello")
            .attach("a.bin", "application/octet-stream", vec![0, 255, 7]);
        let json = serde_json::to_string(&DeliverMail(mail.clone())).unwrap();
        let back: DeliverMail = serde_json::from_str(&json).unwrap();
        assert_eq!(back.0, mail);
    }
}