rust-anything 4.1.0

Rewrite your app in Rust, one piece at a time, checked against the original's recorded behavior at every step. TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C# and PowerShell
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::process::Command;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

pub const EXT: &str = "effects";
const IO_TIMEOUT: Duration = Duration::from_secs(5);
const SETTLE: Duration = Duration::from_secs(2);

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct EffectsConfig {
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub http: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub smtp: bool,
    /// Mail is recorded as decoded headers and MIME parts. Configs saved before it existed leave
    /// it out and keep recording the raw DATA, so their cases still replay.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub smtp_parts: bool,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub db_reset: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub db_dump: Option<String>,
}

const ENV_KINDS: [&str; 4] = ["http-url", "smtp-host", "smtp-port", "smtp-url"];

impl EffectsConfig {
    pub fn is_empty(&self) -> bool {
        !self.http && !self.smtp && self.db_dump.is_none()
    }

    pub fn serial(&self) -> bool {
        self.db_reset.is_some() || self.db_dump.is_some()
    }

    pub fn from_args(
        kinds: &[String],
        env: &[String],
        db_reset: Option<&str>,
        db_dump: Option<&str>,
    ) -> Result<Option<Self>> {
        let mut config = EffectsConfig::default();
        let mut raw = false;
        for kind in kinds.iter().flat_map(|k| k.split(',')).map(str::trim) {
            match kind {
                "http" => config.http = true,
                "smtp" => config.smtp = true,
                "smtp-raw" => {
                    config.smtp = true;
                    raw = true;
                }
                "" => {}
                other => bail!("unknown effect `{other}`: use http, smtp or smtp-raw"),
            }
        }
        for pair in env {
            let (var, kind) = pair
                .split_once('=')
                .with_context(|| format!("--effect-env `{pair}`: give VAR=KIND"))?;
            if !ENV_KINDS.contains(&kind) {
                bail!(
                    "--effect-env `{pair}`: KIND is one of {}",
                    ENV_KINDS.join(", ")
                );
            }
            if kind.starts_with("http") {
                config.http = true;
            } else {
                config.smtp = true;
            }
            config.env.insert(var.to_string(), kind.to_string());
        }
        config.smtp_parts = config.smtp && !raw;
        config.db_reset = db_reset.map(str::to_string);
        config.db_dump = db_dump.map(str::to_string);
        Ok((!config.is_empty() || config.db_reset.is_some()).then_some(config))
    }

    pub fn merge(saved: Option<Self>, given: Option<Self>) -> Option<Self> {
        match (saved, given) {
            (_, Some(g)) => Some(g),
            (s, None) => s,
        }
    }
}

struct Sink {
    port: u16,
    stop: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>,
}

pub struct Sinks {
    config: EffectsConfig,
    events: Arc<Mutex<Vec<String>>>,
    active: Arc<AtomicUsize>,
    http: Option<Sink>,
    smtp: Option<Sink>,
}

impl Sinks {
    pub fn start(config: &EffectsConfig) -> Result<Sinks> {
        let events = Arc::new(Mutex::new(Vec::new()));
        let active = Arc::new(AtomicUsize::new(0));
        let http = config
            .http
            .then(|| listen(&events, &active, serve_http))
            .transpose()?;
        let smtp_handler: Handler = if config.smtp_parts {
            serve_smtp
        } else {
            serve_smtp_raw
        };
        let smtp = config
            .smtp
            .then(|| listen(&events, &active, smtp_handler))
            .transpose()?;
        Ok(Sinks {
            config: config.clone(),
            events,
            active,
            http,
            smtp,
        })
    }

    pub fn env(&self) -> Vec<(String, String)> {
        let mut out = Vec::new();
        if let Some(h) = &self.http {
            let url = format!("http://127.0.0.1:{}", h.port);
            for var in ["RUST_ANYTHING_HTTP_SINK", "HTTP_PROXY", "http_proxy"] {
                out.push((var.to_string(), url.clone()));
            }
        }
        if let Some(s) = &self.smtp {
            out.push(("SMTP_HOST".into(), "127.0.0.1".into()));
            out.push(("SMTP_PORT".into(), s.port.to_string()));
            out.push((
                "RUST_ANYTHING_SMTP_SINK".into(),
                format!("smtp://127.0.0.1:{}", s.port),
            ));
        }
        for (var, kind) in &self.config.env {
            let value = match (kind.as_str(), &self.http, &self.smtp) {
                ("http-url", Some(h), _) => format!("http://127.0.0.1:{}", h.port),
                ("smtp-host", _, Some(_)) => "127.0.0.1".to_string(),
                ("smtp-port", _, Some(s)) => s.port.to_string(),
                ("smtp-url", _, Some(s)) => format!("smtp://127.0.0.1:{}", s.port),
                _ => continue,
            };
            out.push((var.clone(), value));
        }
        out
    }

