refactor: remove shared instance KV (#3123)

* refactor: remove shared instance KV

* test: enable document test
This commit is contained in:
Nathan.fooo
2023-08-06 11:51:03 +08:00
committed by GitHub
parent 9a72f31d60
commit 6f159e741b
13 changed files with 246 additions and 153 deletions

View File

@ -4,7 +4,7 @@ use std::{convert::TryInto, sync::Arc};
use flowy_error::{FlowyError, FlowyResult};
use flowy_server_config::supabase_config::SupabaseConfiguration;
use flowy_sqlite::kv::KV;
use flowy_sqlite::kv::StorePreferences;
use flowy_user_deps::entities::*;
use lib_dispatch::prelude::*;
use lib_infra::box_any::BoxAny;
@ -19,6 +19,15 @@ fn upgrade_session(session: AFPluginState<Weak<UserSession>>) -> FlowyResult<Arc
Ok(session)
}
fn upgrade_store_preferences(
store: AFPluginState<Weak<StorePreferences>>,
) -> FlowyResult<Arc<StorePreferences>> {
let store = store
.upgrade()
.ok_or(FlowyError::internal().context("The store preferences is already drop"))?;
Ok(store)
}
#[tracing::instrument(level = "debug", name = "sign_in", skip(data, session), fields(email = %data.email), err)]
pub async fn sign_in(
data: AFPluginData<SignInPayloadPB>,
@ -107,22 +116,27 @@ pub async fn update_user_profile_handler(
const APPEARANCE_SETTING_CACHE_KEY: &str = "appearance_settings";
#[tracing::instrument(level = "debug", skip(data), err)]
#[tracing::instrument(level = "debug", skip_all, err)]
pub async fn set_appearance_setting(
store_preferences: AFPluginState<Weak<StorePreferences>>,
data: AFPluginData<AppearanceSettingsPB>,
) -> Result<(), FlowyError> {
let store_preferences = upgrade_store_preferences(store_preferences)?;
let mut setting = data.into_inner();
if setting.theme.is_empty() {
setting.theme = APPEARANCE_DEFAULT_THEME.to_string();
}
KV::set_object(APPEARANCE_SETTING_CACHE_KEY, setting)?;
store_preferences.set_object(APPEARANCE_SETTING_CACHE_KEY, setting)?;
Ok(())
}
#[tracing::instrument(level = "debug", err)]
pub async fn get_appearance_setting() -> DataResult<AppearanceSettingsPB, FlowyError> {
match KV::get_str(APPEARANCE_SETTING_CACHE_KEY) {
#[tracing::instrument(level = "debug", skip_all, err)]
pub async fn get_appearance_setting(
store_preferences: AFPluginState<Weak<StorePreferences>>,
) -> DataResult<AppearanceSettingsPB, FlowyError> {
let store_preferences = upgrade_store_preferences(store_preferences)?;
match store_preferences.get_str(APPEARANCE_SETTING_CACHE_KEY) {
None => data_result_ok(AppearanceSettingsPB::default()),
Some(s) => {
let setting = match serde_json::from_str(&s) {
@ -177,9 +191,11 @@ pub async fn set_supabase_config_handler(
#[tracing::instrument(level = "debug", skip_all, err)]
pub async fn get_supabase_config_handler(
store_preferences: AFPluginState<Weak<StorePreferences>>,
_session: AFPluginState<Weak<UserSession>>,
) -> DataResult<SupabaseConfigPB, FlowyError> {
let config = get_supabase_config().unwrap_or_default();
let store_preferences = upgrade_store_preferences(store_preferences)?;
let config = get_supabase_config(&store_preferences).unwrap_or_default();
data_result_ok(config.into())
}

View File

@ -15,9 +15,14 @@ use crate::event_handler::*;
use crate::{errors::FlowyError, services::UserSession};
pub fn init(user_session: Weak<UserSession>) -> AFPlugin {
let store_preferences = user_session
.upgrade()
.and_then(|session| Some(session.get_store_preferences()))
.unwrap();
AFPlugin::new()
.name("Flowy-User")
.state(user_session)
.state(store_preferences)
.event(UserEvent::SignIn, sign_in)
.event(UserEvent::SignUp, sign_up)
.event(UserEvent::InitUser, init_user_handler)

View File

@ -1,13 +1,16 @@
use crate::migrations::migration::UserDataMigration;
use crate::services::session_serde::Session;
use std::sync::Arc;
use appflowy_integrate::{RocksCollabDB, YrsDocAction};
use collab::core::collab::MutexCollab;
use collab::core::origin::{CollabClient, CollabOrigin};
use collab_document::document::Document;
use collab_document::document_data::default_document_data;
use collab_folder::core::Folder;
use flowy_error::{internal_error, FlowyResult};
use std::sync::Arc;
use crate::migrations::migration::UserDataMigration;
use crate::services::session_serde::Session;
/// Migrate the first level documents of the workspace by inserting documents
pub struct HistoricalEmptyDocumentMigration;
@ -30,7 +33,7 @@ impl UserDataMigration for HistoricalEmptyDocumentMigration {
for view in migration_views {
// Read all updates of the view
if let Ok(view_updates) = write_txn.get_all_updates(session.user_id, &view.id) {
if let Err(_) = Document::from_updates(origin.clone(), view_updates, &view.id, vec![]) {
if Document::from_updates(origin.clone(), view_updates, &view.id, vec![]).is_err() {
// Create a document with default data
let document_data = default_document_data();
let collab = Arc::new(MutexCollab::new(origin.clone(), &view.id, vec![]));

View File

@ -8,9 +8,10 @@ use uuid::Uuid;
use flowy_error::{internal_error, ErrorCode, FlowyResult};
use flowy_server_config::supabase_config::SupabaseConfiguration;
use flowy_sqlite::kv::StorePreferences;
use flowy_sqlite::schema::{user_table, user_workspace_table};
use flowy_sqlite::ConnectionPool;
use flowy_sqlite::{kv::KV, query_dsl::*, DBConnection, ExpressionMethods};
use flowy_sqlite::{query_dsl::*, DBConnection, ExpressionMethods};
use flowy_user_deps::entities::*;
use lib_infra::box_any::BoxAny;
use lib_infra::util::timestamp;
@ -56,6 +57,7 @@ pub struct UserSession {
database: UserDB,
session_config: UserSessionConfig,
cloud_services: Arc<dyn UserCloudServiceProvider>,
store_preferences: Arc<StorePreferences>,
pub(crate) user_status_callback: RwLock<Arc<dyn UserStatusCallback>>,
}
@ -63,6 +65,7 @@ impl UserSession {
pub fn new(
session_config: UserSessionConfig,
cloud_services: Arc<dyn UserCloudServiceProvider>,
store_preferences: Arc<StorePreferences>,
) -> Self {
let database = UserDB::new(&session_config.root_dir);
let user_status_callback: RwLock<Arc<dyn UserStatusCallback>> =
@ -71,10 +74,15 @@ impl UserSession {
database,
session_config,
cloud_services,
store_preferences,
user_status_callback,
}
}
pub fn get_store_preferences(&self) -> Weak<StorePreferences> {
Arc::downgrade(&self.store_preferences)
}
pub async fn init<C: UserStatusCallback + 'static>(&self, user_status_callback: C) {
if let Ok(session) = self.get_session() {
match (
@ -443,7 +451,9 @@ impl UserSession {
pub fn save_supabase_config(&self, config: SupabaseConfiguration) {
self.cloud_services.update_supabase_config(&config);
let _ = KV::set_object(SUPABASE_CONFIG_CACHE_KEY, config);
let _ = self
.store_preferences
.set_object(SUPABASE_CONFIG_CACHE_KEY, config);
}
async fn update_user(
@ -554,9 +564,13 @@ impl UserSession {
fn set_session(&self, session: Option<Session>) -> Result<(), FlowyError> {
tracing::debug!("Set user session: {:?}", session);
match &session {
None => KV::remove(&self.session_config.session_cache_key),
None => self
.store_preferences
.remove(&self.session_config.session_cache_key),
Some(session) => {
KV::set_object(&self.session_config.session_cache_key, session.clone())
self
.store_preferences
.set_object(&self.session_config.session_cache_key, session.clone())
.map_err(internal_error)?;
},
}
@ -564,24 +578,34 @@ impl UserSession {
}
fn log_user(&self, uid: i64, storage_path: String) {
let mut logger_users = KV::get_object::<HistoricalUsers>(HISTORICAL_USER).unwrap_or_default();
let mut logger_users = self
.store_preferences
.get_object::<HistoricalUsers>(HISTORICAL_USER)
.unwrap_or_default();
logger_users.add_user(HistoricalUser {
user_id: uid,
sign_in_timestamp: timestamp(),
storage_path,
});
let _ = KV::set_object(HISTORICAL_USER, logger_users);
let _ = self
.store_preferences
.set_object(HISTORICAL_USER, logger_users);
}
pub fn get_historical_users(&self) -> Vec<HistoricalUser> {
KV::get_object::<HistoricalUsers>(HISTORICAL_USER)
self
.store_preferences
.get_object::<HistoricalUsers>(HISTORICAL_USER)
.unwrap_or_default()
.users
}
/// Returns the current user session.
pub fn get_session(&self) -> Result<Session, FlowyError> {
match KV::get_object::<Session>(&self.session_config.session_cache_key) {
match self
.store_preferences
.get_object::<Session>(&self.session_config.session_cache_key)
{
None => Err(FlowyError::new(
ErrorCode::RecordNotFound,
"User is not logged in",
@ -591,8 +615,11 @@ impl UserSession {
}
}
pub fn get_supabase_config() -> Option<SupabaseConfiguration> {
KV::get_str(SUPABASE_CONFIG_CACHE_KEY)
pub fn get_supabase_config(
store_preference: &Arc<StorePreferences>,
) -> Option<SupabaseConfiguration> {
store_preference
.get_str(SUPABASE_CONFIG_CACHE_KEY)
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_else(|| SupabaseConfiguration::from_env().ok())
}