mailbridge 0.1.0

Provider-neutral transactional email library for Rust services
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
use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::Instant;

use serde::{Deserialize, Serialize};

use crate::config::MailbridgeConfig;
use crate::email::EmailMessage;
use crate::error::{MailError, Result};
use crate::provider::MailProvider;
use crate::queue::{MailQueue, QueueHandle, QueueId, QueueItem};
use crate::telemetry::{TelemetryEvent, TelemetryFields, emit};

#[cfg(feature = "rate-limit")]
use crate::rate_limit::MailRateLimiter;

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MessageId(String);

impl MessageId {
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for MessageId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SendReceipt {
    provider: &'static str,
    message_id: MessageId,
    provider_id: Option<String>,
}

impl SendReceipt {
    #[must_use]
    pub fn new(provider: &'static str, message_id: MessageId, provider_id: Option<String>) -> Self {
        Self {
            provider,
            message_id,
            provider_id,
        }
    }

    #[must_use]
    pub fn provider(&self) -> &'static str {
        self.provider
    }

    #[must_use]
    pub fn message_id(&self) -> &MessageId {
        &self.message_id
    }

    #[must_use]
    pub fn provider_id(&self) -> Option<&str> {
        self.provider_id.as_deref()
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum DeliveryMode {
    #[default]
    SendNow,
    Queue,
}

#[derive(Debug)]
pub struct MailClient<P> {
    provider: Arc<P>,
    allowed_from_domains: BTreeSet<String>,
    queue: Option<QueueHandle>,
    #[cfg(feature = "rate-limit")]
    rate_limiter: Option<MailRateLimiter>,
}

impl<P> Clone for MailClient<P> {
    fn clone(&self) -> Self {
        Self {
            provider: Arc::clone(&self.provider),
            allowed_from_domains: self.allowed_from_domains.clone(),
            queue: self.queue.clone(),
            #[cfg(feature = "rate-limit")]
            rate_limiter: self.rate_limiter.clone(),
        }
    }
}

impl<P> MailClient<P> {
    #[must_use]
    pub fn new(provider: P) -> Self {
        Self {
            provider: Arc::new(provider),
            allowed_from_domains: BTreeSet::new(),
            queue: None,
            #[cfg(feature = "rate-limit")]
            rate_limiter: None,
        }
    }

    /// Builds a client from configuration without opening durable queue
    /// connections.
    ///
    /// # Errors
    ///
    /// Returns an error when the configuration selects a durable queue backend.
    pub fn from_config(provider: P, config: &MailbridgeConfig) -> Result<Self> {
        if !matches!(config.queue_backend(), crate::config::QueueBackend::Memory) {
            return Err(MailError::Config(
                "MailClient::from_config only supports the memory queue backend; use MailClient::try_from_config for durable queue backends"
                    .to_owned(),
            ));
        }

        let builder = MailClientBuilder::new(provider).allowed_from_domains(
            config
                .allowed_from_domains()
                .iter()
                .map(std::string::ToString::to_string),
        );

        #[cfg(feature = "rate-limit")]
        let builder = builder.rate_limiter(MailRateLimiter::new(
            config.rate_limit(),
            config
                .allowed_from_domains()
                .iter()
                .map(std::string::ToString::to_string),
        ));

        #[cfg(feature = "queue-memory")]
        let builder = if matches!(config.queue_backend(), crate::config::QueueBackend::Memory) {
            builder.queue(QueueHandle::memory_default())
        } else {
            builder
        };

        Ok(builder.build())
    }

    /// Builds a client from configuration and initializes the configured queue.
    ///
    /// # Errors
    ///
    /// Returns an error when queue initialization fails or the selected queue
    /// feature is not enabled.
    pub async fn try_from_config(provider: P, config: &MailbridgeConfig) -> Result<Self> {
        let builder = MailClientBuilder::new(provider).allowed_from_domains(
            config
                .allowed_from_domains()
                .iter()
                .map(std::string::ToString::to_string),
        );

        #[cfg(feature = "rate-limit")]
        let builder = builder.rate_limiter(MailRateLimiter::new(
            config.rate_limit(),
            config
                .allowed_from_domains()
                .iter()
                .map(std::string::ToString::to_string),
        ));

        let queue = Box::pin(QueueHandle::from_backend(config.queue_backend())).await?;
        Ok(builder.queue(queue).build())
    }

    #[must_use]
    pub fn provider(&self) -> &P {
        self.provider.as_ref()
    }

    #[must_use]
    pub fn with_allowed_from_domains(mut self, domains: impl IntoIterator<Item = String>) -> Self {
        self.allowed_from_domains = domains.into_iter().collect();
        self
    }

    #[must_use]
    pub fn with_queue(mut self, queue: QueueHandle) -> Self {
        self.queue = Some(queue);
        self
    }

    #[cfg(feature = "rate-limit")]
    #[must_use]
    pub fn with_rate_limiter(mut self, limiter: MailRateLimiter) -> Self {
        self.rate_limiter = Some(limiter);
        self
    }

    #[must_use]
    pub fn queue(&self) -> Option<&QueueHandle> {
        self.queue.as_ref()
    }
}

impl<P> MailClient<P>
where
    P: MailProvider,
{
    /// Sends a validated message, waiting for any configured rate limiter.
    ///
    /// # Errors
    ///
    /// Returns validation, rate-limit, provider, or transport errors.
    pub async fn send(&self, message: EmailMessage) -> Result<SendReceipt> {
        self.validate(&message)?;
        self.wait_for_rate_limit(&message).await;

        let started = Instant::now();
        emit(
            TelemetryEvent::SendStarted,
            &TelemetryFields::new()
                .domain(message.from_address().domain())
                .provider(self.provider.provider_name()),
        );
        let result = self.provider.send(&message).await;

        emit(
            if result.is_ok() {
                TelemetryEvent::SendAccepted
            } else {
                TelemetryEvent::SendFailed
            },
            &TelemetryFields::new()
                .domain(message.from_address().domain())
                .provider(self.provider.provider_name())
                .elapsed_ms(started.elapsed().as_millis()),
        );

        result
    }

    /// Sends a validated message without waiting for rate-limit capacity.
    ///
    /// # Errors
    ///
    /// Returns validation, rate-limit, provider, or transport errors.
    pub async fn try_send(&self, message: EmailMessage) -> Result<SendReceipt> {
        self.validate(&message)?;
        if let Err(error) = self.check_rate_limit(&message) {
            emit(
                TelemetryEvent::RateLimited,
                &TelemetryFields::new()
                    .domain(message.from_address().domain())
                    .provider(self.provider.provider_name()),
            );
            return Err(error);
        }

        let started = Instant::now();
        emit(
            TelemetryEvent::SendStarted,
            &TelemetryFields::new()
                .domain(message.from_address().domain())
                .provider(self.provider.provider_name()),
        );
        let result = self.provider.send(&message).await;
        emit(
            if result.is_ok() {
                TelemetryEvent::SendAccepted
            } else {
                TelemetryEvent::SendFailed
            },
            &TelemetryFields::new()
                .domain(message.from_address().domain())
                .provider(self.provider.provider_name())
                .elapsed_ms(started.elapsed().as_millis()),
        );

        result
    }

    /// Enqueues a validated message on the configured queue.
    ///
    /// # Errors
    ///
    /// Returns validation errors, queue backend errors, or an error when no
    /// queue is configured.
    pub async fn enqueue(&self, message: EmailMessage) -> Result<QueueId> {
        self.validate(&message)?;
        let domain = message.from_address().domain().to_owned();
        let queue = self
            .queue
            .as_ref()
            .ok_or_else(|| MailError::Queue("mail queue is not configured".to_owned()))?;

        let id = queue.enqueue(QueueItem::new(message)).await?;
        emit(
            TelemetryEvent::QueueEnqueued,
            &TelemetryFields::new().domain(&domain),
        );

        Ok(id)
    }

    fn validate(&self, message: &EmailMessage) -> Result<()> {
        message.validate()?;

        if self.allowed_from_domains.is_empty() {
            return Ok(());
        }

        message.validate_sender_domain(&self.allowed_from_domains)
    }

    #[cfg(feature = "rate-limit")]
    async fn wait_for_rate_limit(&self, message: &EmailMessage) {
        if let Some(limiter) = &self.rate_limiter {
            limiter.wait(message.from_address().domain()).await;
        }
    }

    #[cfg(not(feature = "rate-limit"))]
    async fn wait_for_rate_limit(&self, _message: &EmailMessage) {}

    #[cfg(feature = "rate-limit")]
    fn check_rate_limit(&self, message: &EmailMessage) -> Result<()> {
        self.rate_limiter.as_ref().map_or(Ok(()), |limiter| {
            limiter.check(message.from_address().domain())
        })
    }

    #[cfg(not(feature = "rate-limit"))]
    fn check_rate_limit(&self, _message: &EmailMessage) -> Result<()> {
        Ok(())
    }
}

#[derive(Debug)]
pub struct MailClientBuilder<P> {
    provider: P,
    allowed_from_domains: BTreeSet<String>,
    queue: Option<QueueHandle>,
    #[cfg(feature = "rate-limit")]
    rate_limiter: Option<MailRateLimiter>,
}

impl<P> MailClientBuilder<P> {
    #[must_use]
    pub fn new(provider: P) -> Self {
        Self {
            provider,
            allowed_from_domains: BTreeSet::new(),
            queue: None,
            #[cfg(feature = "rate-limit")]
            rate_limiter: None,
        }
    }

    #[must_use]
    pub fn allowed_from_domains(mut self, domains: impl IntoIterator<Item = String>) -> Self {
        self.allowed_from_domains = domains.into_iter().collect();
        self
    }

    #[must_use]
    pub fn queue(mut self, queue: QueueHandle) -> Self {
        self.queue = Some(queue);
        self
    }

    #[cfg(feature = "rate-limit")]
    #[must_use]
    pub fn rate_limiter(mut self, limiter: MailRateLimiter) -> Self {
        self.rate_limiter = Some(limiter);
        self
    }

    #[must_use]
    pub fn build(self) -> MailClient<P> {
        MailClient {
            provider: Arc::new(self.provider),
            allowed_from_domains: self.allowed_from_domains,
            queue: self.queue,
            #[cfg(feature = "rate-limit")]
            rate_limiter: self.rate_limiter,
        }
    }
}

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

    use super::*;
    use crate::email::EmailMessage;
    use crate::error::MailError;
    use crate::provider::SendStatus;

    #[derive(Debug, Clone)]
    struct MockProvider;

    #[async_trait]
    impl MailProvider for MockProvider {
        async fn send(&self, message: &EmailMessage) -> Result<SendReceipt> {
            Ok(SendReceipt::new(
                self.provider_name(),
                MessageId::new(message.subject()),
                None,
            ))
        }

        async fn get_status(&self, _id: &MessageId) -> Result<Option<SendStatus>> {
            Ok(None)
        }

        fn provider_name(&self) -> &'static str {
            "mock"
        }
    }

