config sdk initialize

This commit is contained in:
appflowy 2021-07-02 20:47:52 +08:00
parent 7e1cf1222f
commit 1cfcdab124
11 changed files with 79 additions and 96 deletions

View File

@ -6,7 +6,7 @@ members = [
"flowy-log", "flowy-log",
"flowy-user", "flowy-user",
"flowy-ast", "flowy-ast",
"flowy-derive",
] ]
[profile.dev] [profile.dev]

View File

@ -26,4 +26,9 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = {version = "1.0"} serde_json = {version = "1.0"}
flowy-sys = {path = "../flowy-sys"} flowy-sys = {path = "../flowy-sys"}
flowy-sdk = {path = "../flowy-sdk"} flowy-sdk = {path = "../flowy-sdk"}
flowy-log = {path = "../flowy-log"}
#[features]
#use_serde = ["bincode"]
#use_protobuf= ["protobuf"]

View File

@ -3,35 +3,41 @@ mod c;
use crate::c::forget_rust; use crate::c::forget_rust;
use flowy_sdk::*; use flowy_sdk::*;
use flowy_sys::prelude::*; 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] #[no_mangle]
pub extern "C" fn init_sdk(path: *mut c_char) -> i64 { pub extern "C" fn init_sdk(path: *mut c_char) -> i64 {
let c_str: &CStr = unsafe { CStr::from_ptr(path) }; let c_str: &CStr = unsafe { CStr::from_ptr(path) };
let path: &str = c_str.to_str().unwrap(); let path: &str = c_str.to_str().unwrap();
println!("{}", path); FlowySDK::init_log();
FlowySDK::init(path);
return 1; return 1;
} }
#[derive(serde::Deserialize)]
pub struct FFICommand { pub struct FFICommand {
event: String, event: String,
payload: Vec<u8>, payload: Vec<u8>,
} }
impl FFICommand { impl FFICommand {
pub fn from_bytes(bytes: Vec<u8>) -> Self { unimplemented!() } pub fn from_bytes(bytes: Vec<u8>) -> Self {
let command: FFICommand = serde_json::from_slice(&bytes).unwrap();
command
}
pub fn from_u8_pointer(pointer: *const u8, len: usize) -> Self { pub fn from_u8_pointer(pointer: *const u8, len: usize) -> Self {
let bytes = unsafe { std::slice::from_raw_parts(pointer, len) }.to_vec(); let bytes = unsafe { std::slice::from_raw_parts(pointer, len) }.to_vec();
unimplemented!() FFICommand::from_bytes(bytes)
} }
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn async_command(port: i64, input: *const u8, len: usize) { pub extern "C" fn async_command(port: i64, input: *const u8, len: usize) {
let FFICommand { event, payload } = FFICommand::from_u8_pointer(input, len); 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); 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); async_send(request);
spawn_future(async { vec![] }, 123);
} }
#[no_mangle] #[no_mangle]
@ -48,3 +55,20 @@ pub extern "C" fn sync_command(input: *const u8, len: usize) -> *const u8 { unim
#[inline(never)] #[inline(never)]
#[no_mangle] #[no_mangle]
pub extern "C" fn link_me_please() {} pub extern "C" fn link_me_please() {}
#[inline(always)]
fn spawn_future<F>(future: F, port: i64)
where
F: Future<Output = Vec<u8>> + 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 😡");
// }
// }
}

View File

@ -6,9 +6,10 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
tracing = { version = "0.1", features = ["log"] } tracing = { version = "0.1" }
tracing-log = "0.1.1" tracing-log = { version = "0.1.1", features = ["env_logger"]}
tracing-futures = "0.2.4" tracing-futures = "0.2.4"
tracing-subscriber = { version = "0.2.12", features = ["registry", "env-filter"] } tracing-subscriber = { version = "0.2.12", features = ["registry", "env-filter"] }
tracing-bunyan-formatter = "0.2.2" tracing-bunyan-formatter = "0.2.2"
tracing-appender = "0.1"
log = "0.4.14" log = "0.4.14"

View File

