autoeq_measurements/read/read_api/
backend.rs1use async_trait::async_trait;
15use std::collections::HashMap;
16use std::path::{Path, PathBuf};
17use std::sync::{Arc, Mutex};
18
19pub type BackendResult<T> = Result<T, Box<dyn std::error::Error>>;
21
22#[async_trait]
24pub trait MeasurementBackend: Send + Sync {
25 async fn get_text(&self, url: &str) -> BackendResult<String>;
27}
28
29#[async_trait]
31pub trait MeasurementCache: Send + Sync {
32 async fn read_to_string(&self, path: &Path) -> BackendResult<Option<String>>;
34
35 async fn write(&self, path: &Path, content: &str) -> BackendResult<()>;
37
38 async fn create_dir_all(&self, path: &Path) -> BackendResult<()>;
40}
41
42#[derive(Debug, Default, Clone, Copy)]
44pub struct ReqwestMeasurementBackend;
45
46impl ReqwestMeasurementBackend {
47 pub fn new() -> Self {
49 Self
50 }
51}
52
53#[async_trait]
54impl MeasurementBackend for ReqwestMeasurementBackend {
55 async fn get_text(&self, url: &str) -> BackendResult<String> {
56 let response = reqwest::get(url).await?;
57 if !response.status().is_success() {
58 return Err(format!("API request failed with status: {}", response.status()).into());
59 }
60 Ok(response.text().await?)
61 }
62}
63
64#[derive(Debug, Default, Clone, Copy)]
66pub struct FsMeasurementCache;
67
68impl FsMeasurementCache {
69 pub fn new() -> Self {
71 Self
72 }
73}
74
75#[async_trait]
76impl MeasurementCache for FsMeasurementCache {
77 async fn read_to_string(&self, path: &Path) -> BackendResult<Option<String>> {
78 match tokio::fs::read_to_string(path).await {
79 Ok(v) => Ok(Some(v)),
80 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
81 Err(e) => Err(e.into()),
82 }
83 }
84
85 async fn write(&self, path: &Path, content: &str) -> BackendResult<()> {
86 tokio::fs::write(path, content).await?;
87 Ok(())
88 }
89
90 async fn create_dir_all(&self, path: &Path) -> BackendResult<()> {
91 tokio::fs::create_dir_all(path).await?;
92 Ok(())
93 }
94}
95
96#[derive(Debug, Default, Clone)]
98pub struct InMemoryMeasurementCache {
99 files: Arc<Mutex<HashMap<PathBuf, String>>>,
100 dirs: Arc<Mutex<Vec<PathBuf>>>,
101}
102
103impl InMemoryMeasurementCache {
104 pub fn new() -> Self {
106 Self::default()
107 }
108
109 pub fn insert(&self, path: impl Into<PathBuf>, content: impl Into<String>) {
111 self.files
112 .lock()
113 .unwrap()
114 .insert(path.into(), content.into());
115 }
116
117 pub fn get(&self, path: &Path) -> Option<String> {
119 self.files.lock().unwrap().get(path).cloned()
120 }
121
122 pub fn is_dir(&self, path: &Path) -> bool {
124 self.dirs.lock().unwrap().contains(&path.to_path_buf())
125 }
126}
127
128#[async_trait]
129impl MeasurementCache for InMemoryMeasurementCache {
130 async fn read_to_string(&self, path: &Path) -> BackendResult<Option<String>> {
131 Ok(self.files.lock().unwrap().get(path).cloned())
132 }
133
134 async fn write(&self, path: &Path, content: &str) -> BackendResult<()> {
135 self.files
136 .lock()
137 .unwrap()
138 .insert(path.to_path_buf(), content.to_string());
139 Ok(())
140 }
141
142 async fn create_dir_all(&self, path: &Path) -> BackendResult<()> {
143 let mut dirs = self.dirs.lock().unwrap();
144 let mut current = Some(path);
145 while let Some(p) = current {
146 let owned = p.to_path_buf();
147 if !dirs.contains(&owned) {
148 dirs.push(owned);
149 }
150 current = p.parent();
151 }
152 Ok(())
153 }
154}
155
156#[derive(Debug, Default, Clone)]
158pub struct MockMeasurementBackend {
159 response: String,
160}
161
162impl MockMeasurementBackend {
163 pub fn new(response: impl Into<String>) -> Self {
165 Self {
166 response: response.into(),
167 }
168 }
169}
170
171#[async_trait]
172impl MeasurementBackend for MockMeasurementBackend {
173 async fn get_text(&self, _url: &str) -> BackendResult<String> {
174 Ok(self.response.clone())
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::{
181 FsMeasurementCache, InMemoryMeasurementCache, MeasurementBackend, MeasurementCache,
182 MockMeasurementBackend,
183 };
184
185 #[tokio::test]
186 async fn in_memory_cache_round_trip() {
187 let cache = InMemoryMeasurementCache::new();
188 let path = std::path::Path::new("speakers/test/CEA2034.json");
189 cache.create_dir_all(path.parent().unwrap()).await.unwrap();
190 cache.write(path, "{\"data\":[]}").await.unwrap();
191 assert!(cache.is_dir(path.parent().unwrap()));
192 assert_eq!(cache.get(path).unwrap(), "{\"data\":[]}");
193 }
194
195 #[tokio::test]
196 async fn mock_backend_returns_fixed_response() {
197 let backend = MockMeasurementBackend::new("hello");
198 assert_eq!(backend.get_text("any-url").await.unwrap(), "hello");
199 }
200
201 #[tokio::test]
202 async fn fs_cache_round_trip() {
203 let tmp = tempfile::TempDir::new().unwrap();
204 let cache = FsMeasurementCache::new();
205 let path = tmp.path().join("a/b/c.json");
206 cache.create_dir_all(path.parent().unwrap()).await.unwrap();
207 cache.write(&path, "{}").await.unwrap();
208 assert_eq!(cache.read_to_string(&path).await.unwrap().unwrap(), "{}");
209 }
210}