diff --git a/backend/rustfmt.toml b/backend/rustfmt.toml index d76ec139c3..2464575494 100644 --- a/backend/rustfmt.toml +++ b/backend/rustfmt.toml @@ -1,18 +1,18 @@ # https://rust-lang.github.io/rustfmt/?version=master&search= max_width = 120 tab_spaces = 4 -fn_single_line = true -match_block_trailing_comma = true -normalize_comments = true -wrap_comments = true -use_field_init_shorthand = true -use_try_shorthand = true -normalize_doc_attributes = true -report_todo = "Never" -report_fixme = "Always" -imports_layout = "HorizontalVertical" -imports_granularity = "Crate" -reorder_modules = true -reorder_imports = true -enum_discrim_align_threshold = 20 +# fn_single_line = true +# match_block_trailing_comma = true +# normalize_comments = true +# wrap_comments = true +# use_field_init_shorthand = true +# use_try_shorthand = true +# normalize_doc_attributes = true +# report_todo = "Never" +# report_fixme = "Always" +# imports_layout = "HorizontalVertical" +# imports_granularity = "Crate" +# reorder_modules = true +# reorder_imports = true +# enum_discrim_align_threshold = 20 edition = "2018" diff --git a/backend/src/application.rs b/backend/src/application.rs index 81518fd9dc..499209d178 100644 --- a/backend/src/application.rs +++ b/backend/src/application.rs @@ -8,8 +8,7 @@ use tokio::time::interval; use crate::{ config::{ env::{domain, secret, use_https}, - DatabaseSettings, - Settings, + DatabaseSettings, Settings, }, context::AppContext, services::{ @@ -34,9 +33,13 @@ impl Application { Ok(Self { port, server }) } - pub async fn run_until_stopped(self) -> Result<(), std::io::Error> { self.server.await } + pub async fn run_until_stopped(self) -> Result<(), std::io::Error> { + self.server.await + } - pub fn port(&self) -> u16 { self.port } + pub fn port(&self) -> u16 { + self.port + } } pub fn run(listener: TcpListener, app_ctx: AppContext) -> Result { @@ -72,62 +75,63 @@ async fn period_check(_pool: PgPool) { } } -fn ws_scope() -> Scope { web::scope("/ws").service(crate::services::web_socket::router::establish_ws_connection) } +fn ws_scope() -> Scope { + web::scope("/ws").service(crate::services::web_socket::router::establish_ws_connection) +} fn user_scope() -> Scope { // https://developer.mozilla.org/en-US/docs/Web/HTTP // TODO: replace GET body with query params web::scope("/api") // authentication - .service(web::resource("/auth") - .route(web::post().to(user::sign_in_handler)) - .route(web::delete().to(user::sign_out_handler)) + .service( + web::resource("/auth") + .route(web::post().to(user::sign_in_handler)) + .route(web::delete().to(user::sign_out_handler)), ) - .service(web::resource("/user") - .route(web::patch().to(user::set_user_profile_handler)) - .route(web::get().to(user::get_user_profile_handler)) + .service( + web::resource("/user") + .route(web::patch().to(user::set_user_profile_handler)) + .route(web::get().to(user::get_user_profile_handler)), ) - .service(web::resource("/register") - .route(web::post().to(user::register_handler)) + .service(web::resource("/register").route(web::post().to(user::register_handler))) + .service( + web::resource("/workspace") + .route(web::post().to(workspace::create_handler)) + .route(web::delete().to(workspace::delete_handler)) + .route(web::get().to(workspace::read_handler)) + .route(web::patch().to(workspace::update_handler)), ) - .service(web::resource("/workspace") - .route(web::post().to(workspace::create_handler)) - .route(web::delete().to(workspace::delete_handler)) - .route(web::get().to(workspace::read_handler)) - .route(web::patch().to(workspace::update_handler)) + .service(web::resource("/workspace_list/{user_id}").route(web::get().to(workspace::workspace_list))) + .service( + web::resource("/app") + .route(web::post().to(app::create_handler)) + .route(web::get().to(app::read_handler)) + .route(web::delete().to(app::delete_handler)) + .route(web::patch().to(app::update_handler)), ) - .service(web::resource("/workspace_list/{user_id}") - .route(web::get().to(workspace::workspace_list)) + .service( + web::resource("/view") + .route(web::post().to(view::create_handler)) + .route(web::delete().to(view::delete_handler)) + .route(web::get().to(view::read_handler)) + .route(web::patch().to(view::update_handler)), ) - .service(web::resource("/app") - .route(web::post().to(app::create_handler)) - .route(web::get().to(app::read_handler)) - .route(web::delete().to(app::delete_handler)) - .route(web::patch().to(app::update_handler)) + .service( + web::resource("/doc") + .route(web::post().to(doc::create_document_handler)) + .route(web::get().to(doc::read_document_handler)) + .route(web::patch().to(doc::reset_document_handler)), ) - .service(web::resource("/view") - .route(web::post().to(view::create_handler)) - .route(web::delete().to(view::delete_handler)) - .route(web::get().to(view::read_handler)) - .route(web::patch().to(view::update_handler)) - ) - .service(web::resource("/doc") - .route(web::post().to(doc::create_document_handler)) - .route(web::get().to(doc::read_document_handler)) - .route(web::patch().to(doc::reset_document_handler)) - ) - .service(web::resource("/trash") - .route(web::post().to(trash::create_handler)) - .route(web::delete().to(trash::delete_handler)) - .route(web::get().to(trash::read_handler)) - ) - .service(web::resource("/sync") - .route(web::post().to(trash::create_handler)) + .service( + web::resource("/trash") + .route(web::post().to(trash::create_handler)) + .route(web::delete().to(trash::delete_handler)) + .route(web::get().to(trash::read_handler)), ) + .service(web::resource("/sync").route(web::post().to(trash::create_handler))) // password - .service(web::resource("/password_change") - .route(web::post().to(user::change_password)) - ) + .service(web::resource("/password_change").route(web::post().to(user::change_password))) } pub async fn init_app_context(configuration: &Settings) -> AppContext { diff --git a/backend/src/config/configuration.rs b/backend/src/config/configuration.rs index c3e79708a0..d18522a2dd 100644 --- a/backend/src/config/configuration.rs +++ b/backend/src/config/configuration.rs @@ -49,7 +49,9 @@ impl DatabaseSettings { .ssl_mode(ssl_mode) } - pub fn with_db(&self) -> PgConnectOptions { self.without_db().database(&self.database_name) } + pub fn with_db(&self) -> PgConnectOptions { + self.without_db().database(&self.database_name) + } } pub fn get_configuration() -> Result { diff --git a/backend/src/config/env.rs b/backend/src/config/env.rs index 0cbd063341..b4e1c2e376 100644 --- a/backend/src/config/env.rs +++ b/backend/src/config/env.rs @@ -1,9 +1,17 @@ use std::env; -pub fn domain() -> String { env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string()) } +pub fn domain() -> String { + env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string()) +} -pub fn jwt_secret() -> String { env::var("JWT_SECRET").unwrap_or_else(|_| "my secret".into()) } +pub fn jwt_secret() -> String { + env::var("JWT_SECRET").unwrap_or_else(|_| "my secret".into()) +} -pub fn secret() -> String { env::var("SECRET_KEY").unwrap_or_else(|_| "0123".repeat(8)) } +pub fn secret() -> String { + env::var("SECRET_KEY").unwrap_or_else(|_| "0123".repeat(8)) +} -pub fn use_https() -> bool { false } +pub fn use_https() -> bool { + false +} diff --git a/backend/src/context.rs b/backend/src/context.rs index 9c6a3dead1..6ae58c1d24 100644 --- a/backend/src/context.rs +++ b/backend/src/context.rs @@ -56,7 +56,11 @@ pub struct FlowyPersistence { } impl FlowyPersistence { - pub fn pg_pool(&self) -> PgPool { self.pg_pool.clone() } + pub fn pg_pool(&self) -> PgPool { + self.pg_pool.clone() + } - pub fn kv_store(&self) -> Arc { self.kv_store.clone() } + pub fn kv_store(&self) -> Arc { + self.kv_store.clone() + } } diff --git a/backend/src/entities/logged_user.rs b/backend/src/entities/logged_user.rs index 82eda21414..9930afa035 100644 --- a/backend/src/entities/logged_user.rs +++ b/backend/src/entities/logged_user.rs @@ -15,7 +15,9 @@ pub struct LoggedUser { } impl std::convert::From for LoggedUser { - fn from(c: Claim) -> Self { Self { user_id: c.user_id() } } + fn from(c: Claim) -> Self { + Self { user_id: c.user_id() } + } } impl LoggedUser { @@ -61,7 +63,7 @@ impl std::convert::TryFrom<&HeaderValue> for LoggedUser { Err(e) => { log::error!("Header to string failed: {:?}", e); Err(ServerError::unauthorized()) - }, + } } } } @@ -76,27 +78,31 @@ pub const EXPIRED_DURATION_DAYS: i64 = 30; pub struct AuthorizedUsers(DashMap); impl std::default::Default for AuthorizedUsers { - fn default() -> Self { Self(DashMap::new()) } + fn default() -> Self { + Self(DashMap::new()) + } } impl AuthorizedUsers { - pub fn new() -> Self { AuthorizedUsers::default() } + pub fn new() -> Self { + AuthorizedUsers::default() + } pub fn is_authorized(&self, user: &LoggedUser) -> bool { match self.0.get(user) { None => { tracing::debug!("user not login yet or server was reboot"); false - }, + } Some(status) => match *status { AuthStatus::Authorized(last_time) => { let current_time = Utc::now(); let days = (current_time - last_time).num_days(); days < EXPIRED_DURATION_DAYS - }, + } AuthStatus::NotAuthorized => { tracing::debug!("user logout already"); false - }, + } }, } } diff --git a/backend/src/entities/token.rs b/backend/src/entities/token.rs index 0f6a0488e2..2f5630699a 100644 --- a/backend/src/entities/token.rs +++ b/backend/src/entities/token.rs @@ -37,7 +37,9 @@ impl Claim { } } - pub fn user_id(self) -> String { self.user_id } + pub fn user_id(self) -> String { + self.user_id + } } // impl From for User { @@ -48,7 +50,7 @@ impl Claim { pub struct Token(pub String); impl Token { pub fn create_token(user_id: &str) -> Result { - let claims = Claim::with_user_id(&user_id); + let claims = Claim::with_user_id(user_id); encode( &Header::new(DEFAULT_ALGORITHM), &claims, diff --git a/backend/src/entities/user.rs b/backend/src/entities/user.rs index b8743f16a5..7a9b27b137 100644 --- a/backend/src/entities/user.rs +++ b/backend/src/entities/user.rs @@ -7,6 +7,7 @@ pub struct UserTable { pub(crate) id: uuid::Uuid, pub(crate) email: String, pub(crate) name: String, + #[allow(dead_code)] pub(crate) create_time: chrono::DateTime, pub(crate) password: String, } diff --git a/backend/src/middleware/auth_middleware.rs b/backend/src/middleware/auth_middleware.rs index 5832fcce95..bd4b5421e3 100644 --- a/backend/src/middleware/auth_middleware.rs +++ b/backend/src/middleware/auth_middleware.rs @@ -1,9 +1,7 @@ use actix_service::{Service, Transform}; use actix_web::{ dev::{ServiceRequest, ServiceResponse}, - Error, - HttpResponse, - ResponseError, + Error, HttpResponse, ResponseError, }; use crate::{ @@ -34,7 +32,9 @@ where type InitError = (); type Future = Ready>; - fn new_transform(&self, service: S) -> Self::Future { ok(AuthenticationMiddleware { service }) } + fn new_transform(&self, service: S) -> Self::Future { + ok(AuthenticationMiddleware { service }) + } } pub struct AuthenticationMiddleware { service: S, @@ -51,7 +51,9 @@ where type Error = Error; type Future = LocalBoxFuture<'static, Result>; - fn poll_ready(&self, cx: &mut Context<'_>) -> Poll> { self.service.poll_ready(cx) } + fn poll_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.service.poll_ready(cx) + } fn call(&self, req: ServiceRequest) -> Self::Future { let mut authenticate_pass: bool = false; @@ -77,7 +79,7 @@ where AUTHORIZED_USERS.store_auth(logged_user, true); } } - }, + } Err(e) => log::error!("{:?}", e), } } else { diff --git a/backend/src/services/core/app/persistence.rs b/backend/src/services/core/app/persistence.rs index 0d0b0414c9..182e10b176 100644 --- a/backend/src/services/core/app/persistence.rs +++ b/backend/src/services/core/app/persistence.rs @@ -101,7 +101,7 @@ fn default_color_style() -> Vec { Err(e) => { log::error!("Serialize color style failed: {:?}", e); vec![] - }, + } } } @@ -121,6 +121,7 @@ pub struct AppTable { pub(crate) last_view_id: String, pub(crate) modified_time: chrono::DateTime, pub(crate) create_time: chrono::DateTime, + #[allow(dead_code)] pub(crate) user_id: String, } impl std::convert::From for AppPB { diff --git a/backend/src/services/core/app/router.rs b/backend/src/services/core/app/router.rs index 714d7603df..21b29a3d93 100644 --- a/backend/src/services/core/app/router.rs +++ b/backend/src/services/core/app/router.rs @@ -73,7 +73,7 @@ pub async fn update_handler(payload: Payload, pool: Data) -> Result { let color_bytes = params.get_color_style().write_to_bytes()?; Some(color_bytes) - }, + } }; let desc = match params.has_desc() { diff --git a/backend/src/services/core/trash/persistence.rs b/backend/src/services/core/trash/persistence.rs index 7fec90abbb..553a7ffbbf 100644 --- a/backend/src/services/core/trash/persistence.rs +++ b/backend/src/services/core/trash/persistence.rs @@ -6,6 +6,7 @@ pub(crate) const TRASH_TABLE: &str = "trash_table"; #[derive(Debug, Clone, sqlx::FromRow)] pub struct TrashTable { pub(crate) id: uuid::Uuid, + #[allow(dead_code)] pub(crate) user_id: String, pub(crate) ty: i32, } diff --git a/backend/src/services/core/trash/trash.rs b/backend/src/services/core/trash/trash.rs index 0cd2c54471..96c07e601a 100644 --- a/backend/src/services/core/trash/trash.rs +++ b/backend/src/services/core/trash/trash.rs @@ -117,13 +117,13 @@ async fn delete_trash_associate_targets( match TrashType::from_i32(ty) { None => log::error!("Parser trash type with value: {} failed", ty), Some(ty) => match ty { - TrashType::Unknown => {}, + TrashType::Unknown => {} TrashType::View => { let _ = delete_view(transaction as &mut DBTransaction<'_>, kv_store, vec![id]).await; - }, + } TrashType::App => { let _ = delete_app(transaction as &mut DBTransaction<'_>, id).await; - }, + } }, } } @@ -164,13 +164,13 @@ pub(crate) async fn read_trash( match TrashType::from_i32(table.ty) { None => log::error!("Parser trash type with value: {} failed", table.ty), Some(ty) => match ty { - TrashType::Unknown => {}, + TrashType::Unknown => {} TrashType::View => { trash.push(read_view_table(table.id, transaction).await?.into()); - }, + } TrashType::App => { trash.push(read_app_table(table.id, transaction).await?.into()); - }, + } }, } } diff --git a/backend/src/services/core/view/controller.rs b/backend/src/services/core/view/controller.rs index 435be53e00..8d0f811606 100644 --- a/backend/src/services/core/view/controller.rs +++ b/backend/src/services/core/view/controller.rs @@ -116,7 +116,7 @@ pub(crate) async fn read_view( let mut views = RepeatedViewPB::default(); views.set_items( - read_view_belong_to_id(&table.id.to_string(), &user, transaction) + read_view_belong_to_id(&table.id.to_string(), user, transaction) .await? .into(), ); diff --git a/backend/src/services/core/view/router.rs b/backend/src/services/core/view/router.rs index cf89f2629c..c8466da76c 100644 --- a/backend/src/services/core/view/router.rs +++ b/backend/src/services/core/view/router.rs @@ -2,11 +2,9 @@ use crate::{ context::FlowyPersistence, entities::logged_user::LoggedUser, services::core::view::{ - create_view, - delete_view, + create_view, delete_view, persistence::{check_view_id, check_view_ids}, - read_view, - update_view, + read_view, update_view, }, util::serde_ext::parse_from_payload, }; @@ -22,10 +20,8 @@ use backend_service::{ use flowy_core_data_model::{ parser::view::{ViewDesc, ViewName, ViewThumbnail}, protobuf::{ - CreateViewParams as CreateViewParamsPB, - QueryViewRequest as QueryViewRequestPB, - UpdateViewParams as UpdateViewParamsPB, - ViewId as ViewIdPB, + CreateViewParams as CreateViewParamsPB, QueryViewRequest as QueryViewRequestPB, + UpdateViewParams as UpdateViewParamsPB, ViewId as ViewIdPB, }, }; use sqlx::PgPool; diff --git a/backend/src/services/core/workspace/router.rs b/backend/src/services/core/workspace/router.rs index 45178e7885..0ed76bb378 100644 --- a/backend/src/services/core/workspace/router.rs +++ b/backend/src/services/core/workspace/router.rs @@ -1,11 +1,7 @@ use crate::{ entities::logged_user::LoggedUser, services::core::workspace::{ - create_workspace, - delete_workspace, - persistence::check_workspace_id, - read_workspaces, - update_workspace, + create_workspace, delete_workspace, persistence::check_workspace_id, read_workspaces, update_workspace, }, util::serde_ext::parse_from_payload, }; @@ -21,8 +17,7 @@ use backend_service::{ use flowy_core_data_model::{ parser::workspace::{WorkspaceDesc, WorkspaceName}, protobuf::{ - CreateWorkspaceParams as CreateWorkspaceParamsPB, - UpdateWorkspaceParams as UpdateWorkspaceParamsPB, + CreateWorkspaceParams as CreateWorkspaceParamsPB, UpdateWorkspaceParams as UpdateWorkspaceParamsPB, WorkspaceId as WorkspaceIdPB, }, }; @@ -110,7 +105,7 @@ pub async fn update_handler( .map_err(invalid_params)? .0; Some(name) - }, + } }; let desc = match params.has_desc() { @@ -120,7 +115,7 @@ pub async fn update_handler( .map_err(invalid_params)? .0; Some(desc) - }, + } }; let mut transaction = pool diff --git a/backend/src/services/document/persistence.rs b/backend/src/services/document/persistence.rs index b7b5ec4ffa..afdde80b4f 100644 --- a/backend/src/services/document/persistence.rs +++ b/backend/src/services/document/persistence.rs @@ -7,11 +7,7 @@ use backend_service::errors::{internal_error, ServerError}; use bytes::Bytes; use flowy_collaboration::{ protobuf::{ - CreateDocParams, - DocumentId, - DocumentInfo, - RepeatedRevision as RepeatedRevisionPB, - ResetDocumentParams, + CreateDocParams, DocumentId, DocumentInfo, RepeatedRevision as RepeatedRevisionPB, ResetDocumentParams, Revision as RevisionPB, }, sync::ServerDocumentManager, @@ -71,15 +67,21 @@ pub struct DocumentKVPersistence { impl std::ops::Deref for DocumentKVPersistence { type Target = Arc; - fn deref(&self) -> &Self::Target { &self.inner } + fn deref(&self) -> &Self::Target { + &self.inner + } } impl std::ops::DerefMut for DocumentKVPersistence { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } } impl DocumentKVPersistence { - pub(crate) fn new(kv_store: Arc) -> Self { DocumentKVPersistence { inner: kv_store } } + pub(crate) fn new(kv_store: Arc) -> Self { + DocumentKVPersistence { inner: kv_store } + } pub(crate) async fn batch_set_revision(&self, revisions: Vec) -> Result<(), ServerError> { let items = revisions_to_key_value_items(revisions)?; @@ -109,7 +111,7 @@ impl DocumentKVPersistence { self.inner .transaction(|mut t| Box::pin(async move { t.batch_get_start_with(&doc_id).await })) .await? - }, + } Some(rev_ids) => { let keys = rev_ids .into_iter() @@ -119,7 +121,7 @@ impl DocumentKVPersistence { self.inner .transaction(|mut t| Box::pin(async move { t.batch_get(keys).await })) .await? - }, + } }; Ok(key_value_items_to_revisions(items)) @@ -136,7 +138,7 @@ impl DocumentKVPersistence { self.inner .transaction(|mut t| Box::pin(async move { t.batch_delete_key_start_with(&doc_id).await })) .await - }, + } Some(rev_ids) => { let keys = rev_ids .into_iter() @@ -146,7 +148,7 @@ impl DocumentKVPersistence { self.inner .transaction(|mut t| Box::pin(async move { t.batch_delete(keys).await })) .await - }, + } } } } @@ -181,7 +183,9 @@ fn key_value_items_to_revisions(items: Vec) -> RepeatedRevisionPB { } #[inline] -fn make_revision_key(doc_id: &str, rev_id: i64) -> String { format!("{}:{}", doc_id, rev_id) } +fn make_revision_key(doc_id: &str, rev_id: i64) -> String { + format!("{}:{}", doc_id, rev_id) +} #[inline] fn make_doc_from_revisions(doc_id: &str, mut revisions: RepeatedRevisionPB) -> Result { diff --git a/backend/src/services/document/router.rs b/backend/src/services/document/router.rs index df7686c571..d3fcbb9021 100644 --- a/backend/src/services/document/router.rs +++ b/backend/src/services/document/router.rs @@ -10,9 +10,7 @@ use actix_web::{ use backend_service::{errors::ServerError, response::FlowyResponse}; use flowy_collaboration::{ protobuf::{ - CreateDocParams as CreateDocParamsPB, - DocumentId as DocumentIdPB, - ResetDocumentParams as ResetDocumentParamsPB, + CreateDocParams as CreateDocParamsPB, DocumentId as DocumentIdPB, ResetDocumentParams as ResetDocumentParamsPB, }, sync::ServerDocumentManager, }; diff --git a/backend/src/services/document/ws_actor.rs b/backend/src/services/document/ws_actor.rs index 52c175a287..e45856a600 100644 --- a/backend/src/services/document/ws_actor.rs +++ b/backend/src/services/document/ws_actor.rs @@ -9,8 +9,7 @@ use backend_service::errors::{internal_error, Result, ServerError}; use flowy_collaboration::{ protobuf::{ - DocumentClientWSData as DocumentClientWSDataPB, - DocumentClientWSDataType as DocumentClientWSDataTypePB, + DocumentClientWSData as DocumentClientWSDataPB, DocumentClientWSDataType as DocumentClientWSDataTypePB, Revision as RevisionPB, }, sync::{RevisionUser, ServerDocumentManager, SyncResponse}, @@ -66,7 +65,7 @@ impl DocumentWebSocketActor { ret, } => { let _ = ret.send(self.handle_client_data(client_data, persistence).await); - }, + } } } @@ -96,14 +95,14 @@ impl DocumentWebSocketActor { .handle_client_revisions(user, document_client_data) .await .map_err(internal_error)?; - }, + } DocumentClientWSDataTypePB::ClientPing => { let _ = self .doc_manager .handle_client_ping(user, document_client_data) .await .map_err(internal_error)?; - }, + } } Ok(()) @@ -135,37 +134,39 @@ impl std::fmt::Debug for ServerDocUser { } impl RevisionUser for ServerDocUser { - fn user_id(&self) -> String { self.user.id().to_string() } + fn user_id(&self) -> String { + self.user.id().to_string() + } fn receive(&self, resp: SyncResponse) { let result = match resp { SyncResponse::Pull(data) => { let msg: WebSocketMessage = data.into(); self.socket.try_send(msg).map_err(internal_error) - }, + } SyncResponse::Push(data) => { let msg: WebSocketMessage = data.into(); self.socket.try_send(msg).map_err(internal_error) - }, + } SyncResponse::Ack(data) => { let msg: WebSocketMessage = data.into(); self.socket.try_send(msg).map_err(internal_error) - }, + } SyncResponse::NewRevision(mut repeated_revision) => { let kv_store = self.persistence.kv_store(); tokio::task::spawn(async move { let revisions = repeated_revision.take_items().into(); match kv_store.batch_set_revision(revisions).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("{}", e), } }); Ok(()) - }, + } }; match result { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[ServerDocUser]: {}", e), } } diff --git a/backend/src/services/document/ws_receiver.rs b/backend/src/services/document/ws_receiver.rs index d9e68685a2..a4e8194219 100644 --- a/backend/src/services/document/ws_receiver.rs +++ b/backend/src/services/document/ws_receiver.rs @@ -13,9 +13,7 @@ use flowy_collaboration::{ entities::doc::DocumentInfo, errors::CollaborateError, protobuf::{ - CreateDocParams as CreateDocParamsPB, - DocumentId, - RepeatedRevision as RepeatedRevisionPB, + CreateDocParams as CreateDocParamsPB, DocumentId, RepeatedRevision as RepeatedRevisionPB, Revision as RevisionPB, }, sync::{DocumentPersistence, ServerDocumentManager}, @@ -65,11 +63,11 @@ impl WebSocketReceiver for DocumentWebSocketReceiver { }; match sender.send(msg).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("{}", e), } match rx.await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("{:?}", e), }; }); @@ -78,7 +76,9 @@ impl WebSocketReceiver for DocumentWebSocketReceiver { pub struct DocumentPersistenceImpl(pub Arc); impl Debug for DocumentPersistenceImpl { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("DocumentPersistenceImpl") } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str("DocumentPersistenceImpl") + } } impl DocumentPersistence for DocumentPersistenceImpl { diff --git a/backend/src/services/kv/kv.rs b/backend/src/services/kv/kv.rs index 4273fe8633..30189edf33 100644 --- a/backend/src/services/kv/kv.rs +++ b/backend/src/services/kv/kv.rs @@ -11,11 +11,7 @@ use lib_infra::future::BoxResultFuture; use sql_builder::SqlBuilder as RawSqlBuilder; use sqlx::{ postgres::{PgArguments, PgRow}, - Arguments, - Error, - PgPool, - Postgres, - Row, + Arguments, Error, PgPool, Postgres, Row, }; const KV_TABLE: &str = "kv_table"; @@ -208,6 +204,7 @@ fn rows_to_key_values(rows: Vec) -> Vec { #[derive(Debug, Clone, sqlx::FromRow)] struct KVTable { + #[allow(dead_code)] pub(crate) id: String, pub(crate) blob: Vec, } diff --git a/backend/src/services/user/controller.rs b/backend/src/services/user/controller.rs index e0ceea690a..7930f06ed1 100644 --- a/backend/src/services/user/controller.rs +++ b/backend/src/services/user/controller.rs @@ -18,12 +18,8 @@ use chrono::Utc; use flowy_user_data_model::{ parser::{UserEmail, UserName, UserPassword}, protobuf::{ - SignInParams as SignInParamsPB, - SignInResponse as SignInResponsePB, - SignUpParams as SignUpParamsPB, - SignUpResponse as SignUpResponsePB, - UpdateUserParams as UpdateUserParamsPB, - UserProfile as UserProfilePB, + SignInParams as SignInParamsPB, SignInResponse as SignInResponsePB, SignUpParams as SignUpParamsPB, + SignUpResponse as SignUpResponsePB, UpdateUserParams as UpdateUserParamsPB, UserProfile as UserProfilePB, }, }; use sqlx::{PgPool, Postgres}; @@ -150,7 +146,7 @@ pub(crate) async fn set_user_profile( let password = UserPassword::parse(params.get_password().to_owned()).map_err(invalid_params)?; let password = hash_password(password.as_ref())?; Some(password) - }, + } }; let (sql, args) = SqlBuilder::update("user_table") @@ -200,7 +196,7 @@ async fn check_user_password( .await .map_err(|err| ServerError::internal().context(err))?; - match verify_password(&password, &user.password) { + match verify_password(password, &user.password) { Ok(true) => Ok(user), _ => Err(ServerError::password_not_match()), } diff --git a/backend/src/services/user/router.rs b/backend/src/services/user/router.rs index bc10737d05..52efbe4dfa 100644 --- a/backend/src/services/user/router.rs +++ b/backend/src/services/user/router.rs @@ -6,14 +6,11 @@ use crate::{ use actix_identity::Identity; use actix_web::{ web::{Data, Payload}, - HttpRequest, - HttpResponse, + HttpRequest, HttpResponse, }; use backend_service::{errors::ServerError, response::FlowyResponse}; use flowy_user_data_model::protobuf::{ - SignInParams as SignInParamsPB, - SignUpParams as SignUpParamsPB, - UpdateUserParams as UpdateUserParamsPB, + SignInParams as SignInParamsPB, SignUpParams as SignUpParamsPB, UpdateUserParams as UpdateUserParamsPB, }; use sqlx::PgPool; diff --git a/backend/src/services/web_socket/entities/connect.rs b/backend/src/services/web_socket/entities/connect.rs index cbab9a194d..c083950e45 100644 --- a/backend/src/services/web_socket/entities/connect.rs +++ b/backend/src/services/web_socket/entities/connect.rs @@ -10,13 +10,15 @@ pub type Socket = Recipient; pub struct SessionId(pub String); impl> std::convert::From for SessionId { - fn from(s: T) -> Self { SessionId(s.as_ref().to_owned()) } + fn from(s: T) -> Self { + SessionId(s.as_ref().to_owned()) + } } impl std::fmt::Display for SessionId { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let desc = &self.0.to_string(); - f.write_str(&desc) + f.write_str(desc) } } diff --git a/backend/src/services/web_socket/entities/message.rs b/backend/src/services/web_socket/entities/message.rs index 056c37cfba..89ea01aafb 100644 --- a/backend/src/services/web_socket/entities/message.rs +++ b/backend/src/services/web_socket/entities/message.rs @@ -11,7 +11,9 @@ pub struct WebSocketMessage(pub Bytes); impl std::ops::Deref for WebSocketMessage { type Target = Bytes; - fn deref(&self) -> &Self::Target { &self.0 } + fn deref(&self) -> &Self::Target { + &self.0 + } } impl std::convert::From for WebSocketMessage { diff --git a/backend/src/services/web_socket/router.rs b/backend/src/services/web_socket/router.rs index 609d27a201..ee9c61cf45 100644 --- a/backend/src/services/web_socket/router.rs +++ b/backend/src/services/web_socket/router.rs @@ -6,9 +6,7 @@ use actix::Addr; use actix_web::{ get, web::{Data, Path, Payload}, - Error, - HttpRequest, - HttpResponse, + Error, HttpRequest, HttpResponse, }; use actix_web_actors::ws; diff --git a/backend/src/services/web_socket/ws_client.rs b/backend/src/services/web_socket/ws_client.rs index 4342a1fbb1..51ddf5e847 100644 --- a/backend/src/services/web_socket/ws_client.rs +++ b/backend/src/services/web_socket/ws_client.rs @@ -3,8 +3,7 @@ use crate::{ entities::logged_user::LoggedUser, services::web_socket::{ entities::{Connect, Disconnect, Socket}, - WSServer, - WebSocketMessage, + WSServer, WebSocketMessage, }, }; use actix::*; @@ -18,22 +17,23 @@ pub trait WebSocketReceiver: Send + Sync { fn receive(&self, data: WSClientData); } +#[derive(Default)] pub struct WebSocketReceivers { inner: HashMap>, } -impl std::default::Default for WebSocketReceivers { - fn default() -> Self { Self { inner: HashMap::new() } } -} - impl WebSocketReceivers { - pub fn new() -> Self { WebSocketReceivers::default() } + pub fn new() -> Self { + WebSocketReceivers::default() + } pub fn set(&mut self, source: WSModule, receiver: Arc) { self.inner.insert(source, receiver); } - pub fn get(&self, source: &WSModule) -> Option> { self.inner.get(source).cloned() } + pub fn get(&self, source: &WSModule) -> Option> { + self.inner.get(source).cloned() + } } #[derive(Debug)] @@ -42,9 +42,13 @@ pub struct WSUser { } impl WSUser { - pub fn new(inner: LoggedUser) -> Self { Self { inner } } + pub fn new(inner: LoggedUser) -> Self { + Self { inner } + } - pub fn id(&self) -> &str { &self.inner.user_id } + pub fn id(&self) -> &str { + &self.inner.user_id + } } pub struct WSClientData { @@ -89,7 +93,7 @@ impl WSClient { match self.ws_receivers.get(&message.module) { None => { log::error!("Can't find the receiver for {:?}", message.module); - }, + } Some(handler) => { let client_data = WSClientData { user: self.user.clone(), @@ -97,7 +101,7 @@ impl WSClient { data: Bytes::from(message.data), }; handler.receive(client_data); - }, + } } } } @@ -108,28 +112,28 @@ impl StreamHandler> for WSClient { Ok(ws::Message::Ping(msg)) => { self.hb = Instant::now(); ctx.pong(&msg); - }, + } Ok(ws::Message::Pong(_msg)) => { // tracing::debug!("Receive {} pong {:?}", &self.session_id, &msg); self.hb = Instant::now(); - }, + } Ok(ws::Message::Binary(bytes)) => { let socket = ctx.address().recipient(); self.handle_binary_message(bytes, socket); - }, + } Ok(Text(_)) => { log::warn!("Receive unexpected text message"); - }, + } Ok(ws::Message::Close(reason)) => { ctx.close(reason); ctx.stop(); - }, - Ok(ws::Message::Continuation(_)) => {}, - Ok(ws::Message::Nop) => {}, + } + Ok(ws::Message::Continuation(_)) => {} + Ok(ws::Message::Nop) => {} Err(e) => { log::error!("[{}]: WebSocketStream protocol error {:?}", self.user.id(), e); ctx.stop(); - }, + } } } } @@ -137,7 +141,9 @@ impl StreamHandler> for WSClient { impl Handler for WSClient { type Result = (); - fn handle(&mut self, msg: WebSocketMessage, ctx: &mut Self::Context) { ctx.binary(msg.0); } + fn handle(&mut self, msg: WebSocketMessage, ctx: &mut Self::Context) { + ctx.binary(msg.0); + } } impl Actor for WSClient { diff --git a/backend/src/services/web_socket/ws_server.rs b/backend/src/services/web_socket/ws_server.rs index 01940472f1..af69c0f4d8 100644 --- a/backend/src/services/web_socket/ws_server.rs +++ b/backend/src/services/web_socket/ws_server.rs @@ -18,9 +18,13 @@ impl std::default::Default for WSServer { } } impl WSServer { - pub fn new() -> Self { WSServer::default() } + pub fn new() -> Self { + WSServer::default() + } - pub fn send(&self, _msg: WebSocketMessage) { unimplemented!() } + pub fn send(&self, _msg: WebSocketMessage) { + unimplemented!() + } } impl Actor for WSServer { @@ -49,7 +53,9 @@ impl Handler for WSServer { impl Handler for WSServer { type Result = (); - fn handle(&mut self, _msg: WebSocketMessage, _ctx: &mut Context) -> Self::Result { unimplemented!() } + fn handle(&mut self, _msg: WebSocketMessage, _ctx: &mut Context) -> Self::Result { + unimplemented!() + } } impl actix::Supervised for WSServer { diff --git a/backend/src/util/serde_ext.rs b/backend/src/util/serde_ext.rs index 327b43a3d6..04b791ca11 100644 --- a/backend/src/util/serde_ext.rs +++ b/backend/src/util/serde_ext.rs @@ -22,7 +22,7 @@ pub fn md5>(data: T) -> String { } pub fn parse_from_bytes(bytes: &[u8]) -> Result { - let result: ProtobufResult = Message::parse_from_bytes(&bytes); + let result: ProtobufResult = Message::parse_from_bytes(bytes); match result { Ok(data) => Ok(data), Err(e) => Err(e.into()), diff --git a/backend/src/util/sqlx_ext/query.rs b/backend/src/util/sqlx_ext/query.rs index f7af99ba24..99414b71b9 100644 --- a/backend/src/util/sqlx_ext/query.rs +++ b/backend/src/util/sqlx_ext/query.rs @@ -117,7 +117,7 @@ impl SqlBuilder { let sql = inner.sql()?; Ok((sql, self.fields_args)) - }, + } BuilderType::Select => { let mut inner = InnerBuilder::select_from(&self.table); self.fields.into_iter().for_each(|field| { @@ -130,7 +130,7 @@ impl SqlBuilder { let sql = inner.sql()?; Ok((sql, self.fields_args)) - }, + } BuilderType::Update => { let mut inner = InnerBuilder::update_table(&self.table); let field_len = self.fields.len(); @@ -145,7 +145,7 @@ impl SqlBuilder { let sql = inner.sql()?; Ok((sql, self.fields_args)) - }, + } BuilderType::Delete => { let mut inner = InnerBuilder::delete_from(&self.table); self.filters.into_iter().enumerate().for_each(|(index, filter)| { @@ -153,7 +153,7 @@ impl SqlBuilder { }); let sql = inner.sql()?; Ok((sql, self.fields_args)) - }, + } } } } diff --git a/backend/src/util/user_ext.rs b/backend/src/util/user_ext.rs index ed4428922b..5d6e8c8867 100644 --- a/backend/src/util/user_ext.rs +++ b/backend/src/util/user_ext.rs @@ -2,7 +2,9 @@ use backend_service::errors::{ErrorCode, ServerError}; use bcrypt::{hash, verify, DEFAULT_COST}; #[allow(dead_code)] -pub fn uuid() -> String { uuid::Uuid::new_v4().to_string() } +pub fn uuid() -> String { + uuid::Uuid::new_v4().to_string() +} pub fn hash_password(plain: &str) -> Result { let hashing_cost = std::env::var("HASH_COST") diff --git a/backend/tests/api_test/auth_test.rs b/backend/tests/api_test/auth_test.rs index 3b98a8a947..aa8c3c2d46 100644 --- a/backend/tests/api_test/auth_test.rs +++ b/backend/tests/api_test/auth_test.rs @@ -76,10 +76,10 @@ async fn user_update_password() { }; match server.sign_in(sign_in_params).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => { assert_eq!(e.code, ErrorCode::PasswordNotMatch); - }, + } } } diff --git a/backend/tests/util/helper.rs b/backend/tests/util/helper.rs index ee1b92b96a..c3970def27 100644 --- a/backend/tests/util/helper.rs +++ b/backend/tests/util/helper.rs @@ -45,9 +45,13 @@ impl TestUserServer { let _ = user_sign_out_request(self.user_token(), &url).await.unwrap(); } - pub fn user_token(&self) -> &str { self.user_token.as_ref().expect("must call register_user first ") } + pub fn user_token(&self) -> &str { + self.user_token.as_ref().expect("must call register_user first ") + } - pub fn user_id(&self) -> &str { self.user_id.as_ref().expect("must call register_user first ") } + pub fn user_id(&self) -> &str { + self.user_id.as_ref().expect("must call register_user first ") + } pub async fn get_user_profile(&self) -> UserProfile { let url = format!("{}/api/user", self.http_addr()); @@ -178,7 +182,9 @@ impl TestUserServer { response } - pub fn http_addr(&self) -> String { self.inner.client_server_config.base_url() } + pub fn http_addr(&self) -> String { + self.inner.client_server_config.base_url() + } pub fn ws_addr(&self) -> String { format!( @@ -336,7 +342,9 @@ impl WorkspaceTest { Self { server, workspace } } - pub async fn create_app(&self) -> App { create_test_app(&self.server, &self.workspace.id).await } + pub async fn create_app(&self) -> App { + create_test_app(&self.server, &self.workspace.id).await + } } pub struct AppTest { diff --git a/frontend/rust-lib/dart-ffi/src/lib.rs b/frontend/rust-lib/dart-ffi/src/lib.rs index ea396464d0..4a0cd5a802 100644 --- a/frontend/rust-lib/dart-ffi/src/lib.rs +++ b/frontend/rust-lib/dart-ffi/src/lib.rs @@ -18,7 +18,9 @@ lazy_static! { static ref FLOWY_SDK: RwLock>> = RwLock::new(None); } -fn dispatch() -> Arc { FLOWY_SDK.read().as_ref().unwrap().dispatcher() } +fn dispatch() -> Arc { + FLOWY_SDK.read().as_ref().unwrap().dispatcher() +} #[no_mangle] pub extern "C" fn init_sdk(path: *mut c_char) -> i64 { @@ -85,13 +87,13 @@ async fn post_to_flutter(response: EventResponse, port: i64) { { Ok(_success) => { log::trace!("[FFI]: Post data to dart success"); - }, + } Err(e) => { if let Some(msg) = e.downcast_ref::<&str>() { log::error!("[FFI]: {:?}", msg); } else { log::error!("[FFI]: allo_isolate post panic"); } - }, + } } } diff --git a/frontend/rust-lib/dart-ffi/src/model/ffi_request.rs b/frontend/rust-lib/dart-ffi/src/model/ffi_request.rs index 043a4e0b22..d1123d40df 100644 --- a/frontend/rust-lib/dart-ffi/src/model/ffi_request.rs +++ b/frontend/rust-lib/dart-ffi/src/model/ffi_request.rs @@ -22,5 +22,7 @@ impl FFIRequest { } impl std::convert::From for ModuleRequest { - fn from(ffi_request: FFIRequest) -> Self { ModuleRequest::new(ffi_request.event).payload(ffi_request.payload) } + fn from(ffi_request: FFIRequest) -> Self { + ModuleRequest::new(ffi_request.event).payload(ffi_request.payload) + } } diff --git a/frontend/rust-lib/dart-ffi/src/model/ffi_response.rs b/frontend/rust-lib/dart-ffi/src/model/ffi_response.rs index 06e81d8b9e..ea9afa5720 100644 --- a/frontend/rust-lib/dart-ffi/src/model/ffi_response.rs +++ b/frontend/rust-lib/dart-ffi/src/model/ffi_response.rs @@ -3,13 +3,15 @@ use lib_dispatch::prelude::{EventResponse, Payload, StatusCode}; #[derive(ProtoBuf_Enum, Clone, Copy)] pub enum FFIStatusCode { - Ok = 0, - Err = 1, + Ok = 0, + Err = 1, Internal = 2, } impl std::default::Default for FFIStatusCode { - fn default() -> FFIStatusCode { FFIStatusCode::Ok } + fn default() -> FFIStatusCode { + FFIStatusCode::Ok + } } #[derive(ProtoBuf, Default)] diff --git a/frontend/rust-lib/dart-notify/src/dart/stream_sender.rs b/frontend/rust-lib/dart-notify/src/dart/stream_sender.rs index 274556b54e..0f41637dc2 100644 --- a/frontend/rust-lib/dart-notify/src/dart/stream_sender.rs +++ b/frontend/rust-lib/dart-notify/src/dart/stream_sender.rs @@ -13,7 +13,9 @@ pub struct DartStreamSender { } impl DartStreamSender { - fn new() -> Self { Self { isolate: None } } + fn new() -> Self { + Self { isolate: None } + } fn inner_set_port(&mut self, port: i64) { log::info!("Setup rust to flutter stream with port {}", port); @@ -27,7 +29,7 @@ impl DartStreamSender { let bytes: Bytes = observable_subject.try_into().unwrap(); isolate.post(bytes.to_vec()); Ok(()) - }, + } None => Err("Isolate is not set".to_owned()), } } @@ -38,7 +40,7 @@ impl DartStreamSender { Err(e) => { let msg = format!("Get rust to flutter stream lock fail. {:?}", e); log::error!("{:?}", msg); - }, + } } } diff --git a/frontend/rust-lib/dart-notify/src/lib.rs b/frontend/rust-lib/dart-notify/src/lib.rs index b0834b3095..b6fbb1ca78 100644 --- a/frontend/rust-lib/dart-notify/src/lib.rs +++ b/frontend/rust-lib/dart-notify/src/lib.rs @@ -34,7 +34,7 @@ impl DartNotifyBuilder { Ok(bytes) => self.payload = Some(bytes), Err(e) => { log::error!("Set observable payload failed: {:?}", e); - }, + } } self @@ -48,7 +48,7 @@ impl DartNotifyBuilder { Ok(bytes) => self.error = Some(bytes), Err(e) => { log::error!("Set observable error failed: {:?}", e); - }, + } } self } @@ -67,7 +67,7 @@ impl DartNotifyBuilder { }; match DartStreamSender::post(subject) { - Ok(_) => {}, + Ok(_) => {} Err(error) => log::error!("Send observable subject failed: {}", error), } } diff --git a/frontend/rust-lib/flowy-core/src/context.rs b/frontend/rust-lib/flowy-core/src/context.rs index 4df573515a..a7b3415751 100644 --- a/frontend/rust-lib/flowy-core/src/context.rs +++ b/frontend/rust-lib/flowy-core/src/context.rs @@ -57,10 +57,10 @@ impl CoreContext { pub fn network_state_changed(&self, new_type: NetworkType) { match new_type { - NetworkType::UnknownNetworkType => {}, - NetworkType::Wifi => {}, - NetworkType::Cell => {}, - NetworkType::Ethernet => {}, + NetworkType::UnknownNetworkType => {} + NetworkType::Wifi => {} + NetworkType::Cell => {} + NetworkType::Ethernet => {} } } diff --git a/frontend/rust-lib/flowy-core/src/event.rs b/frontend/rust-lib/flowy-core/src/event.rs index 403491ca4d..4748f649a1 100644 --- a/frontend/rust-lib/flowy-core/src/event.rs +++ b/frontend/rust-lib/flowy-core/src/event.rs @@ -5,77 +5,77 @@ use strum_macros::Display; #[event_err = "FlowyError"] pub enum WorkspaceEvent { #[event(input = "CreateWorkspaceRequest", output = "Workspace")] - CreateWorkspace = 0, + CreateWorkspace = 0, #[event(output = "CurrentWorkspaceSetting")] - ReadCurWorkspace = 1, + ReadCurWorkspace = 1, #[event(input = "QueryWorkspaceRequest", output = "RepeatedWorkspace")] - ReadWorkspaces = 2, + ReadWorkspaces = 2, #[event(input = "QueryWorkspaceRequest")] - DeleteWorkspace = 3, + DeleteWorkspace = 3, #[event(input = "QueryWorkspaceRequest", output = "Workspace")] - OpenWorkspace = 4, + OpenWorkspace = 4, #[event(input = "QueryWorkspaceRequest", output = "RepeatedApp")] ReadWorkspaceApps = 5, #[event(input = "CreateAppRequest", output = "App")] - CreateApp = 101, + CreateApp = 101, #[event(input = "QueryAppRequest")] - DeleteApp = 102, + DeleteApp = 102, #[event(input = "QueryAppRequest", output = "App")] - ReadApp = 103, + ReadApp = 103, #[event(input = "UpdateAppRequest")] - UpdateApp = 104, + UpdateApp = 104, #[event(input = "CreateViewRequest", output = "View")] - CreateView = 201, + CreateView = 201, #[event(input = "QueryViewRequest", output = "View")] - ReadView = 202, + ReadView = 202, #[event(input = "UpdateViewRequest", output = "View")] - UpdateView = 203, + UpdateView = 203, #[event(input = "QueryViewRequest")] - DeleteView = 204, + DeleteView = 204, #[event(input = "QueryViewRequest")] - DuplicateView = 205, + DuplicateView = 205, #[event()] - CopyLink = 206, + CopyLink = 206, #[event(input = "QueryViewRequest", output = "DocumentDelta")] - OpenView = 207, + OpenView = 207, #[event(input = "QueryViewRequest")] - CloseView = 208, + CloseView = 208, #[event(output = "RepeatedTrash")] - ReadTrash = 300, + ReadTrash = 300, #[event(input = "TrashId")] - PutbackTrash = 301, + PutbackTrash = 301, #[event(input = "RepeatedTrashId")] - DeleteTrash = 302, + DeleteTrash = 302, #[event()] - RestoreAll = 303, + RestoreAll = 303, #[event()] - DeleteAll = 304, + DeleteAll = 304, #[event(input = "DocumentDelta", output = "DocumentDelta")] - ApplyDocDelta = 400, + ApplyDocDelta = 400, #[event(input = "ExportRequest", output = "ExportData")] - ExportDocument = 500, + ExportDocument = 500, } diff --git a/frontend/rust-lib/flowy-core/src/event_handler.rs b/frontend/rust-lib/flowy-core/src/event_handler.rs index 13d32013d3..a173670079 100644 --- a/frontend/rust-lib/flowy-core/src/event_handler.rs +++ b/frontend/rust-lib/flowy-core/src/event_handler.rs @@ -3,8 +3,7 @@ use crate::{ errors::FlowyError, notify::{send_dart_notification, WorkspaceNotification}, services::{ - get_current_workspace, - read_local_workspace_apps, + get_current_workspace, read_local_workspace_apps, workspace::sql::{WorkspaceTable, WorkspaceTableSql}, }, }; @@ -86,14 +85,14 @@ fn read_workspaces_on_server( for app in apps { let views = app.belongings.clone().into_inner(); match app_ctrl.save_app(app, &*conn) { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("create app failed: {:?}", e), } tracing::debug!("Save {} views", views.len()); for view in views { match view_ctrl.save_view(view, &*conn) { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("create view failed: {:?}", e), } } diff --git a/frontend/rust-lib/flowy-core/src/macros.rs b/frontend/rust-lib/flowy-core/src/macros.rs index a02007d694..6afcd95f72 100644 --- a/frontend/rust-lib/flowy-core/src/macros.rs +++ b/frontend/rust-lib/flowy-core/src/macros.rs @@ -15,15 +15,21 @@ macro_rules! impl_def_and_def_mut { impl std::ops::Deref for $target { type Target = Vec<$item>; - fn deref(&self) -> &Self::Target { &self.items } + fn deref(&self) -> &Self::Target { + &self.items + } } impl std::ops::DerefMut for $target { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.items } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.items + } } impl $target { #[allow(dead_code)] - pub fn into_inner(&mut self) -> Vec<$item> { ::std::mem::replace(&mut self.items, vec![]) } + pub fn into_inner(&mut self) -> Vec<$item> { + ::std::mem::replace(&mut self.items, vec![]) + } #[allow(dead_code)] pub fn push(&mut self, item: $item) { @@ -35,7 +41,9 @@ macro_rules! impl_def_and_def_mut { self.items.push(item); } - pub fn first_or_crash(&self) -> &$item { self.items.first().unwrap() } + pub fn first_or_crash(&self) -> &$item { + self.items.first().unwrap() + } } }; } diff --git a/frontend/rust-lib/flowy-core/src/module.rs b/frontend/rust-lib/flowy-core/src/module.rs index e22a2b3d5e..8c22e69c77 100644 --- a/frontend/rust-lib/flowy-core/src/module.rs +++ b/frontend/rust-lib/flowy-core/src/module.rs @@ -6,15 +6,8 @@ use crate::{ event::WorkspaceEvent, event_handler::*, services::{ - app::event_handler::*, - server::construct_workspace_server, - trash::event_handler::*, - view::event_handler::*, - workspace::event_handler::*, - AppController, - TrashController, - ViewController, - WorkspaceController, + app::event_handler::*, server::construct_workspace_server, trash::event_handler::*, view::event_handler::*, + workspace::event_handler::*, AppController, TrashController, ViewController, WorkspaceController, }, }; use backend_service::configuration::ClientServerConfiguration; diff --git a/frontend/rust-lib/flowy-core/src/notify/observable.rs b/frontend/rust-lib/flowy-core/src/notify/observable.rs index f5c379313e..97e807362a 100644 --- a/frontend/rust-lib/flowy-core/src/notify/observable.rs +++ b/frontend/rust-lib/flowy-core/src/notify/observable.rs @@ -6,27 +6,31 @@ const OBSERVABLE_CATEGORY: &str = "Workspace"; // be use directly in flutter #[derive(ProtoBuf_Enum, Debug)] pub(crate) enum WorkspaceNotification { - Unknown = 0, - UserCreateWorkspace = 10, - UserDeleteWorkspace = 11, - WorkspaceUpdated = 12, + Unknown = 0, + UserCreateWorkspace = 10, + UserDeleteWorkspace = 11, + WorkspaceUpdated = 12, WorkspaceListUpdated = 13, WorkspaceAppsChanged = 14, - AppUpdated = 21, - AppViewsChanged = 24, - ViewUpdated = 31, - ViewDeleted = 32, - ViewRestored = 33, - UserUnauthorized = 100, - TrashUpdated = 1000, + AppUpdated = 21, + AppViewsChanged = 24, + ViewUpdated = 31, + ViewDeleted = 32, + ViewRestored = 33, + UserUnauthorized = 100, + TrashUpdated = 1000, } impl std::default::Default for WorkspaceNotification { - fn default() -> Self { WorkspaceNotification::Unknown } + fn default() -> Self { + WorkspaceNotification::Unknown + } } impl std::convert::From for i32 { - fn from(notification: WorkspaceNotification) -> Self { notification as i32 } + fn from(notification: WorkspaceNotification) -> Self { + notification as i32 + } } #[tracing::instrument(level = "debug")] diff --git a/frontend/rust-lib/flowy-core/src/services/app/controller.rs b/frontend/rust-lib/flowy-core/src/services/app/controller.rs index e533810f9d..d73a218678 100644 --- a/frontend/rust-lib/flowy-core/src/services/app/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/app/controller.rs @@ -9,8 +9,7 @@ use crate::{ services::{ app::sql::{AppTable, AppTableChangeset, AppTableSql}, server::Server, - TrashController, - TrashEvent, + TrashController, TrashEvent, }, }; use flowy_database::SqliteConnection; @@ -125,11 +124,11 @@ impl AppController { let server = self.server.clone(); tokio::spawn(async move { match server.update_app(&token, params).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => { // TODO: retry? log::error!("Update app failed: {:?}", e); - }, + } } }); Ok(()) @@ -152,13 +151,13 @@ impl AppController { send_dart_notification(&app.id, WorkspaceNotification::AppUpdated) .payload(app) .send(); - }, + } Err(e) => log::error!("Save app failed: {:?}", e), } - }, + } Err(e) => log::error!("Require db connection failed: {:?}", e), }, - Ok(None) => {}, + Ok(None) => {} Err(e) => log::error!("Read app failed: {:?}", e), } }); @@ -202,7 +201,7 @@ async fn handle_trash_event(database: Arc, trash_can: Arc Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; - }, + } TrashEvent::Delete(identifiers, ret) => { let result = || { let conn = &*db_result?; @@ -222,7 +221,7 @@ async fn handle_trash_event(database: Arc, trash_can: Arc Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; - }, + } } } diff --git a/frontend/rust-lib/flowy-core/src/services/app/sql.rs b/frontend/rust-lib/flowy-core/src/services/app/sql.rs index 204e3950f6..cc2fce439c 100644 --- a/frontend/rust-lib/flowy-core/src/services/app/sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/app/sql.rs @@ -26,7 +26,7 @@ impl AppTableSql { _ => { let changeset = AppTableChangeset::from_table(app_table); diesel_update_table!(app_table, changeset, conn) - }, + } } Ok(()) } @@ -145,7 +145,9 @@ impl std::convert::From for ColorStyleCol { impl std::convert::TryInto> for &ColorStyleCol { type Error = String; - fn try_into(self) -> Result, Self::Error> { bincode::serialize(self).map_err(|e| format!("{:?}", e)) } + fn try_into(self) -> Result, Self::Error> { + bincode::serialize(self).map_err(|e| format!("{:?}", e)) + } } impl std::convert::TryFrom<&[u8]> for ColorStyleCol { diff --git a/frontend/rust-lib/flowy-core/src/services/server/server_api.rs b/frontend/rust-lib/flowy-core/src/services/server/server_api.rs index 2b6b5eabf7..2dfb7c9deb 100644 --- a/frontend/rust-lib/flowy-core/src/services/server/server_api.rs +++ b/frontend/rust-lib/flowy-core/src/services/server/server_api.rs @@ -17,7 +17,9 @@ pub struct WorkspaceHttpServer { } impl WorkspaceHttpServer { - pub fn new(config: ClientServerConfiguration) -> WorkspaceHttpServer { Self { config } } + pub fn new(config: ClientServerConfiguration) -> WorkspaceHttpServer { + Self { config } + } } impl WorkspaceServerAPI for WorkspaceHttpServer { diff --git a/frontend/rust-lib/flowy-core/src/services/trash/controller.rs b/frontend/rust-lib/flowy-core/src/services/trash/controller.rs index ab4070574c..41ff1eedef 100644 --- a/frontend/rust-lib/flowy-core/src/services/trash/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/trash/controller.rs @@ -29,7 +29,9 @@ impl TrashController { } } - pub(crate) fn init(&self) -> Result<(), FlowyError> { Ok(()) } + pub(crate) fn init(&self) -> Result<(), FlowyError> { + Ok(()) + } #[tracing::instrument(level = "debug", skip(self), fields(putback) err)] pub async fn putback(&self, trash_id: &str) -> FlowyResult<()> { @@ -112,9 +114,9 @@ impl TrashController { let _ = self.notify.send(TrashEvent::Delete(trash_identifiers.clone(), tx)); match rx.recv().await { - None => {}, + None => {} Some(result) => match result { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("{}", e), }, } @@ -171,7 +173,9 @@ impl TrashController { Ok(()) } - pub fn subscribe(&self) -> broadcast::Receiver { self.notify.subscribe() } + pub fn subscribe(&self) -> broadcast::Receiver { + self.notify.subscribe() + } pub fn read_trash(&self, conn: &SqliteConnection) -> Result { let repeated_trash = TrashTableSql::read_all(&*conn)?; @@ -198,7 +202,7 @@ impl TrashController { // TODO: retry? let _ = tokio::spawn(async move { match server.create_trash(&token, trash_identifiers).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("Create trash failed: {:?}", e), } }); @@ -212,7 +216,7 @@ impl TrashController { let server = self.server.clone(); let _ = tokio::spawn(async move { match server.delete_trash(&token, trash_identifiers).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("Delete trash failed: {:?}", e), } }); @@ -239,13 +243,13 @@ impl TrashController { match result { Ok(repeated_trash) => { notify_trash_changed(repeated_trash); - }, + } Err(e) => log::error!("Save trash failed: {:?}", e), } - }, + } Err(e) => log::error!("Require db connection failed: {:?}", e), } - }, + } Err(e) => log::error!("Read trash failed: {:?}", e), } }); @@ -295,7 +299,7 @@ impl TrashEvent { } else { Some(TrashEvent::Putback(identifiers, sender)) } - }, + } TrashEvent::Delete(mut identifiers, sender) => { identifiers.items.retain(|item| item.ty == s); if identifiers.items.is_empty() { @@ -303,7 +307,7 @@ impl TrashEvent { } else { Some(TrashEvent::Delete(identifiers, sender)) } - }, + } TrashEvent::NewTrash(mut identifiers, sender) => { identifiers.items.retain(|item| item.ty == s); if identifiers.items.is_empty() { @@ -311,7 +315,7 @@ impl TrashEvent { } else { Some(TrashEvent::NewTrash(identifiers, sender)) } - }, + } } } } diff --git a/frontend/rust-lib/flowy-core/src/services/trash/sql.rs b/frontend/rust-lib/flowy-core/src/services/trash/sql.rs index 092cbe4ff4..5caedb486e 100644 --- a/frontend/rust-lib/flowy-core/src/services/trash/sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/trash/sql.rs @@ -20,7 +20,7 @@ impl TrashTableSql { _ => { let changeset = TrashTableChangeset::from(trash_table); diesel_update_table!(trash_table, changeset, conn) - }, + } } } @@ -109,8 +109,8 @@ impl std::convert::From for TrashTableChangeset { #[sql_type = "Integer"] pub(crate) enum SqlTrashType { Unknown = 0, - View = 1, - App = 2, + View = 1, + App = 2, } impl std::convert::From for SqlTrashType { diff --git a/frontend/rust-lib/flowy-core/src/services/view/controller.rs b/frontend/rust-lib/flowy-core/src/services/view/controller.rs index 57854cc10f..edb158611a 100644 --- a/frontend/rust-lib/flowy-core/src/services/view/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/view/controller.rs @@ -18,8 +18,7 @@ use crate::{ services::{ server::Server, view::sql::{ViewTable, ViewTableChangeset, ViewTableSql}, - TrashController, - TrashEvent, + TrashController, TrashEvent, }, }; use flowy_core_data_model::entities::share::{ExportData, ExportParams}; @@ -84,7 +83,7 @@ impl ViewController { conn.immediate_transaction::<_, FlowyError, _>(|| { let belong_to_id = view.belong_to_id.clone(); let _ = self.save_view(view, conn)?; - let _ = notify_views_changed(&belong_to_id, trash_can, &conn)?; + let _ = notify_views_changed(&belong_to_id, trash_can, conn)?; Ok(()) })?; @@ -227,11 +226,13 @@ impl ViewController { let conn = self.database.db_connection()?; let view_table = ViewTableSql::read_view(&view_id, &*conn)?; Ok(Some(view_table.into())) - }, + } } } - pub(crate) fn set_latest_view(&self, view: &View) { KV::set_str(LATEST_VIEW_ID, view.id.clone()); } + pub(crate) fn set_latest_view(&self, view: &View) { + KV::set_str(LATEST_VIEW_ID, view.id.clone()); + } } impl ViewController { @@ -248,11 +249,11 @@ impl ViewController { let server = self.server.clone(); tokio::spawn(async move { match server.update_view(&token, params).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => { // TODO: retry? log::error!("Update view failed: {:?}", e); - }, + } } }); Ok(()) @@ -275,13 +276,13 @@ impl ViewController { send_dart_notification(&view.id, WorkspaceNotification::ViewUpdated) .payload(view.clone()) .send(); - }, + } Err(e) => log::error!("Save view failed: {:?}", e), } - }, + } Err(e) => log::error!("Require db connection failed: {:?}", e), }, - Ok(None) => {}, + Ok(None) => {} Err(e) => log::error!("Read view failed: {:?}", e), } }); @@ -331,7 +332,7 @@ async fn handle_trash_event( Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; - }, + } TrashEvent::Putback(identifiers, ret) => { let result = || { let conn = &*db_result?; @@ -343,7 +344,7 @@ async fn handle_trash_event( Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; - }, + } TrashEvent::Delete(identifiers, ret) => { let result = || { let conn = &*db_result?; @@ -365,7 +366,7 @@ async fn handle_trash_event( Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; - }, + } } } @@ -394,7 +395,7 @@ fn notify_views_changed( ) -> FlowyResult<()> { let repeated_view = read_belonging_views_on_local(belong_to_id, trash_controller.clone(), conn)?; tracing::Span::current().record("view_count", &format!("{}", repeated_view.len()).as_str()); - send_dart_notification(&belong_to_id, WorkspaceNotification::AppViewsChanged) + send_dart_notification(belong_to_id, WorkspaceNotification::AppViewsChanged) .payload(repeated_view) .send(); Ok(()) diff --git a/frontend/rust-lib/flowy-core/src/services/view/event_handler.rs b/frontend/rust-lib/flowy-core/src/services/view/event_handler.rs index 1357754941..997e7ffd0f 100644 --- a/frontend/rust-lib/flowy-core/src/services/view/event_handler.rs +++ b/frontend/rust-lib/flowy-core/src/services/view/event_handler.rs @@ -2,14 +2,8 @@ use crate::{ entities::{ trash::Trash, view::{ - CreateViewParams, - CreateViewRequest, - QueryViewRequest, - RepeatedViewId, - UpdateViewParams, - UpdateViewRequest, - View, - ViewId, + CreateViewParams, CreateViewRequest, QueryViewRequest, RepeatedViewId, UpdateViewParams, UpdateViewRequest, + View, ViewId, }, }, errors::FlowyError, diff --git a/frontend/rust-lib/flowy-core/src/services/view/sql.rs b/frontend/rust-lib/flowy-core/src/services/view/sql.rs index b33c6fbb18..08f9cfef9e 100644 --- a/frontend/rust-lib/flowy-core/src/services/view/sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/view/sql.rs @@ -23,7 +23,7 @@ impl ViewTableSql { _ => { let changeset = ViewTableChangeset::from_table(view_table); diesel_update_table!(view_table, changeset, conn) - }, + } } Ok(()) } @@ -219,7 +219,9 @@ pub enum ViewTableType { } impl std::default::Default for ViewTableType { - fn default() -> Self { ViewTableType::Docs } + fn default() -> Self { + ViewTableType::Docs + } } impl std::convert::From for ViewTableType { @@ -229,13 +231,15 @@ impl std::convert::From for ViewTableType { o => { log::error!("Unsupported view type {}, fallback to ViewType::Docs", o); ViewTableType::Docs - }, + } } } } impl ViewTableType { - pub fn value(&self) -> i32 { *self as i32 } + pub fn value(&self) -> i32 { + *self as i32 + } } impl_sql_integer_expression!(ViewTableType); diff --git a/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs b/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs index c56f256856..cc6c992791 100644 --- a/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs @@ -35,7 +35,9 @@ impl WorkspaceController { } } - pub(crate) fn init(&self) -> Result<(), FlowyError> { Ok(()) } + pub(crate) fn init(&self) -> Result<(), FlowyError> { + Ok(()) + } pub(crate) async fn create_workspace_from_params( &self, @@ -124,7 +126,7 @@ impl WorkspaceController { set_current_workspace(&workspace.id); Ok(workspace) } else { - return Err(FlowyError::workspace_id().context("Opened workspace id should not be empty")); + Err(FlowyError::workspace_id().context("Opened workspace id should not be empty")) } } @@ -191,11 +193,11 @@ impl WorkspaceController { let (token, server) = (self.user.token()?, self.server.clone()); tokio::spawn(async move { match server.update_workspace(&token, params).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => { // TODO: retry? log::error!("Update workspace failed: {:?}", e); - }, + } } }); Ok(()) @@ -209,11 +211,11 @@ impl WorkspaceController { let (token, server) = (self.user.token()?, self.server.clone()); tokio::spawn(async move { match server.delete_workspace(&token, params).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => { // TODO: retry? log::error!("Delete workspace failed: {:?}", e); - }, + } } }); Ok(()) @@ -222,14 +224,16 @@ impl WorkspaceController { const CURRENT_WORKSPACE_ID: &str = "current_workspace_id"; -fn set_current_workspace(workspace_id: &str) { KV::set_str(CURRENT_WORKSPACE_ID, workspace_id.to_owned()); } +fn set_current_workspace(workspace_id: &str) { + KV::set_str(CURRENT_WORKSPACE_ID, workspace_id.to_owned()); +} pub fn get_current_workspace() -> Result { match KV::get_str(CURRENT_WORKSPACE_ID) { None => { Err(FlowyError::record_not_found() .context("Current workspace not found or should call open workspace first")) - }, + } Some(workspace_id) => Ok(workspace_id), } } diff --git a/frontend/rust-lib/flowy-core/src/services/workspace/sql.rs b/frontend/rust-lib/flowy-core/src/services/workspace/sql.rs index 6c0cf294ab..283c398e50 100644 --- a/frontend/rust-lib/flowy-core/src/services/workspace/sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/workspace/sql.rs @@ -19,7 +19,7 @@ impl WorkspaceTableSql { _ => { let changeset = WorkspaceTableChangeset::from_table(table); diesel_update_table!(workspace_table, changeset, conn); - }, + } } Ok(()) } diff --git a/frontend/rust-lib/flowy-database/src/kv/kv.rs b/frontend/rust-lib/flowy-database/src/kv/kv.rs index 7dcb5b86c4..71c3f1bf1d 100644 --- a/frontend/rust-lib/flowy-database/src/kv/kv.rs +++ b/frontend/rust-lib/flowy-database/src/kv/kv.rs @@ -57,7 +57,7 @@ impl KV { match KV_HOLDER.write() { Ok(mut guard) => { guard.cache.remove(key); - }, + } Err(e) => log::error!("Require write lock failed: {:?}", e), }; @@ -94,7 +94,7 @@ fn read_cache(key: &str) -> Option { Err(e) => { log::error!("Require read lock failed: {:?}", e); None - }, + } } } @@ -102,7 +102,7 @@ fn update_cache(value: KeyValue) { match KV_HOLDER.write() { Ok(mut guard) => { guard.cache.insert(value.key.clone(), value); - }, + } Err(e) => log::error!("Require write lock failed: {:?}", e), }; } @@ -132,10 +132,10 @@ macro_rules! impl_set_func { let mut item = KeyValue::new(key); item.$set_method = Some(value); match KV::set(item) { - Ok(_) => {}, + Ok(_) => {} Err(e) => { log::error!("{:?}", e) - }, + } }; } } @@ -168,12 +168,12 @@ fn get_connection() -> Result { .get_connection() .map_err(|e| format!("KVStore error: {:?}", e))?; Ok(conn) - }, + } Err(e) => { let msg = format!("KVStore get connection failed: {:?}", e); log::error!("{:?}", msg); Err(msg) - }, + } } } diff --git a/frontend/rust-lib/flowy-database/src/macros.rs b/frontend/rust-lib/flowy-database/src/macros.rs index 404a605512..9ef9740fee 100644 --- a/frontend/rust-lib/flowy-database/src/macros.rs +++ b/frontend/rust-lib/flowy-database/src/macros.rs @@ -125,7 +125,7 @@ macro_rules! impl_sql_binary_expression { e ); panic!(); - }, + } } } } diff --git a/frontend/rust-lib/flowy-document/src/controller.rs b/frontend/rust-lib/flowy-document/src/controller.rs index 1ff83d0d16..b108ac55f7 100644 --- a/frontend/rust-lib/flowy-document/src/controller.rs +++ b/frontend/rust-lib/flowy-document/src/controller.rs @@ -3,9 +3,7 @@ use crate::{ core::{ edit::ClientDocumentEditor, revision::{DocumentRevisionCache, DocumentRevisionManager, RevisionServer}, - DocumentWSReceivers, - DocumentWebSocket, - WSStateReceiver, + DocumentWSReceivers, DocumentWebSocket, WSStateReceiver, }, errors::FlowyError, server::Server, @@ -101,8 +99,8 @@ impl DocumentController { match self.open_cache.get(doc_id) { None => { let db_pool = self.user.db_pool()?; - self.make_editor(&doc_id, db_pool).await - }, + self.make_editor(doc_id, db_pool).await + } Some(editor) => Ok(editor), } } @@ -123,7 +121,7 @@ impl DocumentController { }); let doc_editor = ClientDocumentEditor::new(doc_id, user, rev_manager, self.ws_sender.clone(), server).await?; self.ws_receivers.add(doc_id, doc_editor.ws_handler()); - self.open_cache.insert(&doc_id, &doc_editor); + self.open_cache.insert(doc_id, &doc_editor); Ok(doc_editor) } @@ -162,7 +160,9 @@ pub struct OpenDocCache { } impl OpenDocCache { - fn new() -> Self { Self { inner: DashMap::new() } } + fn new() -> Self { + Self { inner: DashMap::new() } + } pub(crate) fn insert(&self, doc_id: &str, doc: &Arc) { if self.inner.contains_key(doc_id) { @@ -171,10 +171,12 @@ impl OpenDocCache { self.inner.insert(doc_id.to_string(), doc.clone()); } - pub(crate) fn contains(&self, doc_id: &str) -> bool { self.inner.get(doc_id).is_some() } + pub(crate) fn contains(&self, doc_id: &str) -> bool { + self.inner.get(doc_id).is_some() + } pub(crate) fn get(&self, doc_id: &str) -> Option> { - if !self.contains(&doc_id) { + if !self.contains(doc_id) { return None; } let opened_doc = self.inner.get(doc_id).unwrap(); diff --git a/frontend/rust-lib/flowy-document/src/core/edit/editor.rs b/frontend/rust-lib/flowy-document/src/core/edit/editor.rs index aaa8f52d6a..e6af2b9913 100644 --- a/frontend/rust-lib/flowy-document/src/core/edit/editor.rs +++ b/frontend/rust-lib/flowy-document/src/core/edit/editor.rs @@ -151,9 +151,13 @@ impl ClientDocumentEditor { } #[tracing::instrument(level = "debug", skip(self))] - pub fn stop(&self) { self.ws_manager.stop(); } + pub fn stop(&self) { + self.ws_manager.stop(); + } - pub(crate) fn ws_handler(&self) -> Arc { self.ws_manager.receiver() } + pub(crate) fn ws_handler(&self) -> Arc { + self.ws_manager.receiver() + } } fn spawn_edit_queue( @@ -185,5 +189,7 @@ impl ClientDocumentEditor { Ok(delta) } - pub fn rev_manager(&self) -> Arc { self.rev_manager.clone() } + pub fn rev_manager(&self) -> Arc { + self.rev_manager.clone() + } } diff --git a/frontend/rust-lib/flowy-document/src/core/edit/queue.rs b/frontend/rust-lib/flowy-document/src/core/edit/queue.rs index 6873ff0766..dc33943040 100644 --- a/frontend/rust-lib/flowy-document/src/core/edit/queue.rs +++ b/frontend/rust-lib/flowy-document/src/core/edit/queue.rs @@ -51,7 +51,7 @@ impl EditorCommandQueue { stream .for_each(|command| async { match self.handle_command(command).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::debug!("[EditCommandQueue]: {}", e), } }) @@ -68,7 +68,7 @@ impl EditorCommandQueue { drop(document); let _ = self.save_local_delta(delta, md5).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::ComposeRemoteDelta { revisions, client_delta, @@ -96,7 +96,7 @@ impl EditorCommandQueue { ); let _ = self.rev_manager.add_remote_revision(&client_revision).await?; let _ = ret.send(Ok(server_revision)); - }, + } EditorCommand::OverrideDelta { revisions, delta, ret } => { let mut document = self.document.write().await; let _ = document.set_delta(delta); @@ -107,7 +107,7 @@ impl EditorCommandQueue { assert_eq!(repeated_revision.last().unwrap().md5, md5); let _ = self.rev_manager.reset_document(repeated_revision).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::TransformRevision { revisions, ret } => { let f = || async { let new_delta = make_delta_from_revisions(revisions)?; @@ -130,21 +130,21 @@ impl EditorCommandQueue { }) }; let _ = ret.send(f().await); - }, + } EditorCommand::Insert { index, data, ret } => { let mut write_guard = self.document.write().await; let delta = write_guard.insert(index, data)?; let md5 = write_guard.md5(); let _ = self.save_local_delta(delta, md5).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::Delete { interval, ret } => { let mut write_guard = self.document.write().await; let delta = write_guard.delete(interval)?; let md5 = write_guard.md5(); let _ = self.save_local_delta(delta, md5).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::Format { interval, attribute, @@ -155,42 +155,42 @@ impl EditorCommandQueue { let md5 = write_guard.md5(); let _ = self.save_local_delta(delta, md5).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::Replace { interval, data, ret } => { let mut write_guard = self.document.write().await; let delta = write_guard.replace(interval, data)?; let md5 = write_guard.md5(); let _ = self.save_local_delta(delta, md5).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::CanUndo { ret } => { let _ = ret.send(self.document.read().await.can_undo()); - }, + } EditorCommand::CanRedo { ret } => { let _ = ret.send(self.document.read().await.can_redo()); - }, + } EditorCommand::Undo { ret } => { let mut write_guard = self.document.write().await; let UndoResult { delta } = write_guard.undo()?; let md5 = write_guard.md5(); let _ = self.save_local_delta(delta, md5).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::Redo { ret } => { let mut write_guard = self.document.write().await; let UndoResult { delta } = write_guard.redo()?; let md5 = write_guard.md5(); let _ = self.save_local_delta(delta, md5).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::ReadDoc { ret } => { let data = self.document.read().await.to_json(); let _ = ret.send(Ok(data)); - }, + } EditorCommand::ReadDocDelta { ret } => { let delta = self.document.read().await.delta().clone(); let _ = ret.send(Ok(delta)); - }, + } } Ok(()) } @@ -215,20 +215,20 @@ fn make_client_and_server_revision( md5: DocumentMD5, ) -> (Revision, Option) { let client_revision = Revision::new( - &doc_id, + doc_id, base_rev_id, rev_id, client_delta.to_bytes(), - &user_id, + user_id, md5.clone(), ); match server_delta { None => (client_revision, None), Some(server_delta) => { - let server_revision = Revision::new(&doc_id, base_rev_id, rev_id, server_delta.to_bytes(), &user_id, md5); + let server_revision = Revision::new(doc_id, base_rev_id, rev_id, server_delta.to_bytes(), user_id, md5); (client_revision, Some(server_revision)) - }, + } } } diff --git a/frontend/rust-lib/flowy-document/src/core/revision/cache.rs b/frontend/rust-lib/flowy-document/src/core/revision/cache.rs index db3647ee73..4cf35eb3a5 100644 --- a/frontend/rust-lib/flowy-document/src/core/revision/cache.rs +++ b/frontend/rust-lib/flowy-document/src/core/revision/cache.rs @@ -59,7 +59,9 @@ impl DocumentRevisionCache { Ok(record) } - pub async fn ack(&self, rev_id: i64) { self.memory_cache.ack(&rev_id).await; } + pub async fn ack(&self, rev_id: i64) { + self.memory_cache.ack(&rev_id).await; + } pub async fn get(&self, rev_id: i64) -> Option { match self.memory_cache.get(&rev_id).await { @@ -69,11 +71,11 @@ impl DocumentRevisionCache { assert_eq!(records.len(), 1); } records.pop() - }, + } Err(e) => { tracing::error!("{}", e); None - }, + } }, Some(revision) => Some(revision), } @@ -141,7 +143,7 @@ impl RevisionMemoryCacheDelegate for Arc { "checkpoint_result", &format!("{} records were saved", records.len()).as_str(), ); - let _ = self.write_revision_records(records, &conn)?; + let _ = self.write_revision_records(records, conn)?; } Ok(()) } @@ -153,7 +155,7 @@ impl RevisionMemoryCacheDelegate for Arc { state: RevisionTableState::Ack, }; match self.update_revision_record(vec![changeset]) { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("{}", e), } } @@ -167,5 +169,7 @@ pub struct RevisionRecord { } impl RevisionRecord { - pub fn ack(&mut self) { self.state = RevisionState::Ack; } + pub fn ack(&mut self) { + self.state = RevisionState::Ack; + } } diff --git a/frontend/rust-lib/flowy-document/src/core/revision/disk/sql_impl.rs b/frontend/rust-lib/flowy-document/src/core/revision/disk/sql_impl.rs index 189ec8ff2f..1a453ad9a2 100644 --- a/frontend/rust-lib/flowy-document/src/core/revision/disk/sql_impl.rs +++ b/frontend/rust-lib/flowy-document/src/core/revision/disk/sql_impl.rs @@ -196,11 +196,13 @@ pub(crate) struct RevisionTable { #[sql_type = "Integer"] pub enum RevisionTableState { Local = 0, - Ack = 1, + Ack = 1, } impl std::default::Default for RevisionTableState { - fn default() -> Self { RevisionTableState::Local } + fn default() -> Self { + RevisionTableState::Local + } } impl std::convert::From for RevisionTableState { @@ -211,13 +213,15 @@ impl std::convert::From for RevisionTableState { o => { log::error!("Unsupported rev state {}, fallback to RevState::Local", o); RevisionTableState::Local - }, + } } } } impl RevisionTableState { - pub fn value(&self) -> i32 { *self as i32 } + pub fn value(&self) -> i32 { + *self as i32 + } } impl_sql_integer_expression!(RevisionTableState); @@ -246,7 +250,7 @@ pub(crate) fn mk_revision_record_from_table(user_id: &str, table: RevisionTable) table.base_rev_id, table.rev_id, Bytes::from(table.data), - &user_id, + user_id, md5, ); RevisionRecord { @@ -260,12 +264,14 @@ pub(crate) fn mk_revision_record_from_table(user_id: &str, table: RevisionTable) #[repr(i32)] #[sql_type = "Integer"] pub enum RevTableType { - Local = 0, + Local = 0, Remote = 1, } impl std::default::Default for RevTableType { - fn default() -> Self { RevTableType::Local } + fn default() -> Self { + RevTableType::Local + } } impl std::convert::From for RevTableType { @@ -276,12 +282,14 @@ impl std::convert::From for RevTableType { o => { log::error!("Unsupported rev type {}, fallback to RevTableType::Local", o); RevTableType::Local - }, + } } } } impl RevTableType { - pub fn value(&self) -> i32 { *self as i32 } + pub fn value(&self) -> i32 { + *self as i32 + } } impl_sql_integer_expression!(RevTableType); diff --git a/frontend/rust-lib/flowy-document/src/core/revision/manager.rs b/frontend/rust-lib/flowy-document/src/core/revision/manager.rs index 798f717bd8..588926fd7a 100644 --- a/frontend/rust-lib/flowy-document/src/core/revision/manager.rs +++ b/frontend/rust-lib/flowy-document/src/core/revision/manager.rs @@ -97,9 +97,13 @@ impl DocumentRevisionManager { Ok(()) } - pub fn rev_id(&self) -> i64 { self.rev_id_counter.value() } + pub fn rev_id(&self) -> i64 { + self.rev_id_counter.value() + } - pub fn set_rev_id(&self, rev_id: i64) { self.rev_id_counter.set(rev_id); } + pub fn set_rev_id(&self, rev_id: i64) { + self.rev_id_counter.set(rev_id); + } pub fn next_rev_id_pair(&self) -> (i64, i64) { let cur = self.rev_id_counter.value(); @@ -127,7 +131,9 @@ impl DocumentRevisionManager { }) } - pub async fn latest_revision(&self) -> Revision { self.cache.latest_revision().await } + pub async fn latest_revision(&self) -> Revision { + self.cache.latest_revision().await + } pub async fn get_revision(&self, rev_id: i64) -> Option { self.cache.get(rev_id).await.map(|record| record.revision) @@ -150,7 +156,9 @@ impl std::default::Default for RevisionSyncSequence { } impl RevisionSyncSequence { - fn new() -> Self { RevisionSyncSequence::default() } + fn new() -> Self { + RevisionSyncSequence::default() + } async fn add_revision(&self, record: RevisionRecord) -> Result<(), OTError> { // The last revision's rev_id must be greater than the new one. @@ -189,7 +197,9 @@ impl RevisionSyncSequence { } } - async fn next_sync_rev_id(&self) -> Option { self.local_revs.read().await.front().copied() } + async fn next_sync_rev_id(&self) -> Option { + self.local_revs.read().await.front().copied() + } } struct RevisionLoader { @@ -223,7 +233,7 @@ impl RevisionLoader { .filter(|record| future::ready(record.state == RevisionState::Local)) .for_each(|record| async move { match self.cache.add(record.revision, record.state, false).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("{}", e), } }) @@ -268,12 +278,18 @@ fn correct_delta(delta: &mut RichTextDelta) { #[cfg(feature = "flowy_unit_test")] impl RevisionSyncSequence { #[allow(dead_code)] - pub fn revs_map(&self) -> Arc> { self.revs_map.clone() } + pub fn revs_map(&self) -> Arc> { + self.revs_map.clone() + } #[allow(dead_code)] - pub fn pending_revs(&self) -> Arc>> { self.local_revs.clone() } + pub fn pending_revs(&self) -> Arc>> { + self.local_revs.clone() + } } #[cfg(feature = "flowy_unit_test")] impl DocumentRevisionManager { - pub fn revision_cache(&self) -> Arc { self.cache.clone() } + pub fn revision_cache(&self) -> Arc { + self.cache.clone() + } } diff --git a/frontend/rust-lib/flowy-document/src/core/revision/memory.rs b/frontend/rust-lib/flowy-document/src/core/revision/memory.rs index 4f8dc37f09..b4b35b3402 100644 --- a/frontend/rust-lib/flowy-document/src/core/revision/memory.rs +++ b/frontend/rust-lib/flowy-document/src/core/revision/memory.rs @@ -29,7 +29,9 @@ impl DocumentRevisionMemoryCache { } } - pub(crate) fn contains(&self, rev_id: &i64) -> bool { self.revs_map.contains_key(rev_id) } + pub(crate) fn contains(&self, rev_id: &i64) -> bool { + self.revs_map.contains_key(rev_id) + } pub(crate) async fn add<'a>(&'a self, record: Cow<'a, RevisionRecord>) { let record = match record { @@ -55,7 +57,7 @@ impl DocumentRevisionMemoryCache { pub(crate) async fn ack(&self, rev_id: &i64) { match self.revs_map.get_mut(rev_id) { - None => {}, + None => {} Some(mut record) => record.ack(), } @@ -69,7 +71,7 @@ impl DocumentRevisionMemoryCache { } pub(crate) async fn get(&self, rev_id: &i64) -> Option { - self.revs_map.get(&rev_id).map(|r| r.value().clone()) + self.revs_map.get(rev_id).map(|r| r.value().clone()) } pub(crate) async fn get_with_range(&self, range: &RevisionRange) -> Result, FlowyError> { @@ -123,10 +125,10 @@ impl DocumentRevisionMemoryCache { // https://stackoverflow.com/questions/28952411/what-is-the-idiomatic-way-to-pop-the-last-n-elements-in-a-mutable-vec let mut save_records: Vec = vec![]; revs_write_guard.iter().for_each(|rev_id| match rev_map.get(rev_id) { - None => {}, + None => {} Some(value) => { save_records.push(value.value().clone()); - }, + } }); if delegate.checkpoint_tick(save_records).is_ok() { diff --git a/frontend/rust-lib/flowy-document/src/core/web_socket/http_ws_impl.rs b/frontend/rust-lib/flowy-document/src/core/web_socket/http_ws_impl.rs index f74015b509..9af9db591d 100644 --- a/frontend/rust-lib/flowy-document/src/core/web_socket/http_ws_impl.rs +++ b/frontend/rust-lib/flowy-document/src/core/web_socket/http_ws_impl.rs @@ -15,8 +15,7 @@ use lib_ws::WSConnectState; use std::{convert::TryFrom, sync::Arc}; use tokio::{ sync::{ - broadcast, - mpsc, + broadcast, mpsc, mpsc::{UnboundedReceiver, UnboundedSender}, }, task::spawn_blocking, @@ -77,7 +76,9 @@ impl HttpWebSocketManager { tokio::spawn(stream.run()); } - pub fn scribe_state(&self) -> broadcast::Receiver { self.state.subscribe() } + pub fn scribe_state(&self) -> broadcast::Receiver { + self.state.subscribe() + } } impl DocumentWebSocketManager for Arc { @@ -87,27 +88,31 @@ impl DocumentWebSocketManager for Arc { } } - fn receiver(&self) -> Arc { self.clone() } + fn receiver(&self) -> Arc { + self.clone() + } } impl DocumentWSReceiver for HttpWebSocketManager { fn receive_ws_data(&self, doc_data: DocumentServerWSData) { match self.ws_msg_tx.send(doc_data) { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("❌ Propagate ws message failed. {}", e), } } fn connect_state_changed(&self, state: &WSConnectState) { match self.state.send(state.clone()) { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("{}", e), } } } impl std::ops::Drop for HttpWebSocketManager { - fn drop(&mut self) { tracing::debug!("{} HttpWebSocketManager was drop", self.doc_id) } + fn drop(&mut self) { + tracing::debug!("{} HttpWebSocketManager was drop", self.doc_id) + } } pub trait DocumentWSSteamConsumer: Send + Sync { @@ -168,7 +173,7 @@ impl DocumentWSStream { stream .for_each(|msg| async { match self.handle_message(msg).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[DocumentStream:{}] error: {}", self.doc_id, e), } }) @@ -185,20 +190,20 @@ impl DocumentWSStream { match ty { DocumentServerWSDataType::ServerPushRev => { let _ = self.consumer.receive_push_revision(bytes).await?; - }, + } DocumentServerWSDataType::ServerPullRev => { let range = RevisionRange::try_from(bytes)?; let _ = self.consumer.pull_revisions_in_range(range).await?; - }, + } DocumentServerWSDataType::ServerAck => { let rev_id = RevId::try_from(bytes).unwrap().value; let _ = self.consumer.receive_ack(rev_id.to_string(), ty).await; - }, + } DocumentServerWSDataType::UserConnect => { let new_user = NewDocumentUser::try_from(bytes)?; let _ = self.consumer.receive_new_user_connect(new_user).await; // Notify the user that someone has connected to this document - }, + } } Ok(()) } @@ -258,7 +263,7 @@ impl DocumentWSSink { stream .for_each(|_| async { match self.send_next_revision().await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[DocumentSink]: Send failed, {:?}", e), } }) @@ -270,12 +275,12 @@ impl DocumentWSSink { None => { tracing::trace!("Finish synchronizing revisions"); Ok(()) - }, + } Some(data) => { tracing::trace!("[DocumentSink]: send: {}:{}-{:?}", data.doc_id, data.id(), data.ty); self.ws_sender.send(data) // let _ = tokio::time::timeout(Duration::from_millis(2000), - }, + } } } } diff --git a/frontend/rust-lib/flowy-document/src/core/web_socket/local_ws_impl.rs b/frontend/rust-lib/flowy-document/src/core/web_socket/local_ws_impl.rs index e3be436cbd..9adc6528d7 100644 --- a/frontend/rust-lib/flowy-document/src/core/web_socket/local_ws_impl.rs +++ b/frontend/rust-lib/flowy-document/src/core/web_socket/local_ws_impl.rs @@ -8,7 +8,9 @@ pub(crate) struct LocalWebSocketManager {} impl DocumentWebSocketManager for Arc { fn stop(&self) {} - fn receiver(&self) -> Arc { self.clone() } + fn receiver(&self) -> Arc { + self.clone() + } } impl DocumentWSReceiver for LocalWebSocketManager { diff --git a/frontend/rust-lib/flowy-document/src/core/web_socket/ws_manager.rs b/frontend/rust-lib/flowy-document/src/core/web_socket/ws_manager.rs index 482818dd43..9d217e9222 100644 --- a/frontend/rust-lib/flowy-document/src/core/web_socket/ws_manager.rs +++ b/frontend/rust-lib/flowy-document/src/core/web_socket/ws_manager.rs @@ -1,10 +1,6 @@ use crate::core::{ web_socket::{DocumentWSSinkDataProvider, DocumentWSSteamConsumer, HttpWebSocketManager}, - DocumentRevisionManager, - DocumentWSReceiver, - DocumentWebSocket, - EditorCommand, - TransformDeltas, + DocumentRevisionManager, DocumentWSReceiver, DocumentWebSocket, EditorCommand, TransformDeltas, }; use bytes::Bytes; use flowy_collaboration::{ @@ -84,10 +80,10 @@ fn listen_document_ws_state( tokio::spawn(async move { while let Ok(state) = subscriber.recv().await { match state { - WSConnectState::Init => {}, - WSConnectState::Connecting => {}, - WSConnectState::Connected => {}, - WSConnectState::Disconnected => {}, + WSConnectState::Init => {} + WSConnectState::Connecting => {} + WSConnectState::Connected => {} + WSConnectState::Disconnected => {} } } }); @@ -196,7 +192,7 @@ pub(crate) async fn handle_remote_revision( }); let _ = rx.await.map_err(internal_error)??; Ok(None) - }, + } Some(server_prime) => { let (ret, rx) = oneshot::channel(); let _ = edit_cmd_tx.send(EditorCommand::ComposeRemoteDelta { @@ -206,7 +202,7 @@ pub(crate) async fn handle_remote_revision( ret, }); Ok(rx.await.map_err(internal_error)??) - }, + } } } @@ -233,9 +229,13 @@ impl SharedWSSinkDataProvider { } #[allow(dead_code)] - pub(crate) async fn push_front(&self, data: DocumentClientWSData) { self.shared.write().await.push_front(data); } + pub(crate) async fn push_front(&self, data: DocumentClientWSData) { + self.shared.write().await.push_front(data); + } - async fn push_back(&self, data: DocumentClientWSData) { self.shared.write().await.push_back(data); } + async fn push_back(&self, data: DocumentClientWSData) { + self.shared.write().await.push_back(data); + } async fn next(&self) -> FlowyResult> { let source_ty = self.source_ty.read().await.clone(); @@ -244,11 +244,11 @@ impl SharedWSSinkDataProvider { None => { *self.source_ty.write().await = SourceType::Revision; Ok(None) - }, + } Some(data) => { tracing::debug!("[SharedWSSinkDataProvider]: {}:{:?}", data.doc_id, data.ty); Ok(Some(data.clone())) - }, + } }, SourceType::Revision => { if !self.shared.read().await.is_empty() { @@ -260,15 +260,15 @@ impl SharedWSSinkDataProvider { Some(rev) => { let doc_id = rev.doc_id.clone(); Ok(Some(DocumentClientWSData::from_revisions(&doc_id, vec![rev]))) - }, + } None => { // let doc_id = self.rev_manager.doc_id.clone(); let latest_rev_id = self.rev_manager.rev_id(); Ok(Some(DocumentClientWSData::ping(&doc_id, latest_rev_id))) - }, + } } - }, + } } } @@ -287,22 +287,22 @@ impl SharedWSSinkDataProvider { tracing::error!("The front element's {} is not equal to the {}", expected_id, id); false } - }, + } }; if should_pop { let _ = self.shared.write().await.pop_front(); } - }, + } SourceType::Revision => { match id.parse::() { Ok(rev_id) => { let _ = self.rev_manager.ack_revision(rev_id).await?; - }, + } Err(e) => { tracing::error!("Parse rev_id from {} failed. {}", id, e); - }, + } }; - }, + } } Ok(()) diff --git a/frontend/rust-lib/flowy-document/src/notify/observable.rs b/frontend/rust-lib/flowy-document/src/notify/observable.rs index 751b58625f..a48aa06438 100644 --- a/frontend/rust-lib/flowy-document/src/notify/observable.rs +++ b/frontend/rust-lib/flowy-document/src/notify/observable.rs @@ -7,7 +7,9 @@ pub(crate) enum DocObservable { } impl std::convert::From for i32 { - fn from(o: DocObservable) -> Self { o as i32 } + fn from(o: DocObservable) -> Self { + o as i32 + } } #[allow(dead_code)] diff --git a/frontend/rust-lib/flowy-document/src/server/middleware.rs b/frontend/rust-lib/flowy-document/src/server/middleware.rs index c6cb85bb2d..ede10c0659 100644 --- a/frontend/rust-lib/flowy-document/src/server/middleware.rs +++ b/frontend/rust-lib/flowy-document/src/server/middleware.rs @@ -14,14 +14,14 @@ impl ResponseMiddleware for DocMiddleware { log::error!("document user is unauthorized"); match token { - None => {}, + None => {} Some(_token) => { // let error = // FlowyError::new(ErrorCode::UserUnauthorized, ""); // observable(token, // WorkspaceObservable::UserUnauthorized).error(error). // build() - }, + } } } } diff --git a/frontend/rust-lib/flowy-document/src/server/server_api.rs b/frontend/rust-lib/flowy-document/src/server/server_api.rs index 675cecfa08..784351594e 100644 --- a/frontend/rust-lib/flowy-document/src/server/server_api.rs +++ b/frontend/rust-lib/flowy-document/src/server/server_api.rs @@ -8,7 +8,9 @@ pub struct DocServer { } impl DocServer { - pub fn new(config: ClientServerConfiguration) -> Self { Self { config } } + pub fn new(config: ClientServerConfiguration) -> Self { + Self { config } + } } impl DocumentServerAPI for DocServer { diff --git a/frontend/rust-lib/flowy-document/src/ws_receivers.rs b/frontend/rust-lib/flowy-document/src/ws_receivers.rs index 6816b116e0..b017e8b843 100644 --- a/frontend/rust-lib/flowy-document/src/ws_receivers.rs +++ b/frontend/rust-lib/flowy-document/src/ws_receivers.rs @@ -29,7 +29,9 @@ impl std::default::Default for DocumentWSReceivers { } impl DocumentWSReceivers { - pub fn new() -> Self { DocumentWSReceivers::default() } + pub fn new() -> Self { + DocumentWSReceivers::default() + } pub(crate) fn add(&self, doc_id: &str, receiver: Arc) { if self.receivers.contains_key(doc_id) { @@ -38,23 +40,25 @@ impl DocumentWSReceivers { self.receivers.insert(doc_id.to_string(), receiver); } - pub(crate) fn remove(&self, id: &str) { self.receivers.remove(id); } + pub(crate) fn remove(&self, id: &str) { + self.receivers.remove(id); + } pub fn did_receive_data(&self, data: Bytes) { let data: DocumentServerWSData = data.try_into().unwrap(); match self.receivers.get(&data.doc_id) { None => { log::error!("Can't find any source handler for {:?}", data.doc_id); - }, + } Some(handler) => { handler.receive_ws_data(data); - }, + } } } pub fn ws_connect_state_changed(&self, state: &WSConnectState) { self.receivers.iter().for_each(|receiver| { - receiver.value().connect_state_changed(&state); + receiver.value().connect_state_changed(state); }); } } diff --git a/frontend/rust-lib/flowy-document/tests/document/edit_script.rs b/frontend/rust-lib/flowy-document/tests/document/edit_script.rs index 2fa62a26d6..083d34f522 100644 --- a/frontend/rust-lib/flowy-document/tests/document/edit_script.rs +++ b/frontend/rust-lib/flowy-document/tests/document/edit_script.rs @@ -46,20 +46,20 @@ impl EditorTest { match script { EditorScript::InsertText(s, offset) => { self.editor.insert(offset, s).await.unwrap(); - }, + } EditorScript::Delete(interval) => { self.editor.delete(interval).await.unwrap(); - }, + } EditorScript::Replace(interval, s) => { self.editor.replace(interval, s).await.unwrap(); - }, + } EditorScript::AssertRevisionState(rev_id, state) => { let record = cache.get(rev_id).await.unwrap(); assert_eq!(record.state, state); - }, + } EditorScript::AssertCurrentRevId(rev_id) => { assert_eq!(self.editor.rev_manager().rev_id(), rev_id); - }, + } EditorScript::AssertNextRevId(rev_id) => { let next_revision = rev_manager.next_sync_revision().await.unwrap(); if rev_id.is_none() { @@ -68,7 +68,7 @@ impl EditorTest { } let next_revision = next_revision.unwrap(); assert_eq!(next_revision.rev_id, rev_id.unwrap()); - }, + } EditorScript::AssertJson(expected) => { let expected_delta: RichTextDelta = serde_json::from_str(expected).unwrap(); let delta = self.editor.doc_delta().await.unwrap(); @@ -77,7 +77,7 @@ impl EditorTest { eprintln!("❌ receive: {}", delta.to_json()); } assert_eq!(expected_delta, delta); - }, + } } sleep(Duration::from_millis(SYNC_INTERVAL_IN_MILLIS)).await; } diff --git a/frontend/rust-lib/flowy-document/tests/editor/mod.rs b/frontend/rust-lib/flowy-document/tests/editor/mod.rs index e04443e9d1..46f54ae86c 100644 --- a/frontend/rust-lib/flowy-document/tests/editor/mod.rs +++ b/frontend/rust-lib/flowy-document/tests/editor/mod.rs @@ -112,31 +112,31 @@ impl TestBuilder { tracing::debug!("Insert delta: {}", delta.to_json()); self.deltas.insert(*delta_i, Some(delta)); - }, + } TestOp::Delete(delta_i, iv) => { let document = &mut self.documents[*delta_i]; let delta = document.replace(*iv, "").unwrap(); tracing::trace!("Delete delta: {}", delta.to_json()); self.deltas.insert(*delta_i, Some(delta)); - }, + } TestOp::Replace(delta_i, iv, s) => { let document = &mut self.documents[*delta_i]; let delta = document.replace(*iv, s).unwrap(); tracing::trace!("Replace delta: {}", delta.to_json()); self.deltas.insert(*delta_i, Some(delta)); - }, + } TestOp::InsertBold(delta_i, s, iv) => { let document = &mut self.documents[*delta_i]; document.insert(iv.start, s).unwrap(); document.format(*iv, RichTextAttribute::Bold(true)).unwrap(); - }, + } TestOp::Bold(delta_i, iv, enable) => { let document = &mut self.documents[*delta_i]; let attribute = RichTextAttribute::Bold(*enable); let delta = document.format(*iv, attribute).unwrap(); tracing::trace!("Bold delta: {}", delta.to_json()); self.deltas.insert(*delta_i, Some(delta)); - }, + } TestOp::Italic(delta_i, iv, enable) => { let document = &mut self.documents[*delta_i]; let attribute = match *enable { @@ -146,21 +146,21 @@ impl TestBuilder { let delta = document.format(*iv, attribute).unwrap(); tracing::trace!("Italic delta: {}", delta.to_json()); self.deltas.insert(*delta_i, Some(delta)); - }, + } TestOp::Header(delta_i, iv, level) => { let document = &mut self.documents[*delta_i]; let attribute = RichTextAttribute::Header(*level); let delta = document.format(*iv, attribute).unwrap(); tracing::trace!("Header delta: {}", delta.to_json()); self.deltas.insert(*delta_i, Some(delta)); - }, + } TestOp::Link(delta_i, iv, link) => { let document = &mut self.documents[*delta_i]; let attribute = RichTextAttribute::Link(link.to_owned()); let delta = document.format(*iv, attribute).unwrap(); tracing::trace!("Link delta: {}", delta.to_json()); self.deltas.insert(*delta_i, Some(delta)); - }, + } TestOp::Bullet(delta_i, iv, enable) => { let document = &mut self.documents[*delta_i]; let attribute = RichTextAttribute::Bullet(*enable); @@ -168,7 +168,7 @@ impl TestBuilder { tracing::debug!("Bullet delta: {}", delta.to_json()); self.deltas.insert(*delta_i, Some(delta)); - }, + } TestOp::Transform(delta_a_i, delta_b_i) => { let (a_prime, b_prime) = self.documents[*delta_a_i] .delta() @@ -181,7 +181,7 @@ impl TestBuilder { self.documents[*delta_a_i].set_delta(data_left); self.documents[*delta_b_i].set_delta(data_right); - }, + } TestOp::TransformPrime(a_doc_index, b_doc_index) => { let (prime_left, prime_right) = self.documents[*a_doc_index] .delta() @@ -190,7 +190,7 @@ impl TestBuilder { self.primes.insert(*a_doc_index, Some(prime_left)); self.primes.insert(*b_doc_index, Some(prime_right)); - }, + } TestOp::Invert(delta_a_i, delta_b_i) => { let delta_a = &self.documents[*delta_a_i].delta(); let delta_b = &self.documents[*delta_b_i].delta(); @@ -212,19 +212,19 @@ impl TestBuilder { assert_eq!(delta_a, &&new_delta_after_undo); self.documents[*delta_a_i].set_delta(new_delta_after_undo); - }, + } TestOp::Undo(delta_i) => { self.documents[*delta_i].undo().unwrap(); - }, + } TestOp::Redo(delta_i) => { self.documents[*delta_i].redo().unwrap(); - }, + } TestOp::Wait(mills_sec) => { std::thread::sleep(Duration::from_millis(*mills_sec as u64)); - }, + } TestOp::AssertStr(delta_i, expected) => { assert_eq!(&self.documents[*delta_i].to_plain_string(), expected); - }, + } TestOp::AssertDocJson(delta_i, expected) => { let delta_json = self.documents[*delta_i].to_json(); @@ -236,7 +236,7 @@ impl TestBuilder { log::error!("❌ receive: {}", delta_json); } assert_eq!(target_delta, expected_delta); - }, + } TestOp::AssertPrimeJson(doc_i, expected) => { let prime_json = self.primes[*doc_i].as_ref().unwrap().to_json(); @@ -248,11 +248,11 @@ impl TestBuilder { log::error!("❌ receive prime: {}", prime_json); } assert_eq!(target_prime, expected_prime); - }, + } TestOp::DocComposeDelta(doc_index, delta_i) => { let delta = self.deltas.get(*delta_i).unwrap().as_ref().unwrap(); self.documents[*doc_index].compose_delta(delta.clone()).unwrap(); - }, + } TestOp::DocComposePrime(doc_index, prime_i) => { let delta = self .primes @@ -262,7 +262,7 @@ impl TestBuilder { .unwrap(); let new_delta = self.documents[*doc_index].delta().compose(delta).unwrap(); self.documents[*doc_index].set_delta(new_delta); - }, + } } } @@ -279,12 +279,16 @@ impl TestBuilder { pub struct Rng(StdRng); impl Default for Rng { - fn default() -> Self { Rng(StdRng::from_rng(thread_rng()).unwrap()) } + fn default() -> Self { + Rng(StdRng::from_rng(thread_rng()).unwrap()) + } } impl Rng { #[allow(dead_code)] - pub fn from_seed(seed: [u8; 32]) -> Self { Rng(StdRng::from_seed(seed)) } + pub fn from_seed(seed: [u8; 32]) -> Self { + Rng(StdRng::from_seed(seed)) + } pub fn gen_string(&mut self, len: usize) -> String { (0..len) @@ -311,13 +315,13 @@ impl Rng { match self.0.gen_range(0.0, 1.0) { f if f < 0.2 => { delta.insert(&self.gen_string(i), RichTextAttributes::default()); - }, + } f if f < 0.4 => { delta.delete(i); - }, + } _ => { delta.retain(i, RichTextAttributes::default()); - }, + } } } if self.0.gen_range(0.0, 1.0) < 0.3 { diff --git a/frontend/rust-lib/flowy-error/src/errors.rs b/frontend/rust-lib/flowy-error/src/errors.rs index c8459b9d4e..a0c2cc129f 100644 --- a/frontend/rust-lib/flowy-error/src/errors.rs +++ b/frontend/rust-lib/flowy-error/src/errors.rs @@ -18,7 +18,9 @@ pub struct FlowyError { macro_rules! static_flowy_error { ($name:ident, $code:expr) => { #[allow(non_snake_case, missing_docs)] - pub fn $name() -> FlowyError { $code.into() } + pub fn $name() -> FlowyError { + $code.into() + } }; } @@ -81,7 +83,9 @@ where } impl fmt::Display for FlowyError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", &self.code, &self.msg) } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}: {}", &self.code, &self.msg) + } } impl lib_dispatch::Error for FlowyError { @@ -92,9 +96,13 @@ impl lib_dispatch::Error for FlowyError { } impl std::convert::From for FlowyError { - fn from(error: std::io::Error) -> Self { FlowyError::internal().context(error) } + fn from(error: std::io::Error) -> Self { + FlowyError::internal().context(error) + } } impl std::convert::From for FlowyError { - fn from(e: protobuf::ProtobufError) -> Self { FlowyError::internal().context(e) } + fn from(e: protobuf::ProtobufError) -> Self { + FlowyError::internal().context(e) + } } diff --git a/frontend/rust-lib/flowy-error/src/ext/backend.rs b/frontend/rust-lib/flowy-error/src/ext/backend.rs index 68cc9dca45..3c901ef2a6 100644 --- a/frontend/rust-lib/flowy-error/src/ext/backend.rs +++ b/frontend/rust-lib/flowy-error/src/ext/backend.rs @@ -16,7 +16,7 @@ fn server_error_to_flowy_error(code: ServerErrorCode) -> ErrorCode { ServerErrorCode::RecordNotFound => ErrorCode::RecordNotFound, ServerErrorCode::ConnectRefused | ServerErrorCode::ConnectTimeout | ServerErrorCode::ConnectClose => { ErrorCode::ConnectError - }, + } _ => ErrorCode::Internal, } } diff --git a/frontend/rust-lib/flowy-error/src/ext/collaborate.rs b/frontend/rust-lib/flowy-error/src/ext/collaborate.rs index 82246f7792..bf76be1074 100644 --- a/frontend/rust-lib/flowy-error/src/ext/collaborate.rs +++ b/frontend/rust-lib/flowy-error/src/ext/collaborate.rs @@ -1,5 +1,7 @@ use crate::FlowyError; impl std::convert::From for FlowyError { - fn from(error: flowy_collaboration::errors::CollaborateError) -> Self { FlowyError::internal().context(error) } + fn from(error: flowy_collaboration::errors::CollaborateError) -> Self { + FlowyError::internal().context(error) + } } diff --git a/frontend/rust-lib/flowy-error/src/ext/database.rs b/frontend/rust-lib/flowy-error/src/ext/database.rs index f395a0235c..064105f62b 100644 --- a/frontend/rust-lib/flowy-error/src/ext/database.rs +++ b/frontend/rust-lib/flowy-error/src/ext/database.rs @@ -1,15 +1,21 @@ use crate::FlowyError; impl std::convert::From for FlowyError { - fn from(error: flowy_database::Error) -> Self { FlowyError::internal().context(error) } + fn from(error: flowy_database::Error) -> Self { + FlowyError::internal().context(error) + } } impl std::convert::From<::r2d2::Error> for FlowyError { - fn from(error: r2d2::Error) -> Self { FlowyError::internal().context(error) } + fn from(error: r2d2::Error) -> Self { + FlowyError::internal().context(error) + } } // use diesel::result::{Error, DatabaseErrorKind}; // use lib_sqlite::ErrorKind; impl std::convert::From for FlowyError { - fn from(error: lib_sqlite::Error) -> Self { FlowyError::internal().context(error) } + fn from(error: lib_sqlite::Error) -> Self { + FlowyError::internal().context(error) + } } diff --git a/frontend/rust-lib/flowy-error/src/ext/ot.rs b/frontend/rust-lib/flowy-error/src/ext/ot.rs index bfce081953..6d349bfb9e 100644 --- a/frontend/rust-lib/flowy-error/src/ext/ot.rs +++ b/frontend/rust-lib/flowy-error/src/ext/ot.rs @@ -1,5 +1,7 @@ use crate::FlowyError; impl std::convert::From for FlowyError { - fn from(error: lib_ot::errors::OTError) -> Self { FlowyError::internal().context(error) } + fn from(error: lib_ot::errors::OTError) -> Self { + FlowyError::internal().context(error) + } } diff --git a/frontend/rust-lib/flowy-error/src/ext/serde.rs b/frontend/rust-lib/flowy-error/src/ext/serde.rs index 87c7d55178..2d25aab10d 100644 --- a/frontend/rust-lib/flowy-error/src/ext/serde.rs +++ b/frontend/rust-lib/flowy-error/src/ext/serde.rs @@ -1,5 +1,7 @@ use crate::FlowyError; impl std::convert::From for FlowyError { - fn from(error: serde_json::Error) -> Self { FlowyError::internal().context(error) } + fn from(error: serde_json::Error) -> Self { + FlowyError::internal().context(error) + } } diff --git a/frontend/rust-lib/flowy-net/src/entities/network_state.rs b/frontend/rust-lib/flowy-net/src/entities/network_state.rs index b1de3bc6ec..15a9282c88 100644 --- a/frontend/rust-lib/flowy-net/src/entities/network_state.rs +++ b/frontend/rust-lib/flowy-net/src/entities/network_state.rs @@ -3,9 +3,9 @@ use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; #[derive(ProtoBuf_Enum, Debug, Clone, Eq, PartialEq)] pub enum NetworkType { UnknownNetworkType = 0, - Wifi = 1, - Cell = 2, - Ethernet = 3, + Wifi = 1, + Cell = 2, + Ethernet = 3, } impl NetworkType { @@ -20,7 +20,9 @@ impl NetworkType { } impl std::default::Default for NetworkType { - fn default() -> Self { NetworkType::UnknownNetworkType } + fn default() -> Self { + NetworkType::UnknownNetworkType + } } #[derive(ProtoBuf, Debug, Default, Clone)] diff --git a/frontend/rust-lib/flowy-net/src/services/http_ws/http_ws_impl.rs b/frontend/rust-lib/flowy-net/src/services/http_ws/http_ws_impl.rs index 4b81047095..dcdd320b8a 100644 --- a/frontend/rust-lib/flowy-net/src/services/http_ws/http_ws_impl.rs +++ b/frontend/rust-lib/flowy-net/src/services/http_ws/http_ws_impl.rs @@ -9,7 +9,9 @@ use std::sync::Arc; use tokio::sync::broadcast::Receiver; impl FlowyRawWebSocket for Arc { - fn initialize(&self) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } + fn initialize(&self) -> FutureResult<(), FlowyError> { + FutureResult::new(async { Ok(()) }) + } fn start_connect(&self, addr: String, _user_id: String) -> FutureResult<(), FlowyError> { let cloned_ws = self.clone(); @@ -27,7 +29,9 @@ impl FlowyRawWebSocket for Arc { }) } - fn subscribe_connect_state(&self) -> Receiver { self.subscribe_state() } + fn subscribe_connect_state(&self) -> Receiver { + self.subscribe_state() + } fn reconnect(&self, count: usize) -> FutureResult<(), FlowyError> { let cloned_ws = self.clone(); diff --git a/frontend/rust-lib/flowy-net/src/services/local_ws/local_server.rs b/frontend/rust-lib/flowy-net/src/services/local_ws/local_server.rs index 8fb58f6630..cf4fdb61f6 100644 --- a/frontend/rust-lib/flowy-net/src/services/local_ws/local_server.rs +++ b/frontend/rust-lib/flowy-net/src/services/local_ws/local_server.rs @@ -7,9 +7,7 @@ use flowy_collaboration::{ }, errors::CollaborateError, protobuf::{ - DocumentClientWSData as DocumentClientWSDataPB, - RepeatedRevision as RepeatedRevisionPB, - Revision as RevisionPB, + DocumentClientWSData as DocumentClientWSDataPB, RepeatedRevision as RepeatedRevisionPB, Revision as RevisionPB, }, sync::*, util::repeated_revision_from_repeated_revision_pb, @@ -58,10 +56,10 @@ impl LocalDocumentServer { .doc_manager .handle_client_revisions(user, document_client_data) .await?; - }, + } DocumentClientWSDataType::ClientPing => { let _ = self.doc_manager.handle_client_ping(user, document_client_data).await?; - }, + } } Ok(()) } @@ -72,7 +70,9 @@ struct LocalDocServerPersistence { } impl Debug for LocalDocServerPersistence { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("LocalDocServerPersistence") } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str("LocalDocServerPersistence") + } } impl std::default::Default for LocalDocServerPersistence { @@ -93,7 +93,7 @@ impl DocumentPersistence for LocalDocServerPersistence { Some(val) => { // Ok(val.value().clone()) - }, + } } }) } @@ -130,15 +130,17 @@ struct LocalDocumentUser { } impl RevisionUser for LocalDocumentUser { - fn user_id(&self) -> String { self.user_id.clone() } + fn user_id(&self) -> String { + self.user_id.clone() + } fn receive(&self, resp: SyncResponse) { let sender = self.ws_sender.clone(); let send_fn = |sender: UnboundedSender, msg: WebSocketRawMessage| match sender.send(msg) { - Ok(_) => {}, + Ok(_) => {} Err(e) => { tracing::error!("LocalDocumentUser send message failed: {}", e); - }, + } }; tokio::spawn(async move { @@ -150,7 +152,7 @@ impl RevisionUser for LocalDocumentUser { data: bytes.to_vec(), }; send_fn(sender, msg); - }, + } SyncResponse::Push(data) => { let bytes: Bytes = data.try_into().unwrap(); let msg = WebSocketRawMessage { @@ -158,7 +160,7 @@ impl RevisionUser for LocalDocumentUser { data: bytes.to_vec(), }; send_fn(sender, msg); - }, + } SyncResponse::Ack(data) => { let bytes: Bytes = data.try_into().unwrap(); let msg = WebSocketRawMessage { @@ -166,10 +168,10 @@ impl RevisionUser for LocalDocumentUser { data: bytes.to_vec(), }; send_fn(sender, msg); - }, + } SyncResponse::NewRevision(mut _repeated_revision) => { // unimplemented!() - }, + } } }); } diff --git a/frontend/rust-lib/flowy-net/src/services/local_ws/local_ws_impl.rs b/frontend/rust-lib/flowy-net/src/services/local_ws/local_ws_impl.rs index 962418e88f..d529a7d0c9 100644 --- a/frontend/rust-lib/flowy-net/src/services/local_ws/local_ws_impl.rs +++ b/frontend/rust-lib/flowy-net/src/services/local_ws/local_ws_impl.rs @@ -70,10 +70,10 @@ impl LocalWebSocket { Ok::<(), FlowyError>(()) }; match fut().await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("[LocalWebSocket] error: {:?}", e), } - }, + } Err(e) => tracing::error!("[LocalWebSocket] error: {}", e), } } @@ -102,18 +102,26 @@ impl FlowyRawWebSocket for LocalWebSocket { FutureResult::new(async { Ok(()) }) } - fn stop_connect(&self) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } + fn stop_connect(&self) -> FutureResult<(), FlowyError> { + FutureResult::new(async { Ok(()) }) + } - fn subscribe_connect_state(&self) -> Receiver { self.state_sender.subscribe() } + fn subscribe_connect_state(&self) -> Receiver { + self.state_sender.subscribe() + } - fn reconnect(&self, _count: usize) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } + fn reconnect(&self, _count: usize) -> FutureResult<(), FlowyError> { + FutureResult::new(async { Ok(()) }) + } fn add_receiver(&self, receiver: Arc) -> Result<(), FlowyError> { self.receivers.insert(receiver.source(), receiver); Ok(()) } - fn sender(&self) -> Result, FlowyError> { Ok(Arc::new(self.ws_sender.clone())) } + fn sender(&self) -> Result, FlowyError> { + Ok(Arc::new(self.ws_sender.clone())) + } } #[derive(Clone)] @@ -136,5 +144,7 @@ impl FlowyWSSender for LocalWSSender { impl std::ops::Deref for LocalWSSender { type Target = broadcast::Sender; - fn deref(&self) -> &Self::Target { &self.0 } + fn deref(&self) -> &Self::Target { + &self.0 + } } diff --git a/frontend/rust-lib/flowy-net/src/services/ws_conn.rs b/frontend/rust-lib/flowy-net/src/services/ws_conn.rs index fdec3cf334..3c86400166 100644 --- a/frontend/rust-lib/flowy-net/src/services/ws_conn.rs +++ b/frontend/rust-lib/flowy-net/src/services/ws_conn.rs @@ -42,7 +42,7 @@ impl FlowyWebSocketConnect { pub async fn init(&self) { match self.inner.initialize().await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("FlowyWebSocketConnect init error: {:?}", e), } } @@ -54,7 +54,9 @@ impl FlowyWebSocketConnect { Ok(()) } - pub async fn stop(&self) { let _ = self.inner.stop_connect().await; } + pub async fn stop(&self) { + let _ = self.inner.stop_connect().await; + } pub fn update_network_type(&self, new_type: &NetworkType) { tracing::debug!("Network new state: {:?}", new_type); @@ -67,11 +69,11 @@ impl FlowyWebSocketConnect { (false, true) => { let ws_controller = self.inner.clone(); tokio::spawn(async move { retry_connect(ws_controller, 100).await }); - }, + } (true, false) => { // - }, - _ => {}, + } + _ => {} } *self.connect_type.write() = new_type.clone(); @@ -82,14 +84,18 @@ impl FlowyWebSocketConnect { self.inner.subscribe_connect_state() } - pub fn subscribe_network_ty(&self) -> broadcast::Receiver { self.status_notifier.subscribe() } + pub fn subscribe_network_ty(&self) -> broadcast::Receiver { + self.status_notifier.subscribe() + } pub fn add_ws_message_receiver(&self, receiver: Arc) -> Result<(), FlowyError> { let _ = self.inner.add_receiver(receiver)?; Ok(()) } - pub fn ws_sender(&self) -> Result, FlowyError> { self.inner.sender() } + pub fn ws_sender(&self) -> Result, FlowyError> { + self.inner.sender() + } } #[tracing::instrument(level = "debug", skip(ws_conn))] @@ -103,16 +109,16 @@ pub fn listen_on_websocket(ws_conn: Arc) { Ok(state) => { tracing::info!("Websocket state changed: {}", state); match state { - WSConnectState::Init => {}, - WSConnectState::Connected => {}, - WSConnectState::Connecting => {}, + WSConnectState::Init => {} + WSConnectState::Connected => {} + WSConnectState::Connecting => {} WSConnectState::Disconnected => retry_connect(ws.clone(), 100).await, } - }, + } Err(e) => { tracing::error!("Websocket state notify error: {:?}", e); break; - }, + } } } }); @@ -123,9 +129,9 @@ pub fn listen_on_websocket(ws_conn: Arc) { async fn retry_connect(ws: Arc, count: usize) { match ws.reconnect(count).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => { tracing::error!("websocket connect failed: {:?}", e); - }, + } } } diff --git a/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs b/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs index b42e273c6f..e20bed25d1 100644 --- a/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs +++ b/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs @@ -53,11 +53,17 @@ impl DocumentUser for DocumentUserImpl { Ok(doc_dir) } - fn user_id(&self) -> Result { self.user.user_id() } + fn user_id(&self) -> Result { + self.user.user_id() + } - fn token(&self) -> Result { self.user.token() } + fn token(&self) -> Result { + self.user.token() + } - fn db_pool(&self) -> Result, FlowyError> { self.user.db_pool() } + fn db_pool(&self) -> Result, FlowyError> { + self.user.db_pool() + } } struct DocumentWebSocketAdapter { @@ -76,12 +82,18 @@ impl DocumentWebSocket for DocumentWebSocketAdapter { Ok(()) } - fn subscribe_state_changed(&self) -> WSStateReceiver { self.ws_conn.subscribe_websocket_state() } + fn subscribe_state_changed(&self) -> WSStateReceiver { + self.ws_conn.subscribe_websocket_state() + } } struct WSMessageReceiverAdaptor(Arc); impl WSMessageReceiver for WSMessageReceiverAdaptor { - fn source(&self) -> WSModule { WSModule::Doc } - fn receive_message(&self, msg: WebSocketRawMessage) { self.0.did_receive_data(Bytes::from(msg.data)); } + fn source(&self) -> WSModule { + WSModule::Doc + } + fn receive_message(&self, msg: WebSocketRawMessage) { + self.0.did_receive_data(Bytes::from(msg.data)); + } } diff --git a/frontend/rust-lib/flowy-sdk/src/lib.rs b/frontend/rust-lib/flowy-sdk/src/lib.rs index 4bae25397f..529c7a22c3 100644 --- a/frontend/rust-lib/flowy-sdk/src/lib.rs +++ b/frontend/rust-lib/flowy-sdk/src/lib.rs @@ -122,7 +122,9 @@ impl FlowySDK { } } - pub fn dispatcher(&self) -> Arc { self.dispatcher.clone() } + pub fn dispatcher(&self) -> Arc { + self.dispatcher.clone() + } } fn _init( @@ -161,26 +163,26 @@ async fn _listen_user_status( UserStatus::Login { token, user_id } => { let _ = core.user_did_sign_in(&token).await?; let _ = ws_conn.start(token, user_id).await?; - }, + } UserStatus::Logout { .. } => { core.user_did_logout().await; let _ = ws_conn.stop().await; - }, + } UserStatus::Expired { .. } => { core.user_session_expired().await; let _ = ws_conn.stop().await; - }, + } UserStatus::SignUp { profile, ret } => { let _ = core.user_did_sign_up(&profile.token).await?; let _ = ws_conn.start(profile.token.clone(), profile.id.clone()).await?; let _ = ret.send(()); - }, + } } Ok::<(), FlowyError>(()) }; match result().await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("{}", e), } } @@ -194,7 +196,7 @@ async fn _listen_network_status(mut subscribe: broadcast::Receiver, fn init_kv(root: &str) { match flowy_database::kv::KV::init(root) { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("Init kv store failedL: {}", e), } } diff --git a/frontend/rust-lib/flowy-sdk/src/module.rs b/frontend/rust-lib/flowy-sdk/src/module.rs index 7f2c9c5691..0131bbe64d 100644 --- a/frontend/rust-lib/flowy-sdk/src/module.rs +++ b/frontend/rust-lib/flowy-sdk/src/module.rs @@ -15,8 +15,14 @@ pub fn mk_modules( vec![user_module, core_module, network_module] } -fn mk_user_module(user_session: Arc) -> Module { flowy_user::module::create(user_session) } +fn mk_user_module(user_session: Arc) -> Module { + flowy_user::module::create(user_session) +} -fn mk_core_module(core: Arc) -> Module { flowy_core::module::create(core) } +fn mk_core_module(core: Arc) -> Module { + flowy_core::module::create(core) +} -fn mk_network_module(ws_conn: Arc) -> Module { flowy_net::module::create(ws_conn) } +fn mk_network_module(ws_conn: Arc) -> Module { + flowy_net::module::create(ws_conn) +} diff --git a/frontend/rust-lib/flowy-test/src/event_builder.rs b/frontend/rust-lib/flowy-test/src/event_builder.rs index ca17453417..6129250c59 100644 --- a/frontend/rust-lib/flowy-test/src/event_builder.rs +++ b/frontend/rust-lib/flowy-test/src/event_builder.rs @@ -11,8 +11,12 @@ use std::{ pub type CoreModuleEventBuilder = EventBuilder; impl CoreModuleEventBuilder { - pub fn new(sdk: FlowySDKTest) -> Self { EventBuilder::test(TestContext::new(sdk)) } - pub fn user_profile(&self) -> &Option { &self.user_profile } + pub fn new(sdk: FlowySDKTest) -> Self { + EventBuilder::test(TestContext::new(sdk)) + } + pub fn user_profile(&self) -> &Option { + &self.user_profile + } } pub type UserModuleEventBuilder = CoreModuleEventBuilder; @@ -44,10 +48,10 @@ where Ok(bytes) => { let module_request = self.get_request(); self.context.request = Some(module_request.payload(bytes)) - }, + } Err(e) => { log::error!("Set payload failed: {:?}", e); - }, + } } self } @@ -83,7 +87,7 @@ where Ok(Ok(data)) => data, Ok(Err(e)) => { panic!("parse failed: {:?}", e) - }, + } Err(e) => panic!("Internal error: {:?}", e), } } @@ -104,7 +108,9 @@ where self } - fn dispatch(&self) -> Arc { self.context.sdk.dispatcher() } + fn dispatch(&self) -> Arc { + self.context.sdk.dispatcher() + } fn get_response(&self) -> EventResponse { self.context @@ -114,7 +120,9 @@ where .clone() } - fn get_request(&mut self) -> ModuleRequest { self.context.request.take().expect("must call event first") } + fn get_request(&mut self) -> ModuleRequest { + self.context.request.take().expect("must call event first") + } } #[derive(Clone)] diff --git a/frontend/rust-lib/flowy-test/src/helper.rs b/frontend/rust-lib/flowy-test/src/helper.rs index 30f69e7f5a..8d6bb66e33 100644 --- a/frontend/rust-lib/flowy-test/src/helper.rs +++ b/frontend/rust-lib/flowy-test/src/helper.rs @@ -72,10 +72,10 @@ pub struct ViewTest { impl ViewTest { pub async fn new(sdk: &FlowySDKTest) -> Self { - let workspace = create_workspace(&sdk, "Workspace", "").await; - open_workspace(&sdk, &workspace.id).await; - let app = create_app(&sdk, "App", "AppFlowy GitHub Project", &workspace.id).await; - let view = create_view(&sdk, &app.id).await; + let workspace = create_workspace(sdk, "Workspace", "").await; + open_workspace(sdk, &workspace.id).await; + let app = create_app(sdk, "App", "AppFlowy GitHub Project", &workspace.id).await; + let view = create_view(sdk, &app.id).await; Self { sdk: sdk.clone(), workspace, @@ -291,11 +291,17 @@ pub fn root_dir() -> String { root_dir } -pub fn random_email() -> String { format!("{}@appflowy.io", uuid_string()) } +pub fn random_email() -> String { + format!("{}@appflowy.io", uuid_string()) +} -pub fn login_email() -> String { "annie2@appflowy.io".to_string() } +pub fn login_email() -> String { + "annie2@appflowy.io".to_string() +} -pub fn login_password() -> String { "HelloWorld!123".to_string() } +pub fn login_password() -> String { + "HelloWorld!123".to_string() +} pub struct SignUpContext { pub user_profile: UserProfile, @@ -365,4 +371,6 @@ fn sign_in(dispatch: Arc) -> UserProfile { } #[allow(dead_code)] -fn logout(dispatch: Arc) { let _ = EventDispatcher::sync_send(dispatch, ModuleRequest::new(SignOut)); } +fn logout(dispatch: Arc) { + let _ = EventDispatcher::sync_send(dispatch, ModuleRequest::new(SignOut)); +} diff --git a/frontend/rust-lib/flowy-test/src/lib.rs b/frontend/rust-lib/flowy-test/src/lib.rs index 2ba8a20828..91b09134d5 100644 --- a/frontend/rust-lib/flowy-test/src/lib.rs +++ b/frontend/rust-lib/flowy-test/src/lib.rs @@ -20,7 +20,9 @@ pub struct FlowySDKTest { impl std::ops::Deref for FlowySDKTest { type Target = FlowySDK; - fn deref(&self) -> &Self::Target { &self.inner } + fn deref(&self) -> &Self::Target { + &self.inner + } } impl std::default::Default for FlowySDKTest { diff --git a/frontend/rust-lib/flowy-user/src/event.rs b/frontend/rust-lib/flowy-user/src/event.rs index 0a2357fb26..617fd252eb 100644 --- a/frontend/rust-lib/flowy-user/src/event.rs +++ b/frontend/rust-lib/flowy-user/src/event.rs @@ -5,23 +5,23 @@ use strum_macros::Display; #[event_err = "FlowyError"] pub enum UserEvent { #[event()] - InitUser = 0, + InitUser = 0, #[event(input = "SignInRequest", output = "UserProfile")] - SignIn = 1, + SignIn = 1, #[event(input = "SignUpRequest", output = "UserProfile")] - SignUp = 2, + SignUp = 2, #[event(passthrough)] - SignOut = 3, + SignOut = 3, #[event(input = "UpdateUserRequest")] - UpdateUser = 4, + UpdateUser = 4, #[event(output = "UserProfile")] GetUserProfile = 5, #[event(output = "UserProfile")] - CheckUser = 6, + CheckUser = 6, } diff --git a/frontend/rust-lib/flowy-user/src/notify/observable.rs b/frontend/rust-lib/flowy-user/src/notify/observable.rs index e2d69b9672..f9d4c32f8b 100644 --- a/frontend/rust-lib/flowy-user/src/notify/observable.rs +++ b/frontend/rust-lib/flowy-user/src/notify/observable.rs @@ -4,19 +4,23 @@ const OBSERVABLE_CATEGORY: &str = "User"; #[derive(ProtoBuf_Enum, Debug)] pub(crate) enum UserNotification { - Unknown = 0, - UserAuthChanged = 1, + Unknown = 0, + UserAuthChanged = 1, UserProfileUpdated = 2, - UserUnauthorized = 3, + UserUnauthorized = 3, UserWsConnectStateChanged = 4, } impl std::default::Default for UserNotification { - fn default() -> Self { UserNotification::Unknown } + fn default() -> Self { + UserNotification::Unknown + } } impl std::convert::From for i32 { - fn from(notification: UserNotification) -> Self { notification as i32 } + fn from(notification: UserNotification) -> Self { + notification as i32 + } } pub(crate) fn dart_notify(id: &str, ty: UserNotification) -> DartNotifyBuilder { diff --git a/frontend/rust-lib/flowy-user/src/services/server/server_api.rs b/frontend/rust-lib/flowy-user/src/services/server/server_api.rs index 5161849b37..14f7358b0c 100644 --- a/frontend/rust-lib/flowy-user/src/services/server/server_api.rs +++ b/frontend/rust-lib/flowy-user/src/services/server/server_api.rs @@ -10,7 +10,9 @@ pub struct UserHttpServer { config: ClientServerConfiguration, } impl UserHttpServer { - pub fn new(config: ClientServerConfiguration) -> Self { Self { config } } + pub fn new(config: ClientServerConfiguration) -> Self { + Self { config } + } } impl UserServerAPI for UserHttpServer { @@ -57,7 +59,9 @@ impl UserServerAPI for UserHttpServer { }) } - fn ws_addr(&self) -> String { self.config.ws_addr() } + fn ws_addr(&self) -> String { + self.config.ws_addr() + } } // use crate::notify::*; diff --git a/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs b/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs index bace6bc616..0742de1799 100644 --- a/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs +++ b/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs @@ -35,7 +35,9 @@ impl UserServerAPI for UserServerMock { }) } - fn sign_out(&self, _token: &str) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } + fn sign_out(&self, _token: &str) -> FutureResult<(), FlowyError> { + FutureResult::new(async { Ok(()) }) + } fn update_user(&self, _token: &str, _params: UpdateUserParams) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) @@ -45,5 +47,7 @@ impl UserServerAPI for UserServerMock { FutureResult::new(async { Ok(UserProfile::default()) }) } - fn ws_addr(&self) -> String { "ws://localhost:8000/ws/".to_owned() } + fn ws_addr(&self) -> String { + "ws://localhost:8000/ws/".to_owned() + } } diff --git a/frontend/rust-lib/flowy-user/src/services/user/database.rs b/frontend/rust-lib/flowy-user/src/services/user/database.rs index aa4c603349..e4dc1d7a80 100644 --- a/frontend/rust-lib/flowy-user/src/services/user/database.rs +++ b/frontend/rust-lib/flowy-user/src/services/user/database.rs @@ -37,7 +37,7 @@ impl UserDB { Some(mut write_guard) => { write_guard.insert(user_id.to_owned(), db); Ok(()) - }, + } } } @@ -48,7 +48,7 @@ impl UserDB { set_user_db_init(false, user_id); write_guard.remove(user_id); Ok(()) - }, + } } } @@ -67,7 +67,7 @@ impl UserDB { let _ = self.open_user_db(user_id)?; set_user_db_init(true, user_id); } - }, + } } match DB_MAP.try_read_for(Duration::from_millis(300)) { @@ -75,7 +75,7 @@ impl UserDB { Some(read_guard) => match read_guard.get(user_id) { None => { Err(FlowyError::internal().context("Get connection failed. The database is not initialization")) - }, + } Some(database) => Ok(database.get_pool()), }, } diff --git a/frontend/rust-lib/flowy-user/src/services/user/notifier.rs b/frontend/rust-lib/flowy-user/src/services/user/notifier.rs index 67b3ac78a9..8ffbba5b97 100644 --- a/frontend/rust-lib/flowy-user/src/services/user/notifier.rs +++ b/frontend/rust-lib/flowy-user/src/services/user/notifier.rs @@ -14,7 +14,9 @@ impl std::default::Default for UserNotifier { } impl UserNotifier { - pub(crate) fn new() -> Self { UserNotifier::default() } + pub(crate) fn new() -> Self { + UserNotifier::default() + } pub(crate) fn notify_login(&self, token: &str, user_id: &str) { let _ = self.user_status_notifier.send(UserStatus::Login { @@ -36,5 +38,7 @@ impl UserNotifier { }); } - pub fn subscribe_user_status(&self) -> broadcast::Receiver { self.user_status_notifier.subscribe() } + pub fn subscribe_user_status(&self) -> broadcast::Receiver { + self.user_status_notifier.subscribe() + } } diff --git a/frontend/rust-lib/flowy-user/src/services/user/user_session.rs b/frontend/rust-lib/flowy-user/src/services/user/user_session.rs index 5613d4cf92..a0b33265ce 100644 --- a/frontend/rust-lib/flowy-user/src/services/user/user_session.rs +++ b/frontend/rust-lib/flowy-user/src/services/user/user_session.rs @@ -8,9 +8,7 @@ use flowy_database::{ kv::KV, query_dsl::*, schema::{user_table, user_table::dsl}, - DBConnection, - ExpressionMethods, - UserDatabaseConnection, + DBConnection, ExpressionMethods, UserDatabaseConnection, }; use flowy_user_data_model::entities::{SignInResponse, SignUpResponse}; use lib_sqlite::ConnectionPool; @@ -143,7 +141,9 @@ impl UserSession { Ok(()) } - pub async fn init_user(&self) -> Result<(), FlowyError> { Ok(()) } + pub async fn init_user(&self) -> Result<(), FlowyError> { + Ok(()) + } pub async fn check_user(&self) -> Result { let (user_id, token) = self.get_session()?.into_part(); @@ -171,11 +171,17 @@ impl UserSession { Ok(format!("{}/{}", self.config.root_dir, session.user_id)) } - pub fn user_id(&self) -> Result { Ok(self.get_session()?.user_id) } + pub fn user_id(&self) -> Result { + Ok(self.get_session()?.user_id) + } - pub fn user_name(&self) -> Result { Ok(self.get_session()?.name) } + pub fn user_name(&self) -> Result { + Ok(self.get_session()?.name) + } - pub fn token(&self) -> Result { Ok(self.get_session()?.token) } + pub fn token(&self) -> Result { + Ok(self.get_session()?.token) + } } impl UserSession { @@ -188,12 +194,12 @@ impl UserSession { dart_notify(&token, UserNotification::UserProfileUpdated) .payload(profile) .send(); - }, + } Err(e) => { dart_notify(&token, UserNotification::UserProfileUpdated) .error(e) .send(); - }, + } } }); Ok(()) @@ -204,11 +210,11 @@ impl UserSession { let token = token.to_owned(); let _ = tokio::spawn(async move { match server.update_user(&token, params).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => { // TODO: retry? log::error!("update user profile failed: {:?}", e); - }, + } } }) .await; @@ -220,7 +226,7 @@ impl UserSession { let token = token.to_owned(); let _ = tokio::spawn(async move { match server.sign_out(&token).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("Sign out failed: {:?}", e), } }) @@ -250,11 +256,11 @@ impl UserSession { let mut session = { (*self.session.read()).clone() }; if session.is_none() { match KV::get_str(&self.config.session_cache_key) { - None => {}, + None => {} Some(s) => { session = Some(Session::from(s)); let _ = self.set_session(session.clone())?; - }, + } } } @@ -284,7 +290,9 @@ pub async fn update_user( } impl UserDatabaseConnection for UserSession { - fn get_connection(&self) -> Result { self.db_connection().map_err(|e| format!("{:?}", e)) } + fn get_connection(&self) -> Result { + self.db_connection().map_err(|e| format!("{:?}", e)) + } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -319,7 +327,9 @@ impl std::convert::From for Session { } impl Session { - pub fn into_part(self) -> (String, String) { (self.user_id, self.token) } + pub fn into_part(self) -> (String, String) { + (self.user_id, self.token) + } } impl std::convert::From for Session { @@ -329,7 +339,7 @@ impl std::convert::From for Session { Err(e) => { log::error!("Deserialize string to Session failed: {:?}", e); Session::default() - }, + } } } } @@ -340,7 +350,7 @@ impl std::convert::From for String { Err(e) => { log::error!("Serialize session to string failed: {:?}", e); "".to_string() - }, + } } } } diff --git a/frontend/rust-lib/flowy-user/src/sql_tables/user.rs b/frontend/rust-lib/flowy-user/src/sql_tables/user.rs index a804076301..6d0c9d738b 100644 --- a/frontend/rust-lib/flowy-user/src/sql_tables/user.rs +++ b/frontend/rust-lib/flowy-user/src/sql_tables/user.rs @@ -30,11 +30,15 @@ impl UserTable { } impl std::convert::From for UserTable { - fn from(resp: SignUpResponse) -> Self { UserTable::new(resp.user_id, resp.name, resp.email, resp.token) } + fn from(resp: SignUpResponse) -> Self { + UserTable::new(resp.user_id, resp.name, resp.email, resp.token) + } } impl std::convert::From for UserTable { - fn from(resp: SignInResponse) -> Self { UserTable::new(resp.user_id, resp.name, resp.email, resp.token) } + fn from(resp: SignInResponse) -> Self { + UserTable::new(resp.user_id, resp.name, resp.email, resp.token) + } } impl std::convert::From for UserProfile { diff --git a/frontend/rust-lib/flowy-user/tests/event/helper.rs b/frontend/rust-lib/flowy-user/tests/event/helper.rs index ed1fe6ede8..e43b5b48a0 100644 --- a/frontend/rust-lib/flowy-user/tests/event/helper.rs +++ b/frontend/rust-lib/flowy-user/tests/event/helper.rs @@ -37,4 +37,6 @@ pub(crate) fn invalid_password_test_case() -> Vec { .collect::>() } -pub(crate) fn valid_name() -> String { "AppFlowy".to_string() } +pub(crate) fn valid_name() -> String { + "AppFlowy".to_string() +} diff --git a/frontend/rust-lib/lib-dispatch/src/byte_trait.rs b/frontend/rust-lib/lib-dispatch/src/byte_trait.rs index cb1c9d1d6d..217dd12f9a 100644 --- a/frontend/rust-lib/lib-dispatch/src/byte_trait.rs +++ b/frontend/rust-lib/lib-dispatch/src/byte_trait.rs @@ -20,7 +20,7 @@ where // Err(format!("{:?}", e)) Err(InternalError::ProtobufError(format!("{:?}", e)).into()) - }, + } } } } diff --git a/frontend/rust-lib/lib-dispatch/src/data.rs b/frontend/rust-lib/lib-dispatch/src/data.rs index 76b773f148..e331fe071e 100644 --- a/frontend/rust-lib/lib-dispatch/src/data.rs +++ b/frontend/rust-lib/lib-dispatch/src/data.rs @@ -11,17 +11,23 @@ use std::ops; pub struct Data(pub T); impl Data { - pub fn into_inner(self) -> T { self.0 } + pub fn into_inner(self) -> T { + self.0 + } } impl ops::Deref for Data { type Target = T; - fn deref(&self) -> &T { &self.0 } + fn deref(&self) -> &T { + &self.0 + } } impl ops::DerefMut for Data { - fn deref_mut(&mut self) -> &mut T { &mut self.0 } + fn deref_mut(&mut self) -> &mut T { + &mut self.0 + } } impl FromRequest for Data @@ -60,7 +66,9 @@ where T: FromBytes, { type Error = DispatchError; - fn try_from(payload: &Payload) -> Result, Self::Error> { parse_payload(payload) } + fn try_from(payload: &Payload) -> Result, Self::Error> { + parse_payload(payload) + } } impl std::convert::TryFrom for Data @@ -68,7 +76,9 @@ where T: FromBytes, { type Error = DispatchError; - fn try_from(payload: Payload) -> Result, Self::Error> { parse_payload(&payload) } + fn try_from(payload: Payload) -> Result, Self::Error> { + parse_payload(&payload) + } } fn parse_payload(payload: &Payload) -> Result, DispatchError> @@ -80,7 +90,7 @@ where Payload::Bytes(bytes) => { let data = T::parse_from_bytes(bytes.clone())?; Ok(Data(data)) - }, + } } } @@ -98,5 +108,7 @@ where } impl ToBytes for Data { - fn into_bytes(self) -> Result { Ok(Bytes::from(self.0)) } + fn into_bytes(self) -> Result { + Ok(Bytes::from(self.0)) + } } diff --git a/frontend/rust-lib/lib-dispatch/src/dispatcher.rs b/frontend/rust-lib/lib-dispatch/src/dispatcher.rs index aa178c6d87..b1af7b60fd 100644 --- a/frontend/rust-lib/lib-dispatch/src/dispatcher.rs +++ b/frontend/rust-lib/lib-dispatch/src/dispatcher.rs @@ -144,12 +144,12 @@ impl Service for DispatchService { let fut = module.new_service(()); let service_fut = fut.await?.call(request); service_fut.await - }, + } None => { let msg = format!("Can not find the event handler. {:?}", request); log::error!("{}", msg); Err(InternalError::HandleNotFound(msg).into()) - }, + } } }; diff --git a/frontend/rust-lib/lib-dispatch/src/errors/errors.rs b/frontend/rust-lib/lib-dispatch/src/errors/errors.rs index 5cf674a281..dbee088802 100644 --- a/frontend/rust-lib/lib-dispatch/src/errors/errors.rs +++ b/frontend/rust-lib/lib-dispatch/src/errors/errors.rs @@ -17,7 +17,9 @@ pub trait Error: fmt::Debug + DynClone + Send + Sync { dyn_clone::clone_trait_object!(Error); impl From for DispatchError { - fn from(err: T) -> DispatchError { DispatchError { inner: Box::new(err) } } + fn from(err: T) -> DispatchError { + DispatchError { inner: Box::new(err) } + } } #[derive(Clone)] @@ -26,34 +28,50 @@ pub struct DispatchError { } impl DispatchError { - pub fn inner_error(&self) -> &dyn Error { self.inner.as_ref() } + pub fn inner_error(&self) -> &dyn Error { + self.inner.as_ref() + } } impl fmt::Display for DispatchError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &self.inner) } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", &self.inner) + } } impl fmt::Debug for DispatchError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &self.inner) } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", &self.inner) + } } impl std::error::Error for DispatchError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + None + } - fn cause(&self) -> Option<&dyn std::error::Error> { None } + fn cause(&self) -> Option<&dyn std::error::Error> { + None + } } impl From> for DispatchError { - fn from(err: SendError) -> Self { InternalError::Other(format!("{}", err)).into() } + fn from(err: SendError) -> Self { + InternalError::Other(format!("{}", err)).into() + } } impl From for DispatchError { - fn from(s: String) -> Self { InternalError::Other(s).into() } + fn from(s: String) -> Self { + InternalError::Other(s).into() + } } #[cfg(feature = "use_protobuf")] impl From for DispatchError { - fn from(e: protobuf::ProtobufError) -> Self { InternalError::ProtobufError(format!("{:?}", e)).into() } + fn from(e: protobuf::ProtobufError) -> Self { + InternalError::ProtobufError(format!("{:?}", e)).into() + } } impl FromBytes for DispatchError { @@ -64,7 +82,9 @@ impl FromBytes for DispatchError { } impl From for EventResponse { - fn from(err: DispatchError) -> Self { err.inner_error().as_response() } + fn from(err: DispatchError) -> Self { + err.inner_error().as_response() + } } impl Serialize for DispatchError { @@ -109,5 +129,7 @@ impl Error for InternalError { } impl std::convert::From for InternalError { - fn from(e: JoinError) -> Self { InternalError::JoinError(format!("{}", e)) } + fn from(e: JoinError) -> Self { + InternalError::JoinError(format!("{}", e)) + } } diff --git a/frontend/rust-lib/lib-dispatch/src/module/container.rs b/frontend/rust-lib/lib-dispatch/src/module/container.rs index 7366ecedb7..89a71a15b2 100644 --- a/frontend/rust-lib/lib-dispatch/src/module/container.rs +++ b/frontend/rust-lib/lib-dispatch/src/module/container.rs @@ -55,7 +55,9 @@ impl ModuleDataMap { self.map.contains_key(&TypeId::of::()) } - pub fn extend(&mut self, other: ModuleDataMap) { self.map.extend(other.map); } + pub fn extend(&mut self, other: ModuleDataMap) { + self.map.extend(other.map); + } } fn downcast_owned(boxed: Box) -> Option { diff --git a/frontend/rust-lib/lib-dispatch/src/module/data.rs b/frontend/rust-lib/lib-dispatch/src/module/data.rs index e70863b4a3..44acd305a7 100644 --- a/frontend/rust-lib/lib-dispatch/src/module/data.rs +++ b/frontend/rust-lib/lib-dispatch/src/module/data.rs @@ -11,9 +11,13 @@ impl Unit where T: Send + Sync, { - pub fn new(data: T) -> Self { Unit(Arc::new(data)) } + pub fn new(data: T) -> Self { + Unit(Arc::new(data)) + } - pub fn get_ref(&self) -> &T { self.0.as_ref() } + pub fn get_ref(&self) -> &T { + self.0.as_ref() + } } impl Deref for Unit @@ -22,21 +26,27 @@ where { type Target = Arc; - fn deref(&self) -> &Arc { &self.0 } + fn deref(&self) -> &Arc { + &self.0 + } } impl Clone for Unit where T: ?Sized + Send + Sync, { - fn clone(&self) -> Unit { Unit(self.0.clone()) } + fn clone(&self) -> Unit { + Unit(self.0.clone()) + } } impl From> for Unit where T: ?Sized + Send + Sync, { - fn from(arc: Arc) -> Self { Unit(arc) } + fn from(arc: Arc) -> Self { + Unit(arc) + } } impl FromRequest for Unit diff --git a/frontend/rust-lib/lib-dispatch/src/module/module.rs b/frontend/rust-lib/lib-dispatch/src/module/module.rs index 573d53a47a..bc3ba28dbc 100644 --- a/frontend/rust-lib/lib-dispatch/src/module/module.rs +++ b/frontend/rust-lib/lib-dispatch/src/module/module.rs @@ -17,14 +17,7 @@ use crate::{ request::{payload::Payload, EventRequest, FromRequest}, response::{EventResponse, Responder}, service::{ - factory, - BoxService, - BoxServiceFactory, - Handler, - HandlerService, - Service, - ServiceFactory, - ServiceRequest, + factory, BoxService, BoxServiceFactory, Handler, HandlerService, Service, ServiceFactory, ServiceRequest, ServiceResponse, }, }; @@ -48,7 +41,9 @@ pub(crate) fn as_module_map(modules: Vec) -> ModuleMap { pub struct Event(String); impl std::convert::From for Event { - fn from(t: T) -> Self { Event(format!("{}", t)) } + fn from(t: T) -> Self { + Event(format!("{}", t)) + } } pub type EventServiceFactory = BoxServiceFactory<(), ServiceRequest, ServiceResponse, DispatchError>; @@ -70,7 +65,9 @@ impl std::default::Default for Module { } impl Module { - pub fn new() -> Self { Module::default() } + pub fn new() -> Self { + Module::default() + } pub fn name(mut self, s: &str) -> Self { self.name = s.to_owned(); @@ -103,7 +100,9 @@ impl Module { self } - pub fn events(&self) -> Vec { self.service_map.keys().cloned().collect::>() } + pub fn events(&self) -> Vec { + self.service_map.keys().cloned().collect::>() + } } #[derive(Debug, Clone)] @@ -135,7 +134,9 @@ impl ModuleRequest { } impl std::fmt::Display for ModuleRequest { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}:{:?}", self.id, self.event) } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}:{:?}", self.id, self.event) + } } impl ServiceFactory for Module { @@ -185,11 +186,11 @@ impl Service for ModuleService { }), }; Box::pin(async move { Ok(fut.await.unwrap_or_else(|e| e.into())) }) - }, + } None => { let msg = format!("Can not find service factory for event: {:?}", request.event); Box::pin(async { Err(InternalError::ServiceNotFound(msg).into()) }) - }, + } } } } diff --git a/frontend/rust-lib/lib-dispatch/src/request/payload.rs b/frontend/rust-lib/lib-dispatch/src/request/payload.rs index 5637a82996..a82e2c072a 100644 --- a/frontend/rust-lib/lib-dispatch/src/request/payload.rs +++ b/frontend/rust-lib/lib-dispatch/src/request/payload.rs @@ -11,11 +11,15 @@ pub enum Payload { } impl std::fmt::Debug for Payload { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { format_payload_print(self, f) } + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + format_payload_print(self, f) + } } impl std::fmt::Display for Payload { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { format_payload_print(self, f) } + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + format_payload_print(self, f) + } } fn format_payload_print(payload: &Payload, f: &mut Formatter<'_>) -> fmt::Result { @@ -26,24 +30,36 @@ fn format_payload_print(payload: &Payload, f: &mut Formatter<'_>) -> fmt::Result } impl std::convert::From for Payload { - fn from(s: String) -> Self { Payload::Bytes(Bytes::from(s)) } + fn from(s: String) -> Self { + Payload::Bytes(Bytes::from(s)) + } } impl std::convert::From<&'_ String> for Payload { - fn from(s: &String) -> Self { Payload::Bytes(Bytes::from(s.to_owned())) } + fn from(s: &String) -> Self { + Payload::Bytes(Bytes::from(s.to_owned())) + } } impl std::convert::From for Payload { - fn from(bytes: Bytes) -> Self { Payload::Bytes(bytes) } + fn from(bytes: Bytes) -> Self { + Payload::Bytes(bytes) + } } impl std::convert::From<()> for Payload { - fn from(_: ()) -> Self { Payload::None } + fn from(_: ()) -> Self { + Payload::None + } } impl std::convert::From> for Payload { - fn from(bytes: Vec) -> Self { Payload::Bytes(Bytes::from(bytes)) } + fn from(bytes: Vec) -> Self { + Payload::Bytes(Bytes::from(bytes)) + } } impl std::convert::From<&str> for Payload { - fn from(s: &str) -> Self { s.to_string().into() } + fn from(s: &str) -> Self { + s.to_string().into() + } } diff --git a/frontend/rust-lib/lib-dispatch/src/request/request.rs b/frontend/rust-lib/lib-dispatch/src/request/request.rs index 182d3be205..3004915366 100644 --- a/frontend/rust-lib/lib-dispatch/src/request/request.rs +++ b/frontend/rust-lib/lib-dispatch/src/request/request.rs @@ -60,7 +60,9 @@ impl FromRequest for () { type Error = DispatchError; type Future = Ready>; - fn from_request(_req: &EventRequest, _payload: &mut Payload) -> Self::Future { ready(Ok(())) } + fn from_request(_req: &EventRequest, _payload: &mut Payload) -> Self::Future { + ready(Ok(())) + } } #[doc(hidden)] diff --git a/frontend/rust-lib/lib-dispatch/src/response/builder.rs b/frontend/rust-lib/lib-dispatch/src/response/builder.rs index 85b0bc2116..a9d4ea6802 100644 --- a/frontend/rust-lib/lib-dispatch/src/response/builder.rs +++ b/frontend/rust-lib/lib-dispatch/src/response/builder.rs @@ -6,7 +6,9 @@ use crate::{ macro_rules! static_response { ($name:ident, $status:expr) => { #[allow(non_snake_case, missing_docs)] - pub fn $name() -> ResponseBuilder { ResponseBuilder::new($status) } + pub fn $name() -> ResponseBuilder { + ResponseBuilder::new($status) + } }; } diff --git a/frontend/rust-lib/lib-dispatch/src/response/responder.rs b/frontend/rust-lib/lib-dispatch/src/response/responder.rs index efa7b097d2..35e38d0a8e 100644 --- a/frontend/rust-lib/lib-dispatch/src/response/responder.rs +++ b/frontend/rust-lib/lib-dispatch/src/response/responder.rs @@ -13,7 +13,9 @@ pub trait Responder { macro_rules! impl_responder { ($res: ty) => { impl Responder for $res { - fn respond_to(self, _: &EventRequest) -> EventResponse { ResponseBuilder::Ok().data(self).build() } + fn respond_to(self, _: &EventRequest) -> EventResponse { + ResponseBuilder::Ok().data(self).build() + } } }; } diff --git a/frontend/rust-lib/lib-dispatch/src/response/response.rs b/frontend/rust-lib/lib-dispatch/src/response/response.rs index 6892ced68f..812de68e84 100644 --- a/frontend/rust-lib/lib-dispatch/src/response/response.rs +++ b/frontend/rust-lib/lib-dispatch/src/response/response.rs @@ -10,8 +10,8 @@ use std::{convert::TryFrom, fmt, fmt::Formatter}; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub enum StatusCode { - Ok = 0, - Err = 1, + Ok = 0, + Err = 1, Internal = 2, } @@ -40,11 +40,11 @@ impl EventResponse { StatusCode::Ok => { let data = >::try_from(self.payload)?; Ok(Ok(data.into_inner())) - }, + } StatusCode::Err | StatusCode::Internal => { let err = >::try_from(self.payload)?; Ok(Err(err.into_inner())) - }, + } } } } @@ -64,7 +64,9 @@ impl std::fmt::Display for EventResponse { impl Responder for EventResponse { #[inline] - fn respond_to(self, _: &EventRequest) -> EventResponse { self } + fn respond_to(self, _: &EventRequest) -> EventResponse { + self + } } pub type DataResult = std::result::Result, E>; diff --git a/frontend/rust-lib/lib-dispatch/src/service/boxed.rs b/frontend/rust-lib/lib-dispatch/src/service/boxed.rs index 0447cc0d40..342da26c6c 100644 --- a/frontend/rust-lib/lib-dispatch/src/service/boxed.rs +++ b/frontend/rust-lib/lib-dispatch/src/service/boxed.rs @@ -41,7 +41,9 @@ where type Context = Cfg; type Future = BoxFuture<'static, Result>; - fn new_service(&self, cfg: Cfg) -> Self::Future { self.0.new_service(cfg) } + fn new_service(&self, cfg: Cfg) -> Self::Future { + self.0.new_service(cfg) + } } pub type BoxService = @@ -65,7 +67,9 @@ where type Error = S::Error; type Future = S::Future; - fn call(&self, request: Req) -> S::Future { (**self).call(request) } + fn call(&self, request: Req) -> S::Future { + (**self).call(request) + } } struct ServiceWrapper { @@ -73,7 +77,9 @@ struct ServiceWrapper { } impl ServiceWrapper { - fn new(inner: S) -> Self { Self { inner } } + fn new(inner: S) -> Self { + Self { inner } + } } impl Service for ServiceWrapper @@ -85,7 +91,9 @@ where type Error = Err; type Future = BoxFuture<'static, Result>; - fn call(&self, req: Req) -> Self::Future { Box::pin(self.inner.call(req)) } + fn call(&self, req: Req) -> Self::Future { + Box::pin(self.inner.call(req)) + } } struct FactoryWrapper(SF); diff --git a/frontend/rust-lib/lib-dispatch/src/service/handler.rs b/frontend/rust-lib/lib-dispatch/src/service/handler.rs index d756c43236..774b86114c 100644 --- a/frontend/rust-lib/lib-dispatch/src/service/handler.rs +++ b/frontend/rust-lib/lib-dispatch/src/service/handler.rs @@ -78,7 +78,9 @@ where type Context = (); type Future = Ready>; - fn new_service(&self, _: ()) -> Self::Future { ready(Ok(self.clone())) } + fn new_service(&self, _: ()) -> Self::Future { + ready(Ok(self.clone())) + } } impl Service for HandlerService @@ -129,21 +131,21 @@ where let fut = handle.call(params); let state = HandlerServiceFuture::Handle(fut, req.take()); self.as_mut().set(state); - }, + } Err(err) => { let req = req.take().unwrap(); let system_err: DispatchError = err.into(); let res: EventResponse = system_err.into(); return Poll::Ready(Ok(ServiceResponse::new(req, res))); - }, + } }; - }, + } HandlerServiceProj::Handle(fut, req) => { let result = ready!(fut.poll(cx)); let req = req.take().unwrap(); let resp = result.respond_to(&req); return Poll::Ready(Ok(ServiceResponse::new(req, resp))); - }, + } } } } diff --git a/frontend/rust-lib/lib-dispatch/src/service/service.rs b/frontend/rust-lib/lib-dispatch/src/service/service.rs index 740612cd45..529dd0c8fa 100644 --- a/frontend/rust-lib/lib-dispatch/src/service/service.rs +++ b/frontend/rust-lib/lib-dispatch/src/service/service.rs @@ -29,10 +29,14 @@ pub struct ServiceRequest { } impl ServiceRequest { - pub fn new(req: EventRequest, payload: Payload) -> Self { Self { req, payload } } + pub fn new(req: EventRequest, payload: Payload) -> Self { + Self { req, payload } + } #[inline] - pub fn into_parts(self) -> (EventRequest, Payload) { (self.req, self.payload) } + pub fn into_parts(self) -> (EventRequest, Payload) { + (self.req, self.payload) + } } pub struct ServiceResponse { @@ -41,7 +45,11 @@ pub struct ServiceResponse { } impl ServiceResponse { - pub fn new(request: EventRequest, response: EventResponse) -> Self { ServiceResponse { request, response } } + pub fn new(request: EventRequest, response: EventResponse) -> Self { + ServiceResponse { request, response } + } - pub fn into_parts(self) -> (EventRequest, EventResponse) { (self.request, self.response) } + pub fn into_parts(self) -> (EventRequest, EventResponse) { + (self.request, self.response) + } } diff --git a/frontend/rust-lib/lib-dispatch/src/system.rs b/frontend/rust-lib/lib-dispatch/src/system.rs index 5192ff0888..081f4fa05d 100644 --- a/frontend/rust-lib/lib-dispatch/src/system.rs +++ b/frontend/rust-lib/lib-dispatch/src/system.rs @@ -50,10 +50,10 @@ impl FlowySystem { #[allow(dead_code)] pub fn stop(&self) { match self.sys_cmd_tx.send(SystemCommand::Exit(0)) { - Ok(_) => {}, + Ok(_) => {} Err(e) => { log::error!("Stop system error: {}", e); - }, + } } } @@ -89,7 +89,7 @@ impl Future for SystemController { if let Some(tx) = self.stop_tx.take() { let _ = tx.send(code); } - }, + } }, } } @@ -115,7 +115,7 @@ impl SystemRunner { } else { Ok(()) } - }, + } Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)), } } diff --git a/frontend/rust-lib/lib-dispatch/src/util/ready.rs b/frontend/rust-lib/lib-dispatch/src/util/ready.rs index f6457bc5cf..80720b5803 100644 --- a/frontend/rust-lib/lib-dispatch/src/util/ready.rs +++ b/frontend/rust-lib/lib-dispatch/src/util/ready.rs @@ -10,7 +10,9 @@ pub struct Ready { impl Ready { #[inline] - pub fn into_inner(mut self) -> T { self.val.take().unwrap() } + pub fn into_inner(mut self) -> T { + self.val.take().unwrap() + } } impl Unpin for Ready {} @@ -25,4 +27,6 @@ impl Future for Ready { } } -pub fn ready(val: T) -> Ready { Ready { val: Some(val) } } +pub fn ready(val: T) -> Ready { + Ready { val: Some(val) } +} diff --git a/frontend/rust-lib/lib-dispatch/tests/api/module.rs b/frontend/rust-lib/lib-dispatch/tests/api/module.rs index 47a11c93a4..c04c523828 100644 --- a/frontend/rust-lib/lib-dispatch/tests/api/module.rs +++ b/frontend/rust-lib/lib-dispatch/tests/api/module.rs @@ -1,7 +1,9 @@ use lib_dispatch::prelude::*; use std::sync::Arc; -pub async fn hello() -> String { "say hello".to_string() } +pub async fn hello() -> String { + "say hello".to_string() +} #[tokio::test] async fn test() { diff --git a/frontend/rust-lib/lib-log/src/layer.rs b/frontend/rust-lib/lib-log/src/layer.rs index 6434499ca2..57902704df 100644 --- a/frontend/rust-lib/lib-log/src/layer.rs +++ b/frontend/rust-lib/lib-log/src/layer.rs @@ -49,7 +49,7 @@ impl FlowyFormattingLayer { let mut buffer = Vec::new(); let mut serializer = serde_json::Serializer::new(&mut buffer); let mut map_serializer = serializer.serialize_map(None)?; - let message = format_span_context(&span, ty); + let message = format_span_context(span, ty); self.serialize_flowy_core_fields(&mut map_serializer, &message, span.metadata().level())?; if self.with_target { map_serializer.serialize_entry("target", &span.metadata().target())?; diff --git a/frontend/rust-lib/lib-sqlite/src/conn_ext.rs b/frontend/rust-lib/lib-sqlite/src/conn_ext.rs index e20b91a17b..73c04ce091 100644 --- a/frontend/rust-lib/lib-sqlite/src/conn_ext.rs +++ b/frontend/rust-lib/lib-sqlite/src/conn_ext.rs @@ -17,5 +17,7 @@ impl ConnectionExtension for SqliteConnection { Ok(sql::(query).get_result(self)?) } - fn exec(&self, query: impl AsRef) -> Result { Ok(SqliteConnection::execute(self, query.as_ref())?) } + fn exec(&self, query: impl AsRef) -> Result { + Ok(SqliteConnection::execute(self, query.as_ref())?) + } } diff --git a/frontend/rust-lib/lib-sqlite/src/database.rs b/frontend/rust-lib/lib-sqlite/src/database.rs index ded7e4a19d..49af0a9e0f 100644 --- a/frontend/rust-lib/lib-sqlite/src/database.rs +++ b/frontend/rust-lib/lib-sqlite/src/database.rs @@ -27,14 +27,18 @@ impl Database { }) } - pub fn get_uri(&self) -> &str { &self.uri } + pub fn get_uri(&self) -> &str { + &self.uri + } pub fn get_connection(&self) -> Result { let conn = self.pool.get()?; Ok(conn) } - pub fn get_pool(&self) -> Arc { self.pool.clone() } + pub fn get_pool(&self) -> Arc { + self.pool.clone() + } } pub fn db_file_uri(dir: &str, name: &str) -> String { diff --git a/frontend/rust-lib/lib-sqlite/src/errors.rs b/frontend/rust-lib/lib-sqlite/src/errors.rs index 37bd372834..3a678aa356 100644 --- a/frontend/rust-lib/lib-sqlite/src/errors.rs +++ b/frontend/rust-lib/lib-sqlite/src/errors.rs @@ -1,9 +1,5 @@ use error_chain::{ - error_chain, - error_chain_processing, - impl_error_chain_kind, - impl_error_chain_processed, - impl_extract_backtrace, + error_chain, error_chain_processing, impl_error_chain_kind, impl_error_chain_processed, impl_extract_backtrace, }; error_chain! { diff --git a/frontend/rust-lib/lib-sqlite/src/pool.rs b/frontend/rust-lib/lib-sqlite/src/pool.rs index b0244b58db..b5a3074b66 100644 --- a/frontend/rust-lib/lib-sqlite/src/pool.rs +++ b/frontend/rust-lib/lib-sqlite/src/pool.rs @@ -17,7 +17,9 @@ pub struct ConnectionPool { impl std::ops::Deref for ConnectionPool { type Target = Pool; - fn deref(&self) -> &Self::Target { &self.inner } + fn deref(&self) -> &Self::Target { + &self.inner + } } impl ConnectionPool { @@ -85,15 +87,23 @@ impl ManageConnection for ConnectionManager { type Connection = SqliteConnection; type Error = crate::Error; - fn connect(&self) -> Result { Ok(SqliteConnection::establish(&self.db_uri)?) } + fn connect(&self) -> Result { + Ok(SqliteConnection::establish(&self.db_uri)?) + } - fn is_valid(&self, conn: &mut Self::Connection) -> Result<()> { Ok(conn.execute("SELECT 1").map(|_| ())?) } + fn is_valid(&self, conn: &mut Self::Connection) -> Result<()> { + Ok(conn.execute("SELECT 1").map(|_| ())?) + } - fn has_broken(&self, _conn: &mut Self::Connection) -> bool { false } + fn has_broken(&self, _conn: &mut Self::Connection) -> bool { + false + } } impl ConnectionManager { - pub fn new>(uri: S) -> Self { ConnectionManager { db_uri: uri.into() } } + pub fn new>(uri: S) -> Self { + ConnectionManager { db_uri: uri.into() } + } } #[derive(Debug)] diff --git a/frontend/rust-lib/lib-sqlite/src/pragma.rs b/frontend/rust-lib/lib-sqlite/src/pragma.rs index 8202848862..448203afd8 100644 --- a/frontend/rust-lib/lib-sqlite/src/pragma.rs +++ b/frontend/rust-lib/lib-sqlite/src/pragma.rs @@ -1,3 +1,4 @@ +#![allow(clippy::upper_case_acronyms)] use crate::errors::{Error, Result}; use diesel::{ expression::SqlLiteral, @@ -52,7 +53,9 @@ pub trait PragmaExtension: ConnectionExtension { self.pragma_ret::("busy_timeout", timeout_ms, None) } - fn pragma_get_busy_timeout(&self) -> Result { self.pragma_get::("busy_timeout", None) } + fn pragma_get_busy_timeout(&self) -> Result { + self.pragma_get::("busy_timeout", None) + } fn pragma_set_journal_mode(&self, mode: SQLiteJournalMode, schema: Option<&str>) -> Result { self.pragma_ret::("journal_mode", mode, schema) @@ -117,10 +120,10 @@ impl FromStr for SQLiteJournalMode { #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum SQLiteSynchronous { - EXTRA = 3, - FULL = 2, + EXTRA = 3, + FULL = 2, NORMAL = 1, - OFF = 0, + OFF = 0, } impl fmt::Display for SQLiteSynchronous { diff --git a/frontend/rust-lib/rustfmt.toml b/frontend/rust-lib/rustfmt.toml index d76ec139c3..2464575494 100644 --- a/frontend/rust-lib/rustfmt.toml +++ b/frontend/rust-lib/rustfmt.toml @@ -1,18 +1,18 @@ # https://rust-lang.github.io/rustfmt/?version=master&search= max_width = 120 tab_spaces = 4 -fn_single_line = true -match_block_trailing_comma = true -normalize_comments = true -wrap_comments = true -use_field_init_shorthand = true -use_try_shorthand = true -normalize_doc_attributes = true -report_todo = "Never" -report_fixme = "Always" -imports_layout = "HorizontalVertical" -imports_granularity = "Crate" -reorder_modules = true -reorder_imports = true -enum_discrim_align_threshold = 20 +# fn_single_line = true +# match_block_trailing_comma = true +# normalize_comments = true +# wrap_comments = true +# use_field_init_shorthand = true +# use_try_shorthand = true +# normalize_doc_attributes = true +# report_todo = "Never" +# report_fixme = "Always" +# imports_layout = "HorizontalVertical" +# imports_granularity = "Crate" +# reorder_modules = true +# reorder_imports = true +# enum_discrim_align_threshold = 20 edition = "2018" diff --git a/shared-lib/backend-service/src/configuration.rs b/shared-lib/backend-service/src/configuration.rs index 0840dca19c..6912188826 100644 --- a/shared-lib/backend-service/src/configuration.rs +++ b/shared-lib/backend-service/src/configuration.rs @@ -38,27 +38,49 @@ impl ClientServerConfiguration { self.port = port; } - pub fn base_url(&self) -> String { format!("{}://{}:{}", self.http_scheme, self.host, self.port) } + pub fn base_url(&self) -> String { + format!("{}://{}:{}", self.http_scheme, self.host, self.port) + } - pub fn sign_up_url(&self) -> String { format!("{}/api/register", self.base_url()) } + pub fn sign_up_url(&self) -> String { + format!("{}/api/register", self.base_url()) + } - pub fn sign_in_url(&self) -> String { format!("{}/api/auth", self.base_url()) } + pub fn sign_in_url(&self) -> String { + format!("{}/api/auth", self.base_url()) + } - pub fn sign_out_url(&self) -> String { format!("{}/api/auth", self.base_url()) } + pub fn sign_out_url(&self) -> String { + format!("{}/api/auth", self.base_url()) + } - pub fn user_profile_url(&self) -> String { format!("{}/api/user", self.base_url()) } + pub fn user_profile_url(&self) -> String { + format!("{}/api/user", self.base_url()) + } - pub fn workspace_url(&self) -> String { format!("{}/api/workspace", self.base_url()) } + pub fn workspace_url(&self) -> String { + format!("{}/api/workspace", self.base_url()) + } - pub fn app_url(&self) -> String { format!("{}/api/app", self.base_url()) } + pub fn app_url(&self) -> String { + format!("{}/api/app", self.base_url()) + } - pub fn view_url(&self) -> String { format!("{}/api/view", self.base_url()) } + pub fn view_url(&self) -> String { + format!("{}/api/view", self.base_url()) + } - pub fn doc_url(&self) -> String { format!("{}/api/doc", self.base_url()) } + pub fn doc_url(&self) -> String { + format!("{}/api/doc", self.base_url()) + } - pub fn trash_url(&self) -> String { format!("{}/api/trash", self.base_url()) } + pub fn trash_url(&self) -> String { + format!("{}/api/trash", self.base_url()) + } - pub fn ws_addr(&self) -> String { format!("{}://{}:{}/ws", self.ws_scheme, self.host, self.port) } + pub fn ws_addr(&self) -> String { + format!("{}://{}:{}/ws", self.ws_scheme, self.host, self.port) + } } pub enum Environment { diff --git a/shared-lib/backend-service/src/errors.rs b/shared-lib/backend-service/src/errors.rs index 143e39d559..52c1e90ae1 100644 --- a/shared-lib/backend-service/src/errors.rs +++ b/shared-lib/backend-service/src/errors.rs @@ -37,16 +37,22 @@ impl ServerError { static_error!(connect_refused, ErrorCode::ConnectRefused); static_error!(record_not_found, ErrorCode::RecordNotFound); - pub fn new(msg: String, code: ErrorCode) -> Self { Self { code, msg } } + pub fn new(msg: String, code: ErrorCode) -> Self { + Self { code, msg } + } pub fn context(mut self, error: T) -> Self { self.msg = format!("{:?}", error); self } - pub fn is_record_not_found(&self) -> bool { self.code == ErrorCode::RecordNotFound } + pub fn is_record_not_found(&self) -> bool { + self.code == ErrorCode::RecordNotFound + } - pub fn is_unauthorized(&self) -> bool { self.code == ErrorCode::UserUnauthorized } + pub fn is_unauthorized(&self) -> bool { + self.code == ErrorCode::UserUnauthorized + } } pub fn internal_error(e: T) -> ServerError @@ -56,7 +62,9 @@ where ServerError::internal().context(e) } -pub fn invalid_params(e: T) -> ServerError { ServerError::params_invalid().context(e) } +pub fn invalid_params(e: T) -> ServerError { + ServerError::params_invalid().context(e) +} impl std::fmt::Display for ServerError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { @@ -78,45 +86,45 @@ impl std::convert::From<&ServerError> for FlowyResponse { #[repr(u16)] pub enum ErrorCode { #[display(fmt = "Unauthorized")] - UserUnauthorized = 1, + UserUnauthorized = 1, #[display(fmt = "Payload too large")] - PayloadOverflow = 2, + PayloadOverflow = 2, #[display(fmt = "Payload deserialize failed")] - PayloadSerdeFail = 3, + PayloadSerdeFail = 3, #[display(fmt = "Unexpected empty payload")] PayloadUnexpectedNone = 4, #[display(fmt = "Params is invalid")] - ParamsInvalid = 5, + ParamsInvalid = 5, #[display(fmt = "Protobuf serde error")] - ProtobufError = 10, + ProtobufError = 10, #[display(fmt = "Json serde Error")] - SerdeError = 11, + SerdeError = 11, #[display(fmt = "Email address already exists")] EmailAlreadyExists = 50, #[display(fmt = "Username and password do not match")] - PasswordNotMatch = 51, + PasswordNotMatch = 51, #[display(fmt = "Connect refused")] - ConnectRefused = 100, + ConnectRefused = 100, #[display(fmt = "Connection timeout")] - ConnectTimeout = 101, + ConnectTimeout = 101, #[display(fmt = "Connection closed")] - ConnectClose = 102, + ConnectClose = 102, #[display(fmt = "Connection canceled")] - ConnectCancel = 103, + ConnectCancel = 103, #[display(fmt = "Sql error")] - SqlError = 200, + SqlError = 200, #[display(fmt = "Record not found")] - RecordNotFound = 201, + RecordNotFound = 201, #[display(fmt = "Http request error")] - HttpError = 300, + HttpError = 300, #[display(fmt = "Internal error")] - InternalError = 1000, + InternalError = 1000, } diff --git a/shared-lib/backend-service/src/middleware.rs b/shared-lib/backend-service/src/middleware.rs index fee46765cc..c1e8b695c0 100644 --- a/shared-lib/backend-service/src/middleware.rs +++ b/shared-lib/backend-service/src/middleware.rs @@ -18,7 +18,9 @@ impl WorkspaceMiddleware { } } - pub fn invalid_token_subscribe(&self) -> broadcast::Receiver { self.invalid_token_sender.subscribe() } + pub fn invalid_token_subscribe(&self) -> broadcast::Receiver { + self.invalid_token_sender.subscribe() + } } impl ResponseMiddleware for WorkspaceMiddleware { @@ -27,9 +29,9 @@ impl ResponseMiddleware for WorkspaceMiddleware { if error.is_unauthorized() { log::error!("user is unauthorized"); match token { - None => {}, + None => {} Some(token) => match self.invalid_token_sender.send(token.clone()) { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("{:?}", e), }, } diff --git a/shared-lib/backend-service/src/request/request.rs b/shared-lib/backend-service/src/request/request.rs index b606e18be2..6f0eb5aa4a 100644 --- a/shared-lib/backend-service/src/request/request.rs +++ b/shared-lib/backend-service/src/request/request.rs @@ -37,7 +37,9 @@ impl std::default::Default for HttpRequestBuilder { } impl HttpRequestBuilder { - pub fn new() -> Self { HttpRequestBuilder::default() } + pub fn new() -> Self { + HttpRequestBuilder::default() + } pub fn middleware(mut self, middleware: Arc) -> Self where @@ -162,7 +164,7 @@ impl HttpRequestBuilder { None => { self.response = Some(flowy_response.data); Ok(self) - }, + } Some(error) => Err(error), } } @@ -204,6 +206,6 @@ fn default_client() -> Client { Err(e) => { log::error!("Create reqwest client failed: {}", e); reqwest::Client::new() - }, + } } } diff --git a/shared-lib/backend-service/src/response/response.rs b/shared-lib/backend-service/src/response/response.rs index ac0bd1b3e3..9815b3bcb8 100644 --- a/shared-lib/backend-service/src/response/response.rs +++ b/shared-lib/backend-service/src/response/response.rs @@ -12,9 +12,13 @@ pub struct FlowyResponse { } impl FlowyResponse { - pub fn new(data: Bytes, error: Option) -> Self { FlowyResponse { data, error } } + pub fn new(data: Bytes, error: Option) -> Self { + FlowyResponse { data, error } + } - pub fn success() -> Self { Self::new(Bytes::new(), None) } + pub fn success() -> Self { + Self::new(Bytes::new(), None) + } pub fn data>(mut self, data: T) -> Result { let bytes: Bytes = data.try_into()?; @@ -30,19 +34,27 @@ impl FlowyResponse { } impl std::convert::From for ServerError { - fn from(e: protobuf::ProtobufError) -> Self { ServerError::internal().context(e) } + fn from(e: protobuf::ProtobufError) -> Self { + ServerError::internal().context(e) + } } impl std::convert::From for ServerError { - fn from(error: RecvError) -> Self { ServerError::internal().context(error) } + fn from(error: RecvError) -> Self { + ServerError::internal().context(error) + } } impl std::convert::From for ServerError { - fn from(e: serde_json::Error) -> Self { ServerError::internal().context(e) } + fn from(e: serde_json::Error) -> Self { + ServerError::internal().context(e) + } } impl std::convert::From for ServerError { - fn from(error: anyhow::Error) -> Self { ServerError::internal().context(error) } + fn from(error: anyhow::Error) -> Self { + ServerError::internal().context(error) + } } impl std::convert::From for ServerError { @@ -73,7 +85,7 @@ impl std::convert::From for ServerError { if hyper_error.is_timeout() {} ServerError { code, msg } - }, + } }; } @@ -82,5 +94,7 @@ impl std::convert::From for ServerError { } impl std::convert::From for ServerError { - fn from(e: uuid::Error) -> Self { ServerError::internal().context(e) } + fn from(e: uuid::Error) -> Self { + ServerError::internal().context(e) + } } diff --git a/shared-lib/backend-service/src/response/response_http.rs b/shared-lib/backend-service/src/response/response_http.rs index b5853f49bb..f81bdd75a6 100644 --- a/shared-lib/backend-service/src/response/response_http.rs +++ b/shared-lib/backend-service/src/response/response_http.rs @@ -11,7 +11,9 @@ impl ResponseError for ServerError { } } impl std::convert::Into for FlowyResponse { - fn into(self) -> HttpResponse { HttpResponse::Ok().json(self) } + fn into(self) -> HttpResponse { + HttpResponse::Ok().json(self) + } } impl std::convert::Into for FlowyResponse { diff --git a/shared-lib/error-code/src/error_code.rs b/shared-lib/error-code/src/error_code.rs index 2868a5fa7c..c47d4fd8d4 100644 --- a/shared-lib/error-code/src/error_code.rs +++ b/shared-lib/error-code/src/error_code.rs @@ -7,19 +7,19 @@ use std::convert::{TryFrom, TryInto}; #[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] pub enum ErrorCode { #[display(fmt = "Internal error")] - Internal = 0, + Internal = 0, #[display(fmt = "UserUnauthorized")] - UserUnauthorized = 2, + UserUnauthorized = 2, #[display(fmt = "RecordNotFound")] - RecordNotFound = 3, + RecordNotFound = 3, #[display(fmt = "Workspace name can not be empty or whitespace")] WorkspaceNameInvalid = 100, #[display(fmt = "Workspace id can not be empty or whitespace")] - WorkspaceIdInvalid = 101, + WorkspaceIdInvalid = 101, #[display(fmt = "Color style of the App is invalid")] AppColorStyleInvalid = 102, @@ -31,58 +31,58 @@ pub enum ErrorCode { WorkspaceNameTooLong = 104, #[display(fmt = "App id can not be empty or whitespace")] - AppIdInvalid = 110, + AppIdInvalid = 110, #[display(fmt = "App name can not be empty or whitespace")] - AppNameInvalid = 111, + AppNameInvalid = 111, #[display(fmt = "View name can not be empty or whitespace")] - ViewNameInvalid = 120, + ViewNameInvalid = 120, #[display(fmt = "Thumbnail of the view is invalid")] ViewThumbnailInvalid = 121, #[display(fmt = "View id can not be empty or whitespace")] - ViewIdInvalid = 122, + ViewIdInvalid = 122, #[display(fmt = "View desc too long")] - ViewDescTooLong = 123, + ViewDescTooLong = 123, #[display(fmt = "View data is invalid")] - ViewDataInvalid = 124, + ViewDataInvalid = 124, #[display(fmt = "View name too long")] - ViewNameTooLong = 125, + ViewNameTooLong = 125, #[display(fmt = "Connection error")] - ConnectError = 200, + ConnectError = 200, #[display(fmt = "Email can not be empty or whitespace")] - EmailIsEmpty = 300, + EmailIsEmpty = 300, #[display(fmt = "Email format is not valid")] - EmailFormatInvalid = 301, + EmailFormatInvalid = 301, #[display(fmt = "Email already exists")] - EmailAlreadyExists = 302, + EmailAlreadyExists = 302, #[display(fmt = "Password can not be empty or whitespace")] - PasswordIsEmpty = 303, + PasswordIsEmpty = 303, #[display(fmt = "Password format too long")] - PasswordTooLong = 304, + PasswordTooLong = 304, #[display(fmt = "Password contains forbidden characters.")] PasswordContainsForbidCharacters = 305, #[display(fmt = "Password should contain a minimum of 6 characters with 1 special 1 letter and 1 numeric")] PasswordFormatInvalid = 306, #[display(fmt = "Password not match")] - PasswordNotMatch = 307, + PasswordNotMatch = 307, #[display(fmt = "User name is too long")] - UserNameTooLong = 308, + UserNameTooLong = 308, #[display(fmt = "User name contain forbidden characters")] UserNameContainForbiddenCharacters = 309, #[display(fmt = "User name can not be empty or whitespace")] - UserNameIsEmpty = 310, + UserNameIsEmpty = 310, #[display(fmt = "user id is empty or whitespace")] - UserIdInvalid = 311, + UserIdInvalid = 311, #[display(fmt = "User not exist")] - UserNotExist = 312, + UserNotExist = 312, } impl ErrorCode { diff --git a/shared-lib/flowy-ast/src/ast.rs b/shared-lib/flowy-ast/src/ast.rs index b5c0208c01..73be461b3f 100644 --- a/shared-lib/flowy-ast/src/ast.rs +++ b/shared-lib/flowy-ast/src/ast.rs @@ -22,15 +22,15 @@ impl<'a> ASTContainer<'a> { // https://docs.rs/syn/1.0.48/syn/struct.DataStruct.html let (style, fields) = struct_from_ast(cx, &data.fields); ASTData::Struct(style, fields) - }, + } syn::Data::Union(_) => { cx.error_spanned_by(ast, "Does not support derive for unions"); return None; - }, + } syn::Data::Enum(data) => { // https://docs.rs/syn/1.0.48/syn/struct.DataEnum.html ASTData::Enum(enum_from_ast(cx, &ast.ident, &data.variants, &ast.attrs)) - }, + } }; let ident = ast.ident.clone(); @@ -57,11 +57,11 @@ impl<'a> ASTData<'a> { ASTData::Enum(variants) => { let iter = variants.iter().map(|variant| &variant.attrs); Box::new(iter) - }, + } ASTData::Struct(_, fields) => { let iter = fields.iter().flat_map(|_| None); Box::new(iter) - }, + } } } @@ -74,7 +74,7 @@ impl<'a> ASTData<'a> { _ => None, }); Box::new(iter) - }, + } } } } @@ -89,7 +89,9 @@ pub struct ASTEnumVariant<'a> { } impl<'a> ASTEnumVariant<'a> { - pub fn name(&self) -> String { self.ident.to_string() } + pub fn name(&self) -> String { + self.ident.to_string() + } } pub enum BracketCategory { @@ -119,35 +121,35 @@ impl<'a> ASTField<'a> { match inner.primitive_ty { PrimitiveTy::Map(map_info) => { bracket_category = Some(BracketCategory::Map((map_info.key.clone(), map_info.value))) - }, + } PrimitiveTy::Vec => { bracket_category = Some(BracketCategory::Vec); - }, + } PrimitiveTy::Opt => { bracket_category = Some(BracketCategory::Opt); - }, + } PrimitiveTy::Other => { bracket_category = Some(BracketCategory::Other); - }, + } } match *inner.bracket_ty_info { Some(bracketed_inner_ty) => { bracket_inner_ty = Some(bracketed_inner_ty.ident.clone()); bracket_ty = Some(inner.ident.clone()); - }, + } None => { bracket_ty = Some(inner.ident.clone()); - }, + } } - }, + } Ok(None) => { cx.error_spanned_by(&field.ty, "fail to get the ty inner type"); - }, + } Err(e) => { eprintln!("ASTField parser failed: {:?} with error: {}", field, e); panic!() - }, + } } ASTField { @@ -180,7 +182,9 @@ impl<'a> ASTField<'a> { } } - pub fn is_option(&self) -> bool { attr::is_option(&self.ty) } + pub fn is_option(&self) -> bool { + attr::is_option(self.ty) + } } #[derive(Copy, Clone)] @@ -199,7 +203,7 @@ pub fn struct_from_ast<'a>(cx: &Ctxt, fields: &'a syn::Fields) -> (ASTStyle, Vec syn::Fields::Named(fields) => (ASTStyle::Struct, fields_from_ast(cx, &fields.named)), syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => { (ASTStyle::NewType, fields_from_ast(cx, &fields.unnamed)) - }, + } syn::Fields::Unnamed(fields) => (ASTStyle::Tuple, fields_from_ast(cx, &fields.unnamed)), syn::Fields::Unit => (ASTStyle::Unit, Vec::new()), } diff --git a/shared-lib/flowy-ast/src/attr.rs b/shared-lib/flowy-ast/src/attr.rs index 80a928a8d4..dcc5471de4 100644 --- a/shared-lib/flowy-ast/src/attr.rs +++ b/shared-lib/flowy-ast/src/attr.rs @@ -29,33 +29,33 @@ impl AttrsContainer { if let Ok(into_ty) = parse_lit_into_ty(cx, PB_STRUCT, &m.lit) { pb_struct_type.set_opt(&m.path, Some(into_ty)); } - }, + } // Parse `#[pb(enum = "Type")] Meta(NameValue(m)) if m.path == PB_ENUM => { if let Ok(into_ty) = parse_lit_into_ty(cx, PB_ENUM, &m.lit) { pb_enum_type.set_opt(&m.path, Some(into_ty)); } - }, + } Meta(meta_item) => { let path = meta_item.path().into_token_stream().to_string().replace(' ', ""); cx.error_spanned_by(meta_item.path(), format!("unknown pb container attribute `{}`", path)); - }, + } Lit(lit) => { cx.error_spanned_by(lit, "unexpected literal in pb container attribute"); - }, + } } } match &item.data { syn::Data::Struct(_) => { pb_struct_type.set_if_none(default_pb_type(&cx, &item.ident)); - }, + } syn::Data::Enum(_) => { pb_enum_type.set_if_none(default_pb_type(&cx, &item.ident)); - }, - _ => {}, + } + _ => {} } AttrsContainer { @@ -65,9 +65,13 @@ impl AttrsContainer { } } - pub fn pb_struct_type(&self) -> Option<&syn::Type> { self.pb_struct_type.as_ref() } + pub fn pb_struct_type(&self) -> Option<&syn::Type> { + self.pb_struct_type.as_ref() + } - pub fn pb_enum_type(&self) -> Option<&syn::Type> { self.pb_enum_type.as_ref() } + pub fn pb_enum_type(&self) -> Option<&syn::Type> { + self.pb_enum_type.as_ref() + } } struct ASTAttr<'c, T> { @@ -111,7 +115,9 @@ impl<'c, T> ASTAttr<'c, T> { } } - fn get(self) -> Option { self.value } + fn get(self) -> Option { + self.value + } #[allow(dead_code)] fn get_with_tokens(self) -> Option<(TokenStream, T)> { @@ -154,42 +160,42 @@ impl ASTAttrField { Meta(Path(word)) if word == SKIP => { skip_serializing.set_true(word); skip_deserializing.set_true(word); - }, + } // Parse '#[pb(index = x)]' Meta(NameValue(m)) if m.path == PB_INDEX => { if let syn::Lit::Int(lit) = &m.lit { pb_index.set(&m.path, lit.clone()); } - }, + } // Parse `#[pb(one_of)]` Meta(Path(path)) if path == PB_ONE_OF => { pb_one_of.set_true(path); - }, + } // Parse `#[pb(serialize_with = "...")]` Meta(NameValue(m)) if m.path == SERIALIZE_WITH => { if let Ok(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &m.lit) { serialize_with.set(&m.path, path); } - }, + } // Parse `#[pb(deserialize_with = "...")]` Meta(NameValue(m)) if m.path == DESERIALIZE_WITH => { if let Ok(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &m.lit) { deserialize_with.set(&m.path, path); } - }, + } Meta(meta_item) => { let path = meta_item.path().into_token_stream().to_string().replace(' ', ""); cx.error_spanned_by(meta_item.path(), format!("unknown field attribute `{}`", path)); - }, + } Lit(lit) => { cx.error_spanned_by(lit, "unexpected literal in pb field attribute"); - }, + } } } @@ -205,17 +211,29 @@ impl ASTAttrField { } #[allow(dead_code)] - pub fn pb_index(&self) -> Option { self.pb_index.as_ref().map(|lit| lit.base10_digits().to_string()) } + pub fn pb_index(&self) -> Option { + self.pb_index.as_ref().map(|lit| lit.base10_digits().to_string()) + } - pub fn is_one_of(&self) -> bool { self.pb_one_of } + pub fn is_one_of(&self) -> bool { + self.pb_one_of + } - pub fn serialize_with(&self) -> Option<&syn::ExprPath> { self.serialize_with.as_ref() } + pub fn serialize_with(&self) -> Option<&syn::ExprPath> { + self.serialize_with.as_ref() + } - pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { self.deserialize_with.as_ref() } + pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { + self.deserialize_with.as_ref() + } - pub fn skip_serializing(&self) -> bool { self.skip_serializing } + pub fn skip_serializing(&self) -> bool { + self.skip_serializing + } - pub fn skip_deserializing(&self) -> bool { self.skip_deserializing } + pub fn skip_deserializing(&self) -> bool { + self.skip_deserializing + } } pub enum Default { @@ -267,11 +285,17 @@ impl ASTEnumAttrVariant { } } - pub fn event_input(&self) -> Option { self.event_attrs.input.clone() } + pub fn event_input(&self) -> Option { + self.event_attrs.input.clone() + } - pub fn event_output(&self) -> Option { self.event_attrs.output.clone() } + pub fn event_output(&self) -> Option { + self.event_attrs.output.clone() + } - pub fn event_error(&self) -> String { self.event_attrs.error_ty.as_ref().unwrap().clone() } + pub fn event_error(&self) -> String { + self.event_attrs.error_ty.as_ref().unwrap().clone() + } } fn get_event_attrs_from(ctxt: &Ctxt, variant_attrs: &[syn::Attribute], enum_attrs: &[syn::Attribute]) -> EventAttrs { @@ -320,12 +344,12 @@ fn get_event_attrs_from(ctxt: &Ctxt, variant_attrs: &[syn::Attribute], enum_attr event_attrs.output = Some(output_type); } } - }, + } Meta(Path(word)) => { if word == EVENT_IGNORE && attr.path == EVENT { event_attrs.ignore = true; } - }, + } Lit(s) => ctxt.error_spanned_by(s, "unexpected attribute"), _ => ctxt.error_spanned_by(meta_item, "unexpected attribute"), }; @@ -359,12 +383,12 @@ pub fn get_meta_items(cx: &Ctxt, attr: &syn::Attribute) -> Result { cx.error_spanned_by(other, "expected #[pb(...)] or or #[event(...)]"); Err(()) - }, + } Err(err) => { cx.error_spanned_by(attr, "attribute must be str, e.g. #[pb(xx = \"xxx\")]"); cx.syn_error(err); Err(()) - }, + } } } @@ -442,19 +466,19 @@ pub fn is_option(ty: &syn::Type) -> bool { syn::Type::Path(ty) => &ty.path, _ => { return false; - }, + } }; let seg = match path.segments.last() { Some(seg) => seg, None => { return false; - }, + } }; let args = match &seg.arguments { syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args, _ => { return false; - }, + } }; seg.ident == "Option" && args.len() == 1 } @@ -470,9 +494,15 @@ pub fn ungroup(mut ty: &syn::Type) -> &syn::Type { struct BoolAttr<'c>(ASTAttr<'c, ()>); impl<'c> BoolAttr<'c> { - fn none(cx: &'c Ctxt, name: Symbol) -> Self { BoolAttr(ASTAttr::none(cx, name)) } + fn none(cx: &'c Ctxt, name: Symbol) -> Self { + BoolAttr(ASTAttr::none(cx, name)) + } - fn set_true(&mut self, obj: A) { self.0.set(obj, ()); } + fn set_true(&mut self, obj: A) { + self.0.set(obj, ()); + } - fn get(&self) -> bool { self.0.value.is_some() } + fn get(&self) -> bool { + self.0.value.is_some() + } } diff --git a/shared-lib/flowy-ast/src/ctxt.rs b/shared-lib/flowy-ast/src/ctxt.rs index 54ad810fe6..1bea450059 100644 --- a/shared-lib/flowy-ast/src/ctxt.rs +++ b/shared-lib/flowy-ast/src/ctxt.rs @@ -21,7 +21,9 @@ impl Ctxt { .push(syn::Error::new_spanned(obj.into_token_stream(), msg)); } - pub fn syn_error(&self, err: syn::Error) { self.errors.borrow_mut().as_mut().unwrap().push(err); } + pub fn syn_error(&self, err: syn::Error) { + self.errors.borrow_mut().as_mut().unwrap().push(err); + } pub fn check(self) -> Result<(), Vec> { let errors = self.errors.borrow_mut().take().unwrap(); diff --git a/shared-lib/flowy-ast/src/symbol.rs b/shared-lib/flowy-ast/src/symbol.rs index 6b9e01f05e..64d57fa897 100644 --- a/shared-lib/flowy-ast/src/symbol.rs +++ b/shared-lib/flowy-ast/src/symbol.rs @@ -21,21 +21,31 @@ pub const EVENT: Symbol = Symbol("event"); pub const EVENT_ERR: Symbol = Symbol("event_err"); impl PartialEq for Ident { - fn eq(&self, word: &Symbol) -> bool { self == word.0 } + fn eq(&self, word: &Symbol) -> bool { + self == word.0 + } } impl<'a> PartialEq for &'a Ident { - fn eq(&self, word: &Symbol) -> bool { *self == word.0 } + fn eq(&self, word: &Symbol) -> bool { + *self == word.0 + } } impl PartialEq for Path { - fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } + fn eq(&self, word: &Symbol) -> bool { + self.is_ident(word.0) + } } impl<'a> PartialEq for &'a Path { - fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } + fn eq(&self, word: &Symbol) -> bool { + self.is_ident(word.0) + } } impl Display for Symbol { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(self.0) } + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.0) + } } diff --git a/shared-lib/flowy-ast/src/ty_ext.rs b/shared-lib/flowy-ast/src/ty_ext.rs index 769643f51c..d3dbd84590 100644 --- a/shared-lib/flowy-ast/src/ty_ext.rs +++ b/shared-lib/flowy-ast/src/ty_ext.rs @@ -24,7 +24,9 @@ pub struct MapInfo { } impl MapInfo { - fn new(key: String, value: String) -> Self { MapInfo { key, value } } + fn new(key: String, value: String) -> Self { + MapInfo { key, value } + } } impl<'a> TyInfo<'a> { @@ -34,7 +36,7 @@ impl<'a> TyInfo<'a> { Some(b_ty) => b_ty.ident, None => { panic!() - }, + } } } } @@ -60,8 +62,8 @@ pub fn parse_ty<'a>(ctxt: &Ctxt, ty: &'a syn::Type) -> Result> "Vec" => generate_vec_ty_info(ctxt, seg, bracketed), "Option" => generate_option_ty_info(ctxt, ty, seg, bracketed), _ => { - return Err(format!("Unsupported ty {}", seg.ident.to_string())); - }, + return Err(format!("Unsupported ty {}", seg.ident)); + } } } else { return Ok(Some(TyInfo { @@ -103,7 +105,7 @@ pub fn generate_hashmap_ty_info<'a>( let types = parse_bracketed(bracketed); let key = parse_ty(ctxt, types[0])?.unwrap().ident.to_string(); let value = parse_ty(ctxt, types[1])?.unwrap().ident.to_string(); - let bracket_ty_info = Box::new(parse_ty(ctxt, &types[1])?); + let bracket_ty_info = Box::new(parse_ty(ctxt, types[1])?); Ok(Some(TyInfo { ident: &path_segment.ident, ty, @@ -120,7 +122,7 @@ fn generate_option_ty_info<'a>( ) -> Result>, String> { assert_eq!(path_segment.ident.to_string(), "Option".to_string()); let types = parse_bracketed(bracketed); - let bracket_ty_info = Box::new(parse_ty(ctxt, &types[0])?); + let bracket_ty_info = Box::new(parse_ty(ctxt, types[0])?); Ok(Some(TyInfo { ident: &path_segment.ident, ty, @@ -138,7 +140,7 @@ fn generate_vec_ty_info<'a>( return Ok(None); } if let syn::GenericArgument::Type(ref bracketed_type) = bracketed.args.first().unwrap() { - let bracketed_ty_info = Box::new(parse_ty(ctxt, &bracketed_type)?); + let bracketed_ty_info = Box::new(parse_ty(ctxt, bracketed_type)?); return Ok(Some(TyInfo { ident: &path_segment.ident, ty: bracketed_type, diff --git a/shared-lib/flowy-collaboration/src/document/data.rs b/shared-lib/flowy-collaboration/src/document/data.rs index f2244e6344..449b8bd136 100644 --- a/shared-lib/flowy-collaboration/src/document/data.rs +++ b/shared-lib/flowy-collaboration/src/document/data.rs @@ -6,5 +6,7 @@ pub struct ImageData { } impl ToString for ImageData { - fn to_string(&self) -> String { self.image.clone() } + fn to_string(&self) -> String { + self.image.clone() + } } diff --git a/shared-lib/flowy-collaboration/src/document/default/mod.rs b/shared-lib/flowy-collaboration/src/document/default/mod.rs index ca772be0ae..29de1ddf97 100644 --- a/shared-lib/flowy-collaboration/src/document/default/mod.rs +++ b/shared-lib/flowy-collaboration/src/document/default/mod.rs @@ -1,10 +1,14 @@ use lib_ot::{core::DeltaBuilder, rich_text::RichTextDelta}; #[inline] -pub fn initial_delta() -> RichTextDelta { DeltaBuilder::new().insert("\n").build() } +pub fn initial_delta() -> RichTextDelta { + DeltaBuilder::new().insert("\n").build() +} #[inline] -pub fn initial_delta_string() -> String { initial_delta().to_json() } +pub fn initial_delta_string() -> String { + initial_delta().to_json() +} #[inline] pub fn initial_read_me() -> RichTextDelta { diff --git a/shared-lib/flowy-collaboration/src/document/document.rs b/shared-lib/flowy-collaboration/src/document/document.rs index 2cb5c196fb..071f545c97 100644 --- a/shared-lib/flowy-collaboration/src/document/document.rs +++ b/shared-lib/flowy-collaboration/src/document/document.rs @@ -18,12 +18,16 @@ pub trait InitialDocumentText { pub struct PlainDoc(); impl InitialDocumentText for PlainDoc { - fn initial_delta() -> RichTextDelta { RichTextDelta::new() } + fn initial_delta() -> RichTextDelta { + RichTextDelta::new() + } } pub struct NewlineDoc(); impl InitialDocumentText for NewlineDoc { - fn initial_delta() -> RichTextDelta { initial_delta() } + fn initial_delta() -> RichTextDelta { + initial_delta() + } } pub struct Document { @@ -35,7 +39,9 @@ pub struct Document { } impl Document { - pub fn new() -> Self { Self::from_delta(C::initial_delta()) } + pub fn new() -> Self { + Self::from_delta(C::initial_delta()) + } pub fn from_delta(delta: RichTextDelta) -> Self { Document { @@ -52,13 +58,21 @@ impl Document { Ok(Self::from_delta(delta)) } - pub fn to_json(&self) -> String { self.delta.to_json() } + pub fn to_json(&self) -> String { + self.delta.to_json() + } - pub fn to_bytes(&self) -> Vec { self.delta.clone().to_bytes().to_vec() } + pub fn to_bytes(&self) -> Vec { + self.delta.clone().to_bytes().to_vec() + } - pub fn to_plain_string(&self) -> String { self.delta.apply("").unwrap() } + pub fn to_plain_string(&self) -> String { + self.delta.apply("").unwrap() + } - pub fn delta(&self) -> &RichTextDelta { &self.delta } + pub fn delta(&self) -> &RichTextDelta { + &self.delta + } pub fn md5(&self) -> String { // TODO: Optimize the cost of calculating the md5 @@ -66,17 +80,19 @@ impl Document { format!("{:x}", md5::compute(bytes)) } - pub fn set_notify(&mut self, notify: mpsc::UnboundedSender<()>) { self.notify = Some(notify); } + pub fn set_notify(&mut self, notify: mpsc::UnboundedSender<()>) { + self.notify = Some(notify); + } pub fn set_delta(&mut self, data: RichTextDelta) { tracing::trace!("document: {}", data.to_json()); self.delta = data; match &self.notify { - None => {}, + None => {} Some(notify) => { let _ = notify.send(()); - }, + } } } @@ -117,7 +133,7 @@ impl Document { pub fn delete(&mut self, interval: Interval) -> Result { let _ = validate_interval(&self.delta, &interval)?; - debug_assert_eq!(interval.is_empty(), false); + debug_assert!(!interval.is_empty()); let delete = self.view.delete(&self.delta, interval)?; if !delete.is_empty() { let _ = self.compose_delta(delete.clone())?; @@ -154,9 +170,13 @@ impl Document { Ok(delta) } - pub fn can_undo(&self) -> bool { self.history.can_undo() } + pub fn can_undo(&self) -> bool { + self.history.can_undo() + } - pub fn can_redo(&self) -> bool { self.history.can_redo() } + pub fn can_redo(&self) -> bool { + self.history.can_redo() + } pub fn undo(&mut self) -> Result { match self.history.undo() { @@ -166,7 +186,7 @@ impl Document { self.set_delta(new_delta); self.history.add_redo(inverted_delta); Ok(UndoResult { delta: undo_delta }) - }, + } } } @@ -178,11 +198,13 @@ impl Document { self.set_delta(new_delta); self.history.add_undo(inverted_delta); Ok(UndoResult { delta: redo_delta }) - }, + } } } - pub fn is_empty(&self) -> bool { self.delta == C::initial_delta() } + pub fn is_empty(&self) -> bool { + self.delta == C::initial_delta() + } } impl Document { diff --git a/shared-lib/flowy-collaboration/src/document/extensions/delete/default_delete.rs b/shared-lib/flowy-collaboration/src/document/extensions/delete/default_delete.rs index 348bbaf63e..5b9d3f01a8 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/delete/default_delete.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/delete/default_delete.rs @@ -6,7 +6,9 @@ use lib_ot::{ pub struct DefaultDelete {} impl DeleteExt for DefaultDelete { - fn ext_name(&self) -> &str { "DefaultDelete" } + fn ext_name(&self) -> &str { + "DefaultDelete" + } fn apply(&self, _delta: &RichTextDelta, interval: Interval) -> Option { Some( diff --git a/shared-lib/flowy-collaboration/src/document/extensions/delete/preserve_line_format_merge.rs b/shared-lib/flowy-collaboration/src/document/extensions/delete/preserve_line_format_merge.rs index 81c9359655..fe86029e31 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/delete/preserve_line_format_merge.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/delete/preserve_line_format_merge.rs @@ -6,7 +6,9 @@ use lib_ot::{ pub struct PreserveLineFormatOnMerge {} impl DeleteExt for PreserveLineFormatOnMerge { - fn ext_name(&self) -> &str { "PreserveLineFormatOnMerge" } + fn ext_name(&self) -> &str { + "PreserveLineFormatOnMerge" + } fn apply(&self, delta: &RichTextDelta, interval: Interval) -> Option { if interval.is_empty() { @@ -37,7 +39,7 @@ impl DeleteExt for PreserveLineFormatOnMerge { None => { new_delta.retain(op.len(), plain_attributes()); continue; - }, + } Some(line_break) => { let mut attributes = op.get_attributes(); attributes.mark_all_as_removed_except(None); @@ -49,9 +51,9 @@ impl DeleteExt for PreserveLineFormatOnMerge { new_delta.retain(line_break, plain_attributes()); new_delta.retain(1, attributes); break; - }, + } } - }, + } } } diff --git a/shared-lib/flowy-collaboration/src/document/extensions/format/resolve_block_format.rs b/shared-lib/flowy-collaboration/src/document/extensions/format/resolve_block_format.rs index 42f64c1b8a..c138621048 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/format/resolve_block_format.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/format/resolve_block_format.rs @@ -10,7 +10,9 @@ use crate::{ pub struct ResolveBlockFormat {} impl FormatExt for ResolveBlockFormat { - fn ext_name(&self) -> &str { "ResolveBlockFormat" } + fn ext_name(&self) -> &str { + "ResolveBlockFormat" + } fn apply(&self, delta: &RichTextDelta, interval: Interval, attribute: &RichTextAttribute) -> Option { if attribute.scope != AttributeScope::Block { @@ -28,7 +30,7 @@ impl FormatExt for ResolveBlockFormat { Some(_) => { let tmp_delta = line_break(&next_op, attribute, AttributeScope::Block); new_delta.extend(tmp_delta); - }, + } } start += next_op.len(); @@ -43,7 +45,7 @@ impl FormatExt for ResolveBlockFormat { new_delta.retain(line_break, plain_attributes()); new_delta.retain(1, attribute.clone().into()); break; - }, + } } } diff --git a/shared-lib/flowy-collaboration/src/document/extensions/format/resolve_inline_format.rs b/shared-lib/flowy-collaboration/src/document/extensions/format/resolve_inline_format.rs index 036617ff85..f5355299d1 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/format/resolve_inline_format.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/format/resolve_inline_format.rs @@ -10,7 +10,9 @@ use crate::{ pub struct ResolveInlineFormat {} impl FormatExt for ResolveInlineFormat { - fn ext_name(&self) -> &str { "ResolveInlineFormat" } + fn ext_name(&self) -> &str { + "ResolveInlineFormat" + } fn apply(&self, delta: &RichTextDelta, interval: Interval, attribute: &RichTextAttribute) -> Option { if attribute.scope != AttributeScope::Inline { @@ -28,7 +30,7 @@ impl FormatExt for ResolveInlineFormat { Some(_) => { let tmp_delta = line_break(&next_op, attribute, AttributeScope::Inline); new_delta.extend(tmp_delta); - }, + } } start += next_op.len(); diff --git a/shared-lib/flowy-collaboration/src/document/extensions/helper.rs b/shared-lib/flowy-collaboration/src/document/extensions/helper.rs index d800595ffb..328a41d095 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/helper.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/helper.rs @@ -19,14 +19,14 @@ pub(crate) fn line_break( AttributeScope::Inline => { new_delta.retain(line_break - start, attribute.clone().into()); new_delta.retain(1, plain_attributes()); - }, + } AttributeScope::Block => { new_delta.retain(line_break - start, plain_attributes()); new_delta.retain(1, attribute.clone().into()); - }, + } _ => { log::error!("Unsupported parser line break for {:?}", scope); - }, + } } start = line_break + 1; diff --git a/shared-lib/flowy-collaboration/src/document/extensions/insert/auto_exit_block.rs b/shared-lib/flowy-collaboration/src/document/extensions/insert/auto_exit_block.rs index 6516203a9d..358365ab15 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/insert/auto_exit_block.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/insert/auto_exit_block.rs @@ -7,7 +7,9 @@ use lib_ot::{ pub struct AutoExitBlock {} impl InsertExt for AutoExitBlock { - fn ext_name(&self) -> &str { "AutoExitBlock" } + fn ext_name(&self) -> &str { + "AutoExitBlock" + } fn apply(&self, delta: &RichTextDelta, replace_len: usize, text: &str, index: usize) -> Option { // Auto exit block will be triggered by enter two new lines @@ -33,13 +35,13 @@ impl InsertExt for AutoExitBlock { } match iter.next_op_with_newline() { - None => {}, + None => {} Some((newline_op, _)) => { let newline_attributes = attributes_except_header(&newline_op); if block_attributes == newline_attributes { return None; } - }, + } } attributes.mark_all_as_removed_except(Some(RichTextAttributeKey::Header)); diff --git a/shared-lib/flowy-collaboration/src/document/extensions/insert/auto_format.rs b/shared-lib/flowy-collaboration/src/document/extensions/insert/auto_format.rs index de58e6d5d7..760eb65c8b 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/insert/auto_format.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/insert/auto_format.rs @@ -8,7 +8,9 @@ use url::Url; pub struct AutoFormatExt {} impl InsertExt for AutoFormatExt { - fn ext_name(&self) -> &str { "AutoFormatExt" } + fn ext_name(&self) -> &str { + "AutoFormatExt" + } fn apply(&self, delta: &RichTextDelta, replace_len: usize, text: &str, index: usize) -> Option { // enter whitespace to trigger auto format @@ -18,7 +20,7 @@ impl InsertExt for AutoFormatExt { let mut iter = DeltaIter::new(delta); if let Some(prev) = iter.next_op_with_len(index) { match AutoFormat::parse(prev.get_data()) { - None => {}, + None => {} Some(formatter) => { let mut new_attributes = prev.get_attributes(); @@ -45,7 +47,7 @@ impl InsertExt for AutoFormatExt { .insert_with_attributes(text, next_attributes) .build(), ); - }, + } } } diff --git a/shared-lib/flowy-collaboration/src/document/extensions/insert/default_insert.rs b/shared-lib/flowy-collaboration/src/document/extensions/insert/default_insert.rs index 5dbeab66cf..c32473ba8f 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/insert/default_insert.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/insert/default_insert.rs @@ -6,7 +6,9 @@ use lib_ot::{ pub struct DefaultInsertAttribute {} impl InsertExt for DefaultInsertAttribute { - fn ext_name(&self) -> &str { "DefaultInsertAttribute" } + fn ext_name(&self) -> &str { + "DefaultInsertAttribute" + } fn apply(&self, delta: &RichTextDelta, replace_len: usize, text: &str, index: usize) -> Option { let iter = DeltaIter::new(delta); @@ -19,12 +21,12 @@ impl InsertExt for DefaultInsertAttribute { // {"insert":"456"},{"insert":"\n","attributes":{"header":1}}] if text.ends_with(NEW_LINE) { match iter.last() { - None => {}, + None => {} Some(op) => { if op.get_attributes().contains_key(&RichTextAttributeKey::Header) { attributes.extend_other(op.get_attributes()); } - }, + } } } diff --git a/shared-lib/flowy-collaboration/src/document/extensions/insert/mod.rs b/shared-lib/flowy-collaboration/src/document/extensions/insert/mod.rs index 6d8bcb7ef8..a60ab75878 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/insert/mod.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/insert/mod.rs @@ -16,7 +16,9 @@ mod reset_format_on_new_line; pub struct InsertEmbedsExt {} impl InsertExt for InsertEmbedsExt { - fn ext_name(&self) -> &str { "InsertEmbedsExt" } + fn ext_name(&self) -> &str { + "InsertEmbedsExt" + } fn apply(&self, _delta: &RichTextDelta, _replace_len: usize, _text: &str, _index: usize) -> Option { None @@ -25,7 +27,9 @@ impl InsertExt for InsertEmbedsExt { pub struct ForceNewlineForInsertsAroundEmbedExt {} impl InsertExt for ForceNewlineForInsertsAroundEmbedExt { - fn ext_name(&self) -> &str { "ForceNewlineForInsertsAroundEmbedExt" } + fn ext_name(&self) -> &str { + "ForceNewlineForInsertsAroundEmbedExt" + } fn apply(&self, _delta: &RichTextDelta, _replace_len: usize, _text: &str, _index: usize) -> Option { None diff --git a/shared-lib/flowy-collaboration/src/document/extensions/insert/preserve_block_format.rs b/shared-lib/flowy-collaboration/src/document/extensions/insert/preserve_block_format.rs index 5df18aef1f..3a7232abef 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/insert/preserve_block_format.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/insert/preserve_block_format.rs @@ -2,18 +2,16 @@ use crate::{document::InsertExt, util::is_newline}; use lib_ot::{ core::{DeltaBuilder, DeltaIter, NEW_LINE}, rich_text::{ - attributes_except_header, - plain_attributes, - RichTextAttribute, - RichTextAttributeKey, - RichTextAttributes, + attributes_except_header, plain_attributes, RichTextAttribute, RichTextAttributeKey, RichTextAttributes, RichTextDelta, }, }; pub struct PreserveBlockFormatOnInsert {} impl InsertExt for PreserveBlockFormatOnInsert { - fn ext_name(&self) -> &str { "PreserveBlockFormatOnInsert" } + fn ext_name(&self) -> &str { + "PreserveBlockFormatOnInsert" + } fn apply(&self, delta: &RichTextDelta, replace_len: usize, text: &str, index: usize) -> Option { if !is_newline(text) { @@ -22,7 +20,7 @@ impl InsertExt for PreserveBlockFormatOnInsert { let mut iter = DeltaIter::from_offset(delta, index); match iter.next_op_with_newline() { - None => {}, + None => {} Some((newline_op, offset)) => { let newline_attributes = newline_op.get_attributes(); let block_attributes = attributes_except_header(&newline_op); @@ -58,7 +56,7 @@ impl InsertExt for PreserveBlockFormatOnInsert { } return Some(new_delta); - }, + } } None diff --git a/shared-lib/flowy-collaboration/src/document/extensions/insert/preserve_inline_format.rs b/shared-lib/flowy-collaboration/src/document/extensions/insert/preserve_inline_format.rs index 672ab6af2d..c216cf4567 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/insert/preserve_inline_format.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/insert/preserve_inline_format.rs @@ -9,7 +9,9 @@ use lib_ot::{ pub struct PreserveInlineFormat {} impl InsertExt for PreserveInlineFormat { - fn ext_name(&self) -> &str { "PreserveInlineFormat" } + fn ext_name(&self) -> &str { + "PreserveInlineFormat" + } fn apply(&self, delta: &RichTextDelta, replace_len: usize, text: &str, index: usize) -> Option { if contain_newline(text) { @@ -36,10 +38,10 @@ impl InsertExt for PreserveInlineFormat { match &next { None => attributes = plain_attributes(), Some(next) => { - if OpNewline::parse(&next).is_equal() { + if OpNewline::parse(next).is_equal() { attributes = plain_attributes(); } - }, + } } let new_delta = DeltaBuilder::new() @@ -53,7 +55,9 @@ impl InsertExt for PreserveInlineFormat { pub struct PreserveLineFormatOnSplit {} impl InsertExt for PreserveLineFormatOnSplit { - fn ext_name(&self) -> &str { "PreserveLineFormatOnSplit" } + fn ext_name(&self) -> &str { + "PreserveLineFormatOnSplit" + } fn apply(&self, delta: &RichTextDelta, replace_len: usize, text: &str, index: usize) -> Option { if !is_newline(text) { @@ -82,10 +86,10 @@ impl InsertExt for PreserveLineFormatOnSplit { } match iter.next_op_with_newline() { - None => {}, + None => {} Some((newline_op, _)) => { new_delta.insert(NEW_LINE, newline_op.get_attributes()); - }, + } } Some(new_delta) diff --git a/shared-lib/flowy-collaboration/src/document/extensions/insert/reset_format_on_new_line.rs b/shared-lib/flowy-collaboration/src/document/extensions/insert/reset_format_on_new_line.rs index c920d6f22b..83e46feed5 100644 --- a/shared-lib/flowy-collaboration/src/document/extensions/insert/reset_format_on_new_line.rs +++ b/shared-lib/flowy-collaboration/src/document/extensions/insert/reset_format_on_new_line.rs @@ -6,7 +6,9 @@ use lib_ot::{ pub struct ResetLineFormatOnNewLine {} impl InsertExt for ResetLineFormatOnNewLine { - fn ext_name(&self) -> &str { "ResetLineFormatOnNewLine" } + fn ext_name(&self) -> &str { + "ResetLineFormatOnNewLine" + } fn apply(&self, delta: &RichTextDelta, replace_len: usize, text: &str, index: usize) -> Option { if !is_newline(text) { diff --git a/shared-lib/flowy-collaboration/src/document/history.rs b/shared-lib/flowy-collaboration/src/document/history.rs index 06aec82252..03414340b5 100644 --- a/shared-lib/flowy-collaboration/src/document/history.rs +++ b/shared-lib/flowy-collaboration/src/document/history.rs @@ -28,15 +28,25 @@ impl std::default::Default for History { } impl History { - pub fn new() -> Self { History::default() } + pub fn new() -> Self { + History::default() + } - pub fn can_undo(&self) -> bool { !self.undoes.is_empty() } + pub fn can_undo(&self) -> bool { + !self.undoes.is_empty() + } - pub fn can_redo(&self) -> bool { !self.redoes.is_empty() } + pub fn can_redo(&self) -> bool { + !self.redoes.is_empty() + } - pub fn add_undo(&mut self, delta: RichTextDelta) { self.undoes.push(delta); } + pub fn add_undo(&mut self, delta: RichTextDelta) { + self.undoes.push(delta); + } - pub fn add_redo(&mut self, delta: RichTextDelta) { self.redoes.push(delta); } + pub fn add_redo(&mut self, delta: RichTextDelta) { + self.redoes.push(delta); + } pub fn record(&mut self, delta: RichTextDelta) { if delta.ops.is_empty() { diff --git a/shared-lib/flowy-collaboration/src/entities/doc.rs b/shared-lib/flowy-collaboration/src/entities/doc.rs index e0479cf329..65332b9fd7 100644 --- a/shared-lib/flowy-collaboration/src/entities/doc.rs +++ b/shared-lib/flowy-collaboration/src/entities/doc.rs @@ -118,7 +118,9 @@ pub struct DocumentId { } impl std::convert::From for DocumentId { - fn from(doc_id: String) -> Self { DocumentId { doc_id } } + fn from(doc_id: String) -> Self { + DocumentId { doc_id } + } } impl std::convert::From<&String> for DocumentId { diff --git a/shared-lib/flowy-collaboration/src/entities/parser/doc_id.rs b/shared-lib/flowy-collaboration/src/entities/parser/doc_id.rs index ad51e31bac..f11d1bba44 100644 --- a/shared-lib/flowy-collaboration/src/entities/parser/doc_id.rs +++ b/shared-lib/flowy-collaboration/src/entities/parser/doc_id.rs @@ -12,5 +12,7 @@ impl DocumentIdentify { } impl AsRef for DocumentIdentify { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-collaboration/src/entities/revision.rs b/shared-lib/flowy-collaboration/src/entities/revision.rs index 8c69e9ff5c..02a4393db9 100644 --- a/shared-lib/flowy-collaboration/src/entities/revision.rs +++ b/shared-lib/flowy-collaboration/src/entities/revision.rs @@ -35,11 +35,17 @@ impl std::convert::From> for Revision { } impl Revision { - pub fn is_empty(&self) -> bool { self.base_rev_id == self.rev_id } + pub fn is_empty(&self) -> bool { + self.base_rev_id == self.rev_id + } - pub fn pair_rev_id(&self) -> (i64, i64) { (self.base_rev_id, self.rev_id) } + pub fn pair_rev_id(&self) -> (i64, i64) { + (self.base_rev_id, self.rev_id) + } - pub fn is_initial(&self) -> bool { self.rev_id == 0 } + pub fn is_initial(&self) -> bool { + self.rev_id == 0 + } pub fn initial_revision(user_id: &str, doc_id: &str, delta_data: Bytes) -> Self { let md5 = md5(&delta_data); @@ -70,7 +76,9 @@ impl Revision { } impl std::convert::From for RepeatedRevision { - fn from(revision: Revision) -> Self { RepeatedRevision { items: vec![revision] } } + fn from(revision: Revision) -> Self { + RepeatedRevision { items: vec![revision] } + } } impl std::fmt::Debug for Revision { @@ -81,10 +89,10 @@ impl std::fmt::Debug for Revision { match RichTextDelta::from_bytes(&self.delta_data) { Ok(delta) => { let _ = f.write_fmt(format_args!("delta {:?}", delta.to_json()))?; - }, + } Err(e) => { let _ = f.write_fmt(format_args!("delta {:?}", e))?; - }, + } } Ok(()) } @@ -99,11 +107,15 @@ pub struct RepeatedRevision { impl std::ops::Deref for RepeatedRevision { type Target = Vec; - fn deref(&self) -> &Self::Target { &self.items } + fn deref(&self) -> &Self::Target { + &self.items + } } impl std::ops::DerefMut for RepeatedRevision { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.items } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.items + } } impl RepeatedRevision { @@ -112,9 +124,13 @@ impl RepeatedRevision { Self { items } } - pub fn empty() -> Self { RepeatedRevision { items: vec![] } } + pub fn empty() -> Self { + RepeatedRevision { items: vec![] } + } - pub fn into_inner(self) -> Vec { self.items } + pub fn into_inner(self) -> Vec { + self.items + } } #[derive(Clone, Debug, ProtoBuf, Default)] @@ -124,19 +140,27 @@ pub struct RevId { } impl AsRef for RevId { - fn as_ref(&self) -> &i64 { &self.value } + fn as_ref(&self) -> &i64 { + &self.value + } } impl std::convert::From for i64 { - fn from(rev_id: RevId) -> Self { rev_id.value } + fn from(rev_id: RevId) -> Self { + rev_id.value + } } impl std::convert::From for RevId { - fn from(value: i64) -> Self { RevId { value } } + fn from(value: i64) -> Self { + RevId { value } + } } impl std::fmt::Display for RevId { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_fmt(format_args!("{}", self.value)) } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("{}", self.value)) + } } #[derive(Debug, Clone, Default, ProtoBuf)] @@ -161,7 +185,9 @@ impl RevisionRange { } } - pub fn is_empty(&self) -> bool { self.end == self.start } + pub fn is_empty(&self) -> bool { + self.end == self.start + } pub fn iter(&self) -> RangeInclusive { debug_assert!(self.start != self.end); @@ -178,19 +204,23 @@ pub fn md5>(data: T) -> String { #[derive(Debug, Clone, Eq, PartialEq)] pub enum RevisionState { Local = 0, - Ack = 1, + Ack = 1, } impl AsRef for RevisionState { - fn as_ref(&self) -> &RevisionState { &self } + fn as_ref(&self) -> &RevisionState { + self + } } #[derive(Debug, ProtoBuf_Enum, Clone, Eq, PartialEq)] pub enum RevType { - DeprecatedLocal = 0, + DeprecatedLocal = 0, DeprecatedRemote = 1, } impl std::default::Default for RevType { - fn default() -> Self { RevType::DeprecatedLocal } + fn default() -> Self { + RevType::DeprecatedLocal + } } diff --git a/shared-lib/flowy-collaboration/src/entities/ws.rs b/shared-lib/flowy-collaboration/src/entities/ws.rs index 0080f7a90b..51d17edf1f 100644 --- a/shared-lib/flowy-collaboration/src/entities/ws.rs +++ b/shared-lib/flowy-collaboration/src/entities/ws.rs @@ -9,7 +9,7 @@ use std::convert::{TryFrom, TryInto}; #[derive(Debug, Clone, ProtoBuf_Enum, Eq, PartialEq, Hash)] pub enum DocumentClientWSDataType { ClientPushRev = 0, - ClientPing = 1, + ClientPing = 1, } impl DocumentClientWSDataType { @@ -22,7 +22,9 @@ impl DocumentClientWSDataType { } impl std::default::Default for DocumentClientWSDataType { - fn default() -> Self { DocumentClientWSDataType::ClientPushRev } + fn default() -> Self { + DocumentClientWSDataType::ClientPushRev + } } #[derive(ProtoBuf, Default, Debug, Clone)] @@ -64,19 +66,23 @@ impl DocumentClientWSData { } } - pub fn id(&self) -> String { self.id.clone() } + pub fn id(&self) -> String { + self.id.clone() + } } #[derive(Debug, Clone, ProtoBuf_Enum, Eq, PartialEq, Hash)] pub enum DocumentServerWSDataType { - ServerAck = 0, + ServerAck = 0, ServerPushRev = 1, ServerPullRev = 2, - UserConnect = 3, + UserConnect = 3, } impl std::default::Default for DocumentServerWSDataType { - fn default() -> Self { DocumentServerWSDataType::ServerPushRev } + fn default() -> Self { + DocumentServerWSDataType::ServerPushRev + } } #[derive(ProtoBuf, Default, Debug, Clone)] diff --git a/shared-lib/flowy-collaboration/src/errors.rs b/shared-lib/flowy-collaboration/src/errors.rs index 88f6a7ab42..bc498e4d70 100644 --- a/shared-lib/flowy-collaboration/src/errors.rs +++ b/shared-lib/flowy-collaboration/src/errors.rs @@ -43,19 +43,21 @@ impl CollaborateError { } impl fmt::Display for CollaborateError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", &self.code, &self.msg) } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}: {}", &self.code, &self.msg) + } } #[derive(Debug, Clone, Display, PartialEq, Eq)] pub enum ErrorCode { - DocIdInvalid = 0, - DocNotfound = 1, - UndoFail = 200, - RedoFail = 201, - OutOfBound = 202, + DocIdInvalid = 0, + DocNotfound = 1, + UndoFail = 200, + RedoFail = 201, + OutOfBound = 202, RevisionConflict = 203, - RecordNotFound = 300, - InternalError = 1000, + RecordNotFound = 300, + InternalError = 1000, } impl std::convert::From for CollaborateError { @@ -65,7 +67,9 @@ impl std::convert::From for CollaborateError { } impl std::convert::From for CollaborateError { - fn from(e: protobuf::ProtobufError) -> Self { CollaborateError::internal().context(e) } + fn from(e: protobuf::ProtobufError) -> Self { + CollaborateError::internal().context(e) + } } pub(crate) fn internal_error(e: T) -> CollaborateError diff --git a/shared-lib/flowy-collaboration/src/sync/server.rs b/shared-lib/flowy-collaboration/src/sync/server.rs index ad30b51070..ef86bb9bc6 100644 --- a/shared-lib/flowy-collaboration/src/sync/server.rs +++ b/shared-lib/flowy-collaboration/src/sync/server.rs @@ -65,11 +65,11 @@ impl ServerDocumentManager { CollaborateError::internal().context(format!("Server crate document failed: {}", e)) })?; Ok(()) - }, + } Some(handler) => { let _ = handler.apply_revisions(user, repeated_revision).await?; Ok(()) - }, + } }; if result.is_ok() { @@ -91,11 +91,11 @@ impl ServerDocumentManager { None => { tracing::trace!("Document:{} doesn't exist, ignore pinging", doc_id); Ok(()) - }, + } Some(handler) => { let _ = handler.apply_ping(rev_id, user).await?; Ok(()) - }, + } } } @@ -109,11 +109,11 @@ impl ServerDocumentManager { None => { tracing::warn!("Document:{} doesn't exist, ignore document reset", doc_id); Ok(()) - }, + } Some(handler) => { let _ = handler.apply_document_reset(repeated_revision).await?; Ok(()) - }, + } } } @@ -129,7 +129,7 @@ impl ServerDocumentManager { write_guard.insert(doc_id.to_owned(), handler.clone()); drop(write_guard); Some(handler) - }, + } Err(_) => None, } } @@ -324,7 +324,7 @@ impl DocumentCommandQueue { .await .map_err(internal_error); let _ = ret.send(result); - }, + } DocumentCommand::Ping { user, persistence, @@ -337,7 +337,7 @@ impl DocumentCommandQueue { .await .map_err(internal_error); let _ = ret.send(result); - }, + } DocumentCommand::Reset { persistence, repeated_revision, @@ -349,7 +349,7 @@ impl DocumentCommandQueue { .await .map_err(internal_error); let _ = ret.send(result); - }, + } } } } diff --git a/shared-lib/flowy-collaboration/src/sync/synchronizer.rs b/shared-lib/flowy-collaboration/src/sync/synchronizer.rs index ff3c884f4b..5e43281ff1 100644 --- a/shared-lib/flowy-collaboration/src/sync/synchronizer.rs +++ b/shared-lib/flowy-collaboration/src/sync/synchronizer.rs @@ -92,11 +92,11 @@ impl RevisionSynchronizer { let msg = DocumentServerWSDataBuilder::build_pull_message(&self.doc_id, range); user.receive(SyncResponse::Pull(msg)); } - }, + } Ordering::Equal => { // Do nothing log::warn!("Applied revision rev_id is the same as cur_rev_id"); - }, + } Ordering::Greater => { // The client document is outdated. Transform the client revision delta and then // send the prime delta to the client. Client should compose the this prime @@ -106,7 +106,7 @@ impl RevisionSynchronizer { let _ = self .push_revisions_to_user(user, persistence, from_rev_id, to_rev_id) .await; - }, + } } Ok(()) } @@ -124,7 +124,7 @@ impl RevisionSynchronizer { match server_rev_id.cmp(&client_rev_id) { Ordering::Less => { tracing::error!("Client should not send ping and the server should pull the revisions from the client") - }, + } Ordering::Equal => tracing::trace!("{} is up to date.", doc_id), Ordering::Greater => { // The client document is outdated. Transform the client revision delta and then @@ -136,7 +136,7 @@ impl RevisionSynchronizer { let _ = self .push_revisions_to_user(user, persistence, from_rev_id, to_rev_id) .await; - }, + } } Ok(()) } @@ -159,7 +159,9 @@ impl RevisionSynchronizer { Ok(()) } - pub fn doc_json(&self) -> String { self.document.read().to_json() } + pub fn doc_json(&self) -> String { + self.document.read().to_json() + } fn compose_revision(&self, revision: &RevisionPB) -> Result<(), CollaborateError> { let delta = RichTextDelta::from_bytes(&revision.delta_data)?; @@ -184,12 +186,14 @@ impl RevisionSynchronizer { None => log::error!("Failed to acquire write lock of document"), Some(mut write_guard) => { let _ = write_guard.compose_delta(delta); - }, + } } Ok(()) } - pub(crate) fn rev_id(&self) -> i64 { self.rev_id.load(SeqCst) } + pub(crate) fn rev_id(&self) -> i64 { + self.rev_id.load(SeqCst) + } async fn is_applied_before(&self, new_revision: &RevisionPB, persistence: &Arc) -> bool { if let Ok(revisions) = persistence.get_revisions(&self.doc_id, vec![new_revision.rev_id]).await { @@ -213,17 +217,13 @@ impl RevisionSynchronizer { let rev_ids: Vec = (from..=to).collect(); let revisions = match persistence.get_revisions(&self.doc_id, rev_ids).await { Ok(revisions) => { - assert_eq!( - revisions.is_empty(), - false, - "revisions should not be empty if the doc exists" - ); + debug_assert!(!revisions.is_empty(), "revisions should not be empty if the doc exists"); revisions - }, + } Err(e) => { tracing::error!("{}", e); vec![] - }, + } }; tracing::debug!("Push revision: {} -> {} to client", from, to); @@ -231,11 +231,13 @@ impl RevisionSynchronizer { Ok(repeated_revision) => { let data = DocumentServerWSDataBuilder::build_push_message(&self.doc_id, repeated_revision); user.receive(SyncResponse::Push(data)); - }, + } Err(e) => tracing::error!("{}", e), } } } #[inline] -fn next(rev_id: i64) -> i64 { rev_id + 1 } +fn next(rev_id: i64) -> i64 { + rev_id + 1 +} diff --git a/shared-lib/flowy-collaboration/src/util.rs b/shared-lib/flowy-collaboration/src/util.rs index f8c43c3ce6..ffa3e9cccd 100644 --- a/shared-lib/flowy-collaboration/src/util.rs +++ b/shared-lib/flowy-collaboration/src/util.rs @@ -13,16 +13,24 @@ use std::{ }; #[inline] -pub fn find_newline(s: &str) -> Option { s.find(NEW_LINE) } +pub fn find_newline(s: &str) -> Option { + s.find(NEW_LINE) +} #[inline] -pub fn is_newline(s: &str) -> bool { s == NEW_LINE } +pub fn is_newline(s: &str) -> bool { + s == NEW_LINE +} #[inline] -pub fn is_whitespace(s: &str) -> bool { s == WHITESPACE } +pub fn is_whitespace(s: &str) -> bool { + s == WHITESPACE +} #[inline] -pub fn contain_newline(s: &str) -> bool { s.contains(NEW_LINE) } +pub fn contain_newline(s: &str) -> bool { + s.contains(NEW_LINE) +} #[inline] pub fn md5>(data: T) -> String { @@ -34,14 +42,20 @@ pub fn md5>(data: T) -> String { pub struct RevIdCounter(pub AtomicI64); impl RevIdCounter { - pub fn new(n: i64) -> Self { Self(AtomicI64::new(n)) } + pub fn new(n: i64) -> Self { + Self(AtomicI64::new(n)) + } pub fn next(&self) -> i64 { let _ = self.0.fetch_add(1, SeqCst); self.value() } - pub fn value(&self) -> i64 { self.0.load(SeqCst) } + pub fn value(&self) -> i64 { + self.0.load(SeqCst) + } - pub fn set(&self, n: i64) { let _ = self.0.fetch_update(SeqCst, SeqCst, |_| Some(n)); } + pub fn set(&self, n: i64) { + let _ = self.0.fetch_update(SeqCst, SeqCst, |_| Some(n)); + } } pub fn make_delta_from_revisions(revisions: Vec) -> CollaborateResult { diff --git a/shared-lib/flowy-core-data-model/src/entities/app/app_create.rs b/shared-lib/flowy-core-data-model/src/entities/app/app_create.rs index e3aeca0050..87c58090aa 100644 --- a/shared-lib/flowy-core-data-model/src/entities/app/app_create.rs +++ b/shared-lib/flowy-core-data-model/src/entities/app/app_create.rs @@ -99,7 +99,9 @@ pub struct App { } impl App { - pub fn take_belongings(&mut self) -> RepeatedView { std::mem::take(&mut self.belongings) } + pub fn take_belongings(&mut self) -> RepeatedView { + std::mem::take(&mut self.belongings) + } } #[derive(PartialEq, Debug, Default, ProtoBuf, Clone)] diff --git a/shared-lib/flowy-core-data-model/src/entities/share/export.rs b/shared-lib/flowy-core-data-model/src/entities/share/export.rs index 88ad942636..5f61468e42 100644 --- a/shared-lib/flowy-core-data-model/src/entities/share/export.rs +++ b/shared-lib/flowy-core-data-model/src/entities/share/export.rs @@ -4,13 +4,15 @@ use std::convert::TryInto; #[derive(PartialEq, Debug, ProtoBuf_Enum, Clone)] pub enum ExportType { - Text = 0, + Text = 0, Markdown = 1, - Link = 2, + Link = 2, } impl std::default::Default for ExportType { - fn default() -> Self { ExportType::Text } + fn default() -> Self { + ExportType::Text + } } impl std::convert::From for ExportType { @@ -22,7 +24,7 @@ impl std::convert::From for ExportType { _ => { log::error!("Invalid export type: {}", val); ExportType::Text - }, + } } } } diff --git a/shared-lib/flowy-core-data-model/src/entities/trash/trash_create.rs b/shared-lib/flowy-core-data-model/src/entities/trash/trash_create.rs index c0c8e2d208..054e715837 100644 --- a/shared-lib/flowy-core-data-model/src/entities/trash/trash_create.rs +++ b/shared-lib/flowy-core-data-model/src/entities/trash/trash_create.rs @@ -5,8 +5,8 @@ use std::fmt::Formatter; #[derive(PartialEq, Debug, ProtoBuf_Enum, Clone)] pub enum TrashType { Unknown = 0, - View = 1, - App = 2, + View = 1, + App = 2, } impl std::convert::TryFrom for TrashType { @@ -23,7 +23,9 @@ impl std::convert::TryFrom for TrashType { } impl std::default::Default for TrashType { - fn default() -> Self { TrashType::Unknown } + fn default() -> Self { + TrashType::Unknown + } } #[derive(PartialEq, ProtoBuf, Default, Debug, Clone)] @@ -95,7 +97,9 @@ impl std::convert::From<&Trash> for TrashId { } impl std::fmt::Display for TrashId { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(&format!("{:?}:{}", self.ty, self.id)) } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(&format!("{:?}:{}", self.ty, self.id)) + } } #[derive(PartialEq, ProtoBuf, Default, Debug, Clone)] diff --git a/shared-lib/flowy-core-data-model/src/entities/view/view_create.rs b/shared-lib/flowy-core-data-model/src/entities/view/view_create.rs index b905fa4fde..84fcdfb1fb 100644 --- a/shared-lib/flowy-core-data-model/src/entities/view/view_create.rs +++ b/shared-lib/flowy-core-data-model/src/entities/view/view_create.rs @@ -14,11 +14,13 @@ use std::convert::TryInto; #[derive(PartialEq, Debug, ProtoBuf_Enum, Clone)] pub enum ViewType { Blank = 0, - Doc = 1, + Doc = 1, } impl std::default::Default for ViewType { - fn default() -> Self { ViewType::Blank } + fn default() -> Self { + ViewType::Blank + } } impl std::convert::From for ViewType { @@ -29,7 +31,7 @@ impl std::convert::From for ViewType { _ => { log::error!("Invalid view type: {}", val); ViewType::Blank - }, + } } } } diff --git a/shared-lib/flowy-core-data-model/src/entities/view/view_query.rs b/shared-lib/flowy-core-data-model/src/entities/view/view_query.rs index 798e057254..797f3ed95c 100644 --- a/shared-lib/flowy-core-data-model/src/entities/view/view_query.rs +++ b/shared-lib/flowy-core-data-model/src/entities/view/view_query.rs @@ -16,7 +16,9 @@ pub struct ViewId { } impl std::convert::From for ViewId { - fn from(view_id: String) -> Self { ViewId { view_id } } + fn from(view_id: String) -> Self { + ViewId { view_id } + } } impl std::convert::From for DocumentId { diff --git a/shared-lib/flowy-core-data-model/src/entities/workspace/workspace_create.rs b/shared-lib/flowy-core-data-model/src/entities/workspace/workspace_create.rs index c03b154e9c..7f051ea948 100644 --- a/shared-lib/flowy-core-data-model/src/entities/workspace/workspace_create.rs +++ b/shared-lib/flowy-core-data-model/src/entities/workspace/workspace_create.rs @@ -61,7 +61,9 @@ pub struct Workspace { } impl Workspace { - pub fn take_apps(&mut self) -> RepeatedApp { std::mem::take(&mut self.apps) } + pub fn take_apps(&mut self) -> RepeatedApp { + std::mem::take(&mut self.apps) + } } #[derive(PartialEq, Debug, Default, ProtoBuf)] pub struct RepeatedWorkspace { diff --git a/shared-lib/flowy-core-data-model/src/entities/workspace/workspace_query.rs b/shared-lib/flowy-core-data-model/src/entities/workspace/workspace_query.rs index 649783c8f0..f4f33c166b 100644 --- a/shared-lib/flowy-core-data-model/src/entities/workspace/workspace_query.rs +++ b/shared-lib/flowy-core-data-model/src/entities/workspace/workspace_query.rs @@ -10,7 +10,9 @@ pub struct QueryWorkspaceRequest { } impl QueryWorkspaceRequest { - pub fn new(workspace_id: Option) -> Self { Self { workspace_id } } + pub fn new(workspace_id: Option) -> Self { + Self { workspace_id } + } } // Read all workspaces if the workspace_id is None @@ -21,7 +23,9 @@ pub struct WorkspaceId { } impl WorkspaceId { - pub fn new(workspace_id: Option) -> Self { Self { workspace_id } } + pub fn new(workspace_id: Option) -> Self { + Self { workspace_id } + } } impl TryInto for QueryWorkspaceRequest { diff --git a/shared-lib/flowy-core-data-model/src/macros.rs b/shared-lib/flowy-core-data-model/src/macros.rs index 05cfe0ac76..34d145ed5c 100644 --- a/shared-lib/flowy-core-data-model/src/macros.rs +++ b/shared-lib/flowy-core-data-model/src/macros.rs @@ -4,15 +4,21 @@ macro_rules! impl_def_and_def_mut { impl std::ops::Deref for $target { type Target = Vec<$item>; - fn deref(&self) -> &Self::Target { &self.items } + fn deref(&self) -> &Self::Target { + &self.items + } } impl std::ops::DerefMut for $target { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.items } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.items + } } impl $target { #[allow(dead_code)] - pub fn into_inner(self) -> Vec<$item> { self.items } + pub fn into_inner(self) -> Vec<$item> { + self.items + } #[allow(dead_code)] pub fn push(&mut self, item: $item) { @@ -24,7 +30,9 @@ macro_rules! impl_def_and_def_mut { self.items.push(item); } - pub fn first_or_crash(&self) -> &$item { self.items.first().unwrap() } + pub fn first_or_crash(&self) -> &$item { + self.items.first().unwrap() + } } }; } diff --git a/shared-lib/flowy-core-data-model/src/parser/app/app_desc.rs b/shared-lib/flowy-core-data-model/src/parser/app/app_desc.rs index c9f827b7d8..047542d809 100644 --- a/shared-lib/flowy-core-data-model/src/parser/app/app_desc.rs +++ b/shared-lib/flowy-core-data-model/src/parser/app/app_desc.rs @@ -13,5 +13,7 @@ impl AppDesc { } impl AsRef for AppDesc { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/app/app_id.rs b/shared-lib/flowy-core-data-model/src/parser/app/app_id.rs index 271dc68424..5b73bffeee 100644 --- a/shared-lib/flowy-core-data-model/src/parser/app/app_id.rs +++ b/shared-lib/flowy-core-data-model/src/parser/app/app_id.rs @@ -14,5 +14,7 @@ impl AppIdentify { } impl AsRef for AppIdentify { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/app/app_name.rs b/shared-lib/flowy-core-data-model/src/parser/app/app_name.rs index 9b954cb44c..9052316724 100644 --- a/shared-lib/flowy-core-data-model/src/parser/app/app_name.rs +++ b/shared-lib/flowy-core-data-model/src/parser/app/app_name.rs @@ -14,5 +14,7 @@ impl AppName { } impl AsRef for AppName { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/trash/trash_id.rs b/shared-lib/flowy-core-data-model/src/parser/trash/trash_id.rs index d26329bd4d..3b1c0646b2 100644 --- a/shared-lib/flowy-core-data-model/src/parser/trash/trash_id.rs +++ b/shared-lib/flowy-core-data-model/src/parser/trash/trash_id.rs @@ -12,7 +12,9 @@ impl TrashIdentify { } impl AsRef for TrashIdentify { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } #[derive(Debug)] diff --git a/shared-lib/flowy-core-data-model/src/parser/view/view_desc.rs b/shared-lib/flowy-core-data-model/src/parser/view/view_desc.rs index cce4989c9e..5b6b0758ad 100644 --- a/shared-lib/flowy-core-data-model/src/parser/view/view_desc.rs +++ b/shared-lib/flowy-core-data-model/src/parser/view/view_desc.rs @@ -15,5 +15,7 @@ impl ViewDesc { } impl AsRef for ViewDesc { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/view/view_id.rs b/shared-lib/flowy-core-data-model/src/parser/view/view_id.rs index 9d495e881b..a9a1fffefc 100644 --- a/shared-lib/flowy-core-data-model/src/parser/view/view_id.rs +++ b/shared-lib/flowy-core-data-model/src/parser/view/view_id.rs @@ -14,5 +14,7 @@ impl ViewIdentify { } impl AsRef for ViewIdentify { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/view/view_name.rs b/shared-lib/flowy-core-data-model/src/parser/view/view_name.rs index f7e2545081..e620dd8baa 100644 --- a/shared-lib/flowy-core-data-model/src/parser/view/view_name.rs +++ b/shared-lib/flowy-core-data-model/src/parser/view/view_name.rs @@ -19,5 +19,7 @@ impl ViewName { } impl AsRef for ViewName { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/view/view_thumbnail.rs b/shared-lib/flowy-core-data-model/src/parser/view/view_thumbnail.rs index 7f18e0e920..93b2153dcc 100644 --- a/shared-lib/flowy-core-data-model/src/parser/view/view_thumbnail.rs +++ b/shared-lib/flowy-core-data-model/src/parser/view/view_thumbnail.rs @@ -15,5 +15,7 @@ impl ViewThumbnail { } impl AsRef for ViewThumbnail { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_desc.rs b/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_desc.rs index 71e47ac124..fa15d1d83e 100644 --- a/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_desc.rs +++ b/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_desc.rs @@ -15,5 +15,7 @@ impl WorkspaceDesc { } impl AsRef for WorkspaceDesc { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_id.rs b/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_id.rs index 7f1e4114ef..3c76e05bf7 100644 --- a/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_id.rs +++ b/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_id.rs @@ -14,5 +14,7 @@ impl WorkspaceIdentify { } impl AsRef for WorkspaceIdentify { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_name.rs b/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_name.rs index 3761e5a346..1a796f0779 100644 --- a/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_name.rs +++ b/shared-lib/flowy-core-data-model/src/parser/workspace/workspace_name.rs @@ -19,5 +19,7 @@ impl WorkspaceName { } impl AsRef for WorkspaceName { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-derive/src/proto_buf/deserialize.rs b/shared-lib/flowy-derive/src/proto_buf/deserialize.rs index 15c53c149d..80b37e3dcd 100644 --- a/shared-lib/flowy-derive/src/proto_buf/deserialize.rs +++ b/shared-lib/flowy-derive/src/proto_buf/deserialize.rs @@ -17,7 +17,7 @@ pub fn make_de_token_steam(ctxt: &Ctxt, ast: &ASTContainer) -> Option Option Option { let member = &field.member; let ident = get_member_ident(ctxt, member)?; - let ty_info = match parse_ty(ctxt, &field.ty) { + let ty_info = match parse_ty(ctxt, field.ty) { Ok(ty_info) => ty_info, Err(e) => { eprintln!("token_stream_for_one_of failed: {:?} with error: {}", member, e); panic!(); - }, + } }?; let bracketed_ty_info = ty_info.bracket_ty_info.as_ref().as_ref(); @@ -69,7 +69,7 @@ fn token_stream_for_one_of(ctxt: &Ctxt, field: &ASTField) -> Option o.#member = Some(enum_de_from_pb); } }) - }, + } TypeCategory::Primitive => { let get_func = format_ident!("get_{}", ident.to_string()); Some(quote! { @@ -77,7 +77,7 @@ fn token_stream_for_one_of(ctxt: &Ctxt, field: &ASTField) -> Option o.#member=Some(pb.#get_func()); } }) - }, + } TypeCategory::Str => { let take_func = format_ident!("take_{}", ident.to_string()); Some(quote! { @@ -85,7 +85,7 @@ fn token_stream_for_one_of(ctxt: &Ctxt, field: &ASTField) -> Option o.#member=Some(pb.#take_func()); } }) - }, + } TypeCategory::Array => { let take_func = format_ident!("take_{}", ident.to_string()); Some(quote! { @@ -93,7 +93,7 @@ fn token_stream_for_one_of(ctxt: &Ctxt, field: &ASTField) -> Option o.#member=Some(pb.#take_func()); } }) - }, + } _ => { let take_func = format_ident!("take_{}", ident.to_string()); let ty = bracketed_ty_info.unwrap().ty; @@ -103,7 +103,7 @@ fn token_stream_for_one_of(ctxt: &Ctxt, field: &ASTField) -> Option o.#member=Some(val); } }) - }, + } } } @@ -114,17 +114,17 @@ fn token_stream_for_field(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type, is_ Err(e) => { eprintln!("token_stream_for_field: {:?} with error: {}", member, e); panic!() - }, + } }?; match ident_category(ty_info.ident) { TypeCategory::Array => { assert_bracket_ty_is_some(ctxt, &ty_info); - token_stream_for_vec(ctxt, &member, &ty_info.bracket_ty_info.unwrap()) - }, + token_stream_for_vec(ctxt, member, &ty_info.bracket_ty_info.unwrap()) + } TypeCategory::Map => { assert_bracket_ty_is_some(ctxt, &ty_info); - token_stream_for_map(ctxt, &member, &ty_info.bracket_ty_info.unwrap()) - }, + token_stream_for_map(ctxt, member, &ty_info.bracket_ty_info.unwrap()) + } TypeCategory::Protobuf => { // if the type wrapped by SingularPtrField, should call take first let take = syn::Ident::new("take", Span::call_site()); @@ -137,7 +137,7 @@ fn token_stream_for_field(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type, is_ o.#member = struct_de_from_pb; } }) - }, + } TypeCategory::Enum => { let ty = ty_info.ty; @@ -146,9 +146,9 @@ fn token_stream_for_field(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type, is_ o.#member = enum_de_from_pb; }) - }, + } TypeCategory::Str => { - let take_ident = syn::Ident::new(&format!("take_{}", ident.to_string()), Span::call_site()); + let take_ident = syn::Ident::new(&format!("take_{}", ident), Span::call_site()); if is_option { Some(quote! { if pb.#member.is_empty() { @@ -162,7 +162,7 @@ fn token_stream_for_field(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type, is_ o.#member = pb.#take_ident(); }) } - }, + } TypeCategory::Opt => token_stream_for_field(ctxt, member, ty_info.bracket_ty_info.unwrap().ty, true), TypeCategory::Primitive | TypeCategory::Bytes => { // eprintln!("😄 #{:?}", &field.name().unwrap()); @@ -171,7 +171,7 @@ fn token_stream_for_field(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type, is_ } else { Some(quote! { o.#member = pb.#member.clone(); }) } - }, + } } } @@ -190,20 +190,20 @@ fn token_stream_for_vec(ctxt: &Ctxt, member: &syn::Member, bracketed_type: &TyIn .map(|mut m| #ty::try_from(&mut m).unwrap()) .collect(); }) - }, + } TypeCategory::Bytes => { // Vec Some(quote! { o.#member = pb.#member.clone(); }) - }, + } _ => { // String let take_ident = format_ident!("take_{}", ident.to_string()); Some(quote! { o.#member = pb.#take_ident().into_vec(); }) - }, + } } } diff --git a/shared-lib/flowy-derive/src/proto_buf/mod.rs b/shared-lib/flowy-derive/src/proto_buf/mod.rs index 31e99262d6..78ea151f72 100644 --- a/shared-lib/flowy-derive/src/proto_buf/mod.rs +++ b/shared-lib/flowy-derive/src/proto_buf/mod.rs @@ -4,9 +4,7 @@ mod serialize; mod util; use crate::proto_buf::{ - deserialize::make_de_token_steam, - enum_serde::make_enum_token_stream, - serialize::make_se_token_stream, + deserialize::make_de_token_steam, enum_serde::make_enum_token_stream, serialize::make_se_token_stream, }; use flowy_ast::*; use proc_macro2::TokenStream; diff --git a/shared-lib/flowy-derive/src/proto_buf/serialize.rs b/shared-lib/flowy-derive/src/proto_buf/serialize.rs index 42f2556209..7d1ce44a45 100644 --- a/shared-lib/flowy-derive/src/proto_buf/serialize.rs +++ b/shared-lib/flowy-derive/src/proto_buf/serialize.rs @@ -1,3 +1,4 @@ +#![allow(clippy::while_let_on_iterator)] use crate::{ derive_cache::TypeCategory, proto_buf::util::{get_member_ident, ident_category}, @@ -13,7 +14,7 @@ pub fn make_se_token_stream(ctxt: &Ctxt, ast: &ASTContainer) -> Option Opti } else if field.attrs.is_one_of() { token_stream_for_one_of(ctxt, field) } else { - gen_token_stream(ctxt, &field.member, &field.ty, false) + gen_token_stream(ctxt, &field.member, field.ty, false) } } fn token_stream_for_one_of(ctxt: &Ctxt, field: &ASTField) -> Option { let member = &field.member; let ident = get_member_ident(ctxt, member)?; - let ty_info = match parse_ty(ctxt, &field.ty) { + let ty_info = match parse_ty(ctxt, field.ty) { Ok(ty_info) => ty_info, Err(e) => { eprintln!("token_stream_for_one_of failed: {:?} with error: {}", member, e); panic!(); - }, + } }?; let bracketed_ty_info = ty_info.bracket_ty_info.as_ref().as_ref(); @@ -88,11 +89,11 @@ fn gen_token_stream(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type, is_option Err(e) => { eprintln!("gen_token_stream failed: {:?} with error: {}", member, e); panic!(); - }, + } }?; match ident_category(ty_info.ident) { - TypeCategory::Array => token_stream_for_vec(ctxt, &member, &ty_info.ty), - TypeCategory::Map => token_stream_for_map(ctxt, &member, &ty_info.bracket_ty_info.unwrap().ty), + TypeCategory::Array => token_stream_for_vec(ctxt, member, ty_info.ty), + TypeCategory::Map => token_stream_for_map(ctxt, member, ty_info.bracket_ty_info.unwrap().ty), TypeCategory::Str => { if is_option { Some(quote! { @@ -104,10 +105,10 @@ fn gen_token_stream(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type, is_option } else { Some(quote! { pb.#member = self.#member.clone(); }) } - }, + } TypeCategory::Protobuf => { Some(quote! { pb.#member = ::protobuf::SingularPtrField::some(self.#member.try_into().unwrap()); }) - }, + } TypeCategory::Opt => gen_token_stream(ctxt, member, ty_info.bracket_ty_info.unwrap().ty, true), TypeCategory::Enum => { // let pb_enum_ident = format_ident!("{}", ty_info.ident.to_string()); @@ -117,7 +118,7 @@ fn gen_token_stream(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type, is_option Some(quote! { pb.#member = self.#member.try_into().unwrap(); }) - }, + } _ => Some(quote! { pb.#member = self.#member; }), } } @@ -129,7 +130,7 @@ fn token_stream_for_vec(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type) -> Op Err(e) => { eprintln!("token_stream_for_vec failed: {:?} with error: {}", member, e); panic!(); - }, + } }?; match ident_category(ty_info.ident) { @@ -157,7 +158,7 @@ fn token_stream_for_map(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type) -> Op Err(e) => { eprintln!("token_stream_for_map failed: {:?} with error: {}", member, e); panic!(); - }, + } }?; match ident_category(ty_info.ident) { TypeCategory::Protobuf => { @@ -169,7 +170,7 @@ fn token_stream_for_map(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type) -> Op }); pb.#member = m; }) - }, + } _ => { let value_type = ty_info.ident; @@ -180,6 +181,6 @@ fn token_stream_for_map(ctxt: &Ctxt, member: &syn::Member, ty: &syn::Type) -> Op }); pb.#member = m; }) - }, + } } } diff --git a/shared-lib/flowy-user-data-model/src/parser/user_email.rs b/shared-lib/flowy-user-data-model/src/parser/user_email.rs index f97eb1ec01..0a3ac03006 100644 --- a/shared-lib/flowy-user-data-model/src/parser/user_email.rs +++ b/shared-lib/flowy-user-data-model/src/parser/user_email.rs @@ -19,7 +19,9 @@ impl UserEmail { } impl AsRef for UserEmail { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } #[cfg(test)] diff --git a/shared-lib/flowy-user-data-model/src/parser/user_id.rs b/shared-lib/flowy-user-data-model/src/parser/user_id.rs index 5e77a78bd2..34e2f64505 100644 --- a/shared-lib/flowy-user-data-model/src/parser/user_id.rs +++ b/shared-lib/flowy-user-data-model/src/parser/user_id.rs @@ -14,5 +14,7 @@ impl UserId { } impl AsRef for UserId { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/flowy-user-data-model/src/parser/user_name.rs b/shared-lib/flowy-user-data-model/src/parser/user_name.rs index 0bc860c5f0..011ef1ef53 100644 --- a/shared-lib/flowy-user-data-model/src/parser/user_name.rs +++ b/shared-lib/flowy-user-data-model/src/parser/user_name.rs @@ -34,7 +34,9 @@ impl UserName { } impl AsRef for UserName { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } #[cfg(test)] diff --git a/shared-lib/flowy-user-data-model/src/parser/user_password.rs b/shared-lib/flowy-user-data-model/src/parser/user_password.rs index f9ea0fe37c..2e23f0399f 100644 --- a/shared-lib/flowy-user-data-model/src/parser/user_password.rs +++ b/shared-lib/flowy-user-data-model/src/parser/user_password.rs @@ -31,7 +31,9 @@ impl UserPassword { } impl AsRef for UserPassword { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } lazy_static! { @@ -57,6 +59,6 @@ pub fn validate_password(password: &str) -> bool { Err(e) => { log::error!("validate_password fail: {:?}", e); false - }, + } } } diff --git a/shared-lib/flowy-user-data-model/src/parser/user_workspace.rs b/shared-lib/flowy-user-data-model/src/parser/user_workspace.rs index 8abbefc22d..3ac78588b5 100644 --- a/shared-lib/flowy-user-data-model/src/parser/user_workspace.rs +++ b/shared-lib/flowy-user-data-model/src/parser/user_workspace.rs @@ -12,5 +12,7 @@ impl UserWorkspace { } impl AsRef for UserWorkspace { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } diff --git a/shared-lib/lib-infra/src/lib.rs b/shared-lib/lib-infra/src/lib.rs index 16e16d08a5..0e4beae90c 100644 --- a/shared-lib/lib-infra/src/lib.rs +++ b/shared-lib/lib-infra/src/lib.rs @@ -2,7 +2,11 @@ pub mod future; pub mod retry; #[allow(dead_code)] -pub fn uuid_string() -> String { uuid::Uuid::new_v4().to_string() } +pub fn uuid_string() -> String { + uuid::Uuid::new_v4().to_string() +} #[allow(dead_code)] -pub fn timestamp() -> i64 { chrono::Utc::now().timestamp() } +pub fn timestamp() -> i64 { + chrono::Utc::now().timestamp() +} diff --git a/shared-lib/lib-infra/src/retry/future.rs b/shared-lib/lib-infra/src/retry/future.rs index 9c59fec620..d22d62044b 100644 --- a/shared-lib/lib-infra/src/retry/future.rs +++ b/shared-lib/lib-infra/src/retry/future.rs @@ -132,7 +132,7 @@ where let future = sleep_until(deadline); self.as_mut().project().state.set(RetryState::Sleeping(future)); Ok(self.poll(cx)) - }, + } } } } @@ -159,7 +159,7 @@ where } else { Poll::Ready(Err(err)) } - }, + } }, RetryFuturePoll::Sleeping(poll_result) => match poll_result { Poll::Pending => Poll::Pending, @@ -190,7 +190,9 @@ pub trait Condition { } impl bool> Condition for F { - fn should_retry(&mut self, error: &E) -> bool { self(error) } + fn should_retry(&mut self, error: &E) -> bool { + self(error) + } } pub fn spawn_retry( diff --git a/shared-lib/lib-infra/src/retry/strategy/fixed_interval.rs b/shared-lib/lib-infra/src/retry/strategy/fixed_interval.rs index 9ec18e584a..a45b749b37 100644 --- a/shared-lib/lib-infra/src/retry/strategy/fixed_interval.rs +++ b/shared-lib/lib-infra/src/retry/strategy/fixed_interval.rs @@ -8,7 +8,9 @@ pub struct FixedInterval { impl FixedInterval { /// Constructs a new fixed interval strategy. - pub fn new(duration: Duration) -> FixedInterval { FixedInterval { duration } } + pub fn new(duration: Duration) -> FixedInterval { + FixedInterval { duration } + } /// Constructs a new fixed interval strategy, /// given a duration in milliseconds. @@ -22,7 +24,9 @@ impl FixedInterval { impl Iterator for FixedInterval { type Item = Duration; - fn next(&mut self) -> Option { Some(self.duration) } + fn next(&mut self) -> Option { + Some(self.duration) + } } #[test] diff --git a/shared-lib/lib-infra/src/retry/strategy/jitter.rs b/shared-lib/lib-infra/src/retry/strategy/jitter.rs index edd1a2697e..c11ae8ed87 100644 --- a/shared-lib/lib-infra/src/retry/strategy/jitter.rs +++ b/shared-lib/lib-infra/src/retry/strategy/jitter.rs @@ -1,3 +1,5 @@ use std::time::Duration; -pub fn jitter(duration: Duration) -> Duration { duration.mul_f64(rand::random::()) } +pub fn jitter(duration: Duration) -> Duration { + duration.mul_f64(rand::random::()) +} diff --git a/shared-lib/lib-ot/src/core/delta/builder.rs b/shared-lib/lib-ot/src/core/delta/builder.rs index 03fcc964ca..b61e81f483 100644 --- a/shared-lib/lib-ot/src/core/delta/builder.rs +++ b/shared-lib/lib-ot/src/core/delta/builder.rs @@ -8,14 +8,18 @@ impl std::default::Default for DeltaBuilder where T: Attributes, { - fn default() -> Self { Self { delta: Delta::new() } } + fn default() -> Self { + Self { delta: Delta::new() } + } } impl DeltaBuilder where T: Attributes, { - pub fn new() -> Self { DeltaBuilder::default() } + pub fn new() -> Self { + DeltaBuilder::default() + } pub fn retain_with_attributes(mut self, n: usize, attrs: T) -> Self { self.delta.retain(n, attrs); @@ -47,5 +51,7 @@ where self } - pub fn build(self) -> Delta { self.delta } + pub fn build(self) -> Delta { + self.delta + } } diff --git a/shared-lib/lib-ot/src/core/delta/cursor.rs b/shared-lib/lib-ot/src/core/delta/cursor.rs index 4efaaaa80f..d6ebb8b3cc 100644 --- a/shared-lib/lib-ot/src/core/delta/cursor.rs +++ b/shared-lib/lib-ot/src/core/delta/cursor.rs @@ -1,3 +1,4 @@ +#![allow(clippy::while_let_on_iterator)] use crate::{ core::{Attributes, Delta, Interval, Operation}, errors::{ErrorBuilder, OTError, OTErrorCode}, @@ -35,9 +36,13 @@ where } // get the next operation interval - pub fn next_iv(&self) -> Interval { self.next_iv_with_len(None).unwrap_or_else(|| Interval::new(0, 0)) } + pub fn next_iv(&self) -> Interval { + self.next_iv_with_len(None).unwrap_or_else(|| Interval::new(0, 0)) + } - pub fn next_op(&mut self) -> Option> { self.next_with_len(None) } + pub fn next_op(&mut self) -> Option> { + self.next_with_len(None) + } // get the last operation before the end. // checkout the delta_next_op_with_len_cross_op_return_last test for more detail @@ -91,7 +96,9 @@ where find_op } - pub fn has_next(&self) -> bool { self.next_iter_op().is_some() } + pub fn has_next(&self) -> bool { + self.next_iter_op().is_some() + } fn descend(&mut self, index: usize) { self.consume_iv.start += index; @@ -151,7 +158,7 @@ where Some((o_index, op)) => { cursor.op_index = o_index; Some(op) - }, + } } } diff --git a/shared-lib/lib-ot/src/core/delta/delta.rs b/shared-lib/lib-ot/src/core/delta/delta.rs index 526b3f5c9d..05631d915b 100644 --- a/shared-lib/lib-ot/src/core/delta/delta.rs +++ b/shared-lib/lib-ot/src/core/delta/delta.rs @@ -66,7 +66,9 @@ impl Delta where T: Attributes, { - pub fn new() -> Self { Self::default() } + pub fn new() -> Self { + Self::default() + } #[inline] pub fn with_capacity(capacity: usize) -> Self { @@ -108,21 +110,21 @@ where [.., Operation::::Insert(insert)] => { // insert.merge_or_new_op(&s, attributes) - }, + } [.., Operation::::Insert(pre_insert), Operation::Delete(_)] => { // pre_insert.merge_or_new_op(&s, attributes) - }, + } [.., op_last @ Operation::::Delete(_)] => { let new_last = op_last.clone(); *op_last = OpBuilder::::insert(&s).attributes(attributes).build(); Some(new_last) - }, + } _ => Some(OpBuilder::::insert(&s).attributes(attributes).build()), }; match new_last { - None => {}, + None => {} Some(new_last) => self.ops.push(new_last), } } @@ -157,15 +159,15 @@ where for c in code_point_iter.take(retain.n as usize) { new_s.push_str(str::from_utf8(c.0).unwrap_or("")); } - }, + } Operation::Delete(delete) => { for _ in 0..*delete { code_point_iter.next(); } - }, + } Operation::Insert(insert) => { new_s += &insert.s; - }, + } } } Ok(new_s) @@ -185,13 +187,13 @@ where for _ in 0..retain.n { chars.next(); } - }, + } Operation::Insert(insert) => { inverted.delete(insert.utf16_size()); - }, + } Operation::Delete(delete) => { inverted.insert(&chars.take(*delete as usize).collect::(), op.get_attributes()); - }, + } } } inverted @@ -199,11 +201,17 @@ where /// Checks if this operation has no effect. #[inline] - pub fn is_noop(&self) -> bool { matches!(self.ops.as_slice(), [] | [Operation::Retain(_)]) } + pub fn is_noop(&self) -> bool { + matches!(self.ops.as_slice(), [] | [Operation::Retain(_)]) + } - pub fn is_empty(&self) -> bool { self.ops.is_empty() } + pub fn is_empty(&self) -> bool { + self.ops.is_empty() + } - pub fn extend(&mut self, other: Self) { other.ops.into_iter().for_each(|op| self.add(op)); } + pub fn extend(&mut self, other: Self) { + other.ops.into_iter().for_each(|op| self.add(op)); + } } impl OperationTransformable for Delta @@ -248,20 +256,20 @@ where let composed_attrs = retain.attributes.compose(&other_retain.attributes)?; new_delta.add(OpBuilder::retain(retain.n).attributes(composed_attrs).build()) - }, + } (Operation::Insert(insert), Operation::Retain(other_retain)) => { let mut composed_attrs = insert.attributes.compose(&other_retain.attributes)?; composed_attrs.remove_empty(); new_delta.add(OpBuilder::insert(op.get_data()).attributes(composed_attrs).build()) - }, + } (Operation::Retain(_), Operation::Delete(_)) => { new_delta.add(other_op); - }, + } (a, b) => { - debug_assert_eq!(a.is_insert(), true); - debug_assert_eq!(b.is_delete(), true); + debug_assert!(a.is_insert()); + debug_assert!(b.is_delete()); continue; - }, + } } } Ok(new_delta) @@ -296,94 +304,94 @@ where a_prime.insert(&insert.s, insert.attributes.clone()); b_prime.retain(insert.utf16_size(), insert.attributes.clone()); next_op1 = ops1.next(); - }, + } (_, Some(Operation::Insert(o_insert))) => { let composed_attrs = transform_op_attribute(&next_op1, &next_op2)?; a_prime.retain(o_insert.utf16_size(), composed_attrs.clone()); b_prime.insert(&o_insert.s, composed_attrs); next_op2 = ops2.next(); - }, + } (None, _) => { return Err(ErrorBuilder::new(OTErrorCode::IncompatibleLength).build()); - }, + } (_, None) => { return Err(ErrorBuilder::new(OTErrorCode::IncompatibleLength).build()); - }, + } (Some(Operation::Retain(retain)), Some(Operation::Retain(o_retain))) => { let composed_attrs = transform_op_attribute(&next_op1, &next_op2)?; - match retain.cmp(&o_retain) { + match retain.cmp(o_retain) { Ordering::Less => { a_prime.retain(retain.n, composed_attrs.clone()); b_prime.retain(retain.n, composed_attrs.clone()); next_op2 = Some(OpBuilder::retain(o_retain.n - retain.n).build()); next_op1 = ops1.next(); - }, + } Ordering::Equal => { a_prime.retain(retain.n, composed_attrs.clone()); b_prime.retain(retain.n, composed_attrs.clone()); next_op1 = ops1.next(); next_op2 = ops2.next(); - }, + } Ordering::Greater => { a_prime.retain(o_retain.n, composed_attrs.clone()); b_prime.retain(o_retain.n, composed_attrs.clone()); next_op1 = Some(OpBuilder::retain(retain.n - o_retain.n).build()); next_op2 = ops2.next(); - }, + } }; - }, - (Some(Operation::Delete(i)), Some(Operation::Delete(j))) => match i.cmp(&j) { + } + (Some(Operation::Delete(i)), Some(Operation::Delete(j))) => match i.cmp(j) { Ordering::Less => { next_op2 = Some(OpBuilder::delete(*j - *i).build()); next_op1 = ops1.next(); - }, + } Ordering::Equal => { next_op1 = ops1.next(); next_op2 = ops2.next(); - }, + } Ordering::Greater => { next_op1 = Some(OpBuilder::delete(*i - *j).build()); next_op2 = ops2.next(); - }, + } }, (Some(Operation::Delete(i)), Some(Operation::Retain(o_retain))) => { - match i.cmp(&o_retain) { + match i.cmp(o_retain) { Ordering::Less => { a_prime.delete(*i); next_op2 = Some(OpBuilder::retain(o_retain.n - *i).build()); next_op1 = ops1.next(); - }, + } Ordering::Equal => { a_prime.delete(*i); next_op1 = ops1.next(); next_op2 = ops2.next(); - }, + } Ordering::Greater => { a_prime.delete(o_retain.n); next_op1 = Some(OpBuilder::delete(*i - o_retain.n).build()); next_op2 = ops2.next(); - }, + } }; - }, + } (Some(Operation::Retain(retain)), Some(Operation::Delete(j))) => { - match retain.cmp(&j) { + match retain.cmp(j) { Ordering::Less => { b_prime.delete(retain.n); next_op2 = Some(OpBuilder::delete(*j - retain.n).build()); next_op1 = ops1.next(); - }, + } Ordering::Equal => { b_prime.delete(retain.n); next_op1 = ops1.next(); next_op2 = ops2.next(); - }, + } Ordering::Greater => { b_prime.delete(*j); next_op1 = Some(OpBuilder::retain(retain.n - *j).build()); next_op2 = ops2.next(); - }, + } }; - }, + } } } Ok((a_prime, b_prime)) @@ -402,7 +410,7 @@ where Operation::Delete(n) => { invert_from_other(&mut inverted, other, op, index, index + *n); index += len; - }, + } Operation::Retain(_) => { match op.has_attribute() { true => invert_from_other(&mut inverted, other, op, index, index + len), @@ -410,14 +418,14 @@ where // tracing::trace!("invert retain: {} by retain {} {}", op, len, // op.get_attributes()); inverted.retain(len as usize, op.get_attributes()) - }, + } } index += len; - }, + } Operation::Insert(_) => { // tracing::trace!("invert insert: {} by delete {}", op, len); inverted.delete(len as usize); - }, + } } } inverted @@ -449,7 +457,7 @@ fn invert_from_other( Operation::Delete(n) => { tracing::trace!("invert delete: {} by add {}", n, other_op); base.add(other_op); - }, + } Operation::Retain(_retain) => { tracing::trace!( "invert attributes: {:?}, {:?}", @@ -458,10 +466,10 @@ fn invert_from_other( ); let inverted_attrs = operation.get_attributes().invert(&other_op.get_attributes()); base.retain(other_op.len(), inverted_attrs); - }, + } Operation::Insert(_) => { log::error!("Impossible to here. Insert operation should be treated as delete") - }, + } }); } @@ -505,7 +513,9 @@ impl Delta where T: Attributes + serde::Serialize, { - pub fn to_json(&self) -> String { serde_json::to_string(self).unwrap_or_else(|_| "".to_owned()) } + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_else(|_| "".to_owned()) + } pub fn to_bytes(&self) -> Bytes { let json = self.to_json(); @@ -531,7 +541,9 @@ where T: Attributes + DeserializeOwned, { type Error = OTError; - fn try_from(bytes: Vec) -> Result { Delta::from_bytes(bytes) } + fn try_from(bytes: Vec) -> Result { + Delta::from_bytes(bytes) + } } impl std::convert::TryFrom for Delta @@ -540,5 +552,7 @@ where { type Error = OTError; - fn try_from(bytes: Bytes) -> Result { Delta::from_bytes(&bytes) } + fn try_from(bytes: Bytes) -> Result { + Delta::from_bytes(&bytes) + } } diff --git a/shared-lib/lib-ot/src/core/delta/delta_serde.rs b/shared-lib/lib-ot/src/core/delta/delta_serde.rs index 51045fc764..ceac31ee58 100644 --- a/shared-lib/lib-ot/src/core/delta/delta_serde.rs +++ b/shared-lib/lib-ot/src/core/delta/delta_serde.rs @@ -2,10 +2,7 @@ use crate::core::{Attributes, Delta}; use serde::{ de::{SeqAccess, Visitor}, ser::SerializeSeq, - Deserialize, - Deserializer, - Serialize, - Serializer, + Deserialize, Deserializer, Serialize, Serializer, }; use std::{fmt, marker::PhantomData}; @@ -41,7 +38,9 @@ where { type Value = Delta; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a sequence") } + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } #[inline] fn visit_seq(self, mut seq: A) -> Result diff --git a/shared-lib/lib-ot/src/core/delta/iterator.rs b/shared-lib/lib-ot/src/core/delta/iterator.rs index 363d8c1e86..ccad56845d 100644 --- a/shared-lib/lib-ot/src/core/delta/iterator.rs +++ b/shared-lib/lib-ot/src/core/delta/iterator.rs @@ -32,7 +32,9 @@ where Self { cursor } } - pub fn ops(&mut self) -> Vec> { self.collect::>() } + pub fn ops(&mut self) -> Vec> { + self.collect::>() + } pub fn next_op_len(&self) -> Option { let interval = self.cursor.next_iv(); @@ -43,9 +45,13 @@ where } } - pub fn next_op(&mut self) -> Option> { self.cursor.next_op() } + pub fn next_op(&mut self) -> Option> { + self.cursor.next_op() + } - pub fn next_op_with_len(&mut self, len: usize) -> Option> { self.cursor.next_with_len(Some(len)) } + pub fn next_op_with_len(&mut self, len: usize) -> Option> { + self.cursor.next_with_len(Some(len)) + } // find next op contains NEW_LINE pub fn next_op_with_newline(&mut self) -> Option<(Operation, usize)> { @@ -64,12 +70,14 @@ where pub fn seek(&mut self, index: usize) { match M::seek(&mut self.cursor, index) { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("Seek fail: {:?}", e), } } - pub fn has_next(&self) -> bool { self.cursor.has_next() } + pub fn has_next(&self) -> bool { + self.cursor.has_next() + } pub fn is_next_insert(&self) -> bool { match self.cursor.next_iter_op() { @@ -98,7 +106,9 @@ where T: Attributes, { type Item = Operation; - fn next(&mut self) -> Option { self.next_op() } + fn next(&mut self) -> Option { + self.next_op() + } } pub fn is_empty_line_at_index(delta: &Delta, index: usize) -> bool { @@ -149,14 +159,18 @@ where { type Target = DeltaIter<'a, T>; - fn deref(&self) -> &Self::Target { &self.delta_iter } + fn deref(&self) -> &Self::Target { + &self.delta_iter + } } impl<'a, T> DerefMut for AttributesIter<'a, T> where T: Attributes, { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.delta_iter } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.delta_iter + } } impl<'a, T> Iterator for AttributesIter<'a, T> @@ -171,18 +185,18 @@ where let mut attributes = T::default(); match next_op.unwrap() { - Operation::::Delete(_n) => {}, + Operation::::Delete(_n) => {} Operation::::Retain(retain) => { tracing::trace!("extend retain attributes with {} ", &retain.attributes); attributes.extend_other(retain.attributes.clone()); length = retain.n; - }, + } Operation::::Insert(insert) => { tracing::trace!("extend insert attributes with {} ", &insert.attributes); attributes.extend_other(insert.attributes.clone()); length = insert.utf16_size(); - }, + } } Some((length, attributes)) @@ -221,15 +235,23 @@ impl OpNewline { OpNewline::NotFound } - pub fn is_start(&self) -> bool { self == &OpNewline::Start || self.is_equal() } + pub fn is_start(&self) -> bool { + self == &OpNewline::Start || self.is_equal() + } - pub fn is_end(&self) -> bool { self == &OpNewline::End || self.is_equal() } + pub fn is_end(&self) -> bool { + self == &OpNewline::End || self.is_equal() + } - pub fn is_not_found(&self) -> bool { self == &OpNewline::NotFound } + pub fn is_not_found(&self) -> bool { + self == &OpNewline::NotFound + } pub fn is_contain(&self) -> bool { self.is_start() || self.is_end() || self.is_equal() || self == &OpNewline::Contain } - pub fn is_equal(&self) -> bool { self == &OpNewline::Equal } + pub fn is_equal(&self) -> bool { + self == &OpNewline::Equal + } } diff --git a/shared-lib/lib-ot/src/core/flowy_str.rs b/shared-lib/lib-ot/src/core/flowy_str.rs index 3dab8ac528..95cc1735cc 100644 --- a/shared-lib/lib-ot/src/core/flowy_str.rs +++ b/shared-lib/lib-ot/src/core/flowy_str.rs @@ -6,9 +6,13 @@ pub struct FlowyStr(pub String); impl FlowyStr { // https://stackoverflow.com/questions/2241348/what-is-unicode-utf-8-utf-16 - pub fn utf16_size(&self) -> usize { count_utf16_code_units(&self.0) } + pub fn utf16_size(&self) -> usize { + count_utf16_code_units(&self.0) + } - pub fn utf16_code_unit_iter(&self) -> Utf16CodeUnitIterator { Utf16CodeUnitIterator::new(self) } + pub fn utf16_code_unit_iter(&self) -> Utf16CodeUnitIterator { + Utf16CodeUnitIterator::new(self) + } pub fn sub_str(&self, interval: Interval) -> Option { let mut iter = Utf16CodeUnitIterator::new(self); @@ -30,29 +34,41 @@ impl FlowyStr { } #[allow(dead_code)] - fn utf16_code_point_iter(&self) -> FlowyUtf16CodePointIterator { FlowyUtf16CodePointIterator::new(self, 0) } + fn utf16_code_point_iter(&self) -> FlowyUtf16CodePointIterator { + FlowyUtf16CodePointIterator::new(self, 0) + } } impl std::ops::Deref for FlowyStr { type Target = String; - fn deref(&self) -> &Self::Target { &self.0 } + fn deref(&self) -> &Self::Target { + &self.0 + } } impl std::ops::DerefMut for FlowyStr { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } } impl std::convert::From for FlowyStr { - fn from(s: String) -> Self { FlowyStr(s) } + fn from(s: String) -> Self { + FlowyStr(s) + } } impl std::convert::From<&str> for FlowyStr { - fn from(s: &str) -> Self { s.to_owned().into() } + fn from(s: &str) -> Self { + s.to_owned().into() + } } impl std::fmt::Display for FlowyStr { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } } impl std::ops::Add<&str> for FlowyStr { @@ -65,7 +81,9 @@ impl std::ops::Add<&str> for FlowyStr { } impl std::ops::AddAssign<&str> for FlowyStr { - fn add_assign(&mut self, rhs: &str) { self.0 += rhs; } + fn add_assign(&mut self, rhs: &str) { + self.0 += rhs; + } } impl Serialize for FlowyStr { @@ -87,7 +105,9 @@ impl<'de> Deserialize<'de> for FlowyStr { impl<'de> Visitor<'de> for FlowyStrVisitor { type Value = FlowyStr; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a str") } + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a str") + } fn visit_str(self, s: &str) -> Result where @@ -152,7 +172,9 @@ pub struct FlowyUtf16CodePointIterator<'a> { } impl<'a> FlowyUtf16CodePointIterator<'a> { - pub fn new(s: &'a FlowyStr, offset: usize) -> Self { FlowyUtf16CodePointIterator { s, offset } } + pub fn new(s: &'a FlowyStr, offset: usize) -> Self { + FlowyUtf16CodePointIterator { s, offset } + } } use crate::core::Interval; diff --git a/shared-lib/lib-ot/src/core/interval.rs b/shared-lib/lib-ot/src/core/interval.rs index d07260376c..a6f3131b6a 100644 --- a/shared-lib/lib-ot/src/core/interval.rs +++ b/shared-lib/lib-ot/src/core/interval.rs @@ -23,23 +23,37 @@ impl Interval { Interval { start, end } } - pub fn start(&self) -> usize { self.start } + pub fn start(&self) -> usize { + self.start + } - pub fn end(&self) -> usize { self.end } + pub fn end(&self) -> usize { + self.end + } - pub fn start_end(&self) -> (usize, usize) { (self.start, self.end) } + pub fn start_end(&self) -> (usize, usize) { + (self.start, self.end) + } - pub fn is_before(&self, val: usize) -> bool { self.end <= val } + pub fn is_before(&self, val: usize) -> bool { + self.end <= val + } - pub fn contains(&self, val: usize) -> bool { self.start <= val && val < self.end } + pub fn contains(&self, val: usize) -> bool { + self.start <= val && val < self.end + } pub fn contains_range(&self, start: usize, end: usize) -> bool { !self.intersect(Interval::new(start, end)).is_empty() } - pub fn is_after(&self, val: usize) -> bool { self.start > val } + pub fn is_after(&self, val: usize) -> bool { + self.start > val + } - pub fn is_empty(&self) -> bool { self.end <= self.start } + pub fn is_empty(&self) -> bool { + self.end <= self.start + } pub fn intersect(&self, other: Interval) -> Interval { let start = max(self.start, other.start); @@ -93,19 +107,27 @@ impl Interval { Interval { start, end } } - pub fn size(&self) -> usize { self.end - self.start } + pub fn size(&self) -> usize { + self.end - self.start + } } impl std::default::Default for Interval { - fn default() -> Self { Interval::new(0, 0) } + fn default() -> Self { + Interval::new(0, 0) + } } impl fmt::Display for Interval { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}, {})", self.start(), self.end()) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "[{}, {})", self.start(), self.end()) + } } impl fmt::Debug for Interval { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } } impl From> for Interval { @@ -116,15 +138,21 @@ impl From> for Interval { } impl From> for Interval { - fn from(src: RangeTo) -> Interval { Interval::new(0, src.end) } + fn from(src: RangeTo) -> Interval { + Interval::new(0, src.end) + } } impl From> for Interval { - fn from(src: RangeInclusive) -> Interval { Interval::new(*src.start(), src.end().saturating_add(1)) } + fn from(src: RangeInclusive) -> Interval { + Interval::new(*src.start(), src.end().saturating_add(1)) + } } impl From> for Interval { - fn from(src: RangeToInclusive) -> Interval { Interval::new(0, src.end.saturating_add(1)) } + fn from(src: RangeToInclusive) -> Interval { + Interval::new(0, src.end.saturating_add(1)) + } } #[cfg(test)] diff --git a/shared-lib/lib-ot/src/core/operation/builder.rs b/shared-lib/lib-ot/src/core/operation/builder.rs index efd63c2bff..7c79192b48 100644 --- a/shared-lib/lib-ot/src/core/operation/builder.rs +++ b/shared-lib/lib-ot/src/core/operation/builder.rs @@ -21,11 +21,17 @@ where } } - pub fn retain(n: usize) -> OpBuilder { OpBuilder::new(Operation::Retain(n.into())) } + pub fn retain(n: usize) -> OpBuilder { + OpBuilder::new(Operation::Retain(n.into())) + } - pub fn delete(n: usize) -> OpBuilder { OpBuilder::new(Operation::Delete(n)) } + pub fn delete(n: usize) -> OpBuilder { + OpBuilder::new(Operation::Delete(n)) + } - pub fn insert(s: &str) -> OpBuilder { OpBuilder::new(Operation::Insert(s.into())) } + pub fn insert(s: &str) -> OpBuilder { + OpBuilder::new(Operation::Insert(s.into())) + } pub fn attributes(mut self, attrs: T) -> OpBuilder { self.attrs = attrs; @@ -35,7 +41,7 @@ where pub fn build(self) -> Operation { let mut operation = self.ty; match &mut operation { - Operation::Delete(_) => {}, + Operation::Delete(_) => {} Operation::Retain(retain) => retain.attributes = self.attrs, Operation::Insert(insert) => insert.attributes = self.attrs, } diff --git a/shared-lib/lib-ot/src/core/operation/operation.rs b/shared-lib/lib-ot/src/core/operation/operation.rs index d13996ff41..7ff64d6f29 100644 --- a/shared-lib/lib-ot/src/core/operation/operation.rs +++ b/shared-lib/lib-ot/src/core/operation/operation.rs @@ -61,7 +61,9 @@ where } } - pub fn has_attribute(&self) -> bool { !self.get_attributes().is_empty() } + pub fn has_attribute(&self) -> bool { + !self.get_attributes().is_empty() + } pub fn len(&self) -> usize { match self { @@ -71,7 +73,9 @@ where } } - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } #[allow(dead_code)] pub fn split(&self, index: usize) -> (Option>, Option>) { @@ -82,11 +86,11 @@ where Operation::Delete(n) => { left = Some(OpBuilder::::delete(index).build()); right = Some(OpBuilder::::delete(*n - index).build()); - }, + } Operation::Retain(retain) => { left = Some(OpBuilder::::delete(index).build()); right = Some(OpBuilder::::delete(retain.n - index).build()); - }, + } Operation::Insert(insert) => { let attributes = self.get_attributes(); left = Some( @@ -99,7 +103,7 @@ where .attributes(attributes) .build(), ); - }, + } } (left, right) @@ -118,7 +122,7 @@ where let s = insert.s.sub_str(interval).unwrap_or_else(|| "".to_owned()); OpBuilder::insert(&s).attributes(insert.attributes.clone()).build() } - }, + } }; match op.is_empty() { @@ -166,13 +170,13 @@ where match self { Operation::Delete(n) => { f.write_fmt(format_args!("delete: {}", n))?; - }, + } Operation::Retain(r) => { f.write_fmt(format_args!("{}", r))?; - }, + } Operation::Insert(i) => { f.write_fmt(format_args!("{}", i))?; - }, + } } f.write_str("}")?; Ok(()) @@ -219,7 +223,9 @@ where } } - pub fn is_plain(&self) -> bool { self.attributes.is_empty() } + pub fn is_plain(&self) -> bool { + self.attributes.is_empty() + } } impl std::convert::From for Retain @@ -240,14 +246,18 @@ where { type Target = usize; - fn deref(&self) -> &Self::Target { &self.n } + fn deref(&self) -> &Self::Target { + &self.n + } } impl DerefMut for Retain where T: Attributes, { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.n } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.n + } } #[derive(Clone, Debug, Eq, PartialEq)] @@ -284,7 +294,9 @@ impl Insert where T: Attributes, { - pub fn utf16_size(&self) -> usize { self.s.utf16_size() } + pub fn utf16_size(&self) -> usize { + self.s.utf16_size() + } pub fn merge_or_new_op(&mut self, s: &str, attributes: T) -> Option> { if self.attributes == attributes { @@ -295,7 +307,9 @@ where } } - pub fn is_plain(&self) -> bool { self.attributes.is_empty() } + pub fn is_plain(&self) -> bool { + self.attributes.is_empty() + } } impl std::convert::From for Insert @@ -314,7 +328,9 @@ impl std::convert::From<&str> for Insert where T: Attributes, { - fn from(s: &str) -> Self { Insert::from(s.to_owned()) } + fn from(s: &str) -> Self { + Insert::from(s.to_owned()) + } } impl std::convert::From for Insert diff --git a/shared-lib/lib-ot/src/core/operation/operation_serde.rs b/shared-lib/lib-ot/src/core/operation/operation_serde.rs index 7f8391281e..aefb909d0a 100644 --- a/shared-lib/lib-ot/src/core/operation/operation_serde.rs +++ b/shared-lib/lib-ot/src/core/operation/operation_serde.rs @@ -3,10 +3,7 @@ use serde::{ de, de::{MapAccess, SeqAccess, Visitor}, ser::SerializeMap, - Deserialize, - Deserializer, - Serialize, - Serializer, + Deserialize, Deserializer, Serialize, Serializer, }; use std::{fmt, marker::PhantomData}; @@ -24,7 +21,7 @@ where let mut map = serializer.serialize_map(Some(1))?; map.serialize_entry("delete", i)?; map.end() - }, + } Operation::Insert(insert) => insert.serialize(serializer), } } @@ -64,28 +61,28 @@ where return Err(de::Error::duplicate_field("operation")); } operation = Some(Operation::::Delete(map.next_value()?)); - }, + } "retain" => { if operation.is_some() { return Err(de::Error::duplicate_field("operation")); } let i: usize = map.next_value()?; operation = Some(Operation::::Retain(i.into())); - }, + } "insert" => { if operation.is_some() { return Err(de::Error::duplicate_field("operation")); } let i: String = map.next_value()?; operation = Some(Operation::::Insert(i.into())); - }, + } "attributes" => { if attributes.is_some() { return Err(de::Error::duplicate_field("attributes")); } let map: T = map.next_value()?; attributes = Some(map); - }, + } _ => panic!(), } } @@ -96,7 +93,7 @@ where operation.set_attributes(attributes.unwrap_or_default()); } Ok(operation) - }, + } } } } @@ -139,7 +136,9 @@ where { type Value = Retain; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct Retain") } + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct Retain") + } #[inline] fn visit_seq(self, mut seq: A) -> Result @@ -150,14 +149,14 @@ where Some(val) => val, None => { return Err(de::Error::invalid_length(0, &"struct Retain with 2 elements")); - }, + } }; let attributes = match serde::de::SeqAccess::next_element::(&mut seq)? { Some(val) => val, None => { return Err(de::Error::invalid_length(1, &"struct Retain with 2 elements")); - }, + } }; Ok(Retain:: { n: len, attributes }) @@ -177,13 +176,13 @@ where return Err(de::Error::duplicate_field("retain")); } len = Some(map.next_value()?); - }, + } "attributes" => { if attributes.is_some() { return Err(de::Error::duplicate_field("attributes")); } attributes = Some(map.next_value()?); - }, + } _ => panic!(), } } @@ -240,7 +239,9 @@ where { type Value = Insert; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct Insert") } + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct Insert") + } #[inline] fn visit_seq(self, mut seq: A) -> Result @@ -251,14 +252,14 @@ where Some(val) => val, None => { return Err(de::Error::invalid_length(0, &"struct Insert with 2 elements")); - }, + } }; let attributes = match serde::de::SeqAccess::next_element::(&mut seq)? { Some(val) => val, None => { return Err(de::Error::invalid_length(1, &"struct Retain with 2 elements")); - }, + } }; Ok(Insert:: { s, attributes }) @@ -278,13 +279,13 @@ where return Err(de::Error::duplicate_field("insert")); } s = Some(map.next_value()?); - }, + } "attributes" => { if attributes.is_some() { return Err(de::Error::duplicate_field("attributes")); } attributes = Some(map.next_value()?); - }, + } _ => panic!(), } } diff --git a/shared-lib/lib-ot/src/errors.rs b/shared-lib/lib-ot/src/errors.rs index 31eaf7fc97..e7aea28bcf 100644 --- a/shared-lib/lib-ot/src/errors.rs +++ b/shared-lib/lib-ot/src/errors.rs @@ -9,7 +9,9 @@ pub struct OTError { macro_rules! static_ot_error { ($name:ident, $code:expr) => { #[allow(non_snake_case, missing_docs)] - pub fn $name() -> OTError { $code.into() } + pub fn $name() -> OTError { + $code.into() + } }; } @@ -41,15 +43,21 @@ impl OTError { } impl fmt::Display for OTError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "incompatible lengths") } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "incompatible lengths") + } } impl std::convert::From for OTError { - fn from(error: serde_json::Error) -> Self { ErrorBuilder::new(OTErrorCode::SerdeError).error(error).build() } + fn from(error: serde_json::Error) -> Self { + ErrorBuilder::new(OTErrorCode::SerdeError).error(error).build() + } } impl std::convert::From for OTError { - fn from(error: Utf8Error) -> Self { ErrorBuilder::new(OTErrorCode::SerdeError).error(error).build() } + fn from(error: Utf8Error) -> Self { + ErrorBuilder::new(OTErrorCode::SerdeError).error(error).build() + } } #[derive(Debug, Clone)] @@ -74,7 +82,9 @@ pub struct ErrorBuilder { } impl ErrorBuilder { - pub fn new(code: OTErrorCode) -> Self { ErrorBuilder { code, msg: None } } + pub fn new(code: OTErrorCode) -> Self { + ErrorBuilder { code, msg: None } + } pub fn msg(mut self, msg: T) -> Self where @@ -92,5 +102,7 @@ impl ErrorBuilder { self } - pub fn build(mut self) -> OTError { OTError::new(self.code, &self.msg.take().unwrap_or_else(|| "".to_owned())) } + pub fn build(mut self) -> OTError { + OTError::new(self.code, &self.msg.take().unwrap_or_else(|| "".to_owned())) + } } diff --git a/shared-lib/lib-ot/src/rich_text/attributes.rs b/shared-lib/lib-ot/src/rich_text/attributes.rs index 5af66a817a..f2eb5d80e3 100644 --- a/shared-lib/lib-ot/src/rich_text/attributes.rs +++ b/shared-lib/lib-ot/src/rich_text/attributes.rs @@ -3,9 +3,7 @@ use crate::{ block_attribute, core::{Attributes, OperationTransformable, RichTextOperation}, errors::OTError, - ignore_attribute, - inline_attribute, - list_attribute, + ignore_attribute, inline_attribute, list_attribute, }; use lazy_static::lazy_static; use std::{ @@ -30,15 +28,23 @@ impl std::default::Default for RichTextAttributes { } impl fmt::Display for RichTextAttributes { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!("{:?}", self.inner)) } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_fmt(format_args!("{:?}", self.inner)) + } } -pub fn plain_attributes() -> RichTextAttributes { RichTextAttributes::default() } +pub fn plain_attributes() -> RichTextAttributes { + RichTextAttributes::default() +} impl RichTextAttributes { - pub fn new() -> Self { RichTextAttributes { inner: HashMap::new() } } + pub fn new() -> Self { + RichTextAttributes { inner: HashMap::new() } + } - pub fn is_empty(&self) -> bool { self.inner.is_empty() } + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } pub fn add(&mut self, attribute: RichTextAttribute) { let RichTextAttribute { key, value, scope: _ } = attribute; @@ -57,18 +63,20 @@ impl RichTextAttributes { match attribute { None => { self.inner.iter_mut().for_each(|(_k, v)| v.0 = None); - }, + } Some(attribute) => { self.inner.iter_mut().for_each(|(k, v)| { if k != &attribute { v.0 = None; } }); - }, + } } } - pub fn remove(&mut self, key: RichTextAttributeKey) { self.inner.retain(|k, _| k != &key); } + pub fn remove(&mut self, key: RichTextAttributeKey) { + self.inner.retain(|k, _| k != &key); + } // pub fn block_attributes_except_header(attributes: &Attributes) -> Attributes // { let mut new_attributes = Attributes::new(); @@ -97,11 +105,17 @@ impl RichTextAttributes { } impl Attributes for RichTextAttributes { - fn is_empty(&self) -> bool { self.inner.is_empty() } + fn is_empty(&self) -> bool { + self.inner.is_empty() + } - fn remove_empty(&mut self) { self.inner.retain(|_, v| v.0.is_some()); } + fn remove_empty(&mut self) { + self.inner.retain(|_, v| v.0.is_some()); + } - fn extend_other(&mut self, other: Self) { self.inner.extend(other.inner); } + fn extend_other(&mut self, other: Self) { + self.inner.extend(other.inner); + } } impl OperationTransformable for RichTextAttributes { @@ -161,11 +175,15 @@ impl OperationTransformable for RichTextAttributes { impl std::ops::Deref for RichTextAttributes { type Target = HashMap; - fn deref(&self) -> &Self::Target { &self.inner } + fn deref(&self) -> &Self::Target { + &self.inner + } } impl std::ops::DerefMut for RichTextAttributes { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } } pub fn attributes_except_header(op: &RichTextOperation) -> RichTextAttributes { @@ -218,7 +236,7 @@ impl RichTextAttribute { Err(e) => { log::error!("Attribute serialize to str failed: {}", e); "".to_owned() - }, + } } } } @@ -285,7 +303,9 @@ pub enum RichTextAttributeKey { pub struct RichTextAttributeValue(pub Option); impl std::convert::From<&usize> for RichTextAttributeValue { - fn from(val: &usize) -> Self { RichTextAttributeValue::from(*val) } + fn from(val: &usize) -> Self { + RichTextAttributeValue::from(*val) + } } impl std::convert::From for RichTextAttributeValue { @@ -299,7 +319,9 @@ impl std::convert::From for RichTextAttributeValue { } impl std::convert::From<&str> for RichTextAttributeValue { - fn from(val: &str) -> Self { val.to_owned().into() } + fn from(val: &str) -> Self { + val.to_owned().into() + } } impl std::convert::From for RichTextAttributeValue { @@ -313,7 +335,9 @@ impl std::convert::From for RichTextAttributeValue { } impl std::convert::From<&bool> for RichTextAttributeValue { - fn from(val: &bool) -> Self { RichTextAttributeValue::from(*val) } + fn from(val: &bool) -> Self { + RichTextAttributeValue::from(*val) + } } impl std::convert::From for RichTextAttributeValue { diff --git a/shared-lib/lib-ot/src/rich_text/attributes_serde.rs b/shared-lib/lib-ot/src/rich_text/attributes_serde.rs index 87506ecd99..5126f722e1 100644 --- a/shared-lib/lib-ot/src/rich_text/attributes_serde.rs +++ b/shared-lib/lib-ot/src/rich_text/attributes_serde.rs @@ -4,10 +4,7 @@ use serde::{ de, de::{MapAccess, Visitor}, ser::SerializeMap, - Deserialize, - Deserializer, - Serialize, - Serializer, + Deserialize, Deserializer, Serialize, Serializer, }; use std::fmt; @@ -77,7 +74,7 @@ where | RichTextAttributeKey::Align | RichTextAttributeKey::List => { map_serializer.serialize_entry(&key, v)?; - }, + } } } else { map_serializer.serialize_entry(&key, "")?; @@ -93,7 +90,9 @@ impl<'de> Deserialize<'de> for RichTextAttributes { struct AttributesVisitor; impl<'de> Visitor<'de> for AttributesVisitor { type Value = RichTextAttributes; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("Expect map") } + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Expect map") + } fn visit_map(self, mut map: A) -> Result where diff --git a/shared-lib/lib-ot/src/rich_text/builder.rs b/shared-lib/lib-ot/src/rich_text/builder.rs index 40d9666d1d..84f3f09cfe 100644 --- a/shared-lib/lib-ot/src/rich_text/builder.rs +++ b/shared-lib/lib-ot/src/rich_text/builder.rs @@ -1,4 +1,5 @@ #![allow(non_snake_case)] +#![allow(clippy::derivable_impls)] use crate::rich_text::{RichTextAttribute, RichTextAttributes}; pub struct AttributeBuilder { @@ -14,12 +15,16 @@ impl std::default::Default for AttributeBuilder { } impl AttributeBuilder { - pub fn new() -> Self { AttributeBuilder::default() } + pub fn new() -> Self { + AttributeBuilder::default() + } pub fn add_attr(mut self, attribute: RichTextAttribute) -> Self { self.inner.add(attribute); self } - pub fn build(self) -> RichTextAttributes { self.inner } + pub fn build(self) -> RichTextAttributes { + self.inner + } } diff --git a/shared-lib/lib-ws/src/connect.rs b/shared-lib/lib-ws/src/connect.rs index 5623d0d3f0..0275894438 100644 --- a/shared-lib/lib-ws/src/connect.rs +++ b/shared-lib/lib-ws/src/connect.rs @@ -1,8 +1,7 @@ #![allow(clippy::all)] use crate::{ errors::{internal_error, WSError}, - MsgReceiver, - MsgSender, + MsgReceiver, MsgSender, }; use futures_core::{future::BoxFuture, ready}; use futures_util::{FutureExt, StreamExt}; @@ -17,8 +16,7 @@ use tokio::net::TcpStream; use tokio_tungstenite::{ connect_async, tungstenite::{handshake::client::Response, Error, Message}, - MaybeTlsStream, - WebSocketStream, + MaybeTlsStream, WebSocketStream, }; type WsConnectResult = Result<(WebSocketStream>, Response), Error>; @@ -67,11 +65,11 @@ impl Future for WSConnectionFuture { self.ws_rx.take().expect("WsConnection should be call once "), ); Poll::Ready(Ok(WSStream::new(msg_tx, ws_rx, stream))) - }, + } Err(error) => { tracing::debug!("🐴 ws connect failed: {:?}", error); Poll::Ready(Err(error.into())) - }, + } }; } } @@ -98,7 +96,7 @@ impl WSStream { ws_read .for_each(|message| async { match tx.send(send_message(msg_tx.clone(), message)) { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("WsStream tx closed unexpectedly: {} ", e), } }) @@ -111,12 +109,12 @@ impl WSStream { match rx.recv().await { None => { return Err(WSError::internal().context("WsStream rx closed unexpectedly")); - }, + } Some(result) => { if result.is_err() { return result; } - }, + } } } }; @@ -137,7 +135,9 @@ impl WSStream { } impl fmt::Debug for WSStream { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("WSStream").finish() } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WSStream").finish() + } } impl Future for WSStream { @@ -154,9 +154,9 @@ impl Future for WSStream { Poll::Pending => { self.inner = Some((ws_read, ws_write)); Poll::Pending - }, + } } - }, + } } } } diff --git a/shared-lib/lib-ws/src/errors.rs b/shared-lib/lib-ws/src/errors.rs index ea80a298c7..e263706b44 100644 --- a/shared-lib/lib-ws/src/errors.rs +++ b/shared-lib/lib-ws/src/errors.rs @@ -54,25 +54,33 @@ where #[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] pub enum ErrorCode { - InternalError = 0, + InternalError = 0, UnsupportedMessage = 1, - Unauthorized = 2, + Unauthorized = 2, } impl std::default::Default for ErrorCode { - fn default() -> Self { ErrorCode::InternalError } + fn default() -> Self { + ErrorCode::InternalError + } } impl std::convert::From for WSError { - fn from(error: ParseError) -> Self { WSError::internal().context(error) } + fn from(error: ParseError) -> Self { + WSError::internal().context(error) + } } impl std::convert::From for WSError { - fn from(error: protobuf::ProtobufError) -> Self { WSError::internal().context(error) } + fn from(error: protobuf::ProtobufError) -> Self { + WSError::internal().context(error) + } } impl std::convert::From> for WSError { - fn from(error: TrySendError) -> Self { WSError::internal().context(error) } + fn from(error: TrySendError) -> Self { + WSError::internal().context(error) + } } impl std::convert::From for WSError { @@ -84,7 +92,7 @@ impl std::convert::From for WSError { } else { WSError::internal().context(response) } - }, + } _ => WSError::internal().context(error), } } diff --git a/shared-lib/lib-ws/src/msg.rs b/shared-lib/lib-ws/src/msg.rs index 98baba8d43..717856ca3f 100644 --- a/shared-lib/lib-ws/src/msg.rs +++ b/shared-lib/lib-ws/src/msg.rs @@ -18,7 +18,9 @@ pub enum WSModule { } impl std::default::Default for WSModule { - fn default() -> Self { WSModule::Doc } + fn default() -> Self { + WSModule::Doc + } } impl ToString for WSModule { @@ -37,7 +39,7 @@ impl std::convert::From for TokioMessage { Err(e) => { log::error!("WsMessage serialize error: {:?}", e); TokioMessage::Binary(vec![]) - }, + } } } } diff --git a/shared-lib/lib-ws/src/ws.rs b/shared-lib/lib-ws/src/ws.rs index 386ec9b372..48a41a2ca3 100644 --- a/shared-lib/lib-ws/src/ws.rs +++ b/shared-lib/lib-ws/src/ws.rs @@ -2,8 +2,7 @@ use crate::{ connect::{WSConnectionFuture, WSStream}, errors::WSError, - WSModule, - WebSocketRawMessage, + WSModule, WebSocketRawMessage, }; use backend_service::errors::ServerError; use bytes::Bytes; @@ -57,7 +56,9 @@ impl std::default::Default for WSController { } impl WSController { - pub fn new() -> Self { WSController::default() } + pub fn new() -> Self { + WSController::default() + } pub fn add_ws_message_receiver(&self, handler: Arc) -> Result<(), WSError> { let source = handler.source(); @@ -74,7 +75,9 @@ impl WSController { self.connect(addr, strategy).await } - pub async fn stop(&self) { self.sender_ctrl.write().set_state(WSConnectState::Disconnected); } + pub async fn stop(&self) { + self.sender_ctrl.write().set_state(WSConnectState::Disconnected); + } async fn connect(&self, addr: String, strategy: T) -> Result<(), ServerError> where @@ -104,11 +107,11 @@ impl WSController { sender_ctrl.write().set_state(WSConnectState::Connected); let _ = ret.send(Ok(())); spawn_stream_and_handlers(stream, handlers_fut, sender_ctrl.clone()).await; - }, + } Err(e) => { sender_ctrl.write().set_error(e.clone()); let _ = ret.send(Err(ServerError::internal().context(e))); - }, + } } }); @@ -131,7 +134,9 @@ impl WSController { self.connect(addr, strategy).await } - pub fn subscribe_state(&self) -> broadcast::Receiver { self.state_notify.subscribe() } + pub fn subscribe_state(&self) -> broadcast::Receiver { + self.state_notify.subscribe() + } pub fn ws_message_sender(&self) -> Result, WSError> { match self.sender_ctrl.read().sender() { @@ -165,7 +170,9 @@ pub struct WSHandlerFuture { } impl WSHandlerFuture { - fn new(handlers: Handlers, msg_rx: MsgReceiver) -> Self { Self { msg_rx, handlers } } + fn new(handlers: Handlers, msg_rx: MsgReceiver) -> Self { + Self { msg_rx, handlers } + } fn handler_ws_message(&self, message: Message) { if let Message::Binary(bytes) = message { @@ -182,7 +189,7 @@ impl WSHandlerFuture { }, Err(e) => { log::error!("Deserialize binary ws message failed: {:?}", e); - }, + } } } } @@ -194,7 +201,7 @@ impl Future for WSHandlerFuture { match ready!(self.as_mut().project().msg_rx.poll_next(cx)) { None => { return Poll::Ready(()); - }, + } Some(message) => self.handler_ws_message(message), } } @@ -317,7 +324,7 @@ impl Future for WSConnectActionFut { handlers_fut, sender, })) - }, + } Err(e) => Poll::Ready(Err(e)), } } @@ -343,7 +350,9 @@ impl std::fmt::Display for WSConnectState { } impl std::fmt::Debug for WSConnectState { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(&format!("{}", self)) } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(&format!("{}", self)) + } } struct WSSenderController { @@ -353,7 +362,9 @@ struct WSSenderController { } impl WSSenderController { - fn set_sender(&mut self, sender: WSSender) { self.sender = Some(Arc::new(sender)); } + fn set_sender(&mut self, sender: WSSender) { + self.sender = Some(Arc::new(sender)); + } fn set_state(&mut self, state: WSConnectState) { if state != WSConnectState::Connected { @@ -369,12 +380,18 @@ impl WSSenderController { self.set_state(WSConnectState::Disconnected); } - fn sender(&self) -> Option> { self.sender.clone() } + fn sender(&self) -> Option> { + self.sender.clone() + } - fn is_connecting(&self) -> bool { self.state == WSConnectState::Connecting } + fn is_connecting(&self) -> bool { + self.state == WSConnectState::Connecting + } #[allow(dead_code)] - fn is_connected(&self) -> bool { self.state == WSConnectState::Connected } + fn is_connected(&self) -> bool { + self.state == WSConnectState::Connected + } } impl std::default::Default for WSSenderController { diff --git a/shared-lib/rustfmt.toml b/shared-lib/rustfmt.toml index d76ec139c3..2464575494 100644 --- a/shared-lib/rustfmt.toml +++ b/shared-lib/rustfmt.toml @@ -1,18 +1,18 @@ # https://rust-lang.github.io/rustfmt/?version=master&search= max_width = 120 tab_spaces = 4 -fn_single_line = true -match_block_trailing_comma = true -normalize_comments = true -wrap_comments = true -use_field_init_shorthand = true -use_try_shorthand = true -normalize_doc_attributes = true -report_todo = "Never" -report_fixme = "Always" -imports_layout = "HorizontalVertical" -imports_granularity = "Crate" -reorder_modules = true -reorder_imports = true -enum_discrim_align_threshold = 20 +# fn_single_line = true +# match_block_trailing_comma = true +# normalize_comments = true +# wrap_comments = true +# use_field_init_shorthand = true +# use_try_shorthand = true +# normalize_doc_attributes = true +# report_todo = "Never" +# report_fixme = "Always" +# imports_layout = "HorizontalVertical" +# imports_granularity = "Crate" +# reorder_modules = true +# reorder_imports = true +# enum_discrim_align_threshold = 20 edition = "2018"