loco-rs 1.0.1

The one-person framework for Rust
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
//! This module defines the email-related functionality, including the `Mailer`
//! trait and its implementation, `Email` structure, and the `MailerWorker` for
//! asynchronous email processing.

mod email_sender;
mod template;

use async_trait::async_trait;
pub use email_sender::EmailSender;
use include_dir::Dir;
use serde::{Deserialize, Serialize};
use tracing::error;

use self::template::Template;
use super::{app::AppContext, Result};
use crate::prelude::BackgroundWorker;

pub const DEFAULT_FROM_SENDER: &str = "System <system@example.com>";

/// Default background-queue priority used when enqueuing mailer jobs. Higher
/// values are processed sooner (see [`crate::bgworker::Queue::enqueue`]).
pub const DEFAULT_MAILER_PRIORITY: i32 = 100;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EmailHeaders {
    pub references: Option<String>,
    pub in_reply_to: Option<String>,
    pub message_id: Option<String>,
}

/// The arguments struct for specifying email details such as sender, recipient,
/// reply-to, and locals.
#[derive(Debug, Clone, Default)]
pub struct Args {
    pub from: Option<String>,
    pub to: String,
    pub reply_to: Option<String>,
    pub locals: serde_json::Value,
    pub bcc: Option<String>,
    pub cc: Option<String>,
    pub headers: Option<EmailHeaders>,
}

/// The arguments struct for specifying email details with multiple recipients.
#[derive(Debug, Clone, Default)]
pub struct MultiArgs {
    pub from: Option<String>,
    pub to: Vec<String>,
    pub reply_to: Option<String>,
    pub locals: serde_json::Value,
    pub bcc: Vec<String>,
    pub cc: Vec<String>,
    pub headers: Option<EmailHeaders>,
}

/// The structure representing an email details.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Email {
    /// Mailbox to `From` header
    pub from: Option<String>,
    /// Mailbox to `To` header
    pub to: String,
    /// Mailbox to `ReplyTo` header
    pub reply_to: Option<String>,
    /// Subject header to message
    pub subject: String,
    /// Plain text message
    pub text: String,
    /// HTML template
    pub html: String,
    /// BCC header to message
    pub bcc: Option<String>,
    /// CC header to message
    pub cc: Option<String>,
    /// Custom headers for the email (e.g., References, In-Reply-To, Message-ID)
    pub headers: Option<EmailHeaders>,
}

/// The structure representing an email with multiple recipients.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MultiEmail {
    /// Mailbox to `From` header
    pub from: Option<String>,
    /// Mailboxes to `To` header
    pub to: Vec<String>,
    /// Mailbox to `ReplyTo` header
    pub reply_to: Option<String>,
    /// Subject header to message
    pub subject: String,
    /// Plain text message
    pub text: String,
    /// HTML template
    pub html: String,
    /// Mailboxes to `BCC` header
    pub bcc: Vec<String>,
    /// Mailboxes to `CC` header
    pub cc: Vec<String>,
    /// Custom headers for the email (e.g., References, In-Reply-To, Message-ID)
    pub headers: Option<EmailHeaders>,
}

/// The options struct for configuring the email sender.
#[derive(Debug)]
#[allow(clippy::module_name_repetitions)]
pub struct MailerOpts {
    pub from: String,
    pub reply_to: Option<String>,
    /// Background-queue priority for enqueued mailer jobs.
    pub priority: i32,
}

impl Default for MailerOpts {
    fn default() -> Self {
        Self {
            from: DEFAULT_FROM_SENDER.to_string(),
            reply_to: None,
            priority: DEFAULT_MAILER_PRIORITY,
        }
    }
}

/// The `Mailer` trait defines methods for sending emails and processing email
/// templates.
#[async_trait]
pub trait Mailer {
    /// Returns default options for the mailer.
    #[must_use]
    fn opts() -> MailerOpts {
        MailerOpts {
            from: DEFAULT_FROM_SENDER.to_string(),
            ..Default::default()
        }
    }

    /// Sends an email using the provided [`AppContext`] and email details.
    async fn mail(ctx: &AppContext, email: &Email) -> Result<()> {
        let opts = Self::opts();
        let mut email = email.clone();

        email.from = Some(email.from.unwrap_or_else(|| opts.from.clone()));
        email.reply_to = email.reply_to.or_else(|| opts.reply_to.clone());

        MailerWorker::perform_later_with_priority(ctx, email.clone(), Some(opts.priority)).await?;
        Ok(())
    }

