diff --git a/app_flowy/lib/workspace/infrastructure/repos/user_repo.dart b/app_flowy/lib/workspace/infrastructure/repos/user_repo.dart index 857b5a336d..d638e15de4 100644 --- a/app_flowy/lib/workspace/infrastructure/repos/user_repo.dart +++ b/app_flowy/lib/workspace/infrastructure/repos/user_repo.dart @@ -33,7 +33,7 @@ class UserRepo { } Future, WorkspaceError>> fetchWorkspaces() { - final request = QueryWorkspaceRequest.create()..userId = user.id; + final request = QueryWorkspaceRequest.create(); return WorkspaceEventReadWorkspaces(request).send().then((result) { return result.fold( @@ -44,9 +44,7 @@ class UserRepo { } Future> openWorkspace(String workspaceId) { - final request = QueryWorkspaceRequest.create() - ..userId = user.id - ..workspaceId = workspaceId; + final request = QueryWorkspaceRequest.create()..workspaceId = workspaceId; return WorkspaceEventOpenWorkspace(request).send().then((result) { return result.fold( (workspace) => left(workspace), @@ -58,7 +56,6 @@ class UserRepo { Future> createWorkspace( String name, String desc) { final request = CreateWorkspaceRequest.create() - ..userId = user.id ..name = name ..desc = desc; return WorkspaceEventCreateWorkspace(request).send().then((result) { diff --git a/app_flowy/lib/workspace/infrastructure/repos/workspace_repo.dart b/app_flowy/lib/workspace/infrastructure/repos/workspace_repo.dart index d1db04cee8..ef8eb90b41 100644 --- a/app_flowy/lib/workspace/infrastructure/repos/workspace_repo.dart +++ b/app_flowy/lib/workspace/infrastructure/repos/workspace_repo.dart @@ -40,9 +40,7 @@ class WorkspaceRepo { } Future> getWorkspace() { - final request = QueryWorkspaceRequest.create() - ..userId = user.id - ..workspaceId = workspaceId; + final request = QueryWorkspaceRequest.create()..workspaceId = workspaceId; return WorkspaceEventReadWorkspaces(request).send().then((result) { return result.fold( diff --git a/rust-lib/flowy-infra/src/kv/kv.rs b/rust-lib/flowy-infra/src/kv/kv.rs index 3805058968..fa4099a2db 100644 --- a/rust-lib/flowy-infra/src/kv/kv.rs +++ b/rust-lib/flowy-infra/src/kv/kv.rs @@ -8,16 +8,14 @@ use std::{path::Path, sync::RwLock}; const DB_NAME: &str = "kv.db"; lazy_static! { - static ref KV_HOLDER: RwLock = RwLock::new(KVStore::new()); + static ref KV_HOLDER: RwLock = RwLock::new(KV { database: None }); } -pub struct KVStore { +pub struct KV { database: Option, } -impl KVStore { - fn new() -> Self { KVStore { database: None } } - +impl KV { fn set(item: KeyValue) -> Result<(), String> { let _ = diesel::replace_into(kv_table::table) .values(&item) @@ -56,9 +54,7 @@ impl KVStore { let conn = database.get_connection().unwrap(); SqliteConnection::execute(&*conn, KV_SQL).unwrap(); - let mut store = KV_HOLDER - .write() - .map_err(|e| format!("KVStore write failed: {:?}", e))?; + let mut store = KV_HOLDER.write().map_err(|e| format!("KVStore write failed: {:?}", e))?; store.database = Some(database); Ok(()) @@ -70,10 +66,10 @@ macro_rules! impl_get_func { $func_name:ident, $get_method:ident=>$target:ident ) => { - impl KVStore { + impl KV { #[allow(dead_code)] pub fn $func_name(k: &str) -> Option<$target> { - match KVStore::get(k) { + match KV::get(k) { Ok(item) => item.$get_method, Err(_) => None, } @@ -84,12 +80,12 @@ macro_rules! impl_get_func { macro_rules! impl_set_func { ($func_name:ident,$set_method:ident,$key_type:ident) => { - impl KVStore { + impl KV { #[allow(dead_code)] pub fn $func_name(key: &str, value: $key_type) { let mut item = KeyValue::new(key); item.$set_method = Some(value); - match KVStore::set(item) { + match KV::set(item) { Ok(_) => {}, Err(e) => { log::error!("{:?}", e) @@ -166,7 +162,7 @@ impl KeyValue { #[cfg(test)] mod tests { - use crate::kv::KVStore; + use crate::kv::KV; #[test] fn kv_store_test() { @@ -175,16 +171,16 @@ mod tests { std::fs::create_dir_all(dir).unwrap(); } - KVStore::init(dir).unwrap(); + KV::init(dir).unwrap(); - KVStore::set_str("1", "hello".to_string()); - assert_eq!(KVStore::get_str("1").unwrap(), "hello"); + KV::set_str("1", "hello".to_string()); + assert_eq!(KV::get_str("1").unwrap(), "hello"); - assert_eq!(KVStore::get_str("2"), None); + assert_eq!(KV::get_str("2"), None); - KVStore::set_bool("1", true); - assert_eq!(KVStore::get_bool("1").unwrap(), true); + KV::set_bool("1", true); + assert_eq!(KV::get_bool("1").unwrap(), true); - assert_eq!(KVStore::get_bool("2"), None); + assert_eq!(KV::get_bool("2"), None); } } diff --git a/rust-lib/flowy-sdk/src/lib.rs b/rust-lib/flowy-sdk/src/lib.rs index d9c50b261f..c20106a874 100644 --- a/rust-lib/flowy-sdk/src/lib.rs +++ b/rust-lib/flowy-sdk/src/lib.rs @@ -13,11 +13,7 @@ pub struct FlowySDK { } impl FlowySDK { - pub fn new(root: &str) -> Self { - Self { - root: root.to_owned(), - } - } + pub fn new(root: &str) -> Self { Self { root: root.to_owned() } } pub fn construct(self) { FlowySDK::construct_with(&self.root) } @@ -25,7 +21,7 @@ impl FlowySDK { FlowySDK::init_log(root); tracing::info!("🔥 Root path: {}", root); - match flowy_infra::kv::KVStore::init(root) { + match flowy_infra::kv::KV::init(root) { Ok(_) => {}, Err(e) => tracing::error!("Init kv store failedL: {}", e), } @@ -36,17 +32,12 @@ impl FlowySDK { if !INIT_LOG.load(Ordering::SeqCst) { INIT_LOG.store(true, Ordering::SeqCst); - let _ = flowy_log::Builder::new("flowy") - .local(directory) - .env_filter("info") - .build(); + let _ = flowy_log::Builder::new("flowy").local(directory).env_filter("info").build(); } } fn init_modules(root: &str) { - let config = ModuleConfig { - root: root.to_owned(), - }; + let config = ModuleConfig { root: root.to_owned() }; EventDispatch::construct(|| build_modules(config)); } } diff --git a/rust-lib/flowy-test/src/builder.rs b/rust-lib/flowy-test/src/builder.rs index 23eccd7921..79ff484267 100644 --- a/rust-lib/flowy-test/src/builder.rs +++ b/rust-lib/flowy-test/src/builder.rs @@ -41,19 +41,11 @@ impl Builder where T: TesterTrait, { - fn test(tester: Box) -> Self { - Self { - tester, - user_detail: None, - } - } + fn test(tester: Box) -> Self { Self { tester, user_detail: None } } pub fn sign_up(self) -> SignUpContext { let (user_detail, password) = self.tester.sign_up(); - SignUpContext { - user_detail, - password, - } + SignUpContext { user_detail, password } } pub fn sign_in(mut self) -> Self { @@ -67,11 +59,6 @@ where self.user_detail = Some(user_detail); } - pub fn logout(self) -> Self { - // self.tester.logout(); - self - } - pub fn request

(mut self, request: P) -> Self where P: ToBytes, diff --git a/rust-lib/flowy-test/src/helper.rs b/rust-lib/flowy-test/src/helper.rs index 12bc47aacf..23498f881f 100644 --- a/rust-lib/flowy-test/src/helper.rs +++ b/rust-lib/flowy-test/src/helper.rs @@ -1,6 +1,6 @@ use bytes::Bytes; use flowy_dispatch::prelude::{DispatchError, EventDispatch, ModuleRequest, ToBytes}; -use flowy_infra::{kv::KVStore, uuid}; +use flowy_infra::{kv::KV, uuid}; use flowy_user::errors::{ErrorBuilder, ErrorCode, UserError}; use flowy_workspace::{ entities::workspace::{CreateWorkspaceRequest, QueryWorkspaceRequest, Workspace}, @@ -36,10 +36,10 @@ const DEFAULT_WORKSPACE: &'static str = "Default_Workspace"; pub(crate) fn create_default_workspace_if_need(user_id: &str) -> Result<(), UserError> { let key = format!("{}{}", user_id, DEFAULT_WORKSPACE); - if KVStore::get_bool(&key).unwrap_or(false) { + if KV::get_bool(&key).unwrap_or(false) { return Err(ErrorBuilder::new(ErrorCode::DefaultWorkspaceAlreadyExist).build()); } - KVStore::set_bool(&key, true); + KV::set_bool(&key, true); let payload: Bytes = CreateWorkspaceRequest { name: DEFAULT_WORKSPACE_NAME.to_string(), diff --git a/rust-lib/flowy-user/src/errors.rs b/rust-lib/flowy-user/src/errors.rs index e89d967b0b..f87d6a5ef3 100644 --- a/rust-lib/flowy-user/src/errors.rs +++ b/rust-lib/flowy-user/src/errors.rs @@ -18,12 +18,7 @@ pub struct UserError { } impl UserError { - fn new(code: ErrorCode, msg: &str) -> Self { - Self { - code, - msg: msg.to_owned(), - } - } + pub(crate) fn new(code: ErrorCode, msg: &str) -> Self { Self { code, msg: msg.to_owned() } } } #[derive(Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] @@ -66,9 +61,7 @@ pub enum ErrorCode { PasswordTooLong = 31, #[display(fmt = "Password contains forbidden characters.")] PasswordContainsForbidCharacters = 32, - #[display( - fmt = "Password should contain a minimum of 6 characters with 1 special 1 letter and 1 numeric" - )] + #[display(fmt = "Password should contain a minimum of 6 characters with 1 special 1 letter and 1 numeric")] PasswordFormatInvalid = 33, #[display(fmt = "Password not match")] PasswordNotMatch = 34, @@ -106,19 +99,11 @@ impl std::default::Default for ErrorCode { } impl std::convert::From for UserError { - fn from(error: flowy_database::result::Error) -> Self { - ErrorBuilder::new(ErrorCode::UserDatabaseInternalError) - .error(error) - .build() - } + fn from(error: flowy_database::result::Error) -> Self { ErrorBuilder::new(ErrorCode::UserDatabaseInternalError).error(error).build() } } impl std::convert::From<::r2d2::Error> for UserError { - fn from(error: r2d2::Error) -> Self { - ErrorBuilder::new(ErrorCode::DatabaseConnectError) - .error(error) - .build() - } + fn from(error: r2d2::Error) -> Self { ErrorBuilder::new(ErrorCode::DatabaseConnectError).error(error).build() } } // use diesel::result::{Error, DatabaseErrorKind}; @@ -153,23 +138,15 @@ impl std::convert::From for UserError { // ErrorKind::__Nonexhaustive { .. } => {}, // } - ErrorBuilder::new(ErrorCode::SqlInternalError) - .error(error) - .build() + ErrorBuilder::new(ErrorCode::SqlInternalError).error(error).build() } } impl std::convert::From for UserError { fn from(error: flowy_net::errors::ServerError) -> Self { match error.code { - flowy_net::errors::ErrorCode::PasswordNotMatch => { - ErrorBuilder::new(ErrorCode::PasswordNotMatch) - .error(error.msg) - .build() - }, - _ => ErrorBuilder::new(ErrorCode::ServerError) - .error(error.msg) - .build(), + flowy_net::errors::ErrorCode::PasswordNotMatch => ErrorBuilder::new(ErrorCode::PasswordNotMatch).error(error.msg).build(), + _ => ErrorBuilder::new(ErrorCode::ServerError).error(error.msg).build(), } } } @@ -185,11 +162,7 @@ pub type ErrorBuilder = flowy_infra::errors::Builder; impl flowy_infra::errors::Build for UserError { fn build(code: ErrorCode, msg: String) -> Self { - let msg = if msg.is_empty() { - format!("{}", code) - } else { - msg - }; + let msg = if msg.is_empty() { format!("{}", code) } else { msg }; UserError::new(code, &msg) } } diff --git a/rust-lib/flowy-user/src/handlers/user_handler.rs b/rust-lib/flowy-user/src/handlers/user_handler.rs index 6b02f909b7..5fd7141ff7 100644 --- a/rust-lib/flowy-user/src/handlers/user_handler.rs +++ b/rust-lib/flowy-user/src/handlers/user_handler.rs @@ -4,9 +4,7 @@ use flowy_dispatch::prelude::*; use std::{convert::TryInto, sync::Arc}; #[tracing::instrument(name = "get_user_status", skip(session))] -pub async fn user_status_handler( - session: Unit>, -) -> DataResult { +pub async fn user_profile_handler(session: Unit>) -> DataResult { let user_detail = session.user_detail().await?; data_result(user_detail) } @@ -18,10 +16,7 @@ pub async fn sign_out(session: Unit>) -> Result<(), UserError> } #[tracing::instrument(name = "update_user", skip(data, session))] -pub async fn update_user_handler( - data: Data, - session: Unit>, -) -> Result<(), UserError> { +pub async fn update_user_handler(data: Data, session: Unit>) -> Result<(), UserError> { let params: UpdateUserParams = data.into_inner().try_into()?; session.update_user(params).await?; Ok(()) diff --git a/rust-lib/flowy-user/src/module.rs b/rust-lib/flowy-user/src/module.rs index 54ae495359..8171068cc3 100644 --- a/rust-lib/flowy-user/src/module.rs +++ b/rust-lib/flowy-user/src/module.rs @@ -9,7 +9,7 @@ pub fn create(user_session: Arc) -> Module { .data(user_session) .event(UserEvent::SignIn, sign_in) .event(UserEvent::SignUp, sign_up) - .event(UserEvent::GetUserProfile, user_status_handler) + .event(UserEvent::GetUserProfile, user_profile_handler) .event(UserEvent::SignOut, sign_out) .event(UserEvent::UpdateUser, update_user_handler) } diff --git a/rust-lib/flowy-user/src/services/server/mod.rs b/rust-lib/flowy-user/src/services/server/mod.rs index 88f1aa5e24..f3e8ff72b5 100644 --- a/rust-lib/flowy-user/src/services/server/mod.rs +++ b/rust-lib/flowy-user/src/services/server/mod.rs @@ -20,10 +20,9 @@ pub trait UserServerAPI { } pub(crate) fn construct_user_server() -> Arc { - // if cfg!(feature = "http_server") { - // Arc::new(UserServer {}) - // } else { - // Arc::new(UserServerMock {}) - // } - Arc::new(UserServer {}) + if cfg!(feature = "http_server") { + Arc::new(UserServer {}) + } else { + Arc::new(UserServerMock {}) + } } diff --git a/rust-lib/flowy-user/src/services/user/user_session.rs b/rust-lib/flowy-user/src/services/user/user_session.rs index 02e0f40af6..5524f11428 100644 --- a/rust-lib/flowy-user/src/services/user/user_session.rs +++ b/rust-lib/flowy-user/src/services/user/user_session.rs @@ -14,7 +14,7 @@ use flowy_database::{ }; use crate::services::server::Server; -use flowy_infra::kv::KVStore; +use flowy_infra::kv::KV; use flowy_sqlite::ConnectionPool; use parking_lot::RwLock; use serde::{Deserialize, Serialize}; @@ -164,22 +164,16 @@ impl UserSession { fn set_session(&self, session: Option) -> Result<(), UserError> { log::trace!("Update user session: {:?}", session); match &session { - None => KVStore::set_str(SESSION_CACHE_KEY, "".to_string()), - Some(session) => KVStore::set_str(SESSION_CACHE_KEY, session.clone().into()), + None => KV::remove(SESSION_CACHE_KEY).map_err(|e| UserError::new(ErrorCode::SqlInternalError, &e))?, + Some(session) => KV::set_str(SESSION_CACHE_KEY, session.clone().into()), } - - let mut write_guard = self.session.write(); - *write_guard = session; + *self.session.write() = session; Ok(()) } fn get_session(&self) -> Result { - let mut session = { - let read_guard = self.session.read(); - (*read_guard).clone() - }; - + let mut session = { (*self.session.read()).clone() }; if session.is_none() { - match KVStore::get_str(SESSION_CACHE_KEY) { + match KV::get_str(SESSION_CACHE_KEY) { None => {}, Some(s) => { session = Some(Session::from(s)); @@ -203,7 +197,7 @@ pub async fn update_user(_server: Server, pool: Arc, params: Upd } pub fn current_user_id() -> Result { - match KVStore::get_str(SESSION_CACHE_KEY) { + match KV::get_str(SESSION_CACHE_KEY) { None => Err(ErrorBuilder::new(ErrorCode::UserNotLoginYet).build()), Some(user_id) => Ok(user_id), } diff --git a/rust-lib/flowy-workspace/src/services/workspace_controller.rs b/rust-lib/flowy-workspace/src/services/workspace_controller.rs index 5e63df73b1..9c8f014a1f 100644 --- a/rust-lib/flowy-workspace/src/services/workspace_controller.rs +++ b/rust-lib/flowy-workspace/src/services/workspace_controller.rs @@ -7,7 +7,7 @@ use crate::{ sql_tables::workspace::{WorkspaceSql, WorkspaceTable, WorkspaceTableChangeset}, }; use flowy_dispatch::prelude::DispatchFuture; -use flowy_infra::kv::KVStore; +use flowy_infra::kv::KV; use std::sync::Arc; @@ -202,10 +202,10 @@ impl WorkspaceController { const CURRENT_WORKSPACE_ID: &str = "current_workspace_id"; -fn set_current_workspace(workspace: &str) { KVStore::set_str(CURRENT_WORKSPACE_ID, workspace.to_owned()); } +fn set_current_workspace(workspace: &str) { KV::set_str(CURRENT_WORKSPACE_ID, workspace.to_owned()); } fn get_current_workspace() -> Result { - match KVStore::get_str(CURRENT_WORKSPACE_ID) { + match KV::get_str(CURRENT_WORKSPACE_ID) { None => Err(ErrorBuilder::new(ErrorCode::CurrentWorkspaceNotFound).build()), Some(workspace_id) => Ok(workspace_id), } diff --git a/rust-lib/flowy-workspace/tests/event/helper.rs b/rust-lib/flowy-workspace/tests/event/helper.rs index a25250f36f..c4abf2f0b3 100644 --- a/rust-lib/flowy-workspace/tests/event/helper.rs +++ b/rust-lib/flowy-workspace/tests/event/helper.rs @@ -12,13 +12,16 @@ pub(crate) fn invalid_workspace_name_test_case() -> Vec { } pub fn create_workspace(name: &str, desc: &str) -> Workspace { - let builder = AnnieTestBuilder::new(); let request = CreateWorkspaceRequest { name: name.to_owned(), desc: desc.to_owned(), }; - let workspace = builder.event(CreateWorkspace).request(request).sync_send().parse::(); + let workspace = AnnieTestBuilder::new() + .event(CreateWorkspace) + .request(request) + .sync_send() + .parse::(); workspace }