Skip to main content

kernable_core/
transport.rs

1//! Client channels to a kernel at `http://host:port` (or `host:port`), optionally with mutual
2//! TLS, or, on Unix, at `unix:/path`.
3
4use std::path::PathBuf;
5
6use hyper_util::rt::TokioIo;
7use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Error, Identity, Uri};
8use tower::service_fn;
9
10/// PEM files for mutual TLS: the CA that signed the kernel's certificate, and this
11/// process's own certificate and key.
12#[derive(Debug, Clone)]
13pub struct Tls {
14    pub ca: PathBuf,
15    pub cert: PathBuf,
16    pub key: PathBuf,
17}
18
19/// Connects to a kernel at `host:port` over mutual TLS.
20pub async fn connect_tls(
21    addr: &str,
22    tls: &Tls,
23) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
24    connect_tls_pinging(addr, tls, None).await
25}
26
27/// Pings on the connection every `every`, also when idle, and ends it when a ping is not
28/// answered within as long: a peer the network dropped without a word (a partition) shows
29/// within twice `every`, not after TCP's minutes.
30fn pinging(endpoint: Endpoint, every: Option<std::time::Duration>) -> Endpoint {
31    match every {
32        Some(every) => endpoint
33            .http2_keep_alive_interval(every)
34            .keep_alive_timeout(every)
35            .keep_alive_while_idle(true)
36            .connect_timeout(every.max(std::time::Duration::from_secs(1)) * 2),
37        None => endpoint,
38    }
39}
40
41/// Like [`connect_tls`], pinging every `every` (see [`connect_pinging`]).
42pub async fn connect_tls_pinging(
43    addr: &str,
44    tls: &Tls,
45    every: Option<std::time::Duration>,
46) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
47    let config = ClientTlsConfig::new()
48        .ca_certificate(Certificate::from_pem(std::fs::read(&tls.ca)?))
49        .identity(Identity::from_pem(
50            std::fs::read(&tls.cert)?,
51            std::fs::read(&tls.key)?,
52        ));
53    Ok(pinging(
54        Endpoint::from_shared(format!("https://{}", tcp_addr(addr)))?.tls_config(config)?,
55        every,
56    )
57    .connect()
58    .await?)
59}
60
61/// Connects over TLS to `https://host:port`: the server's certificate checked against the public
62/// CAs (Mozilla's, built in) and `ca` if given, this process's certificate shown only if given.
63/// For a server that knows its clients by their keys, not by certificates (a relay).
64pub async fn connect_https_pinging(
65    addr: &str,
66    ca: Option<&std::path::Path>,
67    identity: Option<(&std::path::Path, &std::path::Path)>,
68    every: Option<std::time::Duration>,
69) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
70    let mut config = ClientTlsConfig::new().with_webpki_roots();
71    if let Some(ca) = ca {
72        config = config.ca_certificate(Certificate::from_pem(std::fs::read(ca)?));
73    }
74    if let Some((cert, key)) = identity {
75        config = config.identity(Identity::from_pem(
76            std::fs::read(cert)?,
77            std::fs::read(key)?,
78        ));
79    }
80    Ok(pinging(
81        Endpoint::from_shared(format!("https://{}", tcp_addr(addr)))?.tls_config(config)?,
82        every,
83    )
84    .connect()
85    .await?)
86}
87
88pub async fn connect(addr: &str) -> Result<Channel, Error> {
89    connect_pinging(addr, None).await
90}
91
92/// Like [`connect`]; with `every`, the connection is pinged that often and ends when a ping is
93/// not answered within as long: a standby notices a primary the network cut off.
94pub async fn connect_pinging(
95    addr: &str,
96    every: Option<std::time::Duration>,
97) -> Result<Channel, Error> {
98    match unix_path(addr) {
99        #[cfg(unix)]
100        Some(path) => {
101            let path = path.to_owned();
102            // The URI is ignored by the connector but must be valid.
103            pinging(Endpoint::from_static("http://kernable"), every)
104                .connect_with_connector(service_fn(move |_: Uri| {
105                    let path = path.clone();
106                    async move {
107                        let stream = tokio::net::UnixStream::connect(path).await?;
108                        Ok::<_, std::io::Error>(TokioIo::new(stream))
109                    }
110                }))
111                .await
112        }
113        // Unix sockets exist on Unix only; the invalid URI says so in the error.
114        #[cfg(not(unix))]
115        Some(_) => {
116            Endpoint::from_shared("unix sockets need Unix")?
117                .connect()
118                .await
119        }
120        None => {
121            pinging(
122                Endpoint::from_shared(format!("http://{}", tcp_addr(addr)))?,
123                every,
124            )
125            .connect()
126            .await
127        }
128    }
129}
130
131/// How often a client of several kernels (a pair) pings each connection, and how long it
132/// waits for the answer: one the network cut off without a word ends within twice this, and the
133/// client turns to the other kernel (a single kernel's client has nowhere else to go, and pings
134/// every 30 s).
135pub const PAIR_PING: std::time::Duration = std::time::Duration::from_secs(2);
136
137/// Pings on the connection, also when idle, so one the network dropped without a word (a dead
138/// host, a NAT that forgot it) ends within 40 s, or within twice [`PAIR_PING`] for a client of
139/// `several` kernels; and a bound on connecting.
140fn sdk_endpoint(endpoint: Endpoint, several: bool) -> Endpoint {
141    let (every, answer, connect) = if several {
142        (PAIR_PING, PAIR_PING, PAIR_PING * 2)
143    } else {
144        (
145            std::time::Duration::from_secs(30),
146            std::time::Duration::from_secs(10),
147            std::time::Duration::from_secs(10),
148        )
149    };
150    endpoint
151        .http2_keep_alive_interval(every)
152        .keep_alive_timeout(answer)
153        .keep_alive_while_idle(true)
154        .connect_timeout(connect)
155}
156
157/// A channel to a kernel that connects on first use and again after the connection drops, so
158/// a process can start before the kernel and survive its restarts (SDK clients). With `tls`,
159/// `addr` is `host:port` over mutual TLS. Needs a tokio runtime.
160pub fn connect_lazy(
161    addr: &str,
162    tls: Option<&Tls>,
163) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
164    connect_lazy_among(addr, tls, false)
165}
166
167/// [`connect_lazy`] for a client of `several` kernels (a pair, a partition's kernels): a
168/// connection the network cut off ends within seconds, so the client turns to another.
169pub fn connect_lazy_among(
170    addr: &str,
171    tls: Option<&Tls>,
172    several: bool,
173) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
174    if let Some(tls) = tls {
175        let config = ClientTlsConfig::new()
176            .ca_certificate(Certificate::from_pem(std::fs::read(&tls.ca)?))
177            .identity(Identity::from_pem(
178                std::fs::read(&tls.cert)?,
179                std::fs::read(&tls.key)?,
180            ));
181        return Ok(sdk_endpoint(
182            Endpoint::from_shared(format!("https://{}", tcp_addr(addr)))?,
183            several,
184        )
185        .tls_config(config)?
186        .connect_lazy());
187    }
188    match unix_path(addr) {
189        #[cfg(unix)]
190        Some(path) => {
191            let path = path.to_owned();
192            Ok(
193                sdk_endpoint(Endpoint::from_static("http://kernable"), several)
194                    .connect_with_connector_lazy(service_fn(move |_: Uri| {
195                        let path = path.clone();
196                        async move {
197                            let stream = tokio::net::UnixStream::connect(path).await?;
198                            Ok::<_, std::io::Error>(TokioIo::new(stream))
199                        }
200                    })),
201            )
202        }
203        #[cfg(not(unix))]
204        Some(_) => Err("unix sockets need Unix".into()),
205        None => Ok(sdk_endpoint(
206            Endpoint::from_shared(format!("http://{}", tcp_addr(addr)))?,
207            several,
208        )
209        .connect_lazy()),
210    }
211}
212
213/// `http://host:port` and `https://host:port` both mean `host:port`.
214pub fn tcp_addr(addr: &str) -> &str {
215    let addr = addr
216        .strip_prefix("http://")
217        .or_else(|| addr.strip_prefix("https://"))
218        .unwrap_or(addr);
219    addr.strip_suffix('/').unwrap_or(addr)
220}
221
222/// `unix:/tmp/k.sock` and `unix:///tmp/k.sock` both mean `/tmp/k.sock`.
223pub fn unix_path(addr: &str) -> Option<&str> {
224    addr.strip_prefix("unix:")
225        .map(|p| p.strip_prefix("//").unwrap_or(p))
226}