rama 0.3.0

modular service framework
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
#![allow(dead_code)]

use std::{
    io::{BufRead, BufReader},
    net::TcpStream,
    path::PathBuf,
    process::Child,
    sync::Once,
    thread,
    time::{Duration, Instant},
};

use base64::Engine;

use rama::telemetry::tracing::{
    level_filters::LevelFilter,
    subscriber::{self, EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt},
};

#[derive(Debug)]
/// A wrapper around a rama service process.
pub(super) struct RamaService {
    process: Child,
}

#[derive(Debug, Clone)]
pub(super) enum EchoMode {
    Tcp,
    Udp,
    Tls,
    Http,
    Https,
    HttpsWithCertIssuer {
        remote_addr: String,
        remote_ca: Option<Vec<u8>>,
        remote_auth: Option<String>,
    },
}

impl RamaService {
    /// Start the rama Ip service with the given port.
    pub(super) fn serve_ip(port: u16, transport: bool, secure: bool) -> Self {
        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("ip")
            .arg("--bind")
            .arg(format!("127.0.0.1:{port}"))
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        if secure {
            const BASE64: base64::engine::GeneralPurpose =
                base64::engine::general_purpose::STANDARD;

            builder.env(
                "RAMA_TLS_CRT",
                BASE64.encode(include_bytes!("./example_tls.crt")),
            );
            builder.env(
                "RAMA_TLS_KEY",
                BASE64.encode(include_bytes!("./example_tls.key")),
            );
            builder.arg("-s");
        }

        if transport {
            builder.arg("-T");
        }

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        let mut stdout = BufReader::new(stdout).lines();

        for line in &mut stdout {
            let line = line.unwrap();
            if line.contains("ip service ready") {
                break;
            }
        }

        thread::spawn(move || {
            for line in stdout {
                let line = line.unwrap();
                eprintln!("rama ip >> {line}");
            }
        });

        Self { process }
    }

    /// Start the rama echo service with the given port.
    #[allow(clippy::needless_pass_by_value)]
    pub(super) fn serve_echo(port: u16, mode: EchoMode) -> Self {
        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        const BASE64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;

        if matches!(mode, EchoMode::Tls | EchoMode::Https) {
            builder.env(
                "RAMA_TLS_CRT",
                BASE64.encode(include_bytes!("./example_tls.crt")),
            );
            builder.env(
                "RAMA_TLS_KEY",
                BASE64.encode(include_bytes!("./example_tls.key")),
            );
        } else if let EchoMode::HttpsWithCertIssuer {
            remote_addr,
            remote_ca,
            remote_auth,
        } = &mode
        {
            builder.env("RAMA_TLS_REMOTE", remote_addr);
            if let Some(remote_ca) = remote_ca {
                builder.env("RAMA_TLS_REMOTE_CA", BASE64.encode(remote_ca));
            }
            if let Some(remote_auth) = remote_auth {
                builder.env("RAMA_TLS_REMOTE_AUTH", remote_auth);
            }
        }

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("echo")
            .arg("--bind")
            .arg(format!("127.0.0.1:{port}"))
            .arg("--mode")
            .arg(match &mode {
                EchoMode::Tcp => "tcp",
                EchoMode::Udp => "udp",
                EchoMode::Tls => "tls",
                EchoMode::Http => "http",
                EchoMode::Https | EchoMode::HttpsWithCertIssuer { .. } => "https",
            })
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        if matches!(
            &mode,
            EchoMode::Http | EchoMode::Https | EchoMode::HttpsWithCertIssuer { .. }
        ) {
            builder.arg("--ws");
        }

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        let mut stdout = BufReader::new(stdout).lines();

        for line in &mut stdout {
            let line = line.unwrap();
            if line.contains("echo service ready") {
                break;
            }
        }

        thread::spawn(move || {
            for line in stdout {
                let line = line.unwrap();
                println!("rama echo >> {line}");
            }
        });

        Self { process }
    }

    // Start the rama fp service with the given port.
    pub(super) fn serve_fp(port: u16, secure: bool) -> Self {
        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        if secure {
            const BASE64: base64::engine::GeneralPurpose =
                base64::engine::general_purpose::STANDARD;

            builder.env(
                "RAMA_TLS_CRT",
                BASE64.encode(include_bytes!("./example_tls.crt")),
            );
            builder.env(
                "RAMA_TLS_KEY",
                BASE64.encode(include_bytes!("./example_tls.key")),
            );
        }

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("fp")
            .arg("--bind")
            .arg(format!("127.0.0.1:{port}"))
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        if secure {
            builder.arg("--secure");
        }

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        let mut stdout = BufReader::new(stdout).lines();

        for line in &mut stdout {
            let line = line.unwrap();
            if line.contains("FP Service (auto) listening") {
                break;
            }
        }

        thread::spawn(move || {
            for line in stdout {
                let line = line.unwrap();
                println!("rama fp >> {line}");
            }
        });

        Self { process }
    }

