Skip to content

Commit

Permalink
Applying DI to api layer
Browse files Browse the repository at this point in the history
  • Loading branch information
williamwoldum committed Nov 20, 2023
1 parent b8d8571 commit 4bb7a4c
Show file tree
Hide file tree
Showing 11 changed files with 120 additions and 28 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ serde = "1.0.189"
chrono = "0.4.31"
uuid = { version = "1.5.0", features = ["v4"] }
regex = "1.10.2"
mockall = "0.11.4"

[build-dependencies]
tonic-build = "0.10.2"
Expand Down
49 changes: 25 additions & 24 deletions src/api/ecdar_api.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
use std::env;
use std::fmt::{Debug, Formatter};
use std::sync::Arc;

use crate::api::server::server::get_auth_token_request::user_credentials;
use crate::entities::session::Model;
use chrono::Local;
use mockall::automock;
use regex::Regex;
use sea_orm::SqlErr;
use tonic::{Code, Request, Response, Status};

use crate::api::server::server::{
ecdar_api_auth_server::EcdarApiAuth, ecdar_api_server::EcdarApi,
ecdar_backend_client::EcdarBackendClient,
};
use crate::api::server::server::{ecdar_api_auth_server::EcdarApiAuth, ecdar_api_server::EcdarApi};
use crate::database::access_context::AccessContextTrait;
use crate::database::in_use_context::InUseContextTrait;
use crate::database::model_context::ModelContextTrait;
Expand All @@ -29,9 +28,9 @@ use super::{
},
};

#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct ConcreteEcdarApi {
reveaal_address: String,
reveaal_context: Arc<dyn EcdarBackend>,
model_context: Arc<dyn ModelContextTrait>,
user_context: Arc<dyn UserContextTrait>,
access_context: Arc<dyn AccessContextTrait>,
Expand All @@ -40,6 +39,19 @@ pub struct ConcreteEcdarApi {
in_use_context: Arc<dyn InUseContextTrait>,
}

impl Debug for ConcreteEcdarApi {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("")
.field(&self.model_context)
.field(&self.user_context)
.field(&self.access_context)
.field(&self.query_context)
.field(&self.session_context)
.field(&self.in_use_context)
.finish()
}
}

