xitca_postgres/
driver.rs

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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
//! client driver module.

pub(crate) mod codec;
pub(crate) mod generic;

mod connect;

pub(crate) use generic::DriverTx;

#[cfg(feature = "tls")]
mod tls;

#[cfg(feature = "quic")]
pub(crate) mod quic;

use core::{
    future::{Future, IntoFuture},
    net::SocketAddr,
    pin::Pin,
};

use std::io;

use postgres_protocol::message::{backend, frontend};
use xitca_io::{
    bytes::{Buf, BytesMut},
    io::{AsyncIo, AsyncIoDyn, Interest},
    net::TcpStream,
};

use super::{
    client::Client,
    config::{Config, SslMode, SslNegotiation},
    error::{unexpected_eof_err, ConfigError, Error},
    iter::AsyncLendingIterator,
    session::{ConnectInfo, Session},
};

use self::generic::GenericDriver;

#[cfg(feature = "tls")]
use xitca_tls::rustls::{ClientConnection, TlsStream};

#[cfg(unix)]
use xitca_io::net::UnixStream;

pub(super) async fn connect(cfg: &mut Config) -> Result<(Client, Driver), Error> {
    if cfg.get_hosts().is_empty() {
        return Err(ConfigError::EmptyHost.into());
    }

    if cfg.get_ports().is_empty() {
        return Err(ConfigError::EmptyPort.into());
    }

    let mut err = None;
    let hosts = cfg.get_hosts().to_vec();
    for host in hosts {
        match self::connect::connect_host(host, cfg).await {
            Ok((tx, session, drv)) => return Ok((Client::new(tx, session), drv)),
            Err(e) => err = Some(e),
        }
    }

    Err(err.unwrap())
}

pub(super) async fn connect_io<Io>(io: Io, cfg: &mut Config) -> Result<(Client, Driver), Error>
where
    Io: AsyncIo + Send + 'static,
{
    let (tx, session, drv) = prepare_driver(ConnectInfo::default(), Box::new(io) as _, cfg).await?;
    Ok((Client::new(tx, session), Driver::Dynamic(drv)))
}

pub(super) async fn connect_info(info: ConnectInfo) -> Result<(DriverTx, Driver), Error> {
    self::connect::connect_info(info).await
}

async fn prepare_driver<Io>(
    info: ConnectInfo,
    io: Io,
    cfg: &mut Config,
) -> Result<(DriverTx, Session, GenericDriver<Io>), Error>
where
    Io: AsyncIo + Send + 'static,
{
    let (mut drv, tx) = GenericDriver::new(io);
    let session = Session::prepare_session(info, &mut drv, cfg).await?;
    Ok((tx, session, drv))
}

async fn should_connect_tls<Io>(io: &mut Io, ssl_mode: SslMode, ssl_negotiation: SslNegotiation) -> Result<bool, Error>
where
    Io: AsyncIo,
{
    async fn query_tls_availability<Io>(io: &mut Io) -> std::io::Result<bool>
    where
        Io: AsyncIo,
    {
        let mut buf = BytesMut::new();
        frontend::ssl_request(&mut buf);

        while !buf.is_empty() {
            match io.write(&buf) {
                Ok(0) => return Err(unexpected_eof_err()),
                Ok(n) => buf.advance(n),
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    io.ready(Interest::WRITABLE).await?;
                }
                Err(e) => return Err(e),
            }
        }

        let mut buf = [0];
        loop {
            match io.read(&mut buf) {
                Ok(0) => return Err(unexpected_eof_err()),
                Ok(_) => return Ok(buf[0] == b'S'),
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    io.ready(Interest::READABLE).await?;
                }
                Err(e) => return Err(e),
            }
        }
    }

    match ssl_mode {
        SslMode::Disable => Ok(false),
        _ if matches!(ssl_negotiation, SslNegotiation::Direct) => Ok(true),
        mode => match (query_tls_availability(io).await?, mode) {
            (false, SslMode::Require) => Err(Error::todo()),
            (bool, _) => Ok(bool),
        },
    }
}

async fn dns_resolve<'p>(host: &'p str, ports: &'p [u16]) -> Result<impl Iterator<Item = SocketAddr> + 'p, Error> {
    let addrs = tokio::net::lookup_host((host, 0)).await?.flat_map(|mut addr| {
        ports.iter().map(move |port| {
            addr.set_port(*port);
            addr
        })
    });
    Ok(addrs)
}

