Skip to main content

rust_anything/
effects.rs

1use std::collections::BTreeMap;
2use std::io::{BufRead, BufReader, Read, Write};
3use std::net::{TcpListener, TcpStream};
4use std::path::Path;
5use std::process::Command;
6use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
7use std::sync::{Arc, Mutex};
8use std::thread::JoinHandle;
9use std::time::{Duration, Instant};
10
11use anyhow::{Context, Result, bail};
12use serde::{Deserialize, Serialize};
13
14pub const EXT: &str = "effects";
15const IO_TIMEOUT: Duration = Duration::from_secs(5);
16const SETTLE: Duration = Duration::from_secs(2);
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19pub struct HttpResponseRule {
20    /// HTTP method token (case-sensitive per RFC 9110), or `*` to match any method.
21    pub method: String,
22    /// Path pattern (leading `/`), supporting `*` wildcards.
23    pub path: String,
24    pub status: u16,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub content_type: Option<String>,
27    #[serde(default, skip_serializing_if = "String::is_empty")]
28    pub body: String,
29    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
30    pub body_base64: bool,
31}
32
33fn is_http_token(s: &str) -> bool {
34    !s.is_empty()
35        && s.bytes()
36            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
37}
38
39impl HttpResponseRule {
40    /// Parses `[METHOD ]/path=STATUS[ BODY|@FILE]`, loading `@FILE` relative to `repo`.
41    pub fn parse(spec: &str, repo: &Path) -> Result<Self> {
42        let trimmed = spec.trim_start();
43        let (first, after_first) = match trimmed.find(char::is_whitespace) {
44            Some(i) => (&trimmed[..i], trimmed[i..].trim_start()),
45            None => (trimmed, ""),
46        };
47        let (method, path_and_status, rest) = if first.starts_with('/') {
48            ("*".to_string(), first, after_first)
49        } else {
50            let (p_and_s, rest) = match after_first.find(char::is_whitespace) {
51                Some(i) => (&after_first[..i], after_first[i..].trim_start()),
52                None => (after_first, ""),
53            };
54            (first.to_string(), p_and_s, rest)
55        };
56        if method != "*" && !is_http_token(&method) {
57            bail!("--effect-response `{spec}`: invalid HTTP method `{method}`");
58        }
59        let (path, status_str) = path_and_status.rsplit_once('=').with_context(|| {
60            format!("--effect-response `{spec}`: give `METHOD /path=STATUS [BODY|@FILE]`")
61        })?;
62        if !path.starts_with('/') {
63            bail!("--effect-response `{spec}`: path `{path}` must start with `/`");
64        }
65        let status: u16 = status_str
66            .parse()
67            .ok()
68            .filter(|&s| (200..=599).contains(&s))
69            .with_context(|| {
70                format!(
71                    "--effect-response `{spec}`: invalid HTTP status `{status_str}` (expected 200-599)"
72                )
73            })?;
74
75        let (body, body_base64, content_type) = if rest.is_empty() {
76            (String::new(), false, None)
77        } else if let Some(file_spec) = rest.strip_prefix('@') {
78            let rel = file_spec.trim();
79            if rel.is_empty() {
80                bail!("--effect-response `{spec}`: missing file path after `@`");
81            }
82            let file_path = if Path::new(rel).is_absolute() {
83                std::path::PathBuf::from(rel)
84            } else {
85                repo.join(rel)
86            };
87            let bytes = std::fs::read(&file_path).with_context(|| {
88                format!(
89                    "--effect-response `{spec}`: cannot read `{}`",
90                    file_path.display()
91                )
92            })?;
93            let ext = file_path
94                .extension()
95                .and_then(|e| e.to_str())
96                .map(str::to_ascii_lowercase);
97            match String::from_utf8(bytes) {
98                Ok(text) => {
99                    let ct = infer_content_type(ext.as_deref(), &text);
100                    (text, false, Some(ct.to_string()))
101                }
102                Err(err) => {
103                    let raw = err.into_bytes();
104                    let ct = match ext.as_deref() {
105                        Some("json") => "application/json",
106                        Some("xml") => "application/xml",
107                        Some("html" | "htm") => "text/html; charset=utf-8",
108                        _ => "application/octet-stream",
109                    };
110                    (encode_base64(&raw), true, Some(ct.to_string()))
111                }
112            }
113        } else {
114            let ct = infer_content_type(None, rest);
115            (rest.to_string(), false, Some(ct.to_string()))
116        };
117
118        Ok(Self {
119            method,
120            path: path.to_string(),
121            status,
122            content_type,
123            body,
124            body_base64,
125        })
126    }
127
128    fn matches(&self, method: &str, target: &str) -> bool {
129        if self.method != "*" && self.method != method {
130            return false;
131        }
132        let req_path = request_path(target);
133        let candidate = if self.path.contains('?') {
134            req_path.as_ref()
135        } else {
136            req_path.split('?').next().unwrap_or(req_path.as_ref())
137        };
138        glob_match(&self.path, candidate)
139    }
140
141    fn response_bytes(&self, request_method: &str) -> Vec<u8> {
142        let body = if self.body_base64 {
143            decode_base64(self.body.as_bytes())
144        } else {
145            self.body.as_bytes().to_vec()
146        };
147        let mut head = format!(
148            "HTTP/1.1 {} {}\r\n",
149            self.status,
150            status_reason(self.status)
151        );
152        let no_body_status = matches!(self.status, 204 | 205 | 304);
153        let is_head = request_method == "HEAD";
154        if !no_body_status && let Some(ct) = &self.content_type {
155            head.push_str(&format!("Content-Type: {ct}\r\n"));
156        }
157        if no_body_status || is_head {
158            head.push_str("Connection: close\r\n\r\n");
159            return head.into_bytes();
160        }
161        head.push_str(&format!(
162            "Content-Length: {}\r\nConnection: close\r\n\r\n",
163            body.len()
164        ));
165        let mut out = head.into_bytes();
166        out.extend_from_slice(&body);
167        out
168    }
169}
170
171#[derive(Debug, Clone, Default, Serialize, Deserialize)]
172pub struct EffectsConfig {
173    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
174    pub http: bool,
175    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
176    pub smtp: bool,
177    /// Mail is recorded as decoded headers and MIME parts. Configs saved before it existed leave
178    /// it out and keep recording the raw DATA, so their cases still replay.
179    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
180    pub smtp_parts: bool,
181    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
182    pub env: BTreeMap<String, String>,
183    /// Canned responses for the HTTP effect sink, matched in order; unmatched requests get `200 {}`.
184    #[serde(default, skip_serializing_if = "Vec::is_empty")]
185    pub http_responses: Vec<HttpResponseRule>,
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub db_reset: Option<String>,
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub db_dump: Option<String>,
190    /// Whether `--effects` named the kinds. `--effect-env` turns a sink on too, but that is inferred
191    /// from a variable, not a request to replace the saved kinds.
192    #[serde(skip)]
193    pub named_kinds: bool,
194}
195
196const ENV_KINDS: [&str; 4] = ["http-url", "smtp-host", "smtp-port", "smtp-url"];
197
198impl EffectsConfig {
199    pub fn is_empty(&self) -> bool {
200        !self.http && !self.smtp && self.db_dump.is_none()
201    }
202
203    pub fn serial(&self) -> bool {
204        self.db_reset.is_some() || self.db_dump.is_some()
205    }
206
207    pub fn from_args(
208        kinds: &[String],
209        env: &[String],
210        db_reset: Option<&str>,
211        db_dump: Option<&str>,
212    ) -> Result<Option<Self>> {
213        Self::from_args_with_responses(kinds, env, &[], Path::new("."), db_reset, db_dump)
214    }
215
216    pub fn from_args_with_responses(
217        kinds: &[String],
218        env: &[String],
219        responses: &[String],
220        repo: &Path,
221        db_reset: Option<&str>,
222        db_dump: Option<&str>,
223    ) -> Result<Option<Self>> {
224        let mut config = EffectsConfig::default();
225        let mut raw = false;
226        for kind in kinds.iter().flat_map(|k| k.split(',')).map(str::trim) {
227            config.named_kinds |= !kind.is_empty();
228            match kind {
229                "http" => config.http = true,
230                "smtp" => config.smtp = true,
231                "smtp-raw" => {
232                    config.smtp = true;
233                    raw = true;
234                }
235                "" => {}
236                other => bail!("unknown effect `{other}`: use http, smtp or smtp-raw"),
237            }
238        }
239        for pair in env {
240            let (var, kind) = pair
241                .split_once('=')
242                .with_context(|| format!("--effect-env `{pair}`: give VAR=KIND"))?;
243            if !ENV_KINDS.contains(&kind) {
244                bail!(
245                    "--effect-env `{pair}`: KIND is one of {}",
246                    ENV_KINDS.join(", ")
247                );
248            }
249            if kind.starts_with("http") {
250                config.http = true;
251            } else {
252                config.smtp = true;
253            }
254            config.env.insert(var.to_string(), kind.to_string());
255        }
256        for spec in responses {
257            config
258                .http_responses
259                .push(HttpResponseRule::parse(spec, repo)?);
260            config.http = true;
261        }
262        config.smtp_parts = config.smtp && !raw;
263        config.db_reset = db_reset.map(str::to_string);
264        config.db_dump = db_dump.map(str::to_string);
265        Ok((!config.is_empty() || config.db_reset.is_some()).then_some(config))
266    }
267
268    /// Merges field by field, as `http::merge_config` does for `--port` and `--arg`: a flag replaces
269    /// only what it names, so re-recording with one effect flag keeps the others it saved before.
270    pub fn merge(saved: Option<Self>, given: Option<Self>) -> Option<Self> {
271        let (mut saved, given) = match (saved, given) {
272            (Some(saved), Some(given)) => (saved, given),
273            (saved, given) => return saved.or(given),
274        };
275        // `--effects` names the kinds, so it replaces them. `--effect-env` also turns a sink on, but
276        // that is inferred: it must not switch the other sink off or change the saved mail mode.
277        if given.named_kinds {
278            saved.http = given.http;
279            saved.smtp = given.smtp;
280            saved.smtp_parts = given.smtp_parts;
281        } else {
282            if given.smtp && !saved.smtp {
283                saved.smtp_parts = given.smtp_parts;
284            }
285            saved.http |= given.http;
286            saved.smtp |= given.smtp;
287        }
288        // `--effect-env` adds or replaces one variable at a time.
289        for (var, kind) in given.env {
290            saved.env.insert(var, kind);
291        }
292        // The rules are tried in order, so the ones given replace the saved list as a whole.
293        if !given.http_responses.is_empty() {
294            saved.http_responses = given.http_responses;
295        }
296        if given.db_reset.is_some() {
297            saved.db_reset = given.db_reset;
298        }
299        if given.db_dump.is_some() {
300            saved.db_dump = given.db_dump;
301        }
302        (!saved.is_empty() || saved.db_reset.is_some()).then_some(saved)
303    }
304}
305
306/// Two configs are equal when they save the same effects: `named_kinds` records how this run was
307/// called, not what is kept, and it is not serialized.
308impl PartialEq for EffectsConfig {
309    fn eq(&self, other: &Self) -> bool {
310        self.http == other.http
311            && self.smtp == other.smtp
312            && self.smtp_parts == other.smtp_parts
313            && self.env == other.env
314            && self.http_responses == other.http_responses
315            && self.db_reset == other.db_reset
316            && self.db_dump == other.db_dump
317    }
318}
319
320struct Sink {
321    port: u16,
322    stop: Arc<AtomicBool>,
323    thread: Option<JoinHandle<()>>,
324}
325
326pub struct Sinks {
327    config: EffectsConfig,
328    events: Arc<Mutex<Vec<String>>>,
329    active: Arc<AtomicUsize>,
330    http: Option<Sink>,
331    smtp: Option<Sink>,
332}
333
334impl Sinks {
335    pub fn start(config: &EffectsConfig) -> Result<Sinks> {
336        if config.http
337            && let Some(rule) = config
338                .http_responses
339                .iter()
340                .find(|r| !(200..=599).contains(&r.status))
341        {
342            bail!(
343                "saved effect response `{} {}` has invalid HTTP status {} (expected 200-599)",
344                rule.method,
345                rule.path,
346                rule.status
347            );
348        }
349        let events = Arc::new(Mutex::new(Vec::new()));
350        let active = Arc::new(AtomicUsize::new(0));
351        let http = config
352            .http
353            .then(|| {
354                let rules = Arc::new(config.http_responses.clone());
355                listen(&events, &active, move |stream, ev| {
356                    serve_http(stream, ev, &rules);
357                })
358            })
359            .transpose()?;
360        let smtp_parts = config.smtp_parts;
361        let smtp = config
362            .smtp
363            .then(|| {
364                listen(&events, &active, move |stream, ev| {
365                    if smtp_parts {
366                        serve_smtp(stream, ev);
367                    } else {
368                        serve_smtp_raw(stream, ev);
369                    }
370                })
371            })
372            .transpose()?;
373        Ok(Sinks {
374            config: config.clone(),
375            events,
376            active,
377            http,
378            smtp,
379        })
380    }
381
382    pub fn env(&self) -> Vec<(String, String)> {
383        let mut out = Vec::new();
384        if let Some(h) = &self.http {
385            let url = format!("http://127.0.0.1:{}", h.port);
386            for var in ["RUST_ANYTHING_HTTP_SINK", "HTTP_PROXY", "http_proxy"] {
387                out.push((var.to_string(), url.clone()));
388            }
389        }
390        if let Some(s) = &self.smtp {
391            out.push(("SMTP_HOST".into(), "127.0.0.1".into()));
392            out.push(("SMTP_PORT".into(), s.port.to_string()));
393            out.push((
394                "RUST_ANYTHING_SMTP_SINK".into(),
395                format!("smtp://127.0.0.1:{}", s.port),
396            ));
397        }
398        for (var, kind) in &self.config.env {
399            let value = match (kind.as_str(), &self.http, &self.smtp) {
400                ("http-url", Some(h), _) => format!("http://127.0.0.1:{}", h.port),
401                ("smtp-host", _, Some(_)) => "127.0.0.1".to_string(),
402                ("smtp-port", _, Some(s)) => s.port.to_string(),
403                ("smtp-url", _, Some(s)) => format!("smtp://127.0.0.1:{}", s.port),
404                _ => continue,
405            };
406            out.push((var.clone(), value));
407        }
408        out
409    }
410
411    /// Runs `--db-reset` in `cwd`, the folder the case or server runs in.
412    pub fn reset(&self, cwd: &Path, repo: &Path) -> Result<()> {
413        if let Some(cmd) = &self.config.db_reset {
414            let out = shell(cmd, cwd, repo, &self.env())?;
415            if !out.status.success() {
416                bail!(
417                    "--db-reset `{cmd}` failed ({}): {}",
418                    out.status,
419                    String::from_utf8_lossy(&out.stderr).trim()
420                );
421            }
422        }
423        Ok(())
424    }
425
426    /// Collects the effects and runs `--db-dump` in `cwd`, the folder the case or server ran in.
427    pub fn take(&self, cwd: &Path, repo: &Path) -> Vec<u8> {
428        let deadline = Instant::now() + SETTLE;
429        while self.active.load(Ordering::SeqCst) > 0 && Instant::now() < deadline {
430            std::thread::sleep(Duration::from_millis(10));
431        }
432        let mut text: String = self
433            .events
434            .lock()
435            .map(|mut e| e.drain(..).collect())
436            .unwrap_or_default();
437        if let Some(cmd) = &self.config.db_dump {
438            text.push_str("db\n");
439            match shell(cmd, cwd, repo, &self.env()) {
440                Ok(out) => {
441                    text.push_str(&String::from_utf8_lossy(&out.stdout));
442                    if !out.status.success() {
443                        text.push_str(&format!("(db dump failed: {})\n", out.status));
444                    }
445                }
446                Err(e) => text.push_str(&format!("(db dump failed: {e:#})\n")),
447            }
448        }
449        text.into_bytes()
450    }
451}
452
453impl Drop for Sinks {
454    fn drop(&mut self) {
455        for sink in [self.http.as_mut(), self.smtp.as_mut()]
456            .into_iter()
457            .flatten()
458        {
459            sink.stop.store(true, Ordering::SeqCst);
460            if let Some(t) = sink.thread.take() {
461                let _ = t.join();
462            }
463        }
464    }
465}
466
467/// Extensions of the files `with_repo_scripts` points at the repository.
468const SCRIPTS: [&str; 14] = [
469    "py", "sh", "bash", "js", "mjs", "cjs", "ts", "rb", "php", "pl", "ps1", "bat", "cmd", "sql",
470];
471
472/// The command runs where the case runs, so a script it names by a relative path (`reset.py`,
473/// `"my scripts/reset.py"`, `< schema.sql`) is pointed at the repository's copy. Other words, such
474/// as `app.db`, the target of an output redirect (`> snapshot.sql`), a here-string and the body of a
475/// here-document stay as written: they name the case's own files or are input. Everything else in
476/// the command is kept as written.
477fn with_repo_scripts(cmd: &str, repo: &Path) -> String {
478    let mut out = String::with_capacity(cmd.len());
479    let mut kept = 0;
480    let mut skip_next = false;
481    for word in shell_words(cmd) {
482        if word.op {
483            // The word after `>`, `>>` or `2>` is an output, after `<<` a here-document's
484            // delimiter, after `<<<` a here-string: none is a file to read.
485            skip_next = word.text.contains('>') || word.text.starts_with("<<");
486            continue;
487        }
488        if std::mem::take(&mut skip_next) {
489            continue;
490        }
491        let path = word.text.as_str();
492        let script = Path::new(path)
493            .extension()
494            .and_then(|e| e.to_str())
495            .is_some_and(|e| SCRIPTS.contains(&e.to_ascii_lowercase().as_str()));
496        let in_repo = repo.join(path);
497        if script && Path::new(path).is_relative() && in_repo.is_file() {
498            out.push_str(&cmd[kept..word.start]);
499            out.push_str(&quoted(&in_repo));
500            kept = word.end;
501        }
502    }
503    out.push_str(&cmd[kept..]);
504    out
505}
506
507/// A word of a shell command: where it sits in the command, its text without quotes, and whether
508/// it is a redirect operator (`<`, `>`, `>>`, `<<`, `<<-`, `<<<`) rather than a word.
509struct ShellWord {
510    start: usize,
511    end: usize,
512    text: String,
513    op: bool,
514}
515
516/// Splits a command into words as the shell does: whitespace, `;`, `&` and `|` separate words
517/// outside quotes, an unquoted `<` or `>` starts a redirect operator of its own, and quotes group
518/// without being part of the text. The body of a here-document is input, so it gives no words.
519/// cmd quotes with `"` and escapes with `^`; sh also quotes with `'`, escapes with a backslash, and
520/// skips a comment (`#` at the start of a word) to the end of the line.
521fn shell_words(cmd: &str) -> Vec<ShellWord> {
522    shell_words_as(cmd, cfg!(not(windows)))
523}
524
525/// `shell_words` as sh (`unix`) or cmd reads the command.
526fn shell_words_as(cmd: &str, unix: bool) -> Vec<ShellWord> {
527    let mut words = Vec::new();
528    let mut word: Option<ShellWord> = None;
529    let mut quote = None;
530    // Here-documents whose bodies start on the next line: the delimiter, and whether it is `<<-`,
531    // which strips leading tabs.
532    let mut heredocs = Vec::new();
533    // cmd blocks open, `(` at the start of a word, and not yet closed.
534    let mut blocks = 0usize;
535    let mut i = 0;
536    while let Some(c) = cmd[i..].chars().next() {
537        let len = c.len_utf8();
538        // A line continuation (`\` in sh, `^` in cmd, then a newline) joins the lines before the
539        // command is split into words, so it is part of no word and makes none of its own.
540        let escape = if unix { '\\' } else { '^' };
541        if quote.is_none() && c == escape {
542            let rest = &cmd[i + len..];
543            if let Some(newline) = ["\r\n", "\n"].into_iter().find(|n| rest.starts_with(n)) {
544                i += len + newline.len();
545                continue;
546            }
547        }
548        let in_op = word.as_ref().is_some_and(|w| w.op);
549        let redirect = quote.is_none() && matches!(c, '<' | '>');
550        // sh groups commands with `(` and `)`. cmd does with a `(` that starts a word and the `)`
551        // that closes it; elsewhere a parenthesis is part of a name (`my(1).py`).
552        let opens = !unix && quote.is_none() && c == '(' && word.is_none();
553        let closes = !unix && quote.is_none() && c == ')' && blocks > 0;
554        let separator = quote.is_none()
555            && (c.is_whitespace()
556                || matches!(c, ';' | '&' | '|')
557                || (unix && matches!(c, '(' | ')'))
558                || opens
559                || closes);
560        if opens {
561            blocks += 1;
562        } else if closes {
563            blocks -= 1;
564        }
565        let op_goes_on = redirect || (c == '-' && word.as_ref().is_some_and(|w| w.text == "<<"));
566        if separator || (redirect && !in_op) || (in_op && !op_goes_on) {
567            finish(&mut words, &mut heredocs, word.take());
568        }
569        // sh: an unquoted `#` that starts a word comments out the rest of the line.
570        if unix && c == '#' && quote.is_none() && word.is_none() {
571            i = cmd[i..].find('\n').map_or(cmd.len(), |n| i + n);
572            continue;
573        }
574        if separator {
575            i += len;
576            if c == '\n' && !heredocs.is_empty() {
577                i = past_heredocs(cmd, i, &mut heredocs);
578            }
579            continue;
580        }
581        let w = word.get_or_insert_with(|| ShellWord {
582            start: i,
583            end: i,
584            text: String::new(),
585            op: redirect,
586        });
587        match (quote, c) {
588            (Some(q), c) if c == q => quote = None,
589            // sh: in double quotes a backslash escapes only these, and drops a newline.
590            (Some('"'), '\\') if unix => match cmd[i + len..].chars().next() {
591                Some(next @ ('$' | '`' | '"' | '\\' | '\n')) => {
592                    if next != '\n' {
593                        w.text.push(next);
594                    }
595                    i += len + next.len_utf8();
596                    w.end = i;
597                    continue;
598                }
599                _ => w.text.push('\\'),
600            },
601            (Some(_), c) => w.text.push(c),
602            (None, '"') => quote = Some('"'),
603            (None, '\'') if unix => quote = Some('\''),
604            // A backslash (sh) or caret (cmd) escapes the next character.
605            (None, c) if c == escape => {
606                if let Some(next) = cmd[i + len..].chars().next() {
607                    w.text.push(next);
608                    i += len + next.len_utf8();
609                    w.end = i;
610                    continue;
611                }
612            }
613            (None, c) => w.text.push(c),
614        }
615        i += len;
616        w.end = i;
617    }
618    finish(&mut words, &mut heredocs, word);
619    words
620}
621
622/// Ends a word; a word right after `<<` or `<<-` is the delimiter of a here-document.
623fn finish(words: &mut Vec<ShellWord>, heredocs: &mut Vec<(String, bool)>, word: Option<ShellWord>) {
624    let Some(w) = word.filter(|w| w.end > w.start) else {
625        return;
626    };
627    let after = words
628        .last()
629        .filter(|p| p.op && !w.op)
630        .map(|p| p.text.as_str());
631    if let Some(op @ ("<<" | "<<-")) = after {
632        heredocs.push((w.text.clone(), op == "<<-"));
633    }
634    words.push(w);
635}
636
637/// Skips the bodies of the pending here-documents, which start at `from`, through each closing
638/// delimiter line, and returns where the command goes on.
639fn past_heredocs(cmd: &str, mut from: usize, heredocs: &mut Vec<(String, bool)>) -> usize {
640    for (delimiter, tabs) in heredocs.drain(..) {
641        while from < cmd.len() {
642            let end = cmd[from..].find('\n').map_or(cmd.len(), |n| from + n);
643            let line = cmd[from..end].trim_end_matches('\r');
644            let line = if tabs {
645                line.trim_start_matches('\t')
646            } else {
647                line
648            };
649            from = (end + 1).min(cmd.len());
650            if line == delimiter {
651                break;
652            }
653        }
654    }
655    from
656}
657
658#[cfg(windows)]
659fn quoted(path: &Path) -> String {
660    format!("\"{}\"", path.display())
661}
662
663#[cfg(not(windows))]
664fn quoted(path: &Path) -> String {
665    format!("'{}'", path.display().to_string().replace('\'', r"'\''"))
666}
667
668fn shell(
669    cmd: &str,
670    cwd: &Path,
671    repo: &Path,
672    env: &[(String, String)],
673) -> Result<crate::process::Output> {
674    let cmd = with_repo_scripts(cmd, repo);
675    #[cfg(windows)]
676    let mut c = {
677        use std::os::windows::process::CommandExt as _;
678        // `/S` strips exactly the outer quotes, so the command keeps the quotes `quoted` added;
679        // `arg` would escape them as `\"`, which cmd does not read.
680        let mut c = Command::new("cmd");
681        c.args(["/S", "/C"]).raw_arg(format!("\"{cmd}\""));
682        c
683    };
684    #[cfg(not(windows))]
685    let mut c = {
686        let mut c = Command::new("sh");
687        c.args(["-c", &cmd]);
688        c
689    };
690    c.current_dir(cwd)
691        .envs(env.iter().map(|(k, v)| (k, v)))
692        .stdin(std::process::Stdio::null());
693    crate::process::output(&mut c, crate::process::QUICK)
694}
695
696fn listen<F>(
697    events: &Arc<Mutex<Vec<String>>>,
698    active: &Arc<AtomicUsize>,
699    handler: F,
700) -> Result<Sink>
701where
702    F: Fn(TcpStream, &Mutex<Vec<String>>) + Send + Sync + 'static,
703{
704    let listener = TcpListener::bind("127.0.0.1:0").context("starting an effect sink")?;
705    listener.set_nonblocking(true)?;
706    let port = listener.local_addr()?.port();
707    let stop = Arc::new(AtomicBool::new(false));
708    let (events, active, flag) = (events.clone(), active.clone(), stop.clone());
709    let handler = Arc::new(handler);
710    let thread = std::thread::spawn(move || {
711        while !flag.load(Ordering::SeqCst) {
712            match listener.accept() {
713                Ok((stream, _)) => {
714                    let _ = stream.set_nonblocking(false);
715                    let _ = stream.set_read_timeout(Some(IO_TIMEOUT));
716                    let (events, active, handler) =
717                        (events.clone(), active.clone(), handler.clone());
718                    active.fetch_add(1, Ordering::SeqCst);
719                    std::thread::spawn(move || {
720                        handler(stream, &events);
721                        active.fetch_sub(1, Ordering::SeqCst);
722                    });
723                }
724                Err(_) => std::thread::sleep(Duration::from_millis(5)),
725            }
726        }
727    });
728    Ok(Sink {
729        port,
730        stop,
731        thread: Some(thread),
732    })
733}
734
735fn push(events: &Mutex<Vec<String>>, event: String) {
736    if let Ok(mut e) = events.lock() {
737        e.push(event);
738    }
739}
740
741fn body_text(body: &[u8]) -> String {
742    match std::str::from_utf8(body) {
743        Ok(t) => t.to_string(),
744        Err(_) => format!("({} bytes)", body.len()),
745    }
746}
747
748fn serve_http(mut stream: TcpStream, events: &Mutex<Vec<String>>, rules: &[HttpResponseRule]) {
749    let mut reader = BufReader::new(match stream.try_clone() {
750        Ok(s) => s,
751        Err(_) => return,
752    });
753    let mut line = String::new();
754    if reader.read_line(&mut line).unwrap_or(0) == 0 {
755        return;
756    }
757    let mut parts = line.split_whitespace();
758    let method = parts.next().unwrap_or_default().to_string();
759    let target = parts.next().unwrap_or_default().to_string();
760    let mut headers: Vec<(String, String)> = Vec::new();
761    loop {
762        let mut h = String::new();
763        if reader.read_line(&mut h).unwrap_or(0) == 0 {
764            break;
765        }
766        let h = h.trim_end();
767        if h.is_empty() {
768            break;
769        }
770        if let Some((k, v)) = h.split_once(':') {
771            headers.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));
772        }
773    }
774    let header = |name: &str| {
775        headers
776            .iter()
777            .find(|(k, _)| k == name)
778            .map(|(_, v)| v.clone())
779    };
780    if method.eq_ignore_ascii_case("CONNECT") {
781        push(events, format!("https CONNECT {target}\n"));
782        let _ = stream.write_all(
783            b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
784        );
785        return;
786    }
787    let mut body = Vec::new();
788    if header("transfer-encoding").is_some_and(|t| t.eq_ignore_ascii_case("chunked")) {
789        loop {
790            let mut size = String::new();
791            if reader.read_line(&mut size).unwrap_or(0) == 0 {
792                break;
793            }
794            let n = usize::from_str_radix(size.trim().split(';').next().unwrap_or("0"), 16)
795                .unwrap_or(0);
796            if n == 0 {
797                break;
798            }
799            let mut chunk = vec![0; n + 2];
800            if reader.read_exact(&mut chunk).is_err() {
801                break;
802            }
803            chunk.truncate(n);
804            body.extend(chunk);
805        }
806    } else if let Some(n) = header("content-length").and_then(|v| v.parse::<usize>().ok()) {
807        body.resize(n, 0);
808        if reader.read_exact(&mut body).is_err() {
809            body.clear();
810        }
811    }
812    let matched = rules.iter().find(|r| r.matches(&method, &target));
813    let url = if strip_http_scheme(&target).is_some() {
814        target
815    } else {
816        format!("http://{}{target}", header("host").unwrap_or_default())
817    };
818    let url = match stream.local_addr() {
819        Ok(local) => url
820            .replace(&format!("127.0.0.1:{}", local.port()), "sink")
821            .replace(&format!("localhost:{}", local.port()), "sink"),
822        Err(_) => url,
823    };
824    let mut event = format!("http {method} {url}\n");
825    if let Some(ct) = header("content-type") {
826        event.push_str(&format!("content-type: {ct}\n"));
827    }
828    if !body.is_empty() {
829        event.push('\n');
830        event.push_str(&body_text(&body));
831        if !event.ends_with('\n') {
832            event.push('\n');
833        }
834    }
835    push(events, event);
836    let _ = stream.set_write_timeout(Some(IO_TIMEOUT));
837    if let Some(rule) = matched {
838        let _ = stream.write_all(&rule.response_bytes(&method));
839    } else if method == "HEAD" {
840        let _ = stream.write_all(
841            b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n",
842        );
843    } else {
844        let _ = stream.write_all(
845            b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
846        );
847    }
848}
849
850fn strip_http_scheme(target: &str) -> Option<&str> {
851    let bytes = target.as_bytes();
852    if bytes.len() >= 7 && bytes[..7].eq_ignore_ascii_case(b"http://") {
853        Some(&target[7..])
854    } else if bytes.len() >= 8 && bytes[..8].eq_ignore_ascii_case(b"https://") {
855        Some(&target[8..])
856    } else {
857        None
858    }
859}
860
861fn request_path(target: &str) -> std::borrow::Cow<'_, str> {
862    if let Some(rest) = strip_http_scheme(target) {
863        match rest.find(['/', '?']) {
864            Some(i) if rest.as_bytes()[i] == b'/' => std::borrow::Cow::Borrowed(&rest[i..]),
865            Some(i) => std::borrow::Cow::Owned(format!("/{}", &rest[i..])),
866            None => std::borrow::Cow::Borrowed("/"),
867        }
868    } else if target.starts_with('?') {
869        std::borrow::Cow::Owned(format!("/{target}"))
870    } else {
871        std::borrow::Cow::Borrowed(target)
872    }
873}
874
875fn glob_match(pattern: &str, text: &str) -> bool {
876    let (p, t) = (pattern.as_bytes(), text.as_bytes());
877    let (mut pi, mut ti) = (0usize, 0usize);
878    let mut star = None;
879    let mut match_ti = 0usize;
880    while ti < t.len() {
881        if pi < p.len() && p[pi] == b'*' {
882            star = Some(pi);
883            match_ti = ti;
884            pi += 1;
885        } else if pi < p.len() && p[pi] == t[ti] {
886            pi += 1;
887            ti += 1;
888        } else if let Some(s) = star {
889            pi = s + 1;
890            match_ti += 1;
891            ti = match_ti;
892        } else {
893            return false;
894        }
895    }
896    while pi < p.len() && p[pi] == b'*' {
897        pi += 1;
898    }
899    pi == p.len()
900}
901
902fn infer_content_type(ext: Option<&str>, text: &str) -> &'static str {
903    match ext {
904        Some("json") => "application/json",
905        Some("xml") => "application/xml",
906        Some("html" | "htm") => "text/html; charset=utf-8",
907        Some("txt") => "text/plain; charset=utf-8",
908        _ => {
909            let trimmed = text.trim_start();
910            if trimmed.starts_with('{') || trimmed.starts_with('[') {
911                "application/json"
912            } else {
913                "text/plain; charset=utf-8"
914            }
915        }
916    }
917}
918
919fn status_reason(status: u16) -> &'static str {
920    match status {
921        200 => "OK",
922        201 => "Created",
923        202 => "Accepted",
924        204 => "No Content",
925        301 => "Moved Permanently",
926        302 => "Found",
927        304 => "Not Modified",
928        400 => "Bad Request",
929        401 => "Unauthorized",
930        403 => "Forbidden",
931        404 => "Not Found",
932        405 => "Method Not Allowed",
933        409 => "Conflict",
934        410 => "Gone",
935        422 => "Unprocessable Entity",
936        429 => "Too Many Requests",
937        500 => "Internal Server Error",
938        502 => "Bad Gateway",
939        503 => "Service Unavailable",
940        504 => "Gateway Timeout",
941        _ => "Status",
942    }
943}
944
945fn encode_base64(input: &[u8]) -> String {
946    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
947    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
948    for chunk in input.chunks(3) {
949        let b0 = chunk[0] as u32;
950        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
951        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
952        let n = (b0 << 16) | (b1 << 8) | b2;
953        out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
954        out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
955        out.push(if chunk.len() > 1 {
956            TABLE[((n >> 6) & 0x3f) as usize] as char
957        } else {
958            '='
959        });
960        out.push(if chunk.len() > 2 {
961            TABLE[(n & 0x3f) as usize] as char
962        } else {
963            '='
964        });
965    }
966    out
967}
968
969fn decode_base64(input: &[u8]) -> Vec<u8> {
970    let mut out = Vec::with_capacity(input.len() * 3 / 4);
971    let mut buf = 0u32;
972    let mut bits = 0u8;
973    for &b in input {
974        let val = match b {
975            b'A'..=b'Z' => b - b'A',
976            b'a'..=b'z' => b - b'a' + 26,
977            b'0'..=b'9' => b - b'0' + 52,
978            b'+' => 62,
979            b'/' => 63,
980            b'=' => break,
981            _ => continue,
982        };
983        buf = (buf << 6) | u32::from(val);
984        bits += 6;
985        if bits >= 8 {
986            bits -= 8;
987            out.push((buf >> bits) as u8);
988        }
989    }
990    out
991}
992
993fn serve_smtp(stream: TcpStream, events: &Mutex<Vec<String>>) {
994    serve_smtp_mode(stream, events, false);
995}
996
997fn serve_smtp_raw(stream: TcpStream, events: &Mutex<Vec<String>>) {
998    serve_smtp_mode(stream, events, true);
999}
1000
1001fn serve_smtp_mode(stream: TcpStream, events: &Mutex<Vec<String>>, raw: bool) {
1002    let Ok(mut out) = stream.try_clone() else {
1003        return;
1004    };
1005    let mut reader = BufReader::new(stream);
1006    let mut say = |line: &str| out.write_all(format!("{line}\r\n").as_bytes()).is_ok();
1007    if !say("220 rust-anything ESMTP") {
1008        return;
1009    }
1010    let (mut from, mut to) = (String::new(), Vec::<String>::new());
1011    loop {
1012        let mut line = String::new();
1013        if reader.read_line(&mut line).unwrap_or(0) == 0 {
1014            return;
1015        }
1016        let cmd = line.trim_end();
1017        let upper = cmd.to_ascii_uppercase();
1018        let ok = if upper.starts_with("EHLO") {
1019            say("250-rust-anything") && say("250 AUTH PLAIN LOGIN")
1020        } else if upper.starts_with("HELO") {
1021            say("250 rust-anything")
1022        } else if upper.starts_with("MAIL FROM:") {
1023            from = cmd[10..].trim().to_string();
1024            say("250 OK")
1025        } else if upper.starts_with("RCPT TO:") {
1026            to.push(cmd[8..].trim().to_string());
1027            say("250 OK")
1028        } else if upper == "DATA" {
1029            if !say("354 End data with <CR><LF>.<CR><LF>") {
1030                return;
1031            }
1032            let mut data = String::new();
1033            loop {
1034                let mut l = String::new();
1035                if reader.read_line(&mut l).unwrap_or(0) == 0 {
1036                    return;
1037                }
1038                let t = l.trim_end_matches(['\r', '\n']);
1039                if t == "." {
1040                    break;
1041                }
1042                data.push_str(
1043                    t.strip_prefix('.')
1044                        .filter(|_| t.starts_with(".."))
1045                        .unwrap_or(t),
1046                );
1047                data.push('\n');
1048            }
1049            let body = if raw {
1050                data
1051            } else {
1052                crate::mime::format_email(&data)
1053            };
1054            push(
1055                events,
1056                format!("smtp from {from} to {}\n{body}", to.join(", ")),
1057            );
1058            from.clear();
1059            to.clear();
1060            say("250 OK queued")
1061        } else if upper.starts_with("AUTH") {
1062            say("235 Authentication succeeded")
1063        } else if upper == "RSET" {
1064            from.clear();
1065            to.clear();
1066            say("250 OK")
1067        } else if upper == "QUIT" {
1068            let _ = say("221 Bye");
1069            return;
1070        } else if upper.starts_with("STARTTLS") {
1071            say("454 TLS not available")
1072        } else {
1073            say("250 OK")
1074        };
1075        if !ok {
1076            return;
1077        }
1078    }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083    use super::*;
1084
1085    #[test]
1086    fn only_scripts_of_the_repository_are_pointed_at_it() {
1087        let repo = std::env::temp_dir().join(format!("ra-effects-scripts-{}", std::process::id()));
1088        std::fs::create_dir_all(repo.join("scripts")).unwrap();
1089        for file in ["reset.py", "scripts/seed.sh", "app.db"] {
1090            std::fs::write(repo.join(file), "").unwrap();
1091        }
1092        let at = |file: &str| quoted(&repo.join(file));
1093        assert_eq!(
1094            with_repo_scripts("python3 reset.py --all", &repo),
1095            format!("python3 {} --all", at("reset.py"))
1096        );
1097        assert_eq!(
1098            with_repo_scripts("sh scripts/seed.sh && sqlite3 app.db .dump", &repo),
1099            format!("sh {} && sqlite3 app.db .dump", at("scripts/seed.sh"))
1100        );
1101        // Not in the repository, or not a relative path: left as written.
1102        assert_eq!(
1103            with_repo_scripts("python3 missing.py", &repo),
1104            "python3 missing.py"
1105        );
1106        let absolute = repo.join("reset.py").display().to_string();
1107        assert_eq!(
1108            with_repo_scripts(&format!("python3 {absolute}"), &repo),
1109            format!("python3 {absolute}")
1110        );
1111        std::fs::remove_dir_all(&repo).unwrap();
1112    }
1113
1114    #[test]
1115    fn script_words_are_read_as_the_shell_reads_them() {
1116        let repo = std::env::temp_dir().join(format!("ra-effects-words-{}", std::process::id()));
1117        std::fs::create_dir_all(repo.join("my scripts")).unwrap();
1118        for file in [
1119            "reset.py",
1120            "my scripts/seed.py",
1121            "schema.sql",
1122            "snapshot.sql",
1123        ] {
1124            std::fs::write(repo.join(file), "").unwrap();
1125        }
1126        let at = |file: &str| quoted(&repo.join(file));
1127        // Quoted, and quoted with a space.
1128        assert_eq!(
1129            with_repo_scripts(r#"python3 "reset.py""#, &repo),
1130            format!("python3 {}", at("reset.py"))
1131        );
1132        assert_eq!(
1133            with_repo_scripts(r#"python3 "my scripts/seed.py" --all"#, &repo),
1134            format!("python3 {} --all", at("my scripts/seed.py"))
1135        );
1136        // An input is the repository's; an output stays in the case's folder.
1137        assert_eq!(
1138            with_repo_scripts("sqlite3 app.db < schema.sql", &repo),
1139            format!("sqlite3 app.db < {}", at("schema.sql"))
1140        );
1141        assert_eq!(
1142            with_repo_scripts("sqlite3 app.db <schema.sql", &repo),
1143            format!("sqlite3 app.db <{}", at("schema.sql"))
1144        );
1145        for cmd in [
1146            "sqlite3 app.db .dump > snapshot.sql",
1147            "sqlite3 app.db .dump >> snapshot.sql",
1148            "sqlite3 app.db .dump >snapshot.sql",
1149            "sqlite3 app.db .dump 2> snapshot.sql",
1150        ] {
1151            assert_eq!(with_repo_scripts(cmd, &repo), cmd);
1152        }
1153        // Spacing and operators around the words are kept as written.
1154        assert_eq!(
1155            with_repo_scripts("python3  reset.py;  echo  ok", &repo),
1156            format!("python3  {};  echo  ok", at("reset.py"))
1157        );
1158        std::fs::remove_dir_all(&repo).unwrap();
1159    }
1160
1161    #[test]
1162    fn sh_continuations_escapes_and_parentheses_are_read_as_sh_reads_them() {
1163        let words = |cmd: &str| -> Vec<String> {
1164            shell_words_as(cmd, true)
1165                .into_iter()
1166                .map(|w| w.text)
1167                .collect()
1168        };
1169        // A line continuation is no part of any word, and makes none of its own.
1170        assert_eq!(words("python3 \\\nreset.py"), ["python3", "reset.py"]);
1171        assert_eq!(words("python3 \\\n  reset.py"), ["python3", "reset.py"]);
1172        assert_eq!(words("echo '' x"), ["echo", "", "x"]);
1173        let ops: Vec<(String, bool)> = shell_words_as("echo result > \\\n snapshot.sql", true)
1174            .into_iter()
1175            .map(|w| (w.text, w.op))
1176            .collect();
1177        assert_eq!(
1178            ops,
1179            [
1180                ("echo".to_string(), false),
1181                ("result".to_string(), false),
1182                (">".to_string(), true),
1183                ("snapshot.sql".to_string(), false)
1184            ]
1185        );
1186        assert_eq!(words("python3 re\\\nset.py"), ["python3", "reset.py"]);
1187        assert_eq!(words("python3 \"re\\\nset.py\""), ["python3", "reset.py"]);
1188        // Unquoted parentheses group commands; quoted ones are part of a name.
1189        assert_eq!(words("(python3 reset.py)"), ["python3", "reset.py"]);
1190        assert_eq!(words("python3 '(x).py'"), ["python3", "(x).py"]);
1191        // In double quotes a backslash escapes only `$`, `` ` ``, `"`, `\` and a newline.
1192        assert_eq!(words(r#"echo "a\"b" "c\d""#), ["echo", "a\"b", "c\\d"]);
1193        assert_eq!(words(r"echo 'a\b'"), ["echo", "a\\b"]);
1194    }
1195
1196    #[test]
1197    fn cmd_blocks_and_carets_are_read_as_cmd_reads_them() {
1198        let words = |cmd: &str| -> Vec<String> {
1199            shell_words_as(cmd, false)
1200                .into_iter()
1201                .map(|w| w.text)
1202                .collect()
1203        };
1204        // A `(` that starts a word opens a block, and a `)` in a block closes it.
1205        assert_eq!(
1206            words("if exist app.db (python reset.py)"),
1207            ["if", "exist", "app.db", "python", "reset.py"]
1208        );
1209        assert_eq!(words("(python reset.py)"), ["python", "reset.py"]);
1210        // Outside a block, and quoted or escaped with `^`, parentheses are part of a name.
1211        assert_eq!(words("python my(1).py"), ["python", "my(1).py"]);
1212        assert_eq!(words(r#"python "a (1).py""#), ["python", "a (1).py"]);
1213        assert_eq!(words("(echo ^(x^))"), ["echo", "(x)"]);
1214    }
1215
1216    #[test]
1217    fn sh_comments_give_no_words() {
1218        let words = |cmd: &str| -> Vec<String> {
1219            shell_words_as(cmd, true)
1220                .into_iter()
1221                .map(|w| w.text)
1222                .collect()
1223        };
1224        // A comment's `<<EOF` starts no here-document, so the next line is still read.
1225        assert_eq!(words("# <<EOF\npython3 reset.py"), ["python3", "reset.py"]);
1226        assert_eq!(
1227            words("python3 reset.py # then <<EOF\necho ok"),
1228            ["python3", "reset.py", "echo", "ok"]
1229        );
1230        // `#` inside a word or in quotes is text.
1231        assert_eq!(words("echo a#b '#c' \"#d\""), ["echo", "a#b", "#c", "#d"]);
1232        // cmd has no `#` comments.
1233        assert_eq!(
1234            shell_words_as("echo # x", false)
1235                .into_iter()
1236                .map(|w| w.text)
1237                .collect::<Vec<_>>(),
1238            ["echo", "#", "x"]
1239        );
1240    }
1241
1242    #[test]
1243    fn redirects_and_here_documents_are_read_as_the_shell_reads_them() {
1244        let repo = std::env::temp_dir().join(format!("ra-effects-heredoc-{}", std::process::id()));
1245        std::fs::create_dir_all(&repo).unwrap();
1246        for file in ["reset.py", "schema.sql", "snapshot.sql"] {
1247            std::fs::write(repo.join(file), "").unwrap();
1248        }
1249        let at = |file: &str| quoted(&repo.join(file));
1250        // A redirect needs no space before it.
1251        assert_eq!(
1252            with_repo_scripts("sqlite3 app.db<schema.sql", &repo),
1253            format!("sqlite3 app.db<{}", at("schema.sql"))
1254        );
1255        for cmd in [
1256            "echo result> snapshot.sql",
1257            "echo result>snapshot.sql",
1258            "echo result>>snapshot.sql",
1259            "python3 check.py 2>&1 >snapshot.sql",
1260        ] {
1261            assert_eq!(with_repo_scripts(cmd, &repo), cmd);
1262        }
1263        // A here-document's body and a here-string are input, not words; the command goes on
1264        // after the delimiter.
1265        let heredoc = "cat <<EOF > notes.txt\nschema.sql\nEOF\npython3 reset.py";
1266        assert_eq!(
1267            with_repo_scripts(heredoc, &repo),
1268            format!(
1269                "cat <<EOF > notes.txt\nschema.sql\nEOF\npython3 {}",
1270                at("reset.py")
1271            )
1272        );
1273        let tabs = "cat <<-END\n\tschema.sql\n\tEND\npython3 reset.py";
1274        assert_eq!(
1275            with_repo_scripts(tabs, &repo),
1276            format!(
1277                "cat <<-END\n\tschema.sql\n\tEND\npython3 {}",
1278                at("reset.py")
1279            )
1280        );
1281        assert_eq!(
1282            with_repo_scripts("sqlite3 app.db <<< schema.sql", &repo),
1283            "sqlite3 app.db <<< schema.sql"
1284        );
1285        if cfg!(not(windows)) {
1286            let quoted_delim = "cat <<'EOF'\nschema.sql\nEOF\npython3 reset.py";
1287            assert_eq!(
1288                with_repo_scripts(quoted_delim, &repo),
1289                format!("cat <<'EOF'\nschema.sql\nEOF\npython3 {}", at("reset.py"))
1290            );
1291        }
1292        std::fs::remove_dir_all(&repo).unwrap();
1293    }
1294
1295    fn send(port: u16, text: &str) -> String {
1296        let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap();
1297        s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1298        s.write_all(text.as_bytes()).unwrap();
1299        let mut out = String::new();
1300        let _ = s.read_to_string(&mut out);
1301        out
1302    }
1303
1304    #[test]
1305    fn http_requests_and_mail_become_effects() {
1306        let config = EffectsConfig::from_args(
1307            &["http".into(), "smtp".into()],
1308            &["HOOK=http-url".into()],
1309            None,
1310            None,
1311        )
1312        .unwrap()
1313        .unwrap();
1314        let sinks = Sinks::start(&config).unwrap();
1315        let env: BTreeMap<String, String> = sinks.env().into_iter().collect();
1316        let http: u16 = env["HOOK"].rsplit(':').next().unwrap().parse().unwrap();
1317        let smtp: u16 = env["SMTP_PORT"].parse().unwrap();
1318        let reply = send(
1319            http,
1320            "POST http://hooks.example/new HTTP/1.1\r\nHost: hooks.example\r\nContent-Type: application/json\r\nContent-Length: 7\r\n\r\n{\"a\":1}",
1321        );
1322        assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
1323        let mut mail = TcpStream::connect(("127.0.0.1", smtp)).unwrap();
1324        mail.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1325        mail.write_all(
1326            b"EHLO me\r\nMAIL FROM:<a@x.test>\r\nRCPT TO:<b@y.test>\r\nDATA\r\nSubject: hi\r\n\r\n..dot\r\n.\r\nQUIT\r\n",
1327        )
1328        .unwrap();
1329        let mut out = String::new();
1330        let _ = mail.read_to_string(&mut out);
1331        assert!(out.contains("221"), "{out}");
1332        let text = String::from_utf8(sinks.take(Path::new("."), Path::new("."))).unwrap();
1333        assert_eq!(
1334            text,
1335            "http POST http://hooks.example/new\ncontent-type: application/json\n\n{\"a\":1}\n\
1336             smtp from <a@x.test> to <b@y.test>\nSubject: hi\npart text/plain\n.dot\n"
1337        );
1338        assert!(sinks.take(Path::new("."), Path::new(".")).is_empty());
1339    }
1340
1341    #[test]
1342    fn smtp_raw_records_unparsed_mime_data() {
1343        let config = EffectsConfig::from_args(&["smtp-raw".into()], &[], None, None)
1344            .unwrap()
1345            .unwrap();
1346        assert!(config.smtp && !config.smtp_parts);
1347        let sinks = Sinks::start(&config).unwrap();
1348        let env: BTreeMap<String, String> = sinks.env().into_iter().collect();
1349        let smtp: u16 = env["SMTP_PORT"].parse().unwrap();
1350        let mut mail = TcpStream::connect(("127.0.0.1", smtp)).unwrap();
1351        mail.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1352        mail.write_all(
1353            b"EHLO me\r\nMAIL FROM:<a@x.test>\r\nRCPT TO:<b@y.test>\r\nDATA\r\nX-Custom: keep\r\nSubject: hi\r\n\r\n..dot\r\n.\r\nQUIT\r\n",
1354        )
1355        .unwrap();
1356        let mut out = String::new();
1357        let _ = mail.read_to_string(&mut out);
1358        assert!(out.contains("221"), "{out}");
1359        let text = String::from_utf8(sinks.take(Path::new("."), Path::new("."))).unwrap();
1360        assert_eq!(
1361            text,
1362            "smtp from <a@x.test> to <b@y.test>\nX-Custom: keep\nSubject: hi\n\n.dot\n"
1363        );
1364    }
1365
1366    #[test]
1367    fn a_config_saved_before_smtp_parts_keeps_recording_raw_mail() {
1368        let old: EffectsConfig = serde_json::from_str(r#"{"smtp":true}"#).unwrap();
1369        assert!(old.smtp && !old.smtp_parts);
1370        let parts = EffectsConfig::from_args(&["smtp".into()], &[], None, None)
1371            .unwrap()
1372            .unwrap();
1373        assert!(parts.smtp_parts);
1374        let saved: EffectsConfig =
1375            serde_json::from_str(&serde_json::to_string(&parts).unwrap()).unwrap();
1376        assert_eq!(saved, parts);
1377        let env_only = EffectsConfig::from_args(&[], &["MAIL=smtp-url".into()], None, None)
1378            .unwrap()
1379            .unwrap();
1380        assert!(env_only.smtp_parts);
1381        let raw = EffectsConfig::from_args(&["smtp,smtp-raw".into()], &[], None, None)
1382            .unwrap()
1383            .unwrap();
1384        assert!(raw.smtp && !raw.smtp_parts);
1385    }
1386
1387    #[test]
1388    fn effect_arguments_are_checked() {
1389        assert!(
1390            EffectsConfig::from_args(&[], &[], None, None)
1391                .unwrap()
1392                .is_none()
1393        );
1394        assert!(EffectsConfig::from_args(&["ftp".into()], &[], None, None).is_err());
1395        assert!(EffectsConfig::from_args(&[], &["X".into()], None, None).is_err());
1396        let c = EffectsConfig::from_args(&[], &["URL=smtp-url".into()], None, Some("cat db"))
1397            .unwrap()
1398            .unwrap();
1399        assert!(c.smtp && !c.http && c.serial());
1400    }
1401
1402    #[test]
1403    fn http_effect_responses_match_method_wildcards_fixtures_and_fallback() {
1404        let dir =
1405            std::env::temp_dir().join(format!("rust-anything-http-resp-{}", std::process::id()));
1406        let _ = std::fs::remove_dir_all(&dir);
1407        std::fs::create_dir_all(dir.join("fixtures")).unwrap();
1408        std::fs::write(
1409            dir.join("fixtures/charge.json"),
1410            r#"{"id":"ch_123","ok":true}"#,
1411        )
1412        .unwrap();
1413
1414        let config = EffectsConfig::from_args_with_responses(
1415            &[],
1416            &["API_URL=http-url".into()],
1417            &[
1418                "POST /v1/charges=201 @fixtures/charge.json".into(),
1419                "POST /hooks/ok=202 accepted".into(),
1420                "POST /hooks/*=500".into(),
1421                "GET /token=200 {\"token\":\"abc\"}".into(),
1422            ],
1423            &dir,
1424            None,
1425            None,
1426        )
1427        .unwrap()
1428        .unwrap();
1429        assert!(config.http);
1430        assert_eq!(config.http_responses.len(), 4);
1431        // Round-trip through JSON (as saved in rust-anything.json for replay).
1432        let saved: EffectsConfig =
1433            serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
1434        assert_eq!(saved, config);
1435
1436        let sinks = Sinks::start(&saved).unwrap();
1437        let env: BTreeMap<String, String> = sinks.env().into_iter().collect();
1438        let port: u16 = env["API_URL"].rsplit(':').next().unwrap().parse().unwrap();
1439
1440        // Exact match with @fixture via proxy-style absolute URL + query string.
1441        let r1 = send(
1442            port,
1443            "POST http://pay.example/v1/charges?dry=1 HTTP/1.1\r\nHost: pay.example\r\nContent-Length: 2\r\n\r\n{}",
1444        );
1445        assert!(r1.starts_with("HTTP/1.1 201 Created\r\n"), "{r1}");
1446        assert!(r1.contains("Content-Type: application/json\r\n"), "{r1}");
1447        assert!(r1.ends_with(r#"{"id":"ch_123","ok":true}"#), "{r1}");
1448
1449        // First matching rule wins (`POST /hooks/ok` before `POST /hooks/*`).
1450        let r2 = send(
1451            port,
1452            "POST /hooks/ok HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\n\r\n",
1453        );
1454        assert!(r2.starts_with("HTTP/1.1 202 Accepted\r\n"), "{r2}");
1455        assert!(r2.ends_with("accepted"), "{r2}");
1456
1457        // Wildcard match with status only (empty body).
1458        let r3 = send(
1459            port,
1460            "POST /hooks/v2/fail HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\n\r\n",
1461        );
1462        assert!(
1463            r3.starts_with("HTTP/1.1 500 Internal Server Error\r\n"),
1464            "{r3}"
1465        );
1466        assert!(r3.contains("Content-Length: 0\r\n"), "{r3}");
1467
1468        // Method mismatch falls back to default `200 {}`.
1469        let r4 = send(
1470            port,
1471            "GET /hooks/v2/fail HTTP/1.1\r\nHost: localhost\r\n\r\n",
1472        );
1473        assert!(r4.starts_with("HTTP/1.1 200 OK\r\n"), "{r4}");
1474        assert!(r4.ends_with("{}"), "{r4}");
1475
1476        // Inline JSON body.
1477        let r5 = send(port, "GET /token HTTP/1.1\r\nHost: localhost\r\n\r\n");
1478        assert!(r5.starts_with("HTTP/1.1 200 OK\r\n"), "{r5}");
1479        assert!(r5.ends_with(r#"{"token":"abc"}"#), "{r5}");
1480
1481        // Validation errors for malformed specs (including 1xx interim statuses).
1482        assert!(HttpResponseRule::parse("no-equals", &dir).is_err());
1483        assert!(HttpResponseRule::parse("POST relative=200", &dir).is_err());
1484        assert!(HttpResponseRule::parse("POST /x=103", &dir).is_err());
1485        assert!(HttpResponseRule::parse("POST /x=999", &dir).is_err());
1486        assert!(HttpResponseRule::parse("POST /x=200 @fixtures/missing.json", &dir).is_err());
1487
1488        let _ = std::fs::remove_dir_all(&dir);
1489    }
1490
1491    #[test]
1492    fn http_effect_responses_follow_rfc_matching_and_body_rules() {
1493        let dir = Path::new(".");
1494        // Query patterns with `=` inside the query string.
1495        let q_rule =
1496            HttpResponseRule::parse("GET /items?mode=full=201 {\"ok\":true}", dir).unwrap();
1497        assert_eq!(q_rule.method, "GET");
1498        assert_eq!(q_rule.path, "/items?mode=full");
1499        assert_eq!(q_rule.status, 201);
1500        assert_eq!(q_rule.body, "{\"ok\":true}");
1501        assert!(q_rule.matches("GET", "/items?mode=full"));
1502        assert!(!q_rule.matches("GET", "/items?mode=short"));
1503
1504        // Case-sensitive HTTP methods and RFC 9110 method tokens with punctuation.
1505        let upper = HttpResponseRule::parse("POST /x=201", dir).unwrap();
1506        let lower = HttpResponseRule::parse("post /x=410", dir).unwrap();
1507        assert!(upper.matches("POST", "/x"));
1508        assert!(!upper.matches("post", "/x"));
1509        assert!(lower.matches("post", "/x"));
1510        assert!(!lower.matches("POST", "/x"));
1511
1512        let msearch = HttpResponseRule::parse("M-SEARCH /devices=201 ok", dir).unwrap();
1513        assert_eq!(msearch.method, "M-SEARCH");
1514        assert!(msearch.matches("M-SEARCH", "/devices"));
1515
1516        // Wildcard `*` when input contains a literal `*`, and absolute URI with query before `/`.
1517        let star = HttpResponseRule::parse("GET /a*b=201", dir).unwrap();
1518        assert!(star.matches("GET", "/axb"));
1519        assert!(star.matches("GET", "/a*xb"));
1520        let abs_q = HttpResponseRule::parse("GET /?next/*=201", dir).unwrap();
1521        assert!(abs_q.matches("GET", "/?next/foo"));
1522        assert!(abs_q.matches("GET", "http://example.test?next/foo"));
1523
1524        // RFC 9110 body & Content-Length suppression for 204, 304, and HEAD.
1525        let r204 = String::from_utf8(
1526            HttpResponseRule::parse("GET /x=204", dir)
1527                .unwrap()
1528                .response_bytes("GET"),
1529        )
1530        .unwrap();
1531        assert!(r204.starts_with("HTTP/1.1 204 No Content\r\n"), "{r204}");
1532        assert!(!r204.contains("Content-Length"), "{r204}");
1533        assert!(r204.ends_with("\r\n\r\n"), "{r204}");
1534
1535        let r304 = String::from_utf8(
1536            HttpResponseRule::parse("GET /x=304 stale", dir)
1537                .unwrap()
1538                .response_bytes("GET"),
1539        )
1540        .unwrap();
1541        assert!(r304.starts_with("HTTP/1.1 304 Not Modified\r\n"), "{r304}");
1542        assert!(!r304.contains("Content-Length"), "{r304}");
1543        assert!(r304.ends_with("\r\n\r\n"), "{r304}");
1544
1545        let r205 = String::from_utf8(
1546            HttpResponseRule::parse("GET /x=205 reset", dir)
1547                .unwrap()
1548                .response_bytes("GET"),
1549        )
1550        .unwrap();
1551        assert!(r205.starts_with("HTTP/1.1 205 "), "{r205}");
1552        assert!(!r205.contains("Content-Length"), "{r205}");
1553        assert!(r205.ends_with("\r\n\r\n"), "{r205}");
1554
1555        let head_body = String::from_utf8(
1556            HttpResponseRule::parse("HEAD /x=200 sample", dir)
1557                .unwrap()
1558                .response_bytes("HEAD"),
1559        )
1560        .unwrap();
1561        assert!(!head_body.contains("Content-Length"), "{head_body}");
1562        assert!(head_body.ends_with("\r\n\r\n"), "{head_body}");
1563
1564        let head_empty = String::from_utf8(
1565            HttpResponseRule::parse("HEAD /x=200", dir)
1566                .unwrap()
1567                .response_bytes("HEAD"),
1568        )
1569        .unwrap();
1570        assert!(!head_empty.contains("Content-Length"), "{head_empty}");
1571        assert!(head_empty.ends_with("\r\n\r\n"), "{head_empty}");
1572
1573        // Trailing whitespace preserved in inline body, case-insensitive HTTP:// scheme,
1574        // and saved-config status validation in Sinks::start.
1575        let nl = HttpResponseRule::parse("GET /x=200 ready\n", dir).unwrap();
1576        assert_eq!(nl.body, "ready\n");
1577        assert!(nl.matches("GET", "HTTP://example.test/x"));
1578        assert!(nl.matches("GET", "HTTPS://example.test/x"));
1579        assert!(!nl.matches("GET", "/aaaaaƩ"));
1580
1581        let mut bad_cfg = EffectsConfig {
1582            http: true,
1583            ..Default::default()
1584        };
1585        bad_cfg.http_responses.push(HttpResponseRule {
1586            method: "GET".into(),
1587            path: "/x".into(),
1588            status: 103,
1589            content_type: None,
1590            body: String::new(),
1591            body_base64: false,
1592        });
1593        assert!(Sinks::start(&bad_cfg).is_err());
1594    }
1595}
1596
1597#[cfg(test)]
1598mod merge_tests {
1599    use super::*;
1600
1601    #[test]
1602    fn a_second_record_with_one_flag_keeps_the_saved_effects() {
1603        // `--effects http --effect-env HOOK=http-url`, then only `--db-dump "echo x"`: the second run
1604        // must keep the sink and the variable, or the webhook stops being recorded (issue #331).
1605        let saved =
1606            EffectsConfig::from_args(&["http".into()], &["HOOK=http-url".into()], None, None);
1607        let given = EffectsConfig::from_args(&[], &[], None, Some("echo x"));
1608        let merged = EffectsConfig::merge(saved.unwrap(), given.unwrap()).unwrap();
1609        assert!(merged.http, "the HTTP sink survived: {merged:?}");
1610        assert_eq!(merged.env.get("HOOK").map(String::as_str), Some("http-url"));
1611        assert_eq!(merged.db_dump.as_deref(), Some("echo x"));
1612    }
1613
1614    #[test]
1615    fn a_given_kind_list_replaces_the_saved_kinds() {
1616        let saved = EffectsConfig::from_args(&["http".into(), "smtp".into()], &[], None, None);
1617        let given = EffectsConfig::from_args(&["smtp".into()], &[], None, None);
1618        let merged = EffectsConfig::merge(saved.unwrap(), given.unwrap()).unwrap();
1619        assert!(
1620            !merged.http,
1621            "a named kind list replaces the kinds: {merged:?}"
1622        );
1623        assert!(merged.smtp);
1624    }
1625
1626    #[test]
1627    fn an_environment_only_update_keeps_both_sinks_and_the_mail_mode() {
1628        // Saved: http and smtp, recorded as raw MIME. A run that only sets `HOOK` infers `http`, but
1629        // that is not a request to drop SMTP or to switch to decoded parts.
1630        let mut saved =
1631            EffectsConfig::from_args(&["http".into(), "smtp-raw".into()], &[], None, None)
1632                .unwrap()
1633                .unwrap();
1634        saved.env.insert("MAIL".into(), "smtp-host".into());
1635        let given = EffectsConfig::from_args(&[], &["HOOK=http-url".into()], None, None)
1636            .unwrap()
1637            .unwrap();
1638        let merged = EffectsConfig::merge(Some(saved), Some(given)).unwrap();
1639        assert!(merged.http && merged.smtp, "both sinks stay: {merged:?}");
1640        assert!(
1641            !merged.smtp_parts,
1642            "the saved raw mail mode stays: {merged:?}"
1643        );
1644        assert_eq!(merged.env.len(), 2, "{merged:?}");
1645        assert_eq!(merged.env.get("HOOK").map(String::as_str), Some("http-url"));
1646    }
1647
1648    #[test]
1649    fn effect_responses_replace_the_saved_rules_and_survive_other_flags() {
1650        let repo = Path::new(".");
1651        let saved = EffectsConfig::from_args_with_responses(
1652            &["http".into()],
1653            &[],
1654            &["GET /a=404".into()],
1655            repo,
1656            None,
1657            None,
1658        )
1659        .unwrap();
1660        let env_only =
1661            EffectsConfig::from_args(&[], &["HOOK=http-url".into()], None, None).unwrap();
1662        let kept = EffectsConfig::merge(saved.clone(), env_only).unwrap();
1663        assert_eq!(kept.http_responses, saved.as_ref().unwrap().http_responses);
1664        let given = EffectsConfig::from_args_with_responses(
1665            &[],
1666            &[],
1667            &["POST /b=500".into()],
1668            repo,
1669            None,
1670            None,
1671        )
1672        .unwrap();
1673        let replaced = EffectsConfig::merge(saved, given).unwrap();
1674        assert_eq!(replaced.http_responses.len(), 1);
1675        assert_eq!(replaced.http_responses[0].path, "/b");
1676    }
1677
1678    #[test]
1679    fn an_environment_update_turns_on_the_sink_it_needs() {
1680        let saved = EffectsConfig::from_args(&["http".into()], &[], None, None).unwrap();
1681        let given = EffectsConfig::from_args(&[], &["MAIL=smtp-host".into()], None, None).unwrap();
1682        let merged = EffectsConfig::merge(saved, given).unwrap();
1683        assert!(
1684            merged.http && merged.smtp,
1685            "the new mapping's sink is added: {merged:?}"
1686        );
1687        assert!(merged.smtp_parts, "{merged:?}");
1688    }
1689
1690    #[test]
1691    fn an_effect_env_replaces_one_variable_and_keeps_the_others() {
1692        let saved = EffectsConfig::from_args(
1693            &["http".into()],
1694            &["HOOK=http-url".into(), "MAIL=smtp-host".into()],
1695            None,
1696            None,
1697        );
1698        let given = EffectsConfig::from_args(&[], &["HOOK=http-url".into()], None, None);
1699        let merged = EffectsConfig::merge(saved.unwrap(), given.unwrap()).unwrap();
1700        assert_eq!(merged.env.len(), 2, "{merged:?}");
1701        assert!(
1702            merged.http && merged.smtp,
1703            "an env update keeps both sinks: {merged:?}"
1704        );
1705    }
1706
1707    #[test]
1708    fn nothing_given_keeps_everything_saved() {
1709        let saved =
1710            EffectsConfig::from_args(&["http".into()], &[], Some("rm x"), Some("echo y")).unwrap();
1711        let kept = saved.clone().unwrap();
1712        let merged = EffectsConfig::merge(saved, None).unwrap();
1713        assert_eq!(merged.http, kept.http);
1714        assert_eq!(merged.db_reset.as_deref(), Some("rm x"));
1715        assert_eq!(merged.db_dump.as_deref(), Some("echo y"));
1716        assert_eq!(EffectsConfig::merge(None, None), None);
1717    }
1718}