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                ready_request: http_config.ready_request.as_deref(),
202            };
203            let server = match http_config.port {
204                Some(port) => Server::start(&config.run, &launch, &repo, port),
205                None => http::start_ephemeral(&config.run, &launch, &repo, http::free_port),
206            }
207            .context("starting the original (--upstream uses one that is already running)")?;
208            let addr = server.addr;
209            (Some(server), addr)
210        }
211    };
212    let (_original_server, upstream) = original;
213    let scratch = app::temp_dir("shadow")?;
214    let files = http::snapshot_to(&repo, &http_config.fresh, &scratch.join("files"))?;
215    let sinks = sinks_for(config.effects.as_ref());
216    let launch = Launch {
217        args: &http_config.args,
218        files: files.as_deref(),
219        pace: None,
220        effects: Some(&sinks),
221        ready,
222        ready_request: http_config.ready_request.as_deref(),
223    };
224    let build = http::start_ephemeral(&command, &launch, &repo, http::free_port)
225        .context("starting the build")?;
226
227    let shadow_dir = dir.join(SHADOW_DIR);
228    std::fs::create_dir_all(&shadow_dir)
229        .with_context(|| format!("creating {}", shadow_dir.display()))?;
230    let mut outcome = ShadowOutcome {
231        requests: 0,
232        matched: 0,
233        mismatches: Vec::new(),
234        groups: Vec::new(),
235        log: shadow_dir.join(MISMATCHES_FILE),
236        inputs: opts.keep.then(|| shadow_dir.join(INPUTS_FILE)),
237    };
238    if let Some(progress) = opts.progress {
239        progress(Event::Listening(listener.local_addr()?));
240    }
241    for client in listener.incoming() {
242        let Ok(mut client) = client else {
243            continue;
244        };
245        client.set_read_timeout(Some(timeout))?;
246        client.set_write_timeout(Some(timeout))?;
247        let Ok(req) = http::read_request(&mut client) else {
248            let _ = client.write_all(
249                b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
250            );
251            continue;
252        };
253        outcome.requests += 1;
254        match http::exchange(upstream, &req, timeout) {
255            Err(_) => {
256                let _ = client.write_all(
257                    b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
258                );
259            }
260            Ok((answer, raw)) => {
261                let _ = client.write_all(&raw);
262                drop(client);
263                let problems = match http::exchange(build.addr, &req, timeout) {
264                    Ok((built, _)) => compare(&norm, &noisy, &answer, &built),
265                    Err(_) => vec![shape("response", At::new("no response"))],
266                };
267                build.drain_effects(&repo);
268                if problems.is_empty() {
269                    outcome.matched += 1;
270                } else {
271                    let failure = mismatch(&req, problems);
272                    record(&outcome, &failure, &req)?;
273                    if let Some(progress) = opts.progress {
274                        progress(Event::Mismatch(&failure));
275                    }
276                    outcome.mismatches.push(failure);
277                }
278            }
279        }
280        if opts.requests.is_some_and(|n| outcome.requests >= n) {
281            break;
282        }
283    }
284    drop(build);
285    let _ = std::fs::remove_dir_all(&scratch);
286    outcome.groups = crate::mismatch::replay_groups(&outcome.mismatches);
287    Ok(outcome)
288}
289
290fn mismatch(req: &Req, problems: Vec<Problem>) -> Failure {
291    let path = hash(&req.path);
292    Failure {
293        case: format!("{} {path}", req.method),
294        args: vec![req.method.clone(), path],
295        problems,
296    }
297}
298
299/// Appends the mismatch's shape to the log and, with `--keep`, the request to the inputs.
300fn record(outcome: &ShadowOutcome, failure: &Failure, req: &Req) -> Result<()> {
301    append(&outcome.log, &serde_json::to_string(failure)?)?;
302    if let Some(inputs) = &outcome.inputs {
303        let mut kept = req.clone();
304        kept.headers.retain(|k, _| !k.eq_ignore_ascii_case("host"));
305        append(inputs, &serde_json::to_string(&kept)?)?;
306    }
307    Ok(())
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use std::collections::BTreeMap;
314
315    fn config(normalize: &[&str]) -> Config {
316        serde_json::from_value(serde_json::json!({
317            "schema": "rust-anything/app-cases@1",
318            "name": "server",
319            "run": ["node", "server.js"],
320            "normalize": normalize,
321        }))
322        .unwrap()
323    }
324
325    fn resp(status: u16, headers: &[(&str, &str)], body: &str) -> Resp {
326        Resp {
327            status,
328            headers: headers
329                .iter()
330                .map(|(k, v)| (k.to_string(), v.to_string()))
331                .collect::<BTreeMap<_, _>>(),
332            body: body.as_bytes().to_vec(),
333        }
334    }
335
336    fn fields(problems: &[Problem]) -> Vec<&str> {
337        problems.iter().map(|p| p.field.as_str()).collect()
338    }
339
340    #[test]
341    fn answers_compare_by_status_headers_and_body_as_shapes() {
342        let norm = Normalizers::new(&config(&["timestamps"])).unwrap();
343        let none = BTreeSet::new();
344        let a = resp(
345            200,
346            &[
347                ("content-type", "text/plain"),
348                ("date", "x"),
349                ("x-at", "2024-01-02T03:04:05Z"),
350            ],
351            "at 2024-01-02T03:04:05Z: secret\n",
352        );
353        let same = resp(
354            200,
355            &[
356                ("content-type", "text/plain"),
357                ("x-at", "2025-06-07T08:09:10Z"),
358            ],
359            "at 2025-06-07T08:09:10Z: secret\n",
360        );
361        assert!(compare(&norm, &none, &a, &same).is_empty());
362        let other = resp(500, &[("x-at", "2025-06-07T08:09:10Z")], "at 2025: oops\n");
363        let problems = compare(&norm, &none, &a, &other);
364        assert_eq!(fields(&problems), ["status", "header content-type", "body"]);
365        let text = format!("{problems:?}");
366        assert!(!text.contains("secret") && !text.contains("oops"), "{text}");
367        assert_eq!(problems[0].detail, "status (200→500)\n");
368        assert_eq!(problems[1].detail, "header content-type (missing key)\n");
369        assert_eq!(
370            problems[2].detail,
371            "body (text), line 1, column 4, char 3, length 16 expected, 14 got\n"
372        );
373    }
374
375    #[test]
376    fn a_header_the_original_varied_on_is_checked_for_presence_only() {
377        let norm = Normalizers::new(&config(&[])).unwrap();
378        let noisy: BTreeSet<String> = ["set-cookie".to_string()].into();
379        let a = resp(200, &[("set-cookie", "id=1")], "");
380        assert!(compare(&norm, &noisy, &a, &resp(200, &[("set-cookie", "id=2")], "")).is_empty());
381        assert_eq!(
382            fields(&compare(&norm, &noisy, &a, &resp(200, &[], ""))),
383            ["header set-cookie"]
384        );
385    }
386
387    #[test]
388    fn the_build_gets_both_sinks_and_no_database_commands() {
389        let saved = EffectsConfig::from_args(
390            &["smtp-raw".into()],
391            &["HOOK=http-url".into()],
392            Some("reset"),
393            Some("dump"),
394        )
395        .unwrap()
396        .unwrap();
397        let sinks = sinks_for(Some(&saved));
398        assert!(sinks.http && sinks.smtp && !sinks.smtp_parts);
399        assert_eq!(sinks.env["HOOK"], "http-url");
400        assert!(sinks.db_reset.is_none() && sinks.db_dump.is_none());
401        let fresh = sinks_for(None);
402        assert!(fresh.http && fresh.smtp && fresh.smtp_parts);
403    }
404
405    #[test]
406    fn a_mismatch_names_the_request_by_method_and_path_hash() {
407        let req = Req {
408            method: "GET".to_string(),
409            path: "/users/alice".to_string(),
410            headers: BTreeMap::new(),
411            body: None,
412            body_base64: None,
413            body_file: None,
414        };
415        let failure = mismatch(&req, Vec::new());
416        assert_eq!(failure.case, format!("GET {}", hash("/users/alice")));
417        assert_eq!(failure.case.len(), "GET ".len() + 16);
418        assert!(!format!("{failure:?}").contains("alice"));
419        assert_ne!(hash("/users/alice"), hash("/users/bob"));
420    }
421}