use std::sync::Arc;
use axum::{extract::State, response::IntoResponse, routing::post};
use endhost_api_models::{PathDiscovery, UnderlayDiscovery};
use endhost_api_protobuf::endhost::api_service::v1::{
ListSegmentsRequest, ListSegmentsResponse, ListUnderlaysRequest, ListUnderlaysResponse,
};
use scion_proto::{address::IsdAsn, path::SegmentsError};
use scion_sdk_axum_connect_rpc::extractor::ConnectRpc;
pub const ENDHOST_API_V1: &str = "scion.endhost.v1";
pub const UNDERLAY_SERVICE: &str = "UnderlayService";
pub const PATH_SERVICE: &str = "PathService";
pub const LIST_UNDERLAYS: &str = "/ListUnderlays";
pub const LIST_PATHS: &str = "/ListPaths";
pub fn nest_endhost_api(
base_router: axum::Router,
underlay_service: Arc<dyn UnderlayDiscovery>,
path_service: Arc<dyn PathDiscovery>,
) -> axum::Router {
let underlay_router = axum::Router::new()
.route(LIST_UNDERLAYS, post(list_underlays_handler))
.with_state(underlay_service);
let base_router = base_router.nest(
&service_path(ENDHOST_API_V1, UNDERLAY_SERVICE),
underlay_router,
);
let path_router = axum::Router::new()
.route(LIST_PATHS, post(list_segments_handler))
.with_state(path_service);
base_router.nest(&service_path(ENDHOST_API_V1, PATH_SERVICE), path_router)
}
async fn list_underlays_handler(
State(underlay_service): State<Arc<dyn UnderlayDiscovery>>,
ConnectRpc(request): ConnectRpc<ListUnderlaysRequest>,
) -> ConnectRpc<ListUnderlaysResponse> {
ConnectRpc(
underlay_service
.list_underlays(request.isd_as.map(IsdAsn::from).unwrap_or(IsdAsn::WILDCARD))
.into(),
)
}
async fn list_segments_handler(
State(path_service): State<Arc<dyn PathDiscovery>>,
ConnectRpc(request): ConnectRpc<ListSegmentsRequest>,
) -> Result<ConnectRpc<ListSegmentsResponse>, axum::response::Response> {
let (src, dst) = (
IsdAsn::from(request.src_isd_as),
IsdAsn::from(request.dst_isd_as),
);
match path_service
.list_segments(src, dst, request.page_size, request.page_token)
.await
{
Ok(segments) => Ok(ConnectRpc(segments.into())),
Err(SegmentsError::InvalidArgument(msg)) => {
Err((axum::http::StatusCode::BAD_REQUEST, msg).into_response())
}
Err(SegmentsError::InternalError(msg)) => {
Err((axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg).into_response())
}
}
}
fn service_path(api: &str, service: &str) -> String {
format!("/{api}.{service}")
}