From 1cfcdab1247d2398a6c139625f2e33a36f8e292f Mon Sep 17 00:00:00 2001 From: appflowy Date: Fri, 2 Jul 2021 20:47:52 +0800 Subject: [PATCH] config sdk initialize --- rust-lib/Cargo.toml | 2 +- rust-lib/dart-ffi/Cargo.toml | 7 ++- rust-lib/dart-ffi/src/lib.rs | 34 +++++++++++-- rust-lib/flowy-log/Cargo.toml | 5 +- rust-lib/flowy-log/src/lib.rs | 5 +- rust-lib/flowy-sdk/src/lib.rs | 47 ++++-------------- rust-lib/flowy-sdk/tests/sdk/helper.rs | 51 +++++++------------- rust-lib/flowy-sdk/tests/sdk/user_check.rs | 14 ++---- rust-lib/flowy-user/Cargo.toml | 2 +- rust-lib/flowy-user/src/domain/user_email.rs | 2 +- rust-lib/flowy-user/src/handlers/auth.rs | 6 +-- 11 files changed, 79 insertions(+), 96 deletions(-) diff --git a/rust-lib/Cargo.toml b/rust-lib/Cargo.toml index 429b676a21..1e07ba2a25 100644 --- a/rust-lib/Cargo.toml +++ b/rust-lib/Cargo.toml @@ -6,7 +6,7 @@ members = [ "flowy-log", "flowy-user", "flowy-ast", - + "flowy-derive", ] [profile.dev] diff --git a/rust-lib/dart-ffi/Cargo.toml b/rust-lib/dart-ffi/Cargo.toml index 91c33cf435..5d7006663a 100644 --- a/rust-lib/dart-ffi/Cargo.toml +++ b/rust-lib/dart-ffi/Cargo.toml @@ -26,4 +26,9 @@ serde = { version = "1.0", features = ["derive"] } serde_json = {version = "1.0"} flowy-sys = {path = "../flowy-sys"} -flowy-sdk = {path = "../flowy-sdk"} \ No newline at end of file +flowy-sdk = {path = "../flowy-sdk"} +flowy-log = {path = "../flowy-log"} + +#[features] +#use_serde = ["bincode"] +#use_protobuf= ["protobuf"] \ No newline at end of file diff --git a/rust-lib/dart-ffi/src/lib.rs b/rust-lib/dart-ffi/src/lib.rs index 27d803128c..a8e90739f4 100644 --- a/rust-lib/dart-ffi/src/lib.rs +++ b/rust-lib/dart-ffi/src/lib.rs @@ -3,35 +3,41 @@ mod c; use crate::c::forget_rust; use flowy_sdk::*; use flowy_sys::prelude::*; -use std::{cell::RefCell, ffi::CStr, os::raw::c_char}; +use std::{cell::RefCell, ffi::CStr, future::Future, os::raw::c_char}; #[no_mangle] pub extern "C" fn init_sdk(path: *mut c_char) -> i64 { let c_str: &CStr = unsafe { CStr::from_ptr(path) }; let path: &str = c_str.to_str().unwrap(); - println!("{}", path); + FlowySDK::init_log(); + FlowySDK::init(path); return 1; } +#[derive(serde::Deserialize)] pub struct FFICommand { event: String, payload: Vec, } impl FFICommand { - pub fn from_bytes(bytes: Vec) -> Self { unimplemented!() } + pub fn from_bytes(bytes: Vec) -> Self { + let command: FFICommand = serde_json::from_slice(&bytes).unwrap(); + command + } pub fn from_u8_pointer(pointer: *const u8, len: usize) -> Self { let bytes = unsafe { std::slice::from_raw_parts(pointer, len) }.to_vec(); - unimplemented!() + FFICommand::from_bytes(bytes) } } #[no_mangle] pub extern "C" fn async_command(port: i64, input: *const u8, len: usize) { let FFICommand { event, payload } = FFICommand::from_u8_pointer(input, len); + log::info!("Event: {:?}", event); - let mut request = SenderRequest::new(port, event).callback(|_, resp| { + let mut request = DispatchRequest::new(port, event).callback(|_, resp| { log::info!("async resp: {:?}", resp); }); @@ -40,6 +46,7 @@ pub extern "C" fn async_command(port: i64, input: *const u8, len: usize) { } async_send(request); + spawn_future(async { vec![] }, 123); } #[no_mangle] @@ -48,3 +55,20 @@ pub extern "C" fn sync_command(input: *const u8, len: usize) -> *const u8 { unim #[inline(never)] #[no_mangle] pub extern "C" fn link_me_please() {} + +#[inline(always)] +fn spawn_future(future: F, port: i64) +where + F: Future> + Send + 'static, +{ + let isolate = allo_isolate::Isolate::new(port); + isolate.catch_unwind(future); + + // if let Err(e) = isolate.catch_unwind(future) { + // if let Some(msg) = e.downcast_ref::<&str>() { + // log::error!("🔥 {:?}", msg); + // } else { + // log::error!("no info provided for that panic 😡"); + // } + // } +} diff --git a/rust-lib/flowy-log/Cargo.toml b/rust-lib/flowy-log/Cargo.toml index 957bde80c1..3a54ab023f 100644 --- a/rust-lib/flowy-log/Cargo.toml +++ b/rust-lib/flowy-log/Cargo.toml @@ -6,9 +6,10 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -tracing = { version = "0.1", features = ["log"] } -tracing-log = "0.1.1" +tracing = { version = "0.1" } +tracing-log = { version = "0.1.1", features = ["env_logger"]} tracing-futures = "0.2.4" tracing-subscriber = { version = "0.2.12", features = ["registry", "env-filter"] } tracing-bunyan-formatter = "0.2.2" +tracing-appender = "0.1" log = "0.4.14" \ No newline at end of file diff --git a/rust-lib/flowy-log/src/lib.rs b/rust-lib/flowy-log/src/lib.rs index af26c09d0a..5d90144f76 100644 --- a/rust-lib/flowy-log/src/lib.rs +++ b/rust-lib/flowy-log/src/lib.rs @@ -4,10 +4,13 @@ use tracing_log::LogTracer; use tracing_subscriber::{layer::SubscriberExt, EnvFilter}; pub fn init_log(name: &str, env_filter: &str) -> std::result::Result<(), String> { - let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(env_filter.to_owned())); + let env_filter = + EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(env_filter.to_owned())); let formatting_layer = BunyanFormattingLayer::new(name.to_owned(), std::io::stdout); + let subscriber = tracing_subscriber::fmt() .with_target(false) + .with_writer(std::io::stdout) .with_thread_ids(false) .with_target(false) .compact() diff --git a/rust-lib/flowy-sdk/src/lib.rs b/rust-lib/flowy-sdk/src/lib.rs index 3b52dbe263..1fc35378e7 100644 --- a/rust-lib/flowy-sdk/src/lib.rs +++ b/rust-lib/flowy-sdk/src/lib.rs @@ -3,51 +3,22 @@ pub use module::*; use flowy_sys::prelude::*; use module::build_modules; -use std::cell::RefCell; pub struct FlowySDK {} impl FlowySDK { - pub fn init(path: &str) { - flowy_log::init_log("flowy", "Debug").unwrap(); + pub fn init_log() { flowy_log::init_log("flowy", "Debug").unwrap(); } - log::info!("🔥🔥🔥 System start running"); - match init_system(build_modules()).run() { - Ok(_) => {}, - Err(e) => log::error!("System run fail with error: {:?}", e), - } + pub fn init(path: &str) { + log::info!("🔥 System start running"); + log::debug!("🔥 Root path: {}", path); + EventDispatch::construct(|| build_modules()); } } -pub fn init_system(modules: Vec) -> SystemRunner { - FlowySystem::construct( - || modules, - |module_map, runtime| { - let mut sender = Sender::::new(module_map.clone()); - runtime.spawn(SenderRunner::new(module_map, sender.take_rx())); - - SENDER.with(|cell| { - *cell.borrow_mut() = Some(sender); - }); - }, - ) +pub async fn async_send(data: DispatchRequest) -> Result { + EventDispatch::async_send(data).await } -thread_local!( - static SENDER: RefCell>> = RefCell::new(None); -); - -pub fn sync_send(data: SenderRequest) -> EventResponse { - SENDER.with(|cell| match &*cell.borrow() { - Some(stream) => stream.sync_send(data), - None => panic!(""), - }) -} - -pub fn async_send(data: SenderRequest) { - SENDER.with(|cell| match &*cell.borrow() { - Some(stream) => { - stream.async_send(data); - }, - None => panic!(""), - }); +pub fn sync_send(data: DispatchRequest) -> Result { + EventDispatch::sync_send(data) } diff --git a/rust-lib/flowy-sdk/tests/sdk/helper.rs b/rust-lib/flowy-sdk/tests/sdk/helper.rs index c733c8a6b3..2f70aa6b56 100644 --- a/rust-lib/flowy-sdk/tests/sdk/helper.rs +++ b/rust-lib/flowy-sdk/tests/sdk/helper.rs @@ -8,30 +8,18 @@ use std::{ }; static INIT: Once = Once::new(); -pub fn run_test_system(f: F) -where - F: FnOnce() + 'static, -{ +#[allow(dead_code)] + +pub fn init_system() { INIT.call_once(|| { - flowy_log::init_log("flowy", "Debug").unwrap(); + FlowySDK::init_log(); }); - let mut runner = init_system(build_modules()); - runner = runner.spawn(async { - f(); - FlowySystem::current().stop(); - }); - - log::info!("🔥🔥🔥 System start running"); - match runner.run() { - Ok(_) => {}, - Err(e) => log::error!("System run fail with error: {:?}", e), - } + FlowySDK::init("123"); } pub struct FlowySDKTester { - request: SenderRequest, - callback: Option>, + request: DispatchRequest, } impl FlowySDKTester { @@ -40,8 +28,7 @@ impl FlowySDKTester { E: Eq + Hash + Debug + Clone + Display, { Self { - request: SenderRequest::new(1, event), - callback: None, + request: DispatchRequest::new(1, event), } } @@ -65,21 +52,17 @@ impl FlowySDKTester { self } - #[allow(dead_code)] - pub fn callback(mut self, callback: F) -> Self - where - F: FnOnce(i64, EventResponse) + 'static + Send + Sync, - { - self.request = self.request.callback(|config, response| { - dbg!(&response); - callback(config, response); - }); - self + pub async fn async_send(self) -> EventResponse { + init_system(); + let resp = async_send(self.request).await.unwrap(); + dbg!(&resp); + resp } - pub fn run(self) { - run_test_system(move || { - async_send(self.request); - }); + pub fn sync_send(self) -> EventResponse { + init_system(); + let resp = sync_send(self.request).unwrap(); + dbg!(&resp); + resp } } diff --git a/rust-lib/flowy-sdk/tests/sdk/user_check.rs b/rust-lib/flowy-sdk/tests/sdk/user_check.rs index 65529b86a1..0b2a379e8d 100644 --- a/rust-lib/flowy-sdk/tests/sdk/user_check.rs +++ b/rust-lib/flowy-sdk/tests/sdk/user_check.rs @@ -1,6 +1,7 @@ use super::helper::*; use flowy_sys::prelude::*; use flowy_user::prelude::*; +use tokio::time::{sleep, Duration}; #[test] fn auth_check_no_payload() { @@ -8,19 +9,14 @@ fn auth_check_no_payload() { assert_eq!(resp.status, StatusCode::Err); }; - FlowySDKTester::new(AuthCheck).callback(callback).run(); + let resp = FlowySDKTester::new(AuthCheck).sync_send(); } -#[test] -fn auth_check_with_user_name_email_payload() { - let callback = |_, resp: EventResponse| { - assert_eq!(resp.status, StatusCode::Ok); - }; - +#[tokio::test] +async fn auth_check_with_user_name_email_payload() { let user_data = UserData::new("jack".to_owned(), "helloworld@gmail.com".to_owned()); FlowySDKTester::new(AuthCheck) .bytes_payload(user_data) - .callback(callback) - .run(); + .sync_send(); } diff --git a/rust-lib/flowy-user/Cargo.toml b/rust-lib/flowy-user/Cargo.toml index b44094a8a1..8b0e3cd3b1 100644 --- a/rust-lib/flowy-user/Cargo.toml +++ b/rust-lib/flowy-user/Cargo.toml @@ -10,7 +10,7 @@ derive_more = {version = "0.99", features = ["display"]} flowy-sys = { path = "../flowy-sys" } flowy-log = { path = "../flowy-log" } tracing = { version = "0.1", features = ["log"] } -bytes = "0.5" +bytes = "1.0" serde = { version = "1.0", features = ["derive"] } validator = "0.12.0" rand = { version = "0.8", features=["std_rng"] } diff --git a/rust-lib/flowy-user/src/domain/user_email.rs b/rust-lib/flowy-user/src/domain/user_email.rs index c82e75fb4e..5e4acf9588 100644 --- a/rust-lib/flowy-user/src/domain/user_email.rs +++ b/rust-lib/flowy-user/src/domain/user_email.rs @@ -22,7 +22,7 @@ mod tests { use super::*; use claim::assert_err; use fake::{faker::internet::en::SafeEmail, Fake}; - use quickcheck::Gen; + #[test] fn empty_string_is_rejected() { diff --git a/rust-lib/flowy-user/src/handlers/auth.rs b/rust-lib/flowy-user/src/handlers/auth.rs index be4f2aa8e4..b01a6652c5 100644 --- a/rust-lib/flowy-user/src/handlers/auth.rs +++ b/rust-lib/flowy-user/src/handlers/auth.rs @@ -1,5 +1,5 @@ use crate::domain::{User, UserEmail, UserName}; -use bytes::Bytes; + use flowy_sys::prelude::{response_ok, Data, FromBytes, ResponseResult, SystemError, ToBytes}; use std::convert::TryInto; @@ -13,7 +13,7 @@ use std::convert::TryInto; ) )] pub async fn user_check(data: Data) -> ResponseResult { - let user: User = data.into_inner().try_into()?; + let _user: User = data.into_inner().try_into()?; response_ok(UserStatus { is_login: false }) } @@ -24,7 +24,7 @@ pub struct UserStatus { } impl FromBytes for UserData { - fn parse_from_bytes(bytes: &Vec) -> Result { unimplemented!() } + fn parse_from_bytes(_bytes: &Vec) -> Result { unimplemented!() } } impl ToBytes for UserStatus {