summaryrefslogtreecommitdiff
path: root/crates/directory/src/backend/smtp/pool.rs
blob: 094a7a8e17150ca17f3dcbc509d020d6a6509cdc (plain)
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use deadpool::managed;
use mail_send::{smtp::AssertReply, Error};

use super::{SmtpClient, SmtpConnectionManager};

impl managed::Manager for SmtpConnectionManager {
    type Type = SmtpClient;
    type Error = Error;

    async fn create(&self) -> Result<SmtpClient, Error> {
        let mut client = self.builder.connect().await?;
        let capabilities = client
            .capabilities(&self.builder.local_host, self.builder.is_lmtp)
            .await?;

        Ok(SmtpClient {
            capabilities,
            client,
            max_auth_errors: self.max_auth_errors,
            max_rcpt: self.max_rcpt,
            num_rcpts: 0,
            num_auth_failures: 0,
            sent_mail_from: false,
        })
    }

    async fn recycle(
        &self,
        conn: &mut SmtpClient,
        _: &managed::Metrics,
    ) -> managed::RecycleResult<Error> {
        if conn.num_auth_failures < conn.max_auth_errors {
            conn.client
                .cmd(b"NOOP\r\n")
                .await?
                .assert_positive_completion()
                .map(|_| ())
                .map_err(managed::RecycleError::Backend)
        } else {
            Err(managed::RecycleError::Message(
                "No longer valid: Too many authentication failures"
                    .to_string()
                    .into(),
            ))
        }
    }
}