Skip to content

Commit 4554da0

Browse files
committed
fix: refine
1 parent 6ac9c62 commit 4554da0

File tree

7 files changed

+58
-78
lines changed

7 files changed

+58
-78
lines changed

src/adapter/src/repositories/grpc/gpt_answer_client.rs

Lines changed: 10 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use anyhow::Error;
21
use tonic::{
32
async_trait,
43
transport::{Channel, Endpoint},
@@ -15,27 +14,10 @@ use rust_core::{common::errors::CoreError, ports::gpt_answer::GptAnswerPort};
1514
/// methods for connecting to the service, sending a question, and receiving an answer.
1615
#[derive(Clone)]
1716
pub struct GptAnswerClient {
18-
client: Option<GptAnswerServiceClient<Channel>>,
1917
endpoint: Endpoint,
2018
}
2119

2220
impl GptAnswerClient {
23-
/// Creates a new `GptAnswerClient` instance with the provided gRPC endpoint.
24-
///
25-
/// # Arguments
26-
///
27-
/// * `endpoint`: An `Endpoint` representing the gRPC communication endpoint.
28-
///
29-
/// # Returns
30-
///
31-
/// Returns a new instance of `GptAnswerClient`.
32-
fn new(endpoint: Endpoint) -> Self {
33-
Self {
34-
client: None,
35-
endpoint,
36-
}
37-
}
38-
3921
/// Initializes a new `GptAnswerClient` instance with the provided URI.
4022
///
4123
/// # Arguments
@@ -46,12 +28,10 @@ impl GptAnswerClient {
4628
///
4729
/// Returns a `Result` containing the initialized `GptAnswerClient` if successful,
4830
/// or a `CoreError` if an error occurs during initialization.
49-
pub async fn init(uri: String) -> Result<Self, CoreError> {
50-
// Establish connection to the gRPC server
51-
let endpoint =
52-
Channel::from_shared(uri).map_err(|err| CoreError::InternalError(err.into()))?;
53-
54-
Ok(Self::new(endpoint))
31+
pub fn new(uri: String) -> Result<Self, CoreError> {
32+
Channel::from_shared(uri)
33+
.map_err(|err| CoreError::InternalError(err.into()))
34+
.map(|endpoint| Self { endpoint })
5535
}
5636

5737
/// Establishes a connection to the GPT answer service at the specified URI.
@@ -60,13 +40,10 @@ impl GptAnswerClient {
6040
///
6141
/// Returns a `Result` containing the connected `GptAnswerServiceClient` if successful,
6242
/// or a `CoreError` if an error occurs during connection.
63-
pub async fn connect(&mut self) -> Result<(), CoreError> {
64-
let client = GptAnswerServiceClient::connect(self.endpoint.clone())
43+
pub async fn connect(&self) -> Result<GptAnswerServiceClient<Channel>, CoreError> {
44+
GptAnswerServiceClient::connect(self.endpoint.clone())
6545
.await
66-
.map_err(|err| CoreError::InternalError(err.into()))?;
67-
68-
self.client = Some(client);
69-
Ok(())
46+
.map_err(|err| CoreError::InternalError(err.into()))
7047
}
7148
}
7249

@@ -83,17 +60,13 @@ impl GptAnswerPort for GptAnswerClient {
8360
/// Returns a `Result` containing the generated answer as a `String` if successful,
8461
/// or a `CoreError` if an error occurs during communication with the service.
8562
async fn get_answer(&self, question: &str) -> Result<String, CoreError> {
86-
let client = self
87-
.client
88-
.as_ref()
89-
.ok_or_else(|| CoreError::InternalError(Error::msg("Client not initialized")))?;
90-
9163
let request = tonic::Request::new(GetAnswerPayload {
9264
question: question.to_string(),
9365
});
9466

95-
let response = client
96-
.clone()
67+
let response = self
68+
.connect()
69+
.await?
9770
.get_answer(request)
9871
.await
9972
.map_err(|err| CoreError::InternalError(err.into()))?;

src/gpt_answer_server/src/controllers/gpt_answer.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,18 @@ use common::grpc::gpt_answer::gpt_answer::{
1010
/// the `GptAnswerService` trait generated by Tonic, which defines the RPC methods for answering
1111
/// questions.
1212
#[derive(Debug, Default)]
13-
pub struct GptAnswerServer;
13+
pub struct GptAnswerServiceImpl {
14+
pub dummy_prop: String,
15+
}
16+
17+
impl GptAnswerServiceImpl {
18+
pub fn new(dummy_prop: String) -> Self {
19+
Self { dummy_prop }
20+
}
21+
}
1422

1523
#[tonic::async_trait]
16-
impl GptAnswerService for GptAnswerServer {
24+
impl GptAnswerService for GptAnswerServiceImpl {
1725
/// Handle the gRPC `get_answer` request.
1826
///
1927
/// This method is called when a gRPC client sends a request to get an answer to a question.
@@ -38,7 +46,7 @@ impl GptAnswerService for GptAnswerServer {
3846

3947
// TODO: Implement your logic to generate an answer based on the question.
4048
// Placeholder logic: Generate an answer string
41-
let answer = format!("Answer to: {}", payload.question);
49+
let answer = format!("Answer to: {}, {}", payload.question, self.dummy_prop);
4250

4351
// Construct a response containing the generated answer
4452
let response = GetAnswerResponse { answer };

src/gpt_answer_server/src/main.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,16 @@ use tonic::transport::Server;
55
use common::grpc::gpt_answer::gpt_answer::gpt_answer_service_server::GptAnswerServiceServer;
66
use common::loggers::telemetry::init_telemetry;
77
use common::options::parse_options;
8-
use gpt_answer_server::controllers::gpt_answer::GptAnswerServer;
8+
use gpt_answer_server::controllers::gpt_answer::GptAnswerServiceImpl;
99
use gpt_answer_server::options::Options;
1010

11-
pub async fn init_grpc_server(options: Options) {
12-
let server_endpoint = &options.server_endpoint;
13-
let address = server_endpoint.parse().unwrap();
14-
println!("Starting GPT Answer server at {}", server_endpoint);
11+
pub async fn serve(options: Options) {
12+
let address = options.server_endpoint.parse().unwrap();
13+
println!("Starting GPT Answer server at {}", options.server_endpoint);
1514

16-
let gpt_answer_server = GptAnswerServer::default();
15+
let gpt_answer_service = GptAnswerServiceImpl::new("dummy_prop".to_string());
1716
Server::builder()
18-
.add_service(GptAnswerServiceServer::new(gpt_answer_server))
17+
.add_service(GptAnswerServiceServer::new(gpt_answer_service))
1918
.serve(address)
2019
.await
2120
.unwrap();
@@ -48,9 +47,9 @@ async fn main() {
4847
options.log.level.as_str(),
4948
);
5049

51-
let gpt_answer_server = tokio::spawn(init_grpc_server(options));
50+
let server = tokio::spawn(serve(options));
5251

53-
tokio::try_join!(gpt_answer_server).expect("Failed to run servers");
52+
tokio::try_join!(server).expect("Failed to run servers");
5453

5554
global::shutdown_tracer_provider();
5655
}

src/public/src/controllers/question.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ pub async fn update_question(
132132
#[instrument(level = "info", skip(question_port, gpt_answer_client))]
133133
pub async fn get_question_answer(
134134
question_port: Arc<dyn QuestionPort + Send + Sync>,
135-
mut gpt_answer_client: GptAnswerClient,
135+
gpt_answer_client: Arc<GptAnswerClient>,
136136
id: String,
137137
) -> Result<impl Reply, Rejection> {
138138
let question_id = QuestionId::from_str(&id).map_err(WarpError::from)?;
@@ -142,8 +142,6 @@ pub async fn get_question_answer(
142142
.await
143143
.map_err(WarpError::from)?;
144144

145-
gpt_answer_client.connect().await.map_err(WarpError::from)?;
146-
147145
let answer = gpt_answer_client
148146
.get_answer(&question.content)
149147
.await

src/public/src/main.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
1-
use std::net::{Ipv4Addr, SocketAddrV4};
2-
use std::str::FromStr;
3-
use std::sync::Arc;
4-
51
#[cfg_attr(debug_assertions, allow(dead_code, unused_imports))]
62
use openssl;
73
#[rustfmt::skip]
84
#[cfg_attr(debug_assertions, allow(dead_code, unused_imports))]
95
use diesel;
6+
7+
use std::net::{Ipv4Addr, SocketAddrV4};
8+
use std::str::FromStr;
9+
use std::sync::Arc;
10+
1011
use clap::{Parser, Subcommand};
1112
use deadpool_diesel::postgres::Pool;
1213
use deadpool_diesel::{Manager, Runtime};
1314
use opentelemetry::global;
1415
use tracing::info;
1516

17+
use adapter::repositories::grpc::gpt_answer_client::GptAnswerClient;
1618
use adapter::repositories::in_memory::question::QuestionInMemoryRepository;
1719
use adapter::repositories::postgres::question_db::QuestionDBRepository;
1820
use cli::options::Options;
@@ -48,8 +50,8 @@ async fn main() {
4850
options.log.level.as_str(),
4951
);
5052

51-
let warp_server = tokio::spawn(run_warp_server(options));
52-
tokio::try_join!(warp_server).expect("Failed to run servers");
53+
let server = tokio::spawn(serve(options));
54+
tokio::try_join!(server).expect("Failed to run servers");
5355

5456
global::shutdown_tracer_provider();
5557
}
@@ -74,7 +76,7 @@ enum Commands {
7476
Config,
7577
}
7678

77-
pub async fn run_warp_server(options: Options) {
79+
pub async fn serve(options: Options) {
7880
let question_port: Arc<dyn QuestionPort + Send + Sync> = if options.db.in_memory.is_some() {
7981
info!("Using in-memory database");
8082
Arc::new(QuestionInMemoryRepository::new())
@@ -92,13 +94,15 @@ pub async fn run_warp_server(options: Options) {
9294
Arc::new(QuestionInMemoryRepository::new())
9395
};
9496

95-
let grpc_client = options.gpt_answer_service_url.clone();
96-
let router = Router::new(question_port, grpc_client.into());
97-
let routers = router.routes().await;
97+
let gpt_answer_client =
98+
Arc::new(GptAnswerClient::new(options.gpt_answer_service_url.to_string()).unwrap());
99+
100+
let router = Router::new(question_port, gpt_answer_client);
101+
let routes = router.routes();
98102
let address = SocketAddrV4::new(
99103
Ipv4Addr::from_str(options.server.url.as_str()).unwrap(),
100104
options.server.port,
101105
);
102106

103-
warp::serve(routers).run(address).await
107+
warp::serve(routes).run(address).await
104108
}

src/public/src/router.rs

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::sync::Arc;
2+
23
use warp::http::Method;
34
use warp::{Filter, Rejection, Reply};
45

@@ -14,33 +15,25 @@ use crate::errors::return_error;
1415
/// Router for handling HTTP requests related to questions.
1516
pub struct Router {
1617
question_port: Arc<dyn QuestionPort + Send + Sync + 'static>,
17-
gpt_answer_service_url: Arc<String>,
18+
gpt_answer_client: Arc<GptAnswerClient>,
1819
}
1920

2021
impl Router {
2122
/// Creates a new Router instance with the specified QuestionPort.
2223
pub fn new(
2324
question_port: Arc<dyn QuestionPort + Send + Sync + 'static>,
24-
gpt_answer_service_url: Arc<String>,
25+
gpt_answer_client: Arc<GptAnswerClient>,
2526
) -> Self {
2627
Router {
2728
question_port: question_port.clone(),
28-
gpt_answer_service_url: gpt_answer_service_url.clone(),
29+
gpt_answer_client,
2930
}
3031
}
3132

3233
/// Configures and returns the Warp filter for handling HTTP requests.
33-
pub async fn routes(self) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
34+
pub fn routes(self) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
3435
let store_filter = warp::any().map(move || self.question_port.clone());
3536

36-
let gpt_answer_client = GptAnswerClient::init(self.gpt_answer_service_url.to_string())
37-
.await
38-
.map_err(|err| {
39-
tracing::error!("Failed to init GPT answer service: {:?}", err);
40-
err
41-
})
42-
.unwrap();
43-
4437
let cors = warp::cors()
4538
.allow_any_origin()
4639
.allow_header("content-type")
@@ -85,7 +78,7 @@ impl Router {
8578
let get_question_answer = warp::get()
8679
.and(warp::path("questions"))
8780
.and(store_filter.clone())
88-
.and(warp::any().map(move || gpt_answer_client.clone()))
81+
.and(warp::any().map(move || self.gpt_answer_client.clone()))
8982
.and(warp::path::param::<String>())
9083
.and(warp::path("answer"))
9184
.and_then(get_question_answer);

src/public/tests/questions_router_test.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ mod tests {
1212
use warp::test::request;
1313

1414
use adapter::repositories::{
15+
grpc::gpt_answer_client::GptAnswerClient,
1516
in_memory::question::QuestionInMemoryRepository,
1617
postgres::question_db::{QuestionDBRepository, MIGRATIONS},
1718
};
@@ -32,8 +33,12 @@ mod tests {
3233
{
3334
let gpt_answer_service_url = "grpc://0.0.0.0:50051".to_string();
3435

35-
let router = Router::new(question_port, gpt_answer_service_url.into());
36-
let routers = router.routes().await;
36+
let gpt_answer_client: Arc<
37+
adapter::repositories::grpc::gpt_answer_client::GptAnswerClient,
38+
> = Arc::new(GptAnswerClient::new(gpt_answer_service_url.to_string()).unwrap());
39+
40+
let router = Router::new(question_port, gpt_answer_client);
41+
let routers = router.routes();
3742

3843
let raw_question_id: String = rand::thread_rng().gen_range(1..=1000).to_string();
3944
let question_id = QuestionId::from_str(&raw_question_id.clone()).unwrap();

0 commit comments

Comments
 (0)