Skip to main content

autoeq_measurements/read/read_api/
backend.rs

1//! Pluggable measurement backend and cache for `read_api`.
2//!
3//! This module introduces two seams that were previously hard-wired inside
4//! `fetch.rs`:
5//!
6//! - [`MeasurementBackend`] performs the actual network (or mock) request.
7//! - [`MeasurementCache`] persists and loads cached responses.
8//!
9//! Production implementations (`ReqwestMeasurementBackend`,
10//! `FsMeasurementCache`) are used by the public free functions by default.
11//! Tests can swap in an in-memory cache and a mock backend to run fully
12//! offline and deterministically.
13
14use async_trait::async_trait;
15use std::collections::HashMap;
16use std::path::{Path, PathBuf};
17use std::sync::{Arc, Mutex};
18
19/// Error type alias for backend/cache operations.
20pub type BackendResult<T> = Result<T, Box<dyn std::error::Error>>;
21
22/// Abstraction over the network/source that provides measurement data.
23#[async_trait]
24pub trait MeasurementBackend: Send + Sync {
25    /// Fetch a URL and return the raw response body as text.
26    async fn get_text(&self, url: &str) -> BackendResult<String>;
27}
28
29/// Abstraction over the local measurement cache.
30#[async_trait]
31pub trait MeasurementCache: Send + Sync {
32    /// Read a cached file as a UTF-8 string.
33    async fn read_to_string(&self, path: &Path) -> BackendResult<Option<String>>;
34
35    /// Write a UTF-8 string to the cache.
36    async fn write(&self, path: &Path, content: &str) -> BackendResult<()>;
37
38    /// Ensure that `path` and its parents exist in the cache.
39    async fn create_dir_all(&self, path: &Path) -> BackendResult<()>;
40}
41
42/// Production backend that issues real HTTP GET requests via `reqwest`.
43#[derive(Debug, Default, Clone, Copy)]
44pub struct ReqwestMeasurementBackend;
45
46impl ReqwestMeasurementBackend {
47    /// Create a new production backend.
48    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/// Production cache backed by the local filesystem.
65#[derive(Debug, Default, Clone, Copy)]
66pub struct FsMeasurementCache;
67
68impl FsMeasurementCache {
69    /// Create a new filesystem-backed cache.
70    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/// In-memory cache for deterministic tests.
97#[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    /// Create a new empty in-memory cache.
105    pub fn new() -> Self {
106        Self::default()
107    }
108
109    /// Pre-seed a cache entry.
110    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    /// Return the content stored under `path`, if any.
118    pub fn get(&self, path: &Path) -> Option<String> {
119        self.files.lock().unwrap().get(path).cloned()
120    }
121
122    /// Return true if `path` has been created as a directory.
123    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/// Simple mock backend that returns a fixed response for a given URL.
157#[derive(Debug, Default, Clone)]
158pub struct MockMeasurementBackend {
159    response: String,
160}
161
162impl MockMeasurementBackend {
163    /// Create a backend that always returns `response`.
164    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}