    /// Sends an email to multiple recipients using the provided [`AppContext`]
    /// and email details.
    ///
    /// # Errors
    /// Returns an error if enqueuing the email fails.
    async fn mail_multi(ctx: &AppContext, email: &MultiEmail) -> Result<()> {
        let opts = Self::opts();
        let mut email = email.clone();

        email.from = Some(email.from.unwrap_or_else(|| opts.from.clone()));
        email.reply_to = email.reply_to.or_else(|| opts.reply_to.clone());

        MultiMailerWorker::perform_later(ctx, email.clone()).await?;
        Ok(())
    }

    /// Renders and sends an email using the provided [`AppContext`], template
    /// directory, and arguments.
    async fn mail_template(ctx: &AppContext, dir: &Dir<'_>, args: Args) -> Result<()> {
        Self::mail_template_with_shared(ctx, dir, &[], args).await
    }

    /// Renders and sends an email using the provided [`AppContext`], template
    /// directory, shared template directories, and arguments.
    ///
    /// This lets multiple mailers share common templates (e.g. a base HTML
    /// layout). Templates from `shared_dirs` are loaded first, then templates
    /// from the main directory, so main-directory templates can extend shared
    /// ones and override any with the same name.
    ///
    /// # Errors
    /// Returns an error if a template is missing/invalid or the send fails.
    async fn mail_template_with_shared(
        ctx: &AppContext,
        dir: &Dir<'_>,
        shared_dirs: &[&Dir<'_>],
        args: Args,
    ) -> Result<()> {
        let content = Template::new_with_shared(dir, shared_dirs)?.render(&args.locals)?;
        Self::mail(
            ctx,
            &Email {
                from: args.from.clone(),
                to: args.to.clone(),
                reply_to: args.reply_to.clone(),
                subject: content.subject,
                text: content.text,
                html: content.html,
                bcc: args.bcc.clone(),
                cc: args.cc.clone(),
                headers: args.headers.clone(),
            },
        )
        .await
    }

    /// Renders and sends an email to multiple recipients using the provided
    /// [`AppContext`], template directory, and arguments.
    ///
    /// # Errors
    /// Returns an error if a template is missing/invalid or enqueuing fails.
    async fn mail_template_multi(ctx: &AppContext, dir: &Dir<'_>, args: MultiArgs) -> Result<()> {
        let content = Template::new(dir)?.render(&args.locals)?;
        Self::mail_multi(
            ctx,
            &MultiEmail {
                from: args.from.clone(),
                to: args.to.clone(),
                reply_to: args.reply_to.clone(),
                subject: content.subject,
                text: content.text,
                html: content.html,
                bcc: args.bcc.clone(),
                cc: args.cc.clone(),
                headers: args.headers.clone(),
            },
        )
        .await
    }

    /// Sends an email **synchronously**, bypassing the background worker queue
    /// (Rails' `deliver_now`). Prefer [`Mailer::mail`] (which enqueues, like
    /// `deliver_later`) unless you specifically need the send to complete inline.
    ///
    /// # Errors
    /// Returns an error if no mailer is configured or the send fails.
    async fn deliver_now(ctx: &AppContext, email: &Email) -> Result<()> {
        let opts = Self::opts();
        let mut email = email.clone();
        email.from = Some(email.from.unwrap_or_else(|| opts.from.clone()));
        email.reply_to = email.reply_to.or_else(|| opts.reply_to.clone());
        send_now(ctx, &email).await
    }

    /// Renders a template and sends it **synchronously** (see
    /// [`Mailer::deliver_now`]). The template-rendering counterpart to
    /// [`Mailer::mail_template`], which enqueues instead.
    ///
    /// # Errors
    /// Returns an error if rendering fails, no mailer is configured, or the send fails.
    async fn mail_template_now(ctx: &AppContext, dir: &Dir<'_>, args: Args) -> Result<()> {
        let content = Template::new(dir)?.render(&args.locals)?;
        Self::deliver_now(
            ctx,
            &Email {
                from: args.from.clone(),
                to: args.to.clone(),
                reply_to: args.reply_to.clone(),
                subject: content.subject,
                text: content.text,
                html: content.html,
                bcc: args.bcc.clone(),
                cc: args.cc.clone(),
                headers: args.headers.clone(),
            },
        )
        .await
    }
}

/// Sends an already-prepared email synchronously through the context's
/// configured [`EmailSender`], bypassing the background queue. Errors if no
/// mailer is configured.
async fn send_now(ctx: &AppContext, email: &Email) -> Result<()> {
    if let Some(mailer) = &ctx.mailer {
        mailer.mail(email).await.inspect_err(|err| {
            error!(err = err.to_string(), "mailer error");
        })
    } else {
        let err = crate::Error::Message(
            "attempting to send email but no email sender configured".to_string(),
        );
        error!(err = err.to_string(), "mailer error");
        Err(err)
    }
}

/// The [`MailerWorker`] struct represents a worker responsible for asynchronous
/// email processing.
#[allow(clippy::module_name_repetitions)]
pub struct MailerWorker {
    pub ctx: AppContext,
}

/// Implementation of the [`Worker`] trait for the [`MailerWorker`].
#[async_trait]
impl BackgroundWorker<Email> for MailerWorker {
    fn queue() -> Option<String> {
        Some("mailer".to_string())
    }