    /// Start the rama proxy service with the given port.
    pub(super) fn serve_proxy(port: u16) -> Self {
        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("proxy")
            .arg("--bind")
            .arg(format!("127.0.0.1:{port}"))
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        let mut stdout = BufReader::new(stdout).lines();

        for line in &mut stdout {
            let line = line.unwrap();
            if line.contains("proxy ready") {
                break;
            }
        }

        thread::spawn(move || {
            for line in stdout {
                let line = line.unwrap();
                println!("rama proxy >> {line}");
            }
        });

        Self { process }
    }

    /// Start the rama discard service with the given port.
    pub(super) fn serve_discard(port: u16, mode: &'static str) -> Self {
        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        if mode.eq_ignore_ascii_case("tls") {
            const BASE64: base64::engine::GeneralPurpose =
                base64::engine::general_purpose::STANDARD;

            builder.env(
                "RAMA_TLS_CRT",
                BASE64.encode(include_bytes!("./example_tls.crt")),
            );
            builder.env(
                "RAMA_TLS_KEY",
                BASE64.encode(include_bytes!("./example_tls.key")),
            );
        }

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("discard")
            .arg("--bind")
            .arg(format!("127.0.0.1:{port}"))
            .arg("--mode")
            .arg(mode)
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        let mut stdout = BufReader::new(stdout).lines();

        for line in &mut stdout {
            let line = line.unwrap();
            if line.contains("discard service ready") {
                break;
            }
        }

        thread::spawn(move || {
            for line in stdout {
                let line = line.unwrap();
                println!("rama discard >> {line}");
            }
        });

        Self { process }
    }

    // Start the rama http-test service with the given port.
    pub(super) fn serve_http_test(port: u16, secure: bool) -> Self {
        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        if secure {
            const BASE64: base64::engine::GeneralPurpose =
                base64::engine::general_purpose::STANDARD;

            builder.env(
                "RAMA_TLS_CRT",
                BASE64.encode(include_bytes!("./example_tls.crt")),
            );
            builder.env(
                "RAMA_TLS_KEY",
                BASE64.encode(include_bytes!("./example_tls.key")),
            );
        }

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("http-test")
            .arg("--bind")
            .arg(format!("127.0.0.1:{port}"))
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        if secure {
            builder.arg("--secure");
        }

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        thread::spawn(move || {
            let stdout = BufReader::new(stdout).lines();
            for line in stdout {
                let line = line.unwrap();
                println!("rama http-test >> {line}");
            }
        });

        wait_for_tcp_listener(&mut process, port, "http-test");

        Self { process }
    }

