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
//! # Sōzu client
//!
//! This library provides a client to interact with Sōzu.
//! The client is able to do one-time request or send batches.

use bb8::Pool;
use sozu_command_lib::{
    channel::ChannelError,
    proto::command::{request::RequestType, Request, Response, ResponseStatus, WorkerRequest},
};
use tempdir::TempDir;
use tokio::{
    fs::File,
    io::{AsyncWriteExt, BufWriter},
    task::{spawn_blocking as blocking, JoinError},
};
use tracing::trace;

use crate::channel::{ConnectionManager, ConnectionProperties};

pub mod channel;
pub mod config;
pub mod socket;
#[cfg(feature = "unpooled")]
pub mod unpooled;

// -----------------------------------------------------------------------------
// Error

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("failed to create connection pool over unix socket, {0}")]
    CreatePool(channel::Error),
    #[error("failed to execute blocking task, {0}")]
    Join(JoinError),
    #[error("failed to get connection to socket, {0}")]
    GetConnection(bb8::RunError<channel::Error>),
    #[error("failed to send request, {0}")]
    Send(ChannelError),
    #[error("failed to read response, {0}")]
    Receive(ChannelError),
    #[error("got an invalid status code, {0}")]
    InvalidStatusCode(i32),
    #[error("failed to execute request, got status '{0}', {1}")]
    Failure(String, String, Response),
    #[error("failed to create temporary directory, {0}")]
    CreateTempDir(std::io::Error),
    #[error("failed to create temporary file, {0}")]
    CreateTempFile(std::io::Error),
    #[error("failed to serialize worker request, {0}")]
    Serialize(serde_json::Error),
    #[error("failed to write worker request, {0}")]
    Write(std::io::Error),
    #[error("failed to flush worker request buffer, {0}")]
    Flush(std::io::Error),
}

impl From<JoinError> for Error {
    #[tracing::instrument]
    fn from(err: JoinError) -> Self {
        Self::Join(err)
    }
}

impl Error {
    #[tracing::instrument]
    pub fn is_recoverable(&self) -> bool {
        !matches!(self, Self::Send(_) | Self::Receive(_) | Self::CreatePool(_) | Self::GetConnection(_))
    }
}

// -----------------------------------------------------------------------------
// Sender

#[async_trait::async_trait]
pub trait Sender {
    type Error;

    async fn send(&self, request: RequestType) -> Result<Response, Self::Error>;

    async fn send_all(&self, requests: &[RequestType]) -> Result<Response, Self::Error>;
}

// -----------------------------------------------------------------------------
// Client

#[derive(Clone, Debug)]
pub struct Client {
    pool: Pool<ConnectionManager>,
}

#[async_trait::async_trait]
impl Sender for Client {
    type Error = Error;

    #[tracing::instrument(skip_all)]
    async fn send(&self, request: RequestType) -> Result<Response, Self::Error> {
        trace!("Retrieve a connection to Sōzu's socket");
        let mut conn = self.pool.get().await.map_err(Error::GetConnection)?;

        trace!("Send request to Sōzu");
        conn.write_message(&Request {
            request_type: Some(request),
        })
        .map_err(Error::Send)?;

        loop {
            trace!("Read request to Sōzu");
            let response = conn.read_message().map_err(Error::Receive)?;

            let status = ResponseStatus::try_from(response.status)
                .map_err(|_| Error::InvalidStatusCode(response.status))?;

            match status {
                ResponseStatus::Processing => continue,
                ResponseStatus::Failure => {
                    return Err(Error::Failure(status.as_str_name().to_string(), response.message.to_string().to_lowercase(), response));
                }
                ResponseStatus::Ok => {
                    return Ok(response);
                }
            }
        }
    }

    #[tracing::instrument(skip_all)]
    async fn send_all(&self, requests: &[RequestType]) -> Result<Response, Self::Error> {
        // -------------------------------------------------------------------------
        // Create temporary folder and writer to batch requests
        let tmpdir =
            blocking(|| TempDir::new(env!("CARGO_PKG_NAME")).map_err(Error::CreateTempDir))
                .await??;

        let path = tmpdir.path().join("requests.json");
        let mut writer = BufWriter::new(File::create(&path).await.map_err(Error::CreateTempFile)?);

        for (idx, request) in requests.iter().cloned().enumerate() {
            let worker_request = WorkerRequest {
                id: format!("{}-{idx}", env!("CARGO_PKG_NAME")).to_uppercase(),
                content: Request::from(request),
            };

            let payload =
                blocking(move || serde_json::to_string(&worker_request).map_err(Error::Serialize))
                    .await??;

            writer
                .write_all(format!("{payload}\n\0").as_bytes())
                .await
                .map_err(Error::Write)?;
        }

        writer.flush().await.map_err(Error::Flush)?;

        // -------------------------------------------------------------------------
        // Send a LoadState request with the file that we have created.
        self.send(RequestType::LoadState(path.to_string_lossy().to_string()))
            .await
    }
}

impl From<Pool<ConnectionManager>> for Client {
    #[tracing::instrument(skip_all)]
    fn from(pool: Pool<ConnectionManager>) -> Self {
        Self { pool }
    }
}

impl Client {
    #[tracing::instrument]
    pub async fn try_new(opts: ConnectionProperties) -> Result<Self, Error> {
        let pool = Pool::builder()
            .build(ConnectionManager::new(opts))
            .await
            .map_err(Error::CreatePool)?;

        Ok(Self::from(pool))
    }
}