From e709e6bbbc5cd6063e6128b4fb80e84bbd44fd43 Mon Sep 17 00:00:00 2001 From: appflowy Date: Fri, 20 Aug 2021 21:09:21 +0800 Subject: [PATCH] config user login --- backend/src/routers/helper.rs | 14 +-- backend/src/routers/mod.rs | 2 +- backend/src/routers/user.rs | 4 +- backend/src/startup.rs | 5 ++ backend/src/user_service/auth.rs | 4 +- backend/src/ws_service/entities/connect.rs | 6 +- backend/src/ws_service/ws_server.rs | 6 +- rust-lib/flowy-net/Cargo.toml | 3 + rust-lib/flowy-net/src/config.rs | 7 ++ rust-lib/flowy-net/src/errors.rs | 26 ++++-- rust-lib/flowy-net/src/lib.rs | 2 + rust-lib/flowy-net/src/request/mod.rs | 3 + rust-lib/flowy-net/src/request/request.rs | 86 +++++++++++++++++++ rust-lib/flowy-net/src/response/response.rs | 8 +- .../flowy-net/src/response/response_http.rs | 18 ++-- .../flowy-net/src/response/response_serde.rs | 6 +- .../src/services/user/user_server.rs | 27 ++++-- 17 files changed, 175 insertions(+), 52 deletions(-) create mode 100644 rust-lib/flowy-net/src/config.rs create mode 100644 rust-lib/flowy-net/src/request/mod.rs create mode 100644 rust-lib/flowy-net/src/request/request.rs diff --git a/backend/src/routers/helper.rs b/backend/src/routers/helper.rs index 03312dc44f..6b90af0382 100644 --- a/backend/src/routers/helper.rs +++ b/backend/src/routers/helper.rs @@ -1,15 +1,15 @@ use crate::config::MAX_PAYLOAD_SIZE; use actix_web::web; -use flowy_net::{errors::ServerError, response::*}; +use flowy_net::{errors::NetworkError, response::*}; use futures::StreamExt; use protobuf::{Message, ProtobufResult}; -pub async fn parse_from_payload(payload: web::Payload) -> Result { +pub async fn parse_from_payload(payload: web::Payload) -> Result { let bytes = poll_payload(payload).await?; parse_from_bytes(&bytes) } -pub fn parse_from_bytes(bytes: &[u8]) -> Result { +pub fn parse_from_bytes(bytes: &[u8]) -> Result { let result: ProtobufResult = Message::parse_from_bytes(&bytes); match result { Ok(data) => Ok(data), @@ -17,13 +17,13 @@ pub fn parse_from_bytes(bytes: &[u8]) -> Result { } } -pub async fn poll_payload(mut payload: web::Payload) -> Result { +pub async fn poll_payload(mut payload: web::Payload) -> Result { let mut body = web::BytesMut::new(); while let Some(chunk) = payload.next().await { - let chunk = chunk.map_err(|e| ServerError::InternalError(format!("{:?}", e)))?; + let chunk = chunk.map_err(|e| NetworkError::InternalError(format!("{:?}", e)))?; if (body.len() + chunk.len()) > MAX_PAYLOAD_SIZE { - let resp = ServerResponse::from_msg("Payload overflow", ServerCode::PayloadOverflow); - return Err(ServerError::BadRequest(resp)); + let resp = FlowyResponse::from_msg("Payload overflow", ServerCode::PayloadOverflow); + return Err(NetworkError::BadRequest(resp)); } body.extend_from_slice(&chunk); } diff --git a/backend/src/routers/mod.rs b/backend/src/routers/mod.rs index 41bdf89771..21700ba3ce 100644 --- a/backend/src/routers/mod.rs +++ b/backend/src/routers/mod.rs @@ -1,5 +1,5 @@ mod helper; -mod user; +pub(crate) mod user; pub(crate) mod ws; pub use user::*; diff --git a/backend/src/routers/user.rs b/backend/src/routers/user.rs index 2f4b901845..7c2f1210b7 100644 --- a/backend/src/routers/user.rs +++ b/backend/src/routers/user.rs @@ -10,7 +10,7 @@ use flowy_user::protobuf::SignUpParams; use std::sync::Arc; -pub async fn user_register( +pub async fn register( _request: HttpRequest, payload: Payload, auth: Data>, @@ -18,7 +18,7 @@ pub async fn user_register( let params: SignUpParams = parse_from_payload(payload).await?; let _ = auth.sign_up(params)?; - let resp = ServerResponse::success(); + let resp = FlowyResponse::success(); Ok(resp.into()) } diff --git a/backend/src/startup.rs b/backend/src/startup.rs index 4f0d3d6b78..85c55fb961 100644 --- a/backend/src/startup.rs +++ b/backend/src/startup.rs @@ -16,6 +16,7 @@ pub fn run(app_ctx: Arc, listener: TcpListener) -> Result, listener: TcpListener) -> Result Scope { web::scope("/ws").service(ws::start_connection) } +fn user_scope() -> Scope { + web::scope("/user").service(web::resource("/register").route(web::post().to(user::register))) +} + pub async fn init_app_context() -> Arc { let _ = flowy_log::Builder::new("flowy").env_filter("Debug").build(); let config = Arc::new(Config::new()); diff --git a/backend/src/user_service/auth.rs b/backend/src/user_service/auth.rs index dea84dd3eb..9d560f5f8f 100644 --- a/backend/src/user_service/auth.rs +++ b/backend/src/user_service/auth.rs @@ -1,4 +1,4 @@ -use flowy_net::errors::ServerError; +use flowy_net::errors::NetworkError; use flowy_user::protobuf::SignUpParams; use sqlx::PgPool; use std::sync::Arc; @@ -10,5 +10,5 @@ pub struct Auth { impl Auth { pub fn new(db_pool: Arc) -> Self { Self { db_pool } } - pub fn sign_up(&self, params: SignUpParams) -> Result<(), ServerError> { Ok(()) } + pub fn sign_up(&self, params: SignUpParams) -> Result<(), NetworkError> { Ok(()) } } diff --git a/backend/src/ws_service/entities/connect.rs b/backend/src/ws_service/entities/connect.rs index 10f04b285a..fd7404bee9 100644 --- a/backend/src/ws_service/entities/connect.rs +++ b/backend/src/ws_service/entities/connect.rs @@ -1,6 +1,6 @@ use crate::ws_service::ClientMessage; use actix::{Message, Recipient}; -use flowy_net::errors::ServerError; +use flowy_net::errors::NetworkError; use serde::{Deserialize, Serialize}; use std::fmt::Formatter; @@ -37,14 +37,14 @@ impl std::fmt::Display for SessionId { } #[derive(Debug, Message, Clone)] -#[rtype(result = "Result<(), ServerError>")] +#[rtype(result = "Result<(), NetworkError>")] pub struct Connect { pub socket: Socket, pub sid: SessionId, } #[derive(Debug, Message, Clone)] -#[rtype(result = "Result<(), ServerError>")] +#[rtype(result = "Result<(), NetworkError>")] pub struct Disconnect { pub sid: SessionId, } diff --git a/backend/src/ws_service/ws_server.rs b/backend/src/ws_service/ws_server.rs index ac307504ad..e223d167f3 100644 --- a/backend/src/ws_service/ws_server.rs +++ b/backend/src/ws_service/ws_server.rs @@ -4,7 +4,7 @@ use crate::ws_service::{ }; use actix::{Actor, Context, Handler}; use dashmap::DashMap; -use flowy_net::errors::ServerError; +use flowy_net::errors::NetworkError; pub struct WSServer { sessions: DashMap, @@ -26,7 +26,7 @@ impl Actor for WSServer { } impl Handler for WSServer { - type Result = Result<(), ServerError>; + type Result = Result<(), NetworkError>; fn handle(&mut self, msg: Connect, _ctx: &mut Context) -> Self::Result { let session: Session = msg.into(); self.sessions.insert(session.id.clone(), session); @@ -36,7 +36,7 @@ impl Handler for WSServer { } impl Handler for WSServer { - type Result = Result<(), ServerError>; + type Result = Result<(), NetworkError>; fn handle(&mut self, msg: Disconnect, _: &mut Context) -> Self::Result { self.sessions.remove(&msg.sid); Ok(()) diff --git a/rust-lib/flowy-net/Cargo.toml b/rust-lib/flowy-net/Cargo.toml index ee9e9cb88d..65ccf20b5b 100644 --- a/rust-lib/flowy-net/Cargo.toml +++ b/rust-lib/flowy-net/Cargo.toml @@ -14,6 +14,9 @@ serde_repr = "0.1" actix-web = {version = "3", optional = true} pin-project = "1.0.0" futures-core = { version = "0.3", default-features = false } +log = "0.4" +bytes = "1.0" +lazy_static = "1.4.0" [features] http = ["actix-web"] \ No newline at end of file diff --git a/rust-lib/flowy-net/src/config.rs b/rust-lib/flowy-net/src/config.rs new file mode 100644 index 0000000000..8c529766f3 --- /dev/null +++ b/rust-lib/flowy-net/src/config.rs @@ -0,0 +1,7 @@ +use lazy_static::lazy_static; + +pub const HOST: &'static str = "0.0.0.0:3030"; + +lazy_static! { + pub static ref SIGN_UP_URL: String = format!("{}/user/register", HOST); +} diff --git a/rust-lib/flowy-net/src/errors.rs b/rust-lib/flowy-net/src/errors.rs index 7a10e3f90a..322e19bdc1 100644 --- a/rust-lib/flowy-net/src/errors.rs +++ b/rust-lib/flowy-net/src/errors.rs @@ -1,30 +1,38 @@ -use crate::response::ServerResponse; +use crate::response::FlowyResponse; use protobuf::ProtobufError; + use std::fmt::{Formatter, Write}; #[derive(Debug)] -pub enum ServerError { +pub enum NetworkError { InternalError(String), - BadRequest(ServerResponse), + BadRequest(FlowyResponse), Unauthorized, } -impl std::fmt::Display for ServerError { +impl std::fmt::Display for NetworkError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - ServerError::InternalError(_) => f.write_str("Internal Server Error"), - ServerError::BadRequest(request) => { + NetworkError::InternalError(_) => f.write_str("Internal Server Error"), + NetworkError::BadRequest(request) => { let msg = format!("Bad Request: {:?}", request); f.write_str(&msg) }, - ServerError::Unauthorized => f.write_str("Unauthorized"), + NetworkError::Unauthorized => f.write_str("Unauthorized"), } } } -impl std::convert::From for ServerError { +impl std::convert::From for NetworkError { fn from(err: ProtobufError) -> Self { let msg = format!("{:?}", err); - ServerError::InternalError(msg) + NetworkError::InternalError(msg) + } +} + +impl std::convert::From for NetworkError { + fn from(error: reqwest::Error) -> Self { + let msg = format!("{:?}", error); + NetworkError::InternalError(msg) } } diff --git a/rust-lib/flowy-net/src/lib.rs b/rust-lib/flowy-net/src/lib.rs index e9f7d68747..a0b6d841ce 100644 --- a/rust-lib/flowy-net/src/lib.rs +++ b/rust-lib/flowy-net/src/lib.rs @@ -1,4 +1,6 @@ pub mod errors; pub mod future; +pub mod config; +pub mod request; pub mod response; diff --git a/rust-lib/flowy-net/src/request/mod.rs b/rust-lib/flowy-net/src/request/mod.rs new file mode 100644 index 0000000000..3edd9a21fa --- /dev/null +++ b/rust-lib/flowy-net/src/request/mod.rs @@ -0,0 +1,3 @@ +mod request; + +pub use request::*; diff --git a/rust-lib/flowy-net/src/request/request.rs b/rust-lib/flowy-net/src/request/request.rs new file mode 100644 index 0000000000..e91c965cfa --- /dev/null +++ b/rust-lib/flowy-net/src/request/request.rs @@ -0,0 +1,86 @@ +use crate::errors::NetworkError; +use bytes::Bytes; +use protobuf::Message; +use reqwest::{Client, Response}; +use std::{convert::TryFrom, time::Duration}; + +pub struct FlowyRequest { + client: Client, +} + +impl FlowyRequest { + pub fn new() -> Self { + let client = default_client(); + Self { client } + } + + pub async fn get(&self, url: &str) -> Result + where + T: Message, + { + let url = url.to_owned(); + let response = self.client.get(&url).send().await?; + parse_response(response).await + } + + pub async fn post(&self, url: &str, data: T) -> Result + where + T: Message, + { + let url = url.to_owned(); + let body = data.write_to_bytes()?; + let response = self.client.post(&url).body(body).send().await?; + parse_response(response).await + } + + pub async fn post_data(&self, url: &str, bytes: Vec) -> Result + where + T: for<'a> TryFrom<&'a Vec>, + { + let url = url.to_owned(); + let response = self.client.post(&url).body(bytes).send().await?; + let bytes = response.bytes().await?.to_vec(); + let data = T::try_from(&bytes).map_err(|_e| panic!("")).unwrap(); + Ok(data) + } +} + +async fn parse_response(response: Response) -> Result +where + T: Message, +{ + let bytes = response.bytes().await?; + parse_bytes(bytes) +} + +fn parse_bytes(bytes: Bytes) -> Result +where + T: Message, +{ + match Message::parse_from_bytes(&bytes) { + Ok(data) => Ok(data), + Err(e) => { + log::error!( + "Parse bytes for {:?} failed: {}", + std::any::type_name::(), + e + ); + Err(e.into()) + }, + } +} + +fn default_client() -> Client { + let result = reqwest::Client::builder() + .connect_timeout(Duration::from_millis(500)) + .timeout(Duration::from_secs(5)) + .build(); + + match result { + Ok(client) => client, + Err(e) => { + log::error!("Create reqwest client failed: {}", e); + reqwest::Client::new() + }, + } +} diff --git a/rust-lib/flowy-net/src/response/response.rs b/rust-lib/flowy-net/src/response/response.rs index a30178c972..f04878657d 100644 --- a/rust-lib/flowy-net/src/response/response.rs +++ b/rust-lib/flowy-net/src/response/response.rs @@ -14,15 +14,15 @@ pub enum ServerCode { } #[derive(Debug, Serialize)] -pub struct ServerResponse { +pub struct FlowyResponse { pub msg: String, pub data: Option, pub code: ServerCode, } -impl ServerResponse { +impl FlowyResponse { pub fn new(data: Option, msg: &str, code: ServerCode) -> Self { - ServerResponse { + FlowyResponse { msg: msg.to_owned(), data, code, @@ -34,7 +34,7 @@ impl ServerResponse { } } -impl ServerResponse { +impl FlowyResponse { pub fn success() -> Self { Self::from_msg("", ServerCode::Success) } pub fn from_msg(msg: &str, code: ServerCode) -> Self { diff --git a/rust-lib/flowy-net/src/response/response_http.rs b/rust-lib/flowy-net/src/response/response_http.rs index 89fe389f45..e357f5b848 100644 --- a/rust-lib/flowy-net/src/response/response_http.rs +++ b/rust-lib/flowy-net/src/response/response_http.rs @@ -1,30 +1,30 @@ -use crate::{errors::ServerError, response::*}; +use crate::{errors::NetworkError, response::*}; use actix_web::{body::Body, error::ResponseError, HttpResponse}; use serde::Serialize; -impl ResponseError for ServerError { +impl ResponseError for NetworkError { fn error_response(&self) -> HttpResponse { match self { - ServerError::InternalError(msg) => { - let resp = ServerResponse::from_msg(&msg, ServerCode::InternalError); + NetworkError::InternalError(msg) => { + let resp = FlowyResponse::from_msg(&msg, ServerCode::InternalError); HttpResponse::InternalServerError().json(resp) }, - ServerError::BadRequest(ref resp) => HttpResponse::BadRequest().json(resp), - ServerError::Unauthorized => { - let resp = ServerResponse::from_msg("Unauthorized", ServerCode::Unauthorized); + NetworkError::BadRequest(ref resp) => HttpResponse::BadRequest().json(resp), + NetworkError::Unauthorized => { + let resp = FlowyResponse::from_msg("Unauthorized", ServerCode::Unauthorized); HttpResponse::Unauthorized().json(resp) }, } } } -impl std::convert::Into for ServerResponse { +impl std::convert::Into for FlowyResponse { fn into(self) -> HttpResponse { match serde_json::to_string(&self) { Ok(body) => HttpResponse::Ok().body(Body::from(body)), Err(e) => { let msg = format!("Serial error: {:?}", e); - ServerError::InternalError(msg).error_response() + NetworkError::InternalError(msg).error_response() }, } } diff --git a/rust-lib/flowy-net/src/response/response_serde.rs b/rust-lib/flowy-net/src/response/response_serde.rs index 0ab1c61e75..b81b61a0cd 100644 --- a/rust-lib/flowy-net/src/response/response_serde.rs +++ b/rust-lib/flowy-net/src/response/response_serde.rs @@ -1,4 +1,4 @@ -use crate::response::{ServerCode, ServerResponse}; +use crate::response::{FlowyResponse, ServerCode}; use serde::{ de::{self, MapAccess, Visitor}, Deserialize, @@ -8,7 +8,7 @@ use serde::{ use std::{fmt, marker::PhantomData, str::FromStr}; pub trait ServerData<'a>: Serialize + Deserialize<'a> + FromStr {} -impl<'de, T: ServerData<'de>> Deserialize<'de> for ServerResponse { +impl<'de, T: ServerData<'de>> Deserialize<'de> for FlowyResponse { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, @@ -18,7 +18,7 @@ impl<'de, T: ServerData<'de>> Deserialize<'de> for ServerResponse { where T: ServerData<'de>, { - type Value = ServerResponse; + type Value = FlowyResponse; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct Duration") diff --git a/rust-lib/flowy-user/src/services/user/user_server.rs b/rust-lib/flowy-user/src/services/user/user_server.rs index 479bb28d96..089b8f7891 100644 --- a/rust-lib/flowy-user/src/services/user/user_server.rs +++ b/rust-lib/flowy-user/src/services/user/user_server.rs @@ -3,8 +3,7 @@ use crate::{ errors::{ErrorBuilder, UserErrCode, UserError}, }; -use flowy_infra::uuid; -use flowy_net::future::ResultFuture; +use flowy_net::{future::ResultFuture, request::FlowyRequest}; use std::sync::Arc; pub(crate) trait UserServer { @@ -27,13 +26,23 @@ impl UserServerImpl {} impl UserServer for UserServerImpl { fn sign_up(&self, _params: SignUpParams) -> ResultFuture { - ResultFuture::new(async { - Ok(SignUpResponse { - uid: "".to_string(), - name: "".to_string(), - email: "".to_string(), - }) - }) + // let bytes: Vec = params.try_into().unwrap(); + // ResultFuture::new(async move { + // match FlowyRequest::new() + // .post_data::("SIGN_UP_URL.as_ref()", bytes) + // .await + // { + // Ok(a) => {}, + // Err(err) => {}, + // } + // + // Ok(SignUpResponse { + // uid: "".to_string(), + // name: "".to_string(), + // email: "".to_string(), + // }) + // }) + unimplemented!() } fn sign_in(&self, _params: SignInParams) -> ResultFuture {