    /// Run any rama cmd
    pub(super) fn run(args: &[&'static str]) -> Result<String, Box<dyn std::error::Error>> {
        let child = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command()
            .stderr(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .args(args)
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            )
            .spawn()
            .unwrap();

        let output = child.wait_with_output()?;
        if !output.status.success() {
            // Surface the child's own diagnostics — otherwise the test
            // panic only carries the args, which is rarely enough to
            // pinpoint what went wrong (TLS handshake? bind in use?
            // bad CLI flag?).
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            panic!(
                "rama exited unsuccessfully\n  args: {args:?}\n  status: {status}\n  --- stderr ---\n{stderr}\n  --- stdout ---\n{stdout}",
                status = output.status,
            );
        }
        let mut s = String::from_utf8(output.stderr)?;
        s.push_str(&String::from_utf8(output.stdout)?);
        Ok(s)
    }

    /// Run any rama cmd allowing failure — returns (exit_success,
    /// stdout, stderr) so callers can assert on error diagnostics
    /// without the harness panicking on non-zero exit.
    #[allow(clippy::type_complexity)]
    pub(super) fn run_capture(
        args: &[&str],
    ) -> Result<(bool, String, String), Box<dyn std::error::Error>> {
        let child = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command()
            .stderr(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .args(args)
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            )
            .spawn()
            .unwrap();
        let output = child.wait_with_output()?;
        Ok((
            output.status.success(),
            String::from_utf8(output.stdout)?,
            String::from_utf8(output.stderr)?,
        ))
    }

    /// Run the http command
    pub(super) fn http(
        input_args: Vec<&'static str>,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let mut args = vec!["--verbose", "-L", "-k"];
        args.extend(input_args);
        Self::run(&args)
    }

    /// Run the probe tls command
    pub(super) fn probe_tls(addr: &'static str) -> Result<String, Box<dyn std::error::Error>> {
        let args = vec!["probe", "tls", "-k", addr];
        Self::run(&args)
    }

    /// Run the probe tcp command
    pub(super) fn probe_tcp(addr: &'static str) -> Result<String, Box<dyn std::error::Error>> {
        let args = vec!["probe", "tcp", addr];
        Self::run(&args)
    }

    /// Run the resolve command
    pub(super) fn resolve(
        domain: &'static str,
        record_type: Option<&'static str>,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let mut args = vec!["resolve", domain];
        if let Some(rt) = record_type {
            args.push(rt);
        }
        Self::run(&args)
    }

    /// Start the rama serve service with the given port and content path.
    pub(super) fn serve_fs(port: u16, path: Option<PathBuf>) -> Self {
        let secure = true;

        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        if secure {
            const BASE64: base64::engine::GeneralPurpose =
                base64::engine::general_purpose::STANDARD;

            builder.env(
                "RAMA_TLS_CRT",
                BASE64.encode(include_bytes!("./example_tls.crt")),
            );
            builder.env(
                "RAMA_TLS_KEY",
                BASE64.encode(include_bytes!("./example_tls.key")),
            );
        }

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("fs")
            .arg("--bind")
            .arg(format!("127.0.0.1:{port}"))
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        if secure {
            builder.arg("-s");
        }

        if let Some(path) = path {
            builder.arg(path);
        }

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        let mut stdout = BufReader::new(stdout).lines();

        for line in &mut stdout {
            let line = line.unwrap();
            if line.contains("ready to serve") {
                break;
            }
        }

        thread::spawn(move || {
            for line in stdout {
                let line = line.unwrap();
                println!("rama serve >> {line}");
            }
        });

        Self { process }
    }

    // Start the rama stunnel exit node with the default port and the forward address.
    // with self-signed certificates for testing
    pub(super) fn serve_stunnel_exit(bind: &str, forward: &str) -> Self {
        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("stunnel")
            .arg("exit")
            .arg("--bind")
            .arg(bind)
            .arg("--forward")
            .arg(forward)
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        let mut stdout = BufReader::new(stdout).lines();

        for line in &mut stdout {
            let line = line.unwrap();
            if line.contains("Stunnel exit node is running") {
                break;
            }
        }

        thread::spawn(move || {
            for line in stdout {
                let line = line.unwrap();
                eprintln!("rama stunnel-server >> {line}");
            }
        });

        Self { process }
    }

    /// Start the rama stunnel entry node in insecure mode (skip verification).
    pub(super) fn serve_stunnel_entry_insecure(bind: &str, connect: &str) -> Self {
        let mut builder = escargot::CargoBuild::new()
            .package("rama-cli")
            .bin("rama")
            .target_dir("./target/")
            .run()
            .unwrap()
            .command();

        builder
            .stdout(std::process::Stdio::piped())
            .arg("serve")
            .arg("stunnel")
            .arg("entry")
            .arg("--insecure")
            .arg("--bind")
            .arg(bind)
            .arg("--connect")
            .arg(connect)
            .env(
                "RUST_LOG",
                std::env::var("RUST_LOG").unwrap_or("info".into()),
            );

        let mut process = builder.spawn().unwrap();

        let stdout = process.stdout.take().unwrap();
        let mut stdout = BufReader::new(stdout).lines();

        for line in &mut stdout {
            let line = line.unwrap();
            if line.contains("Stunnel entry node is running") {
                break;
            }
        }

        thread::spawn(move || {
            for line in stdout {
                let line = line.unwrap();
                eprintln!("rama stunnel-client >> {line}");
            }
        });

        Self { process }
    }
}

fn wait_for_tcp_listener(process: &mut Child, port: u16, name: &str) {
    let deadline = Instant::now() + Duration::from_secs(10);
    let addr = format!("127.0.0.1:{port}");

    loop {
        if TcpStream::connect(&addr).is_ok() {
            return;
        }

        if let Some(status) = process.try_wait().expect("check service status") {
            panic!("{name} service exited before listening on {addr}: {status}");
        }

        assert!(
            Instant::now() < deadline,
            "{name} service did not listen on {addr} before timeout"
        );

        thread::sleep(Duration::from_millis(25));
    }
}

impl Drop for RamaService {
    fn drop(&mut self) {
        self.process.kill().expect("kill server process");
    }
}

/// to ensure we only ever register tracing once,
/// in the first test that gets run.
///
/// Dirty but it works, good enough for tests.
static INIT_TRACING_ONCE: Once = Once::new();

/// Initialize tracing for example tests
pub(super) fn init_tracing() {
    INIT_TRACING_ONCE.call_once(|| {
        _ = subscriber::registry()
            .with(fmt::layer())
            .with(
                EnvFilter::builder()
                    .with_default_directive(LevelFilter::TRACE.into())
                    .from_env_lossy(),
            )
            .try_init();
    });
}