    #[tokio::test]
    async fn send_rejects_disallowed_sender_domain_before_provider_call() {
        let message = EmailMessage::builder()
            .from("App", "sender@example.com")
            .expect("valid from address")
            .to("User", "user@example.net")
            .expect("valid to address")
            .subject("hello")
            .text("body")
            .build()
            .expect("valid message");
        let config = MailbridgeConfig::builder()
            .api_base_url("https://relay.example.com/api/console")
            .expect("valid url")
            .api_key("secret")
            .allowed_from_domain("allowed.example")
            .build()
            .expect("valid config");
        let client = MailClient::from_config(MockProvider, &config).expect("client builds");

        let error = client
            .send(message)
            .await
            .expect_err("sender domain should be rejected");

        assert_eq!(
            error,
            MailError::SenderDomainNotAllowed {
                domain: "example.com".to_owned()
            }
        );
    }

    #[tokio::test]
    async fn enqueue_requires_configured_queue() {
        let message = EmailMessage::builder()
            .from("App", "sender@example.com")
            .expect("valid from address")
            .to("User", "user@example.net")
            .expect("valid to address")
            .subject("hello")
            .text("body")
            .build()
            .expect("valid message");
        let client = MailClient::new(MockProvider);

        let error = client
            .enqueue(message)
            .await
            .expect_err("missing queue should fail");

        assert_eq!(
            error,
            MailError::Queue("mail queue is not configured".to_owned())
        );
    }

