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