    /// Runs `--db-reset` in `cwd`, the folder the case or server runs in.
    pub fn reset(&self, cwd: &Path, repo: &Path) -> Result<()> {
        if let Some(cmd) = &self.config.db_reset {
            let out = shell(cmd, cwd, repo, &self.env())?;
            if !out.status.success() {
                bail!(
                    "--db-reset `{cmd}` failed ({}): {}",
                    out.status,
                    String::from_utf8_lossy(&out.stderr).trim()
                );
            }
        }
        Ok(())
    }

    /// Collects the effects and runs `--db-dump` in `cwd`, the folder the case or server ran in.
    pub fn take(&self, cwd: &Path, repo: &Path) -> Vec<u8> {
        let deadline = Instant::now() + SETTLE;
        while self.active.load(Ordering::SeqCst) > 0 && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        let mut text: String = self
            .events
            .lock()
            .map(|mut e| e.drain(..).collect())
            .unwrap_or_default();
        if let Some(cmd) = &self.config.db_dump {
            text.push_str("db\n");
            match shell(cmd, cwd, repo, &self.env()) {
                Ok(out) => {
                    text.push_str(&String::from_utf8_lossy(&out.stdout));
                    if !out.status.success() {
                        text.push_str(&format!("(db dump failed: {})\n", out.status));
                    }
                }
                Err(e) => text.push_str(&format!("(db dump failed: {e:#})\n")),
            }
        }
        text.into_bytes()
    }
}

impl Drop for Sinks {
    fn drop(&mut self) {
        for sink in [self.http.as_mut(), self.smtp.as_mut()]
            .into_iter()
            .flatten()
        {
            sink.stop.store(true, Ordering::SeqCst);
            if let Some(t) = sink.thread.take() {
                let _ = t.join();
            }
        }
    }
}

/// Extensions of the files `with_repo_scripts` points at the repository.
const SCRIPTS: [&str; 14] = [
    "py", "sh", "bash", "js", "mjs", "cjs", "ts", "rb", "php", "pl", "ps1", "bat", "cmd", "sql",
];

/// The command runs where the case runs, so a script it names by a relative path (`reset.py`,
/// `"my scripts/reset.py"`, `< schema.sql`) is pointed at the repository's copy. Other words, such
/// as `app.db`, the target of an output redirect (`> snapshot.sql`), a here-string and the body of a
/// here-document stay as written: they name the case's own files or are input. Everything else in
/// the command is kept as written.
fn with_repo_scripts(cmd: &str, repo: &Path) -> String {
    let mut out = String::with_capacity(cmd.len());
    let mut kept = 0;
    let mut skip_next = false;
    for word in shell_words(cmd) {
        if word.op {
            // The word after `>`, `>>` or `2>` is an output, after `<<` a here-document's
            // delimiter, after `<<<` a here-string: none is a file to read.
            skip_next = word.text.contains('>') || word.text.starts_with("<<");
            continue;
        }
        if std::mem::take(&mut skip_next) {
            continue;
        }
        let path = word.text.as_str();
        let script = Path::new(path)
            .extension()
            .and_then(|e| e.to_str())
            .is_some_and(|e| SCRIPTS.contains(&e.to_ascii_lowercase().as_str()));
        let in_repo = repo.join(path);
        if script && Path::new(path).is_relative() && in_repo.is_file() {
            out.push_str(&cmd[kept..word.start]);
            out.push_str(&quoted(&in_repo));
            kept = word.end;
        }
    }
    out.push_str(&cmd[kept..]);
    out
}

/// A word of a shell command: where it sits in the command, its text without quotes, and whether
/// it is a redirect operator (`<`, `>`, `>>`, `<<`, `<<-`, `<<<`) rather than a word.
struct ShellWord {
    start: usize,
    end: usize,
    text: String,
    op: bool,
}

