1use std::collections::{BTreeMap, BTreeSet};
5use std::io::{Read, Write};
6use std::net::{SocketAddr, TcpListener, TcpStream};
7use std::path::{Path, PathBuf};
8use std::process::{Child, Command, Stdio};
9use std::time::{Duration, Instant};
10
11use anyhow::{Context, Result, bail, ensure};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use toml_edit::{DocumentMut, Item, Table, value};
15
16use crate::app::{
17 self, Config, Failure, Fallback, Normalizers, Problem, RecordOptions, RecordOutcome,
18 ReplayOutcome,
19};
20
21pub const HTTP_DIR: &str = "http";
22const READY: Duration = Duration::from_secs(60);
23const SKIP_HEADERS: [&str; 12] = [
24 "date",
25 "host",
26 "server",
27 "connection",
28 "keep-alive",
29 "transfer-encoding",
30 "content-length",
31 "x-powered-by",
32 "etag",
33 "last-modified",
34 "age",
35 "via",
36];
37const LOCAL_HOSTS: [&str; 4] = ["localhost", "127.0.0.1", "0.0.0.0", "[::1]"];
38
39#[derive(Debug, Clone, Default, Serialize, Deserialize)]
41pub struct HttpConfig {
42 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub port: Option<u16>,
46}
47
48fn get() -> String {
49 "GET".to_string()
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Req {
55 #[serde(default = "get")]
56 pub method: String,
57 pub path: String,
58 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
59 pub headers: BTreeMap<String, String>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub body: Option<String>,
62}
63
64#[derive(Debug, Deserialize)]
65struct HttpInput {
66 #[serde(default)]
67 name: Option<String>,
68 #[serde(flatten)]
69 req: Req,
70}
71
72#[derive(Debug, Clone)]
73struct Resp {
74 status: u16,
75 headers: BTreeMap<String, String>,
76 body: Vec<u8>,
77}
78
79pub fn free_port() -> Result<u16> {
80 Ok(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
81}
82
83fn local(port: u16) -> SocketAddr {
84 SocketAddr::from(([127, 0, 0, 1], port))
85}
86
87fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
88 haystack.windows(needle.len()).position(|w| w == needle)
89}
90
91fn fill(stream: &mut impl Read, buf: &mut Vec<u8>, need: usize) -> Result<()> {
92 let mut chunk = [0u8; 8192];
93 while buf.len() < need {
94 let n = stream.read(&mut chunk)?;
95 ensure!(n > 0, "the connection closed in the middle of the response");
96 buf.extend_from_slice(&chunk[..n]);
97 }
98 Ok(())
99}
100
101fn chunk_line_end(stream: &mut impl Read, buf: &mut Vec<u8>) -> Result<usize> {
102 loop {
103 if let Some(end) = find(buf, b"\r\n") {
104 return Ok(end);
105 }
106 let need = buf.len() + 1;
107 fill(stream, buf, need)?;
108 }
109}
110
111fn read_chunked(stream: &mut impl Read, mut buf: Vec<u8>) -> Result<Vec<u8>> {
112 let mut body = Vec::new();
113 loop {
114 let line_end = chunk_line_end(stream, &mut buf)?;
115 let size_text = String::from_utf8_lossy(&buf[..line_end]).into_owned();
116 let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
117 .with_context(|| format!("bad chunk size `{size_text}`"))?;
118 buf.drain(..line_end + 2);
119 if size == 0 {
120 loop {
121 let line_end = chunk_line_end(stream, &mut buf)?;
122 if line_end == 0 {
123 return Ok(body);
124 }
125 buf.drain(..line_end + 2);
126 }
127 }
128 let end = size.checked_add(2).context("chunk size is too large")?;
129 fill(stream, &mut buf, end)?;
130 ensure!(&buf[size..end] == b"\r\n", "bad chunk terminator");
131 body.extend_from_slice(&buf[..size]);
132 buf.drain(..end);
133 }
134}
135
136fn read_response(stream: &mut impl Read, head_only: bool) -> Result<Resp> {
137 let mut buf = Vec::new();
138 let mut chunk = [0u8; 8192];
139 let (status, head, mut rest) = loop {
140 let header_end = loop {
141 if let Some(i) = find(&buf, b"\r\n\r\n") {
142 break i;
143 }
144 let n = stream.read(&mut chunk)?;
145 ensure!(n > 0, "the connection closed before a full response");
146 buf.extend_from_slice(&chunk[..n]);
147 };
148 let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
149 let status_line = head.split("\r\n").next().unwrap_or_default();
150 let status: u16 = status_line
151 .split_whitespace()
152 .nth(1)
153 .and_then(|s| s.parse().ok())
154 .with_context(|| format!("not an HTTP response: `{status_line}`"))?;
155 let rest = buf.split_off(header_end + 4);
156 if status == 101 || !(100..200).contains(&status) {
157 break (status, head, rest);
158 }
159 buf = rest;
160 };
161 let lines = head.split("\r\n").skip(1);
162 let mut headers: BTreeMap<String, String> = BTreeMap::new();
163 for line in lines {
164 if let Some((k, v)) = line.split_once(':') {
165 let v = v.trim().to_string();
166 headers
167 .entry(k.trim().to_ascii_lowercase())
168 .and_modify(|e| {
169 e.push_str(", ");
170 e.push_str(&v);
171 })
172 .or_insert(v);
173 }
174 }
175 let chunked = headers
176 .get("transfer-encoding")
177 .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
178 let body = if head_only || status == 204 || status == 304 || (100..200).contains(&status) {
179 Vec::new()
180 } else if chunked {
181 read_chunked(stream, rest)?
182 } else if let Some(len) = headers
183 .get("content-length")
184 .and_then(|l| l.parse::<usize>().ok())
185 {
186 fill(stream, &mut rest, len)?;
187 rest.truncate(len);
188 rest
189 } else {
190 stream
191 .read_to_end(&mut rest)
192 .context("reading close-delimited HTTP body")?;
193 rest
194 };
195 Ok(Resp {
196 status,
197 headers,
198 body,
199 })
200}
201
202fn send(port: u16, req: &Req, timeout: Duration) -> Result<Resp> {
203 let mut stream = TcpStream::connect_timeout(&local(port), timeout)?;
204 stream.set_read_timeout(Some(timeout))?;
205 stream.set_write_timeout(Some(timeout))?;
206 let body = req.body.as_deref().unwrap_or("").as_bytes();
207 let mut head = format!(
208 "{} {} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n",
209 req.method, req.path
210 );
211 for (k, v) in &req.headers {
212 if !matches!(
213 k.to_ascii_lowercase().as_str(),
214 "host" | "connection" | "content-length"
215 ) {
216 head += &format!("{k}: {v}\r\n");
217 }
218 }
219 if req.body.is_some() || matches!(req.method.as_str(), "POST" | "PUT" | "PATCH") {
220 head += &format!("Content-Length: {}\r\n", body.len());
221 }
222 head += "\r\n";
223 stream.write_all(head.as_bytes())?;
224 stream.write_all(body)?;
225 read_response(&mut stream, req.method == "HEAD")
226}
227
228struct Server {
230 child: Child,
231 port: u16,
232 dir: PathBuf,
233 log: PathBuf,
234 stopped: bool,
235}
236
237impl Server {
238 fn start(command: &[String], repo: &Path, port: u16) -> Result<Server> {
239 let dir = app::temp_dir("server")?;
240 let words: Vec<String> = command
241 .iter()
242 .map(|w| app::resolve_word(repo, &w.replace("{port}", &port.to_string())))
243 .collect();
244 let (program, rest) = words.split_first().context("empty command")?;
245 let log = dir.join("fallback.log");
246 let mut child = Command::new(program)
247 .args(rest)
248 .current_dir(repo)
249 .env("PORT", port.to_string())
250 .env(app::FALLBACK_ENV, &log)
251 .stdin(Stdio::null())
252 .stdout(std::fs::File::create(dir.join("stdout"))?)
253 .stderr(std::fs::File::create(dir.join("stderr"))?)
254 .spawn()
255 .with_context(|| format!("starting `{}`", command.join(" ")))?;
256 let deadline = Instant::now() + READY;
257 loop {
258 if TcpStream::connect_timeout(&local(port), Duration::from_millis(200)).is_ok() {
259 break;
260 }
261 let failure = if let Some(status) = child.try_wait()? {
262 Some(format!("exited ({status}) before listening"))
263 } else if Instant::now() > deadline {
264 Some(format!("did not listen within {}s", READY.as_secs()))
265 } else {
266 None
267 };
268 if let Some(failure) = failure {
269 let _ = child.kill();
270 let _ = child.wait();
271 let stderr = std::fs::read_to_string(dir.join("stderr")).unwrap_or_default();
272 let tail: Vec<&str> = stderr.lines().rev().take(15).collect();
273 let tail: Vec<&str> = tail.into_iter().rev().collect();
274 let _ = std::fs::remove_dir_all(&dir);
275 bail!(
276 "`{}` {failure} on port {port}{}",
277 command.join(" "),
278 if tail.is_empty() {
279 String::new()
280 } else {
281 format!(":\n{}", tail.join("\n"))
282 }
283 );
284 }
285 std::thread::sleep(Duration::from_millis(50));
286 }
287 Ok(Server {
288 child,
289 port,
290 dir,
291 log,
292 stopped: false,
293 })
294 }
295
296 fn fallbacks(&self) -> Option<usize> {
297 std::fs::read_to_string(&self.log)
298 .ok()
299 .map(|t| t.lines().count())
300 }
301
302 fn stop(&mut self) {
303 if self.stopped {
304 return;
305 }
306 self.stopped = true;
307 #[cfg(unix)]
308 {
309 let _ = Command::new("kill")
310 .args(["-TERM", &self.child.id().to_string()])
311 .stderr(Stdio::null())
312 .status();
313 let deadline = Instant::now() + Duration::from_secs(5);
314 while Instant::now() < deadline {
315 if let Ok(Some(_)) = self.child.try_wait() {
316 break;
317 }
318 std::thread::sleep(Duration::from_millis(20));
319 }
320 }
321 let _ = self.child.kill();
322 let _ = self.child.wait();
323 let _ = std::fs::remove_dir_all(&self.dir);
324 }
325}
326
327impl Drop for Server {
328 fn drop(&mut self) {
329 self.stop();
330 }
331}
332
333type Answer = (std::result::Result<Resp, String>, Option<bool>);
334
335fn run_all(
337 command: &[String],
338 repo: &Path,
339 port: u16,
340 reqs: &[&Req],
341 timeout: Duration,
342) -> Result<Vec<Answer>> {
343 let mut server = Server::start(command, repo, port)?;
344 let mut out = Vec::new();
345 for req in reqs {
346 let before = server.fallbacks().unwrap_or(0);
347 let resp = send(server.port, req, timeout).map_err(|e| format!("{e:#}"));
348 let fell_back = server.fallbacks().map(|after| after > before);
349 out.push((resp, fell_back));
350 }
351 server.stop();
352 Ok(out)
353}
354
355fn percent_decode(text: &str) -> String {
356 let bytes = text.as_bytes();
357 let mut out = Vec::new();
358 let mut i = 0;
359 while i < bytes.len() {
360 if bytes[i] == b'%'
361 && let Some(hex) = text.get(i + 1..i + 3)
362 && let Ok(b) = u8::from_str_radix(hex, 16)
363 {
364 out.push(b);
365 i += 3;
366 continue;
367 }
368 out.push(bytes[i]);
369 i += 1;
370 }
371 String::from_utf8_lossy(&out).into_owned()
372}
373
374fn percent_encode(text: &str) -> String {
375 let mut out = String::new();
376 for b in text.bytes() {
377 if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
378 out.push(char::from(b));
379 } else {
380 out += &format!("%{b:02X}");
381 }
382 }
383 out
384}
385
386fn parse_curl(line: &str, repo: &Path, doc_dir: &Path) -> Option<Req> {
387 let toks = app::shell_tokens(line)?;
388 if toks.iter().any(|t| t.op) {
389 return None;
390 }
391 let words: Vec<String> = toks.into_iter().map(|t| t.text).collect();
392 let (first, args) = words.split_first()?;
393 if first != "curl" {
394 return None;
395 }
396 let mut method: Option<String> = None;
397 let mut headers = BTreeMap::new();
398 let mut data: Vec<String> = Vec::new();
399 let mut url: Option<String> = None;
400 let mut i = 0;
401 let read_file = |name: &str| -> Option<String> {
402 let name = name.strip_prefix('@')?;
403 [repo.join(name), doc_dir.join(name)]
404 .iter()
405 .find(|p| p.is_file())
406 .and_then(|p| std::fs::read_to_string(p).ok())
407 };
408 while i < args.len() {
409 let arg = &args[i];
410 let mut next = || -> Option<String> {
411 i += 1;
412 args.get(i).cloned()
413 };
414 match arg.as_str() {
415 "-X" | "--request" => method = Some(next()?),
416 "-H" | "--header" => {
417 let h = next()?;
418 let (k, v) = h.split_once(':')?;
419 headers.insert(k.trim().to_string(), v.trim().to_string());
420 }
421 "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" => {
422 let d = next()?;
423 data.push(if d.starts_with('@') && arg != "--data-raw" {
424 read_file(&d)?
425 } else {
426 d
427 });
428 }
429 "--json" => {
430 let d = next()?;
431 data.push(if d.starts_with('@') {
432 read_file(&d)?
433 } else {
434 d
435 });
436 headers
437 .entry("Content-Type".to_string())
438 .or_insert_with(|| "application/json".to_string());
439 headers
440 .entry("Accept".to_string())
441 .or_insert_with(|| "application/json".to_string());
442 }
443 "-A" | "--user-agent" => {
444 headers.insert("User-Agent".to_string(), next()?);
445 }
446 "-b" | "--cookie" => {
447 headers.insert("Cookie".to_string(), next()?);
448 }
449 "-e" | "--referer" => {
450 headers.insert("Referer".to_string(), next()?);
451 }
452 "-o" | "--output" | "-w" | "--write-out" | "-m" | "--max-time"
453 | "--connect-timeout" => {
454 next()?;
455 }
456 "--silent"
457 | "--show-error"
458 | "--include"
459 | "--verbose"
460 | "--location"
461 | "--fail"
462 | "--insecure"
463 | "--no-progress-meter" => {}
464 other if other.starts_with("-X") && other.len() > 2 => {
465 method = Some(other[2..].to_string());
466 }
467 other if other.starts_with("-H") && other.len() > 2 => {
468 let (k, v) = other[2..].split_once(':')?;
469 headers.insert(k.trim().to_string(), v.trim().to_string());
470 }
471 other
472 if other.starts_with('-')
473 && other.len() > 1
474 && !other.starts_with("--")
475 && other[1..].chars().all(|c| "sSivLfk".contains(c)) => {}
476 other if other.starts_with('-') => return None,
477 other => url = Some(other.to_string()),
478 }
479 i += 1;
480 }
481 let url = url?;
482 let (scheme, rest) = url.split_once("://").unwrap_or(("http", &url));
483 if !matches!(scheme, "http" | "https") {
484 return None;
485 }
486 let rest = rest.split('#').next()?;
487 let (host, target) = rest.split_at(rest.find(['/', '?']).unwrap_or(rest.len()));
488 let path = if target.starts_with('/') {
489 target.to_string()
490 } else {
491 format!("/{target}")
492 };
493 let host = if host.starts_with('[') {
494 host.split_inclusive(']').next().unwrap_or(host)
495 } else {
496 host.split(':').next().unwrap_or(host)
497 };
498 if !LOCAL_HOSTS.contains(&host) {
499 return None;
500 }
501 let body = (!data.is_empty()).then(|| data.join("&"));
502 if body.is_some()
503 && !headers
504 .keys()
505 .any(|k| k.eq_ignore_ascii_case("content-type"))
506 {
507 headers.insert(
508 "Content-Type".to_string(),
509 "application/x-www-form-urlencoded".to_string(),
510 );
511 }
512 let method = method.unwrap_or_else(|| if body.is_some() { "POST" } else { "GET" }.to_string());
513 Some(Req {
514 method,
515 path,
516 headers,
517 body,
518 })
519}
520
521fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Req)>> {
522 let text =
523 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
524 let mut out = Vec::new();
525 for (n, line) in text.lines().enumerate() {
526 if line.trim().is_empty() {
527 continue;
528 }
529 let input: HttpInput = serde_json::from_str(line).with_context(|| {
530 format!(
531 "{}:{}: expected {{\"method\", \"path\", \"headers\": {{...}}, \"body\"}}",
532 path.display(),
533 n + 1
534 )
535 })?;
536 ensure!(
537 input.req.path.starts_with('/'),
538 "{}:{}: `path` must start with /",
539 path.display(),
540 n + 1
541 );
542 out.push((input.name, input.req));
543 }
544 Ok(out)
545}
546
547fn trap_values(raw: &str) -> Vec<&'static str> {
548 if raw.parse::<i128>().is_ok() {
549 app::INT_TRAPS.to_vec()
550 } else if raw.parse::<f64>().is_ok() && raw.contains(['.', 'e', 'E']) {
551 app::FLOAT_TRAPS.to_vec()
552 } else {
553 app::STRING_TRAPS.to_vec()
554 }
555}
556
557fn traps(bases: &[Req]) -> Vec<Req> {
558 let mut out = Vec::new();
559 for base in bases {
560 let (path, query) = match base.path.split_once('?') {
561 Some((p, q)) => (p, Some(q)),
562 None => (base.path.as_str(), None),
563 };
564 let segments: Vec<&str> = path.split('/').collect();
565 for i in 2..segments.len() {
566 let raw = percent_decode(segments[i]);
567 for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
568 let mut parts: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
569 parts[i] = percent_encode(v);
570 let mut req = base.clone();
571 req.path = parts.join("/") + &query.map(|q| format!("?{q}")).unwrap_or_default();
572 out.push(req);
573 }
574 }
575 if let Some(query) = query {
576 let pairs: Vec<&str> = query.split('&').collect();
577 for (i, pair) in pairs.iter().enumerate() {
578 let Some((key, raw)) = pair.split_once('=') else {
579 continue;
580 };
581 let raw = percent_decode(raw);
582 for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
583 let mut new: Vec<String> = pairs.iter().map(|p| p.to_string()).collect();
584 new[i] = format!("{key}={}", percent_encode(v));
585 let mut req = base.clone();
586 req.path = format!("{path}?{}", new.join("&"));
587 out.push(req);
588 }
589 }
590 }
591 if let Some(body) = &base.body {
592 let json =
593 serde_json::from_str::<Value>(body).is_ok_and(|v| v.is_object() || v.is_array());
594 let values: &[&str] = if json {
595 &app::JSON_TRAPS
596 } else {
597 &app::STDIN_TRAPS
598 };
599 for v in values {
600 let mut req = base.clone();
601 req.body = Some(v.to_string());
602 out.push(req);
603 }
604 }
605 }
606 out.push(Req {
607 method: "GET".to_string(),
608 path: "/rust-anything-missing".to_string(),
609 headers: BTreeMap::new(),
610 body: None,
611 });
612 out.truncate(app::MAX_TRAPS);
613 out
614}
615
616fn case_slug(req: &Req) -> String {
617 let first = req
618 .path
619 .split(['/', '?'])
620 .find(|s| !s.is_empty())
621 .unwrap_or("root");
622 app::slug(&format!("{} {first}", req.method))
623}
624
625fn settle_headers(
626 norm: &Normalizers,
627 a: &BTreeMap<String, String>,
628 b: &BTreeMap<String, String>,
629) -> (BTreeMap<String, String>, bool) {
630 let mut out = BTreeMap::new();
631 let mut noisy = false;
632 for (k, va) in a {
633 if SKIP_HEADERS.contains(&k.as_str()) {
634 continue;
635 }
636 let Some(vb) = b.get(k) else {
637 noisy = true;
638 continue;
639 };
640 let (va, vb) = (norm.apply(va), norm.apply(vb));
641 if va == vb {
642 out.insert(k.clone(), va);
643 } else {
644 noisy = true;
645 out.insert(k.clone(), app::merge_line(&va, &vb));
646 }
647 }
648 noisy |= b
649 .keys()
650 .any(|k| !a.contains_key(k) && !SKIP_HEADERS.contains(&k.as_str()));
651 (out, noisy)
652}
653
654fn table(entries: &BTreeMap<String, String>) -> Table {
655 let mut t = Table::new();
656 for (k, v) in entries {
657 t[k.as_str()] = value(v.as_str());
658 }
659 t
660}
661
662fn write_case(
663 dir: &Path,
664 name: &str,
665 req: &Req,
666 status: u16,
667 headers: &BTreeMap<String, String>,
668 body: &[u8],
669 binary: bool,
670) -> Result<()> {
671 let mut doc = DocumentMut::new();
672 let mut request = Table::new();
673 request["method"] = value(req.method.as_str());
674 request["path"] = value(req.path.as_str());
675 if let Some(body) = &req.body {
676 request["body"] = value(body.as_str());
677 }
678 if !req.headers.is_empty() {
679 request.insert("headers", Item::Table(table(&req.headers)));
680 }
681 doc.insert("request", Item::Table(request));
682 let mut response = Table::new();
683 response["status"] = value(i64::from(status));
684 if binary {
685 response["binary"] = value(true);
686 }
687 if !headers.is_empty() {
688 response.insert("headers", Item::Table(table(headers)));
689 }
690 doc.insert("response", Item::Table(response));
691 std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
692 std::fs::write(dir.join(format!("{name}.body")), body)?;
693 Ok(())
694}
695
696pub(crate) fn record(
697 repo: &Path,
698 config: &Config,
699 norm: &Normalizers,
700 opts: &RecordOptions,
701) -> Result<RecordOutcome> {
702 let examples = app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir));
703 let inputs = match opts.inputs {
704 Some(path) => read_inputs(path)?,
705 None => Vec::new(),
706 };
707 let mut planned: Vec<(String, Req)> = Vec::new();
708 let mut seen = BTreeSet::new();
709 let mut counts = [0usize; 3];
710 let mut bases = Vec::new();
711 let mut push = |kind: usize, given: Option<String>, req: Req| -> bool {
712 let key = serde_json::to_string(&req).unwrap_or_default();
713 if !seen.insert(key) {
714 return false;
715 }
716 counts[kind] += 1;
717 let prefix = ["example", "input", "trap"][kind];
718 let name = match given.map(|g| app::slug(&g)).filter(|g| !g.is_empty()) {
719 Some(g) => g,
720 None => format!("{prefix}-{:03}-{}", counts[kind], case_slug(&req)),
721 };
722 planned.push((name, req));
723 true
724 };
725 for req in examples {
726 if push(0, None, req.clone()) {
727 bases.push(req);
728 }
729 }
730 for (given, req) in inputs {
731 if push(1, given, req.clone()) {
732 bases.push(req);
733 }
734 }
735 if bases.is_empty() {
736 let root = Req {
737 method: "GET".to_string(),
738 path: "/".to_string(),
739 headers: BTreeMap::new(),
740 body: None,
741 };
742 push(0, None, root.clone());
743 bases.push(root);
744 }
745 if opts.traps {
746 for req in traps(&bases) {
747 push(2, None, req);
748 }
749 }
750 planned.sort_by(|a, b| a.0.cmp(&b.0));
751
752 let timeout = Duration::from_secs(config.timeout_secs);
753 let fixed = config.http.as_ref().and_then(|h| h.port);
754 let reqs: Vec<&Req> = planned.iter().map(|(_, r)| r).collect();
755 let one = run_all(
756 &config.run,
757 repo,
758 fixed.map_or_else(free_port, Ok)?,
759 &reqs,
760 timeout,
761 )?;
762 let two = run_all(
763 &config.run,
764 repo,
765 fixed.map_or_else(free_port, Ok)?,
766 &reqs,
767 timeout,
768 )?;
769
770 let dir = app::cases_dir(repo).join(HTTP_DIR);
771 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
772 let mut outcome = RecordOutcome {
773 dir: dir.clone(),
774 run: config.run.clone(),
775 cases: 0,
776 examples: counts[0],
777 inputs: counts[1],
778 traps: counts[2],
779 noisy: Vec::new(),
780 noise: Vec::new(),
781 unstable: Vec::new(),
782 timed_out: Vec::new(),
783 };
784 for (((name, req), (a, _)), (b, _)) in planned.iter().zip(one).zip(two) {
785 let (Ok(a), Ok(b)) = (a, b) else {
786 outcome.timed_out.push(name.clone());
787 continue;
788 };
789 let (body, body_noise, binary) = app::settle_text(norm, &a.body, &b.body);
790 let (headers, header_noisy) = settle_headers(norm, &a.headers, &b.headers);
791 write_case(&dir, name, req, a.status, &headers, &body, binary)?;
792 outcome.cases += 1;
793 if body_noise.is_some() || header_noisy {
794 outcome.noisy.push(name.clone());
795 }
796 for (field, kind) in [
797 ("body", body_noise),
798 ("headers", header_noisy.then_some(app::NoiseKind::Values)),
799 ] {
800 if let Some(kind) = kind {
801 outcome.noise.push(app::Noise {
802 case: name.clone(),
803 field: field.to_string(),
804 kind,
805 });
806 }
807 }
808 if a.status != b.status || (binary && body_noise.is_some()) {
809 outcome.unstable.push(name.clone());
810 }
811 }
812 Ok(outcome)
813}
814
815struct Spec {
816 name: String,
817 req: Req,
818 status: u16,
819 headers: BTreeMap<String, String>,
820 body: Option<Vec<u8>>,
821 binary: bool,
822}
823
824fn strings(item: Option<&Item>) -> BTreeMap<String, String> {
825 item.and_then(Item::as_table_like)
826 .map(|t| {
827 t.iter()
828 .map(|(k, v)| (k.to_string(), v.as_str().unwrap_or_default().to_string()))
829 .collect()
830 })
831 .unwrap_or_default()
832}
833
834fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
835 let name = path
836 .file_stem()
837 .map(|s| s.to_string_lossy().into_owned())
838 .unwrap_or_default();
839 let doc: DocumentMut = std::fs::read_to_string(path)
840 .with_context(|| format!("reading {}", path.display()))?
841 .parse()
842 .with_context(|| format!("parsing {}", path.display()))?;
843 let request = doc.get("request").context("no [request]")?;
844 let response = doc.get("response").context("no [response]")?;
845 let body_file = dir.join(format!("{name}.body"));
846 Ok(Spec {
847 req: Req {
848 method: request
849 .get("method")
850 .and_then(Item::as_str)
851 .unwrap_or("GET")
852 .to_string(),
853 path: request
854 .get("path")
855 .and_then(Item::as_str)
856 .with_context(|| format!("{}: no request.path", path.display()))?
857 .to_string(),
858 headers: strings(request.get("headers")),
859 body: request
860 .get("body")
861 .and_then(Item::as_str)
862 .map(str::to_string),
863 },
864 status: response
865 .get("status")
866 .and_then(Item::as_integer)
867 .and_then(|s| u16::try_from(s).ok())
868 .with_context(|| format!("{}: no response.status", path.display()))?,
869 headers: strings(response.get("headers")),
870 body: if body_file.exists() {
871 Some(std::fs::read(&body_file)?)
872 } else {
873 None
874 },
875 binary: response
876 .get("binary")
877 .and_then(Item::as_bool)
878 .unwrap_or(false),
879 name,
880 })
881}
882
883pub(crate) fn recorded_routes(repo: &Path) -> Result<Vec<String>> {
885 let mut seen = BTreeSet::new();
886 let mut out = Vec::new();
887 for spec in load_specs(&app::cases_dir(repo).join(HTTP_DIR))? {
888 let path = spec.req.path.split('?').next().unwrap_or("/").to_string();
889 let route = format!("{} {path}", spec.req.method);
890 if seen.insert(route.clone()) {
891 out.push(route);
892 }
893 }
894 Ok(out)
895}
896
897fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
898 let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
899 .with_context(|| {
900 format!(
901 "no HTTP cases in {}: run `rust-anything app record` first",
902 dir.display()
903 )
904 })?
905 .flatten()
906 .map(|e| e.path())
907 .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
908 .collect();
909 paths.sort();
910 let specs = paths
911 .iter()
912 .map(|p| load_spec(dir, p))
913 .collect::<Result<Vec<_>>>()?;
914 ensure!(!specs.is_empty(), "no HTTP cases in {}", dir.display());
915 Ok(specs)
916}
917
918pub(crate) fn replay(
919 repo: &Path,
920 config: &Config,
921 norm: &Normalizers,
922 command: &[String],
923 port: Option<u16>,
924 case: Option<&str>,
925 timeout: Duration,
926) -> Result<ReplayOutcome> {
927 let dir = app::cases_dir(repo);
928 let specs = app::only_case(load_specs(&dir.join(HTTP_DIR))?, case, |s| &s.name)?;
929 let port = match port.or(config.http.as_ref().and_then(|h| h.port)) {
930 Some(p) => p,
931 None => free_port()?,
932 };
933 let reqs: Vec<&Req> = specs.iter().map(|s| &s.req).collect();
934 let answers = run_all(command, repo, port, &reqs, timeout)?;
935 let mut outcome = ReplayOutcome {
936 build: command.to_vec(),
937 passed: 0,
938 total: 0,
939 skipped: 0,
940 failures: Vec::new(),
941 fallback: None,
942 report: dir.join(app::REPORT_FILE),
943 };
944 let (mut reported, mut fell_back) = (false, Vec::new());
945 for (spec, (answer, fallback)) in specs.iter().zip(answers) {
946 outcome.total += 1;
947 reported |= fallback.is_some();
948 if fallback == Some(true) {
949 fell_back.push(spec.name.clone());
950 }
951 let mut problems = Vec::new();
952 match answer {
953 Err(e) => problems.push(Problem {
954 field: "response".to_string(),
955 detail: format!("no response: {e}\n"),
956 }),
957 Ok(resp) => {
958 if resp.status != spec.status {
959 problems.push(Problem {
960 field: "status".to_string(),
961 detail: format!("expected {}, got {}\n", spec.status, resp.status),
962 });
963 }
964 for (k, expected) in &spec.headers {
965 let field = format!("header {k}");
966 let key = k.to_ascii_lowercase();
967 match resp.headers.get(&key) {
968 None => problems.push(Problem {
969 field,
970 detail: format!("- {expected}\n(missing)\n"),
971 }),
972 Some(actual) => {
973 let (e, a) = (norm.apply(expected), norm.apply(actual));
974 if !app::line_matches(&e, &a) {
975 problems.push(Problem {
976 field,
977 detail: format!("- {e}\n+ {a}\n"),
978 });
979 }
980 }
981 }
982 }
983 if let Some(expected) = &spec.body
984 && let Some(detail) = app::compare(
985 norm,
986 expected,
987 &resp.body,
988 spec.binary,
989 norm.unordered(&spec.name, "body"),
990 )
991 {
992 problems.push(Problem {
993 field: "body".to_string(),
994 detail,
995 });
996 }
997 }
998 }
999 if problems.is_empty() {
1000 outcome.passed += 1;
1001 } else {
1002 outcome.failures.push(Failure {
1003 case: spec.name.clone(),
1004 args: vec![spec.req.method.clone(), spec.req.path.clone()],
1005 problems,
1006 });
1007 }
1008 }
1009 if reported {
1010 outcome.fallback = Some(Fallback {
1011 cases: fell_back.len(),
1012 total: outcome.total,
1013 rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
1014 names: fell_back,
1015 });
1016 }
1017 std::fs::write(&outcome.report, app::report_markdown(&outcome))
1018 .with_context(|| format!("writing {}", outcome.report.display()))?;
1019 Ok(outcome)
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024 use super::*;
1025
1026 #[test]
1027 fn curl_lines_become_requests() {
1028 let here = Path::new(".");
1029 let r = parse_curl(
1030 "curl -sS -X POST -H 'Content-Type: text/plain' -d 'hello world' http://localhost:8080/upper?x=1",
1031 here,
1032 here,
1033 )
1034 .unwrap();
1035 assert_eq!(r.method, "POST");
1036 assert_eq!(r.path, "/upper?x=1");
1037 assert_eq!(r.body.as_deref(), Some("hello world"));
1038 assert_eq!(r.headers["Content-Type"], "text/plain");
1039 let g = parse_curl("curl 127.0.0.1:3000", here, here).unwrap();
1040 assert_eq!((g.method.as_str(), g.path.as_str()), ("GET", "/"));
1041 let form = parse_curl("curl -d a=1 http://[::1]:80/f", here, here).unwrap();
1042 assert_eq!(form.method, "POST");
1043 assert_eq!(
1044 form.headers["Content-Type"],
1045 "application/x-www-form-urlencoded"
1046 );
1047 assert!(parse_curl("curl https://example.com/x", here, here).is_none());
1048 let query = parse_curl("curl 'http://localhost?x=y#section'", here, here).unwrap();
1049 assert_eq!(query.path, "/?x=y");
1050 let fragment = parse_curl("curl 'http://[::1]:8080/path#section'", here, here).unwrap();
1051 assert_eq!(fragment.path, "/path");
1052 assert!(parse_curl("curl ftp://localhost/file", here, here).is_none());
1053 assert!(parse_curl("curl --unknown x http://localhost/", here, here).is_none());
1054 assert!(parse_curl("curl http://localhost/ | jq .", here, here).is_none());
1055 }
1056
1057 #[test]
1058 fn informational_responses_do_not_replace_the_final_response() {
1059 let raw = b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 103 Early Hints\r\nLink: </app.js>\r\n\r\nHTTP/1.1 201 Created\r\nContent-Length: 2\r\n\r\nok";
1060 let response = read_response(&mut &raw[..], false).unwrap();
1061 assert_eq!(response.status, 201);
1062 assert_eq!(response.body, b"ok");
1063 assert!(!response.headers.contains_key("link"));
1064
1065 let switching = b"HTTP/1.1 101 Switching Protocols\r\n\r\n";
1066 assert_eq!(
1067 read_response(&mut &switching[..], false).unwrap().status,
1068 101
1069 );
1070 }
1071
1072 #[test]
1073 fn responses_parse_with_length_chunks_or_close() {
1074 let fixed =
1075 b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
1076 let r = read_response(&mut &fixed[..], false).unwrap();
1077 assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));
1078 assert_eq!(r.headers["content-type"], "text/plain");
1079 let chunked = b"HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nnot \r\n5;x=y\r\nfound\r\n0\r\n\r\n";
1080 let r = read_response(&mut &chunked[..], false).unwrap();
1081 assert_eq!((r.status, r.body.as_slice()), (404, &b"not found"[..]));
1082 let close = b"HTTP/1.0 500 Oops\r\n\r\nbye";
1083 assert_eq!(read_response(&mut &close[..], false).unwrap().body, b"bye");
1084 }
1085
1086 #[test]
1087 fn malformed_http_chunks_are_errors() {
1088 let mut bad_ending = &b"1\r\naXX0\r\n\r\n"[..];
1089 assert!(read_chunked(&mut bad_ending, Vec::new()).is_err());
1090 let max = format!("{:x}\r\n", usize::MAX);
1091 assert!(read_chunked(&mut max.as_bytes(), Vec::new()).is_err());
1092 let mut truncated = &b"1\r\na\r\n0\r\n"[..];
1093 assert!(read_chunked(&mut truncated, Vec::new()).is_err());
1094 let mut trailers = &b"1\r\na\r\n0\r\nX-Trailer: present\r\n\r\n"[..];
1095 assert_eq!(read_chunked(&mut trailers, Vec::new()).unwrap(), b"a");
1096 }
1097
1098 #[test]
1099 fn interrupted_close_delimited_body_is_an_error() {
1100 struct BrokenBody;
1101
1102 impl Read for BrokenBody {
1103 fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
1104 Err(std::io::ErrorKind::TimedOut.into())
1105 }
1106 }
1107
1108 let response = &b"HTTP/1.0 200 OK\r\n\r\npartial"[..];
1109 assert!(read_response(&mut response.chain(BrokenBody), false).is_err());
1110 }
1111
1112 #[test]
1113 fn traps_change_path_segments_queries_and_bodies() {
1114 let base = Req {
1115 method: "POST".into(),
1116 path: "/div/7/2?name=bob".into(),
1117 headers: BTreeMap::new(),
1118 body: Some("{\"a\":1}".into()),
1119 };
1120 let t = traps(&[base]);
1121 assert!(t.iter().any(|r| r.path == "/div/-7/2?name=bob"));
1122 assert!(t.iter().any(|r| r.path == "/div/7/0?name=bob"));
1123 assert!(
1124 t.iter()
1125 .any(|r| r.path == "/div/7/2?name=%F0%9F%91%8D%F0%9F%8F%BD%20thumbs")
1126 );
1127 assert!(
1128 t.iter()
1129 .all(|r| r.path.starts_with("/div/") || r.path == "/rust-anything-missing")
1130 );
1131 assert!(
1132 t.iter()
1133 .any(|r| r.body.as_deref() == Some(app::JSON_TRAPS[0]))
1134 );
1135 assert_eq!(percent_decode("a%20b%zz"), "a b%zz");
1136 }
1137}