use anyhow::Result;
use axum::Router;
use openvet_common::{rust::*, storage::StorageClient};
use std::{collections::BTreeSet, net::SocketAddr};
use tarpc::{client::Config, context, tokio_serde::formats::Json};
#[derive(Clone, Debug)]
pub struct Backend {
storage: StorageClient,
}
mod api;
impl Backend {
pub async fn new(storage: SocketAddr) -> Result<Self> {
let mut transport = tarpc::serde_transport::tcp::connect(storage, Json::default);
transport.config_mut().max_frame_length(usize::MAX);
let storage = StorageClient::new(Config::default(), transport.await?).spawn();
Ok(Self { storage })
}
pub async fn router(&self) -> Router {
Router::new().nest("/api", self.router_api())
}
pub async fn listen(&self, addr: SocketAddr) -> Result<()> {
let app = self.router().await;
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
pub fn storage(&self) -> &StorageClient {
&self.storage
}
pub async fn crates_list(&self) -> Result<BTreeSet<CrateName>> {
Ok(self.storage.crate_list(context::current()).await?)
}
}