rust-anything 2.0.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 and Java
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
//! The HTTP front door: an axum server that proxies every route no unit answers to the original
//! server, which it starts on a port of its own.

use std::collections::BTreeMap;

use anyhow::{Result, bail, ensure};

use crate::app;
use crate::front_door::{KILL_SWITCH_PREFIX, State, ident};

const METHODS: [&str; 7] = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];

/// A wired route: `METHOD /path/{param}`, `/path` (any method), or `*` (everything else).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Route {
    pub method: Option<String>,
    pub path: String,
}

impl Route {
    pub fn parse(text: &str) -> Result<Route> {
        let text = text.trim();
        if text == "*" {
            return Ok(Route {
                method: None,
                path: "*".to_string(),
            });
        }
        let (method, path) = match text.split_once(' ') {
            Some((m, p)) => (Some(m.trim().to_ascii_uppercase()), p.trim()),
            None => (None, text),
        };
        if let Some(m) = &method {
            ensure!(
                METHODS.contains(&m.as_str()),
                "route `{text}`: the method must be one of {}",
                METHODS.join(", ")
            );
        }
        ensure!(
            path.starts_with('/') && !path.contains(' ') && !path.contains('?'),
            "route `{text}`: give `METHOD /path` (axum syntax: /users/{{id}}, /files/{{*rest}}), `/path` for any method, or `*`"
        );
        Ok(Route {
            method,
            path: path.to_string(),
        })
    }

    pub fn key(&self) -> String {
        match &self.method {
            Some(m) => format!("{m} {}", self.path),
            None => self.path.clone(),
        }
    }

    fn has_params(&self) -> bool {
        self.path.contains('{')
    }
}

/// Rejects routes another unit already answers, and a path both for any method and for one.
pub(crate) fn check_routes(state: &State, unit: &str, routes: &[String]) -> Result<Vec<Route>> {
    let parsed = routes
        .iter()
        .map(|r| Route::parse(r))
        .collect::<Result<Vec<_>>>()?;
    let mut all: Vec<(String, Route)> = state
        .units
        .iter()
        .filter(|u| u.name != unit)
        .flat_map(|u| {
            u.routes
                .iter()
                .filter_map(|r| Route::parse(r).ok())
                .map(|r| (u.name.clone(), r))
                .collect::<Vec<_>>()
        })
        .collect();
    for route in &parsed {
        for (owner, other) in &all {
            if other.path == route.path
                && (other.method == route.method
                    || other.method.is_none()
                    || route.method.is_none())
            {
                bail!(
                    "`{}` overlaps `{}`, already wired to {owner}",
                    route.key(),
                    other.key()
                );
            }
        }
        all.push((unit.to_string(), route.clone()));
    }
    Ok(parsed)
}

pub(crate) fn cargo_toml(binary: &str, name: &str) -> String {
    format!(
        "[package]\nname = \"{binary}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
         description = \"Front door for `{name}`, generated by rust-anything: Rust owns the server, the original answers what is not ported yet\"\n\n\
         [[bin]]\nname = \"{binary}\"\npath = \"src/main.rs\"\n\n\
         [dependencies]\n\
         axum = \"0.8\"\n\
         reqwest = {{ version = \"0.12\", default-features = false }}\n\
         tokio = {{ version = \"1\", features = [\"macros\", \"net\", \"rt-multi-thread\", \"signal\", \"time\"] }}\n\n\
         [workspace]\n"
    )
}

