Skip to content

Commit

Permalink
fix: structure
Browse files Browse the repository at this point in the history
  • Loading branch information
thuan2172001 committed Apr 1, 2024
1 parent 96ddae9 commit a50a9fa
Show file tree
Hide file tree
Showing 44 changed files with 482 additions and 505 deletions.
215 changes: 106 additions & 109 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[workspace]
members = ["src/public", "src/grpc_server"]
members = ["src/public", "src/gpt_answer_server"]
resolver = "2"
16 changes: 8 additions & 8 deletions src/adapter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,14 @@ autoexamples = true
autotests = true
autobenches = true

[dependencies]
diesel_migrations = "2.1.0"
[dependencies.rust_core]
path = "../core"

[dependencies.common]
path = "../common"

[dependencies.diesel_migrations]
version = "2.1.0"

[dependencies.async-trait]
version = "0.1.77"
Expand All @@ -26,9 +32,6 @@ features = ["postgres", "serde"]
version = "2.1.4"
features = ["postgres", "postgres_backend", "uuid"]

[dependencies.rust_core]
path = "../core"

[dependencies.serde]
version = "1.0"
features = ["derive"]
Expand All @@ -46,6 +49,3 @@ version = "1.0.80"

[dependencies.tonic]
version = "0.11.0"

[dependencies.grpc_interface]
path = "../grpc"
15 changes: 0 additions & 15 deletions src/adapter/src/repositories/grpc/config.rs

This file was deleted.

103 changes: 103 additions & 0 deletions src/adapter/src/repositories/grpc/gpt_answer_client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
use anyhow::Error;
use tonic::{
async_trait,
transport::{Channel, Endpoint},
};

use common::grpc::gpt_answer::gpt_answer::{
gpt_answer_service_client::GptAnswerServiceClient, GetAnswerPayload,
};
use rust_core::{common::errors::CoreError, ports::gpt_answer::GptAnswerPort};

/// gRPC client for interacting with a GPT (Generative Pre-trained Transformer) answer service.
///
/// This struct represents a client for making gRPC calls to a GPT answer service. It provides
/// methods for connecting to the service, sending a question, and receiving an answer.
#[derive(Clone)]
pub struct GptAnswerClient {
client: Option<GptAnswerServiceClient<Channel>>,
endpoint: Endpoint,
}

impl GptAnswerClient {
/// Creates a new `GptAnswerClient` instance with the provided gRPC endpoint.
///
/// # Arguments
///
/// * `endpoint`: An `Endpoint` representing the gRPC communication endpoint.
///
/// # Returns
///
/// Returns a new instance of `GptAnswerClient`.
fn new(endpoint: Endpoint) -> Self {
Self {
client: None,
endpoint,
}
}

/// Initializes a new `GptAnswerClient` instance with the provided URI.
///
/// # Arguments
///
/// * `uri`: A `String` representing the URI of the GPT answer service.
///
/// # Returns
///
/// Returns a `Result` containing the initialized `GptAnswerClient` if successful,
/// or a `CoreError` if an error occurs during initialization.
pub async fn init(uri: String) -> Result<Self, CoreError> {
// Establish connection to the gRPC server
let endpoint =
Channel::from_shared(uri).map_err(|err| CoreError::InternalError(err.into()))?;

Ok(Self::new(endpoint))
}

/// Establishes a connection to the GPT answer service at the specified URI.
///
/// # Returns
///
/// Returns a `Result` containing the connected `GptAnswerServiceClient` if successful,
/// or a `CoreError` if an error occurs during connection.
pub async fn connect(&mut self) -> Result<(), CoreError> {
let client = GptAnswerServiceClient::connect(self.endpoint.clone())
.await
.map_err(|err| CoreError::InternalError(err.into()))?;

self.client = Some(client);
Ok(())
}
}

#[async_trait]
impl GptAnswerPort for GptAnswerClient {
/// Sends a question to the GPT answer service and retrieves the generated answer.
///
/// # Arguments
///
/// * `question`: A `&str` representing the question to be sent to the service.
///
/// # Returns
///
/// Returns a `Result` containing the generated answer as a `String` if successful,
/// or a `CoreError` if an error occurs during communication with the service.
async fn get_answer(&self, question: &str) -> Result<String, CoreError> {
let client = self
.client
.as_ref()
.ok_or_else(|| CoreError::InternalError(Error::msg("Client not initialized")))?;

let request = tonic::Request::new(GetAnswerPayload {
question: question.to_string(),
});

let response = client
.clone()
.get_answer(request)
.await
.map_err(|err| CoreError::InternalError(err.into()))?;

Ok(response.into_inner().answer)
}
}
3 changes: 1 addition & 2 deletions src/adapter/src/repositories/grpc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod config;
pub mod models;
pub mod gpt_answer_client;
40 changes: 0 additions & 40 deletions src/adapter/src/repositories/grpc/models/gpt_answer.rs

This file was deleted.

9 changes: 4 additions & 5 deletions src/adapter/src/repositories/postgres/models/question.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use std::{
io::{Error, ErrorKind},
time::SystemTime,
};
use std::io::{Error, ErrorKind};
use std::time::SystemTime;

use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use rust_core::entities::question::{QuestionEntity, QuestionId};
use serde::Serialize;

use rust_core::entities::question::{QuestionEntity, QuestionId};

