Skip to main content

tokio_postgres/
connection.rs

1use crate::codec::{BackendMessage, BackendMessages, FrontendMessage, PostgresCodec};
2use crate::copy_in::CopyInReceiver;
3use crate::error::DbError;
4use crate::maybe_tls_stream::MaybeTlsStream;
5use crate::{AsyncMessage, Error, Notification};
6use bytes::BytesMut;
7use fallible_iterator::FallibleIterator;
8use futures_channel::mpsc;
9use futures_util::{Sink, Stream, StreamExt, ready, stream::FusedStream};
10use log::{info, trace};
11use postgres_protocol::message::backend::Message;
12use postgres_protocol::message::frontend;
13use std::collections::{HashMap, VecDeque};
14use std::future::Future;
15use std::pin::Pin;
16use std::task::{Context, Poll};
17use tokio::io::{AsyncRead, AsyncWrite};
18use tokio_util::codec::Framed;
19
20pub enum RequestMessages {
21    Single(FrontendMessage),
22    CopyIn(CopyInReceiver),
23}
24
25pub struct Request {
26    pub messages: RequestMessages,
27    pub sender: mpsc::Sender<BackendMessages>,
28}
29
30pub struct Response {
31    sender: mpsc::Sender<BackendMessages>,
32}
33
34#[derive(PartialEq, Debug)]
35enum State {
36    Active,
37    Terminating,
38    Closing,
39}
40
41/// A connection to a PostgreSQL database.
42///
43/// This is one half of what is returned when a new connection is established. It performs the actual IO with the
44/// server, and should generally be spawned off onto an executor to run in the background.
45///
46/// `Connection` implements `Future`, and only resolves when the connection is closed, either because a fatal error has
47/// occurred, or because its associated `Client` has dropped and all outstanding work has completed.
48#[must_use = "futures do nothing unless polled"]
49pub struct Connection<S, T> {
50    stream: Framed<MaybeTlsStream<S, T>, PostgresCodec>,
51    parameters: HashMap<String, String>,
52    receiver: mpsc::UnboundedReceiver<Request>,
53    pending_request: Option<RequestMessages>,
54    pending_responses: VecDeque<BackendMessage>,
55    responses: VecDeque<Response>,
56    state: State,
57    /// What a new request wakes instead of the task polling the connection,
58    /// if set: see [`Connection::driven_by`].
59    request_waker: Option<std::task::Waker>,
60}
61
62impl<S, T> Connection<S, T>
63where
64    S: AsyncRead + AsyncWrite + Unpin,
65    T: AsyncRead + AsyncWrite + Unpin,
66{
67    pub(crate) fn new(
68        stream: Framed<MaybeTlsStream<S, T>, PostgresCodec>,
69        pending_responses: VecDeque<BackendMessage>,
70        parameters: HashMap<String, String>,
71        receiver: mpsc::UnboundedReceiver<Request>,
72    ) -> Connection<S, T> {
73        Connection {
74            stream,
75            parameters,
76            receiver,
77            pending_request: None,
78            pending_responses,
79            responses: VecDeque::new(),
80            state: State::Active,
81            request_waker: None,
82        }
83    }
84
85    pub(crate) fn set_request_waker(&mut self, waker: std::task::Waker) {
86        self.request_waker = Some(waker);
87    }
88
89    fn poll_response(
90        &mut self,
91        cx: &mut Context<'_>,
92    ) -> Poll<Option<Result<BackendMessage, Error>>> {
93        if let Some(message) = self.pending_responses.pop_front() {
94            trace!("retrying pending response");
95            return Poll::Ready(Some(Ok(message)));
96        }
97
98        Pin::new(&mut self.stream)
99            .poll_next(cx)
100            .map(|o| o.map(|r| r.map_err(Error::io)))
101    }
102
103    fn poll_read(&mut self, cx: &mut Context<'_>) -> Result<Option<AsyncMessage>, Error> {
104        if self.state != State::Active {
105            trace!("poll_read: done");
106            return Ok(None);
107        }
108
109        loop {
110            let message = match self.poll_response(cx)? {
111                Poll::Ready(Some(message)) => message,
112                Poll::Ready(None) => return Err(Error::closed()),
113                Poll::Pending => {
114                    trace!("poll_read: waiting on response");
115                    return Ok(None);
116                }
117            };
118
119            let (mut messages, request_complete) = match message {
120                BackendMessage::Async(Message::NoticeResponse(body)) => {
121                    let error = DbError::parse(&mut body.fields()).map_err(Error::parse)?;
122                    return Ok(Some(AsyncMessage::Notice(error)));
123                }
124                BackendMessage::Async(Message::NotificationResponse(body)) => {
125                    let notification = Notification {
126                        process_id: body.process_id(),
127                        channel: body.channel().map_err(Error::parse)?.to_string(),
128                        payload: body.message().map_err(Error::parse)?.to_string(),
129                    };
130                    return Ok(Some(AsyncMessage::Notification(notification)));
131                }
132                BackendMessage::Async(Message::ParameterStatus(body)) => {
133                    self.parameters.insert(
134                        body.name().map_err(Error::parse)?.to_string(),
135                        body.value().map_err(Error::parse)?.to_string(),
136                    );
137                    continue;
138                }
139                BackendMessage::Async(_) => unreachable!(),
140                BackendMessage::Normal {
141                    messages,
142                    request_complete,
143                } => (messages, request_complete),
144            };
145
146            let mut response = match self.responses.pop_front() {
147                Some(response) => response,
148                None => match messages.next().map_err(Error::parse)? {
149                    Some(Message::ErrorResponse(error)) => return Err(Error::db(error)),
150                    _ => return Err(Error::unexpected_message()),
151                },
152            };
153
154            match response.sender.poll_ready(cx) {
155                Poll::Ready(Ok(())) => {
156                    let _ = response.sender.start_send(messages);
157                    if !request_complete {
158                        self.responses.push_front(response);
159                    }
160                }
161                Poll::Ready(Err(_)) => {
162                    // we need to keep paging through the rest of the messages even if the receiver's hung up
163                    if !request_complete {
164                        self.responses.push_front(response);
165                    }
166                }
167                Poll::Pending => {
168                    self.responses.push_front(response);
169                    self.pending_responses.push_back(BackendMessage::Normal {
170                        messages,
171                        request_complete,
172                    });
173                    trace!("poll_read: waiting on sender");
174                    return Ok(None);
175                }
176            }
177        }
178    }
179
180    fn poll_request(&mut self, cx: &mut Context<'_>) -> Poll<Option<RequestMessages>> {
181        if let Some(messages) = self.pending_request.take() {
182            trace!("retrying pending request");
183            return Poll::Ready(Some(messages));
184        }
185
186        if self.receiver.is_terminated() {
187            return Poll::Ready(None);
188        }
189
190        let next = match &self.request_waker {
191            Some(waker) => self
192                .receiver
193                .poll_next_unpin(&mut Context::from_waker(waker)),
194            None => self.receiver.poll_next_unpin(cx),
195        };
196        match next {
197            Poll::Ready(Some(request)) => {
198                trace!("polled new request");
199                self.responses.push_back(Response {
200                    sender: request.sender,
201                });
202                Poll::Ready(Some(request.messages))
203            }
204            Poll::Ready(None) => Poll::Ready(None),
205            Poll::Pending => Poll::Pending,
206        }
207    }
208
209    fn poll_write(&mut self, cx: &mut Context<'_>) -> Result<bool, Error> {
210        loop {
211            if self.state == State::Closing {
212                trace!("poll_write: done");
213                return Ok(false);
214            }
215
216            if Pin::new(&mut self.stream)
217                .poll_ready(cx)
218                .map_err(Error::io)?
219                .is_pending()
220            {
221                trace!("poll_write: waiting on socket");
222                return Ok(false);
223            }
224
225            let request = match self.poll_request(cx) {
226                Poll::Ready(Some(request)) => request,
227                Poll::Ready(None) if self.responses.is_empty() && self.state == State::Active => {
228                    trace!("poll_write: at eof, terminating");
229                    self.state = State::Terminating;
230                    let mut request = BytesMut::new();
231                    frontend::terminate(&mut request);
232                    RequestMessages::Single(FrontendMessage::Raw(request.freeze()))
233                }
234                Poll::Ready(None) => {
235                    trace!(
236                        "poll_write: at eof, pending responses {}",
237                        self.responses.len()
238                    );
239                    return Ok(true);
240                }
241                Poll::Pending => {
242                    trace!("poll_write: waiting on request");
243                    return Ok(true);
244                }
245            };
246
247            match request {
248                RequestMessages::Single(request) => {
249                    Pin::new(&mut self.stream)
250                        .start_send(request)
251                        .map_err(Error::io)?;
252                    if self.state == State::Terminating {
253                        trace!("poll_write: sent eof, closing");
254                        self.state = State::Closing;
255                    }
256                }
257                RequestMessages::CopyIn(mut receiver) => {
258                    let message = match receiver.poll_next_unpin(cx) {
259                        Poll::Ready(Some(message)) => message,
260                        Poll::Ready(None) => {
261                            trace!("poll_write: finished copy_in request");
262                            continue;
263                        }
264                        Poll::Pending => {
265                            trace!("poll_write: waiting on copy_in stream");
266                            self.pending_request = Some(RequestMessages::CopyIn(receiver));
267                            return Ok(true);
268                        }
269                    };
270                    Pin::new(&mut self.stream)
271                        .start_send(message)
272                        .map_err(Error::io)?;
273                    self.pending_request = Some(RequestMessages::CopyIn(receiver));
274                }
275            }
276        }
277    }
278
279    fn poll_flush(&mut self, cx: &mut Context<'_>) -> Result<(), Error> {
280        match Pin::new(&mut self.stream)
281            .poll_flush(cx)
282            .map_err(Error::io)?
283        {
284            Poll::Ready(()) => trace!("poll_flush: flushed"),
285            Poll::Pending => trace!("poll_flush: waiting on socket"),
286        }
287        Ok(())
288    }
289
290    fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
291        if self.state != State::Closing {
292            return Poll::Pending;
293        }
294
295        match Pin::new(&mut self.stream)
296            .poll_close(cx)
297            .map_err(Error::io)?
298        {
299            Poll::Ready(()) => {
300                trace!("poll_shutdown: complete");
301                Poll::Ready(Ok(()))
302            }
303            Poll::Pending => {
304                trace!("poll_shutdown: waiting on socket");
305                Poll::Pending
306            }
307        }
308    }
309
310    /// Returns the value of a runtime parameter for this connection.
311    pub fn parameter(&self, name: &str) -> Option<&str> {
312        self.parameters.get(name).map(|s| &**s)
313    }
314
315    /// Polls for asynchronous messages from the server.
316    ///
317    /// The server can send notices as well as notifications asynchronously to the client. Applications that wish to
318    /// examine those messages should use this method to drive the connection rather than its `Future` implementation.
319    ///
320    /// Return values of `None` or `Some(Err(_))` are "terminal"; callers should not invoke this method again after
321    /// receiving one of those values.
322    pub fn poll_message(
323        &mut self,
324        cx: &mut Context<'_>,
325    ) -> Poll<Option<Result<AsyncMessage, Error>>> {
326        let message = self.poll_read(cx)?;
327        let want_flush = self.poll_write(cx)?;
328        if want_flush {
329            self.poll_flush(cx)?;
330        }
331        match message {
332            Some(message) => Poll::Ready(Some(Ok(message))),
333            None => match self.poll_shutdown(cx) {
334                Poll::Ready(Ok(())) => Poll::Ready(None),
335                Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))),
336                Poll::Pending => Poll::Pending,
337            },
338        }
339    }
340}
341
342impl<S, T> Future for Connection<S, T>
343where
344    S: AsyncRead + AsyncWrite + Unpin,
345    T: AsyncRead + AsyncWrite + Unpin,
346{
347    type Output = Result<(), Error>;
348
349    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
350        while let Some(message) = ready!(self.poll_message(cx)?) {
351            if let AsyncMessage::Notice(notice) = message {
352                info!("{}: {}", notice.severity(), notice.message());
353            }
354        }
355        Poll::Ready(Ok(()))
356    }
357}