use std::net::SocketAddr;
use std::sync::Arc;
use axum_server::tls_rustls::RustlsConfig;
use tokio::task::JoinHandle;
use torrust_tracker_configuration::{AccessTokens, HttpApi};
use tracing::instrument;
use super::make_rust_tls;
use crate::core;
use crate::servers::apis::server::{ApiServer, Launcher};
use crate::servers::apis::Version;
use crate::servers::registar::ServiceRegistrationForm;
#[derive(Debug)]
pub struct ApiServerJobStarted();
#[instrument(skip(config, tracker, form))]
pub async fn start_job(
config: &HttpApi,
tracker: Arc<core::Tracker>,
form: ServiceRegistrationForm,
version: Version,
) -> Option<JoinHandle<()>> {
let bind_to = config.bind_address;
let tls = make_rust_tls(&config.tsl_config)
.await
.map(|tls| tls.expect("it should have a valid tracker api tls configuration"));
let access_tokens = Arc::new(config.access_tokens.clone());
match version {
Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), form, access_tokens).await),
}
}
#[allow(clippy::async_yields_async)]
#[instrument(skip(socket, tls, tracker, form, access_tokens))]
async fn start_v1(
socket: SocketAddr,
tls: Option<RustlsConfig>,
tracker: Arc<core::Tracker>,
form: ServiceRegistrationForm,
access_tokens: Arc<AccessTokens>,
) -> JoinHandle<()> {
let server = ApiServer::new(Launcher::new(socket, tls))
.start(tracker, form, access_tokens)
.await
.expect("it should be able to start to the tracker api");
tokio::spawn(async move {
assert!(!server.state.halt_task.is_closed(), "Halt channel should be open");
server.state.task.await.expect("failed to close service");
})
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use torrust_tracker_test_helpers::configuration::ephemeral_public;
use crate::bootstrap::app::initialize_with_configuration;
use crate::bootstrap::jobs::tracker_apis::start_job;
use crate::servers::apis::Version;
use crate::servers::registar::Registar;
#[tokio::test]
async fn it_should_start_http_tracker() {
let cfg = Arc::new(ephemeral_public());
let config = &cfg.http_api.clone().unwrap();
let tracker = initialize_with_configuration(&cfg);
let version = Version::V1;
start_job(config, tracker, Registar::default().give_form(), version)
.await
.expect("it should be able to join to the tracker api start-job");
}
}