1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
//! Engine-seam tests: pin the production of the `SearchError` variants
//! that `tests/search.rs` does not reach (it pins only `InvalidQuery`
//! via `&&` and `Backend` via its "boom" server), plus the
//! `GN3_TIMEOUT_SECS` -> reqwest timeout plumbing.
//!
//! These call the engine (`Gn3`) directly rather than through the
//! `/search` route, so no auth/JWKS stub is needed: the engine reads
//! only `GN3_URL` / `GN3_TIMEOUT_SECS`. A separate test binary is its
//! own process with its own environment, which keeps these env
//! mutations isolated from `tests/search.rs`; within this file the
//! scenarios run in one sequential test function, per the
//! process-global-state rule in docs/SKILL.md.
use axum::Router;
use axum::routing::get;
use genenetwork4::search::{Engine, SearchError, SearchHit, gn3::Gn3};
use std::time::{Duration, Instant};
use tokio::net::TcpListener;
/// The name of a result's variant, so a failed assertion can name what
/// it got without requiring `SearchHit: Debug`.
fn variant_name(result: &Result<Vec<SearchHit>, SearchError>) -> &'static str {
match result {
Ok(_) => "Ok",
Err(SearchError::InvalidQuery { .. }) => "InvalidQuery",
Err(SearchError::Unreachable(_)) => "Unreachable",
Err(SearchError::Misbehaving(_)) => "Misbehaving",
Err(SearchError::Backend(_)) => "Backend",
Err(SearchError::Internal(_)) => "Internal",
}
}
/// Serves an axum app on an ephemeral loopback port and returns its
/// base URL in the `.../api/` form the engine appends `search/` to.
async fn base_url_for(app: Router) -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
format!("http://127.0.0.1:{port}/api/")
}
/// A 200 response whose body is not the hits JSON: the decode step in
/// the engine must surface as `Misbehaving`.
async fn serve_not_json() -> &'static str {
"this is not the hits array"
}
/// A 200 response that stalls for 2s before answering, so a 1s
/// `GN3_TIMEOUT_SECS` fires first and the request surfaces as
/// `Unreachable`; without the timeout plumbing it would succeed.
/// The sleep runs on the blocking pool (house pattern, cf. every
/// `spawn_blocking` call in src/routes): a bare `std::thread::sleep`
/// here parks a runtime worker, and when the client future's wake
/// then lands on the parked worker, the timeout cancel is processed
/// only after the 2s response completes — a scheduler-dependent
/// ~30% flake (3/10 isolated failures measured at commit 1597f51,
/// both with and without unrelated working-tree changes).
async fn serve_slow() -> &'static str {
tokio::task::spawn_blocking(|| {
std::thread::sleep(Duration::from_secs(2));
"[]"
})
.await
.expect("slow-response task joins")
}
/// A bare TCP listener that accepts each connection and immediately
/// drops it, so the HTTP request fails with a transport error
/// (`Unreachable`) rather than any status.
async fn drop_server_base_url() -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
loop {
if let Ok((socket, _)) = listener.accept().await {
drop(socket);
}
}
});
format!("http://127.0.0.1:{port}/api/")
}
fn set(key: &str, value: &str) {
// SAFETY: this test binary has a single test function and no other
// thread reads these keys concurrently, so process-global env
// mutation is sound here (see the module doc comment).
unsafe { std::env::set_var(key, value) };
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn engine_produces_its_error_variants_and_honours_the_timeout() {
// Set before the first engine call: the shared reqwest client is
// built once, on first use, capturing this timeout.
set("GN3_TIMEOUT_SECS", "1");
// 1. Internal: an unparseable GN3_URL is a local misconfiguration
// and never reaches the network.
set("GN3_URL", ":::not a url");
let result = Gn3.search("alcohol", "phenotype", 5, 1).await;
assert_eq!(variant_name(&result), "Internal");
// 2. Misbehaving: a success status with a body that is not the hits
// JSON fails to decode.
let not_json_url = base_url_for(Router::new().route("/api/search/", get(serve_not_json))).await;
set("GN3_URL", ¬_json_url);
let result = Gn3.search("alcohol", "phenotype", 5, 1).await;
assert_eq!(variant_name(&result), "Misbehaving");
// 3. Unreachable: the upstream drops the connection.
let drop_url = drop_server_base_url().await;
set("GN3_URL", &drop_url);
let result = Gn3.search("alcohol", "phenotype", 5, 1).await;
assert_eq!(variant_name(&result), "Unreachable");
// 4. Timeout plumbing: with GN3_TIMEOUT_SECS=1, a 2s response is
// aborted well before it arrives, surfacing as Unreachable.
let slow_url = base_url_for(Router::new().route("/api/search/", get(serve_slow))).await;
set("GN3_URL", &slow_url);
let started = Instant::now();
let result = Gn3.search("alcohol", "phenotype", 5, 1).await;
let elapsed = started.elapsed();
assert_eq!(variant_name(&result), "Unreachable");
assert!(
elapsed < Duration::from_millis(1900),
"GN3_TIMEOUT_SECS=1 did not fire before the 2s response: {elapsed:?}"
);
}
|