grpc/
client_stub.rs

1use crate::client::Client;
2use crate::client::ClientBuilder;
3use crate::ClientConf;
4use crate::Result as grpc_Result;
5use std::sync::Arc;
6
7/// Trait implemented by `XxxClient` structs for `Xxx` trait.
8pub trait ClientStub: Sized {
9    /// Create a client stub using given `Client` object.
10    fn with_client(grpc_client: Arc<Client>) -> Self;
11}
12
13/// Utilities to work with generated code clients.
14pub trait ClientStubExt: Sized {
15    /// Create a plain (non-encrypted) client connected to specified host and port
16    fn new_plain(host: &str, port: u16, conf: ClientConf) -> crate::Result<Self>;
17
18    /// Create a client connected to specified host and port using TLS.
19    fn new_tls<C: ::tls_api::TlsConnector>(
20        host: &str,
21        port: u16,
22        conf: ClientConf,
23    ) -> grpc_Result<Self>;
24
25    /// Create a client connected to specified unix socket.
26    fn new_plain_unix(addr: &str, conf: ClientConf) -> grpc_Result<Self>;
27}
28
29impl<C: ClientStub> ClientStubExt for C {
30    fn new_plain(host: &str, port: u16, conf: ClientConf) -> grpc_Result<Self> {
31        ClientBuilder::new(host, port)
32            .conf(conf)
33            .build()
34            .map(|c| Self::with_client(Arc::new(c)))
35    }
36
37    fn new_tls<T: ::tls_api::TlsConnector>(
38        host: &str,
39        port: u16,
40        conf: ClientConf,
41    ) -> grpc_Result<Self> {
42        ClientBuilder::new(host, port)
43            .tls::<T>()
44            .conf(conf)
45            .build()
46            .map(|c| Self::with_client(Arc::new(c)))
47    }
48
49    #[cfg(unix)]
50    fn new_plain_unix(addr: &str, conf: ClientConf) -> grpc_Result<Self> {
51        ClientBuilder::new_unix(addr)
52            .conf(conf)
53            .build()
54            .map(|c| Self::with_client(Arc::new(c)))
55    }
56
57    #[cfg(not(unix))]
58    fn new_plain_unix(addr: &str, conf: ClientConf) -> grpc_Result<Self> {
59        Err(crate::Error::Other("new_plain_unix unsupported"))
60    }
61}