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