rename flowy-dispatch structs

This commit is contained in:
appflowy
2021-12-04 11:26:17 +08:00
parent 76691e3e8c
commit c649673b2b
8 changed files with 40 additions and 40 deletions

View File

@ -18,7 +18,7 @@ lazy_static! {
static ref FLOWY_SDK: RwLock<Option<Arc<FlowySDK>>> = RwLock::new(None); static ref FLOWY_SDK: RwLock<Option<Arc<FlowySDK>>> = RwLock::new(None);
} }
fn dispatch() -> Arc<EventDispatch> { FLOWY_SDK.read().as_ref().unwrap().dispatch() } fn dispatch() -> Arc<EventDispatcher> { FLOWY_SDK.read().as_ref().unwrap().dispatcher() }
#[no_mangle] #[no_mangle]
pub extern "C" fn init_sdk(path: *mut c_char) -> i64 { pub extern "C" fn init_sdk(path: *mut c_char) -> i64 {
@ -42,7 +42,7 @@ pub extern "C" fn async_event(port: i64, input: *const u8, len: usize) {
port port
); );
let _ = EventDispatch::async_send_with_callback(dispatch(), request, move |resp: EventResponse| { let _ = EventDispatcher::async_send_with_callback(dispatch(), request, move |resp: EventResponse| {
log::trace!("[FFI]: Post data to dart through {} port", port); log::trace!("[FFI]: Post data to dart through {} port", port);
Box::pin(post_to_flutter(resp, port)) Box::pin(post_to_flutter(resp, port))
}); });
@ -52,7 +52,7 @@ pub extern "C" fn async_event(port: i64, input: *const u8, len: usize) {
pub extern "C" fn sync_event(input: *const u8, len: usize) -> *const u8 { pub extern "C" fn sync_event(input: *const u8, len: usize) -> *const u8 {
let request: ModuleRequest = FFIRequest::from_u8_pointer(input, len).into(); let request: ModuleRequest = FFIRequest::from_u8_pointer(input, len).into();
log::trace!("[FFI]: {} Sync Event: {:?}", &request.id, &request.event,); log::trace!("[FFI]: {} Sync Event: {:?}", &request.id, &request.event,);
let _response = EventDispatch::sync_send(dispatch(), request); let _response = EventDispatcher::sync_send(dispatch(), request);
// FFIResponse { } // FFIResponse { }
let response_bytes = vec![]; let response_bytes = vec![];

View File

@ -64,7 +64,7 @@ pub struct FlowySDK {
pub user_session: Arc<UserSession>, pub user_session: Arc<UserSession>,
pub flowy_document: Arc<FlowyDocument>, pub flowy_document: Arc<FlowyDocument>,
pub workspace: Arc<WorkspaceController>, pub workspace: Arc<WorkspaceController>,
pub dispatch: Arc<EventDispatch>, pub dispatcher: Arc<EventDispatcher>,
} }
impl FlowySDK { impl FlowySDK {
@ -82,22 +82,22 @@ impl FlowySDK {
let flowy_document = mk_document_module(user_session.clone(), &config.server_config); let flowy_document = mk_document_module(user_session.clone(), &config.server_config);
let workspace = mk_workspace(user_session.clone(), flowy_document.clone(), &config.server_config); let workspace = mk_workspace(user_session.clone(), flowy_document.clone(), &config.server_config);
let modules = mk_modules(workspace.clone(), user_session.clone()); let modules = mk_modules(workspace.clone(), user_session.clone());
let dispatch = Arc::new(EventDispatch::construct(|| modules)); let dispatcher = Arc::new(EventDispatcher::construct(|| modules));
_init(&dispatch, user_session.clone(), workspace.clone()); _init(&dispatcher, user_session.clone(), workspace.clone());
Self { Self {
config, config,
user_session, user_session,
flowy_document, flowy_document,
workspace, workspace,
dispatch, dispatcher,
} }
} }
pub fn dispatch(&self) -> Arc<EventDispatch> { self.dispatch.clone() } pub fn dispatcher(&self) -> Arc<EventDispatcher> { self.dispatcher.clone() }
} }
fn _init(dispatch: &EventDispatch, user_session: Arc<UserSession>, workspace_controller: Arc<WorkspaceController>) { fn _init(dispatch: &EventDispatcher, user_session: Arc<UserSession>, workspace_controller: Arc<WorkspaceController>) {
let subscribe = user_session.status_subscribe(); let subscribe = user_session.status_subscribe();
dispatch.spawn(async move { dispatch.spawn(async move {
user_session.init(); user_session.init();

View File

@ -1,5 +1,5 @@
use flowy_user::entities::UserProfile; use flowy_user::entities::UserProfile;
use lib_dispatch::prelude::{EventDispatch, EventResponse, FromBytes, ModuleRequest, StatusCode, ToBytes}; use lib_dispatch::prelude::{EventDispatcher, EventResponse, FromBytes, ModuleRequest, StatusCode, ToBytes};
use std::{ use std::{
fmt::{Debug, Display}, fmt::{Debug, Display},
hash::Hash, hash::Hash,
@ -69,14 +69,14 @@ where
pub fn sync_send(mut self) -> Self { pub fn sync_send(mut self) -> Self {
let request = self.get_request(); let request = self.get_request();
let resp = EventDispatch::sync_send(self.dispatch(), request); let resp = EventDispatcher::sync_send(self.dispatch(), request);
self.context.response = Some(resp); self.context.response = Some(resp);
self self
} }
pub async fn async_send(mut self) -> Self { pub async fn async_send(mut self) -> Self {
let request = self.get_request(); let request = self.get_request();
let resp = EventDispatch::async_send(self.dispatch(), request).await; let resp = EventDispatcher::async_send(self.dispatch(), request).await;
self.context.response = Some(resp); self.context.response = Some(resp);
self self
} }
@ -113,7 +113,7 @@ where
pub fn sdk(&self) -> FlowySDK { self.context.sdk.clone() } pub fn sdk(&self) -> FlowySDK { self.context.sdk.clone() }
fn dispatch(&self) -> Arc<EventDispatch> { self.context.sdk.dispatch() } fn dispatch(&self) -> Arc<EventDispatcher> { self.context.sdk.dispatcher() }
fn get_response(&self) -> EventResponse { fn get_response(&self) -> EventResponse {
self.context self.context

View File

@ -1,5 +1,5 @@
use bytes::Bytes; use bytes::Bytes;
use lib_dispatch::prelude::{EventDispatch, ModuleRequest, ToBytes}; use lib_dispatch::prelude::{EventDispatcher, ModuleRequest, ToBytes};
use lib_infra::{kv::KV, uuid}; use lib_infra::{kv::KV, uuid};
use flowy_user::{ use flowy_user::{
@ -41,7 +41,7 @@ const DEFAULT_WORKSPACE_DESC: &str = "This is your first workspace";
const DEFAULT_WORKSPACE: &str = "Default_Workspace"; const DEFAULT_WORKSPACE: &str = "Default_Workspace";
#[allow(dead_code)] #[allow(dead_code)]
pub(crate) fn create_default_workspace_if_need(dispatch: Arc<EventDispatch>, user_id: &str) -> Result<(), UserError> { pub(crate) fn create_default_workspace_if_need(dispatch: Arc<EventDispatcher>, user_id: &str) -> Result<(), UserError> {
let key = format!("{}{}", user_id, DEFAULT_WORKSPACE); let key = format!("{}{}", user_id, DEFAULT_WORKSPACE);
if KV::get_bool(&key).unwrap_or(false) { if KV::get_bool(&key).unwrap_or(false) {
return Err(UserError::internal()); return Err(UserError::internal());
@ -56,7 +56,7 @@ pub(crate) fn create_default_workspace_if_need(dispatch: Arc<EventDispatch>, use
.unwrap(); .unwrap();
let request = ModuleRequest::new(CreateWorkspace).payload(payload); let request = ModuleRequest::new(CreateWorkspace).payload(payload);
let result = EventDispatch::sync_send(dispatch.clone(), request) let result = EventDispatcher::sync_send(dispatch.clone(), request)
.parse::<Workspace, WorkspaceError>() .parse::<Workspace, WorkspaceError>()
.map_err(|e| UserError::internal().context(e))?; .map_err(|e| UserError::internal().context(e))?;
@ -68,7 +68,7 @@ pub(crate) fn create_default_workspace_if_need(dispatch: Arc<EventDispatch>, use
.unwrap(); .unwrap();
let request = ModuleRequest::new(OpenWorkspace).payload(query); let request = ModuleRequest::new(OpenWorkspace).payload(query);
let _result = EventDispatch::sync_send(dispatch, request) let _result = EventDispatcher::sync_send(dispatch, request)
.parse::<Workspace, WorkspaceError>() .parse::<Workspace, WorkspaceError>()
.unwrap() .unwrap()
.unwrap(); .unwrap();
@ -81,7 +81,7 @@ pub struct SignUpContext {
pub password: String, pub password: String,
} }
pub fn sign_up(dispatch: Arc<EventDispatch>) -> SignUpContext { pub fn sign_up(dispatch: Arc<EventDispatcher>) -> SignUpContext {
let password = login_password(); let password = login_password();
let payload = SignUpRequest { let payload = SignUpRequest {
email: random_email(), email: random_email(),
@ -92,7 +92,7 @@ pub fn sign_up(dispatch: Arc<EventDispatch>) -> SignUpContext {
.unwrap(); .unwrap();
let request = ModuleRequest::new(SignUp).payload(payload); let request = ModuleRequest::new(SignUp).payload(payload);
let user_profile = EventDispatch::sync_send(dispatch, request) let user_profile = EventDispatcher::sync_send(dispatch, request)
.parse::<UserProfile, UserError>() .parse::<UserProfile, UserError>()
.unwrap() .unwrap()
.unwrap(); .unwrap();
@ -100,7 +100,7 @@ pub fn sign_up(dispatch: Arc<EventDispatch>) -> SignUpContext {
SignUpContext { user_profile, password } SignUpContext { user_profile, password }
} }
pub async fn async_sign_up(dispatch: Arc<EventDispatch>) -> SignUpContext { pub async fn async_sign_up(dispatch: Arc<EventDispatcher>) -> SignUpContext {
let password = login_password(); let password = login_password();
let payload = SignUpRequest { let payload = SignUpRequest {
email: random_email(), email: random_email(),
@ -111,7 +111,7 @@ pub async fn async_sign_up(dispatch: Arc<EventDispatch>) -> SignUpContext {
.unwrap(); .unwrap();
let request = ModuleRequest::new(SignUp).payload(payload); let request = ModuleRequest::new(SignUp).payload(payload);
let user_profile = EventDispatch::async_send(dispatch.clone(), request) let user_profile = EventDispatcher::async_send(dispatch.clone(), request)
.await .await
.parse::<UserProfile, UserError>() .parse::<UserProfile, UserError>()
.unwrap() .unwrap()
@ -122,7 +122,7 @@ pub async fn async_sign_up(dispatch: Arc<EventDispatch>) -> SignUpContext {
} }
#[allow(dead_code)] #[allow(dead_code)]
fn sign_in(dispatch: Arc<EventDispatch>) -> UserProfile { fn sign_in(dispatch: Arc<EventDispatcher>) -> UserProfile {
let payload = SignInRequest { let payload = SignInRequest {
email: login_email(), email: login_email(),
password: login_password(), password: login_password(),
@ -132,11 +132,11 @@ fn sign_in(dispatch: Arc<EventDispatch>) -> UserProfile {
.unwrap(); .unwrap();
let request = ModuleRequest::new(SignIn).payload(payload); let request = ModuleRequest::new(SignIn).payload(payload);
EventDispatch::sync_send(dispatch, request) EventDispatcher::sync_send(dispatch, request)
.parse::<UserProfile, UserError>() .parse::<UserProfile, UserError>()
.unwrap() .unwrap()
.unwrap() .unwrap()
} }
#[allow(dead_code)] #[allow(dead_code)]
fn logout(dispatch: Arc<EventDispatch>) { let _ = EventDispatch::sync_send(dispatch, ModuleRequest::new(SignOut)); } fn logout(dispatch: Arc<EventDispatcher>) { let _ = EventDispatcher::sync_send(dispatch, ModuleRequest::new(SignOut)); }

View File

@ -24,17 +24,17 @@ impl FlowyTest {
pub fn setup() -> Self { pub fn setup() -> Self {
let server_config = ServerConfig::default(); let server_config = ServerConfig::default();
let test = Self::setup_with(server_config); let test = Self::setup_with(server_config);
std::mem::forget(test.sdk.dispatch()); std::mem::forget(test.sdk.dispatcher());
test test
} }
pub async fn sign_up(&self) -> SignUpContext { pub async fn sign_up(&self) -> SignUpContext {
let context = async_sign_up(self.sdk.dispatch()).await; let context = async_sign_up(self.sdk.dispatcher()).await;
context context
} }
pub async fn init_user(&self) -> UserProfile { pub async fn init_user(&self) -> UserProfile {
let context = async_sign_up(self.sdk.dispatch()).await; let context = async_sign_up(self.sdk.dispatcher()).await;
context.user_profile context.user_profile
} }

View File

@ -11,13 +11,13 @@ use futures_util::task::Context;
use pin_project::pin_project; use pin_project::pin_project;
use std::{future::Future, sync::Arc}; use std::{future::Future, sync::Arc};
use tokio::macros::support::{Pin, Poll}; use tokio::macros::support::{Pin, Poll};
pub struct EventDispatch { pub struct EventDispatcher {
module_map: ModuleMap, module_map: ModuleMap,
runtime: tokio::runtime::Runtime, runtime: tokio::runtime::Runtime,
} }
impl EventDispatch { impl EventDispatcher {
pub fn construct<F>(module_factory: F) -> EventDispatch pub fn construct<F>(module_factory: F) -> EventDispatcher
where where
F: FnOnce() -> Vec<Module>, F: FnOnce() -> Vec<Module>,
{ {
@ -26,18 +26,18 @@ impl EventDispatch {
tracing::trace!("{}", module_info(&modules)); tracing::trace!("{}", module_info(&modules));
let module_map = as_module_map(modules); let module_map = as_module_map(modules);
EventDispatch { module_map, runtime } EventDispatcher { module_map, runtime }
} }
pub fn async_send<Req>(dispatch: Arc<EventDispatch>, request: Req) -> DispatchFuture<EventResponse> pub fn async_send<Req>(dispatch: Arc<EventDispatcher>, request: Req) -> DispatchFuture<EventResponse>
where where
Req: std::convert::Into<ModuleRequest>, Req: std::convert::Into<ModuleRequest>,
{ {
EventDispatch::async_send_with_callback(dispatch, request, |_| Box::pin(async {})) EventDispatcher::async_send_with_callback(dispatch, request, |_| Box::pin(async {}))
} }
pub fn async_send_with_callback<Req, Callback>( pub fn async_send_with_callback<Req, Callback>(
dispatch: Arc<EventDispatch>, dispatch: Arc<EventDispatcher>,
request: Req, request: Req,
callback: Callback, callback: Callback,
) -> DispatchFuture<EventResponse> ) -> DispatchFuture<EventResponse>
@ -70,9 +70,9 @@ impl EventDispatch {
} }
} }
pub fn sync_send(dispatch: Arc<EventDispatch>, request: ModuleRequest) -> EventResponse { pub fn sync_send(dispatch: Arc<EventDispatcher>, request: ModuleRequest) -> EventResponse {
futures::executor::block_on(async { futures::executor::block_on(async {
EventDispatch::async_send_with_callback(dispatch, request, |_| Box::pin(async {})).await EventDispatcher::async_send_with_callback(dispatch, request, |_| Box::pin(async {})).await
}) })
} }

View File

@ -7,7 +7,7 @@ mod util;
mod byte_trait; mod byte_trait;
mod data; mod data;
mod dispatch; mod dispatcher;
mod system; mod system;
#[macro_use] #[macro_use]
@ -16,5 +16,5 @@ pub mod macros;
pub use errors::Error; pub use errors::Error;
pub mod prelude { pub mod prelude {
pub use crate::{byte_trait::*, data::*, dispatch::*, errors::*, module::*, request::*, response::*}; pub use crate::{byte_trait::*, data::*, dispatcher::*, errors::*, module::*, request::*, response::*};
} }

View File

@ -8,9 +8,9 @@ async fn test() {
env_logger::init(); env_logger::init();
let event = "1"; let event = "1";
let dispatch = Arc::new(EventDispatch::construct(|| vec![Module::new().event(event, hello)])); let dispatch = Arc::new(EventDispatcher::construct(|| vec![Module::new().event(event, hello)]));
let request = ModuleRequest::new(event); let request = ModuleRequest::new(event);
let _ = EventDispatch::async_send_with_callback(dispatch.clone(), request, |resp| { let _ = EventDispatcher::async_send_with_callback(dispatch.clone(), request, |resp| {
Box::pin(async move { Box::pin(async move {
dbg!(&resp); dbg!(&resp);
}) })