    fn build(ctx: &AppContext) -> Self {
        Self { ctx: ctx.clone() }
    }

    /// Performs the email sending operation using the provided [`AppContext`]
    /// and email details.
    async fn perform(&self, email: Email) -> crate::Result<()> {
        send_now(&self.ctx, &email).await
    }
}

/// Sends an already-prepared multi-recipient email synchronously through the
/// context's configured [`EmailSender`], bypassing the background queue. Errors
/// if no mailer is configured.
async fn send_multi_now(ctx: &AppContext, email: &MultiEmail) -> Result<()> {
    if let Some(mailer) = &ctx.mailer {
        mailer.mail_multi(email).await.inspect_err(|err| {
            error!(err = err.to_string(), "mailer error");
        })
    } else {
        let err = crate::Error::Message(
            "attempting to send email but no email sender configured".to_string(),
        );
        error!(err = err.to_string(), "mailer error");
        Err(err)
    }
}

/// The [`MultiMailerWorker`] struct represents a worker responsible for
/// asynchronous multi-recipient email processing.
#[allow(clippy::module_name_repetitions)]
pub struct MultiMailerWorker {
    pub ctx: AppContext,
}

/// Implementation of the [`Worker`] trait for the [`MultiMailerWorker`].
#[async_trait]
impl BackgroundWorker<MultiEmail> for MultiMailerWorker {
    fn queue() -> Option<String> {
        Some("mailer".to_string())
    }

    fn build(ctx: &AppContext) -> Self {
        Self { ctx: ctx.clone() }
    }

    /// Performs the multi-recipient email sending operation using the provided
    /// [`AppContext`] and email details.
    async fn perform(&self, email: MultiEmail) -> crate::Result<()> {
        send_multi_now(&self.ctx, &email).await
    }
}

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

    struct TestMailer;
    impl Mailer for TestMailer {}

    #[tokio::test]
    async fn deliver_now_sends_synchronously_without_worker() {
        let mut ctx = crate::tests_cfg::app::get_app_context().await;
        ctx.mailer = Some(EmailSender::stub());

        let email = Email {
            from: None,
            to: "user1@framework.com".to_string(),
            reply_to: None,
            subject: "Subject".to_string(),
            text: "Welcome".to_string(),
            html: "<html><body>Welcome</body></html>".to_string(),
            bcc: None,
            cc: None,
            headers: None,
        };

        TestMailer::deliver_now(&ctx, &email)
            .await
            .expect("deliver_now should succeed");

        let deliveries = ctx.mailer.as_ref().unwrap().deliveries();
        assert_eq!(deliveries.count, 1);
    }

    #[tokio::test]
    async fn deliver_now_errors_when_no_mailer_configured() {
        let ctx = crate::tests_cfg::app::get_app_context().await;
        assert!(ctx.mailer.is_none());

        let email = Email {
            from: None,
            to: "user1@framework.com".to_string(),
            reply_to: None,
            subject: "Subject".to_string(),
            text: "Welcome".to_string(),
            html: "<html><body>Welcome</body></html>".to_string(),
            bcc: None,
            cc: None,
            headers: None,
        };

        let err = TestMailer::deliver_now(&ctx, &email)
            .await
            .expect_err("deliver_now should error without a configured mailer");
        assert_eq!(
            err.to_string(),
            "attempting to send email but no email sender configured"
        );
    }
}