1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//! # OpenVet Backend
//!

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?)
    }
}