Skip to main content

pgdo/cluster/
client.rs

1//! A minimal, synchronous PostgreSQL client.
2//!
3//! This is just enough client for pgdo's own needs: it connects over a
4//! Unix-domain socket, supports only [trust authentication][trust] – which is
5//! how pgdo creates clusters – and sends queries using the [simple query
6//! protocol][simple-query], receiving all values as text.
7//!
8//! It is synchronous in the most ordinary way: it blocks on socket I/O. Unlike
9//! clients that wrap an async implementation, it is safe to call from within an
10//! async context, though it will block the calling thread.
11//!
12//! To work with a cluster from your own code, use a full-featured client
13//! library, connecting via [`Cluster::datadir`][`super::Cluster::datadir`]
14//! or [`Cluster::url`][`super::Cluster::url`].
15//!
16//! [trust]: https://www.postgresql.org/docs/current/auth-trust.html
17//! [simple-query]:
18//!     https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-SIMPLE-QUERY
19
20use std::fmt;
21use std::io::{self, Read, Write};
22use std::os::unix::net::UnixStream;
23use std::path::Path;
24
25use bytes::BytesMut;
26use fallible_iterator::FallibleIterator;
27use postgres_protocol::message::{backend::Message, frontend};
28
29use super::PORT;
30
31/// The path to the Unix-domain socket of a server listening on `port` in
32/// `socketdir`.
33pub(super) fn socket_path(socketdir: &Path, port: u16) -> std::path::PathBuf {
34    socketdir.join(format!(".s.PGSQL.{port}"))
35}
36
37/// Does a server accept connections on the Unix-domain socket for `port` in
38/// `socketdir`?
39///
40/// This works across PID namespaces on the same kernel, where PostgreSQL's own
41/// check – signalling the PID in `postmaster.pid` – does not. It does not work
42/// across kernels, e.g. from macOS into a Linux VM.
43///
44/// Returns an error if we cannot tell, e.g. because the socket's path is too
45/// long for this platform. Treating that as "no" could lead the caller to start
46/// a second server on the same data.
47pub(super) fn accepts_connections(socketdir: &Path, port: u16) -> io::Result<bool> {
48    match UnixStream::connect(socket_path(socketdir, port)) {
49        Ok(_) => Ok(true),
50        Err(err)
51            if matches!(
52                err.kind(),
53                io::ErrorKind::ConnectionRefused | io::ErrorKind::NotFound
54            ) =>
55        {
56            Ok(false)
57        }
58        Err(err) => Err(err),
59    }
60}
61
62/// SQLSTATE for "duplicate database".
63pub(super) const DUPLICATE_DATABASE: &str = "42P04";
64/// SQLSTATE for "undefined database" (a.k.a. "invalid catalog name").
65pub(super) const UNDEFINED_DATABASE: &str = "3D000";
66
67/// Error communicating with a cluster.
68#[derive(thiserror::Error, Debug)]
69pub enum ClientError {
70    #[error("could not communicate with cluster")]
71    IoError(#[from] io::Error),
72    #[error(transparent)]
73    ServerError(Box<ServerError>),
74    #[error("cluster requires {0} authentication, which pgdo does not support")]
75    AuthenticationError(&'static str),
76    #[error("unexpected message from cluster: {0}")]
77    ProtocolError(String),
78}
79
80impl ClientError {
81    /// A suggestion for how to resolve this error, if there is one, e.g. a hint
82    /// from the PostgreSQL server.
83    pub fn help(&self) -> Option<String> {
84        match self {
85            Self::AuthenticationError(_) => Some(
86                "pgdo creates clusters with trust authentication; check `pg_hba.conf` in the \
87                 cluster."
88                    .into(),
89            ),
90            Self::ServerError(err) => err.hint.clone(),
91            Self::IoError(_) | Self::ProtocolError(_) => None,
92        }
93    }
94}
95
96impl From<ServerError> for ClientError {
97    fn from(error: ServerError) -> Self {
98        Self::ServerError(Box::new(error))
99    }
100}
101
102/// An error reported by the PostgreSQL server.
103#[derive(Debug, Clone)]
104pub struct ServerError {
105    /// e.g. `ERROR`, `FATAL`.
106    pub severity: String,
107    /// The [SQLSTATE code][sqlstate], e.g. `42P04`.
108    ///
109    /// [sqlstate]: https://www.postgresql.org/docs/current/errcodes-appendix.html
110    pub code: String,
111    pub message: String,
112    pub detail: Option<String>,
113    pub hint: Option<String>,
114}
115
116impl std::error::Error for ServerError {}
117
118impl fmt::Display for ServerError {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(
121            f,
122            "{}: {} (SQLSTATE {})",
123            self.severity, self.message, self.code
124        )?;
125        if let Some(detail) = &self.detail {
126            write!(f, "; {detail}")?;
127        }
128        Ok(())
129    }
130}
131
132impl ServerError {
133    fn from_fields(body: &postgres_protocol::message::backend::ErrorResponseBody) -> Self {
134        let mut error = ServerError {
135            severity: String::new(),
136            code: String::new(),
137            message: String::new(),
138            detail: None,
139            hint: None,
140        };
141        let mut fields = body.fields();
142        // Stop at the first malformed field; we'll use what we have so far.
143        while let Ok(Some(field)) = fields.next() {
144            let value = String::from_utf8_lossy(field.value_bytes()).into_owned();
145            match field.type_() {
146                // Non-localised severity is preferred; it's only present in
147                // PostgreSQL 9.6 and later, but that's everything we support.
148                b'V' => error.severity = value,
149                b'C' => error.code = value,
150                b'M' => error.message = value,
151                b'D' => error.detail = Some(value),
152                b'H' => error.hint = Some(value),
153                _ => (),
154            }
155        }
156        error
157    }
158}
159
160/// A row returned from a query. All values are text, or `None` for `NULL`.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub(super) struct Row(Vec<Option<String>>);
163
164impl Row {
165    /// Get the value in the given column. Panics if the column is out of
166    /// range; that's a programming error.
167    pub(super) fn get(&self, column: usize) -> Option<&str> {
168        self.0[column].as_deref()
169    }
170}
171
172/// A connection to a cluster.
173pub(super) struct Client {
174    stream: UnixStream,
175    buf: BytesMut,
176}
177
178impl Client {
179    /// Connect to the cluster listening in `socketdir`, with trust
180    /// authentication.
181    pub(super) fn connect(
182        socketdir: &Path,
183        user: &str,
184        database: &str,
185    ) -> Result<Self, ClientError> {
186        let stream = UnixStream::connect(socket_path(socketdir, PORT))?;
187        let mut client = Client { stream, buf: BytesMut::new() };
188
189        let mut message = BytesMut::new();
190        frontend::startup_message(
191            [
192                ("user", user),
193                ("database", database),
194                ("application_name", "pgdo"),
195                // We decode values as UTF-8; ask the server to send them so.
196                ("client_encoding", "UTF8"),
197            ],
198            &mut message,
199        )?;
200        client.stream.write_all(&message)?;
201
202        // Authentication.
203        match client.receive()? {
204            Message::AuthenticationOk => (),
205            Message::ErrorResponse(body) => Err(ServerError::from_fields(&body))?,
206            Message::AuthenticationCleartextPassword => {
207                Err(ClientError::AuthenticationError("password"))?;
208            }
209            Message::AuthenticationMd5Password(_) => Err(ClientError::AuthenticationError("MD5"))?,
210            Message::AuthenticationSasl(_) => Err(ClientError::AuthenticationError("SASL"))?,
211            Message::AuthenticationGss | Message::AuthenticationSspi => {
212                Err(ClientError::AuthenticationError("GSSAPI/SSPI"))?;
213            }
214            message => Err(unexpected(&message))?,
215        }
216
217        // Wait for the server to be ready, ignoring parameter statuses, etc.
218        loop {
219            match client.receive()? {
220                Message::ReadyForQuery(_) => break Ok(client),
221                Message::ErrorResponse(body) => Err(ServerError::from_fields(&body))?,
222                Message::ParameterStatus(_)
223                | Message::BackendKeyData(_)
224                | Message::NoticeResponse(_) => continue,
225                message => Err(unexpected(&message))?,
226            }
227        }
228    }
229
230    /// Execute the given SQL and return all rows from all statements.
231    ///
232    /// This uses the simple query protocol, so `sql` may contain several
233    /// statements, but cannot have parameters: escape values into it with
234    /// [`postgres_protocol::escape`]. `COPY` is not supported.
235    pub(super) fn query(&mut self, sql: &str) -> Result<Vec<Row>, ClientError> {
236        let mut message = BytesMut::new();
237        frontend::query(sql, &mut message)?;
238        self.stream.write_all(&message)?;
239
240        let mut rows = Vec::new();
241        let mut error = None;
242        loop {
243            match self.receive()? {
244                Message::ReadyForQuery(_) => break,
245                Message::DataRow(body) => {
246                    let buffer = body.buffer();
247                    let row = body
248                        .ranges()
249                        .map(|range| {
250                            Ok(range
251                                .map(|range| String::from_utf8_lossy(&buffer[range]).into_owned()))
252                        })
253                        .collect()?;
254                    rows.push(Row(row));
255                    continue;
256                }
257                Message::ErrorResponse(body) => {
258                    error = Some(ServerError::from_fields(&body));
259                    continue;
260                }
261                Message::RowDescription(_)
262                | Message::CommandComplete(_)
263                | Message::EmptyQueryResponse
264                | Message::NoticeResponse(_)
265                | Message::ParameterStatus(_) => continue,
266                message => Err(unexpected(&message))?,
267            }
268        }
269
270        match error {
271            Some(error) => Err(error)?,
272            None => Ok(rows),
273        }
274    }
275
276    /// Execute the given SQL, discarding any rows.
277    pub(super) fn execute(&mut self, sql: &str) -> Result<(), ClientError> {
278        self.query(sql).map(|_| ())
279    }
280
281    /// Receive one message from the server.
282    fn receive(&mut self) -> Result<Message, ClientError> {
283        loop {
284            if let Some(message) = Message::parse(&mut self.buf)? {
285                return Ok(message);
286            } else {
287                let mut chunk = [0u8; 8192];
288                match self.stream.read(&mut chunk)? {
289                    0 => Err(io::Error::from(io::ErrorKind::UnexpectedEof))?,
290                    n => {
291                        self.buf.extend_from_slice(&chunk[..n]);
292                        continue;
293                    }
294                }
295            }
296        }
297    }
298}
299
300impl Drop for Client {
301    fn drop(&mut self) {
302        // Say goodbye politely. If this fails the server will notice the
303        // connection has gone anyway.
304        let mut message = BytesMut::new();
305        frontend::terminate(&mut message);
306        let _ = self.stream.write_all(&message);
307    }
308}
309
310fn unexpected(message: &Message) -> ClientError {
311    // `Message` does not implement `Debug`, so describe it by its variant.
312    let name = match message {
313        Message::CopyInResponse(_) | Message::CopyOutResponse(_) | Message::CopyData(_) => "COPY",
314        Message::NotificationResponse(_) => "notification",
315        Message::AuthenticationSaslContinue(_) | Message::AuthenticationSaslFinal(_) => {
316            "authentication"
317        }
318        _ => "other",
319    };
320    ClientError::ProtocolError(name.into())
321}
322
323#[cfg(test)]
324mod tests {
325    use super::{Client, ClientError, Row, UNDEFINED_DATABASE};
326    use crate::cluster::{Cluster, DATABASE_POSTGRES};
327    use crate::runtime::strategy::Strategy;
328
329    type TestResult = Result<(), Box<dyn std::error::Error>>;
330
331    fn with_cluster(test: impl FnOnce(&Cluster) -> TestResult) -> TestResult {
332        let tempdir = tempfile::tempdir()?;
333        let cluster = Cluster::new(tempdir.path().join("data"), Strategy::default())?;
334        cluster.start(&[])?;
335        let result = test(&cluster);
336        cluster.stop()?;
337        result
338    }
339
340    fn connect(cluster: &Cluster, database: &str) -> Result<Client, ClientError> {
341        let user = crate::util::current_user().unwrap();
342        Client::connect(&cluster.datadir, &user, database)
343    }
344
345    #[test]
346    fn query_returns_rows_including_nulls() -> TestResult {
347        with_cluster(|cluster| {
348            let mut client = connect(cluster, DATABASE_POSTGRES)?;
349            let rows = client.query("SELECT 1, NULL, 'three' UNION ALL SELECT 4, '5', NULL")?;
350            assert_eq!(
351                rows,
352                vec![
353                    Row(vec![Some("1".into()), None, Some("three".into())]),
354                    Row(vec![Some("4".into()), Some("5".into()), None]),
355                ]
356            );
357            Ok(())
358        })
359    }
360
361    #[test]
362    fn query_returns_rows_from_all_statements() -> TestResult {
363        with_cluster(|cluster| {
364            let mut client = connect(cluster, DATABASE_POSTGRES)?;
365            let rows = client.query("SELECT 1; SELECT 2; ; SET application_name = 'foo'")?;
366            let values: Vec<_> = rows.iter().map(|row| row.get(0)).collect();
367            assert_eq!(values, vec![Some("1"), Some("2")]);
368            Ok(())
369        })
370    }
371
372    #[test]
373    fn query_returns_large_results() -> TestResult {
374        with_cluster(|cluster| {
375            let mut client = connect(cluster, DATABASE_POSTGRES)?;
376            // Larger than the read buffer, to exercise reassembly of messages.
377            let rows = client.query("SELECT repeat('x', 100000) FROM generate_series(1, 3)")?;
378            assert_eq!(rows.len(), 3);
379            assert!(rows
380                .iter()
381                .all(|row| row.get(0).map(str::len) == Some(100_000)));
382            Ok(())
383        })
384    }
385
386    #[test]
387    fn query_reports_server_errors_and_client_remains_usable() -> TestResult {
388        with_cluster(|cluster| {
389            let mut client = connect(cluster, DATABASE_POSTGRES)?;
390            match client.query("SELECT * FROM no_such_table") {
391                Err(ClientError::ServerError(error)) => {
392                    assert_eq!(error.severity, "ERROR");
393                    assert_eq!(error.code, "42P01"); // undefined_table.
394                }
395                other => panic!("unexpected result: {other:?}"),
396            }
397            assert_eq!(client.query("SELECT 'ok'")?[0].get(0), Some("ok"));
398            Ok(())
399        })
400    }
401
402    #[test]
403    fn query_decodes_utf8() -> TestResult {
404        with_cluster(|cluster| {
405            let mut client = connect(cluster, DATABASE_POSTGRES)?;
406            let rows = client.query("SELECT 'Hello, 世界 🐘'")?;
407            assert_eq!(rows[0].get(0), Some("Hello, 世界 🐘"));
408            Ok(())
409        })
410    }
411
412    #[test]
413    fn connect_reports_missing_database() -> TestResult {
414        with_cluster(|cluster| {
415            match connect(cluster, "no-such-database") {
416                Err(ClientError::ServerError(error)) => {
417                    assert_eq!(error.severity, "FATAL");
418                    assert_eq!(error.code, UNDEFINED_DATABASE);
419                }
420                Err(err) => panic!("unexpected error: {err:?}"),
421                Ok(_) => panic!("unexpectedly connected"),
422            }
423            Ok(())
424        })
425    }
426
427    #[test]
428    fn client_works_within_async_context() -> TestResult {
429        // The `postgres` crate panics here; this client merely blocks.
430        with_cluster(|cluster| {
431            let runtime = tokio::runtime::Builder::new_current_thread().build()?;
432            runtime.block_on(async {
433                let mut client = connect(cluster, DATABASE_POSTGRES)?;
434                assert_eq!(client.query("SELECT 1")?[0].get(0), Some("1"));
435                Ok(())
436            })
437        })
438    }
439}