Line data Source code
1 : use std::net::IpAddr;
2 :
3 : use postgres_protocol2::message::backend::Message;
4 : use tokio::net::TcpStream;
5 : use tokio::sync::mpsc;
6 :
7 : use crate::client::SocketConfig;
8 : use crate::codec::BackendMessage;
9 : use crate::config::Host;
10 : use crate::connect_raw::connect_raw;
11 : use crate::connect_socket::connect_socket;
12 : use crate::connect_tls::connect_tls;
13 : use crate::tls::{MakeTlsConnect, TlsConnect};
14 : use crate::{Client, Config, Connection, Error, RawConnection};
15 :
16 0 : pub async fn connect<T>(
17 0 : tls: &T,
18 0 : config: &Config,
19 0 : ) -> Result<(Client, Connection<TcpStream, T::Stream>), Error>
20 0 : where
21 0 : T: MakeTlsConnect<TcpStream>,
22 0 : {
23 0 : let hostname = match &config.host {
24 0 : Host::Tcp(host) => host.as_str(),
25 : };
26 :
27 0 : let tls = tls
28 0 : .make_tls_connect(hostname)
29 0 : .map_err(|e| Error::tls(e.into()))?;
30 :
31 0 : match connect_once(config.host_addr, &config.host, config.port, tls, config).await {
32 0 : Ok((client, connection)) => Ok((client, connection)),
33 0 : Err(e) => Err(e),
34 : }
35 0 : }
36 :
37 0 : async fn connect_once<T>(
38 0 : host_addr: Option<IpAddr>,
39 0 : host: &Host,
40 0 : port: u16,
41 0 : tls: T,
42 0 : config: &Config,
43 0 : ) -> Result<(Client, Connection<TcpStream, T::Stream>), Error>
44 0 : where
45 0 : T: TlsConnect<TcpStream>,
46 0 : {
47 0 : let socket = connect_socket(host_addr, host, port, config.connect_timeout).await?;
48 0 : let stream = connect_tls(socket, config.ssl_mode, tls).await?;
49 : let RawConnection {
50 0 : stream,
51 0 : parameters,
52 0 : delayed_notice,
53 0 : process_id,
54 0 : secret_key,
55 0 : } = connect_raw(stream, config).await?;
56 :
57 0 : let socket_config = SocketConfig {
58 0 : host_addr,
59 0 : host: host.clone(),
60 0 : port,
61 0 : connect_timeout: config.connect_timeout,
62 0 : };
63 :
64 0 : let (client_tx, conn_rx) = mpsc::unbounded_channel();
65 0 : let (conn_tx, client_rx) = mpsc::channel(4);
66 0 : let client = Client::new(
67 0 : client_tx,
68 0 : client_rx,
69 0 : socket_config,
70 0 : config.ssl_mode,
71 0 : process_id,
72 0 : secret_key,
73 : );
74 :
75 : // delayed notices are always sent as "Async" messages.
76 0 : let delayed = delayed_notice
77 0 : .into_iter()
78 0 : .map(|m| BackendMessage::Async(Message::NoticeResponse(m)))
79 0 : .collect();
80 :
81 0 : let connection = Connection::new(stream, delayed, parameters, conn_tx, conn_rx);
82 :
83 0 : Ok((client, connection))
84 0 : }
|