Skip to content

Commit

Permalink
fix: structure
Browse files Browse the repository at this point in the history
  • Loading branch information
thuan2172001 committed Mar 29, 2024
1 parent 96ddae9 commit 66f554f
Show file tree
Hide file tree
Showing 39 changed files with 268 additions and 336 deletions.
19 changes: 5 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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_service"]
resolver = "2"
12 changes: 6 additions & 6 deletions src/adapter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ autoexamples = true
autotests = true
autobenches = true

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

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

[dependencies]
diesel_migrations = "2.1.0"

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.

1 change: 0 additions & 1 deletion 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;
56 changes: 48 additions & 8 deletions src/adapter/src/repositories/grpc/models/gpt_answer.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,80 @@
use rust_core::common::errors::CoreError;
use tonic::transport::Channel;

use grpc_interface::interfaces::gpt_answer::gpt_answer::{
use common::grpc::gpt_answer::gpt_answer::{
gpt_answer_service_client::GptAnswerServiceClient, GetAnswerPayload,
};
use rust_core::common::errors::CoreError;

/// 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.
pub struct GptAnswerGrpcClient {
client: GptAnswerServiceClient<Channel>,
}

impl GptAnswerGrpcClient {
/// Creates a new `GptAnswerGrpcClient` instance with the provided gRPC channel.
///
/// # Arguments
///
/// * `channel`: A `Channel` representing the gRPC communication channel.
///
/// # Returns
///
/// Returns a new instance of `GptAnswerGrpcClient`.
fn new(channel: Channel) -> Self {
let client = GptAnswerServiceClient::new(channel);
Self { client }
}

pub async fn get_instance(uri: &'static str) -> Result<Self, CoreError> {
let channel = Channel::from_static(uri).connect().await.map_err(|err| {
eprintln!("Error connecting to GPT: {:?}", err);
CoreError::InternalError
})?;
/// Establishes a connection to the GPT answer service at the specified URI.
///
/// # Arguments
///
/// * `uri`: The URI of the GPT answer service.
///
/// # Returns
///
/// Returns a `Result` containing the connected `GptAnswerGrpcClient` if successful,
/// or a `CoreError` if an error occurs during connection.
pub async fn connect(uri: &'static str) -> Result<Self, CoreError> {
// Establish connection to the gRPC server
let channel: Channel = match Channel::from_static(uri).connect().await {
Ok(channel) => channel,
Err(err) => {
return Err(CoreError::InternalError(err.into()));
}
};

// Create a new client instance with the connected channel
let client = Self::new(channel);
Ok(client)
}

/// 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.
pub async fn get_answer(&mut self, question: &str) -> Result<String, CoreError> {
// Create a gRPC request with the question payload
let request = tonic::Request::new(GetAnswerPayload {
question: question.to_string(),
});

// Send the request to the gRPC server and await the response
let response = self.client.get_answer(request).await.map_err(|err| {
eprintln!("Error getting answer from GPT: {:?}", err);
CoreError::InternalError
CoreError::InternalError(err.into())
})?;

// Extract and return the answer from the response
Ok(response.into_inner().answer)
}
}
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
11 changes: 11 additions & 0 deletions src/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,14 @@ 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 = "0.11.0"
glob = "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;
2 changes: 1 addition & 1 deletion src/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ features = ["derive"]
version = "1.0.57"

[dependencies]
anyhow = "1.0.80"
anyhow = "1.0.80"
9 changes: 7 additions & 2 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,13 @@ pub enum CoreError {

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

#[error("not found")]
NotFound,
#[error("transparent")]
InternalError,

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

#[error("unknown data store error")]
Unknown,
}
Loading

0 comments on commit 66f554f

Please sign in to comment.