diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 2da79b9ed7..6cba8fa609 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -1151,6 +1151,15 @@ dependencies = [ "backtrace", ] +[[package]] +name = "error-code" +version = "0.1.0" +dependencies = [ + "derive_more", + "flowy-derive", + "protobuf", +] + [[package]] name = "eyre" version = "0.6.5" @@ -1241,6 +1250,7 @@ dependencies = [ "flowy-database", "flowy-derive", "flowy-document", + "flowy-error", "flowy-net", "futures", "futures-core", @@ -1267,6 +1277,7 @@ dependencies = [ "bytes", "chrono", "derive_more", + "error-code", "flowy-collaboration", "flowy-derive", "log", @@ -1317,6 +1328,7 @@ dependencies = [ "flowy-collaboration", "flowy-database", "flowy-derive", + "flowy-error", "futures", "futures-core", "futures-util", @@ -1343,11 +1355,18 @@ dependencies = [ name = "flowy-error" version = "0.1.0" dependencies = [ + "backend-service", "bytes", - "derive_more", + "error-code", + "flowy-collaboration", + "flowy-database", "flowy-derive", "lib-dispatch", + "lib-ot", + "lib-sqlite", "protobuf", + "r2d2", + "serde_json", ] [[package]] @@ -1431,6 +1450,7 @@ dependencies = [ "diesel_derives", "flowy-database", "flowy-derive", + "flowy-error", "flowy-net", "flowy-user-infra", "futures-core", @@ -1460,6 +1480,7 @@ version = "0.1.0" dependencies = [ "bytes", "derive_more", + "error-code", "fancy-regex", "flowy-derive", "lazy_static", diff --git a/backend/src/services/doc/ws_actor.rs b/backend/src/services/doc/ws_actor.rs index 85b196dfb7..df93edaba5 100644 --- a/backend/src/services/doc/ws_actor.rs +++ b/backend/src/services/doc/ws_actor.rs @@ -8,7 +8,7 @@ use crate::{ use actix_rt::task::spawn_blocking; use actix_web::web::Data; use async_stream::stream; -use backend_service::errors::{internal_error, Result as DocResult, ServerError}; +use backend_service::errors::{internal_error, Result, ServerError}; use flowy_collaboration::{ core::sync::ServerDocManager, protobuf::{WsDataType, WsDocumentData}, @@ -23,7 +23,7 @@ pub enum DocWsMsg { ClientData { client_data: WsClientData, pool: Data, - ret: oneshot::Sender>, + ret: oneshot::Sender>, }, } @@ -66,11 +66,11 @@ impl DocWsActor { } } - async fn handle_client_data(&self, client_data: WsClientData, pool: Data) -> DocResult<()> { + async fn handle_client_data(&self, client_data: WsClientData, pool: Data) -> Result<()> { let WsClientData { user, socket, data } = client_data; let document_data = spawn_blocking(move || { let document_data: WsDocumentData = parse_from_bytes(&data)?; - DocResult::Ok(document_data) + Result::Ok(document_data) }) .await .map_err(internal_error)??; @@ -91,11 +91,11 @@ impl DocWsActor { socket: Socket, data: Vec, pg_pool: Data, - ) -> DocResult<()> { + ) -> Result<()> { let mut revision_pb = spawn_blocking(move || { let revision: Revision = parse_from_bytes(&data)?; let _ = verify_md5(&revision)?; - DocResult::Ok(revision) + Result::Ok(revision) }) .await .map_err(internal_error)??; @@ -116,7 +116,7 @@ impl DocWsActor { } } -fn verify_md5(revision: &Revision) -> DocResult<()> { +fn verify_md5(revision: &Revision) -> Result<()> { if md5(&revision.delta_data) != revision.md5 { return Err(ServerError::internal().context("Revision md5 not match")); } 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 f67bcae063..56452bf338 100644 --- a/frontend/app_flowy/lib/user/application/sign_in_bloc.dart +++ b/frontend/app_flowy/lib/user/application/sign_in_bloc.dart @@ -1,7 +1,7 @@ import 'package:app_flowy/user/domain/i_auth.dart'; import 'package:dartz/dartz.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile, ErrorCode; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -40,7 +40,7 @@ class SignInBloc extends Bloc { ); } - SignInState stateFromCode(UserError error) { + SignInState stateFromCode(FlowyError error) { switch (ErrorCode.valueOf(error.code)!) { case ErrorCode.EmailFormatInvalid: return state.copyWith(isSubmitting: false, emailError: some(error.msg), passwordError: none()); @@ -67,7 +67,7 @@ abstract class SignInState with _$SignInState { required bool isSubmitting, required Option passwordError, required Option emailError, - required Option> successOrFail, + required Option> successOrFail, }) = _SignInState; factory SignInState.initial() => SignInState( diff --git a/frontend/app_flowy/lib/user/application/sign_in_bloc.freezed.dart b/frontend/app_flowy/lib/user/application/sign_in_bloc.freezed.dart index 2f557809d5..29b67d3fa7 100644 --- a/frontend/app_flowy/lib/user/application/sign_in_bloc.freezed.dart +++ b/frontend/app_flowy/lib/user/application/sign_in_bloc.freezed.dart @@ -519,7 +519,7 @@ class _$SignInStateTearOff { required bool isSubmitting, required Option passwordError, required Option emailError, - required Option> successOrFail}) { + required Option> successOrFail}) { return _SignInState( email: email, password: password, @@ -541,7 +541,7 @@ mixin _$SignInState { bool get isSubmitting => throw _privateConstructorUsedError; Option get passwordError => throw _privateConstructorUsedError; Option get emailError => throw _privateConstructorUsedError; - Option> get successOrFail => + Option> get successOrFail => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -560,7 +560,7 @@ abstract class $SignInStateCopyWith<$Res> { bool isSubmitting, Option passwordError, Option emailError, - Option> successOrFail}); + Option> successOrFail}); } /// @nodoc @@ -604,7 +604,7 @@ class _$SignInStateCopyWithImpl<$Res> implements $SignInStateCopyWith<$Res> { successOrFail: successOrFail == freezed ? _value.successOrFail : successOrFail // ignore: cast_nullable_to_non_nullable - as Option>, + as Option>, )); } } @@ -622,7 +622,7 @@ abstract class _$SignInStateCopyWith<$Res> bool isSubmitting, Option passwordError, Option emailError, - Option> successOrFail}); + Option> successOrFail}); } /// @nodoc @@ -668,7 +668,7 @@ class __$SignInStateCopyWithImpl<$Res> extends _$SignInStateCopyWithImpl<$Res> successOrFail: successOrFail == freezed ? _value.successOrFail : successOrFail // ignore: cast_nullable_to_non_nullable - as Option>, + as Option>, )); } } @@ -695,7 +695,7 @@ class _$_SignInState implements _SignInState { @override final Option emailError; @override - final Option> successOrFail; + final Option> successOrFail; @override String toString() { @@ -748,7 +748,7 @@ abstract class _SignInState implements SignInState { required bool isSubmitting, required Option passwordError, required Option emailError, - required Option> successOrFail}) = + required Option> successOrFail}) = _$_SignInState; @override @@ -762,7 +762,7 @@ abstract class _SignInState implements SignInState { @override Option get emailError => throw _privateConstructorUsedError; @override - Option> get successOrFail => + Option> get successOrFail => throw _privateConstructorUsedError; @override @JsonKey(ignore: true) 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 0271de7309..a0ade691ea 100644 --- a/frontend/app_flowy/lib/user/application/sign_up_bloc.dart +++ b/frontend/app_flowy/lib/user/application/sign_up_bloc.dart @@ -2,7 +2,7 @@ import 'package:app_flowy/user/domain/i_auth.dart'; import 'package:dartz/dartz.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile, ErrorCode; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:app_flowy/generated/locale_keys.g.dart'; @@ -78,7 +78,7 @@ class SignUpBloc extends Bloc { ); } - SignUpState stateFromCode(UserError error) { + SignUpState stateFromCode(FlowyError error) { switch (ErrorCode.valueOf(error.code)!) { case ErrorCode.EmailFormatInvalid: return state.copyWith( @@ -118,7 +118,7 @@ class SignUpState with _$SignUpState { required Option passwordError, required Option repeatPasswordError, required Option emailError, - required Option> successOrFail, + required Option> successOrFail, }) = _SignUpState; factory SignUpState.initial() => SignUpState( diff --git a/frontend/app_flowy/lib/user/application/sign_up_bloc.freezed.dart b/frontend/app_flowy/lib/user/application/sign_up_bloc.freezed.dart index ec7b4d9dac..ec6c377fd1 100644 --- a/frontend/app_flowy/lib/user/application/sign_up_bloc.freezed.dart +++ b/frontend/app_flowy/lib/user/application/sign_up_bloc.freezed.dart @@ -707,7 +707,7 @@ class _$SignUpStateTearOff { required Option passwordError, required Option repeatPasswordError, required Option emailError, - required Option> successOrFail}) { + required Option> successOrFail}) { return _SignUpState( email: email, password: password, @@ -733,7 +733,7 @@ mixin _$SignUpState { Option get passwordError => throw _privateConstructorUsedError; Option get repeatPasswordError => throw _privateConstructorUsedError; Option get emailError => throw _privateConstructorUsedError; - Option> get successOrFail => + Option> get successOrFail => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -754,7 +754,7 @@ abstract class $SignUpStateCopyWith<$Res> { Option passwordError, Option repeatPasswordError, Option emailError, - Option> successOrFail}); + Option> successOrFail}); } /// @nodoc @@ -808,7 +808,7 @@ class _$SignUpStateCopyWithImpl<$Res> implements $SignUpStateCopyWith<$Res> { successOrFail: successOrFail == freezed ? _value.successOrFail : successOrFail // ignore: cast_nullable_to_non_nullable - as Option>, + as Option>, )); } } @@ -828,7 +828,7 @@ abstract class _$SignUpStateCopyWith<$Res> Option passwordError, Option repeatPasswordError, Option emailError, - Option> successOrFail}); + Option> successOrFail}); } /// @nodoc @@ -884,7 +884,7 @@ class __$SignUpStateCopyWithImpl<$Res> extends _$SignUpStateCopyWithImpl<$Res> successOrFail: successOrFail == freezed ? _value.successOrFail : successOrFail // ignore: cast_nullable_to_non_nullable - as Option>, + as Option>, )); } } @@ -917,7 +917,7 @@ class _$_SignUpState implements _SignUpState { @override final Option emailError; @override - final Option> successOrFail; + final Option> successOrFail; @override String toString() { @@ -980,7 +980,7 @@ abstract class _SignUpState implements SignUpState { required Option passwordError, required Option repeatPasswordError, required Option emailError, - required Option> successOrFail}) = + required Option> successOrFail}) = _$_SignUpState; @override @@ -998,7 +998,7 @@ abstract class _SignUpState implements SignUpState { @override Option get emailError => throw _privateConstructorUsedError; @override - Option> get successOrFail => + Option> get successOrFail => throw _privateConstructorUsedError; @override @JsonKey(ignore: true) diff --git a/frontend/app_flowy/lib/user/domain/auth_state.dart b/frontend/app_flowy/lib/user/domain/auth_state.dart index 6dc7d08e33..37916fbf7a 100644 --- a/frontend/app_flowy/lib/user/domain/auth_state.dart +++ b/frontend/app_flowy/lib/user/domain/auth_state.dart @@ -1,11 +1,11 @@ import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'auth_state.freezed.dart'; @freezed abstract class AuthState with _$AuthState { const factory AuthState.authenticated(UserProfile userProfile) = Authenticated; - const factory AuthState.unauthenticated(UserError error) = Unauthenticated; + const factory AuthState.unauthenticated(FlowyError error) = Unauthenticated; const factory AuthState.initial() = _Initial; } diff --git a/frontend/app_flowy/lib/user/domain/auth_state.freezed.dart b/frontend/app_flowy/lib/user/domain/auth_state.freezed.dart index 85e8fc3822..cf5aaa25c7 100644 --- a/frontend/app_flowy/lib/user/domain/auth_state.freezed.dart +++ b/frontend/app_flowy/lib/user/domain/auth_state.freezed.dart @@ -23,7 +23,7 @@ class _$AuthStateTearOff { ); } - Unauthenticated unauthenticated(UserError error) { + Unauthenticated unauthenticated(FlowyError error) { return Unauthenticated( error, ); @@ -42,21 +42,21 @@ mixin _$AuthState { @optionalTypeArgs TResult when({ required TResult Function(UserProfile userProfile) authenticated, - required TResult Function(UserError error) unauthenticated, + required TResult Function(FlowyError error) unauthenticated, required TResult Function() initial, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull({ TResult Function(UserProfile userProfile)? authenticated, - TResult Function(UserError error)? unauthenticated, + TResult Function(FlowyError error)? unauthenticated, TResult Function()? initial, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen({ TResult Function(UserProfile userProfile)? authenticated, - TResult Function(UserError error)? unauthenticated, + TResult Function(FlowyError error)? unauthenticated, TResult Function()? initial, required TResult orElse(), }) => @@ -166,7 +166,7 @@ class _$Authenticated implements Authenticated { @optionalTypeArgs TResult when({ required TResult Function(UserProfile userProfile) authenticated, - required TResult Function(UserError error) unauthenticated, + required TResult Function(FlowyError error) unauthenticated, required TResult Function() initial, }) { return authenticated(userProfile); @@ -176,7 +176,7 @@ class _$Authenticated implements Authenticated { @optionalTypeArgs TResult? whenOrNull({ TResult Function(UserProfile userProfile)? authenticated, - TResult Function(UserError error)? unauthenticated, + TResult Function(FlowyError error)? unauthenticated, TResult Function()? initial, }) { return authenticated?.call(userProfile); @@ -186,7 +186,7 @@ class _$Authenticated implements Authenticated { @optionalTypeArgs TResult maybeWhen({ TResult Function(UserProfile userProfile)? authenticated, - TResult Function(UserError error)? unauthenticated, + TResult Function(FlowyError error)? unauthenticated, TResult Function()? initial, required TResult orElse(), }) { @@ -245,7 +245,7 @@ abstract class $UnauthenticatedCopyWith<$Res> { factory $UnauthenticatedCopyWith( Unauthenticated value, $Res Function(Unauthenticated) then) = _$UnauthenticatedCopyWithImpl<$Res>; - $Res call({UserError error}); + $Res call({FlowyError error}); } /// @nodoc @@ -266,7 +266,7 @@ class _$UnauthenticatedCopyWithImpl<$Res> extends _$AuthStateCopyWithImpl<$Res> error == freezed ? _value.error : error // ignore: cast_nullable_to_non_nullable - as UserError, + as FlowyError, )); } } @@ -277,7 +277,7 @@ class _$Unauthenticated implements Unauthenticated { const _$Unauthenticated(this.error); @override - final UserError error; + final FlowyError error; @override String toString() { @@ -305,7 +305,7 @@ class _$Unauthenticated implements Unauthenticated { @optionalTypeArgs TResult when({ required TResult Function(UserProfile userProfile) authenticated, - required TResult Function(UserError error) unauthenticated, + required TResult Function(FlowyError error) unauthenticated, required TResult Function() initial, }) { return unauthenticated(error); @@ -315,7 +315,7 @@ class _$Unauthenticated implements Unauthenticated { @optionalTypeArgs TResult? whenOrNull({ TResult Function(UserProfile userProfile)? authenticated, - TResult Function(UserError error)? unauthenticated, + TResult Function(FlowyError error)? unauthenticated, TResult Function()? initial, }) { return unauthenticated?.call(error); @@ -325,7 +325,7 @@ class _$Unauthenticated implements Unauthenticated { @optionalTypeArgs TResult maybeWhen({ TResult Function(UserProfile userProfile)? authenticated, - TResult Function(UserError error)? unauthenticated, + TResult Function(FlowyError error)? unauthenticated, TResult Function()? initial, required TResult orElse(), }) { @@ -371,9 +371,9 @@ class _$Unauthenticated implements Unauthenticated { } abstract class Unauthenticated implements AuthState { - const factory Unauthenticated(UserError error) = _$Unauthenticated; + const factory Unauthenticated(FlowyError error) = _$Unauthenticated; - UserError get error => throw _privateConstructorUsedError; + FlowyError get error => throw _privateConstructorUsedError; @JsonKey(ignore: true) $UnauthenticatedCopyWith get copyWith => throw _privateConstructorUsedError; @@ -417,7 +417,7 @@ class _$_Initial implements _Initial { @optionalTypeArgs TResult when({ required TResult Function(UserProfile userProfile) authenticated, - required TResult Function(UserError error) unauthenticated, + required TResult Function(FlowyError error) unauthenticated, required TResult Function() initial, }) { return initial(); @@ -427,7 +427,7 @@ class _$_Initial implements _Initial { @optionalTypeArgs TResult? whenOrNull({ TResult Function(UserProfile userProfile)? authenticated, - TResult Function(UserError error)? unauthenticated, + TResult Function(FlowyError error)? unauthenticated, TResult Function()? initial, }) { return initial?.call(); @@ -437,7 +437,7 @@ class _$_Initial implements _Initial { @optionalTypeArgs TResult maybeWhen({ TResult Function(UserProfile userProfile)? authenticated, - TResult Function(UserError error)? unauthenticated, + TResult Function(FlowyError error)? unauthenticated, TResult Function()? initial, required TResult orElse(), }) { diff --git a/frontend/app_flowy/lib/user/domain/i_auth.dart b/frontend/app_flowy/lib/user/domain/i_auth.dart index 3b557616e8..ecece96f3f 100644 --- a/frontend/app_flowy/lib/user/domain/i_auth.dart +++ b/frontend/app_flowy/lib/user/domain/i_auth.dart @@ -1,5 +1,5 @@ import 'package:dartz/dartz.dart'; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/protobuf.dart'; import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile; import 'package:flutter/material.dart'; @@ -14,9 +14,9 @@ class NewUser { } abstract class IAuth { - Future> signIn(String? email, String? password); - Future> signUp(String? name, String? password, String? email); - Future> signOut(); + Future> signIn(String? email, String? password); + Future> signUp(String? name, String? password, String? email); + Future> signOut(); } abstract class IAuthRouter { diff --git a/frontend/app_flowy/lib/user/infrastructure/i_auth_impl.dart b/frontend/app_flowy/lib/user/infrastructure/i_auth_impl.dart index b348d38c77..e94008cfb0 100644 --- a/frontend/app_flowy/lib/user/infrastructure/i_auth_impl.dart +++ b/frontend/app_flowy/lib/user/infrastructure/i_auth_impl.dart @@ -8,7 +8,7 @@ import 'package:flowy_infra_ui/widget/route/animation.dart'; import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile; import 'package:app_flowy/user/domain/i_auth.dart'; import 'package:app_flowy/user/infrastructure/repos/auth_repo.dart'; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/protobuf.dart'; import 'package:flutter/material.dart'; @@ -19,17 +19,17 @@ class AuthImpl extends IAuth { }); @override - Future> signIn(String? email, String? password) { + Future> signIn(String? email, String? password) { return repo.signIn(email: email, password: password); } @override - Future> signUp(String? name, String? password, String? email) { + Future> signUp(String? name, String? password, String? email) { return repo.signUp(name: name, password: password, email: email); } @override - Future> signOut() { + Future> signOut() { return repo.signOut(); } } diff --git a/frontend/app_flowy/lib/user/infrastructure/i_splash_impl.dart b/frontend/app_flowy/lib/user/infrastructure/i_splash_impl.dart index 79e8ce78e3..237b9ad60c 100644 --- a/frontend/app_flowy/lib/user/infrastructure/i_splash_impl.dart +++ b/frontend/app_flowy/lib/user/infrastructure/i_splash_impl.dart @@ -24,8 +24,8 @@ class SplashUserImpl implements ISplashUser { (userProfile) { return AuthState.authenticated(userProfile); }, - (userError) { - return AuthState.unauthenticated(userError); + (FlowyError) { + return AuthState.unauthenticated(FlowyError); }, ); }); diff --git a/frontend/app_flowy/lib/user/infrastructure/repos/auth_repo.dart b/frontend/app_flowy/lib/user/infrastructure/repos/auth_repo.dart index aea044d905..b42a5f7eda 100644 --- a/frontend/app_flowy/lib/user/infrastructure/repos/auth_repo.dart +++ b/frontend/app_flowy/lib/user/infrastructure/repos/auth_repo.dart @@ -1,10 +1,10 @@ import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/dispatch/dispatch.dart'; import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show SignInRequest, SignUpRequest, UserProfile; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; class AuthRepository { - Future> signIn({required String? email, required String? password}) { + Future> signIn({required String? email, required String? password}) { // final request = SignInRequest.create() ..email = email ?? '' @@ -13,7 +13,7 @@ class AuthRepository { return UserEventSignIn(request).send(); } - Future> signUp( + Future> signUp( {required String? name, required String? password, required String? email}) { final request = SignUpRequest.create() ..email = email ?? '' @@ -35,7 +35,7 @@ class AuthRepository { // }); } - Future> signOut() { + Future> signOut() { return UserEventSignOut().send(); } } diff --git a/frontend/app_flowy/lib/user/presentation/sign_in_screen.dart b/frontend/app_flowy/lib/user/presentation/sign_in_screen.dart index 869c55e715..9dd984f278 100644 --- a/frontend/app_flowy/lib/user/presentation/sign_in_screen.dart +++ b/frontend/app_flowy/lib/user/presentation/sign_in_screen.dart @@ -9,7 +9,7 @@ import 'package:flowy_infra_ui/widget/rounded_button.dart'; import 'package:flowy_infra_ui/widget/rounded_input_field.dart'; import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flowy_infra_ui/style_widget/snap_bar.dart'; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -39,7 +39,7 @@ class SignInScreen extends StatelessWidget { ); } - void _handleSuccessOrFail(Either result, BuildContext context) { + void _handleSuccessOrFail(Either result, BuildContext context) { result.fold( (user) => router.pushWelcomeScreen(context, user), (error) => showSnapBar(context, error.msg), diff --git a/frontend/app_flowy/lib/user/presentation/sign_up_screen.dart b/frontend/app_flowy/lib/user/presentation/sign_up_screen.dart index 40aa18ef25..915fe6c505 100644 --- a/frontend/app_flowy/lib/user/presentation/sign_up_screen.dart +++ b/frontend/app_flowy/lib/user/presentation/sign_up_screen.dart @@ -7,7 +7,7 @@ import 'package:flowy_infra/theme.dart'; import 'package:flowy_infra_ui/widget/rounded_button.dart'; import 'package:flowy_infra_ui/widget/rounded_input_field.dart'; import 'package:flowy_infra_ui/widget/spacing.dart'; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile; import 'package:flowy_infra_ui/style_widget/snap_bar.dart'; import 'package:flutter/material.dart'; @@ -36,7 +36,7 @@ class SignUpScreen extends StatelessWidget { ); } - void _handleSuccessOrFail(BuildContext context, Either result) { + void _handleSuccessOrFail(BuildContext context, Either result) { result.fold( (user) => router.pushWelcomeScreen(context, user), (error) => showSnapBar(context, error.msg), diff --git a/frontend/app_flowy/lib/user/presentation/skip_log_in_screen.dart b/frontend/app_flowy/lib/user/presentation/skip_log_in_screen.dart index 4c6df28b0f..c559c64371 100644 --- a/frontend/app_flowy/lib/user/presentation/skip_log_in_screen.dart +++ b/frontend/app_flowy/lib/user/presentation/skip_log_in_screen.dart @@ -10,7 +10,7 @@ import 'package:flowy_infra_ui/widget/spacing.dart'; import 'package:flowy_log/flowy_log.dart'; import 'package:flowy_sdk/dispatch/dispatch.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/protobuf.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -113,7 +113,7 @@ class _SkipLogInScreenState extends State { void _openCurrentWorkspace( BuildContext context, UserProfile user, - dartz.Either workspacesOrError, + dartz.Either workspacesOrError, ) { workspacesOrError.fold( (workspaceSetting) { diff --git a/frontend/app_flowy/lib/workspace/application/app/app_bloc.dart b/frontend/app_flowy/lib/workspace/application/app/app_bloc.dart index a66eb5f56d..77888caa14 100644 --- a/frontend/app_flowy/lib/workspace/application/app/app_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/app/app_bloc.dart @@ -2,7 +2,7 @@ import 'package:app_flowy/workspace/domain/i_app.dart'; import 'package:flowy_log/flowy_log.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/app_create.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:dartz/dartz.dart'; @@ -61,7 +61,7 @@ class AppBloc extends Bloc { return super.close(); } - void _handleViewsChanged(Either, WorkspaceError> result) { + void _handleViewsChanged(Either, FlowyError> result) { result.fold( (views) => add(AppEvent.didReceiveViews(views)), (error) { @@ -112,7 +112,7 @@ class AppState with _$AppState { required bool isLoading, required List? views, View? latestCreatedView, - required Either successOrFailure, + required Either successOrFailure, }) = _AppState; factory AppState.initial(App app) => AppState( diff --git a/frontend/app_flowy/lib/workspace/application/app/app_bloc.freezed.dart b/frontend/app_flowy/lib/workspace/application/app/app_bloc.freezed.dart index d795abad45..97c6987f07 100644 --- a/frontend/app_flowy/lib/workspace/application/app/app_bloc.freezed.dart +++ b/frontend/app_flowy/lib/workspace/application/app/app_bloc.freezed.dart @@ -1051,7 +1051,7 @@ class _$AppStateTearOff { required bool isLoading, required List? views, View? latestCreatedView, - required Either successOrFailure}) { + required Either successOrFailure}) { return _AppState( app: app, isLoading: isLoading, @@ -1071,7 +1071,7 @@ mixin _$AppState { bool get isLoading => throw _privateConstructorUsedError; List? get views => throw _privateConstructorUsedError; View? get latestCreatedView => throw _privateConstructorUsedError; - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -1088,7 +1088,7 @@ abstract class $AppStateCopyWith<$Res> { bool isLoading, List? views, View? latestCreatedView, - Either successOrFailure}); + Either successOrFailure}); } /// @nodoc @@ -1127,7 +1127,7 @@ class _$AppStateCopyWithImpl<$Res> implements $AppStateCopyWith<$Res> { successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -1142,7 +1142,7 @@ abstract class _$AppStateCopyWith<$Res> implements $AppStateCopyWith<$Res> { bool isLoading, List? views, View? latestCreatedView, - Either successOrFailure}); + Either successOrFailure}); } /// @nodoc @@ -1182,7 +1182,7 @@ class __$AppStateCopyWithImpl<$Res> extends _$AppStateCopyWithImpl<$Res> successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -1206,7 +1206,7 @@ class _$_AppState implements _AppState { @override final View? latestCreatedView; @override - final Either successOrFailure; + final Either successOrFailure; @override String toString() { @@ -1253,7 +1253,7 @@ abstract class _AppState implements AppState { required bool isLoading, required List? views, View? latestCreatedView, - required Either successOrFailure}) = _$_AppState; + required Either successOrFailure}) = _$_AppState; @override App get app => throw _privateConstructorUsedError; @@ -1264,7 +1264,7 @@ abstract class _AppState implements AppState { @override View? get latestCreatedView => throw _privateConstructorUsedError; @override - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @override @JsonKey(ignore: true) diff --git a/frontend/app_flowy/lib/workspace/application/doc/doc_bloc.dart b/frontend/app_flowy/lib/workspace/application/doc/doc_bloc.dart index 0ba9405b8f..e1c954cb89 100644 --- a/frontend/app_flowy/lib/workspace/application/doc/doc_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/doc/doc_bloc.dart @@ -4,7 +4,7 @@ import 'package:app_flowy/workspace/domain/i_trash.dart'; import 'package:app_flowy/workspace/domain/i_view.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/trash_create.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flutter_quill/flutter_quill.dart'; import 'package:flowy_log/flowy_log.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -155,5 +155,5 @@ class DocState with _$DocState { @freezed class DocLoadState with _$DocLoadState { const factory DocLoadState.loading() = _Loading; - const factory DocLoadState.finish(Either successOrFail) = _Finish; + const factory DocLoadState.finish(Either successOrFail) = _Finish; } diff --git a/frontend/app_flowy/lib/workspace/application/doc/doc_bloc.freezed.dart b/frontend/app_flowy/lib/workspace/application/doc/doc_bloc.freezed.dart index 02a1f50d94..4b6f63f3d6 100644 --- a/frontend/app_flowy/lib/workspace/application/doc/doc_bloc.freezed.dart +++ b/frontend/app_flowy/lib/workspace/application/doc/doc_bloc.freezed.dart @@ -909,7 +909,7 @@ class _$DocLoadStateTearOff { return const _Loading(); } - _Finish finish(Either successOrFail) { + _Finish finish(Either successOrFail) { return _Finish( successOrFail, ); @@ -924,20 +924,20 @@ mixin _$DocLoadState { @optionalTypeArgs TResult when({ required TResult Function() loading, - required TResult Function(Either successOrFail) + required TResult Function(Either successOrFail) finish, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull({ TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen({ TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, required TResult orElse(), }) => throw _privateConstructorUsedError; @@ -1016,7 +1016,7 @@ class _$_Loading implements _Loading { @optionalTypeArgs TResult when({ required TResult Function() loading, - required TResult Function(Either successOrFail) + required TResult Function(Either successOrFail) finish, }) { return loading(); @@ -1026,7 +1026,7 @@ class _$_Loading implements _Loading { @optionalTypeArgs TResult? whenOrNull({ TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, }) { return loading?.call(); } @@ -1035,7 +1035,7 @@ class _$_Loading implements _Loading { @optionalTypeArgs TResult maybeWhen({ TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, required TResult orElse(), }) { if (loading != null) { @@ -1084,7 +1084,7 @@ abstract class _Loading implements DocLoadState { abstract class _$FinishCopyWith<$Res> { factory _$FinishCopyWith(_Finish value, $Res Function(_Finish) then) = __$FinishCopyWithImpl<$Res>; - $Res call({Either successOrFail}); + $Res call({Either successOrFail}); } /// @nodoc @@ -1104,7 +1104,7 @@ class __$FinishCopyWithImpl<$Res> extends _$DocLoadStateCopyWithImpl<$Res> successOrFail == freezed ? _value.successOrFail : successOrFail // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -1115,7 +1115,7 @@ class _$_Finish implements _Finish { const _$_Finish(this.successOrFail); @override - final Either successOrFail; + final Either successOrFail; @override String toString() { @@ -1144,7 +1144,7 @@ class _$_Finish implements _Finish { @optionalTypeArgs TResult when({ required TResult Function() loading, - required TResult Function(Either successOrFail) + required TResult Function(Either successOrFail) finish, }) { return finish(successOrFail); @@ -1154,7 +1154,7 @@ class _$_Finish implements _Finish { @optionalTypeArgs TResult? whenOrNull({ TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, }) { return finish?.call(successOrFail); } @@ -1163,7 +1163,7 @@ class _$_Finish implements _Finish { @optionalTypeArgs TResult maybeWhen({ TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, required TResult orElse(), }) { if (finish != null) { @@ -1205,9 +1205,9 @@ class _$_Finish implements _Finish { } abstract class _Finish implements DocLoadState { - const factory _Finish(Either successOrFail) = _$_Finish; + const factory _Finish(Either successOrFail) = _$_Finish; - Either get successOrFail => + Either get successOrFail => throw _privateConstructorUsedError; @JsonKey(ignore: true) _$FinishCopyWith<_Finish> get copyWith => throw _privateConstructorUsedError; diff --git a/frontend/app_flowy/lib/workspace/application/doc/share_bloc.dart b/frontend/app_flowy/lib/workspace/application/doc/share_bloc.dart index 48582082f3..c1504c4da7 100644 --- a/frontend/app_flowy/lib/workspace/application/doc/share_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/doc/share_bloc.dart @@ -2,7 +2,7 @@ import 'package:app_flowy/workspace/domain/i_share.dart'; import 'package:app_flowy/workspace/infrastructure/markdown/delta_markdown.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/export.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:dartz/dartz.dart'; @@ -48,5 +48,5 @@ class DocShareEvent with _$DocShareEvent { class DocShareState with _$DocShareState { const factory DocShareState.initial() = _Initial; const factory DocShareState.loading() = _Loading; - const factory DocShareState.finish(Either successOrFail) = _Finish; + const factory DocShareState.finish(Either successOrFail) = _Finish; } diff --git a/frontend/app_flowy/lib/workspace/application/doc/share_bloc.freezed.dart b/frontend/app_flowy/lib/workspace/application/doc/share_bloc.freezed.dart index ce72e660f2..2df633c426 100644 --- a/frontend/app_flowy/lib/workspace/application/doc/share_bloc.freezed.dart +++ b/frontend/app_flowy/lib/workspace/application/doc/share_bloc.freezed.dart @@ -434,7 +434,7 @@ class _$DocShareStateTearOff { return const _Loading(); } - _Finish finish(Either successOrFail) { + _Finish finish(Either successOrFail) { return _Finish( successOrFail, ); @@ -450,7 +450,7 @@ mixin _$DocShareState { TResult when({ required TResult Function() initial, required TResult Function() loading, - required TResult Function(Either successOrFail) + required TResult Function(Either successOrFail) finish, }) => throw _privateConstructorUsedError; @@ -458,14 +458,14 @@ mixin _$DocShareState { TResult? whenOrNull({ TResult Function()? initial, TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen({ TResult Function()? initial, TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, required TResult orElse(), }) => throw _privateConstructorUsedError; @@ -549,7 +549,7 @@ class _$_Initial implements _Initial { TResult when({ required TResult Function() initial, required TResult Function() loading, - required TResult Function(Either successOrFail) + required TResult Function(Either successOrFail) finish, }) { return initial(); @@ -560,7 +560,7 @@ class _$_Initial implements _Initial { TResult? whenOrNull({ TResult Function()? initial, TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, }) { return initial?.call(); } @@ -570,7 +570,7 @@ class _$_Initial implements _Initial { TResult maybeWhen({ TResult Function()? initial, TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, required TResult orElse(), }) { if (initial != null) { @@ -657,7 +657,7 @@ class _$_Loading implements _Loading { TResult when({ required TResult Function() initial, required TResult Function() loading, - required TResult Function(Either successOrFail) + required TResult Function(Either successOrFail) finish, }) { return loading(); @@ -668,7 +668,7 @@ class _$_Loading implements _Loading { TResult? whenOrNull({ TResult Function()? initial, TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, }) { return loading?.call(); } @@ -678,7 +678,7 @@ class _$_Loading implements _Loading { TResult maybeWhen({ TResult Function()? initial, TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, required TResult orElse(), }) { if (loading != null) { @@ -730,7 +730,7 @@ abstract class _Loading implements DocShareState { abstract class _$FinishCopyWith<$Res> { factory _$FinishCopyWith(_Finish value, $Res Function(_Finish) then) = __$FinishCopyWithImpl<$Res>; - $Res call({Either successOrFail}); + $Res call({Either successOrFail}); } /// @nodoc @@ -750,7 +750,7 @@ class __$FinishCopyWithImpl<$Res> extends _$DocShareStateCopyWithImpl<$Res> successOrFail == freezed ? _value.successOrFail : successOrFail // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -761,7 +761,7 @@ class _$_Finish implements _Finish { const _$_Finish(this.successOrFail); @override - final Either successOrFail; + final Either successOrFail; @override String toString() { @@ -791,7 +791,7 @@ class _$_Finish implements _Finish { TResult when({ required TResult Function() initial, required TResult Function() loading, - required TResult Function(Either successOrFail) + required TResult Function(Either successOrFail) finish, }) { return finish(successOrFail); @@ -802,7 +802,7 @@ class _$_Finish implements _Finish { TResult? whenOrNull({ TResult Function()? initial, TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, }) { return finish?.call(successOrFail); } @@ -812,7 +812,7 @@ class _$_Finish implements _Finish { TResult maybeWhen({ TResult Function()? initial, TResult Function()? loading, - TResult Function(Either successOrFail)? finish, + TResult Function(Either successOrFail)? finish, required TResult orElse(), }) { if (finish != null) { @@ -857,10 +857,10 @@ class _$_Finish implements _Finish { } abstract class _Finish implements DocShareState { - const factory _Finish(Either successOrFail) = + const factory _Finish(Either successOrFail) = _$_Finish; - Either get successOrFail => + Either get successOrFail => throw _privateConstructorUsedError; @JsonKey(ignore: true) _$FinishCopyWith<_Finish> get copyWith => throw _privateConstructorUsedError; diff --git a/frontend/app_flowy/lib/workspace/application/home/home_listen_bloc.dart b/frontend/app_flowy/lib/workspace/application/home/home_listen_bloc.dart index 5e71b82380..e7ae03b094 100644 --- a/frontend/app_flowy/lib/workspace/application/home/home_listen_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/home/home_listen_bloc.dart @@ -1,5 +1,6 @@ import 'package:app_flowy/workspace/domain/i_user.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:dartz/dartz.dart'; @@ -31,7 +32,7 @@ class HomeListenBloc extends Bloc { super.close(); } - void _authDidChanged(Either errorOrNothing) { + void _authDidChanged(Either errorOrNothing) { errorOrNothing.fold((_) {}, (error) { if (error.code == ErrorCode.UserUnauthorized.value) { add(HomeListenEvent.unauthorized(error.msg)); diff --git a/frontend/app_flowy/lib/workspace/application/menu/menu_bloc.dart b/frontend/app_flowy/lib/workspace/application/menu/menu_bloc.dart index 84db381db7..651d569451 100644 --- a/frontend/app_flowy/lib/workspace/application/menu/menu_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/menu/menu_bloc.dart @@ -5,7 +5,7 @@ import 'package:app_flowy/workspace/presentation/stack_page/blank/blank_page.dar import 'package:dartz/dartz.dart'; import 'package:flowy_log/flowy_log.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/app_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -77,7 +77,7 @@ class MenuBloc extends Bloc { ); } - void _handleAppsOrFail(Either, WorkspaceError> appsOrFail) { + void _handleAppsOrFail(Either, FlowyError> appsOrFail) { appsOrFail.fold( (apps) => add(MenuEvent.didReceiveApps(left(apps))), (error) => add(MenuEvent.didReceiveApps(right(error))), @@ -91,7 +91,7 @@ class MenuEvent with _$MenuEvent { const factory MenuEvent.collapse() = Collapse; const factory MenuEvent.openPage(HomeStackContext context) = OpenPage; const factory MenuEvent.createApp(String name, {String? desc}) = CreateApp; - const factory MenuEvent.didReceiveApps(Either, WorkspaceError> appsOrFail) = ReceiveApps; + const factory MenuEvent.didReceiveApps(Either, FlowyError> appsOrFail) = ReceiveApps; } @freezed @@ -99,7 +99,7 @@ class MenuState with _$MenuState { const factory MenuState({ required bool isCollapse, required Option> apps, - required Either successOrFailure, + required Either successOrFailure, required HomeStackContext stackContext, }) = _MenuState; diff --git a/frontend/app_flowy/lib/workspace/application/menu/menu_bloc.freezed.dart b/frontend/app_flowy/lib/workspace/application/menu/menu_bloc.freezed.dart index 3aa13660bc..a23f8bcd04 100644 --- a/frontend/app_flowy/lib/workspace/application/menu/menu_bloc.freezed.dart +++ b/frontend/app_flowy/lib/workspace/application/menu/menu_bloc.freezed.dart @@ -38,7 +38,7 @@ class _$MenuEventTearOff { ); } - ReceiveApps didReceiveApps(Either, WorkspaceError> appsOrFail) { + ReceiveApps didReceiveApps(Either, FlowyError> appsOrFail) { return ReceiveApps( appsOrFail, ); @@ -57,7 +57,7 @@ mixin _$MenuEvent { required TResult Function(HomeStackContext context) openPage, required TResult Function(String name, String? desc) createApp, - required TResult Function(Either, WorkspaceError> appsOrFail) + required TResult Function(Either, FlowyError> appsOrFail) didReceiveApps, }) => throw _privateConstructorUsedError; @@ -67,7 +67,7 @@ mixin _$MenuEvent { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, }) => throw _privateConstructorUsedError; @@ -77,7 +77,7 @@ mixin _$MenuEvent { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, required TResult orElse(), }) => @@ -169,7 +169,7 @@ class _$_Initial implements _Initial { required TResult Function(HomeStackContext context) openPage, required TResult Function(String name, String? desc) createApp, - required TResult Function(Either, WorkspaceError> appsOrFail) + required TResult Function(Either, FlowyError> appsOrFail) didReceiveApps, }) { return initial(); @@ -182,7 +182,7 @@ class _$_Initial implements _Initial { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, }) { return initial?.call(); @@ -195,7 +195,7 @@ class _$_Initial implements _Initial { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, required TResult orElse(), }) { @@ -292,7 +292,7 @@ class _$Collapse implements Collapse { required TResult Function(HomeStackContext context) openPage, required TResult Function(String name, String? desc) createApp, - required TResult Function(Either, WorkspaceError> appsOrFail) + required TResult Function(Either, FlowyError> appsOrFail) didReceiveApps, }) { return collapse(); @@ -305,7 +305,7 @@ class _$Collapse implements Collapse { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, }) { return collapse?.call(); @@ -318,7 +318,7 @@ class _$Collapse implements Collapse { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, required TResult orElse(), }) { @@ -440,7 +440,7 @@ class _$OpenPage implements OpenPage { required TResult Function(HomeStackContext context) openPage, required TResult Function(String name, String? desc) createApp, - required TResult Function(Either, WorkspaceError> appsOrFail) + required TResult Function(Either, FlowyError> appsOrFail) didReceiveApps, }) { return openPage(context); @@ -453,7 +453,7 @@ class _$OpenPage implements OpenPage { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, }) { return openPage?.call(context); @@ -466,7 +466,7 @@ class _$OpenPage implements OpenPage { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, required TResult orElse(), }) { @@ -606,7 +606,7 @@ class _$CreateApp implements CreateApp { required TResult Function(HomeStackContext context) openPage, required TResult Function(String name, String? desc) createApp, - required TResult Function(Either, WorkspaceError> appsOrFail) + required TResult Function(Either, FlowyError> appsOrFail) didReceiveApps, }) { return createApp(name, desc); @@ -619,7 +619,7 @@ class _$CreateApp implements CreateApp { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, }) { return createApp?.call(name, desc); @@ -632,7 +632,7 @@ class _$CreateApp implements CreateApp { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, required TResult orElse(), }) { @@ -698,7 +698,7 @@ abstract class $ReceiveAppsCopyWith<$Res> { factory $ReceiveAppsCopyWith( ReceiveApps value, $Res Function(ReceiveApps) then) = _$ReceiveAppsCopyWithImpl<$Res>; - $Res call({Either, WorkspaceError> appsOrFail}); + $Res call({Either, FlowyError> appsOrFail}); } /// @nodoc @@ -719,7 +719,7 @@ class _$ReceiveAppsCopyWithImpl<$Res> extends _$MenuEventCopyWithImpl<$Res> appsOrFail == freezed ? _value.appsOrFail : appsOrFail // ignore: cast_nullable_to_non_nullable - as Either, WorkspaceError>, + as Either, FlowyError>, )); } } @@ -730,7 +730,7 @@ class _$ReceiveApps implements ReceiveApps { const _$ReceiveApps(this.appsOrFail); @override - final Either, WorkspaceError> appsOrFail; + final Either, FlowyError> appsOrFail; @override String toString() { @@ -763,7 +763,7 @@ class _$ReceiveApps implements ReceiveApps { required TResult Function(HomeStackContext context) openPage, required TResult Function(String name, String? desc) createApp, - required TResult Function(Either, WorkspaceError> appsOrFail) + required TResult Function(Either, FlowyError> appsOrFail) didReceiveApps, }) { return didReceiveApps(appsOrFail); @@ -776,7 +776,7 @@ class _$ReceiveApps implements ReceiveApps { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, }) { return didReceiveApps?.call(appsOrFail); @@ -789,7 +789,7 @@ class _$ReceiveApps implements ReceiveApps { TResult Function()? collapse, TResult Function(HomeStackContext context)? openPage, TResult Function(String name, String? desc)? createApp, - TResult Function(Either, WorkspaceError> appsOrFail)? + TResult Function(Either, FlowyError> appsOrFail)? didReceiveApps, required TResult orElse(), }) { @@ -841,10 +841,10 @@ class _$ReceiveApps implements ReceiveApps { } abstract class ReceiveApps implements MenuEvent { - const factory ReceiveApps(Either, WorkspaceError> appsOrFail) = + const factory ReceiveApps(Either, FlowyError> appsOrFail) = _$ReceiveApps; - Either, WorkspaceError> get appsOrFail => + Either, FlowyError> get appsOrFail => throw _privateConstructorUsedError; @JsonKey(ignore: true) $ReceiveAppsCopyWith get copyWith => @@ -858,7 +858,7 @@ class _$MenuStateTearOff { _MenuState call( {required bool isCollapse, required Option> apps, - required Either successOrFailure, + required Either successOrFailure, required HomeStackContext stackContext}) { return _MenuState( isCollapse: isCollapse, @@ -876,7 +876,7 @@ const $MenuState = _$MenuStateTearOff(); mixin _$MenuState { bool get isCollapse => throw _privateConstructorUsedError; Option> get apps => throw _privateConstructorUsedError; - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; HomeStackContext get stackContext => throw _privateConstructorUsedError; @@ -893,7 +893,7 @@ abstract class $MenuStateCopyWith<$Res> { $Res call( {bool isCollapse, Option> apps, - Either successOrFailure, + Either successOrFailure, HomeStackContext stackContext}); } @@ -924,7 +924,7 @@ class _$MenuStateCopyWithImpl<$Res> implements $MenuStateCopyWith<$Res> { successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, stackContext: stackContext == freezed ? _value.stackContext : stackContext // ignore: cast_nullable_to_non_nullable @@ -942,7 +942,7 @@ abstract class _$MenuStateCopyWith<$Res> implements $MenuStateCopyWith<$Res> { $Res call( {bool isCollapse, Option> apps, - Either successOrFailure, + Either successOrFailure, HomeStackContext stackContext}); } @@ -974,7 +974,7 @@ class __$MenuStateCopyWithImpl<$Res> extends _$MenuStateCopyWithImpl<$Res> successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, stackContext: stackContext == freezed ? _value.stackContext : stackContext // ignore: cast_nullable_to_non_nullable @@ -997,7 +997,7 @@ class _$_MenuState implements _MenuState { @override final Option> apps; @override - final Either successOrFailure; + final Either successOrFailure; @override final HomeStackContext stackContext; @@ -1041,7 +1041,7 @@ abstract class _MenuState implements MenuState { const factory _MenuState( {required bool isCollapse, required Option> apps, - required Either successOrFailure, + required Either successOrFailure, required HomeStackContext stackContext}) = _$_MenuState; @override @@ -1049,7 +1049,7 @@ abstract class _MenuState implements MenuState { @override Option> get apps => throw _privateConstructorUsedError; @override - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @override HomeStackContext get stackContext => diff --git a/frontend/app_flowy/lib/workspace/application/menu/menu_user_bloc.dart b/frontend/app_flowy/lib/workspace/application/menu/menu_user_bloc.dart index b68700f4d8..f66da0262e 100644 --- a/frontend/app_flowy/lib/workspace/application/menu/menu_user_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/menu/menu_user_bloc.dart @@ -1,7 +1,7 @@ import 'package:app_flowy/workspace/domain/i_user.dart'; import 'package:flowy_log/flowy_log.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/workspace_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:dartz/dartz.dart'; @@ -39,8 +39,8 @@ class MenuUserBloc extends Bloc { result.fold((l) => null, (error) => Log.error(error)); } - void _profileUpdated(Either userOrFailed) {} - void _workspacesUpdated(Either, WorkspaceError> workspacesOrFailed) { + void _profileUpdated(Either userOrFailed) {} + void _workspacesUpdated(Either, FlowyError> workspacesOrFailed) { // fetch workspaces // iUserImpl.fetchWorkspaces().then((result) { // result.fold( diff --git a/frontend/app_flowy/lib/workspace/application/trash/trash_bloc.dart b/frontend/app_flowy/lib/workspace/application/trash/trash_bloc.dart index cd20a56a97..3eda6e3eaa 100644 --- a/frontend/app_flowy/lib/workspace/application/trash/trash_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/trash/trash_bloc.dart @@ -2,7 +2,7 @@ import 'package:app_flowy/workspace/domain/i_trash.dart'; import 'package:dartz/dartz.dart'; import 'package:flowy_log/flowy_log.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/trash_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'trash_bloc.freezed.dart'; @@ -45,14 +45,14 @@ class TrashBloc extends Bloc { ); } - Stream _handleResult(Either result) async* { + Stream _handleResult(Either result) async* { yield result.fold( (l) => state.copyWith(successOrFailure: left(unit)), (error) => state.copyWith(successOrFailure: right(error)), ); } - void _listenTrashUpdated(Either, WorkspaceError> trashOrFailed) { + void _listenTrashUpdated(Either, FlowyError> trashOrFailed) { trashOrFailed.fold( (trash) { add(TrashEvent.didReceiveTrash(trash)); @@ -84,7 +84,7 @@ class TrashEvent with _$TrashEvent { class TrashState with _$TrashState { const factory TrashState({ required List objects, - required Either successOrFailure, + required Either successOrFailure, }) = _TrashState; factory TrashState.init() => TrashState( diff --git a/frontend/app_flowy/lib/workspace/application/trash/trash_bloc.freezed.dart b/frontend/app_flowy/lib/workspace/application/trash/trash_bloc.freezed.dart index aa26cda8b8..5fc468749e 100644 --- a/frontend/app_flowy/lib/workspace/application/trash/trash_bloc.freezed.dart +++ b/frontend/app_flowy/lib/workspace/application/trash/trash_bloc.freezed.dart @@ -980,7 +980,7 @@ class _$TrashStateTearOff { _TrashState call( {required List objects, - required Either successOrFailure}) { + required Either successOrFailure}) { return _TrashState( objects: objects, successOrFailure: successOrFailure, @@ -994,7 +994,7 @@ const $TrashState = _$TrashStateTearOff(); /// @nodoc mixin _$TrashState { List get objects => throw _privateConstructorUsedError; - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -1008,7 +1008,7 @@ abstract class $TrashStateCopyWith<$Res> { TrashState value, $Res Function(TrashState) then) = _$TrashStateCopyWithImpl<$Res>; $Res call( - {List objects, Either successOrFailure}); + {List objects, Either successOrFailure}); } /// @nodoc @@ -1032,7 +1032,7 @@ class _$TrashStateCopyWithImpl<$Res> implements $TrashStateCopyWith<$Res> { successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -1044,7 +1044,7 @@ abstract class _$TrashStateCopyWith<$Res> implements $TrashStateCopyWith<$Res> { __$TrashStateCopyWithImpl<$Res>; @override $Res call( - {List objects, Either successOrFailure}); + {List objects, Either successOrFailure}); } /// @nodoc @@ -1070,7 +1070,7 @@ class __$TrashStateCopyWithImpl<$Res> extends _$TrashStateCopyWithImpl<$Res> successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -1083,7 +1083,7 @@ class _$_TrashState implements _TrashState { @override final List objects; @override - final Either successOrFailure; + final Either successOrFailure; @override String toString() { @@ -1117,12 +1117,12 @@ class _$_TrashState implements _TrashState { abstract class _TrashState implements TrashState { const factory _TrashState( {required List objects, - required Either successOrFailure}) = _$_TrashState; + required Either successOrFailure}) = _$_TrashState; @override List get objects => throw _privateConstructorUsedError; @override - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @override @JsonKey(ignore: true) diff --git a/frontend/app_flowy/lib/workspace/application/view/view_bloc.dart b/frontend/app_flowy/lib/workspace/application/view/view_bloc.dart index 579c3d4165..92f0fc6a31 100644 --- a/frontend/app_flowy/lib/workspace/application/view/view_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/view/view_bloc.dart @@ -1,6 +1,6 @@ import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:app_flowy/workspace/domain/i_view.dart'; @@ -56,7 +56,7 @@ class ViewBloc extends Bloc { ); } - Stream _handleViewDidUpdate(Either result) async* { + Stream _handleViewDidUpdate(Either result) async* { yield result.fold( (view) => state.copyWith(view: view, successOrFailure: left(unit)), (error) => state.copyWith(successOrFailure: right(error)), @@ -77,7 +77,7 @@ class ViewEvent with _$ViewEvent { const factory ViewEvent.rename(String newName) = Rename; const factory ViewEvent.delete() = Delete; const factory ViewEvent.duplicate() = Duplicate; - const factory ViewEvent.viewDidUpdate(Either result) = ViewDidUpdate; + const factory ViewEvent.viewDidUpdate(Either result) = ViewDidUpdate; } @freezed @@ -85,7 +85,7 @@ class ViewState with _$ViewState { const factory ViewState({ required View view, required bool isEditing, - required Either successOrFailure, + required Either successOrFailure, }) = _ViewState; factory ViewState.init(View view) => ViewState( diff --git a/frontend/app_flowy/lib/workspace/application/view/view_bloc.freezed.dart b/frontend/app_flowy/lib/workspace/application/view/view_bloc.freezed.dart index 2a25991d3c..4f1fe4b838 100644 --- a/frontend/app_flowy/lib/workspace/application/view/view_bloc.freezed.dart +++ b/frontend/app_flowy/lib/workspace/application/view/view_bloc.freezed.dart @@ -41,7 +41,7 @@ class _$ViewEventTearOff { return const Duplicate(); } - ViewDidUpdate viewDidUpdate(Either result) { + ViewDidUpdate viewDidUpdate(Either result) { return ViewDidUpdate( result, ); @@ -60,7 +60,7 @@ mixin _$ViewEvent { required TResult Function(String newName) rename, required TResult Function() delete, required TResult Function() duplicate, - required TResult Function(Either result) + required TResult Function(Either result) viewDidUpdate, }) => throw _privateConstructorUsedError; @@ -71,7 +71,7 @@ mixin _$ViewEvent { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -81,7 +81,7 @@ mixin _$ViewEvent { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, required TResult orElse(), }) => throw _privateConstructorUsedError; @@ -175,7 +175,7 @@ class _$Initial implements Initial { required TResult Function(String newName) rename, required TResult Function() delete, required TResult Function() duplicate, - required TResult Function(Either result) + required TResult Function(Either result) viewDidUpdate, }) { return initial(); @@ -189,7 +189,7 @@ class _$Initial implements Initial { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, }) { return initial?.call(); } @@ -202,7 +202,7 @@ class _$Initial implements Initial { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, required TResult orElse(), }) { if (initial != null) { @@ -328,7 +328,7 @@ class _$SetEditing implements SetEditing { required TResult Function(String newName) rename, required TResult Function() delete, required TResult Function() duplicate, - required TResult Function(Either result) + required TResult Function(Either result) viewDidUpdate, }) { return setIsEditing(isEditing); @@ -342,7 +342,7 @@ class _$SetEditing implements SetEditing { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, }) { return setIsEditing?.call(isEditing); } @@ -355,7 +355,7 @@ class _$SetEditing implements SetEditing { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, required TResult orElse(), }) { if (setIsEditing != null) { @@ -484,7 +484,7 @@ class _$Rename implements Rename { required TResult Function(String newName) rename, required TResult Function() delete, required TResult Function() duplicate, - required TResult Function(Either result) + required TResult Function(Either result) viewDidUpdate, }) { return rename(newName); @@ -498,7 +498,7 @@ class _$Rename implements Rename { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, }) { return rename?.call(newName); } @@ -511,7 +511,7 @@ class _$Rename implements Rename { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, required TResult orElse(), }) { if (rename != null) { @@ -614,7 +614,7 @@ class _$Delete implements Delete { required TResult Function(String newName) rename, required TResult Function() delete, required TResult Function() duplicate, - required TResult Function(Either result) + required TResult Function(Either result) viewDidUpdate, }) { return delete(); @@ -628,7 +628,7 @@ class _$Delete implements Delete { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, }) { return delete?.call(); } @@ -641,7 +641,7 @@ class _$Delete implements Delete { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, required TResult orElse(), }) { if (delete != null) { @@ -740,7 +740,7 @@ class _$Duplicate implements Duplicate { required TResult Function(String newName) rename, required TResult Function() delete, required TResult Function() duplicate, - required TResult Function(Either result) + required TResult Function(Either result) viewDidUpdate, }) { return duplicate(); @@ -754,7 +754,7 @@ class _$Duplicate implements Duplicate { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, }) { return duplicate?.call(); } @@ -767,7 +767,7 @@ class _$Duplicate implements Duplicate { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, required TResult orElse(), }) { if (duplicate != null) { @@ -829,7 +829,7 @@ abstract class $ViewDidUpdateCopyWith<$Res> { factory $ViewDidUpdateCopyWith( ViewDidUpdate value, $Res Function(ViewDidUpdate) then) = _$ViewDidUpdateCopyWithImpl<$Res>; - $Res call({Either result}); + $Res call({Either result}); } /// @nodoc @@ -850,7 +850,7 @@ class _$ViewDidUpdateCopyWithImpl<$Res> extends _$ViewEventCopyWithImpl<$Res> result == freezed ? _value.result : result // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -861,7 +861,7 @@ class _$ViewDidUpdate implements ViewDidUpdate { const _$ViewDidUpdate(this.result); @override - final Either result; + final Either result; @override String toString() { @@ -893,7 +893,7 @@ class _$ViewDidUpdate implements ViewDidUpdate { required TResult Function(String newName) rename, required TResult Function() delete, required TResult Function() duplicate, - required TResult Function(Either result) + required TResult Function(Either result) viewDidUpdate, }) { return viewDidUpdate(result); @@ -907,7 +907,7 @@ class _$ViewDidUpdate implements ViewDidUpdate { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, }) { return viewDidUpdate?.call(result); } @@ -920,7 +920,7 @@ class _$ViewDidUpdate implements ViewDidUpdate { TResult Function(String newName)? rename, TResult Function()? delete, TResult Function()? duplicate, - TResult Function(Either result)? viewDidUpdate, + TResult Function(Either result)? viewDidUpdate, required TResult orElse(), }) { if (viewDidUpdate != null) { @@ -974,10 +974,10 @@ class _$ViewDidUpdate implements ViewDidUpdate { } abstract class ViewDidUpdate implements ViewEvent { - const factory ViewDidUpdate(Either result) = + const factory ViewDidUpdate(Either result) = _$ViewDidUpdate; - Either get result => throw _privateConstructorUsedError; + Either get result => throw _privateConstructorUsedError; @JsonKey(ignore: true) $ViewDidUpdateCopyWith get copyWith => throw _privateConstructorUsedError; @@ -990,7 +990,7 @@ class _$ViewStateTearOff { _ViewState call( {required View view, required bool isEditing, - required Either successOrFailure}) { + required Either successOrFailure}) { return _ViewState( view: view, isEditing: isEditing, @@ -1006,7 +1006,7 @@ const $ViewState = _$ViewStateTearOff(); mixin _$ViewState { View get view => throw _privateConstructorUsedError; bool get isEditing => throw _privateConstructorUsedError; - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -1021,7 +1021,7 @@ abstract class $ViewStateCopyWith<$Res> { $Res call( {View view, bool isEditing, - Either successOrFailure}); + Either successOrFailure}); } /// @nodoc @@ -1050,7 +1050,7 @@ class _$ViewStateCopyWithImpl<$Res> implements $ViewStateCopyWith<$Res> { successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -1064,7 +1064,7 @@ abstract class _$ViewStateCopyWith<$Res> implements $ViewStateCopyWith<$Res> { $Res call( {View view, bool isEditing, - Either successOrFailure}); + Either successOrFailure}); } /// @nodoc @@ -1094,7 +1094,7 @@ class __$ViewStateCopyWithImpl<$Res> extends _$ViewStateCopyWithImpl<$Res> successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -1112,7 +1112,7 @@ class _$_ViewState implements _ViewState { @override final bool isEditing; @override - final Either successOrFailure; + final Either successOrFailure; @override String toString() { @@ -1150,14 +1150,14 @@ abstract class _ViewState implements ViewState { const factory _ViewState( {required View view, required bool isEditing, - required Either successOrFailure}) = _$_ViewState; + required Either successOrFailure}) = _$_ViewState; @override View get view => throw _privateConstructorUsedError; @override bool get isEditing => throw _privateConstructorUsedError; @override - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @override @JsonKey(ignore: true) diff --git a/frontend/app_flowy/lib/workspace/application/workspace/welcome_bloc.dart b/frontend/app_flowy/lib/workspace/application/workspace/welcome_bloc.dart index 16fc9805ff..8f563344a8 100644 --- a/frontend/app_flowy/lib/workspace/application/workspace/welcome_bloc.dart +++ b/frontend/app_flowy/lib/workspace/application/workspace/welcome_bloc.dart @@ -2,7 +2,7 @@ import 'package:app_flowy/workspace/domain/i_user.dart'; import 'package:app_flowy/workspace/infrastructure/repos/user_repo.dart'; import 'package:flowy_log/flowy_log.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/workspace_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:dartz/dartz.dart'; @@ -76,7 +76,7 @@ class WelcomeBloc extends Bloc { ); } - void _workspacesUpdated(Either, WorkspaceError> workspacesOrFail) { + void _workspacesUpdated(Either, FlowyError> workspacesOrFail) { add(WelcomeEvent.workspacesReveived(workspacesOrFail)); } } @@ -87,7 +87,7 @@ class WelcomeEvent with _$WelcomeEvent { // const factory WelcomeEvent.fetchWorkspaces() = FetchWorkspace; const factory WelcomeEvent.createWorkspace(String name, String desc) = CreateWorkspace; const factory WelcomeEvent.openWorkspace(Workspace workspace) = OpenWorkspace; - const factory WelcomeEvent.workspacesReveived(Either, WorkspaceError> workspacesOrFail) = + const factory WelcomeEvent.workspacesReveived(Either, FlowyError> workspacesOrFail) = WorkspacesReceived; } @@ -96,7 +96,7 @@ class WelcomeState with _$WelcomeState { const factory WelcomeState({ required bool isLoading, required List workspaces, - required Either successOrFailure, + required Either successOrFailure, }) = _WelcomeState; factory WelcomeState.initial() => WelcomeState( diff --git a/frontend/app_flowy/lib/workspace/application/workspace/welcome_bloc.freezed.dart b/frontend/app_flowy/lib/workspace/application/workspace/welcome_bloc.freezed.dart index d0b7ebac29..6bd2c9bf4f 100644 --- a/frontend/app_flowy/lib/workspace/application/workspace/welcome_bloc.freezed.dart +++ b/frontend/app_flowy/lib/workspace/application/workspace/welcome_bloc.freezed.dart @@ -35,7 +35,7 @@ class _$WelcomeEventTearOff { } WorkspacesReceived workspacesReveived( - Either, WorkspaceError> workspacesOrFail) { + Either, FlowyError> workspacesOrFail) { return WorkspacesReceived( workspacesOrFail, ); @@ -53,7 +53,7 @@ mixin _$WelcomeEvent { required TResult Function(String name, String desc) createWorkspace, required TResult Function(Workspace workspace) openWorkspace, required TResult Function( - Either, WorkspaceError> workspacesOrFail) + Either, FlowyError> workspacesOrFail) workspacesReveived, }) => throw _privateConstructorUsedError; @@ -62,7 +62,7 @@ mixin _$WelcomeEvent { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, }) => throw _privateConstructorUsedError; @@ -71,7 +71,7 @@ mixin _$WelcomeEvent { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, required TResult orElse(), }) => @@ -160,7 +160,7 @@ class _$Initial implements Initial { required TResult Function(String name, String desc) createWorkspace, required TResult Function(Workspace workspace) openWorkspace, required TResult Function( - Either, WorkspaceError> workspacesOrFail) + Either, FlowyError> workspacesOrFail) workspacesReveived, }) { return initial(); @@ -172,7 +172,7 @@ class _$Initial implements Initial { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, }) { return initial?.call(); @@ -184,7 +184,7 @@ class _$Initial implements Initial { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, required TResult orElse(), }) { @@ -316,7 +316,7 @@ class _$CreateWorkspace implements CreateWorkspace { required TResult Function(String name, String desc) createWorkspace, required TResult Function(Workspace workspace) openWorkspace, required TResult Function( - Either, WorkspaceError> workspacesOrFail) + Either, FlowyError> workspacesOrFail) workspacesReveived, }) { return createWorkspace(name, desc); @@ -328,7 +328,7 @@ class _$CreateWorkspace implements CreateWorkspace { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, }) { return createWorkspace?.call(name, desc); @@ -340,7 +340,7 @@ class _$CreateWorkspace implements CreateWorkspace { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, required TResult orElse(), }) { @@ -467,7 +467,7 @@ class _$OpenWorkspace implements OpenWorkspace { required TResult Function(String name, String desc) createWorkspace, required TResult Function(Workspace workspace) openWorkspace, required TResult Function( - Either, WorkspaceError> workspacesOrFail) + Either, FlowyError> workspacesOrFail) workspacesReveived, }) { return openWorkspace(workspace); @@ -479,7 +479,7 @@ class _$OpenWorkspace implements OpenWorkspace { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, }) { return openWorkspace?.call(workspace); @@ -491,7 +491,7 @@ class _$OpenWorkspace implements OpenWorkspace { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, required TResult orElse(), }) { @@ -553,7 +553,7 @@ abstract class $WorkspacesReceivedCopyWith<$Res> { factory $WorkspacesReceivedCopyWith( WorkspacesReceived value, $Res Function(WorkspacesReceived) then) = _$WorkspacesReceivedCopyWithImpl<$Res>; - $Res call({Either, WorkspaceError> workspacesOrFail}); + $Res call({Either, FlowyError> workspacesOrFail}); } /// @nodoc @@ -575,7 +575,7 @@ class _$WorkspacesReceivedCopyWithImpl<$Res> workspacesOrFail == freezed ? _value.workspacesOrFail : workspacesOrFail // ignore: cast_nullable_to_non_nullable - as Either, WorkspaceError>, + as Either, FlowyError>, )); } } @@ -586,7 +586,7 @@ class _$WorkspacesReceived implements WorkspacesReceived { const _$WorkspacesReceived(this.workspacesOrFail); @override - final Either, WorkspaceError> workspacesOrFail; + final Either, FlowyError> workspacesOrFail; @override String toString() { @@ -619,7 +619,7 @@ class _$WorkspacesReceived implements WorkspacesReceived { required TResult Function(String name, String desc) createWorkspace, required TResult Function(Workspace workspace) openWorkspace, required TResult Function( - Either, WorkspaceError> workspacesOrFail) + Either, FlowyError> workspacesOrFail) workspacesReveived, }) { return workspacesReveived(workspacesOrFail); @@ -631,7 +631,7 @@ class _$WorkspacesReceived implements WorkspacesReceived { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, }) { return workspacesReveived?.call(workspacesOrFail); @@ -643,7 +643,7 @@ class _$WorkspacesReceived implements WorkspacesReceived { TResult Function()? initial, TResult Function(String name, String desc)? createWorkspace, TResult Function(Workspace workspace)? openWorkspace, - TResult Function(Either, WorkspaceError> workspacesOrFail)? + TResult Function(Either, FlowyError> workspacesOrFail)? workspacesReveived, required TResult orElse(), }) { @@ -693,10 +693,10 @@ class _$WorkspacesReceived implements WorkspacesReceived { abstract class WorkspacesReceived implements WelcomeEvent { const factory WorkspacesReceived( - Either, WorkspaceError> workspacesOrFail) = + Either, FlowyError> workspacesOrFail) = _$WorkspacesReceived; - Either, WorkspaceError> get workspacesOrFail => + Either, FlowyError> get workspacesOrFail => throw _privateConstructorUsedError; @JsonKey(ignore: true) $WorkspacesReceivedCopyWith get copyWith => @@ -710,7 +710,7 @@ class _$WelcomeStateTearOff { _WelcomeState call( {required bool isLoading, required List workspaces, - required Either successOrFailure}) { + required Either successOrFailure}) { return _WelcomeState( isLoading: isLoading, workspaces: workspaces, @@ -726,7 +726,7 @@ const $WelcomeState = _$WelcomeStateTearOff(); mixin _$WelcomeState { bool get isLoading => throw _privateConstructorUsedError; List get workspaces => throw _privateConstructorUsedError; - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -742,7 +742,7 @@ abstract class $WelcomeStateCopyWith<$Res> { $Res call( {bool isLoading, List workspaces, - Either successOrFailure}); + Either successOrFailure}); } /// @nodoc @@ -771,7 +771,7 @@ class _$WelcomeStateCopyWithImpl<$Res> implements $WelcomeStateCopyWith<$Res> { successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -786,7 +786,7 @@ abstract class _$WelcomeStateCopyWith<$Res> $Res call( {bool isLoading, List workspaces, - Either successOrFailure}); + Either successOrFailure}); } /// @nodoc @@ -817,7 +817,7 @@ class __$WelcomeStateCopyWithImpl<$Res> extends _$WelcomeStateCopyWithImpl<$Res> successOrFailure: successOrFailure == freezed ? _value.successOrFailure : successOrFailure // ignore: cast_nullable_to_non_nullable - as Either, + as Either, )); } } @@ -835,7 +835,7 @@ class _$_WelcomeState implements _WelcomeState { @override final List workspaces; @override - final Either successOrFailure; + final Either successOrFailure; @override String toString() { @@ -874,7 +874,7 @@ abstract class _WelcomeState implements WelcomeState { const factory _WelcomeState( {required bool isLoading, required List workspaces, - required Either successOrFailure}) = + required Either successOrFailure}) = _$_WelcomeState; @override @@ -882,7 +882,7 @@ abstract class _WelcomeState implements WelcomeState { @override List get workspaces => throw _privateConstructorUsedError; @override - Either get successOrFailure => + Either get successOrFailure => throw _privateConstructorUsedError; @override @JsonKey(ignore: true) diff --git a/frontend/app_flowy/lib/workspace/domain/i_app.dart b/frontend/app_flowy/lib/workspace/domain/i_app.dart index 3073809dc5..0c0d76d0c9 100644 --- a/frontend/app_flowy/lib/workspace/domain/i_app.dart +++ b/frontend/app_flowy/lib/workspace/domain/i_app.dart @@ -1,18 +1,18 @@ import 'package:flowy_sdk/protobuf/flowy-core-infra/protobuf.dart'; import 'package:dartz/dartz.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; typedef AppUpdatedCallback = void Function(App app); -typedef AppViewsChangeCallback = void Function(Either, WorkspaceError> viewsOrFailed); +typedef AppViewsChangeCallback = void Function(Either, FlowyError> viewsOrFailed); abstract class IApp { - Future, WorkspaceError>> getViews(); + Future, FlowyError>> getViews(); - Future> createView({required String name, String? desc, required ViewType viewType}); + Future> createView({required String name, String? desc, required ViewType viewType}); - Future> delete(); + Future> delete(); - Future> rename(String newName); + Future> rename(String newName); } abstract class IAppListenr { diff --git a/frontend/app_flowy/lib/workspace/domain/i_doc.dart b/frontend/app_flowy/lib/workspace/domain/i_doc.dart index 14c99c5118..3d65996189 100644 --- a/frontend/app_flowy/lib/workspace/domain/i_doc.dart +++ b/frontend/app_flowy/lib/workspace/domain/i_doc.dart @@ -1,10 +1,10 @@ import 'dart:async'; import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/protobuf/flowy-collaboration/doc.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; abstract class IDoc { - Future> readDoc(); - Future> composeDelta({required String json}); - Future> closeDoc(); + Future> readDoc(); + Future> composeDelta({required String json}); + Future> closeDoc(); } diff --git a/frontend/app_flowy/lib/workspace/domain/i_share.dart b/frontend/app_flowy/lib/workspace/domain/i_share.dart index cd24047807..11f119e9db 100644 --- a/frontend/app_flowy/lib/workspace/domain/i_share.dart +++ b/frontend/app_flowy/lib/workspace/domain/i_share.dart @@ -1,12 +1,12 @@ import 'dart:async'; import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/protobuf.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; abstract class IShare { - Future> exportText(String docId); + Future> exportText(String docId); - Future> exportMarkdown(String docId); + Future> exportMarkdown(String docId); - Future> exportURL(String docId); + Future> exportURL(String docId); } diff --git a/frontend/app_flowy/lib/workspace/domain/i_trash.dart b/frontend/app_flowy/lib/workspace/domain/i_trash.dart index 5ab660f081..b72d815217 100644 --- a/frontend/app_flowy/lib/workspace/domain/i_trash.dart +++ b/frontend/app_flowy/lib/workspace/domain/i_trash.dart @@ -1,21 +1,21 @@ import 'dart:async'; import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/trash_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; abstract class ITrash { - Future, WorkspaceError>> readTrash(); + Future, FlowyError>> readTrash(); - Future> putback(String trashId); + Future> putback(String trashId); - Future> deleteViews(List> trashList); + Future> deleteViews(List> trashList); - Future> restoreAll(); + Future> restoreAll(); - Future> deleteAll(); + Future> deleteAll(); } -typedef TrashUpdatedCallback = void Function(Either, WorkspaceError> trashOrFailed); +typedef TrashUpdatedCallback = void Function(Either, FlowyError> trashOrFailed); abstract class ITrashListener { void start(TrashUpdatedCallback updateCallback); diff --git a/frontend/app_flowy/lib/workspace/domain/i_user.dart b/frontend/app_flowy/lib/workspace/domain/i_user.dart index 4fc5ecab1d..c035da9b3c 100644 --- a/frontend/app_flowy/lib/workspace/domain/i_user.dart +++ b/frontend/app_flowy/lib/workspace/domain/i_user.dart @@ -1,24 +1,22 @@ import 'package:dartz/dartz.dart'; import 'package:flowy_infra/notifier.dart'; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile; import 'package:flowy_sdk/protobuf/flowy-core-infra/workspace_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; -export 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; export 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProfile; abstract class IUser { UserProfile get user; - Future> fetchUserProfile(String userId); - Future, WorkspaceError>> fetchWorkspaces(); - Future> deleteWorkspace(String workspaceId); - Future> signOut(); - Future> initUser(); + Future> fetchUserProfile(String userId); + Future, FlowyError>> fetchWorkspaces(); + Future> deleteWorkspace(String workspaceId); + Future> signOut(); + Future> initUser(); } -typedef UserProfileUpdatedNotifierValue = Either; -typedef AuthNotifierValue = Either; -typedef WorkspaceUpdatedNotifierValue = Either, WorkspaceError>; +typedef UserProfileUpdatedNotifierValue = Either; +typedef AuthNotifierValue = Either; +typedef WorkspaceUpdatedNotifierValue = Either, FlowyError>; abstract class IUserListener { void start(); diff --git a/frontend/app_flowy/lib/workspace/domain/i_view.dart b/frontend/app_flowy/lib/workspace/domain/i_view.dart index d982baf00f..5675dbda80 100644 --- a/frontend/app_flowy/lib/workspace/domain/i_view.dart +++ b/frontend/app_flowy/lib/workspace/domain/i_view.dart @@ -1,22 +1,22 @@ import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; import 'package:dartz/dartz.dart'; import 'package:flowy_infra/notifier.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; -typedef ViewUpdatedCallback = void Function(Either); +typedef ViewUpdatedCallback = void Function(Either); -typedef DeleteNotifierValue = Either; -typedef UpdateNotifierValue = Either; -typedef RestoreNotifierValue = Either; +typedef DeleteNotifierValue = Either; +typedef UpdateNotifierValue = Either; +typedef RestoreNotifierValue = Either; abstract class IView { View get view; - Future> delete(); + Future> delete(); - Future> rename(String newName); + Future> rename(String newName); - Future> duplicate(); + Future> duplicate(); } abstract class IViewListener { diff --git a/frontend/app_flowy/lib/workspace/domain/i_workspace.dart b/frontend/app_flowy/lib/workspace/domain/i_workspace.dart index beb85d0115..0b9e016fb2 100644 --- a/frontend/app_flowy/lib/workspace/domain/i_workspace.dart +++ b/frontend/app_flowy/lib/workspace/domain/i_workspace.dart @@ -1,15 +1,15 @@ import 'package:flowy_sdk/protobuf/flowy-core-infra/protobuf.dart'; import 'package:dartz/dartz.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; -typedef WorkspaceAppsChangedCallback = void Function(Either, WorkspaceError> appsOrFail); +typedef WorkspaceAppsChangedCallback = void Function(Either, FlowyError> appsOrFail); typedef WorkspaceUpdatedCallback = void Function(String name, String desc); abstract class IWorkspace { - Future> createApp({required String name, String? desc}); + Future> createApp({required String name, String? desc}); - Future, WorkspaceError>> getApps(); + Future, FlowyError>> getApps(); } abstract class IWorkspaceListener { diff --git a/frontend/app_flowy/lib/workspace/infrastructure/i_app_impl.dart b/frontend/app_flowy/lib/workspace/infrastructure/i_app_impl.dart index 2dec77f617..2960f6acec 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/i_app_impl.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/i_app_impl.dart @@ -2,7 +2,7 @@ import 'package:app_flowy/workspace/infrastructure/repos/app_repo.dart'; import 'package:dartz/dartz.dart'; import 'package:app_flowy/workspace/domain/i_app.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; export 'package:app_flowy/workspace/domain/i_app.dart'; class IAppImpl extends IApp { @@ -12,12 +12,12 @@ class IAppImpl extends IApp { }); @override - Future, WorkspaceError>> getViews() { + Future, FlowyError>> getViews() { return repo.getViews(); } @override - Future> createView({required String name, String? desc, required ViewType viewType}) { + Future> createView({required String name, String? desc, required ViewType viewType}) { return repo.createView(name, desc ?? "", viewType).then((result) { return result.fold( (view) => left(view), @@ -27,12 +27,12 @@ class IAppImpl extends IApp { } @override - Future> delete() { + Future> delete() { return repo.delete(); } @override - Future> rename(String newName) { + Future> rename(String newName) { return repo.updateApp(name: newName); } } diff --git a/frontend/app_flowy/lib/workspace/infrastructure/i_doc_impl.dart b/frontend/app_flowy/lib/workspace/infrastructure/i_doc_impl.dart index a1f281bea0..d188b579f8 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/i_doc_impl.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/i_doc_impl.dart @@ -5,7 +5,7 @@ import 'package:dartz/dartz.dart'; import 'package:app_flowy/workspace/domain/i_doc.dart'; import 'package:app_flowy/workspace/infrastructure/repos/doc_repo.dart'; import 'package:flowy_sdk/protobuf/flowy-collaboration/doc.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; class IDocImpl extends IDoc { DocRepository repo; @@ -13,18 +13,18 @@ class IDocImpl extends IDoc { IDocImpl({required this.repo}); @override - Future> closeDoc() { + Future> closeDoc() { return repo.closeDoc(); } @override - Future> readDoc() async { + Future> readDoc() async { final docOrFail = await repo.readDoc(); return docOrFail; } @override - Future> composeDelta({required String json}) { + Future> composeDelta({required String json}) { return repo.composeDelta(data: json); } } diff --git a/frontend/app_flowy/lib/workspace/infrastructure/i_share_impl.dart b/frontend/app_flowy/lib/workspace/infrastructure/i_share_impl.dart index 12ed9722c4..5b2b4bc20d 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/i_share_impl.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/i_share_impl.dart @@ -1,6 +1,6 @@ import 'package:app_flowy/workspace/domain/i_share.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/protobuf.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:dartz/dartz.dart'; import 'repos/share_repo.dart'; @@ -11,17 +11,17 @@ class IShareImpl extends IShare { IShareImpl({required this.repo}); @override - Future> exportText(String docId) { + Future> exportText(String docId) { return repo.export(docId, ExportType.Text); } @override - Future> exportMarkdown(String docId) { + Future> exportMarkdown(String docId) { return repo.export(docId, ExportType.Markdown); } @override - Future> exportURL(String docId) { + Future> exportURL(String docId) { return repo.export(docId, ExportType.Link); } } diff --git a/frontend/app_flowy/lib/workspace/infrastructure/i_trash_impl.dart b/frontend/app_flowy/lib/workspace/infrastructure/i_trash_impl.dart index 26a44ba169..c20c3c639a 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/i_trash_impl.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/i_trash_impl.dart @@ -2,7 +2,7 @@ import 'package:app_flowy/workspace/domain/i_trash.dart'; import 'package:app_flowy/workspace/infrastructure/repos/trash_repo.dart'; import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/trash_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; class ITrashImpl implements ITrash { TrashRepo repo; @@ -10,7 +10,7 @@ class ITrashImpl implements ITrash { ITrashImpl({required this.repo}); @override - Future, WorkspaceError>> readTrash() { + Future, FlowyError>> readTrash() { return repo.readTrash().then((result) { return result.fold( (repeatedTrash) => left(repeatedTrash.items), @@ -20,22 +20,22 @@ class ITrashImpl implements ITrash { } @override - Future> putback(String trashId) { + Future> putback(String trashId) { return repo.putback(trashId); } @override - Future> deleteAll() { + Future> deleteAll() { return repo.deleteAll(); } @override - Future> restoreAll() { + Future> restoreAll() { return repo.restoreAll(); } @override - Future> deleteViews(List> trashList) { + Future> deleteViews(List> trashList) { return repo.deleteViews(trashList); } } diff --git a/frontend/app_flowy/lib/workspace/infrastructure/i_user_impl.dart b/frontend/app_flowy/lib/workspace/infrastructure/i_user_impl.dart index 08d7e3e12e..73e85d1b9f 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/i_user_impl.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/i_user_impl.dart @@ -10,7 +10,7 @@ import 'package:flowy_sdk/protobuf/flowy-user-infra/errors.pb.dart'; // import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart' as user_error; import 'package:flowy_sdk/protobuf/flowy-user/observable.pb.dart' as user; import 'package:flowy_sdk/protobuf/flowy-core-infra/workspace_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core/observable.pb.dart'; export 'package:app_flowy/workspace/domain/i_user.dart'; export 'package:app_flowy/workspace/infrastructure/repos/user_repo.dart'; @@ -24,17 +24,17 @@ class IUserImpl extends IUser { }); @override - Future> deleteWorkspace(String workspaceId) { + Future> deleteWorkspace(String workspaceId) { return repo.deleteWorkspace(workspaceId: workspaceId); } @override - Future> fetchUserProfile(String userId) { + Future> fetchUserProfile(String userId) { return repo.fetchUserProfile(userId: userId); } @override - Future> signOut() { + Future> signOut() { return repo.signOut(); } @@ -42,12 +42,12 @@ class IUserImpl extends IUser { UserProfile get user => repo.user; @override - Future, WorkspaceError>> fetchWorkspaces() { + Future, FlowyError>> fetchWorkspaces() { return repo.getWorkspaces(); } @override - Future> initUser() { + Future> initUser() { return repo.initUser(); } } @@ -88,7 +88,7 @@ class IUserListenerImpl extends IUserListener { await _subscription?.cancel(); } - void _notificationCallback(WorkspaceNotification ty, Either result) { + void _notificationCallback(WorkspaceNotification ty, Either result) { switch (ty) { case WorkspaceNotification.UserCreateWorkspace: case WorkspaceNotification.UserDeleteWorkspace: @@ -101,7 +101,7 @@ class IUserListenerImpl extends IUserListener { case WorkspaceNotification.UserUnauthorized: result.fold( (_) {}, - (error) => authDidChangedNotifier.value = right(UserError.create()..code = ErrorCode.UserUnauthorized.value), + (error) => authDidChangedNotifier.value = right(FlowyError.create()..code = ErrorCode.UserUnauthorized.value), ); break; default: @@ -109,7 +109,7 @@ class IUserListenerImpl extends IUserListener { } } - void _userNotificationCallback(user.UserNotification ty, Either result) { + void _userNotificationCallback(user.UserNotification ty, Either result) { switch (ty) { case user.UserNotification.UserUnauthorized: result.fold( diff --git a/frontend/app_flowy/lib/workspace/infrastructure/i_view_impl.dart b/frontend/app_flowy/lib/workspace/infrastructure/i_view_impl.dart index 84bc049b33..3d1b4c3232 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/i_view_impl.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/i_view_impl.dart @@ -3,7 +3,7 @@ import 'package:app_flowy/workspace/infrastructure/repos/view_repo.dart'; import 'package:flowy_infra/notifier.dart'; import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; class IViewImpl extends IView { ViewRepository repo; @@ -14,7 +14,7 @@ class IViewImpl extends IView { View get view => repo.view; @override - Future> delete() { + Future> delete() { return repo.delete().then((result) { return result.fold( (_) => left(unit), @@ -24,12 +24,12 @@ class IViewImpl extends IView { } @override - Future> rename(String newName) { + Future> rename(String newName) { return repo.updateView(name: newName); } @override - Future> duplicate() { + Future> duplicate() { return repo.duplicate(); } } diff --git a/frontend/app_flowy/lib/workspace/infrastructure/i_workspace_impl.dart b/frontend/app_flowy/lib/workspace/infrastructure/i_workspace_impl.dart index a90e9b62c3..8be815a11d 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/i_workspace_impl.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/i_workspace_impl.dart @@ -2,7 +2,7 @@ import 'package:app_flowy/workspace/domain/i_workspace.dart'; import 'package:app_flowy/workspace/infrastructure/repos/workspace_repo.dart'; import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/app_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; export 'package:app_flowy/workspace/domain/i_workspace.dart'; @@ -13,12 +13,12 @@ class IWorkspaceImpl extends IWorkspace { }); @override - Future> createApp({required String name, String? desc}) { + Future> createApp({required String name, String? desc}) { return repo.createApp(name, desc ?? ""); } @override - Future, WorkspaceError>> getApps() { + Future, FlowyError>> getApps() { return repo.getApps().then((result) { return result.fold( (apps) => left(apps), diff --git a/frontend/app_flowy/lib/workspace/infrastructure/repos/app_repo.dart b/frontend/app_flowy/lib/workspace/infrastructure/repos/app_repo.dart index d5cb40af1c..836ac852cf 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/repos/app_repo.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/repos/app_repo.dart @@ -9,7 +9,7 @@ import 'package:flowy_sdk/protobuf/flowy-core-infra/app_create.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/app_query.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/app_update.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core/observable.pb.dart'; import 'package:flowy_sdk/rust_stream.dart'; import 'helper.dart'; @@ -20,13 +20,13 @@ class AppRepository { required this.appId, }); - Future> getAppDesc() { + Future> getAppDesc() { final request = QueryAppRequest.create()..appIds.add(appId); return WorkspaceEventReadApp(request).send(); } - Future> createView(String name, String desc, ViewType viewType) { + Future> createView(String name, String desc, ViewType viewType) { final request = CreateViewRequest.create() ..belongToId = appId ..name = name @@ -36,7 +36,7 @@ class AppRepository { return WorkspaceEventCreateView(request).send(); } - Future, WorkspaceError>> getViews() { + Future, FlowyError>> getViews() { final request = QueryAppRequest.create()..appIds.add(appId); return WorkspaceEventReadApp(request).send().then((result) { @@ -47,12 +47,12 @@ class AppRepository { }); } - Future> delete() { + Future> delete() { final request = QueryAppRequest.create()..appIds.add(appId); return WorkspaceEventDeleteApp(request).send(); } - Future> updateApp({String? name}) { + Future> updateApp({String? name}) { UpdateAppRequest request = UpdateAppRequest.create()..appId = appId; if (name != null) { @@ -80,7 +80,7 @@ class AppListenerRepository { _subscription = RustStreamReceiver.listen((observable) => _parser.parse(observable)); } - void _bservableCallback(WorkspaceNotification ty, Either result) { + void _bservableCallback(WorkspaceNotification ty, Either result) { switch (ty) { case WorkspaceNotification.AppViewsChanged: if (_viewsChanged != null) { diff --git a/frontend/app_flowy/lib/workspace/infrastructure/repos/doc_repo.dart b/frontend/app_flowy/lib/workspace/infrastructure/repos/doc_repo.dart index 696143f6fd..76d640d60d 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/repos/doc_repo.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/repos/doc_repo.dart @@ -2,7 +2,7 @@ import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/dispatch/dispatch.dart'; import 'package:flowy_sdk/protobuf/flowy-collaboration/doc.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_query.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; class DocRepository { final String docId; @@ -10,19 +10,19 @@ class DocRepository { required this.docId, }); - Future> readDoc() { + Future> readDoc() { final request = QueryViewRequest(viewIds: [docId]); return WorkspaceEventOpenView(request).send(); } - Future> composeDelta({required String data}) { + Future> composeDelta({required String data}) { final request = DocDelta.create() ..docId = docId ..data = data; return WorkspaceEventApplyDocDelta(request).send(); } - Future> closeDoc() { + Future> closeDoc() { final request = QueryViewRequest(viewIds: [docId]); return WorkspaceEventCloseView(request).send(); } diff --git a/frontend/app_flowy/lib/workspace/infrastructure/repos/helper.dart b/frontend/app_flowy/lib/workspace/infrastructure/repos/helper.dart index 2110e6f725..2894bdd771 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/repos/helper.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/repos/helper.dart @@ -2,30 +2,30 @@ import 'dart:typed_data'; import 'package:flowy_sdk/protobuf/dart-notify/protobuf.dart'; import 'package:flowy_sdk/protobuf/flowy-user/protobuf.dart'; import 'package:dartz/dartz.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core/observable.pb.dart'; -typedef UserNotificationCallback = void Function(UserNotification, Either); +typedef UserNotificationCallback = void Function(UserNotification, Either); -class UserNotificationParser extends NotificationParser { +class UserNotificationParser extends NotificationParser { UserNotificationParser({required String id, required UserNotificationCallback callback}) : super( id: id, callback: callback, tyParser: (ty) => UserNotification.valueOf(ty), - errorParser: (bytes) => UserError.fromBuffer(bytes), + errorParser: (bytes) => FlowyError.fromBuffer(bytes), ); } -typedef NotificationCallback = void Function(WorkspaceNotification, Either); +typedef NotificationCallback = void Function(WorkspaceNotification, Either); -class WorkspaceNotificationParser extends NotificationParser { +class WorkspaceNotificationParser extends NotificationParser { WorkspaceNotificationParser({String? id, required NotificationCallback callback}) : super( id: id, callback: callback, tyParser: (ty) => WorkspaceNotification.valueOf(ty), - errorParser: (bytes) => WorkspaceError.fromBuffer(bytes), + errorParser: (bytes) => FlowyError.fromBuffer(bytes), ); } diff --git a/frontend/app_flowy/lib/workspace/infrastructure/repos/share_repo.dart b/frontend/app_flowy/lib/workspace/infrastructure/repos/share_repo.dart index 85f8334316..8289f4a97c 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/repos/share_repo.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/repos/share_repo.dart @@ -2,10 +2,10 @@ import 'dart:async'; import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/dispatch/dispatch.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/protobuf.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; class ShareRepo { - Future> export(String docId, ExportType type) { + Future> export(String docId, ExportType type) { final request = ExportRequest.create() ..docId = docId ..exportType = type; diff --git a/frontend/app_flowy/lib/workspace/infrastructure/repos/trash_repo.dart b/frontend/app_flowy/lib/workspace/infrastructure/repos/trash_repo.dart index 821c1db7af..9656f1432d 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/repos/trash_repo.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/repos/trash_repo.dart @@ -6,22 +6,22 @@ import 'package:dartz/dartz.dart'; import 'package:flowy_sdk/dispatch/dispatch.dart'; import 'package:flowy_sdk/protobuf/dart-notify/subject.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/trash_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core/observable.pb.dart'; import 'package:flowy_sdk/rust_stream.dart'; class TrashRepo { - Future> readTrash() { + Future> readTrash() { return WorkspaceEventReadTrash().send(); } - Future> putback(String trashId) { + Future> putback(String trashId) { final id = TrashIdentifier.create()..id = trashId; return WorkspaceEventPutbackTrash(id).send(); } - Future> deleteViews(List> trashList) { + Future> deleteViews(List> trashList) { final items = trashList.map((trash) { return TrashIdentifier.create() ..id = trash.value1 @@ -32,11 +32,11 @@ class TrashRepo { return WorkspaceEventDeleteTrash(trashIdentifiers).send(); } - Future> restoreAll() { + Future> restoreAll() { return WorkspaceEventRestoreAll().send(); } - Future> deleteAll() { + Future> deleteAll() { return WorkspaceEventDeleteAll().send(); } } @@ -52,7 +52,7 @@ class TrashListenerRepo { _subscription = RustStreamReceiver.listen((observable) => _parser.parse(observable)); } - void _bservableCallback(WorkspaceNotification ty, Either result) { + void _bservableCallback(WorkspaceNotification ty, Either result) { switch (ty) { case WorkspaceNotification.TrashUpdated: if (_trashUpdated != null) { diff --git a/frontend/app_flowy/lib/workspace/infrastructure/repos/user_repo.dart b/frontend/app_flowy/lib/workspace/infrastructure/repos/user_repo.dart index 2d5411739a..b35a771b47 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/repos/user_repo.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/repos/user_repo.dart @@ -4,7 +4,7 @@ import 'package:flowy_sdk/dispatch/dispatch.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/workspace_create.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/workspace_query.pb.dart'; import 'package:app_flowy/workspace/domain/i_user.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; class UserRepo { final UserProfile user; @@ -12,23 +12,23 @@ class UserRepo { required this.user, }); - Future> fetchUserProfile({required String userId}) { + Future> fetchUserProfile({required String userId}) { return UserEventGetUserProfile().send(); } - Future> deleteWorkspace({required String workspaceId}) { + Future> deleteWorkspace({required String workspaceId}) { throw UnimplementedError(); } - Future> signOut() { + Future> signOut() { return UserEventSignOut().send(); } - Future> initUser() async { + Future> initUser() async { return UserEventInitUser().send(); } - Future, WorkspaceError>> getWorkspaces() { + Future, FlowyError>> getWorkspaces() { final request = QueryWorkspaceRequest.create(); return WorkspaceEventReadWorkspaces(request).send().then((result) { @@ -39,7 +39,7 @@ class UserRepo { }); } - Future> openWorkspace(String workspaceId) { + Future> openWorkspace(String workspaceId) { final request = QueryWorkspaceRequest.create()..workspaceId = workspaceId; return WorkspaceEventOpenWorkspace(request).send().then((result) { return result.fold( @@ -49,7 +49,7 @@ class UserRepo { }); } - Future> createWorkspace(String name, String desc) { + Future> createWorkspace(String name, String desc) { final request = CreateWorkspaceRequest.create() ..name = name ..desc = desc; diff --git a/frontend/app_flowy/lib/workspace/infrastructure/repos/view_repo.dart b/frontend/app_flowy/lib/workspace/infrastructure/repos/view_repo.dart index 96d19d80b8..2a2629f09f 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/repos/view_repo.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/repos/view_repo.dart @@ -6,7 +6,7 @@ import 'package:flowy_sdk/protobuf/dart-notify/subject.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_query.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_update.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core/observable.pb.dart'; import 'package:flowy_sdk/rust_stream.dart'; @@ -21,12 +21,12 @@ class ViewRepository { required this.view, }); - Future> readView() { + Future> readView() { final request = QueryViewRequest(viewIds: [view.id]); return WorkspaceEventReadView(request).send(); } - Future> updateView({String? name, String? desc}) { + Future> updateView({String? name, String? desc}) { final request = UpdateViewRequest.create()..viewId = view.id; if (name != null) { @@ -40,12 +40,12 @@ class ViewRepository { return WorkspaceEventUpdateView(request).send(); } - Future> delete() { + Future> delete() { final request = QueryViewRequest.create()..viewIds.add(view.id); return WorkspaceEventDeleteView(request).send(); } - Future> duplicate() { + Future> duplicate() { final request = QueryViewRequest.create()..viewIds.add(view.id); return WorkspaceEventDuplicateView(request).send(); } @@ -74,7 +74,7 @@ class ViewListenerRepository { _subscription = RustStreamReceiver.listen((observable) => _parser.parse(observable)); } - void _handleObservableType(WorkspaceNotification ty, Either result) { + void _handleObservableType(WorkspaceNotification ty, Either result) { switch (ty) { case WorkspaceNotification.ViewUpdated: result.fold( diff --git a/frontend/app_flowy/lib/workspace/infrastructure/repos/workspace_repo.dart b/frontend/app_flowy/lib/workspace/infrastructure/repos/workspace_repo.dart index c9d192c370..c14a5d75d1 100644 --- a/frontend/app_flowy/lib/workspace/infrastructure/repos/workspace_repo.dart +++ b/frontend/app_flowy/lib/workspace/infrastructure/repos/workspace_repo.dart @@ -10,7 +10,7 @@ import 'package:flowy_sdk/protobuf/flowy-user-infra/protobuf.dart' show UserProf import 'package:flowy_sdk/protobuf/flowy-core-infra/app_create.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/workspace_create.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/workspace_query.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core/observable.pb.dart'; import 'package:flowy_sdk/rust_stream.dart'; @@ -27,7 +27,7 @@ class WorkspaceRepo { required this.workspaceId, }); - Future> createApp(String appName, String desc) { + Future> createApp(String appName, String desc) { final request = CreateAppRequest.create() ..name = appName ..workspaceId = workspaceId @@ -35,7 +35,7 @@ class WorkspaceRepo { return WorkspaceEventCreateApp(request).send(); } - Future> getWorkspace() { + Future> getWorkspace() { final request = QueryWorkspaceRequest.create()..workspaceId = workspaceId; return WorkspaceEventReadWorkspaces(request).send().then((result) { return result.fold( @@ -43,7 +43,7 @@ class WorkspaceRepo { assert(workspaces.items.length == 1); if (workspaces.items.isEmpty) { - return right(WorkspaceError.create()..msg = LocaleKeys.workspace_notFoundError.tr()); + return right(FlowyError.create()..msg = LocaleKeys.workspace_notFoundError.tr()); } else { return left(workspaces.items[0]); } @@ -53,7 +53,7 @@ class WorkspaceRepo { }); } - Future, WorkspaceError>> getApps() { + Future, FlowyError>> getApps() { final request = QueryWorkspaceRequest.create()..workspaceId = workspaceId; return WorkspaceEventReadWorkspaceApps(request).send().then((result) { return result.fold( @@ -94,7 +94,7 @@ class WorkspaceListenerRepo { _subscription = RustStreamReceiver.listen((observable) => _parser.parse(observable)); } - void _handleObservableType(WorkspaceNotification ty, Either result) { + void _handleObservableType(WorkspaceNotification ty, Either result) { switch (ty) { case WorkspaceNotification.WorkspaceUpdated: if (_update != null) { diff --git a/frontend/app_flowy/lib/workspace/presentation/stack_page/doc/doc_stack_page.dart b/frontend/app_flowy/lib/workspace/presentation/stack_page/doc/doc_stack_page.dart index 65ca557600..d6d960423b 100644 --- a/frontend/app_flowy/lib/workspace/presentation/stack_page/doc/doc_stack_page.dart +++ b/frontend/app_flowy/lib/workspace/presentation/stack_page/doc/doc_stack_page.dart @@ -14,7 +14,7 @@ import 'package:flowy_infra_ui/widget/rounded_button.dart'; import 'package:flowy_log/flowy_log.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/export.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core-infra/view_create.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; +import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flutter/material.dart'; import 'package:dartz/dartz.dart' as dartz; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -200,7 +200,7 @@ class DocShareButton extends StatelessWidget { } } - void _handleExportError(WorkspaceError error) {} + void _handleExportError(FlowyError error) {} void _showActionList(BuildContext context, Offset offset) { final actionList = ShareActions(onSelected: (result) { diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/dispatch/code_gen.dart b/frontend/app_flowy/packages/flowy_sdk/lib/dispatch/code_gen.dart index b3ffb53705..fdf3cddf4f 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/dispatch/code_gen.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/dispatch/code_gen.dart @@ -6,7 +6,7 @@ class WorkspaceEventCreateWorkspace { CreateWorkspaceRequest request; WorkspaceEventCreateWorkspace(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.CreateWorkspace.toString() ..payload = requestToBytes(this.request); @@ -14,7 +14,7 @@ class WorkspaceEventCreateWorkspace { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(Workspace.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -22,13 +22,13 @@ class WorkspaceEventCreateWorkspace { class WorkspaceEventReadCurWorkspace { WorkspaceEventReadCurWorkspace(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.ReadCurWorkspace.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (okBytes) => left(CurrentWorkspaceSetting.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -37,7 +37,7 @@ class WorkspaceEventReadWorkspaces { QueryWorkspaceRequest request; WorkspaceEventReadWorkspaces(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.ReadWorkspaces.toString() ..payload = requestToBytes(this.request); @@ -45,7 +45,7 @@ class WorkspaceEventReadWorkspaces { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(RepeatedWorkspace.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -54,7 +54,7 @@ class WorkspaceEventDeleteWorkspace { QueryWorkspaceRequest request; WorkspaceEventDeleteWorkspace(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.DeleteWorkspace.toString() ..payload = requestToBytes(this.request); @@ -62,7 +62,7 @@ class WorkspaceEventDeleteWorkspace { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -71,7 +71,7 @@ class WorkspaceEventOpenWorkspace { QueryWorkspaceRequest request; WorkspaceEventOpenWorkspace(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.OpenWorkspace.toString() ..payload = requestToBytes(this.request); @@ -79,7 +79,7 @@ class WorkspaceEventOpenWorkspace { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(Workspace.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -88,7 +88,7 @@ class WorkspaceEventReadWorkspaceApps { QueryWorkspaceRequest request; WorkspaceEventReadWorkspaceApps(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.ReadWorkspaceApps.toString() ..payload = requestToBytes(this.request); @@ -96,7 +96,7 @@ class WorkspaceEventReadWorkspaceApps { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(RepeatedApp.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -105,7 +105,7 @@ class WorkspaceEventCreateApp { CreateAppRequest request; WorkspaceEventCreateApp(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.CreateApp.toString() ..payload = requestToBytes(this.request); @@ -113,7 +113,7 @@ class WorkspaceEventCreateApp { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(App.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -122,7 +122,7 @@ class WorkspaceEventDeleteApp { QueryAppRequest request; WorkspaceEventDeleteApp(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.DeleteApp.toString() ..payload = requestToBytes(this.request); @@ -130,7 +130,7 @@ class WorkspaceEventDeleteApp { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -139,7 +139,7 @@ class WorkspaceEventReadApp { QueryAppRequest request; WorkspaceEventReadApp(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.ReadApp.toString() ..payload = requestToBytes(this.request); @@ -147,7 +147,7 @@ class WorkspaceEventReadApp { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(App.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -156,7 +156,7 @@ class WorkspaceEventUpdateApp { UpdateAppRequest request; WorkspaceEventUpdateApp(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.UpdateApp.toString() ..payload = requestToBytes(this.request); @@ -164,7 +164,7 @@ class WorkspaceEventUpdateApp { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -173,7 +173,7 @@ class WorkspaceEventCreateView { CreateViewRequest request; WorkspaceEventCreateView(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.CreateView.toString() ..payload = requestToBytes(this.request); @@ -181,7 +181,7 @@ class WorkspaceEventCreateView { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(View.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -190,7 +190,7 @@ class WorkspaceEventReadView { QueryViewRequest request; WorkspaceEventReadView(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.ReadView.toString() ..payload = requestToBytes(this.request); @@ -198,7 +198,7 @@ class WorkspaceEventReadView { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(View.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -207,7 +207,7 @@ class WorkspaceEventUpdateView { UpdateViewRequest request; WorkspaceEventUpdateView(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.UpdateView.toString() ..payload = requestToBytes(this.request); @@ -215,7 +215,7 @@ class WorkspaceEventUpdateView { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(View.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -224,7 +224,7 @@ class WorkspaceEventDeleteView { QueryViewRequest request; WorkspaceEventDeleteView(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.DeleteView.toString() ..payload = requestToBytes(this.request); @@ -232,7 +232,7 @@ class WorkspaceEventDeleteView { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -241,7 +241,7 @@ class WorkspaceEventDuplicateView { QueryViewRequest request; WorkspaceEventDuplicateView(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.DuplicateView.toString() ..payload = requestToBytes(this.request); @@ -249,7 +249,7 @@ class WorkspaceEventDuplicateView { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -257,13 +257,13 @@ class WorkspaceEventDuplicateView { class WorkspaceEventCopyLink { WorkspaceEventCopyLink(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.CopyLink.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -272,7 +272,7 @@ class WorkspaceEventOpenView { QueryViewRequest request; WorkspaceEventOpenView(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.OpenView.toString() ..payload = requestToBytes(this.request); @@ -280,7 +280,7 @@ class WorkspaceEventOpenView { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(DocDelta.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -289,7 +289,7 @@ class WorkspaceEventCloseView { QueryViewRequest request; WorkspaceEventCloseView(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.CloseView.toString() ..payload = requestToBytes(this.request); @@ -297,7 +297,7 @@ class WorkspaceEventCloseView { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -305,13 +305,13 @@ class WorkspaceEventCloseView { class WorkspaceEventReadTrash { WorkspaceEventReadTrash(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.ReadTrash.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (okBytes) => left(RepeatedTrash.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -320,7 +320,7 @@ class WorkspaceEventPutbackTrash { TrashIdentifier request; WorkspaceEventPutbackTrash(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.PutbackTrash.toString() ..payload = requestToBytes(this.request); @@ -328,7 +328,7 @@ class WorkspaceEventPutbackTrash { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -337,7 +337,7 @@ class WorkspaceEventDeleteTrash { TrashIdentifiers request; WorkspaceEventDeleteTrash(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.DeleteTrash.toString() ..payload = requestToBytes(this.request); @@ -345,7 +345,7 @@ class WorkspaceEventDeleteTrash { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -353,13 +353,13 @@ class WorkspaceEventDeleteTrash { class WorkspaceEventRestoreAll { WorkspaceEventRestoreAll(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.RestoreAll.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -367,13 +367,13 @@ class WorkspaceEventRestoreAll { class WorkspaceEventDeleteAll { WorkspaceEventDeleteAll(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.DeleteAll.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -382,7 +382,7 @@ class WorkspaceEventApplyDocDelta { DocDelta request; WorkspaceEventApplyDocDelta(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.ApplyDocDelta.toString() ..payload = requestToBytes(this.request); @@ -390,7 +390,7 @@ class WorkspaceEventApplyDocDelta { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(DocDelta.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -399,7 +399,7 @@ class WorkspaceEventExportDocument { ExportRequest request; WorkspaceEventExportDocument(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = WorkspaceEvent.ExportDocument.toString() ..payload = requestToBytes(this.request); @@ -407,7 +407,7 @@ class WorkspaceEventExportDocument { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(ExportData.fromBuffer(okBytes)), - (errBytes) => right(WorkspaceError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -432,13 +432,13 @@ class NetworkEventUpdateNetworkType { class UserEventInitUser { UserEventInitUser(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = UserEvent.InitUser.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(UserError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -447,7 +447,7 @@ class UserEventSignIn { SignInRequest request; UserEventSignIn(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = UserEvent.SignIn.toString() ..payload = requestToBytes(this.request); @@ -455,7 +455,7 @@ class UserEventSignIn { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(UserProfile.fromBuffer(okBytes)), - (errBytes) => right(UserError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -464,7 +464,7 @@ class UserEventSignUp { SignUpRequest request; UserEventSignUp(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = UserEvent.SignUp.toString() ..payload = requestToBytes(this.request); @@ -472,7 +472,7 @@ class UserEventSignUp { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (okBytes) => left(UserProfile.fromBuffer(okBytes)), - (errBytes) => right(UserError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -480,13 +480,13 @@ class UserEventSignUp { class UserEventSignOut { UserEventSignOut(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = UserEvent.SignOut.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(UserError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -495,7 +495,7 @@ class UserEventUpdateUser { UpdateUserRequest request; UserEventUpdateUser(this.request); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = UserEvent.UpdateUser.toString() ..payload = requestToBytes(this.request); @@ -503,7 +503,7 @@ class UserEventUpdateUser { return Dispatch.asyncRequest(request) .then((bytesResult) => bytesResult.fold( (bytes) => left(unit), - (errBytes) => right(UserError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -511,13 +511,13 @@ class UserEventUpdateUser { class UserEventGetUserProfile { UserEventGetUserProfile(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = UserEvent.GetUserProfile.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (okBytes) => left(UserProfile.fromBuffer(okBytes)), - (errBytes) => right(UserError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } @@ -525,13 +525,13 @@ class UserEventGetUserProfile { class UserEventCheckUser { UserEventCheckUser(); - Future> send() { + Future> send() { final request = FFIRequest.create() ..event = UserEvent.CheckUser.toString(); return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( (okBytes) => left(UserProfile.fromBuffer(okBytes)), - (errBytes) => right(UserError.fromBuffer(errBytes)), + (errBytes) => right(FlowyError.fromBuffer(errBytes)), )); } } diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/dispatch/dispatch.dart b/frontend/app_flowy/packages/flowy_sdk/lib/dispatch/dispatch.dart index 157693177c..9768873400 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/dispatch/dispatch.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/dispatch/dispatch.dart @@ -6,9 +6,7 @@ import 'package:flowy_sdk/protobuf/dart-ffi/ffi_response.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-net/event.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-net/network_state.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-user/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-user/event.pb.dart'; -import 'package:flowy_sdk/protobuf/flowy-core/errors.pb.dart'; import 'package:flowy_sdk/protobuf/flowy-core/event.pb.dart'; import 'package:isolates/isolates.dart'; import 'package:isolates/ports.dart'; diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbenum.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pb.dart similarity index 74% rename from frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbenum.dart rename to frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pb.dart index 2bb3f5b53b..6817422f70 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbenum.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pb.dart @@ -1,7 +1,11 @@ /// // Generated code. Do not modify. -// source: errors.proto +// source: error_code.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields +import 'dart:core' as $core; + +export 'error_code.pbenum.dart'; + diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbenum.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbenum.dart new file mode 100644 index 0000000000..5cc919914a --- /dev/null +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbenum.dart @@ -0,0 +1,82 @@ +/// +// Generated code. Do not modify. +// source: error_code.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields + +// ignore_for_file: UNDEFINED_SHOWN_NAME +import 'dart:core' as $core; +import 'package:protobuf/protobuf.dart' as $pb; + +class ErrorCode extends $pb.ProtobufEnum { + static const ErrorCode Internal = ErrorCode._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'Internal'); + static const ErrorCode UserUnauthorized = ErrorCode._(2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserUnauthorized'); + static const ErrorCode RecordNotFound = ErrorCode._(3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'RecordNotFound'); + static const ErrorCode WorkspaceNameInvalid = ErrorCode._(100, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceNameInvalid'); + static const ErrorCode WorkspaceIdInvalid = ErrorCode._(101, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceIdInvalid'); + static const ErrorCode AppColorStyleInvalid = ErrorCode._(102, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppColorStyleInvalid'); + static const ErrorCode WorkspaceDescTooLong = ErrorCode._(103, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceDescTooLong'); + static const ErrorCode WorkspaceNameTooLong = ErrorCode._(104, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WorkspaceNameTooLong'); + static const ErrorCode AppIdInvalid = ErrorCode._(110, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppIdInvalid'); + static const ErrorCode AppNameInvalid = ErrorCode._(111, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'AppNameInvalid'); + static const ErrorCode ViewNameInvalid = ErrorCode._(120, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ViewNameInvalid'); + static const ErrorCode ViewThumbnailInvalid = ErrorCode._(121, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ViewThumbnailInvalid'); + static const ErrorCode ViewIdInvalid = ErrorCode._(122, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ViewIdInvalid'); + static const ErrorCode ViewDescTooLong = ErrorCode._(123, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ViewDescTooLong'); + static const ErrorCode ViewDataInvalid = ErrorCode._(124, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ViewDataInvalid'); + static const ErrorCode ViewNameTooLong = ErrorCode._(125, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ViewNameTooLong'); + static const ErrorCode ConnectError = ErrorCode._(200, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ConnectError'); + static const ErrorCode EmailIsEmpty = ErrorCode._(300, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'EmailIsEmpty'); + static const ErrorCode EmailFormatInvalid = ErrorCode._(301, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'EmailFormatInvalid'); + static const ErrorCode EmailAlreadyExists = ErrorCode._(302, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'EmailAlreadyExists'); + static const ErrorCode PasswordIsEmpty = ErrorCode._(303, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PasswordIsEmpty'); + static const ErrorCode PasswordTooLong = ErrorCode._(304, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PasswordTooLong'); + static const ErrorCode PasswordContainsForbidCharacters = ErrorCode._(305, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PasswordContainsForbidCharacters'); + static const ErrorCode PasswordFormatInvalid = ErrorCode._(306, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PasswordFormatInvalid'); + static const ErrorCode PasswordNotMatch = ErrorCode._(307, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PasswordNotMatch'); + static const ErrorCode UserNameTooLong = ErrorCode._(308, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNameTooLong'); + static const ErrorCode UserNameContainForbiddenCharacters = ErrorCode._(309, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNameContainForbiddenCharacters'); + static const ErrorCode UserNameIsEmpty = ErrorCode._(310, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNameIsEmpty'); + static const ErrorCode UserIdInvalid = ErrorCode._(311, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserIdInvalid'); + static const ErrorCode UserNotExist = ErrorCode._(312, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserNotExist'); + + static const $core.List values = [ + Internal, + UserUnauthorized, + RecordNotFound, + WorkspaceNameInvalid, + WorkspaceIdInvalid, + AppColorStyleInvalid, + WorkspaceDescTooLong, + WorkspaceNameTooLong, + AppIdInvalid, + AppNameInvalid, + ViewNameInvalid, + ViewThumbnailInvalid, + ViewIdInvalid, + ViewDescTooLong, + ViewDataInvalid, + ViewNameTooLong, + ConnectError, + EmailIsEmpty, + EmailFormatInvalid, + EmailAlreadyExists, + PasswordIsEmpty, + PasswordTooLong, + PasswordContainsForbidCharacters, + PasswordFormatInvalid, + PasswordNotMatch, + UserNameTooLong, + UserNameContainForbiddenCharacters, + UserNameIsEmpty, + UserIdInvalid, + UserNotExist, + ]; + + static final $core.Map<$core.int, ErrorCode> _byValue = $pb.ProtobufEnum.initByValue(values); + static ErrorCode? valueOf($core.int value) => _byValue[value]; + + const ErrorCode._($core.int v, $core.String n) : super(v, n); +} + diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbjson.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbjson.dart new file mode 100644 index 0000000000..5d30b04f64 --- /dev/null +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbjson.dart @@ -0,0 +1,49 @@ +/// +// Generated code. Do not modify. +// source: error_code.proto +// +// @dart = 2.12 +// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package + +import 'dart:core' as $core; +import 'dart:convert' as $convert; +import 'dart:typed_data' as $typed_data; +@$core.Deprecated('Use errorCodeDescriptor instead') +const ErrorCode$json = const { + '1': 'ErrorCode', + '2': const [ + const {'1': 'Internal', '2': 0}, + const {'1': 'UserUnauthorized', '2': 2}, + const {'1': 'RecordNotFound', '2': 3}, + const {'1': 'WorkspaceNameInvalid', '2': 100}, + const {'1': 'WorkspaceIdInvalid', '2': 101}, + const {'1': 'AppColorStyleInvalid', '2': 102}, + const {'1': 'WorkspaceDescTooLong', '2': 103}, + const {'1': 'WorkspaceNameTooLong', '2': 104}, + const {'1': 'AppIdInvalid', '2': 110}, + const {'1': 'AppNameInvalid', '2': 111}, + const {'1': 'ViewNameInvalid', '2': 120}, + const {'1': 'ViewThumbnailInvalid', '2': 121}, + const {'1': 'ViewIdInvalid', '2': 122}, + const {'1': 'ViewDescTooLong', '2': 123}, + const {'1': 'ViewDataInvalid', '2': 124}, + const {'1': 'ViewNameTooLong', '2': 125}, + const {'1': 'ConnectError', '2': 200}, + const {'1': 'EmailIsEmpty', '2': 300}, + const {'1': 'EmailFormatInvalid', '2': 301}, + const {'1': 'EmailAlreadyExists', '2': 302}, + const {'1': 'PasswordIsEmpty', '2': 303}, + const {'1': 'PasswordTooLong', '2': 304}, + const {'1': 'PasswordContainsForbidCharacters', '2': 305}, + const {'1': 'PasswordFormatInvalid', '2': 306}, + const {'1': 'PasswordNotMatch', '2': 307}, + const {'1': 'UserNameTooLong', '2': 308}, + const {'1': 'UserNameContainForbiddenCharacters', '2': 309}, + const {'1': 'UserNameIsEmpty', '2': 310}, + const {'1': 'UserIdInvalid', '2': 311}, + const {'1': 'UserNotExist', '2': 312}, + ], +}; + +/// Descriptor for `ErrorCode`. Decode as a `google.protobuf.EnumDescriptorProto`. +final $typed_data.Uint8List errorCodeDescriptor = $convert.base64Decode('CglFcnJvckNvZGUSDAoISW50ZXJuYWwQABIUChBVc2VyVW5hdXRob3JpemVkEAISEgoOUmVjb3JkTm90Rm91bmQQAxIYChRXb3Jrc3BhY2VOYW1lSW52YWxpZBBkEhYKEldvcmtzcGFjZUlkSW52YWxpZBBlEhgKFEFwcENvbG9yU3R5bGVJbnZhbGlkEGYSGAoUV29ya3NwYWNlRGVzY1Rvb0xvbmcQZxIYChRXb3Jrc3BhY2VOYW1lVG9vTG9uZxBoEhAKDEFwcElkSW52YWxpZBBuEhIKDkFwcE5hbWVJbnZhbGlkEG8SEwoPVmlld05hbWVJbnZhbGlkEHgSGAoUVmlld1RodW1ibmFpbEludmFsaWQQeRIRCg1WaWV3SWRJbnZhbGlkEHoSEwoPVmlld0Rlc2NUb29Mb25nEHsSEwoPVmlld0RhdGFJbnZhbGlkEHwSEwoPVmlld05hbWVUb29Mb25nEH0SEQoMQ29ubmVjdEVycm9yEMgBEhEKDEVtYWlsSXNFbXB0eRCsAhIXChJFbWFpbEZvcm1hdEludmFsaWQQrQISFwoSRW1haWxBbHJlYWR5RXhpc3RzEK4CEhQKD1Bhc3N3b3JkSXNFbXB0eRCvAhIUCg9QYXNzd29yZFRvb0xvbmcQsAISJQogUGFzc3dvcmRDb250YWluc0ZvcmJpZENoYXJhY3RlcnMQsQISGgoVUGFzc3dvcmRGb3JtYXRJbnZhbGlkELICEhUKEFBhc3N3b3JkTm90TWF0Y2gQswISFAoPVXNlck5hbWVUb29Mb25nELQCEicKIlVzZXJOYW1lQ29udGFpbkZvcmJpZGRlbkNoYXJhY3RlcnMQtQISFAoPVXNlck5hbWVJc0VtcHR5ELYCEhIKDVVzZXJJZEludmFsaWQQtwISEQoMVXNlck5vdEV4aXN0ELgC'); diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbserver.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbserver.dart similarity index 84% rename from frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbserver.dart rename to frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbserver.dart index 18b02b9216..a38de6d5a4 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbserver.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/error_code.pbserver.dart @@ -1,9 +1,9 @@ /// // Generated code. Do not modify. -// source: errors.proto +// source: error_code.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package -export 'errors.pb.dart'; +export 'error_code.pb.dart'; diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/protobuf.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/protobuf.dart new file mode 100644 index 0000000000..379334caf0 --- /dev/null +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/error-code/protobuf.dart @@ -0,0 +1,2 @@ +// Auto-generated, do not edit +export './error_code.pb.dart'; diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pb.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pb.dart deleted file mode 100644 index b03dd960be..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pb.dart +++ /dev/null @@ -1,72 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields - -import 'dart:core' as $core; - -import 'package:protobuf/protobuf.dart' as $pb; - -class WorkspaceError extends $pb.GeneratedMessage { - static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'WorkspaceError', createEmptyInstance: create) - ..a<$core.int>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'code', $pb.PbFieldType.O3) - ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'msg') - ..hasRequiredFields = false - ; - - WorkspaceError._() : super(); - factory WorkspaceError({ - $core.int? code, - $core.String? msg, - }) { - final _result = create(); - if (code != null) { - _result.code = code; - } - if (msg != null) { - _result.msg = msg; - } - return _result; - } - factory WorkspaceError.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory WorkspaceError.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - WorkspaceError clone() => WorkspaceError()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - WorkspaceError copyWith(void Function(WorkspaceError) updates) => super.copyWith((message) => updates(message as WorkspaceError)) as WorkspaceError; // ignore: deprecated_member_use - $pb.BuilderInfo get info_ => _i; - @$core.pragma('dart2js:noInline') - static WorkspaceError create() => WorkspaceError._(); - WorkspaceError createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); - @$core.pragma('dart2js:noInline') - static WorkspaceError getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); - static WorkspaceError? _defaultInstance; - - @$pb.TagNumber(1) - $core.int get code => $_getIZ(0); - @$pb.TagNumber(1) - set code($core.int v) { $_setSignedInt32(0, v); } - @$pb.TagNumber(1) - $core.bool hasCode() => $_has(0); - @$pb.TagNumber(1) - void clearCode() => clearField(1); - - @$pb.TagNumber(2) - $core.String get msg => $_getSZ(1); - @$pb.TagNumber(2) - set msg($core.String v) { $_setString(1, v); } - @$pb.TagNumber(2) - $core.bool hasMsg() => $_has(1); - @$pb.TagNumber(2) - void clearMsg() => clearField(2); -} - diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbjson.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbjson.dart deleted file mode 100644 index dd6a45e8d9..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbjson.dart +++ /dev/null @@ -1,21 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package - -import 'dart:core' as $core; -import 'dart:convert' as $convert; -import 'dart:typed_data' as $typed_data; -@$core.Deprecated('Use workspaceErrorDescriptor instead') -const WorkspaceError$json = const { - '1': 'WorkspaceError', - '2': const [ - const {'1': 'code', '3': 1, '4': 1, '5': 5, '10': 'code'}, - const {'1': 'msg', '3': 2, '4': 1, '5': 9, '10': 'msg'}, - ], -}; - -/// Descriptor for `WorkspaceError`. Decode as a `google.protobuf.DescriptorProto`. -final $typed_data.Uint8List workspaceErrorDescriptor = $convert.base64Decode('Cg5Xb3Jrc3BhY2VFcnJvchISCgRjb2RlGAEgASgFUgRjb2RlEhAKA21zZxgCIAEoCVIDbXNn'); diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbserver.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbserver.dart deleted file mode 100644 index 18b02b9216..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/errors.pbserver.dart +++ /dev/null @@ -1,9 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package - -export 'errors.pb.dart'; - diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/protobuf.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/protobuf.dart index bb4f1f6e45..0cd5547d0a 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/protobuf.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-core/protobuf.dart @@ -1,4 +1,3 @@ // Auto-generated, do not edit export './observable.pb.dart'; -export './errors.pb.dart'; export './event.pb.dart'; diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pb.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pb.dart deleted file mode 100644 index fbb5affe8e..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pb.dart +++ /dev/null @@ -1,76 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields - -import 'dart:core' as $core; - -import 'package:protobuf/protobuf.dart' as $pb; - -import 'errors.pbenum.dart'; - -export 'errors.pbenum.dart'; - -class DocError extends $pb.GeneratedMessage { - static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'DocError', createEmptyInstance: create) - ..e(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'code', $pb.PbFieldType.OE, defaultOrMaker: ErrorCode.WsConnectError, valueOf: ErrorCode.valueOf, enumValues: ErrorCode.values) - ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'msg') - ..hasRequiredFields = false - ; - - DocError._() : super(); - factory DocError({ - ErrorCode? code, - $core.String? msg, - }) { - final _result = create(); - if (code != null) { - _result.code = code; - } - if (msg != null) { - _result.msg = msg; - } - return _result; - } - factory DocError.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory DocError.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - DocError clone() => DocError()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - DocError copyWith(void Function(DocError) updates) => super.copyWith((message) => updates(message as DocError)) as DocError; // ignore: deprecated_member_use - $pb.BuilderInfo get info_ => _i; - @$core.pragma('dart2js:noInline') - static DocError create() => DocError._(); - DocError createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); - @$core.pragma('dart2js:noInline') - static DocError getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); - static DocError? _defaultInstance; - - @$pb.TagNumber(1) - ErrorCode get code => $_getN(0); - @$pb.TagNumber(1) - set code(ErrorCode v) { setField(1, v); } - @$pb.TagNumber(1) - $core.bool hasCode() => $_has(0); - @$pb.TagNumber(1) - void clearCode() => clearField(1); - - @$pb.TagNumber(2) - $core.String get msg => $_getSZ(1); - @$pb.TagNumber(2) - set msg($core.String v) { $_setString(1, v); } - @$pb.TagNumber(2) - $core.bool hasMsg() => $_has(1); - @$pb.TagNumber(2) - void clearMsg() => clearField(2); -} - diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbenum.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbenum.dart deleted file mode 100644 index 5933af7967..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbenum.dart +++ /dev/null @@ -1,32 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields - -// ignore_for_file: UNDEFINED_SHOWN_NAME -import 'dart:core' as $core; -import 'package:protobuf/protobuf.dart' as $pb; - -class ErrorCode extends $pb.ProtobufEnum { - static const ErrorCode WsConnectError = ErrorCode._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'WsConnectError'); - static const ErrorCode DocNotfound = ErrorCode._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DocNotfound'); - static const ErrorCode DuplicateRevision = ErrorCode._(2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DuplicateRevision'); - static const ErrorCode UserUnauthorized = ErrorCode._(10, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UserUnauthorized'); - static const ErrorCode InternalError = ErrorCode._(1000, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'InternalError'); - - static const $core.List values = [ - WsConnectError, - DocNotfound, - DuplicateRevision, - UserUnauthorized, - InternalError, - ]; - - static final $core.Map<$core.int, ErrorCode> _byValue = $pb.ProtobufEnum.initByValue(values); - static ErrorCode? valueOf($core.int value) => _byValue[value]; - - const ErrorCode._($core.int v, $core.String n) : super(v, n); -} - diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbjson.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbjson.dart deleted file mode 100644 index a707e66df7..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/errors.pbjson.dart +++ /dev/null @@ -1,35 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package - -import 'dart:core' as $core; -import 'dart:convert' as $convert; -import 'dart:typed_data' as $typed_data; -@$core.Deprecated('Use errorCodeDescriptor instead') -const ErrorCode$json = const { - '1': 'ErrorCode', - '2': const [ - const {'1': 'WsConnectError', '2': 0}, - const {'1': 'DocNotfound', '2': 1}, - const {'1': 'DuplicateRevision', '2': 2}, - const {'1': 'UserUnauthorized', '2': 10}, - const {'1': 'InternalError', '2': 1000}, - ], -}; - -/// Descriptor for `ErrorCode`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List errorCodeDescriptor = $convert.base64Decode('CglFcnJvckNvZGUSEgoOV3NDb25uZWN0RXJyb3IQABIPCgtEb2NOb3Rmb3VuZBABEhUKEUR1cGxpY2F0ZVJldmlzaW9uEAISFAoQVXNlclVuYXV0aG9yaXplZBAKEhIKDUludGVybmFsRXJyb3IQ6Ac='); -@$core.Deprecated('Use docErrorDescriptor instead') -const DocError$json = const { - '1': 'DocError', - '2': const [ - const {'1': 'code', '3': 1, '4': 1, '5': 14, '6': '.ErrorCode', '10': 'code'}, - const {'1': 'msg', '3': 2, '4': 1, '5': 9, '10': 'msg'}, - ], -}; - -/// Descriptor for `DocError`. Decode as a `google.protobuf.DescriptorProto`. -final $typed_data.Uint8List docErrorDescriptor = $convert.base64Decode('CghEb2NFcnJvchIeCgRjb2RlGAEgASgOMgouRXJyb3JDb2RlUgRjb2RlEhAKA21zZxgCIAEoCVIDbXNn'); diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/protobuf.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/protobuf.dart index 463cec0dc3..7353db8c64 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/protobuf.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-document/protobuf.dart @@ -1,3 +1,2 @@ // Auto-generated, do not edit export './observable.pb.dart'; -export './errors.pb.dart'; diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pb.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pb.dart index 7d0a6cb8f4..95122bdd41 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pb.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pb.dart @@ -9,8 +9,6 @@ import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; -export 'errors.pbenum.dart'; - class FlowyError extends $pb.GeneratedMessage { static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'FlowyError', createEmptyInstance: create) ..a<$core.int>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'code', $pb.PbFieldType.O3) diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pbenum.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pbenum.dart index 8d31a7370b..2bb3f5b53b 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pbenum.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pbenum.dart @@ -5,20 +5,3 @@ // @dart = 2.12 // ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields -// ignore_for_file: UNDEFINED_SHOWN_NAME -import 'dart:core' as $core; -import 'package:protobuf/protobuf.dart' as $pb; - -class ErrorCode extends $pb.ProtobufEnum { - static const ErrorCode Internal = ErrorCode._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'Internal'); - - static const $core.List values = [ - Internal, - ]; - - static final $core.Map<$core.int, ErrorCode> _byValue = $pb.ProtobufEnum.initByValue(values); - static ErrorCode? valueOf($core.int value) => _byValue[value]; - - const ErrorCode._($core.int v, $core.String n) : super(v, n); -} - diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pbjson.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pbjson.dart index b9209928ce..18f397fbe8 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pbjson.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-error/errors.pbjson.dart @@ -8,16 +8,6 @@ import 'dart:core' as $core; import 'dart:convert' as $convert; import 'dart:typed_data' as $typed_data; -@$core.Deprecated('Use errorCodeDescriptor instead') -const ErrorCode$json = const { - '1': 'ErrorCode', - '2': const [ - const {'1': 'Internal', '2': 0}, - ], -}; - -/// Descriptor for `ErrorCode`. Decode as a `google.protobuf.EnumDescriptorProto`. -final $typed_data.Uint8List errorCodeDescriptor = $convert.base64Decode('CglFcnJvckNvZGUSDAoISW50ZXJuYWwQAA=='); @$core.Deprecated('Use flowyErrorDescriptor instead') const FlowyError$json = const { '1': 'FlowyError', diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pb.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pb.dart deleted file mode 100644 index a6bf94f671..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pb.dart +++ /dev/null @@ -1,72 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields - -import 'dart:core' as $core; - -import 'package:protobuf/protobuf.dart' as $pb; - -class UserError extends $pb.GeneratedMessage { - static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'UserError', createEmptyInstance: create) - ..a<$core.int>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'code', $pb.PbFieldType.O3) - ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'msg') - ..hasRequiredFields = false - ; - - UserError._() : super(); - factory UserError({ - $core.int? code, - $core.String? msg, - }) { - final _result = create(); - if (code != null) { - _result.code = code; - } - if (msg != null) { - _result.msg = msg; - } - return _result; - } - factory UserError.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory UserError.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - UserError clone() => UserError()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - UserError copyWith(void Function(UserError) updates) => super.copyWith((message) => updates(message as UserError)) as UserError; // ignore: deprecated_member_use - $pb.BuilderInfo get info_ => _i; - @$core.pragma('dart2js:noInline') - static UserError create() => UserError._(); - UserError createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); - @$core.pragma('dart2js:noInline') - static UserError getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); - static UserError? _defaultInstance; - - @$pb.TagNumber(1) - $core.int get code => $_getIZ(0); - @$pb.TagNumber(1) - set code($core.int v) { $_setSignedInt32(0, v); } - @$pb.TagNumber(1) - $core.bool hasCode() => $_has(0); - @$pb.TagNumber(1) - void clearCode() => clearField(1); - - @$pb.TagNumber(2) - $core.String get msg => $_getSZ(1); - @$pb.TagNumber(2) - set msg($core.String v) { $_setString(1, v); } - @$pb.TagNumber(2) - $core.bool hasMsg() => $_has(1); - @$pb.TagNumber(2) - void clearMsg() => clearField(2); -} - diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart deleted file mode 100644 index 2bb3f5b53b..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbenum.dart +++ /dev/null @@ -1,7 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields - diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart deleted file mode 100644 index c9eaa6f189..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbjson.dart +++ /dev/null @@ -1,21 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package - -import 'dart:core' as $core; -import 'dart:convert' as $convert; -import 'dart:typed_data' as $typed_data; -@$core.Deprecated('Use userErrorDescriptor instead') -const UserError$json = const { - '1': 'UserError', - '2': const [ - const {'1': 'code', '3': 1, '4': 1, '5': 5, '10': 'code'}, - const {'1': 'msg', '3': 2, '4': 1, '5': 9, '10': 'msg'}, - ], -}; - -/// Descriptor for `UserError`. Decode as a `google.protobuf.DescriptorProto`. -final $typed_data.Uint8List userErrorDescriptor = $convert.base64Decode('CglVc2VyRXJyb3ISEgoEY29kZRgBIAEoBVIEY29kZRIQCgNtc2cYAiABKAlSA21zZw=='); diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbserver.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbserver.dart deleted file mode 100644 index 18b02b9216..0000000000 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/errors.pbserver.dart +++ /dev/null @@ -1,9 +0,0 @@ -/// -// Generated code. Do not modify. -// source: errors.proto -// -// @dart = 2.12 -// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package - -export 'errors.pb.dart'; - diff --git a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/protobuf.dart b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/protobuf.dart index bb4f1f6e45..0cd5547d0a 100644 --- a/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/protobuf.dart +++ b/frontend/app_flowy/packages/flowy_sdk/lib/protobuf/flowy-user/protobuf.dart @@ -1,4 +1,3 @@ // Auto-generated, do not edit export './observable.pb.dart'; -export './errors.pb.dart'; export './event.pb.dart'; diff --git a/frontend/rust-lib/flowy-core/Cargo.toml b/frontend/rust-lib/flowy-core/Cargo.toml index 6a464bd687..44e1523c6d 100644 --- a/frontend/rust-lib/flowy-core/Cargo.toml +++ b/frontend/rust-lib/flowy-core/Cargo.toml @@ -16,6 +16,7 @@ lib-infra = { path = "../../../shared-lib/lib-infra" } flowy-document = { path = "../flowy-document" } flowy-database = { path = "../flowy-database" } +flowy-error = { path = "../flowy-error", features = ["db", "backend"]} flowy-net = { path = "../flowy-net" } dart-notify = { path = "../dart-notify" } lib-dispatch = { path = "../lib-dispatch" } diff --git a/frontend/rust-lib/flowy-core/src/core/aggregate_tasks/workspace_task.rs b/frontend/rust-lib/flowy-core/src/core/aggregate_tasks/workspace_task.rs index 39cffec56e..747a4e81c9 100644 --- a/frontend/rust-lib/flowy-core/src/core/aggregate_tasks/workspace_task.rs +++ b/frontend/rust-lib/flowy-core/src/core/aggregate_tasks/workspace_task.rs @@ -1,6 +1,6 @@ use crate::{ core::CoreContext, - errors::WorkspaceError, + errors::FlowyError, notify::{send_dart_notification, WorkspaceNotification}, services::workspace::sql::{WorkspaceTable, WorkspaceTableSql}, }; @@ -13,7 +13,7 @@ pub fn read_workspaces_on_server( core: Unit>, user_id: String, params: WorkspaceIdentifier, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let (token, server) = (core.user.token()?, core.server.clone()); let app_ctrl = core.app_controller.clone(); let view_ctrl = core.view_controller.clone(); @@ -22,7 +22,7 @@ pub fn read_workspaces_on_server( tokio::spawn(async move { // Opti: handle the error and retry? let workspaces = server.read_workspace(&token, params).await?; - let _ = (&*conn).immediate_transaction::<_, WorkspaceError, _>(|| { + let _ = (&*conn).immediate_transaction::<_, FlowyError, _>(|| { tracing::debug!("Save {} workspace", workspaces.len()); for workspace in &workspaces.items { let m_workspace = workspace.clone(); @@ -53,7 +53,7 @@ pub fn read_workspaces_on_server( send_dart_notification(&token, WorkspaceNotification::WorkspaceListUpdated) .payload(workspaces) .send(); - Result::<(), WorkspaceError>::Ok(()) + Result::<(), FlowyError>::Ok(()) }); Ok(()) diff --git a/frontend/rust-lib/flowy-core/src/core/core_context.rs b/frontend/rust-lib/flowy-core/src/core/core_context.rs index 0f94565e39..2b9a4431ca 100644 --- a/frontend/rust-lib/flowy-core/src/core/core_context.rs +++ b/frontend/rust-lib/flowy-core/src/core/core_context.rs @@ -10,7 +10,7 @@ use flowy_net::entities::NetworkType; use crate::{ entities::workspace::RepeatedWorkspace, - errors::{WorkspaceError, WorkspaceResult}, + errors::{FlowyError, FlowyResult}, module::{WorkspaceDatabase, WorkspaceUser}, notify::{send_dart_notification, WorkspaceNotification}, services::{server::Server, AppController, TrashController, ViewController, WorkspaceController}, @@ -64,7 +64,7 @@ impl CoreContext { } } - pub async fn user_did_sign_in(&self, token: &str) -> WorkspaceResult<()> { + pub async fn user_did_sign_in(&self, token: &str) -> FlowyResult<()> { log::debug!("workspace initialize after sign in"); let _ = self.init(token).await?; Ok(()) @@ -78,7 +78,7 @@ impl CoreContext { // TODO: (nathan) do something here } - pub async fn user_did_sign_up(&self, _token: &str) -> WorkspaceResult<()> { + pub async fn user_did_sign_up(&self, _token: &str) -> FlowyResult<()> { log::debug!("Create user default workspace"); let time = Utc::now(); let mut workspace = user_default::create_default_workspace(time); @@ -120,7 +120,7 @@ impl CoreContext { Ok(()) } - async fn init(&self, token: &str) -> Result<(), WorkspaceError> { + async fn init(&self, token: &str) -> Result<(), FlowyError> { if let Some(is_init) = INIT_WORKSPACE.read().get(token) { if *is_init { return Ok(()); diff --git a/frontend/rust-lib/flowy-core/src/core/event_handler.rs b/frontend/rust-lib/flowy-core/src/core/event_handler.rs index 9d9a7b7bb4..e7686c9620 100644 --- a/frontend/rust-lib/flowy-core/src/core/event_handler.rs +++ b/frontend/rust-lib/flowy-core/src/core/event_handler.rs @@ -1,6 +1,6 @@ use crate::{ core::{aggregate_tasks::read_workspaces_on_server, CoreContext}, - errors::WorkspaceError, + errors::FlowyError, services::{get_current_workspace, read_local_workspace_apps}, }; use flowy_core_infra::entities::{ @@ -14,14 +14,14 @@ use std::{convert::TryInto, sync::Arc}; pub(crate) async fn read_workspaces_handler( data: Data, core: Unit>, -) -> DataResult { +) -> DataResult { let params: WorkspaceIdentifier = data.into_inner().try_into()?; let user_id = core.user.user_id()?; let conn = &*core.database.db_connection()?; let workspace_controller = core.workspace_controller.clone(); let trash_controller = core.trash_controller.clone(); - let workspaces = conn.immediate_transaction::<_, WorkspaceError, _>(|| { + let workspaces = conn.immediate_transaction::<_, FlowyError, _>(|| { let mut workspaces = workspace_controller.read_local_workspaces(params.workspace_id.clone(), &user_id, conn)?; for workspace in workspaces.iter_mut() { let apps = read_local_workspace_apps(&workspace.id, trash_controller.clone(), conn)?.into_inner(); @@ -38,7 +38,7 @@ pub(crate) async fn read_workspaces_handler( #[tracing::instrument(skip(core), err)] pub async fn read_cur_workspace_handler( core: Unit>, -) -> DataResult { +) -> DataResult { let workspace_id = get_current_workspace()?; let user_id = core.user.user_id()?; let params = WorkspaceIdentifier { diff --git a/frontend/rust-lib/flowy-core/src/errors.rs b/frontend/rust-lib/flowy-core/src/errors.rs deleted file mode 100644 index c0240ad2c5..0000000000 --- a/frontend/rust-lib/flowy-core/src/errors.rs +++ /dev/null @@ -1,106 +0,0 @@ -use bytes::Bytes; - -use backend_service::errors::ErrorCode as ServerErrorCode; -pub use flowy_core_infra::errors::ErrorCode; -use flowy_derive::ProtoBuf; -use flowy_document::errors::DocError; -use lib_dispatch::prelude::{EventResponse, ResponseBuilder}; -use std::{convert::TryInto, fmt, fmt::Debug}; - -pub type WorkspaceResult = std::result::Result; - -#[derive(Debug, Default, Clone, ProtoBuf)] -pub struct WorkspaceError { - #[pb(index = 1)] - pub code: i32, - - #[pb(index = 2)] - pub msg: String, -} - -macro_rules! static_workspace_error { - ($name:ident, $code:expr) => { - #[allow(non_snake_case, missing_docs)] - pub fn $name() -> WorkspaceError { $code.into() } - }; -} - -impl WorkspaceError { - pub fn new(code: ErrorCode, msg: &str) -> Self { - Self { - code: code.value(), - msg: msg.to_owned(), - } - } - - static_workspace_error!(workspace_name, ErrorCode::WorkspaceNameInvalid); - static_workspace_error!(workspace_id, ErrorCode::WorkspaceIdInvalid); - static_workspace_error!(color_style, ErrorCode::AppColorStyleInvalid); - static_workspace_error!(workspace_desc, ErrorCode::WorkspaceDescTooLong); - static_workspace_error!(app_name, ErrorCode::AppNameInvalid); - static_workspace_error!(invalid_app_id, ErrorCode::AppIdInvalid); - static_workspace_error!(view_name, ErrorCode::ViewNameInvalid); - static_workspace_error!(view_thumbnail, ErrorCode::ViewThumbnailInvalid); - static_workspace_error!(invalid_view_id, ErrorCode::ViewIdInvalid); - static_workspace_error!(view_desc, ErrorCode::ViewDescTooLong); - static_workspace_error!(view_data, ErrorCode::ViewDataInvalid); - static_workspace_error!(unauthorized, ErrorCode::UserUnauthorized); - static_workspace_error!(internal, ErrorCode::InternalError); - static_workspace_error!(record_not_found, ErrorCode::RecordNotFound); - static_workspace_error!(ws, ErrorCode::WsConnectError); - - pub fn context(mut self, error: T) -> Self { - self.msg = format!("{:?}", error); - self - } -} - -pub fn internal_error(e: T) -> WorkspaceError -where - T: std::fmt::Debug, -{ - WorkspaceError::internal().context(e) -} - -impl std::convert::From for WorkspaceError { - fn from(code: ErrorCode) -> Self { - WorkspaceError { - code: code.value(), - msg: format!("{}", code), - } - } -} - -impl std::convert::From for WorkspaceError { - fn from(error: DocError) -> Self { WorkspaceError::internal().context(error) } -} - -impl std::convert::From for WorkspaceError { - fn from(error: backend_service::errors::ServerError) -> Self { - let code = server_error_to_workspace_error(error.code); - WorkspaceError::new(code, &error.msg) - } -} - -impl std::convert::From for WorkspaceError { - fn from(error: flowy_database::Error) -> Self { WorkspaceError::internal().context(error) } -} - -impl lib_dispatch::Error for WorkspaceError { - fn as_response(&self) -> EventResponse { - let bytes: Bytes = self.clone().try_into().unwrap(); - ResponseBuilder::Err().data(bytes).build() - } -} - -impl fmt::Display for WorkspaceError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", &self.code, &self.msg) } -} - -fn server_error_to_workspace_error(code: ServerErrorCode) -> ErrorCode { - match code { - ServerErrorCode::UserUnauthorized => ErrorCode::UserUnauthorized, - ServerErrorCode::RecordNotFound => ErrorCode::RecordNotFound, - _ => ErrorCode::InternalError, - } -} diff --git a/frontend/rust-lib/flowy-core/src/event.rs b/frontend/rust-lib/flowy-core/src/event.rs index e89a638275..a6e23a5458 100644 --- a/frontend/rust-lib/flowy-core/src/event.rs +++ b/frontend/rust-lib/flowy-core/src/event.rs @@ -2,7 +2,7 @@ use flowy_derive::{Flowy_Event, ProtoBuf_Enum}; use strum_macros::Display; #[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Hash, ProtoBuf_Enum, Flowy_Event)] -#[event_err = "WorkspaceError"] +#[event_err = "FlowyError"] pub enum WorkspaceEvent { #[event(input = "CreateWorkspaceRequest", output = "Workspace")] CreateWorkspace = 0, diff --git a/frontend/rust-lib/flowy-core/src/lib.rs b/frontend/rust-lib/flowy-core/src/lib.rs index 8de43ec141..5629b3b38e 100644 --- a/frontend/rust-lib/flowy-core/src/lib.rs +++ b/frontend/rust-lib/flowy-core/src/lib.rs @@ -11,7 +11,7 @@ mod macros; extern crate flowy_database; pub mod core; -pub mod errors; + mod notify; pub mod protobuf; mod util; @@ -21,3 +21,7 @@ pub mod prelude { pub use crate::{core::*, errors::*, module::*}; } + +pub mod errors { + pub use flowy_error::{internal_error, ErrorCode, FlowyError, FlowyResult}; +} diff --git a/frontend/rust-lib/flowy-core/src/macros.rs b/frontend/rust-lib/flowy-core/src/macros.rs index 44bae654bb..a02007d694 100644 --- a/frontend/rust-lib/flowy-core/src/macros.rs +++ b/frontend/rust-lib/flowy-core/src/macros.rs @@ -1,7 +1,7 @@ // #[macro_export] // macro_rules! impl_save_func { // ($func_name:ident, $target:ident, $table_name:expr, $conn:ident) => { -// fn $func_name(object: $target) -> Result<(), WorkspaceError> { +// fn $func_name(object: $target) -> Result<(), FlowyError> { // let _ = diesel::insert_into($table_name) // .values($target) // .execute(&*($conn))?; diff --git a/frontend/rust-lib/flowy-core/src/module.rs b/frontend/rust-lib/flowy-core/src/module.rs index 6ea6b64f8d..bb98d8080a 100644 --- a/frontend/rust-lib/flowy-core/src/module.rs +++ b/frontend/rust-lib/flowy-core/src/module.rs @@ -8,7 +8,7 @@ use lib_sqlite::ConnectionPool; use crate::{ core::{event_handler::*, CoreContext}, - errors::WorkspaceError, + errors::FlowyError, event::WorkspaceEvent, services::{ app::event_handler::*, @@ -26,16 +26,16 @@ use crate::{ pub trait WorkspaceDeps: WorkspaceUser + WorkspaceDatabase {} pub trait WorkspaceUser: Send + Sync { - fn user_id(&self) -> Result; - fn token(&self) -> Result; + fn user_id(&self) -> Result; + fn token(&self) -> Result; } pub trait WorkspaceDatabase: Send + Sync { - fn db_pool(&self) -> Result, WorkspaceError>; + fn db_pool(&self) -> Result, FlowyError>; - fn db_connection(&self) -> Result { + fn db_connection(&self) -> Result { let pool = self.db_pool()?; - let conn = pool.get().map_err(|e| WorkspaceError::internal().context(e))?; + let conn = pool.get().map_err(|e| FlowyError::internal().context(e))?; Ok(conn) } } diff --git a/frontend/rust-lib/flowy-core/src/protobuf/model/errors.rs b/frontend/rust-lib/flowy-core/src/protobuf/model/errors.rs deleted file mode 100644 index 4fd34284af..0000000000 --- a/frontend/rust-lib/flowy-core/src/protobuf/model/errors.rs +++ /dev/null @@ -1,243 +0,0 @@ -// This file is generated by rust-protobuf 2.22.1. Do not edit -// @generated - -// https://github.com/rust-lang/rust-clippy/issues/702 -#![allow(unknown_lints)] -#![allow(clippy::all)] - -#![allow(unused_attributes)] -#![cfg_attr(rustfmt, rustfmt::skip)] - -#![allow(box_pointers)] -#![allow(dead_code)] -#![allow(missing_docs)] -#![allow(non_camel_case_types)] -#![allow(non_snake_case)] -#![allow(non_upper_case_globals)] -#![allow(trivial_casts)] -#![allow(unused_imports)] -#![allow(unused_results)] -//! Generated file from `errors.proto` - -/// Generated files are compatible only with the same version -/// of protobuf runtime. -// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_22_1; - -#[derive(PartialEq,Clone,Default)] -pub struct WorkspaceError { - // message fields - pub code: i32, - pub msg: ::std::string::String, - // special fields - pub unknown_fields: ::protobuf::UnknownFields, - pub cached_size: ::protobuf::CachedSize, -} - -impl<'a> ::std::default::Default for &'a WorkspaceError { - fn default() -> &'a WorkspaceError { - ::default_instance() - } -} - -impl WorkspaceError { - pub fn new() -> WorkspaceError { - ::std::default::Default::default() - } - - // int32 code = 1; - - - pub fn get_code(&self) -> i32 { - self.code - } - pub fn clear_code(&mut self) { - self.code = 0; - } - - // Param is passed by value, moved - pub fn set_code(&mut self, v: i32) { - self.code = v; - } - - // string msg = 2; - - - pub fn get_msg(&self) -> &str { - &self.msg - } - pub fn clear_msg(&mut self) { - self.msg.clear(); - } - - // Param is passed by value, moved - pub fn set_msg(&mut self, v: ::std::string::String) { - self.msg = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_msg(&mut self) -> &mut ::std::string::String { - &mut self.msg - } - - // Take field - pub fn take_msg(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.msg, ::std::string::String::new()) - } -} - -impl ::protobuf::Message for WorkspaceError { - fn is_initialized(&self) -> bool { - true - } - - fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != ::protobuf::wire_format::WireTypeVarint { - return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.code = tmp; - }, - 2 => { - ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.msg)?; - }, - _ => { - ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if self.code != 0 { - my_size += ::protobuf::rt::value_size(1, self.code, ::protobuf::wire_format::WireTypeVarint); - } - if !self.msg.is_empty() { - my_size += ::protobuf::rt::string_size(2, &self.msg); - } - my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { - if self.code != 0 { - os.write_int32(1, self.code)?; - } - if !self.msg.is_empty() { - os.write_string(2, &self.msg)?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { - self - } - - fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> WorkspaceError { - WorkspaceError::new() - } - - fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { - static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( - "code", - |m: &WorkspaceError| { &m.code }, - |m: &mut WorkspaceError| { &mut m.code }, - )); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( - "msg", - |m: &WorkspaceError| { &m.msg }, - |m: &mut WorkspaceError| { &mut m.msg }, - )); - ::protobuf::reflect::MessageDescriptor::new_pb_name::( - "WorkspaceError", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static WorkspaceError { - static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; - instance.get(WorkspaceError::new) - } -} - -impl ::protobuf::Clear for WorkspaceError { - fn clear(&mut self) { - self.code = 0; - self.msg.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for WorkspaceError { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::protobuf::text_format::fmt(self, f) - } -} - -impl ::protobuf::reflect::ProtobufValue for WorkspaceError { - fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { - ::protobuf::reflect::ReflectValueRef::Message(self) - } -} - -static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x0cerrors.proto\"6\n\x0eWorkspaceError\x12\x12\n\x04code\x18\x01\x20\ - \x01(\x05R\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\tR\x03msgJ\x98\x01\ - \n\x06\x12\x04\0\0\x05\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\ - \0\x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x16\n\x0b\n\ - \x04\x04\0\x02\0\x12\x03\x03\x04\x13\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\ - \x03\x04\t\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\n\x0e\n\x0c\n\x05\x04\ - \0\x02\0\x03\x12\x03\x03\x11\x12\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\ - \x04\x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\ - \0\x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\ - \x04\x11\x12b\x06proto3\ -"; - -static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { - ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() -} - -pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() - }) -} diff --git a/frontend/rust-lib/flowy-core/src/protobuf/model/mod.rs b/frontend/rust-lib/flowy-core/src/protobuf/model/mod.rs index cd35f2090b..b9a7e246fd 100644 --- a/frontend/rust-lib/flowy-core/src/protobuf/model/mod.rs +++ b/frontend/rust-lib/flowy-core/src/protobuf/model/mod.rs @@ -4,8 +4,5 @@ mod observable; pub use observable::*; -mod errors; -pub use errors::*; - mod event; pub use event::*; diff --git a/frontend/rust-lib/flowy-core/src/protobuf/proto/errors.proto b/frontend/rust-lib/flowy-core/src/protobuf/proto/errors.proto deleted file mode 100644 index b67c663608..0000000000 --- a/frontend/rust-lib/flowy-core/src/protobuf/proto/errors.proto +++ /dev/null @@ -1,6 +0,0 @@ -syntax = "proto3"; - -message WorkspaceError { - int32 code = 1; - string msg = 2; -} diff --git a/frontend/rust-lib/flowy-core/src/services/app/controller.rs b/frontend/rust-lib/flowy-core/src/services/app/controller.rs index e35b2f9f7b..97065ba8d0 100644 --- a/frontend/rust-lib/flowy-core/src/services/app/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/app/controller.rs @@ -39,20 +39,20 @@ impl AppController { } } - pub fn init(&self) -> Result<(), WorkspaceError> { + pub fn init(&self) -> Result<(), FlowyError> { self.listen_trash_can_event(); Ok(()) } #[tracing::instrument(level = "debug", skip(self, params), fields(name = %params.name) err)] - pub(crate) async fn create_app_from_params(&self, params: CreateAppParams) -> Result { + pub(crate) async fn create_app_from_params(&self, params: CreateAppParams) -> Result { let app = self.create_app_on_server(params).await?; self.create_app(app).await } - pub(crate) async fn create_app(&self, app: App) -> Result { + pub(crate) async fn create_app(&self, app: App) -> Result { let conn = &*self.database.db_connection()?; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = self.save_app(app.clone(), &*conn)?; let _ = notify_apps_changed(&app.workspace_id, self.trash_can.clone(), conn)?; Ok(()) @@ -61,30 +61,30 @@ impl AppController { Ok(app) } - pub(crate) fn save_app(&self, app: App, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn save_app(&self, app: App, conn: &SqliteConnection) -> Result<(), FlowyError> { let app_table = AppTable::new(app); let _ = AppTableSql::create_app(app_table, &*conn)?; Ok(()) } - pub(crate) async fn read_app(&self, params: AppIdentifier) -> Result { + pub(crate) async fn read_app(&self, params: AppIdentifier) -> Result { let conn = self.database.db_connection()?; let app_table = AppTableSql::read_app(¶ms.app_id, &*conn)?; let trash_ids = self.trash_can.trash_ids(&conn)?; if trash_ids.contains(&app_table.id) { - return Err(WorkspaceError::record_not_found()); + return Err(FlowyError::record_not_found()); } let _ = self.read_app_on_server(params)?; Ok(app_table.into()) } - pub(crate) async fn update_app(&self, params: UpdateAppParams) -> Result<(), WorkspaceError> { + pub(crate) async fn update_app(&self, params: UpdateAppParams) -> Result<(), FlowyError> { let changeset = AppTableChangeset::new(params.clone()); let app_id = changeset.id.clone(); let conn = &*self.database.db_connection()?; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = AppTableSql::update_app(changeset, conn)?; let app: App = AppTableSql::read_app(&app_id, conn)?.into(); send_dart_notification(&app_id, WorkspaceNotification::AppUpdated) @@ -97,10 +97,10 @@ impl AppController { Ok(()) } - pub(crate) fn read_app_tables(&self, ids: Vec) -> Result, WorkspaceError> { + pub(crate) fn read_app_tables(&self, ids: Vec) -> Result, FlowyError> { let conn = &*self.database.db_connection()?; let mut app_tables = vec![]; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { for app_id in ids { app_tables.push(AppTableSql::read_app(&app_id, conn)?); } @@ -113,14 +113,14 @@ impl AppController { impl AppController { #[tracing::instrument(level = "debug", skip(self), err)] - async fn create_app_on_server(&self, params: CreateAppParams) -> Result { + async fn create_app_on_server(&self, params: CreateAppParams) -> Result { let token = self.user.token()?; let app = self.server.create_app(&token, params).await?; Ok(app) } #[tracing::instrument(level = "debug", skip(self), err)] - fn update_app_on_server(&self, params: UpdateAppParams) -> Result<(), WorkspaceError> { + fn update_app_on_server(&self, params: UpdateAppParams) -> Result<(), FlowyError> { let token = self.user.token()?; let server = self.server.clone(); tokio::spawn(async move { @@ -136,7 +136,7 @@ impl AppController { } #[tracing::instrument(level = "debug", skip(self), err)] - fn read_app_on_server(&self, params: AppIdentifier) -> Result<(), WorkspaceError> { + fn read_app_on_server(&self, params: AppIdentifier) -> Result<(), FlowyError> { let token = self.user.token()?; let server = self.server.clone(); let pool = self.database.db_pool()?; @@ -192,21 +192,21 @@ async fn handle_trash_event(database: Arc, trash_can: Arc TrashEvent::NewTrash(identifiers, ret) | TrashEvent::Putback(identifiers, ret) => { let result = || { let conn = &*db_result?; - let _ = conn.immediate_transaction::<_, WorkspaceError, _>(|| { + let _ = conn.immediate_transaction::<_, FlowyError, _>(|| { for identifier in identifiers.items { let app_table = AppTableSql::read_app(&identifier.id, conn)?; let _ = notify_apps_changed(&app_table.workspace_id, trash_can.clone(), conn)?; } Ok(()) })?; - Ok::<(), WorkspaceError>(()) + Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; }, TrashEvent::Delete(identifiers, ret) => { let result = || { let conn = &*db_result?; - let _ = conn.immediate_transaction::<_, WorkspaceError, _>(|| { + let _ = conn.immediate_transaction::<_, FlowyError, _>(|| { let mut notify_ids = HashSet::new(); for identifier in identifiers.items { let app_table = AppTableSql::read_app(&identifier.id, conn)?; @@ -219,7 +219,7 @@ async fn handle_trash_event(database: Arc, trash_can: Arc } Ok(()) })?; - Ok::<(), WorkspaceError>(()) + Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; }, @@ -231,7 +231,7 @@ fn notify_apps_changed( workspace_id: &str, trash_can: Arc, conn: &SqliteConnection, -) -> WorkspaceResult<()> { +) -> FlowyResult<()> { let repeated_app = read_local_workspace_apps(workspace_id, trash_can, conn)?; send_dart_notification(workspace_id, WorkspaceNotification::WorkspaceAppsChanged) .payload(repeated_app) @@ -243,7 +243,7 @@ pub fn read_local_workspace_apps( workspace_id: &str, trash_controller: Arc, conn: &SqliteConnection, -) -> Result { +) -> Result { let mut app_tables = AppTableSql::read_workspace_apps(workspace_id, false, conn)?; let trash_ids = trash_controller.trash_ids(conn)?; app_tables.retain(|app_table| !trash_ids.contains(&app_table.id)); @@ -254,8 +254,8 @@ pub fn read_local_workspace_apps( // #[tracing::instrument(level = "debug", skip(self), err)] // pub(crate) async fn delete_app(&self, app_id: &str) -> Result<(), -// WorkspaceError> { let conn = &*self.database.db_connection()?; -// conn.immediate_transaction::<_, WorkspaceError, _>(|| { +// FlowyError> { let conn = &*self.database.db_connection()?; +// conn.immediate_transaction::<_, FlowyError, _>(|| { // let app = AppTableSql::delete_app(app_id, &*conn)?; // let apps = self.read_local_apps(&app.workspace_id, &*conn)?; // send_dart_notification(&app.workspace_id, @@ -269,7 +269,7 @@ pub fn read_local_workspace_apps( // } // // #[tracing::instrument(level = "debug", skip(self), err)] -// fn delete_app_on_server(&self, app_id: &str) -> Result<(), WorkspaceError> { +// fn delete_app_on_server(&self, app_id: &str) -> Result<(), FlowyError> { // let token = self.user.token()?; // let server = self.server.clone(); // let params = DeleteAppParams { @@ -291,7 +291,7 @@ pub fn read_local_workspace_apps( // // Ok(_) => {}, // // Err(e) => log::error!("Delete app failed: {:?}", e), // // } -// // Ok::<(), WorkspaceError>(()) +// // Ok::<(), FlowyError>(()) // // } // // }); // // diff --git a/frontend/rust-lib/flowy-core/src/services/app/event_handler.rs b/frontend/rust-lib/flowy-core/src/services/app/event_handler.rs index 011af97ade..5c9cc6f78d 100644 --- a/frontend/rust-lib/flowy-core/src/services/app/event_handler.rs +++ b/frontend/rust-lib/flowy-core/src/services/app/event_handler.rs @@ -11,7 +11,7 @@ use crate::{ }, trash::Trash, }, - errors::WorkspaceError, + errors::FlowyError, services::{AppController, TrashController, ViewController}, }; use lib_dispatch::prelude::{data_result, Data, DataResult, Unit}; @@ -20,7 +20,7 @@ use std::{convert::TryInto, sync::Arc}; pub(crate) async fn create_app_handler( data: Data, controller: Unit>, -) -> DataResult { +) -> DataResult { let params: CreateAppParams = data.into_inner().try_into()?; let detail = controller.create_app_from_params(params).await?; @@ -31,7 +31,7 @@ pub(crate) async fn delete_app_handler( data: Data, controller: Unit>, trash_can: Unit>, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let params: AppIdentifier = data.into_inner().try_into()?; let trash = controller .read_app_tables(vec![params.app_id])? @@ -47,7 +47,7 @@ pub(crate) async fn delete_app_handler( pub(crate) async fn update_app_handler( data: Data, controller: Unit>, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let params: UpdateAppParams = data.into_inner().try_into()?; let _ = controller.update_app(params).await?; Ok(()) @@ -58,7 +58,7 @@ pub(crate) async fn read_app_handler( data: Data, app_controller: Unit>, view_controller: Unit>, -) -> DataResult { +) -> DataResult { let params: AppIdentifier = data.into_inner().try_into()?; let mut app = app_controller.read_app(params.clone()).await?; app.belongings = view_controller.read_views_belong_to(¶ms.app_id).await?; diff --git a/frontend/rust-lib/flowy-core/src/services/app/sql.rs b/frontend/rust-lib/flowy-core/src/services/app/sql.rs index 12b08d55e9..204e3950f6 100644 --- a/frontend/rust-lib/flowy-core/src/services/app/sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/app/sql.rs @@ -15,12 +15,12 @@ use flowy_database::{ use serde::{Deserialize, Serialize, __private::TryFrom}; use std::convert::TryInto; -use crate::errors::WorkspaceError; +use crate::errors::FlowyError; pub struct AppTableSql {} impl AppTableSql { - pub(crate) fn create_app(app_table: AppTable, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn create_app(app_table: AppTable, conn: &SqliteConnection) -> Result<(), FlowyError> { match diesel_record_count!(app_table, &app_table.id, conn) { 0 => diesel_insert_table!(app_table, &app_table, conn), _ => { @@ -31,12 +31,12 @@ impl AppTableSql { Ok(()) } - pub(crate) fn update_app(changeset: AppTableChangeset, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn update_app(changeset: AppTableChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { diesel_update_table!(app_table, changeset, conn); Ok(()) } - pub(crate) fn read_app(app_id: &str, conn: &SqliteConnection) -> Result { + pub(crate) fn read_app(app_id: &str, conn: &SqliteConnection) -> Result { let filter = dsl::app_table.filter(app_table::id.eq(app_id)).into_boxed(); let app_table = filter.first::(conn)?; Ok(app_table) @@ -46,7 +46,7 @@ impl AppTableSql { workspace_id: &str, is_trash: bool, conn: &SqliteConnection, - ) -> Result, WorkspaceError> { + ) -> Result, FlowyError> { let app_table = dsl::app_table .filter(app_table::workspace_id.eq(workspace_id)) .filter(app_table::is_trash.eq(is_trash)) @@ -56,7 +56,7 @@ impl AppTableSql { Ok(app_table) } - pub(crate) fn delete_app(app_id: &str, conn: &SqliteConnection) -> Result { + pub(crate) fn delete_app(app_id: &str, conn: &SqliteConnection) -> Result { let app_table = dsl::app_table .filter(app_table::id.eq(app_id)) .first::(conn)?; @@ -67,10 +67,10 @@ impl AppTableSql { // pub(crate) fn read_views_belong_to_app( // &self, // app_id: &str, - // ) -> Result, WorkspaceError> { + // ) -> Result, FlowyError> { // let conn = self.database.db_connection()?; // - // let views = conn.immediate_transaction::<_, WorkspaceError, _>(|| { + // let views = conn.immediate_transaction::<_, FlowyError, _>(|| { // let app_table: AppTable = dsl::app_table // .filter(app_table::id.eq(app_id)) // .first::(&*(conn))?; diff --git a/frontend/rust-lib/flowy-core/src/services/server/mod.rs b/frontend/rust-lib/flowy-core/src/services/server/mod.rs index 940ba5d6d3..ad47f5201a 100644 --- a/frontend/rust-lib/flowy-core/src/services/server/mod.rs +++ b/frontend/rust-lib/flowy-core/src/services/server/mod.rs @@ -12,7 +12,7 @@ use crate::{ view::{CreateViewParams, UpdateViewParams, View, ViewIdentifier, ViewIdentifiers}, workspace::{CreateWorkspaceParams, RepeatedWorkspace, UpdateWorkspaceParams, Workspace, WorkspaceIdentifier}, }, - errors::WorkspaceError, + errors::FlowyError, }; use backend_service::configuration::ClientServerConfiguration; use lib_infra::future::FutureResult; @@ -24,42 +24,38 @@ pub trait WorkspaceServerAPI { fn init(&self); // Workspace - fn create_workspace(&self, token: &str, params: CreateWorkspaceParams) -> FutureResult; + fn create_workspace(&self, token: &str, params: CreateWorkspaceParams) -> FutureResult; - fn read_workspace( - &self, - token: &str, - params: WorkspaceIdentifier, - ) -> FutureResult; + fn read_workspace(&self, token: &str, params: WorkspaceIdentifier) -> FutureResult; - fn update_workspace(&self, token: &str, params: UpdateWorkspaceParams) -> FutureResult<(), WorkspaceError>; + fn update_workspace(&self, token: &str, params: UpdateWorkspaceParams) -> FutureResult<(), FlowyError>; - fn delete_workspace(&self, token: &str, params: WorkspaceIdentifier) -> FutureResult<(), WorkspaceError>; + fn delete_workspace(&self, token: &str, params: WorkspaceIdentifier) -> FutureResult<(), FlowyError>; // View - fn create_view(&self, token: &str, params: CreateViewParams) -> FutureResult; + fn create_view(&self, token: &str, params: CreateViewParams) -> FutureResult; - fn read_view(&self, token: &str, params: ViewIdentifier) -> FutureResult, WorkspaceError>; + fn read_view(&self, token: &str, params: ViewIdentifier) -> FutureResult, FlowyError>; - fn delete_view(&self, token: &str, params: ViewIdentifiers) -> FutureResult<(), WorkspaceError>; + fn delete_view(&self, token: &str, params: ViewIdentifiers) -> FutureResult<(), FlowyError>; - fn update_view(&self, token: &str, params: UpdateViewParams) -> FutureResult<(), WorkspaceError>; + fn update_view(&self, token: &str, params: UpdateViewParams) -> FutureResult<(), FlowyError>; // App - fn create_app(&self, token: &str, params: CreateAppParams) -> FutureResult; + fn create_app(&self, token: &str, params: CreateAppParams) -> FutureResult; - fn read_app(&self, token: &str, params: AppIdentifier) -> FutureResult, WorkspaceError>; + fn read_app(&self, token: &str, params: AppIdentifier) -> FutureResult, FlowyError>; - fn update_app(&self, token: &str, params: UpdateAppParams) -> FutureResult<(), WorkspaceError>; + fn update_app(&self, token: &str, params: UpdateAppParams) -> FutureResult<(), FlowyError>; - fn delete_app(&self, token: &str, params: AppIdentifier) -> FutureResult<(), WorkspaceError>; + fn delete_app(&self, token: &str, params: AppIdentifier) -> FutureResult<(), FlowyError>; // Trash - fn create_trash(&self, token: &str, params: TrashIdentifiers) -> FutureResult<(), WorkspaceError>; + fn create_trash(&self, token: &str, params: TrashIdentifiers) -> FutureResult<(), FlowyError>; - fn delete_trash(&self, token: &str, params: TrashIdentifiers) -> FutureResult<(), WorkspaceError>; + fn delete_trash(&self, token: &str, params: TrashIdentifiers) -> FutureResult<(), FlowyError>; - fn read_trash(&self, token: &str) -> FutureResult; + fn read_trash(&self, token: &str) -> FutureResult; } pub(crate) fn construct_workspace_server( diff --git a/frontend/rust-lib/flowy-core/src/services/server/server_api.rs b/frontend/rust-lib/flowy-core/src/services/server/server_api.rs index 68fadd59af..d3bee512fb 100644 --- a/frontend/rust-lib/flowy-core/src/services/server/server_api.rs +++ b/frontend/rust-lib/flowy-core/src/services/server/server_api.rs @@ -5,12 +5,11 @@ use crate::{ view::{CreateViewParams, UpdateViewParams, View, ViewIdentifier, ViewIdentifiers}, workspace::{CreateWorkspaceParams, RepeatedWorkspace, UpdateWorkspaceParams, Workspace, WorkspaceIdentifier}, }, - errors::WorkspaceError, + errors::{ErrorCode, FlowyError}, notify::{send_dart_notification, WorkspaceNotification}, services::server::WorkspaceServerAPI, }; use backend_service::{configuration::ClientServerConfiguration, middleware::*, workspace_request::*}; -use flowy_core_infra::errors::ErrorCode; use lib_infra::future::FutureResult; pub struct WorkspaceHttpServer { @@ -26,7 +25,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { let mut rx = BACKEND_API_MIDDLEWARE.invalid_token_subscribe(); tokio::spawn(async move { while let Ok(invalid_token) = rx.recv().await { - let error = WorkspaceError::new(ErrorCode::UserUnauthorized, ""); + let error = FlowyError::new(ErrorCode::UserUnauthorized, ""); send_dart_notification(&invalid_token, WorkspaceNotification::UserUnauthorized) .error(error) .send() @@ -34,7 +33,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }); } - fn create_workspace(&self, token: &str, params: CreateWorkspaceParams) -> FutureResult { + fn create_workspace(&self, token: &str, params: CreateWorkspaceParams) -> FutureResult { let token = token.to_owned(); let url = self.config.workspace_url(); FutureResult::new(async move { @@ -43,11 +42,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn read_workspace( - &self, - token: &str, - params: WorkspaceIdentifier, - ) -> FutureResult { + fn read_workspace(&self, token: &str, params: WorkspaceIdentifier) -> FutureResult { let token = token.to_owned(); let url = self.config.workspace_url(); FutureResult::new(async move { @@ -56,7 +51,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn update_workspace(&self, token: &str, params: UpdateWorkspaceParams) -> FutureResult<(), WorkspaceError> { + fn update_workspace(&self, token: &str, params: UpdateWorkspaceParams) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.workspace_url(); FutureResult::new(async move { @@ -65,7 +60,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn delete_workspace(&self, token: &str, params: WorkspaceIdentifier) -> FutureResult<(), WorkspaceError> { + fn delete_workspace(&self, token: &str, params: WorkspaceIdentifier) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.workspace_url(); FutureResult::new(async move { @@ -74,7 +69,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn create_view(&self, token: &str, params: CreateViewParams) -> FutureResult { + fn create_view(&self, token: &str, params: CreateViewParams) -> FutureResult { let token = token.to_owned(); let url = self.config.view_url(); FutureResult::new(async move { @@ -83,7 +78,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn read_view(&self, token: &str, params: ViewIdentifier) -> FutureResult, WorkspaceError> { + fn read_view(&self, token: &str, params: ViewIdentifier) -> FutureResult, FlowyError> { let token = token.to_owned(); let url = self.config.view_url(); FutureResult::new(async move { @@ -92,7 +87,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn delete_view(&self, token: &str, params: ViewIdentifiers) -> FutureResult<(), WorkspaceError> { + fn delete_view(&self, token: &str, params: ViewIdentifiers) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.view_url(); FutureResult::new(async move { @@ -101,7 +96,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn update_view(&self, token: &str, params: UpdateViewParams) -> FutureResult<(), WorkspaceError> { + fn update_view(&self, token: &str, params: UpdateViewParams) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.view_url(); FutureResult::new(async move { @@ -110,7 +105,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn create_app(&self, token: &str, params: CreateAppParams) -> FutureResult { + fn create_app(&self, token: &str, params: CreateAppParams) -> FutureResult { let token = token.to_owned(); let url = self.config.app_url(); FutureResult::new(async move { @@ -119,7 +114,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn read_app(&self, token: &str, params: AppIdentifier) -> FutureResult, WorkspaceError> { + fn read_app(&self, token: &str, params: AppIdentifier) -> FutureResult, FlowyError> { let token = token.to_owned(); let url = self.config.app_url(); FutureResult::new(async move { @@ -128,7 +123,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn update_app(&self, token: &str, params: UpdateAppParams) -> FutureResult<(), WorkspaceError> { + fn update_app(&self, token: &str, params: UpdateAppParams) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.app_url(); FutureResult::new(async move { @@ -137,7 +132,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn delete_app(&self, token: &str, params: AppIdentifier) -> FutureResult<(), WorkspaceError> { + fn delete_app(&self, token: &str, params: AppIdentifier) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.app_url(); FutureResult::new(async move { @@ -146,7 +141,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn create_trash(&self, token: &str, params: TrashIdentifiers) -> FutureResult<(), WorkspaceError> { + fn create_trash(&self, token: &str, params: TrashIdentifiers) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.trash_url(); FutureResult::new(async move { @@ -155,7 +150,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn delete_trash(&self, token: &str, params: TrashIdentifiers) -> FutureResult<(), WorkspaceError> { + fn delete_trash(&self, token: &str, params: TrashIdentifiers) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.trash_url(); FutureResult::new(async move { @@ -164,7 +159,7 @@ impl WorkspaceServerAPI for WorkspaceHttpServer { }) } - fn read_trash(&self, token: &str) -> FutureResult { + fn read_trash(&self, token: &str) -> FutureResult { let token = token.to_owned(); let url = self.config.trash_url(); FutureResult::new(async move { diff --git a/frontend/rust-lib/flowy-core/src/services/server/server_api_mock.rs b/frontend/rust-lib/flowy-core/src/services/server/server_api_mock.rs index 336d0d9c53..dabc9dd055 100644 --- a/frontend/rust-lib/flowy-core/src/services/server/server_api_mock.rs +++ b/frontend/rust-lib/flowy-core/src/services/server/server_api_mock.rs @@ -5,7 +5,7 @@ use crate::{ view::{CreateViewParams, RepeatedView, UpdateViewParams, View, ViewIdentifier, ViewIdentifiers}, workspace::{CreateWorkspaceParams, RepeatedWorkspace, UpdateWorkspaceParams, Workspace, WorkspaceIdentifier}, }, - errors::WorkspaceError, + errors::FlowyError, services::server::WorkspaceServerAPI, }; use lib_infra::{future::FutureResult, timestamp, uuid}; @@ -15,7 +15,7 @@ pub struct WorkspaceServerMock {} impl WorkspaceServerAPI for WorkspaceServerMock { fn init(&self) {} - fn create_workspace(&self, _token: &str, params: CreateWorkspaceParams) -> FutureResult { + fn create_workspace(&self, _token: &str, params: CreateWorkspaceParams) -> FutureResult { let time = timestamp(); let workspace = Workspace { id: uuid(), @@ -33,22 +33,22 @@ impl WorkspaceServerAPI for WorkspaceServerMock { &self, _token: &str, _params: WorkspaceIdentifier, - ) -> FutureResult { + ) -> FutureResult { FutureResult::new(async { let repeated_workspace = RepeatedWorkspace { items: vec![] }; Ok(repeated_workspace) }) } - fn update_workspace(&self, _token: &str, _params: UpdateWorkspaceParams) -> FutureResult<(), WorkspaceError> { + fn update_workspace(&self, _token: &str, _params: UpdateWorkspaceParams) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn delete_workspace(&self, _token: &str, _params: WorkspaceIdentifier) -> FutureResult<(), WorkspaceError> { + fn delete_workspace(&self, _token: &str, _params: WorkspaceIdentifier) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn create_view(&self, _token: &str, params: CreateViewParams) -> FutureResult { + fn create_view(&self, _token: &str, params: CreateViewParams) -> FutureResult { let time = timestamp(); let view = View { id: uuid(), @@ -64,19 +64,19 @@ impl WorkspaceServerAPI for WorkspaceServerMock { FutureResult::new(async { Ok(view) }) } - fn read_view(&self, _token: &str, _params: ViewIdentifier) -> FutureResult, WorkspaceError> { + fn read_view(&self, _token: &str, _params: ViewIdentifier) -> FutureResult, FlowyError> { FutureResult::new(async { Ok(None) }) } - fn delete_view(&self, _token: &str, _params: ViewIdentifiers) -> FutureResult<(), WorkspaceError> { + fn delete_view(&self, _token: &str, _params: ViewIdentifiers) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn update_view(&self, _token: &str, _params: UpdateViewParams) -> FutureResult<(), WorkspaceError> { + fn update_view(&self, _token: &str, _params: UpdateViewParams) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn create_app(&self, _token: &str, params: CreateAppParams) -> FutureResult { + fn create_app(&self, _token: &str, params: CreateAppParams) -> FutureResult { let time = timestamp(); let app = App { id: uuid(), @@ -91,27 +91,27 @@ impl WorkspaceServerAPI for WorkspaceServerMock { FutureResult::new(async { Ok(app) }) } - fn read_app(&self, _token: &str, _params: AppIdentifier) -> FutureResult, WorkspaceError> { + fn read_app(&self, _token: &str, _params: AppIdentifier) -> FutureResult, FlowyError> { FutureResult::new(async { Ok(None) }) } - fn update_app(&self, _token: &str, _params: UpdateAppParams) -> FutureResult<(), WorkspaceError> { + fn update_app(&self, _token: &str, _params: UpdateAppParams) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn delete_app(&self, _token: &str, _params: AppIdentifier) -> FutureResult<(), WorkspaceError> { + fn delete_app(&self, _token: &str, _params: AppIdentifier) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn create_trash(&self, _token: &str, _params: TrashIdentifiers) -> FutureResult<(), WorkspaceError> { + fn create_trash(&self, _token: &str, _params: TrashIdentifiers) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn delete_trash(&self, _token: &str, _params: TrashIdentifiers) -> FutureResult<(), WorkspaceError> { + fn delete_trash(&self, _token: &str, _params: TrashIdentifiers) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn read_trash(&self, _token: &str) -> FutureResult { + fn read_trash(&self, _token: &str) -> FutureResult { FutureResult::new(async { let repeated_trash = RepeatedTrash { items: vec![] }; Ok(repeated_trash) diff --git a/frontend/rust-lib/flowy-core/src/services/trash/controller.rs b/frontend/rust-lib/flowy-core/src/services/trash/controller.rs index 670111860b..b878baac59 100644 --- a/frontend/rust-lib/flowy-core/src/services/trash/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/trash/controller.rs @@ -1,6 +1,6 @@ use crate::{ entities::trash::{RepeatedTrash, Trash, TrashIdentifier, TrashIdentifiers, TrashType}, - errors::{WorkspaceError, WorkspaceResult}, + errors::{FlowyError, FlowyResult}, module::{WorkspaceDatabase, WorkspaceUser}, notify::{send_anonymous_dart_notification, WorkspaceNotification}, services::{server::Server, trash::sql::TrashTableSql}, @@ -29,21 +29,21 @@ impl TrashController { } } - pub(crate) fn init(&self) -> Result<(), WorkspaceError> { Ok(()) } + pub(crate) fn init(&self) -> Result<(), FlowyError> { Ok(()) } #[tracing::instrument(level = "debug", skip(self), fields(putback) err)] - pub async fn putback(&self, trash_id: &str) -> WorkspaceResult<()> { - let (tx, mut rx) = mpsc::channel::>(1); + pub async fn putback(&self, trash_id: &str) -> FlowyResult<()> { + let (tx, mut rx) = mpsc::channel::>(1); let trash_table = TrashTableSql::read(trash_id, &*self.database.db_connection()?)?; let _ = thread::scope(|_s| { let conn = self.database.db_connection()?; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = TrashTableSql::delete_trash(trash_id, &*conn)?; notify_trash_changed(TrashTableSql::read_all(&conn)?); Ok(()) })?; - Ok::<(), WorkspaceError>(()) + Ok::<(), FlowyError>(()) }) .unwrap()?; @@ -64,10 +64,10 @@ impl TrashController { } #[tracing::instrument(level = "debug", skip(self) err)] - pub async fn restore_all(&self) -> WorkspaceResult<()> { + pub async fn restore_all(&self) -> FlowyResult<()> { let repeated_trash = thread::scope(|_s| { let conn = self.database.db_connection()?; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let repeated_trash = TrashTableSql::read_all(&*conn)?; let _ = TrashTableSql::delete_all(&*conn)?; Ok(repeated_trash) @@ -76,7 +76,7 @@ impl TrashController { .unwrap()?; let identifiers: TrashIdentifiers = repeated_trash.items.clone().into(); - let (tx, mut rx) = mpsc::channel::>(1); + let (tx, mut rx) = mpsc::channel::>(1); let _ = self.notify.send(TrashEvent::Putback(identifiers, tx)); let _ = rx.recv().await; @@ -86,7 +86,7 @@ impl TrashController { } #[tracing::instrument(level = "debug", skip(self), err)] - pub async fn delete_all(&self) -> WorkspaceResult<()> { + pub async fn delete_all(&self) -> FlowyResult<()> { let repeated_trash = TrashTableSql::read_all(&*(self.database.db_connection()?))?; let trash_identifiers: TrashIdentifiers = repeated_trash.items.clone().into(); let _ = self.delete_with_identifiers(trash_identifiers.clone()).await?; @@ -97,7 +97,7 @@ impl TrashController { } #[tracing::instrument(level = "debug", skip(self), err)] - pub async fn delete(&self, trash_identifiers: TrashIdentifiers) -> WorkspaceResult<()> { + pub async fn delete(&self, trash_identifiers: TrashIdentifiers) -> FlowyResult<()> { let _ = self.delete_with_identifiers(trash_identifiers.clone()).await?; notify_trash_changed(TrashTableSql::read_all(&*(self.database.db_connection()?))?); let _ = self.delete_trash_on_server(trash_identifiers)?; @@ -106,8 +106,8 @@ impl TrashController { } #[tracing::instrument(level = "debug", skip(self), fields(delete_trash_ids), err)] - pub async fn delete_with_identifiers(&self, trash_identifiers: TrashIdentifiers) -> WorkspaceResult<()> { - let (tx, mut rx) = mpsc::channel::>(1); + pub async fn delete_with_identifiers(&self, trash_identifiers: TrashIdentifiers) -> FlowyResult<()> { + let (tx, mut rx) = mpsc::channel::>(1); tracing::Span::current().record("delete_trash_ids", &format!("{}", trash_identifiers).as_str()); let _ = self.notify.send(TrashEvent::Delete(trash_identifiers.clone(), tx)); @@ -120,7 +120,7 @@ impl TrashController { } let conn = self.database.db_connection()?; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { for trash_identifier in &trash_identifiers.items { let _ = TrashTableSql::delete_trash(&trash_identifier.id, &conn)?; } @@ -136,8 +136,8 @@ impl TrashController { // CREATE and DROP tables operations because those are auto-commit in the // database. #[tracing::instrument(name = "add_trash", level = "debug", skip(self, trash), fields(trash_ids), err)] - pub async fn add>(&self, trash: Vec) -> Result<(), WorkspaceError> { - let (tx, mut rx) = mpsc::channel::>(1); + pub async fn add>(&self, trash: Vec) -> Result<(), FlowyError> { + let (tx, mut rx) = mpsc::channel::>(1); let repeated_trash = trash.into_iter().map(|t| t.into()).collect::>(); let identifiers = repeated_trash .iter() @@ -157,14 +157,14 @@ impl TrashController { ); let _ = thread::scope(|_s| { let conn = self.database.db_connection()?; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = TrashTableSql::create_trash(repeated_trash.clone(), &*conn)?; let _ = self.create_trash_on_server(repeated_trash); notify_trash_changed(TrashTableSql::read_all(&conn)?); Ok(()) })?; - Ok::<(), WorkspaceError>(()) + Ok::<(), FlowyError>(()) }) .unwrap()?; @@ -176,13 +176,13 @@ impl TrashController { pub fn subscribe(&self) -> broadcast::Receiver { self.notify.subscribe() } - pub fn read_trash(&self, conn: &SqliteConnection) -> Result { + pub fn read_trash(&self, conn: &SqliteConnection) -> Result { let repeated_trash = TrashTableSql::read_all(&*conn)?; let _ = self.read_trash_on_server()?; Ok(repeated_trash) } - pub fn trash_ids(&self, conn: &SqliteConnection) -> Result, WorkspaceError> { + pub fn trash_ids(&self, conn: &SqliteConnection) -> Result, FlowyError> { let ids = TrashTableSql::read_all(&*conn)? .into_inner() .into_iter() @@ -194,7 +194,7 @@ impl TrashController { impl TrashController { #[tracing::instrument(level = "debug", skip(self, trash), err)] - fn create_trash_on_server>(&self, trash: T) -> WorkspaceResult<()> { + fn create_trash_on_server>(&self, trash: T) -> FlowyResult<()> { let token = self.user.token()?; let trash_identifiers = trash.into(); let server = self.server.clone(); @@ -209,7 +209,7 @@ impl TrashController { } #[tracing::instrument(level = "debug", skip(self, trash), err)] - fn delete_trash_on_server>(&self, trash: T) -> WorkspaceResult<()> { + fn delete_trash_on_server>(&self, trash: T) -> FlowyResult<()> { let token = self.user.token()?; let trash_identifiers = trash.into(); let server = self.server.clone(); @@ -223,7 +223,7 @@ impl TrashController { } #[tracing::instrument(level = "debug", skip(self), err)] - fn read_trash_on_server(&self) -> WorkspaceResult<()> { + fn read_trash_on_server(&self) -> FlowyResult<()> { let token = self.user.token()?; let server = self.server.clone(); let pool = self.database.db_pool()?; @@ -234,7 +234,7 @@ impl TrashController { tracing::debug!("Remote trash count: {}", repeated_trash.items.len()); match pool.get() { Ok(conn) => { - let result = conn.immediate_transaction::<_, WorkspaceError, _>(|| { + let result = conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = TrashTableSql::create_trash(repeated_trash.items.clone(), &*conn)?; TrashTableSql::read_all(&conn) }); @@ -256,7 +256,7 @@ impl TrashController { } #[tracing::instrument(level = "debug", skip(self), err)] - async fn delete_all_trash_on_server(&self) -> WorkspaceResult<()> { + async fn delete_all_trash_on_server(&self) -> FlowyResult<()> { let token = self.user.token()?; let server = self.server.clone(); server.delete_trash(&token, TrashIdentifiers::all()).await @@ -273,9 +273,9 @@ fn notify_trash_changed(repeated_trash: RepeatedTrash) { #[derive(Clone)] pub enum TrashEvent { - NewTrash(TrashIdentifiers, mpsc::Sender>), - Putback(TrashIdentifiers, mpsc::Sender>), - Delete(TrashIdentifiers, mpsc::Sender>), + NewTrash(TrashIdentifiers, mpsc::Sender>), + Putback(TrashIdentifiers, mpsc::Sender>), + Delete(TrashIdentifiers, mpsc::Sender>), } impl std::fmt::Debug for TrashEvent { diff --git a/frontend/rust-lib/flowy-core/src/services/trash/event_handler.rs b/frontend/rust-lib/flowy-core/src/services/trash/event_handler.rs index 3b72f630c0..10656ae8b3 100644 --- a/frontend/rust-lib/flowy-core/src/services/trash/event_handler.rs +++ b/frontend/rust-lib/flowy-core/src/services/trash/event_handler.rs @@ -1,6 +1,6 @@ use crate::{ entities::trash::{RepeatedTrash, TrashIdentifier, TrashIdentifiers}, - errors::WorkspaceError, + errors::FlowyError, services::TrashController, }; use lib_dispatch::prelude::{data_result, Data, DataResult, Unit}; @@ -9,7 +9,7 @@ use std::sync::Arc; #[tracing::instrument(skip(controller), err)] pub(crate) async fn read_trash_handler( controller: Unit>, -) -> DataResult { +) -> DataResult { let conn = controller.database.db_connection()?; let repeated_trash = controller.read_trash(&conn)?; data_result(repeated_trash) @@ -19,7 +19,7 @@ pub(crate) async fn read_trash_handler( pub(crate) async fn putback_trash_handler( identifier: Data, controller: Unit>, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let _ = controller.putback(&identifier.id).await?; Ok(()) } @@ -28,19 +28,19 @@ pub(crate) async fn putback_trash_handler( pub(crate) async fn delete_trash_handler( identifiers: Data, controller: Unit>, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let _ = controller.delete(identifiers.into_inner()).await?; Ok(()) } #[tracing::instrument(skip(controller), err)] -pub(crate) async fn restore_all_handler(controller: Unit>) -> Result<(), WorkspaceError> { +pub(crate) async fn restore_all_handler(controller: Unit>) -> Result<(), FlowyError> { let _ = controller.restore_all().await?; Ok(()) } #[tracing::instrument(skip(controller), err)] -pub(crate) async fn delete_all_handler(controller: Unit>) -> Result<(), WorkspaceError> { +pub(crate) async fn delete_all_handler(controller: Unit>) -> Result<(), FlowyError> { let _ = controller.delete_all().await?; Ok(()) } diff --git a/frontend/rust-lib/flowy-core/src/services/trash/sql.rs b/frontend/rust-lib/flowy-core/src/services/trash/sql.rs index b65b448a96..092cbe4ff4 100644 --- a/frontend/rust-lib/flowy-core/src/services/trash/sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/trash/sql.rs @@ -1,6 +1,6 @@ use crate::{ entities::trash::{RepeatedTrash, Trash, TrashType}, - errors::WorkspaceError, + errors::FlowyError, }; use diesel::sql_types::Integer; use flowy_database::{ @@ -12,7 +12,7 @@ use flowy_database::{ pub struct TrashTableSql {} impl TrashTableSql { - pub(crate) fn create_trash(repeated_trash: Vec, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn create_trash(repeated_trash: Vec, conn: &SqliteConnection) -> Result<(), FlowyError> { for trash in repeated_trash { let trash_table: TrashTable = trash.into(); match diesel_record_count!(trash_table, &trash_table.id, conn) { @@ -27,25 +27,25 @@ impl TrashTableSql { Ok(()) } - pub(crate) fn read_all(conn: &SqliteConnection) -> Result { + pub(crate) fn read_all(conn: &SqliteConnection) -> Result { let trash_tables = dsl::trash_table.load::(conn)?; let items = trash_tables.into_iter().map(|t| t.into()).collect::>(); Ok(RepeatedTrash { items }) } - pub(crate) fn delete_all(conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn delete_all(conn: &SqliteConnection) -> Result<(), FlowyError> { let _ = diesel::delete(dsl::trash_table).execute(conn)?; Ok(()) } - pub(crate) fn read(trash_id: &str, conn: &SqliteConnection) -> Result { + pub(crate) fn read(trash_id: &str, conn: &SqliteConnection) -> Result { let trash_table = dsl::trash_table .filter(trash_table::id.eq(trash_id)) .first::(conn)?; Ok(trash_table) } - pub(crate) fn delete_trash(trash_id: &str, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn delete_trash(trash_id: &str, conn: &SqliteConnection) -> Result<(), FlowyError> { diesel_delete_table!(trash_table, trash_id, conn); Ok(()) } diff --git a/frontend/rust-lib/flowy-core/src/services/view/controller.rs b/frontend/rust-lib/flowy-core/src/services/view/controller.rs index d6ff221383..da9370fc96 100644 --- a/frontend/rust-lib/flowy-core/src/services/view/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/view/controller.rs @@ -8,7 +8,7 @@ use crate::{ trash::{TrashIdentifiers, TrashType}, view::{CreateViewParams, RepeatedView, UpdateViewParams, View, ViewIdentifier}, }, - errors::{internal_error, WorkspaceError, WorkspaceResult}, + errors::{internal_error, FlowyError, FlowyResult}, module::{WorkspaceDatabase, WorkspaceUser}, notify::{send_dart_notification, WorkspaceNotification}, services::{ @@ -49,23 +49,23 @@ impl ViewController { } } - pub(crate) fn init(&self) -> Result<(), WorkspaceError> { + pub(crate) fn init(&self) -> Result<(), FlowyError> { let _ = self.document.init()?; self.listen_trash_can_event(); Ok(()) } #[tracing::instrument(level = "debug", skip(self, params), fields(name = %params.name), err)] - pub(crate) async fn create_view_from_params(&self, params: CreateViewParams) -> Result { + pub(crate) async fn create_view_from_params(&self, params: CreateViewParams) -> Result { let view = self.create_view_on_server(params.clone()).await?; self.create_view(view).await } - pub(crate) async fn create_view(&self, view: View) -> Result { + pub(crate) async fn create_view(&self, view: View) -> Result { let conn = &*self.database.db_connection()?; let trash_can = self.trash_can.clone(); - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = self.save_view(view.clone(), conn)?; let _ = notify_views_changed(&view.belong_to_id, trash_can, &conn)?; @@ -75,20 +75,20 @@ impl ViewController { Ok(view) } - pub(crate) fn save_view(&self, view: View, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn save_view(&self, view: View, conn: &SqliteConnection) -> Result<(), FlowyError> { let view_table = ViewTable::new(view); let _ = ViewTableSql::create_view(view_table, conn)?; Ok(()) } #[tracing::instrument(skip(self, params), fields(view_id = %params.view_id), err)] - pub(crate) async fn read_view(&self, params: ViewIdentifier) -> Result { + pub(crate) async fn read_view(&self, params: ViewIdentifier) -> Result { let conn = self.database.db_connection()?; let view_table = ViewTableSql::read_view(¶ms.view_id, &*conn)?; let trash_ids = self.trash_can.trash_ids(&conn)?; if trash_ids.contains(&view_table.id) { - return Err(WorkspaceError::record_not_found()); + return Err(FlowyError::record_not_found()); } let view: View = view_table.into(); @@ -96,10 +96,10 @@ impl ViewController { Ok(view) } - pub(crate) fn read_view_tables(&self, ids: Vec) -> Result, WorkspaceError> { + pub(crate) fn read_view_tables(&self, ids: Vec) -> Result, FlowyError> { let conn = &*self.database.db_connection()?; let mut view_tables = vec![]; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { for view_id in ids { view_tables.push(ViewTableSql::read_view(&view_id, conn)?); } @@ -110,7 +110,7 @@ impl ViewController { } #[tracing::instrument(level = "debug", skip(self, params), fields(doc_id = %params.doc_id), err)] - pub(crate) async fn open_view(&self, params: DocIdentifier) -> Result { + pub(crate) async fn open_view(&self, params: DocIdentifier) -> Result { let doc_id = params.doc_id.clone(); let edit_context = self.document.open(params).await?; @@ -119,13 +119,13 @@ impl ViewController { } #[tracing::instrument(level = "debug", skip(self,params), fields(doc_id = %params.doc_id), err)] - pub(crate) async fn close_view(&self, params: DocIdentifier) -> Result<(), WorkspaceError> { + pub(crate) async fn close_view(&self, params: DocIdentifier) -> Result<(), FlowyError> { let _ = self.document.close(params).await?; Ok(()) } #[tracing::instrument(level = "debug", skip(self,params), fields(doc_id = %params.doc_id), err)] - pub(crate) async fn delete_view(&self, params: DocIdentifier) -> Result<(), WorkspaceError> { + pub(crate) async fn delete_view(&self, params: DocIdentifier) -> Result<(), FlowyError> { if let Some(view_id) = KV::get_str(LATEST_VIEW_ID) { if view_id == params.doc_id { let _ = KV::remove(LATEST_VIEW_ID); @@ -136,7 +136,7 @@ impl ViewController { } #[tracing::instrument(level = "debug", skip(self, params), fields(doc_id = %params.doc_id), err)] - pub(crate) async fn duplicate_view(&self, params: DocIdentifier) -> Result<(), WorkspaceError> { + pub(crate) async fn duplicate_view(&self, params: DocIdentifier) -> Result<(), FlowyError> { let view: View = ViewTableSql::read_view(¶ms.doc_id, &*self.database.db_connection()?)?.into(); let delta_data = self .document @@ -157,7 +157,7 @@ impl ViewController { } #[tracing::instrument(level = "debug", skip(self, params), err)] - pub(crate) async fn export_doc(&self, params: ExportParams) -> Result { + pub(crate) async fn export_doc(&self, params: ExportParams) -> Result { let doc_identifier: DocIdentifier = params.doc_id.into(); let doc = self .document @@ -172,7 +172,7 @@ impl ViewController { // belong_to_id will be the app_id or view_id. #[tracing::instrument(level = "debug", skip(self), err)] - pub(crate) async fn read_views_belong_to(&self, belong_to_id: &str) -> Result { + pub(crate) async fn read_views_belong_to(&self, belong_to_id: &str) -> Result { // TODO: read from server let conn = self.database.db_connection()?; let repeated_view = read_local_belonging_view(belong_to_id, self.trash_can.clone(), &conn)?; @@ -180,12 +180,12 @@ impl ViewController { } #[tracing::instrument(level = "debug", skip(self, params), err)] - pub(crate) async fn update_view(&self, params: UpdateViewParams) -> Result { + pub(crate) async fn update_view(&self, params: UpdateViewParams) -> Result { let conn = &*self.database.db_connection()?; let changeset = ViewTableChangeset::new(params.clone()); let view_id = changeset.id.clone(); - let updated_view = conn.immediate_transaction::<_, WorkspaceError, _>(|| { + let updated_view = conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = ViewTableSql::update_view(changeset, conn)?; let view: View = ViewTableSql::read_view(&view_id, conn)?.into(); Ok(view) @@ -201,12 +201,12 @@ impl ViewController { Ok(updated_view) } - pub(crate) async fn apply_doc_delta(&self, params: DocDelta) -> Result { + pub(crate) async fn apply_doc_delta(&self, params: DocDelta) -> Result { let doc = self.document.apply_doc_delta(params).await?; Ok(doc) } - pub(crate) fn latest_visit_view(&self) -> WorkspaceResult> { + pub(crate) fn latest_visit_view(&self) -> FlowyResult> { match KV::get_str(LATEST_VIEW_ID) { None => Ok(None), Some(view_id) => { @@ -222,14 +222,14 @@ impl ViewController { impl ViewController { #[tracing::instrument(skip(self), err)] - async fn create_view_on_server(&self, params: CreateViewParams) -> Result { + async fn create_view_on_server(&self, params: CreateViewParams) -> Result { let token = self.user.token()?; let view = self.server.create_view(&token, params).await?; Ok(view) } #[tracing::instrument(skip(self), err)] - fn update_view_on_server(&self, params: UpdateViewParams) -> Result<(), WorkspaceError> { + fn update_view_on_server(&self, params: UpdateViewParams) -> Result<(), FlowyError> { let token = self.user.token()?; let server = self.server.clone(); tokio::spawn(async move { @@ -245,7 +245,7 @@ impl ViewController { } #[tracing::instrument(skip(self), err)] - fn read_view_on_server(&self, params: ViewIdentifier) -> Result<(), WorkspaceError> { + fn read_view_on_server(&self, params: ViewIdentifier) -> Result<(), FlowyError> { let token = self.user.token()?; let server = self.server.clone(); let pool = self.database.db_pool()?; @@ -314,7 +314,7 @@ async fn handle_trash_event( let _ = notify_views_changed(&view_table.belong_to_id, trash_can.clone(), conn)?; notify_dart(view_table, WorkspaceNotification::ViewDeleted); } - Ok::<(), WorkspaceError>(()) + Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; }, @@ -326,14 +326,14 @@ async fn handle_trash_event( let _ = notify_views_changed(&view_table.belong_to_id, trash_can.clone(), conn)?; notify_dart(view_table, WorkspaceNotification::ViewRestored); } - Ok::<(), WorkspaceError>(()) + Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; }, TrashEvent::Delete(identifiers, ret) => { let result = || { let conn = &*db_result?; - let _ = conn.immediate_transaction::<_, WorkspaceError, _>(|| { + let _ = conn.immediate_transaction::<_, FlowyError, _>(|| { let mut notify_ids = HashSet::new(); for identifier in identifiers.items { let view_table = ViewTableSql::read_view(&identifier.id, conn)?; @@ -348,19 +348,16 @@ async fn handle_trash_event( Ok(()) })?; - Ok::<(), WorkspaceError>(()) + Ok::<(), FlowyError>(()) }; let _ = ret.send(result()).await; }, } } -fn get_view_table_from( - identifiers: TrashIdentifiers, - conn: &SqliteConnection, -) -> Result, WorkspaceError> { +fn get_view_table_from(identifiers: TrashIdentifiers, conn: &SqliteConnection) -> Result, FlowyError> { let mut view_tables = vec![]; - let _ = conn.immediate_transaction::<_, WorkspaceError, _>(|| { + let _ = conn.immediate_transaction::<_, FlowyError, _>(|| { for identifier in identifiers.items { let view_table = ViewTableSql::read_view(&identifier.id, conn)?; view_tables.push(view_table); @@ -380,7 +377,7 @@ fn notify_views_changed( belong_to_id: &str, trash_can: Arc, conn: &SqliteConnection, -) -> WorkspaceResult<()> { +) -> FlowyResult<()> { let repeated_view = read_local_belonging_view(belong_to_id, trash_can.clone(), conn)?; tracing::Span::current().record("view_count", &format!("{}", repeated_view.len()).as_str()); send_dart_notification(&belong_to_id, WorkspaceNotification::AppViewsChanged) @@ -393,7 +390,7 @@ fn read_local_belonging_view( belong_to_id: &str, trash_can: Arc, conn: &SqliteConnection, -) -> WorkspaceResult { +) -> FlowyResult { let mut view_tables = ViewTableSql::read_views(belong_to_id, conn)?; let trash_ids = trash_can.trash_ids(conn)?; view_tables.retain(|view_table| !trash_ids.contains(&view_table.id)); diff --git a/frontend/rust-lib/flowy-core/src/services/view/event_handler.rs b/frontend/rust-lib/flowy-core/src/services/view/event_handler.rs index 1f5a1e3b80..b042e8e670 100644 --- a/frontend/rust-lib/flowy-core/src/services/view/event_handler.rs +++ b/frontend/rust-lib/flowy-core/src/services/view/event_handler.rs @@ -12,7 +12,7 @@ use crate::{ ViewIdentifiers, }, }, - errors::WorkspaceError, + errors::FlowyError, services::{TrashController, ViewController}, }; use flowy_collaboration::entities::doc::DocDelta; @@ -23,7 +23,7 @@ use std::{convert::TryInto, sync::Arc}; pub(crate) async fn create_view_handler( data: Data, controller: Unit>, -) -> DataResult { +) -> DataResult { let params: CreateViewParams = data.into_inner().try_into()?; let view = controller.create_view_from_params(params).await?; data_result(view) @@ -32,7 +32,7 @@ pub(crate) async fn create_view_handler( pub(crate) async fn read_view_handler( data: Data, controller: Unit>, -) -> DataResult { +) -> DataResult { let params: ViewIdentifier = data.into_inner().try_into()?; let mut view = controller.read_view(params.clone()).await?; view.belongings = controller.read_views_belong_to(¶ms.view_id).await?; @@ -44,7 +44,7 @@ pub(crate) async fn read_view_handler( pub(crate) async fn update_view_handler( data: Data, controller: Unit>, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let params: UpdateViewParams = data.into_inner().try_into()?; let _ = controller.update_view(params).await?; @@ -54,7 +54,7 @@ pub(crate) async fn update_view_handler( pub(crate) async fn apply_doc_delta_handler( data: Data, controller: Unit>, -) -> DataResult { +) -> DataResult { // let params: DocDelta = data.into_inner().try_into()?; let doc = controller.apply_doc_delta(data.into_inner()).await?; data_result(doc) @@ -64,7 +64,7 @@ pub(crate) async fn delete_view_handler( data: Data, controller: Unit>, trash_can: Unit>, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let params: ViewIdentifiers = data.into_inner().try_into()?; for view_id in ¶ms.view_ids { let _ = controller.delete_view(view_id.into()).await; @@ -83,7 +83,7 @@ pub(crate) async fn delete_view_handler( pub(crate) async fn open_view_handler( data: Data, controller: Unit>, -) -> DataResult { +) -> DataResult { let params: ViewIdentifier = data.into_inner().try_into()?; let doc = controller.open_view(params.into()).await?; data_result(doc) @@ -92,7 +92,7 @@ pub(crate) async fn open_view_handler( pub(crate) async fn close_view_handler( data: Data, controller: Unit>, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let params: ViewIdentifier = data.into_inner().try_into()?; let _ = controller.close_view(params.into()).await?; Ok(()) @@ -102,7 +102,7 @@ pub(crate) async fn close_view_handler( pub(crate) async fn duplicate_view_handler( data: Data, controller: Unit>, -) -> Result<(), WorkspaceError> { +) -> Result<(), FlowyError> { let params: ViewIdentifier = data.into_inner().try_into()?; let _ = controller.duplicate_view(params.into()).await?; Ok(()) @@ -112,7 +112,7 @@ pub(crate) async fn duplicate_view_handler( pub(crate) async fn export_handler( data: Data, controller: Unit>, -) -> DataResult { +) -> DataResult { let params: ExportParams = data.into_inner().try_into()?; let data = controller.export_doc(params).await?; data_result(data) diff --git a/frontend/rust-lib/flowy-core/src/services/view/sql.rs b/frontend/rust-lib/flowy-core/src/services/view/sql.rs index fedd6310bb..b33c6fbb18 100644 --- a/frontend/rust-lib/flowy-core/src/services/view/sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/view/sql.rs @@ -3,7 +3,7 @@ use crate::{ trash::{Trash, TrashType}, view::{RepeatedView, UpdateViewParams, View, ViewType}, }, - errors::WorkspaceError, + errors::FlowyError, services::app::sql::AppTable, }; use diesel::sql_types::Integer; @@ -17,7 +17,7 @@ use lib_infra::timestamp; pub struct ViewTableSql {} impl ViewTableSql { - pub(crate) fn create_view(view_table: ViewTable, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn create_view(view_table: ViewTable, conn: &SqliteConnection) -> Result<(), FlowyError> { match diesel_record_count!(view_table, &view_table.id, conn) { 0 => diesel_insert_table!(view_table, &view_table, conn), _ => { @@ -28,7 +28,7 @@ impl ViewTableSql { Ok(()) } - pub(crate) fn read_view(view_id: &str, conn: &SqliteConnection) -> Result { + pub(crate) fn read_view(view_id: &str, conn: &SqliteConnection) -> Result { // https://docs.diesel.rs/diesel/query_builder/struct.UpdateStatement.html // let mut filter = // dsl::view_table.filter(view_table::id.eq(view_id)).into_boxed(); @@ -44,7 +44,7 @@ impl ViewTableSql { } // belong_to_id will be the app_id or view_id. - pub(crate) fn read_views(belong_to_id: &str, conn: &SqliteConnection) -> Result, WorkspaceError> { + pub(crate) fn read_views(belong_to_id: &str, conn: &SqliteConnection) -> Result, FlowyError> { let view_tables = dsl::view_table .filter(view_table::belong_to_id.eq(belong_to_id)) .order(view_table::create_time.asc()) @@ -54,12 +54,12 @@ impl ViewTableSql { Ok(view_tables) } - pub(crate) fn update_view(changeset: ViewTableChangeset, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn update_view(changeset: ViewTableChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { diesel_update_table!(view_table, changeset, conn); Ok(()) } - pub(crate) fn delete_view(view_id: &str, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn delete_view(view_id: &str, conn: &SqliteConnection) -> Result<(), FlowyError> { diesel_delete_table!(view_table, view_id, conn); Ok(()) } @@ -69,7 +69,7 @@ impl ViewTableSql { // belong_to_id: &str, // is_trash: Option, // conn: &SqliteConnection, -// ) -> Result { +// ) -> Result { // let views = dsl::view_table // .inner_join(trash_table::dsl::trash_table.on(trash_id.ne(view_table:: // id))) .filter(view_table::belong_to_id.eq(belong_to_id)) diff --git a/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs b/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs index aebda93def..0c04928707 100644 --- a/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs +++ b/frontend/rust-lib/flowy-core/src/services/workspace/controller.rs @@ -35,17 +35,17 @@ impl WorkspaceController { } } - pub(crate) fn init(&self) -> Result<(), WorkspaceError> { Ok(()) } + pub(crate) fn init(&self) -> Result<(), FlowyError> { Ok(()) } pub(crate) async fn create_workspace_from_params( &self, params: CreateWorkspaceParams, - ) -> Result { + ) -> Result { let workspace = self.create_workspace_on_server(params.clone()).await?; self.create_workspace(workspace).await } - pub(crate) async fn create_workspace(&self, workspace: Workspace) -> Result { + pub(crate) async fn create_workspace(&self, workspace: Workspace) -> Result { let user_id = self.user.user_id()?; let token = self.user.token()?; let workspace_table = WorkspaceTable::new(workspace.clone(), &user_id); @@ -61,7 +61,7 @@ impl WorkspaceController { // immediately. EXCLUSIVE and IMMEDIATE are the same in WAL mode, but in // other journaling modes, EXCLUSIVE prevents other database connections from // reading the database while the transaction is underway. - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { WorkspaceTableSql::create_workspace(workspace_table, conn)?; let repeated_workspace = self.read_local_workspaces(None, &user_id, conn)?; send_dart_notification(&token, WorkspaceNotification::UserCreateWorkspace) @@ -77,11 +77,11 @@ impl WorkspaceController { } #[allow(dead_code)] - pub(crate) async fn update_workspace(&self, params: UpdateWorkspaceParams) -> Result<(), WorkspaceError> { + pub(crate) async fn update_workspace(&self, params: UpdateWorkspaceParams) -> Result<(), FlowyError> { let changeset = WorkspaceTableChangeset::new(params.clone()); let workspace_id = changeset.id.clone(); let conn = &*self.database.db_connection()?; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = WorkspaceTableSql::update_workspace(changeset, conn)?; let user_id = self.user.user_id()?; let workspace = self.read_local_workspace(workspace_id.clone(), &user_id, conn)?; @@ -98,11 +98,11 @@ impl WorkspaceController { } #[allow(dead_code)] - pub(crate) async fn delete_workspace(&self, workspace_id: &str) -> Result<(), WorkspaceError> { + pub(crate) async fn delete_workspace(&self, workspace_id: &str) -> Result<(), FlowyError> { let user_id = self.user.user_id()?; let token = self.user.token()?; let conn = &*self.database.db_connection()?; - conn.immediate_transaction::<_, WorkspaceError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = WorkspaceTableSql::delete_workspace(workspace_id, conn)?; let repeated_workspace = self.read_local_workspaces(None, &user_id, conn)?; send_dart_notification(&token, WorkspaceNotification::UserDeleteWorkspace) @@ -116,7 +116,7 @@ impl WorkspaceController { Ok(()) } - pub(crate) async fn open_workspace(&self, params: WorkspaceIdentifier) -> Result { + pub(crate) async fn open_workspace(&self, params: WorkspaceIdentifier) -> Result { let user_id = self.user.user_id()?; let conn = self.database.db_connection()?; if let Some(workspace_id) = params.workspace_id { @@ -124,11 +124,11 @@ impl WorkspaceController { set_current_workspace(&workspace.id); Ok(workspace) } else { - return Err(WorkspaceError::workspace_id().context("Opened workspace id should not be empty")); + return Err(FlowyError::workspace_id().context("Opened workspace id should not be empty")); } } - pub(crate) async fn read_current_workspace_apps(&self) -> Result { + pub(crate) async fn read_current_workspace_apps(&self) -> Result { let workspace_id = get_current_workspace()?; let conn = self.database.db_connection()?; let repeated_app = self.read_local_apps(&workspace_id, &*conn)?; @@ -142,7 +142,7 @@ impl WorkspaceController { workspace_id: Option, user_id: &str, conn: &SqliteConnection, - ) -> Result { + ) -> Result { let workspace_id = workspace_id.to_owned(); let workspace_tables = WorkspaceTableSql::read_workspaces(workspace_id, user_id, conn)?; @@ -159,11 +159,11 @@ impl WorkspaceController { workspace_id: String, user_id: &str, conn: &SqliteConnection, - ) -> Result { + ) -> Result { // Opti: fetch single workspace from local db let mut repeated_workspace = self.read_local_workspaces(Some(workspace_id.clone()), user_id, conn)?; if repeated_workspace.is_empty() { - return Err(WorkspaceError::record_not_found().context(format!("{} workspace not found", workspace_id))); + return Err(FlowyError::record_not_found().context(format!("{} workspace not found", workspace_id))); } debug_assert_eq!(repeated_workspace.len(), 1); @@ -172,7 +172,7 @@ impl WorkspaceController { } #[tracing::instrument(level = "debug", skip(self, conn), err)] - fn read_local_apps(&self, workspace_id: &str, conn: &SqliteConnection) -> Result { + fn read_local_apps(&self, workspace_id: &str, conn: &SqliteConnection) -> Result { let repeated_app = read_local_workspace_apps(workspace_id, self.trash_controller.clone(), conn)?; Ok(repeated_app) } @@ -180,14 +180,14 @@ impl WorkspaceController { impl WorkspaceController { #[tracing::instrument(level = "debug", skip(self), err)] - async fn create_workspace_on_server(&self, params: CreateWorkspaceParams) -> Result { + async fn create_workspace_on_server(&self, params: CreateWorkspaceParams) -> Result { let token = self.user.token()?; let workspace = self.server.create_workspace(&token, params).await?; Ok(workspace) } #[tracing::instrument(level = "debug", skip(self), err)] - fn update_workspace_on_server(&self, params: UpdateWorkspaceParams) -> Result<(), WorkspaceError> { + fn update_workspace_on_server(&self, params: UpdateWorkspaceParams) -> Result<(), FlowyError> { let (token, server) = (self.user.token()?, self.server.clone()); tokio::spawn(async move { match server.update_workspace(&token, params).await { @@ -202,7 +202,7 @@ impl WorkspaceController { } #[tracing::instrument(level = "debug", skip(self), err)] - fn delete_workspace_on_server(&self, workspace_id: &str) -> Result<(), WorkspaceError> { + fn delete_workspace_on_server(&self, workspace_id: &str) -> Result<(), FlowyError> { let params = WorkspaceIdentifier { workspace_id: Some(workspace_id.to_string()), }; @@ -224,10 +224,12 @@ const CURRENT_WORKSPACE_ID: &str = "current_workspace_id"; fn set_current_workspace(workspace_id: &str) { KV::set_str(CURRENT_WORKSPACE_ID, workspace_id.to_owned()); } -pub fn get_current_workspace() -> Result { +pub fn get_current_workspace() -> Result { match KV::get_str(CURRENT_WORKSPACE_ID) { - None => Err(WorkspaceError::record_not_found() - .context("Current workspace not found or should call open workspace first")), + None => { + Err(FlowyError::record_not_found() + .context("Current workspace not found or should call open workspace first")) + }, Some(workspace_id) => Ok(workspace_id), } } diff --git a/frontend/rust-lib/flowy-core/src/services/workspace/event_handler.rs b/frontend/rust-lib/flowy-core/src/services/workspace/event_handler.rs index 7f04b7f56c..8d7eaf9658 100644 --- a/frontend/rust-lib/flowy-core/src/services/workspace/event_handler.rs +++ b/frontend/rust-lib/flowy-core/src/services/workspace/event_handler.rs @@ -1,4 +1,4 @@ -use crate::{errors::WorkspaceError, services::WorkspaceController}; +use crate::{errors::FlowyError, services::WorkspaceController}; use flowy_core_infra::entities::{app::RepeatedApp, workspace::*}; use lib_dispatch::prelude::{data_result, Data, DataResult, Unit}; @@ -8,7 +8,7 @@ use std::{convert::TryInto, sync::Arc}; pub(crate) async fn create_workspace_handler( data: Data, controller: Unit>, -) -> DataResult { +) -> DataResult { let controller = controller.get_ref().clone(); let params: CreateWorkspaceParams = data.into_inner().try_into()?; let detail = controller.create_workspace_from_params(params).await?; @@ -18,7 +18,7 @@ pub(crate) async fn create_workspace_handler( #[tracing::instrument(skip(controller), err)] pub(crate) async fn read_workspace_apps_handler( controller: Unit>, -) -> DataResult { +) -> DataResult { let repeated_app = controller.read_current_workspace_apps().await?; data_result(repeated_app) } @@ -27,7 +27,7 @@ pub(crate) async fn read_workspace_apps_handler( pub(crate) async fn open_workspace_handler( data: Data, controller: Unit>, -) -> DataResult { +) -> DataResult { let params: WorkspaceIdentifier = data.into_inner().try_into()?; let workspaces = controller.open_workspace(params).await?; data_result(workspaces) diff --git a/frontend/rust-lib/flowy-core/src/services/workspace/sql.rs b/frontend/rust-lib/flowy-core/src/services/workspace/sql.rs index bda1a8def9..6c0cf294ab 100644 --- a/frontend/rust-lib/flowy-core/src/services/workspace/sql.rs +++ b/frontend/rust-lib/flowy-core/src/services/workspace/sql.rs @@ -3,7 +3,7 @@ use crate::{ app::RepeatedApp, workspace::{UpdateWorkspaceParams, Workspace}, }, - errors::WorkspaceError, + errors::FlowyError, }; use diesel::SqliteConnection; use flowy_database::{ @@ -13,7 +13,7 @@ use flowy_database::{ pub(crate) struct WorkspaceTableSql {} impl WorkspaceTableSql { - pub(crate) fn create_workspace(table: WorkspaceTable, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn create_workspace(table: WorkspaceTable, conn: &SqliteConnection) -> Result<(), FlowyError> { match diesel_record_count!(workspace_table, &table.id, conn) { 0 => diesel_insert_table!(workspace_table, &table, conn), _ => { @@ -28,7 +28,7 @@ impl WorkspaceTableSql { workspace_id: Option, user_id: &str, conn: &SqliteConnection, - ) -> Result, WorkspaceError> { + ) -> Result, FlowyError> { let mut filter = dsl::workspace_table .filter(workspace_table::user_id.eq(user_id)) .order(workspace_table::create_time.asc()) @@ -47,13 +47,13 @@ impl WorkspaceTableSql { pub(crate) fn update_workspace( changeset: WorkspaceTableChangeset, conn: &SqliteConnection, - ) -> Result<(), WorkspaceError> { + ) -> Result<(), FlowyError> { diesel_update_table!(workspace_table, changeset, conn); Ok(()) } #[allow(dead_code)] - pub(crate) fn delete_workspace(workspace_id: &str, conn: &SqliteConnection) -> Result<(), WorkspaceError> { + pub(crate) fn delete_workspace(workspace_id: &str, conn: &SqliteConnection) -> Result<(), FlowyError> { diesel_delete_table!(workspace_table, workspace_id, conn); Ok(()) } diff --git a/frontend/rust-lib/flowy-document/Cargo.toml b/frontend/rust-lib/flowy-document/Cargo.toml index 2f949ff0f9..6c01690360 100644 --- a/frontend/rust-lib/flowy-document/Cargo.toml +++ b/frontend/rust-lib/flowy-document/Cargo.toml @@ -9,17 +9,17 @@ edition = "2018" [dependencies] flowy-collaboration = { path = "../../../shared-lib/flowy-collaboration" } flowy-derive = { path = "../../../shared-lib/flowy-derive" } +backend-service = { path = "../../../shared-lib/backend-service" } lib-ot = { path = "../../../shared-lib/lib-ot" } lib-ws = { path = "../../../shared-lib/lib-ws" } -backend-service = { path = "../../../shared-lib/backend-service" } lib-infra = { path = "../../../shared-lib/lib-infra" } derive_more = {version = "0.99", features = ["display"]} lib-dispatch = { path = "../lib-dispatch" } flowy-database = { path = "../flowy-database" } +flowy-error = { path = "../flowy-error", features = ["collaboration", "ot", "backend", "serde", "db"] } dart-notify = { path = "../dart-notify" } - diesel = {version = "1.4.8", features = ["sqlite"]} diesel_derives = {version = "1.4.1", features = ["sqlite"]} protobuf = {version = "2.18.0"} diff --git a/frontend/rust-lib/flowy-document/src/errors.rs b/frontend/rust-lib/flowy-document/src/errors.rs deleted file mode 100644 index 526799dcb5..0000000000 --- a/frontend/rust-lib/flowy-document/src/errors.rs +++ /dev/null @@ -1,138 +0,0 @@ -use backend_service::errors::ServerError; -use bytes::Bytes; -use derive_more::Display; -use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; -use lib_dispatch::prelude::{EventResponse, ResponseBuilder}; -use std::{convert::TryInto, fmt}; - -pub type DocResult = std::result::Result; - -#[derive(Debug, Default, Clone, ProtoBuf)] -pub struct DocError { - #[pb(index = 1)] - pub code: ErrorCode, - - #[pb(index = 2)] - pub msg: String, -} - -macro_rules! static_doc_error { - ($name:ident, $status:expr) => { - #[allow(non_snake_case, missing_docs)] - pub fn $name() -> DocError { - DocError { - code: $status, - msg: format!("{}", $status), - } - } - }; -} - -impl DocError { - fn new(code: ErrorCode, msg: &str) -> Self { - Self { - code, - msg: msg.to_owned(), - } - } - - pub fn context(mut self, error: T) -> Self { - self.msg = format!("{:?}", error); - self - } - - pub fn is_record_not_found(&self) -> bool { self.code == ErrorCode::DocNotfound } - - static_doc_error!(ws, ErrorCode::WsConnectError); - static_doc_error!(internal, ErrorCode::InternalError); - static_doc_error!(unauthorized, ErrorCode::UserUnauthorized); - static_doc_error!(doc_not_found, ErrorCode::DocNotfound); - static_doc_error!(duplicate_rev, ErrorCode::DuplicateRevision); -} - -pub fn internal_error(e: T) -> DocError -where - T: std::fmt::Debug, -{ - DocError::internal().context(e) -} - -#[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] -pub enum ErrorCode { - #[display(fmt = "Document websocket error")] - WsConnectError = 0, - - #[display(fmt = "DocNotfound")] - DocNotfound = 1, - - #[display(fmt = "Duplicate revision")] - DuplicateRevision = 2, - - #[display(fmt = "UserUnauthorized")] - UserUnauthorized = 10, - - #[display(fmt = "InternalError")] - InternalError = 1000, -} - -impl std::default::Default for ErrorCode { - fn default() -> Self { ErrorCode::InternalError } -} - -impl std::convert::From for DocError { - fn from(error: flowy_database::Error) -> Self { - match error { - flowy_database::Error::NotFound => DocError::doc_not_found().context(error), - _ => DocError::internal().context(error), - } - } -} - -impl std::convert::From for DocError { - fn from(error: lib_ot::errors::OTError) -> Self { DocError::internal().context(error) } -} - -impl std::convert::From for DocError { - fn from(error: flowy_collaboration::errors::CollaborateError) -> Self { DocError::internal().context(error) } -} - -impl std::convert::From for DocError { - fn from(error: std::io::Error) -> Self { DocError::internal().context(error) } -} - -impl std::convert::From for DocError { - fn from(error: serde_json::Error) -> Self { DocError::internal().context(error) } -} - -impl std::convert::From for DocError { - fn from(e: protobuf::ProtobufError) -> Self { DocError::internal().context(e) } -} - -impl std::convert::From for DocError { - fn from(error: ServerError) -> Self { - let code = server_error_to_doc_error(error.code); - DocError::new(code, &error.msg) - } -} - -use backend_service::errors::ErrorCode as ServerErrorCode; -use std::fmt::Debug; - -fn server_error_to_doc_error(code: ServerErrorCode) -> ErrorCode { - match code { - ServerErrorCode::UserUnauthorized => ErrorCode::UserUnauthorized, - ServerErrorCode::RecordNotFound => ErrorCode::DocNotfound, - _ => ErrorCode::InternalError, - } -} - -impl lib_dispatch::Error for DocError { - fn as_response(&self) -> EventResponse { - let bytes: Bytes = self.clone().try_into().unwrap(); - ResponseBuilder::Err().data(bytes).build() - } -} - -impl fmt::Display for DocError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", &self.code, &self.msg) } -} diff --git a/frontend/rust-lib/flowy-document/src/lib.rs b/frontend/rust-lib/flowy-document/src/lib.rs index c3ffb87b3d..c176ca4083 100644 --- a/frontend/rust-lib/flowy-document/src/lib.rs +++ b/frontend/rust-lib/flowy-document/src/lib.rs @@ -1,4 +1,3 @@ -pub mod errors; pub mod module; mod notify; pub mod protobuf; @@ -7,3 +6,7 @@ mod sql_tables; #[macro_use] extern crate flowy_database; + +pub mod errors { + pub use flowy_error::{internal_error, ErrorCode, FlowyError}; +} diff --git a/frontend/rust-lib/flowy-document/src/module.rs b/frontend/rust-lib/flowy-document/src/module.rs index adda90094c..b590b5dc43 100644 --- a/frontend/rust-lib/flowy-document/src/module.rs +++ b/frontend/rust-lib/flowy-document/src/module.rs @@ -1,5 +1,5 @@ use crate::{ - errors::DocError, + errors::FlowyError, services::{ doc::{controller::DocController, edit::ClientDocEditor}, server::construct_doc_server, @@ -12,10 +12,10 @@ use flowy_database::ConnectionPool; use std::sync::Arc; pub trait DocumentUser: Send + Sync { - fn user_dir(&self) -> Result; - fn user_id(&self) -> Result; - fn token(&self) -> Result; - fn db_pool(&self) -> Result, DocError>; + fn user_dir(&self) -> Result; + fn user_id(&self) -> Result; + fn token(&self) -> Result; + fn db_pool(&self) -> Result, FlowyError>; } pub struct FlowyDocument { @@ -34,22 +34,22 @@ impl FlowyDocument { Self { doc_ctrl, user } } - pub fn init(&self) -> Result<(), DocError> { + pub fn init(&self) -> Result<(), FlowyError> { let _ = self.doc_ctrl.init()?; Ok(()) } - pub fn delete(&self, params: DocIdentifier) -> Result<(), DocError> { + pub fn delete(&self, params: DocIdentifier) -> Result<(), FlowyError> { let _ = self.doc_ctrl.delete(params)?; Ok(()) } - pub async fn open(&self, params: DocIdentifier) -> Result, DocError> { + pub async fn open(&self, params: DocIdentifier) -> Result, FlowyError> { let edit_context = self.doc_ctrl.open(params, self.user.db_pool()?).await?; Ok(edit_context) } - pub async fn close(&self, params: DocIdentifier) -> Result<(), DocError> { + pub async fn close(&self, params: DocIdentifier) -> Result<(), FlowyError> { let _ = self.doc_ctrl.close(¶ms.doc_id)?; Ok(()) } @@ -58,13 +58,13 @@ impl FlowyDocument { &self, params: DocIdentifier, pool: Arc, - ) -> Result { + ) -> Result { let edit_context = self.doc_ctrl.open(params, pool).await?; let delta = edit_context.delta().await?; Ok(delta) } - pub async fn apply_doc_delta(&self, params: DocDelta) -> Result { + pub async fn apply_doc_delta(&self, params: DocDelta) -> Result { // workaround: compare the rust's delta with flutter's delta. Will be removed // very soon let doc = self diff --git a/frontend/rust-lib/flowy-document/src/protobuf/model/errors.rs b/frontend/rust-lib/flowy-document/src/protobuf/model/errors.rs deleted file mode 100644 index 61831522d9..0000000000 --- a/frontend/rust-lib/flowy-document/src/protobuf/model/errors.rs +++ /dev/null @@ -1,312 +0,0 @@ -// This file is generated by rust-protobuf 2.22.1. Do not edit -// @generated - -// https://github.com/rust-lang/rust-clippy/issues/702 -#![allow(unknown_lints)] -#![allow(clippy::all)] - -#![allow(unused_attributes)] -#![cfg_attr(rustfmt, rustfmt::skip)] - -#![allow(box_pointers)] -#![allow(dead_code)] -#![allow(missing_docs)] -#![allow(non_camel_case_types)] -#![allow(non_snake_case)] -#![allow(non_upper_case_globals)] -#![allow(trivial_casts)] -#![allow(unused_imports)] -#![allow(unused_results)] -//! Generated file from `errors.proto` - -/// Generated files are compatible only with the same version -/// of protobuf runtime. -// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_22_1; - -#[derive(PartialEq,Clone,Default)] -pub struct DocError { - // message fields - pub code: ErrorCode, - pub msg: ::std::string::String, - // special fields - pub unknown_fields: ::protobuf::UnknownFields, - pub cached_size: ::protobuf::CachedSize, -} - -impl<'a> ::std::default::Default for &'a DocError { - fn default() -> &'a DocError { - ::default_instance() - } -} - -impl DocError { - pub fn new() -> DocError { - ::std::default::Default::default() - } - - // .ErrorCode code = 1; - - - pub fn get_code(&self) -> ErrorCode { - self.code - } - pub fn clear_code(&mut self) { - self.code = ErrorCode::WsConnectError; - } - - // Param is passed by value, moved - pub fn set_code(&mut self, v: ErrorCode) { - self.code = v; - } - - // string msg = 2; - - - pub fn get_msg(&self) -> &str { - &self.msg - } - pub fn clear_msg(&mut self) { - self.msg.clear(); - } - - // Param is passed by value, moved - pub fn set_msg(&mut self, v: ::std::string::String) { - self.msg = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_msg(&mut self) -> &mut ::std::string::String { - &mut self.msg - } - - // Take field - pub fn take_msg(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.msg, ::std::string::String::new()) - } -} - -impl ::protobuf::Message for DocError { - fn is_initialized(&self) -> bool { - true - } - - fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.code, 1, &mut self.unknown_fields)? - }, - 2 => { - ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.msg)?; - }, - _ => { - ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if self.code != ErrorCode::WsConnectError { - my_size += ::protobuf::rt::enum_size(1, self.code); - } - if !self.msg.is_empty() { - my_size += ::protobuf::rt::string_size(2, &self.msg); - } - my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { - if self.code != ErrorCode::WsConnectError { - os.write_enum(1, ::protobuf::ProtobufEnum::value(&self.code))?; - } - if !self.msg.is_empty() { - os.write_string(2, &self.msg)?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { - self - } - - fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> DocError { - DocError::new() - } - - fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { - static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum>( - "code", - |m: &DocError| { &m.code }, - |m: &mut DocError| { &mut m.code }, - )); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( - "msg", - |m: &DocError| { &m.msg }, - |m: &mut DocError| { &mut m.msg }, - )); - ::protobuf::reflect::MessageDescriptor::new_pb_name::( - "DocError", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static DocError { - static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; - instance.get(DocError::new) - } -} - -impl ::protobuf::Clear for DocError { - fn clear(&mut self) { - self.code = ErrorCode::WsConnectError; - self.msg.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for DocError { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::protobuf::text_format::fmt(self, f) - } -} - -impl ::protobuf::reflect::ProtobufValue for DocError { - fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { - ::protobuf::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -pub enum ErrorCode { - WsConnectError = 0, - DocNotfound = 1, - DuplicateRevision = 2, - UserUnauthorized = 10, - InternalError = 1000, -} - -impl ::protobuf::ProtobufEnum for ErrorCode { - fn value(&self) -> i32 { - *self as i32 - } - - fn from_i32(value: i32) -> ::std::option::Option { - match value { - 0 => ::std::option::Option::Some(ErrorCode::WsConnectError), - 1 => ::std::option::Option::Some(ErrorCode::DocNotfound), - 2 => ::std::option::Option::Some(ErrorCode::DuplicateRevision), - 10 => ::std::option::Option::Some(ErrorCode::UserUnauthorized), - 1000 => ::std::option::Option::Some(ErrorCode::InternalError), - _ => ::std::option::Option::None - } - } - - fn values() -> &'static [Self] { - static values: &'static [ErrorCode] = &[ - ErrorCode::WsConnectError, - ErrorCode::DocNotfound, - ErrorCode::DuplicateRevision, - ErrorCode::UserUnauthorized, - ErrorCode::InternalError, - ]; - values - } - - fn enum_descriptor_static() -> &'static ::protobuf::reflect::EnumDescriptor { - static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::EnumDescriptor> = ::protobuf::rt::LazyV2::INIT; - descriptor.get(|| { - ::protobuf::reflect::EnumDescriptor::new_pb_name::("ErrorCode", file_descriptor_proto()) - }) - } -} - -impl ::std::marker::Copy for ErrorCode { -} - -impl ::std::default::Default for ErrorCode { - fn default() -> Self { - ErrorCode::WsConnectError - } -} - -impl ::protobuf::reflect::ProtobufValue for ErrorCode { - fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { - ::protobuf::reflect::ReflectValueRef::Enum(::protobuf::ProtobufEnum::descriptor(self)) - } -} - -static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x0cerrors.proto\"<\n\x08DocError\x12\x1e\n\x04code\x18\x01\x20\x01(\ - \x0e2\n.ErrorCodeR\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\tR\x03msg*q\ - \n\tErrorCode\x12\x12\n\x0eWsConnectError\x10\0\x12\x0f\n\x0bDocNotfound\ - \x10\x01\x12\x15\n\x11DuplicateRevision\x10\x02\x12\x14\n\x10UserUnautho\ - rized\x10\n\x12\x12\n\rInternalError\x10\xe8\x07J\xfd\x02\n\x06\x12\x04\ - \0\0\x0c\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\ - \0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x10\n\x0b\n\x04\x04\0\x02\ - \0\x12\x03\x03\x04\x17\n\x0c\n\x05\x04\0\x02\0\x06\x12\x03\x03\x04\r\n\ - \x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x0e\x12\n\x0c\n\x05\x04\0\x02\0\ - \x03\x12\x03\x03\x15\x16\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x13\n\ - \x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\ - \x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x11\ - \x12\n\n\n\x02\x05\0\x12\x04\x06\0\x0c\x01\n\n\n\x03\x05\0\x01\x12\x03\ - \x06\x05\x0e\n\x0b\n\x04\x05\0\x02\0\x12\x03\x07\x04\x17\n\x0c\n\x05\x05\ - \0\x02\0\x01\x12\x03\x07\x04\x12\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x07\ - \x15\x16\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x08\x04\x14\n\x0c\n\x05\x05\0\ - \x02\x01\x01\x12\x03\x08\x04\x0f\n\x0c\n\x05\x05\0\x02\x01\x02\x12\x03\ - \x08\x12\x13\n\x0b\n\x04\x05\0\x02\x02\x12\x03\t\x04\x1a\n\x0c\n\x05\x05\ - \0\x02\x02\x01\x12\x03\t\x04\x15\n\x0c\n\x05\x05\0\x02\x02\x02\x12\x03\t\ - \x18\x19\n\x0b\n\x04\x05\0\x02\x03\x12\x03\n\x04\x1a\n\x0c\n\x05\x05\0\ - \x02\x03\x01\x12\x03\n\x04\x14\n\x0c\n\x05\x05\0\x02\x03\x02\x12\x03\n\ - \x17\x19\n\x0b\n\x04\x05\0\x02\x04\x12\x03\x0b\x04\x19\n\x0c\n\x05\x05\0\ - \x02\x04\x01\x12\x03\x0b\x04\x11\n\x0c\n\x05\x05\0\x02\x04\x02\x12\x03\ - \x0b\x14\x18b\x06proto3\ -"; - -static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { - ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() -} - -pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() - }) -} diff --git a/frontend/rust-lib/flowy-document/src/protobuf/model/mod.rs b/frontend/rust-lib/flowy-document/src/protobuf/model/mod.rs index 2145302222..08899a0b2d 100644 --- a/frontend/rust-lib/flowy-document/src/protobuf/model/mod.rs +++ b/frontend/rust-lib/flowy-document/src/protobuf/model/mod.rs @@ -3,6 +3,3 @@ mod observable; pub use observable::*; - -mod errors; -pub use errors::*; diff --git a/frontend/rust-lib/flowy-document/src/protobuf/proto/errors.proto b/frontend/rust-lib/flowy-document/src/protobuf/proto/errors.proto deleted file mode 100644 index b2bbb6dd62..0000000000 --- a/frontend/rust-lib/flowy-document/src/protobuf/proto/errors.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -message DocError { - ErrorCode code = 1; - string msg = 2; -} -enum ErrorCode { - WsConnectError = 0; - DocNotfound = 1; - DuplicateRevision = 2; - UserUnauthorized = 10; - InternalError = 1000; -} diff --git a/frontend/rust-lib/flowy-document/src/services/doc/controller.rs b/frontend/rust-lib/flowy-document/src/services/doc/controller.rs index cab76400b4..0185af24af 100644 --- a/frontend/rust-lib/flowy-document/src/services/doc/controller.rs +++ b/frontend/rust-lib/flowy-document/src/services/doc/controller.rs @@ -1,5 +1,5 @@ use crate::{ - errors::{DocError, DocResult}, + errors::FlowyError, module::DocumentUser, services::{ doc::{ @@ -14,6 +14,7 @@ use bytes::Bytes; use dashmap::DashMap; use flowy_collaboration::entities::doc::{Doc, DocDelta, DocIdentifier}; use flowy_database::ConnectionPool; +use flowy_error::FlowyResult; use lib_infra::future::FutureResult; use std::sync::Arc; @@ -35,7 +36,7 @@ impl DocController { } } - pub(crate) fn init(&self) -> DocResult<()> { + pub(crate) fn init(&self) -> FlowyResult<()> { self.ws_manager.init(); Ok(()) } @@ -44,7 +45,7 @@ impl DocController { &self, params: DocIdentifier, pool: Arc, - ) -> Result, DocError> { + ) -> Result, FlowyError> { if !self.open_cache.contains(¶ms.doc_id) { let edit_ctx = self.make_edit_context(¶ms.doc_id, pool.clone()).await?; return Ok(edit_ctx); @@ -54,7 +55,7 @@ impl DocController { Ok(edit_doc_ctx) } - pub(crate) fn close(&self, doc_id: &str) -> Result<(), DocError> { + pub(crate) fn close(&self, doc_id: &str) -> Result<(), FlowyError> { tracing::debug!("Close doc {}", doc_id); self.open_cache.remove(doc_id); self.ws_manager.remove_handler(doc_id); @@ -62,7 +63,7 @@ impl DocController { } #[tracing::instrument(level = "debug", skip(self), err)] - pub(crate) fn delete(&self, params: DocIdentifier) -> Result<(), DocError> { + pub(crate) fn delete(&self, params: DocIdentifier) -> Result<(), FlowyError> { let doc_id = ¶ms.doc_id; self.open_cache.remove(doc_id); self.ws_manager.remove_handler(doc_id); @@ -78,7 +79,7 @@ impl DocController { &self, delta: DocDelta, db_pool: Arc, - ) -> Result { + ) -> Result { if !self.open_cache.contains(&delta.doc_id) { let doc_identifier: DocIdentifier = delta.doc_id.clone().into(); let _ = self.open(doc_identifier, db_pool).await?; @@ -95,7 +96,7 @@ impl DocController { &self, doc_id: &str, pool: Arc, - ) -> Result, DocError> { + ) -> Result, FlowyError> { let user = self.user.clone(); let rev_manager = self.make_rev_manager(doc_id, pool.clone())?; let edit_ctx = ClientDocEditor::new(doc_id, user, pool, rev_manager, self.ws_manager.ws()).await?; @@ -105,7 +106,7 @@ impl DocController { Ok(edit_ctx) } - fn make_rev_manager(&self, doc_id: &str, pool: Arc) -> Result { + fn make_rev_manager(&self, doc_id: &str, pool: Arc) -> Result { // Opti: require upgradable_read lock and then upgrade to write lock using // RwLockUpgradableReadGuard::upgrade(xx) of ws // let doc = self.read_doc(doc_id, pool.clone()).await?; @@ -128,7 +129,7 @@ struct RevisionServerImpl { impl RevisionServer for RevisionServerImpl { #[tracing::instrument(level = "debug", skip(self))] - fn fetch_document(&self, doc_id: &str) -> FutureResult { + fn fetch_document(&self, doc_id: &str) -> FutureResult { let params = DocIdentifier { doc_id: doc_id.to_string(), }; @@ -137,7 +138,7 @@ impl RevisionServer for RevisionServerImpl { FutureResult::new(async move { match server.read_doc(&token, params).await? { - None => Err(DocError::doc_not_found().context("Remote doesn't have this document")), + None => Err(FlowyError::record_not_found().context("Remote doesn't have this document")), Some(doc) => Ok(doc), } }) @@ -161,7 +162,7 @@ impl OpenDocCache { pub(crate) fn contains(&self, doc_id: &str) -> bool { self.inner.get(doc_id).is_some() } - pub(crate) fn get(&self, doc_id: &str) -> Result, DocError> { + pub(crate) fn get(&self, doc_id: &str) -> Result, FlowyError> { if !self.contains(&doc_id) { return Err(doc_not_found()); } @@ -179,4 +180,6 @@ impl OpenDocCache { } } -fn doc_not_found() -> DocError { DocError::doc_not_found().context("Doc is close or you should call open first") } +fn doc_not_found() -> FlowyError { + FlowyError::record_not_found().context("Doc is close or you should call open first") +} diff --git a/frontend/rust-lib/flowy-document/src/services/doc/edit/editor.rs b/frontend/rust-lib/flowy-document/src/services/doc/edit/editor.rs index f60a7d5e86..673c637c25 100644 --- a/frontend/rust-lib/flowy-document/src/services/doc/edit/editor.rs +++ b/frontend/rust-lib/flowy-document/src/services/doc/edit/editor.rs @@ -1,5 +1,5 @@ use crate::{ - errors::{internal_error, DocError, DocResult}, + errors::FlowyError, module::DocumentUser, services::{ doc::{ @@ -16,6 +16,7 @@ use flowy_collaboration::{ errors::CollaborateResult, }; use flowy_database::ConnectionPool; +use flowy_error::{internal_error, FlowyResult}; use lib_infra::retry::{ExponentialBackoff, Retry}; use lib_ot::{ core::Interval, @@ -45,7 +46,7 @@ impl ClientDocEditor { pool: Arc, mut rev_manager: RevisionManager, ws_sender: Arc, - ) -> DocResult> { + ) -> FlowyResult> { let delta = rev_manager.load_document().await?; let edit_cmd_tx = spawn_edit_queue(doc_id, delta, pool.clone()); let doc_id = doc_id.to_string(); @@ -69,7 +70,7 @@ impl ClientDocEditor { Ok(edit_doc) } - pub async fn insert(&self, index: usize, data: T) -> Result<(), DocError> { + pub async fn insert(&self, index: usize, data: T) -> Result<(), FlowyError> { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::Insert { index, @@ -82,7 +83,7 @@ impl ClientDocEditor { Ok(()) } - pub async fn delete(&self, interval: Interval) -> Result<(), DocError> { + pub async fn delete(&self, interval: Interval) -> Result<(), FlowyError> { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::Delete { interval, ret }; let _ = self.edit_cmd_tx.send(msg); @@ -91,7 +92,7 @@ impl ClientDocEditor { Ok(()) } - pub async fn format(&self, interval: Interval, attribute: RichTextAttribute) -> Result<(), DocError> { + pub async fn format(&self, interval: Interval, attribute: RichTextAttribute) -> Result<(), FlowyError> { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::Format { interval, @@ -104,7 +105,7 @@ impl ClientDocEditor { Ok(()) } - pub async fn replace(&self, interval: Interval, data: T) -> Result<(), DocError> { + pub async fn replace(&self, interval: Interval, data: T) -> Result<(), FlowyError> { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::Replace { interval, @@ -131,7 +132,7 @@ impl ClientDocEditor { rx.await.unwrap_or(false) } - pub async fn undo(&self) -> Result { + pub async fn undo(&self) -> Result { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::Undo { ret }; let _ = self.edit_cmd_tx.send(msg); @@ -139,7 +140,7 @@ impl ClientDocEditor { Ok(r) } - pub async fn redo(&self) -> Result { + pub async fn redo(&self) -> Result { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::Redo { ret }; let _ = self.edit_cmd_tx.send(msg); @@ -147,7 +148,7 @@ impl ClientDocEditor { Ok(r) } - pub async fn delta(&self) -> DocResult { + pub async fn delta(&self) -> FlowyResult { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::ReadDoc { ret }; let _ = self.edit_cmd_tx.send(msg); @@ -159,7 +160,7 @@ impl ClientDocEditor { }) } - async fn save_local_delta(&self, delta: RichTextDelta) -> Result { + async fn save_local_delta(&self, delta: RichTextDelta) -> Result { let delta_data = delta.to_bytes(); let (base_rev_id, rev_id) = self.rev_manager.next_rev_id(); let delta_data = delta_data.to_vec(); @@ -170,7 +171,7 @@ impl ClientDocEditor { } #[tracing::instrument(level = "debug", skip(self, data), err)] - pub(crate) async fn composing_local_delta(&self, data: Bytes) -> Result<(), DocError> { + pub(crate) async fn composing_local_delta(&self, data: Bytes) -> Result<(), FlowyError> { let delta = RichTextDelta::from_bytes(&data)?; let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::ComposeDelta { @@ -207,7 +208,7 @@ impl ClientDocEditor { } #[tracing::instrument(level = "debug", skip(self))] - pub(crate) async fn handle_push_rev(&self, bytes: Bytes) -> DocResult<()> { + pub(crate) async fn handle_push_rev(&self, bytes: Bytes) -> FlowyResult<()> { // Transform the revision let (ret, rx) = oneshot::channel::>(); let _ = self.edit_cmd_tx.send(EditCommand::ProcessRemoteRevision { bytes, ret }); @@ -262,7 +263,7 @@ impl ClientDocEditor { Ok(()) } - pub async fn handle_ws_message(&self, doc_data: WsDocumentData) -> DocResult<()> { + pub async fn handle_ws_message(&self, doc_data: WsDocumentData) -> FlowyResult<()> { match self.ws_msg_tx.send(doc_data) { Ok(_) => {}, Err(e) => tracing::error!("❌Propagate ws message failed. {}", e), @@ -323,7 +324,7 @@ fn start_sync( #[cfg(feature = "flowy_unit_test")] impl ClientDocEditor { - pub async fn doc_json(&self) -> DocResult { + pub async fn doc_json(&self) -> FlowyResult { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::ReadDoc { ret }; let _ = self.edit_cmd_tx.send(msg); @@ -331,7 +332,7 @@ impl ClientDocEditor { Ok(s) } - pub async fn doc_delta(&self) -> DocResult { + pub async fn doc_delta(&self) -> FlowyResult { let (ret, rx) = oneshot::channel::>(); let msg = EditCommand::ReadDocDelta { ret }; let _ = self.edit_cmd_tx.send(msg); diff --git a/frontend/rust-lib/flowy-document/src/services/doc/edit/model.rs b/frontend/rust-lib/flowy-document/src/services/doc/edit/model.rs index c2454c267e..71a6bb195a 100644 --- a/frontend/rust-lib/flowy-document/src/services/doc/edit/model.rs +++ b/frontend/rust-lib/flowy-document/src/services/doc/edit/model.rs @@ -1,6 +1,6 @@ #![allow(clippy::all)] #![cfg_attr(rustfmt, rustfmt::skip)] -use crate::{errors::DocError, services::ws::DocumentWebSocket}; +use crate::{errors::FlowyError, services::ws::DocumentWebSocket}; use futures::future::BoxFuture; use lib_infra::retry::Action; @@ -29,7 +29,7 @@ impl OpenDocAction { impl Action for OpenDocAction { type Future = BoxFuture<'static, Result>; type Item = (); - type Error = DocError; + type Error = FlowyError; fn run(&mut self) -> Self::Future { // let new_doc_user = NewDocUser { @@ -42,6 +42,6 @@ impl Action for OpenDocAction { // Ok(_) => Box::pin(future::ready(Ok::<(), DocError>(()))), // Err(e) => Box::pin(future::ready(Err::<(), DocError>(e))), // } - Box::pin(future::ready(Ok::<(), DocError>(()))) + Box::pin(future::ready(Ok::<(), FlowyError>(()))) } } diff --git a/frontend/rust-lib/flowy-document/src/services/doc/revision/cache/cache.rs b/frontend/rust-lib/flowy-document/src/services/doc/revision/cache/cache.rs index 2eaeb75f63..e4d8bbbe48 100644 --- a/frontend/rust-lib/flowy-document/src/services/doc/revision/cache/cache.rs +++ b/frontend/rust-lib/flowy-document/src/services/doc/revision/cache/cache.rs @@ -1,5 +1,5 @@ use crate::{ - errors::{internal_error, DocError, DocResult}, + errors::FlowyError, services::doc::revision::{ cache::{disk::RevisionDiskCache, memory::RevisionMemoryCache}, RevisionRecord, @@ -9,6 +9,7 @@ use crate::{ }; use flowy_collaboration::entities::doc::Doc; use flowy_database::ConnectionPool; +use flowy_error::{internal_error, FlowyResult}; use lib_infra::future::FutureResult; use lib_ot::{ core::{Operation, OperationTransformable}, @@ -22,10 +23,10 @@ use tokio::{ }; pub trait RevisionIterator: Send + Sync { - fn next(&self) -> FutureResult, DocError>; + fn next(&self) -> FutureResult, FlowyError>; } -type DocRevisionDeskCache = dyn RevisionDiskCache; +type DocRevisionDeskCache = dyn RevisionDiskCache; pub struct RevisionCache { user_id: String, @@ -57,9 +58,9 @@ impl RevisionCache { } #[tracing::instrument(level = "debug", skip(self, revision))] - pub async fn add_local_revision(&self, revision: Revision) -> DocResult<()> { + pub async fn add_local_revision(&self, revision: Revision) -> FlowyResult<()> { if self.memory_cache.contains(&revision.rev_id) { - return Err(DocError::duplicate_rev().context(format!("Duplicate revision id: {}", revision.rev_id))); + return Err(FlowyError::internal().context(format!("Duplicate revision id: {}", revision.rev_id))); } let record = RevisionRecord { revision, @@ -71,9 +72,9 @@ impl RevisionCache { } #[tracing::instrument(level = "debug", skip(self, revision))] - pub async fn add_remote_revision(&self, revision: Revision) -> DocResult<()> { + pub async fn add_remote_revision(&self, revision: Revision) -> FlowyResult<()> { if self.memory_cache.contains(&revision.rev_id) { - return Err(DocError::duplicate_rev().context(format!("Duplicate revision id: {}", revision.rev_id))); + return Err(FlowyError::internal().context(format!("Duplicate revision id: {}", revision.rev_id))); } let record = RevisionRecord { revision, @@ -126,7 +127,7 @@ impl RevisionCache { })); } - pub async fn revisions_in_range(&self, range: RevisionRange) -> DocResult> { + pub async fn revisions_in_range(&self, range: RevisionRange) -> FlowyResult> { let revs = self.memory_cache.revisions_in_range(&range).await?; if revs.len() == range.len() as usize { Ok(revs) @@ -145,7 +146,7 @@ impl RevisionCache { } } - pub async fn load_document(&self) -> DocResult { + pub async fn load_document(&self) -> FlowyResult { // Loading the document from disk and it will be sync with server. let result = load_from_disk(&self.doc_id, self.memory_cache.clone(), self.dish_cache.clone()).await; if result.is_ok() { @@ -170,7 +171,7 @@ impl RevisionCache { } impl RevisionIterator for RevisionCache { - fn next(&self) -> FutureResult, DocError> { + fn next(&self) -> FutureResult, FlowyError> { let memory_cache = self.memory_cache.clone(); let disk_cache = self.dish_cache.clone(); let doc_id = self.doc_id.clone(); @@ -196,13 +197,13 @@ async fn load_from_disk( doc_id: &str, memory_cache: Arc, disk_cache: Arc, -) -> DocResult { +) -> FlowyResult { let doc_id = doc_id.to_owned(); let (tx, mut rx) = mpsc::channel(2); let doc = spawn_blocking(move || { let records = disk_cache.read_revisions(&doc_id)?; if records.is_empty() { - return Err(DocError::doc_not_found().context("Local doesn't have this document")); + return Err(FlowyError::record_not_found().context("Local doesn't have this document")); } let (base_rev_id, rev_id) = records.last().unwrap().revision.pair_rev_id(); @@ -224,7 +225,7 @@ async fn load_from_disk( } correct_delta_if_need(&mut delta); - Result::::Ok(Doc { + Result::::Ok(Doc { id: doc_id, data: delta.to_json(), rev_id, @@ -261,11 +262,11 @@ pub(crate) struct Persistence { } impl RevisionDiskCache for Persistence { - type Error = DocError; + type Error = FlowyError; fn create_revisions(&self, revisions: Vec) -> Result<(), Self::Error> { let conn = &*self.pool.get().map_err(internal_error)?; - conn.immediate_transaction::<_, DocError, _>(|| { + conn.immediate_transaction::<_, FlowyError, _>(|| { let _ = RevTableSql::create_rev_table(revisions, conn)?; Ok(()) }) diff --git a/frontend/rust-lib/flowy-document/src/services/doc/revision/manager.rs b/frontend/rust-lib/flowy-document/src/services/doc/revision/manager.rs index 434badcfd8..0ff47cbc2f 100644 --- a/frontend/rust-lib/flowy-document/src/services/doc/revision/manager.rs +++ b/frontend/rust-lib/flowy-document/src/services/doc/revision/manager.rs @@ -1,11 +1,12 @@ use crate::{ - errors::{DocError, DocResult}, + errors::FlowyError, services::{ doc::revision::{RevisionCache, RevisionUpStream, SteamStopRx}, ws::DocumentWebSocket, }, }; use flowy_collaboration::{entities::doc::Doc, util::RevIdCounter}; +use flowy_error::FlowyResult; use lib_infra::future::FutureResult; use lib_ot::{ core::OperationTransformable, @@ -15,7 +16,7 @@ use lib_ot::{ use std::sync::Arc; pub trait RevisionServer: Send + Sync { - fn fetch_document(&self, doc_id: &str) -> FutureResult; + fn fetch_document(&self, doc_id: &str) -> FutureResult; } pub struct RevisionManager { @@ -38,23 +39,23 @@ impl RevisionManager { } } - pub async fn load_document(&mut self) -> DocResult { + pub async fn load_document(&mut self) -> FlowyResult { let doc = self.cache.load_document().await?; self.update_rev_id_counter_value(doc.rev_id); Ok(doc.delta()?) } - pub async fn add_remote_revision(&self, revision: &Revision) -> Result<(), DocError> { + pub async fn add_remote_revision(&self, revision: &Revision) -> Result<(), FlowyError> { let _ = self.cache.add_remote_revision(revision.clone()).await?; Ok(()) } - pub async fn add_local_revision(&self, revision: &Revision) -> Result<(), DocError> { + pub async fn add_local_revision(&self, revision: &Revision) -> Result<(), FlowyError> { let _ = self.cache.add_local_revision(revision.clone()).await?; Ok(()) } - pub async fn ack_revision(&self, rev_id: RevId) -> Result<(), DocError> { + pub async fn ack_revision(&self, rev_id: RevId) -> Result<(), FlowyError> { self.cache.ack_revision(rev_id.into()).await; Ok(()) } @@ -69,7 +70,7 @@ impl RevisionManager { pub fn update_rev_id_counter_value(&self, rev_id: i64) { self.rev_id_counter.set(rev_id); } - pub async fn mk_revisions(&self, range: RevisionRange) -> Result { + pub async fn mk_revisions(&self, range: RevisionRange) -> Result { debug_assert!(range.doc_id == self.doc_id); let revisions = self.cache.revisions_in_range(range.clone()).await?; let mut new_delta = RichTextDelta::new(); diff --git a/frontend/rust-lib/flowy-document/src/services/doc/revision/sync.rs b/frontend/rust-lib/flowy-document/src/services/doc/revision/sync.rs index 9fccdd2512..f42b8ac28d 100644 --- a/frontend/rust-lib/flowy-document/src/services/doc/revision/sync.rs +++ b/frontend/rust-lib/flowy-document/src/services/doc/revision/sync.rs @@ -1,16 +1,14 @@ -use crate::{ - errors::{internal_error, DocResult}, - services::{ - doc::{ - edit::ClientDocEditor, - revision::{RevisionIterator, RevisionManager}, - }, - ws::DocumentWebSocket, +use crate::services::{ + doc::{ + edit::ClientDocEditor, + revision::{RevisionIterator, RevisionManager}, }, + ws::DocumentWebSocket, }; use async_stream::stream; use bytes::Bytes; use flowy_collaboration::entities::ws::{WsDataType, WsDocumentData}; +use flowy_error::{internal_error, FlowyResult}; use futures::stream::StreamExt; use lib_ot::revision::{RevId, RevisionRange}; use std::{convert::TryFrom, sync::Arc}; @@ -81,7 +79,7 @@ impl RevisionDownStream { .await; } - async fn handle_message(&self, msg: WsDocumentData) -> DocResult<()> { + async fn handle_message(&self, msg: WsDocumentData) -> FlowyResult<()> { let WsDocumentData { doc_id: _, ty, data } = msg; let bytes = spawn_blocking(move || Bytes::from(data)) .await @@ -169,13 +167,13 @@ impl RevisionUpStream { .await; } - async fn handle_msg(&self, msg: UpStreamMsg) -> DocResult<()> { + async fn handle_msg(&self, msg: UpStreamMsg) -> FlowyResult<()> { match msg { UpStreamMsg::Tick => self.send_next_revision().await, } } - async fn send_next_revision(&self) -> DocResult<()> { + async fn send_next_revision(&self) -> FlowyResult<()> { match self.revisions.next().await? { None => Ok(()), Some(record) => { diff --git a/frontend/rust-lib/flowy-document/src/services/server/middleware.rs b/frontend/rust-lib/flowy-document/src/services/server/middleware.rs index d4875c1c89..38b3c917df 100644 --- a/frontend/rust-lib/flowy-document/src/services/server/middleware.rs +++ b/frontend/rust-lib/flowy-document/src/services/server/middleware.rs @@ -17,7 +17,7 @@ impl ResponseMiddleware for DocMiddleware { None => {}, Some(_token) => { // let error = - // WorkspaceError::new(ErrorCode::UserUnauthorized, ""); + // FlowyError::new(ErrorCode::UserUnauthorized, ""); // observable(token, // WorkspaceObservable::UserUnauthorized).error(error). // build() diff --git a/frontend/rust-lib/flowy-document/src/services/server/mod.rs b/frontend/rust-lib/flowy-document/src/services/server/mod.rs index 864eed78ac..4f19269cb0 100644 --- a/frontend/rust-lib/flowy-document/src/services/server/mod.rs +++ b/frontend/rust-lib/flowy-document/src/services/server/mod.rs @@ -4,7 +4,7 @@ mod server_api_mock; pub use server_api::*; // TODO: ignore mock files in production -use crate::errors::DocError; +use crate::errors::FlowyError; use backend_service::configuration::ClientServerConfiguration; use flowy_collaboration::entities::doc::{CreateDocParams, Doc, DocIdentifier, UpdateDocParams}; use lib_infra::future::FutureResult; @@ -13,11 +13,11 @@ use std::sync::Arc; pub(crate) type Server = Arc; pub trait DocumentServerAPI { - fn create_doc(&self, token: &str, params: CreateDocParams) -> FutureResult<(), DocError>; + fn create_doc(&self, token: &str, params: CreateDocParams) -> FutureResult<(), FlowyError>; - fn read_doc(&self, token: &str, params: DocIdentifier) -> FutureResult, DocError>; + fn read_doc(&self, token: &str, params: DocIdentifier) -> FutureResult, FlowyError>; - fn update_doc(&self, token: &str, params: UpdateDocParams) -> FutureResult<(), DocError>; + fn update_doc(&self, token: &str, params: UpdateDocParams) -> FutureResult<(), FlowyError>; } pub(crate) fn construct_doc_server( diff --git a/frontend/rust-lib/flowy-document/src/services/server/server_api.rs b/frontend/rust-lib/flowy-document/src/services/server/server_api.rs index c5a56aaa5c..c12f0a9662 100644 --- a/frontend/rust-lib/flowy-document/src/services/server/server_api.rs +++ b/frontend/rust-lib/flowy-document/src/services/server/server_api.rs @@ -1,4 +1,4 @@ -use crate::{errors::DocError, services::server::DocumentServerAPI}; +use crate::{errors::FlowyError, services::server::DocumentServerAPI}; use backend_service::{configuration::*, request::HttpRequestBuilder}; use flowy_collaboration::entities::doc::{CreateDocParams, Doc, DocIdentifier, UpdateDocParams}; use lib_infra::future::FutureResult; @@ -12,19 +12,19 @@ impl DocServer { } impl DocumentServerAPI for DocServer { - fn create_doc(&self, token: &str, params: CreateDocParams) -> FutureResult<(), DocError> { + fn create_doc(&self, token: &str, params: CreateDocParams) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.doc_url(); FutureResult::new(async move { create_doc_request(&token, params, &url).await }) } - fn read_doc(&self, token: &str, params: DocIdentifier) -> FutureResult, DocError> { + fn read_doc(&self, token: &str, params: DocIdentifier) -> FutureResult, FlowyError> { let token = token.to_owned(); let url = self.config.doc_url(); FutureResult::new(async move { read_doc_request(&token, params, &url).await }) } - fn update_doc(&self, token: &str, params: UpdateDocParams) -> FutureResult<(), DocError> { + fn update_doc(&self, token: &str, params: UpdateDocParams) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.doc_url(); FutureResult::new(async move { update_doc_request(&token, params, &url).await }) @@ -35,7 +35,7 @@ pub(crate) fn request_builder() -> HttpRequestBuilder { HttpRequestBuilder::new().middleware(super::middleware::MIDDLEWARE.clone()) } -pub async fn create_doc_request(token: &str, params: CreateDocParams, url: &str) -> Result<(), DocError> { +pub async fn create_doc_request(token: &str, params: CreateDocParams, url: &str) -> Result<(), FlowyError> { let _ = request_builder() .post(&url.to_owned()) .header(HEADER_TOKEN, token) @@ -45,7 +45,7 @@ pub async fn create_doc_request(token: &str, params: CreateDocParams, url: &str) Ok(()) } -pub async fn read_doc_request(token: &str, params: DocIdentifier, url: &str) -> Result, DocError> { +pub async fn read_doc_request(token: &str, params: DocIdentifier, url: &str) -> Result, FlowyError> { let doc = request_builder() .get(&url.to_owned()) .header(HEADER_TOKEN, token) @@ -56,7 +56,7 @@ pub async fn read_doc_request(token: &str, params: DocIdentifier, url: &str) -> Ok(doc) } -pub async fn update_doc_request(token: &str, params: UpdateDocParams, url: &str) -> Result<(), DocError> { +pub async fn update_doc_request(token: &str, params: UpdateDocParams, url: &str) -> Result<(), FlowyError> { let _ = request_builder() .patch(&url.to_owned()) .header(HEADER_TOKEN, token) diff --git a/frontend/rust-lib/flowy-document/src/services/server/server_api_mock.rs b/frontend/rust-lib/flowy-document/src/services/server/server_api_mock.rs index faf728f195..b2bdd3b7ed 100644 --- a/frontend/rust-lib/flowy-document/src/services/server/server_api_mock.rs +++ b/frontend/rust-lib/flowy-document/src/services/server/server_api_mock.rs @@ -4,16 +4,16 @@ use flowy_collaboration::{ }; use lib_infra::future::FutureResult; -use crate::{errors::DocError, services::server::DocumentServerAPI}; +use crate::{errors::FlowyError, services::server::DocumentServerAPI}; pub struct DocServerMock {} impl DocumentServerAPI for DocServerMock { - fn create_doc(&self, _token: &str, _params: CreateDocParams) -> FutureResult<(), DocError> { + fn create_doc(&self, _token: &str, _params: CreateDocParams) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn read_doc(&self, _token: &str, params: DocIdentifier) -> FutureResult, DocError> { + fn read_doc(&self, _token: &str, params: DocIdentifier) -> FutureResult, FlowyError> { let doc = Doc { id: params.doc_id, data: initial_string(), @@ -23,7 +23,7 @@ impl DocumentServerAPI for DocServerMock { FutureResult::new(async { Ok(Some(doc)) }) } - fn update_doc(&self, _token: &str, _params: UpdateDocParams) -> FutureResult<(), DocError> { + fn update_doc(&self, _token: &str, _params: UpdateDocParams) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } } diff --git a/frontend/rust-lib/flowy-document/src/services/ws/ws_manager.rs b/frontend/rust-lib/flowy-document/src/services/ws/ws_manager.rs index eb2c8cc0cb..efccc18ece 100644 --- a/frontend/rust-lib/flowy-document/src/services/ws/ws_manager.rs +++ b/frontend/rust-lib/flowy-document/src/services/ws/ws_manager.rs @@ -1,4 +1,4 @@ -use crate::errors::DocError; +use crate::errors::FlowyError; use bytes::Bytes; use dashmap::DashMap; use flowy_collaboration::entities::ws::WsDocumentData; @@ -12,7 +12,7 @@ pub(crate) trait WsDocumentHandler: Send + Sync { pub type WsStateReceiver = tokio::sync::broadcast::Receiver; pub trait DocumentWebSocket: Send + Sync { - fn send(&self, data: WsDocumentData) -> Result<(), DocError>; + fn send(&self, data: WsDocumentData) -> Result<(), FlowyError>; fn subscribe_state_changed(&self) -> WsStateReceiver; } diff --git a/frontend/rust-lib/flowy-document/src/sql_tables/doc/rev_sql.rs b/frontend/rust-lib/flowy-document/src/sql_tables/doc/rev_sql.rs index 61077c26fd..80a9f106bf 100644 --- a/frontend/rust-lib/flowy-document/src/sql_tables/doc/rev_sql.rs +++ b/frontend/rust-lib/flowy-document/src/sql_tables/doc/rev_sql.rs @@ -1,5 +1,5 @@ use crate::{ - errors::DocError, + errors::FlowyError, services::doc::revision::RevisionRecord, sql_tables::{doc::RevTable, mk_revision_record_from_table, RevChangeset, RevTableState, RevTableType}, }; @@ -10,7 +10,7 @@ use lib_ot::revision::RevisionRange; pub struct RevTableSql {} impl RevTableSql { - pub(crate) fn create_rev_table(revisions: Vec, conn: &SqliteConnection) -> Result<(), DocError> { + pub(crate) fn create_rev_table(revisions: Vec, conn: &SqliteConnection) -> Result<(), FlowyError> { // Batch insert: https://diesel.rs/guides/all-about-inserts.html let records = revisions .into_iter() @@ -33,7 +33,7 @@ impl RevTableSql { } #[allow(dead_code)] - pub(crate) fn update_rev_table(changeset: RevChangeset, conn: &SqliteConnection) -> Result<(), DocError> { + pub(crate) fn update_rev_table(changeset: RevChangeset, conn: &SqliteConnection) -> Result<(), FlowyError> { let filter = dsl::rev_table .filter(dsl::rev_id.eq(changeset.rev_id.as_ref())) .filter(dsl::doc_id.eq(changeset.doc_id)); @@ -46,7 +46,7 @@ impl RevTableSql { user_id: &str, doc_id: &str, conn: &SqliteConnection, - ) -> Result, DocError> { + ) -> Result, FlowyError> { let filter = dsl::rev_table .filter(dsl::doc_id.eq(doc_id)) .order(dsl::rev_id.asc()) @@ -64,7 +64,7 @@ impl RevTableSql { doc_id: &str, revision_id: &i64, conn: &SqliteConnection, - ) -> Result, DocError> { + ) -> Result, FlowyError> { let filter = dsl::rev_table .filter(dsl::doc_id.eq(doc_id)) .filter(dsl::rev_id.eq(revision_id)); @@ -82,7 +82,7 @@ impl RevTableSql { doc_id: &str, range: RevisionRange, conn: &SqliteConnection, - ) -> Result, DocError> { + ) -> Result, FlowyError> { let rev_tables = dsl::rev_table .filter(dsl::rev_id.ge(range.start)) .filter(dsl::rev_id.le(range.end)) @@ -98,7 +98,7 @@ impl RevTableSql { } #[allow(dead_code)] - pub(crate) fn delete_rev_table(doc_id_s: &str, rev_id_s: i64, conn: &SqliteConnection) -> Result<(), DocError> { + pub(crate) fn delete_rev_table(doc_id_s: &str, rev_id_s: i64, conn: &SqliteConnection) -> Result<(), FlowyError> { let filter = dsl::rev_table .filter(dsl::rev_id.eq(rev_id_s)) .filter(dsl::doc_id.eq(doc_id_s)); diff --git a/frontend/rust-lib/flowy-error/Cargo.toml b/frontend/rust-lib/flowy-error/Cargo.toml index b738a43422..5ec55b475e 100644 --- a/frontend/rust-lib/flowy-error/Cargo.toml +++ b/frontend/rust-lib/flowy-error/Cargo.toml @@ -7,7 +7,23 @@ edition = "2018" [dependencies] flowy-derive = { path = "../../../shared-lib/flowy-derive" } -derive_more = {version = "0.99", features = ["display"]} +error-code = { path = "../../../shared-lib/error-code" } lib-dispatch = { path = "../lib-dispatch" } protobuf = {version = "2.20.0"} -bytes = "1.0" \ No newline at end of file +bytes = "1.0" + + +flowy-collaboration = { path = "../../../shared-lib/flowy-collaboration", optional = true} +lib-ot = { path = "../../../shared-lib/lib-ot", optional = true} +serde_json = {version = "1.0", optional = true} +backend-service = { path = "../../../shared-lib/backend-service", optional = true} +flowy-database = { path = "../flowy-database", optional = true} +lib-sqlite = { path = "../../../shared-lib/lib-sqlite", optional = true} +r2d2 = { version = "0.8", optional = true} + +[features] +collaboration = ["flowy-collaboration"] +ot = ["lib-ot"] +serde = ["serde_json"] +backend = ["backend-service"] +db = ["flowy-database", "lib-sqlite", "r2d2"] diff --git a/frontend/rust-lib/flowy-error/src/errors.rs b/frontend/rust-lib/flowy-error/src/errors.rs index e79b08bee8..c8459b9d4e 100644 --- a/frontend/rust-lib/flowy-error/src/errors.rs +++ b/frontend/rust-lib/flowy-error/src/errors.rs @@ -1,13 +1,10 @@ -use crate::protobuf::ErrorCode as ProtoBufErrorCode; use bytes::Bytes; -use derive_more::Display; -use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; +use error_code::ErrorCode; +use flowy_derive::ProtoBuf; use lib_dispatch::prelude::{EventResponse, ResponseBuilder}; -use protobuf::ProtobufEnum; -use std::{ - convert::{TryFrom, TryInto}, - fmt::Debug, -}; +use std::{convert::TryInto, fmt, fmt::Debug}; + +pub type FlowyResult = std::result::Result; #[derive(Debug, Default, Clone, ProtoBuf)] pub struct FlowyError { @@ -18,7 +15,7 @@ pub struct FlowyError { pub msg: String, } -macro_rules! static_any_error { +macro_rules! static_flowy_error { ($name:ident, $code:expr) => { #[allow(non_snake_case, missing_docs)] pub fn $name() -> FlowyError { $code.into() } @@ -37,7 +34,34 @@ impl FlowyError { self } - static_any_error!(internal, ErrorCode::Internal); + static_flowy_error!(internal, ErrorCode::Internal); + static_flowy_error!(record_not_found, ErrorCode::RecordNotFound); + static_flowy_error!(workspace_name, ErrorCode::WorkspaceNameInvalid); + static_flowy_error!(workspace_id, ErrorCode::WorkspaceIdInvalid); + static_flowy_error!(color_style, ErrorCode::AppColorStyleInvalid); + static_flowy_error!(workspace_desc, ErrorCode::WorkspaceDescTooLong); + static_flowy_error!(app_name, ErrorCode::AppNameInvalid); + static_flowy_error!(invalid_app_id, ErrorCode::AppIdInvalid); + static_flowy_error!(view_name, ErrorCode::ViewNameInvalid); + static_flowy_error!(view_thumbnail, ErrorCode::ViewThumbnailInvalid); + static_flowy_error!(invalid_view_id, ErrorCode::ViewIdInvalid); + 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!(email_empty, ErrorCode::EmailIsEmpty); + static_flowy_error!(email_format, ErrorCode::EmailFormatInvalid); + static_flowy_error!(email_exist, ErrorCode::EmailAlreadyExists); + static_flowy_error!(password_empty, ErrorCode::PasswordIsEmpty); + static_flowy_error!(passworkd_too_long, ErrorCode::PasswordTooLong); + static_flowy_error!(password_forbid_char, ErrorCode::PasswordContainsForbidCharacters); + static_flowy_error!(password_format, ErrorCode::PasswordFormatInvalid); + static_flowy_error!(password_not_match, ErrorCode::PasswordNotMatch); + static_flowy_error!(name_too_long, ErrorCode::UserNameTooLong); + static_flowy_error!(name_forbid_char, ErrorCode::UserNameContainForbiddenCharacters); + static_flowy_error!(name_empty, ErrorCode::UserNameIsEmpty); + static_flowy_error!(user_id, ErrorCode::UserIdInvalid); + static_flowy_error!(user_not_exist, ErrorCode::UserNotExist); } impl std::convert::From for FlowyError { @@ -49,26 +73,6 @@ impl std::convert::From for FlowyError { } } -#[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] -pub enum ErrorCode { - #[display(fmt = "Internal error")] - Internal = 0, -} - -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(), - } - } -} - pub fn internal_error(e: T) -> FlowyError where T: std::fmt::Debug, @@ -76,9 +80,21 @@ where FlowyError::internal().context(e) } +impl fmt::Display for FlowyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", &self.code, &self.msg) } +} + impl lib_dispatch::Error for FlowyError { fn as_response(&self) -> EventResponse { let bytes: Bytes = self.clone().try_into().unwrap(); ResponseBuilder::Err().data(bytes).build() } } + +impl std::convert::From for FlowyError { + fn from(error: std::io::Error) -> Self { FlowyError::internal().context(error) } +} + +impl std::convert::From for FlowyError { + fn from(e: protobuf::ProtobufError) -> Self { FlowyError::internal().context(e) } +} diff --git a/frontend/rust-lib/flowy-error/src/ext/backend.rs b/frontend/rust-lib/flowy-error/src/ext/backend.rs new file mode 100644 index 0000000000..68cc9dca45 --- /dev/null +++ b/frontend/rust-lib/flowy-error/src/ext/backend.rs @@ -0,0 +1,22 @@ +use crate::FlowyError; +use backend_service::errors::{ErrorCode as ServerErrorCode, ServerError}; +use error_code::ErrorCode; + +impl std::convert::From for FlowyError { + fn from(error: ServerError) -> Self { + let code = server_error_to_flowy_error(error.code); + FlowyError::new(code, &error.msg) + } +} + +fn server_error_to_flowy_error(code: ServerErrorCode) -> ErrorCode { + match code { + ServerErrorCode::UserUnauthorized => ErrorCode::UserUnauthorized, + ServerErrorCode::PasswordNotMatch => ErrorCode::PasswordNotMatch, + ServerErrorCode::RecordNotFound => ErrorCode::RecordNotFound, + ServerErrorCode::ConnectRefused | ServerErrorCode::ConnectTimeout | ServerErrorCode::ConnectClose => { + ErrorCode::ConnectError + }, + _ => ErrorCode::Internal, + } +} diff --git a/frontend/rust-lib/flowy-error/src/ext/collaborate.rs b/frontend/rust-lib/flowy-error/src/ext/collaborate.rs new file mode 100644 index 0000000000..82246f7792 --- /dev/null +++ b/frontend/rust-lib/flowy-error/src/ext/collaborate.rs @@ -0,0 +1,5 @@ +use crate::FlowyError; + +impl std::convert::From for FlowyError { + fn from(error: flowy_collaboration::errors::CollaborateError) -> Self { FlowyError::internal().context(error) } +} diff --git a/frontend/rust-lib/flowy-error/src/ext/database.rs b/frontend/rust-lib/flowy-error/src/ext/database.rs new file mode 100644 index 0000000000..f395a0235c --- /dev/null +++ b/frontend/rust-lib/flowy-error/src/ext/database.rs @@ -0,0 +1,15 @@ +use crate::FlowyError; + +impl std::convert::From for FlowyError { + fn from(error: flowy_database::Error) -> Self { FlowyError::internal().context(error) } +} + +impl std::convert::From<::r2d2::Error> for FlowyError { + fn from(error: r2d2::Error) -> Self { FlowyError::internal().context(error) } +} + +// use diesel::result::{Error, DatabaseErrorKind}; +// use lib_sqlite::ErrorKind; +impl std::convert::From for FlowyError { + fn from(error: lib_sqlite::Error) -> Self { FlowyError::internal().context(error) } +} diff --git a/frontend/rust-lib/flowy-error/src/ext/mod.rs b/frontend/rust-lib/flowy-error/src/ext/mod.rs new file mode 100644 index 0000000000..8bd455de93 --- /dev/null +++ b/frontend/rust-lib/flowy-error/src/ext/mod.rs @@ -0,0 +1,27 @@ +#[cfg(feature = "collaboration")] +mod collaborate; +#[cfg(feature = "collaboration")] +pub use collaborate::*; + +// +#[cfg(feature = "ot")] +mod ot; +#[cfg(feature = "ot")] +pub use ot::*; + +// +#[cfg(feature = "serde")] +mod serde; +#[cfg(feature = "serde")] +pub use serde::*; + +// +#[cfg(feature = "backend")] +mod backend; +#[cfg(feature = "backend")] +pub use backend::*; + +#[cfg(feature = "db")] +mod database; +#[cfg(feature = "db")] +pub use database::*; diff --git a/frontend/rust-lib/flowy-error/src/ext/ot.rs b/frontend/rust-lib/flowy-error/src/ext/ot.rs new file mode 100644 index 0000000000..bfce081953 --- /dev/null +++ b/frontend/rust-lib/flowy-error/src/ext/ot.rs @@ -0,0 +1,5 @@ +use crate::FlowyError; + +impl std::convert::From for FlowyError { + fn from(error: lib_ot::errors::OTError) -> Self { FlowyError::internal().context(error) } +} diff --git a/frontend/rust-lib/flowy-error/src/ext/serde.rs b/frontend/rust-lib/flowy-error/src/ext/serde.rs new file mode 100644 index 0000000000..87c7d55178 --- /dev/null +++ b/frontend/rust-lib/flowy-error/src/ext/serde.rs @@ -0,0 +1,5 @@ +use crate::FlowyError; + +impl std::convert::From for FlowyError { + fn from(error: serde_json::Error) -> Self { FlowyError::internal().context(error) } +} diff --git a/frontend/rust-lib/flowy-error/src/lib.rs b/frontend/rust-lib/flowy-error/src/lib.rs index e7c6be4852..756eb4e82c 100644 --- a/frontend/rust-lib/flowy-error/src/lib.rs +++ b/frontend/rust-lib/flowy-error/src/lib.rs @@ -1,4 +1,6 @@ mod errors; +mod ext; pub mod protobuf; +pub use error_code::ErrorCode; pub use errors::*; diff --git a/frontend/rust-lib/flowy-error/src/protobuf/model/errors.rs b/frontend/rust-lib/flowy-error/src/protobuf/model/errors.rs index e30f60612c..a3dcaf639b 100644 --- a/frontend/rust-lib/flowy-error/src/protobuf/model/errors.rs +++ b/frontend/rust-lib/flowy-error/src/protobuf/model/errors.rs @@ -217,67 +217,17 @@ impl ::protobuf::reflect::ProtobufValue for FlowyError { } } -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -pub enum ErrorCode { - Internal = 0, -} - -impl ::protobuf::ProtobufEnum for ErrorCode { - fn value(&self) -> i32 { - *self as i32 - } - - fn from_i32(value: i32) -> ::std::option::Option { - match value { - 0 => ::std::option::Option::Some(ErrorCode::Internal), - _ => ::std::option::Option::None - } - } - - fn values() -> &'static [Self] { - static values: &'static [ErrorCode] = &[ - ErrorCode::Internal, - ]; - values - } - - fn enum_descriptor_static() -> &'static ::protobuf::reflect::EnumDescriptor { - static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::EnumDescriptor> = ::protobuf::rt::LazyV2::INIT; - descriptor.get(|| { - ::protobuf::reflect::EnumDescriptor::new_pb_name::("ErrorCode", file_descriptor_proto()) - }) - } -} - -impl ::std::marker::Copy for ErrorCode { -} - -impl ::std::default::Default for ErrorCode { - fn default() -> Self { - ErrorCode::Internal - } -} - -impl ::protobuf::reflect::ProtobufValue for ErrorCode { - fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { - ::protobuf::reflect::ReflectValueRef::Enum(::protobuf::ProtobufEnum::descriptor(self)) - } -} - static file_descriptor_proto_data: &'static [u8] = b"\ \n\x0cerrors.proto\"2\n\nFlowyError\x12\x12\n\x04code\x18\x01\x20\x01(\ - \x05R\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\tR\x03msg*\x19\n\tErrorC\ - ode\x12\x0c\n\x08Internal\x10\0J\xd9\x01\n\x06\x12\x04\0\0\x08\x01\n\x08\ - \n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\n\ - \x03\x04\0\x01\x12\x03\x02\x08\x12\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\ - \x04\x13\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x04\t\n\x0c\n\x05\x04\0\ - \x02\0\x01\x12\x03\x03\n\x0e\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\x11\ - \x12\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x13\n\x0c\n\x05\x04\0\x02\ - \x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\x0b\ - \x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x11\x12\n\n\n\x02\x05\0\ - \x12\x04\x06\0\x08\x01\n\n\n\x03\x05\0\x01\x12\x03\x06\x05\x0e\n\x0b\n\ - \x04\x05\0\x02\0\x12\x03\x07\x04\x11\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\ - \x07\x04\x0c\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x07\x0f\x10b\x06proto3\ + \x05R\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\tR\x03msgJ\x98\x01\n\x06\ + \x12\x04\0\0\x05\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\ + \x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x12\n\x0b\n\x04\ + \x04\0\x02\0\x12\x03\x03\x04\x13\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\ + \x04\t\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\n\x0e\n\x0c\n\x05\x04\0\ + \x02\0\x03\x12\x03\x03\x11\x12\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\ + \x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\ + \x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\ + \x04\x11\x12b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/frontend/rust-lib/flowy-error/src/protobuf/proto/errors.proto b/frontend/rust-lib/flowy-error/src/protobuf/proto/errors.proto index 434258f108..2be9375a15 100644 --- a/frontend/rust-lib/flowy-error/src/protobuf/proto/errors.proto +++ b/frontend/rust-lib/flowy-error/src/protobuf/proto/errors.proto @@ -4,6 +4,3 @@ message FlowyError { int32 code = 1; string msg = 2; } -enum ErrorCode { - Internal = 0; -} diff --git a/frontend/rust-lib/flowy-net/src/handlers/mod.rs b/frontend/rust-lib/flowy-net/src/handlers/mod.rs index 6e6486c28c..d02093db8d 100644 --- a/frontend/rust-lib/flowy-net/src/handlers/mod.rs +++ b/frontend/rust-lib/flowy-net/src/handlers/mod.rs @@ -1,5 +1,5 @@ use crate::{entities::NetworkState, services::ws::WsManager}; -use bytes::Bytes; + use flowy_error::FlowyError; use lib_dispatch::prelude::{Data, Unit}; use std::sync::Arc; diff --git a/frontend/rust-lib/flowy-net/src/module.rs b/frontend/rust-lib/flowy-net/src/module.rs index 18b17ad8a5..888fb2316b 100644 --- a/frontend/rust-lib/flowy-net/src/module.rs +++ b/frontend/rust-lib/flowy-net/src/module.rs @@ -5,6 +5,6 @@ use std::sync::Arc; pub fn create(ws_manager: Arc) -> Module { Module::new() .name("Flowy-Network") - .data(ws_manager.clone()) + .data(ws_manager) .event(NetworkEvent::UpdateNetworkType, update_network_ty) } diff --git a/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs b/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs index 150385f1f1..b320f13b53 100644 --- a/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs +++ b/frontend/rust-lib/flowy-sdk/src/deps_resolve/document_deps.rs @@ -2,15 +2,12 @@ use bytes::Bytes; use flowy_collaboration::entities::ws::WsDocumentData; use flowy_database::ConnectionPool; use flowy_document::{ - errors::{internal_error, DocError}, + errors::{internal_error, FlowyError}, module::DocumentUser, services::ws::{DocumentWebSocket, WsDocumentManager, WsStateReceiver}, }; use flowy_net::services::ws::WsManager; -use flowy_user::{ - errors::{ErrorCode, UserError}, - services::user::UserSession, -}; +use flowy_user::services::user::UserSession; use lib_ws::{WsMessage, WsMessageHandler, WsModule}; use std::{convert::TryInto, path::Path, sync::Arc}; @@ -20,16 +17,14 @@ impl DocumentDepsResolver { ws_manager: Arc, user_session: Arc, ) -> (Arc, Arc) { - let user = Arc::new(DocumentUserImpl { - user: user_session.clone(), - }); + let user = Arc::new(DocumentUserImpl { user: user_session }); let sender = Arc::new(WsSenderImpl { ws_manager: ws_manager.clone(), }); let ws_doc = Arc::new(WsDocumentManager::new(sender)); let ws_handler = Arc::new(DocumentWsMessageReceiver { inner: ws_doc.clone() }); - ws_manager.add_handler(ws_handler); + ws_manager.add_handler(ws_handler).unwrap(); (user, ws_doc) } } @@ -40,16 +35,12 @@ struct DocumentUserImpl { impl DocumentUserImpl {} -fn map_user_error(error: UserError) -> DocError { - match ErrorCode::from_i32(error.code) { - ErrorCode::InternalError => DocError::internal().context(error.msg), - _ => DocError::internal().context(error), - } -} - impl DocumentUser for DocumentUserImpl { - fn user_dir(&self) -> Result { - let dir = self.user.user_dir().map_err(|e| DocError::unauthorized().context(e))?; + fn user_dir(&self) -> Result { + let dir = self + .user + .user_dir() + .map_err(|e| FlowyError::unauthorized().context(e))?; let doc_dir = format!("{}/doc", dir); if !Path::new(&doc_dir).exists() { @@ -58,11 +49,11 @@ impl DocumentUser for DocumentUserImpl { Ok(doc_dir) } - fn user_id(&self) -> Result { self.user.user_id().map_err(map_user_error) } + fn user_id(&self) -> Result { self.user.user_id() } - fn token(&self) -> Result { self.user.token().map_err(map_user_error) } + fn token(&self) -> Result { self.user.token() } - fn db_pool(&self) -> Result, DocError> { self.user.db_pool().map_err(map_user_error) } + fn db_pool(&self) -> Result, FlowyError> { self.user.db_pool() } } struct WsSenderImpl { @@ -70,7 +61,7 @@ struct WsSenderImpl { } impl DocumentWebSocket for WsSenderImpl { - fn send(&self, data: WsDocumentData) -> Result<(), DocError> { + fn send(&self, data: WsDocumentData) -> Result<(), FlowyError> { let bytes: Bytes = data.try_into().unwrap(); let msg = WsMessage { module: WsModule::Doc, diff --git a/frontend/rust-lib/flowy-sdk/src/deps_resolve/workspace_deps.rs b/frontend/rust-lib/flowy-sdk/src/deps_resolve/workspace_deps.rs index e89ad9138a..f44b45568e 100644 --- a/frontend/rust-lib/flowy-sdk/src/deps_resolve/workspace_deps.rs +++ b/frontend/rust-lib/flowy-sdk/src/deps_resolve/workspace_deps.rs @@ -1,5 +1,5 @@ use flowy_core::{ - errors::WorkspaceError, + errors::FlowyError, module::{WorkspaceDatabase, WorkspaceUser}, }; use flowy_database::ConnectionPool; @@ -29,23 +29,21 @@ impl WorkspaceDepsResolver { } impl WorkspaceDatabase for Resolver { - fn db_pool(&self) -> Result, WorkspaceError> { + fn db_pool(&self) -> Result, FlowyError> { self.user_session .db_pool() - .map_err(|e| WorkspaceError::internal().context(e)) + .map_err(|e| FlowyError::internal().context(e)) } } impl WorkspaceUser for Resolver { - fn user_id(&self) -> Result { + fn user_id(&self) -> Result { self.user_session .user_id() - .map_err(|e| WorkspaceError::internal().context(e)) + .map_err(|e| FlowyError::internal().context(e)) } - fn token(&self) -> Result { - self.user_session - .token() - .map_err(|e| WorkspaceError::internal().context(e)) + fn token(&self) -> Result { + self.user_session.token().map_err(|e| FlowyError::internal().context(e)) } } diff --git a/frontend/rust-lib/flowy-sdk/src/lib.rs b/frontend/rust-lib/flowy-sdk/src/lib.rs index 45cbb96a17..55efc14fa8 100644 --- a/frontend/rust-lib/flowy-sdk/src/lib.rs +++ b/frontend/rust-lib/flowy-sdk/src/lib.rs @@ -3,7 +3,7 @@ mod deps_resolve; pub mod module; use crate::deps_resolve::{DocumentDepsResolver, WorkspaceDepsResolver}; use backend_service::configuration::ClientServerConfiguration; -use flowy_core::{errors::WorkspaceError, module::init_core, prelude::CoreContext}; +use flowy_core::{errors::FlowyError, module::init_core, prelude::CoreContext}; use flowy_document::module::FlowyDocument; use flowy_net::{entities::NetworkType, services::ws::WsManager}; use flowy_user::{ @@ -130,7 +130,7 @@ async fn _listen_user_status( match status { UserStatus::Login { token } => { let _ = core.user_did_sign_in(&token).await?; - let _ = ws_manager.start(token).await.unwrap(); + let _ = ws_manager.start(token).await?; }, UserStatus::Logout { .. } => { core.user_did_logout().await; @@ -143,7 +143,7 @@ async fn _listen_user_status( let _ = ret.send(()); }, } - Ok::<(), WorkspaceError>(()) + Ok::<(), FlowyError>(()) }; match result().await { diff --git a/frontend/rust-lib/flowy-sdk/src/module.rs b/frontend/rust-lib/flowy-sdk/src/module.rs index 9c9af5e2e1..572373b761 100644 --- a/frontend/rust-lib/flowy-sdk/src/module.rs +++ b/frontend/rust-lib/flowy-sdk/src/module.rs @@ -1,7 +1,5 @@ -use crate::deps_resolve::DocumentDepsResolver; -use backend_service::configuration::ClientServerConfiguration; use flowy_core::prelude::CoreContext; -use flowy_document::module::FlowyDocument; + use flowy_net::services::ws::WsManager; use flowy_user::services::user::UserSession; use lib_dispatch::prelude::Module; diff --git a/frontend/rust-lib/flowy-test/src/event_builder.rs b/frontend/rust-lib/flowy-test/src/event_builder.rs index 0cacef01af..ca17453417 100644 --- a/frontend/rust-lib/flowy-test/src/event_builder.rs +++ b/frontend/rust-lib/flowy-test/src/event_builder.rs @@ -1,28 +1,22 @@ -use flowy_user::entities::UserProfile; -use lib_dispatch::prelude::{EventDispatcher, EventResponse, FromBytes, ModuleRequest, StatusCode, ToBytes}; +use crate::FlowySDKTest; +use flowy_user::{entities::UserProfile, errors::FlowyError}; +use lib_dispatch::prelude::{EventDispatcher, EventResponse, FromBytes, ModuleRequest, StatusCode, ToBytes, *}; use std::{ + convert::TryFrom, fmt::{Debug, Display}, hash::Hash, + marker::PhantomData, + sync::Arc, }; -use crate::FlowySDKTest; -use flowy_core::errors::WorkspaceError; - -use flowy_user::errors::UserError; -use lib_dispatch::prelude::*; -use std::{convert::TryFrom, marker::PhantomData, sync::Arc}; - -pub type CoreModuleEventBuilder = EventBuilder; +pub type CoreModuleEventBuilder = EventBuilder; impl CoreModuleEventBuilder { pub fn new(sdk: FlowySDKTest) -> Self { EventBuilder::test(TestContext::new(sdk)) } -} - -pub type UserModuleEventBuilder = EventBuilder; -impl UserModuleEventBuilder { - pub fn new(sdk: FlowySDKTest) -> Self { EventBuilder::test(TestContext::new(sdk)) } pub fn user_profile(&self) -> &Option { &self.user_profile } } +pub type UserModuleEventBuilder = CoreModuleEventBuilder; + #[derive(Clone)] pub struct EventBuilder { context: TestContext, diff --git a/frontend/rust-lib/flowy-test/src/helper.rs b/frontend/rust-lib/flowy-test/src/helper.rs index a533e8473f..c276462630 100644 --- a/frontend/rust-lib/flowy-test/src/helper.rs +++ b/frontend/rust-lib/flowy-test/src/helper.rs @@ -13,7 +13,7 @@ use flowy_core::{ }; use flowy_user::{ entities::{SignInRequest, SignUpRequest, UserProfile}, - errors::UserError, + errors::FlowyError, event::UserEvent::{InitUser, SignIn, SignOut, SignUp}, }; use lib_dispatch::prelude::{EventDispatcher, ModuleRequest, ToBytes}; @@ -316,7 +316,7 @@ pub fn sign_up(dispatch: Arc) -> SignUpContext { let request = ModuleRequest::new(SignUp).payload(payload); let user_profile = EventDispatcher::sync_send(dispatch, request) - .parse::() + .parse::() .unwrap() .unwrap(); @@ -336,7 +336,7 @@ pub async fn async_sign_up(dispatch: Arc) -> SignUpContext { let request = ModuleRequest::new(SignUp).payload(payload); let user_profile = EventDispatcher::async_send(dispatch.clone(), request) .await - .parse::() + .parse::() .unwrap() .unwrap(); @@ -361,7 +361,7 @@ fn sign_in(dispatch: Arc) -> UserProfile { let request = ModuleRequest::new(SignIn).payload(payload); EventDispatcher::sync_send(dispatch, request) - .parse::() + .parse::() .unwrap() .unwrap() } diff --git a/frontend/rust-lib/flowy-user/Cargo.toml b/frontend/rust-lib/flowy-user/Cargo.toml index d688229ed7..c6532cfbb0 100644 --- a/frontend/rust-lib/flowy-user/Cargo.toml +++ b/frontend/rust-lib/flowy-user/Cargo.toml @@ -19,6 +19,7 @@ flowy-database = { path = "../flowy-database" } flowy-net = { path = "../flowy-net" } dart-notify = { path = "../dart-notify" } lib-dispatch = { path = "../lib-dispatch" } +flowy-error = { path = "../flowy-error", features = ["db", "backend"] } tracing = { version = "0.1", features = ["log"] } diff --git a/frontend/rust-lib/flowy-user/src/errors.rs b/frontend/rust-lib/flowy-user/src/errors.rs deleted file mode 100644 index 814c40d2d8..0000000000 --- a/frontend/rust-lib/flowy-user/src/errors.rs +++ /dev/null @@ -1,117 +0,0 @@ -use bytes::Bytes; -use flowy_derive::ProtoBuf; -pub use flowy_user_infra::errors::ErrorCode; -use lib_dispatch::prelude::{EventResponse, ResponseBuilder}; -use std::{convert::TryInto, fmt, fmt::Debug}; - -#[derive(Debug, Default, Clone, ProtoBuf)] -pub struct UserError { - #[pb(index = 1)] - pub code: i32, - - #[pb(index = 2)] - pub msg: String, -} - -impl std::fmt::Display for UserError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", &self.code, &self.msg) } -} - -macro_rules! static_user_error { - ($name:ident, $code:expr) => { - #[allow(non_snake_case, missing_docs)] - pub fn $name() -> UserError { $code.into() } - }; -} - -impl UserError { - pub(crate) fn new(code: ErrorCode, msg: &str) -> Self { - Self { - code: code.value(), - msg: msg.to_owned(), - } - } - - pub fn context(mut self, error: T) -> Self { - self.msg = format!("{:?}", error); - self - } - - static_user_error!(email_empty, ErrorCode::EmailIsEmpty); - static_user_error!(email_format, ErrorCode::EmailFormatInvalid); - static_user_error!(email_exist, ErrorCode::EmailAlreadyExists); - static_user_error!(password_empty, ErrorCode::PasswordIsEmpty); - static_user_error!(passworkd_too_long, ErrorCode::PasswordTooLong); - static_user_error!(password_forbid_char, ErrorCode::PasswordContainsForbidCharacters); - static_user_error!(password_format, ErrorCode::PasswordFormatInvalid); - static_user_error!(password_not_match, ErrorCode::PasswordNotMatch); - static_user_error!(name_too_long, ErrorCode::UserNameTooLong); - static_user_error!(name_forbid_char, ErrorCode::UserNameContainForbiddenCharacters); - static_user_error!(name_empty, ErrorCode::UserNameIsEmpty); - static_user_error!(user_id, ErrorCode::UserIdInvalid); - static_user_error!(unauthorized, ErrorCode::UserUnauthorized); - static_user_error!(user_not_exist, ErrorCode::UserNotExist); - static_user_error!(internal, ErrorCode::InternalError); -} - -impl std::convert::From for UserError { - fn from(code: ErrorCode) -> Self { - UserError { - code: code.value(), - msg: format!("{}", code), - } - } -} - -impl std::convert::From for UserError { - fn from(error: flowy_database::Error) -> Self { - match error { - flowy_database::Error::NotFound => UserError::user_not_exist().context(error), - _ => UserError::internal().context(error), - } - } -} - -impl std::convert::From<::r2d2::Error> for UserError { - fn from(error: r2d2::Error) -> Self { UserError::internal().context(error) } -} - -// use diesel::result::{Error, DatabaseErrorKind}; -// use lib_sqlite::ErrorKind; -impl std::convert::From for UserError { - fn from(error: lib_sqlite::Error) -> Self { UserError::internal().context(error) } -} - -impl std::convert::From for UserError { - fn from(error: backend_service::errors::ServerError) -> Self { - let (code, msg) = server_error_to_user_error(error); - UserError::new(code, &msg) - } -} - -use backend_service::errors::ErrorCode as ServerErrorCode; -fn server_error_to_user_error(error: backend_service::errors::ServerError) -> (ErrorCode, String) { - let code = match error.code { - ServerErrorCode::UserUnauthorized => ErrorCode::UserUnauthorized, - ServerErrorCode::PasswordNotMatch => ErrorCode::PasswordNotMatch, - ServerErrorCode::RecordNotFound => ErrorCode::UserNotExist, - ServerErrorCode::ConnectRefused | ServerErrorCode::ConnectTimeout | ServerErrorCode::ConnectClose => { - ErrorCode::ServerError - }, - _ => ErrorCode::InternalError, - }; - - if code != ErrorCode::InternalError { - let msg = format!("{}", &code); - (code, msg) - } else { - (code, error.msg) - } -} - -impl lib_dispatch::Error for UserError { - fn as_response(&self) -> EventResponse { - let bytes: Bytes = self.clone().try_into().unwrap(); - ResponseBuilder::Err().data(bytes).build() - } -} diff --git a/frontend/rust-lib/flowy-user/src/event.rs b/frontend/rust-lib/flowy-user/src/event.rs index efd8f42112..0a2357fb26 100644 --- a/frontend/rust-lib/flowy-user/src/event.rs +++ b/frontend/rust-lib/flowy-user/src/event.rs @@ -2,7 +2,7 @@ use flowy_derive::{Flowy_Event, ProtoBuf_Enum}; use strum_macros::Display; #[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Hash, ProtoBuf_Enum, Flowy_Event)] -#[event_err = "UserError"] +#[event_err = "FlowyError"] pub enum UserEvent { #[event()] InitUser = 0, diff --git a/frontend/rust-lib/flowy-user/src/handlers/auth_handler.rs b/frontend/rust-lib/flowy-user/src/handlers/auth_handler.rs index 1fdcb67f96..fa99f19b06 100644 --- a/frontend/rust-lib/flowy-user/src/handlers/auth_handler.rs +++ b/frontend/rust-lib/flowy-user/src/handlers/auth_handler.rs @@ -1,10 +1,13 @@ -use crate::{entities::*, errors::UserError, services::user::UserSession}; +use crate::{entities::*, errors::FlowyError, services::user::UserSession}; use lib_dispatch::prelude::*; use std::{convert::TryInto, sync::Arc}; // tracing instrument 👉🏻 https://docs.rs/tracing/0.1.26/tracing/attr.instrument.html #[tracing::instrument(name = "sign_in", skip(data, session), fields(email = %data.email), err)] -pub async fn sign_in(data: Data, session: Unit>) -> DataResult { +pub async fn sign_in( + data: Data, + session: Unit>, +) -> DataResult { let params: SignInParams = data.into_inner().try_into()?; let user_profile = session.sign_in(params).await?; data_result(user_profile) @@ -19,7 +22,10 @@ pub async fn sign_in(data: Data, session: Unit>) ), err )] -pub async fn sign_up(data: Data, session: Unit>) -> DataResult { +pub async fn sign_up( + data: Data, + session: Unit>, +) -> DataResult { let params: SignUpParams = data.into_inner().try_into()?; let user_profile = session.sign_up(params).await?; diff --git a/frontend/rust-lib/flowy-user/src/handlers/user_handler.rs b/frontend/rust-lib/flowy-user/src/handlers/user_handler.rs index 4e3a18e11c..e282632c36 100644 --- a/frontend/rust-lib/flowy-user/src/handlers/user_handler.rs +++ b/frontend/rust-lib/flowy-user/src/handlers/user_handler.rs @@ -1,28 +1,28 @@ -use crate::{entities::*, errors::UserError, services::user::UserSession}; -use flowy_net::entities::NetworkState; +use crate::{entities::*, errors::FlowyError, services::user::UserSession}; + use lib_dispatch::prelude::*; use std::{convert::TryInto, sync::Arc}; #[tracing::instrument(skip(session))] -pub async fn init_user_handler(session: Unit>) -> Result<(), UserError> { +pub async fn init_user_handler(session: Unit>) -> Result<(), FlowyError> { let _ = session.init_user().await?; Ok(()) } #[tracing::instrument(skip(session))] -pub async fn check_user_handler(session: Unit>) -> DataResult { +pub async fn check_user_handler(session: Unit>) -> DataResult { let user_profile = session.check_user().await?; data_result(user_profile) } #[tracing::instrument(skip(session))] -pub async fn get_user_profile_handler(session: Unit>) -> DataResult { +pub async fn get_user_profile_handler(session: Unit>) -> DataResult { let user_profile = session.user_profile().await?; data_result(user_profile) } #[tracing::instrument(name = "sign_out", skip(session))] -pub async fn sign_out(session: Unit>) -> Result<(), UserError> { +pub async fn sign_out(session: Unit>) -> Result<(), FlowyError> { let _ = session.sign_out().await?; Ok(()) } @@ -31,7 +31,7 @@ pub async fn sign_out(session: Unit>) -> Result<(), UserError> pub async fn update_user_handler( data: Data, session: Unit>, -) -> Result<(), UserError> { +) -> Result<(), FlowyError> { let params: UpdateUserParams = data.into_inner().try_into()?; session.update_user(params).await?; Ok(()) diff --git a/frontend/rust-lib/flowy-user/src/lib.rs b/frontend/rust-lib/flowy-user/src/lib.rs index 33a922fa34..5484162948 100644 --- a/frontend/rust-lib/flowy-user/src/lib.rs +++ b/frontend/rust-lib/flowy-user/src/lib.rs @@ -1,14 +1,11 @@ -mod handlers; -mod sql_tables; - -pub mod errors; - pub mod entities; pub mod event; +mod handlers; pub mod module; pub mod notify; pub mod protobuf; pub mod services; +mod sql_tables; #[macro_use] extern crate flowy_database; @@ -16,3 +13,7 @@ extern crate flowy_database; pub mod prelude { pub use crate::{entities::*, services::server::*}; } + +pub mod errors { + pub use flowy_error::{internal_error, ErrorCode, FlowyError}; +} diff --git a/frontend/rust-lib/flowy-user/src/protobuf/model/errors.rs b/frontend/rust-lib/flowy-user/src/protobuf/model/errors.rs deleted file mode 100644 index 2e50c10899..0000000000 --- a/frontend/rust-lib/flowy-user/src/protobuf/model/errors.rs +++ /dev/null @@ -1,243 +0,0 @@ -// This file is generated by rust-protobuf 2.22.1. Do not edit -// @generated - -// https://github.com/rust-lang/rust-clippy/issues/702 -#![allow(unknown_lints)] -#![allow(clippy::all)] - -#![allow(unused_attributes)] -#![cfg_attr(rustfmt, rustfmt::skip)] - -#![allow(box_pointers)] -#![allow(dead_code)] -#![allow(missing_docs)] -#![allow(non_camel_case_types)] -#![allow(non_snake_case)] -#![allow(non_upper_case_globals)] -#![allow(trivial_casts)] -#![allow(unused_imports)] -#![allow(unused_results)] -//! Generated file from `errors.proto` - -/// Generated files are compatible only with the same version -/// of protobuf runtime. -// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_22_1; - -#[derive(PartialEq,Clone,Default)] -pub struct UserError { - // message fields - pub code: i32, - pub msg: ::std::string::String, - // special fields - pub unknown_fields: ::protobuf::UnknownFields, - pub cached_size: ::protobuf::CachedSize, -} - -impl<'a> ::std::default::Default for &'a UserError { - fn default() -> &'a UserError { - ::default_instance() - } -} - -impl UserError { - pub fn new() -> UserError { - ::std::default::Default::default() - } - - // int32 code = 1; - - - pub fn get_code(&self) -> i32 { - self.code - } - pub fn clear_code(&mut self) { - self.code = 0; - } - - // Param is passed by value, moved - pub fn set_code(&mut self, v: i32) { - self.code = v; - } - - // string msg = 2; - - - pub fn get_msg(&self) -> &str { - &self.msg - } - pub fn clear_msg(&mut self) { - self.msg.clear(); - } - - // Param is passed by value, moved - pub fn set_msg(&mut self, v: ::std::string::String) { - self.msg = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_msg(&mut self) -> &mut ::std::string::String { - &mut self.msg - } - - // Take field - pub fn take_msg(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.msg, ::std::string::String::new()) - } -} - -impl ::protobuf::Message for UserError { - fn is_initialized(&self) -> bool { - true - } - - fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != ::protobuf::wire_format::WireTypeVarint { - return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.code = tmp; - }, - 2 => { - ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.msg)?; - }, - _ => { - ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if self.code != 0 { - my_size += ::protobuf::rt::value_size(1, self.code, ::protobuf::wire_format::WireTypeVarint); - } - if !self.msg.is_empty() { - my_size += ::protobuf::rt::string_size(2, &self.msg); - } - my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { - if self.code != 0 { - os.write_int32(1, self.code)?; - } - if !self.msg.is_empty() { - os.write_string(2, &self.msg)?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { - self - } - - fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> UserError { - UserError::new() - } - - fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { - static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( - "code", - |m: &UserError| { &m.code }, - |m: &mut UserError| { &mut m.code }, - )); - fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( - "msg", - |m: &UserError| { &m.msg }, - |m: &mut UserError| { &mut m.msg }, - )); - ::protobuf::reflect::MessageDescriptor::new_pb_name::( - "UserError", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static UserError { - static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; - instance.get(UserError::new) - } -} - -impl ::protobuf::Clear for UserError { - fn clear(&mut self) { - self.code = 0; - self.msg.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for UserError { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::protobuf::text_format::fmt(self, f) - } -} - -impl ::protobuf::reflect::ProtobufValue for UserError { - fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { - ::protobuf::reflect::ReflectValueRef::Message(self) - } -} - -static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x0cerrors.proto\"1\n\tUserError\x12\x12\n\x04code\x18\x01\x20\x01(\ - \x05R\x04code\x12\x10\n\x03msg\x18\x02\x20\x01(\tR\x03msgJ\x98\x01\n\x06\ - \x12\x04\0\0\x05\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\ - \x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x11\n\x0b\n\x04\ - \x04\0\x02\0\x12\x03\x03\x04\x13\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\ - \x04\t\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\n\x0e\n\x0c\n\x05\x04\0\ - \x02\0\x03\x12\x03\x03\x11\x12\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\ - \x13\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\ - \x02\x01\x01\x12\x03\x04\x0b\x0e\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\ - \x04\x11\x12b\x06proto3\ -"; - -static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { - ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() -} - -pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() - }) -} diff --git a/frontend/rust-lib/flowy-user/src/protobuf/model/mod.rs b/frontend/rust-lib/flowy-user/src/protobuf/model/mod.rs index cd35f2090b..b9a7e246fd 100644 --- a/frontend/rust-lib/flowy-user/src/protobuf/model/mod.rs +++ b/frontend/rust-lib/flowy-user/src/protobuf/model/mod.rs @@ -4,8 +4,5 @@ mod observable; pub use observable::*; -mod errors; -pub use errors::*; - mod event; pub use event::*; diff --git a/frontend/rust-lib/flowy-user/src/protobuf/proto/errors.proto b/frontend/rust-lib/flowy-user/src/protobuf/proto/errors.proto deleted file mode 100644 index b2dec22eb0..0000000000 --- a/frontend/rust-lib/flowy-user/src/protobuf/proto/errors.proto +++ /dev/null @@ -1,6 +0,0 @@ -syntax = "proto3"; - -message UserError { - int32 code = 1; - string msg = 2; -} diff --git a/frontend/rust-lib/flowy-user/src/services/server/mod.rs b/frontend/rust-lib/flowy-user/src/services/server/mod.rs index f6c4ea33f0..6178abd3dd 100644 --- a/frontend/rust-lib/flowy-user/src/services/server/mod.rs +++ b/frontend/rust-lib/flowy-user/src/services/server/mod.rs @@ -8,17 +8,17 @@ use std::sync::Arc; pub(crate) type Server = Arc; use crate::{ entities::{SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile}, - errors::UserError, + errors::FlowyError, }; use backend_service::configuration::ClientServerConfiguration; use lib_infra::future::FutureResult; pub trait UserServerAPI { - fn sign_up(&self, params: SignUpParams) -> FutureResult; - fn sign_in(&self, params: SignInParams) -> FutureResult; - fn sign_out(&self, token: &str) -> FutureResult<(), UserError>; - fn update_user(&self, token: &str, params: UpdateUserParams) -> FutureResult<(), UserError>; - fn get_user(&self, token: &str) -> FutureResult; + fn sign_up(&self, params: SignUpParams) -> FutureResult; + fn sign_in(&self, params: SignInParams) -> FutureResult; + fn sign_out(&self, token: &str) -> FutureResult<(), FlowyError>; + fn update_user(&self, token: &str, params: UpdateUserParams) -> FutureResult<(), FlowyError>; + fn get_user(&self, token: &str) -> FutureResult; fn ws_addr(&self) -> String; } diff --git a/frontend/rust-lib/flowy-user/src/services/server/server_api.rs b/frontend/rust-lib/flowy-user/src/services/server/server_api.rs index 72d54a7319..58e16e7765 100644 --- a/frontend/rust-lib/flowy-user/src/services/server/server_api.rs +++ b/frontend/rust-lib/flowy-user/src/services/server/server_api.rs @@ -1,6 +1,6 @@ use crate::{ entities::{SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile}, - errors::UserError, + errors::FlowyError, services::server::UserServerAPI, }; use backend_service::{configuration::*, user_request::*}; @@ -14,7 +14,7 @@ impl UserHttpServer { } impl UserServerAPI for UserHttpServer { - fn sign_up(&self, params: SignUpParams) -> FutureResult { + fn sign_up(&self, params: SignUpParams) -> FutureResult { let url = self.config.sign_up_url(); FutureResult::new(async move { let resp = user_sign_up_request(params, &url).await?; @@ -22,7 +22,7 @@ impl UserServerAPI for UserHttpServer { }) } - fn sign_in(&self, params: SignInParams) -> FutureResult { + fn sign_in(&self, params: SignInParams) -> FutureResult { let url = self.config.sign_in_url(); FutureResult::new(async move { let resp = user_sign_in_request(params, &url).await?; @@ -30,7 +30,7 @@ impl UserServerAPI for UserHttpServer { }) } - fn sign_out(&self, token: &str) -> FutureResult<(), UserError> { + fn sign_out(&self, token: &str) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.sign_out_url(); FutureResult::new(async move { @@ -39,7 +39,7 @@ impl UserServerAPI for UserHttpServer { }) } - fn update_user(&self, token: &str, params: UpdateUserParams) -> FutureResult<(), UserError> { + fn update_user(&self, token: &str, params: UpdateUserParams) -> FutureResult<(), FlowyError> { let token = token.to_owned(); let url = self.config.user_profile_url(); FutureResult::new(async move { @@ -48,7 +48,7 @@ impl UserServerAPI for UserHttpServer { }) } - fn get_user(&self, token: &str) -> FutureResult { + fn get_user(&self, token: &str) -> FutureResult { let token = token.to_owned(); let url = self.config.user_profile_url(); FutureResult::new(async move { @@ -77,7 +77,7 @@ impl UserServerAPI for UserHttpServer { // None => {}, // Some(token) => { // let error = -// UserError::new(ErrorCode::UserUnauthorized, ""); +// FlowyError::new(ErrorCode::UserUnauthorized, ""); // dart_notify(token, UserNotification::UserUnauthorized) // .error(error) .send() // }, diff --git a/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs b/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs index 435020e856..ae8c68da47 100644 --- a/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs +++ b/frontend/rust-lib/flowy-user/src/services/server/server_api_mock.rs @@ -1,6 +1,6 @@ use crate::{ entities::{SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile}, - errors::UserError, + errors::FlowyError, }; use crate::services::server::UserServerAPI; @@ -11,7 +11,7 @@ pub struct UserServerMock {} impl UserServerMock {} impl UserServerAPI for UserServerMock { - fn sign_up(&self, params: SignUpParams) -> FutureResult { + fn sign_up(&self, params: SignUpParams) -> FutureResult { let uid = uuid(); FutureResult::new(async move { Ok(SignUpResponse { @@ -23,7 +23,7 @@ impl UserServerAPI for UserServerMock { }) } - fn sign_in(&self, params: SignInParams) -> FutureResult { + fn sign_in(&self, params: SignInParams) -> FutureResult { let user_id = uuid(); FutureResult::new(async { Ok(SignInResponse { @@ -35,13 +35,13 @@ impl UserServerAPI for UserServerMock { }) } - fn sign_out(&self, _token: &str) -> FutureResult<(), UserError> { FutureResult::new(async { Ok(()) }) } + fn sign_out(&self, _token: &str) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn update_user(&self, _token: &str, _params: UpdateUserParams) -> FutureResult<(), UserError> { + fn update_user(&self, _token: &str, _params: UpdateUserParams) -> FutureResult<(), FlowyError> { FutureResult::new(async { Ok(()) }) } - fn get_user(&self, _token: &str) -> FutureResult { + fn get_user(&self, _token: &str) -> FutureResult { FutureResult::new(async { Ok(UserProfile::default()) }) } diff --git a/frontend/rust-lib/flowy-user/src/services/user/database.rs b/frontend/rust-lib/flowy-user/src/services/user/database.rs index a3a450c792..aa4c603349 100644 --- a/frontend/rust-lib/flowy-user/src/services/user/database.rs +++ b/frontend/rust-lib/flowy-user/src/services/user/database.rs @@ -1,4 +1,4 @@ -use crate::errors::UserError; +use crate::errors::FlowyError; use flowy_database::{DBConnection, Database}; use lazy_static::lazy_static; use lib_sqlite::ConnectionPool; @@ -20,20 +20,20 @@ impl UserDB { } } - fn open_user_db(&self, user_id: &str) -> Result<(), UserError> { + fn open_user_db(&self, user_id: &str) -> Result<(), FlowyError> { if user_id.is_empty() { - return Err(UserError::internal().context("user id is empty")); + return Err(FlowyError::internal().context("user id is empty")); } tracing::info!("open user db {}", user_id); let dir = format!("{}/{}", self.db_dir, user_id); let db = flowy_database::init(&dir).map_err(|e| { log::error!("init user db failed, {:?}, user_id: {}", e, user_id); - UserError::internal().context(e) + FlowyError::internal().context(e) })?; match DB_MAP.try_write_for(Duration::from_millis(300)) { - None => Err(UserError::internal().context("Acquire write lock to save user db failed")), + None => Err(FlowyError::internal().context("Acquire write lock to save user db failed")), Some(mut write_guard) => { write_guard.insert(user_id.to_owned(), db); Ok(()) @@ -41,9 +41,9 @@ impl UserDB { } } - pub(crate) fn close_user_db(&self, user_id: &str) -> Result<(), UserError> { + pub(crate) fn close_user_db(&self, user_id: &str) -> Result<(), FlowyError> { match DB_MAP.try_write_for(Duration::from_millis(300)) { - None => Err(UserError::internal().context("Acquire write lock to close user db failed")), + None => Err(FlowyError::internal().context("Acquire write lock to close user db failed")), Some(mut write_guard) => { set_user_db_init(false, user_id); write_guard.remove(user_id); @@ -52,12 +52,12 @@ impl UserDB { } } - pub(crate) fn get_connection(&self, user_id: &str) -> Result { + pub(crate) fn get_connection(&self, user_id: &str) -> Result { let conn = self.get_pool(user_id)?.get()?; Ok(conn) } - pub(crate) fn get_pool(&self, user_id: &str) -> Result, UserError> { + pub(crate) fn get_pool(&self, user_id: &str) -> Result, FlowyError> { // Opti: INIT_LOCK try to lock the INIT_RECORD accesses. Because the write guard // can not nested in the read guard that will cause the deadlock. match INIT_LOCK.try_lock_for(Duration::from_millis(300)) { @@ -71,9 +71,11 @@ impl UserDB { } match DB_MAP.try_read_for(Duration::from_millis(300)) { - None => Err(UserError::internal().context("Acquire read lock to read user db failed")), + None => Err(FlowyError::internal().context("Acquire read lock to read user db failed")), Some(read_guard) => match read_guard.get(user_id) { - None => Err(UserError::internal().context("Get connection failed. The database is not initialization")), + None => { + Err(FlowyError::internal().context("Get connection failed. The database is not initialization")) + }, Some(database) => Ok(database.get_pool()), }, } diff --git a/frontend/rust-lib/flowy-user/src/services/user/notifier.rs b/frontend/rust-lib/flowy-user/src/services/user/notifier.rs index a8d86a0319..eadb2fcc5b 100644 --- a/frontend/rust-lib/flowy-user/src/services/user/notifier.rs +++ b/frontend/rust-lib/flowy-user/src/services/user/notifier.rs @@ -1,5 +1,5 @@ use crate::entities::{UserProfile, UserStatus}; -use flowy_net::entities::NetworkType; + use tokio::sync::{broadcast, mpsc}; pub struct UserNotifier { diff --git a/frontend/rust-lib/flowy-user/src/services/user/user_session.rs b/frontend/rust-lib/flowy-user/src/services/user/user_session.rs index d4774fa6b9..5cb571ac52 100644 --- a/frontend/rust-lib/flowy-user/src/services/user/user_session.rs +++ b/frontend/rust-lib/flowy-user/src/services/user/user_session.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use parking_lot::RwLock; use serde::{Deserialize, Serialize}; -use tokio::sync::{broadcast, mpsc}; +use tokio::sync::mpsc; use backend_service::configuration::ClientServerConfiguration; use flowy_database::{ @@ -18,7 +18,7 @@ use lib_sqlite::ConnectionPool; use crate::{ entities::{SignInParams, SignUpParams, UpdateUserParams, UserProfile}, - errors::{ErrorCode, UserError}, + errors::{ErrorCode, FlowyError}, notify::*, services::{ server::{construct_user_server, Server}, @@ -26,7 +26,6 @@ use crate::{ }, sql_tables::{UserTable, UserTableChangeset}, }; -use flowy_net::entities::NetworkState; pub struct UserSessionConfig { root_dir: String, @@ -73,7 +72,7 @@ impl UserSession { } } - pub fn db_connection(&self) -> Result { + pub fn db_connection(&self) -> Result { let user_id = self.get_session()?.user_id; self.database.get_connection(&user_id) } @@ -84,13 +83,13 @@ impl UserSession { // // let pool = self.db_connection_pool()?; // let conn: PooledConnection = pool.get()?; - pub fn db_pool(&self) -> Result, UserError> { + pub fn db_pool(&self) -> Result, FlowyError> { let user_id = self.get_session()?.user_id; self.database.get_pool(&user_id) } #[tracing::instrument(level = "debug", skip(self))] - pub async fn sign_in(&self, params: SignInParams) -> Result { + pub async fn sign_in(&self, params: SignInParams) -> Result { if self.is_login(¶ms.email) { self.user_profile().await } else { @@ -105,7 +104,7 @@ impl UserSession { } #[tracing::instrument(level = "debug", skip(self))] - pub async fn sign_up(&self, params: SignUpParams) -> Result { + pub async fn sign_up(&self, params: SignUpParams) -> Result { if self.is_login(¶ms.email) { self.user_profile().await } else { @@ -123,7 +122,7 @@ impl UserSession { } #[tracing::instrument(level = "debug", skip(self))] - pub async fn sign_out(&self) -> Result<(), UserError> { + pub async fn sign_out(&self) -> Result<(), FlowyError> { let session = self.get_session()?; let _ = diesel::delete(dsl::user_table.filter(dsl::id.eq(&session.user_id))).execute(&*(self.db_connection()?))?; @@ -136,7 +135,7 @@ impl UserSession { } #[tracing::instrument(level = "debug", skip(self))] - pub async fn update_user(&self, params: UpdateUserParams) -> Result<(), UserError> { + pub async fn update_user(&self, params: UpdateUserParams) -> Result<(), FlowyError> { let session = self.get_session()?; let changeset = UserTableChangeset::new(params.clone()); diesel_update_table!(user_table, changeset, &*self.db_connection()?); @@ -145,9 +144,9 @@ impl UserSession { Ok(()) } - pub async fn init_user(&self) -> Result<(), UserError> { Ok(()) } + pub async fn init_user(&self) -> Result<(), FlowyError> { Ok(()) } - pub async fn check_user(&self) -> Result { + pub async fn check_user(&self) -> Result { let (user_id, token) = self.get_session()?.into_part(); let user = dsl::user_table @@ -158,7 +157,7 @@ impl UserSession { Ok(user.into()) } - pub async fn user_profile(&self) -> Result { + pub async fn user_profile(&self) -> Result { let (user_id, token) = self.get_session()?.into_part(); let user = dsl::user_table .filter(user_table::id.eq(&user_id)) @@ -168,20 +167,20 @@ impl UserSession { Ok(user.into()) } - pub fn user_dir(&self) -> Result { + pub fn user_dir(&self) -> Result { let session = self.get_session()?; Ok(format!("{}/{}", self.config.root_dir, session.user_id)) } - pub fn user_id(&self) -> Result { Ok(self.get_session()?.user_id) } + pub fn user_id(&self) -> Result { Ok(self.get_session()?.user_id) } - pub fn user_name(&self) -> Result { Ok(self.get_session()?.name) } + pub fn user_name(&self) -> Result { Ok(self.get_session()?.name) } - pub fn token(&self) -> Result { Ok(self.get_session()?.token) } + pub fn token(&self) -> Result { Ok(self.get_session()?.token) } } impl UserSession { - fn read_user_profile_on_server(&self, token: &str) -> Result<(), UserError> { + fn read_user_profile_on_server(&self, token: &str) -> Result<(), FlowyError> { let server = self.server.clone(); let token = token.to_owned(); tokio::spawn(async move { @@ -201,7 +200,7 @@ impl UserSession { Ok(()) } - async fn update_user_on_server(&self, token: &str, params: UpdateUserParams) -> Result<(), UserError> { + async fn update_user_on_server(&self, token: &str, params: UpdateUserParams) -> Result<(), FlowyError> { let server = self.server.clone(); let token = token.to_owned(); let _ = tokio::spawn(async move { @@ -217,7 +216,7 @@ impl UserSession { Ok(()) } - async fn sign_out_on_server(&self, token: &str) -> Result<(), UserError> { + async fn sign_out_on_server(&self, token: &str) -> Result<(), FlowyError> { let server = self.server.clone(); let token = token.to_owned(); let _ = tokio::spawn(async move { @@ -230,7 +229,7 @@ impl UserSession { Ok(()) } - async fn save_user(&self, user: UserTable) -> Result { + async fn save_user(&self, user: UserTable) -> Result { let conn = self.db_connection()?; let _ = diesel::insert_into(user_table::table) .values(user.clone()) @@ -238,19 +237,17 @@ impl UserSession { Ok(user) } - fn set_session(&self, session: Option) -> Result<(), UserError> { + fn set_session(&self, session: Option) -> Result<(), FlowyError> { tracing::debug!("Set user session: {:?}", session); match &session { - None => { - KV::remove(&self.config.session_cache_key).map_err(|e| UserError::new(ErrorCode::InternalError, &e))? - }, + None => KV::remove(&self.config.session_cache_key).map_err(|e| FlowyError::new(ErrorCode::Internal, &e))?, Some(session) => KV::set_str(&self.config.session_cache_key, session.clone().into()), } *self.session.write() = session; Ok(()) } - fn get_session(&self) -> Result { + fn get_session(&self) -> Result { let mut session = { (*self.session.read()).clone() }; if session.is_none() { match KV::get_str(&self.config.session_cache_key) { @@ -263,7 +260,7 @@ impl UserSession { } match session { - None => Err(UserError::unauthorized()), + None => Err(FlowyError::unauthorized()), Some(session) => Ok(session), } } @@ -280,7 +277,7 @@ pub async fn update_user( _server: Server, pool: Arc, params: UpdateUserParams, -) -> Result<(), UserError> { +) -> Result<(), FlowyError> { let changeset = UserTableChangeset::new(params); let conn = pool.get()?; diesel_update_table!(user_table, changeset, &*conn); diff --git a/shared-lib/Cargo.lock b/shared-lib/Cargo.lock index 9c0c172f00..b840c8332f 100644 --- a/shared-lib/Cargo.lock +++ b/shared-lib/Cargo.lock @@ -633,6 +633,15 @@ dependencies = [ "backtrace", ] +[[package]] +name = "error-code" +version = "0.1.0" +dependencies = [ + "derive_more", + "flowy-derive", + "protobuf", +] + [[package]] name = "fake" version = "2.3.0" @@ -710,6 +719,7 @@ dependencies = [ "bytes", "chrono", "derive_more", + "error-code", "flowy-collaboration", "flowy-derive", "log", @@ -740,6 +750,7 @@ dependencies = [ "bytes", "claim", "derive_more", + "error-code", "fake", "fancy-regex", "flowy-derive", diff --git a/shared-lib/Cargo.toml b/shared-lib/Cargo.toml index d48aa6532e..c923acbfb2 100644 --- a/shared-lib/Cargo.toml +++ b/shared-lib/Cargo.toml @@ -10,6 +10,7 @@ members = [ "backend-service", "flowy-derive", "flowy-ast", + "error-code", ] [profile.dev] diff --git a/shared-lib/error-code/Cargo.toml b/shared-lib/error-code/Cargo.toml new file mode 100644 index 0000000000..5688c869ee --- /dev/null +++ b/shared-lib/error-code/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "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"]} \ No newline at end of file diff --git a/shared-lib/error-code/Flowy.toml b/shared-lib/error-code/Flowy.toml new file mode 100644 index 0000000000..1c788f7599 --- /dev/null +++ b/shared-lib/error-code/Flowy.toml @@ -0,0 +1,3 @@ + +proto_crates = ["src/error_code.rs"] +event_files = [] \ No newline at end of file diff --git a/shared-lib/error-code/src/error_code.rs b/shared-lib/error-code/src/error_code.rs new file mode 100644 index 0000000000..2868a5fa7c --- /dev/null +++ b/shared-lib/error-code/src/error_code.rs @@ -0,0 +1,100 @@ +use crate::protobuf::ErrorCode as ProtoBufErrorCode; +use derive_more::Display; +use flowy_derive::ProtoBuf_Enum; +use protobuf::ProtobufEnum; +use std::convert::{TryFrom, TryInto}; + +#[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] +pub enum ErrorCode { + #[display(fmt = "Internal error")] + Internal = 0, + + #[display(fmt = "UserUnauthorized")] + UserUnauthorized = 2, + + #[display(fmt = "RecordNotFound")] + RecordNotFound = 3, + + #[display(fmt = "Workspace name can not be empty or whitespace")] + WorkspaceNameInvalid = 100, + + #[display(fmt = "Workspace id can not be empty or whitespace")] + WorkspaceIdInvalid = 101, + + #[display(fmt = "Color style of the App is invalid")] + AppColorStyleInvalid = 102, + + #[display(fmt = "Workspace desc is invalid")] + WorkspaceDescTooLong = 103, + + #[display(fmt = "Workspace description too long")] + WorkspaceNameTooLong = 104, + + #[display(fmt = "App id can not be empty or whitespace")] + AppIdInvalid = 110, + + #[display(fmt = "App name can not be empty or whitespace")] + AppNameInvalid = 111, + + #[display(fmt = "View name can not be empty or whitespace")] + ViewNameInvalid = 120, + + #[display(fmt = "Thumbnail of the view is invalid")] + ViewThumbnailInvalid = 121, + + #[display(fmt = "View id can not be empty or whitespace")] + ViewIdInvalid = 122, + + #[display(fmt = "View desc too long")] + ViewDescTooLong = 123, + + #[display(fmt = "View data is invalid")] + ViewDataInvalid = 124, + + #[display(fmt = "View name too long")] + ViewNameTooLong = 125, + + #[display(fmt = "Connection error")] + ConnectError = 200, + + #[display(fmt = "Email can not be empty or whitespace")] + EmailIsEmpty = 300, + #[display(fmt = "Email format is not valid")] + EmailFormatInvalid = 301, + #[display(fmt = "Email already exists")] + EmailAlreadyExists = 302, + #[display(fmt = "Password can not be empty or whitespace")] + PasswordIsEmpty = 303, + #[display(fmt = "Password format too long")] + PasswordTooLong = 304, + #[display(fmt = "Password contains forbidden characters.")] + PasswordContainsForbidCharacters = 305, + #[display(fmt = "Password should contain a minimum of 6 characters with 1 special 1 letter and 1 numeric")] + PasswordFormatInvalid = 306, + #[display(fmt = "Password not match")] + PasswordNotMatch = 307, + #[display(fmt = "User name is too long")] + UserNameTooLong = 308, + #[display(fmt = "User name contain forbidden characters")] + UserNameContainForbiddenCharacters = 309, + #[display(fmt = "User name can not be empty or whitespace")] + UserNameIsEmpty = 310, + #[display(fmt = "user id is empty or whitespace")] + UserIdInvalid = 311, + #[display(fmt = "User not exist")] + UserNotExist = 312, +} + +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(), + } + } +} diff --git a/shared-lib/error-code/src/lib.rs b/shared-lib/error-code/src/lib.rs new file mode 100644 index 0000000000..90a67f9c77 --- /dev/null +++ b/shared-lib/error-code/src/lib.rs @@ -0,0 +1,4 @@ +mod error_code; +mod protobuf; + +pub use error_code::*; diff --git a/shared-lib/error-code/src/protobuf/mod.rs b/shared-lib/error-code/src/protobuf/mod.rs new file mode 100644 index 0000000000..da97aad28a --- /dev/null +++ b/shared-lib/error-code/src/protobuf/mod.rs @@ -0,0 +1,4 @@ +#![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/error-code/src/protobuf/model/error_code.rs b/shared-lib/error-code/src/protobuf/model/error_code.rs new file mode 100644 index 0000000000..0fe3afbf55 --- /dev/null +++ b/shared-lib/error-code/src/protobuf/model/error_code.rs @@ -0,0 +1,253 @@ +// This file is generated by rust-protobuf 2.22.1. Do not edit +// @generated + +// https://github.com/rust-lang/rust-clippy/issues/702 +#![allow(unknown_lints)] +#![allow(clippy::all)] + +#![allow(unused_attributes)] +#![cfg_attr(rustfmt, rustfmt::skip)] + +#![allow(box_pointers)] +#![allow(dead_code)] +#![allow(missing_docs)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +#![allow(trivial_casts)] +#![allow(unused_imports)] +#![allow(unused_results)] +//! Generated file from `error_code.proto` + +/// Generated files are compatible only with the same version +/// of protobuf runtime. +// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_22_1; + +#[derive(Clone,PartialEq,Eq,Debug,Hash)] +pub enum ErrorCode { + Internal = 0, + UserUnauthorized = 2, + RecordNotFound = 3, + 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, +} + +impl ::protobuf::ProtobufEnum for ErrorCode { + fn value(&self) -> i32 { + *self as i32 + } + + fn from_i32(value: i32) -> ::std::option::Option { + match value { + 0 => ::std::option::Option::Some(ErrorCode::Internal), + 2 => ::std::option::Option::Some(ErrorCode::UserUnauthorized), + 3 => ::std::option::Option::Some(ErrorCode::RecordNotFound), + 100 => ::std::option::Option::Some(ErrorCode::WorkspaceNameInvalid), + 101 => ::std::option::Option::Some(ErrorCode::WorkspaceIdInvalid), + 102 => ::std::option::Option::Some(ErrorCode::AppColorStyleInvalid), + 103 => ::std::option::Option::Some(ErrorCode::WorkspaceDescTooLong), + 104 => ::std::option::Option::Some(ErrorCode::WorkspaceNameTooLong), + 110 => ::std::option::Option::Some(ErrorCode::AppIdInvalid), + 111 => ::std::option::Option::Some(ErrorCode::AppNameInvalid), + 120 => ::std::option::Option::Some(ErrorCode::ViewNameInvalid), + 121 => ::std::option::Option::Some(ErrorCode::ViewThumbnailInvalid), + 122 => ::std::option::Option::Some(ErrorCode::ViewIdInvalid), + 123 => ::std::option::Option::Some(ErrorCode::ViewDescTooLong), + 124 => ::std::option::Option::Some(ErrorCode::ViewDataInvalid), + 125 => ::std::option::Option::Some(ErrorCode::ViewNameTooLong), + 200 => ::std::option::Option::Some(ErrorCode::ConnectError), + 300 => ::std::option::Option::Some(ErrorCode::EmailIsEmpty), + 301 => ::std::option::Option::Some(ErrorCode::EmailFormatInvalid), + 302 => ::std::option::Option::Some(ErrorCode::EmailAlreadyExists), + 303 => ::std::option::Option::Some(ErrorCode::PasswordIsEmpty), + 304 => ::std::option::Option::Some(ErrorCode::PasswordTooLong), + 305 => ::std::option::Option::Some(ErrorCode::PasswordContainsForbidCharacters), + 306 => ::std::option::Option::Some(ErrorCode::PasswordFormatInvalid), + 307 => ::std::option::Option::Some(ErrorCode::PasswordNotMatch), + 308 => ::std::option::Option::Some(ErrorCode::UserNameTooLong), + 309 => ::std::option::Option::Some(ErrorCode::UserNameContainForbiddenCharacters), + 310 => ::std::option::Option::Some(ErrorCode::UserNameIsEmpty), + 311 => ::std::option::Option::Some(ErrorCode::UserIdInvalid), + 312 => ::std::option::Option::Some(ErrorCode::UserNotExist), + _ => ::std::option::Option::None + } + } + + fn values() -> &'static [Self] { + static values: &'static [ErrorCode] = &[ + ErrorCode::Internal, + ErrorCode::UserUnauthorized, + ErrorCode::RecordNotFound, + ErrorCode::WorkspaceNameInvalid, + ErrorCode::WorkspaceIdInvalid, + ErrorCode::AppColorStyleInvalid, + ErrorCode::WorkspaceDescTooLong, + ErrorCode::WorkspaceNameTooLong, + ErrorCode::AppIdInvalid, + ErrorCode::AppNameInvalid, + ErrorCode::ViewNameInvalid, + ErrorCode::ViewThumbnailInvalid, + ErrorCode::ViewIdInvalid, + ErrorCode::ViewDescTooLong, + ErrorCode::ViewDataInvalid, + ErrorCode::ViewNameTooLong, + ErrorCode::ConnectError, + ErrorCode::EmailIsEmpty, + ErrorCode::EmailFormatInvalid, + ErrorCode::EmailAlreadyExists, + ErrorCode::PasswordIsEmpty, + ErrorCode::PasswordTooLong, + ErrorCode::PasswordContainsForbidCharacters, + ErrorCode::PasswordFormatInvalid, + ErrorCode::PasswordNotMatch, + ErrorCode::UserNameTooLong, + ErrorCode::UserNameContainForbiddenCharacters, + ErrorCode::UserNameIsEmpty, + ErrorCode::UserIdInvalid, + ErrorCode::UserNotExist, + ]; + values + } + + fn enum_descriptor_static() -> &'static ::protobuf::reflect::EnumDescriptor { + static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::EnumDescriptor> = ::protobuf::rt::LazyV2::INIT; + descriptor.get(|| { + ::protobuf::reflect::EnumDescriptor::new_pb_name::("ErrorCode", file_descriptor_proto()) + }) + } +} + +impl ::std::marker::Copy for ErrorCode { +} + +impl ::std::default::Default for ErrorCode { + fn default() -> Self { + ErrorCode::Internal + } +} + +impl ::protobuf::reflect::ProtobufValue for ErrorCode { + fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { + ::protobuf::reflect::ReflectValueRef::Enum(::protobuf::ProtobufEnum::descriptor(self)) + } +} + +static file_descriptor_proto_data: &'static [u8] = b"\ + \n\x10error_code.proto*\xc4\x05\n\tErrorCode\x12\x0c\n\x08Internal\x10\0\ + \x12\x14\n\x10UserUnauthorized\x10\x02\x12\x12\n\x0eRecordNotFound\x10\ + \x03\x12\x18\n\x14WorkspaceNameInvalid\x10d\x12\x16\n\x12WorkspaceIdInva\ + lid\x10e\x12\x18\n\x14AppColorStyleInvalid\x10f\x12\x18\n\x14WorkspaceDe\ + scTooLong\x10g\x12\x18\n\x14WorkspaceNameTooLong\x10h\x12\x10\n\x0cAppId\ + Invalid\x10n\x12\x12\n\x0eAppNameInvalid\x10o\x12\x13\n\x0fViewNameInval\ + id\x10x\x12\x18\n\x14ViewThumbnailInvalid\x10y\x12\x11\n\rViewIdInvalid\ + \x10z\x12\x13\n\x0fViewDescTooLong\x10{\x12\x13\n\x0fViewDataInvalid\x10\ + |\x12\x13\n\x0fViewNameTooLong\x10}\x12\x11\n\x0cConnectError\x10\xc8\ + \x01\x12\x11\n\x0cEmailIsEmpty\x10\xac\x02\x12\x17\n\x12EmailFormatInval\ + id\x10\xad\x02\x12\x17\n\x12EmailAlreadyExists\x10\xae\x02\x12\x14\n\x0f\ + PasswordIsEmpty\x10\xaf\x02\x12\x14\n\x0fPasswordTooLong\x10\xb0\x02\x12\ + %\n\x20PasswordContainsForbidCharacters\x10\xb1\x02\x12\x1a\n\x15Passwor\ + dFormatInvalid\x10\xb2\x02\x12\x15\n\x10PasswordNotMatch\x10\xb3\x02\x12\ + \x14\n\x0fUserNameTooLong\x10\xb4\x02\x12'\n\"UserNameContainForbiddenCh\ + aracters\x10\xb5\x02\x12\x14\n\x0fUserNameIsEmpty\x10\xb6\x02\x12\x12\n\ + \rUserIdInvalid\x10\xb7\x02\x12\x11\n\x0cUserNotExist\x10\xb8\x02J\xf8\t\ + \n\x06\x12\x04\0\0!\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x05\0\ + \x12\x04\x02\0!\x01\n\n\n\x03\x05\0\x01\x12\x03\x02\x05\x0e\n\x0b\n\x04\ + \x05\0\x02\0\x12\x03\x03\x04\x11\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\x03\ + \x04\x0c\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\x03\x0f\x10\n\x0b\n\x04\x05\ + \0\x02\x01\x12\x03\x04\x04\x19\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\x04\ + \x04\x14\n\x0c\n\x05\x05\0\x02\x01\x02\x12\x03\x04\x17\x18\n\x0b\n\x04\ + \x05\0\x02\x02\x12\x03\x05\x04\x17\n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\ + \x05\x04\x12\n\x0c\n\x05\x05\0\x02\x02\x02\x12\x03\x05\x15\x16\n\x0b\n\ + \x04\x05\0\x02\x03\x12\x03\x06\x04\x1f\n\x0c\n\x05\x05\0\x02\x03\x01\x12\ + \x03\x06\x04\x18\n\x0c\n\x05\x05\0\x02\x03\x02\x12\x03\x06\x1b\x1e\n\x0b\ + \n\x04\x05\0\x02\x04\x12\x03\x07\x04\x1d\n\x0c\n\x05\x05\0\x02\x04\x01\ + \x12\x03\x07\x04\x16\n\x0c\n\x05\x05\0\x02\x04\x02\x12\x03\x07\x19\x1c\n\ + \x0b\n\x04\x05\0\x02\x05\x12\x03\x08\x04\x1f\n\x0c\n\x05\x05\0\x02\x05\ + \x01\x12\x03\x08\x04\x18\n\x0c\n\x05\x05\0\x02\x05\x02\x12\x03\x08\x1b\ + \x1e\n\x0b\n\x04\x05\0\x02\x06\x12\x03\t\x04\x1f\n\x0c\n\x05\x05\0\x02\ + \x06\x01\x12\x03\t\x04\x18\n\x0c\n\x05\x05\0\x02\x06\x02\x12\x03\t\x1b\ + \x1e\n\x0b\n\x04\x05\0\x02\x07\x12\x03\n\x04\x1f\n\x0c\n\x05\x05\0\x02\ + \x07\x01\x12\x03\n\x04\x18\n\x0c\n\x05\x05\0\x02\x07\x02\x12\x03\n\x1b\ + \x1e\n\x0b\n\x04\x05\0\x02\x08\x12\x03\x0b\x04\x17\n\x0c\n\x05\x05\0\x02\ + \x08\x01\x12\x03\x0b\x04\x10\n\x0c\n\x05\x05\0\x02\x08\x02\x12\x03\x0b\ + \x13\x16\n\x0b\n\x04\x05\0\x02\t\x12\x03\x0c\x04\x19\n\x0c\n\x05\x05\0\ + \x02\t\x01\x12\x03\x0c\x04\x12\n\x0c\n\x05\x05\0\x02\t\x02\x12\x03\x0c\ + \x15\x18\n\x0b\n\x04\x05\0\x02\n\x12\x03\r\x04\x1a\n\x0c\n\x05\x05\0\x02\ + \n\x01\x12\x03\r\x04\x13\n\x0c\n\x05\x05\0\x02\n\x02\x12\x03\r\x16\x19\n\ + \x0b\n\x04\x05\0\x02\x0b\x12\x03\x0e\x04\x1f\n\x0c\n\x05\x05\0\x02\x0b\ + \x01\x12\x03\x0e\x04\x18\n\x0c\n\x05\x05\0\x02\x0b\x02\x12\x03\x0e\x1b\ + \x1e\n\x0b\n\x04\x05\0\x02\x0c\x12\x03\x0f\x04\x18\n\x0c\n\x05\x05\0\x02\ + \x0c\x01\x12\x03\x0f\x04\x11\n\x0c\n\x05\x05\0\x02\x0c\x02\x12\x03\x0f\ + \x14\x17\n\x0b\n\x04\x05\0\x02\r\x12\x03\x10\x04\x1a\n\x0c\n\x05\x05\0\ + \x02\r\x01\x12\x03\x10\x04\x13\n\x0c\n\x05\x05\0\x02\r\x02\x12\x03\x10\ + \x16\x19\n\x0b\n\x04\x05\0\x02\x0e\x12\x03\x11\x04\x1a\n\x0c\n\x05\x05\0\ + \x02\x0e\x01\x12\x03\x11\x04\x13\n\x0c\n\x05\x05\0\x02\x0e\x02\x12\x03\ + \x11\x16\x19\n\x0b\n\x04\x05\0\x02\x0f\x12\x03\x12\x04\x1a\n\x0c\n\x05\ + \x05\0\x02\x0f\x01\x12\x03\x12\x04\x13\n\x0c\n\x05\x05\0\x02\x0f\x02\x12\ + \x03\x12\x16\x19\n\x0b\n\x04\x05\0\x02\x10\x12\x03\x13\x04\x17\n\x0c\n\ + \x05\x05\0\x02\x10\x01\x12\x03\x13\x04\x10\n\x0c\n\x05\x05\0\x02\x10\x02\ + \x12\x03\x13\x13\x16\n\x0b\n\x04\x05\0\x02\x11\x12\x03\x14\x04\x17\n\x0c\ + \n\x05\x05\0\x02\x11\x01\x12\x03\x14\x04\x10\n\x0c\n\x05\x05\0\x02\x11\ + \x02\x12\x03\x14\x13\x16\n\x0b\n\x04\x05\0\x02\x12\x12\x03\x15\x04\x1d\n\ + \x0c\n\x05\x05\0\x02\x12\x01\x12\x03\x15\x04\x16\n\x0c\n\x05\x05\0\x02\ + \x12\x02\x12\x03\x15\x19\x1c\n\x0b\n\x04\x05\0\x02\x13\x12\x03\x16\x04\ + \x1d\n\x0c\n\x05\x05\0\x02\x13\x01\x12\x03\x16\x04\x16\n\x0c\n\x05\x05\0\ + \x02\x13\x02\x12\x03\x16\x19\x1c\n\x0b\n\x04\x05\0\x02\x14\x12\x03\x17\ + \x04\x1a\n\x0c\n\x05\x05\0\x02\x14\x01\x12\x03\x17\x04\x13\n\x0c\n\x05\ + \x05\0\x02\x14\x02\x12\x03\x17\x16\x19\n\x0b\n\x04\x05\0\x02\x15\x12\x03\ + \x18\x04\x1a\n\x0c\n\x05\x05\0\x02\x15\x01\x12\x03\x18\x04\x13\n\x0c\n\ + \x05\x05\0\x02\x15\x02\x12\x03\x18\x16\x19\n\x0b\n\x04\x05\0\x02\x16\x12\ + \x03\x19\x04+\n\x0c\n\x05\x05\0\x02\x16\x01\x12\x03\x19\x04$\n\x0c\n\x05\ + \x05\0\x02\x16\x02\x12\x03\x19'*\n\x0b\n\x04\x05\0\x02\x17\x12\x03\x1a\ + \x04\x20\n\x0c\n\x05\x05\0\x02\x17\x01\x12\x03\x1a\x04\x19\n\x0c\n\x05\ + \x05\0\x02\x17\x02\x12\x03\x1a\x1c\x1f\n\x0b\n\x04\x05\0\x02\x18\x12\x03\ + \x1b\x04\x1b\n\x0c\n\x05\x05\0\x02\x18\x01\x12\x03\x1b\x04\x14\n\x0c\n\ + \x05\x05\0\x02\x18\x02\x12\x03\x1b\x17\x1a\n\x0b\n\x04\x05\0\x02\x19\x12\ + \x03\x1c\x04\x1a\n\x0c\n\x05\x05\0\x02\x19\x01\x12\x03\x1c\x04\x13\n\x0c\ + \n\x05\x05\0\x02\x19\x02\x12\x03\x1c\x16\x19\n\x0b\n\x04\x05\0\x02\x1a\ + \x12\x03\x1d\x04-\n\x0c\n\x05\x05\0\x02\x1a\x01\x12\x03\x1d\x04&\n\x0c\n\ + \x05\x05\0\x02\x1a\x02\x12\x03\x1d),\n\x0b\n\x04\x05\0\x02\x1b\x12\x03\ + \x1e\x04\x1a\n\x0c\n\x05\x05\0\x02\x1b\x01\x12\x03\x1e\x04\x13\n\x0c\n\ + \x05\x05\0\x02\x1b\x02\x12\x03\x1e\x16\x19\n\x0b\n\x04\x05\0\x02\x1c\x12\ + \x03\x1f\x04\x18\n\x0c\n\x05\x05\0\x02\x1c\x01\x12\x03\x1f\x04\x11\n\x0c\ + \n\x05\x05\0\x02\x1c\x02\x12\x03\x1f\x14\x17\n\x0b\n\x04\x05\0\x02\x1d\ + \x12\x03\x20\x04\x17\n\x0c\n\x05\x05\0\x02\x1d\x01\x12\x03\x20\x04\x10\n\ + \x0c\n\x05\x05\0\x02\x1d\x02\x12\x03\x20\x13\x16b\x06proto3\ +"; + +static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; + +fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { + ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +} + +pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { + file_descriptor_proto_lazy.get(|| { + parse_descriptor_proto() + }) +} diff --git a/shared-lib/error-code/src/protobuf/model/mod.rs b/shared-lib/error-code/src/protobuf/model/mod.rs new file mode 100644 index 0000000000..e6c7f34086 --- /dev/null +++ b/shared-lib/error-code/src/protobuf/model/mod.rs @@ -0,0 +1,5 @@ +#![cfg_attr(rustfmt, rustfmt::skip)] +// Auto-generated, do not edit + +mod error_code; +pub use error_code::*; diff --git a/shared-lib/error-code/src/protobuf/proto/error_code.proto b/shared-lib/error-code/src/protobuf/proto/error_code.proto new file mode 100644 index 0000000000..ed12d58848 --- /dev/null +++ b/shared-lib/error-code/src/protobuf/proto/error_code.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +enum ErrorCode { + Internal = 0; + UserUnauthorized = 2; + RecordNotFound = 3; + 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; +} diff --git a/shared-lib/flowy-core-infra/Cargo.toml b/shared-lib/flowy-core-infra/Cargo.toml index 28898dabf7..e3420abe0a 100644 --- a/shared-lib/flowy-core-infra/Cargo.toml +++ b/shared-lib/flowy-core-infra/Cargo.toml @@ -17,6 +17,7 @@ log = "0.4.14" flowy-collaboration = { path = "../flowy-collaboration" } uuid = { version = "0.8", features = ["serde", "v4"] } chrono = { version = "0.4" } +error-code = { path = "../error-code" } [features] default = [] diff --git a/shared-lib/flowy-core-infra/Flowy.toml b/shared-lib/flowy-core-infra/Flowy.toml index d1411c4d2b..5e88aadda5 100644 --- a/shared-lib/flowy-core-infra/Flowy.toml +++ b/shared-lib/flowy-core-infra/Flowy.toml @@ -1,3 +1,3 @@ -proto_crates = ["src/entities", "src/errors.rs"] +proto_crates = ["src/entities",] event_files = [] \ No newline at end of file diff --git a/shared-lib/flowy-core-infra/src/entities/view/view_update.rs b/shared-lib/flowy-core-infra/src/entities/view/view_update.rs index 7205f6c39c..5a3b10df93 100644 --- a/shared-lib/flowy-core-infra/src/entities/view/view_update.rs +++ b/shared-lib/flowy-core-infra/src/entities/view/view_update.rs @@ -93,11 +93,11 @@ impl TryInto for UpdateViewRequest { // } // // impl TryInto for DocDeltaRequest { -// type Error = WorkspaceError; +// type Error = FlowyError; // // fn try_into(self) -> Result { // let view_id = ViewId::parse(self.view_id) -// .map_err(|e| WorkspaceError::view_id().context(e))? +// .map_err(|e| FlowyError::view_id().context(e))? // .0; // // Ok(DocDelta { doc_id: view_id, data: self.data }) diff --git a/shared-lib/flowy-core-infra/src/errors.rs b/shared-lib/flowy-core-infra/src/errors.rs deleted file mode 100644 index a9a07a99a6..0000000000 --- a/shared-lib/flowy-core-infra/src/errors.rs +++ /dev/null @@ -1,77 +0,0 @@ -use crate::protobuf::ErrorCode as ProtoBufErrorCode; - -use derive_more::Display; -use flowy_derive::ProtoBuf_Enum; -use protobuf::ProtobufEnum; -use std::convert::{TryFrom, TryInto}; - -#[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] -pub enum ErrorCode { - #[display(fmt = "Workspace name can not be empty or whitespace")] - WorkspaceNameInvalid = 0, - - #[display(fmt = "Workspace id can not be empty or whitespace")] - WorkspaceIdInvalid = 1, - - #[display(fmt = "Color style of the App is invalid")] - AppColorStyleInvalid = 2, - - #[display(fmt = "Workspace desc is invalid")] - WorkspaceDescTooLong = 3, - - #[display(fmt = "Workspace description too long")] - WorkspaceNameTooLong = 4, - - #[display(fmt = "App id can not be empty or whitespace")] - AppIdInvalid = 10, - - #[display(fmt = "App name can not be empty or whitespace")] - AppNameInvalid = 11, - - #[display(fmt = "View name can not be empty or whitespace")] - ViewNameInvalid = 20, - - #[display(fmt = "Thumbnail of the view is invalid")] - ViewThumbnailInvalid = 21, - - #[display(fmt = "View id can not be empty or whitespace")] - ViewIdInvalid = 22, - - #[display(fmt = "View desc too long")] - ViewDescTooLong = 23, - - #[display(fmt = "View data is invalid")] - ViewDataInvalid = 24, - - #[display(fmt = "View name too long")] - ViewNameTooLong = 25, - - #[display(fmt = "User unauthorized")] - UserUnauthorized = 100, - - #[display(fmt = "Workspace websocket error")] - WsConnectError = 200, - - #[display(fmt = "Server error")] - InternalError = 1000, - #[display(fmt = "Record not found")] - RecordNotFound = 1001, -} - -impl std::default::Default for ErrorCode { - fn default() -> Self { ErrorCode::InternalError } -} - -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::InternalError, - Some(code) => ErrorCode::try_from(&code).unwrap(), - } - } -} diff --git a/shared-lib/flowy-core-infra/src/lib.rs b/shared-lib/flowy-core-infra/src/lib.rs index 631fdf050b..841c93b8d7 100644 --- a/shared-lib/flowy-core-infra/src/lib.rs +++ b/shared-lib/flowy-core-infra/src/lib.rs @@ -1,5 +1,4 @@ pub mod entities; -pub mod errors; pub mod parser; #[macro_use] @@ -8,3 +7,7 @@ mod macros; // #[cfg(feature = "backend")] pub mod protobuf; pub mod user_default; + +pub mod errors { + pub use error_code::ErrorCode; +} diff --git a/shared-lib/flowy-derive/src/derive_cache/derive_cache.rs b/shared-lib/flowy-derive/src/derive_cache/derive_cache.rs index 57014f3213..3e314e6a7f 100644 --- a/shared-lib/flowy-derive/src/derive_cache/derive_cache.rs +++ b/shared-lib/flowy-derive/src/derive_cache/derive_cache.rs @@ -16,14 +16,11 @@ pub fn category_from_str(type_str: &str) -> TypeCategory { "HashMap" => TypeCategory::Map, "u8" => TypeCategory::Bytes, "String" => TypeCategory::Str, - "WorkspaceError" - | "DocError" - | "FFIRequest" + "FFIRequest" | "FFIResponse" | "FlowyError" | "SubscribeObject" | "NetworkState" - | "UserError" | "QueryAppRequest" | "AppIdentifier" | "CreateAppRequest" @@ -82,7 +79,6 @@ pub fn category_from_str(type_str: &str) -> TypeCategory { => TypeCategory::Protobuf, "WorkspaceEvent" | "WorkspaceNotification" - | "ErrorCode" | "DocObservable" | "FFIStatusCode" | "NetworkEvent" @@ -93,6 +89,7 @@ pub fn category_from_str(type_str: &str) -> TypeCategory { | "ViewType" | "ExportType" | "WsDataType" + | "ErrorCode" | "WsModule" | "RevType" | "RevState" diff --git a/shared-lib/flowy-user-infra/Cargo.toml b/shared-lib/flowy-user-infra/Cargo.toml index 918516780c..5e0afba7c9 100644 --- a/shared-lib/flowy-user-infra/Cargo.toml +++ b/shared-lib/flowy-user-infra/Cargo.toml @@ -7,6 +7,7 @@ edition = "2018" [dependencies] flowy-derive = { path = "../flowy-derive" } +error-code = { path = "../error-code" } protobuf = {version = "2.18.0"} bytes = "1.0" unicode-segmentation = "1.8" diff --git a/shared-lib/flowy-user-infra/src/errors.rs b/shared-lib/flowy-user-infra/src/errors.rs deleted file mode 100644 index 2fe57dc53f..0000000000 --- a/shared-lib/flowy-user-infra/src/errors.rs +++ /dev/null @@ -1,61 +0,0 @@ -use crate::protobuf::ErrorCode as ProtoBufErrorCode; -use derive_more::Display; -use flowy_derive::ProtoBuf_Enum; -use protobuf::ProtobufEnum; -use std::convert::{TryFrom, TryInto}; - -#[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)] -pub enum ErrorCode { - #[display(fmt = "Email can not be empty or whitespace")] - EmailIsEmpty = 0, - #[display(fmt = "Email format is not valid")] - EmailFormatInvalid = 1, - #[display(fmt = "Email already exists")] - EmailAlreadyExists = 2, - #[display(fmt = "Password can not be empty or whitespace")] - PasswordIsEmpty = 10, - #[display(fmt = "Password format too long")] - PasswordTooLong = 11, - #[display(fmt = "Password contains forbidden characters.")] - PasswordContainsForbidCharacters = 12, - #[display(fmt = "Password should contain a minimum of 6 characters with 1 special 1 letter and 1 numeric")] - PasswordFormatInvalid = 13, - #[display(fmt = "Password not match")] - PasswordNotMatch = 14, - #[display(fmt = "User name is too long")] - UserNameTooLong = 20, - #[display(fmt = "User name contain forbidden characters")] - UserNameContainForbiddenCharacters = 21, - #[display(fmt = "User name can not be empty or whitespace")] - UserNameIsEmpty = 22, - #[display(fmt = "user id is empty or whitespace")] - UserIdInvalid = 23, - #[display(fmt = "User token is invalid")] - UserUnauthorized = 24, - #[display(fmt = "User not exist")] - UserNotExist = 25, - - #[display(fmt = "Server error")] - ServerError = 99, - - #[display(fmt = "Internal error")] - InternalError = 100, -} - -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::InternalError, - Some(code) => ErrorCode::try_from(&code).unwrap(), - } - } -} - -impl std::default::Default for ErrorCode { - fn default() -> Self { ErrorCode::InternalError } -} diff --git a/shared-lib/flowy-user-infra/src/lib.rs b/shared-lib/flowy-user-infra/src/lib.rs index 3ee07bd886..706b26a74f 100644 --- a/shared-lib/flowy-user-infra/src/lib.rs +++ b/shared-lib/flowy-user-infra/src/lib.rs @@ -1,5 +1,7 @@ pub mod entities; -pub mod errors; pub mod parser; pub mod protobuf; -pub mod user_default; + +pub mod errors { + pub use error_code::ErrorCode; +} diff --git a/shared-lib/flowy-user-infra/src/user_default.rs b/shared-lib/flowy-user-infra/src/user_default.rs deleted file mode 100644 index 8b13789179..0000000000 --- a/shared-lib/flowy-user-infra/src/user_default.rs +++ /dev/null @@ -1 +0,0 @@ -