1use std::sync::{Arc, PoisonError, RwLock};
9use std::time::Duration;
10
11use rustls::{ClientConfig, ServerConfig};
12
13use crate::material::{Configs, Contents, TlsError, TlsFiles, build};
14
15#[cfg(test)]
16mod tests;
17
18#[derive(Debug, Clone)]
20pub struct Tls {
21 inner: Arc<Inner>,
22 handshake_timeout: Duration,
23 handshakes_at_once: usize,
24}
25
26#[derive(Debug)]
27struct Inner {
28 files: TlsFiles,
29 worker_name: String,
30 ui_name: String,
31 state: RwLock<State>,
32}
33
34#[derive(Debug)]
35struct State {
36 contents: Contents,
37 configs: Configs,
38 generation: u64,
39 failed: Option<String>,
41}
42
43#[derive(Debug)]
45pub enum Reload {
46 Unchanged,
48 Reloaded,
50 Failed(TlsError),
52}
53
54impl Tls {
55 pub fn load(files: TlsFiles, worker_name: &str, ui_name: &str) -> Result<Self, TlsError> {
62 let contents = files.read()?;
63 let configs = build(&contents, &files, (worker_name, ui_name))?;
64 Ok(Self {
65 inner: Arc::new(Inner {
66 files,
67 worker_name: worker_name.to_owned(),
68 ui_name: ui_name.to_owned(),
69 state: RwLock::new(State {
70 contents,
71 configs,
72 generation: 0,
73 failed: None,
74 }),
75 }),
76 handshake_timeout: crate::incoming::HANDSHAKE_TIMEOUT,
77 handshakes_at_once: crate::incoming::MAX_HANDSHAKES,
78 })
79 }
80
81 #[must_use]
83 pub fn with_handshake_timeout(self, timeout: Duration) -> Self {
84 Self {
85 handshake_timeout: timeout,
86 ..self
87 }
88 }
89
90 #[must_use]
92 pub const fn handshake_timeout(&self) -> Duration {
93 self.handshake_timeout
94 }
95
96 #[must_use]
98 pub fn with_handshakes_at_once(self, most: usize) -> Self {
99 Self {
100 handshakes_at_once: most.max(1),
101 ..self
102 }
103 }
104
105 #[must_use]
107 pub const fn handshakes_at_once(&self) -> usize {
108 self.handshakes_at_once
109 }
110
111 fn configs(&self) -> Configs {
112 self.inner
113 .state
114 .read()
115 .unwrap_or_else(PoisonError::into_inner)
116 .configs
117 .clone()
118 }
119
120 #[must_use]
122 pub fn grpc_server(&self) -> Arc<ServerConfig> {
123 self.configs().grpc_server
124 }
125
126 #[must_use]
128 pub fn http_server(&self) -> Arc<ServerConfig> {
129 self.configs().http_server
130 }
131
132 #[must_use]
134 pub fn grpc_client(&self) -> Arc<ClientConfig> {
135 self.configs().grpc_client
136 }
137
138 #[must_use]
140 pub fn worker_client(&self) -> Arc<ClientConfig> {
141 self.configs().worker_client
142 }
143
144 #[must_use]
146 pub fn ui_server(&self) -> Arc<ServerConfig> {
147 self.configs().ui_server
148 }
149
150 #[must_use]
152 pub fn api_client(&self) -> Arc<ClientConfig> {
153 self.configs().api_client
154 }
155
156 #[must_use]
158 pub fn generation(&self) -> u64 {
159 self.inner
160 .state
161 .read()
162 .unwrap_or_else(PoisonError::into_inner)
163 .generation
164 }
165
166 pub fn reload(&self) -> Reload {
168 let read = self.inner.files.read();
169 let mut state = self
170 .inner
171 .state
172 .write()
173 .unwrap_or_else(PoisonError::into_inner);
174 let built = read.and_then(|contents| {
175 if contents == state.contents {
176 return Ok(None);
177 }
178 let names = (self.inner.worker_name.as_str(), self.inner.ui_name.as_str());
179 let configs = build(&contents, &self.inner.files, names)?;
180 Ok(Some((contents, configs)))
181 });
182 match built {
183 Ok(None) => {
184 state.failed = None;
185 Reload::Unchanged
186 }
187 Ok(Some((contents, configs))) => {
188 state.contents = contents;
189 state.configs = configs;
190 state.generation += 1;
191 state.failed = None;
192 Reload::Reloaded
193 }
194 Err(error) => {
195 let text = error.to_string();
196 if state.failed.as_ref() == Some(&text) {
197 return Reload::Unchanged;
198 }
199 state.failed = Some(text);
200 Reload::Failed(error)
201 }
202 }
203 }
204
205 pub async fn watch(self, interval: Duration, stop: impl Future<Output = ()>) {
207 tokio::pin!(stop);
208 let mut tick = tokio::time::interval(interval);
209 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
210 tick.tick().await;
211 loop {
212 tokio::select! {
213 () = &mut stop => return,
214 _ = tick.tick() => match self.reload() {
215 Reload::Unchanged => {}
216 Reload::Reloaded => tracing::info!(
217 cert = %self.inner.files.cert.display(),
218 "TLS certificates changed: new connections use them"
219 ),
220 Reload::Failed(error) => tracing::error!(
221 %error,
222 "TLS certificates changed but can't be used; keeping the previous ones"
223 ),
224 },
225 }
226 }
227 }
228}