arcana-base-server 0.6.0

Library to help create your own arcana activation server
Documentation
use std::collections::HashMap;
use std::fmt::Display;
use std::io::Result as IoResult;
use std::sync::Arc;

use log::{debug, error};

use rand_chacha::ChaCha20Rng;
use rand_core::{RngCore, SeedableRng};
use tokio::sync::{Mutex, mpsc};
use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Response, Status, async_trait};
use url::Url;

use crate::activation::{
    ApplyRequest, ApplyResponse, BuildRequest, BuildResponse, ConnectRequest, ConnectResponse,
    CopyClosureRequest, CopyClosureResponse, HeadedRequest, RequestHeader,
    activation_server::Activation,
};
use crate::util::decode_session_id;

type Stream<U> = ReceiverStream<Result<U, Status>>;
type ApplyStream = Stream<ApplyResponse>;
type BuildStream = Stream<BuildResponse>;
type CopyClosureStream = Stream<CopyClosureResponse>;

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct Id([u8; 32]);

/// Generic implementation of the activation server.
/// Communication with the arcana client is abstracted by this object.
///
/// This object takes 3 functions:
/// * The `apply_function`, which takes an ApplyRequest and process it
/// * The `build_function`, which takes a BuildRequest and process it
/// * The `copy_closure_function`, which takes a CopyClosureRequest and process it
///
/// Types of each functions must be:
/// * `async fn apply_function(TH, tokio::sync::mpsc::Sender<Result<ApplyResponse, Status>>,
/// ApplyRequest) -> std::io::Result<()>`
/// * `async fn build_function(TH, tokio::sync::mpsc::Sender<Result<BuildResponse, Status>>,
/// BuildRequest) -> std::io::Result<()>`
/// * `async fn copy_closure__function(TH, tokio::sync::mpsc::Sender<Result<CopyClosureResponse, Status>>,
/// CopyClosureRequest) -> std::io::Result<()>`
///
/// TH generic type is the abstraction of the Target Host and should be able to
/// parse a url. It is used as a state object through functions.
/// This type has to be implemented by the server implementation.
///
/// `AT`, `BT` and `CT` are generic types which describe the type of the functions
/// `apply_function`, `build_function` and `copy_closure_function` respectively.
/// If you follow the signature as described above, the functions will have the correct type.
#[derive(Debug, Clone)]
pub struct ActivationServiceImpl<TH, AT, BT, CT>
where
    TH: Clone,
    TH: TryFrom<Url, Error = String>,
    TH: Send,
    TH: Display,
    TH: 'static,
    AT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<ApplyResponse, Status>>,
            ApplyRequest,
            Output = IoResult<()>,
        >,
    AT: Send,
    AT: Sync,
    AT: Copy,
    AT: 'static,
    BT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<BuildResponse, Status>>,
            BuildRequest,
            Output = IoResult<()>,
        >,
    BT: Send,
    BT: Sync,
    BT: Copy,
    BT: 'static,
    CT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<CopyClosureResponse, Status>>,
            CopyClosureRequest,
            Output = IoResult<()>,
        >,
    CT: Send,
    CT: Sync,
    CT: Copy,
    CT: 'static,
{
    apply_function: AT,
    build_function: BT,
    copy_closure_function: CT,
    targets: Arc<Mutex<HashMap<Id, TH>>>,
}

