Skip to content

Commit b8933a6

Browse files
voidstackloopclaude
andcommitted
Make monitor a better-behaved, more resilient citizen against real sites
Feature 3 of 4 requested large improvements. monitor hits real third-party government sites it doesn't control; two gaps in how it did that: 1. A single failed page load (browser::open) was reported as "Page load: Fail" immediately, with no distinction between "this form is genuinely down" and "the network hiccuped once." open() now retries up to 3 times with backoff (500ms, then 1s) before giving up — every attempt still has to fail for a real Fail to be reported. Verified retry actually happens (not just fails once and gives up) with a new tests/browser_test.rs: points at a file:// path that doesn't exist on the first attempt (confirmed empirically that a missing local file lands on the same chrome-error:// interstitial as a real network failure, via a throwaway probe test before committing to this design), then creates the file during open()'s own retry backoff window. Verified this test is meaningful by temporarily setting OPEN_ATTEMPTS to 1 and watching it fail exactly as predicted, before restoring it. 2. monitor's concurrency (buffer_unordered(4)) starts all 4 forms at once with no way to spread load over time — fine for formwatch's own infrastructure, less fine for a large forms.yml hitting real government sites. Added `--delay-ms` (default 0, unchanged behavior) and extracted the pacing into a small `paced()` stream combinator, directly unit-tested (pure timing logic, no browser needed) rather than left untested inline: one test proves zero delay adds no meaningful wait, another proves a real delay actually spaces items out — verified meaningful by stripping the sleep out of paced() and watching the second test catch it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 8d4021c commit b8933a6

5 files changed

Lines changed: 188 additions & 41 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ project doesn't have a release yet, so everything below is grouped under
3838
previous run `diff` compares against. A check that changed once and
3939
stayed changed is a genuine regression or fix, not flakiness — only
4040
the unstable, back-and-forth case gets the "Flaky" badge.
41+
- `monitor --delay-ms MS`: paces how fast new forms start (default 0 —
42+
unchanged behavior), so a large `forms.yml` against real third-party
43+
sites can spread its load out instead of firing up to
44+
`MAX_CONCURRENT_FORMS` requests at once.
45+
- Page loads now retry up to 3 times with backoff (500ms, then 1s)
46+
before reporting "Page load: Fail" — a transient DNS blip or dropped
47+
connection against a real site no longer gets mistaken for the form
48+
itself being down.
4149

4250
### Fixed
4351

‎README.md‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,13 @@ for why it's built the way it is.
2121
- **Page load** — if the form doesn't load at all (unreachable, DNS
2222
failure, connection refused), that's reported as a single clear Fail
2323
rather than running — and being misled by — the rest of the checks
24-
against Chrome's own error page. Likewise, if any individual check hits
25-
a transient problem, it's reported as a Warn on just that check; one
26-
check failing never loses the results of the others.
24+
against Chrome's own error page. A load is retried a couple of times
25+
with backoff first, so a transient network blip against a real
26+
third-party site doesn't get misreported as the form itself being
27+
down — every attempt still has to fail for that to be reported.
28+
Likewise, if any individual check hits a transient problem, it's
29+
reported as a Warn on just that check; one check failing never loses
30+
the results of the others.
2731
- **Submission flow** — the form exists and is reachable. Fields are
2832
filled with plausible dummy data on each screen; if a step has a
2933
Next/Continue control (multi-step wizards are common for permit/license
@@ -63,12 +67,16 @@ for why it's built the way it is.
6367
custom-check mechanism below.
6468
- `formwatch test <url> [--name NAME] [--submit] [--wait SECS] [--headful]
6569
[--checks-dir DIR] [--json]` — run every check once against a single form.
66-
- `formwatch monitor <forms.yml>... [--checks-dir DIR] [--json]` — run
67-
`test` against every form across one or more YAML configs (a shell glob
68-
like `community-forms/**/*.yml` works — the shell expands it to
69-
multiple arguments). Checks up to 4 forms at once (each gets its own
70-
browser page — they can't interfere with each other) and prints
71-
results in config order regardless of which one finishes first:
70+
- `formwatch monitor <forms.yml>... [--checks-dir DIR] [--json]
71+
[--delay-ms MS]` — run `test` against every form across one or more
72+
YAML configs (a shell glob like `community-forms/**/*.yml` works — the
73+
shell expands it to multiple arguments). Checks up to 4 forms at once
74+
(each gets its own browser page — they can't interfere with each
75+
other) and prints results in config order regardless of which one
76+
finishes first. `--delay-ms` (default 0) is a courtesy knob for a
77+
large `forms.yml` against real third-party sites you don't control —
78+
it paces how fast new forms start, spreading the load out instead of
79+
firing up to 4 requests at once:
7280
```yaml
7381
forms:
7482
- name: Business License Renewal

‎src/browser.rs‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use anyhow::{Context, Result};
22
use chromiumoxide::{Browser, BrowserConfig, BrowserFetcher, BrowserFetcherOptions, Page};
33
use futures::StreamExt;
44
use std::path::{Path, PathBuf};
5-
use std::time::{SystemTime, UNIX_EPOCH};
5+
use std::time::{Duration, SystemTime, UNIX_EPOCH};
66
use tokio::task::JoinHandle;
77

88
/// Downloads a Chrome-for-Testing build into ~/.cache/formwatch/chrome. Only
@@ -116,12 +116,39 @@ pub async fn launch(headful: bool) -> Result<(Browser, JoinHandle<()>)> {
116116
Ok((browser, handle))
117117
}
118118

119-
/// Opens `url` in a new page and waits for it to load. Returns `Err` if
120-
/// the page never loaded at all — including the case where Chrome
121-
/// "successfully" navigates to its own error interstitial (a DNS
119+
/// How many times [`open`] attempts to load a page before giving up. A
120+
/// real government site under real-world conditions can have a
121+
/// transient DNS blip or a dropped connection that has nothing to do
122+
/// with the form itself being broken — retrying a couple of times
123+
/// before reporting "Page load: Fail" avoids mistaking network noise
124+
/// for a real finding, without masking a form that's genuinely down
125+
/// (every attempt still has to fail for that to be reported).
126+
const OPEN_ATTEMPTS: u32 = 3;
127+
128+
/// Backoff between attempts; doubles each retry (500ms, then 1s).
129+
const OPEN_RETRY_BACKOFF: Duration = Duration::from_millis(500);
130+
131+
/// Opens `url` in a new page and waits for it to load, retrying up to
132+
/// [`OPEN_ATTEMPTS`] times with backoff on failure. Returns `Err` only
133+
/// if every attempt failed to load at all — including the case where
134+
/// Chrome "successfully" navigates to its own error interstitial (a DNS
122135
/// failure, connection refused, or blocked port), which callers should
123136
/// treat as the page genuinely being unreachable, not a real result.
124137
pub async fn open(browser: &Browser, url: &str) -> Result<Page> {
138+
let mut last_err = None;
139+
for attempt in 0..OPEN_ATTEMPTS {
140+
match open_once(browser, url).await {
141+
Ok(page) => return Ok(page),
142+
Err(e) => last_err = Some(e),
143+
}
144+
if attempt + 1 < OPEN_ATTEMPTS {
145+
tokio::time::sleep(OPEN_RETRY_BACKOFF * 2u32.pow(attempt)).await;
146+
}
147+
}
148+
Err(last_err.expect("loop runs at least once, always setting last_err on failure"))
149+
}
150+
151+
async fn open_once(browser: &Browser, url: &str) -> Result<Page> {
125152
let page = browser
126153
.new_page(url)
127154
.await

‎src/main.rs‎

Lines changed: 89 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,12 @@ enum Command {
7676
checks_dir: Option<PathBuf>,
7777
#[arg(long)]
7878
json: bool,
79+
/// Milliseconds to wait before starting each form's checks (0 = no
80+
/// delay). A real-world courtesy knob for a large forms.yml against
81+
/// third-party sites you don't control — spreads the load out
82+
/// instead of firing up to MAX_CONCURRENT_FORMS requests at once.
83+
#[arg(long, default_value_t = 0)]
84+
delay_ms: u64,
7985
},
8086
/// Print (or render to HTML/JSON) the most recent run of every form formwatch knows about.
8187
Report {
@@ -172,6 +178,7 @@ async fn main() -> Result<()> {
172178
headful,
173179
checks_dir,
174180
json,
181+
delay_ms,
175182
} => {
176183
let mut entries = vec![];
177184
for config in &configs {
@@ -191,35 +198,37 @@ async fn main() -> Result<()> {
191198

192199
let (browser, _handle) = browser::launch(headful).await?;
193200
let checks_dir_ref = checks_dir.as_deref();
194-
let mut indexed: Vec<(usize, history::RunResult)> =
195-
stream::iter(entries.into_iter().enumerate())
196-
.map(|(i, entry)| {
197-
let browser = &browser;
198-
let history_dir = &history_dir;
199-
async move {
200-
match runner::run_one(
201-
browser,
202-
history_dir,
203-
entry.name.clone(),
204-
entry.url,
205-
submit,
206-
wait,
207-
checks_dir_ref,
208-
)
209-
.await
210-
{
211-
Ok(run) => Some((i, run)),
212-
Err(e) => {
213-
eprintln!("{}: {e:#}", format!("{} failed", entry.name).red());
214-
None
215-
}
216-
}
201+
let mut indexed: Vec<(usize, history::RunResult)> = paced(
202+
stream::iter(entries.into_iter().enumerate()),
203+
std::time::Duration::from_millis(delay_ms),
204+
)
205+
.map(|(i, entry)| {
206+
let browser = &browser;
207+
let history_dir = &history_dir;
208+
async move {
209+
match runner::run_one(
210+
browser,
211+
history_dir,
212+
entry.name.clone(),
213+
entry.url,
214+
submit,
215+
wait,
216+
checks_dir_ref,
217+
)
218+
.await
219+
{
220+
Ok(run) => Some((i, run)),
221+
Err(e) => {
222+
eprintln!("{}: {e:#}", format!("{} failed", entry.name).red());
223+
None
217224
}
218-
})
219-
.buffer_unordered(MAX_CONCURRENT_FORMS)
220-
.filter_map(|x| async move { x })
221-
.collect()
222-
.await;
225+
}
226+
}
227+
})
228+
.buffer_unordered(MAX_CONCURRENT_FORMS)
229+
.filter_map(|x| async move { x })
230+
.collect()
231+
.await;
223232
// buffer_unordered completes in whichever order each form's
224233
// checks finish, not config order — restore config order so
225234
// "monitor a, b, c" doesn't print in a different order every
@@ -261,6 +270,25 @@ async fn main() -> Result<()> {
261270
Ok(())
262271
}
263272

273+
/// Paces a stream so each item is only yielded `delay` after the item
274+
/// before it (a no-op pass-through when `delay` is zero) — used to
275+
/// spread `monitor`'s per-form checks out over time instead of firing
276+
/// up to `MAX_CONCURRENT_FORMS` requests at once, a real-world courtesy
277+
/// against third-party sites this tool doesn't control. A plain
278+
/// `buffer_unordered(N)` alone doesn't pace anything: it happily starts
279+
/// all N immediately, then refills as each one finishes.
280+
fn paced<S: stream::Stream>(
281+
source: S,
282+
delay: std::time::Duration,
283+
) -> impl stream::Stream<Item = S::Item> {
284+
source.then(move |item| async move {
285+
if !delay.is_zero() {
286+
tokio::time::sleep(delay).await;
287+
}
288+
item
289+
})
290+
}
291+
264292
fn load_forms_config(path: &Path) -> Result<FormsConfig> {
265293
let text =
266294
std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
@@ -459,4 +487,37 @@ mod tests {
459487

460488
let _ = std::fs::remove_dir_all(&dir);
461489
}
490+
491+
#[tokio::test]
492+
async fn paced_with_zero_delay_does_not_slow_the_stream() {
493+
let start = std::time::Instant::now();
494+
let items: Vec<i32> = paced(stream::iter(0..5), std::time::Duration::ZERO)
495+
.collect()
496+
.await;
497+
assert_eq!(items, vec![0, 1, 2, 3, 4]);
498+
assert!(
499+
start.elapsed() < std::time::Duration::from_millis(200),
500+
"zero delay should add no meaningful wait, took {:?}",
501+
start.elapsed()
502+
);
503+
}
504+
505+
#[tokio::test]
506+
async fn paced_with_a_delay_spaces_items_out() {
507+
// --delay-ms is meant to spread monitor's per-form requests out
508+
// over time, not just cap concurrency — this is the one property
509+
// that actually distinguishes `paced` from a plain pass-through,
510+
// so it's the one worth proving directly rather than trusting
511+
// that `.then()` obviously does the right thing.
512+
let delay = std::time::Duration::from_millis(30);
513+
let start = std::time::Instant::now();
514+
let items: Vec<i32> = paced(stream::iter(0..3), delay).collect().await;
515+
assert_eq!(items, vec![0, 1, 2]);
516+
assert!(
517+
start.elapsed() >= delay * 3,
518+
"expected at least {:?} total, took {:?}",
519+
delay * 3,
520+
start.elapsed()
521+
);
522+
}
462523
}

‎tests/browser_test.rs‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//! Exercises `browser::open`'s retry behavior — needs a real Chrome, same
2+
//! as `checks_test.rs`.
3+
4+
use formwatch::browser;
5+
6+
#[tokio::test]
7+
async fn open_retries_and_succeeds_once_a_transient_failure_resolves() {
8+
// A missing local file lands on the same chrome-error:// interstitial
9+
// as a real network failure (DNS, connection refused) — confirmed
10+
// directly before writing this test. Points at a file that doesn't
11+
// exist on the first attempt (so the first attempt genuinely fails,
12+
// not a no-op), then creates it during open()'s own retry backoff
13+
// window, proving it actually retries rather than failing once and
14+
// giving up.
15+
let (browser, _handle) = browser::launch(false).await.expect("launch chrome");
16+
let path = std::env::temp_dir().join("formwatch-test-open-retry.html");
17+
let _ = std::fs::remove_file(&path);
18+
let url = format!("file://{}", path.display());
19+
20+
tokio::spawn({
21+
let path = path.clone();
22+
async move {
23+
// Well inside open()'s 500ms-then-1s backoff window (a real
24+
// attempt happens at t=0, ~500ms, and ~1500ms), and well after
25+
// the first attempt has already failed.
26+
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
27+
std::fs::write(&path, "<html><body>ready</body></html>").expect("write file");
28+
}
29+
});
30+
31+
let page = browser::open(&browser, &url)
32+
.await
33+
.expect("open should retry until the file exists and succeed");
34+
let text: String = page
35+
.evaluate("document.body.innerText")
36+
.await
37+
.expect("evaluate")
38+
.into_value()
39+
.expect("string");
40+
assert_eq!(text, "ready");
41+
42+
let _ = std::fs::remove_file(&path);
43+
}

0 commit comments

Comments
 (0)