/// Updates or creates a session in the database for a given user.
///
///
Expand Down Expand Up @@ -125,10 +137,10 @@ impl ConcreteEcdarApi {
query_context: Arc<dyn QueryContextTrait>,
session_context: Arc<dyn SessionContextTrait>,
in_use_context: Arc<dyn InUseContextTrait>,
reveaal_context: Arc<dyn EcdarBackend>,
) -> Self {
ConcreteEcdarApi {
reveaal_address: env::var("REVEAAL_ADDRESS")
.expect("Expected REVEAAL_ADDRESS to be set."),
reveaal_context,
model_context,
user_context,
access_context,
Expand Down Expand Up @@ -370,45 +382,34 @@ impl EcdarApiAuth for ConcreteEcdarApi {

/// Implementation of the EcdarBackend trait, which is used to ensure backwards compatability with the Reveaal engine.
#[tonic::async_trait]
#[automock]
impl EcdarBackend for ConcreteEcdarApi {
async fn get_user_token(
&self,
_request: Request<()>,
) -> Result<Response<UserTokenResponse>, Status> {
let mut client = EcdarBackendClient::connect(self.reveaal_address.clone())
.await
.unwrap();
client.get_user_token(_request).await
self.reveaal_context.get_user_token(_request).await
}

async fn send_query(
&self,
request: Request<QueryRequest>,
) -> Result<Response<QueryResponse>, Status> {
let mut client = EcdarBackendClient::connect(self.reveaal_address.clone())
.await
.unwrap();
client.send_query(request).await
self.reveaal_context.send_query(request).await
}

async fn start_simulation(
&self,
request: Request<SimulationStartRequest>,
) -> Result<Response<SimulationStepResponse>, Status> {
let mut client = EcdarBackendClient::connect(self.reveaal_address.clone())
.await
.unwrap();
client.start_simulation(request).await
self.reveaal_context.start_simulation(request).await
}

async fn take_simulation_step(
&self,
request: Request<SimulationStepRequest>,
) -> Result<Response<SimulationStepResponse>, Status> {
let mut client = EcdarBackendClient::connect(self.reveaal_address.clone())
.await
.unwrap();
client.take_simulation_step(request).await
self.reveaal_context.take_simulation_step(request).await
}
}

Expand Down
1 change: 1 addition & 0 deletions src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod auth;
pub mod ecdar_api;
pub mod reveaal_context;
pub mod server;
67 changes: 67 additions & 0 deletions src/api/reveaal_context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use crate::api::server::server::ecdar_backend_client::EcdarBackendClient;
use crate::api::server::server::ecdar_backend_server::EcdarBackend;
use crate::api::server::server::{
QueryRequest, QueryResponse, SimulationStartRequest, SimulationStepRequest,
SimulationStepResponse, UserTokenResponse,
};
use async_trait::async_trait;
use std::env;
use tonic::transport::Channel;
use tonic::{Request, Response, Status};

#[derive(Debug)]
pub struct ReveaalContext;

impl ReveaalContext {
async fn get_connection() -> EcdarBackendClient<Channel> {
let url = env::var("REVEAAL_ADDRESS").expect("Expected REVEAAL_ADDRESS to be set.");
EcdarBackendClient::connect(url).await.unwrap()
}
}

#[async_trait]
impl EcdarBackend for ReveaalContext {
async fn get_user_token(
&self,
request: Request<()>,
) -> Result<Response<UserTokenResponse>, Status> {
Ok(ReveaalContext::get_connection()
.await
.get_user_token(request)
.await
.unwrap())
}

async fn send_query(
&self,
request: Request<QueryRequest>,
) -> Result<Response<QueryResponse>, Status> {
Ok(ReveaalContext::get_connection()
.await
.send_query(request)
.await
.unwrap())
}

async fn start_simulation(
&self,
request: Request<SimulationStartRequest>,
) -> Result<Response<SimulationStepResponse>, Status> {
Ok(ReveaalContext::get_connection()
.await
.start_simulation(request)
.await
.unwrap())
}

async fn take_simulation_step(
&self,
request: Request<SimulationStepRequest>,
) -> Result<Response<SimulationStepResponse>, Status> {
Ok(ReveaalContext::get_connection()
.await
.take_simulation_step(request)
.await
.unwrap())
}
}
4 changes: 3 additions & 1 deletion src/api/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::api::auth;
use crate::api::ecdar_api::ConcreteEcdarApi;
use crate::api::server::server::ecdar_api_auth_server::EcdarApiAuthServer;
use crate::api::server::server::ecdar_api_server::EcdarApiServer;
use crate::api::server::server::ecdar_backend_server::EcdarBackendServer;
use crate::api::server::server::ecdar_backend_server::{EcdarBackend, EcdarBackendServer};
use crate::database::access_context::AccessContextTrait;
use crate::database::in_use_context::InUseContextTrait;
use crate::database::model_context::ModelContextTrait;
Expand All @@ -20,6 +20,7 @@ pub mod server {
}

pub async fn start_grpc_server(
reveaal_context: Arc<dyn EcdarBackend>,
model_context: Arc<dyn ModelContextTrait>,
user_context: Arc<dyn UserContextTrait>,
access_context: Arc<dyn AccessContextTrait>,
Expand All @@ -42,6 +43,7 @@ pub async fn start_grpc_server(
query_context,
session_context,
in_use_context,
reveaal_context,
)
.await;

Expand Down
1 change: 1 addition & 0 deletions src/database/entity_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::fmt::Debug;
use std::sync::Arc;

#[async_trait]

pub trait EntityContextTrait<T>: Send + Sync + Debug {
fn new(db_context: Arc<dyn DatabaseContextTrait>) -> Self
where
Expand Down
1 change: 1 addition & 0 deletions src/database/session_context.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use chrono::{Local, Utc};
use mockall::automock;
use sea_orm::prelude::async_trait::async_trait;
use sea_orm::ActiveValue::{Set, Unchanged};
use sea_orm::{ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, QueryFilter};
Expand Down
1 change: 1 addition & 0 deletions src/database/user_context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::database::database_context::DatabaseContextTrait;
use crate::database::entity_context::EntityContextTrait;
use crate::entities::user;
use mockall::automock;
use sea_orm::prelude::async_trait::async_trait;
use sea_orm::ActiveValue::{Set, Unchanged};
use sea_orm::{ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, QueryFilter};
Expand Down
4 changes: 4 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ mod database;
mod entities;
mod tests;

use crate::api::reveaal_context::ReveaalContext;
use crate::api::server::server::ecdar_backend_server::EcdarBackend;
use crate::database::access_context::AccessContext;
use crate::database::database_context::{PostgresDatabaseContext, SQLiteDatabaseContext};
use crate::database::in_use_context::InUseContext;
Expand Down Expand Up @@ -37,8 +39,10 @@ async fn main() -> Result<(), Box<dyn Error>> {
let query_context = Arc::new(QueryContext::new(db_context.clone()));
let session_context = Arc::new(SessionContext::new(db_context.clone()));
let in_use_context = Arc::new(InUseContext::new(db_context.clone()));
let reveaal_context = Arc::new(ReveaalContext);

start_grpc_server(
reveaal_context,
model_context,
user_context,
access_context,
Expand Down
8 changes: 6 additions & 2 deletions src/tests/api/ecdar_api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#[cfg(test)]
mod ecdar_api {
use crate::api::ecdar_api::handle_session;
use crate::api::ecdar_api::{
handle_session, MockConcreteEcdarApi, MockConcreteEcdarApi_EcdarBackend,
};
use crate::api::server::server::ecdar_api_auth_server::EcdarApiAuth;
use crate::api::server::server::get_auth_token_request::user_credentials;
use crate::api::server::server::get_auth_token_request::UserCredentials;
Expand All @@ -10,7 +12,9 @@ mod ecdar_api {
entities::user::Model as User,
};
use std::str::FromStr;
use std::sync::Arc;

use crate::api::server::server::ecdar_backend_server::EcdarBackend;
use crate::tests::api::helpers::get_reset_concrete_ecdar_api;
use tonic::{metadata, Request};

Expand Down Expand Up @@ -371,7 +375,7 @@ mod ecdar_api {

#[tokio::test]
async fn handle_session_update_non_existing_session_returns_err() {
let api = get_reset_concrete_ecdar_api().await;
let api = get_reset_concrete_ecdar_api(Arc::new(MockEcdarBackend)).await;

let mut get_auth_token_request = Request::new(GetAuthTokenRequest {
user_credentials: Some(UserCredentials {
Expand Down
11 changes: 10 additions & 1 deletion src/tests/api/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
#![cfg(test)]

use crate::api::ecdar_api::ConcreteEcdarApi;
use crate::api::server::server::ecdar_backend_server::EcdarBackend;
use crate::api::server::server::{
QueryRequest, QueryResponse, SimulationStartRequest, SimulationStepRequest,
SimulationStepResponse, UserTokenResponse,
};
use crate::database::access_context::AccessContext;
use crate::database::database_context::{
DatabaseContextTrait, PostgresDatabaseContext, SQLiteDatabaseContext,
Expand All @@ -15,8 +20,11 @@ use dotenv::dotenv;
use sea_orm::{ConnectionTrait, Database, DbBackend};
use std::env;
use std::sync::Arc;
use tonic::{Request, Response, Status};

pub async fn get_reset_concrete_ecdar_api() -> ConcreteEcdarApi {
pub async fn get_reset_concrete_ecdar_api(
mock_ecdar_backend: Arc<dyn EcdarBackend>,
) -> ConcreteEcdarApi {
dotenv().ok();

let url = env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set to run tests.");
Expand All @@ -43,6 +51,7 @@ pub async fn get_reset_concrete_ecdar_api() -> ConcreteEcdarApi {
query_context,
session_context,
in_use_context,
mock_ecdar_backend,
)
.await
}

0 comments on commit 4bb7a4c

Please sign in to comment.