forked from superradcompany/microsandbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmsbserver.rs
More file actions
89 lines (73 loc) · 2.61 KB
/
msbserver.rs
File metadata and controls
89 lines (73 loc) · 2.61 KB
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
use std::sync::Arc;
use tokio::sync::RwLock;
use axum::http::{
Method,
header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE},
};
use clap::Parser;
use microsandbox_cli::{MicrosandboxCliResult, MsbserverArgs};
use microsandbox_server::{Config, port::PortManager, route, state::AppState};
use microsandbox_utils::CHECKMARK;
use tower_http::cors::{Any, CorsLayer};
//--------------------------------------------------------------------------------------------------
// Functions: Main
//--------------------------------------------------------------------------------------------------
#[tokio::main]
pub async fn main() -> MicrosandboxCliResult<()> {
// Initialize tracing
tracing_subscriber::fmt::init();
// Parse command line arguments
let args = MsbserverArgs::parse();
if args.dev_mode {
tracing::info!("Development mode: {}", args.dev_mode);
println!(
"{} Running in {} mode",
&*CHECKMARK,
console::style("development").yellow()
);
}
// Create configuration from arguments
let config = Arc::new(Config::new(
args.key,
args.host,
args.port,
args.namespace_dir.clone(),
args.dev_mode,
)?);
// Get namespace directory and port range from config
let namespace_dir = config.get_namespace_dir().clone();
let port_range = (
config.get_port_range_min().as_ref().copied(),
config.get_port_range_max().as_ref().copied(),
);
// Initialize the port manager with the configured port range
let port_manager = if let (Some(min), Some(max)) = port_range {
PortManager::new_with_range(namespace_dir, Some((min, max))).await
} else {
PortManager::new(namespace_dir).await
}
.map_err(|e| {
eprintln!("Error initializing port manager: {}", e);
e
})?;
let port_manager = Arc::new(RwLock::new(port_manager));
// Create application state
let state = AppState::new(config.clone(), port_manager);
// Configure CORS
let cors = CorsLayer::new()
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
.allow_headers([AUTHORIZATION, ACCEPT, CONTENT_TYPE])
.allow_origin(Any);
// Build application
let app = route::create_router(state).layer(cors);
// Start server
tracing::info!("Starting server on {}", config.get_addr());
println!(
"{} Server listening on {}",
&*CHECKMARK,
console::style(config.get_addr()).yellow()
);
let listener = tokio::net::TcpListener::bind(config.get_addr()).await?;
axum::serve(listener, app).await?;
Ok(())
}