const SHUTDOWN: &str = "
/// Ctrl-C or SIGTERM: stop taking requests and finish the open ones.
pub async fn shutdown_signal() {
    #[cfg(unix)]
    {
        let mut term =
            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                .expect(\"a SIGTERM handler\");
        tokio::select! {
            _ = tokio::signal::ctrl_c() => {}
            _ = term.recv() => {}
        }
    }
    #[cfg(not(unix))]
    {
        let _ = tokio::signal::ctrl_c().await;
    }
}
";

fn serve(app: &str) -> String {
    format!(
        "    let port = std::env::var(\"PORT\")
        .ok()
        .and_then(|p| p.parse().ok())
        .unwrap_or(8080);
    let listener = tokio::net::TcpListener::bind(SocketAddr::from(([0, 0, 0, 0], port)))
        .await
        .expect(\"binding the port\");
    let listener = listener.tap_io(|tcp| {{
        let _ = tcp.set_nodelay(true);
    }});
    axum::serve(listener, {app})
        .with_graceful_shutdown(shutdown_signal())
        .await
        .expect(\"serving\");
"
    )
}

pub(crate) fn main_rs() -> String {
    format!(
        "mod original;
mod units;

use std::net::SocketAddr;

use axum::serve::ListenerExt;
use original::shutdown_signal;

#[tokio::main]
async fn main() {{
    original::report_fallbacks();
    let original = original::Original::start().await;
    let app = units::router().with_state(original.clone());
{}    original.stop();
}}
",
        serve("app")
    )
}

/// `main.rs` of the front door as this version writes it, then as earlier versions did (before
/// `TCP_NODELAY`): lift recognizes either as untouched.
pub(crate) fn main_rs_versions() -> Vec<String> {
    let current = main_rs();
    let before_nodelay = current
        .replace(
            "    let listener = listener.tap_io(|tcp| {\n        let _ = tcp.set_nodelay(true);\n    });\n",
            "",
        )
        .replace("use axum::serve::ListenerExt;\n", "");
    vec![current, before_nodelay]
}

pub(crate) fn lifted_main_rs() -> String {
    format!(
        "mod units;

use std::net::SocketAddr;

use axum::serve::ListenerExt;

#[tokio::main]
async fn main() {{
{}}}
{SHUTDOWN}",
        serve("units::router()")
    )
}

/// `in_root`: the original runs in the repository, as recorded; otherwise in the front door's
/// own working directory (the recording copies fresh files there).
pub(crate) fn original_rs(run: &[String], in_root: bool) -> String {
    let words: Vec<String> = run.iter().map(|w| format!("{w:?}")).collect();
    let cwd = if in_root {
        ".current_dir(ROOT)
            "
    } else {
        ""
    };
    format!(
        "use std::ffi::OsString;
use std::io::Write;
use std::net::TcpListener;
use std::path::Path;
use std::process::{{Child, Command, Stdio}};
use std::sync::{{Arc, Mutex}};
use std::time::{{Duration, Instant}};

use axum::body::Body;
use axum::extract::{{Request, State}};
use axum::http::{{StatusCode, header}};
use axum::response::{{IntoResponse, Response}};

const ROOT: &str = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../..\");
const RUN: &[&str] = &[{words}];
const FALLBACK_LOG: &str = \"{log}\";

fn resolve(word: &str, port: u16) -> OsString {{
    let word = word.replace(\"{{port}}\", &port.to_string());
    if word.starts_with('-') {{
        return word.into();
    }}
    let path = Path::new(ROOT).join(&word);
    let looks_like_path = word.contains('/') || word.contains('\\\\') || path.is_file();
    if looks_like_path && path.exists() {{
        return std::path::absolute(&path).unwrap_or(path).into_os_string();
    }}
    word.into()
}}

fn log() -> Option<std::fs::File> {{
    let path = std::env::var_os(FALLBACK_LOG)?;
    std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .ok()
}}

/// Tells `rust-anything app replay` this build counts its fallbacks, even when it makes none.
pub fn report_fallbacks() {{
    let _ = log();
}}

/// The original server, started on a free port of its own.
#[derive(Clone)]
pub struct Original {{
    base: String,
    client: reqwest::Client,
    child: Arc<Mutex<Option<Child>>>,
}}

impl Original {{
    pub async fn start() -> Self {{
        let port = TcpListener::bind(\"127.0.0.1:0\")
            .and_then(|l| l.local_addr())
            .map(|a| a.port())
            .expect(\"a free port\");
        let (program, rest) = RUN.split_first().expect(\"the original's command\");
        let mut child = Command::new(resolve(program, port))
            .args(rest.iter().map(|w| resolve(w, port)))
            .args(std::env::args_os().skip(1))
            {cwd}.env(\"PORT\", port.to_string())
            .env_remove(FALLBACK_LOG)
            .stdin(Stdio::null())
            .spawn()
            .expect(\"starting the original\");
        let deadline = Instant::now() + Duration::from_secs(60);
        while tokio::net::TcpStream::connect((\"127.0.0.1\", port))
            .await
            .is_err()
        {{
            if let Ok(Some(status)) = child.try_wait() {{
                panic!(\"the original exited ({{status}}) before listening on port {{port}}\");
            }}
            assert!(
                Instant::now() < deadline,
                \"the original did not listen on port {{port}}\"
            );
            tokio::time::sleep(Duration::from_millis(50)).await;
        }}
        let client = reqwest::Client::builder()
            .no_proxy()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .expect(\"an HTTP client\");
        Original {{
            base: format!(\"http://127.0.0.1:{{port}}\"),
            client,
            child: Arc::new(Mutex::new(Some(child))),
        }}
    }}

    pub fn stop(&self) {{
        if let Ok(mut slot) = self.child.lock()
            && let Some(mut child) = slot.take()
        {{
            let _ = child.kill();
            let _ = child.wait();
        }}
    }}
}}

/// Sends the request to the original and passes its answer through. Each call is one fallback.
pub async fn proxy(State(original): State<Original>, req: Request) -> Response {{
    let (parts, body) = req.into_parts();
    let target = parts
        .uri
        .path_and_query()
        .map_or(\"/\", |p| p.as_str())
        .to_string();
    if let Some(mut file) = log() {{
        let _ = writeln!(file, \"{{}} {{target}}\", parts.method);
    }}
    let Ok(body) = axum::body::to_bytes(body, usize::MAX).await else {{
        return (StatusCode::BAD_REQUEST, \"front door: unreadable request body\").into_response();
    }};
    let mut request = original
        .client
        .request(parts.method, format!(\"{{}}{{target}}\", original.base))
        .body(body);
    for (name, value) in &parts.headers {{
        if name != header::HOST {{
            request = request.header(name, value);
        }}
    }}
    match request.send().await {{
        Ok(answer) => {{
            let mut response = Response::builder().status(answer.status());
            for (name, value) in answer.headers() {{
                if name != header::TRANSFER_ENCODING && name != header::CONNECTION {{
                    response = response.header(name, value);
                }}
            }}
            let body = answer.bytes().await.unwrap_or_default();
            response
                .body(Body::from(body))
                .unwrap_or_else(|_| StatusCode::BAD_GATEWAY.into_response())
        }}
        Err(e) => (
            StatusCode::BAD_GATEWAY,
            format!(\"front door: the original did not answer: {{e}}\"),
        )
            .into_response(),
    }}
}}
{SHUTDOWN}",
        words = words.join(", "),
        log = app::FALLBACK_ENV
    )
}

/// Path parameters are read from the URI here rather than by axum's extractors, which answer a
/// 400 of their own when an escape is not UTF-8: the unit gets every request, as the original does.
const PATH_PARAMS: &str = "
/// The parameters of `route` (`/users/{id}`, `/files/{*rest}`) in `path`, percent-decoded; one
/// whose escapes are not UTF-8 stays as sent.
fn path_params(route: &str, path: &str) -> HashMap<String, String> {
    let mut out = HashMap::new();
    let mut segments = path.trim_start_matches('/').split('/');
    for part in route.trim_start_matches('/').split('/') {
        if let Some(name) = part.strip_prefix(\"{*\").and_then(|p| p.strip_suffix('}')) {
            let rest: Vec<&str> = segments.by_ref().collect();
            out.insert(name.to_string(), decode(&rest.join(\"/\")));
            break;
        }
        let segment = segments.next().unwrap_or_default();
        if let Some(name) = part.strip_prefix('{').and_then(|p| p.strip_suffix('}')) {
            out.insert(name.to_string(), decode(segment));
        }
    }
    out
}

fn decode(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let hex = |at: usize| bytes.get(at).and_then(|b| char::from(*b).to_digit(16));
        if bytes[i] == b'%'
            && let (Some(high), Some(low)) = (hex(i + 1), hex(i + 2))
        {
            out.push((high * 16 + low) as u8);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8(out).unwrap_or_else(|_| text.to_string())
}
";

fn method_fn(method: &Option<String>) -> String {
    method
        .as_deref()
        .map_or("any".to_string(), str::to_ascii_lowercase)
}

/// `src/units/mod.rs`: wired routes in front of the original (front door), or alone (lifted).
pub(crate) fn units_rs(state: &State, lifted: bool) -> String {
    let mut handlers: Vec<(String, Route, String)> = Vec::new();
    for unit in &state.units {
        for text in &unit.routes {
            if let Ok(route) = Route::parse(text) {
                handlers.push((ident(&unit.name), route, unit.switch.clone()));
            }
        }
    }
    let header = if lifted {
        "//! Written by `rust-anything app lift`: every route is answered in Rust.\n\n"
    } else {
        "//! Generated by `rust-anything app wire` from rust-anything.json; it is rewritten on every wire.\n\n"
    };
    let mut out = header.to_string();
    if handlers.is_empty() && !lifted {
        out += "use axum::Router;\n\nuse crate::original::{self, Original};\n\n\
                pub fn router() -> Router<Original> {\n    Router::new().fallback(original::proxy)\n}\n";
        return out;
    }
    let state_ty = if lifted { "" } else { "<Original>" };
    let mut methods: Vec<String> = handlers
        .iter()
        .filter(|(_, r, _)| r.path != "*")
        .map(|(_, r, _)| method_fn(&r.method))
        .collect();
    methods.sort();
    methods.dedup();
    let any_params = handlers.iter().any(|(_, r, _)| r.has_params());
    out += "use std::collections::HashMap;\n\nuse axum::Router;\n";
    out += &format!(
        "use axum::extract::{{{}Request{}}};\n",
        "",
        if lifted { "" } else { ", State" }
    );
    out += "use axum::response::Response;\n";
    if !methods.is_empty() {
        out += &format!("use axum::routing::{{{}}};\n", methods.join(", "));
    }
    if !lifted {
        out += "\nuse crate::original::{self, Original};\n";
    }
    out.push('\n');
    let mut modules: Vec<&String> = handlers.iter().map(|(m, _, _)| m).collect();
    modules.sort();
    modules.dedup();
    for module in modules {
        out += &format!("mod {module};\n");
    }
    if !lifted {
        out += &format!(
            "\n/// `{KILL_SWITCH_PREFIX}<NAME>=original` sends that unit back to the original.\n\
             fn sent_to_original(unit: &str) -> bool {{\n    \
                 std::env::var(format!(\"{KILL_SWITCH_PREFIX}{{unit}}\")).is_ok_and(|v| v == \"original\")\n\
             }}\n"
        );
    }
    if any_params {
        out += PATH_PARAMS;
    }
    let star = handlers.iter().position(|(_, r, _)| r.path == "*");
    let fallback = match (star, lifted) {
        (Some(_), _) => Some("fallback"),
        (None, false) => Some("original::proxy"),
        (None, true) => None,
    };
    let mut by_path: BTreeMap<&str, Vec<(usize, &Route)>> = BTreeMap::new();
    for (i, (_, route, _)) in handlers.iter().enumerate() {
        if route.path != "*" {
            by_path
                .entry(route.path.as_str())
                .or_default()
                .push((i, route));
        }
    }
    out += &format!("\npub fn router() -> Router{state_ty} {{\n    Router::new()\n");
    for (path, routes) in &by_path {
        let mut chain: Vec<String> = routes
            .iter()
            .map(|(i, r)| format!("{}(route_{i})", method_fn(&r.method)))
            .collect();
        let any_method = routes.iter().any(|(_, r)| r.method.is_none());
        let mut line = chain.remove(0);
        for c in chain {
            line += &format!(".{c}");
        }
        if !any_method && let Some(f) = fallback {
            line += &format!(".fallback({f})");
        }
        out += &format!("        .route({path:?}, {line})\n");
    }
    if let Some(f) = fallback {
        out += &format!("        .fallback({f})\n");
    }
    out += "}\n";
    for (i, (module, route, switch)) in handlers.iter().enumerate() {
        let name = if route.path == "*" {
            "fallback".to_string()
        } else {
            format!("route_{i}")
        };
        let mut params = Vec::new();
        if !lifted {
            params.push("State(original): State<Original>".to_string());
        }
        params.push("req: Request".to_string());
        out += &format!("\nasync fn {name}({}) -> Response {{\n", params.join(", "));
        if !lifted {
            let switch = switch.strip_prefix(KILL_SWITCH_PREFIX).unwrap_or(switch);
            out += &format!(
                "    if sent_to_original({switch:?}) {{\n        return original::proxy(State(original), req).await;\n    }}\n"
            );
        }
        out += &format!(
            "    {module}::handle({:?}, {}, req).await\n}}\n",
            route.key(),
            if route.has_params() {
                format!("path_params({:?}, req.uri().path())", route.path)
            } else {
                "HashMap::new()".to_string()
            }
        );
    }
    out
}

pub(crate) fn glue_rs(crate_name: &str) -> String {
    let krate = crate_name.replace('-', "_");
    format!(
        "//! Glue from the front door to `{crate_name}`: read the request, call `{krate}::port`,\n\
         //! answer what the original answers (status, headers that matter, body).\n\n\
         use std::collections::HashMap;\n\n\
         use axum::extract::Request;\n\
         use axum::response::Response;\n\n\
         /// `route` is the route as wired (`GET /users/{{id}}`, or `*`), `params` its path parameters.\n\
         pub async fn handle(route: &str, params: HashMap<String, String>, req: Request) -> Response {{\n    \
             unimplemented!(\"glue for `{{route}}` {{params:?}} {{}}: call {krate}::port\", req.uri())\n\
         }}\n"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::front_door::{AppKind, WiredUnit};

    fn state(routes: &[&str]) -> State {
        State {
            schema: String::new(),
            name: "srv".into(),
            commands: Vec::new(),
            units: vec![WiredUnit {
                name: "api".into(),
                crate_name: "api-rs".into(),
                path: "../api-rs".into(),
                commands: Vec::new(),
                routes: routes.iter().map(|r| r.to_string()).collect(),
                switch: "RUST_ANYTHING_UNIT_API".into(),
                unit: None,
                shadow: None,
                kept: Vec::new(),
            }],
            lifted: false,
            kind: AppKind::Http,
            routes: Vec::new(),
            api: Vec::new(),
        }
    }

    #[test]
    fn generated_servers_send_without_nagle_delays() {
        for code in [main_rs(), lifted_main_rs()] {
            assert!(code.contains("tcp.set_nodelay(true)"), "{code}");
            assert!(code.contains("use axum::serve::ListenerExt;"), "{code}");
        }
        let versions = main_rs_versions();
        assert!(!versions[1].contains("nodelay") && !versions[1].contains("ListenerExt"));
    }

    #[test]
    fn routes_parse_and_overlaps_are_refused() {
        assert_eq!(
            Route::parse("get /div/{a}/{b}").unwrap().key(),
            "GET /div/{a}/{b}"
        );
        assert_eq!(Route::parse("/any").unwrap().method, None);
        assert!(Route::parse("FETCH /x").is_err());
        assert!(Route::parse("GET x").is_err());
        let s = state(&["GET /hello", "*"]);
        assert!(check_routes(&s, "other", &["POST /hello".into()]).is_ok());
        assert!(check_routes(&s, "other", &["GET /hello".into()]).is_err());
        assert!(check_routes(&s, "other", &["/hello".into()]).is_err());
        assert!(check_routes(&s, "other", &["*".into()]).is_err());
        assert!(check_routes(&s, "api", &["GET /hello".into()]).is_ok());
    }

    #[test]
    fn units_route_with_kill_switches_and_fallback() {
        let s = state(&["GET /div/{a}/{b}", "POST /div/{a}/{b}", "GET /hello", "*"]);
        let code = units_rs(&s, false);
        assert!(
            code.contains(
                ".route(\"/div/{a}/{b}\", get(route_0).post(route_1).fallback(fallback))"
            ),
            "{code}"
        );
        assert!(code.contains("if sent_to_original(\"API\")"), "{code}");
        assert!(
            code.contains("api::handle(\"*\", HashMap::new(), req).await"),
            "{code}"
        );
        assert!(
            code.contains("api::handle(\"GET /div/{a}/{b}\", path_params(\"/div/{a}/{b}\", req.uri().path()), req)"),
            "{code}"
        );
        let lifted = units_rs(&s, true);
        assert!(!lifted.contains("original"), "{lifted}");
        assert!(lifted.contains("pub fn router() -> Router {"), "{lifted}");
        let empty = units_rs(&state(&[]), false);
        assert!(empty.contains("Router::new().fallback(original::proxy)"));
        let no_star = units_rs(&state(&["GET /hello"]), true);
        assert!(!no_star.contains(".fallback("), "{no_star}");
    }
}