/// Splits a command into words as the shell does: whitespace, `;`, `&` and `|` separate words
/// outside quotes, an unquoted `<` or `>` starts a redirect operator of its own, and quotes group
/// without being part of the text. The body of a here-document is input, so it gives no words.
/// cmd quotes with `"` and escapes with `^`; sh also quotes with `'`, escapes with a backslash, and
/// skips a comment (`#` at the start of a word) to the end of the line.
fn shell_words(cmd: &str) -> Vec<ShellWord> {
    shell_words_as(cmd, cfg!(not(windows)))
}

/// `shell_words` as sh (`unix`) or cmd reads the command.
fn shell_words_as(cmd: &str, unix: bool) -> Vec<ShellWord> {
    let mut words = Vec::new();
    let mut word: Option<ShellWord> = None;
    let mut quote = None;
    // Here-documents whose bodies start on the next line: the delimiter, and whether it is `<<-`,
    // which strips leading tabs.
    let mut heredocs = Vec::new();
    // cmd blocks open, `(` at the start of a word, and not yet closed.
    let mut blocks = 0usize;
    let mut i = 0;
    while let Some(c) = cmd[i..].chars().next() {
        let len = c.len_utf8();
        // A line continuation (`\` in sh, `^` in cmd, then a newline) joins the lines before the
        // command is split into words, so it is part of no word and makes none of its own.
        let escape = if unix { '\\' } else { '^' };
        if quote.is_none() && c == escape {
            let rest = &cmd[i + len..];
            if let Some(newline) = ["\r\n", "\n"].into_iter().find(|n| rest.starts_with(n)) {
                i += len + newline.len();
                continue;
            }
        }
        let in_op = word.as_ref().is_some_and(|w| w.op);
        let redirect = quote.is_none() && matches!(c, '<' | '>');
        // sh groups commands with `(` and `)`. cmd does with a `(` that starts a word and the `)`
        // that closes it; elsewhere a parenthesis is part of a name (`my(1).py`).
        let opens = !unix && quote.is_none() && c == '(' && word.is_none();
        let closes = !unix && quote.is_none() && c == ')' && blocks > 0;
        let separator = quote.is_none()
            && (c.is_whitespace()
                || matches!(c, ';' | '&' | '|')
                || (unix && matches!(c, '(' | ')'))
                || opens
                || closes);
        if opens {
            blocks += 1;
        } else if closes {
            blocks -= 1;
        }
        let op_goes_on = redirect || (c == '-' && word.as_ref().is_some_and(|w| w.text == "<<"));
        if separator || (redirect && !in_op) || (in_op && !op_goes_on) {
            finish(&mut words, &mut heredocs, word.take());
        }
        // sh: an unquoted `#` that starts a word comments out the rest of the line.
        if unix && c == '#' && quote.is_none() && word.is_none() {
            i = cmd[i..].find('\n').map_or(cmd.len(), |n| i + n);
            continue;
        }
        if separator {
            i += len;
            if c == '\n' && !heredocs.is_empty() {
                i = past_heredocs(cmd, i, &mut heredocs);
            }
            continue;
        }
        let w = word.get_or_insert_with(|| ShellWord {
            start: i,
            end: i,
            text: String::new(),
            op: redirect,
        });
        match (quote, c) {
            (Some(q), c) if c == q => quote = None,
            // sh: in double quotes a backslash escapes only these, and drops a newline.
            (Some('"'), '\\') if unix => match cmd[i + len..].chars().next() {
                Some(next @ ('$' | '`' | '"' | '\\' | '\n')) => {
                    if next != '\n' {
                        w.text.push(next);
                    }
                    i += len + next.len_utf8();
                    w.end = i;
                    continue;
                }
                _ => w.text.push('\\'),
            },
            (Some(_), c) => w.text.push(c),
            (None, '"') => quote = Some('"'),
            (None, '\'') if unix => quote = Some('\''),
            // A backslash (sh) or caret (cmd) escapes the next character.
            (None, c) if c == escape => {
                if let Some(next) = cmd[i + len..].chars().next() {
                    w.text.push(next);
                    i += len + next.len_utf8();
                    w.end = i;
                    continue;
                }
            }
            (None, c) => w.text.push(c),
        }
        i += len;
        w.end = i;
    }
    finish(&mut words, &mut heredocs, word);
    words
}

/// Ends a word; a word right after `<<` or `<<-` is the delimiter of a here-document.
fn finish(words: &mut Vec<ShellWord>, heredocs: &mut Vec<(String, bool)>, word: Option<ShellWord>) {
    let Some(w) = word.filter(|w| w.end > w.start) else {
        return;
    };
    let after = words
        .last()
        .filter(|p| p.op && !w.op)
        .map(|p| p.text.as_str());
    if let Some(op @ ("<<" | "<<-")) = after {
        heredocs.push((w.text.clone(), op == "<<-"));
    }
    words.push(w);
}

