#[path = "../src/scratch.rs"]
mod scratch;
use fats::provider::{Api, Reply};
use scratch::Scratch;
use serde_json::Value;
use std::sync::{Mutex, MutexGuard};
use std::time::{Duration, Instant};
fn slow(api: Api, _: &str, req: &Value) -> Reply {
let url = req["url"].as_str().unwrap_or_default();
if api == Api::BdRequest && url.contains("q=oxyslow") {
let body = r#"{"organic":[{"link":"https://ex.com/bd","title":"From BD","description":"d"}]}"#;
return Reply { status: 200, headers: vec![], body: body.as_bytes().to_vec() };
}
let (ms, body) = if api == Api::BdRequest && url.contains("/lands3s") {
let p = "A page that lands after three seconds still lands whole, with its numbers: 12 apples. ".repeat(12);
let html =
format!("<html><head><title>Lands Late</title></head><body><h1>Lands Late</h1><p>{p}</p></body></html>");
("3000", serde_json::json!({"status_code": 200, "headers": {}, "body": html}).to_string())
} else {
("30000", "{}".to_string())
};
let headers = vec![("x-fake-delay-ms".to_string(), ms.to_string())];
Reply { status: 200, headers, body: body.into_bytes() }
}
fn site_403() -> String {
use std::io::{Read, Write};
let site = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let url = format!("http://{}", site.local_addr().expect("addr"));
std::thread::spawn(move || {
for mut c in site.incoming().flatten() {
if c.read(&mut [0; 4096]).is_ok_and(|n| n > 0) {
c.write_all(b"HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\nconnection: close\r\n\r\n").ok();
}
}
});
url
}
fn run(args: &[&str]) -> (String, Duration) {
let t0 = Instant::now();
let (out, ..) = fats::cli::run(&args.iter().map(|a| a.to_string()).collect::<Vec<_>>());
(out, t0.elapsed())
}
#[expect(unsafe_code, reason = "set_var once per process, before the first settings read")]
fn setup_env() -> (Scratch, MutexGuard<'static, ()>) {
static ONCE: std::sync::Once = std::sync::Once::new();
static TURN: Mutex<()> = Mutex::new(());
let turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
ONCE.call_once(|| {
let dir = Scratch::path("wait");
unsafe {
std::env::set_var("FATS_CACHE", dir.join("cache"));
std::env::set_var("FATS_KEY_DIR", dir.join("keys"));
std::env::set_var("FATS_SESSION", "t");
std::env::set_var("BRIGHTDATA_UNLOCKER_ZONE", "my_unlocker");
std::env::remove_var("FATS_OFFLINE");
std::env::set_var("FATS_TELEMETRY", "0");
std::env::set_var("FATS_ALLOW_PRIVATE", "1");
}
fats::provider::fake(slow);
});
let fresh = Scratch::new("wait");
scratch::auth(&fresh.join("keys"), &[("oxy", "oxyK3y-wait"), ("bd", "bdK3y-wait"), ("gh", "ghp_wait")]);
(fresh, turn)
}
fn answers_by_wait(cmd: &str, row: &str) {
let _dir = setup_env();
let t0 = Instant::now();
let (out, ..) = fats::cli::run(&cmd.split_whitespace().map(String::from).collect::<Vec<_>>());
let took = t0.elapsed();
eprintln!("{cmd}: {} ms", took.as_millis());
assert!(took <= Duration::from_millis(2000), "{cmd} took {took:?}: {out}");
let more = if row.contains("pending") { " j1 wait:30 · free, check again in 30 s" } else { " wait:30" };
assert!(out.contains(row) && out.contains(more), "the fix gives more time: {cmd}: {out}");
assert!(!out.contains("budget_hit"), "a cut tier is not a budget stop: {out}");
}
#[test]
fn search_answers_by_wait() {
answers_by_wait("slow words fetch:0 wait:1", "= j1 pending 1s search \"slow words\" → ");
}
#[test]
fn search_hedge_zero_answers_by_wait() {
answers_by_wait("slow words fetch:0 wait:1 hedge:0", "= j1 pending 1s search \"slow words\" → ");
}
#[test]
fn gh_answers_by_wait() {
answers_by_wait("gh slow fetch:0 wait:1", "! provider_timeout gh wait:1s");
}
#[test]
fn account_answers_by_wait() {
answers_by_wait("account fresh:true wait:1", "bd ! provider_timeout wait:1s → ");
}
#[test]
fn setup_answers_by_wait() {
answers_by_wait("setup wait:1", "bd ! provider_timeout wait:1s");
}
#[test]
fn search_hedge_answers_by_wait() {
let _dir = setup_env();
let t0 = Instant::now();
let (out, ..) = fats::cli::run(&["oxyslow", "words", "fetch:0", "wait:5"].map(String::from));
let took = t0.elapsed();
eprintln!("oxyslow words wait:5: {} ms", took.as_millis());
assert!(took >= Duration::from_millis(2500) && took < Duration::from_millis(5000), "{took:?}: {out}");
assert!(out.contains("From BD") && out.contains("bd "), "bd answered: {out}");
}
#[test]
fn timeout_is_one_wall_with_both_keys() {
let _dir = setup_env();
let url = format!("{}/cut", site_403());
let (out, took) = run(&[&url, "timeout:2", "hedge:1", "wait:30"]);
eprintln!("timeout:2: {} ms\n{out}", took.as_millis());
let eq = out.lines().find(|l| l.starts_with("= ")).unwrap_or_default();
assert_eq!(eq.matches("provider_timeout✗").count(), 1, "one cut call: {out}");
assert!(took <= Duration::from_secs(3), "{took:?}: {out}");
}
#[test]
fn a_live_url_asked_again_waits_for_its_run() {
let _dir = setup_env();
let url = format!("{}/lands3s", site_403());
let (first, took) = run(&[&url, "wait:1"]);
assert!(first.starts_with("= j1.u1 pending ") && took < Duration::from_secs(2), "{took:?}: {first}");
let (dry, _) = run(&[&url, "dry:true"]);
assert!(dry.contains("/lands3s = u1 (running) · waits up to 30s for it · $0"), "{dry}");
let (again, took) = run(&[&url, "wait:30"]);
let head = again.lines().next().unwrap_or_default();
assert!(head.starts_with("= j1.u1 Lands Late ") && !head.contains("pending"), "{took:?}: {again}");
assert!(took < Duration::from_secs(5), "the page the moment it lands: {took:?}");
let (third, _) = run(&[&url]);
assert!(third.lines().next().is_some_and(|l| l.contains("Lands Late") && l.contains(" · cache ")), "{third}");
}