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-user",
"flowy-ast",
"flowy-derive",
]
[profile.dev]

View File

@ -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"}
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 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<u8>,
}
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 {
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<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
[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"

View File

@ -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()

View File

@ -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<Module>) -> SystemRunner {
FlowySystem::construct(
|| 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);
});
},
)
pub async fn async_send(data: DispatchRequest<i64>) -> Result<EventResponse, SystemError> {
EventDispatch::async_send(data).await
}
thread_local!(
static SENDER: RefCell<Option<Sender<i64>>> = RefCell::new(None);
);
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!(""),
});
pub fn sync_send(data: DispatchRequest<i64>) -> Result<EventResponse, SystemError> {
EventDispatch::sync_send(data)
}

View File

@ -8,30 +8,18 @@ use std::{
};
static INIT: Once = Once::new();
pub fn run_test_system<F>(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<i64>,
callback: Option<BoxStreamCallback<i64>>,
request: DispatchRequest<i64>,
}
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<F>(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
}
}

View File

@ -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();
}

View File

@ -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"] }

View File

@ -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() {

View File

@ -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<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 })
}
@ -24,7 +24,7 @@ pub struct UserStatus {
}
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 {