/// Skips the bodies of the pending here-documents, which start at `from`, through each closing
/// delimiter line, and returns where the command goes on.
fn past_heredocs(cmd: &str, mut from: usize, heredocs: &mut Vec<(String, bool)>) -> usize {
    for (delimiter, tabs) in heredocs.drain(..) {
        while from < cmd.len() {
            let end = cmd[from..].find('\n').map_or(cmd.len(), |n| from + n);
            let line = cmd[from..end].trim_end_matches('\r');
            let line = if tabs {
                line.trim_start_matches('\t')
            } else {
                line
            };
            from = (end + 1).min(cmd.len());
            if line == delimiter {
                break;
            }
        }
    }
    from
}

#[cfg(windows)]
fn quoted(path: &Path) -> String {
    format!("\"{}\"", path.display())
}

#[cfg(not(windows))]
fn quoted(path: &Path) -> String {
    format!("'{}'", path.display().to_string().replace('\'', r"'\''"))
}

fn shell(
    cmd: &str,
    cwd: &Path,
    repo: &Path,
    env: &[(String, String)],
) -> Result<crate::process::Output> {
    let cmd = with_repo_scripts(cmd, repo);
    #[cfg(windows)]
    let mut c = {
        use std::os::windows::process::CommandExt as _;
        // `/S` strips exactly the outer quotes, so the command keeps the quotes `quoted` added;
        // `arg` would escape them as `\"`, which cmd does not read.
        let mut c = Command::new("cmd");
        c.args(["/S", "/C"]).raw_arg(format!("\"{cmd}\""));
        c
    };
    #[cfg(not(windows))]
    let mut c = {
        let mut c = Command::new("sh");
        c.args(["-c", &cmd]);
        c
    };
    c.current_dir(cwd)
        .envs(env.iter().map(|(k, v)| (k, v)))
        .stdin(std::process::Stdio::null());
    crate::process::output(&mut c, crate::process::QUICK)
}

type Handler = fn(TcpStream, &Mutex<Vec<String>>);

fn listen(
    events: &Arc<Mutex<Vec<String>>>,
    active: &Arc<AtomicUsize>,
    handler: Handler,
) -> Result<Sink> {
    let listener = TcpListener::bind("127.0.0.1:0").context("starting an effect sink")?;
    listener.set_nonblocking(true)?;
    let port = listener.local_addr()?.port();
    let stop = Arc::new(AtomicBool::new(false));
    let (events, active, flag) = (events.clone(), active.clone(), stop.clone());
    let thread = std::thread::spawn(move || {
        while !flag.load(Ordering::SeqCst) {
            match listener.accept() {
                Ok((stream, _)) => {
                    let _ = stream.set_nonblocking(false);
                    let _ = stream.set_read_timeout(Some(IO_TIMEOUT));
                    let (events, active) = (events.clone(), active.clone());
                    active.fetch_add(1, Ordering::SeqCst);
                    std::thread::spawn(move || {
                        handler(stream, &events);
                        active.fetch_sub(1, Ordering::SeqCst);
                    });
                }
                Err(_) => std::thread::sleep(Duration::from_millis(5)),
            }
        }
    });
    Ok(Sink {
        port,
        stop,
        thread: Some(thread),
    })
}

fn push(events: &Mutex<Vec<String>>, event: String) {
    if let Ok(mut e) = events.lock() {
        e.push(event);
    }
}

fn body_text(body: &[u8]) -> String {
    match std::str::from_utf8(body) {
        Ok(t) => t.to_string(),
        Err(_) => format!("({} bytes)", body.len()),
    }
}

