-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.rs
145 lines (127 loc) · 4 KB
/
main.rs
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
use std::net::SocketAddr;
use std::time::Duration;
use axum::error_handling::HandleErrorLayer;
use axum::extract::RawBody;
use axum::routing::post;
use axum::Router;
use serde::Serialize;
use tokio::fs;
use tokio::process::Command;
use tower::limit::GlobalConcurrencyLimitLayer;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;
use tracing::{debug, info, error};
use common::errors::{timeout_or_500, ApiError};
use common::init_tracing;
use common::response::Bson;
use lazy_static::lazy_static;
lazy_static! {
static ref APP_DIR: String =
std::env::var("APP_DIR").unwrap_or_else(|_| "../../app".to_string());
static ref TRUNK_BIN: String =
std::env::var("TRUNK_BIN").unwrap_or_else(|_| "trunk".to_string());
static ref PORT: u16 = std::env::var("PORT")
.ok()
.and_then(|it| it.parse().ok())
.unwrap_or(4000);
}
#[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Response {
Output {
index_html: String,
js: String,
wasm: Vec<u8>,
},
CompileError(String),
}
async fn run(RawBody(body): RawBody) -> Result<Bson<Response>, ApiError> {
let body = hyper::body::to_bytes(body).await.unwrap();
if body.is_empty() {
return Err(ApiError::NoBody);
}
let body = String::from_utf8_lossy(&body);
let app_dir = match fs::canonicalize(&*APP_DIR).await {
Ok(v) => v,
Err(e) => {
error!(?e, "failed to canonicalize app_dir path");
return Err(ApiError::IoError(e))
},
};
match fs::write(app_dir.join("src/main.rs"), &*body).await {
Ok(_) => {},
Err(e) => {
error!(?e, "failed to write main.rs");
return Err(ApiError::IoError(e))
},
};
let mut cmd = Command::new(&*TRUNK_BIN);
let cmd = cmd
.arg("--config")
.arg(app_dir.join("Trunk.toml"))
.arg("build");
debug!(?cmd, "running command");
let output = match cmd.output().await {
Ok(o) => o,
Err(e) => {
error!(?e, "running trunk failed");
return Err(ApiError::IoError(e))
},
};
if !output.status.success() {
return Ok(Bson(Response::CompileError(
String::from_utf8_lossy(&output.stderr).to_string(),
)));
}
let dist = app_dir.join("dist");
let index_html = fs::read_to_string(dist.join("index.html")).await.map_err(|e| {
error!(?e, "failed to read index.html");
ApiError::IoError(e)
})?;
let js = fs::read_to_string(dist.join("app.js")).await.map_err(|e| {
error!(?e, "failed to read app.js");
ApiError::IoError(e)
})?;
let wasm = fs::read(dist.join("app_bg.wasm")).await.map_err(|e| {
error!(?e, "failed to read app_bg.wasm");
ApiError::IoError(e)
})?;
Ok(Bson(Response::Output {
index_html,
js,
wasm,
}))
}
async fn trunk_version() -> String {
Command::new(&*TRUNK_BIN)
.arg("--version")
.output()
.await
.map(|v| String::from_utf8_lossy(&v.stdout).trim().to_string())
.unwrap_or_else(|_| "failed to get trunk version".to_string())
}
#[tokio::main]
async fn main() {
let app_dir = &*APP_DIR;
let trunk_path = &*TRUNK_BIN;
init_tracing();
debug!(?app_dir);
let trunk_version = trunk_version().await;
debug!(trunk_bin_path = ?trunk_path, trunk_version = ?trunk_version);
// build our application with a single route
let app = Router::new()
.route("/run", post(run))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(timeout_or_500))
.timeout(Duration::from_secs(10)),
)
.layer(GlobalConcurrencyLimitLayer::new(1))
.layer(TraceLayer::new_for_http());
let addr = SocketAddr::new("0.0.0.0".parse().unwrap(), *PORT);
info!("Server running on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}