navree_http/
maintenance.rs1use std::io;
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
6use std::sync::{PoisonError, RwLock};
7#[cfg(test)]
8use std::time::Duration;
9
10use http::StatusCode;
11use http::header::{HeaderValue, RETRY_AFTER};
12use serde::{Deserialize, Serialize};
13use tokio::time::Instant;
14
15use crate::AppError;
16
17#[cfg(test)]
19const CHECK_INTERVAL: Duration = Duration::from_millis(CHECK_INTERVAL_MS);
20const CHECK_INTERVAL_MS: u64 = 1000;
21
22#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
24pub struct MaintenanceInfo {
25 #[serde(default)]
27 pub time: Option<i64>,
28 #[serde(default)]
30 pub retry: Option<u64>,
31 #[serde(default)]
33 pub message: Option<String>,
34}
35
36impl MaintenanceInfo {
37 pub fn error(&self) -> AppError {
39 let detail = self
40 .message
41 .clone()
42 .unwrap_or_else(|| "The application is down for maintenance.".to_owned());
43 let mut error = AppError::new(
44 StatusCode::SERVICE_UNAVAILABLE,
45 crate::codes::MAINTENANCE,
46 "Service Unavailable",
47 )
48 .with_detail(detail);
49 if let Some(retry) = self.retry {
50 error = error.with_header(RETRY_AFTER, HeaderValue::from(retry));
51 }
52 error
53 }
54}
55
56#[derive(Debug)]
63pub struct MaintenanceMode {
64 path: PathBuf,
65 down: AtomicBool,
67 info: RwLock<Option<MaintenanceInfo>>,
69 checked_at: AtomicU64,
72 epoch: Instant,
73}
74
75impl MaintenanceMode {
76 pub(crate) fn new(path: PathBuf) -> Self {
77 Self {
78 path,
79 down: AtomicBool::new(false),
80 info: RwLock::new(None),
81 checked_at: AtomicU64::new(0),
82 epoch: Instant::now(),
83 }
84 }
85
86 pub fn path(&self) -> &Path {
88 &self.path
89 }
90
91 pub async fn current(&self) -> Option<MaintenanceInfo> {
94 if self.claim_refresh() {
95 let info = read_info(&self.path).await;
96 self.set(info);
97 }
98 if !self.down.load(Ordering::Acquire) {
99 return None;
100 }
101 self.info
102 .read()
103 .unwrap_or_else(PoisonError::into_inner)
104 .clone()
105 }
106
107 pub async fn down(&self, info: MaintenanceInfo) -> io::Result<()> {
109 if let Some(dir) = self.path.parent()
110 && !dir.as_os_str().is_empty()
111 {
112 tokio::fs::create_dir_all(dir).await?;
113 }
114 let json = serde_json::to_vec_pretty(&info).map_err(io::Error::other)?;
115 tokio::fs::write(&self.path, json).await?;
116 self.set(Some(info));
117 Ok(())
118 }
119
120 pub async fn up(&self) -> io::Result<()> {
122 match tokio::fs::remove_file(&self.path).await {
123 Ok(()) => {}
124 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
125 Err(error) => return Err(error),
126 }
127 self.set(None);
128 Ok(())
129 }
130
131 fn set(&self, info: Option<MaintenanceInfo>) {
132 let down = info.is_some();
133 *self.info.write().unwrap_or_else(PoisonError::into_inner) = info;
134 self.down.store(down, Ordering::Release);
135 self.checked_at.store(self.now(), Ordering::Release);
136 }
137
138 fn claim_refresh(&self) -> bool {
140 let now = self.now();
141 let at = self.checked_at.load(Ordering::Acquire);
142 if at != 0 && now.saturating_sub(at) < CHECK_INTERVAL_MS {
143 return false;
144 }
145 self.checked_at
146 .compare_exchange(at, now, Ordering::AcqRel, Ordering::Relaxed)
147 .is_ok()
148 }
149
150 fn now(&self) -> u64 {
152 let elapsed = Instant::now().duration_since(self.epoch).as_millis();
153 u64::try_from(elapsed).unwrap_or(u64::MAX - 1) + 1
154 }
155}
156
157async fn read_info(path: &Path) -> Option<MaintenanceInfo> {
160 match tokio::fs::read(path).await {
161 Ok(bytes) => Some(serde_json::from_slice(&bytes).unwrap_or_default()),
162 Err(error) if error.kind() == io::ErrorKind::NotFound => None,
163 Err(error) => {
164 tracing::warn!(target: "navree::http", path = %path.display(), %error, "cannot read the maintenance file; treating the app as down");
165 Some(MaintenanceInfo::default())
166 }
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[tokio::test]
175 async fn down_and_up_toggle_the_file_and_the_state() {
176 let dir = tempfile::Builder::new()
177 .prefix("navree-test-")
178 .tempdir()
179 .unwrap();
180 let mode = MaintenanceMode::new(dir.path().join("framework").join("down"));
181 assert_eq!(mode.current().await, None);
182
183 let info = MaintenanceInfo {
184 time: Some(1),
185 retry: Some(60),
186 message: Some("Upgrading".into()),
187 };
188 mode.down(info.clone()).await.unwrap();
189 assert!(mode.path().exists());
190 assert_eq!(mode.current().await, Some(info));
191
192 mode.up().await.unwrap();
193 assert!(!mode.path().exists());
194 assert_eq!(mode.current().await, None);
195 mode.up().await.unwrap();
196 }
197
198 #[tokio::test]
199 async fn a_file_removed_by_another_process_is_noticed_within_a_second() {
200 let dir = tempfile::Builder::new()
201 .prefix("navree-test-")
202 .tempdir()
203 .unwrap();
204 let path = dir.path().join("down");
205 std::fs::write(&path, r#"{"retry": 5}"#).unwrap();
206 let mode = MaintenanceMode::new(path.clone());
207 assert_eq!(mode.current().await.and_then(|info| info.retry), Some(5));
208
209 std::fs::remove_file(&path).unwrap();
210 assert!(
211 mode.current().await.is_some(),
212 "the last check is reused for up to a second"
213 );
214 tokio::time::sleep(CHECK_INTERVAL + Duration::from_millis(100)).await;
215 assert_eq!(mode.current().await, None);
216 }
217
218 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
221 async fn concurrent_requests_agree_on_the_state() {
222 let dir = tempfile::Builder::new()
223 .prefix("navree-test-")
224 .tempdir()
225 .unwrap();
226 let mode = std::sync::Arc::new(MaintenanceMode::new(dir.path().join("down")));
227 let readers = |mode: &std::sync::Arc<MaintenanceMode>| {
228 (0..64)
229 .map(|_| {
230 let mode = mode.clone();
231 tokio::spawn(async move { mode.current().await })
232 })
233 .collect::<Vec<_>>()
234 };
235 for reader in readers(&mode) {
236 assert_eq!(reader.await.unwrap(), None);
237 }
238 let info = MaintenanceInfo {
239 message: Some("Upgrading".into()),
240 ..MaintenanceInfo::default()
241 };
242 mode.down(info.clone()).await.unwrap();
243 for reader in readers(&mode) {
244 assert_eq!(reader.await.unwrap(), Some(info.clone()));
245 }
246 mode.up().await.unwrap();
247 for reader in readers(&mode) {
248 assert_eq!(reader.await.unwrap(), None);
249 }
250 }
251
252 #[tokio::test]
253 async fn a_file_written_by_another_process_is_noticed() {
254 let dir = tempfile::Builder::new()
255 .prefix("navree-test-")
256 .tempdir()
257 .unwrap();
258 let path = dir.path().join("down");
259 std::fs::write(&path, "not json").unwrap();
260 let mode = MaintenanceMode::new(path);
261 let info = mode.current().await.expect("down");
262 assert_eq!(info, MaintenanceInfo::default());
263 assert_eq!(info.error().status, StatusCode::SERVICE_UNAVAILABLE);
264 }
265}