#[derive(Debug, Queryable, Serialize, Selectable, Insertable, AsChangeset, Identifiable)]
#[diesel(table_name = super::super::schema::questions)]
#[cfg_attr(feature = "postgres", derive(diesel::pg::Pg))]
Expand Down
18 changes: 9 additions & 9 deletions src/adapter/src/repositories/postgres/question_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ impl QuestionPort for QuestionDBRepository {
.await
.unwrap()
.interact(move |conn| {
let question =
QuestionModel::try_from(question).map_err(|_| CoreError::InternalError)?;
let question = QuestionModel::try_from(question)
.map_err(|err| CoreError::InternalError(err.into()))?;
let response = insert_into(questions)
.values(&question)
.get_result::<QuestionModel>(conn)
.map_err(|err| match err {
diesel::result::Error::NotFound => CoreError::NotFound,
_ => CoreError::InternalError,
_ => CoreError::InternalError(err.into()),
})
.unwrap();
Ok(response.into())
Expand All @@ -59,14 +59,14 @@ impl QuestionPort for QuestionDBRepository {
.await
.unwrap()
.interact(move |conn| {
let question =
QuestionModel::try_from(question).map_err(|_| CoreError::InternalError)?;
let question = QuestionModel::try_from(question)
.map_err(|err| CoreError::InternalError(err.into()))?;
let response = update(questions.filter(id.eq(question.id)))
.set(&question)
.get_result::<QuestionModel>(conn)
.map_err(|err| match err {
diesel::result::Error::NotFound => CoreError::NotFound,
_ => CoreError::InternalError,
_ => CoreError::InternalError(err.into()),
})?
.into();

Expand All @@ -87,7 +87,7 @@ impl QuestionPort for QuestionDBRepository {
.execute(conn)
.map_err(|err| match err {
diesel::result::Error::NotFound => CoreError::NotFound,
_ => CoreError::InternalError,
_ => CoreError::InternalError(err.into()),
})?;

Ok(())
Expand All @@ -109,7 +109,7 @@ impl QuestionPort for QuestionDBRepository {
.first(conn)
.map_err(|err| match err {
diesel::result::Error::NotFound => CoreError::NotFound,
_ => CoreError::InternalError,
_ => CoreError::InternalError(err.into()),
})?
.into();

Expand All @@ -133,7 +133,7 @@ impl QuestionPort for QuestionDBRepository {
.load(conn)
.map_err(|err| match err {
diesel::result::Error::NotFound => CoreError::NotFound,
_ => CoreError::InternalError,
_ => CoreError::InternalError(err.into()),
})?;

Ok(question_list
Expand Down
2 changes: 1 addition & 1 deletion src/adapter/src/repositories/repository_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ mod tests {
query_params.insert("start".to_string(), "0".to_string());
query_params.insert("end".to_string(), "10".to_string());

let pagination = match PaginationEntity::from_query(&query_params) {
let pagination = match PaginationEntity::try_from(query_params) {
Ok(pagination_entity) => pagination_entity,
Err(err) => {
panic!("Failed to parse pagination entity: {:?}", err);
Expand Down
32 changes: 26 additions & 6 deletions src/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,20 @@ autoexamples = true
autotests = true
autobenches = true

[dependencies]
config = "0.14.0"
glob = "0.3.1"
tracing = "0.1"
tracing-bunyan-formatter = "0.3.9"
tracing-opentelemetry = "0.23.0"
[dependencies.config]
version = "0.14.0"

[dependencies.glob]
version = "0.3.1"

[dependencies.tracing]
version = "0.1"

[dependencies.tracing-bunyan-formatter]
version = "0.3.9"

[dependencies.tracing-opentelemetry]
version = "0.23.0"

[dependencies.opentelemetry]
version = "0.22.0"
Expand All @@ -39,3 +47,15 @@ features = ["derive"]
[dependencies.tracing-subscriber]
version = "0.3.18"
features = ["env-filter"]

[dependencies.tonic]
version = "0.11.0"

[dependencies.prost]
version = "0.12.3"

[build-dependencies.tonic-build]
version = "0.11.0"

[build-dependencies.glob]
version = "0.3.1"
File renamed without changes.
File renamed without changes.
9 changes: 9 additions & 0 deletions src/common/src/grpc/gpt_answer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/// Module for gRPC service definitions related to answering questions with GPT (Generative Pre-trained Transformer) models.
///
/// This module includes generated gRPC service definitions for answering questions using GPT models.
/// The `tonic::include_proto!` macro is used to include the protobuf definitions, enabling easy
/// integration of gRPC services into Rust code.
pub mod gpt_answer {
// Include the protobuf definitions for the gpt_answer service.
tonic::include_proto!("gpt_answer");
}
File renamed without changes.
1 change: 1 addition & 0 deletions src/common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod grpc;
pub mod loggers;
pub mod options;
4 changes: 2 additions & 2 deletions src/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ features = ["derive"]
[dependencies.thiserror]
version = "1.0.57"

[dependencies]
anyhow = "1.0.80"
[dependencies.anyhow]
version = "1.0.80"
10 changes: 6 additions & 4 deletions src/core/src/common/errors.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use anyhow::Error;

#[derive(thiserror::Error, Debug)]
pub enum CoreError {
#[error("parse error {0}")]
Expand All @@ -8,10 +10,10 @@ pub enum CoreError {

#[error("missing parameters")]
MissingParameters,

#[error("not found")]
NotFound,
#[error("transparent")]
InternalError,
#[error("unknown data store error")]
Unknown,

#[error("internal error {0}")]
InternalError(#[from] Error),
}
Loading

0 comments on commit a50a9fa

Please sign in to comment.