@@ -11,6 +11,7 @@ use regex::Regex;
1111use tonic:: transport:: Certificate ;
1212use tonic:: transport:: Channel ;
1313use tonic:: transport:: ClientTlsConfig ;
14+ use tonic:: transport:: Endpoint ;
1415use tonic:: transport:: Identity ;
1516
1617use crate :: internal_err;
@@ -77,28 +78,42 @@ impl SecurityManager {
7778 where
7879 Factory : FnOnce ( Channel ) -> Client ,
7980 {
80- let addr = "http://" . to_string ( ) + & SCHEME_REG . replace ( addr, "" ) ;
81-
8281 info ! ( "connect to rpc server at endpoint: {:?}" , addr) ;
8382
84- let mut builder = Channel :: from_shared ( addr) ?
85- . tcp_keepalive ( Some ( Duration :: from_secs ( 10 ) ) )
86- . keep_alive_timeout ( Duration :: from_secs ( 3 ) ) ;
87-
88- if !self . ca . is_empty ( ) {
89- let tls = ClientTlsConfig :: new ( )
90- . ca_certificate ( Certificate :: from_pem ( & self . ca ) )
91- . identity ( Identity :: from_pem (
92- & self . cert ,
93- load_pem_file ( "private key" , & self . key ) ?,
94- ) ) ;
95- builder = builder. tls_config ( tls) ?;
83+ let channel = if !self . ca . is_empty ( ) {
84+ self . tls_channel ( addr) . await ?
85+ } else {
86+ self . default_channel ( addr) . await ?
9687 } ;
97-
98- let ch = builder. connect ( ) . await ?;
88+ let ch = channel. connect ( ) . await ?;
9989
10090 Ok ( factory ( ch) )
10191 }
92+
93+ async fn tls_channel ( & self , addr : & str ) -> Result < Endpoint > {
94+ let addr = "https://" . to_string ( ) + & SCHEME_REG . replace ( addr, "" ) ;
95+ let builder = self . endpoint ( addr. to_string ( ) ) ?;
96+ let tls = ClientTlsConfig :: new ( )
97+ . ca_certificate ( Certificate :: from_pem ( & self . ca ) )
98+ . identity ( Identity :: from_pem (
99+ & self . cert ,
100+ load_pem_file ( "private key" , & self . key ) ?,
101+ ) ) ;
102+ let builder = builder. tls_config ( tls) ?;
103+ Ok ( builder)
104+ }
105+
106+ async fn default_channel ( & self , addr : & str ) -> Result < Endpoint > {
107+ let addr = "http://" . to_string ( ) + & SCHEME_REG . replace ( addr, "" ) ;
108+ self . endpoint ( addr)
109+ }
110+
111+ fn endpoint ( & self , addr : String ) -> Result < Endpoint > {
112+ let endpoint = Channel :: from_shared ( addr) ?
113+ . tcp_keepalive ( Some ( Duration :: from_secs ( 10 ) ) )
114+ . keep_alive_timeout ( Duration :: from_secs ( 3 ) ) ;
115+ Ok ( endpoint)
116+ }
102117}
103118
104119#[ cfg( test) ]
0 commit comments