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
use crate::build::{build_internal, finalize};
use crate::cmd::{cfg_spinner, run_stage};
use crate::errors::*;
use crate::thread::{spawn_thread, ThreadHandle};
use console::{style, Emoji};
use indicatif::{MultiProgress, ProgressBar};
use std::env;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
static BUILDING_SERVER: Emoji<'_, '_> = Emoji("📡", "");
static SERVING: Emoji<'_, '_> = Emoji("🛰️ ", "");
macro_rules! handle_exit_code {
($code:expr) => {{
let (stdout, stderr, code) = $code;
if code != 0 {
return $crate::errors::Result::Ok(code);
}
(stdout, stderr)
}};
}
fn build_server(
dir: PathBuf,
spinners: &MultiProgress,
did_build: bool,
exec: Arc<Mutex<String>>,
) -> Result<ThreadHandle<impl FnOnce() -> Result<i32>, Result<i32>>> {
let num_steps = match did_build {
true => 4,
false => 2,
};
let target = dir.join(".perseus/server");
let sb_msg = format!(
"{} {} Building server",
style(format!("[{}/{}]", num_steps - 1, num_steps))
.bold()
.dim(),
BUILDING_SERVER
);
let sb_spinner = spinners.insert(num_steps - 1, ProgressBar::new_spinner());
let sb_spinner = cfg_spinner(sb_spinner, &sb_msg);
let sb_target = target;
let sb_thread = spawn_thread(move || {
let (stdout, _stderr) = handle_exit_code!(run_stage(
vec![&format!(
"{} build --message-format json",
env::var("PERSEUS_CARGO_PATH").unwrap_or_else(|_| "cargo".to_string())
)],
&sb_target,
&sb_spinner,
&sb_msg
)?);
let msgs: Vec<&str> = stdout.trim().split('\n').collect();
let msg = msgs.get(msgs.len() - 2);
let msg = match msg {
Some(msg) => serde_json::from_str::<serde_json::Value>(msg)
.map_err(|err| ErrorKind::GetServerExecutableFailed(err.to_string()))?,
None => bail!(ErrorKind::GetServerExecutableFailed(
"expected second-last message, none existed (too few messages)".to_string()
)),
};
let server_exec_path = msg.get("executable");
let server_exec_path = match server_exec_path {
Some(server_exec_path) => match server_exec_path.as_str() {
Some(server_exec_path) => server_exec_path,
None => bail!(ErrorKind::GetServerExecutableFailed(
"expected 'executable' field to be string".to_string()
)),
},
None => bail!(ErrorKind::GetServerExecutableFailed(
"expected 'executable' field in JSON map in second-last message, not present"
.to_string()
)),
};
let mut exec_val = exec.lock().unwrap();
*exec_val = server_exec_path.to_string();
Ok(0)
});
Ok(sb_thread)
}
fn run_server(exec: Arc<Mutex<String>>, dir: PathBuf, did_build: bool) -> Result<i32> {
let target = dir.join(".perseus/server");
let num_steps = match did_build {
true => 4,
false => 2,
};
let exec_val = exec.lock().unwrap();
if exec_val.is_empty() {
bail!(ErrorKind::GetServerExecutableFailed(
"mutex value empty, implies uncaught thread termination (please report this as a bug)"
.to_string()
))
}
let server_exec_path = (*exec_val).to_string();
let child = Command::new(&server_exec_path)
.current_dir(target)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|err| ErrorKind::CmdExecFailed(server_exec_path, err.to_string()))?;
let host = env::var("HOST").unwrap_or_else(|_| "localhost".to_string());
let port = env::var("PORT")
.unwrap_or_else(|_| "8080".to_string())
.parse::<u16>()
.map_err(|err| ErrorKind::PortNotNumber(err.to_string()))?;
println!(
" {} {} Your app is now live on <http://{host}:{port}>! To change this, re-run this command with different settings of the HOST/PORT environment variables.",
style(format!("[{}/{}]", num_steps, num_steps)).bold().dim(),
SERVING,
host=host,
port=port
);
let output = child.wait_with_output().unwrap();
let exit_code = match output.status.code() {
Some(exit_code) => exit_code,
None if output.status.success() => 0,
None => 1,
};
if !output.stderr.is_empty() && exit_code != 0 {
std::io::stderr().write_all(&output.stderr).unwrap();
return Ok(1);
}
Ok(0)
}
pub fn serve(dir: PathBuf, prog_args: &[String]) -> Result<i32> {
let spinners = MultiProgress::new();
let did_build = !prog_args.contains(&"--no-build".to_string());
let should_run = !prog_args.contains(&"--no-run".to_string());
let exec = Arc::new(Mutex::new(String::new()));
let sb_thread = build_server(dir.clone(), &spinners, did_build, Arc::clone(&exec))?;
if did_build {
let (sg_thread, wb_thread) = build_internal(dir.clone(), &spinners, 4)?;
let sg_res = sg_thread
.join()
.map_err(|_| ErrorKind::ThreadWaitFailed)??;
let wb_res = wb_thread
.join()
.map_err(|_| ErrorKind::ThreadWaitFailed)??;
if sg_res != 0 {
return Ok(sg_res);
} else if wb_res != 0 {
return Ok(wb_res);
}
}
let sb_res = sb_thread
.join()
.map_err(|_| ErrorKind::ThreadWaitFailed)??;
if sb_res != 0 {
return Ok(sb_res);
}
if did_build {
finalize(&dir.join(".perseus"))?;
}
if should_run {
let exit_code = run_server(Arc::clone(&exec), dir, did_build)?;
Ok(exit_code)
} else {
let exec_str: String = (*exec.lock().unwrap()).to_string();
println!("Not running server because `--no-run` was provided. You can run it manually by running the following executable in `.perseus/server/`.\n{}", exec_str);
Ok(0)
}
}