Skip to content

Commit f1caa3b

Browse files
voidstackloopclaude
andcommitted
Cache serve's history reads for 2 seconds
Same theme as the earlier history-I/O fixes this week, applied to the one place they don't help at all: formwatch serve. /metrics and /api/forms both called history::all_known_forms fresh on every single HTTP request - even after the filename-based fix (ac7cf22) made that one file read per form instead of every historical run, it's still a full directory walk plus one file read per form, repeated on every request to a service whose entire purpose is being polled. Prometheus scrapes /metrics on a fixed interval, an orchestrator hits /readyz repeatedly, a status page refreshes /api/forms - all far more often than `monitor` actually writes a new run on its own cron schedule. Added HistoryCache: a small Mutex<Option<(Instant, Arc<Vec<RunResult>>)>> with a 2-second TTL, shared via Arc across every connection the process handles. Both endpoints read through it instead of calling all_known_forms directly, so a burst of near-simultaneous requests (a status page loading /metrics and /api/forms back to back, several Prometheus scrapes close together) collapses to one disk read. 2 seconds of staleness is unnoticeable to any of the real consumers this serves - none of them need sub-second freshness - so no new CLI flag or config knob for the TTL; it's a fixed constant. route() keeps its existing signature otherwise, still directly unit-testable without a real server; existing tests pass a HistoryCache::new(Duration::ZERO) so they see exactly the same "always fresh" behavior as before the cache existed. Verified with a real cache-behavior test, not just correctness: writes one run, reads /metrics, writes a second run within the TTL window, confirms /metrics still reports the stale (cached) count, then sleeps past the TTL and confirms the next read picks up the second run. Verified the test actually catches a regression by temporarily making the cache never expire (dropped the TTL check entirely) - the refresh-after-expiry assertion failed exactly as predicted - then restored the fix. cargo fmt/clippy -D warnings clean, full suite green (164 tests). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent c61b5dc commit f1caa3b

3 files changed

Lines changed: 135 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,16 @@ project doesn't have a release yet, so everything below is grouped under
2424

2525
### Performance
2626