    #[tokio::test]
    async fn enqueue_uses_configured_queue() {
        let message = EmailMessage::builder()
            .from("App", "sender@example.com")
            .expect("valid from address")
            .to("User", "user@example.net")
            .expect("valid to address")
            .subject("hello")
            .text("body")
            .build()
            .expect("valid message");
        let queue = QueueHandle::memory(2);
        let client = MailClient::new(MockProvider).with_queue(queue);

        let id = client.enqueue(message).await.expect("enqueue succeeds");

        assert!(!id.as_str().is_empty());
    }

    #[cfg(feature = "queue-postgres")]
    #[test]
    fn from_config_rejects_durable_queue_backends() {
        let config = MailbridgeConfig::builder()
            .api_base_url("https://relay.example.com/api/console")
            .expect("valid url")
            .api_key("secret")
            .allowed_from_domain("example.com")
            .queue_backend(crate::config::QueueBackend::Postgres {
                database_url: secrecy::SecretString::new(
                    "postgres://localhost/mailbridge"
                        .to_owned()
                        .into_boxed_str(),
                ),
            })
            .build()
            .expect("valid config");

        let error = MailClient::from_config(MockProvider, &config)
            .expect_err("durable backend should require async constructor");

        assert!(matches!(error, MailError::Config(message) if message.contains("try_from_config")));
    }
}