Skip to main content

rust_anything/
app_shadow.rs

1//! `app shadow`: a proxy in front of a server and a build. Every request is answered by the
2//! original; the build gets the same request afterwards and its answer is compared. The build's
3//! outbound HTTP and mail go to local sinks and its files to a fresh copy, so no side effect
4//! happens twice. Mismatches are logged as shapes, never values.
5
6use std::collections::BTreeSet;
7use std::io::Write;
8use std::net::{SocketAddr, TcpListener, ToSocketAddrs};
9use std::path::{Path, PathBuf};
10use std::time::Duration;
11
12use anyhow::{Context, Result, bail, ensure};
13use serde::Serialize;
14
15use crate::app::{self, Config, Failure, Normalizers, Problem};
16use crate::effects::EffectsConfig;
17use crate::http::{self, Launch, Req, Resp, Server};
18use crate::mismatch::{At, Group, text_at};
19use crate::walk::Canonical;
20
21pub const SHADOW_DIR: &str = "shadow";
22pub const MISMATCHES_FILE: &str = "mismatches.jsonl";
23pub const INPUTS_FILE: &str = "inputs.jsonl";
24
25/// What a running shadow reports as it goes.
26pub enum Event<'a> {
27    /// The proxy accepts requests at this address.
28    Listening(SocketAddr),
29    /// The build answered a request differently.
30    Mismatch(&'a Failure),
31}
32
33pub struct ShadowOptions<'a> {
34    pub repo: &'a Path,
35    /// Command line of the build to compare.
36    pub build: &'a str,
37    /// The port the proxy listens on; a free one when `None`.
38    pub listen: Option<u16>,
39    /// `HOST:PORT` of an original that is already running; the saved command starts one when
40    /// `None`.
41    pub upstream: Option<&'a str>,
42    /// Stop after this many requests; run until stopped when `None`.
43    pub requests: Option<usize>,
44    pub timeout_secs: Option<u64>,
45    /// Append each mismatching request to `shadow/inputs.jsonl`.
46    pub keep: bool,
47    pub progress: Option<&'a dyn Fn(Event)>,
48}
49
50#[derive(Debug, Serialize)]
51pub struct ShadowOutcome {
52    pub requests: usize,
53    pub matched: usize,
54    /// One per mismatching request, as shapes: the path is hashed and no value is kept.
55    pub mismatches: Vec<Failure>,
56    /// The distinct differences among the mismatches, most requests first.
57    #[serde(skip_serializing_if = "Vec::is_empty")]
58    pub groups: Vec<Group>,
59    pub log: PathBuf,
60    /// The kept requests (`--keep`), in `app record --inputs` format.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub inputs: Option<PathBuf>,
63}
64
65/// FNV-1a, 64 bits, as hex.
66fn hash(text: &str) -> String {
67    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
68    for b in text.bytes() {
69        hash ^= u64::from(b);
70        hash = hash.wrapping_mul(0x0100_0000_01b3);
71    }
72    format!("{hash:016x}")
73}
74
75/// The effects the build runs with: the saved ones, with both sinks on and no database
76/// commands, which would reach the original's database.
77fn sinks_for(saved: Option<&EffectsConfig>) -> EffectsConfig {
78    let mut config = saved.cloned().unwrap_or_default();
79    if !config.smtp {
80        config.smtp_parts = true;
81    }
82    config.http = true;
83    config.smtp = true;
84    config.db_reset = None;
85    config.db_dump = None;
86    config
87}
88
89/// A problem as its shape: where the answers part, with no value kept.
90fn shape(field: impl Into<String>, mut at: At) -> Problem {
91    at.context = None;
92    let mut problem = Problem::new(field, String::new()).at(at);
93    problem.detail = problem
94        .at
95        .as_ref()
96        .map(|at| format!("{}\n", at.shape()))
97        .unwrap_or_default();
98    problem
99}
100
101/// What differs between the original's answer and the build's, as shapes: status codes, header
102/// names, where the body first differs and its size.
103fn compare(
104    norm: &Normalizers,
105    noisy: &BTreeSet<String>,
106    original: &Resp,
107    build: &Resp,
108) -> Vec<Problem> {
109    let mut problems = Vec::new();
110    if original.status != build.status {
111        problems.push(shape(
112            "status",
113            At::new(&format!("{}→{}", original.status, build.status)),
114        ));
115    }
116    for (k, expected) in &original.headers {
117        if http::is_skipped_header(k) {
118            continue;
119        }
120        let at = match build.headers.get(k) {
121            None => At::new("missing key"),
122            Some(_) if noisy.contains(k) => continue,
123            Some(actual) => {
124                let (e, a) = (norm.apply(expected), norm.apply(actual));
125                if app::line_matches(&e, &a) {
126                    continue;
127                }
128                text_at("text", e.split("[..]").next().unwrap_or_default(), &a)
129            }
130        };
131        problems.push(shape(format!("header {k}"), at));
132    }
133    if app::compare(norm, &original.body, &build.body, false, false).is_some() {
134        let at = app::locate(norm, &original.body, &build.body, false, false);
135        problems.push(shape("body", at));
136    }
137    problems
138}
139
140fn append(path: &Path, line: &str) -> Result<()> {
141    let mut file = std::fs::OpenOptions::new()
142        .create(true)
143        .append(true)
144        .open(path)
145        .with_context(|| format!("opening {}", path.display()))?;
146    writeln!(file, "{line}").with_context(|| format!("writing {}", path.display()))
147}
148
149fn upstream_addr(text: &str) -> Result<SocketAddr> {
150    text.to_socket_addrs()
151        .with_context(|| format!("--upstream `{text}`: give HOST:PORT"))?
152        .next()
153        .with_context(|| format!("--upstream `{text}`: no address"))
154}
155
156pub fn shadow(opts: &ShadowOptions) -> Result<ShadowOutcome> {
157    app::check_timeout(opts.timeout_secs)?;
158    ensure!(opts.requests != Some(0), "--requests must be at least 1");
159    let repo = opts
160        .repo
161        .canonical()
162        .with_context(|| format!("no folder {}", opts.repo.display()))?;
163    let dir = app::cases_dir(&repo);
164    let Some(config) = Config::load(&repo)? else {
165        bail!(
166            "no {} in {}: record the server first (`rust-anything app record --http`)",
167            app::CONFIG_FILE,
168            dir.display()
169        );
170    };
171    let Some(http_config) = config.http.clone() else {
172        bail!(
173            "the recording in {} is a CLI's: `app shadow` covers servers only",
174            dir.display()
175        );
176    };
177    let command = app::shell_split(opts.build)?;
178    ensure!(!command.is_empty(), "the build command is empty");
179    let norm = Normalizers::new(&config)?;
180    let timeout_secs = opts.timeout_secs.unwrap_or(config.timeout_secs);
181    ensure!(
182        timeout_secs >= 1,
183        "--timeout must be at least 1 second (saved timeout_secs in {} is 0)",
184        app::CONFIG_FILE
185    );
186    let timeout = Duration::from_secs(timeout_secs);
187    let noisy = http::noisy_headers(&repo);
188    let ready = http::ready_timeout(&http_config);
189
190    let listener = TcpListener::bind(("127.0.0.1", opts.listen.unwrap_or(0)))
191        .with_context(|| format!("listening on port {}", opts.listen.unwrap_or(0)))?;
192    let original = match opts.upstream {
193        Some(text) => (None, upstream_addr(text)?),
194        None => {
195            let launch = Launch {
196                args: &http_config.args,
197                files: None,
198                pace: None,
199                effects: None,
200                ready,
201            };
202            let server = match http_config.port {
203                Some(port) => Server::start(&config.run, &launch, &repo, port),
204                None => http::start_ephemeral(&config.run, &launch, &repo, http::free_port),
205            }
206            .context("starting the original (--upstream uses one that is already running)")?;
207            let addr = server.addr;
208            (Some(server), addr)
209        }
210    };
211    let (_original_server, upstream) = original;
212    let scratch = app::temp_dir("shadow")?;
213    let files = http::snapshot_to(&repo, &http_config.fresh, &scratch.join("files"))?;
214    let sinks = sinks_for(config.effects.as_ref());
215    let launch = Launch {
216        args: &http_config.args,
217        files: files.as_deref(),
218        pace: None,
219        effects: Some(&sinks),
220        ready,
221    };
222    let build = http::start_ephemeral(&command, &launch, &repo, http::free_port)
223        .context("starting the build")?;
224
225    let shadow_dir = dir.join(SHADOW_DIR);
226    std::fs::create_dir_all(&shadow_dir)
227        .with_context(|| format!("creating {}", shadow_dir.display()))?;
228    let mut outcome = ShadowOutcome {
229        requests: 0,
230        matched: 0,
231        mismatches: Vec::new(),
232        groups: Vec::new(),
233        log: shadow_dir.join(MISMATCHES_FILE),
234        inputs: opts.keep.then(|| shadow_dir.join(INPUTS_FILE)),
235    };
236    if let Some(progress) = opts.progress {
237        progress(Event::Listening(listener.local_addr()?));
238    }
239    for client in listener.incoming() {
240        let Ok(mut client) = client else {
241            continue;
242        };
243        client.set_read_timeout(Some(timeout))?;
244        client.set_write_timeout(Some(timeout))?;
245        let Ok(req) = http::read_request(&mut client) else {
246            let _ = client.write_all(
247                b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
248            );
249            continue;
250        };
251        outcome.requests += 1;
252        match http::exchange(upstream, &req, timeout) {
253            Err(_) => {
254                let _ = client.write_all(
255                    b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
256                );
257            }
258            Ok((answer, raw)) => {
259                let _ = client.write_all(&raw);
260                drop(client);
261                let problems = match http::exchange(build.addr, &req, timeout) {
262                    Ok((built, _)) => compare(&norm, &noisy, &answer, &built),
263                    Err(_) => vec![shape("response", At::new("no response"))],
264                };
265                build.drain_effects(&repo);
266                if problems.is_empty() {
267                    outcome.matched += 1;
268                } else {
269                    let failure = mismatch(&req, problems);
270                    record(&outcome, &failure, &req)?;
271                    if let Some(progress) = opts.progress {
272                        progress(Event::Mismatch(&failure));
273                    }
274                    outcome.mismatches.push(failure);
275                }
276            }
277        }
278        if opts.requests.is_some_and(|n| outcome.requests >= n) {
279            break;
280        }
281    }
282    drop(build);
283    let _ = std::fs::remove_dir_all(&scratch);
284    outcome.groups = crate::mismatch::replay_groups(&outcome.mismatches);
285    Ok(outcome)
286}
287
288fn mismatch(req: &Req, problems: Vec<Problem>) -> Failure {
289    let path = hash(&req.path);
290    Failure {
291        case: format!("{} {path}", req.method),
292        args: vec![req.method.clone(), path],
293        problems,
294    }
295}
296
297/// Appends the mismatch's shape to the log and, with `--keep`, the request to the inputs.
298fn record(outcome: &ShadowOutcome, failure: &Failure, req: &Req) -> Result<()> {
299    append(&outcome.log, &serde_json::to_string(failure)?)?;
300    if let Some(inputs) = &outcome.inputs {
301        let mut kept = req.clone();
302        kept.headers.retain(|k, _| !k.eq_ignore_ascii_case("host"));
303        append(inputs, &serde_json::to_string(&kept)?)?;
304    }
305    Ok(())
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use std::collections::BTreeMap;
312
313    fn config(normalize: &[&str]) -> Config {
314        serde_json::from_value(serde_json::json!({
315            "schema": "rust-anything/app-cases@1",
316            "name": "server",
317            "run": ["node", "server.js"],
318            "normalize": normalize,
319        }))
320        .unwrap()
321    }
322
323    fn resp(status: u16, headers: &[(&str, &str)], body: &str) -> Resp {
324        Resp {
325            status,
326            headers: headers
327                .iter()
328                .map(|(k, v)| (k.to_string(), v.to_string()))
329                .collect::<BTreeMap<_, _>>(),
330            body: body.as_bytes().to_vec(),
331        }
332    }
333
334    fn fields(problems: &[Problem]) -> Vec<&str> {
335        problems.iter().map(|p| p.field.as_str()).collect()
336    }
337
338    #[test]
339    fn answers_compare_by_status_headers_and_body_as_shapes() {
340        let norm = Normalizers::new(&config(&["timestamps"])).unwrap();
341        let none = BTreeSet::new();
342        let a = resp(
343            200,
344            &[
345                ("content-type", "text/plain"),
346                ("date", "x"),
347                ("x-at", "2024-01-02T03:04:05Z"),
348            ],
349            "at 2024-01-02T03:04:05Z: secret\n",
350        );
351        let same = resp(
352            200,
353            &[
354                ("content-type", "text/plain"),
355                ("x-at", "2025-06-07T08:09:10Z"),
356            ],
357            "at 2025-06-07T08:09:10Z: secret\n",
358        );
359        assert!(compare(&norm, &none, &a, &same).is_empty());
360        let other = resp(500, &[("x-at", "2025-06-07T08:09:10Z")], "at 2025: oops\n");
361        let problems = compare(&norm, &none, &a, &other);
362        assert_eq!(fields(&problems), ["status", "header content-type", "body"]);
363        let text = format!("{problems:?}");
364        assert!(!text.contains("secret") && !text.contains("oops"), "{text}");
365        assert_eq!(problems[0].detail, "status (200→500)\n");
366        assert_eq!(problems[1].detail, "header content-type (missing key)\n");
367        assert_eq!(
368            problems[2].detail,
369            "body (text), line 1, column 4, char 3, length 16 expected, 14 got\n"
370        );
371    }
372
373    #[test]
374    fn a_header_the_original_varied_on_is_checked_for_presence_only() {
375        let norm = Normalizers::new(&config(&[])).unwrap();
376        let noisy: BTreeSet<String> = ["set-cookie".to_string()].into();
377        let a = resp(200, &[("set-cookie", "id=1")], "");
378        assert!(compare(&norm, &noisy, &a, &resp(200, &[("set-cookie", "id=2")], "")).is_empty());
379        assert_eq!(
380            fields(&compare(&norm, &noisy, &a, &resp(200, &[], ""))),
381            ["header set-cookie"]
382        );
383    }
384
385    #[test]
386    fn the_build_gets_both_sinks_and_no_database_commands() {
387        let saved = EffectsConfig::from_args(
388            &["smtp-raw".into()],
389            &["HOOK=http-url".into()],
390            Some("reset"),
391            Some("dump"),
392        )
393        .unwrap()
394        .unwrap();
395        let sinks = sinks_for(Some(&saved));
396        assert!(sinks.http && sinks.smtp && !sinks.smtp_parts);
397        assert_eq!(sinks.env["HOOK"], "http-url");
398        assert!(sinks.db_reset.is_none() && sinks.db_dump.is_none());
399        let fresh = sinks_for(None);
400        assert!(fresh.http && fresh.smtp && fresh.smtp_parts);
401    }
402
403    #[test]
404    fn a_mismatch_names_the_request_by_method_and_path_hash() {
405        let req = Req {
406            method: "GET".to_string(),
407            path: "/users/alice".to_string(),
408            headers: BTreeMap::new(),
409            body: None,
410            body_base64: None,
411            body_file: None,
412        };
413        let failure = mismatch(&req, Vec::new());
414        assert_eq!(failure.case, format!("GET {}", hash("/users/alice")));
415        assert_eq!(failure.case.len(), "GET ".len() + 16);
416        assert!(!format!("{failure:?}").contains("alice"));
417        assert_ne!(hash("/users/alice"), hash("/users/bob"));
418    }
419}