fn serve_http(mut stream: TcpStream, events: &Mutex<Vec<String>>) {
    let mut reader = BufReader::new(match stream.try_clone() {
        Ok(s) => s,
        Err(_) => return,
    });
    let mut line = String::new();
    if reader.read_line(&mut line).unwrap_or(0) == 0 {
        return;
    }
    let mut parts = line.split_whitespace();
    let method = parts.next().unwrap_or_default().to_string();
    let target = parts.next().unwrap_or_default().to_string();
    let mut headers: Vec<(String, String)> = Vec::new();
    loop {
        let mut h = String::new();
        if reader.read_line(&mut h).unwrap_or(0) == 0 {
            break;
        }
        let h = h.trim_end();
        if h.is_empty() {
            break;
        }
        if let Some((k, v)) = h.split_once(':') {
            headers.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));
        }
    }
    let header = |name: &str| {
        headers
            .iter()
            .find(|(k, _)| k == name)
            .map(|(_, v)| v.clone())
    };
    if method.eq_ignore_ascii_case("CONNECT") {
        push(events, format!("https CONNECT {target}\n"));
        let _ = stream.write_all(
            b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
        );
        return;
    }
    let mut body = Vec::new();
    if header("transfer-encoding").is_some_and(|t| t.eq_ignore_ascii_case("chunked")) {
        loop {
            let mut size = String::new();
            if reader.read_line(&mut size).unwrap_or(0) == 0 {
                break;
            }
            let n = usize::from_str_radix(size.trim().split(';').next().unwrap_or("0"), 16)
                .unwrap_or(0);
            if n == 0 {
                break;
            }
            let mut chunk = vec![0; n + 2];
            if reader.read_exact(&mut chunk).is_err() {
                break;
            }
            chunk.truncate(n);
            body.extend(chunk);
        }
    } else if let Some(n) = header("content-length").and_then(|v| v.parse::<usize>().ok()) {
        body.resize(n, 0);
        if reader.read_exact(&mut body).is_err() {
            body.clear();
        }
    }
    let url = if target.starts_with("http://") || target.starts_with("https://") {
        target
    } else {
        format!("http://{}{target}", header("host").unwrap_or_default())
    };
    let url = match stream.local_addr() {
        Ok(local) => url
            .replace(&format!("127.0.0.1:{}", local.port()), "sink")
            .replace(&format!("localhost:{}", local.port()), "sink"),
        Err(_) => url,
    };
    let mut event = format!("http {method} {url}\n");
    if let Some(ct) = header("content-type") {
        event.push_str(&format!("content-type: {ct}\n"));
    }
    if !body.is_empty() {
        event.push('\n');
        event.push_str(&body_text(&body));
        if !event.ends_with('\n') {
            event.push('\n');
        }
    }
    push(events, event);
    let _ = stream.write_all(
        b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
    );
}

fn serve_smtp(stream: TcpStream, events: &Mutex<Vec<String>>) {
    serve_smtp_mode(stream, events, false);
}

fn serve_smtp_raw(stream: TcpStream, events: &Mutex<Vec<String>>) {
    serve_smtp_mode(stream, events, true);
}

