Skip to main content

mockforge_smtp/
spec_registry.rs

1//! SMTP SpecRegistry implementation
2
3use crate::fixtures::{SmtpFixture, StoredEmail};
4use mockforge_core::fixture_store::{
5    load_fixtures_from_dir, FixtureFileFormat, FixtureFileGranularity, FixtureLoadErrorMode,
6    FixtureLoadOptions,
7};
8use mockforge_core::protocol_abstraction::{
9    Protocol, ProtocolRequest, ProtocolResponse, ResponseStatus, SpecOperation, SpecRegistry,
10    ValidationError, ValidationResult,
11};
12use mockforge_core::Result;
13use regex::Regex;
14use std::collections::HashMap;
15use std::path::Path;
16use std::sync::RwLock;
17use tracing::{info, warn};
18
19/// Email search filters
20#[derive(Debug, Clone, Default)]
21pub struct EmailSearchFilters {
22    pub sender: Option<String>,
23    pub recipient: Option<String>,
24    pub subject: Option<String>,
25    pub body: Option<String>,
26    pub since: Option<chrono::DateTime<chrono::Utc>>,
27    pub until: Option<chrono::DateTime<chrono::Utc>>,
28    pub use_regex: bool,
29    pub case_sensitive: bool,
30}
31
32/// SMTP protocol registry implementing SpecRegistry trait
33pub struct SmtpSpecRegistry {
34    /// Loaded fixtures
35    fixtures: Vec<SmtpFixture>,
36    /// In-memory mailbox
37    mailbox: RwLock<Vec<StoredEmail>>,
38    /// Maximum mailbox size
39    max_mailbox_size: usize,
40}
41
42impl SmtpSpecRegistry {
43    /// Create a new SMTP registry
44    pub fn new() -> Self {
45        Self {
46            fixtures: Vec::new(),
47            mailbox: RwLock::new(Vec::new()),
48            max_mailbox_size: 1000,
49        }
50    }
51
52    /// Create a new registry with custom mailbox size
53    pub fn with_mailbox_size(max_size: usize) -> Self {
54        Self {
55            fixtures: Vec::new(),
56            mailbox: RwLock::new(Vec::new()),
57            max_mailbox_size: max_size,
58        }
59    }
60
61    /// Load fixtures from a directory
62    pub fn load_fixtures<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
63        let path = path.as_ref();
64
65        if !path.exists() {
66            warn!("Fixtures directory does not exist: {:?}", path);
67            return Ok(());
68        }
69
70        let options = FixtureLoadOptions {
71            formats: vec![FixtureFileFormat::Yaml, FixtureFileFormat::Json],
72            error_mode: FixtureLoadErrorMode::FailFast,
73            granularity: FixtureFileGranularity::Single,
74        };
75
76        let loaded: Vec<SmtpFixture> = load_fixtures_from_dir(path, &options)?;
77
78        for fixture in loaded {
79            self.fixtures.push(fixture);
80        }
81
82        info!("Loaded {} SMTP fixtures", self.fixtures.len());
83        Ok(())
84    }
85
86    /// Find a matching fixture for the given email
87    pub fn find_matching_fixture(
88        &self,
89        from: &str,
90        to: &str,
91        subject: &str,
92    ) -> Option<&SmtpFixture> {
93        // First, try to find a specific match
94        for fixture in &self.fixtures {
95            if !fixture.match_criteria.match_all && fixture.matches(from, to, subject) {
96                return Some(fixture);
97            }
98        }
99
100        // If no specific match, find a default (match_all) fixture
101        self.fixtures.iter().find(|f| f.match_criteria.match_all)
102    }
103
104    /// Store an email in the mailbox
105    pub fn store_email(&self, email: StoredEmail) -> Result<()> {
106        let mut mailbox = self.mailbox.write().map_err(|e| {
107            mockforge_core::Error::internal(format!("Failed to acquire mailbox lock: {}", e))
108        })?;
109
110        // Check mailbox size limit
111        if mailbox.len() >= self.max_mailbox_size {
112            warn!("Mailbox is full, removing oldest email");
113            mailbox.remove(0);
114        }
115
116        mailbox.push(email);
117        Ok(())
118    }
119
120    /// Get all emails from the mailbox
121    pub fn get_emails(&self) -> Result<Vec<StoredEmail>> {
122        let mailbox = self.mailbox.read().map_err(|e| {
123            mockforge_core::Error::internal(format!("Failed to acquire mailbox lock: {}", e))
124        })?;
125
126        Ok(mailbox.clone())
127    }
128
129    /// Get a specific email by ID
130    pub fn get_email_by_id(&self, id: &str) -> Result<Option<StoredEmail>> {
131        let mailbox = self.mailbox.read().map_err(|e| {
132            mockforge_core::Error::internal(format!("Failed to acquire mailbox lock: {}", e))
133        })?;
134
135        Ok(mailbox.iter().find(|e| e.id == id).cloned())
136    }
137
138    /// Clear all emails from the mailbox
139    pub fn clear_mailbox(&self) -> Result<()> {
140        let mut mailbox = self.mailbox.write().map_err(|e| {
141            mockforge_core::Error::internal(format!("Failed to acquire mailbox lock: {}", e))
142        })?;
143
144        mailbox.clear();
145        info!("Mailbox cleared");
146        Ok(())
147    }
148
149    /// Get mailbox statistics
150    pub fn get_mailbox_stats(&self) -> Result<MailboxStats> {
151        let mailbox = self.mailbox.read().map_err(|e| {
152            mockforge_core::Error::internal(format!("Failed to acquire mailbox lock: {}", e))
153        })?;
154
155        Ok(MailboxStats {
156            total_emails: mailbox.len(),
157            max_capacity: self.max_mailbox_size,
158        })
159    }
160
161    /// Search emails with filters
162    pub fn search_emails(&self, filters: EmailSearchFilters) -> Result<Vec<StoredEmail>> {
163        let mailbox = self.mailbox.read().map_err(|e| {
164            mockforge_core::Error::internal(format!("Failed to acquire mailbox lock: {}", e))
165        })?;
166
167        let mut results: Vec<StoredEmail> = mailbox
168            .iter()
169            .filter(|email| {
170                // Helper function to check if field matches filter
171                let matches_filter = |field: &str, filter: &Option<String>| -> bool {
172                    if let Some(ref f) = filter {
173                        let field_cmp = if filters.case_sensitive {
174                            field.to_string()
175                        } else {
176                            field.to_lowercase()
177                        };
178                        let filter_cmp = if filters.case_sensitive {
179                            f.clone()
180                        } else {
181                            f.to_lowercase()
182                        };
183
184                        if filters.use_regex {
185                            if let Ok(re) = Regex::new(&filter_cmp) {
186                                re.is_match(&field_cmp)
187                            } else {
188                                false // invalid regex, no match
189                            }
190                        } else {
191                            field_cmp.contains(&filter_cmp)
192                        }
193                    } else {
194                        true
195                    }
196                };
197
198                // Filter by sender
199                if !matches_filter(&email.from, &filters.sender) {
200                    return false;
201                }
202
203                // Filter by recipient
204                if let Some(ref recipient_filter) = filters.recipient {
205                    let has_recipient = email
206                        .to
207                        .iter()
208                        .any(|to| matches_filter(to, &Some(recipient_filter.clone())));
209                    if !has_recipient {
210                        return false;
211                    }
212                }
213
214                // Filter by subject
215                if !matches_filter(&email.subject, &filters.subject) {
216                    return false;
217                }
218
219                // Filter by body
220                if !matches_filter(&email.body, &filters.body) {
221                    return false;
222                }
223
224                // Filter by date range
225                if let Some(since) = filters.since {
226                    if email.received_at < since {
227                        return false;
228                    }
229                }
230
231                if let Some(until) = filters.until {
232                    if email.received_at > until {
233                        return false;
234                    }
235                }
236
237                true
238            })
239            .cloned()
240            .collect();
241
242        // Sort by received_at descending (newest first)
243        results.sort_by(|a, b| b.received_at.cmp(&a.received_at));
244
245        Ok(results)
246    }
247}
248
249/// Mailbox statistics
250#[derive(Debug, Clone)]
251pub struct MailboxStats {
252    pub total_emails: usize,
253    pub max_capacity: usize,
254}
255
256impl Default for SmtpSpecRegistry {
257    fn default() -> Self {
258        Self::new()
259    }
260}
261
262impl SpecRegistry for SmtpSpecRegistry {
263    fn protocol(&self) -> Protocol {
264        Protocol::Smtp
265    }
266
267    fn operations(&self) -> Vec<SpecOperation> {
268        self.fixtures
269            .iter()
270            .map(|fixture| SpecOperation {
271                name: fixture.name.clone(),
272                path: fixture.identifier.clone(),
273                operation_type: "SEND".to_string(),
274                input_schema: None,
275                output_schema: None,
276                metadata: HashMap::from([
277                    ("description".to_string(), fixture.description.clone()),
278                    ("status_code".to_string(), fixture.response.status_code.to_string()),
279                ]),
280            })
281            .collect()
282    }
283
284    fn find_operation(&self, operation: &str, path: &str) -> Option<SpecOperation> {
285        self.fixtures
286            .iter()
287            .find(|f| f.identifier == path)
288            .map(|fixture| SpecOperation {
289                name: fixture.name.clone(),
290                path: fixture.identifier.clone(),
291                operation_type: operation.to_string(),
292                input_schema: None,
293                output_schema: None,
294                metadata: HashMap::from([
295                    ("description".to_string(), fixture.description.clone()),
296                    ("status_code".to_string(), fixture.response.status_code.to_string()),
297                ]),
298            })
299    }
300
301    fn validate_request(&self, request: &ProtocolRequest) -> Result<ValidationResult> {
302        // Validate protocol
303        if request.protocol != Protocol::Smtp {
304            return Ok(ValidationResult::failure(vec![ValidationError {
305                message: "Invalid protocol for SMTP registry".to_string(),
306                path: None,
307                code: Some("INVALID_PROTOCOL".to_string()),
308            }]));
309        }
310
311        // Basic SMTP validation
312        let from = request.metadata.get("from");
313        let to = request.metadata.get("to");
314
315        if from.is_none() {
316            return Ok(ValidationResult::failure(vec![ValidationError {
317                message: "Missing 'from' address".to_string(),
318                path: Some("metadata.from".to_string()),
319                code: Some("MISSING_FROM".to_string()),
320            }]));
321        }
322
323        if to.is_none() {
324            return Ok(ValidationResult::failure(vec![ValidationError {
325                message: "Missing 'to' address".to_string(),
326                path: Some("metadata.to".to_string()),
327                code: Some("MISSING_TO".to_string()),
328            }]));
329        }
330
331        Ok(ValidationResult::success())
332    }
333
334    fn generate_mock_response(&self, request: &ProtocolRequest) -> Result<ProtocolResponse> {
335        let from = request.metadata.get("from").unwrap_or(&String::new()).clone();
336        let to = request.metadata.get("to").unwrap_or(&String::new()).clone();
337        let subject = request.metadata.get("subject").unwrap_or(&String::new()).clone();
338
339        // Find matching fixture
340        let fixture = self.find_matching_fixture(&from, &to, &subject).ok_or_else(|| {
341            mockforge_core::Error::internal("No matching fixture found for email")
342        })?;
343
344        // Storage lives in `server::process_email` now so every delivered
345        // message is captured whether or not a fixture matched. The old
346        // fixture-gated storage here caused silent drops in the common case
347        // of running the mock without any fixtures loaded.
348
349        // Generate response
350        let response_message =
351            format!("{} {}\r\n", fixture.response.status_code, fixture.response.message);
352
353        Ok(ProtocolResponse {
354            status: ResponseStatus::SmtpStatus(fixture.response.status_code),
355            metadata: HashMap::new(),
356            body: response_message.into_bytes(),
357            content_type: "text/plain".to_string(),
358        })
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    fn test_registry_creation() {
368        let registry = SmtpSpecRegistry::new();
369        assert_eq!(registry.protocol(), Protocol::Smtp);
370        assert_eq!(registry.fixtures.len(), 0);
371    }
372
373    #[test]
374    fn test_registry_default() {
375        let registry = SmtpSpecRegistry::default();
376        assert_eq!(registry.protocol(), Protocol::Smtp);
377        assert_eq!(registry.max_mailbox_size, 1000);
378    }
379
380    #[test]
381    fn test_mailbox_operations() {
382        let registry = SmtpSpecRegistry::new();
383
384        let email = StoredEmail {
385            id: "test-123".to_string(),
386            from: "sender@example.com".to_string(),
387            to: vec!["recipient@example.com".to_string()],
388            subject: "Test".to_string(),
389            body: "Test body".to_string(),
390            headers: HashMap::new(),
391            received_at: chrono::Utc::now(),
392            raw: None,
393        };
394
395        registry.store_email(email.clone()).unwrap();
396
397        let emails = registry.get_emails().unwrap();
398        assert_eq!(emails.len(), 1);
399        assert_eq!(emails[0].from, "sender@example.com");
400
401        registry.clear_mailbox().unwrap();
402        let emails = registry.get_emails().unwrap();
403        assert_eq!(emails.len(), 0);
404    }
405
406    #[test]
407    fn test_mailbox_size_limit() {
408        let registry = SmtpSpecRegistry::with_mailbox_size(2);
409
410        for i in 0..5 {
411            let email = StoredEmail {
412                id: format!("test-{}", i),
413                from: "sender@example.com".to_string(),
414                to: vec!["recipient@example.com".to_string()],
415                subject: format!("Test {}", i),
416                body: "Test body".to_string(),
417                headers: HashMap::new(),
418                received_at: chrono::Utc::now(),
419                raw: None,
420            };
421
422            registry.store_email(email).unwrap();
423        }
424
425        let emails = registry.get_emails().unwrap();
426        assert_eq!(emails.len(), 2); // Should only keep the last 2
427    }
428
429    #[test]
430    fn test_get_email_by_id() {
431        let registry = SmtpSpecRegistry::new();
432
433        let email = StoredEmail {
434            id: "unique-id-123".to_string(),
435            from: "sender@example.com".to_string(),
436            to: vec!["recipient@example.com".to_string()],
437            subject: "Test".to_string(),
438            body: "Test body".to_string(),
439            headers: HashMap::new(),
440            received_at: chrono::Utc::now(),
441            raw: None,
442        };
443
444        registry.store_email(email).unwrap();
445
446        let found = registry.get_email_by_id("unique-id-123").unwrap();
447        assert!(found.is_some());
448        assert_eq!(found.unwrap().id, "unique-id-123");
449
450        let not_found = registry.get_email_by_id("nonexistent").unwrap();
451        assert!(not_found.is_none());
452    }
453
454    #[test]
455    fn test_mailbox_stats() {
456        let registry = SmtpSpecRegistry::with_mailbox_size(100);
457
458        let stats = registry.get_mailbox_stats().unwrap();
459        assert_eq!(stats.total_emails, 0);
460        assert_eq!(stats.max_capacity, 100);
461
462        for i in 0..5 {
463            let email = StoredEmail {
464                id: format!("test-{}", i),
465                from: "sender@example.com".to_string(),
466                to: vec!["recipient@example.com".to_string()],
467                subject: format!("Test {}", i),
468                body: "Test body".to_string(),
469                headers: HashMap::new(),
470                received_at: chrono::Utc::now(),
471                raw: None,
472            };
473            registry.store_email(email).unwrap();
474        }
475
476        let stats = registry.get_mailbox_stats().unwrap();
477        assert_eq!(stats.total_emails, 5);
478    }
479
480    #[test]
481    fn test_email_search_filters_default() {
482        let filters = EmailSearchFilters::default();
483        assert!(filters.sender.is_none());
484        assert!(filters.recipient.is_none());
485        assert!(filters.subject.is_none());
486        assert!(filters.body.is_none());
487        assert!(!filters.use_regex);
488        assert!(!filters.case_sensitive);
489    }
490
491    #[test]
492    fn test_search_emails_by_sender() {
493        let registry = SmtpSpecRegistry::new();
494
495        // Add test emails
496        for i in 0..3 {
497            let email = StoredEmail {
498                id: format!("test-{}", i),
499                from: format!("sender{}@example.com", i),
500                to: vec!["recipient@example.com".to_string()],
501                subject: "Test".to_string(),
502                body: "Test body".to_string(),
503                headers: HashMap::new(),
504                received_at: chrono::Utc::now(),
505                raw: None,
506            };
507            registry.store_email(email).unwrap();
508        }
509
510        let filters = EmailSearchFilters {
511            sender: Some("sender1".to_string()),
512            ..Default::default()
513        };
514        let results = registry.search_emails(filters).unwrap();
515        assert_eq!(results.len(), 1);
516        assert!(results[0].from.contains("sender1"));
517    }
518
519    #[test]
520    fn test_search_emails_by_subject() {
521        let registry = SmtpSpecRegistry::new();
522
523        let email1 = StoredEmail {
524            id: "test-1".to_string(),
525            from: "sender@example.com".to_string(),
526            to: vec!["recipient@example.com".to_string()],
527            subject: "Important update".to_string(),
528            body: "Test body".to_string(),
529            headers: HashMap::new(),
530            received_at: chrono::Utc::now(),
531            raw: None,
532        };
533        let email2 = StoredEmail {
534            id: "test-2".to_string(),
535            from: "sender@example.com".to_string(),
536            to: vec!["recipient@example.com".to_string()],
537            subject: "Newsletter".to_string(),
538            body: "Test body".to_string(),
539            headers: HashMap::new(),
540            received_at: chrono::Utc::now(),
541            raw: None,
542        };
543
544        registry.store_email(email1).unwrap();
545        registry.store_email(email2).unwrap();
546
547        let filters = EmailSearchFilters {
548            subject: Some("Important".to_string()),
549            ..Default::default()
550        };
551        let results = registry.search_emails(filters).unwrap();
552        assert_eq!(results.len(), 1);
553        assert!(results[0].subject.contains("Important"));
554    }
555
556    #[test]
557    fn test_search_emails_with_regex() {
558        let registry = SmtpSpecRegistry::new();
559
560        let email = StoredEmail {
561            id: "test-1".to_string(),
562            from: "admin@example.com".to_string(),
563            to: vec!["recipient@example.com".to_string()],
564            subject: "Test".to_string(),
565            body: "Test body".to_string(),
566            headers: HashMap::new(),
567            received_at: chrono::Utc::now(),
568            raw: None,
569        };
570        registry.store_email(email).unwrap();
571
572        let filters = EmailSearchFilters {
573            sender: Some(r"^admin@.*\.com$".to_string()),
574            use_regex: true,
575            ..Default::default()
576        };
577        let results = registry.search_emails(filters).unwrap();
578        assert_eq!(results.len(), 1);
579    }
580
581    #[test]
582    fn test_operations_empty() {
583        let registry = SmtpSpecRegistry::new();
584        let ops = registry.operations();
585        assert!(ops.is_empty());
586    }
587
588    #[test]
589    fn test_find_operation_not_found() {
590        let registry = SmtpSpecRegistry::new();
591        let op = registry.find_operation("SEND", "/nonexistent");
592        assert!(op.is_none());
593    }
594
595    #[test]
596    fn test_validate_request_missing_from() {
597        let registry = SmtpSpecRegistry::new();
598        let request = ProtocolRequest {
599            protocol: Protocol::Smtp,
600            pattern: mockforge_core::protocol_abstraction::MessagePattern::OneWay,
601            operation: "SEND".to_string(),
602            path: "/".to_string(),
603            topic: None,
604            routing_key: None,
605            partition: None,
606            qos: None,
607            metadata: HashMap::from([("to".to_string(), "recipient@example.com".to_string())]),
608            body: None,
609            client_ip: None,
610        };
611
612        let result = registry.validate_request(&request).unwrap();
613        assert!(!result.valid);
614    }
615
616    #[test]
617    fn test_validate_request_missing_to() {
618        let registry = SmtpSpecRegistry::new();
619        let request = ProtocolRequest {
620            protocol: Protocol::Smtp,
621            pattern: mockforge_core::protocol_abstraction::MessagePattern::OneWay,
622            operation: "SEND".to_string(),
623            path: "/".to_string(),
624            topic: None,
625            routing_key: None,
626            partition: None,
627            qos: None,
628            metadata: HashMap::from([("from".to_string(), "sender@example.com".to_string())]),
629            body: None,
630            client_ip: None,
631        };
632
633        let result = registry.validate_request(&request).unwrap();
634        assert!(!result.valid);
635    }
636
637    #[test]
638    fn test_validate_request_valid() {
639        let registry = SmtpSpecRegistry::new();
640        let request = ProtocolRequest {
641            protocol: Protocol::Smtp,
642            pattern: mockforge_core::protocol_abstraction::MessagePattern::OneWay,
643            operation: "SEND".to_string(),
644            path: "/".to_string(),
645            topic: None,
646            routing_key: None,
647            partition: None,
648            qos: None,
649            metadata: HashMap::from([
650                ("from".to_string(), "sender@example.com".to_string()),
651                ("to".to_string(), "recipient@example.com".to_string()),
652            ]),
653            body: None,
654            client_ip: None,
655        };
656
657        let result = registry.validate_request(&request).unwrap();
658        assert!(result.valid);
659    }
660
661    #[test]
662    fn test_validate_request_wrong_protocol() {
663        let registry = SmtpSpecRegistry::new();
664        let request = ProtocolRequest {
665            protocol: Protocol::Http,
666            pattern: mockforge_core::protocol_abstraction::MessagePattern::OneWay,
667            operation: "SEND".to_string(),
668            path: "/".to_string(),
669            topic: None,
670            routing_key: None,
671            partition: None,
672            qos: None,
673            metadata: HashMap::new(),
674            body: None,
675            client_ip: None,
676        };
677
678        let result = registry.validate_request(&request).unwrap();
679        assert!(!result.valid);
680    }
681
682    #[test]
683    fn test_load_fixtures_nonexistent_dir() {
684        let mut registry = SmtpSpecRegistry::new();
685        let result = registry.load_fixtures("/nonexistent/path");
686        // Should succeed but not load any fixtures
687        assert!(result.is_ok());
688        assert_eq!(registry.fixtures.len(), 0);
689    }
690}