diff --git a/frontend/Makefile.toml b/frontend/Makefile.toml index 1f9c2e9359..a5bc3ae129 100644 --- a/frontend/Makefile.toml +++ b/frontend/Makefile.toml @@ -43,7 +43,6 @@ CRATE_TYPE = "staticlib" LIB_EXT = "a" APP_ENVIRONMENT = "local" FLUTTER_FLOWY_SDK_PATH = "app_flowy/packages/flowy_sdk" -PROTOBUF_DERIVE_CACHE = "../shared-lib/flowy-derive/src/derive_cache/derive_cache.rs" # Test default config TEST_CRATE_TYPE = "cdylib" TEST_LIB_EXT = "dylib" diff --git a/frontend/app_flowy/lib/plugins/grid/application/cell/date_cal_bloc.dart b/frontend/app_flowy/lib/plugins/grid/application/cell/date_cal_bloc.dart index 6dc5df61c1..74a0fd725b 100644 --- a/frontend/app_flowy/lib/plugins/grid/application/cell/date_cal_bloc.dart +++ b/frontend/app_flowy/lib/plugins/grid/application/cell/date_cal_bloc.dart @@ -3,7 +3,7 @@ import 'package:app_flowy/plugins/grid/application/field/field_service.dart'; import 'package:easy_localization/easy_localization.dart' show StringTranslateExtension; import 'package:flowy_sdk/log.dart'; -import 'package:flowy_sdk/protobuf/flowy-error-code/code.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/code.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-grid/date_type_option.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-grid/date_type_option_entities.pb.dart'; diff --git a/frontend/app_flowy/lib/user/application/sign_in_bloc.dart b/frontend/app_flowy/lib/user/application/sign_in_bloc.dart index 1b5838d9c4..58474030c5 100644 --- a/frontend/app_flowy/lib/user/application/sign_in_bloc.dart +++ b/frontend/app_flowy/lib/user/application/sign_in_bloc.dart @@ -1,6 +1,6 @@ import 'package:app_flowy/user/application/auth_service.dart'; import 'package:dartz/dartz.dart'; -import 'package:flowy_sdk/protobuf/flowy-error-code/code.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/code.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-user/protobuf.dart' show UserProfilePB; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -20,24 +20,34 @@ class SignInBloc extends Bloc { ); }, emailChanged: (EmailChanged value) async { - emit(state.copyWith(email: value.email, emailError: none(), successOrFail: none())); + emit(state.copyWith( + email: value.email, emailError: none(), successOrFail: none())); }, passwordChanged: (PasswordChanged value) async { - emit(state.copyWith(password: value.password, passwordError: none(), successOrFail: none())); + emit(state.copyWith( + password: value.password, + passwordError: none(), + successOrFail: none())); }, ); }); } - Future _performActionOnSignIn(SignInState state, Emitter emit) async { - emit(state.copyWith(isSubmitting: true, emailError: none(), passwordError: none(), successOrFail: none())); + Future _performActionOnSignIn( + SignInState state, Emitter emit) async { + emit(state.copyWith( + isSubmitting: true, + emailError: none(), + passwordError: none(), + successOrFail: none())); final result = await authService.signIn( email: state.email, password: state.password, ); emit(result.fold( - (userProfile) => state.copyWith(isSubmitting: false, successOrFail: some(left(userProfile))), + (userProfile) => state.copyWith( + isSubmitting: false, successOrFail: some(left(userProfile))), (error) => stateFromCode(error), )); } @@ -45,18 +55,26 @@ class SignInBloc extends Bloc { SignInState stateFromCode(FlowyError error) { switch (ErrorCode.valueOf(error.code)!) { case ErrorCode.EmailFormatInvalid: - return state.copyWith(isSubmitting: false, emailError: some(error.msg), passwordError: none()); + return state.copyWith( + isSubmitting: false, + emailError: some(error.msg), + passwordError: none()); case ErrorCode.PasswordFormatInvalid: - return state.copyWith(isSubmitting: false, passwordError: some(error.msg), emailError: none()); + return state.copyWith( + isSubmitting: false, + passwordError: some(error.msg), + emailError: none()); default: - return state.copyWith(isSubmitting: false, successOrFail: some(right(error))); + return state.copyWith( + isSubmitting: false, successOrFail: some(right(error))); } } } @freezed class SignInEvent with _$SignInEvent { - const factory SignInEvent.signedInWithUserEmailAndPassword() = SignedInWithUserEmailAndPassword; + const factory SignInEvent.signedInWithUserEmailAndPassword() = + SignedInWithUserEmailAndPassword; const factory SignInEvent.emailChanged(String email) = EmailChanged; const factory SignInEvent.passwordChanged(String password) = PasswordChanged; } diff --git a/frontend/app_flowy/lib/user/application/sign_up_bloc.dart b/frontend/app_flowy/lib/user/application/sign_up_bloc.dart index 0c103fd4d7..6d1e62f364 100644 --- a/frontend/app_flowy/lib/user/application/sign_up_bloc.dart +++ b/frontend/app_flowy/lib/user/application/sign_up_bloc.dart @@ -1,7 +1,7 @@ import 'package:app_flowy/user/application/auth_service.dart'; import 'package:dartz/dartz.dart'; import 'package:easy_localization/easy_localization.dart'; -import 'package:flowy_sdk/protobuf/flowy-error-code/code.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/code.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-user/protobuf.dart' show UserProfilePB; import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -17,11 +17,18 @@ class SignUpBloc extends Bloc { await event.map(signUpWithUserEmailAndPassword: (e) async { await _performActionOnSignUp(emit); }, emailChanged: (_EmailChanged value) async { - emit(state.copyWith(email: value.email, emailError: none(), successOrFail: none())); + emit(state.copyWith( + email: value.email, emailError: none(), successOrFail: none())); }, passwordChanged: (_PasswordChanged value) async { - emit(state.copyWith(password: value.password, passwordError: none(), successOrFail: none())); + emit(state.copyWith( + password: value.password, + passwordError: none(), + successOrFail: none())); }, repeatPasswordChanged: (_RepeatPasswordChanged value) async { - emit(state.copyWith(repeatedPassword: value.password, repeatPasswordError: none(), successOrFail: none())); + emit(state.copyWith( + repeatedPassword: value.password, + repeatPasswordError: none(), + successOrFail: none())); }); }); } @@ -45,7 +52,8 @@ class SignUpBloc extends Bloc { if (repeatedPassword == null) { emit(state.copyWith( isSubmitting: false, - repeatPasswordError: some(LocaleKeys.signUp_repeatPasswordEmptyError.tr()), + repeatPasswordError: + some(LocaleKeys.signUp_repeatPasswordEmptyError.tr()), )); return; } @@ -53,7 +61,8 @@ class SignUpBloc extends Bloc { if (password != repeatedPassword) { emit(state.copyWith( isSubmitting: false, - repeatPasswordError: some(LocaleKeys.signUp_unmatchedPasswordError.tr()), + repeatPasswordError: + some(LocaleKeys.signUp_unmatchedPasswordError.tr()), )); return; } @@ -97,17 +106,20 @@ class SignUpBloc extends Bloc { successOrFail: none(), ); default: - return state.copyWith(isSubmitting: false, successOrFail: some(right(error))); + return state.copyWith( + isSubmitting: false, successOrFail: some(right(error))); } } } @freezed class SignUpEvent with _$SignUpEvent { - const factory SignUpEvent.signUpWithUserEmailAndPassword() = SignUpWithUserEmailAndPassword; + const factory SignUpEvent.signUpWithUserEmailAndPassword() = + SignUpWithUserEmailAndPassword; const factory SignUpEvent.emailChanged(String email) = _EmailChanged; const factory SignUpEvent.passwordChanged(String password) = _PasswordChanged; - const factory SignUpEvent.repeatPasswordChanged(String password) = _RepeatPasswordChanged; + const factory SignUpEvent.repeatPasswordChanged(String password) = + _RepeatPasswordChanged; } @freezed diff --git a/frontend/app_flowy/lib/user/application/user_listener.dart b/frontend/app_flowy/lib/user/application/user_listener.dart index 1fe0566400..d9a6c65d71 100644 --- a/frontend/app_flowy/lib/user/application/user_listener.dart +++ b/frontend/app_flowy/lib/user/application/user_listener.dart @@ -2,7 +2,7 @@ import 'dart:async'; import 'package:app_flowy/core/folder_notification.dart'; import 'package:app_flowy/core/user_notification.dart'; import 'package:dartz/dartz.dart'; -import 'package:flowy_sdk/protobuf/flowy-error-code/code.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/code.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-folder/workspace.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'dart:typed_data'; diff --git a/frontend/app_flowy/lib/user/presentation/splash_screen.dart b/frontend/app_flowy/lib/user/presentation/splash_screen.dart index 99f60105bc..360f91e7a8 100644 --- a/frontend/app_flowy/lib/user/presentation/splash_screen.dart +++ b/frontend/app_flowy/lib/user/presentation/splash_screen.dart @@ -1,6 +1,6 @@ import 'package:flowy_sdk/dispatch/dispatch.dart'; import 'package:flowy_sdk/log.dart'; -import 'package:flowy_sdk/protobuf/flowy-error-code/code.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/code.pb.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; diff --git a/frontend/app_flowy/lib/workspace/application/home/home_bloc.dart b/frontend/app_flowy/lib/workspace/application/home/home_bloc.dart index 221d1e6021..a01252cd1c 100644 --- a/frontend/app_flowy/lib/workspace/application/home/home_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/home/home_bloc.dart @@ -1,7 +1,7 @@ import 'package:app_flowy/user/application/user_listener.dart'; import 'package:flowy_infra/time/duration.dart'; import 'package:flowy_sdk/log.dart'; -import 'package:flowy_sdk/protobuf/flowy-error-code/code.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/code.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-folder/view.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-folder/workspace.pb.dart' diff --git a/frontend/rust-lib/Cargo.lock b/frontend/rust-lib/Cargo.lock index c8578a72f6..a34cda74b4 100644 --- a/frontend/rust-lib/Cargo.lock +++ b/frontend/rust-lib/Cargo.lock @@ -872,10 +872,13 @@ dependencies = [ "flowy-ast", "flowy-codegen", "lazy_static", + "log", "proc-macro2", "quote", "serde_json", "syn", + "tokio", + "trybuild", "walkdir", ] @@ -927,11 +930,11 @@ dependencies = [ name = "flowy-error" version = "0.1.0" dependencies = [ + "anyhow", "bytes", "flowy-codegen", "flowy-database", "flowy-derive", - "flowy-error-code", "flowy-sync", "http-flowy", "lib-dispatch", @@ -940,16 +943,7 @@ dependencies = [ "protobuf", "r2d2", "serde_json", -] - -[[package]] -name = "flowy-error-code" -version = "0.1.0" -dependencies = [ - "derive_more", - "flowy-codegen", - "flowy-derive", - "protobuf", + "thiserror", ] [[package]] @@ -1042,11 +1036,10 @@ name = "flowy-http-model" version = "0.1.0" dependencies = [ "bytes", - "flowy-codegen", - "flowy-derive", - "lib-infra", "md5", - "protobuf", + "serde", + "serde_json", + "serde_repr", ] [[package]] @@ -1441,6 +1434,12 @@ version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4" +[[package]] +name = "glob" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" + [[package]] name = "globset" version = "0.4.8" @@ -1470,7 +1469,6 @@ name = "grid-rev-model" version = "0.1.0" dependencies = [ "bytes", - "flowy-error-code", "indexmap", "nanoid", "serde", @@ -1855,8 +1853,6 @@ version = "0.1.0" dependencies = [ "bytes", "dashmap", - "flowy-codegen", - "flowy-derive", "futures", "futures-channel", "futures-core", @@ -1867,6 +1863,9 @@ dependencies = [ "paste", "pin-project", "protobuf", + "serde", + "serde_json", + "serde_repr", "strum", "strum_macros", "tokio", @@ -3521,6 +3520,21 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" +[[package]] +name = "trybuild" +version = "1.0.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7f408301c7480f9e6294eb779cfc907f54bd901a9660ef24d7f233ed5376485" +dependencies = [ + "glob", + "once_cell", + "serde", + "serde_derive", + "serde_json", + "termcolor", + "toml", +] + [[package]] name = "tungstenite" version = "0.14.0" diff --git a/frontend/rust-lib/Cargo.toml b/frontend/rust-lib/Cargo.toml index 5ff62a50c5..7030e1798d 100644 --- a/frontend/rust-lib/Cargo.toml +++ b/frontend/rust-lib/Cargo.toml @@ -16,6 +16,10 @@ members = [ "flowy-revision", "flowy-grid", "flowy-task", + "flowy-sync", + "flowy-derive", + "flowy-ast", + "flowy-codegen", ] [profile.dev] diff --git a/frontend/rust-lib/dart-ffi/Cargo.toml b/frontend/rust-lib/dart-ffi/Cargo.toml index 74b2c916fc..248ea3a36a 100644 --- a/frontend/rust-lib/dart-ffi/Cargo.toml +++ b/frontend/rust-lib/dart-ffi/Cargo.toml @@ -28,7 +28,7 @@ parking_lot = "0.12.1" lib-dispatch = { path = "../lib-dispatch" } flowy-sdk = { path = "../flowy-sdk" } dart-notify = { path = "../dart-notify" } -flowy-derive = { path = "../../../shared-lib/flowy-derive" } +flowy-derive = { path = "../flowy-derive" } [features] default = ["flowy-sdk/dart", "dart-notify/dart", "flutter"] @@ -37,7 +37,7 @@ http_sync = ["flowy-sdk/http_sync", "flowy-sdk/use_bunyan"] openssl_vendored = ["flowy-sdk/openssl_vendored"] [build-dependencies] -flowy-codegen= { path = "../../../shared-lib/flowy-codegen", features = [ +flowy-codegen = { path = "../flowy-codegen", features = [ "dart", ]} diff --git a/frontend/rust-lib/dart-notify/Cargo.toml b/frontend/rust-lib/dart-notify/Cargo.toml index c6f79a249d..88808d2f73 100644 --- a/frontend/rust-lib/dart-notify/Cargo.toml +++ b/frontend/rust-lib/dart-notify/Cargo.toml @@ -12,11 +12,11 @@ allo-isolate = {version = "^0.1", features = ["catch-unwind",]} log = "0.4.14" bytes = { version = "1.0" } -flowy-derive = {path = "../../../shared-lib/flowy-derive" } +flowy-derive = {path = "../flowy-derive" } lib-dispatch = {path = "../lib-dispatch" } [features] dart = ["flowy-codegen/dart"] [build-dependencies] -flowy-codegen= { path = "../../../shared-lib/flowy-codegen"} +flowy-codegen = { path = "../flowy-codegen"} diff --git a/shared-lib/flowy-ast/Cargo.toml b/frontend/rust-lib/flowy-ast/Cargo.toml similarity index 100% rename from shared-lib/flowy-ast/Cargo.toml rename to frontend/rust-lib/flowy-ast/Cargo.toml diff --git a/shared-lib/flowy-ast/src/ast.rs b/frontend/rust-lib/flowy-ast/src/ast.rs similarity index 100% rename from shared-lib/flowy-ast/src/ast.rs rename to frontend/rust-lib/flowy-ast/src/ast.rs diff --git a/shared-lib/flowy-ast/src/ctxt.rs b/frontend/rust-lib/flowy-ast/src/ctxt.rs similarity index 100% rename from shared-lib/flowy-ast/src/ctxt.rs rename to frontend/rust-lib/flowy-ast/src/ctxt.rs diff --git a/shared-lib/flowy-ast/src/event_attrs.rs b/frontend/rust-lib/flowy-ast/src/event_attrs.rs similarity index 100% rename from shared-lib/flowy-ast/src/event_attrs.rs rename to frontend/rust-lib/flowy-ast/src/event_attrs.rs diff --git a/shared-lib/flowy-ast/src/lib.rs b/frontend/rust-lib/flowy-ast/src/lib.rs similarity index 100% rename from shared-lib/flowy-ast/src/lib.rs rename to frontend/rust-lib/flowy-ast/src/lib.rs diff --git a/shared-lib/flowy-ast/src/node_attrs.rs b/frontend/rust-lib/flowy-ast/src/node_attrs.rs similarity index 100% rename from shared-lib/flowy-ast/src/node_attrs.rs rename to frontend/rust-lib/flowy-ast/src/node_attrs.rs diff --git a/shared-lib/flowy-ast/src/pb_attrs.rs b/frontend/rust-lib/flowy-ast/src/pb_attrs.rs similarity index 100% rename from shared-lib/flowy-ast/src/pb_attrs.rs rename to frontend/rust-lib/flowy-ast/src/pb_attrs.rs diff --git a/shared-lib/flowy-ast/src/symbol.rs b/frontend/rust-lib/flowy-ast/src/symbol.rs similarity index 100% rename from shared-lib/flowy-ast/src/symbol.rs rename to frontend/rust-lib/flowy-ast/src/symbol.rs diff --git a/shared-lib/flowy-ast/src/ty_ext.rs b/frontend/rust-lib/flowy-ast/src/ty_ext.rs similarity index 100% rename from shared-lib/flowy-ast/src/ty_ext.rs rename to frontend/rust-lib/flowy-ast/src/ty_ext.rs diff --git a/shared-lib/flowy-codegen/Cargo.toml b/frontend/rust-lib/flowy-codegen/Cargo.toml similarity index 100% rename from shared-lib/flowy-codegen/Cargo.toml rename to frontend/rust-lib/flowy-codegen/Cargo.toml diff --git a/shared-lib/flowy-codegen/src/dart_event/ast.rs b/frontend/rust-lib/flowy-codegen/src/dart_event/ast.rs similarity index 100% rename from shared-lib/flowy-codegen/src/dart_event/ast.rs rename to frontend/rust-lib/flowy-codegen/src/dart_event/ast.rs diff --git a/shared-lib/flowy-codegen/src/dart_event/dart_event.rs b/frontend/rust-lib/flowy-codegen/src/dart_event/dart_event.rs similarity index 100% rename from shared-lib/flowy-codegen/src/dart_event/dart_event.rs rename to frontend/rust-lib/flowy-codegen/src/dart_event/dart_event.rs diff --git a/shared-lib/flowy-codegen/src/dart_event/event_template.rs b/frontend/rust-lib/flowy-codegen/src/dart_event/event_template.rs similarity index 100% rename from shared-lib/flowy-codegen/src/dart_event/event_template.rs rename to frontend/rust-lib/flowy-codegen/src/dart_event/event_template.rs diff --git a/shared-lib/flowy-codegen/src/dart_event/event_template.tera b/frontend/rust-lib/flowy-codegen/src/dart_event/event_template.tera similarity index 100% rename from shared-lib/flowy-codegen/src/dart_event/event_template.tera rename to frontend/rust-lib/flowy-codegen/src/dart_event/event_template.tera diff --git a/shared-lib/flowy-codegen/src/dart_event/mod.rs b/frontend/rust-lib/flowy-codegen/src/dart_event/mod.rs similarity index 100% rename from shared-lib/flowy-codegen/src/dart_event/mod.rs rename to frontend/rust-lib/flowy-codegen/src/dart_event/mod.rs diff --git a/shared-lib/flowy-codegen/src/flowy_toml.rs b/frontend/rust-lib/flowy-codegen/src/flowy_toml.rs similarity index 100% rename from shared-lib/flowy-codegen/src/flowy_toml.rs rename to frontend/rust-lib/flowy-codegen/src/flowy_toml.rs diff --git a/shared-lib/flowy-codegen/src/lib.rs b/frontend/rust-lib/flowy-codegen/src/lib.rs similarity index 100% rename from shared-lib/flowy-codegen/src/lib.rs rename to frontend/rust-lib/flowy-codegen/src/lib.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/ast.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/ast.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/ast.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/ast.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/mod.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/mod.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/mod.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/mod.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/proto_gen.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/proto_gen.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/proto_gen.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/proto_gen.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/proto_info.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/proto_info.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/proto_info.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/proto_info.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/derive_meta/derive_meta.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/derive_meta/derive_meta.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/derive_meta/derive_meta.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/derive_meta/derive_meta.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/derive_meta/derive_meta.tera b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/derive_meta/derive_meta.tera similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/derive_meta/derive_meta.tera rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/derive_meta/derive_meta.tera diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/derive_meta/mod.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/derive_meta/mod.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/derive_meta/mod.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/derive_meta/mod.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/mod.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/mod.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/mod.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/mod.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/enum.tera b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/enum.tera similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/enum.tera rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/enum.tera diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/enum_template.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/enum_template.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/enum_template.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/enum_template.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/mod.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/mod.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/mod.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/mod.rs diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/struct.tera b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/struct.tera similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/struct.tera rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/struct.tera diff --git a/shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/struct_template.rs b/frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/struct_template.rs similarity index 100% rename from shared-lib/flowy-codegen/src/protobuf_file/template/proto_file/struct_template.rs rename to frontend/rust-lib/flowy-codegen/src/protobuf_file/template/proto_file/struct_template.rs diff --git a/shared-lib/flowy-codegen/src/util.rs b/frontend/rust-lib/flowy-codegen/src/util.rs similarity index 100% rename from shared-lib/flowy-codegen/src/util.rs rename to frontend/rust-lib/flowy-codegen/src/util.rs diff --git a/shared-lib/flowy-derive/.gitignore b/frontend/rust-lib/flowy-derive/.gitignore similarity index 100% rename from shared-lib/flowy-derive/.gitignore rename to frontend/rust-lib/flowy-derive/.gitignore diff --git a/shared-lib/flowy-derive/Cargo.toml b/frontend/rust-lib/flowy-derive/Cargo.toml similarity index 93% rename from shared-lib/flowy-derive/Cargo.toml rename to frontend/rust-lib/flowy-derive/Cargo.toml index 935ee663f5..6af5183bfd 100644 --- a/shared-lib/flowy-derive/Cargo.toml +++ b/frontend/rust-lib/flowy-derive/Cargo.toml @@ -20,7 +20,7 @@ proc-macro2 = "1.0" flowy-ast = { path = "../flowy-ast" } lazy_static = {version = "1.4.0"} dashmap = "5" -flowy-codegen= { path = "../flowy-codegen"} +flowy-codegen = { path = "../flowy-codegen"} serde_json = "1.0" walkdir = "2.3.1" diff --git a/shared-lib/flowy-derive/src/dart_event/mod.rs b/frontend/rust-lib/flowy-derive/src/dart_event/mod.rs similarity index 100% rename from shared-lib/flowy-derive/src/dart_event/mod.rs rename to frontend/rust-lib/flowy-derive/src/dart_event/mod.rs diff --git a/shared-lib/flowy-derive/src/lib.rs b/frontend/rust-lib/flowy-derive/src/lib.rs similarity index 100% rename from shared-lib/flowy-derive/src/lib.rs rename to frontend/rust-lib/flowy-derive/src/lib.rs diff --git a/shared-lib/flowy-derive/src/node/mod.rs b/frontend/rust-lib/flowy-derive/src/node/mod.rs similarity index 100% rename from shared-lib/flowy-derive/src/node/mod.rs rename to frontend/rust-lib/flowy-derive/src/node/mod.rs diff --git a/shared-lib/flowy-derive/src/proto_buf/deserialize.rs b/frontend/rust-lib/flowy-derive/src/proto_buf/deserialize.rs similarity index 100% rename from shared-lib/flowy-derive/src/proto_buf/deserialize.rs rename to frontend/rust-lib/flowy-derive/src/proto_buf/deserialize.rs diff --git a/shared-lib/flowy-derive/src/proto_buf/enum_serde.rs b/frontend/rust-lib/flowy-derive/src/proto_buf/enum_serde.rs similarity index 100% rename from shared-lib/flowy-derive/src/proto_buf/enum_serde.rs rename to frontend/rust-lib/flowy-derive/src/proto_buf/enum_serde.rs diff --git a/shared-lib/flowy-derive/src/proto_buf/mod.rs b/frontend/rust-lib/flowy-derive/src/proto_buf/mod.rs similarity index 100% rename from shared-lib/flowy-derive/src/proto_buf/mod.rs rename to frontend/rust-lib/flowy-derive/src/proto_buf/mod.rs diff --git a/shared-lib/flowy-derive/src/proto_buf/serialize.rs b/frontend/rust-lib/flowy-derive/src/proto_buf/serialize.rs similarity index 100% rename from shared-lib/flowy-derive/src/proto_buf/serialize.rs rename to frontend/rust-lib/flowy-derive/src/proto_buf/serialize.rs diff --git a/shared-lib/flowy-derive/src/proto_buf/util.rs b/frontend/rust-lib/flowy-derive/src/proto_buf/util.rs similarity index 100% rename from shared-lib/flowy-derive/src/proto_buf/util.rs rename to frontend/rust-lib/flowy-derive/src/proto_buf/util.rs diff --git a/shared-lib/flowy-derive/tests/progress.rs b/frontend/rust-lib/flowy-derive/tests/progress.rs similarity index 100% rename from shared-lib/flowy-derive/tests/progress.rs rename to frontend/rust-lib/flowy-derive/tests/progress.rs diff --git a/frontend/rust-lib/flowy-document/Cargo.toml b/frontend/rust-lib/flowy-document/Cargo.toml index ad7602f776..c70fb46d78 100644 --- a/frontend/rust-lib/flowy-document/Cargo.toml +++ b/frontend/rust-lib/flowy-document/Cargo.toml @@ -7,9 +7,9 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -flowy-sync = { path = "../../../shared-lib/flowy-sync"} +flowy-sync = { path = "../flowy-sync"} flowy-http-model = { path = "../../../shared-lib/flowy-http-model"} -flowy-derive = { path = "../../../shared-lib/flowy-derive" } +flowy-derive = { path = "../flowy-derive" } lib-ot = { path = "../../../shared-lib/lib-ot" } lib-ws = { path = "../../../shared-lib/lib-ws" } lib-infra = { path = "../../../shared-lib/lib-infra" } @@ -52,7 +52,7 @@ criterion = "0.3" rand = "0.8.5" [build-dependencies] -flowy-codegen= { path = "../../../shared-lib/flowy-codegen"} +flowy-codegen = { path = "../flowy-codegen"} [features] diff --git a/frontend/rust-lib/flowy-document/src/editor/queue.rs b/frontend/rust-lib/flowy-document/src/editor/queue.rs index c5704d8afe..95f8121517 100644 --- a/frontend/rust-lib/flowy-document/src/editor/queue.rs +++ b/frontend/rust-lib/flowy-document/src/editor/queue.rs @@ -3,7 +3,6 @@ use crate::DocumentUser; use async_stream::stream; use bytes::Bytes; use flowy_error::FlowyError; -use flowy_http_model::revision::RevId; use flowy_revision::RevisionManager; use futures::stream::StreamExt; use lib_ot::core::Transaction; @@ -76,10 +75,10 @@ impl DocumentQueue { } #[tracing::instrument(level = "trace", skip(self, transaction, md5), err)] - async fn save_local_operations(&self, transaction: Transaction, md5: String) -> Result { + async fn save_local_operations(&self, transaction: Transaction, md5: String) -> Result { let bytes = Bytes::from(transaction.to_bytes()?); let rev_id = self.rev_manager.add_local_revision(bytes, md5).await?; - Ok(rev_id.into()) + Ok(rev_id) } } diff --git a/frontend/rust-lib/flowy-document/src/lib.rs b/frontend/rust-lib/flowy-document/src/lib.rs index 39e46f538e..e0067bf083 100644 --- a/frontend/rust-lib/flowy-document/src/lib.rs +++ b/frontend/rust-lib/flowy-document/src/lib.rs @@ -16,13 +16,13 @@ pub mod errors { pub const TEXT_BLOCK_SYNC_INTERVAL_IN_MILLIS: u64 = 1000; use crate::errors::FlowyError; -use flowy_http_model::document::{CreateDocumentParams, DocumentIdPB, DocumentPayloadPB, ResetDocumentParams}; +use flowy_http_model::document::{CreateDocumentParams, DocumentId, DocumentPayload, ResetDocumentParams}; use lib_infra::future::FutureResult; pub trait DocumentCloudService: Send + Sync { fn create_document(&self, token: &str, params: CreateDocumentParams) -> FutureResult<(), FlowyError>; - fn fetch_document(&self, token: &str, params: DocumentIdPB) -> FutureResult, FlowyError>; + fn fetch_document(&self, token: &str, params: DocumentId) -> FutureResult, FlowyError>; fn update_document_content(&self, token: &str, params: ResetDocumentParams) -> FutureResult<(), FlowyError>; } diff --git a/frontend/rust-lib/flowy-document/src/manager.rs b/frontend/rust-lib/flowy-document/src/manager.rs index 38d633ece4..61df05342c 100644 --- a/frontend/rust-lib/flowy-document/src/manager.rs +++ b/frontend/rust-lib/flowy-document/src/manager.rs @@ -8,7 +8,8 @@ use bytes::Bytes; use flowy_database::ConnectionPool; use flowy_error::FlowyResult; use flowy_http_model::util::md5; -use flowy_http_model::{document::DocumentIdPB, revision::Revision, ws_data::ServerRevisionWSData}; +use flowy_http_model::ws_data::ServerRevisionWSData; +use flowy_http_model::{document::DocumentId, revision::Revision}; use flowy_revision::{ PhantomSnapshotPersistence, RevisionCloudService, RevisionManager, RevisionPersistence, RevisionPersistenceConfiguration, RevisionWebSocket, @@ -19,7 +20,8 @@ use lib_infra::future::FutureResult; use lib_infra::ref_map::{RefCountHashMap, RefCountValue}; use lib_ws::WSConnectState; use std::any::Any; -use std::{convert::TryInto, sync::Arc}; +use std::convert::TryFrom; +use std::sync::Arc; use tokio::sync::RwLock; pub trait DocumentUser: Send + Sync { @@ -150,10 +152,14 @@ impl DocumentManager { } pub async fn receive_ws_data(&self, data: Bytes) { - let result: Result = data.try_into(); + let result: Result = ServerRevisionWSData::try_from(data); match result { Ok(data) => match self.editor_map.read().await.get(&data.object_id) { - None => tracing::error!("Can't find any source handler for {:?}-{:?}", data.object_id, data.ty), + None => tracing::error!( + "Can't find any source handler for {:?}-{:?}", + data.object_id, + data.payload + ), Some(handler) => match handler.0.receive_ws_data(data).await { Ok(_) => {} Err(e) => tracing::error!("{}", e), @@ -294,7 +300,7 @@ struct DocumentRevisionCloudService { impl RevisionCloudService for DocumentRevisionCloudService { #[tracing::instrument(level = "trace", skip(self))] fn fetch_object(&self, user_id: &str, object_id: &str) -> FutureResult, FlowyError> { - let params: DocumentIdPB = object_id.to_string().into(); + let params: DocumentId = object_id.to_string().into(); let server = self.server.clone(); let token = self.token.clone(); diff --git a/frontend/rust-lib/flowy-document/src/old_editor/editor.rs b/frontend/rust-lib/flowy-document/src/old_editor/editor.rs index 5973cfd293..1a2cfe6ac5 100644 --- a/frontend/rust-lib/flowy-document/src/old_editor/editor.rs +++ b/frontend/rust-lib/flowy-document/src/old_editor/editor.rs @@ -5,7 +5,7 @@ use crate::{errors::FlowyError, DocumentEditor, DocumentUser}; use bytes::Bytes; use flowy_database::ConnectionPool; use flowy_error::{internal_error, FlowyResult}; -use flowy_http_model::document::DocumentPayloadPB; +use flowy_http_model::document::DocumentPayload; use flowy_http_model::revision::Revision; use flowy_http_model::ws_data::ServerRevisionWSData; use flowy_revision::{ @@ -246,14 +246,14 @@ impl DeltaDocumentEditor { pub struct DeltaDocumentRevisionSerde(); impl RevisionObjectDeserializer for DeltaDocumentRevisionSerde { - type Output = DocumentPayloadPB; + type Output = DocumentPayload; fn deserialize_revisions(object_id: &str, revisions: Vec) -> FlowyResult { let (base_rev_id, rev_id) = revisions.last().unwrap().pair_rev_id(); let mut delta = make_operations_from_revisions(revisions)?; correct_delta(&mut delta); - Result::::Ok(DocumentPayloadPB { + Result::::Ok(DocumentPayload { doc_id: object_id.to_owned(), data: delta.json_bytes().to_vec(), rev_id, diff --git a/frontend/rust-lib/flowy-document/src/old_editor/queue.rs b/frontend/rust-lib/flowy-document/src/old_editor/queue.rs index 16eede80df..4ba5f55b4f 100644 --- a/frontend/rust-lib/flowy-document/src/old_editor/queue.rs +++ b/frontend/rust-lib/flowy-document/src/old_editor/queue.rs @@ -3,7 +3,6 @@ use crate::DocumentUser; use async_stream::stream; use flowy_database::ConnectionPool; use flowy_error::FlowyError; -use flowy_http_model::revision::RevId; use flowy_revision::{RevisionMD5, RevisionManager, TransformOperations}; use flowy_sync::{ client_document::{history::UndoResult, ClientDocument}, @@ -176,10 +175,10 @@ impl EditDocumentQueue { Ok(()) } - async fn save_local_operations(&self, operations: DeltaTextOperations, md5: String) -> Result { + async fn save_local_operations(&self, operations: DeltaTextOperations, md5: String) -> Result { let bytes = operations.json_bytes(); let rev_id = self.rev_manager.add_local_revision(bytes, md5).await?; - Ok(rev_id.into()) + Ok(rev_id) } } diff --git a/frontend/rust-lib/flowy-document/src/old_editor/web_socket.rs b/frontend/rust-lib/flowy-document/src/old_editor/web_socket.rs index f10a8e64be..57c10789e7 100644 --- a/frontend/rust-lib/flowy-document/src/old_editor/web_socket.rs +++ b/frontend/rust-lib/flowy-document/src/old_editor/web_socket.rs @@ -3,10 +3,8 @@ use crate::TEXT_BLOCK_SYNC_INTERVAL_IN_MILLIS; use bytes::Bytes; use flowy_database::ConnectionPool; use flowy_error::{internal_error, FlowyError, FlowyResult}; -use flowy_http_model::{ - revision::{Revision, RevisionRange}, - ws_data::{ClientRevisionWSData, NewDocumentUser, ServerRevisionWSDataType}, -}; +use flowy_http_model::revision::{Revision, RevisionRange}; +use flowy_http_model::ws_data::{ClientRevisionWSData, NewDocumentUser}; use flowy_revision::*; use flowy_sync::errors::CollaborateResult; use flowy_sync::util::make_operations_from_revisions; @@ -96,14 +94,14 @@ impl DocumentRevisionWSDataStream { } impl RevisionWSDataStream for DocumentRevisionWSDataStream { - fn receive_push_revision(&self, bytes: Bytes) -> BoxResultFuture<(), FlowyError> { + fn receive_push_revision(&self, revisions: Vec) -> BoxResultFuture<(), FlowyError> { let resolver = self.conflict_controller.clone(); - Box::pin(async move { resolver.receive_bytes(bytes).await }) + Box::pin(async move { resolver.receive_revisions(revisions).await }) } - fn receive_ack(&self, id: String, ty: ServerRevisionWSDataType) -> BoxResultFuture<(), FlowyError> { + fn receive_ack(&self, rev_id: i64) -> BoxResultFuture<(), FlowyError> { let resolver = self.conflict_controller.clone(); - Box::pin(async move { resolver.ack_revision(id, ty).await }) + Box::pin(async move { resolver.ack_revision(rev_id).await }) } fn receive_new_user_connect(&self, _new_user: NewDocumentUser) -> BoxResultFuture<(), FlowyError> { diff --git a/frontend/rust-lib/flowy-document/src/services/persistence/rev_sqlite/document_rev_sqlite_v0.rs b/frontend/rust-lib/flowy-document/src/services/persistence/rev_sqlite/document_rev_sqlite_v0.rs index 2772e159b7..bab9a15417 100644 --- a/frontend/rust-lib/flowy-document/src/services/persistence/rev_sqlite/document_rev_sqlite_v0.rs +++ b/frontend/rust-lib/flowy-document/src/services/persistence/rev_sqlite/document_rev_sqlite_v0.rs @@ -126,7 +126,7 @@ impl DeltaRevisionSql { fn update(changeset: RevisionChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { let state: TextRevisionState = changeset.state.clone().into(); let filter = dsl::rev_table - .filter(dsl::rev_id.eq(changeset.rev_id.as_ref())) + .filter(dsl::rev_id.eq(changeset.rev_id)) .filter(dsl::doc_id.eq(changeset.object_id)); let _ = update(filter).set(dsl::state.eq(state)).execute(conn)?; tracing::debug!( diff --git a/frontend/rust-lib/flowy-document/src/services/persistence/rev_sqlite/document_rev_sqlite_v1.rs b/frontend/rust-lib/flowy-document/src/services/persistence/rev_sqlite/document_rev_sqlite_v1.rs index 3d491055eb..60856236b7 100644 --- a/frontend/rust-lib/flowy-document/src/services/persistence/rev_sqlite/document_rev_sqlite_v1.rs +++ b/frontend/rust-lib/flowy-document/src/services/persistence/rev_sqlite/document_rev_sqlite_v1.rs @@ -126,7 +126,7 @@ impl DocumentRevisionSql { fn update(changeset: RevisionChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { let state: DocumentRevisionState = changeset.state.clone().into(); let filter = dsl::document_rev_table - .filter(dsl::rev_id.eq(changeset.rev_id.as_ref())) + .filter(dsl::rev_id.eq(changeset.rev_id)) .filter(dsl::document_id.eq(changeset.object_id)); let _ = update(filter).set(dsl::state.eq(state)).execute(conn)?; tracing::debug!( diff --git a/frontend/rust-lib/flowy-error/Cargo.toml b/frontend/rust-lib/flowy-error/Cargo.toml index 6e230c39fb..316e7c5b3b 100644 --- a/frontend/rust-lib/flowy-error/Cargo.toml +++ b/frontend/rust-lib/flowy-error/Cargo.toml @@ -6,8 +6,7 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -flowy-derive = { path = "../../../shared-lib/flowy-derive" } -flowy-error-code = { path = "../../../shared-lib/flowy-error-code"} +flowy-derive = { path = "../flowy-derive" } lib-dispatch = { path = "../lib-dispatch" } protobuf = {version = "2.20.0"} bytes = "1.0" @@ -15,7 +14,7 @@ anyhow = "1.0" thiserror = "1.0" -flowy-sync = { path = "../../../shared-lib/flowy-sync", optional = true} +flowy-sync = { path = "../flowy-sync", optional = true} lib-ot = { path = "../../../shared-lib/lib-ot", optional = true} serde_json = {version = "1.0", optional = true} http-flowy = { git = "https://github.com/AppFlowy-IO/AppFlowy-Server", optional = true} @@ -29,7 +28,7 @@ ot = ["lib-ot"] serde = ["serde_json"] http_server = ["http-flowy"] db = ["flowy-database", "lib-sqlite", "r2d2"] -dart = ["flowy-error-code/dart", "flowy-codegen/dart"] +dart = ["flowy-codegen/dart"] [build-dependencies] -flowy-codegen= { path = "../../../shared-lib/flowy-codegen"} +flowy-codegen = { path = "../flowy-codegen"} diff --git a/frontend/rust-lib/flowy-error/Flowy.toml b/frontend/rust-lib/flowy-error/Flowy.toml index 8794b0b7d5..e7133a75a9 100644 --- a/frontend/rust-lib/flowy-error/Flowy.toml +++ b/frontend/rust-lib/flowy-error/Flowy.toml @@ -1,3 +1,3 @@ # Check out the FlowyConfig (located in flowy_toml.rs) for more details. -proto_input = ["src/errors.rs",] +proto_input = ["src/errors.rs","src/code.rs"] diff --git a/shared-lib/flowy-error-code/src/code.rs b/frontend/rust-lib/flowy-error/src/code.rs similarity index 56% rename from shared-lib/flowy-error-code/src/code.rs rename to frontend/rust-lib/flowy-error/src/code.rs index aeaeffb75c..b66675a6ab 100644 --- a/shared-lib/flowy-error-code/src/code.rs +++ b/frontend/rust-lib/flowy-error/src/code.rs @@ -1,155 +1,166 @@ -use crate::protobuf::ErrorCode as ProtoBufErrorCode; use flowy_derive::ProtoBuf_Enum; -use protobuf::ProtobufEnum; -use std::convert::{TryFrom, TryInto}; use thiserror::Error; -#[derive(Debug, Clone, ProtoBuf_Enum, PartialEq, Eq, Error)] +#[derive(Debug, Clone, PartialEq, Eq, Error, ProtoBuf_Enum)] pub enum ErrorCode { #[error("Internal error")] Internal = 0, - #[error("UserUnauthorized")] + #[error("Unauthorized user")] UserUnauthorized = 2, - #[error("RecordNotFound")] + #[error("Record not found")] RecordNotFound = 3, #[error("User id is empty")] UserIdIsEmpty = 4, #[error("Workspace name can not be empty or whitespace")] - WorkspaceNameInvalid = 100, + WorkspaceNameInvalid = 5, #[error("Workspace id can not be empty or whitespace")] - WorkspaceIdInvalid = 101, + WorkspaceIdInvalid = 6, #[error("Color style of the App is invalid")] - AppColorStyleInvalid = 102, + AppColorStyleInvalid = 7, #[error("Workspace desc is invalid")] - WorkspaceDescTooLong = 103, + WorkspaceDescTooLong = 8, #[error("Workspace description too long")] - WorkspaceNameTooLong = 104, + WorkspaceNameTooLong = 9, #[error("App id can not be empty or whitespace")] - AppIdInvalid = 110, + AppIdInvalid = 10, #[error("App name can not be empty or whitespace")] - AppNameInvalid = 111, + AppNameInvalid = 11, #[error("View name can not be empty or whitespace")] - ViewNameInvalid = 120, + ViewNameInvalid = 12, #[error("Thumbnail of the view is invalid")] - ViewThumbnailInvalid = 121, + ViewThumbnailInvalid = 13, #[error("View id can not be empty or whitespace")] - ViewIdInvalid = 122, + ViewIdInvalid = 14, #[error("View desc too long")] - ViewDescTooLong = 123, + ViewDescTooLong = 15, #[error("View data is invalid")] - ViewDataInvalid = 124, + ViewDataInvalid = 16, #[error("View name too long")] - ViewNameTooLong = 125, + ViewNameTooLong = 17, - #[error("Connection error")] - ConnectError = 200, + #[error("Http server connection error")] + HttpServerConnectError = 18, #[error("Email can not be empty or whitespace")] - EmailIsEmpty = 300, + EmailIsEmpty = 19, + #[error("Email format is not valid")] - EmailFormatInvalid = 301, + EmailFormatInvalid = 20, + #[error("Email already exists")] - EmailAlreadyExists = 302, + EmailAlreadyExists = 21, + #[error("Password can not be empty or whitespace")] - PasswordIsEmpty = 303, + PasswordIsEmpty = 22, + #[error("Password format too long")] - PasswordTooLong = 304, + PasswordTooLong = 23, + #[error("Password contains forbidden characters.")] - PasswordContainsForbidCharacters = 305, + PasswordContainsForbidCharacters = 24, + #[error("Password should contain a minimum of 6 characters with 1 special 1 letter and 1 numeric")] - PasswordFormatInvalid = 306, + PasswordFormatInvalid = 25, + #[error("Password not match")] - PasswordNotMatch = 307, + PasswordNotMatch = 26, + #[error("User name is too long")] - UserNameTooLong = 308, + UserNameTooLong = 27, + #[error("User name contain forbidden characters")] - UserNameContainForbiddenCharacters = 309, + UserNameContainForbiddenCharacters = 28, + #[error("User name can not be empty or whitespace")] - UserNameIsEmpty = 310, + UserNameIsEmpty = 29, + #[error("user id is empty or whitespace")] - UserIdInvalid = 311, + UserIdInvalid = 30, #[error("User not exist")] - UserNotExist = 312, + UserNotExist = 31, + #[error("Text is too long")] - TextTooLong = 400, + TextTooLong = 32, #[error("Grid id is empty")] - GridIdIsEmpty = 410, + GridIdIsEmpty = 33, + #[error("Grid view id is empty")] - GridViewIdIsEmpty = 411, + GridViewIdIsEmpty = 34, #[error("Grid block id is empty")] - BlockIdIsEmpty = 420, + BlockIdIsEmpty = 35, + #[error("Row id is empty")] - RowIdIsEmpty = 430, + RowIdIsEmpty = 36, + #[error("Select option id is empty")] - OptionIdIsEmpty = 431, + OptionIdIsEmpty = 37, + #[error("Field id is empty")] - FieldIdIsEmpty = 440, + FieldIdIsEmpty = 38, + #[error("Field doesn't exist")] - FieldDoesNotExist = 441, + FieldDoesNotExist = 39, + #[error("The name of the option should not be empty")] - SelectOptionNameIsEmpty = 442, + SelectOptionNameIsEmpty = 40, + #[error("Field not exists")] - FieldNotExists = 443, + FieldNotExists = 41, + #[error("The operation in this field is invalid")] - FieldInvalidOperation = 444, + FieldInvalidOperation = 42, + #[error("Filter id is empty")] - FilterIdIsEmpty = 445, + FilterIdIsEmpty = 43, + #[error("Field is not exist")] - FieldRecordNotFound = 446, + FieldRecordNotFound = 44, #[error("Field's type-option data should not be empty")] - TypeOptionDataIsEmpty = 450, + TypeOptionDataIsEmpty = 45, #[error("Group id is empty")] - GroupIdIsEmpty = 460, + GroupIdIsEmpty = 46, #[error("Invalid date time format")] - InvalidDateTimeFormat = 500, + InvalidDateTimeFormat = 47, #[error("The input string is empty or contains invalid characters")] - UnexpectedEmptyString = 999, + UnexpectedEmptyString = 48, #[error("Invalid data")] - InvalidData = 1000, + InvalidData = 49, #[error("Serde")] - Serde = 1001, + Serde = 50, #[error("Protobuf serde")] - ProtobufSerde = 1002, + ProtobufSerde = 51, #[error("Out of bounds")] - OutOfBounds = 10001, + OutOfBounds = 52, } impl ErrorCode { pub fn value(&self) -> i32 { - let code: ProtoBufErrorCode = self.clone().try_into().unwrap(); - code.value() - } - - pub fn from_i32(value: i32) -> Self { - match ProtoBufErrorCode::from_i32(value) { - None => ErrorCode::Internal, - Some(code) => ErrorCode::try_from(&code).unwrap(), - } + self.clone() as i32 } } diff --git a/frontend/rust-lib/flowy-error/src/errors.rs b/frontend/rust-lib/flowy-error/src/errors.rs index f4a2876cc8..fe1a3d4a25 100644 --- a/frontend/rust-lib/flowy-error/src/errors.rs +++ b/frontend/rust-lib/flowy-error/src/errors.rs @@ -1,7 +1,7 @@ +use crate::ErrorCode; use anyhow::Result; use bytes::Bytes; use flowy_derive::ProtoBuf; -use flowy_error_code::ErrorCode; use lib_dispatch::prelude::{AFPluginEventResponse, ResponseBuilder}; use std::{convert::TryInto, fmt::Debug}; use thiserror::Error; @@ -30,7 +30,7 @@ macro_rules! static_flowy_error { impl FlowyError { pub fn new(code: ErrorCode, msg: &str) -> Self { Self { - code: code.value(), + code: code.value() as i32, msg: msg.to_owned(), } } @@ -53,7 +53,7 @@ impl FlowyError { static_flowy_error!(view_desc, ErrorCode::ViewDescTooLong); static_flowy_error!(view_data, ErrorCode::ViewDataInvalid); static_flowy_error!(unauthorized, ErrorCode::UserUnauthorized); - static_flowy_error!(connection, ErrorCode::ConnectError); + static_flowy_error!(connection, ErrorCode::HttpServerConnectError); static_flowy_error!(email_empty, ErrorCode::EmailIsEmpty); static_flowy_error!(email_format, ErrorCode::EmailFormatInvalid); static_flowy_error!(email_exist, ErrorCode::EmailAlreadyExists); @@ -77,7 +77,7 @@ impl FlowyError { impl std::convert::From for FlowyError { fn from(code: ErrorCode) -> Self { FlowyError { - code: code.value(), + code: code.value() as i32, msg: format!("{}", code), } } diff --git a/frontend/rust-lib/flowy-error/src/ext/http_server.rs b/frontend/rust-lib/flowy-error/src/ext/http_server.rs index 25154d0072..be791d4af5 100644 --- a/frontend/rust-lib/flowy-error/src/ext/http_server.rs +++ b/frontend/rust-lib/flowy-error/src/ext/http_server.rs @@ -1,5 +1,4 @@ -use crate::FlowyError; -use flowy_error_code::ErrorCode; +use crate::{ErrorCode, FlowyError}; use http_flowy::errors::{ErrorCode as ServerErrorCode, ServerError}; impl std::convert::From for FlowyError { @@ -15,7 +14,7 @@ fn server_error_to_flowy_error(code: ServerErrorCode) -> ErrorCode { ServerErrorCode::PasswordNotMatch => ErrorCode::PasswordNotMatch, ServerErrorCode::RecordNotFound => ErrorCode::RecordNotFound, ServerErrorCode::ConnectRefused | ServerErrorCode::ConnectTimeout | ServerErrorCode::ConnectClose => { - ErrorCode::ConnectError + ErrorCode::HttpServerConnectError } _ => ErrorCode::Internal, } diff --git a/frontend/rust-lib/flowy-error/src/lib.rs b/frontend/rust-lib/flowy-error/src/lib.rs index a72422d1fa..08dd533e09 100644 --- a/frontend/rust-lib/flowy-error/src/lib.rs +++ b/frontend/rust-lib/flowy-error/src/lib.rs @@ -1,6 +1,7 @@ +mod code; mod errors; mod ext; pub mod protobuf; +pub use code::*; pub use errors::*; -pub use flowy_error_code::ErrorCode; diff --git a/frontend/rust-lib/flowy-folder/Cargo.toml b/frontend/rust-lib/flowy-folder/Cargo.toml index ebd4ca4dd4..a360a39e1e 100644 --- a/frontend/rust-lib/flowy-folder/Cargo.toml +++ b/frontend/rust-lib/flowy-folder/Cargo.toml @@ -7,9 +7,9 @@ edition = "2018" [dependencies] folder-rev-model = { path = "../../../shared-lib/folder-rev-model" } -flowy-sync = { path = "../../../shared-lib/flowy-sync" } +flowy-sync = { path = "../flowy-sync"} flowy-http-model = { path = "../../../shared-lib/flowy-http-model" } -flowy-derive = { path = "../../../shared-lib/flowy-derive" } +flowy-derive = { path = "../flowy-derive" } lib-ot = { path = "../../../shared-lib/lib-ot" } lib-infra = { path = "../../../shared-lib/lib-infra" } @@ -35,14 +35,14 @@ serde = { version = "1.0", features = ["derive"] } tracing = { version = "0.1", features = ["log"] } bytes = { version = "1.0" } unicode-segmentation = "1.8" +serde_json = "1.0" [dev-dependencies] -serde_json = "1.0" flowy-folder = { path = "../flowy-folder", features = ["flowy_unit_test"]} flowy-test = { path = "../flowy-test" } [build-dependencies] -flowy-codegen= { path = "../../../shared-lib/flowy-codegen"} +flowy-codegen = { path = "../flowy-codegen"} [features] diff --git a/frontend/rust-lib/flowy-folder/src/manager.rs b/frontend/rust-lib/flowy-folder/src/manager.rs index 98becc21be..82b6311b0f 100644 --- a/frontend/rust-lib/flowy-folder/src/manager.rs +++ b/frontend/rust-lib/flowy-folder/src/manager.rs @@ -26,7 +26,8 @@ use crate::services::clear_current_workspace; use crate::services::persistence::rev_sqlite::SQLiteFolderRevisionPersistence; use flowy_http_model::ws_data::ServerRevisionWSData; use flowy_sync::client_folder::FolderPad; -use std::{collections::HashMap, convert::TryInto, fmt::Formatter, sync::Arc}; +use std::convert::TryFrom; +use std::{collections::HashMap, fmt::Formatter, sync::Arc}; use tokio::sync::RwLock as TokioRwLock; lazy_static! { static ref INIT_FOLDER_FLAG: TokioRwLock> = TokioRwLock::new(HashMap::new()); @@ -139,7 +140,7 @@ impl FolderManager { // } pub async fn did_receive_ws_data(&self, data: Bytes) { - let result: Result = data.try_into(); + let result = ServerRevisionWSData::try_from(data); match result { Ok(data) => match self.folder_editor.read().await.clone() { None => {} diff --git a/frontend/rust-lib/flowy-folder/src/services/persistence/rev_sqlite/folder_rev_sqlite.rs b/frontend/rust-lib/flowy-folder/src/services/persistence/rev_sqlite/folder_rev_sqlite.rs index 7c2437cd5e..6646a4696b 100644 --- a/frontend/rust-lib/flowy-folder/src/services/persistence/rev_sqlite/folder_rev_sqlite.rs +++ b/frontend/rust-lib/flowy-folder/src/services/persistence/rev_sqlite/folder_rev_sqlite.rs @@ -124,7 +124,7 @@ impl FolderRevisionSql { fn update(changeset: RevisionChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { let state: TextRevisionState = changeset.state.clone().into(); let filter = dsl::rev_table - .filter(dsl::rev_id.eq(changeset.rev_id.as_ref())) + .filter(dsl::rev_id.eq(changeset.rev_id)) .filter(dsl::doc_id.eq(changeset.object_id)); let _ = update(filter).set(dsl::state.eq(state)).execute(conn)?; tracing::debug!( diff --git a/frontend/rust-lib/flowy-folder/src/services/view/controller.rs b/frontend/rust-lib/flowy-folder/src/services/view/controller.rs index 93820c2123..44ef29feb7 100644 --- a/frontend/rust-lib/flowy-folder/src/services/view/controller.rs +++ b/frontend/rust-lib/flowy-folder/src/services/view/controller.rs @@ -16,7 +16,7 @@ use crate::{ }; use bytes::Bytes; use flowy_database::kv::KV; -use flowy_http_model::document::DocumentIdPB; +use flowy_http_model::document::DocumentId; use folder_rev_model::{gen_view_id, ViewRevision}; use futures::{FutureExt, StreamExt}; use std::{collections::HashSet, sync::Arc}; @@ -201,7 +201,7 @@ impl ViewController { } #[tracing::instrument(level = "debug", skip(self,params), fields(doc_id = %params.value), err)] - pub(crate) async fn move_view_to_trash(&self, params: DocumentIdPB) -> Result<(), FlowyError> { + pub(crate) async fn move_view_to_trash(&self, params: DocumentId) -> Result<(), FlowyError> { let view_id = params.value; if let Some(latest_view_id) = KV::get_str(LATEST_VIEW_ID) { if latest_view_id == view_id { diff --git a/frontend/rust-lib/flowy-folder/src/services/web_socket.rs b/frontend/rust-lib/flowy-folder/src/services/web_socket.rs index 6406e80e9f..6eb168d732 100644 --- a/frontend/rust-lib/flowy-folder/src/services/web_socket.rs +++ b/frontend/rust-lib/flowy-folder/src/services/web_socket.rs @@ -3,7 +3,7 @@ use bytes::Bytes; use flowy_database::ConnectionPool; use flowy_error::{FlowyError, FlowyResult}; use flowy_http_model::revision::{Revision, RevisionRange}; -use flowy_http_model::ws_data::{ClientRevisionWSData, NewDocumentUser, ServerRevisionWSDataType}; +use flowy_http_model::ws_data::{ClientRevisionWSData, NewDocumentUser}; use flowy_revision::*; use flowy_sync::client_folder::FolderPad; use flowy_sync::server_folder::FolderOperations; @@ -130,14 +130,14 @@ impl FolderRevisionWSDataStream { } impl RevisionWSDataStream for FolderRevisionWSDataStream { - fn receive_push_revision(&self, bytes: Bytes) -> BoxResultFuture<(), FlowyError> { + fn receive_push_revision(&self, revisions: Vec) -> BoxResultFuture<(), FlowyError> { let resolver = self.conflict_controller.clone(); - Box::pin(async move { resolver.receive_bytes(bytes).await }) + Box::pin(async move { resolver.receive_revisions(revisions).await }) } - fn receive_ack(&self, id: String, ty: ServerRevisionWSDataType) -> BoxResultFuture<(), FlowyError> { + fn receive_ack(&self, rev_id: i64) -> BoxResultFuture<(), FlowyError> { let resolver = self.conflict_controller.clone(); - Box::pin(async move { resolver.ack_revision(id, ty).await }) + Box::pin(async move { resolver.ack_revision(rev_id).await }) } fn receive_new_user_connect(&self, _new_user: NewDocumentUser) -> BoxResultFuture<(), FlowyError> { diff --git a/frontend/rust-lib/flowy-folder/tests/workspace/script.rs b/frontend/rust-lib/flowy-folder/tests/workspace/script.rs index 26fc2829a6..67ac4affa3 100644 --- a/frontend/rust-lib/flowy-folder/tests/workspace/script.rs +++ b/frontend/rust-lib/flowy-folder/tests/workspace/script.rs @@ -15,8 +15,6 @@ use flowy_folder::entities::{ }; use flowy_folder::event_map::FolderEvent::*; use flowy_folder::{errors::ErrorCode, services::folder_editor::FolderEditor}; - -use flowy_http_model::document::DocumentPayloadPB; use flowy_revision::disk::RevisionState; use flowy_revision::REVISION_WRITE_INTERVAL_IN_MILLIS; use flowy_test::{event_builder::*, FlowySDKTest}; @@ -413,17 +411,6 @@ pub async fn delete_view(sdk: &FlowySDKTest, view_ids: Vec) { .await; } -#[allow(dead_code)] -pub async fn set_latest_view(sdk: &FlowySDKTest, view_id: &str) -> DocumentPayloadPB { - let view_id: ViewIdPB = view_id.into(); - FolderEventBuilder::new(sdk.clone()) - .event(SetLatestView) - .payload(view_id) - .async_send() - .await - .parse::() -} - pub async fn read_trash(sdk: &FlowySDKTest) -> RepeatedTrashPB { FolderEventBuilder::new(sdk.clone()) .event(ReadTrash) diff --git a/frontend/rust-lib/flowy-grid/Cargo.toml b/frontend/rust-lib/flowy-grid/Cargo.toml index 50bd00cf22..93af0bbd37 100644 --- a/frontend/rust-lib/flowy-grid/Cargo.toml +++ b/frontend/rust-lib/flowy-grid/Cargo.toml @@ -11,11 +11,11 @@ dart-notify = { path = "../dart-notify" } flowy-revision = { path = "../flowy-revision" } flowy-task= { path = "../flowy-task" } flowy-error = { path = "../flowy-error", features = ["db"]} -flowy-derive = { path = "../../../shared-lib/flowy-derive" } +flowy-derive = { path = "../flowy-derive" } lib-ot = { path = "../../../shared-lib/lib-ot" } lib-infra = { path = "../../../shared-lib/lib-infra" } grid-rev-model = { path = "../../../shared-lib/grid-rev-model" } -flowy-sync = { path = "../../../shared-lib/flowy-sync" } +flowy-sync = { path = "../flowy-sync"} flowy-http-model = { path = "../../../shared-lib/flowy-http-model" } flowy-database = { path = "../flowy-database" } anyhow = "1.0" @@ -52,9 +52,7 @@ flowy-test = { path = "../flowy-test" } flowy-grid = { path = "../flowy-grid", features = ["flowy_unit_test"]} [build-dependencies] -flowy-codegen= { path = "../../../shared-lib/flowy-codegen"} - - +flowy-codegen = { path = "../flowy-codegen"} [features] default = [] diff --git a/frontend/rust-lib/flowy-grid/src/services/field/type_options/selection_type_option/select_type_option.rs b/frontend/rust-lib/flowy-grid/src/services/field/type_options/selection_type_option/select_type_option.rs index 69ec27055c..f1f1602fc7 100644 --- a/frontend/rust-lib/flowy-grid/src/services/field/type_options/selection_type_option/select_type_option.rs +++ b/frontend/rust-lib/flowy-grid/src/services/field/type_options/selection_type_option/select_type_option.rs @@ -7,8 +7,8 @@ use crate::services::cell::{ use crate::services::field::selection_type_option::type_option_transform::SelectOptionTypeOptionTransformHelper; use crate::services::field::{ - CheckboxCellData, ChecklistTypeOptionPB, MultiSelectTypeOptionPB, SingleSelectTypeOptionPB, StrCellData, - TypeOption, TypeOptionCellData, TypeOptionTransform, + CheckboxCellData, ChecklistTypeOptionPB, MultiSelectTypeOptionPB, SingleSelectTypeOptionPB, TypeOption, + TypeOptionCellData, TypeOptionTransform, }; use bytes::Bytes; use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; diff --git a/frontend/rust-lib/flowy-grid/src/services/field/type_options/text_type_option/text_tests.rs b/frontend/rust-lib/flowy-grid/src/services/field/type_options/text_type_option/text_tests.rs index aa73f8c6f7..898c40465f 100644 --- a/frontend/rust-lib/flowy-grid/src/services/field/type_options/text_type_option/text_tests.rs +++ b/frontend/rust-lib/flowy-grid/src/services/field/type_options/text_type_option/text_tests.rs @@ -2,7 +2,7 @@ mod tests { use crate::entities::FieldType; use crate::services::cell::stringify_cell_data; - use crate::services::cell::CellDataDecoder; + use crate::services::field::FieldBuilder; use crate::services::field::*; diff --git a/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_block_sqlite_impl.rs b/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_block_sqlite_impl.rs index 9808973c10..eb8354b84e 100644 --- a/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_block_sqlite_impl.rs +++ b/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_block_sqlite_impl.rs @@ -124,7 +124,7 @@ impl GridMetaRevisionSql { fn update(changeset: RevisionChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { let state: GridBlockRevisionState = changeset.state.clone().into(); let filter = dsl::grid_meta_rev_table - .filter(dsl::rev_id.eq(changeset.rev_id.as_ref())) + .filter(dsl::rev_id.eq(changeset.rev_id)) .filter(dsl::object_id.eq(changeset.object_id)); let _ = update(filter).set(dsl::state.eq(state)).execute(conn)?; tracing::debug!( diff --git a/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_sqlite_impl.rs b/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_sqlite_impl.rs index ddecdd04df..61667860b4 100644 --- a/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_sqlite_impl.rs +++ b/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_sqlite_impl.rs @@ -123,7 +123,7 @@ impl GridRevisionSql { fn update(changeset: RevisionChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { let state: GridRevisionState = changeset.state.clone().into(); let filter = dsl::grid_rev_table - .filter(dsl::rev_id.eq(changeset.rev_id.as_ref())) + .filter(dsl::rev_id.eq(changeset.rev_id)) .filter(dsl::object_id.eq(changeset.object_id)); let _ = update(filter).set(dsl::state.eq(state)).execute(conn)?; tracing::debug!( diff --git a/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_view_sqlite_impl.rs b/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_view_sqlite_impl.rs index bb2fae0634..e45f95ed03 100644 --- a/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_view_sqlite_impl.rs +++ b/frontend/rust-lib/flowy-grid/src/services/persistence/rev_sqlite/grid_view_sqlite_impl.rs @@ -123,7 +123,7 @@ impl GridViewRevisionSql { fn update(changeset: RevisionChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { let state: GridViewRevisionState = changeset.state.clone().into(); let filter = dsl::grid_view_rev_table - .filter(dsl::rev_id.eq(changeset.rev_id.as_ref())) + .filter(dsl::rev_id.eq(changeset.rev_id)) .filter(dsl::object_id.eq(changeset.object_id)); let _ = update(filter).set(dsl::state.eq(state)).execute(conn)?; tracing::debug!( diff --git a/frontend/rust-lib/flowy-net/Cargo.toml b/frontend/rust-lib/flowy-net/Cargo.toml index 78e6aee028..5805a57c26 100644 --- a/frontend/rust-lib/flowy-net/Cargo.toml +++ b/frontend/rust-lib/flowy-net/Cargo.toml @@ -8,8 +8,8 @@ edition = "2018" [dependencies] lib-dispatch = { path = "../lib-dispatch" } flowy-error = { path = "../flowy-error", features = ["collaboration", "http_server"] } -flowy-derive = { path = "../../../shared-lib/flowy-derive" } -flowy-sync = { path = "../../../shared-lib/flowy-sync"} +flowy-derive = { path = "../flowy-derive" } +flowy-sync = { path = "../flowy-sync"} flowy-http-model = { path = "../../../shared-lib/flowy-http-model"} folder-rev-model = { path = "../../../shared-lib/folder-rev-model"} flowy-folder = { path = "../flowy-folder" } @@ -48,4 +48,4 @@ dart = [ ] [build-dependencies] -flowy-codegen = { path = "../../../shared-lib/flowy-codegen"} +flowy-codegen = { path = "../flowy-codegen"} diff --git a/frontend/rust-lib/flowy-net/src/http_server/document.rs b/frontend/rust-lib/flowy-net/src/http_server/document.rs index d372145cb3..62d988dc12 100644 --- a/frontend/rust-lib/flowy-net/src/http_server/document.rs +++ b/frontend/rust-lib/flowy-net/src/http_server/document.rs @@ -4,7 +4,7 @@ use crate::{ }; use flowy_document::DocumentCloudService; use flowy_error::FlowyError; -use flowy_http_model::document::{CreateDocumentParams, DocumentIdPB, DocumentPayloadPB, ResetDocumentParams}; +use flowy_http_model::document::{CreateDocumentParams, DocumentId, DocumentPayload, ResetDocumentParams}; use http_flowy::response::FlowyResponse; use lazy_static::lazy_static; use lib_infra::future::FutureResult; @@ -27,7 +27,7 @@ impl DocumentCloudService for DocumentCloudServiceImpl { FutureResult::new(async move { create_document_request(&token, params, &url).await }) } - fn fetch_document(&self, token: &str, params: DocumentIdPB) -> FutureResult, FlowyError> { + fn fetch_document(&self, token: &str, params: DocumentId) -> FutureResult, FlowyError> { let token = token.to_owned(); let url = self.config.doc_url(); FutureResult::new(async move { read_document_request(&token, params, &url).await }) @@ -44,7 +44,7 @@ pub async fn create_document_request(token: &str, params: CreateDocumentParams, let _ = request_builder() .post(url) .header(HEADER_TOKEN, token) - .protobuf(params)? + .json(params)? .send() .await?; Ok(()) @@ -52,14 +52,14 @@ pub async fn create_document_request(token: &str, params: CreateDocumentParams, pub async fn read_document_request( token: &str, - params: DocumentIdPB, + params: DocumentId, url: &str, -) -> Result, FlowyError> { +) -> Result, FlowyError> { let doc = request_builder() .get(url) .header(HEADER_TOKEN, token) - .protobuf(params)? - .option_response() + .json(params)? + .option_json_response() .await?; Ok(doc) @@ -69,7 +69,7 @@ pub async fn reset_doc_request(token: &str, params: ResetDocumentParams, url: &s let _ = request_builder() .patch(url) .header(HEADER_TOKEN, token) - .protobuf(params)? + .json(params)? .send() .await?; Ok(()) diff --git a/frontend/rust-lib/flowy-net/src/local_server/persistence.rs b/frontend/rust-lib/flowy-net/src/local_server/persistence.rs index b4faa8d5b5..332d1bbce6 100644 --- a/frontend/rust-lib/flowy-net/src/local_server/persistence.rs +++ b/frontend/rust-lib/flowy-net/src/local_server/persistence.rs @@ -1,6 +1,6 @@ -use flowy_http_model::document::DocumentPayloadPB; +use flowy_http_model::document::DocumentPayload; use flowy_http_model::folder::FolderInfo; -use flowy_http_model::revision::{RepeatedRevision, Revision}; +use flowy_http_model::revision::Revision; use flowy_sync::{ errors::CollaborateError, server_document::*, @@ -16,18 +16,14 @@ use std::{ // For the moment, we use memory to cache the data, it will be implemented with // other storage. Like the Firestore,Dropbox.etc. pub trait RevisionCloudStorage: Send + Sync { - fn set_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError>; + fn set_revisions(&self, revisions: Vec) -> BoxResultFuture<(), CollaborateError>; fn get_revisions( &self, object_id: &str, rev_ids: Option>, - ) -> BoxResultFuture; + ) -> BoxResultFuture, CollaborateError>; - fn reset_object( - &self, - object_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture<(), CollaborateError>; + fn reset_object(&self, object_id: &str, revisions: Vec) -> BoxResultFuture<(), CollaborateError>; } pub(crate) struct LocalDocumentCloudPersistence { @@ -53,8 +49,8 @@ impl FolderCloudPersistence for LocalDocumentCloudPersistence { let storage = self.storage.clone(); let folder_id = folder_id.to_owned(); Box::pin(async move { - let repeated_revision = storage.get_revisions(&folder_id, None).await?; - match make_folder_from_revisions_pb(&folder_id, repeated_revision)? { + let revisions = storage.get_revisions(&folder_id, None).await?; + match make_folder_from_revisions_pb(&folder_id, revisions)? { Some(folder_info) => Ok(folder_info), None => Err(CollaborateError::record_not_found()), } @@ -65,20 +61,20 @@ impl FolderCloudPersistence for LocalDocumentCloudPersistence { &self, _user_id: &str, folder_id: &str, - repeated_revision: RepeatedRevision, + revisions: Vec, ) -> BoxResultFuture, CollaborateError> { let folder_id = folder_id.to_owned(); let storage = self.storage.clone(); Box::pin(async move { - let _ = storage.set_revisions(repeated_revision.clone()).await?; - make_folder_from_revisions_pb(&folder_id, repeated_revision) + let _ = storage.set_revisions(revisions.clone()).await?; + make_folder_from_revisions_pb(&folder_id, revisions) }) } - fn save_folder_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError> { + fn save_folder_revisions(&self, revisions: Vec) -> BoxResultFuture<(), CollaborateError> { let storage = self.storage.clone(); Box::pin(async move { - let _ = storage.set_revisions(repeated_revision).await?; + let _ = storage.set_revisions(revisions).await?; Ok(()) }) } @@ -90,28 +86,21 @@ impl FolderCloudPersistence for LocalDocumentCloudPersistence { ) -> BoxResultFuture, CollaborateError> { let folder_id = folder_id.to_owned(); let storage = self.storage.clone(); - Box::pin(async move { - let repeated_revision = storage.get_revisions(&folder_id, rev_ids).await?; - Ok(repeated_revision.into_inner()) - }) + Box::pin(async move { storage.get_revisions(&folder_id, rev_ids).await }) } - fn reset_folder( - &self, - folder_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture<(), CollaborateError> { + fn reset_folder(&self, folder_id: &str, revisions: Vec) -> BoxResultFuture<(), CollaborateError> { let storage = self.storage.clone(); let folder_id = folder_id.to_owned(); Box::pin(async move { - let _ = storage.reset_object(&folder_id, repeated_revision).await?; + let _ = storage.reset_object(&folder_id, revisions).await?; Ok(()) }) } } impl DocumentCloudPersistence for LocalDocumentCloudPersistence { - fn read_document(&self, doc_id: &str) -> BoxResultFuture { + fn read_document(&self, doc_id: &str) -> BoxResultFuture { let storage = self.storage.clone(); let doc_id = doc_id.to_owned(); Box::pin(async move { @@ -126,13 +115,13 @@ impl DocumentCloudPersistence for LocalDocumentCloudPersistence { fn create_document( &self, doc_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture, CollaborateError> { + revisions: Vec, + ) -> BoxResultFuture, CollaborateError> { let doc_id = doc_id.to_owned(); let storage = self.storage.clone(); Box::pin(async move { - let _ = storage.set_revisions(repeated_revision.clone()).await?; - make_document_from_revision_pbs(&doc_id, repeated_revision) + let _ = storage.set_revisions(revisions.clone()).await?; + make_document_from_revision_pbs(&doc_id, revisions) }) } @@ -143,21 +132,18 @@ impl DocumentCloudPersistence for LocalDocumentCloudPersistence { ) -> BoxResultFuture, CollaborateError> { let doc_id = doc_id.to_owned(); let storage = self.storage.clone(); - Box::pin(async move { - let repeated_revision = storage.get_revisions(&doc_id, rev_ids).await?; - Ok(repeated_revision.into_inner()) - }) + Box::pin(async move { storage.get_revisions(&doc_id, rev_ids).await }) } - fn save_document_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError> { + fn save_document_revisions(&self, revisions: Vec) -> BoxResultFuture<(), CollaborateError> { let storage = self.storage.clone(); Box::pin(async move { - let _ = storage.set_revisions(repeated_revision).await?; + let _ = storage.set_revisions(revisions).await?; Ok(()) }) } - fn reset_document(&self, doc_id: &str, revisions: RepeatedRevision) -> BoxResultFuture<(), CollaborateError> { + fn reset_document(&self, doc_id: &str, revisions: Vec) -> BoxResultFuture<(), CollaborateError> { let storage = self.storage.clone(); let doc_id = doc_id.to_owned(); Box::pin(async move { @@ -170,26 +156,19 @@ impl DocumentCloudPersistence for LocalDocumentCloudPersistence { #[derive(Default)] struct MemoryDocumentCloudStorage {} impl RevisionCloudStorage for MemoryDocumentCloudStorage { - fn set_revisions(&self, _repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError> { + fn set_revisions(&self, _revisions: Vec) -> BoxResultFuture<(), CollaborateError> { Box::pin(async move { Ok(()) }) } fn get_revisions( &self, - _doc_id: &str, + _object_id: &str, _rev_ids: Option>, - ) -> BoxResultFuture { - Box::pin(async move { - let repeated_revisions = RepeatedRevision::default(); - Ok(repeated_revisions) - }) + ) -> BoxResultFuture, CollaborateError> { + Box::pin(async move { Ok(vec![]) }) } - fn reset_object( - &self, - _doc_id: &str, - _repeated_revision: RepeatedRevision, - ) -> BoxResultFuture<(), CollaborateError> { + fn reset_object(&self, _object_id: &str, _revisions: Vec) -> 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 index b687452bf7..c1658386c3 100644 --- a/frontend/rust-lib/flowy-net/src/local_server/server.rs +++ b/frontend/rust-lib/flowy-net/src/local_server/server.rs @@ -131,7 +131,7 @@ impl LocalWebSocketRunner { tracing::trace!( "[LocalFolderServer] receive: {}:{}-{:?} ", client_data.object_id, - client_data.id(), + client_data.rev_id, client_data.ty, ); let client_ws_sender = self.client_ws_sender.clone(); @@ -141,19 +141,12 @@ impl LocalWebSocketRunner { channel: WSChannel::Folder, }); let ty = client_data.ty.clone(); - let document_client_data: ClientRevisionWSDataPB = client_data.try_into().unwrap(); match ty { ClientRevisionWSDataType::ClientPushRev => { - let _ = self - .folder_manager - .handle_client_revisions(user, document_client_data) - .await?; + let _ = self.folder_manager.handle_client_revisions(user, client_data).await?; } ClientRevisionWSDataType::ClientPing => { - let _ = self - .folder_manager - .handle_client_ping(user, document_client_data) - .await?; + let _ = self.folder_manager.handle_client_ping(user, client_data).await?; } } Ok(()) @@ -167,7 +160,7 @@ impl LocalWebSocketRunner { tracing::trace!( "[LocalDocumentServer] receive: {}:{}-{:?} ", client_data.object_id, - client_data.id(), + client_data.rev_id, client_data.ty, ); let client_ws_sender = self.client_ws_sender.clone(); @@ -177,16 +170,12 @@ impl LocalWebSocketRunner { channel: WSChannel::Document, }); let ty = client_data.ty.clone(); - let document_client_data: ClientRevisionWSDataPB = client_data.try_into().unwrap(); match ty { ClientRevisionWSDataType::ClientPushRev => { - let _ = self - .doc_manager - .handle_client_revisions(user, document_client_data) - .await?; + let _ = self.doc_manager.handle_client_revisions(user, client_data).await?; } ClientRevisionWSDataType::ClientPing => { - let _ = self.doc_manager.handle_client_ping(user, document_client_data).await?; + let _ = self.doc_manager.handle_client_ping(user, client_data).await?; } } Ok(()) @@ -253,8 +242,7 @@ use flowy_folder::entities::{ view::{CreateViewParams, RepeatedViewIdPB, UpdateViewParams, ViewIdPB}, workspace::{CreateWorkspaceParams, UpdateWorkspaceParams, WorkspaceIdPB}, }; -use flowy_http_model::document::{CreateDocumentParams, DocumentIdPB, DocumentPayloadPB, ResetDocumentParams}; -use flowy_http_model::protobuf::ClientRevisionWSData as ClientRevisionWSDataPB; +use flowy_http_model::document::{CreateDocumentParams, DocumentId, DocumentPayload, ResetDocumentParams}; use flowy_http_model::ws_data::{ClientRevisionWSData, ClientRevisionWSDataType}; use flowy_user::entities::{ SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserProfileParams, UserProfilePB, @@ -414,11 +402,7 @@ impl DocumentCloudService for LocalServer { FutureResult::new(async { Ok(()) }) } - fn fetch_document( - &self, - _token: &str, - _params: DocumentIdPB, - ) -> FutureResult, FlowyError> { + fn fetch_document(&self, _token: &str, _params: DocumentId) -> FutureResult, FlowyError> { FutureResult::new(async { Ok(None) }) } diff --git a/frontend/rust-lib/flowy-net/src/request.rs b/frontend/rust-lib/flowy-net/src/request.rs index f65c19687f..8da4d78741 100644 --- a/frontend/rust-lib/flowy-net/src/request.rs +++ b/frontend/rust-lib/flowy-net/src/request.rs @@ -88,6 +88,14 @@ impl HttpRequestBuilder { self.bytes(body) } + pub fn json(self, body: T) -> Result + where + T: serde::Serialize, + { + let bytes = Bytes::from(serde_json::to_vec(&body)?); + self.bytes(bytes) + } + pub fn bytes(mut self, body: Bytes) -> Result { self.body = Some(body); Ok(self) @@ -109,7 +117,8 @@ impl HttpRequestBuilder { } } - pub async fn option_response(self) -> Result, ServerError> + #[allow(dead_code)] + pub async fn option_protobuf_response(self) -> Result, ServerError> where T: TryFrom, { @@ -126,6 +135,23 @@ impl HttpRequestBuilder { } } + pub async fn option_json_response(self) -> Result, ServerError> + where + T: serde::de::DeserializeOwned + 'static, + { + let result = self.inner_send().await; + match result { + Ok(builder) => match builder.response { + None => Err(unexpected_empty_payload(&builder.url)), + Some(data) => Ok(Some(serde_json::from_slice(&data)?)), + }, + Err(error) => match error.is_record_not_found() { + true => Ok(None), + false => Err(error), + }, + } + } + fn token(&self) -> Option { match self.headers.get(HEADER_TOKEN) { None => None, diff --git a/frontend/rust-lib/flowy-revision/src/cache/disk.rs b/frontend/rust-lib/flowy-revision/src/cache/disk.rs index b2982cda2a..f9cd7e0855 100644 --- a/frontend/rust-lib/flowy-revision/src/cache/disk.rs +++ b/frontend/rust-lib/flowy-revision/src/cache/disk.rs @@ -1,5 +1,5 @@ use flowy_error::{FlowyError, FlowyResult}; -use flowy_http_model::revision::{RevId, Revision, RevisionRange}; +use flowy_http_model::revision::{Revision, RevisionRange}; use std::fmt::Debug; use std::sync::Arc; @@ -106,7 +106,7 @@ impl SyncRecord { pub struct RevisionChangeset { pub object_id: String, - pub rev_id: RevId, + pub rev_id: i64, pub state: RevisionState, } diff --git a/frontend/rust-lib/flowy-revision/src/conflict_resolve.rs b/frontend/rust-lib/flowy-revision/src/conflict_resolve.rs index 794059b5f2..66d0311fca 100644 --- a/frontend/rust-lib/flowy-revision/src/conflict_resolve.rs +++ b/frontend/rust-lib/flowy-revision/src/conflict_resolve.rs @@ -1,12 +1,9 @@ use crate::{RevisionMD5, RevisionManager}; use bytes::Bytes; use flowy_error::{FlowyError, FlowyResult}; -use flowy_http_model::{ - revision::{RepeatedRevision, Revision, RevisionRange}, - ws_data::ServerRevisionWSDataType, -}; +use flowy_http_model::revision::{Revision, RevisionRange}; use lib_infra::future::BoxResultFuture; -use std::{convert::TryFrom, sync::Arc}; +use std::sync::Arc; pub struct TransformOperations { pub client_operations: Operations, @@ -36,7 +33,7 @@ where pub trait ConflictRevisionSink: Send + Sync + 'static { fn send(&self, revisions: Vec) -> BoxResultFuture<(), FlowyError>; - fn ack(&self, rev_id: String, ty: ServerRevisionWSDataType) -> BoxResultFuture<(), FlowyError>; + fn ack(&self, rev_id: i64) -> BoxResultFuture<(), FlowyError>; } pub struct ConflictController @@ -75,13 +72,12 @@ where Operations: OperationsSerializer + OperationsDeserializer + Clone + Send + Sync, Connection: Send + Sync + 'static, { - pub async fn receive_bytes(&self, bytes: Bytes) -> FlowyResult<()> { - let repeated_revision = RepeatedRevision::try_from(bytes)?; - if repeated_revision.is_empty() { + pub async fn receive_revisions(&self, revisions: Vec) -> FlowyResult<()> { + if revisions.is_empty() { return Ok(()); } - match self.handle_revision(repeated_revision).await? { + match self.handle_revision(revisions).await? { None => {} Some(server_revision) => { self.rev_sink.send(vec![server_revision]).await?; @@ -90,8 +86,8 @@ where Ok(()) } - pub async fn ack_revision(&self, rev_id: String, ty: ServerRevisionWSDataType) -> FlowyResult<()> { - let _ = self.rev_sink.ack(rev_id, ty).await?; + pub async fn ack_revision(&self, rev_id: i64) -> FlowyResult<()> { + let _ = self.rev_sink.ack(rev_id).await?; Ok(()) } @@ -101,8 +97,7 @@ where Ok(()) } - async fn handle_revision(&self, repeated_revision: RepeatedRevision) -> FlowyResult> { - let mut revisions = repeated_revision.into_inner(); + async fn handle_revision(&self, mut revisions: Vec) -> FlowyResult> { let first_revision = revisions.first().unwrap(); if let Some(local_revision) = self.rev_manager.get_revision(first_revision.rev_id).await { if local_revision.md5 == first_revision.md5 { diff --git a/frontend/rust-lib/flowy-revision/src/ws_manager.rs b/frontend/rust-lib/flowy-revision/src/ws_manager.rs index eb2ade407c..d11d0db0ae 100644 --- a/frontend/rust-lib/flowy-revision/src/ws_manager.rs +++ b/frontend/rust-lib/flowy-revision/src/ws_manager.rs @@ -1,15 +1,13 @@ use crate::ConflictRevisionSink; use async_stream::stream; -use bytes::Bytes; + use flowy_error::{FlowyError, FlowyResult}; -use flowy_http_model::{ - revision::{RevId, Revision, RevisionRange}, - ws_data::{ClientRevisionWSData, NewDocumentUser, ServerRevisionWSData, ServerRevisionWSDataType}, -}; +use flowy_http_model::revision::{Revision, RevisionRange}; +use flowy_http_model::ws_data::{ClientRevisionWSData, NewDocumentUser, ServerRevisionWSData, WSRevisionPayload}; use futures_util::{future::BoxFuture, stream::StreamExt}; use lib_infra::future::{BoxResultFuture, FutureResult}; use lib_ws::WSConnectState; -use std::{collections::VecDeque, convert::TryFrom, fmt::Formatter, sync::Arc}; +use std::{collections::VecDeque, fmt::Formatter, sync::Arc}; use tokio::{ sync::{ broadcast, mpsc, @@ -21,8 +19,8 @@ use tokio::{ // The consumer consumes the messages pushed by the web socket. pub trait RevisionWSDataStream: Send + Sync { - fn receive_push_revision(&self, bytes: Bytes) -> BoxResultFuture<(), FlowyError>; - fn receive_ack(&self, id: String, ty: ServerRevisionWSDataType) -> BoxResultFuture<(), FlowyError>; + fn receive_push_revision(&self, revisions: Vec) -> BoxResultFuture<(), FlowyError>; + fn receive_ack(&self, rev_id: i64) -> BoxResultFuture<(), FlowyError>; fn receive_new_user_connect(&self, new_user: NewDocumentUser) -> BoxResultFuture<(), FlowyError>; fn pull_revisions_in_range(&self, range: RevisionRange) -> BoxResultFuture<(), FlowyError>; } @@ -214,26 +212,22 @@ impl RevisionWSStream { } async fn handle_message(&self, msg: ServerRevisionWSData) -> FlowyResult<()> { - let ServerRevisionWSData { object_id, ty, data } = msg; - let bytes = Bytes::from(data); - match ty { - ServerRevisionWSDataType::ServerPushRev => { - tracing::trace!("[{}]: new push revision: {}:{:?}", self, object_id, ty); - let _ = self.consumer.receive_push_revision(bytes).await?; + let ServerRevisionWSData { object_id, payload } = msg; + match payload { + WSRevisionPayload::ServerPushRev { revisions } => { + tracing::trace!("[{}]: new push revision: {}", self, object_id); + let _ = self.consumer.receive_push_revision(revisions).await?; } - ServerRevisionWSDataType::ServerPullRev => { - let range = RevisionRange::try_from(bytes)?; - tracing::trace!("[{}]: new pull: {}:{}-{:?}", self, object_id, range, ty); + WSRevisionPayload::ServerPullRev { range } => { + tracing::trace!("[{}]: new pull: {}:{:?}", self, object_id, range); let _ = self.consumer.pull_revisions_in_range(range).await?; } - ServerRevisionWSDataType::ServerAck => { - let rev_id = RevId::try_from(bytes).unwrap().value; - tracing::trace!("[{}]: new ack: {}:{}-{:?}", self, object_id, rev_id, ty); - let _ = self.consumer.receive_ack(rev_id.to_string(), ty).await; + WSRevisionPayload::ServerAck { rev_id } => { + tracing::trace!("[{}]: new ack: {}:{}", self, object_id, rev_id); + let _ = self.consumer.receive_ack(rev_id).await; } - ServerRevisionWSDataType::UserConnect => { - let new_user = NewDocumentUser::try_from(bytes)?; - let _ = self.consumer.receive_new_user_connect(new_user).await; + WSRevisionPayload::UserConnect { user } => { + let _ = self.consumer.receive_new_user_connect(user).await; } } Ok(()) @@ -309,7 +303,7 @@ impl RevisionWSSink { Ok(()) } Some(data) => { - tracing::trace!("[{}]: send {}:{}-{:?}", self, data.object_id, data.id(), data.ty); + tracing::trace!("[{}]: send {}:{}-{:?}", self, data.object_id, data.rev_id, data.ty); self.rev_web_socket.send(data).await } } @@ -397,18 +391,17 @@ impl WSDataProvider { data } - pub async fn ack_data(&self, id: String, _ty: ServerRevisionWSDataType) -> FlowyResult<()> { + pub async fn ack_data(&self, rev_id: i64) -> FlowyResult<()> { let source = self.current_source.read().await.clone(); match source { Source::Custom => { let should_pop = match self.rev_ws_data_list.read().await.front() { None => false, Some(val) => { - let expected_id = val.id(); - if expected_id == id { + if val.rev_id == rev_id { true } else { - tracing::error!("The front element's {} is not equal to the {}", expected_id, id); + tracing::error!("The front element's {} is not equal to the {}", val.rev_id, rev_id); false } } @@ -419,9 +412,6 @@ impl WSDataProvider { 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.data_source.ack_revision(rev_id).await?; Ok::<(), FlowyError>(()) } @@ -439,8 +429,8 @@ impl ConflictRevisionSink for Arc { }) } - fn ack(&self, rev_id: String, ty: ServerRevisionWSDataType) -> BoxResultFuture<(), FlowyError> { + fn ack(&self, rev_id: i64) -> BoxResultFuture<(), FlowyError> { let sink = self.clone(); - Box::pin(async move { sink.ack_data(rev_id, ty).await }) + Box::pin(async move { sink.ack_data(rev_id).await }) } } diff --git a/frontend/rust-lib/flowy-revision/tests/revision_test/script.rs b/frontend/rust-lib/flowy-revision/tests/revision_test/script.rs index 214e648d10..eaa4b46267 100644 --- a/frontend/rust-lib/flowy-revision/tests/revision_test/script.rs +++ b/frontend/rust-lib/flowy-revision/tests/revision_test/script.rs @@ -205,7 +205,7 @@ impl RevisionDiskCache for RevisionDiskCacheMock { .records .write() .iter_mut() - .find(|record| record.revision.rev_id == *changeset.rev_id.as_ref()) + .find(|record| record.revision.rev_id == changeset.rev_id) { record.state = changeset.state; } diff --git a/shared-lib/flowy-sync/Cargo.toml b/frontend/rust-lib/flowy-sync/Cargo.toml similarity index 67% rename from shared-lib/flowy-sync/Cargo.toml rename to frontend/rust-lib/flowy-sync/Cargo.toml index 888de04bd9..442dc2b1c4 100644 --- a/shared-lib/flowy-sync/Cargo.toml +++ b/frontend/rust-lib/flowy-sync/Cargo.toml @@ -6,12 +6,12 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -lib-ot = { path = "../lib-ot" } -lib-infra = { path = "../lib-infra" } +lib-ot = { path = "../../../shared-lib/lib-ot" } +lib-infra = { path = "../../../shared-lib/lib-infra" } flowy-derive = { path = "../flowy-derive" } -folder-rev-model = { path = "../folder-rev-model" } -grid-rev-model = { path = "../grid-rev-model" } -flowy-http-model= { path = "../flowy-http-model" } +folder-rev-model = { path = "../../../shared-lib/folder-rev-model" } +grid-rev-model = { path = "../../../shared-lib/grid-rev-model" } +flowy-http-model = { path = "../../../shared-lib/flowy-http-model" } protobuf = {version = "2.18.0"} bytes = "1.0" log = "0.4.14" diff --git a/shared-lib/flowy-sync/src/client_document/document_pad.rs b/frontend/rust-lib/flowy-sync/src/client_document/document_pad.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/document_pad.rs rename to frontend/rust-lib/flowy-sync/src/client_document/document_pad.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/delete/default_delete.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/delete/default_delete.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/delete/default_delete.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/delete/default_delete.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/delete/mod.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/delete/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/delete/mod.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/delete/mod.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/delete/preserve_line_format_merge.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/delete/preserve_line_format_merge.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/delete/preserve_line_format_merge.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/delete/preserve_line_format_merge.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/format/format_at_position.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/format/format_at_position.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/format/format_at_position.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/format/format_at_position.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/format/mod.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/format/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/format/mod.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/format/mod.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/format/resolve_block_format.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/format/resolve_block_format.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/format/resolve_block_format.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/format/resolve_block_format.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/format/resolve_inline_format.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/format/resolve_inline_format.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/format/resolve_inline_format.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/format/resolve_inline_format.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/helper.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/helper.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/helper.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/helper.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/insert/auto_exit_block.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/auto_exit_block.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/insert/auto_exit_block.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/auto_exit_block.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/insert/auto_format.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/auto_format.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/insert/auto_format.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/auto_format.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/insert/default_insert.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/default_insert.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/insert/default_insert.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/default_insert.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/insert/mod.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/insert/mod.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/mod.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/insert/preserve_block_format.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/preserve_block_format.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/insert/preserve_block_format.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/preserve_block_format.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/insert/preserve_inline_format.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/preserve_inline_format.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/insert/preserve_inline_format.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/preserve_inline_format.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/insert/reset_format_on_new_line.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/reset_format_on_new_line.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/insert/reset_format_on_new_line.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/insert/reset_format_on_new_line.rs diff --git a/shared-lib/flowy-sync/src/client_document/extensions/mod.rs b/frontend/rust-lib/flowy-sync/src/client_document/extensions/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/extensions/mod.rs rename to frontend/rust-lib/flowy-sync/src/client_document/extensions/mod.rs diff --git a/shared-lib/flowy-sync/src/client_document/history.rs b/frontend/rust-lib/flowy-sync/src/client_document/history.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/history.rs rename to frontend/rust-lib/flowy-sync/src/client_document/history.rs diff --git a/shared-lib/flowy-sync/src/client_document/mod.rs b/frontend/rust-lib/flowy-sync/src/client_document/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/mod.rs rename to frontend/rust-lib/flowy-sync/src/client_document/mod.rs diff --git a/shared-lib/flowy-sync/src/client_document/view.rs b/frontend/rust-lib/flowy-sync/src/client_document/view.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_document/view.rs rename to frontend/rust-lib/flowy-sync/src/client_document/view.rs diff --git a/shared-lib/flowy-sync/src/client_folder/builder.rs b/frontend/rust-lib/flowy-sync/src/client_folder/builder.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_folder/builder.rs rename to frontend/rust-lib/flowy-sync/src/client_folder/builder.rs diff --git a/shared-lib/flowy-sync/src/client_folder/folder_node.rs b/frontend/rust-lib/flowy-sync/src/client_folder/folder_node.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_folder/folder_node.rs rename to frontend/rust-lib/flowy-sync/src/client_folder/folder_node.rs diff --git a/shared-lib/flowy-sync/src/client_folder/folder_pad.rs b/frontend/rust-lib/flowy-sync/src/client_folder/folder_pad.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_folder/folder_pad.rs rename to frontend/rust-lib/flowy-sync/src/client_folder/folder_pad.rs diff --git a/shared-lib/flowy-sync/src/client_folder/mod.rs b/frontend/rust-lib/flowy-sync/src/client_folder/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_folder/mod.rs rename to frontend/rust-lib/flowy-sync/src/client_folder/mod.rs diff --git a/shared-lib/flowy-sync/src/client_folder/trash_node.rs b/frontend/rust-lib/flowy-sync/src/client_folder/trash_node.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_folder/trash_node.rs rename to frontend/rust-lib/flowy-sync/src/client_folder/trash_node.rs diff --git a/shared-lib/flowy-sync/src/client_folder/util.rs b/frontend/rust-lib/flowy-sync/src/client_folder/util.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_folder/util.rs rename to frontend/rust-lib/flowy-sync/src/client_folder/util.rs diff --git a/shared-lib/flowy-sync/src/client_folder/workspace_node.rs b/frontend/rust-lib/flowy-sync/src/client_folder/workspace_node.rs similarity index 99% rename from shared-lib/flowy-sync/src/client_folder/workspace_node.rs rename to frontend/rust-lib/flowy-sync/src/client_folder/workspace_node.rs index abc752631a..a74c9bf4ed 100644 --- a/shared-lib/flowy-sync/src/client_folder/workspace_node.rs +++ b/frontend/rust-lib/flowy-sync/src/client_folder/workspace_node.rs @@ -1,6 +1,5 @@ use crate::client_folder::util::*; use crate::client_folder::AtomicNodeTree; - use flowy_derive::Node; use lib_ot::core::*; use std::sync::Arc; diff --git a/shared-lib/flowy-sync/src/client_grid/block_revision_pad.rs b/frontend/rust-lib/flowy-sync/src/client_grid/block_revision_pad.rs similarity index 99% rename from shared-lib/flowy-sync/src/client_grid/block_revision_pad.rs rename to frontend/rust-lib/flowy-sync/src/client_grid/block_revision_pad.rs index 2d5fcebba7..a2b70de239 100644 --- a/shared-lib/flowy-sync/src/client_grid/block_revision_pad.rs +++ b/frontend/rust-lib/flowy-sync/src/client_grid/block_revision_pad.rs @@ -1,6 +1,6 @@ use crate::errors::{CollaborateError, CollaborateResult}; use crate::util::{cal_diff, make_operations_from_revisions}; -use flowy_http_model::revision::{RepeatedRevision, Revision}; +use flowy_http_model::revision::Revision; use flowy_http_model::util::md5; use grid_rev_model::{gen_block_id, gen_row_id, CellRevision, GridBlockRevision, RowChangeset, RowRevision}; use lib_ot::core::{DeltaBuilder, DeltaOperations, EmptyAttributes, OperationTransform}; @@ -264,11 +264,11 @@ pub fn make_grid_block_operations(block_rev: &GridBlockRevision) -> GridBlockOpe GridBlockOperationsBuilder::new().insert(&json).build() } -pub fn make_grid_block_revisions(_user_id: &str, grid_block_meta_data: &GridBlockRevision) -> RepeatedRevision { +pub fn make_grid_block_revisions(_user_id: &str, grid_block_meta_data: &GridBlockRevision) -> Vec { let operations = make_grid_block_operations(grid_block_meta_data); let bytes = operations.json_bytes(); let revision = Revision::initial_revision(&grid_block_meta_data.block_id, bytes); - revision.into() + vec![revision] } impl std::default::Default for GridBlockRevisionPad { diff --git a/shared-lib/flowy-sync/src/client_grid/grid_builder.rs b/frontend/rust-lib/flowy-sync/src/client_grid/grid_builder.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_grid/grid_builder.rs rename to frontend/rust-lib/flowy-sync/src/client_grid/grid_builder.rs diff --git a/shared-lib/flowy-sync/src/client_grid/grid_revision_pad.rs b/frontend/rust-lib/flowy-sync/src/client_grid/grid_revision_pad.rs similarity index 99% rename from shared-lib/flowy-sync/src/client_grid/grid_revision_pad.rs rename to frontend/rust-lib/flowy-sync/src/client_grid/grid_revision_pad.rs index c7fc1e47c4..286f8c5fc0 100644 --- a/shared-lib/flowy-sync/src/client_grid/grid_revision_pad.rs +++ b/frontend/rust-lib/flowy-sync/src/client_grid/grid_revision_pad.rs @@ -1,6 +1,6 @@ use crate::errors::{internal_error, CollaborateError, CollaborateResult}; use crate::util::{cal_diff, make_operations_from_revisions}; -use flowy_http_model::revision::{RepeatedRevision, Revision}; +use flowy_http_model::revision::Revision; use flowy_http_model::util::md5; use grid_rev_model::{ gen_block_id, gen_grid_id, FieldRevision, FieldTypeRevision, GridBlockMetaRevision, GridBlockMetaRevisionChangeset, @@ -410,11 +410,11 @@ pub fn make_grid_operations(grid_rev: &GridRevision) -> GridOperations { GridOperationsBuilder::new().insert(&json).build() } -pub fn make_grid_revisions(_user_id: &str, grid_rev: &GridRevision) -> RepeatedRevision { +pub fn make_grid_revisions(_user_id: &str, grid_rev: &GridRevision) -> Vec { let operations = make_grid_operations(grid_rev); let bytes = operations.json_bytes(); let revision = Revision::initial_revision(&grid_rev.grid_id, bytes); - revision.into() + vec![revision] } impl std::default::Default for GridRevisionPad { diff --git a/shared-lib/flowy-sync/src/client_grid/mod.rs b/frontend/rust-lib/flowy-sync/src/client_grid/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_grid/mod.rs rename to frontend/rust-lib/flowy-sync/src/client_grid/mod.rs diff --git a/shared-lib/flowy-sync/src/client_grid/view_revision_pad.rs b/frontend/rust-lib/flowy-sync/src/client_grid/view_revision_pad.rs similarity index 100% rename from shared-lib/flowy-sync/src/client_grid/view_revision_pad.rs rename to frontend/rust-lib/flowy-sync/src/client_grid/view_revision_pad.rs diff --git a/shared-lib/flowy-sync/src/errors.rs b/frontend/rust-lib/flowy-sync/src/errors.rs similarity index 100% rename from shared-lib/flowy-sync/src/errors.rs rename to frontend/rust-lib/flowy-sync/src/errors.rs diff --git a/shared-lib/flowy-sync/src/lib.rs b/frontend/rust-lib/flowy-sync/src/lib.rs similarity index 100% rename from shared-lib/flowy-sync/src/lib.rs rename to frontend/rust-lib/flowy-sync/src/lib.rs diff --git a/shared-lib/flowy-sync/src/server_document/document_manager.rs b/frontend/rust-lib/flowy-sync/src/server_document/document_manager.rs similarity index 76% rename from shared-lib/flowy-sync/src/server_document/document_manager.rs rename to frontend/rust-lib/flowy-sync/src/server_document/document_manager.rs index 755929bf6f..d1f0cd60b0 100644 --- a/shared-lib/flowy-sync/src/server_document/document_manager.rs +++ b/frontend/rust-lib/flowy-sync/src/server_document/document_manager.rs @@ -2,13 +2,12 @@ use crate::{ errors::{internal_error, CollaborateError, CollaborateResult}, server_document::document_pad::ServerDocument, synchronizer::{RevisionSyncPersistence, RevisionSyncResponse, RevisionSynchronizer, RevisionUser}, - util::rev_id_from_str, }; use async_stream::stream; use dashmap::DashMap; -use flowy_http_model::document::DocumentPayloadPB; -use flowy_http_model::protobuf::ClientRevisionWSData; -use flowy_http_model::revision::{RepeatedRevision, Revision}; +use flowy_http_model::document::DocumentPayload; +use flowy_http_model::entities::ClientRevisionWSData; +use flowy_http_model::revision::Revision; use flowy_http_model::ws_data::ServerRevisionWSDataBuilder; use futures::stream::StreamExt; use lib_infra::future::BoxResultFuture; @@ -21,13 +20,13 @@ use tokio::{ }; pub trait DocumentCloudPersistence: Send + Sync + Debug { - fn read_document(&self, doc_id: &str) -> BoxResultFuture; + fn read_document(&self, doc_id: &str) -> BoxResultFuture; fn create_document( &self, doc_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture, CollaborateError>; + revisions: Vec, + ) -> BoxResultFuture, CollaborateError>; fn read_document_revisions( &self, @@ -35,13 +34,9 @@ pub trait DocumentCloudPersistence: Send + Sync + Debug { rev_ids: Option>, ) -> BoxResultFuture, CollaborateError>; - fn save_document_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError>; + fn save_document_revisions(&self, revisions: Vec) -> BoxResultFuture<(), CollaborateError>; - fn reset_document( - &self, - doc_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture<(), CollaborateError>; + fn reset_document(&self, doc_id: &str, revisions: Vec) -> BoxResultFuture<(), CollaborateError>; } impl RevisionSyncPersistence for Arc { @@ -53,16 +48,12 @@ impl RevisionSyncPersistence for Arc { (**self).read_document_revisions(object_id, rev_ids) } - fn save_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError> { - (**self).save_document_revisions(repeated_revision) + fn save_revisions(&self, revisions: Vec) -> BoxResultFuture<(), CollaborateError> { + (**self).save_document_revisions(revisions) } - fn reset_object( - &self, - object_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture<(), CollaborateError> { - (**self).reset_document(object_id, repeated_revision) + fn reset_object(&self, object_id: &str, revisions: Vec) -> BoxResultFuture<(), CollaborateError> { + (**self).reset_document(object_id, revisions) } } @@ -82,23 +73,25 @@ impl ServerDocumentManager { pub async fn handle_client_revisions( &self, user: Arc, - mut client_data: ClientRevisionWSData, + client_data: ClientRevisionWSData, ) -> Result<(), CollaborateError> { - let repeated_revision: RepeatedRevision = client_data.take_revisions().into(); let cloned_user = user.clone(); - let ack_id = rev_id_from_str(&client_data.data_id)?; + let ack_id = client_data.rev_id; let object_id = client_data.object_id; let result = match self.get_document_handler(&object_id).await { None => { tracing::trace!("Can't find the document. Creating the document {}", object_id); - let _ = self.create_document(&object_id, repeated_revision).await.map_err(|e| { - CollaborateError::internal().context(format!("Server create document failed: {}", e)) - })?; + let _ = self + .create_document(&object_id, client_data.revisions) + .await + .map_err(|e| { + CollaborateError::internal().context(format!("Server create document failed: {}", e)) + })?; Ok(()) } Some(handler) => { - let _ = handler.apply_revisions(user, repeated_revision).await?; + let _ = handler.apply_revisions(user, client_data.revisions).await?; Ok(()) } }; @@ -116,7 +109,7 @@ impl ServerDocumentManager { user: Arc, client_data: ClientRevisionWSData, ) -> Result<(), CollaborateError> { - let rev_id = rev_id_from_str(&client_data.data_id)?; + let rev_id = client_data.rev_id; let doc_id = client_data.object_id.clone(); match self.get_document_handler(&doc_id).await { None => { @@ -133,9 +126,9 @@ impl ServerDocumentManager { pub async fn handle_document_reset( &self, doc_id: &str, - mut repeated_revision: RepeatedRevision, + mut revisions: Vec, ) -> Result<(), CollaborateError> { - repeated_revision.sort_by(|a, b| a.rev_id.cmp(&b.rev_id)); + revisions.sort_by(|a, b| a.rev_id.cmp(&b.rev_id)); match self.get_document_handler(doc_id).await { None => { @@ -143,7 +136,7 @@ impl ServerDocumentManager { Ok(()) } Some(handler) => { - let _ = handler.apply_document_reset(repeated_revision).await?; + let _ = handler.apply_document_reset(revisions).await?; Ok(()) } } @@ -169,9 +162,9 @@ impl ServerDocumentManager { async fn create_document( &self, doc_id: &str, - repeated_revision: RepeatedRevision, + revisions: Vec, ) -> Result, CollaborateError> { - match self.persistence.create_document(doc_id, repeated_revision).await? { + match self.persistence.create_document(doc_id, revisions).await? { None => Err(CollaborateError::internal().context("Create document info from revisions failed")), Some(doc) => { let handler = self.create_document_handler(doc).await?; @@ -187,7 +180,7 @@ impl ServerDocumentManager { #[tracing::instrument(level = "debug", skip(self, doc), err)] async fn create_document_handler( &self, - doc: DocumentPayloadPB, + doc: DocumentPayload, ) -> Result, CollaborateError> { let persistence = self.persistence.clone(); let handle = spawn_blocking(|| OpenDocumentHandler::new(doc, persistence)) @@ -212,7 +205,7 @@ struct OpenDocumentHandler { } impl OpenDocumentHandler { - fn new(doc: DocumentPayloadPB, persistence: Arc) -> Result { + fn new(doc: DocumentPayload, persistence: Arc) -> Result { let doc_id = doc.doc_id.clone(); let (sender, receiver) = mpsc::channel(1000); let users = DashMap::new(); @@ -229,21 +222,17 @@ impl OpenDocumentHandler { #[tracing::instrument( name = "server_document_apply_revision", level = "trace", - skip(self, user, repeated_revision), + skip(self, user, revisions), err )] async fn apply_revisions( &self, user: Arc, - repeated_revision: RepeatedRevision, + revisions: Vec, ) -> Result<(), CollaborateError> { let (ret, rx) = oneshot::channel(); self.users.insert(user.user_id(), user.clone()); - let msg = DocumentCommand::ApplyRevisions { - user, - repeated_revision, - ret, - }; + let msg = DocumentCommand::ApplyRevisions { user, revisions, ret }; let result = self.send(msg, rx).await?; result @@ -257,10 +246,10 @@ impl OpenDocumentHandler { result } - #[tracing::instrument(level = "debug", skip(self, repeated_revision), err)] - async fn apply_document_reset(&self, repeated_revision: RepeatedRevision) -> Result<(), CollaborateError> { + #[tracing::instrument(level = "debug", skip(self, revisions), err)] + async fn apply_document_reset(&self, revisions: Vec) -> Result<(), CollaborateError> { let (ret, rx) = oneshot::channel(); - let msg = DocumentCommand::Reset { repeated_revision, ret }; + let msg = DocumentCommand::Reset { revisions, ret }; let result = self.send(msg, rx).await?; result } @@ -285,7 +274,7 @@ impl std::ops::Drop for OpenDocumentHandler { enum DocumentCommand { ApplyRevisions { user: Arc, - repeated_revision: RepeatedRevision, + revisions: Vec, ret: oneshot::Sender>, }, Ping { @@ -294,7 +283,7 @@ enum DocumentCommand { ret: oneshot::Sender>, }, Reset { - repeated_revision: RepeatedRevision, + revisions: Vec, ret: oneshot::Sender>, }, } @@ -337,14 +326,10 @@ impl DocumentCommandRunner { async fn handle_message(&self, msg: DocumentCommand) { match msg { - DocumentCommand::ApplyRevisions { - user, - repeated_revision, - ret, - } => { + DocumentCommand::ApplyRevisions { user, revisions, ret } => { let result = self .synchronizer - .sync_revisions(user, repeated_revision) + .sync_revisions(user, revisions) .await .map_err(internal_error); let _ = ret.send(result); @@ -353,8 +338,8 @@ impl DocumentCommandRunner { 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); + DocumentCommand::Reset { revisions, ret } => { + let result = self.synchronizer.reset(revisions).await.map_err(internal_error); let _ = ret.send(result); } } diff --git a/shared-lib/flowy-sync/src/server_document/document_pad.rs b/frontend/rust-lib/flowy-sync/src/server_document/document_pad.rs similarity index 100% rename from shared-lib/flowy-sync/src/server_document/document_pad.rs rename to frontend/rust-lib/flowy-sync/src/server_document/document_pad.rs diff --git a/shared-lib/flowy-sync/src/server_document/mod.rs b/frontend/rust-lib/flowy-sync/src/server_document/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/server_document/mod.rs rename to frontend/rust-lib/flowy-sync/src/server_document/mod.rs diff --git a/shared-lib/flowy-sync/src/server_folder/folder_manager.rs b/frontend/rust-lib/flowy-sync/src/server_folder/folder_manager.rs similarity index 80% rename from shared-lib/flowy-sync/src/server_folder/folder_manager.rs rename to frontend/rust-lib/flowy-sync/src/server_folder/folder_manager.rs index 15f62681c0..fdbbd25f9e 100644 --- a/shared-lib/flowy-sync/src/server_folder/folder_manager.rs +++ b/frontend/rust-lib/flowy-sync/src/server_folder/folder_manager.rs @@ -3,12 +3,11 @@ use crate::{ errors::{internal_error, CollaborateError, CollaborateResult}, server_folder::folder_pad::ServerFolder, synchronizer::{RevisionSyncPersistence, RevisionSyncResponse, RevisionUser}, - util::rev_id_from_str, }; use async_stream::stream; +use flowy_http_model::entities::ClientRevisionWSData; use flowy_http_model::folder::FolderInfo; -use flowy_http_model::protobuf::ClientRevisionWSData; -use flowy_http_model::revision::{RepeatedRevision, Revision}; +use flowy_http_model::revision::Revision; use flowy_http_model::ws_data::ServerRevisionWSDataBuilder; use futures::stream::StreamExt; use lib_infra::future::BoxResultFuture; @@ -25,10 +24,10 @@ pub trait FolderCloudPersistence: Send + Sync + Debug { &self, user_id: &str, folder_id: &str, - repeated_revision: RepeatedRevision, + revisions: Vec, ) -> BoxResultFuture, CollaborateError>; - fn save_folder_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError>; + fn save_folder_revisions(&self, revisions: Vec) -> BoxResultFuture<(), CollaborateError>; fn read_folder_revisions( &self, @@ -36,11 +35,7 @@ pub trait FolderCloudPersistence: Send + Sync + Debug { rev_ids: Option>, ) -> BoxResultFuture, CollaborateError>; - fn reset_folder( - &self, - folder_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture<(), CollaborateError>; + fn reset_folder(&self, folder_id: &str, revisions: Vec) -> BoxResultFuture<(), CollaborateError>; } impl RevisionSyncPersistence for Arc { @@ -52,16 +47,12 @@ impl RevisionSyncPersistence for Arc { (**self).read_folder_revisions(object_id, rev_ids) } - fn save_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError> { - (**self).save_folder_revisions(repeated_revision) + fn save_revisions(&self, revisions: Vec) -> BoxResultFuture<(), CollaborateError> { + (**self).save_folder_revisions(revisions) } - fn reset_object( - &self, - object_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture<(), CollaborateError> { - (**self).reset_folder(object_id, repeated_revision) + fn reset_object(&self, object_id: &str, revisions: Vec) -> BoxResultFuture<(), CollaborateError> { + (**self).reset_folder(object_id, revisions) } } @@ -81,24 +72,23 @@ impl ServerFolderManager { pub async fn handle_client_revisions( &self, user: Arc, - mut client_data: ClientRevisionWSData, + client_data: ClientRevisionWSData, ) -> Result<(), CollaborateError> { - let repeated_revision: RepeatedRevision = client_data.take_revisions().into(); let cloned_user = user.clone(); - let ack_id = rev_id_from_str(&client_data.data_id)?; + let ack_id = client_data.rev_id; let folder_id = client_data.object_id; let user_id = user.user_id(); let result = match self.get_folder_handler(&user_id, &folder_id).await { None => { let _ = self - .create_folder(&user_id, &folder_id, repeated_revision) + .create_folder(&user_id, &folder_id, client_data.revisions) .await .map_err(|e| CollaborateError::internal().context(format!("Server create folder failed: {}", e)))?; Ok(()) } Some(handler) => { - let _ = handler.apply_revisions(user, repeated_revision).await?; + let _ = handler.apply_revisions(user, client_data.revisions).await?; Ok(()) } }; @@ -117,7 +107,7 @@ impl ServerFolderManager { client_data: ClientRevisionWSData, ) -> Result<(), CollaborateError> { let user_id = user.user_id(); - let rev_id = rev_id_from_str(&client_data.data_id)?; + let rev_id = client_data.rev_id; let folder_id = client_data.object_id.clone(); match self.get_folder_handler(&user_id, &folder_id).await { None => { @@ -161,18 +151,14 @@ impl ServerFolderManager { Ok(Arc::new(handle?)) } - #[tracing::instrument(level = "debug", skip(self, repeated_revision), err)] + #[tracing::instrument(level = "debug", skip(self, revisions), err)] async fn create_folder( &self, user_id: &str, folder_id: &str, - repeated_revision: RepeatedRevision, + revisions: Vec, ) -> Result, CollaborateError> { - match self - .persistence - .create_folder(user_id, folder_id, repeated_revision) - .await? - { + match self.persistence.create_folder(user_id, folder_id, revisions).await? { Some(folder_info) => { let handler = self.create_folder_handler(folder_info).await?; self.folder_handlers @@ -212,20 +198,12 @@ impl OpenFolderHandler { #[tracing::instrument( name = "server_folder_apply_revision", level = "trace", - skip(self, user, repeated_revision), + skip(self, user, revisions), err )] - async fn apply_revisions( - &self, - user: Arc, - repeated_revision: RepeatedRevision, - ) -> CollaborateResult<()> { + async fn apply_revisions(&self, user: Arc, revisions: Vec) -> CollaborateResult<()> { let (ret, rx) = oneshot::channel(); - let msg = FolderCommand::ApplyRevisions { - user, - repeated_revision, - ret, - }; + let msg = FolderCommand::ApplyRevisions { user, revisions, ret }; self.send(msg, rx).await? } @@ -255,7 +233,7 @@ impl std::ops::Drop for OpenFolderHandler { enum FolderCommand { ApplyRevisions { user: Arc, - repeated_revision: RepeatedRevision, + revisions: Vec, ret: oneshot::Sender>, }, Ping { @@ -302,14 +280,10 @@ impl FolderCommandRunner { async fn handle_message(&self, msg: FolderCommand) { match msg { - FolderCommand::ApplyRevisions { - user, - repeated_revision, - ret, - } => { + FolderCommand::ApplyRevisions { user, revisions, ret } => { let result = self .synchronizer - .sync_revisions(user, repeated_revision) + .sync_revisions(user, revisions) .await .map_err(internal_error); let _ = ret.send(result); diff --git a/shared-lib/flowy-sync/src/server_folder/folder_pad.rs b/frontend/rust-lib/flowy-sync/src/server_folder/folder_pad.rs similarity index 100% rename from shared-lib/flowy-sync/src/server_folder/folder_pad.rs rename to frontend/rust-lib/flowy-sync/src/server_folder/folder_pad.rs diff --git a/shared-lib/flowy-sync/src/server_folder/mod.rs b/frontend/rust-lib/flowy-sync/src/server_folder/mod.rs similarity index 100% rename from shared-lib/flowy-sync/src/server_folder/mod.rs rename to frontend/rust-lib/flowy-sync/src/server_folder/mod.rs diff --git a/shared-lib/flowy-sync/src/synchronizer.rs b/frontend/rust-lib/flowy-sync/src/synchronizer.rs similarity index 87% rename from shared-lib/flowy-sync/src/synchronizer.rs rename to frontend/rust-lib/flowy-sync/src/synchronizer.rs index 6660721877..a85f8d7dbb 100644 --- a/shared-lib/flowy-sync/src/synchronizer.rs +++ b/frontend/rust-lib/flowy-sync/src/synchronizer.rs @@ -1,5 +1,5 @@ use crate::{errors::CollaborateError, util::*}; -use flowy_http_model::revision::{RepeatedRevision, Revision, RevisionRange}; +use flowy_http_model::revision::{Revision, RevisionRange}; use flowy_http_model::ws_data::{ServerRevisionWSData, ServerRevisionWSDataBuilder}; use lib_infra::future::BoxResultFuture; use lib_ot::core::{DeltaOperations, OperationAttributes}; @@ -35,13 +35,9 @@ pub trait RevisionSyncPersistence: Send + Sync + 'static { rev_ids: Option>, ) -> BoxResultFuture, CollaborateError>; - fn save_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError>; + fn save_revisions(&self, revisions: Vec) -> BoxResultFuture<(), CollaborateError>; - fn reset_object( - &self, - object_id: &str, - repeated_revision: RepeatedRevision, - ) -> BoxResultFuture<(), CollaborateError>; + fn reset_object(&self, object_id: &str, revisions: Vec) -> BoxResultFuture<(), CollaborateError>; } pub trait RevisionSyncObject: Send + Sync + 'static { @@ -92,24 +88,23 @@ where } } - #[tracing::instrument(level = "trace", skip(self, user, repeated_revision), err)] + #[tracing::instrument(level = "trace", skip(self, user, revisions), err)] pub async fn sync_revisions( &self, user: Arc, - repeated_revision: RepeatedRevision, + revisions: Vec, ) -> Result<(), CollaborateError> { let object_id = self.object_id.clone(); - if repeated_revision.is_empty() { + if revisions.is_empty() { // Return all the revisions to client let revisions = self.persistence.read_revisions(&object_id, None).await?; - let repeated_revision = RepeatedRevision::from(revisions); - let data = ServerRevisionWSDataBuilder::build_push_message(&object_id, repeated_revision); + let data = ServerRevisionWSDataBuilder::build_push_message(&object_id, revisions); user.receive(RevisionSyncResponse::Push(data)); return Ok(()); } let server_base_rev_id = self.rev_id.load(SeqCst); - let first_revision = repeated_revision.first().unwrap().clone(); + let first_revision = revisions.first().unwrap().clone(); if self.is_applied_before(&first_revision, &self.persistence).await { // Server has received this revision before, so ignore the following revisions return Ok(()); @@ -120,10 +115,10 @@ where let server_rev_id = next(server_base_rev_id); if server_base_rev_id == first_revision.base_rev_id || server_rev_id == first_revision.rev_id { // The rev is in the right order, just compose it. - for revision in repeated_revision.iter() { + for revision in revisions.iter() { let _ = self.compose_revision(revision)?; } - let _ = self.persistence.save_revisions(repeated_revision).await?; + let _ = self.persistence.save_revisions(revisions).await?; } else { // The server ops is outdated, pull the missing revision from the client. let range = RevisionRange { @@ -173,14 +168,13 @@ where Ok(()) } - #[tracing::instrument(level = "debug", skip(self, repeated_revision), fields(object_id), err)] - pub async fn reset(&self, repeated_revision: RepeatedRevision) -> Result<(), CollaborateError> { + #[tracing::instrument(level = "debug", skip(self, revisions), fields(object_id), err)] + pub async fn reset(&self, revisions: Vec) -> Result<(), CollaborateError> { let object_id = self.object_id.clone(); tracing::Span::current().record("object_id", &object_id.as_str()); - let revisions: Vec = repeated_revision.clone().into_inner(); let (_, rev_id) = pair_rev_id_from_revision_pbs(&revisions); - let operations = make_operations_from_revisions(revisions)?; - let _ = self.persistence.reset_object(&object_id, repeated_revision).await?; + let operations = make_operations_from_revisions(revisions.clone())?; + let _ = self.persistence.reset_object(&object_id, revisions).await?; self.object.write().set_operations(operations); let _ = self.rev_id.fetch_update(SeqCst, SeqCst, |_e| Some(rev_id)); Ok(()) @@ -200,7 +194,7 @@ where #[tracing::instrument(level = "debug", skip(self, revision))] fn transform_revision( &self, - revision: &flowy_http_model::protobuf::Revision, + revision: &Revision, ) -> Result<(RevisionOperations, RevisionOperations), CollaborateError> { let client_operations = RevisionOperations::::from_bytes(&revision.bytes)?; let result = self.object.read().transform(&client_operations)?; @@ -252,8 +246,7 @@ where // assert_eq!(revisions.is_empty(), rev_ids.is_empty(),); } - let repeated_revision = RepeatedRevision::from(revisions); - let data = ServerRevisionWSDataBuilder::build_push_message(&self.object_id, repeated_revision); + let data = ServerRevisionWSDataBuilder::build_push_message(&self.object_id, revisions); user.receive(RevisionSyncResponse::Push(data)); } Err(e) => { diff --git a/shared-lib/flowy-sync/src/util.rs b/frontend/rust-lib/flowy-sync/src/util.rs similarity index 93% rename from shared-lib/flowy-sync/src/util.rs rename to frontend/rust-lib/flowy-sync/src/util.rs index 0914cf25a3..14da6b10ac 100644 --- a/shared-lib/flowy-sync/src/util.rs +++ b/frontend/rust-lib/flowy-sync/src/util.rs @@ -1,9 +1,8 @@ use crate::errors::{CollaborateError, CollaborateResult}; use crate::server_folder::FolderOperations; use dissimilar::Chunk; -use flowy_http_model::document::DocumentPayloadPB; +use flowy_http_model::document::DocumentPayload; use flowy_http_model::folder::FolderInfo; -use flowy_http_model::revision::RepeatedRevision; use flowy_http_model::revision::Revision; use lib_ot::core::{DeltaOperationBuilder, OTString, OperationAttributes}; use lib_ot::{ @@ -91,9 +90,8 @@ pub fn pair_rev_id_from_revision_pbs(revisions: &[Revision]) -> (i64, i64) { #[inline] pub fn make_folder_from_revisions_pb( folder_id: &str, - revisions: RepeatedRevision, + revisions: Vec, ) -> Result, CollaborateError> { - let revisions = revisions.into_inner(); if revisions.is_empty() { return Ok(None); } @@ -123,9 +121,8 @@ pub fn make_folder_from_revisions_pb( #[inline] pub fn make_document_from_revision_pbs( doc_id: &str, - revisions: RepeatedRevision, -) -> Result, CollaborateError> { - let revisions = revisions.into_inner(); + revisions: Vec, +) -> Result, CollaborateError> { if revisions.is_empty() { return Ok(None); } @@ -145,7 +142,7 @@ pub fn make_document_from_revision_pbs( delta = delta.compose(&new_delta)?; } - Ok(Some(DocumentPayloadPB { + Ok(Some(DocumentPayload { doc_id: doc_id.to_owned(), data: delta.json_bytes().to_vec(), rev_id, diff --git a/shared-lib/flowy-sync/tests/client_folder/folder_test.rs b/frontend/rust-lib/flowy-sync/tests/client_folder/folder_test.rs similarity index 100% rename from shared-lib/flowy-sync/tests/client_folder/folder_test.rs rename to frontend/rust-lib/flowy-sync/tests/client_folder/folder_test.rs diff --git a/shared-lib/flowy-sync/tests/client_folder/mod.rs b/frontend/rust-lib/flowy-sync/tests/client_folder/mod.rs similarity index 100% rename from shared-lib/flowy-sync/tests/client_folder/mod.rs rename to frontend/rust-lib/flowy-sync/tests/client_folder/mod.rs diff --git a/shared-lib/flowy-sync/tests/client_folder/script.rs b/frontend/rust-lib/flowy-sync/tests/client_folder/script.rs similarity index 100% rename from shared-lib/flowy-sync/tests/client_folder/script.rs rename to frontend/rust-lib/flowy-sync/tests/client_folder/script.rs diff --git a/shared-lib/flowy-sync/tests/client_folder/workspace_test.rs b/frontend/rust-lib/flowy-sync/tests/client_folder/workspace_test.rs similarity index 100% rename from shared-lib/flowy-sync/tests/client_folder/workspace_test.rs rename to frontend/rust-lib/flowy-sync/tests/client_folder/workspace_test.rs diff --git a/shared-lib/flowy-sync/tests/main.rs b/frontend/rust-lib/flowy-sync/tests/main.rs similarity index 100% rename from shared-lib/flowy-sync/tests/main.rs rename to frontend/rust-lib/flowy-sync/tests/main.rs diff --git a/frontend/rust-lib/flowy-test/Cargo.toml b/frontend/rust-lib/flowy-test/Cargo.toml index b8d7b92a70..d55aa7e4c2 100644 --- a/frontend/rust-lib/flowy-test/Cargo.toml +++ b/frontend/rust-lib/flowy-test/Cargo.toml @@ -13,7 +13,7 @@ flowy-folder = { path = "../flowy-folder", default-features = false} flowy-document= { path = "../flowy-document", default-features = false} lib-dispatch = { path = "../lib-dispatch" } -flowy-sync = { path = "../../../shared-lib/flowy-sync" } +flowy-sync = { path = "../flowy-sync"} lib-ot = { path = "../../../shared-lib/lib-ot" } lib-infra = { path = "../../../shared-lib/lib-infra" } diff --git a/frontend/rust-lib/flowy-user/Cargo.toml b/frontend/rust-lib/flowy-user/Cargo.toml index 5d18ec979b..b33b76e2d7 100644 --- a/frontend/rust-lib/flowy-user/Cargo.toml +++ b/frontend/rust-lib/flowy-user/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -flowy-derive = { path = "../../../shared-lib/flowy-derive" } +flowy-derive = { path = "../flowy-derive" } flowy-database = { path = "../flowy-database" } flowy-error = { path = "../flowy-error", features = ["db", "http_server"] } @@ -48,4 +48,4 @@ rand = "0.8.5" dart = ["flowy-codegen/dart"] [build-dependencies] -flowy-codegen= { path = "../../../shared-lib/flowy-codegen"} +flowy-codegen = { path = "../flowy-codegen"} diff --git a/frontend/scripts/makefile/tool.toml b/frontend/scripts/makefile/tool.toml index 870a4888f8..55159275f2 100644 --- a/frontend/scripts/makefile/tool.toml +++ b/frontend/scripts/makefile/tool.toml @@ -17,7 +17,7 @@ script_runner = "@shell" [tasks.rm_macro_build_cache] script = [ """ - path = canonicalize ../shared-lib/flowy-codegen/.cache + path = canonicalize ../frontend/rust-lib/flowy-codegen/.cache if is_path_exists ${path} rm -rf ${path} end diff --git a/shared-lib/Cargo.lock b/shared-lib/Cargo.lock index 125bb8c48c..c0c35f34ae 100644 --- a/shared-lib/Cargo.lock +++ b/shared-lib/Cargo.lock @@ -428,16 +428,6 @@ dependencies = [ "walkdir", ] -[[package]] -name = "flowy-error-code" -version = "0.1.0" -dependencies = [ - "derive_more", - "flowy-codegen", - "flowy-derive", - "protobuf", -] - [[package]] name = "flowy-http-model" version = "0.1.0" @@ -448,6 +438,9 @@ dependencies = [ "lib-infra", "md5", "protobuf", + "serde", + "serde_json", + "serde_repr", ] [[package]] @@ -678,7 +671,6 @@ name = "grid-rev-model" version = "0.1.0" dependencies = [ "bytes", - "flowy-error-code", "indexmap", "nanoid", "serde", @@ -860,7 +852,6 @@ dependencies = [ "dashmap", "env_logger", "flowy-codegen", - "flowy-derive", "futures", "futures-channel", "futures-core", @@ -871,6 +862,9 @@ dependencies = [ "paste", "pin-project", "protobuf", + "serde", + "serde_json", + "serde_repr", "strum", "strum_macros", "tokio", diff --git a/shared-lib/Cargo.toml b/shared-lib/Cargo.toml index 4e65489a8f..ccad2db7fe 100644 --- a/shared-lib/Cargo.toml +++ b/shared-lib/Cargo.toml @@ -1,16 +1,11 @@ [workspace] members = [ - "folder-rev-model", - "flowy-sync", - "flowy-http-model", "lib-ot", "lib-ws", "lib-infra", - "flowy-derive", - "flowy-ast", - "flowy-codegen", - "flowy-error-code", "grid-rev-model", + "folder-rev-model", + "flowy-http-model", ] [profile.dev] diff --git a/shared-lib/flowy-error-code/Cargo.toml b/shared-lib/flowy-error-code/Cargo.toml deleted file mode 100644 index 0441fae88d..0000000000 --- a/shared-lib/flowy-error-code/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "flowy-error-code" -version = "0.1.0" -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -flowy-derive = { path = "../flowy-derive" } -protobuf = {version = "2.18.0"} -derive_more = {version = "0.99", features = ["display"]} -thiserror = "1.0" - -[build-dependencies] -flowy-codegen= { path = "../flowy-codegen", features = ["proto_gen"]} - - -[features] -dart = ["flowy-codegen/dart"] \ No newline at end of file diff --git a/shared-lib/flowy-error-code/Flowy.toml b/shared-lib/flowy-error-code/Flowy.toml deleted file mode 100644 index cdd9dd95ff..0000000000 --- a/shared-lib/flowy-error-code/Flowy.toml +++ /dev/null @@ -1,2 +0,0 @@ -# Check out the FlowyConfig (located in flowy_toml.rs) for more details. -proto_input = ["src/code.rs"] diff --git a/shared-lib/flowy-error-code/build.rs b/shared-lib/flowy-error-code/build.rs deleted file mode 100644 index 90fa29ba4c..0000000000 --- a/shared-lib/flowy-error-code/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - flowy_codegen::protobuf_file::gen(env!("CARGO_PKG_NAME")); -} diff --git a/shared-lib/flowy-error-code/src/lib.rs b/shared-lib/flowy-error-code/src/lib.rs deleted file mode 100644 index 4970c163f7..0000000000 --- a/shared-lib/flowy-error-code/src/lib.rs +++ /dev/null @@ -1,4 +0,0 @@ -mod code; -mod protobuf; - -pub use code::*; diff --git a/shared-lib/flowy-error-code/src/resource/mod.rs b/shared-lib/flowy-error-code/src/resource/mod.rs deleted file mode 100644 index da97aad28a..0000000000 --- a/shared-lib/flowy-error-code/src/resource/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -#![cfg_attr(rustfmt, rustfmt::skip)] -// Auto-generated, do not edit -mod model; -pub use model::*; \ No newline at end of file diff --git a/shared-lib/flowy-error-code/src/resource/model/mod.rs b/shared-lib/flowy-error-code/src/resource/model/mod.rs deleted file mode 100644 index 191b80e077..0000000000 --- a/shared-lib/flowy-error-code/src/resource/model/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -#![cfg_attr(rustfmt, rustfmt::skip)] -// Auto-generated, do not edit - -mod code; -pub use code::*; diff --git a/shared-lib/flowy-error-code/src/resource/proto/code.proto b/shared-lib/flowy-error-code/src/resource/proto/code.proto deleted file mode 100644 index ede9b65657..0000000000 --- a/shared-lib/flowy-error-code/src/resource/proto/code.proto +++ /dev/null @@ -1,48 +0,0 @@ -syntax = "proto3"; -enum ErrorCode { - Internal = 0; - UserUnauthorized = 2; - RecordNotFound = 3; - UserIdIsEmpty = 4; - WorkspaceNameInvalid = 100; - WorkspaceIdInvalid = 101; - AppColorStyleInvalid = 102; - WorkspaceDescTooLong = 103; - WorkspaceNameTooLong = 104; - AppIdInvalid = 110; - AppNameInvalid = 111; - ViewNameInvalid = 120; - ViewThumbnailInvalid = 121; - ViewIdInvalid = 122; - ViewDescTooLong = 123; - ViewDataInvalid = 124; - ViewNameTooLong = 125; - ConnectError = 200; - EmailIsEmpty = 300; - EmailFormatInvalid = 301; - EmailAlreadyExists = 302; - PasswordIsEmpty = 303; - PasswordTooLong = 304; - PasswordContainsForbidCharacters = 305; - PasswordFormatInvalid = 306; - PasswordNotMatch = 307; - UserNameTooLong = 308; - UserNameContainForbiddenCharacters = 309; - UserNameIsEmpty = 310; - UserIdInvalid = 311; - UserNotExist = 312; - TextTooLong = 400; - GridIdIsEmpty = 410; - BlockIdIsEmpty = 420; - RowIdIsEmpty = 430; - OptionIdIsEmpty = 431; - FieldIdIsEmpty = 440; - FieldDoesNotExist = 441; - SelectOptionNameIsEmpty = 442; - FieldNotExists = 443; - FieldInvalidOperation = 444; - TypeOptionDataIsEmpty = 450; - InvalidDateTimeFormat = 500; - UnexpectedEmptyString = 999; - InvalidData = 1000; -} diff --git a/shared-lib/flowy-http-model/Cargo.toml b/shared-lib/flowy-http-model/Cargo.toml index 8405cdd5a1..7e63670624 100644 --- a/shared-lib/flowy-http-model/Cargo.toml +++ b/shared-lib/flowy-http-model/Cargo.toml @@ -7,12 +7,9 @@ edition = "2021" [dependencies] bytes = "1.0" -lib-infra = { path = "../lib-infra" } -flowy-derive = { path = "../flowy-derive" } -protobuf = {version = "2.18.0"} md5 = "0.7.0" - -[build-dependencies] -flowy-codegen= { path = "../flowy-codegen", features = ["proto_gen"]} +serde = {versino = "1.0"} +serde_json = { version = "1.0" } +serde_repr = "0.1" diff --git a/shared-lib/flowy-http-model/Flowy.toml b/shared-lib/flowy-http-model/Flowy.toml deleted file mode 100644 index e27d1eaf3d..0000000000 --- a/shared-lib/flowy-http-model/Flowy.toml +++ /dev/null @@ -1,2 +0,0 @@ -# Check out the FlowyConfig (located in flowy_toml.rs) for more details. -proto_input = ["src/entities"] diff --git a/shared-lib/flowy-http-model/build.rs b/shared-lib/flowy-http-model/build.rs deleted file mode 100644 index 90fa29ba4c..0000000000 --- a/shared-lib/flowy-http-model/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - flowy_codegen::protobuf_file::gen(env!("CARGO_PKG_NAME")); -} diff --git a/shared-lib/flowy-http-model/src/entities/document.rs b/shared-lib/flowy-http-model/src/entities/document.rs index da19023887..6dbf1cf2d1 100644 --- a/shared-lib/flowy-http-model/src/entities/document.rs +++ b/shared-lib/flowy-http-model/src/entities/document.rs @@ -1,31 +1,21 @@ -use crate::entities::revision::{RepeatedRevision, Revision}; -use flowy_derive::ProtoBuf; +use crate::revision::Revision; +use serde::{Deserialize, Serialize}; -#[derive(ProtoBuf, Default, Debug, Clone)] +#[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct CreateDocumentParams { - #[pb(index = 1)] pub doc_id: String, - - #[pb(index = 2)] - pub revisions: RepeatedRevision, + pub revisions: Vec, } -#[derive(ProtoBuf, Default, Debug, Clone, Eq, PartialEq)] -pub struct DocumentPayloadPB { - #[pb(index = 1)] +#[derive(Serialize, Deserialize, Default, Debug, Clone, Eq, PartialEq)] +pub struct DocumentPayload { pub doc_id: String, - - #[pb(index = 2)] pub data: Vec, - - #[pb(index = 3)] pub rev_id: i64, - - #[pb(index = 4)] pub base_rev_id: i64, } -impl std::convert::TryFrom for DocumentPayloadPB { +impl std::convert::TryFrom for DocumentPayload { type Error = String; fn try_from(revision: Revision) -> Result { @@ -33,7 +23,7 @@ impl std::convert::TryFrom for DocumentPayloadPB { return Err("Revision's rev_id should be 0 when creating the document".to_string()); } - Ok(DocumentPayloadPB { + Ok(DocumentPayload { doc_id: revision.object_id, data: revision.bytes, rev_id: revision.rev_id, @@ -42,40 +32,36 @@ impl std::convert::TryFrom for DocumentPayloadPB { } } -#[derive(ProtoBuf, Default, Debug, Clone)] +#[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct ResetDocumentParams { - #[pb(index = 1)] pub doc_id: String, - - #[pb(index = 2)] - pub revisions: RepeatedRevision, + pub revisions: Vec, } -#[derive(ProtoBuf, Default, Debug, Clone)] -pub struct DocumentIdPB { - #[pb(index = 1)] +#[derive(Serialize, Deserialize, Default, Debug, Clone)] +pub struct DocumentId { pub value: String, } -impl AsRef for DocumentIdPB { +impl AsRef for DocumentId { fn as_ref(&self) -> &str { &self.value } } -impl std::convert::From for DocumentIdPB { +impl std::convert::From for DocumentId { fn from(value: String) -> Self { - DocumentIdPB { value } + DocumentId { value } } } -impl std::convert::From for String { - fn from(block_id: DocumentIdPB) -> Self { +impl std::convert::From for String { + fn from(block_id: DocumentId) -> Self { block_id.value } } -impl std::convert::From<&String> for DocumentIdPB { +impl std::convert::From<&String> for DocumentId { fn from(s: &String) -> Self { - DocumentIdPB { value: s.to_owned() } + DocumentId { value: s.to_owned() } } } diff --git a/shared-lib/flowy-http-model/src/entities/folder.rs b/shared-lib/flowy-http-model/src/entities/folder.rs index 1f7ecd0b60..5e85360c79 100644 --- a/shared-lib/flowy-http-model/src/entities/folder.rs +++ b/shared-lib/flowy-http-model/src/entities/folder.rs @@ -1,16 +1,9 @@ -use flowy_derive::ProtoBuf; +use serde::{Deserialize, Serialize}; -#[derive(ProtoBuf, Default, Debug, Clone, Eq, PartialEq)] +#[derive(Serialize, Deserialize, Default, Debug, Clone, Eq, PartialEq)] pub struct FolderInfo { - #[pb(index = 1)] pub folder_id: String, - - #[pb(index = 2)] pub text: String, - - #[pb(index = 3)] pub rev_id: i64, - - #[pb(index = 4)] pub base_rev_id: i64, } diff --git a/shared-lib/flowy-http-model/src/entities/mod.rs b/shared-lib/flowy-http-model/src/entities/mod.rs index 649ee1bbaa..93e6431dd0 100644 --- a/shared-lib/flowy-http-model/src/entities/mod.rs +++ b/shared-lib/flowy-http-model/src/entities/mod.rs @@ -1,4 +1,6 @@ pub mod document; pub mod folder; -pub mod revision; -pub mod ws_data; + +pub use crate::ws_data::*; +pub use document::*; +pub use folder::*; diff --git a/shared-lib/flowy-http-model/src/entities/ws_data.rs b/shared-lib/flowy-http-model/src/entities/ws_data.rs deleted file mode 100644 index ee8841c325..0000000000 --- a/shared-lib/flowy-http-model/src/entities/ws_data.rs +++ /dev/null @@ -1,139 +0,0 @@ -use crate::entities::revision::{RepeatedRevision, RevId, Revision, RevisionRange}; -use bytes::Bytes; -use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; -use std::convert::TryInto; - -#[derive(Debug, Clone, ProtoBuf_Enum, Eq, PartialEq, Hash)] -pub enum ClientRevisionWSDataType { - ClientPushRev = 0, - ClientPing = 1, -} - -// impl ClientRevisionWSDataType { -// pub fn data(&self, bytes: Bytes) -> Result -// where -// T: TryFrom, -// { -// T::try_from(bytes) -// } -// } - -impl Default for ClientRevisionWSDataType { - fn default() -> Self { - ClientRevisionWSDataType::ClientPushRev - } -} - -#[derive(ProtoBuf, Default, Debug, Clone)] -pub struct ClientRevisionWSData { - #[pb(index = 1)] - pub object_id: String, - - #[pb(index = 2)] - pub ty: ClientRevisionWSDataType, - - #[pb(index = 3)] - pub revisions: RepeatedRevision, - - #[pb(index = 4)] - pub data_id: String, -} - -impl ClientRevisionWSData { - pub fn from_revisions(object_id: &str, revisions: Vec) -> Self { - let rev_id = match revisions.first() { - None => 0, - Some(revision) => revision.rev_id, - }; - - Self { - object_id: object_id.to_owned(), - ty: ClientRevisionWSDataType::ClientPushRev, - revisions: RepeatedRevision::new(revisions), - data_id: rev_id.to_string(), - } - } - - pub fn ping(object_id: &str, rev_id: i64) -> Self { - Self { - object_id: object_id.to_owned(), - ty: ClientRevisionWSDataType::ClientPing, - revisions: RepeatedRevision::empty(), - data_id: rev_id.to_string(), - } - } - - pub fn id(&self) -> String { - self.data_id.clone() - } -} - -#[derive(Debug, Clone, ProtoBuf_Enum, Eq, PartialEq, Hash)] -pub enum ServerRevisionWSDataType { - ServerAck = 0, - ServerPushRev = 1, - ServerPullRev = 2, - UserConnect = 3, -} - -impl Default for ServerRevisionWSDataType { - fn default() -> Self { - ServerRevisionWSDataType::ServerPushRev - } -} - -#[derive(ProtoBuf, Default, Debug, Clone)] -pub struct ServerRevisionWSData { - #[pb(index = 1)] - pub object_id: String, - - #[pb(index = 2)] - pub ty: ServerRevisionWSDataType, - - #[pb(index = 3)] - pub data: Vec, -} - -pub struct ServerRevisionWSDataBuilder(); -impl ServerRevisionWSDataBuilder { - pub fn build_push_message(object_id: &str, repeated_revision: RepeatedRevision) -> ServerRevisionWSData { - let bytes: Bytes = repeated_revision.try_into().unwrap(); - ServerRevisionWSData { - object_id: object_id.to_string(), - ty: ServerRevisionWSDataType::ServerPushRev, - data: bytes.to_vec(), - } - } - - pub fn build_pull_message(object_id: &str, range: RevisionRange) -> ServerRevisionWSData { - let bytes: Bytes = range.try_into().unwrap(); - ServerRevisionWSData { - object_id: object_id.to_string(), - ty: ServerRevisionWSDataType::ServerPullRev, - data: bytes.to_vec(), - } - } - - pub fn build_ack_message(object_id: &str, rev_id: i64) -> ServerRevisionWSData { - let rev_id: RevId = rev_id.into(); - let bytes: Bytes = rev_id.try_into().unwrap(); - ServerRevisionWSData { - object_id: object_id.to_string(), - ty: ServerRevisionWSDataType::ServerAck, - data: bytes.to_vec(), - } - } -} - -#[derive(ProtoBuf, Default, Debug, Clone)] -pub struct NewDocumentUser { - #[pb(index = 1)] - pub user_id: String, - - #[pb(index = 2)] - pub doc_id: String, - - // revision_data: the latest rev_id of the document. - #[pb(index = 3)] - pub revision_data: Vec, -} diff --git a/shared-lib/flowy-http-model/src/lib.rs b/shared-lib/flowy-http-model/src/lib.rs index 7e2586293c..d62dc9a03f 100644 --- a/shared-lib/flowy-http-model/src/lib.rs +++ b/shared-lib/flowy-http-model/src/lib.rs @@ -1,6 +1,5 @@ +pub mod entities; +pub mod revision; pub mod util; - -pub mod protobuf; - -mod entities; +pub mod ws_data; pub use entities::*; diff --git a/shared-lib/flowy-http-model/src/entities/revision.rs b/shared-lib/flowy-http-model/src/revision.rs similarity index 57% rename from shared-lib/flowy-http-model/src/entities/revision.rs rename to shared-lib/flowy-http-model/src/revision.rs index 5cdbd02267..e068fe10ce 100644 --- a/shared-lib/flowy-http-model/src/entities/revision.rs +++ b/shared-lib/flowy-http-model/src/revision.rs @@ -1,23 +1,14 @@ use crate::util::md5; use bytes::Bytes; -use flowy_derive::ProtoBuf; +use serde::{Deserialize, Serialize}; use std::{convert::TryFrom, fmt::Formatter, ops::RangeInclusive}; -#[derive(PartialEq, Eq, Clone, Default, ProtoBuf)] +#[derive(PartialEq, Eq, Clone, Default, Serialize, Deserialize)] pub struct Revision { - #[pb(index = 1)] pub base_rev_id: i64, - - #[pb(index = 2)] pub rev_id: i64, - - #[pb(index = 3)] pub bytes: Vec, - - #[pb(index = 4)] pub md5: String, - - #[pb(index = 5)] pub object_id: String, } @@ -28,6 +19,14 @@ impl std::convert::From> for Revision { } } +impl std::convert::TryFrom for Revision { + type Error = serde_json::Error; + + fn try_from(bytes: Bytes) -> Result { + serde_json::from_slice(&bytes) + } +} + impl Revision { pub fn new>(object_id: &str, base_rev_id: i64, rev_id: i64, bytes: Bytes, md5: T) -> Revision { let object_id = object_id.to_owned(); @@ -75,89 +74,9 @@ impl std::fmt::Debug for Revision { } } -#[derive(PartialEq, Debug, Default, ProtoBuf, Clone)] -pub struct RepeatedRevision { - #[pb(index = 1)] - items: Vec, -} - -impl std::ops::Deref for RepeatedRevision { - type Target = Vec; - - fn deref(&self) -> &Self::Target { - &self.items - } -} - -impl std::ops::DerefMut for RepeatedRevision { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.items - } -} - -impl std::convert::From for RepeatedRevision { - fn from(revision: Revision) -> Self { - Self { items: vec![revision] } - } -} - -impl std::convert::From> for RepeatedRevision { - fn from(revisions: Vec) -> Self { - Self { items: revisions } - } -} - -impl RepeatedRevision { - pub fn new(mut items: Vec) -> Self { - items.sort_by(|a, b| a.rev_id.cmp(&b.rev_id)); - Self { items } - } - - pub fn empty() -> Self { - RepeatedRevision { items: vec![] } - } - - pub fn into_inner(self) -> Vec { - self.items - } -} - -#[derive(Clone, Debug, ProtoBuf, Default)] -pub struct RevId { - #[pb(index = 1)] - pub value: i64, -} - -impl AsRef for RevId { - fn as_ref(&self) -> &i64 { - &self.value - } -} - -impl std::convert::From for i64 { - fn from(rev_id: RevId) -> Self { - rev_id.value - } -} - -impl std::convert::From for RevId { - 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)) - } -} - -#[derive(Debug, Clone, Default, ProtoBuf)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct RevisionRange { - #[pb(index = 1)] pub start: i64, - - #[pb(index = 2)] pub end: i64, } diff --git a/shared-lib/flowy-http-model/src/ws_data.rs b/shared-lib/flowy-http-model/src/ws_data.rs new file mode 100644 index 0000000000..56a9bab56d --- /dev/null +++ b/shared-lib/flowy-http-model/src/ws_data.rs @@ -0,0 +1,127 @@ +use crate::revision::{Revision, RevisionRange}; +use bytes::Bytes; +use serde::{Deserialize, Serialize}; +use serde_repr::*; + +#[derive(Debug, Clone, Serialize_repr, Deserialize_repr, Eq, PartialEq, Hash)] +#[repr(u8)] +pub enum ClientRevisionWSDataType { + ClientPushRev = 0, + ClientPing = 1, +} + +impl Default for ClientRevisionWSDataType { + fn default() -> Self { + ClientRevisionWSDataType::ClientPushRev + } +} + +#[derive(Serialize, Deserialize, Default, Debug, Clone)] +pub struct ClientRevisionWSData { + pub object_id: String, + pub ty: ClientRevisionWSDataType, + pub revisions: Vec, + pub rev_id: i64, +} + +impl ClientRevisionWSData { + pub fn from_revisions(object_id: &str, revisions: Vec) -> Self { + let rev_id = match revisions.first() { + None => 0, + Some(revision) => revision.rev_id, + }; + + Self { + object_id: object_id.to_owned(), + ty: ClientRevisionWSDataType::ClientPushRev, + revisions, + rev_id, + } + } + + pub fn ping(object_id: &str, rev_id: i64) -> Self { + Self { + object_id: object_id.to_owned(), + ty: ClientRevisionWSDataType::ClientPing, + revisions: vec![], + rev_id: rev_id, + } + } +} + +impl std::convert::TryFrom for ClientRevisionWSData { + type Error = serde_json::Error; + + fn try_from(bytes: Bytes) -> Result { + serde_json::from_slice(&bytes) + } +} + +impl std::convert::TryFrom for Bytes { + type Error = serde_json::Error; + + fn try_from(bytes: ClientRevisionWSData) -> Result { + serde_json::to_vec(&bytes).map(|bytes| Bytes::from(bytes)) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum WSRevisionPayload { + ServerAck { rev_id: i64 }, + ServerPushRev { revisions: Vec }, + ServerPullRev { range: RevisionRange }, + UserConnect { user: NewDocumentUser }, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct ServerRevisionWSData { + pub object_id: String, + pub payload: WSRevisionPayload, +} + +impl std::convert::TryFrom for ServerRevisionWSData { + type Error = serde_json::Error; + + fn try_from(bytes: Bytes) -> Result { + serde_json::from_slice(&bytes) + } +} + +impl std::convert::TryFrom for Bytes { + type Error = serde_json::Error; + + fn try_from(bytes: ServerRevisionWSData) -> Result { + serde_json::to_vec(&bytes).map(|bytes| Bytes::from(bytes)) + } +} + +pub struct ServerRevisionWSDataBuilder(); +impl ServerRevisionWSDataBuilder { + pub fn build_push_message(object_id: &str, revisions: Vec) -> ServerRevisionWSData { + ServerRevisionWSData { + object_id: object_id.to_string(), + payload: WSRevisionPayload::ServerPushRev { revisions }, + } + } + + pub fn build_pull_message(object_id: &str, range: RevisionRange) -> ServerRevisionWSData { + ServerRevisionWSData { + object_id: object_id.to_string(), + payload: WSRevisionPayload::ServerPullRev { range }, + } + } + + pub fn build_ack_message(object_id: &str, rev_id: i64) -> ServerRevisionWSData { + ServerRevisionWSData { + object_id: object_id.to_string(), + payload: WSRevisionPayload::ServerAck { rev_id }, + } + } +} + +#[derive(Serialize, Deserialize, Default, Debug, Clone)] +pub struct NewDocumentUser { + pub user_id: String, + pub doc_id: String, + pub latest_rev_id: i64, +} diff --git a/shared-lib/grid-rev-model/Cargo.toml b/shared-lib/grid-rev-model/Cargo.toml index edcee680ec..786e59171c 100644 --- a/shared-lib/grid-rev-model/Cargo.toml +++ b/shared-lib/grid-rev-model/Cargo.toml @@ -11,5 +11,5 @@ serde = { version = "1.0", features = ["derive", "rc"] } serde_json = {version = "1.0"} serde_repr = "0.1" nanoid = "0.4.0" -flowy-error-code = { path = "../flowy-error-code"} +#flowy-error-code = { path = "../flowy-error-code"} indexmap = {version = "1.9.1", features = ["serde"]} diff --git a/shared-lib/lib-ws/Cargo.toml b/shared-lib/lib-ws/Cargo.toml index b57c98d836..4c41097875 100644 --- a/shared-lib/lib-ws/Cargo.toml +++ b/shared-lib/lib-ws/Cargo.toml @@ -6,7 +6,9 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -flowy-derive = { path = "../flowy-derive" } +serde_repr = "0.1" +serde = "1.0" +serde_json = {version = "1.0"} lib-infra = { path = "../lib-infra" } tokio-tungstenite = "0.15" @@ -27,12 +29,6 @@ strum_macros = "0.21" parking_lot = "0.12.1" dashmap = "5" -[build-dependencies] -flowy-codegen= { path = "../flowy-codegen"} - [dev-dependencies] tokio = {version = "1", features = ["full"]} -env_logger = "0.8.2" - -[features] -dart = ["flowy-codegen/dart"] \ No newline at end of file +env_logger = "0.8.2" \ No newline at end of file diff --git a/shared-lib/lib-ws/Flowy.toml b/shared-lib/lib-ws/Flowy.toml deleted file mode 100644 index a1f5aad68d..0000000000 --- a/shared-lib/lib-ws/Flowy.toml +++ /dev/null @@ -1,2 +0,0 @@ -# Check out the FlowyConfig (located in flowy_toml.rs) for more details. -proto_input = ["src/errors.rs", "src/msg.rs"] diff --git a/shared-lib/lib-ws/build.rs b/shared-lib/lib-ws/build.rs deleted file mode 100644 index 90fa29ba4c..0000000000 --- a/shared-lib/lib-ws/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - flowy_codegen::protobuf_file::gen(env!("CARGO_PKG_NAME")); -} diff --git a/shared-lib/lib-ws/src/errors.rs b/shared-lib/lib-ws/src/errors.rs index 318b8fa7de..1a17137ecd 100644 --- a/shared-lib/lib-ws/src/errors.rs +++ b/shared-lib/lib-ws/src/errors.rs @@ -1,17 +1,15 @@ -use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; use futures_channel::mpsc::TrySendError; +use serde::{Deserialize, Serialize}; +use serde_repr::*; use std::fmt::Debug; use strum_macros::Display; use tokio::sync::oneshot::error::RecvError; use tokio_tungstenite::tungstenite::{http::StatusCode, Message}; use url::ParseError; -#[derive(Debug, Default, Clone, ProtoBuf)] +#[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct WSError { - #[pb(index = 1)] pub code: ErrorCode, - - #[pb(index = 2)] pub msg: String, } @@ -53,7 +51,8 @@ where WSError::internal().context(e) } -#[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] +#[derive(Debug, Clone, Serialize_repr, Deserialize_repr, Display, PartialEq, Eq)] +#[repr(u8)] pub enum ErrorCode { InternalError = 0, UnsupportedMessage = 1, diff --git a/shared-lib/lib-ws/src/lib.rs b/shared-lib/lib-ws/src/lib.rs index 65e5213152..d1be0a9f37 100644 --- a/shared-lib/lib-ws/src/lib.rs +++ b/shared-lib/lib-ws/src/lib.rs @@ -1,7 +1,6 @@ pub mod connect; pub mod errors; mod msg; -pub mod protobuf; mod ws; pub use msg::*; diff --git a/shared-lib/lib-ws/src/msg.rs b/shared-lib/lib-ws/src/msg.rs index 51f0a76607..33935ceaf8 100644 --- a/shared-lib/lib-ws/src/msg.rs +++ b/shared-lib/lib-ws/src/msg.rs @@ -1,19 +1,26 @@ -use bytes::Bytes; -use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; -use std::convert::TryInto; +use serde::{Deserialize, Serialize}; +use serde_repr::*; use tokio_tungstenite::tungstenite::Message as TokioMessage; -#[derive(ProtoBuf, Debug, Clone, Default)] +#[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct WebSocketRawMessage { - #[pb(index = 1)] pub channel: WSChannel, - - #[pb(index = 2)] pub data: Vec, } +impl WebSocketRawMessage { + pub fn to_bytes(&self) -> Vec { + serde_json::to_vec(&self).unwrap_or_default() + } + + pub fn from_bytes>(bytes: T) -> Self { + serde_json::from_slice(bytes.as_ref()).unwrap_or_default() + } +} + // The lib-ws crate should not contain business logic.So WSChannel should be removed into another place. -#[derive(ProtoBuf_Enum, Debug, Clone, Eq, PartialEq, Hash)] +#[derive(Serialize_repr, Deserialize_repr, Debug, Clone, Eq, PartialEq, Hash)] +#[repr(u8)] pub enum WSChannel { Document = 0, Folder = 1, @@ -38,13 +45,6 @@ impl ToString for WSChannel { impl std::convert::From for TokioMessage { fn from(msg: WebSocketRawMessage) -> Self { - let result: Result = msg.try_into(); - match result { - Ok(bytes) => TokioMessage::Binary(bytes.to_vec()), - Err(e) => { - log::error!("WsMessage serialize error: {:?}", e); - TokioMessage::Binary(vec![]) - } - } + TokioMessage::Binary(msg.to_bytes()) } } diff --git a/shared-lib/lib-ws/src/ws.rs b/shared-lib/lib-ws/src/ws.rs index adbb49f9ac..f66e477449 100644 --- a/shared-lib/lib-ws/src/ws.rs +++ b/shared-lib/lib-ws/src/ws.rs @@ -4,14 +4,12 @@ use crate::{ errors::WSError, WSChannel, WebSocketRawMessage, }; -use bytes::Bytes; use dashmap::DashMap; use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender}; use futures_core::{ready, Stream}; use lib_infra::retry::{Action, FixedInterval, Retry}; use pin_project::pin_project; use std::{ - convert::TryFrom, fmt::Formatter, future::Future, pin::Pin, @@ -206,15 +204,10 @@ impl WSHandlerFuture { } fn handle_binary_message(&self, bytes: Vec) { - let bytes = Bytes::from(bytes); - match WebSocketRawMessage::try_from(bytes) { - Ok(message) => match self.handlers.get(&message.channel) { - None => log::error!("Can't find any handler for message: {:?}", message), - Some(handler) => handler.receive_message(message.clone()), - }, - Err(e) => { - log::error!("Deserialize binary ws message failed: {:?}", e); - } + let msg = WebSocketRawMessage::from_bytes(bytes); + match self.handlers.get(&msg.channel) { + None => log::error!("Can't find any handler for message: {:?}", msg), + Some(handler) => handler.receive_message(msg), } } }