fn serve_smtp_mode(stream: TcpStream, events: &Mutex<Vec<String>>, raw: bool) {
    let Ok(mut out) = stream.try_clone() else {
        return;
    };
    let mut reader = BufReader::new(stream);
    let mut say = |line: &str| out.write_all(format!("{line}\r\n").as_bytes()).is_ok();
    if !say("220 rust-anything ESMTP") {
        return;
    }
    let (mut from, mut to) = (String::new(), Vec::<String>::new());
    loop {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap_or(0) == 0 {
            return;
        }
        let cmd = line.trim_end();
        let upper = cmd.to_ascii_uppercase();
        let ok = if upper.starts_with("EHLO") {
            say("250-rust-anything") && say("250 AUTH PLAIN LOGIN")
        } else if upper.starts_with("HELO") {
            say("250 rust-anything")
        } else if upper.starts_with("MAIL FROM:") {
            from = cmd[10..].trim().to_string();
            say("250 OK")
        } else if upper.starts_with("RCPT TO:") {
            to.push(cmd[8..].trim().to_string());
            say("250 OK")
        } else if upper == "DATA" {
            if !say("354 End data with <CR><LF>.<CR><LF>") {
                return;
            }
            let mut data = String::new();
            loop {
                let mut l = String::new();
                if reader.read_line(&mut l).unwrap_or(0) == 0 {
                    return;
                }
                let t = l.trim_end_matches(['\r', '\n']);
                if t == "." {
                    break;
                }
                data.push_str(
                    t.strip_prefix('.')
                        .filter(|_| t.starts_with(".."))
                        .unwrap_or(t),
                );
                data.push('\n');
            }
            let body = if raw {
                data
            } else {
                crate::mime::format_email(&data)
            };
            push(
                events,
                format!("smtp from {from} to {}\n{body}", to.join(", ")),
            );
            from.clear();
            to.clear();
            say("250 OK queued")
        } else if upper.starts_with("AUTH") {
            say("235 Authentication succeeded")
        } else if upper == "RSET" {
            from.clear();
            to.clear();
            say("250 OK")
        } else if upper == "QUIT" {
            let _ = say("221 Bye");
            return;
        } else if upper.starts_with("STARTTLS") {
            say("454 TLS not available")
        } else {
            say("250 OK")
        };
        if !ok {
            return;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn only_scripts_of_the_repository_are_pointed_at_it() {
        let repo = std::env::temp_dir().join(format!("ra-effects-scripts-{}", std::process::id()));
        std::fs::create_dir_all(repo.join("scripts")).unwrap();
        for file in ["reset.py", "scripts/seed.sh", "app.db"] {
            std::fs::write(repo.join(file), "").unwrap();
        }
        let at = |file: &str| quoted(&repo.join(file));
        assert_eq!(
            with_repo_scripts("python3 reset.py --all", &repo),
            format!("python3 {} --all", at("reset.py"))
        );
        assert_eq!(
            with_repo_scripts("sh scripts/seed.sh && sqlite3 app.db .dump", &repo),
            format!("sh {} && sqlite3 app.db .dump", at("scripts/seed.sh"))
        );
        // Not in the repository, or not a relative path: left as written.
        assert_eq!(
            with_repo_scripts("python3 missing.py", &repo),
            "python3 missing.py"
        );
        let absolute = repo.join("reset.py").display().to_string();
        assert_eq!(
            with_repo_scripts(&format!("python3 {absolute}"), &repo),
            format!("python3 {absolute}")
        );
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn script_words_are_read_as_the_shell_reads_them() {
        let repo = std::env::temp_dir().join(format!("ra-effects-words-{}", std::process::id()));
        std::fs::create_dir_all(repo.join("my scripts")).unwrap();
        for file in [
            "reset.py",
            "my scripts/seed.py",
            "schema.sql",
            "snapshot.sql",
        ] {
            std::fs::write(repo.join(file), "").unwrap();
        }
        let at = |file: &str| quoted(&repo.join(file));
        // Quoted, and quoted with a space.
        assert_eq!(
            with_repo_scripts(r#"python3 "reset.py""#, &repo),
            format!("python3 {}", at("reset.py"))
        );
        assert_eq!(
            with_repo_scripts(r#"python3 "my scripts/seed.py" --all"#, &repo),
            format!("python3 {} --all", at("my scripts/seed.py"))
        );
        // An input is the repository's; an output stays in the case's folder.
        assert_eq!(
            with_repo_scripts("sqlite3 app.db < schema.sql", &repo),
            format!("sqlite3 app.db < {}", at("schema.sql"))
        );
        assert_eq!(
            with_repo_scripts("sqlite3 app.db <schema.sql", &repo),
            format!("sqlite3 app.db <{}", at("schema.sql"))
        );
        for cmd in [
            "sqlite3 app.db .dump > snapshot.sql",
            "sqlite3 app.db .dump >> snapshot.sql",
            "sqlite3 app.db .dump >snapshot.sql",
            "sqlite3 app.db .dump 2> snapshot.sql",
        ] {
            assert_eq!(with_repo_scripts(cmd, &repo), cmd);
        }
        // Spacing and operators around the words are kept as written.
        assert_eq!(
            with_repo_scripts("python3  reset.py;  echo  ok", &repo),
            format!("python3  {};  echo  ok", at("reset.py"))
        );
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn sh_continuations_escapes_and_parentheses_are_read_as_sh_reads_them() {
        let words = |cmd: &str| -> Vec<String> {
            shell_words_as(cmd, true)
                .into_iter()
                .map(|w| w.text)
                .collect()
        };
        // A line continuation is no part of any word, and makes none of its own.
        assert_eq!(words("python3 \\\nreset.py"), ["python3", "reset.py"]);
        assert_eq!(words("python3 \\\n  reset.py"), ["python3", "reset.py"]);
        assert_eq!(words("echo '' x"), ["echo", "", "x"]);
        let ops: Vec<(String, bool)> = shell_words_as("echo result > \\\n snapshot.sql", true)
            .into_iter()
            .map(|w| (w.text, w.op))
            .collect();
        assert_eq!(
            ops,
            [
                ("echo".to_string(), false),
                ("result".to_string(), false),
                (">".to_string(), true),
                ("snapshot.sql".to_string(), false)
            ]
        );
        assert_eq!(words("python3 re\\\nset.py"), ["python3", "reset.py"]);
        assert_eq!(words("python3 \"re\\\nset.py\""), ["python3", "reset.py"]);
        // Unquoted parentheses group commands; quoted ones are part of a name.
        assert_eq!(words("(python3 reset.py)"), ["python3", "reset.py"]);
        assert_eq!(words("python3 '(x).py'"), ["python3", "(x).py"]);
        // In double quotes a backslash escapes only `$`, `` ` ``, `"`, `\` and a newline.
        assert_eq!(words(r#"echo "a\"b" "c\d""#), ["echo", "a\"b", "c\\d"]);
        assert_eq!(words(r"echo 'a\b'"), ["echo", "a\\b"]);
    }

    #[test]
    fn cmd_blocks_and_carets_are_read_as_cmd_reads_them() {
        let words = |cmd: &str| -> Vec<String> {
            shell_words_as(cmd, false)
                .into_iter()
                .map(|w| w.text)
                .collect()
        };
        // A `(` that starts a word opens a block, and a `)` in a block closes it.
        assert_eq!(
            words("if exist app.db (python reset.py)"),
            ["if", "exist", "app.db", "python", "reset.py"]
        );
        assert_eq!(words("(python reset.py)"), ["python", "reset.py"]);
        // Outside a block, and quoted or escaped with `^`, parentheses are part of a name.
        assert_eq!(words("python my(1).py"), ["python", "my(1).py"]);
        assert_eq!(words(r#"python "a (1).py""#), ["python", "a (1).py"]);
        assert_eq!(words("(echo ^(x^))"), ["echo", "(x)"]);
    }

    #[test]
    fn sh_comments_give_no_words() {
        let words = |cmd: &str| -> Vec<String> {
            shell_words_as(cmd, true)
                .into_iter()
                .map(|w| w.text)
                .collect()
        };
        // A comment's `<<EOF` starts no here-document, so the next line is still read.
        assert_eq!(words("# <<EOF\npython3 reset.py"), ["python3", "reset.py"]);
        assert_eq!(
            words("python3 reset.py # then <<EOF\necho ok"),
            ["python3", "reset.py", "echo", "ok"]
        );
        // `#` inside a word or in quotes is text.
        assert_eq!(words("echo a#b '#c' \"#d\""), ["echo", "a#b", "#c", "#d"]);
        // cmd has no `#` comments.
        assert_eq!(
            shell_words_as("echo # x", false)
                .into_iter()
                .map(|w| w.text)
                .collect::<Vec<_>>(),
            ["echo", "#", "x"]
        );
    }

    #[test]
    fn redirects_and_here_documents_are_read_as_the_shell_reads_them() {
        let repo = std::env::temp_dir().join(format!("ra-effects-heredoc-{}", std::process::id()));
        std::fs::create_dir_all(&repo).unwrap();
        for file in ["reset.py", "schema.sql", "snapshot.sql"] {
            std::fs::write(repo.join(file), "").unwrap();
        }
        let at = |file: &str| quoted(&repo.join(file));
        // A redirect needs no space before it.
        assert_eq!(
            with_repo_scripts("sqlite3 app.db<schema.sql", &repo),
            format!("sqlite3 app.db<{}", at("schema.sql"))
        );
        for cmd in [
            "echo result> snapshot.sql",
            "echo result>snapshot.sql",
            "echo result>>snapshot.sql",
            "python3 check.py 2>&1 >snapshot.sql",
        ] {
            assert_eq!(with_repo_scripts(cmd, &repo), cmd);
        }
        // A here-document's body and a here-string are input, not words; the command goes on
        // after the delimiter.
        let heredoc = "cat <<EOF > notes.txt\nschema.sql\nEOF\npython3 reset.py";
        assert_eq!(
            with_repo_scripts(heredoc, &repo),
            format!(
                "cat <<EOF > notes.txt\nschema.sql\nEOF\npython3 {}",
                at("reset.py")
            )
        );
        let tabs = "cat <<-END\n\tschema.sql\n\tEND\npython3 reset.py";
        assert_eq!(
            with_repo_scripts(tabs, &repo),
            format!(
                "cat <<-END\n\tschema.sql\n\tEND\npython3 {}",
                at("reset.py")
            )
        );
        assert_eq!(
            with_repo_scripts("sqlite3 app.db <<< schema.sql", &repo),
            "sqlite3 app.db <<< schema.sql"
        );
        if cfg!(not(windows)) {
            let quoted_delim = "cat <<'EOF'\nschema.sql\nEOF\npython3 reset.py";
            assert_eq!(
                with_repo_scripts(quoted_delim, &repo),
                format!("cat <<'EOF'\nschema.sql\nEOF\npython3 {}", at("reset.py"))
            );
        }
        std::fs::remove_dir_all(&repo).unwrap();
    }

    fn send(port: u16, text: &str) -> String {
        let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap();
        s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        s.write_all(text.as_bytes()).unwrap();
        let mut out = String::new();
        let _ = s.read_to_string(&mut out);
        out
    }

    #[test]
    fn http_requests_and_mail_become_effects() {
        let config = EffectsConfig::from_args(
            &["http".into(), "smtp".into()],
            &["HOOK=http-url".into()],
            None,
            None,
        )
        .unwrap()
        .unwrap();
        let sinks = Sinks::start(&config).unwrap();
        let env: BTreeMap<String, String> = sinks.env().into_iter().collect();
        let http: u16 = env["HOOK"].rsplit(':').next().unwrap().parse().unwrap();
        let smtp: u16 = env["SMTP_PORT"].parse().unwrap();
        let reply = send(
            http,
            "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}",
        );
        assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
        let mut mail = TcpStream::connect(("127.0.0.1", smtp)).unwrap();
        mail.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        mail.write_all(
            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",
        )
        .unwrap();
        let mut out = String::new();
        let _ = mail.read_to_string(&mut out);
        assert!(out.contains("221"), "{out}");
        let text = String::from_utf8(sinks.take(Path::new("."), Path::new("."))).unwrap();
        assert_eq!(
            text,
            "http POST http://hooks.example/new\ncontent-type: application/json\n\n{\"a\":1}\n\
             smtp from <a@x.test> to <b@y.test>\nSubject: hi\npart text/plain\n.dot\n"
        );
        assert!(sinks.take(Path::new("."), Path::new(".")).is_empty());
    }

    #[test]
    fn smtp_raw_records_unparsed_mime_data() {
        let config = EffectsConfig::from_args(&["smtp-raw".into()], &[], None, None)
            .unwrap()
            .unwrap();
        assert!(config.smtp && !config.smtp_parts);
        let sinks = Sinks::start(&config).unwrap();
        let env: BTreeMap<String, String> = sinks.env().into_iter().collect();
        let smtp: u16 = env["SMTP_PORT"].parse().unwrap();
        let mut mail = TcpStream::connect(("127.0.0.1", smtp)).unwrap();
        mail.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        mail.write_all(
            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",
        )
        .unwrap();
        let mut out = String::new();
        let _ = mail.read_to_string(&mut out);
        assert!(out.contains("221"), "{out}");
        let text = String::from_utf8(sinks.take(Path::new("."), Path::new("."))).unwrap();
        assert_eq!(
            text,
            "smtp from <a@x.test> to <b@y.test>\nX-Custom: keep\nSubject: hi\n\n.dot\n"
        );
    }

    #[test]
    fn a_config_saved_before_smtp_parts_keeps_recording_raw_mail() {
        let old: EffectsConfig = serde_json::from_str(r#"{"smtp":true}"#).unwrap();
        assert!(old.smtp && !old.smtp_parts);
        let parts = EffectsConfig::from_args(&["smtp".into()], &[], None, None)
            .unwrap()
            .unwrap();
        assert!(parts.smtp_parts);
        let saved: EffectsConfig =
            serde_json::from_str(&serde_json::to_string(&parts).unwrap()).unwrap();
        assert_eq!(saved, parts);
        let env_only = EffectsConfig::from_args(&[], &["MAIL=smtp-url".into()], None, None)
            .unwrap()
            .unwrap();
        assert!(env_only.smtp_parts);
        let raw = EffectsConfig::from_args(&["smtp,smtp-raw".into()], &[], None, None)
            .unwrap()
            .unwrap();
        assert!(raw.smtp && !raw.smtp_parts);
    }

    #[test]
    fn effect_arguments_are_checked() {
        assert!(
            EffectsConfig::from_args(&[], &[], None, None)
                .unwrap()
                .is_none()
        );
        assert!(EffectsConfig::from_args(&["ftp".into()], &[], None, None).is_err());
        assert!(EffectsConfig::from_args(&[], &["X".into()], None, None).is_err());
        let c = EffectsConfig::from_args(&[], &["URL=smtp-url".into()], None, Some("cat db"))
            .unwrap()
            .unwrap();
        assert!(c.smtp && !c.http && c.serial());
    }
}