1pub mod dynamic_router;
2pub mod embed_webserver;
3pub mod prelude;
4pub mod spec;
5pub mod static_router;
6mod termination;
7pub mod types;
8
9pub use prelude::*;
10
11pub fn init_tracing_subscriber(debug: bool) {
17 let level = if debug {
18 tracing::level_filters::LevelFilter::DEBUG
19 } else {
20 tracing::level_filters::LevelFilter::INFO
21 };
22
23 tracing_subscriber::fmt()
24 .with_env_filter(
25 tracing_subscriber::EnvFilter::from_default_env().add_directive(level.into()),
26 )
27 .without_time()
28 .with_ansi(false)
29 .init();
30}
31
32pub async fn start_plugin<S, P>(
42 app: axum::Router<S>,
43 state: S,
44 addr: std::net::SocketAddr,
45 ui_path: Option<P>,
46) -> anyhow::Result<()>
47where
48 S: Clone + Send + Sync + 'static,
49 P: AsRef<str>,
50{
51 let (terminator, mut rx) = termination::create_termination();
52
53 let listener = tokio::net::TcpListener::bind(addr).await?;
54
55 let termination_handler = async move |_: axum::extract::State<S>| {
57 if let Err(e) = terminator.terminate(termination::Interrupted::UserInt) {
58 tracing::error!("Failed to send termination signal: {e:?}");
59 axum::http::StatusCode::INTERNAL_SERVER_ERROR
60 } else {
61 axum::http::StatusCode::OK
62 }
63 };
64
65 let app = if let Some(ui_path) = ui_path {
66 let term_path = format!("{}/term", ui_path.as_ref().trim_end_matches('/'));
67
68 app.route(&term_path, axum::routing::get(termination_handler.clone()))
69 } else {
70 app
71 };
72
73 let server_future = axum::serve(listener, app.with_state(state));
74
75 tokio::select! {
76 _ = rx.recv() => {
77 tracing::info!("Termination signal received, shutting down plugin.");
78 Ok(())
79 }
80 result = server_future => {
81 if let Err(e) = result {
82 tracing::error!("Axum server error: {e:?}",);
83 Err(anyhow::anyhow!("Axum server error: {e:?}",))
84 } else {
85 tracing::info!("Axum server has shut down.");
86 Ok(())
87 }
88 }
89 }
90}