impl<TH, AT, BT, CT> ActivationServiceImpl<TH, AT, BT, CT>
where
    TH: Clone,
    TH: TryFrom<Url, Error = String>,
    TH: Send,
    TH: Display,
    TH: 'static,
    AT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<ApplyResponse, Status>>,
            ApplyRequest,
            Output = IoResult<()>,
        >,
    AT: Send,
    AT: Sync,
    AT: Copy,
    AT: 'static,
    BT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<BuildResponse, Status>>,
            BuildRequest,
            Output = IoResult<()>,
        >,
    BT: Send,
    BT: Sync,
    BT: Copy,
    BT: 'static,
    CT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<CopyClosureResponse, Status>>,
            CopyClosureRequest,
            Output = IoResult<()>,
        >,
    CT: Send,
    CT: Sync,
    CT: Copy,
    CT: 'static,
{
    pub fn new(apply_function: AT, build_function: BT, copy_closure_function: CT) -> Self {
        Self {
            apply_function,
            build_function,
            copy_closure_function,
            targets: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    async fn process_request<Req, Resp, F>(
        &self,
        request: Request<Req>,
        callback: F,
    ) -> Result<Response<Stream<Resp>>, Status>
    where
        Req: HeadedRequest,
        Req: Send,
        Req: 'static,
        Resp: Send,
        Resp: 'static,
        F: async_fn_traits::AsyncFnOnce3<
                TH,
                mpsc::Sender<Result<Resp, Status>>,
                Req,
                Output = IoResult<()>,
            > + std::marker::Send
            + 'static,
    {
        let req = request.into_inner();

        let target = self.get_target(req.header().as_ref()).await?.clone();

        let (tx, rx) = mpsc::channel(128);

        tokio::task::spawn_blocking(move || {
            if let Err(e) = tokio::runtime::Handle::current().block_on(callback(target, tx, req)) {
                error!("{e:?}");
            }
        });

        Ok(Response::new(ReceiverStream::new(rx)))
    }

    async fn get_target(&self, request_header: Option<&RequestHeader>) -> Result<TH, Status> {
        // Because each connection is identified by an unique id, we have
        // to get the connection information from this id.
        let session_id = match request_header {
            Some(header) => Id(decode_session_id(&header.session_id)
                .map_err(|_| Status::unauthenticated("invalid session_id"))?),
            None => {
                return Err(Status::unauthenticated("session_id was not provided"));
            }
        };

        let targets = self.targets.lock().await;

        (*targets)
            .get(&session_id)
            .ok_or(Status::unauthenticated("invalid session_id"))
            .cloned()
    }
}

#[async_trait]
impl<TH, AT, BT, CT> Activation for ActivationServiceImpl<TH, AT, BT, CT>
where
    TH: Clone,
    TH: TryFrom<Url, Error = String>,
    TH: Send,
    TH: Display,
    TH: 'static,
    AT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<ApplyResponse, Status>>,
            ApplyRequest,
            Output = IoResult<()>,
        >,
    AT: Send,
    AT: Sync,
    AT: Copy,
    AT: 'static,
    BT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<BuildResponse, Status>>,
            BuildRequest,
            Output = IoResult<()>,
        >,
    BT: Send,
    BT: Sync,
    BT: Copy,
    BT: 'static,
    CT: async_fn_traits::AsyncFnOnce3<
            TH,
            mpsc::Sender<Result<CopyClosureResponse, Status>>,
            CopyClosureRequest,
            Output = IoResult<()>,
        >,
    CT: Send,
    CT: Sync,
    CT: Copy,
    CT: 'static,
{
    type ApplyStream = ApplyStream;
    type BuildStream = BuildStream;
    type CopyClosureStream = CopyClosureStream;

    async fn apply(&self, request: Request<ApplyRequest>) -> Result<Response<ApplyStream>, Status> {
        self.process_request(request, self.apply_function).await
    }

    async fn build(&self, request: Request<BuildRequest>) -> Result<Response<BuildStream>, Status> {
        self.process_request(request, self.build_function).await
    }

    async fn copy_closure(
        &self,
        request: Request<CopyClosureRequest>,
    ) -> Result<Response<CopyClosureStream>, Status> {
        self.process_request(request, self.copy_closure_function)
            .await
    }

    async fn connect_to(
        &self,
        request: Request<ConnectRequest>,
    ) -> Result<Response<ConnectResponse>, Status> {
        let req = request.into_inner();

        // Uri used to connect to the client should follow the URL standard.
        // Uri is parsed by the Url parser and then passed to the
        // servertype-specific TargetHost which also parse the uri.
        let uri = Url::parse(&req.connection_uri)
            .map_err(|_| Status::invalid_argument("connection_uri is malformed"))?;

        let target = TH::try_from(uri).map_err(|err| {
            Status::invalid_argument(format!("error while parsing connection_uri, {err}"))
        })?;

        debug!("New session for connection {}", target);

        // Each connection is identified with an unique id to be able to accept
        // multiple activations at the same time.
        let mut id: [u8; 32] = [0; 32];
        ChaCha20Rng::from_os_rng().fill_bytes(&mut id);

        let session_id = Id(id);

        let mut targets = self.targets.lock().await;
        (*targets).insert(session_id.clone(), target);

        // We send back the id as a hexstring, so we just transform
        // the [u8; 32] into String.
        Ok(Response::new(ConnectResponse {
            session_id: session_id
                .0
                .iter()
                .fold(String::new(), |s, i| format!("{s}{i:02x}")),
        }))
    }
}