Skip to main content

interloper_server/
service.rs

1//! The logic the routes call. Routes own HTTP; this owns everything else.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use futures::StreamExt;
7use interloper::parse::extract_otp;
8use interloper::regex::Regex;
9use interloper::{Address, Inbox, Interloper, MailFilter, Message, Request};
10
11use crate::error::ApiError;
12use crate::fleet::HealthSync;
13use crate::store::Store;
14
15pub struct Service {
16    pub il: Interloper,
17    pub store: Store,
18    /// Set in fleet mode (Postgres): health shared with the other instances.
19    pub fleet: Option<Arc<HealthSync>>,
20}
21
22impl Service {
23    pub fn new(il: Interloper, store: Store) -> Arc<Self> {
24        Self::with_fleet(il, store, None)
25    }
26
27    pub fn with_fleet(il: Interloper, store: Store, fleet: Option<Arc<HealthSync>>) -> Arc<Self> {
28        Arc::new(Service { il, store, fleet })
29    }
30
31    pub async fn create(&self, req: &Request) -> Result<Address, ApiError> {
32        let inbox = self.il.inbox(req).await?;
33        let address = inbox.address().clone();
34        self.store.put(&address).await?;
35        Ok(address)
36    }
37
38    /// A live inbox for a stored address. The provider is looked up by name,
39    /// so the object serving a request is not the one that issued the address
40    /// (in fleet mode, not even the same process).
41    pub async fn inbox(&self, value: &str) -> Result<Inbox, ApiError> {
42        let address = self
43            .store
44            .get(value)
45            .await?
46            .ok_or(ApiError::UnknownAddress)?;
47        Ok(self.il.resume(address)?)
48    }
49
50    /// Return a quarantined provider to routing; fleet-wide in fleet mode.
51    pub async fn clear_quarantine(&self, provider: &str) -> Result<bool, ApiError> {
52        match &self.fleet {
53            Some(f) => Ok(f.clear_quarantine(provider).await?),
54            None => Ok(self.il.health().unquarantine(provider)),
55        }
56    }
57
58    pub async fn get_message(
59        &self,
60        value: &str,
61        id: &str,
62    ) -> Result<(Message, Option<String>), ApiError> {
63        let m = self.inbox(value).await?.get(id).await?;
64        let code = extract_otp(&m.subject, &m.text, None);
65        Ok((m, code))
66    }
67
68    /// Hold until matching mail arrives or `timeout` passes. `Ok(None)` means
69    /// nothing arrived in time: a normal answer, not an error. With
70    /// `want_otp`, mail without a code is skipped: a caller waiting for a code
71    /// does not want the newsletter that arrived first.
72    pub async fn wait(
73        &self,
74        value: &str,
75        timeout: Duration,
76        pattern: Option<&Regex>,
77        want_otp: bool,
78        filter: &MailFilter,
79    ) -> Result<Option<(Message, Option<String>)>, ApiError> {
80        let inbox = self.inbox(value).await?;
81        let search = async {
82            let mut stream = inbox.watch(None);
83            while let Some(m) = stream.next().await {
84                let m = m?;
85                if !filter.accepts(&m) {
86                    continue;
87                }
88                let code = extract_otp(&m.subject, &m.text, pattern);
89                if want_otp && code.is_none() {
90                    continue;
91                }
92                return Ok(Some((m, code)));
93            }
94            Ok(None)
95        };
96        // Dropping the stream on timeout cancels its polling; nothing leaks.
97        match tokio::time::timeout(timeout, search).await {
98            Ok(r) => r,
99            Err(_) => Ok(None),
100        }
101    }
102}