stateroom_cli/commands/
serve.rs1use crate::cli_opts::ServeCommand;
2use stateroom_server::Server;
3use stateroom_wasm_host::WasmHostFactory;
4use std::{ffi::OsStr, path::Path, time::Duration};
5
6pub fn serve(serve_opts: ServeCommand) -> anyhow::Result<()> {
7 let ServeCommand {
8 module,
9 port,
10 heartbeat_interval,
11 heartbeat_timeout,
12 } = serve_opts;
13
14 let path = Path::new(&module);
15 let ext = path
16 .extension()
17 .and_then(OsStr::to_str)
18 .map(str::to_ascii_lowercase);
19
20 let server_settings = Server {
21 heartbeat_interval: Duration::from_secs(heartbeat_interval),
22 heartbeat_timeout: Duration::from_secs(heartbeat_timeout),
23 port,
24 ..Server::default()
25 };
26
27 if let Some("wasm" | "wat") = ext.as_deref() {
28 let host_factory = WasmHostFactory::new(&module)?;
29 server_settings.serve(host_factory).map_err(|e| e.into())
30 } else if path.is_file() {
31 unimplemented!("Only .wasm and .wat files are supported.");
32 } else if path.is_dir() {
33 let server_module = path.join("server.wasm");
34
35 if !server_module.exists() {
36 return Err(anyhow::anyhow!("Expected server.wasm"));
37 }
38
39 let static_dir = path.join("static");
40
41 let static_dir = if static_dir.exists() {
42 Some(static_dir.to_str().unwrap().to_string())
43 } else {
44 None
45 };
46
47 let host_factory = WasmHostFactory::new(&server_module)?;
48
49 server_settings
50 .with_static_path(static_dir)
51 .serve(host_factory)
52 .map_err(|e| e.into())
53 } else {
54 Err(anyhow::anyhow!("Expected a file or directory."))
55 }
56}