@ -4,10 +4,13 @@ use tracing_log::LogTracer;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter}; use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
pub fn init_log(name: &str, env_filter: &str) -> std::result::Result<(), String> { 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 formatting_layer = BunyanFormattingLayer::new(name.to_owned(), std::io::stdout);
let subscriber = tracing_subscriber::fmt() let subscriber = tracing_subscriber::fmt()
.with_target(false) .with_target(false)
.with_writer(std::io::stdout)
.with_thread_ids(false) .with_thread_ids(false)
.with_target(false) .with_target(false)
.compact() .compact()

View File

@ -3,51 +3,22 @@ pub use module::*;
use flowy_sys::prelude::*; use flowy_sys::prelude::*;
use module::build_modules; use module::build_modules;
use std::cell::RefCell;
pub struct FlowySDK {} pub struct FlowySDK {}
impl FlowySDK { impl FlowySDK {
pub fn init(path: &str) { pub fn init_log() { flowy_log::init_log("flowy", "Debug").unwrap(); }
flowy_log::init_log("flowy", "Debug").unwrap();
log::info!("🔥🔥🔥 System start running"); pub fn init(path: &str) {
match init_system(build_modules()).run() { log::info!("🔥 System start running");
Ok(_) => {}, log::debug!("🔥 Root path: {}", path);
Err(e) => log::error!("System run fail with error: {:?}", e), EventDispatch::construct(|| build_modules());
}
} }
} }
pub fn init_system(modules: Vec<Module>) -> SystemRunner { pub async fn async_send(data: DispatchRequest<i64>) -> Result<EventResponse, SystemError> {
FlowySystem::construct( EventDispatch::async_send(data).await
|| modules,
|module_map, runtime| {
let mut sender = Sender::<i64>::new(module_map.clone());
runtime.spawn(SenderRunner::new(module_map, sender.take_rx()));
SENDER.with(|cell| {
*cell.borrow_mut() = Some(sender);
});
},
)
} }
thread_local!( pub fn sync_send(data: DispatchRequest<i64>) -> Result<EventResponse, SystemError> {
static SENDER: RefCell<Option<Sender<i64>>> = RefCell::new(None); EventDispatch::sync_send(data)
);
pub fn sync_send(data: SenderRequest<i64>) -> EventResponse {
SENDER.with(|cell| match &*cell.borrow() {
Some(stream) => stream.sync_send(data),
None => panic!(""),
})
}
pub fn async_send(data: SenderRequest<i64>) {
SENDER.with(|cell| match &*cell.borrow() {
Some(stream) => {
stream.async_send(data);
},
None => panic!(""),
});
} }

View File

@ -8,30 +8,18 @@ use std::{
}; };
static INIT: Once = Once::new(); static INIT: Once = Once::new();
pub fn run_test_system<F>(f: F) #[allow(dead_code)]
where
F: FnOnce() + 'static, pub fn init_system() {
{
INIT.call_once(|| { INIT.call_once(|| {
flowy_log::init_log("flowy", "Debug").unwrap(); FlowySDK::init_log();
}); });
let mut runner = init_system(build_modules()); FlowySDK::init("123");
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),
}
} }
pub struct FlowySDKTester { pub struct FlowySDKTester {
request: SenderRequest<i64>, request: DispatchRequest<i64>,
callback: Option<BoxStreamCallback<i64>>,
} }
impl FlowySDKTester { impl FlowySDKTester {
@ -40,8 +28,7 @@ impl FlowySDKTester {
E: Eq + Hash + Debug + Clone + Display, E: Eq + Hash + Debug + Clone + Display,
{ {
Self { Self {
request: SenderRequest::new(1, event), request: DispatchRequest::new(1, event),
callback: None,
} }
} }
@ -65,21 +52,17 @@ impl FlowySDKTester {
self self
} }
#[allow(dead_code)] pub async fn async_send(self) -> EventResponse {
pub fn callback<F>(mut self, callback: F) -> Self init_system();
where let resp = async_send(self.request).await.unwrap();
F: FnOnce(i64, EventResponse) + 'static + Send + Sync, dbg!(&resp);
{ resp
self.request = self.request.callback(|config, response| {
dbg!(&response);
callback(config, response);
});
self
} }
pub fn run(self) { pub fn sync_send(self) -> EventResponse {
run_test_system(move || { init_system();
async_send(self.request); let resp = sync_send(self.request).unwrap();
}); dbg!(&resp);
resp
} }
} }

