From bba8f8ae018401c461788c98f39a6d4370adfb62 Mon Sep 17 00:00:00 2001 From: appflowy Date: Mon, 24 Jan 2022 17:35:58 +0800 Subject: [PATCH] fix fmt and clippy warnings --- backend/src/context.rs | 12 +- backend/src/services/document/ws_actor.rs | 21 +- backend/src/services/document/ws_receiver.rs | 12 +- backend/src/services/folder/trash/trash.rs | 12 +- backend/src/services/folder/view/router.rs | 12 +- .../src/services/folder/workspace/router.rs | 13 +- backend/src/services/folder/ws_actor.rs | 21 +- backend/src/services/folder/ws_receiver.rs | 10 +- backend/src/services/kv/revision_kv.rs | 24 +- backend/src/services/web_socket/ws_client.rs | 48 +-- backend/tests/api_test/auth_test.rs | 2 +- backend/tests/document_test/edit_script.rs | 1 + .../flowy_sdk/macos/Classes/binding.h | 0 frontend/rust-lib/Cargo.toml | 0 frontend/rust-lib/dart-ffi/Cargo.toml | 0 frontend/rust-lib/dart-ffi/Flowy.toml | 0 frontend/rust-lib/dart-ffi/binding.h | 0 frontend/rust-lib/dart-ffi/src/c.rs | 0 frontend/rust-lib/dart-ffi/src/lib.rs | 0 .../dart-ffi/src/model/ffi_request.rs | 0 .../dart-ffi/src/model/ffi_response.rs | 0 frontend/rust-lib/dart-ffi/src/model/mod.rs | 0 .../rust-lib/dart-ffi/src/protobuf/mod.rs | 0 .../src/protobuf/model/ffi_request.rs | 0 .../src/protobuf/model/ffi_response.rs | 0 .../dart-ffi/src/protobuf/model/mod.rs | 0 .../src/protobuf/proto/ffi_request.proto | 0 .../src/protobuf/proto/ffi_response.proto | 0 frontend/rust-lib/dart-ffi/src/util.rs | 0 frontend/rust-lib/dart-notify/Cargo.toml | 0 frontend/rust-lib/dart-notify/Flowy.toml | 0 frontend/rust-lib/dart-notify/src/dart/mod.rs | 0 .../dart-notify/src/dart/stream_sender.rs | 0 .../rust-lib/dart-notify/src/entities/mod.rs | 0 .../dart-notify/src/entities/subject.rs | 0 frontend/rust-lib/dart-notify/src/lib.rs | 0 .../rust-lib/dart-notify/src/protobuf/mod.rs | 0 .../dart-notify/src/protobuf/model/mod.rs | 0 .../dart-notify/src/protobuf/model/subject.rs | 0 .../src/protobuf/proto/subject.proto | 0 frontend/rust-lib/flowy-core/Cargo.toml | 0 frontend/rust-lib/flowy-core/Flowy.toml | 0 frontend/rust-lib/flowy-core/src/context.rs | 141 -------- .../rust-lib/flowy-core/src/controller.rs | 41 ++- .../flowy-core/src/dart_notification.rs | 0 frontend/rust-lib/flowy-core/src/event.rs | 48 +-- .../rust-lib/flowy-core/src/event_handler.rs | 111 ------- frontend/rust-lib/flowy-core/src/lib.rs | 0 frontend/rust-lib/flowy-core/src/macros.rs | 0 frontend/rust-lib/flowy-core/src/module.rs | 0 .../rust-lib/flowy-core/src/protobuf/mod.rs | 0 .../src/protobuf/model/dart_notification.rs | 0 .../flowy-core/src/protobuf/model/event.rs | 0 .../flowy-core/src/protobuf/model/mod.rs | 0 .../protobuf/proto/dart_notification.proto | 0 .../flowy-core/src/protobuf/proto/event.proto | 0 .../flowy-core/src/services/app/controller.rs | 17 +- .../src/services/app/event_handler.rs | 0 .../flowy-core/src/services/app/mod.rs | 0 .../flowy-core/src/services/folder_editor.rs | 10 +- .../rust-lib/flowy-core/src/services/mod.rs | 0 .../src/services/persistence/migration.rs | 0 .../src/services/persistence/mod.rs | 4 +- .../services/persistence/version_1/app_sql.rs | 0 .../src/services/persistence/version_1/mod.rs | 0 .../persistence/version_1/trash_sql.rs | 0 .../services/persistence/version_1/v1_impl.rs | 61 +++- .../persistence/version_1/view_sql.rs | 0 .../persistence/version_1/workspace_sql.rs | 2 +- .../src/services/persistence/version_2/mod.rs | 0 .../services/persistence/version_2/v2_impl.rs | 54 ++- .../src/services/server/server_api.rs | 172 ---------- .../src/services/trash/controller.rs | 22 +- .../src/services/trash/event_handler.rs | 0 .../flowy-core/src/services/trash/mod.rs | 0 .../src/services/view/controller.rs | 27 +- .../src/services/view/event_handler.rs | 0 .../flowy-core/src/services/view/mod.rs | 0 .../flowy-core/src/services/web_socket.rs | 0 .../src/services/workspace/controller.rs | 19 +- .../src/services/workspace/event_handler.rs | 4 +- .../flowy-core/src/services/workspace/mod.rs | 0 frontend/rust-lib/flowy-core/src/util.rs | 0 .../flowy-core/tests/workspace/folder_test.rs | 0 .../flowy-core/tests/workspace/helper.rs | 0 .../flowy-core/tests/workspace/main.rs | 0 .../flowy-core/tests/workspace/script.rs | 80 ++--- frontend/rust-lib/flowy-database/.env | 0 frontend/rust-lib/flowy-database/Cargo.toml | 0 frontend/rust-lib/flowy-database/diesel.toml | 0 .../flowy-database/migrations/.gitkeep | 0 .../2021-07-09-063045_flowy-user/down.sql | 0 .../2021-07-09-063045_flowy-user/up.sql | 0 .../2021-07-14-022241_flowy-user/down.sql | 0 .../2021-07-14-022241_flowy-user/up.sql | 0 .../2021-07-22-234458_flowy-editor/down.sql | 0 .../2021-07-22-234458_flowy-editor/up.sql | 0 .../2021-09-22-074638_flowy-doc-op/down.sql | 0 .../2021-09-22-074638_flowy-doc-op/up.sql | 0 frontend/rust-lib/flowy-database/src/kv/kv.rs | 2 +- .../rust-lib/flowy-database/src/kv/mod.rs | 0 .../rust-lib/flowy-database/src/kv/schema.rs | 0 frontend/rust-lib/flowy-database/src/lib.rs | 0 .../rust-lib/flowy-database/src/macros.rs | 0 .../rust-lib/flowy-database/src/schema.rs | 0 frontend/rust-lib/flowy-document/Cargo.toml | 0 frontend/rust-lib/flowy-document/Flowy.toml | 0 .../rust-lib/flowy-document/src/controller.rs | 26 +- .../flowy-document/src/core/editor.rs | 25 +- .../rust-lib/flowy-document/src/core/mod.rs | 0 .../rust-lib/flowy-document/src/core/queue.rs | 30 +- .../src/core/revision/manager.rs | 295 ----------------- .../flowy-document/src/core/web_socket.rs | 10 +- .../src/core/web_socket/http_ws_impl.rs | 293 ----------------- .../src/core/web_socket/local_ws_impl.rs | 20 -- .../src/core/web_socket/ws_manager.rs | 310 ------------------ frontend/rust-lib/flowy-document/src/lib.rs | 0 .../flowy-document/src/notify/observable.rs | 18 - .../flowy-document/src/protobuf/mod.rs | 0 .../flowy-document/src/protobuf/model/mod.rs | 0 .../flowy-document/src/server/middleware.rs | 29 -- .../flowy-document/src/server/server_api.rs | 69 ---- .../flowy-document/src/ws_receivers.rs | 64 ---- .../tests/document/document_test.rs | 0 .../tests/document/edit_script.rs | 2 +- .../flowy-document/tests/document/mod.rs | 0 .../tests/editor/attribute_test.rs | 0 .../flowy-document/tests/editor/mod.rs | 6 +- .../flowy-document/tests/editor/op_test.rs | 0 .../flowy-document/tests/editor/serde_test.rs | 2 +- .../tests/editor/undo_redo_test.rs | 0 .../rust-lib/flowy-document/tests/main.rs | 0 frontend/rust-lib/flowy-error/Cargo.toml | 0 frontend/rust-lib/flowy-error/Flowy.toml | 0 frontend/rust-lib/flowy-error/src/errors.rs | 0 .../rust-lib/flowy-error/src/ext/backend.rs | 0 .../flowy-error/src/ext/collaborate.rs | 0 .../rust-lib/flowy-error/src/ext/database.rs | 0 frontend/rust-lib/flowy-error/src/ext/mod.rs | 0 frontend/rust-lib/flowy-error/src/ext/ot.rs | 4 +- .../rust-lib/flowy-error/src/ext/serde.rs | 0 frontend/rust-lib/flowy-error/src/lib.rs | 0 .../rust-lib/flowy-error/src/protobuf/mod.rs | 0 .../flowy-error/src/protobuf/model/errors.rs | 0 .../flowy-error/src/protobuf/model/mod.rs | 0 .../src/protobuf/proto/errors.proto | 0 frontend/rust-lib/flowy-net/Cargo.toml | 0 frontend/rust-lib/flowy-net/Flowy.toml | 0 .../rust-lib/flowy-net/src/entities/mod.rs | 0 .../flowy-net/src/entities/network_state.rs | 0 frontend/rust-lib/flowy-net/src/event.rs | 0 .../rust-lib/flowy-net/src/handlers/mod.rs | 0 .../flowy-net/src/http_server/core.rs | 16 +- .../flowy-net/src/http_server/document.rs | 12 +- .../rust-lib/flowy-net/src/http_server/mod.rs | 0 .../flowy-net/src/http_server/user.rs | 19 +- frontend/rust-lib/flowy-net/src/lib.rs | 0 .../flowy-net/src/local_server/mod.rs | 0 .../flowy-net/src/local_server/persistence.rs | 8 +- .../flowy-net/src/local_server/server.rs | 43 +-- .../rust-lib/flowy-net/src/local_server/ws.rs | 8 +- frontend/rust-lib/flowy-net/src/module.rs | 0 .../rust-lib/flowy-net/src/protobuf/mod.rs | 0 .../flowy-net/src/protobuf/model/event.rs | 0 .../flowy-net/src/protobuf/model/mod.rs | 0 .../src/protobuf/model/network_state.rs | 0 .../flowy-net/src/protobuf/proto/event.proto | 0 .../src/protobuf/proto/network_state.proto | 0 .../src/services/local_ws/local_server.rs | 178 ---------- .../src/services/local_ws/local_ws_impl.rs | 150 --------- .../rust-lib/flowy-net/src/ws/connection.rs | 30 +- frontend/rust-lib/flowy-net/src/ws/http_ws.rs | 6 +- frontend/rust-lib/flowy-net/src/ws/mod.rs | 0 frontend/rust-lib/flowy-sdk/.gitignore | 0 frontend/rust-lib/flowy-sdk/Cargo.toml | 0 .../src/deps_resolve/document_deps.rs | 28 +- .../flowy-sdk/src/deps_resolve/folder_deps.rs | 22 +- .../flowy-sdk/src/deps_resolve/mod.rs | 0 .../flowy-sdk/src/deps_resolve/user_deps.rs | 0 frontend/rust-lib/flowy-sdk/src/lib.rs | 0 frontend/rust-lib/flowy-sdk/src/module.rs | 12 +- frontend/rust-lib/flowy-sync/Cargo.toml | 0 .../rust-lib/flowy-sync/src/cache/disk/mod.rs | 0 .../flowy-sync/src/cache/disk/sql_impl.rs | 29 +- .../rust-lib/flowy-sync/src/cache/memory.rs | 0 frontend/rust-lib/flowy-sync/src/cache/mod.rs | 0 .../flowy-sync/src/conflict_resolve.rs | 14 +- frontend/rust-lib/flowy-sync/src/lib.rs | 0 .../rust-lib/flowy-sync/src/rev_manager.rs | 40 ++- .../rust-lib/flowy-sync/src/ws_manager.rs | 49 +-- frontend/rust-lib/flowy-test/Cargo.toml | 0 .../rust-lib/flowy-test/src/event_builder.rs | 22 +- frontend/rust-lib/flowy-test/src/helper.rs | 0 frontend/rust-lib/flowy-test/src/lib.rs | 0 frontend/rust-lib/flowy-user/Cargo.toml | 0 frontend/rust-lib/flowy-user/Flowy.toml | 0 .../flowy-user/src/dart_notification.rs | 0 frontend/rust-lib/flowy-user/src/event.rs | 0 .../flowy-user/src/handlers/auth_handler.rs | 0 .../rust-lib/flowy-user/src/handlers/mod.rs | 0 .../flowy-user/src/handlers/user_handler.rs | 0 frontend/rust-lib/flowy-user/src/lib.rs | 0 frontend/rust-lib/flowy-user/src/module.rs | 7 +- .../rust-lib/flowy-user/src/protobuf/mod.rs | 0 .../src/protobuf/model/dart_notification.rs | 0 .../flowy-user/src/protobuf/model/event.rs | 0 .../flowy-user/src/protobuf/model/mod.rs | 0 .../protobuf/proto/dart_notification.proto | 0 .../flowy-user/src/protobuf/proto/event.proto | 0 .../flowy-user/src/services/database.rs | 8 +- .../rust-lib/flowy-user/src/services/mod.rs | 0 .../flowy-user/src/services/notifier.rs | 0 .../src/services/server/server_api.rs | 92 ------ .../src/services/server/server_api_mock.rs | 53 --- .../flowy-user/src/services/user_session.rs | 7 +- .../flowy-user/src/sql_tables/user.rs | 73 ----- .../flowy-user/tests/event/auth_test.rs | 0 .../rust-lib/flowy-user/tests/event/helper.rs | 0 .../rust-lib/flowy-user/tests/event/main.rs | 0 .../tests/event/user_profile_test.rs | 0 frontend/rust-lib/lib-dispatch/Cargo.toml | 0 .../rust-lib/lib-dispatch/src/byte_trait.rs | 0 frontend/rust-lib/lib-dispatch/src/data.rs | 0 .../rust-lib/lib-dispatch/src/dispatcher.rs | 0 .../lib-dispatch/src/errors/errors.rs | 0 .../rust-lib/lib-dispatch/src/errors/mod.rs | 0 frontend/rust-lib/lib-dispatch/src/lib.rs | 0 frontend/rust-lib/lib-dispatch/src/macros.rs | 0 .../lib-dispatch/src/module/container.rs | 0 .../rust-lib/lib-dispatch/src/module/data.rs | 0 .../rust-lib/lib-dispatch/src/module/mod.rs | 0 .../lib-dispatch/src/module/module.rs | 0 .../rust-lib/lib-dispatch/src/request/mod.rs | 0 .../lib-dispatch/src/request/payload.rs | 0 .../lib-dispatch/src/request/request.rs | 0 .../lib-dispatch/src/response/builder.rs | 0 .../rust-lib/lib-dispatch/src/response/mod.rs | 0 .../lib-dispatch/src/response/responder.rs | 0 .../lib-dispatch/src/response/response.rs | 0 .../lib-dispatch/src/service/boxed.rs | 0 .../lib-dispatch/src/service/handler.rs | 0 .../rust-lib/lib-dispatch/src/service/mod.rs | 0 .../lib-dispatch/src/service/service.rs | 0 frontend/rust-lib/lib-dispatch/src/system.rs | 0 .../rust-lib/lib-dispatch/src/util/mod.rs | 0 .../rust-lib/lib-dispatch/src/util/ready.rs | 0 .../rust-lib/lib-dispatch/tests/api/main.rs | 0 .../rust-lib/lib-dispatch/tests/api/module.rs | 0 frontend/rust-lib/lib-log/Cargo.toml | 0 .../lib-log/flowy_log_test.2021-11-09 | 0 frontend/rust-lib/lib-log/src/layer.rs | 0 frontend/rust-lib/lib-log/src/lib.rs | 7 - frontend/rust-lib/lib-sqlite/Cargo.toml | 0 frontend/rust-lib/lib-sqlite/src/conn_ext.rs | 0 frontend/rust-lib/lib-sqlite/src/database.rs | 0 frontend/rust-lib/lib-sqlite/src/errors.rs | 0 frontend/rust-lib/lib-sqlite/src/lib.rs | 0 frontend/rust-lib/lib-sqlite/src/pool.rs | 0 frontend/rust-lib/lib-sqlite/src/pragma.rs | 0 shared-lib/backend-service/src/errors.rs | 46 +-- .../src/client_document/document_pad.rs | 50 ++- .../src/entities/revision.rs | 68 ++-- .../src/entities/ws_data.rs | 18 +- .../src/folder/folder_pad.rs | 34 +- .../src/server_document/document_manager.rs | 22 +- .../src/server_document/document_pad.rs | 16 +- .../src/server_folder/folder_manager.rs | 18 +- .../src/server_folder/folder_pad.rs | 12 +- .../flowy-collaboration/src/synchronizer.rs | 30 +- shared-lib/flowy-collaboration/src/util.rs | 8 +- .../src/entities/view.rs | 12 +- .../src/entities/workspace.rs | 8 +- .../flowy-core-data-model/src/macros.rs | 20 +- .../lib-ot/src/core/operation/operation.rs | 20 +- shared-lib/lib-ws/src/connect.rs | 24 +- shared-lib/lib-ws/src/msg.rs | 8 +- shared-lib/lib-ws/src/ws.rs | 43 ++- 277 files changed, 906 insertions(+), 2690 deletions(-) mode change 100644 => 100755 frontend/app_flowy/packages/flowy_sdk/macos/Classes/binding.h mode change 100644 => 100755 frontend/rust-lib/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/dart-ffi/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/dart-ffi/Flowy.toml mode change 100644 => 100755 frontend/rust-lib/dart-ffi/binding.h mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/c.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/model/ffi_request.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/model/ffi_response.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/model/mod.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/protobuf/mod.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/protobuf/model/ffi_request.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/protobuf/model/ffi_response.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/protobuf/model/mod.rs mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/protobuf/proto/ffi_request.proto mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/protobuf/proto/ffi_response.proto mode change 100644 => 100755 frontend/rust-lib/dart-ffi/src/util.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/dart-notify/Flowy.toml mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/dart/mod.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/dart/stream_sender.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/entities/mod.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/entities/subject.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/protobuf/mod.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/protobuf/model/mod.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/protobuf/model/subject.rs mode change 100644 => 100755 frontend/rust-lib/dart-notify/src/protobuf/proto/subject.proto mode change 100644 => 100755 frontend/rust-lib/flowy-core/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-core/Flowy.toml delete mode 100644 frontend/rust-lib/flowy-core/src/context.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/controller.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/dart_notification.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/event.rs delete mode 100644 frontend/rust-lib/flowy-core/src/event_handler.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/macros.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/module.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/protobuf/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/protobuf/model/dart_notification.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/protobuf/model/event.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/protobuf/model/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/protobuf/proto/dart_notification.proto mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/protobuf/proto/event.proto mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/app/controller.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/app/event_handler.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/app/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/folder_editor.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/migration.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/version_1/app_sql.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/version_1/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/version_1/trash_sql.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/version_1/v1_impl.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/version_1/view_sql.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/version_1/workspace_sql.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/version_2/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/persistence/version_2/v2_impl.rs delete mode 100644 frontend/rust-lib/flowy-core/src/services/server/server_api.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/trash/controller.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/trash/event_handler.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/trash/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/view/controller.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/view/event_handler.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/view/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/web_socket.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/workspace/controller.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/workspace/event_handler.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/services/workspace/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/src/util.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/tests/workspace/folder_test.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/tests/workspace/helper.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/tests/workspace/main.rs mode change 100644 => 100755 frontend/rust-lib/flowy-core/tests/workspace/script.rs mode change 100644 => 100755 frontend/rust-lib/flowy-database/.env mode change 100644 => 100755 frontend/rust-lib/flowy-database/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-database/diesel.toml mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/.gitkeep mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/down.sql mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/up.sql mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/2021-07-14-022241_flowy-user/down.sql mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/2021-07-14-022241_flowy-user/up.sql mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/2021-07-22-234458_flowy-editor/down.sql mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/2021-07-22-234458_flowy-editor/up.sql mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/2021-09-22-074638_flowy-doc-op/down.sql mode change 100644 => 100755 frontend/rust-lib/flowy-database/migrations/2021-09-22-074638_flowy-doc-op/up.sql mode change 100644 => 100755 frontend/rust-lib/flowy-database/src/kv/kv.rs mode change 100644 => 100755 frontend/rust-lib/flowy-database/src/kv/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-database/src/kv/schema.rs mode change 100644 => 100755 frontend/rust-lib/flowy-database/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/flowy-database/src/macros.rs mode change 100644 => 100755 frontend/rust-lib/flowy-database/src/schema.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-document/Flowy.toml mode change 100644 => 100755 frontend/rust-lib/flowy-document/src/controller.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/src/core/editor.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/src/core/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/src/core/queue.rs delete mode 100644 frontend/rust-lib/flowy-document/src/core/revision/manager.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/src/core/web_socket.rs delete mode 100644 frontend/rust-lib/flowy-document/src/core/web_socket/http_ws_impl.rs delete mode 100644 frontend/rust-lib/flowy-document/src/core/web_socket/local_ws_impl.rs delete mode 100644 frontend/rust-lib/flowy-document/src/core/web_socket/ws_manager.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/src/lib.rs delete mode 100644 frontend/rust-lib/flowy-document/src/notify/observable.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/src/protobuf/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/src/protobuf/model/mod.rs delete mode 100644 frontend/rust-lib/flowy-document/src/server/middleware.rs delete mode 100644 frontend/rust-lib/flowy-document/src/server/server_api.rs delete mode 100644 frontend/rust-lib/flowy-document/src/ws_receivers.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/document/document_test.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/document/edit_script.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/document/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/editor/attribute_test.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/editor/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/editor/op_test.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/editor/serde_test.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/editor/undo_redo_test.rs mode change 100644 => 100755 frontend/rust-lib/flowy-document/tests/main.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-error/Flowy.toml mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/errors.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/ext/backend.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/ext/collaborate.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/ext/database.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/ext/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/ext/ot.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/ext/serde.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/protobuf/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/protobuf/model/errors.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/protobuf/model/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-error/src/protobuf/proto/errors.proto mode change 100644 => 100755 frontend/rust-lib/flowy-net/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-net/Flowy.toml mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/entities/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/entities/network_state.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/event.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/handlers/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/http_server/core.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/http_server/document.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/http_server/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/http_server/user.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/local_server/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/local_server/persistence.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/local_server/server.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/local_server/ws.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/module.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/protobuf/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/protobuf/model/event.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/protobuf/model/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/protobuf/model/network_state.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/protobuf/proto/event.proto mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/protobuf/proto/network_state.proto delete mode 100644 frontend/rust-lib/flowy-net/src/services/local_ws/local_server.rs delete mode 100644 frontend/rust-lib/flowy-net/src/services/local_ws/local_ws_impl.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/ws/connection.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/ws/http_ws.rs mode change 100644 => 100755 frontend/rust-lib/flowy-net/src/ws/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sdk/.gitignore mode change 100644 => 100755 frontend/rust-lib/flowy-sdk/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sdk/src/deps_resolve/folder_deps.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sdk/src/deps_resolve/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sdk/src/deps_resolve/user_deps.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sdk/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sdk/src/module.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sync/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-sync/src/cache/disk/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sync/src/cache/disk/sql_impl.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sync/src/cache/memory.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sync/src/cache/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sync/src/conflict_resolve.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sync/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sync/src/rev_manager.rs mode change 100644 => 100755 frontend/rust-lib/flowy-sync/src/ws_manager.rs mode change 100644 => 100755 frontend/rust-lib/flowy-test/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-test/src/event_builder.rs mode change 100644 => 100755 frontend/rust-lib/flowy-test/src/helper.rs mode change 100644 => 100755 frontend/rust-lib/flowy-test/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/flowy-user/Flowy.toml mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/dart_notification.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/event.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/handlers/auth_handler.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/handlers/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/handlers/user_handler.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/module.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/protobuf/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/protobuf/model/dart_notification.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/protobuf/model/event.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/protobuf/model/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/protobuf/proto/dart_notification.proto mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/protobuf/proto/event.proto mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/services/database.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/services/mod.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/services/notifier.rs delete mode 100644 frontend/rust-lib/flowy-user/src/services/server/server_api.rs delete mode 100644 frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/src/services/user_session.rs delete mode 100644 frontend/rust-lib/flowy-user/src/sql_tables/user.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/tests/event/auth_test.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/tests/event/helper.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/tests/event/main.rs mode change 100644 => 100755 frontend/rust-lib/flowy-user/tests/event/user_profile_test.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/byte_trait.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/data.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/dispatcher.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/errors/errors.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/errors/mod.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/macros.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/module/container.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/module/data.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/module/mod.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/module/module.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/request/mod.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/request/payload.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/request/request.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/response/builder.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/response/mod.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/response/responder.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/response/response.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/service/boxed.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/service/handler.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/service/mod.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/service/service.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/system.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/util/mod.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/src/util/ready.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/tests/api/main.rs mode change 100644 => 100755 frontend/rust-lib/lib-dispatch/tests/api/module.rs mode change 100644 => 100755 frontend/rust-lib/lib-log/Cargo.toml delete mode 100644 frontend/rust-lib/lib-log/flowy_log_test.2021-11-09 mode change 100644 => 100755 frontend/rust-lib/lib-log/src/layer.rs mode change 100644 => 100755 frontend/rust-lib/lib-log/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/lib-sqlite/Cargo.toml mode change 100644 => 100755 frontend/rust-lib/lib-sqlite/src/conn_ext.rs mode change 100644 => 100755 frontend/rust-lib/lib-sqlite/src/database.rs mode change 100644 => 100755 frontend/rust-lib/lib-sqlite/src/errors.rs mode change 100644 => 100755 frontend/rust-lib/lib-sqlite/src/lib.rs mode change 100644 => 100755 frontend/rust-lib/lib-sqlite/src/pool.rs mode change 100644 => 100755 frontend/rust-lib/lib-sqlite/src/pragma.rs diff --git a/backend/src/context.rs b/backend/src/context.rs index 74a2085f0c..d3b80af564 100644 --- a/backend/src/context.rs +++ b/backend/src/context.rs @@ -78,9 +78,15 @@ 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 document_kv_store(&self) -> Arc { self.document_store.clone() } + pub fn document_kv_store(&self) -> Arc { + self.document_store.clone() + } - pub fn folder_kv_store(&self) -> Arc { self.folder_store.clone() } + pub fn folder_kv_store(&self) -> Arc { + self.folder_store.clone() + } } diff --git a/backend/src/services/document/ws_actor.rs b/backend/src/services/document/ws_actor.rs index ea2466193a..d48055a4a3 100644 --- a/backend/src/services/document/ws_actor.rs +++ b/backend/src/services/document/ws_actor.rs @@ -10,8 +10,7 @@ use backend_service::errors::{internal_error, Result, ServerError}; use crate::services::web_socket::revision_data_to_ws_message; use flowy_collaboration::{ protobuf::{ - ClientRevisionWSData as ClientRevisionWSDataPB, - ClientRevisionWSDataType as ClientRevisionWSDataTypePB, + ClientRevisionWSData as ClientRevisionWSDataPB, ClientRevisionWSDataType as ClientRevisionWSDataTypePB, Revision as RevisionPB, }, server_document::ServerDocumentManager, @@ -69,7 +68,7 @@ impl DocumentWebSocketActor { ret, } => { let _ = ret.send(self.handle_document_data(client_data).await); - }, + } } } @@ -94,14 +93,14 @@ impl DocumentWebSocketActor { .handle_client_revisions(user, document_client_data) .await .map_err(internal_error)?; - }, + } ClientRevisionWSDataTypePB::ClientPing => { let _ = self .doc_manager .handle_client_ping(user, document_client_data) .await .map_err(internal_error)?; - }, + } } Ok(()) @@ -132,26 +131,28 @@ impl std::fmt::Debug for DocumentRevisionUser { } impl RevisionUser for DocumentRevisionUser { - fn user_id(&self) -> String { self.user.id().to_string() } + fn user_id(&self) -> String { + self.user.id().to_string() + } fn receive(&self, resp: RevisionSyncResponse) { let result = match resp { RevisionSyncResponse::Pull(data) => { let msg: WebSocketMessage = revision_data_to_ws_message(data, WSChannel::Document); self.socket.try_send(msg).map_err(internal_error) - }, + } RevisionSyncResponse::Push(data) => { let msg: WebSocketMessage = revision_data_to_ws_message(data, WSChannel::Document); self.socket.try_send(msg).map_err(internal_error) - }, + } RevisionSyncResponse::Ack(data) => { let msg: WebSocketMessage = revision_data_to_ws_message(data, WSChannel::Document); self.socket.try_send(msg).map_err(internal_error) - }, + } }; match result { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[DocumentRevisionUser]: {}", e), } } diff --git a/backend/src/services/document/ws_receiver.rs b/backend/src/services/document/ws_receiver.rs index 5bdfe33967..e152e71162 100644 --- a/backend/src/services/document/ws_receiver.rs +++ b/backend/src/services/document/ws_receiver.rs @@ -14,9 +14,7 @@ use flowy_collaboration::{ entities::document_info::DocumentInfo, errors::CollaborateError, protobuf::{ - CreateDocParams as CreateDocParamsPB, - DocumentId, - RepeatedRevision as RepeatedRevisionPB, + CreateDocParams as CreateDocParamsPB, DocumentId, RepeatedRevision as RepeatedRevisionPB, Revision as RevisionPB, }, server_document::{DocumentCloudPersistence, ServerDocumentManager}, @@ -69,11 +67,11 @@ impl WebSocketReceiver for DocumentWebSocketReceiver { }; match actor_msg_sender.send(msg).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[DocumentWebSocketReceiver]: send message to actor failed: {}", e), } match rx.await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[DocumentWebSocketReceiver]: message ret failed {:?}", e), }; }); @@ -82,7 +80,9 @@ impl WebSocketReceiver for DocumentWebSocketReceiver { pub struct HttpDocumentCloudPersistence(pub Arc); impl Debug for HttpDocumentCloudPersistence { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("HttpDocumentCloudPersistence") } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str("HttpDocumentCloudPersistence") + } } impl DocumentCloudPersistence for HttpDocumentCloudPersistence { diff --git a/backend/src/services/folder/trash/trash.rs b/backend/src/services/folder/trash/trash.rs index e0bdab571f..f038b691cd 100644 --- a/backend/src/services/folder/trash/trash.rs +++ b/backend/src/services/folder/trash/trash.rs @@ -115,13 +115,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<'_>, document_store, vec![id]).await; - }, + } TrashType::App => { let _ = delete_app(transaction as &mut DBTransaction<'_>, id).await; - }, + } }, } } @@ -162,13 +162,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/folder/view/router.rs b/backend/src/services/folder/view/router.rs index fd53616dbc..b328ed3e83 100644 --- a/backend/src/services/folder/view/router.rs +++ b/backend/src/services/folder/view/router.rs @@ -2,11 +2,9 @@ use crate::{ context::FlowyPersistence, entities::logged_user::LoggedUser, services::folder::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/folder/workspace/router.rs b/backend/src/services/folder/workspace/router.rs index d87a017786..8ad8d9d93a 100644 --- a/backend/src/services/folder/workspace/router.rs +++ b/backend/src/services/folder/workspace/router.rs @@ -1,11 +1,7 @@ use crate::{ entities::logged_user::LoggedUser, services::folder::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/folder/ws_actor.rs b/backend/src/services/folder/ws_actor.rs index 044b0af37e..3e655243c0 100644 --- a/backend/src/services/folder/ws_actor.rs +++ b/backend/src/services/folder/ws_actor.rs @@ -9,8 +9,7 @@ use backend_service::errors::{internal_error, Result}; use flowy_collaboration::{ protobuf::{ - ClientRevisionWSData as ClientRevisionWSDataPB, - ClientRevisionWSDataType as ClientRevisionWSDataTypePB, + ClientRevisionWSData as ClientRevisionWSDataPB, ClientRevisionWSDataType as ClientRevisionWSDataTypePB, }, server_folder::ServerFolderManager, synchronizer::{RevisionSyncResponse, RevisionUser}, @@ -67,7 +66,7 @@ impl FolderWebSocketActor { ret, } => { let _ = ret.send(self.handle_folder_data(client_data).await); - }, + } } } @@ -92,14 +91,14 @@ impl FolderWebSocketActor { .handle_client_revisions(user, folder_client_data) .await .map_err(internal_error)?; - }, + } ClientRevisionWSDataTypePB::ClientPing => { let _ = self .folder_manager .handle_client_ping(user, folder_client_data) .await .map_err(internal_error)?; - }, + } } Ok(()) } @@ -121,26 +120,28 @@ impl std::fmt::Debug for FolderRevisionUser { } impl RevisionUser for FolderRevisionUser { - fn user_id(&self) -> String { self.user.id().to_string() } + fn user_id(&self) -> String { + self.user.id().to_string() + } fn receive(&self, resp: RevisionSyncResponse) { let result = match resp { RevisionSyncResponse::Pull(data) => { let msg: WebSocketMessage = revision_data_to_ws_message(data, WSChannel::Folder); self.socket.try_send(msg).map_err(internal_error) - }, + } RevisionSyncResponse::Push(data) => { let msg: WebSocketMessage = revision_data_to_ws_message(data, WSChannel::Folder); self.socket.try_send(msg).map_err(internal_error) - }, + } RevisionSyncResponse::Ack(data) => { let msg: WebSocketMessage = revision_data_to_ws_message(data, WSChannel::Folder); self.socket.try_send(msg).map_err(internal_error) - }, + } }; match result { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[FolderRevisionUser]: {}", e), } } diff --git a/backend/src/services/folder/ws_receiver.rs b/backend/src/services/folder/ws_receiver.rs index b223338450..4d77ea7ce7 100644 --- a/backend/src/services/folder/ws_receiver.rs +++ b/backend/src/services/folder/ws_receiver.rs @@ -57,13 +57,13 @@ impl WebSocketReceiver for FolderWebSocketReceiver { }; match actor_msg_sender.send(msg).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => { log::error!("[FolderWebSocketReceiver]: send message to actor failed: {}", e); - }, + } } match rx.await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[FolderWebSocketReceiver]: message ret failed {:?}", e), }; }); @@ -72,7 +72,9 @@ impl WebSocketReceiver for FolderWebSocketReceiver { pub struct HttpFolderCloudPersistence(pub Arc); impl Debug for HttpFolderCloudPersistence { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("HttpFolderCloudPersistence") } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str("HttpFolderCloudPersistence") + } } impl FolderCloudPersistence for HttpFolderCloudPersistence { diff --git a/backend/src/services/kv/revision_kv.rs b/backend/src/services/kv/revision_kv.rs index dff6b85ab9..c263d84e97 100644 --- a/backend/src/services/kv/revision_kv.rs +++ b/backend/src/services/kv/revision_kv.rs @@ -16,15 +16,21 @@ pub struct RevisionKVPersistence { impl std::ops::Deref for RevisionKVPersistence { type Target = Arc; - fn deref(&self) -> &Self::Target { &self.inner } + fn deref(&self) -> &Self::Target { + &self.inner + } } impl std::ops::DerefMut for RevisionKVPersistence { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } } impl RevisionKVPersistence { - pub(crate) fn new(kv_store: Arc) -> Self { RevisionKVPersistence { inner: kv_store } } + pub(crate) fn new(kv_store: Arc) -> Self { + RevisionKVPersistence { inner: kv_store } + } pub(crate) async fn set_revision(&self, revisions: Vec) -> Result<(), ServerError> { let items = revisions_to_key_value_items(revisions)?; @@ -45,7 +51,7 @@ impl RevisionKVPersistence { self.inner .transaction(|mut t| Box::pin(async move { t.batch_get_start_with(&object_id).await })) .await? - }, + } Some(rev_ids) => { let keys = rev_ids .into_iter() @@ -55,7 +61,7 @@ impl RevisionKVPersistence { self.inner .transaction(|mut t| Box::pin(async move { t.batch_get(keys).await })) .await? - }, + } }; Ok(key_value_items_to_revisions(items)) @@ -72,7 +78,7 @@ impl RevisionKVPersistence { self.inner .transaction(|mut t| Box::pin(async move { t.batch_delete_key_start_with(&object_id).await })) .await - }, + } Some(rev_ids) => { let keys = rev_ids .into_iter() @@ -82,7 +88,7 @@ impl RevisionKVPersistence { self.inner .transaction(|mut t| Box::pin(async move { t.batch_delete(keys).await })) .await - }, + } } } } @@ -117,4 +123,6 @@ fn key_value_items_to_revisions(items: Vec) -> RepeatedRevisionPB { } #[inline] -fn make_revision_key(object_id: &str, rev_id: i64) -> String { format!("{}:{}", object_id, rev_id) } +fn make_revision_key(object_id: &str, rev_id: i64) -> String { + format!("{}:{}", object_id, rev_id) +} diff --git a/backend/src/services/web_socket/ws_client.rs b/backend/src/services/web_socket/ws_client.rs index a4ce91fa5e..46eb105b13 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,23 +17,24 @@ 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, channel: WSChannel, receiver: Arc) { tracing::trace!("Add {:?} receiver", channel); self.inner.insert(channel, receiver); } - pub fn get(&self, source: &WSChannel) -> Option> { self.inner.get(source).cloned() } + pub fn get(&self, source: &WSChannel) -> Option> { + self.inner.get(source).cloned() + } } #[derive(Debug)] @@ -43,9 +43,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 { @@ -90,7 +94,7 @@ impl WSClient { match self.ws_receivers.get(&message.channel) { None => { log::error!("Can't find the receiver for {:?}", message.channel); - }, + } Some(handler) => { let client_data = WSClientData { user: self.user.clone(), @@ -98,7 +102,7 @@ impl WSClient { data: Bytes::from(message.data), }; handler.receive(client_data); - }, + } } } } @@ -109,28 +113,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(); - }, + } } } } @@ -138,7 +142,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/tests/api_test/auth_test.rs b/backend/tests/api_test/auth_test.rs index aa8c3c2d46..bcab6d0f4b 100644 --- a/backend/tests/api_test/auth_test.rs +++ b/backend/tests/api_test/auth_test.rs @@ -88,7 +88,7 @@ async fn user_update_name() { let server = TestUserServer::new().await; let name = "tom".to_string(); - let params = UpdateUserParams::new(&server.user_id()).name(&name); + let params = UpdateUserParams::new(server.user_id()).name(&name); server.update_user_profile(params).await.unwrap(); let user = server.get_user_profile().await; diff --git a/backend/tests/document_test/edit_script.rs b/backend/tests/document_test/edit_script.rs index d0b7a05bf5..7bf77a0eea 100644 --- a/backend/tests/document_test/edit_script.rs +++ b/backend/tests/document_test/edit_script.rs @@ -55,6 +55,7 @@ struct ScriptContext { client_editor: Option>, client_sdk: FlowySDKTest, client_user_session: Arc, + #[allow(dead_code)] ws_conn: Arc, server: TestServer, doc_id: String, diff --git a/frontend/app_flowy/packages/flowy_sdk/macos/Classes/binding.h b/frontend/app_flowy/packages/flowy_sdk/macos/Classes/binding.h old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/Cargo.toml b/frontend/rust-lib/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/Cargo.toml b/frontend/rust-lib/dart-ffi/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/Flowy.toml b/frontend/rust-lib/dart-ffi/Flowy.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/binding.h b/frontend/rust-lib/dart-ffi/binding.h old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/c.rs b/frontend/rust-lib/dart-ffi/src/c.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/lib.rs b/frontend/rust-lib/dart-ffi/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/model/ffi_request.rs b/frontend/rust-lib/dart-ffi/src/model/ffi_request.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/model/ffi_response.rs b/frontend/rust-lib/dart-ffi/src/model/ffi_response.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/model/mod.rs b/frontend/rust-lib/dart-ffi/src/model/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/protobuf/mod.rs b/frontend/rust-lib/dart-ffi/src/protobuf/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/protobuf/model/ffi_request.rs b/frontend/rust-lib/dart-ffi/src/protobuf/model/ffi_request.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/protobuf/model/ffi_response.rs b/frontend/rust-lib/dart-ffi/src/protobuf/model/ffi_response.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/protobuf/model/mod.rs b/frontend/rust-lib/dart-ffi/src/protobuf/model/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/protobuf/proto/ffi_request.proto b/frontend/rust-lib/dart-ffi/src/protobuf/proto/ffi_request.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/protobuf/proto/ffi_response.proto b/frontend/rust-lib/dart-ffi/src/protobuf/proto/ffi_response.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-ffi/src/util.rs b/frontend/rust-lib/dart-ffi/src/util.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/Cargo.toml b/frontend/rust-lib/dart-notify/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/Flowy.toml b/frontend/rust-lib/dart-notify/Flowy.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/dart/mod.rs b/frontend/rust-lib/dart-notify/src/dart/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/dart/stream_sender.rs b/frontend/rust-lib/dart-notify/src/dart/stream_sender.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/entities/mod.rs b/frontend/rust-lib/dart-notify/src/entities/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/entities/subject.rs b/frontend/rust-lib/dart-notify/src/entities/subject.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/lib.rs b/frontend/rust-lib/dart-notify/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/protobuf/mod.rs b/frontend/rust-lib/dart-notify/src/protobuf/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/protobuf/model/mod.rs b/frontend/rust-lib/dart-notify/src/protobuf/model/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/protobuf/model/subject.rs b/frontend/rust-lib/dart-notify/src/protobuf/model/subject.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/dart-notify/src/protobuf/proto/subject.proto b/frontend/rust-lib/dart-notify/src/protobuf/proto/subject.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/Cargo.toml b/frontend/rust-lib/flowy-core/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/Flowy.toml b/frontend/rust-lib/flowy-core/Flowy.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/context.rs b/frontend/rust-lib/flowy-core/src/context.rs deleted file mode 100644 index a7b3415751..0000000000 --- a/frontend/rust-lib/flowy-core/src/context.rs +++ /dev/null @@ -1,141 +0,0 @@ -use std::{collections::HashMap, sync::Arc}; - -use chrono::Utc; -use lazy_static::lazy_static; -use parking_lot::RwLock; - -use flowy_collaboration::document::default::{initial_delta, initial_read_me}; -use flowy_core_data_model::{entities::view::CreateViewParams, user_default}; -use flowy_net::entities::NetworkType; - -use crate::{ - entities::workspace::RepeatedWorkspace, - errors::{FlowyError, FlowyResult}, - module::{WorkspaceDatabase, WorkspaceUser}, - notify::{send_dart_notification, WorkspaceNotification}, - services::{server::Server, AppController, TrashController, ViewController, WorkspaceController}, -}; - -lazy_static! { - static ref INIT_WORKSPACE: RwLock> = RwLock::new(HashMap::new()); -} - -pub struct CoreContext { - pub user: Arc, - pub(crate) server: Server, - pub(crate) database: Arc, - pub workspace_controller: Arc, - pub(crate) app_controller: Arc, - pub(crate) view_controller: Arc, - pub(crate) trash_controller: Arc, -} - -impl CoreContext { - pub(crate) fn new( - user: Arc, - server: Server, - database: Arc, - workspace_controller: Arc, - app_controller: Arc, - view_controller: Arc, - trash_controller: Arc, - ) -> Self { - if let Ok(token) = user.token() { - INIT_WORKSPACE.write().insert(token, false); - } - - Self { - user, - server, - database, - workspace_controller, - app_controller, - view_controller, - trash_controller, - } - } - - pub fn network_state_changed(&self, new_type: NetworkType) { - match new_type { - NetworkType::UnknownNetworkType => {} - NetworkType::Wifi => {} - NetworkType::Cell => {} - NetworkType::Ethernet => {} - } - } - - pub async fn user_did_sign_in(&self, token: &str) -> FlowyResult<()> { - log::debug!("workspace initialize after sign in"); - let _ = self.init(token).await?; - Ok(()) - } - - pub async fn user_did_logout(&self) { - // TODO: (nathan) do something here - } - - pub async fn user_session_expired(&self) { - // TODO: (nathan) do something here - } - - pub async fn user_did_sign_up(&self, _token: &str) -> FlowyResult<()> { - log::debug!("Create user default workspace"); - let time = Utc::now(); - let mut workspace = user_default::create_default_workspace(time); - let apps = workspace.take_apps().into_inner(); - let cloned_workspace = workspace.clone(); - - let _ = self.workspace_controller.create_workspace_on_local(workspace).await?; - for mut app in apps { - let app_id = app.id.clone(); - let views = app.take_belongings().into_inner(); - let _ = self.app_controller.create_app_on_local(app).await?; - for (index, view) in views.into_iter().enumerate() { - let view_data = if index == 0 { - initial_read_me().to_json() - } else { - initial_delta().to_json() - }; - self.view_controller.set_latest_view(&view); - let params = CreateViewParams { - belong_to_id: app_id.clone(), - name: view.name, - desc: view.desc, - thumbnail: "".to_string(), - view_type: view.view_type, - view_data, - view_id: view.id.clone(), - }; - let _ = self.view_controller.create_view_from_params(params).await?; - } - } - - let token = self.user.token()?; - let repeated_workspace = RepeatedWorkspace { - items: vec![cloned_workspace], - }; - - send_dart_notification(&token, WorkspaceNotification::UserCreateWorkspace) - .payload(repeated_workspace) - .send(); - - tracing::debug!("Create default workspace after sign up"); - let _ = self.init(&token).await?; - Ok(()) - } - - async fn init(&self, token: &str) -> Result<(), FlowyError> { - if let Some(is_init) = INIT_WORKSPACE.read().get(token) { - if *is_init { - return Ok(()); - } - } - INIT_WORKSPACE.write().insert(token.to_owned(), true); - let _ = self.workspace_controller.init()?; - let _ = self.app_controller.init()?; - let _ = self.view_controller.init()?; - let _ = self.trash_controller.init()?; - - Ok(()) - } -} diff --git a/frontend/rust-lib/flowy-core/src/controller.rs b/frontend/rust-lib/flowy-core/src/controller.rs old mode 100644 new mode 100755 index 16e5410d23..a450dd8842 --- a/frontend/rust-lib/flowy-core/src/controller.rs +++ b/frontend/rust-lib/flowy-core/src/controller.rs @@ -17,13 +17,8 @@ use crate::{ errors::FlowyResult, module::{FolderCouldServiceV1, WorkspaceDatabase, WorkspaceUser}, services::{ - folder_editor::FolderEditor, - persistence::FolderPersistence, - set_current_workspace, - AppController, - TrashController, - ViewController, - WorkspaceController, + folder_editor::FolderEditor, persistence::FolderPersistence, set_current_workspace, AppController, + TrashController, ViewController, WorkspaceController, }, }; @@ -36,19 +31,27 @@ const FOLDER_ID_SPLIT: &str = ":"; #[derive(Clone)] pub struct FolderId(String); impl FolderId { - pub fn new(user_id: &str) -> Self { Self(format!("{}{}{}", user_id, FOLDER_ID_SPLIT, FOLDER_ID)) } + pub fn new(user_id: &str) -> Self { + Self(format!("{}{}{}", user_id, FOLDER_ID_SPLIT, FOLDER_ID)) + } } impl std::fmt::Display for FolderId { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(FOLDER_ID) } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(FOLDER_ID) + } } impl std::fmt::Debug for FolderId { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(FOLDER_ID) } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(FOLDER_ID) + } } impl AsRef for FolderId { - fn as_ref(&self) -> &str { &self.0 } + fn as_ref(&self) -> &str { + &self.0 + } } pub struct FolderManager { @@ -128,15 +131,15 @@ impl FolderManager { let result: Result = data.try_into(); match result { Ok(data) => match self.folder_editor.read().await.clone() { - None => {}, + None => {} Some(editor) => match editor.receive_ws_data(data).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("Folder receive data error: {:?}", e), }, }, Err(e) => { tracing::error!("Folder ws data parser failed: {:?}", e); - }, + } } } @@ -165,7 +168,9 @@ impl FolderManager { self.initialize(user_id, token).await } - pub async fn clear(&self) { *self.folder_editor.write().await = None; } + pub async fn clear(&self) { + *self.folder_editor.write().await = None; + } } struct DefaultFolderBuilder(); @@ -187,7 +192,7 @@ impl DefaultFolderBuilder { } else { initial_delta().to_json() }; - view_controller.set_latest_view(&view); + view_controller.set_latest_view(view); let _ = view_controller .create_view_document_content(&view.id, view_data) .await?; @@ -206,5 +211,7 @@ impl DefaultFolderBuilder { #[cfg(feature = "flowy_unit_test")] impl FolderManager { - pub async fn folder_editor(&self) -> Arc { self.folder_editor.read().await.clone().unwrap() } + pub async fn folder_editor(&self) -> Arc { + self.folder_editor.read().await.clone().unwrap() + } } diff --git a/frontend/rust-lib/flowy-core/src/dart_notification.rs b/frontend/rust-lib/flowy-core/src/dart_notification.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/event.rs b/frontend/rust-lib/flowy-core/src/event.rs old mode 100644 new mode 100755 index 11e18cce93..5972ed299f --- 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")] - OpenDocument = 207, + OpenDocument = 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()] - RestoreAllTrash = 303, + RestoreAllTrash = 303, #[event()] - DeleteAllTrash = 304, + DeleteAllTrash = 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 deleted file mode 100644 index a173670079..0000000000 --- a/frontend/rust-lib/flowy-core/src/event_handler.rs +++ /dev/null @@ -1,111 +0,0 @@ -use crate::{ - context::CoreContext, - errors::FlowyError, - notify::{send_dart_notification, WorkspaceNotification}, - services::{ - get_current_workspace, read_local_workspace_apps, - workspace::sql::{WorkspaceTable, WorkspaceTableSql}, - }, -}; -use flowy_core_data_model::entities::{ - view::View, - workspace::{CurrentWorkspaceSetting, QueryWorkspaceRequest, RepeatedWorkspace, WorkspaceId}, -}; -use lib_dispatch::prelude::{data_result, Data, DataResult, Unit}; -use std::{convert::TryInto, sync::Arc}; - -#[tracing::instrument(skip(data, core), err)] -pub(crate) async fn read_workspaces_handler( - data: Data, - core: Unit>, -) -> DataResult { - let params: WorkspaceId = data.into_inner().try_into()?; - let user_id = core.user.user_id()?; - let conn = &*core.database.db_connection()?; - let workspace_controller = core.workspace_controller.clone(); - - let trash_controller = core.trash_controller.clone(); - let workspaces = conn.immediate_transaction::<_, FlowyError, _>(|| { - let mut workspaces = workspace_controller.read_local_workspaces(params.workspace_id.clone(), &user_id, conn)?; - for workspace in workspaces.iter_mut() { - let apps = read_local_workspace_apps(&workspace.id, trash_controller.clone(), conn)?.into_inner(); - workspace.apps.items = apps; - } - Ok(workspaces) - })?; - - let _ = read_workspaces_on_server(core, user_id, params); - - data_result(workspaces) -} - -#[tracing::instrument(skip(core), err)] -pub async fn read_cur_workspace_handler( - core: Unit>, -) -> DataResult { - let workspace_id = get_current_workspace()?; - let user_id = core.user.user_id()?; - let params = WorkspaceId { - workspace_id: Some(workspace_id.clone()), - }; - let conn = &*core.database.db_connection()?; - let workspace = core - .workspace_controller - .read_local_workspace(workspace_id, &user_id, conn)?; - - let latest_view: Option = core.view_controller.latest_visit_view().unwrap_or(None); - let setting = CurrentWorkspaceSetting { workspace, latest_view }; - let _ = read_workspaces_on_server(core, user_id, params); - data_result(setting) -} - -#[tracing::instrument(level = "debug", skip(core), err)] -fn read_workspaces_on_server( - core: Unit>, - user_id: String, - params: WorkspaceId, -) -> Result<(), FlowyError> { - let (token, server) = (core.user.token()?, core.server.clone()); - let app_ctrl = core.app_controller.clone(); - let view_ctrl = core.view_controller.clone(); - let conn = core.database.db_connection()?; - - tokio::spawn(async move { - // Opti: handle the error and retry? - let workspaces = server.read_workspace(&token, params).await?; - let _ = (&*conn).immediate_transaction::<_, FlowyError, _>(|| { - tracing::debug!("Save {} workspace", workspaces.len()); - for workspace in &workspaces.items { - let m_workspace = workspace.clone(); - let apps = m_workspace.apps.clone().into_inner(); - let workspace_table = WorkspaceTable::new(m_workspace, &user_id); - - let _ = WorkspaceTableSql::create_workspace(workspace_table, &*conn)?; - tracing::debug!("Save {} apps", apps.len()); - for app in apps { - let views = app.belongings.clone().into_inner(); - match app_ctrl.save_app(app, &*conn) { - 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(_) => {} - Err(e) => log::error!("create view failed: {:?}", e), - } - } - } - } - Ok(()) - })?; - - send_dart_notification(&token, WorkspaceNotification::WorkspaceListUpdated) - .payload(workspaces) - .send(); - Result::<(), FlowyError>::Ok(()) - }); - - Ok(()) -} diff --git a/frontend/rust-lib/flowy-core/src/lib.rs b/frontend/rust-lib/flowy-core/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/macros.rs b/frontend/rust-lib/flowy-core/src/macros.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/module.rs b/frontend/rust-lib/flowy-core/src/module.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/protobuf/mod.rs b/frontend/rust-lib/flowy-core/src/protobuf/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/protobuf/model/dart_notification.rs b/frontend/rust-lib/flowy-core/src/protobuf/model/dart_notification.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/protobuf/model/event.rs b/frontend/rust-lib/flowy-core/src/protobuf/model/event.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/protobuf/model/mod.rs b/frontend/rust-lib/flowy-core/src/protobuf/model/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/protobuf/proto/dart_notification.proto b/frontend/rust-lib/flowy-core/src/protobuf/proto/dart_notification.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/protobuf/proto/event.proto b/frontend/rust-lib/flowy-core/src/protobuf/proto/event.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/app/controller.rs b/frontend/rust-lib/flowy-core/src/services/app/controller.rs old mode 100644 new mode 100755 index 111cef1522..87cefdea2d --- a/frontend/rust-lib/flowy-core/src/services/app/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/app/controller.rs @@ -8,8 +8,7 @@ use crate::{ module::{FolderCouldServiceV1, WorkspaceUser}, services::{ persistence::{AppChangeset, FolderPersistence, FolderPersistenceTransaction}, - TrashController, - TrashEvent, + TrashController, TrashEvent, }, }; @@ -125,11 +124,11 @@ impl AppController { let server = self.cloud_service.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(()) @@ -151,11 +150,11 @@ impl AppController { send_dart_notification(&app.id, WorkspaceNotification::AppUpdated) .payload(app) .send(); - }, + } Err(e) => log::error!("Save app failed: {:?}", e), } - }, - Ok(None) => {}, + } + Ok(None) => {} Err(e) => log::error!("Read app failed: {:?}", e), } }); @@ -200,7 +199,7 @@ async fn handle_trash_event( }) .await; let _ = ret.send(result).await; - }, + } TrashEvent::Delete(identifiers, ret) => { let result = persistence .begin_transaction(|transaction| { @@ -218,7 +217,7 @@ async fn handle_trash_event( }) .await; let _ = ret.send(result).await; - }, + } } } diff --git a/frontend/rust-lib/flowy-core/src/services/app/event_handler.rs b/frontend/rust-lib/flowy-core/src/services/app/event_handler.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/app/mod.rs b/frontend/rust-lib/flowy-core/src/services/app/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/folder_editor.rs b/frontend/rust-lib/flowy-core/src/services/folder_editor.rs old mode 100644 new mode 100755 index 70dbafa8ca..6136e8257a --- a/frontend/rust-lib/flowy-core/src/services/folder_editor.rs +++ b/frontend/rust-lib/flowy-core/src/services/folder_editor.rs @@ -7,11 +7,7 @@ use flowy_collaboration::{ use crate::controller::FolderId; use flowy_error::{FlowyError, FlowyResult}; use flowy_sync::{ - RevisionCache, - RevisionCloudService, - RevisionManager, - RevisionObjectBuilder, - RevisionWebSocket, + RevisionCache, RevisionCloudService, RevisionManager, RevisionObjectBuilder, RevisionWebSocket, RevisionWebSocketManager, }; use lib_infra::future::FutureResult; @@ -112,5 +108,7 @@ impl RevisionCloudService for FolderRevisionCloudServiceImpl { #[cfg(feature = "flowy_unit_test")] impl FolderEditor { - 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-core/src/services/mod.rs b/frontend/rust-lib/flowy-core/src/services/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/migration.rs b/frontend/rust-lib/flowy-core/src/services/persistence/migration.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/mod.rs b/frontend/rust-lib/flowy-core/src/services/persistence/mod.rs old mode 100644 new mode 100755 index a39ce94613..bfeb87fb07 --- a/frontend/rust-lib/flowy-core/src/services/persistence/mod.rs +++ b/frontend/rust-lib/flowy-core/src/services/persistence/mod.rs @@ -95,7 +95,9 @@ impl FolderPersistence { } } - pub fn db_pool(&self) -> FlowyResult> { self.database.db_pool() } + pub fn db_pool(&self) -> FlowyResult> { + self.database.db_pool() + } pub async fn initialize(&self, user_id: &str, folder_id: &FolderId) -> FlowyResult<()> { let migrations = FolderMigration::new(user_id, self.database.clone()); diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/version_1/app_sql.rs b/frontend/rust-lib/flowy-core/src/services/persistence/version_1/app_sql.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/version_1/mod.rs b/frontend/rust-lib/flowy-core/src/services/persistence/version_1/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/version_1/trash_sql.rs b/frontend/rust-lib/flowy-core/src/services/persistence/version_1/trash_sql.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/version_1/v1_impl.rs b/frontend/rust-lib/flowy-core/src/services/persistence/version_1/v1_impl.rs old mode 100644 new mode 100755 index 7b20026dc4..092f6b07a1 --- a/frontend/rust-lib/flowy-core/src/services/persistence/version_1/v1_impl.rs +++ b/frontend/rust-lib/flowy-core/src/services/persistence/version_1/v1_impl.rs @@ -4,8 +4,7 @@ use crate::services::persistence::{ view_sql::{ViewChangeset, ViewTableSql}, workspace_sql::{WorkspaceChangeset, WorkspaceTableSql}, }, - FolderPersistenceTransaction, - TrashTableSql, + FolderPersistenceTransaction, TrashTableSql, }; use flowy_core_data_model::entities::{ app::App, @@ -103,7 +102,7 @@ impl<'a> FolderPersistenceTransaction for V1Transaction<'a> { Ok(RepeatedTrash { items: vec![Trash::from(table)], }) - }, + } } } @@ -112,10 +111,10 @@ impl<'a> FolderPersistenceTransaction for V1Transaction<'a> { None => TrashTableSql::delete_all(&*self.0), Some(trash_ids) => { for trash_id in &trash_ids { - let _ = TrashTableSql::delete_trash(&trash_id, &*self.0)?; + let _ = TrashTableSql::delete_trash(trash_id, &*self.0)?; } Ok(()) - }, + } } } } @@ -137,33 +136,59 @@ where (**self).update_workspace(changeset) } - fn delete_workspace(&self, workspace_id: &str) -> FlowyResult<()> { (**self).delete_workspace(workspace_id) } + fn delete_workspace(&self, workspace_id: &str) -> FlowyResult<()> { + (**self).delete_workspace(workspace_id) + } - fn create_app(&self, app: App) -> FlowyResult<()> { (**self).create_app(app) } + fn create_app(&self, app: App) -> FlowyResult<()> { + (**self).create_app(app) + } - fn update_app(&self, changeset: AppChangeset) -> FlowyResult<()> { (**self).update_app(changeset) } + fn update_app(&self, changeset: AppChangeset) -> FlowyResult<()> { + (**self).update_app(changeset) + } - fn read_app(&self, app_id: &str) -> FlowyResult { (**self).read_app(app_id) } + fn read_app(&self, app_id: &str) -> FlowyResult { + (**self).read_app(app_id) + } fn read_workspace_apps(&self, workspace_id: &str) -> FlowyResult> { (**self).read_workspace_apps(workspace_id) } - fn delete_app(&self, app_id: &str) -> FlowyResult { (**self).delete_app(app_id) } + fn delete_app(&self, app_id: &str) -> FlowyResult { + (**self).delete_app(app_id) + } - fn create_view(&self, view: View) -> FlowyResult<()> { (**self).create_view(view) } + fn create_view(&self, view: View) -> FlowyResult<()> { + (**self).create_view(view) + } - fn read_view(&self, view_id: &str) -> FlowyResult { (**self).read_view(view_id) } + fn read_view(&self, view_id: &str) -> FlowyResult { + (**self).read_view(view_id) + } - fn read_views(&self, belong_to_id: &str) -> FlowyResult> { (**self).read_views(belong_to_id) } + fn read_views(&self, belong_to_id: &str) -> FlowyResult> { + (**self).read_views(belong_to_id) + } - fn update_view(&self, changeset: ViewChangeset) -> FlowyResult<()> { (**self).update_view(changeset) } + fn update_view(&self, changeset: ViewChangeset) -> FlowyResult<()> { + (**self).update_view(changeset) + } - fn delete_view(&self, view_id: &str) -> FlowyResult<()> { (**self).delete_view(view_id) } + fn delete_view(&self, view_id: &str) -> FlowyResult<()> { + (**self).delete_view(view_id) + } - fn create_trash(&self, trashes: Vec) -> FlowyResult<()> { (**self).create_trash(trashes) } + fn create_trash(&self, trashes: Vec) -> FlowyResult<()> { + (**self).create_trash(trashes) + } - fn read_trash(&self, trash_id: Option) -> FlowyResult { (**self).read_trash(trash_id) } + fn read_trash(&self, trash_id: Option) -> FlowyResult { + (**self).read_trash(trash_id) + } - fn delete_trash(&self, trash_ids: Option>) -> FlowyResult<()> { (**self).delete_trash(trash_ids) } + fn delete_trash(&self, trash_ids: Option>) -> FlowyResult<()> { + (**self).delete_trash(trash_ids) + } } diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/version_1/view_sql.rs b/frontend/rust-lib/flowy-core/src/services/persistence/version_1/view_sql.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/version_1/workspace_sql.rs b/frontend/rust-lib/flowy-core/src/services/persistence/version_1/workspace_sql.rs old mode 100644 new mode 100755 index 74ff142a85..ce95d09275 --- a/frontend/rust-lib/flowy-core/src/services/persistence/version_1/workspace_sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/persistence/version_1/workspace_sql.rs @@ -17,7 +17,7 @@ impl WorkspaceTableSql { workspace: Workspace, conn: &SqliteConnection, ) -> Result<(), FlowyError> { - let table = WorkspaceTable::new(workspace, &user_id); + let table = WorkspaceTable::new(workspace, user_id); match diesel_record_count!(workspace_table, &table.id, conn) { 0 => diesel_insert_table!(workspace_table, &table, conn), _ => { diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/version_2/mod.rs b/frontend/rust-lib/flowy-core/src/services/persistence/version_2/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/persistence/version_2/v2_impl.rs b/frontend/rust-lib/flowy-core/src/services/persistence/version_2/v2_impl.rs old mode 100644 new mode 100755 index ce358dec70..233e95e116 --- a/frontend/rust-lib/flowy-core/src/services/persistence/version_2/v2_impl.rs +++ b/frontend/rust-lib/flowy-core/src/services/persistence/version_2/v2_impl.rs @@ -70,7 +70,7 @@ impl FolderPersistenceTransaction for FolderEditor { match workspaces.first() { None => { Err(FlowyError::record_not_found().context(format!("can't find workspace with id {}", workspace_id))) - }, + } Some(workspace) => Ok(workspace.apps.clone().take_items()), } } @@ -154,33 +154,59 @@ where (**self).update_workspace(changeset) } - fn delete_workspace(&self, workspace_id: &str) -> FlowyResult<()> { (**self).delete_workspace(workspace_id) } + fn delete_workspace(&self, workspace_id: &str) -> FlowyResult<()> { + (**self).delete_workspace(workspace_id) + } - fn create_app(&self, app: App) -> FlowyResult<()> { (**self).create_app(app) } + fn create_app(&self, app: App) -> FlowyResult<()> { + (**self).create_app(app) + } - fn update_app(&self, changeset: AppChangeset) -> FlowyResult<()> { (**self).update_app(changeset) } + fn update_app(&self, changeset: AppChangeset) -> FlowyResult<()> { + (**self).update_app(changeset) + } - fn read_app(&self, app_id: &str) -> FlowyResult { (**self).read_app(app_id) } + fn read_app(&self, app_id: &str) -> FlowyResult { + (**self).read_app(app_id) + } fn read_workspace_apps(&self, workspace_id: &str) -> FlowyResult> { (**self).read_workspace_apps(workspace_id) } - fn delete_app(&self, app_id: &str) -> FlowyResult { (**self).delete_app(app_id) } + fn delete_app(&self, app_id: &str) -> FlowyResult { + (**self).delete_app(app_id) + } - fn create_view(&self, view: View) -> FlowyResult<()> { (**self).create_view(view) } + fn create_view(&self, view: View) -> FlowyResult<()> { + (**self).create_view(view) + } - fn read_view(&self, view_id: &str) -> FlowyResult { (**self).read_view(view_id) } + fn read_view(&self, view_id: &str) -> FlowyResult { + (**self).read_view(view_id) + } - fn read_views(&self, belong_to_id: &str) -> FlowyResult> { (**self).read_views(belong_to_id) } + fn read_views(&self, belong_to_id: &str) -> FlowyResult> { + (**self).read_views(belong_to_id) + } - fn update_view(&self, changeset: ViewChangeset) -> FlowyResult<()> { (**self).update_view(changeset) } + fn update_view(&self, changeset: ViewChangeset) -> FlowyResult<()> { + (**self).update_view(changeset) + } - fn delete_view(&self, view_id: &str) -> FlowyResult<()> { (**self).delete_view(view_id) } + fn delete_view(&self, view_id: &str) -> FlowyResult<()> { + (**self).delete_view(view_id) + } - fn create_trash(&self, trashes: Vec) -> FlowyResult<()> { (**self).create_trash(trashes) } + fn create_trash(&self, trashes: Vec) -> FlowyResult<()> { + (**self).create_trash(trashes) + } - fn read_trash(&self, trash_id: Option) -> FlowyResult { (**self).read_trash(trash_id) } + fn read_trash(&self, trash_id: Option) -> FlowyResult { + (**self).read_trash(trash_id) + } - fn delete_trash(&self, trash_ids: Option>) -> FlowyResult<()> { (**self).delete_trash(trash_ids) } + fn delete_trash(&self, trash_ids: Option>) -> FlowyResult<()> { + (**self).delete_trash(trash_ids) + } } 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 deleted file mode 100644 index 2dfb7c9deb..0000000000 --- a/frontend/rust-lib/flowy-core/src/services/server/server_api.rs +++ /dev/null @@ -1,172 +0,0 @@ -use crate::{ - entities::{ - app::{App, AppId, CreateAppParams, UpdateAppParams}, - trash::{RepeatedTrash, RepeatedTrashId}, - view::{CreateViewParams, RepeatedViewId, UpdateViewParams, View, ViewId}, - workspace::{CreateWorkspaceParams, RepeatedWorkspace, UpdateWorkspaceParams, Workspace, WorkspaceId}, - }, - errors::{ErrorCode, FlowyError}, - notify::{send_dart_notification, WorkspaceNotification}, - services::server::WorkspaceServerAPI, -}; -use backend_service::{configuration::ClientServerConfiguration, http_request::*, middleware::*}; -use lib_infra::future::FutureResult; - -pub struct WorkspaceHttpServer { - config: ClientServerConfiguration, -} - -impl WorkspaceHttpServer { - pub fn new(config: ClientServerConfiguration) -> WorkspaceHttpServer { - Self { config } - } -} - -impl WorkspaceServerAPI for WorkspaceHttpServer { - fn init(&self) { - let mut rx = BACKEND_API_MIDDLEWARE.invalid_token_subscribe(); - tokio::spawn(async move { - while let Ok(invalid_token) = rx.recv().await { - let error = FlowyError::new(ErrorCode::UserUnauthorized, ""); - send_dart_notification(&invalid_token, WorkspaceNotification::UserUnauthorized) - .error(error) - .send() - } - }); - } - - fn create_workspace(&self, token: &str, params: CreateWorkspaceParams) -> FutureResult { - let token = token.to_owned(); - let url = self.config.workspace_url(); - FutureResult::new(async move { - let workspace = create_workspace_request(&token, params, &url).await?; - Ok(workspace) - }) - } - - fn read_workspace(&self, token: &str, params: WorkspaceId) -> FutureResult { - let token = token.to_owned(); - let url = self.config.workspace_url(); - FutureResult::new(async move { - let repeated_workspace = read_workspaces_request(&token, params, &url).await?; - Ok(repeated_workspace) - }) - } - - fn update_workspace(&self, token: &str, params: UpdateWorkspaceParams) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.workspace_url(); - FutureResult::new(async move { - let _ = update_workspace_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn delete_workspace(&self, token: &str, params: WorkspaceId) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.workspace_url(); - FutureResult::new(async move { - let _ = delete_workspace_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn create_view(&self, token: &str, params: CreateViewParams) -> FutureResult { - let token = token.to_owned(); - let url = self.config.view_url(); - FutureResult::new(async move { - let view = create_view_request(&token, params, &url).await?; - Ok(view) - }) - } - - fn read_view(&self, token: &str, params: ViewId) -> FutureResult, FlowyError> { - let token = token.to_owned(); - let url = self.config.view_url(); - FutureResult::new(async move { - let view = read_view_request(&token, params, &url).await?; - Ok(view) - }) - } - - fn delete_view(&self, token: &str, params: RepeatedViewId) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.view_url(); - FutureResult::new(async move { - let _ = delete_view_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn update_view(&self, token: &str, params: UpdateViewParams) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.view_url(); - FutureResult::new(async move { - let _ = update_view_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn create_app(&self, token: &str, params: CreateAppParams) -> FutureResult { - let token = token.to_owned(); - let url = self.config.app_url(); - FutureResult::new(async move { - let app = create_app_request(&token, params, &url).await?; - Ok(app) - }) - } - - fn read_app(&self, token: &str, params: AppId) -> FutureResult, FlowyError> { - let token = token.to_owned(); - let url = self.config.app_url(); - FutureResult::new(async move { - let app = read_app_request(&token, params, &url).await?; - Ok(app) - }) - } - - fn update_app(&self, token: &str, params: UpdateAppParams) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.app_url(); - FutureResult::new(async move { - let _ = update_app_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn delete_app(&self, token: &str, params: AppId) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.app_url(); - FutureResult::new(async move { - let _ = delete_app_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn create_trash(&self, token: &str, params: RepeatedTrashId) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.trash_url(); - FutureResult::new(async move { - let _ = create_trash_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn delete_trash(&self, token: &str, params: RepeatedTrashId) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.trash_url(); - FutureResult::new(async move { - let _ = delete_trash_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn read_trash(&self, token: &str) -> FutureResult { - let token = token.to_owned(); - let url = self.config.trash_url(); - FutureResult::new(async move { - let repeated_trash = read_trash_request(&token, &url).await?; - Ok(repeated_trash) - }) - } -} diff --git a/frontend/rust-lib/flowy-core/src/services/trash/controller.rs b/frontend/rust-lib/flowy-core/src/services/trash/controller.rs old mode 100644 new mode 100755 index 848dd88d28..d5087358b3 --- a/frontend/rust-lib/flowy-core/src/services/trash/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/trash/controller.rs @@ -119,9 +119,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), }, } @@ -179,7 +179,9 @@ impl TrashController { Ok(()) } - pub fn subscribe(&self) -> broadcast::Receiver { self.notify.subscribe() } + pub fn subscribe(&self) -> broadcast::Receiver { + self.notify.subscribe() + } pub async fn read_trash(&self) -> Result { let repeated_trash = self @@ -213,7 +215,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), } }); @@ -227,7 +229,7 @@ impl TrashController { let server = self.cloud_service.clone(); let _ = tokio::spawn(async move { match server.delete_trash(&token, trash_identifiers).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("Delete trash failed: {:?}", e), } }); @@ -254,10 +256,10 @@ impl TrashController { match result { Ok(repeated_trash) => { notify_trash_changed(repeated_trash); - }, + } Err(e) => log::error!("Save trash failed: {:?}", e), } - }, + } Err(e) => log::error!("Read trash failed: {:?}", e), } }); @@ -307,7 +309,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() { @@ -315,7 +317,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() { @@ -323,7 +325,7 @@ impl TrashEvent { } else { Some(TrashEvent::NewTrash(identifiers, sender)) } - }, + } } } } diff --git a/frontend/rust-lib/flowy-core/src/services/trash/event_handler.rs b/frontend/rust-lib/flowy-core/src/services/trash/event_handler.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/trash/mod.rs b/frontend/rust-lib/flowy-core/src/services/trash/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/view/controller.rs b/frontend/rust-lib/flowy-core/src/services/view/controller.rs old mode 100644 new mode 100755 index b927904266..30f2a53834 --- 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::{ module::{FolderCouldServiceV1, WorkspaceUser}, services::{ persistence::{FolderPersistence, FolderPersistenceTransaction, ViewChangeset}, - TrashController, - TrashEvent, + TrashController, TrashEvent, }, }; use flowy_core_data_model::entities::share::{ExportData, ExportParams}; @@ -246,11 +245,13 @@ impl ViewController { .begin_transaction(|transaction| transaction.read_view(&view_id)) .await?; Ok(Some(view)) - }, + } } } - 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 { @@ -267,11 +268,11 @@ impl ViewController { let server = self.cloud_service.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(()) @@ -294,11 +295,11 @@ impl ViewController { send_dart_notification(&view.id, WorkspaceNotification::ViewUpdated) .payload(view.clone()) .send(); - }, + } Err(e) => log::error!("Save view failed: {:?}", e), } - }, - Ok(None) => {}, + } + Ok(None) => {} Err(e) => log::error!("Read view failed: {:?}", e), } }); @@ -353,7 +354,7 @@ async fn handle_trash_event( }) .await; let _ = ret.send(result).await; - }, + } TrashEvent::Putback(identifiers, ret) => { let result = persistence .begin_transaction(|transaction| { @@ -366,7 +367,7 @@ async fn handle_trash_event( }) .await; let _ = ret.send(result).await; - }, + } TrashEvent::Delete(identifiers, ret) => { let result = persistence .begin_transaction(|transaction| { @@ -386,7 +387,7 @@ async fn handle_trash_event( }) .await; let _ = ret.send(result).await; - }, + } } } @@ -414,7 +415,7 @@ fn notify_views_changed<'a>( ) -> FlowyResult<()> { let repeated_view = read_belonging_views_on_local(belong_to_id, trash_controller.clone(), transaction)?; 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 old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/view/mod.rs b/frontend/rust-lib/flowy-core/src/services/view/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/web_socket.rs b/frontend/rust-lib/flowy-core/src/services/web_socket.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs b/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs old mode 100644 new mode 100755 index 18a3401114..00cff40d84 --- a/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs @@ -4,8 +4,7 @@ use crate::{ module::{FolderCouldServiceV1, WorkspaceUser}, services::{ persistence::{FolderPersistence, FolderPersistenceTransaction, WorkspaceChangeset}, - read_local_workspace_apps, - TrashController, + read_local_workspace_apps, TrashController, }, }; use flowy_core_data_model::entities::{app::RepeatedApp, workspace::*}; @@ -105,7 +104,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")) } } @@ -162,11 +161,11 @@ impl WorkspaceController { let (token, server) = (self.user.token()?, self.cloud_service.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(()) @@ -180,11 +179,11 @@ impl WorkspaceController { let (token, server) = (self.user.token()?, self.cloud_service.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(()) @@ -193,14 +192,16 @@ impl WorkspaceController { const CURRENT_WORKSPACE_ID: &str = "current_workspace_id"; -pub fn set_current_workspace(workspace_id: &str) { KV::set_str(CURRENT_WORKSPACE_ID, workspace_id.to_owned()); } +pub 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/event_handler.rs b/frontend/rust-lib/flowy-core/src/services/workspace/event_handler.rs old mode 100644 new mode 100755 index 85787fc08c..4747f46c1d --- a/frontend/rust-lib/flowy-core/src/services/workspace/event_handler.rs +++ b/frontend/rust-lib/flowy-core/src/services/workspace/event_handler.rs @@ -116,14 +116,14 @@ fn read_workspaces_on_server( for app in apps { let views = app.belongings.clone().into_inner(); match transaction.create_app(app) { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("create app failed: {:?}", e), } tracing::debug!("Save {} views", views.len()); for view in views { match transaction.create_view(view) { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("create view failed: {:?}", e), } } diff --git a/frontend/rust-lib/flowy-core/src/services/workspace/mod.rs b/frontend/rust-lib/flowy-core/src/services/workspace/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/src/util.rs b/frontend/rust-lib/flowy-core/src/util.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/tests/workspace/folder_test.rs b/frontend/rust-lib/flowy-core/tests/workspace/folder_test.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/tests/workspace/helper.rs b/frontend/rust-lib/flowy-core/tests/workspace/helper.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/tests/workspace/main.rs b/frontend/rust-lib/flowy-core/tests/workspace/main.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-core/tests/workspace/script.rs b/frontend/rust-lib/flowy-core/tests/workspace/script.rs old mode 100644 new mode 100755 index f6b6d0d097..1f8fde85fa --- a/frontend/rust-lib/flowy-core/tests/workspace/script.rs +++ b/frontend/rust-lib/flowy-core/tests/workspace/script.rs @@ -103,11 +103,11 @@ impl FolderTest { FolderScript::ReadAllWorkspaces => { let all_workspace = read_workspace(sdk, None).await; self.all_workspace = all_workspace; - }, + } FolderScript::CreateWorkspace { name, desc } => { let workspace = create_workspace(sdk, &name, &desc).await; self.workspace = workspace; - }, + } FolderScript::AssertWorkspaceJson(expected_json) => { let workspace = read_workspace(sdk, Some(self.workspace.id.clone())) .await @@ -115,74 +115,74 @@ impl FolderTest { .unwrap(); let json = serde_json::to_string(&workspace).unwrap(); assert_eq!(json, expected_json); - }, + } FolderScript::AssertWorkspace(workspace) => { assert_eq!(self.workspace, workspace); - }, + } FolderScript::ReadWorkspace(workspace_id) => { let workspace = read_workspace(sdk, workspace_id).await.pop().unwrap(); self.workspace = workspace; - }, + } FolderScript::CreateApp { name, desc } => { - let app = create_app(&sdk, &self.workspace.id, name, desc).await; + let app = create_app(sdk, &self.workspace.id, name, desc).await; self.app = app; - }, + } FolderScript::AssertAppJson(expected_json) => { let json = serde_json::to_string(&self.app).unwrap(); assert_eq!(json, expected_json); - }, + } FolderScript::AssertApp(app) => { assert_eq!(self.app, app); - }, + } FolderScript::ReadApp(app_id) => { - let app = read_app(&sdk, &app_id).await; + let app = read_app(sdk, &app_id).await; self.app = app; - }, + } FolderScript::UpdateApp { name, desc } => { - update_app(&sdk, &self.app.id, name, desc).await; - }, + update_app(sdk, &self.app.id, name, desc).await; + } FolderScript::DeleteApp => { - delete_app(&sdk, &self.app.id).await; - }, + delete_app(sdk, &self.app.id).await; + } FolderScript::CreateView { name, desc } => { - let view = create_view(&sdk, &self.app.id, name, desc, ViewType::Doc).await; + let view = create_view(sdk, &self.app.id, name, desc, ViewType::Doc).await; self.view = view; - }, + } FolderScript::AssertView(view) => { assert_eq!(self.view, view); - }, + } FolderScript::ReadView(view_id) => { - let view = read_view(&sdk, vec![view_id]).await; + let view = read_view(sdk, vec![view_id]).await; self.view = view; - }, + } FolderScript::UpdateView { name, desc } => { - update_view(&sdk, &self.view.id, name, desc).await; - }, + update_view(sdk, &self.view.id, name, desc).await; + } FolderScript::DeleteView => { - delete_view(&sdk, vec![self.view.id.clone()]).await; - }, + delete_view(sdk, vec![self.view.id.clone()]).await; + } FolderScript::DeleteViews(view_ids) => { - delete_view(&sdk, view_ids).await; - }, + delete_view(sdk, view_ids).await; + } FolderScript::RestoreAppFromTrash => { - restore_app_from_trash(&sdk, &self.app.id).await; - }, + restore_app_from_trash(sdk, &self.app.id).await; + } FolderScript::RestoreViewFromTrash => { - restore_view_from_trash(&sdk, &self.view.id).await; - }, + restore_view_from_trash(sdk, &self.view.id).await; + } FolderScript::ReadTrash => { - let trash = read_trash(&sdk).await; + let trash = read_trash(sdk).await; self.trash = trash.into_inner(); - }, + } FolderScript::DeleteAllTrash => { - delete_all_trash(&sdk).await; + delete_all_trash(sdk).await; self.trash = vec![]; - }, + } FolderScript::OpenDocument => { - let document_info = open_document(&sdk, &self.view.id).await; + let document_info = open_document(sdk, &self.view.id).await; self.document_info = Some(document_info); - }, + } FolderScript::AssertRevisionState { rev_id, state } => { let record = cache.get(rev_id).await.unwrap(); assert_eq!(record.state, state); @@ -191,21 +191,21 @@ impl FolderTest { // Make sure everything is written. sleep(Duration::from_millis(2 * REVISION_WRITE_INTERVAL_IN_MILLIS)).await; } - }, + } FolderScript::AssertCurrentRevId(rev_id) => { assert_eq!(rev_manager.rev_id(), rev_id); - }, + } FolderScript::AssertNextSyncRevId(rev_id) => { let next_revision = rev_manager.next_sync_revision().await.unwrap(); if rev_id.is_none() { - assert_eq!(next_revision.is_none(), true, "Next revision should be None"); + assert!(next_revision.is_none(), "Next revision should be None"); return; } let next_revision = next_revision.unwrap(); let mut receiver = rev_manager.revision_ack_receiver(); let _ = receiver.recv().await; assert_eq!(next_revision.rev_id, rev_id.unwrap()); - }, + } } } } diff --git a/frontend/rust-lib/flowy-database/.env b/frontend/rust-lib/flowy-database/.env old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/Cargo.toml b/frontend/rust-lib/flowy-database/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/diesel.toml b/frontend/rust-lib/flowy-database/diesel.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/.gitkeep b/frontend/rust-lib/flowy-database/migrations/.gitkeep old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/down.sql b/frontend/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/down.sql old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/up.sql b/frontend/rust-lib/flowy-database/migrations/2021-07-09-063045_flowy-user/up.sql old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/2021-07-14-022241_flowy-user/down.sql b/frontend/rust-lib/flowy-database/migrations/2021-07-14-022241_flowy-user/down.sql old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/2021-07-14-022241_flowy-user/up.sql b/frontend/rust-lib/flowy-database/migrations/2021-07-14-022241_flowy-user/up.sql old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/2021-07-22-234458_flowy-editor/down.sql b/frontend/rust-lib/flowy-database/migrations/2021-07-22-234458_flowy-editor/down.sql old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/2021-07-22-234458_flowy-editor/up.sql b/frontend/rust-lib/flowy-database/migrations/2021-07-22-234458_flowy-editor/up.sql old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/2021-09-22-074638_flowy-doc-op/down.sql b/frontend/rust-lib/flowy-database/migrations/2021-09-22-074638_flowy-doc-op/down.sql old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/migrations/2021-09-22-074638_flowy-doc-op/up.sql b/frontend/rust-lib/flowy-database/migrations/2021-09-22-074638_flowy-doc-op/up.sql old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/src/kv/kv.rs b/frontend/rust-lib/flowy-database/src/kv/kv.rs old mode 100644 new mode 100755 index 71c3f1bf1d..e9dfd57a5a --- a/frontend/rust-lib/flowy-database/src/kv/kv.rs +++ b/frontend/rust-lib/flowy-database/src/kv/kv.rs @@ -216,7 +216,7 @@ mod tests { assert_eq!(KV::get_str("2"), None); KV::set_bool("1", true); - assert_eq!(KV::get_bool("1").unwrap(), true); + assert!(KV::get_bool("1").unwrap()); assert_eq!(KV::get_bool("2"), None); } diff --git a/frontend/rust-lib/flowy-database/src/kv/mod.rs b/frontend/rust-lib/flowy-database/src/kv/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/src/kv/schema.rs b/frontend/rust-lib/flowy-database/src/kv/schema.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/src/lib.rs b/frontend/rust-lib/flowy-database/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/src/macros.rs b/frontend/rust-lib/flowy-database/src/macros.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-database/src/schema.rs b/frontend/rust-lib/flowy-database/src/schema.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/Cargo.toml b/frontend/rust-lib/flowy-document/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/Flowy.toml b/frontend/rust-lib/flowy-document/Flowy.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/src/controller.rs b/frontend/rust-lib/flowy-document/src/controller.rs old mode 100644 new mode 100755 index b5d7d63703..8db6b4e677 --- a/frontend/rust-lib/flowy-document/src/controller.rs +++ b/frontend/rust-lib/flowy-document/src/controller.rs @@ -108,13 +108,13 @@ impl FlowyDocumentManager { Ok(data) => match self.ws_receivers.get(&data.object_id) { None => tracing::error!("Can't find any source handler for {:?}-{:?}", data.object_id, data.ty), Some(handler) => match handler.receive_ws_data(data).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("{}", e), }, }, Err(e) => { tracing::error!("Document ws data parser failed: {:?}", e); - }, + } } } @@ -130,8 +130,8 @@ impl FlowyDocumentManager { 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), } } @@ -150,7 +150,7 @@ impl FlowyDocumentManager { }); let doc_editor = ClientDocumentEditor::new(doc_id, user, rev_manager, self.web_socket.clone(), server).await?; self.add_ws_receiver(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) } @@ -167,7 +167,9 @@ impl FlowyDocumentManager { self.ws_receivers.insert(object_id.to_string(), receiver); } - fn remove_ws_receiver(&self, id: &str) { self.ws_receivers.remove(id); } + fn remove_ws_receiver(&self, id: &str) { + self.ws_receivers.remove(id); + } } struct DocumentRevisionCloudServiceImpl { @@ -194,7 +196,7 @@ impl RevisionCloudService for DocumentRevisionCloudServiceImpl { let revision = Revision::new(&doc.doc_id, doc.base_rev_id, doc.rev_id, delta_data, &user_id, doc_md5); Ok(vec![revision]) - }, + } } }) } @@ -205,7 +207,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) { @@ -214,10 +218,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/editor.rs b/frontend/rust-lib/flowy-document/src/core/editor.rs old mode 100644 new mode 100755 index ef9ea80928..63dceb6e8d --- a/frontend/rust-lib/flowy-document/src/core/editor.rs +++ b/frontend/rust-lib/flowy-document/src/core/editor.rs @@ -1,8 +1,7 @@ use crate::{ core::{make_document_ws_manager, EditorCommand, EditorCommandQueue, EditorCommandSender}, errors::FlowyError, - DocumentUser, - DocumentWSReceiver, + DocumentUser, DocumentWSReceiver, }; use bytes::Bytes; use flowy_collaboration::{ @@ -12,11 +11,7 @@ use flowy_collaboration::{ }; use flowy_error::{internal_error, FlowyResult}; use flowy_sync::{ - RevisionCloudService, - RevisionManager, - RevisionObjectBuilder, - RevisionWebSocket, - RevisionWebSocketManager, + RevisionCloudService, RevisionManager, RevisionObjectBuilder, RevisionWebSocket, RevisionWebSocketManager, }; use lib_ot::{ core::{Interval, Operation}, @@ -160,13 +155,19 @@ impl ClientDocumentEditor { Ok(()) } - 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.clone() } + pub(crate) fn ws_handler(&self) -> Arc { + self.ws_manager.clone() + } } impl std::ops::Drop for ClientDocumentEditor { - fn drop(&mut self) { tracing::trace!("{} ClientDocumentEditor was dropped", self.doc_id) } + fn drop(&mut self) { + tracing::trace!("{} ClientDocumentEditor was dropped", self.doc_id) + } } // The edit queue will exit after the EditorCommandSender was dropped. @@ -199,7 +200,9 @@ impl ClientDocumentEditor { Ok(delta) } - pub fn rev_manager(&self) -> Arc { self.rev_manager.clone() } + pub fn rev_manager(&self) -> Arc { + self.rev_manager.clone() + } } struct DocumentInfoBuilder(); diff --git a/frontend/rust-lib/flowy-document/src/core/mod.rs b/frontend/rust-lib/flowy-document/src/core/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/src/core/queue.rs b/frontend/rust-lib/flowy-document/src/core/queue.rs old mode 100644 new mode 100755 index 99d31c53b5..87265b81d1 --- a/frontend/rust-lib/flowy-document/src/core/queue.rs +++ b/frontend/rust-lib/flowy-document/src/core/queue.rs @@ -53,7 +53,7 @@ impl EditorCommandQueue { stream .for_each(|command| async { match self.handle_command(command).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::debug!("[EditCommandQueue]: {}", e), } }) @@ -70,21 +70,21 @@ impl EditorCommandQueue { drop(document); let _ = self.save_local_delta(delta, md5).await?; let _ = ret.send(Ok(())); - }, + } EditorCommand::ComposeRemoteDelta { client_delta, ret } => { let mut document = self.document.write().await; let _ = document.compose_delta(client_delta.clone())?; let md5 = document.md5(); drop(document); let _ = ret.send(Ok(md5)); - }, + } EditorCommand::ResetDelta { delta, ret } => { let mut document = self.document.write().await; let _ = document.set_delta(delta); let md5 = document.md5(); drop(document); let _ = ret.send(Ok(md5)); - }, + } EditorCommand::TransformDelta { delta, ret } => { let f = || async { let read_guard = self.document.read().await; @@ -106,21 +106,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, @@ -131,42 +131,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::ReadDocumentAsJson { ret } => { let data = self.document.read().await.to_json(); let _ = ret.send(Ok(data)); - }, + } EditorCommand::ReadDocumentAsDelta { ret } => { let delta = self.document.read().await.delta().clone(); let _ = ret.send(Ok(delta)); - }, + } } Ok(()) } diff --git a/frontend/rust-lib/flowy-document/src/core/revision/manager.rs b/frontend/rust-lib/flowy-document/src/core/revision/manager.rs deleted file mode 100644 index 588926fd7a..0000000000 --- a/frontend/rust-lib/flowy-document/src/core/revision/manager.rs +++ /dev/null @@ -1,295 +0,0 @@ -use crate::{ - core::{revision::DocumentRevisionCache, RevisionRecord}, - errors::FlowyError, -}; -use bytes::Bytes; -use dashmap::DashMap; -use flowy_collaboration::{ - entities::{ - doc::DocumentInfo, - revision::{RepeatedRevision, Revision, RevisionRange, RevisionState}, - }, - util::{make_delta_from_revisions, md5, pair_rev_id_from_revisions, RevIdCounter}, -}; -use flowy_error::FlowyResult; -use futures_util::{future, stream, stream::StreamExt}; -use lib_infra::future::FutureResult; -use lib_ot::{core::Operation, errors::OTError, rich_text::RichTextDelta}; -use std::{collections::VecDeque, sync::Arc}; -use tokio::sync::RwLock; - -pub trait RevisionServer: Send + Sync { - fn fetch_document(&self, doc_id: &str) -> FutureResult; -} - -pub struct DocumentRevisionManager { - pub(crate) doc_id: String, - user_id: String, - rev_id_counter: RevIdCounter, - cache: Arc, - sync_seq: Arc, -} - -impl DocumentRevisionManager { - pub fn new(user_id: &str, doc_id: &str, cache: Arc) -> Self { - let rev_id_counter = RevIdCounter::new(0); - let sync_seq = Arc::new(RevisionSyncSequence::new()); - Self { - doc_id: doc_id.to_string(), - user_id: user_id.to_owned(), - rev_id_counter, - cache, - sync_seq, - } - } - - pub async fn load_document(&mut self, server: Arc) -> FlowyResult { - let revisions = RevisionLoader { - doc_id: self.doc_id.clone(), - user_id: self.user_id.clone(), - server, - cache: self.cache.clone(), - } - .load() - .await?; - let doc = mk_doc_from_revisions(&self.doc_id, revisions)?; - self.rev_id_counter.set(doc.rev_id); - Ok(doc.delta()?) - } - - #[tracing::instrument(level = "debug", skip(self, revisions), err)] - pub async fn reset_document(&self, revisions: RepeatedRevision) -> FlowyResult<()> { - let rev_id = pair_rev_id_from_revisions(&revisions).1; - let _ = self - .cache - .reset_with_revisions(&self.doc_id, revisions.into_inner()) - .await?; - self.rev_id_counter.set(rev_id); - Ok(()) - } - - #[tracing::instrument(level = "debug", skip(self, revision), err)] - pub async fn add_remote_revision(&self, revision: &Revision) -> Result<(), FlowyError> { - if revision.delta_data.is_empty() { - return Err(FlowyError::internal().context("Delta data should be empty")); - } - let _ = self.cache.add(revision.clone(), RevisionState::Ack, true).await?; - self.rev_id_counter.set(revision.rev_id); - Ok(()) - } - - #[tracing::instrument(level = "debug", skip(self, revision))] - pub async fn add_local_revision(&self, revision: &Revision) -> Result<(), FlowyError> { - if revision.delta_data.is_empty() { - return Err(FlowyError::internal().context("Delta data should be empty")); - } - - let record = self.cache.add(revision.clone(), RevisionState::Local, true).await?; - self.sync_seq.add_revision(record).await?; - Ok(()) - } - - #[tracing::instrument(level = "debug", skip(self), err)] - pub async fn ack_revision(&self, rev_id: i64) -> Result<(), FlowyError> { - if self.sync_seq.ack(&rev_id).await.is_ok() { - self.cache.ack(rev_id).await; - } - Ok(()) - } - - 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 next_rev_id_pair(&self) -> (i64, i64) { - let cur = self.rev_id_counter.value(); - let next = self.rev_id_counter.next(); - (cur, next) - } - - pub async fn get_revisions_in_range(&self, range: RevisionRange) -> Result, FlowyError> { - debug_assert!(range.doc_id == self.doc_id); - let revisions = self.cache.revisions_in_range(range.clone()).await?; - Ok(revisions) - } - - pub fn next_sync_revision(&self) -> FutureResult, FlowyError> { - let sync_seq = self.sync_seq.clone(); - let cache = self.cache.clone(); - FutureResult::new(async move { - match sync_seq.next_sync_revision().await { - None => match sync_seq.next_sync_rev_id().await { - None => Ok(None), - Some(rev_id) => Ok(cache.get(rev_id).await.map(|record| record.revision)), - }, - Some((_, record)) => Ok(Some(record.revision)), - } - }) - } - - 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) - } -} - -struct RevisionSyncSequence { - revs_map: Arc>, - local_revs: Arc>>, -} - -impl std::default::Default for RevisionSyncSequence { - fn default() -> Self { - let local_revs = Arc::new(RwLock::new(VecDeque::new())); - RevisionSyncSequence { - revs_map: Arc::new(DashMap::new()), - local_revs, - } - } -} - -impl RevisionSyncSequence { - 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. - if let Some(rev_id) = self.local_revs.read().await.back() { - if *rev_id >= record.revision.rev_id { - return Err(OTError::revision_id_conflict() - .context(format!("The new revision's id must be greater than {}", rev_id))); - } - } - self.local_revs.write().await.push_back(record.revision.rev_id); - self.revs_map.insert(record.revision.rev_id, record); - Ok(()) - } - - async fn ack(&self, rev_id: &i64) -> FlowyResult<()> { - if let Some(pop_rev_id) = self.next_sync_rev_id().await { - if &pop_rev_id != rev_id { - let desc = format!( - "The ack rev_id:{} is not equal to the current rev_id:{}", - rev_id, pop_rev_id - ); - return Err(FlowyError::internal().context(desc)); - } - - tracing::trace!("{} revision finish synchronizing", pop_rev_id); - self.revs_map.remove(&pop_rev_id); - let _ = self.local_revs.write().await.pop_front(); - } - Ok(()) - } - - async fn next_sync_revision(&self) -> Option<(i64, RevisionRecord)> { - match self.local_revs.read().await.front() { - None => None, - Some(rev_id) => self.revs_map.get(rev_id).map(|r| (*r.key(), r.value().clone())), - } - } - - async fn next_sync_rev_id(&self) -> Option { - self.local_revs.read().await.front().copied() - } -} - -struct RevisionLoader { - doc_id: String, - user_id: String, - server: Arc, - cache: Arc, -} - -impl RevisionLoader { - async fn load(&self) -> Result, FlowyError> { - let records = self.cache.batch_get(&self.doc_id)?; - let revisions: Vec; - if records.is_empty() { - let doc = self.server.fetch_document(&self.doc_id).await?; - let delta_data = Bytes::from(doc.text.clone()); - let doc_md5 = md5(&delta_data); - let revision = Revision::new( - &doc.doc_id, - doc.base_rev_id, - doc.rev_id, - delta_data, - &self.user_id, - doc_md5, - ); - let _ = self.cache.add(revision.clone(), RevisionState::Ack, true).await?; - revisions = vec![revision]; - } else { - // Sync the records if their state is RevisionState::Local. - stream::iter(records.clone()) - .filter(|record| future::ready(record.state == RevisionState::Local)) - .for_each(|record| async move { - match self.cache.add(record.revision, record.state, false).await { - Ok(_) => {} - Err(e) => tracing::error!("{}", e), - } - }) - .await; - revisions = records.into_iter().map(|record| record.revision).collect::<_>(); - } - - Ok(revisions) - } -} - -fn mk_doc_from_revisions(doc_id: &str, revisions: Vec) -> FlowyResult { - let (base_rev_id, rev_id) = revisions.last().unwrap().pair_rev_id(); - let mut delta = make_delta_from_revisions(revisions)?; - correct_delta(&mut delta); - - Result::::Ok(DocumentInfo { - doc_id: doc_id.to_owned(), - text: delta.to_json(), - rev_id, - base_rev_id, - }) -} - -// quill-editor requires the delta should end with '\n' and only contains the -// insert operation. The function, correct_delta maybe be removed in the future. -fn correct_delta(delta: &mut RichTextDelta) { - if let Some(op) = delta.ops.last() { - let op_data = op.get_data(); - if !op_data.ends_with('\n') { - log::warn!("The document must end with newline. Correcting it by inserting newline op"); - delta.ops.push(Operation::Insert("\n".into())); - } - } - - if let Some(op) = delta.ops.iter().find(|op| !op.is_insert()) { - log::warn!("The document can only contains insert operations, but found {:?}", op); - delta.ops.retain(|op| op.is_insert()); - } -} - -#[cfg(feature = "flowy_unit_test")] -impl RevisionSyncSequence { - #[allow(dead_code)] - pub fn revs_map(&self) -> Arc> { - self.revs_map.clone() - } - #[allow(dead_code)] - 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() - } -} diff --git a/frontend/rust-lib/flowy-document/src/core/web_socket.rs b/frontend/rust-lib/flowy-document/src/core/web_socket.rs old mode 100644 new mode 100755 index e79884e164..cfbb057489 --- a/frontend/rust-lib/flowy-document/src/core/web_socket.rs +++ b/frontend/rust-lib/flowy-document/src/core/web_socket.rs @@ -63,10 +63,10 @@ fn listen_document_ws_state(_user_id: &str, _doc_id: &str, mut subscriber: broad 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 => {} } } }); @@ -176,7 +176,7 @@ impl DocumentWSReceiver for RevisionWebSocketManager { fn connect_state_changed(&self, state: WSConnectState) { match self.state_passthrough_tx.send(state) { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("{}", e), } } 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 deleted file mode 100644 index 9af9db591d..0000000000 --- a/frontend/rust-lib/flowy-document/src/core/web_socket/http_ws_impl.rs +++ /dev/null @@ -1,293 +0,0 @@ -use crate::{ - core::{web_socket::ws_manager::DocumentWebSocketManager, SYNC_INTERVAL_IN_MILLIS}, - ws_receivers::{DocumentWSReceiver, DocumentWebSocket}, -}; -use async_stream::stream; -use bytes::Bytes; -use flowy_collaboration::entities::{ - revision::{RevId, RevisionRange}, - ws::{DocumentClientWSData, DocumentServerWSData, DocumentServerWSDataType, NewDocumentUser}, -}; -use flowy_error::{internal_error, FlowyError, FlowyResult}; -use futures::stream::StreamExt; -use lib_infra::future::FutureResult; -use lib_ws::WSConnectState; -use std::{convert::TryFrom, sync::Arc}; -use tokio::{ - sync::{ - broadcast, mpsc, - mpsc::{UnboundedReceiver, UnboundedSender}, - }, - task::spawn_blocking, - time::{interval, Duration}, -}; - -pub(crate) struct HttpWebSocketManager { - doc_id: String, - data_provider: Arc, - stream_consumer: Arc, - ws_conn: Arc, - ws_msg_tx: UnboundedSender, - ws_msg_rx: Option>, - stop_sync_tx: SinkStopTx, - state: broadcast::Sender, -} - -impl HttpWebSocketManager { - pub(crate) fn new( - doc_id: &str, - ws_conn: Arc, - data_provider: Arc, - stream_consumer: Arc, - ) -> Self { - let (ws_msg_tx, ws_msg_rx) = mpsc::unbounded_channel(); - let (stop_sync_tx, _) = tokio::sync::broadcast::channel(2); - let doc_id = doc_id.to_string(); - let (state, _) = broadcast::channel(2); - let mut manager = HttpWebSocketManager { - doc_id, - data_provider, - stream_consumer, - ws_conn, - ws_msg_tx, - ws_msg_rx: Some(ws_msg_rx), - stop_sync_tx, - state, - }; - manager.run(); - manager - } - - fn run(&mut self) { - let ws_msg_rx = self.ws_msg_rx.take().expect("Only take once"); - let sink = DocumentWSSink::new( - &self.doc_id, - self.data_provider.clone(), - self.ws_conn.clone(), - self.stop_sync_tx.subscribe(), - ); - let stream = DocumentWSStream::new( - &self.doc_id, - self.stream_consumer.clone(), - ws_msg_rx, - self.stop_sync_tx.subscribe(), - ); - tokio::spawn(sink.run()); - tokio::spawn(stream.run()); - } - - pub fn scribe_state(&self) -> broadcast::Receiver { - self.state.subscribe() - } -} - -impl DocumentWebSocketManager for Arc { - fn stop(&self) { - if self.stop_sync_tx.send(()).is_ok() { - tracing::debug!("{} stop sync", self.doc_id) - } - } - - 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(_) => {} - Err(e) => tracing::error!("❌ Propagate ws message failed. {}", e), - } - } - - fn connect_state_changed(&self, state: &WSConnectState) { - match self.state.send(state.clone()) { - Ok(_) => {} - Err(e) => tracing::error!("{}", e), - } - } -} - -impl std::ops::Drop for HttpWebSocketManager { - fn drop(&mut self) { - tracing::debug!("{} HttpWebSocketManager was drop", self.doc_id) - } -} - -pub trait DocumentWSSteamConsumer: Send + Sync { - fn receive_push_revision(&self, bytes: Bytes) -> FutureResult<(), FlowyError>; - fn receive_ack(&self, id: String, ty: DocumentServerWSDataType) -> FutureResult<(), FlowyError>; - fn receive_new_user_connect(&self, new_user: NewDocumentUser) -> FutureResult<(), FlowyError>; - fn pull_revisions_in_range(&self, range: RevisionRange) -> FutureResult<(), FlowyError>; -} - -pub struct DocumentWSStream { - doc_id: String, - consumer: Arc, - ws_msg_rx: Option>, - stop_rx: Option, -} - -impl DocumentWSStream { - pub fn new( - doc_id: &str, - consumer: Arc, - ws_msg_rx: mpsc::UnboundedReceiver, - stop_rx: SinkStopRx, - ) -> Self { - DocumentWSStream { - doc_id: doc_id.to_owned(), - consumer, - ws_msg_rx: Some(ws_msg_rx), - stop_rx: Some(stop_rx), - } - } - - pub async fn run(mut self) { - let mut receiver = self.ws_msg_rx.take().expect("Only take once"); - let mut stop_rx = self.stop_rx.take().expect("Only take once"); - let doc_id = self.doc_id.clone(); - let stream = stream! { - loop { - tokio::select! { - result = receiver.recv() => { - match result { - Some(msg) => { - yield msg - }, - None => { - tracing::debug!("[DocumentStream:{}] loop exit", doc_id); - break; - }, - } - }, - _ = stop_rx.recv() => { - tracing::debug!("[DocumentStream:{}] loop exit", doc_id); - break - }, - }; - } - }; - - stream - .for_each(|msg| async { - match self.handle_message(msg).await { - Ok(_) => {} - Err(e) => log::error!("[DocumentStream:{}] error: {}", self.doc_id, e), - } - }) - .await; - } - - async fn handle_message(&self, msg: DocumentServerWSData) -> FlowyResult<()> { - let DocumentServerWSData { doc_id: _, ty, data } = msg; - let bytes = spawn_blocking(move || Bytes::from(data)) - .await - .map_err(internal_error)?; - - tracing::trace!("[DocumentStream]: new message: {:?}", ty); - 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(()) - } -} - -pub type Tick = (); -pub type SinkStopRx = broadcast::Receiver<()>; -pub type SinkStopTx = broadcast::Sender<()>; - -pub trait DocumentWSSinkDataProvider: Send + Sync { - fn next(&self) -> FutureResult, FlowyError>; -} - -pub struct DocumentWSSink { - provider: Arc, - ws_sender: Arc, - stop_rx: Option, - doc_id: String, -} - -impl DocumentWSSink { - pub fn new( - doc_id: &str, - provider: Arc, - ws_sender: Arc, - stop_rx: SinkStopRx, - ) -> Self { - Self { - provider, - ws_sender, - stop_rx: Some(stop_rx), - doc_id: doc_id.to_owned(), - } - } - - pub async fn run(mut self) { - let (tx, mut rx) = mpsc::unbounded_channel(); - let mut stop_rx = self.stop_rx.take().expect("Only take once"); - let doc_id = self.doc_id.clone(); - tokio::spawn(tick(tx)); - let stream = stream! { - loop { - tokio::select! { - result = rx.recv() => { - match result { - Some(msg) => yield msg, - None => break, - } - }, - _ = stop_rx.recv() => { - tracing::debug!("[DocumentSink:{}] loop exit", doc_id); - break - }, - }; - } - }; - stream - .for_each(|_| async { - match self.send_next_revision().await { - Ok(_) => {} - Err(e) => log::error!("[DocumentSink]: Send failed, {:?}", e), - } - }) - .await; - } - - async fn send_next_revision(&self) -> FlowyResult<()> { - match self.provider.next().await? { - 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), - } - } - } -} - -async fn tick(sender: mpsc::UnboundedSender) { - let mut interval = interval(Duration::from_millis(SYNC_INTERVAL_IN_MILLIS)); - while sender.send(()).is_ok() { - interval.tick().await; - } -} 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 deleted file mode 100644 index 9adc6528d7..0000000000 --- a/frontend/rust-lib/flowy-document/src/core/web_socket/local_ws_impl.rs +++ /dev/null @@ -1,20 +0,0 @@ -use crate::core::{web_socket::DocumentWebSocketManager, DocumentWSReceiver}; -use flowy_collaboration::entities::ws::DocumentServerWSData; -use lib_ws::WSConnectState; -use std::sync::Arc; - -pub(crate) struct LocalWebSocketManager {} - -impl DocumentWebSocketManager for Arc { - fn stop(&self) {} - - fn receiver(&self) -> Arc { - self.clone() - } -} - -impl DocumentWSReceiver for LocalWebSocketManager { - fn receive_ws_data(&self, _doc_data: DocumentServerWSData) {} - - fn connect_state_changed(&self, _state: &WSConnectState) {} -} 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 deleted file mode 100644 index 9d217e9222..0000000000 --- a/frontend/rust-lib/flowy-document/src/core/web_socket/ws_manager.rs +++ /dev/null @@ -1,310 +0,0 @@ -use crate::core::{ - web_socket::{DocumentWSSinkDataProvider, DocumentWSSteamConsumer, HttpWebSocketManager}, - DocumentRevisionManager, DocumentWSReceiver, DocumentWebSocket, EditorCommand, TransformDeltas, -}; -use bytes::Bytes; -use flowy_collaboration::{ - entities::{ - revision::{RepeatedRevision, Revision, RevisionRange}, - ws::{DocumentClientWSData, NewDocumentUser}, - }, - errors::CollaborateResult, -}; -use flowy_error::{internal_error, FlowyError, FlowyResult}; -use lib_infra::future::FutureResult; - -use flowy_collaboration::entities::ws::DocumentServerWSDataType; - -use lib_ws::WSConnectState; -use std::{collections::VecDeque, convert::TryFrom, sync::Arc}; -use tokio::sync::{broadcast, mpsc::UnboundedSender, oneshot, RwLock}; - -pub(crate) trait DocumentWebSocketManager: Send + Sync { - fn stop(&self); - fn receiver(&self) -> Arc; -} - -pub(crate) async fn make_document_ws_manager( - doc_id: String, - user_id: String, - edit_cmd_tx: UnboundedSender, - rev_manager: Arc, - ws_conn: Arc, -) -> Arc { - // if cfg!(feature = "http_server") { - // let shared_sink = - // Arc::new(SharedWSSinkDataProvider::new(rev_manager.clone())); - // let ws_stream_consumer = Arc::new(DocumentWebSocketSteamConsumerAdapter { - // doc_id: doc_id.clone(), - // edit_cmd_tx, - // rev_manager: rev_manager.clone(), - // shared_sink: shared_sink.clone(), - // }); - // let data_provider = - // Arc::new(DocumentWSSinkDataProviderAdapter(shared_sink)); - // let ws_manager = Arc::new(HttpWebSocketManager::new( - // &doc_id, - // ws_conn, - // data_provider, - // ws_stream_consumer, - // )); - // listen_document_ws_state(&user_id, &doc_id, ws_manager.scribe_state(), - // rev_manager); Arc::new(ws_manager) - // } else { - // Arc::new(Arc::new(LocalWebSocketManager {})) - // } - let shared_sink = Arc::new(SharedWSSinkDataProvider::new(rev_manager.clone())); - let ws_stream_consumer = Arc::new(DocumentWebSocketSteamConsumerAdapter { - doc_id: doc_id.clone(), - edit_cmd_tx, - rev_manager: rev_manager.clone(), - shared_sink: shared_sink.clone(), - }); - let data_provider = Arc::new(DocumentWSSinkDataProviderAdapter(shared_sink)); - let ws_manager = Arc::new(HttpWebSocketManager::new( - &doc_id, - ws_conn, - data_provider, - ws_stream_consumer, - )); - listen_document_ws_state(&user_id, &doc_id, ws_manager.scribe_state(), rev_manager); - Arc::new(ws_manager) -} - -fn listen_document_ws_state( - _user_id: &str, - _doc_id: &str, - mut subscriber: broadcast::Receiver, - _rev_manager: Arc, -) { - tokio::spawn(async move { - while let Ok(state) = subscriber.recv().await { - match state { - WSConnectState::Init => {} - WSConnectState::Connecting => {} - WSConnectState::Connected => {} - WSConnectState::Disconnected => {} - } - } - }); -} - -pub(crate) struct DocumentWebSocketSteamConsumerAdapter { - pub(crate) doc_id: String, - pub(crate) edit_cmd_tx: UnboundedSender, - pub(crate) rev_manager: Arc, - pub(crate) shared_sink: Arc, -} - -impl DocumentWSSteamConsumer for DocumentWebSocketSteamConsumerAdapter { - fn receive_push_revision(&self, bytes: Bytes) -> FutureResult<(), FlowyError> { - let rev_manager = self.rev_manager.clone(); - let edit_cmd_tx = self.edit_cmd_tx.clone(); - let shared_sink = self.shared_sink.clone(); - let doc_id = self.doc_id.clone(); - FutureResult::new(async move { - if let Some(server_composed_revision) = handle_remote_revision(edit_cmd_tx, rev_manager, bytes).await? { - let data = DocumentClientWSData::from_revisions(&doc_id, vec![server_composed_revision]); - shared_sink.push_back(data).await; - } - Ok(()) - }) - } - - fn receive_ack(&self, id: String, ty: DocumentServerWSDataType) -> FutureResult<(), FlowyError> { - let shared_sink = self.shared_sink.clone(); - FutureResult::new(async move { shared_sink.ack(id, ty).await }) - } - - fn receive_new_user_connect(&self, _new_user: NewDocumentUser) -> FutureResult<(), FlowyError> { - // the _new_user will be used later - FutureResult::new(async move { Ok(()) }) - } - - fn pull_revisions_in_range(&self, range: RevisionRange) -> FutureResult<(), FlowyError> { - let rev_manager = self.rev_manager.clone(); - let shared_sink = self.shared_sink.clone(); - let doc_id = self.doc_id.clone(); - FutureResult::new(async move { - let revisions = rev_manager.get_revisions_in_range(range).await?; - let data = DocumentClientWSData::from_revisions(&doc_id, revisions); - shared_sink.push_back(data).await; - Ok(()) - }) - } -} - -pub(crate) struct DocumentWSSinkDataProviderAdapter(pub(crate) Arc); -impl DocumentWSSinkDataProvider for DocumentWSSinkDataProviderAdapter { - fn next(&self) -> FutureResult, FlowyError> { - let shared_sink = self.0.clone(); - FutureResult::new(async move { shared_sink.next().await }) - } -} - -async fn transform_pushed_revisions( - revisions: Vec, - edit_cmd: &UnboundedSender, -) -> FlowyResult { - let (ret, rx) = oneshot::channel::>(); - let _ = edit_cmd.send(EditorCommand::TransformRevision { revisions, ret }); - Ok(rx.await.map_err(internal_error)??) -} - -#[tracing::instrument(level = "debug", skip(edit_cmd_tx, rev_manager, bytes))] -pub(crate) async fn handle_remote_revision( - edit_cmd_tx: UnboundedSender, - rev_manager: Arc, - bytes: Bytes, -) -> FlowyResult> { - let mut revisions = RepeatedRevision::try_from(bytes)?.into_inner(); - if revisions.is_empty() { - return Ok(None); - } - - let first_revision = revisions.first().unwrap(); - if let Some(local_revision) = rev_manager.get_revision(first_revision.rev_id).await { - if local_revision.md5 == first_revision.md5 { - // The local revision is equal to the pushed revision. Just ignore it. - revisions = revisions.split_off(1); - if revisions.is_empty() { - return Ok(None); - } - } else { - return Ok(None); - } - } - - let TransformDeltas { - client_prime, - server_prime, - } = transform_pushed_revisions(revisions.clone(), &edit_cmd_tx).await?; - - match server_prime { - None => { - // The server_prime is None means the client local revisions conflict with the - // server, and it needs to override the client delta. - let (ret, rx) = oneshot::channel(); - let _ = edit_cmd_tx.send(EditorCommand::OverrideDelta { - revisions, - delta: client_prime, - ret, - }); - let _ = rx.await.map_err(internal_error)??; - Ok(None) - } - Some(server_prime) => { - let (ret, rx) = oneshot::channel(); - let _ = edit_cmd_tx.send(EditorCommand::ComposeRemoteDelta { - revisions, - client_delta: client_prime, - server_delta: server_prime, - ret, - }); - Ok(rx.await.map_err(internal_error)??) - } - } -} - -#[derive(Clone)] -enum SourceType { - Shared, - Revision, -} - -#[derive(Clone)] -pub(crate) struct SharedWSSinkDataProvider { - shared: Arc>>, - rev_manager: Arc, - source_ty: Arc>, -} - -impl SharedWSSinkDataProvider { - pub(crate) fn new(rev_manager: Arc) -> Self { - SharedWSSinkDataProvider { - shared: Arc::new(RwLock::new(VecDeque::new())), - rev_manager, - source_ty: Arc::new(RwLock::new(SourceType::Shared)), - } - } - - #[allow(dead_code)] - 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 next(&self) -> FlowyResult> { - let source_ty = self.source_ty.read().await.clone(); - match source_ty { - SourceType::Shared => match self.shared.read().await.front() { - 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() { - *self.source_ty.write().await = SourceType::Shared; - return Ok(None); - } - - match self.rev_manager.next_sync_revision().await? { - 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))) - } - } - } - } - } - - async fn ack(&self, id: String, _ty: DocumentServerWSDataType) -> FlowyResult<()> { - // let _ = self.rev_manager.ack_revision(id).await?; - let source_ty = self.source_ty.read().await.clone(); - match source_ty { - SourceType::Shared => { - let should_pop = match self.shared.read().await.front() { - None => false, - Some(val) => { - let expected_id = val.id(); - if expected_id == id { - true - } else { - 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/lib.rs b/frontend/rust-lib/flowy-document/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/src/notify/observable.rs b/frontend/rust-lib/flowy-document/src/notify/observable.rs deleted file mode 100644 index a48aa06438..0000000000 --- a/frontend/rust-lib/flowy-document/src/notify/observable.rs +++ /dev/null @@ -1,18 +0,0 @@ -use dart_notify::DartNotifyBuilder; -use flowy_derive::ProtoBuf_Enum; -const OBSERVABLE_CATEGORY: &str = "Doc"; -#[derive(ProtoBuf_Enum, Debug)] -pub(crate) enum DocObservable { - UserCreateDoc = 0, -} - -impl std::convert::From for i32 { - fn from(o: DocObservable) -> Self { - o as i32 - } -} - -#[allow(dead_code)] -pub(crate) fn dart_notify(id: &str, ty: DocObservable) -> DartNotifyBuilder { - DartNotifyBuilder::new(id, ty, OBSERVABLE_CATEGORY) -} diff --git a/frontend/rust-lib/flowy-document/src/protobuf/mod.rs b/frontend/rust-lib/flowy-document/src/protobuf/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/src/protobuf/model/mod.rs b/frontend/rust-lib/flowy-document/src/protobuf/model/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/src/server/middleware.rs b/frontend/rust-lib/flowy-document/src/server/middleware.rs deleted file mode 100644 index ede10c0659..0000000000 --- a/frontend/rust-lib/flowy-document/src/server/middleware.rs +++ /dev/null @@ -1,29 +0,0 @@ -use backend_service::{request::ResponseMiddleware, response::FlowyResponse}; -use lazy_static::lazy_static; -use std::sync::Arc; - -lazy_static! { - pub(crate) static ref MIDDLEWARE: Arc = Arc::new(DocMiddleware {}); -} - -pub(crate) struct DocMiddleware {} -impl ResponseMiddleware for DocMiddleware { - fn receive_response(&self, token: &Option, response: &FlowyResponse) { - if let Some(error) = &response.error { - if error.is_unauthorized() { - log::error!("document user is unauthorized"); - - match token { - 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 deleted file mode 100644 index 784351594e..0000000000 --- a/frontend/rust-lib/flowy-document/src/server/server_api.rs +++ /dev/null @@ -1,69 +0,0 @@ -use crate::{errors::FlowyError, server::DocumentServerAPI}; -use backend_service::{configuration::*, request::HttpRequestBuilder}; -use flowy_collaboration::entities::doc::{CreateDocParams, DocumentId, DocumentInfo, ResetDocumentParams}; -use lib_infra::future::FutureResult; - -pub struct DocServer { - config: ClientServerConfiguration, -} - -impl DocServer { - pub fn new(config: ClientServerConfiguration) -> Self { - Self { config } - } -} - -impl DocumentServerAPI for DocServer { - fn create_doc(&self, token: &str, params: CreateDocParams) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.doc_url(); - FutureResult::new(async move { create_doc_request(&token, params, &url).await }) - } - - fn read_doc(&self, token: &str, params: DocumentId) -> FutureResult, FlowyError> { - let token = token.to_owned(); - let url = self.config.doc_url(); - FutureResult::new(async move { read_doc_request(&token, params, &url).await }) - } - - fn update_doc(&self, token: &str, params: ResetDocumentParams) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.doc_url(); - FutureResult::new(async move { reset_doc_request(&token, params, &url).await }) - } -} - -pub(crate) fn request_builder() -> HttpRequestBuilder { - HttpRequestBuilder::new().middleware(super::middleware::MIDDLEWARE.clone()) -} - -pub async fn create_doc_request(token: &str, params: CreateDocParams, url: &str) -> Result<(), FlowyError> { - let _ = request_builder() - .post(&url.to_owned()) - .header(HEADER_TOKEN, token) - .protobuf(params)? - .send() - .await?; - Ok(()) -} - -pub async fn read_doc_request(token: &str, params: DocumentId, url: &str) -> Result, FlowyError> { - let doc = request_builder() - .get(&url.to_owned()) - .header(HEADER_TOKEN, token) - .protobuf(params)? - .option_response() - .await?; - - Ok(doc) -} - -pub async fn reset_doc_request(token: &str, params: ResetDocumentParams, url: &str) -> Result<(), FlowyError> { - let _ = request_builder() - .patch(&url.to_owned()) - .header(HEADER_TOKEN, token) - .protobuf(params)? - .send() - .await?; - Ok(()) -} diff --git a/frontend/rust-lib/flowy-document/src/ws_receivers.rs b/frontend/rust-lib/flowy-document/src/ws_receivers.rs deleted file mode 100644 index b017e8b843..0000000000 --- a/frontend/rust-lib/flowy-document/src/ws_receivers.rs +++ /dev/null @@ -1,64 +0,0 @@ -use crate::errors::FlowyError; -use bytes::Bytes; -use dashmap::DashMap; -use flowy_collaboration::entities::ws::{DocumentClientWSData, DocumentServerWSData}; -use lib_ws::WSConnectState; -use std::{convert::TryInto, sync::Arc}; - -pub(crate) trait DocumentWSReceiver: Send + Sync { - fn receive_ws_data(&self, data: DocumentServerWSData); - fn connect_state_changed(&self, state: &WSConnectState); -} - -pub type WSStateReceiver = tokio::sync::broadcast::Receiver; -pub trait DocumentWebSocket: Send + Sync { - fn send(&self, data: DocumentClientWSData) -> Result<(), FlowyError>; - fn subscribe_state_changed(&self) -> WSStateReceiver; -} - -pub struct DocumentWSReceivers { - // key: the document id - receivers: Arc>>, -} - -impl std::default::Default for DocumentWSReceivers { - fn default() -> Self { - let receivers: Arc>> = Arc::new(DashMap::new()); - DocumentWSReceivers { receivers } - } -} - -impl DocumentWSReceivers { - pub fn new() -> Self { - DocumentWSReceivers::default() - } - - pub(crate) fn add(&self, doc_id: &str, receiver: Arc) { - if self.receivers.contains_key(doc_id) { - log::error!("Duplicate handler registered for {:?}", doc_id); - } - self.receivers.insert(doc_id.to_string(), receiver); - } - - 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); - }); - } -} diff --git a/frontend/rust-lib/flowy-document/tests/document/document_test.rs b/frontend/rust-lib/flowy-document/tests/document/document_test.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/tests/document/edit_script.rs b/frontend/rust-lib/flowy-document/tests/document/edit_script.rs old mode 100644 new mode 100755 index 2af5f4058a..d9ad0999ee --- a/frontend/rust-lib/flowy-document/tests/document/edit_script.rs +++ b/frontend/rust-lib/flowy-document/tests/document/edit_script.rs @@ -63,7 +63,7 @@ impl EditorTest { EditorScript::AssertNextRevId(rev_id) => { let next_revision = rev_manager.next_sync_revision().await.unwrap(); if rev_id.is_none() { - assert_eq!(next_revision.is_none(), true, "Next revision should be None"); + assert!(next_revision.is_none(), "Next revision should be None"); return; } let next_revision = next_revision.unwrap(); diff --git a/frontend/rust-lib/flowy-document/tests/document/mod.rs b/frontend/rust-lib/flowy-document/tests/document/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/tests/editor/attribute_test.rs b/frontend/rust-lib/flowy-document/tests/editor/attribute_test.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/tests/editor/mod.rs b/frontend/rust-lib/flowy-document/tests/editor/mod.rs old mode 100644 new mode 100755 index 34cd64c382..32c94bae9c --- a/frontend/rust-lib/flowy-document/tests/editor/mod.rs +++ b/frontend/rust-lib/flowy-document/tests/editor/mod.rs @@ -171,7 +171,7 @@ impl TestBuilder { TestOp::Transform(delta_a_i, delta_b_i) => { let (a_prime, b_prime) = self.documents[*delta_a_i] .delta() - .transform(&self.documents[*delta_b_i].delta()) + .transform(self.documents[*delta_b_i].delta()) .unwrap(); tracing::trace!("a:{:?},b:{:?}", a_prime, b_prime); @@ -184,7 +184,7 @@ impl TestBuilder { TestOp::TransformPrime(a_doc_index, b_doc_index) => { let (prime_left, prime_right) = self.documents[*a_doc_index] .delta() - .transform(&self.documents[*b_doc_index].delta()) + .transform(self.documents[*b_doc_index].delta()) .unwrap(); self.primes.insert(*a_doc_index, Some(prime_left)); @@ -198,7 +198,7 @@ impl TestBuilder { tracing::debug!("b: {}", delta_b.to_json()); let (_, b_prime) = delta_a.transform(delta_b).unwrap(); - let undo = b_prime.invert(&delta_a); + let undo = b_prime.invert(delta_a); let new_delta = delta_a.compose(&b_prime).unwrap(); tracing::debug!("new delta: {}", new_delta.to_json()); diff --git a/frontend/rust-lib/flowy-document/tests/editor/op_test.rs b/frontend/rust-lib/flowy-document/tests/editor/op_test.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/tests/editor/serde_test.rs b/frontend/rust-lib/flowy-document/tests/editor/serde_test.rs old mode 100644 new mode 100755 index 89e9e10c7b..da64d4bcf8 --- a/frontend/rust-lib/flowy-document/tests/editor/serde_test.rs +++ b/frontend/rust-lib/flowy-document/tests/editor/serde_test.rs @@ -1,9 +1,9 @@ use flowy_collaboration::client_document::{ClientDocument, PlainDoc}; +use lib_ot::rich_text::RichTextOperation; use lib_ot::{ core::*, rich_text::{AttributeBuilder, RichTextAttribute, RichTextAttributeValue, RichTextDelta}, }; -use lib_ot::rich_text::RichTextOperation; #[test] fn operation_insert_serialize_test() { diff --git a/frontend/rust-lib/flowy-document/tests/editor/undo_redo_test.rs b/frontend/rust-lib/flowy-document/tests/editor/undo_redo_test.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-document/tests/main.rs b/frontend/rust-lib/flowy-document/tests/main.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/Cargo.toml b/frontend/rust-lib/flowy-error/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/Flowy.toml b/frontend/rust-lib/flowy-error/Flowy.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/errors.rs b/frontend/rust-lib/flowy-error/src/errors.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/ext/backend.rs b/frontend/rust-lib/flowy-error/src/ext/backend.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/ext/collaborate.rs b/frontend/rust-lib/flowy-error/src/ext/collaborate.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/ext/database.rs b/frontend/rust-lib/flowy-error/src/ext/database.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/ext/mod.rs b/frontend/rust-lib/flowy-error/src/ext/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/ext/ot.rs b/frontend/rust-lib/flowy-error/src/ext/ot.rs old mode 100644 new mode 100755 index fbeb683bbb..c9346b835d --- 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.msg) } + fn from(error: lib_ot::errors::OTError) -> Self { + FlowyError::internal().context(error.msg) + } } diff --git a/frontend/rust-lib/flowy-error/src/ext/serde.rs b/frontend/rust-lib/flowy-error/src/ext/serde.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/lib.rs b/frontend/rust-lib/flowy-error/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/protobuf/mod.rs b/frontend/rust-lib/flowy-error/src/protobuf/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/protobuf/model/errors.rs b/frontend/rust-lib/flowy-error/src/protobuf/model/errors.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/protobuf/model/mod.rs b/frontend/rust-lib/flowy-error/src/protobuf/model/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-error/src/protobuf/proto/errors.proto b/frontend/rust-lib/flowy-error/src/protobuf/proto/errors.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/Cargo.toml b/frontend/rust-lib/flowy-net/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/Flowy.toml b/frontend/rust-lib/flowy-net/Flowy.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/entities/mod.rs b/frontend/rust-lib/flowy-net/src/entities/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/entities/network_state.rs b/frontend/rust-lib/flowy-net/src/entities/network_state.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/event.rs b/frontend/rust-lib/flowy-net/src/event.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/handlers/mod.rs b/frontend/rust-lib/flowy-net/src/handlers/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/http_server/core.rs b/frontend/rust-lib/flowy-net/src/http_server/core.rs old mode 100644 new mode 100755 index 4f69d60f24..909726e518 --- a/frontend/rust-lib/flowy-net/src/http_server/core.rs +++ b/frontend/rust-lib/flowy-net/src/http_server/core.rs @@ -23,7 +23,9 @@ pub struct CoreHttpCloudService { } impl CoreHttpCloudService { - pub fn new(config: ClientServerConfiguration) -> CoreHttpCloudService { Self { config } } + pub fn new(config: ClientServerConfiguration) -> CoreHttpCloudService { + Self { config } + } } impl FolderCouldServiceV2 for CoreHttpCloudService {} @@ -167,7 +169,9 @@ impl FolderCouldServiceV1 for CoreHttpCloudService { } } -fn request_builder() -> HttpRequestBuilder { HttpRequestBuilder::new().middleware(MIDDLEWARE.clone()) } +fn request_builder() -> HttpRequestBuilder { + HttpRequestBuilder::new().middleware(MIDDLEWARE.clone()) +} pub async fn create_workspace_request( token: &str, @@ -352,7 +356,9 @@ impl CoreResponseMiddleware { } #[allow(dead_code)] - fn invalid_token_subscribe(&self) -> broadcast::Receiver { self.invalid_token_sender.subscribe() } + fn invalid_token_subscribe(&self) -> broadcast::Receiver { + self.invalid_token_sender.subscribe() + } } impl ResponseMiddleware for CoreResponseMiddleware { @@ -361,9 +367,9 @@ impl ResponseMiddleware for CoreResponseMiddleware { if error.is_unauthorized() { tracing::error!("user is unauthorized"); match token { - None => {}, + None => {} Some(token) => match self.invalid_token_sender.send(token.clone()) { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("{:?}", e), }, } diff --git a/frontend/rust-lib/flowy-net/src/http_server/document.rs b/frontend/rust-lib/flowy-net/src/http_server/document.rs old mode 100644 new mode 100755 index 7b527f9672..8615ad1f77 --- a/frontend/rust-lib/flowy-net/src/http_server/document.rs +++ b/frontend/rust-lib/flowy-net/src/http_server/document.rs @@ -15,7 +15,9 @@ pub struct DocumentHttpCloudService { } impl DocumentHttpCloudService { - pub fn new(config: ClientServerConfiguration) -> Self { Self { config } } + pub fn new(config: ClientServerConfiguration) -> Self { + Self { config } + } } impl DocumentCloudService for DocumentHttpCloudService { @@ -73,7 +75,9 @@ pub async fn reset_doc_request(token: &str, params: ResetDocumentParams, url: &s Ok(()) } -fn request_builder() -> HttpRequestBuilder { HttpRequestBuilder::new().middleware(MIDDLEWARE.clone()) } +fn request_builder() -> HttpRequestBuilder { + HttpRequestBuilder::new().middleware(MIDDLEWARE.clone()) +} lazy_static! { pub(crate) static ref MIDDLEWARE: Arc = Arc::new(DocumentResponseMiddleware {}); @@ -87,14 +91,14 @@ impl ResponseMiddleware for DocumentResponseMiddleware { tracing::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-net/src/http_server/mod.rs b/frontend/rust-lib/flowy-net/src/http_server/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/http_server/user.rs b/frontend/rust-lib/flowy-net/src/http_server/user.rs old mode 100644 new mode 100755 index 494ac71f0a..01d3faab5c --- a/frontend/rust-lib/flowy-net/src/http_server/user.rs +++ b/frontend/rust-lib/flowy-net/src/http_server/user.rs @@ -2,12 +2,7 @@ use backend_service::{configuration::*, errors::ServerError, request::HttpReques use flowy_error::FlowyError; use flowy_user::module::UserCloudService; use flowy_user_data_model::entities::{ - SignInParams, - SignInResponse, - SignUpParams, - SignUpResponse, - UpdateUserParams, - UserProfile, + SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile, }; use lib_infra::future::FutureResult; @@ -15,7 +10,9 @@ pub struct UserHttpCloudService { config: ClientServerConfiguration, } impl UserHttpCloudService { - pub fn new(config: &ClientServerConfiguration) -> Self { Self { config: config.clone() } } + pub fn new(config: &ClientServerConfiguration) -> Self { + Self { config: config.clone() } + } } impl UserCloudService for UserHttpCloudService { @@ -62,7 +59,9 @@ impl UserCloudService for UserHttpCloudService { }) } - fn ws_addr(&self) -> String { self.config.ws_addr() } + fn ws_addr(&self) -> String { + self.config.ws_addr() + } } pub async fn user_sign_up_request(params: SignUpParams, url: &str) -> Result { @@ -111,4 +110,6 @@ pub async fn update_user_profile_request(token: &str, params: UpdateUserParams, Ok(()) } -fn request_builder() -> HttpRequestBuilder { HttpRequestBuilder::new() } +fn request_builder() -> HttpRequestBuilder { + HttpRequestBuilder::new() +} diff --git a/frontend/rust-lib/flowy-net/src/lib.rs b/frontend/rust-lib/flowy-net/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/local_server/mod.rs b/frontend/rust-lib/flowy-net/src/local_server/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/local_server/persistence.rs b/frontend/rust-lib/flowy-net/src/local_server/persistence.rs old mode 100644 new mode 100755 index fe7f1dc9d5..8a0a8dcff0 --- a/frontend/rust-lib/flowy-net/src/local_server/persistence.rs +++ b/frontend/rust-lib/flowy-net/src/local_server/persistence.rs @@ -34,7 +34,9 @@ pub(crate) struct LocalDocumentCloudPersistence { } impl Debug for LocalDocumentCloudPersistence { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("LocalRevisionCloudPersistence") } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str("LocalRevisionCloudPersistence") + } } impl std::default::Default for LocalDocumentCloudPersistence { @@ -166,10 +168,8 @@ impl DocumentCloudPersistence for LocalDocumentCloudPersistence { } } +#[derive(Default)] struct MemoryDocumentCloudStorage {} -impl std::default::Default for MemoryDocumentCloudStorage { - fn default() -> Self { Self {} } -} impl RevisionCloudStorage for MemoryDocumentCloudStorage { fn set_revisions(&self, _repeated_revision: RepeatedRevisionPB) -> BoxResultFuture<(), CollaborateError> { Box::pin(async move { Ok(()) }) diff --git a/frontend/rust-lib/flowy-net/src/local_server/server.rs b/frontend/rust-lib/flowy-net/src/local_server/server.rs old mode 100644 new mode 100755 index f35549a3cb..23ccef0b56 --- a/frontend/rust-lib/flowy-net/src/local_server/server.rs +++ b/frontend/rust-lib/flowy-net/src/local_server/server.rs @@ -103,7 +103,7 @@ impl LocalWebSocketRunner { stream .for_each(|message| async { match self.handle_message(message).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("[LocalWebSocketRunner]: {}", e), } }) @@ -117,11 +117,11 @@ impl LocalWebSocketRunner { WSChannel::Document => { let _ = self.handle_document_client_data(client_data, "".to_owned()).await?; Ok(()) - }, + } WSChannel::Folder => { let _ = self.handle_folder_client_data(client_data, "".to_owned()).await?; Ok(()) - }, + } } } @@ -150,13 +150,13 @@ impl LocalWebSocketRunner { .folder_manager .handle_client_revisions(user, document_client_data) .await?; - }, + } ClientRevisionWSDataType::ClientPing => { let _ = self .folder_manager .handle_client_ping(user, document_client_data) .await?; - }, + } } Ok(()) } @@ -186,10 +186,10 @@ impl LocalWebSocketRunner { .doc_manager .handle_client_revisions(user, document_client_data) .await?; - }, + } ClientRevisionWSDataType::ClientPing => { let _ = self.doc_manager.handle_client_ping(user, document_client_data).await?; - }, + } } Ok(()) } @@ -203,15 +203,17 @@ struct LocalRevisionUser { } impl RevisionUser for LocalRevisionUser { - fn user_id(&self) -> String { self.user_id.clone() } + fn user_id(&self) -> String { + self.user_id.clone() + } fn receive(&self, resp: RevisionSyncResponse) { let sender = self.client_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); - }, + } }; let channel = self.channel.clone(); @@ -224,7 +226,7 @@ impl RevisionUser for LocalRevisionUser { data: bytes.to_vec(), }; send_fn(sender, msg); - }, + } RevisionSyncResponse::Push(data) => { let bytes: Bytes = data.try_into().unwrap(); let msg = WebSocketRawMessage { @@ -232,7 +234,7 @@ impl RevisionUser for LocalRevisionUser { data: bytes.to_vec(), }; send_fn(sender, msg); - }, + } RevisionSyncResponse::Ack(data) => { let bytes: Bytes = data.try_into().unwrap(); let msg = WebSocketRawMessage { @@ -240,7 +242,7 @@ impl RevisionUser for LocalRevisionUser { data: bytes.to_vec(), }; send_fn(sender, msg); - }, + } } }); } @@ -255,12 +257,7 @@ use flowy_core_data_model::entities::{ use flowy_document::DocumentCloudService; use flowy_user::module::UserCloudService; use flowy_user_data_model::entities::{ - SignInParams, - SignInResponse, - SignUpParams, - SignUpResponse, - UpdateUserParams, - UserProfile, + SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile, }; use lib_infra::{future::FutureResult, timestamp, uuid_string}; @@ -394,7 +391,9 @@ impl UserCloudService for LocalServer { }) } - 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(()) }) @@ -404,7 +403,9 @@ impl UserCloudService for LocalServer { 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() + } } impl DocumentCloudService for LocalServer { diff --git a/frontend/rust-lib/flowy-net/src/local_server/ws.rs b/frontend/rust-lib/flowy-net/src/local_server/ws.rs old mode 100644 new mode 100755 index 08733634b5..88f11f2709 --- a/frontend/rust-lib/flowy-net/src/local_server/ws.rs +++ b/frontend/rust-lib/flowy-net/src/local_server/ws.rs @@ -55,14 +55,18 @@ 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) -> BoxFuture> { let subscribe = self.state_sender.subscribe(); Box::pin(async move { 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_msg_receiver(&self, receiver: Arc) -> Result<(), FlowyError> { tracing::trace!("Local web socket add ws receiver: {:?}", receiver.source()); diff --git a/frontend/rust-lib/flowy-net/src/module.rs b/frontend/rust-lib/flowy-net/src/module.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/protobuf/mod.rs b/frontend/rust-lib/flowy-net/src/protobuf/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/protobuf/model/event.rs b/frontend/rust-lib/flowy-net/src/protobuf/model/event.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/protobuf/model/mod.rs b/frontend/rust-lib/flowy-net/src/protobuf/model/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/protobuf/model/network_state.rs b/frontend/rust-lib/flowy-net/src/protobuf/model/network_state.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/protobuf/proto/event.proto b/frontend/rust-lib/flowy-net/src/protobuf/proto/event.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-net/src/protobuf/proto/network_state.proto b/frontend/rust-lib/flowy-net/src/protobuf/proto/network_state.proto old mode 100644 new mode 100755 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 deleted file mode 100644 index cf4fdb61f6..0000000000 --- a/frontend/rust-lib/flowy-net/src/services/local_ws/local_server.rs +++ /dev/null @@ -1,178 +0,0 @@ -use bytes::Bytes; -use dashmap::DashMap; -use flowy_collaboration::{ - entities::{ - doc::DocumentInfo, - ws::{DocumentClientWSData, DocumentClientWSDataType}, - }, - errors::CollaborateError, - protobuf::{ - DocumentClientWSData as DocumentClientWSDataPB, RepeatedRevision as RepeatedRevisionPB, Revision as RevisionPB, - }, - sync::*, - util::repeated_revision_from_repeated_revision_pb, -}; -use lib_infra::future::BoxResultFuture; -use lib_ws::{WSModule, WebSocketRawMessage}; -use std::{ - convert::TryInto, - fmt::{Debug, Formatter}, - sync::Arc, -}; -use tokio::sync::{mpsc, mpsc::UnboundedSender}; - -pub struct LocalDocumentServer { - pub doc_manager: Arc, - sender: mpsc::UnboundedSender, -} - -impl LocalDocumentServer { - pub fn new(sender: mpsc::UnboundedSender) -> Self { - let persistence = Arc::new(LocalDocServerPersistence::default()); - let doc_manager = Arc::new(ServerDocumentManager::new(persistence)); - LocalDocumentServer { doc_manager, sender } - } - - pub async fn handle_client_data( - &self, - client_data: DocumentClientWSData, - user_id: String, - ) -> Result<(), CollaborateError> { - tracing::trace!( - "[LocalDocumentServer] receive: {}:{}-{:?} ", - client_data.doc_id, - client_data.id(), - client_data.ty, - ); - let user = Arc::new(LocalDocumentUser { - user_id, - ws_sender: self.sender.clone(), - }); - let ty = client_data.ty.clone(); - let document_client_data: DocumentClientWSDataPB = client_data.try_into().unwrap(); - match ty { - DocumentClientWSDataType::ClientPushRev => { - let _ = self - .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(()) - } -} - -struct LocalDocServerPersistence { - inner: Arc>, -} - -impl Debug for LocalDocServerPersistence { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - f.write_str("LocalDocServerPersistence") - } -} - -impl std::default::Default for LocalDocServerPersistence { - fn default() -> Self { - LocalDocServerPersistence { - inner: Arc::new(DashMap::new()), - } - } -} - -impl DocumentPersistence for LocalDocServerPersistence { - fn read_doc(&self, doc_id: &str) -> BoxResultFuture { - let inner = self.inner.clone(); - let doc_id = doc_id.to_owned(); - Box::pin(async move { - match inner.get(&doc_id) { - None => Err(CollaborateError::record_not_found()), - Some(val) => { - // - Ok(val.value().clone()) - } - } - }) - } - - fn create_doc( - &self, - doc_id: &str, - repeated_revision: RepeatedRevisionPB, - ) -> BoxResultFuture { - let doc_id = doc_id.to_owned(); - Box::pin(async move { - let repeated_revision = repeated_revision_from_repeated_revision_pb(repeated_revision)?; - DocumentInfo::from_revisions(&doc_id, repeated_revision.into_inner()) - }) - } - - fn get_revisions(&self, _doc_id: &str, _rev_ids: Vec) -> BoxResultFuture, CollaborateError> { - Box::pin(async move { Ok(vec![]) }) - } - - fn get_doc_revisions(&self, _doc_id: &str) -> BoxResultFuture, CollaborateError> { - unimplemented!() - } - - fn reset_document(&self, _doc_id: &str, _revisions: RepeatedRevisionPB) -> BoxResultFuture<(), CollaborateError> { - unimplemented!() - } -} - -#[derive(Debug)] -struct LocalDocumentUser { - user_id: String, - ws_sender: mpsc::UnboundedSender, -} - -impl RevisionUser for LocalDocumentUser { - 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(_) => {} - Err(e) => { - tracing::error!("LocalDocumentUser send message failed: {}", e); - } - }; - - tokio::spawn(async move { - match resp { - SyncResponse::Pull(data) => { - let bytes: Bytes = data.try_into().unwrap(); - let msg = WebSocketRawMessage { - module: WSModule::Doc, - data: bytes.to_vec(), - }; - send_fn(sender, msg); - } - SyncResponse::Push(data) => { - let bytes: Bytes = data.try_into().unwrap(); - let msg = WebSocketRawMessage { - module: WSModule::Doc, - data: bytes.to_vec(), - }; - send_fn(sender, msg); - } - SyncResponse::Ack(data) => { - let bytes: Bytes = data.try_into().unwrap(); - let msg = WebSocketRawMessage { - module: WSModule::Doc, - 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 deleted file mode 100644 index d529a7d0c9..0000000000 --- a/frontend/rust-lib/flowy-net/src/services/local_ws/local_ws_impl.rs +++ /dev/null @@ -1,150 +0,0 @@ -use bytes::Bytes; -use dashmap::DashMap; -use flowy_collaboration::entities::ws::*; -use flowy_error::{internal_error, FlowyError}; -use lib_infra::future::FutureResult; -use lib_ws::{WSConnectState, WSMessageReceiver, WSModule, WebSocketRawMessage}; - -use crate::services::{ - local_ws::local_server::LocalDocumentServer, - ws_conn::{FlowyRawWebSocket, FlowyWSSender}, -}; -use parking_lot::RwLock; -use std::{convert::TryFrom, sync::Arc}; -use tokio::sync::{broadcast, broadcast::Receiver, mpsc, mpsc::UnboundedReceiver}; - -pub struct LocalWebSocket { - receivers: Arc>>, - state_sender: broadcast::Sender, - ws_sender: LocalWSSender, - server: Arc, - server_rx: RwLock>>, - user_id: Arc>>, -} - -impl std::default::Default for LocalWebSocket { - fn default() -> Self { - let (state_sender, _) = broadcast::channel(16); - let ws_sender = LocalWSSender::default(); - let receivers = Arc::new(DashMap::new()); - - let (server_tx, server_rx) = mpsc::unbounded_channel(); - let server = Arc::new(LocalDocumentServer::new(server_tx)); - let server_rx = RwLock::new(Some(server_rx)); - let user_token = Arc::new(RwLock::new(None)); - - LocalWebSocket { - receivers, - state_sender, - ws_sender, - server, - server_rx, - user_id: user_token, - } - } -} - -impl LocalWebSocket { - fn spawn_client(&self, _addr: String) { - let mut ws_receiver = self.ws_sender.subscribe(); - let local_server = self.server.clone(); - let user_id = self.user_id.clone(); - tokio::spawn(async move { - loop { - // Polling the web socket message sent by user - match ws_receiver.recv().await { - Ok(message) => { - let user_id = user_id.read().clone(); - if user_id.is_none() { - continue; - } - let user_id = user_id.unwrap(); - let server = local_server.clone(); - let fut = || async move { - let bytes = Bytes::from(message.data); - let client_data = DocumentClientWSData::try_from(bytes).map_err(internal_error)?; - let _ = server - .handle_client_data(client_data, user_id) - .await - .map_err(internal_error)?; - Ok::<(), FlowyError>(()) - }; - match fut().await { - Ok(_) => {} - Err(e) => tracing::error!("[LocalWebSocket] error: {:?}", e), - } - } - Err(e) => tracing::error!("[LocalWebSocket] error: {}", e), - } - } - }); - } -} - -impl FlowyRawWebSocket for LocalWebSocket { - fn initialize(&self) -> FutureResult<(), FlowyError> { - let mut server_rx = self.server_rx.write().take().expect("Only take once"); - let receivers = self.receivers.clone(); - tokio::spawn(async move { - while let Some(message) = server_rx.recv().await { - match receivers.get(&message.module) { - None => tracing::error!("Can't find any handler for message: {:?}", message), - Some(handler) => handler.receive_message(message.clone()), - } - } - }); - FutureResult::new(async { Ok(()) }) - } - - fn start_connect(&self, addr: String, user_id: String) -> FutureResult<(), FlowyError> { - *self.user_id.write() = Some(user_id); - self.spawn_client(addr); - 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 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())) - } -} - -#[derive(Clone)] -struct LocalWSSender(broadcast::Sender); - -impl std::default::Default for LocalWSSender { - fn default() -> Self { - let (tx, _) = broadcast::channel(16); - Self(tx) - } -} - -impl FlowyWSSender for LocalWSSender { - fn send(&self, msg: WebSocketRawMessage) -> Result<(), FlowyError> { - let _ = self.0.send(msg); - Ok(()) - } -} - -impl std::ops::Deref for LocalWSSender { - type Target = broadcast::Sender; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} diff --git a/frontend/rust-lib/flowy-net/src/ws/connection.rs b/frontend/rust-lib/flowy-net/src/ws/connection.rs old mode 100644 new mode 100755 index d94504dbc4..0818770075 --- a/frontend/rust-lib/flowy-net/src/ws/connection.rs +++ b/frontend/rust-lib/flowy-net/src/ws/connection.rs @@ -55,7 +55,7 @@ impl FlowyWebSocketConnect { pub async fn init(&self) { match self.inner.initialize().await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("FlowyWebSocketConnect init error: {:?}", e), } } @@ -67,7 +67,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); @@ -80,11 +82,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(); @@ -95,7 +97,9 @@ impl FlowyWebSocketConnect { self.inner.subscribe_connect_state().await } - 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_msg_receiver(receiver)?; @@ -117,16 +121,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(raw_web_socket.clone(), 100).await, } - }, + } Err(e) => { tracing::error!("Websocket state notify error: {:?}", e); break; - }, + } } } }); @@ -134,9 +138,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-net/src/ws/http_ws.rs b/frontend/rust-lib/flowy-net/src/ws/http_ws.rs old mode 100644 new mode 100755 index 73e71787bb..ce74f5d0d7 --- a/frontend/rust-lib/flowy-net/src/ws/http_ws.rs +++ b/frontend/rust-lib/flowy-net/src/ws/http_ws.rs @@ -10,7 +10,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(); @@ -54,7 +56,7 @@ impl FlowyRawWebSocket for Arc { Some(sender) => { let sender = sender as Arc; Ok(Some(sender)) - }, + } } }) } diff --git a/frontend/rust-lib/flowy-net/src/ws/mod.rs b/frontend/rust-lib/flowy-net/src/ws/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sdk/.gitignore b/frontend/rust-lib/flowy-sdk/.gitignore old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sdk/Cargo.toml b/frontend/rust-lib/flowy-sdk/Cargo.toml old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 index 5800037f14..1bbc3701a1 --- a/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs +++ b/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs @@ -4,14 +4,10 @@ use flowy_collaboration::entities::ws_data::ClientRevisionWSData; use flowy_database::ConnectionPool; use flowy_document::{ errors::{internal_error, FlowyError}, - DocumentCloudService, - DocumentUser, - FlowyDocumentManager, + DocumentCloudService, DocumentUser, FlowyDocumentManager, }; use flowy_net::{ - http_server::document::DocumentHttpCloudService, - local_server::LocalServer, - ws::connection::FlowyWebSocketConnect, + http_server::document::DocumentHttpCloudService, local_server::LocalServer, ws::connection::FlowyWebSocketConnect, }; use flowy_sync::{RevisionWebSocket, WSStateReceiver}; use flowy_user::services::UserSession; @@ -55,11 +51,17 @@ impl DocumentUser for DocumentUserImpl { Ok(doc_dir) } - fn user_id(&self) -> Result { self.0.user_id() } + fn user_id(&self) -> Result { + self.0.user_id() + } - fn token(&self) -> Result { self.0.token() } + fn token(&self) -> Result { + self.0.token() + } - fn db_pool(&self) -> Result, FlowyError> { self.0.db_pool() } + fn db_pool(&self) -> Result, FlowyError> { + self.0.db_pool() + } } struct DocumentWebSocketImpl(Arc); @@ -73,10 +75,10 @@ impl RevisionWebSocket for DocumentWebSocketImpl { let ws_conn = self.0.clone(); Box::pin(async move { match ws_conn.web_socket().await? { - None => {}, + None => {} Some(sender) => { sender.send(msg).map_err(internal_error)?; - }, + } } Ok(()) }) @@ -90,7 +92,9 @@ impl RevisionWebSocket for DocumentWebSocketImpl { struct DocumentWSMessageReceiverImpl(Arc); impl WSMessageReceiver for DocumentWSMessageReceiverImpl { - fn source(&self) -> WSChannel { WSChannel::Document } + fn source(&self) -> WSChannel { + WSChannel::Document + } fn receive_message(&self, msg: WebSocketRawMessage) { let handler = self.0.clone(); tokio::spawn(async move { diff --git a/frontend/rust-lib/flowy-sdk/src/deps_resolve/folder_deps.rs b/frontend/rust-lib/flowy-sdk/src/deps_resolve/folder_deps.rs old mode 100644 new mode 100755 index 9d2fbfd6fe..fdc9c4d1ca --- a/frontend/rust-lib/flowy-sdk/src/deps_resolve/folder_deps.rs +++ b/frontend/rust-lib/flowy-sdk/src/deps_resolve/folder_deps.rs @@ -9,9 +9,7 @@ use flowy_core::{ use flowy_database::ConnectionPool; use flowy_document::FlowyDocumentManager; use flowy_net::{ - http_server::core::CoreHttpCloudService, - local_server::LocalServer, - ws::connection::FlowyWebSocketConnect, + http_server::core::CoreHttpCloudService, local_server::LocalServer, ws::connection::FlowyWebSocketConnect, }; use flowy_sync::{RevisionWebSocket, WSStateReceiver}; use flowy_user::services::UserSession; @@ -50,7 +48,7 @@ impl FolderDepsResolver { if let (Ok(user_id), Ok(token)) = (user.user_id(), user.token()) { match folder_manager.initialize(&user_id, &token).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("Initialize folder manager failed: {}", e), } } @@ -71,9 +69,13 @@ impl WorkspaceDatabase for WorkspaceDatabaseImpl { struct WorkspaceUserImpl(Arc); impl WorkspaceUser for WorkspaceUserImpl { - fn user_id(&self) -> Result { self.0.user_id().map_err(|e| FlowyError::internal().context(e)) } + fn user_id(&self) -> Result { + self.0.user_id().map_err(|e| FlowyError::internal().context(e)) + } - fn token(&self) -> Result { self.0.token().map_err(|e| FlowyError::internal().context(e)) } + fn token(&self) -> Result { + self.0.token().map_err(|e| FlowyError::internal().context(e)) + } } struct FolderWebSocketImpl(Arc); @@ -88,10 +90,10 @@ impl RevisionWebSocket for FolderWebSocketImpl { let ws_conn = self.0.clone(); Box::pin(async move { match ws_conn.web_socket().await? { - None => {}, + None => {} Some(sender) => { sender.send(msg).map_err(internal_error)?; - }, + } } Ok(()) }) @@ -105,7 +107,9 @@ impl RevisionWebSocket for FolderWebSocketImpl { struct FolderWSMessageReceiverImpl(Arc); impl WSMessageReceiver for FolderWSMessageReceiverImpl { - fn source(&self) -> WSChannel { WSChannel::Folder } + fn source(&self) -> WSChannel { + WSChannel::Folder + } fn receive_message(&self, msg: WebSocketRawMessage) { let handler = self.0.clone(); tokio::spawn(async move { diff --git a/frontend/rust-lib/flowy-sdk/src/deps_resolve/mod.rs b/frontend/rust-lib/flowy-sdk/src/deps_resolve/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sdk/src/deps_resolve/user_deps.rs b/frontend/rust-lib/flowy-sdk/src/deps_resolve/user_deps.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sdk/src/lib.rs b/frontend/rust-lib/flowy-sdk/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sdk/src/module.rs b/frontend/rust-lib/flowy-sdk/src/module.rs old mode 100644 new mode 100755 index 9260b88031..cf49c1c240 --- 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, folder_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_folder_module(core: Arc) -> Module { flowy_core::module::create(core) } +fn mk_folder_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-sync/Cargo.toml b/frontend/rust-lib/flowy-sync/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sync/src/cache/disk/mod.rs b/frontend/rust-lib/flowy-sync/src/cache/disk/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sync/src/cache/disk/sql_impl.rs b/frontend/rust-lib/flowy-sync/src/cache/disk/sql_impl.rs old mode 100644 new mode 100755 index a1a8660941..305b3bf568 --- a/frontend/rust-lib/flowy-sync/src/cache/disk/sql_impl.rs +++ b/frontend/rust-lib/flowy-sync/src/cache/disk/sql_impl.rs @@ -6,8 +6,7 @@ use flowy_collaboration::{ util::md5, }; use flowy_database::{ - impl_sql_integer_expression, - insert_or_ignore_into, + impl_sql_integer_expression, insert_or_ignore_into, prelude::*, schema::{rev_table, rev_table::dsl}, ConnectionPool, @@ -201,11 +200,13 @@ pub(crate) struct RevisionTable { #[sql_type = "Integer"] pub enum RevisionTableState { Sync = 0, - Ack = 1, + Ack = 1, } impl std::default::Default for RevisionTableState { - fn default() -> Self { RevisionTableState::Sync } + fn default() -> Self { + RevisionTableState::Sync + } } impl std::convert::From for RevisionTableState { @@ -216,13 +217,15 @@ impl std::convert::From for RevisionTableState { o => { tracing::error!("Unsupported rev state {}, fallback to RevState::Local", o); RevisionTableState::Sync - }, + } } } } impl RevisionTableState { - pub fn value(&self) -> i32 { *self as i32 } + pub fn value(&self) -> i32 { + *self as i32 + } } impl_sql_integer_expression!(RevisionTableState); @@ -251,7 +254,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 { @@ -265,12 +268,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 { @@ -281,12 +286,14 @@ impl std::convert::From for RevTableType { o => { tracing::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-sync/src/cache/memory.rs b/frontend/rust-lib/flowy-sync/src/cache/memory.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sync/src/cache/mod.rs b/frontend/rust-lib/flowy-sync/src/cache/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sync/src/conflict_resolve.rs b/frontend/rust-lib/flowy-sync/src/conflict_resolve.rs old mode 100644 new mode 100755 index 391db36741..d294fb3f0d --- a/frontend/rust-lib/flowy-sync/src/conflict_resolve.rs +++ b/frontend/rust-lib/flowy-sync/src/conflict_resolve.rs @@ -65,10 +65,10 @@ where } match self.handle_revision(repeated_revision).await? { - None => {}, + None => {} Some(server_revision) => { self.rev_sink.send(vec![server_revision]).await?; - }, + } } Ok(()) } @@ -115,7 +115,7 @@ where assert_eq!(repeated_revision.last().unwrap().md5, md5); let _ = self.rev_manager.reset_object(repeated_revision).await?; Ok(None) - }, + } Some(server_prime) => { let md5 = self.target.compose_delta(client_prime.clone()).await?; for revision in &revisions { @@ -130,7 +130,7 @@ where ); let _ = self.rev_manager.add_remote_revision(&client_revision).await?; Ok(server_revision) - }, + } } } } @@ -151,7 +151,7 @@ where base_rev_id, rev_id, client_delta.to_bytes(), - &user_id, + user_id, md5.clone(), ); @@ -163,11 +163,11 @@ where base_rev_id, rev_id, server_delta.to_bytes(), - &user_id, + user_id, md5, ); (client_revision, Some(server_revision)) - }, + } } } diff --git a/frontend/rust-lib/flowy-sync/src/lib.rs b/frontend/rust-lib/flowy-sync/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-sync/src/rev_manager.rs b/frontend/rust-lib/flowy-sync/src/rev_manager.rs old mode 100644 new mode 100755 index 34e43c2764..366ce22129 --- a/frontend/rust-lib/flowy-sync/src/rev_manager.rs +++ b/frontend/rust-lib/flowy-sync/src/rev_manager.rs @@ -7,7 +7,7 @@ use flowy_collaboration::{ use flowy_error::{FlowyError, FlowyResult}; use lib_infra::future::FutureResult; use std::{collections::VecDeque, sync::Arc}; -use tokio::sync::{broadcast, RwLock}; +use tokio::sync::RwLock; pub trait RevisionCloudService: Send + Sync { fn fetch_object(&self, user_id: &str, object_id: &str) -> FutureResult, FlowyError>; @@ -26,7 +26,7 @@ pub struct RevisionManager { revision_sync_seq: Arc, #[cfg(feature = "flowy_unit_test")] - revision_ack_notifier: broadcast::Sender, + revision_ack_notifier: tokio::sync::broadcast::Sender, } impl RevisionManager { @@ -34,7 +34,7 @@ impl RevisionManager { let rev_id_counter = RevIdCounter::new(0); let revision_sync_seq = Arc::new(RevisionSyncSequence::new()); #[cfg(feature = "flowy_unit_test")] - let (revision_ack_notifier, _) = broadcast::channel(1); + let (revision_ack_notifier, _) = tokio::sync::broadcast::channel(1); Self { object_id: object_id.to_string(), @@ -114,7 +114,9 @@ impl RevisionManager { 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 next_rev_id_pair(&self) -> (i64, i64) { let cur = self.rev_id_counter.value(); @@ -142,7 +144,9 @@ impl RevisionManager { }) } - pub async fn latest_revision(&self) -> Revision { self.revision_cache.latest_revision().await } + pub async fn latest_revision(&self) -> Revision { + self.revision_cache.latest_revision().await + } pub async fn get_revision(&self, rev_id: i64) -> Option { self.revision_cache.get(rev_id).await.map(|record| record.revision) @@ -165,7 +169,9 @@ impl std::default::Default for RevisionSyncSequence { } impl RevisionSyncSequence { - fn new() -> Self { RevisionSyncSequence::default() } + fn new() -> Self { + RevisionSyncSequence::default() + } async fn add_revision_record(&self, record: RevisionRecord) -> FlowyResult<()> { if !record.state.is_need_sync() { @@ -208,7 +214,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 { @@ -246,7 +254,7 @@ impl RevisionLoader { Ok::<(), FlowyError>(()) }; match f().await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("[RevisionLoader]: {}", e), } } @@ -265,13 +273,21 @@ impl RevisionLoader { #[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 RevisionManager { - pub fn revision_cache(&self) -> Arc { self.revision_cache.clone() } - pub fn revision_ack_receiver(&self) -> broadcast::Receiver { self.revision_ack_notifier.subscribe() } + pub fn revision_cache(&self) -> Arc { + self.revision_cache.clone() + } + pub fn revision_ack_receiver(&self) -> tokio::sync::broadcast::Receiver { + self.revision_ack_notifier.subscribe() + } } diff --git a/frontend/rust-lib/flowy-sync/src/ws_manager.rs b/frontend/rust-lib/flowy-sync/src/ws_manager.rs old mode 100644 new mode 100755 index 6f66d29ea8..aa108a366a --- a/frontend/rust-lib/flowy-sync/src/ws_manager.rs +++ b/frontend/rust-lib/flowy-sync/src/ws_manager.rs @@ -12,8 +12,7 @@ use lib_ws::WSConnectState; use std::{collections::VecDeque, convert::TryFrom, fmt::Formatter, sync::Arc}; use tokio::{ sync::{ - broadcast, - mpsc, + broadcast, mpsc, mpsc::{Receiver, Sender}, RwLock, }, @@ -107,7 +106,9 @@ impl RevisionWebSocketManager { tokio::spawn(stream.run()); } - pub fn scribe_state(&self) -> broadcast::Receiver { self.state_passthrough_tx.subscribe() } + pub fn scribe_state(&self) -> broadcast::Receiver { + self.state_passthrough_tx.subscribe() + } pub fn stop(&self) { if self.stop_sync_tx.send(()).is_ok() { @@ -117,7 +118,9 @@ impl RevisionWebSocketManager { } impl std::ops::Drop for RevisionWebSocketManager { - fn drop(&mut self) { tracing::trace!("{} was dropped", self) } + fn drop(&mut self) { + tracing::trace!("{} was dropped", self) + } } pub struct RevisionWSStream { @@ -135,7 +138,9 @@ impl std::fmt::Display for RevisionWSStream { } impl std::ops::Drop for RevisionWSStream { - fn drop(&mut self) { tracing::trace!("{} was dropped", self) } + fn drop(&mut self) { + tracing::trace!("{} was dropped", self) + } } impl RevisionWSStream { @@ -185,7 +190,7 @@ impl RevisionWSStream { stream .for_each(|msg| async { match self.handle_message(msg).await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("[{}]:{} error: {}", &self, self.object_id, e), } }) @@ -199,19 +204,19 @@ impl RevisionWSStream { match ty { ServerRevisionWSDataType::ServerPushRev => { let _ = self.consumer.receive_push_revision(bytes).await?; - }, + } ServerRevisionWSDataType::ServerPullRev => { let range = RevisionRange::try_from(bytes)?; let _ = self.consumer.pull_revisions_in_range(range).await?; - }, + } ServerRevisionWSDataType::ServerAck => { let rev_id = RevId::try_from(bytes).unwrap().value; let _ = self.consumer.receive_ack(rev_id.to_string(), ty).await; - }, + } ServerRevisionWSDataType::UserConnect => { let new_user = NewDocumentUser::try_from(bytes)?; let _ = self.consumer.receive_new_user_connect(new_user).await; - }, + } } Ok(()) } @@ -272,7 +277,7 @@ impl RevisionWSSink { stream .for_each(|_| async { match self.send_next_revision().await { - Ok(_) => {}, + Ok(_) => {} Err(e) => tracing::error!("[{}] send failed, {:?}", self, e), } }) @@ -284,11 +289,11 @@ impl RevisionWSSink { None => { tracing::trace!("[{}]: Finish synchronizing revisions", self); Ok(()) - }, + } Some(data) => { tracing::trace!("[{}]: send {}:{}-{:?}", self, data.object_id, data.id(), data.ty); self.ws_sender.send(data).await - }, + } } } } @@ -300,7 +305,9 @@ impl std::fmt::Display for RevisionWSSink { } impl std::ops::Drop for RevisionWSSink { - fn drop(&mut self) { tracing::trace!("{} was dropped", self) } + fn drop(&mut self) { + tracing::trace!("{} was dropped", self) + } } async fn tick(sender: mpsc::Sender<()>, duration: Duration) { @@ -334,7 +341,9 @@ impl CompositeWSSinkDataProvider { } } - pub async fn push_data(&self, data: ClientRevisionWSData) { self.container.write().await.push_back(data); } + pub async fn push_data(&self, data: ClientRevisionWSData) { + self.container.write().await.push_back(data); + } pub async fn next(&self) -> FlowyResult> { let source = self.source.read().await.clone(); @@ -343,7 +352,7 @@ impl CompositeWSSinkDataProvider { None => { *self.source.write().await = Source::Revision; Ok(None) - }, + } Some(data) => Ok(Some(data.clone())), }, Source::Revision => { @@ -359,7 +368,7 @@ impl CompositeWSSinkDataProvider { self.rev_manager.rev_id(), ))), } - }, + } }; data } @@ -378,20 +387,20 @@ impl CompositeWSSinkDataProvider { tracing::error!("The front element's {} is not equal to the {}", expected_id, id); false } - }, + } }; if should_pop { let _ = self.container.write().await.pop_front(); } Ok(()) - }, + } Source::Revision => { let rev_id = id.parse::().map_err(|e| { FlowyError::internal().context(format!("Parse {} rev_id from {} failed. {}", self.object_id, id, e)) })?; let _ = self.rev_manager.ack_revision(rev_id).await?; Ok::<(), FlowyError>(()) - }, + } } } } diff --git a/frontend/rust-lib/flowy-test/Cargo.toml b/frontend/rust-lib/flowy-test/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-test/src/event_builder.rs b/frontend/rust-lib/flowy-test/src/event_builder.rs old mode 100644 new mode 100755 index 2a5720eff0..ef0ed4e5d0 --- 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 FolderEventBuilder = EventBuilder; impl FolderEventBuilder { - 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 = FolderEventBuilder; @@ -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 old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-test/src/lib.rs b/frontend/rust-lib/flowy-test/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/Cargo.toml b/frontend/rust-lib/flowy-user/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/Flowy.toml b/frontend/rust-lib/flowy-user/Flowy.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/dart_notification.rs b/frontend/rust-lib/flowy-user/src/dart_notification.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/event.rs b/frontend/rust-lib/flowy-user/src/event.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/handlers/auth_handler.rs b/frontend/rust-lib/flowy-user/src/handlers/auth_handler.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/handlers/mod.rs b/frontend/rust-lib/flowy-user/src/handlers/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/handlers/user_handler.rs b/frontend/rust-lib/flowy-user/src/handlers/user_handler.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/lib.rs b/frontend/rust-lib/flowy-user/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/module.rs b/frontend/rust-lib/flowy-user/src/module.rs old mode 100644 new mode 100755 index fd69935c07..976b266bbf --- a/frontend/rust-lib/flowy-user/src/module.rs +++ b/frontend/rust-lib/flowy-user/src/module.rs @@ -1,11 +1,6 @@ use crate::{errors::FlowyError, event::UserEvent, handlers::*, services::UserSession}; use flowy_user_data_model::entities::{ - SignInParams, - SignInResponse, - SignUpParams, - SignUpResponse, - UpdateUserParams, - UserProfile, + SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile, }; use lib_dispatch::prelude::*; use lib_infra::future::FutureResult; diff --git a/frontend/rust-lib/flowy-user/src/protobuf/mod.rs b/frontend/rust-lib/flowy-user/src/protobuf/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/protobuf/model/dart_notification.rs b/frontend/rust-lib/flowy-user/src/protobuf/model/dart_notification.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/protobuf/model/event.rs b/frontend/rust-lib/flowy-user/src/protobuf/model/event.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/protobuf/model/mod.rs b/frontend/rust-lib/flowy-user/src/protobuf/model/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/protobuf/proto/dart_notification.proto b/frontend/rust-lib/flowy-user/src/protobuf/proto/dart_notification.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/protobuf/proto/event.proto b/frontend/rust-lib/flowy-user/src/protobuf/proto/event.proto old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/services/database.rs b/frontend/rust-lib/flowy-user/src/services/database.rs old mode 100644 new mode 100755 index cc9f95516d..f7a8e9a85c --- a/frontend/rust-lib/flowy-user/src/services/database.rs +++ b/frontend/rust-lib/flowy-user/src/services/database.rs @@ -130,11 +130,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/src/services/mod.rs b/frontend/rust-lib/flowy-user/src/services/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/src/services/notifier.rs b/frontend/rust-lib/flowy-user/src/services/notifier.rs old mode 100644 new mode 100755 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 deleted file mode 100644 index 14f7358b0c..0000000000 --- a/frontend/rust-lib/flowy-user/src/services/server/server_api.rs +++ /dev/null @@ -1,92 +0,0 @@ -use crate::{ - entities::{SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile}, - errors::FlowyError, - services::server::UserServerAPI, -}; -use backend_service::{configuration::*, http_request::*}; -use lib_infra::future::FutureResult; - -pub struct UserHttpServer { - config: ClientServerConfiguration, -} -impl UserHttpServer { - pub fn new(config: ClientServerConfiguration) -> Self { - Self { config } - } -} - -impl UserServerAPI for UserHttpServer { - fn sign_up(&self, params: SignUpParams) -> FutureResult { - let url = self.config.sign_up_url(); - FutureResult::new(async move { - let resp = user_sign_up_request(params, &url).await?; - Ok(resp) - }) - } - - fn sign_in(&self, params: SignInParams) -> FutureResult { - let url = self.config.sign_in_url(); - FutureResult::new(async move { - let resp = user_sign_in_request(params, &url).await?; - Ok(resp) - }) - } - - fn sign_out(&self, token: &str) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.sign_out_url(); - FutureResult::new(async move { - let _ = user_sign_out_request(&token, &url).await; - Ok(()) - }) - } - - fn update_user(&self, token: &str, params: UpdateUserParams) -> FutureResult<(), FlowyError> { - let token = token.to_owned(); - let url = self.config.user_profile_url(); - FutureResult::new(async move { - let _ = update_user_profile_request(&token, params, &url).await?; - Ok(()) - }) - } - - fn get_user(&self, token: &str) -> FutureResult { - let token = token.to_owned(); - let url = self.config.user_profile_url(); - FutureResult::new(async move { - let profile = get_user_profile_request(&token, &url).await?; - Ok(profile) - }) - } - - fn ws_addr(&self) -> String { - self.config.ws_addr() - } -} - -// use crate::notify::*; -// use backend_service::response::FlowyResponse; -// use flowy_user_data_model::errors::ErrorCode; - -// struct Middleware {} -// -// -// -// impl ResponseMiddleware for Middleware { -// fn receive_response(&self, token: &Option, response: -// &FlowyResponse) { if let Some(error) = &response.error { -// if error.is_unauthorized() { -// log::error!("user unauthorized"); -// match token { -// None => {}, -// Some(token) => { -// let error = -// FlowyError::new(ErrorCode::UserUnauthorized, ""); -// dart_notify(token, UserNotification::UserUnauthorized) -// .error(error) .send() -// }, -// } -// } -// } -// } -// } 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 deleted file mode 100644 index 0742de1799..0000000000 --- a/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs +++ /dev/null @@ -1,53 +0,0 @@ -use crate::{ - entities::{SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile}, - errors::FlowyError, -}; - -use crate::services::server::UserServerAPI; -use lib_infra::{future::FutureResult, uuid_string}; - -pub struct UserServerMock {} - -impl UserServerMock {} - -impl UserServerAPI for UserServerMock { - fn sign_up(&self, params: SignUpParams) -> FutureResult { - let uid = uuid_string(); - FutureResult::new(async move { - Ok(SignUpResponse { - user_id: uid.clone(), - name: params.name, - email: params.email, - token: uid, - }) - }) - } - - fn sign_in(&self, params: SignInParams) -> FutureResult { - let user_id = uuid_string(); - FutureResult::new(async { - Ok(SignInResponse { - user_id: user_id.clone(), - name: params.name, - email: params.email, - token: user_id, - }) - }) - } - - 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(()) }) - } - - fn get_user(&self, _token: &str) -> FutureResult { - FutureResult::new(async { Ok(UserProfile::default()) }) - } - - fn ws_addr(&self) -> String { - "ws://localhost:8000/ws/".to_owned() - } -} diff --git a/frontend/rust-lib/flowy-user/src/services/user_session.rs b/frontend/rust-lib/flowy-user/src/services/user_session.rs old mode 100644 new mode 100755 index 89d621bfc4..a14ef89074 --- a/frontend/rust-lib/flowy-user/src/services/user_session.rs +++ b/frontend/rust-lib/flowy-user/src/services/user_session.rs @@ -14,12 +14,7 @@ use flowy_database::{ DBConnection, ExpressionMethods, UserDatabaseConnection, }; use flowy_user_data_model::entities::{ - SignInParams, - SignInResponse, - SignUpParams, - SignUpResponse, - UpdateUserParams, - UserProfile, + SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile, }; use lib_sqlite::ConnectionPool; use parking_lot::RwLock; diff --git a/frontend/rust-lib/flowy-user/src/sql_tables/user.rs b/frontend/rust-lib/flowy-user/src/sql_tables/user.rs deleted file mode 100644 index 6d0c9d738b..0000000000 --- a/frontend/rust-lib/flowy-user/src/sql_tables/user.rs +++ /dev/null @@ -1,73 +0,0 @@ -use crate::entities::{SignInResponse, SignUpResponse, UpdateUserParams}; -use flowy_database::schema::user_table; -use flowy_user_data_model::entities::UserProfile; - -#[derive(Clone, Default, Queryable, Identifiable, Insertable)] -#[table_name = "user_table"] -pub struct UserTable { - pub(crate) id: String, - pub(crate) name: String, - pub(crate) token: String, - pub(crate) email: String, - pub(crate) workspace: String, // deprecated -} - -impl UserTable { - pub fn new(id: String, name: String, email: String, token: String) -> Self { - Self { - id, - name, - email, - token, - workspace: "".to_owned(), - } - } - - pub fn set_workspace(mut self, workspace: String) -> Self { - self.workspace = workspace; - self - } -} - -impl std::convert::From for UserTable { - 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) - } -} - -impl std::convert::From for UserProfile { - fn from(table: UserTable) -> Self { - UserProfile { - id: table.id, - email: table.email, - name: table.name, - token: table.token, - } - } -} - -#[derive(AsChangeset, Identifiable, Default, Debug)] -#[table_name = "user_table"] -pub struct UserTableChangeset { - pub id: String, - pub workspace: Option, // deprecated - pub name: Option, - pub email: Option, -} - -impl UserTableChangeset { - pub fn new(params: UpdateUserParams) -> Self { - UserTableChangeset { - id: params.id, - workspace: None, - name: params.name, - email: params.email, - } - } -} diff --git a/frontend/rust-lib/flowy-user/tests/event/auth_test.rs b/frontend/rust-lib/flowy-user/tests/event/auth_test.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/tests/event/helper.rs b/frontend/rust-lib/flowy-user/tests/event/helper.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/tests/event/main.rs b/frontend/rust-lib/flowy-user/tests/event/main.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/flowy-user/tests/event/user_profile_test.rs b/frontend/rust-lib/flowy-user/tests/event/user_profile_test.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/Cargo.toml b/frontend/rust-lib/lib-dispatch/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/byte_trait.rs b/frontend/rust-lib/lib-dispatch/src/byte_trait.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/data.rs b/frontend/rust-lib/lib-dispatch/src/data.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/dispatcher.rs b/frontend/rust-lib/lib-dispatch/src/dispatcher.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/errors/errors.rs b/frontend/rust-lib/lib-dispatch/src/errors/errors.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/errors/mod.rs b/frontend/rust-lib/lib-dispatch/src/errors/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/lib.rs b/frontend/rust-lib/lib-dispatch/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/macros.rs b/frontend/rust-lib/lib-dispatch/src/macros.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/module/container.rs b/frontend/rust-lib/lib-dispatch/src/module/container.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/module/data.rs b/frontend/rust-lib/lib-dispatch/src/module/data.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/module/mod.rs b/frontend/rust-lib/lib-dispatch/src/module/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/module/module.rs b/frontend/rust-lib/lib-dispatch/src/module/module.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/request/mod.rs b/frontend/rust-lib/lib-dispatch/src/request/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/request/payload.rs b/frontend/rust-lib/lib-dispatch/src/request/payload.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/request/request.rs b/frontend/rust-lib/lib-dispatch/src/request/request.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/response/builder.rs b/frontend/rust-lib/lib-dispatch/src/response/builder.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/response/mod.rs b/frontend/rust-lib/lib-dispatch/src/response/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/response/responder.rs b/frontend/rust-lib/lib-dispatch/src/response/responder.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/response/response.rs b/frontend/rust-lib/lib-dispatch/src/response/response.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/service/boxed.rs b/frontend/rust-lib/lib-dispatch/src/service/boxed.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/service/handler.rs b/frontend/rust-lib/lib-dispatch/src/service/handler.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/service/mod.rs b/frontend/rust-lib/lib-dispatch/src/service/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/service/service.rs b/frontend/rust-lib/lib-dispatch/src/service/service.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/system.rs b/frontend/rust-lib/lib-dispatch/src/system.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/util/mod.rs b/frontend/rust-lib/lib-dispatch/src/util/mod.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/src/util/ready.rs b/frontend/rust-lib/lib-dispatch/src/util/ready.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/tests/api/main.rs b/frontend/rust-lib/lib-dispatch/tests/api/main.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-dispatch/tests/api/module.rs b/frontend/rust-lib/lib-dispatch/tests/api/module.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-log/Cargo.toml b/frontend/rust-lib/lib-log/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-log/flowy_log_test.2021-11-09 b/frontend/rust-lib/lib-log/flowy_log_test.2021-11-09 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/frontend/rust-lib/lib-log/src/layer.rs b/frontend/rust-lib/lib-log/src/layer.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-log/src/lib.rs b/frontend/rust-lib/lib-log/src/lib.rs old mode 100644 new mode 100755 index 4e8cd07a17..c667f33344 --- a/frontend/rust-lib/lib-log/src/lib.rs +++ b/frontend/rust-lib/lib-log/src/lib.rs @@ -84,13 +84,6 @@ impl Builder { #[cfg(test)] mod tests { use super::*; - - #[derive(Debug)] - struct Position { - x: f32, - y: f32, - } - // run cargo test --features="use_bunyan" or cargo test #[test] fn test_log() { diff --git a/frontend/rust-lib/lib-sqlite/Cargo.toml b/frontend/rust-lib/lib-sqlite/Cargo.toml old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-sqlite/src/conn_ext.rs b/frontend/rust-lib/lib-sqlite/src/conn_ext.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-sqlite/src/database.rs b/frontend/rust-lib/lib-sqlite/src/database.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-sqlite/src/errors.rs b/frontend/rust-lib/lib-sqlite/src/errors.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-sqlite/src/lib.rs b/frontend/rust-lib/lib-sqlite/src/lib.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-sqlite/src/pool.rs b/frontend/rust-lib/lib-sqlite/src/pool.rs old mode 100644 new mode 100755 diff --git a/frontend/rust-lib/lib-sqlite/src/pragma.rs b/frontend/rust-lib/lib-sqlite/src/pragma.rs old mode 100644 new mode 100755 diff --git a/shared-lib/backend-service/src/errors.rs b/shared-lib/backend-service/src/errors.rs index 2b11f111c1..8035798817 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 to_collaborate_error(&self) -> CollaborateError { if self.is_record_not_found() { @@ -64,7 +70,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 { @@ -86,45 +94,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/flowy-collaboration/src/client_document/document_pad.rs b/shared-lib/flowy-collaboration/src/client_document/document_pad.rs index 10680df605..2559955e6d 100644 --- a/shared-lib/flowy-collaboration/src/client_document/document_pad.rs +++ b/shared-lib/flowy-collaboration/src/client_document/document_pad.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 ClientDocument { @@ -35,7 +39,9 @@ pub struct ClientDocument { } impl ClientDocument { - 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 { ClientDocument { @@ -52,30 +58,40 @@ impl ClientDocument { 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 { let bytes = self.to_bytes(); 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(()); - }, + } } } @@ -116,7 +132,7 @@ impl ClientDocument { 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())?; @@ -153,9 +169,13 @@ impl ClientDocument { 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() { @@ -165,7 +185,7 @@ impl ClientDocument { self.set_delta(new_delta); self.history.add_redo(inverted_delta); Ok(UndoResult { delta: undo_delta }) - }, + } } } @@ -177,7 +197,7 @@ impl ClientDocument { self.set_delta(new_delta); self.history.add_undo(inverted_delta); Ok(UndoResult { delta: redo_delta }) - }, + } } } diff --git a/shared-lib/flowy-collaboration/src/entities/revision.rs b/shared-lib/flowy-collaboration/src/entities/revision.rs index cd413ce07e..d36ab1b986 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, object_id: &str, delta_data: Bytes) -> Self { let md5 = md5(&delta_data); @@ -77,7 +83,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 { @@ -88,10 +96,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(()) } @@ -106,11 +114,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 { @@ -119,9 +131,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)] @@ -131,19 +147,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)] @@ -168,7 +192,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); @@ -185,7 +211,7 @@ pub fn md5>(data: T) -> String { #[derive(Debug, Clone, Eq, PartialEq)] pub enum RevisionState { Sync = 0, - Ack = 1, + Ack = 1, } impl RevisionState { @@ -198,15 +224,19 @@ impl RevisionState { } 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_data.rs b/shared-lib/flowy-collaboration/src/entities/ws_data.rs index 8b67caa99f..8bcbe3615b 100644 --- a/shared-lib/flowy-collaboration/src/entities/ws_data.rs +++ b/shared-lib/flowy-collaboration/src/entities/ws_data.rs @@ -9,7 +9,7 @@ use std::convert::{TryFrom, TryInto}; #[derive(Debug, Clone, ProtoBuf_Enum, Eq, PartialEq, Hash)] pub enum ClientRevisionWSDataType { ClientPushRev = 0, - ClientPing = 1, + ClientPing = 1, } impl ClientRevisionWSDataType { @@ -22,7 +22,9 @@ impl ClientRevisionWSDataType { } impl std::default::Default for ClientRevisionWSDataType { - fn default() -> Self { ClientRevisionWSDataType::ClientPushRev } + fn default() -> Self { + ClientRevisionWSDataType::ClientPushRev + } } #[derive(ProtoBuf, Default, Debug, Clone)] @@ -64,19 +66,23 @@ impl ClientRevisionWSData { } } - pub fn id(&self) -> String { self.data_id.clone() } + pub fn id(&self) -> String { + self.data_id.clone() + } } #[derive(Debug, Clone, ProtoBuf_Enum, Eq, PartialEq, Hash)] pub enum ServerRevisionWSDataType { - ServerAck = 0, + ServerAck = 0, ServerPushRev = 1, ServerPullRev = 2, - UserConnect = 3, + UserConnect = 3, } impl std::default::Default for ServerRevisionWSDataType { - fn default() -> Self { ServerRevisionWSDataType::ServerPushRev } + fn default() -> Self { + ServerRevisionWSDataType::ServerPushRev + } } #[derive(ProtoBuf, Default, Debug, Clone)] diff --git a/shared-lib/flowy-collaboration/src/folder/folder_pad.rs b/shared-lib/flowy-collaboration/src/folder/folder_pad.rs index 95dc5775d5..5800922c50 100644 --- a/shared-lib/flowy-collaboration/src/folder/folder_pad.rs +++ b/shared-lib/flowy-collaboration/src/folder/folder_pad.rs @@ -54,9 +54,13 @@ impl FolderPad { FolderPadBuilder::new().build_with_revisions(revisions) } - pub fn from_delta(delta: FolderDelta) -> CollaborateResult { FolderPadBuilder::new().build_with_delta(delta) } + pub fn from_delta(delta: FolderDelta) -> CollaborateResult { + FolderPadBuilder::new().build_with_delta(delta) + } - pub fn delta(&self) -> &FolderDelta { &self.root } + pub fn delta(&self) -> &FolderDelta { + &self.root + } pub fn reset_folder(&mut self, delta: FolderDelta) -> CollaborateResult { let folder = FolderPad::from_delta(delta)?; @@ -72,7 +76,9 @@ impl FolderPad { self.reset_folder(composed_delta) } - pub fn is_empty(&self) -> bool { self.workspaces.is_empty() && self.trash.is_empty() } + pub fn is_empty(&self) -> bool { + self.workspaces.is_empty() && self.trash.is_empty() + } pub fn create_workspace(&mut self, workspace: Workspace) -> CollaborateResult> { let workspace = Arc::new(workspace); @@ -114,7 +120,7 @@ impl FolderPad { .map(|workspace| workspace.as_ref().clone()) .collect::>(); Ok(workspaces) - }, + } Some(workspace_id) => { if let Some(workspace) = self.workspaces.iter().find(|workspace| workspace.id == workspace_id) { Ok(vec![workspace.as_ref().clone()]) @@ -122,7 +128,7 @@ impl FolderPad { Err(CollaborateError::record_not_found() .context(format!("Can't find workspace with id {}", workspace_id))) } - }, + } } } @@ -276,7 +282,9 @@ impl FolderPad { } } - pub fn md5(&self) -> String { md5(&self.root.to_bytes()) } + pub fn md5(&self) -> String { + md5(&self.root.to_bytes()) + } } impl FolderPad { @@ -293,7 +301,7 @@ impl FolderPad { let delta = cal_diff(old, new); self.root = self.root.compose(&delta)?; Ok(Some(FolderChange { delta, md5: self.md5() })) - }, + } } } @@ -324,7 +332,7 @@ impl FolderPad { let delta = cal_diff(old, new); self.root = self.root.compose(&delta)?; Ok(Some(FolderChange { delta, md5: self.md5() })) - }, + } } } @@ -340,7 +348,7 @@ impl FolderPad { None => { tracing::warn!("[RootFolder]: Can't find any app with id: {}", app_id); return Ok(None); - }, + } Some(workspace) => workspace.id.clone(), }; @@ -359,7 +367,7 @@ impl FolderPad { None => { tracing::warn!("[RootFolder]: Can't find any view with id: {}", view_id); Ok(None) - }, + } Some(view) => f(view), } }) @@ -378,13 +386,13 @@ fn cal_diff(old: String, new: String) -> Delta { match chunk { Chunk::Equal(s) => { delta_builder = delta_builder.retain(FlowyStr::from(*s).utf16_size()); - }, + } Chunk::Delete(s) => { delta_builder = delta_builder.delete(FlowyStr::from(*s).utf16_size()); - }, + } Chunk::Insert(s) => { delta_builder = delta_builder.insert(*s); - }, + } } } delta_builder.build() diff --git a/shared-lib/flowy-collaboration/src/server_document/document_manager.rs b/shared-lib/flowy-collaboration/src/server_document/document_manager.rs index 5b19d53f05..e204d43ae4 100644 --- a/shared-lib/flowy-collaboration/src/server_document/document_manager.rs +++ b/shared-lib/flowy-collaboration/src/server_document/document_manager.rs @@ -93,11 +93,11 @@ impl ServerDocumentManager { CollaborateError::internal().context(format!("Server create document failed: {}", e)) })?; Ok(()) - }, + } Some(handler) => { let _ = handler.apply_revisions(user, repeated_revision).await?; Ok(()) - }, + } }; if result.is_ok() { @@ -119,11 +119,11 @@ impl ServerDocumentManager { None => { tracing::trace!("Document:{} doesn't exist, ignore client ping", doc_id); Ok(()) - }, + } Some(handler) => { let _ = handler.apply_ping(rev_id, user).await?; Ok(()) - }, + } } } @@ -137,11 +137,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(()) - }, + } } } @@ -157,7 +157,7 @@ impl ServerDocumentManager { write_guard.insert(doc_id.to_owned(), handler.clone()); drop(write_guard); Some(handler) - }, + } Err(_) => None, } } @@ -177,7 +177,7 @@ impl ServerDocumentManager { .await .insert(doc_id.to_owned(), handler.clone()); Ok(handler) - }, + } } } @@ -341,15 +341,15 @@ impl DocumentCommandRunner { .await .map_err(internal_error); let _ = ret.send(result); - }, + } DocumentCommand::Ping { user, rev_id, ret } => { let result = self.synchronizer.pong(user, rev_id).await.map_err(internal_error); let _ = ret.send(result); - }, + } DocumentCommand::Reset { repeated_revision, ret } => { let result = self.synchronizer.reset(repeated_revision).await.map_err(internal_error); let _ = ret.send(result); - }, + } } } } diff --git a/shared-lib/flowy-collaboration/src/server_document/document_pad.rs b/shared-lib/flowy-collaboration/src/server_document/document_pad.rs index a67f49a227..e7c02f5566 100644 --- a/shared-lib/flowy-collaboration/src/server_document/document_pad.rs +++ b/shared-lib/flowy-collaboration/src/server_document/document_pad.rs @@ -11,7 +11,9 @@ pub struct ServerDocument { impl ServerDocument { #[allow(dead_code)] - pub fn new(doc_id: &str) -> Self { Self::from_delta(doc_id, C::initial_delta()) } + pub fn new(doc_id: &str) -> Self { + Self::from_delta(doc_id, C::initial_delta()) + } pub fn from_delta(doc_id: &str, delta: RichTextDelta) -> Self { let doc_id = doc_id.to_owned(); @@ -20,7 +22,9 @@ impl ServerDocument { } impl RevisionSyncObject for ServerDocument { - fn id(&self) -> &str { &self.doc_id } + fn id(&self) -> &str { + &self.doc_id + } fn compose(&mut self, other: &RichTextDelta) -> Result<(), CollaborateError> { // tracing::trace!("{} compose {}", &self.delta.to_json(), other.to_json()); @@ -34,7 +38,11 @@ impl RevisionSyncObject for ServerDocument { Ok(value) } - fn to_json(&self) -> String { self.delta.to_json() } + fn to_json(&self) -> String { + self.delta.to_json() + } - fn set_delta(&mut self, new_delta: Delta) { self.delta = new_delta; } + fn set_delta(&mut self, new_delta: Delta) { + self.delta = new_delta; + } } diff --git a/shared-lib/flowy-collaboration/src/server_folder/folder_manager.rs b/shared-lib/flowy-collaboration/src/server_folder/folder_manager.rs index 7b59b9ea30..96b7cb71cb 100644 --- a/shared-lib/flowy-collaboration/src/server_folder/folder_manager.rs +++ b/shared-lib/flowy-collaboration/src/server_folder/folder_manager.rs @@ -97,11 +97,11 @@ impl ServerFolderManager { .await .map_err(|e| CollaborateError::internal().context(format!("Server create folder failed: {}", e)))?; Ok(()) - }, + } Some(handler) => { let _ = handler.apply_revisions(user, repeated_revision).await?; Ok(()) - }, + } }; if result.is_ok() { @@ -124,11 +124,11 @@ impl ServerFolderManager { None => { tracing::trace!("Folder:{} doesn't exist, ignore client ping", folder_id); Ok(()) - }, + } Some(handler) => { let _ = handler.apply_ping(rev_id, user).await?; Ok(()) - }, + } } } @@ -149,7 +149,7 @@ impl ServerFolderManager { write_guard.insert(folder_id, handler.clone()); drop(write_guard); Some(handler) - }, + } Err(_) => None, } } @@ -181,8 +181,8 @@ impl ServerFolderManager { .await .insert(folder_id.to_owned(), handler.clone()); Ok(handler) - }, - None => Err(CollaborateError::internal().context(format!(""))), + } + None => Err(CollaborateError::internal().context(String::new())), } } } @@ -316,11 +316,11 @@ impl FolderCommandRunner { .await .map_err(internal_error); let _ = ret.send(result); - }, + } FolderCommand::Ping { user, rev_id, ret } => { let result = self.synchronizer.pong(user, rev_id).await.map_err(internal_error); let _ = ret.send(result); - }, + } } } } diff --git a/shared-lib/flowy-collaboration/src/server_folder/folder_pad.rs b/shared-lib/flowy-collaboration/src/server_folder/folder_pad.rs index 781f8fe980..3c7c002ef6 100644 --- a/shared-lib/flowy-collaboration/src/server_folder/folder_pad.rs +++ b/shared-lib/flowy-collaboration/src/server_folder/folder_pad.rs @@ -16,7 +16,9 @@ impl ServerFolder { } impl RevisionSyncObject for ServerFolder { - fn id(&self) -> &str { &self.folder_id } + fn id(&self) -> &str { + &self.folder_id + } fn compose(&mut self, other: &Delta) -> Result<(), CollaborateError> { let new_delta = self.delta.compose(other)?; @@ -32,7 +34,11 @@ impl RevisionSyncObject for ServerFolder { Ok(value) } - fn to_json(&self) -> String { self.delta.to_json() } + fn to_json(&self) -> String { + self.delta.to_json() + } - fn set_delta(&mut self, new_delta: Delta) { self.delta = new_delta; } + fn set_delta(&mut self, new_delta: Delta) { + self.delta = new_delta; + } } diff --git a/shared-lib/flowy-collaboration/src/synchronizer.rs b/shared-lib/flowy-collaboration/src/synchronizer.rs index 338fc9826e..b6c10452ed 100644 --- a/shared-lib/flowy-collaboration/src/synchronizer.rs +++ b/shared-lib/flowy-collaboration/src/synchronizer.rs @@ -125,11 +125,11 @@ where let msg = ServerRevisionWSDataBuilder::build_pull_message(&self.object_id, range); user.receive(RevisionSyncResponse::Pull(msg)); } - }, + } Ordering::Equal => { // Do nothing tracing::warn!("Applied {} revision rev_id is the same as cur_rev_id", self.object_id); - }, + } Ordering::Greater => { // The client delta is outdated. Transform the client revision delta and then // send the prime delta to the client. Client should compose the this prime @@ -137,7 +137,7 @@ where let from_rev_id = first_revision.rev_id; let to_rev_id = server_base_rev_id; let _ = self.push_revisions_to_user(user, from_rev_id, to_rev_id).await; - }, + } } Ok(()) } @@ -151,7 +151,7 @@ where 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.", object_id), Ordering::Greater => { // The client delta is outdated. Transform the client revision delta and then @@ -161,7 +161,7 @@ where let to_rev_id = server_rev_id; tracing::trace!("Push revisions to user"); let _ = self.push_revisions_to_user(user, from_rev_id, to_rev_id).await; - }, + } } Ok(()) } @@ -179,7 +179,9 @@ where Ok(()) } - pub fn object_json(&self) -> String { self.object.read().to_json() } + pub fn object_json(&self) -> String { + self.object.read().to_json() + } fn compose_revision(&self, revision: &RevisionPB) -> Result<(), CollaborateError> { let delta = Delta::::from_bytes(&revision.delta_data)?; @@ -204,12 +206,14 @@ where None => log::error!("Failed to acquire write lock of object"), Some(mut write_guard) => { let _ = write_guard.compose(&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, @@ -245,16 +249,18 @@ where Ok(repeated_revision) => { let data = ServerRevisionWSDataBuilder::build_push_message(&self.object_id, repeated_revision); user.receive(RevisionSyncResponse::Push(data)); - }, + } Err(e) => tracing::error!("{}", e), } - }, + } 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 f60cd53f35..0893073b4d 100644 --- a/shared-lib/flowy-collaboration/src/util.rs +++ b/shared-lib/flowy-collaboration/src/util.rs @@ -6,9 +6,7 @@ use crate::{ }, errors::{CollaborateError, CollaborateResult}, protobuf::{ - DocumentInfo as DocumentInfoPB, - FolderInfo as FolderInfoPB, - RepeatedRevision as RepeatedRevisionPB, + DocumentInfo as DocumentInfoPB, FolderInfo as FolderInfoPB, RepeatedRevision as RepeatedRevisionPB, Revision as RevisionPB, }, }; @@ -159,7 +157,7 @@ pub fn make_folder_from_revisions_pb( .try_into() .map_err(|e| CollaborateError::internal().context(e))?; Ok(Some(folder_info)) - }, + } } } @@ -207,7 +205,7 @@ pub fn make_document_info_from_revisions_pb( CollaborateError::internal().context(format!("Deserialize document info from pb failed: {}", e)) })?; Ok(Some(document_info)) - }, + } } } diff --git a/shared-lib/flowy-core-data-model/src/entities/view.rs b/shared-lib/flowy-core-data-model/src/entities/view.rs index 47826dfd78..2bdefa2003 100644 --- a/shared-lib/flowy-core-data-model/src/entities/view.rs +++ b/shared-lib/flowy-core-data-model/src/entities/view.rs @@ -65,11 +65,13 @@ impl std::convert::From for Trash { #[derive(Eq, PartialEq, Debug, ProtoBuf_Enum, Clone, Serialize, Deserialize)] 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 { @@ -80,7 +82,7 @@ impl std::convert::From for ViewType { _ => { log::error!("Invalid view type: {}", val); ViewType::Blank - }, + } } } } @@ -188,7 +190,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 TryInto for QueryViewRequest { diff --git a/shared-lib/flowy-core-data-model/src/entities/workspace.rs b/shared-lib/flowy-core-data-model/src/entities/workspace.rs index a86468123f..0fac386d4d 100644 --- a/shared-lib/flowy-core-data-model/src/entities/workspace.rs +++ b/shared-lib/flowy-core-data-model/src/entities/workspace.rs @@ -77,7 +77,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 @@ -88,7 +90,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 46f6e206cc..36e53c3a86 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) { @@ -25,9 +31,13 @@ macro_rules! impl_def_and_def_mut { } #[allow(dead_code)] - pub fn take_items(&mut self) -> Vec<$item> { std::mem::take(&mut self.items) } + pub fn take_items(&mut self) -> Vec<$item> { + std::mem::take(&mut self.items) + } - 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/lib-ot/src/core/operation/operation.rs b/shared-lib/lib-ot/src/core/operation/operation.rs index 3d89aaf849..a30f884ae6 100644 --- a/shared-lib/lib-ot/src/core/operation/operation.rs +++ b/shared-lib/lib-ot/src/core/operation/operation.rs @@ -341,11 +341,15 @@ where #[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize)] pub struct PlainTextAttributes(); impl fmt::Display for PlainTextAttributes { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("PlainTextAttributes") } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PlainTextAttributes") + } } impl Attributes for PlainTextAttributes { - fn is_empty(&self) -> bool { true } + fn is_empty(&self) -> bool { + true + } fn remove_empty(&mut self) {} @@ -353,9 +357,15 @@ impl Attributes for PlainTextAttributes { } impl OperationTransformable for PlainTextAttributes { - fn compose(&self, _other: &Self) -> Result { Ok(self.clone()) } + fn compose(&self, _other: &Self) -> Result { + Ok(self.clone()) + } - fn transform(&self, other: &Self) -> Result<(Self, Self), OTError> { Ok((self.clone(), other.clone())) } + fn transform(&self, other: &Self) -> Result<(Self, Self), OTError> { + Ok((self.clone(), other.clone())) + } - fn invert(&self, _other: &Self) -> Self { self.clone() } + fn invert(&self, _other: &Self) -> Self { + self.clone() + } } diff --git a/shared-lib/lib-ws/src/connect.rs b/shared-lib/lib-ws/src/connect.rs index 51d2a60af3..02b207282d 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>; @@ -71,11 +69,11 @@ impl Future for WSConnectionFuture { .expect("[WebSocket]: WSConnection should be call once "), ); Poll::Ready(Ok(WSStream::new(msg_tx, ws_rx, stream))) - }, + } Err(error) => { tracing::debug!("[WebSocket]: ❌ connect failed: {:?}", error); Poll::Ready(Err(error.into())) - }, + } }; } } @@ -102,7 +100,7 @@ impl WSStream { ws_read .for_each(|message| async { match tx.send(send_message(msg_tx.clone(), message)) { - Ok(_) => {}, + Ok(_) => {} Err(e) => log::error!("[WebSocket]: WSStream sender closed unexpectedly: {} ", e), } }) @@ -116,12 +114,12 @@ impl WSStream { None => { return Err(WSError::internal() .context("[WebSocket]: WSStream receiver closed unexpectedly")); - }, + } Some(result) => { if result.is_err() { return result; } - }, + } } } }; @@ -142,7 +140,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 { @@ -159,9 +159,9 @@ impl Future for WSStream { Poll::Pending => { self.inner = Some((ws_read, ws_write)); Poll::Pending - }, + } } - }, + } } } } diff --git a/shared-lib/lib-ws/src/msg.rs b/shared-lib/lib-ws/src/msg.rs index 36787ad9d1..522491a8a6 100644 --- a/shared-lib/lib-ws/src/msg.rs +++ b/shared-lib/lib-ws/src/msg.rs @@ -15,11 +15,13 @@ pub struct WebSocketRawMessage { #[derive(ProtoBuf_Enum, Debug, Clone, Eq, PartialEq, Hash)] pub enum WSChannel { Document = 0, - Folder = 1, + Folder = 1, } impl std::default::Default for WSChannel { - fn default() -> Self { WSChannel::Document } + fn default() -> Self { + WSChannel::Document + } } impl ToString for WSChannel { @@ -39,7 +41,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 5d88f29c72..05e3f98b68 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, - WSChannel, - WebSocketRawMessage, + WSChannel, WebSocketRawMessage, }; use backend_service::errors::ServerError; use bytes::Bytes; @@ -44,7 +43,9 @@ pub struct WSController { } impl std::fmt::Display for WSController { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("WebSocket") } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str("WebSocket") + } } impl std::default::Default for WSController { @@ -59,7 +60,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(); @@ -124,14 +127,14 @@ impl WSController { let _ = ret.send(Ok(())); spawn_stream_and_handlers(stream, handlers_fut).await; - }, + } Err(e) => { cloned_conn_state .write() .await .update_state(WSConnectState::Disconnected); let _ = ret.send(Err(ServerError::internal().context(e))); - }, + } } }); rx.await? @@ -166,7 +169,7 @@ impl WSController { WSConnectState::Disconnected => { let msg = "WebSocket is disconnected"; Err(WSError::internal().context(msg)) - }, + } _ => Ok(None), }, Some(sender) => Ok(Some(sender)), @@ -193,7 +196,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 { @@ -210,7 +215,7 @@ impl WSHandlerFuture { }, Err(e) => { log::error!("Deserialize binary ws message failed: {:?}", e); - }, + } } } } @@ -222,7 +227,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), } } @@ -340,7 +345,7 @@ impl Future for WSConnectActionFut { handlers_fut, sender, })) - }, + } Err(e) => Poll::Ready(Err(e)), } } @@ -355,11 +360,17 @@ pub enum WSConnectState { } impl WSConnectState { - fn is_connected(&self) -> bool { self == &WSConnectState::Connected } + fn is_connected(&self) -> bool { + self == &WSConnectState::Connected + } - fn is_connecting(&self) -> bool { self == &WSConnectState::Connecting } + fn is_connecting(&self) -> bool { + self == &WSConnectState::Connecting + } - fn is_disconnected(&self) -> bool { self == &WSConnectState::Disconnected || self == &WSConnectState::Init } + fn is_disconnected(&self) -> bool { + self == &WSConnectState::Disconnected || self == &WSConnectState::Init + } } impl std::fmt::Display for WSConnectState { @@ -374,7 +385,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 WSConnectStateNotifier {