27+
- **`serve`'s `/metrics` and `/api/forms` cache history for 2 seconds.**
28+
Both endpoints called `history::all_known_forms` fresh on every single
29+
request, even though `serve` exists specifically to be *polled* —
30+
Prometheus scraping `/metrics`, an orchestrator hitting `/readyz`, a
31+
status page refreshing `/api/forms` — far more often than `monitor`
32+
actually writes a new run. A shared, short-TTL cache (`HistoryCache`)
33+
means repeated scrapes within the same interval reuse one loaded
34+
result instead of each re-walking the whole history directory; a scrape
35+
a few seconds later than the last real change is indistinguishable
36+
from a fresh read to any monitoring consumer.
2737
- **`prune` no longer opens or parses any run file.** Same anti-pattern
2838
as `all_known_forms` below, in the one command whose entire job is
2939
handling a *lot* of accumulated history: `history::prune` read and

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,12 @@ It binds to `127.0.0.1` by default; set `--addr`, `serve_addr:`, or
522522
`/readyz`, or a status page at `/api/forms`. It runs until interrupted
523523
(Ctrl-C).
524524
525+
`/metrics` and `/api/forms` cache the loaded history for 2 seconds,
526+
shared across every connection the process handles — since a scrape
527+
interval is almost always shorter than how often `monitor` actually
528+
writes a new run, this avoids re-walking the whole history directory
529+
(and re-reading every form's latest run file) on every single poll.
530+
525531
## Retention
526532
527533
History is append-only, so a deployment that runs nightly accumulates runs

‎src/serve.rs‎

Lines changed: 119 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
//! to `127.0.0.1` by default.
1717
1818
use crate::history;
19+
use crate::history::RunResult;
1920
use crate::metrics;
2021
use anyhow::{Context, Result};
2122
use bytes::Bytes;
@@ -26,8 +27,8 @@ use hyper::{Method, Request, Response, StatusCode};
2627
use hyper_util::rt::TokioIo;
2728
use std::net::SocketAddr;
2829
use std::path::{Path, PathBuf};
29-
use std::sync::Arc;
30-
use std::time::Duration;
30+
use std::sync::{Arc, Mutex};
31+
use std::time::{Duration, Instant};
3132
use tokio::net::TcpListener;
3233
use tokio::sync::Semaphore;
3334

@@ -37,9 +38,55 @@ const JSON: &str = "application/json; charset=utf-8";
3738

3839
const INDEX: &str = "formwatch (read-only)\n\n GET /healthz liveness\n GET /readyz readiness\n GET /metrics Prometheus metrics\n GET /api/forms latest run of every form (JSON)\n";
3940

41+
/// How long a loaded [`history::all_known_forms`] result is reused before
42+
/// the next `/metrics` or `/api/forms` request re-reads history from
43+
/// disk. `/metrics` in particular is meant to be scraped (Prometheus,
44+
/// `/readyz`-style liveness polling, a status page) far more often than
45+
/// `monitor` actually writes new runs — without this, every scrape
46+
/// re-walked the entire history directory (one file read per form) for
47+
/// data that, almost always, hadn't changed since the last scrape a few
48+
/// seconds earlier. Short enough that nobody scraping a monitoring
49+
/// endpoint will notice the staleness.
50+
const HISTORY_CACHE_TTL: Duration = Duration::from_secs(2);
51+
52+
/// Caches the last [`history::all_known_forms`] result for
53+
/// [`HISTORY_CACHE_TTL`], shared across every request `serve` handles —
54+
/// `/metrics` and `/api/forms` both read through it instead of each
55+
/// re-scanning history independently.
56+
struct HistoryCache {
57+
ttl: Duration,
58+
loaded: Mutex<Option<(Instant, Arc<Vec<RunResult>>)>>,
59+
}
60+
61+
impl HistoryCache {
62+
fn new(ttl: Duration) -> Self {
63+
Self {
64+
ttl,
65+
loaded: Mutex::new(None),
66+
}
67+
}
68+
69+
fn get_or_load(&self, history_dir: &Path) -> Result<Arc<Vec<RunResult>>> {
70+
let mut loaded = self.loaded.lock().unwrap_or_else(|e| e.into_inner());
71+
if let Some((fetched_at, runs)) = loaded.as_ref()
72+
&& fetched_at.elapsed() < self.ttl
73+
{
74+
return Ok(runs.clone());
75+
}
76+
let runs = Arc::new(history::all_known_forms(history_dir)?);
77+
*loaded = Some((Instant::now(), runs.clone()));
78+
Ok(runs)
79+
}
80+
}
81+
4082
/// Routes a request to a `(status, content-type, body)` triple. Kept
4183
/// separate from the socket plumbing so it can be unit-tested directly.
42-
fn route(method: &Method, path: &str, history_dir: &Path) -> (StatusCode, &'static str, String) {
84+
fn route(
85+
method: &Method,
86+
path: &str,
87+
history_dir: &Path,
88+
cache: &HistoryCache,
89+
) -> (StatusCode, &'static str, String) {
4390
if method != Method::GET {
4491
return (
4592
StatusCode::METHOD_NOT_ALLOWED,
@@ -57,16 +104,16 @@ fn route(method: &Method, path: &str, history_dir: &Path) -> (StatusCode, &'stat
57104
format!("history directory not writable: {e}\n"),
58105
),
59106
},
60-
"/metrics" => match history::all_known_forms(history_dir) {
107+
"/metrics" => match cache.get_or_load(history_dir) {
61108
Ok(runs) => (StatusCode::OK, PROMETHEUS, metrics::render(&runs)),
62109
Err(e) => (
63110
StatusCode::INTERNAL_SERVER_ERROR,
64111
TEXT,
65112
format!("error rendering metrics: {e}\n"),
66113
),
67114
},
68-
"/api/forms" | "/api/runs" => match history::all_known_forms(history_dir) {
69-
Ok(runs) => match serde_json::to_string_pretty(&runs) {
115+
"/api/forms" | "/api/runs" => match cache.get_or_load(history_dir) {
116+
Ok(runs) => match serde_json::to_string_pretty(&*runs) {
70117
Ok(body) => (StatusCode::OK, JSON, body),
71118
Err(e) => (
72119
StatusCode::INTERNAL_SERVER_ERROR,
@@ -100,9 +147,10 @@ fn readiness(history_dir: &Path) -> std::io::Result<()> {
100147
async fn handle(
101148
req: Request<Incoming>,
102149
history_dir: PathBuf,
150+
cache: Arc<HistoryCache>,
103151
) -> Result<Response<Full<Bytes>>, std::convert::Infallible> {
104152
let path = req.uri().path().to_string();
105-
let (status, content_type, body) = route(req.method(), &path, &history_dir);
153+
let (status, content_type, body) = route(req.method(), &path, &history_dir, &cache);
106154
let response = Response::builder()
107155
.status(status)
108156
.header("content-type", content_type)
@@ -130,6 +178,7 @@ pub async fn run(history_dir: PathBuf, addr: SocketAddr) -> Result<()> {
130178
// with unbounded half-open connections.
131179
const MAX_CONNECTIONS: usize = 64;
132180
let limit = Arc::new(Semaphore::new(MAX_CONNECTIONS));
181+
let cache = Arc::new(HistoryCache::new(HISTORY_CACHE_TTL));
133182

134183
loop {
135184
tokio::select! {
@@ -149,10 +198,11 @@ pub async fn run(history_dir: PathBuf, addr: SocketAddr) -> Result<()> {
149198
}
150199
};
151200
let history_dir = history_dir.clone();
201+
let cache = cache.clone();
152202
tokio::spawn(async move {
153203
let _permit = permit;
154204
let io = TokioIo::new(stream);
155-
let service = service_fn(move |req| handle(req, history_dir.clone()));
205+
let service = service_fn(move |req| handle(req, history_dir.clone(), cache.clone()));
156206
if let Err(e) =
157207
hyper::server::conn::http1::Builder::new()
158208
.header_read_timeout(Duration::from_secs(10))
@@ -199,13 +249,21 @@ mod tests {
199249
dir
200250
}
201251

252+
/// A cache that never actually caches, so existing tests see exactly
253+
/// the same "always fresh" behavior `route` had before the cache
254+
/// existed.
255+
fn no_cache() -> HistoryCache {
256+
HistoryCache::new(Duration::ZERO)
257+
}
258+
202259
#[test]
203260
fn health_and_readiness_are_ok() {
204261
let dir = seeded_history("health");
205-
let (status, _, body) = route(&Method::GET, "/healthz", &dir);
262+
let cache = no_cache();
263+
let (status, _, body) = route(&Method::GET, "/healthz", &dir, &cache);
206264
assert_eq!(status, StatusCode::OK);
207265
assert_eq!(body, "ok\n");
208-
let (status, _, _) = route(&Method::GET, "/readyz", &dir);
266+
let (status, _, _) = route(&Method::GET, "/readyz", &dir, &cache);
209267
assert_eq!(status, StatusCode::OK);
210268
let _ = std::fs::remove_dir_all(&dir);
211269
}
@@ -219,15 +277,15 @@ mod tests {
219277
// fails, so readiness must report 503.
220278
let file = base.join("history");
221279
std::fs::write(&file, b"x").expect("write file");
222-
let (status, _, _) = route(&Method::GET, "/readyz", &file);
280+
let (status, _, _) = route(&Method::GET, "/readyz", &file, &no_cache());
223281
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
224282
let _ = std::fs::remove_dir_all(&base);
225283
}
226284

227285
#[test]
228286
fn metrics_endpoint_renders_prometheus() {
229287
let dir = seeded_history("metrics");
230-
let (status, content_type, body) = route(&Method::GET, "/metrics", &dir);
288+
let (status, content_type, body) = route(&Method::GET, "/metrics", &dir, &no_cache());
231289
assert_eq!(status, StatusCode::OK);
232290
assert!(content_type.contains("version=0.0.4"));
233291
assert!(body.contains("formwatch_forms 1"), "{body}");
@@ -238,7 +296,7 @@ mod tests {
238296
#[test]
239297
fn forms_endpoint_returns_json() {
240298
let dir = seeded_history("forms");
241-
let (status, content_type, body) = route(&Method::GET, "/api/forms", &dir);
299+
let (status, content_type, body) = route(&Method::GET, "/api/forms", &dir, &no_cache());
242300
assert_eq!(status, StatusCode::OK);
243301
assert!(content_type.contains("application/json"));
244302
let value: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
@@ -250,11 +308,57 @@ mod tests {
250308
#[test]
251309
fn unknown_paths_and_write_methods_are_rejected() {
252310
let dir = seeded_history("unknown");
253-
let (status, _, _) = route(&Method::GET, "/nope", &dir);
311+
let cache = no_cache();
312+
let (status, _, _) = route(&Method::GET, "/nope", &dir, &cache);
254313
assert_eq!(status, StatusCode::NOT_FOUND);
255314
// Critically, nothing that mutates is served.
256-
let (status, _, _) = route(&Method::POST, "/api/forms", &dir);
315+
let (status, _, _) = route(&Method::POST, "/api/forms", &dir, &cache);
257316
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
258317
let _ = std::fs::remove_dir_all(&dir);
259318
}
319+
320+
#[test]
321+
fn metrics_are_cached_within_the_ttl_and_refreshed_after_it_expires() {
322+
let dir = seeded_history("cache-ttl");
323+
let cache = HistoryCache::new(Duration::from_millis(50));
324+
325+
let (_, _, first) = route(&Method::GET, "/metrics", &dir, &cache);
326+
assert!(first.contains("formwatch_forms 1"), "{first}");
327+
328+
// A second form's run lands on disk, but within the TTL the
329+
// cached result must still be served — proving this genuinely
330+
// avoids re-reading history, not just that it returns correct
331+
// data on a cold cache.
332+
history::save_run(
333+
&dir,
334+
&RunResult {
335+
schema_version: SCHEMA_VERSION,
336+
name: "Renewal".into(),
337+
url: "https://city.gov/renewal".into(),
338+
timestamp: 43,
339+
checks: vec![CheckResult {
340+
name: "Accessibility".into(),
341+
status: Status::Pass,
342+
detail: String::new(),
343+
screenshot: None,
344+
}],
345+
},
346+
)
347+
.expect("save second run");
348+
349+
let (_, _, still_cached) = route(&Method::GET, "/metrics", &dir, &cache);
350+
assert!(
351+
still_cached.contains("formwatch_forms 1"),
352+
"expected the cached (stale) count within the TTL, got: {still_cached}"
353+
);
354+
355+
std::thread::sleep(Duration::from_millis(60));
356+
let (_, _, refreshed) = route(&Method::GET, "/metrics", &dir, &cache);
357+
assert!(
358+
refreshed.contains("formwatch_forms 2"),
359+
"expected a fresh read after the TTL expired, got: {refreshed}"
360+
);
361+
362+
let _ = std::fs::remove_dir_all(&dir);
363+
}
260364
}

0 commit comments

Comments
 (0)