View File

@ -1,6 +1,7 @@
use super::helper::*; use super::helper::*;
use flowy_sys::prelude::*; use flowy_sys::prelude::*;
use flowy_user::prelude::*; use flowy_user::prelude::*;
use tokio::time::{sleep, Duration};
#[test] #[test]
fn auth_check_no_payload() { fn auth_check_no_payload() {
@ -8,19 +9,14 @@ fn auth_check_no_payload() {
assert_eq!(resp.status, StatusCode::Err); assert_eq!(resp.status, StatusCode::Err);
}; };
FlowySDKTester::new(AuthCheck).callback(callback).run(); let resp = FlowySDKTester::new(AuthCheck).sync_send();
} }
#[test] #[tokio::test]
fn auth_check_with_user_name_email_payload() { async fn auth_check_with_user_name_email_payload() {
let callback = |_, resp: EventResponse| {
assert_eq!(resp.status, StatusCode::Ok);
};
let user_data = UserData::new("jack".to_owned(), "helloworld@gmail.com".to_owned()); let user_data = UserData::new("jack".to_owned(), "helloworld@gmail.com".to_owned());
FlowySDKTester::new(AuthCheck) FlowySDKTester::new(AuthCheck)
.bytes_payload(user_data) .bytes_payload(user_data)
.callback(callback) .sync_send();
.run();
} }

View File

@ -10,7 +10,7 @@ derive_more = {version = "0.99", features = ["display"]}
flowy-sys = { path = "../flowy-sys" } flowy-sys = { path = "../flowy-sys" }
flowy-log = { path = "../flowy-log" } flowy-log = { path = "../flowy-log" }
tracing = { version = "0.1", features = ["log"] } tracing = { version = "0.1", features = ["log"] }
bytes = "0.5" bytes = "1.0"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
validator = "0.12.0" validator = "0.12.0"
rand = { version = "0.8", features=["std_rng"] } rand = { version = "0.8", features=["std_rng"] }

View File

@ -22,7 +22,7 @@ mod tests {
use super::*; use super::*;
use claim::assert_err; use claim::assert_err;
use fake::{faker::internet::en::SafeEmail, Fake}; use fake::{faker::internet::en::SafeEmail, Fake};
use quickcheck::Gen;
#[test] #[test]
fn empty_string_is_rejected() { fn empty_string_is_rejected() {

View File

@ -1,5 +1,5 @@
use crate::domain::{User, UserEmail, UserName}; use crate::domain::{User, UserEmail, UserName};
use bytes::Bytes;
use flowy_sys::prelude::{response_ok, Data, FromBytes, ResponseResult, SystemError, ToBytes}; use flowy_sys::prelude::{response_ok, Data, FromBytes, ResponseResult, SystemError, ToBytes};
use std::convert::TryInto; use std::convert::TryInto;
@ -13,7 +13,7 @@ use std::convert::TryInto;
) )
)] )]
pub async fn user_check(data: Data<UserData>) -> ResponseResult<UserStatus, String> { pub async fn user_check(data: Data<UserData>) -> ResponseResult<UserStatus, String> {
let user: User = data.into_inner().try_into()?; let _user: User = data.into_inner().try_into()?;
response_ok(UserStatus { is_login: false }) response_ok(UserStatus { is_login: false })
} }
@ -24,7 +24,7 @@ pub struct UserStatus {
} }
impl FromBytes for UserData { impl FromBytes for UserData {
fn parse_from_bytes(bytes: &Vec<u8>) -> Result<UserData, SystemError> { unimplemented!() } fn parse_from_bytes(_bytes: &Vec<u8>) -> Result<UserData, SystemError> { unimplemented!() }
} }
impl ToBytes for UserStatus { impl ToBytes for UserStatus {