vacuna/
lib.rs

1use std::{
2    error::Error,
3    result::Result,
4    sync::mpsc::{channel, Sender},
5};
6
7mod config;
8mod error;
9mod files;
10mod log_middleware;
11mod server;
12
13use actix_web::dev::ServerHandle;
14pub use config::Config;
15pub use server::server;
16use tracing::error;
17
18pub struct Vacuna {
19    server: ServerHandle,
20}
21
22impl Vacuna {
23    pub fn start_background_from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Box<dyn Error>> {
24        let config = Config::read(path)?;
25        Self::start_background(config)
26    }
27    pub fn start_background_from_string_config(text: &str) -> Result<Self, Box<dyn Error>> {
28        let config = Config::from_str(text)?;
29        Self::start_background(config)
30    }
31    pub fn start_background(config: Config) -> Result<Self, Box<dyn Error>> {
32        let (started_tx, started_rx) = channel();
33        std::thread::spawn(move || {
34            actix_rt::System::new().block_on(async move {
35                if let Err(e) = Self::background_start(config, started_tx).await {
36                    error!("fail background start {}", e)
37                }
38            });
39        });
40        let handle = started_rx.recv()?;
41        Ok(Self { server: handle })
42    }
43    async fn background_start(config: Config, started_tx: Sender<ServerHandle>) -> Result<(), Box<dyn Error>> {
44        let server = server(config)?;
45        started_tx.send(server.handle())?;
46        server.await?;
47        Ok(())
48    }
49
50    pub async fn run_from_file<P: AsRef<std::path::Path>>(path: P) -> Result<(), Box<dyn Error>> {
51        let config = Config::read(path)?;
52        Self::run(config).await?;
53        Ok(())
54    }
55    pub async fn run(config: Config) -> Result<(), Box<dyn Error>> {
56        let server = server(config)?;
57        server.await?;
58        Ok(())
59    }
60    pub async fn stop(&self) {
61        self.server.stop(true).await;
62    }
63}