/// async driver of [`Client`]
///
/// it handles IO and emit server sent message that do not belong to any query with [`AsyncLendingIterator`]
/// trait impl.
///
/// # Examples
/// ```
/// use std::future::IntoFuture;
/// use xitca_postgres::{iter::AsyncLendingIterator, Driver};
///
/// // drive the client and listen to server notify at the same time.
/// fn drive_with_server_notify(mut drv: Driver) {
///     tokio::spawn(async move {
///         while let Ok(Some(msg)) = drv.try_next().await {
///             // *Note:
///             // handle message must be non-blocking to prevent starvation of driver.
///         }
///     });
/// }
///
/// // drive client without handling notify.
/// fn drive_only(drv: Driver) {
///     tokio::spawn(drv.into_future());
/// }
/// ```
///
/// # Lifetime
/// Driver and [`Client`] have a dependent lifetime where either side can trigger the other part to shutdown.
/// From Driver side it's in the form of dropping ownership.
/// ## Examples
/// ```
/// # use xitca_postgres::{error::Error, Config, Execute, Postgres};
/// # async fn shut_down(cfg: Config) -> Result<(), Error> {
/// // connect to a database
/// let (cli, drv) = Postgres::new(cfg).connect().await?;
///
/// // drop driver
/// drop(drv);
///
/// // client will always return error when it's driver is gone.
/// let e = "SELECT 1".query(&cli).await.unwrap_err();
/// // a shortcut method can be used to determine if the error is caused by a shutdown driver.
/// assert!(e.is_driver_down());
///
/// # Ok(())
/// # }
/// ```
///
// TODO: use Box<dyn AsyncIterator> when life time GAT is object safe.
pub enum Driver {
    Tcp(GenericDriver<TcpStream>),
    Dynamic(GenericDriver<Box<dyn AsyncIoDyn + Send>>),
    #[cfg(feature = "tls")]
    Tls(GenericDriver<TlsStream<ClientConnection, TcpStream>>),
    #[cfg(unix)]
    Unix(GenericDriver<UnixStream>),
    #[cfg(all(unix, feature = "tls"))]
    UnixTls(GenericDriver<TlsStream<ClientConnection, UnixStream>>),
    #[cfg(feature = "quic")]
    Quic(GenericDriver<crate::driver::quic::QuicStream>),
}

impl Driver {
    #[inline]
    pub(crate) async fn send(&mut self, buf: BytesMut) -> Result<(), Error> {
        match self {
            Self::Tcp(ref mut drv) => drv.send(buf).await,
            Self::Dynamic(ref mut drv) => drv.send(buf).await,
            #[cfg(feature = "tls")]
            Self::Tls(ref mut drv) => drv.send(buf).await,
            #[cfg(unix)]
            Self::Unix(ref mut drv) => drv.send(buf).await,
            #[cfg(all(unix, feature = "tls"))]
            Self::UnixTls(ref mut drv) => drv.send(buf).await,
            #[cfg(feature = "quic")]
            Self::Quic(ref mut drv) => drv.send(buf).await,
        }
    }
}

impl AsyncLendingIterator for Driver {
    type Ok<'i>
        = backend::Message
    where
        Self: 'i;
    type Err = Error;

    #[inline]
    async fn try_next(&mut self) -> Result<Option<Self::Ok<'_>>, Self::Err> {
        match self {
            Self::Tcp(ref mut drv) => drv.try_next().await,
            Self::Dynamic(ref mut drv) => drv.try_next().await,
            #[cfg(feature = "tls")]
            Self::Tls(ref mut drv) => drv.try_next().await,
            #[cfg(unix)]
            Self::Unix(ref mut drv) => drv.try_next().await,
            #[cfg(all(unix, feature = "tls"))]
            Self::UnixTls(ref mut drv) => drv.try_next().await,
            #[cfg(feature = "quic")]
            Self::Quic(ref mut drv) => drv.try_next().await,
        }
    }
}

impl IntoFuture for Driver {
    type Output = Result<(), Error>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;

    fn into_future(mut self) -> Self::IntoFuture {
        Box::pin(async move {
            while self.try_next().await?.is_some() {}
            Ok(())
        })
    }
}