78 lines
3.0 KiB
Rust
78 lines
3.0 KiB
Rust
extern crate botdiscord;
|
|
use ::tracing::info;
|
|
use actix_cors::Cors;
|
|
use actix_web::dev::Service;
|
|
use actix_web::http::header;
|
|
use actix_web::{web, App, HttpServer};
|
|
use botdiscord::api::apidocs::ApiDocs;
|
|
use botdiscord::api::init::init_api;
|
|
use botdiscord::config::parse_local_config;
|
|
use botdiscord::db;
|
|
use botdiscord::{botv2::init::start_bot, tracing};
|
|
use std::{process, time::Duration};
|
|
use tokio::{sync::oneshot, time::sleep};
|
|
use tracing_actix_web::{RequestId, TracingLogger};
|
|
use utoipa::OpenApi;
|
|
use utoipa_swagger_ui::SwaggerUi;
|
|
|
|
#[actix_web::main]
|
|
async fn main() -> std::io::Result<()> {
|
|
let config = parse_local_config();
|
|
let port = config.port;
|
|
tracing::init::init_tracing(config.tracing.clone(), config.bot_name.clone());
|
|
match db::init::init_db(config.persistence.clone()).await {
|
|
Ok(_) => {}
|
|
Err(e) => {
|
|
println!("Error initializing database: {}", e);
|
|
return Ok(());
|
|
}
|
|
}
|
|
let (tx, rx) = oneshot::channel();
|
|
let http = start_bot(config.clone(), rx).await;
|
|
info!("API Server started on port {}", port);
|
|
let mut openapi = ApiDocs::openapi();
|
|
openapi.info.title = format!("{} Api", config.bot_name.clone());
|
|
openapi.info.version = env!("CARGO_PKG_VERSION").to_string();
|
|
let api_config = config.clone();
|
|
HttpServer::new(move || {
|
|
let cors = Cors::default()
|
|
.allow_any_header()
|
|
.allow_any_method()
|
|
.allow_any_origin();
|
|
let swagger_ui =
|
|
SwaggerUi::new("/api/docs/{_:.*}").url("/api/docs/docs.json", openapi.clone());
|
|
App::new()
|
|
.app_data(web::Data::new(api_config.clone()))
|
|
.app_data(web::Data::new(http.clone()))
|
|
.wrap(cors)
|
|
.service(swagger_ui)
|
|
.service(
|
|
init_api()
|
|
.wrap_fn(|mut req, srv| {
|
|
let request_id_asc = req.extract::<RequestId>();
|
|
let fut = srv.call(req);
|
|
async move {
|
|
let mut res = fut.await?;
|
|
let request_id: RequestId = request_id_asc.await.unwrap();
|
|
let request_id_str = format!("{}", request_id);
|
|
let headers = res.headers_mut();
|
|
headers.insert(
|
|
header::HeaderName::from_static("x-request-id"),
|
|
header::HeaderValue::from_str(request_id_str.as_str()).unwrap(),
|
|
);
|
|
Ok(res)
|
|
}
|
|
})
|
|
.wrap(TracingLogger::default()),
|
|
)
|
|
})
|
|
.bind(("0.0.0.0", port))?
|
|
.run()
|
|
.await?;
|
|
info!("API Server stopped.");
|
|
tx.send(()).unwrap();
|
|
tracing::init::stop_tracing(config.tracing.clone(), config.bot_name.clone());
|
|
sleep(Duration::from_secs(2)).await;
|
|
process::exit(1); // This is a workaround to stop the bot, it should be replaced by a better solution
|
|
}
|