diff --git a/rust-lib/flowy-sys/Cargo.toml b/rust-lib/flowy-sys/Cargo.toml index 88cc9549b1..23728a4d63 100644 --- a/rust-lib/flowy-sys/Cargo.toml +++ b/rust-lib/flowy-sys/Cargo.toml @@ -13,7 +13,7 @@ futures-channel = "0.3.15" futures = "0.3.15" futures-util = "0.3.15" bytes = "0.5" - +tokio = { version = "1", features = ["sync"] } [dev-dependencies] tokio = { version = "1", features = ["full"] } \ No newline at end of file diff --git a/rust-lib/flowy-sys/src/data/container.rs b/rust-lib/flowy-sys/src/data/container.rs index 4fb5e29df2..2d512c0586 100644 --- a/rust-lib/flowy-sys/src/data/container.rs +++ b/rust-lib/flowy-sys/src/data/container.rs @@ -1,8 +1,6 @@ use std::{ any::{Any, TypeId}, collections::HashMap, - fmt, - mem, }; #[derive(Default)] @@ -23,6 +21,22 @@ impl DataContainer { .insert(TypeId::of::(), Box::new(val)) .and_then(downcast_owned) } + + pub fn remove(&mut self) -> Option { self.map.remove(&TypeId::of::()).and_then(downcast_owned) } + + pub fn get(&self) -> Option<&T> { + self.map.get(&TypeId::of::()).and_then(|boxed| boxed.downcast_ref()) + } + + pub fn get_mut(&mut self) -> Option<&mut T> { + self.map + .get_mut(&TypeId::of::()) + .and_then(|boxed| boxed.downcast_mut()) + } + + pub fn contains(&self) -> bool { self.map.contains_key(&TypeId::of::()) } + + pub fn extend(&mut self, other: DataContainer) { self.map.extend(other.map); } } fn downcast_owned(boxed: Box) -> Option { boxed.downcast().ok().map(|boxed| *boxed) } diff --git a/rust-lib/flowy-sys/src/data/mod.rs b/rust-lib/flowy-sys/src/data/mod.rs index 13791c98c2..18581c4bb7 100644 --- a/rust-lib/flowy-sys/src/data/mod.rs +++ b/rust-lib/flowy-sys/src/data/mod.rs @@ -1,2 +1 @@ pub mod container; -pub mod payload; diff --git a/rust-lib/flowy-sys/src/error.rs b/rust-lib/flowy-sys/src/error.rs deleted file mode 100644 index b245716630..0000000000 --- a/rust-lib/flowy-sys/src/error.rs +++ /dev/null @@ -1,150 +0,0 @@ -use crate::response::{FlowyResponse, StatusCode}; -use std::cell::RefCell; -use std::fmt; - -pub struct Error { - inner: Box, -} - -impl Error { - pub fn as_handler_error(&self) -> &dyn HandlerError { - self.inner.as_ref() - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(&self.inner, f) - } -} - -impl fmt::Debug for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", &self.inner) - } -} - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - None - } - - fn cause(&self) -> Option<&dyn std::error::Error> { - None - } -} - -impl From for FlowyResponse { - fn from(err: Error) -> Self { - FlowyResponse::from_error(err) - } -} - -impl From for Error { - fn from(res: FlowyResponse) -> Error { - InternalError::from_response("", res).into() - } -} - -/// `Error` for any error that implements `ResponseError` -impl From for Error { - fn from(err: T) -> Error { - Error { - inner: Box::new(err), - } - } -} - -pub trait HandlerError: fmt::Debug + fmt::Display { - fn status_code(&self) -> StatusCode; - - fn as_response(&self) -> FlowyResponse { - let resp = FlowyResponse::new(self.status_code()); - resp - } -} - -pub struct InternalError { - inner: T, - status: InternalErrorType, -} - -enum InternalErrorType { - Status(StatusCode), - Response(RefCell>), -} - -impl InternalError { - pub fn new(inner: T, status: StatusCode) -> Self { - InternalError { - inner, - status: InternalErrorType::Status(status), - } - } - - pub fn from_response(inner: T, response: FlowyResponse) -> Self { - InternalError { - inner, - status: InternalErrorType::Response(RefCell::new(Some(response))), - } - } -} - -impl fmt::Debug for InternalError -where - T: fmt::Debug + 'static, -{ - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Debug::fmt(&self.inner, f) - } -} - -impl fmt::Display for InternalError -where - T: fmt::Display + 'static, -{ - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(&self.inner, f) - } -} - -impl HandlerError for InternalError -where - T: fmt::Debug + fmt::Display + 'static, -{ - fn status_code(&self) -> StatusCode { - match self.status { - InternalErrorType::Status(st) => st, - InternalErrorType::Response(ref resp) => { - if let Some(resp) = resp.borrow().as_ref() { - resp.status.clone() - } else { - StatusCode::Error - } - } - } - } - - fn as_response(&self) -> FlowyResponse { - panic!() - // match self.status { - // InternalErrorType::Status(st) => { - // let mut res = Response::new(st); - // let mut buf = BytesMut::new(); - // let _ = write!(Writer(&mut buf), "{}", self); - // res.headers_mut().insert( - // header::CONTENT_TYPE, - // header::HeaderValue::from_static("text/plain; charset=utf-8"), - // ); - // res.set_body(Body::from(buf)) - // } - // InternalErrorType::Response(ref resp) => { - // if let Some(resp) = resp.borrow_mut().take() { - // resp - // } else { - // Response::new(StatusCode::INTERNAL_SERVER_ERROR) - // } - // } - // } - } -} diff --git a/rust-lib/flowy-sys/src/error/error.rs b/rust-lib/flowy-sys/src/error/error.rs new file mode 100644 index 0000000000..e545971f61 --- /dev/null +++ b/rust-lib/flowy-sys/src/error/error.rs @@ -0,0 +1,38 @@ +use crate::response::{FlowyResponse, StatusCode}; +use std::{cell::RefCell, fmt}; + +pub trait Error: fmt::Debug + fmt::Display { + fn status_code(&self) -> StatusCode; + + fn as_response(&self) -> FlowyResponse { FlowyResponse::new(self.status_code()) } +} + +impl From for SystemError { + fn from(err: T) -> SystemError { SystemError { inner: Box::new(err) } } +} + +pub struct SystemError { + inner: Box, +} + +impl SystemError { + pub fn inner_error(&self) -> &dyn Error { self.inner.as_ref() } +} + +impl fmt::Display for SystemError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.inner, f) } +} + +impl fmt::Debug for SystemError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &self.inner) } +} + +impl std::error::Error for SystemError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } + + fn cause(&self) -> Option<&dyn std::error::Error> { None } +} + +impl From for FlowyResponse { + fn from(err: SystemError) -> Self { err.inner_error().as_response() } +} diff --git a/rust-lib/flowy-sys/src/error/mod.rs b/rust-lib/flowy-sys/src/error/mod.rs new file mode 100644 index 0000000000..3925f93ff7 --- /dev/null +++ b/rust-lib/flowy-sys/src/error/mod.rs @@ -0,0 +1,3 @@ +mod error; + +pub use error::*; diff --git a/rust-lib/flowy-sys/src/handler/dispatch.rs b/rust-lib/flowy-sys/src/handler/dispatch.rs deleted file mode 100644 index 6179bd7bbd..0000000000 --- a/rust-lib/flowy-sys/src/handler/dispatch.rs +++ /dev/null @@ -1,65 +0,0 @@ -use crate::{ - error::Error, - handler::{boxed, BoxServiceFactory, Handler, HandlerService}, - request::FromRequest, - response::Responder, - service::{ServiceRequest, ServiceResponse}, -}; - -use std::{ - future::Future, - pin::Pin, - task::{Context, Poll}, -}; - -pub struct HandlerDispatch { - service: BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>, -} - -impl HandlerDispatch { - pub fn new(handler: H) -> Self - where - H: Handler, - T: FromRequest + 'static, - R: Future + 'static, - R::Output: Responder + 'static, - { - HandlerDispatch { - service: boxed::factory(HandlerService::new(handler)), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{payload::Payload, request::FlowyRequest, service::ServiceFactory}; - - pub async fn no_params() -> String { - println!("no params"); - "hello".to_string() - } - #[tokio::test] - async fn extract_no_params() { - let dispatch = HandlerDispatch::new(no_params); - let resp = response_from_dispatch(dispatch).await; - } - - pub async fn one_params(s: String) -> String { - println!("one params"); - "hello".to_string() - } - - #[tokio::test] - async fn extract_one_params() { - let dispatch = HandlerDispatch::new(one_params); - let resp = response_from_dispatch(dispatch).await; - } - - async fn response_from_dispatch(dispatch: HandlerDispatch) -> ServiceResponse { - let service = dispatch.service.new_service(()).await.unwrap(); - let service_request = ServiceRequest::new(FlowyRequest::default(), Payload::None); - let resp = service.call(service_request).await.unwrap(); - resp - } -} diff --git a/rust-lib/flowy-sys/src/lib.rs b/rust-lib/flowy-sys/src/lib.rs index 1502ae6655..931712c2c2 100644 --- a/rust-lib/flowy-sys/src/lib.rs +++ b/rust-lib/flowy-sys/src/lib.rs @@ -1,7 +1,6 @@ mod data; mod error; -mod handler; -mod payload; +mod module; mod request; mod response; mod service; diff --git a/rust-lib/flowy-sys/src/module/data.rs b/rust-lib/flowy-sys/src/module/data.rs new file mode 100644 index 0000000000..0c07d1b044 --- /dev/null +++ b/rust-lib/flowy-sys/src/module/data.rs @@ -0,0 +1,36 @@ +use crate::{ + error::SystemError, + request::{payload::Payload, FlowyRequest, FromRequest}, + util::ready::Ready, +}; +use std::{ops::Deref, sync::Arc}; + +pub struct ModuleData(Arc); + +impl ModuleData { + pub fn new(data: T) -> Self { ModuleData(Arc::new(data)) } + + pub fn get_ref(&self) -> &T { self.0.as_ref() } +} + +impl Deref for ModuleData { + type Target = Arc; + + fn deref(&self) -> &Arc { &self.0 } +} + +impl Clone for ModuleData { + fn clone(&self) -> ModuleData { ModuleData(self.0.clone()) } +} + +impl From> for ModuleData { + fn from(arc: Arc) -> Self { ModuleData(arc) } +} + +impl FromRequest for ModuleData { + type Error = SystemError; + type Future = Ready>; + + #[inline] + fn from_request(req: &FlowyRequest, _: &mut Payload) -> Self::Future { unimplemented!() } +} diff --git a/rust-lib/flowy-sys/src/module/mod.rs b/rust-lib/flowy-sys/src/module/mod.rs new file mode 100644 index 0000000000..b37a3cf92a --- /dev/null +++ b/rust-lib/flowy-sys/src/module/mod.rs @@ -0,0 +1,5 @@ +mod data; +mod module; + +pub use data::*; +pub use module::*; diff --git a/rust-lib/flowy-sys/src/module/module.rs b/rust-lib/flowy-sys/src/module/module.rs new file mode 100644 index 0000000000..86ec74dbf8 --- /dev/null +++ b/rust-lib/flowy-sys/src/module/module.rs @@ -0,0 +1,115 @@ +use crate::{ + data::container::DataContainer, + error::SystemError, + module::ModuleData, + request::FromRequest, + response::Responder, + service::{BoxService, Handler, Service, ServiceFactory, ServiceRequest, ServiceResponse}, +}; + +use futures_core::{future::LocalBoxFuture, ready}; +use std::{ + collections::HashMap, + future::Future, + hash::Hash, + marker::PhantomData, + pin::Pin, + rc::Rc, + task::{Context, Poll}, +}; +use tokio::sync::{mpsc, mpsc::UnboundedReceiver}; + +use crate::{ + request::{payload::Payload, FlowyRequest}, + service::{factory, BoxServiceFactory, HandlerService}, +}; +use pin_project::pin_project; +use std::fmt::Debug; + +pub type Command = String; +pub type ModuleServiceFactory = BoxServiceFactory<(), ServiceRequest, ServiceResponse, SystemError>; + +#[pin_project::pin_project] +pub struct Module { + name: String, + data: DataContainer, + fact_map: HashMap, + cmd_rx: UnboundedReceiver, +} + +impl Module { + pub fn new(cmd_rx: UnboundedReceiver) -> Self { + Self { + name: "".to_owned(), + data: DataContainer::new(), + fact_map: HashMap::new(), + cmd_rx, + } + } + + pub fn name(mut self, s: &str) -> Self { + self.name = s.to_owned(); + self + } + + pub fn data(mut self, data: D) -> Self { + let module_data = ModuleData::new(data); + self.data.insert(module_data); + self + } + + pub fn event(mut self, command: Command, handler: H) -> Self + where + H: Handler, + T: FromRequest + 'static, + R: Future + 'static, + R::Output: Responder + 'static, + { + self.fact_map.insert(command, factory(HandlerService::new(handler))); + self + } +} + +impl Future for Module { + type Output = (); + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + loop { + match ready!(Pin::new(&mut self.cmd_rx).poll_recv(cx)) { + None => return Poll::Ready(()), + Some(request) => match self.fact_map.get(request.get_id()) { + Some(factory) => { + let service_future = factory.new_service(()); + tokio::task::spawn_local(ModuleServiceFuture { + request, + service_future, + }); + }, + None => {}, + }, + } + } + } +} + +#[pin_project(project = HandlerServiceProj)] +pub struct ModuleServiceFuture { + request: FlowyRequest, + #[pin] + service_future: LocalBoxFuture<'static, Result>, +} + +impl Future for ModuleServiceFuture { + type Output = (); + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { unimplemented!() } +} + +impl ServiceFactory for Module { + type Response = ServiceResponse; + type Error = SystemError; + type Service = BoxService; + type Config = (); + type Future = LocalBoxFuture<'static, Result>; + + fn new_service(&self, cfg: Self::Config) -> Self::Future { unimplemented!() } +} diff --git a/rust-lib/flowy-sys/src/request/mod.rs b/rust-lib/flowy-sys/src/request/mod.rs index 3edd9a21fa..cab7b63efc 100644 --- a/rust-lib/flowy-sys/src/request/mod.rs +++ b/rust-lib/flowy-sys/src/request/mod.rs @@ -1,3 +1,4 @@ -mod request; - pub use request::*; + +pub mod payload; +mod request; diff --git a/rust-lib/flowy-sys/src/data/payload.rs b/rust-lib/flowy-sys/src/request/payload.rs similarity index 100% rename from rust-lib/flowy-sys/src/data/payload.rs rename to rust-lib/flowy-sys/src/request/payload.rs diff --git a/rust-lib/flowy-sys/src/request/request.rs b/rust-lib/flowy-sys/src/request/request.rs index 13f5e5b597..a0a839708c 100644 --- a/rust-lib/flowy-sys/src/request/request.rs +++ b/rust-lib/flowy-sys/src/request/request.rs @@ -1,18 +1,26 @@ -use crate::{ - error::Error, - payload::Payload, - util::ready::{ready, Ready}, -}; use std::future::Future; -pub struct FlowyRequest {} +use crate::{ + error::SystemError, + request::payload::Payload, + util::ready::{ready, Ready}, +}; +use std::hash::Hash; + +pub struct FlowyRequest { + id: String, +} + +impl FlowyRequest { + pub fn get_id(&self) -> &str { &self.id } +} impl std::default::Default for FlowyRequest { - fn default() -> Self { Self {} } + fn default() -> Self { Self { id: "".to_string() } } } pub trait FromRequest: Sized { - type Error: Into; + type Error: Into; type Future: Future>; fn from_request(req: &FlowyRequest, payload: &mut Payload) -> Self::Future; @@ -20,16 +28,16 @@ pub trait FromRequest: Sized { #[doc(hidden)] impl FromRequest for () { - type Error = Error; - type Future = Ready>; + type Error = SystemError; + type Future = Ready>; - fn from_request(req: &FlowyRequest, payload: &mut Payload) -> Self::Future { ready(Ok(())) } + fn from_request(_req: &FlowyRequest, _payload: &mut Payload) -> Self::Future { ready(Ok(())) } } #[doc(hidden)] impl FromRequest for String { - type Error = Error; - type Future = Ready>; + type Error = SystemError; + type Future = Ready>; - fn from_request(req: &FlowyRequest, payload: &mut Payload) -> Self::Future { ready(Ok("".to_string())) } + fn from_request(_req: &FlowyRequest, _payload: &mut Payload) -> Self::Future { ready(Ok("".to_string())) } } diff --git a/rust-lib/flowy-sys/src/response/builder.rs b/rust-lib/flowy-sys/src/response/builder.rs index 6fccbb70bf..c5c24df334 100644 --- a/rust-lib/flowy-sys/src/response/builder.rs +++ b/rust-lib/flowy-sys/src/response/builder.rs @@ -1,19 +1,19 @@ -use crate::error::Error; -use crate::response::{FlowyResponse, ResponseData, StatusCode}; +use crate::{ + error::SystemError, + response::{data::ResponseData, FlowyResponse, StatusCode}, +}; macro_rules! static_response { ($name:ident, $status:expr) => { #[allow(non_snake_case, missing_docs)] - pub fn $name() -> FlowyResponseBuilder { - FlowyResponseBuilder::new($status) - } + pub fn $name() -> FlowyResponseBuilder { FlowyResponseBuilder::new($status) } }; } pub struct FlowyResponseBuilder { pub data: T, pub status: StatusCode, - pub error: Option, + pub error: Option, } impl FlowyResponseBuilder { @@ -30,7 +30,7 @@ impl FlowyResponseBuilder { self } - pub fn error(mut self, error: Option) -> Self { + pub fn error(mut self, error: Option) -> Self { self.error = error; self } diff --git a/rust-lib/flowy-sys/src/response/data.rs b/rust-lib/flowy-sys/src/response/data.rs new file mode 100644 index 0000000000..87b2b12762 --- /dev/null +++ b/rust-lib/flowy-sys/src/response/data.rs @@ -0,0 +1,12 @@ +pub enum ResponseData { + Bytes(Vec), + None, +} + +impl std::convert::Into for String { + fn into(self) -> ResponseData { ResponseData::Bytes(self.into_bytes()) } +} + +impl std::convert::Into for &str { + fn into(self) -> ResponseData { self.to_string().into() } +} diff --git a/rust-lib/flowy-sys/src/response/mod.rs b/rust-lib/flowy-sys/src/response/mod.rs index c0992fea73..b3f464fbb4 100644 --- a/rust-lib/flowy-sys/src/response/mod.rs +++ b/rust-lib/flowy-sys/src/response/mod.rs @@ -1,7 +1,8 @@ -mod builder; -mod responder; -mod response; - pub use builder::*; pub use responder::*; pub use response::*; + +mod builder; +pub mod data; +mod responder; +mod response; diff --git a/rust-lib/flowy-sys/src/response/response.rs b/rust-lib/flowy-sys/src/response/response.rs index a9fd41901e..14bc6e1e66 100644 --- a/rust-lib/flowy-sys/src/response/response.rs +++ b/rust-lib/flowy-sys/src/response/response.rs @@ -1,9 +1,8 @@ use crate::{ - error::Error, + error::SystemError, request::FlowyRequest, - response::{FlowyResponseBuilder, Responder}, + response::{data::ResponseData, Responder}, }; -use std::future::Future; #[derive(Clone, Copy)] pub enum StatusCode { @@ -11,15 +10,10 @@ pub enum StatusCode { Error, } -pub enum ResponseData { - Bytes(Vec), - None, -} - pub struct FlowyResponse { pub data: T, pub status: StatusCode, - pub error: Option, + pub error: Option, } impl FlowyResponse { @@ -30,32 +24,9 @@ impl FlowyResponse { error: None, } } - - pub fn success() -> Self { - FlowyResponse { - data: ResponseData::None, - status: StatusCode::Success, - error: None, - } - } - - #[inline] - pub fn from_error(error: Error) -> FlowyResponse { - let mut resp = error.as_handler_error().as_response(); - resp.error = Some(error); - resp - } } impl Responder for FlowyResponse { #[inline] fn respond_to(self, _: &FlowyRequest) -> FlowyResponse { self } } - -impl std::convert::Into for String { - fn into(self) -> ResponseData { ResponseData::Bytes(self.into_bytes()) } -} - -impl std::convert::Into for &str { - fn into(self) -> ResponseData { self.to_string().into() } -} diff --git a/rust-lib/flowy-sys/src/handler/boxed.rs b/rust-lib/flowy-sys/src/service/boxed.rs similarity index 70% rename from rust-lib/flowy-sys/src/handler/boxed.rs rename to rust-lib/flowy-sys/src/service/boxed.rs index cfe06f562d..9aa27d8e1c 100644 --- a/rust-lib/flowy-sys/src/handler/boxed.rs +++ b/rust-lib/flowy-sys/src/service/boxed.rs @@ -1,24 +1,11 @@ use crate::{ - error::Error, - payload::Payload, - request::FlowyRequest, - response::{FlowyResponse, Responder}, service::{Service, ServiceFactory, ServiceRequest, ServiceResponse}, util::ready::*, }; -use futures_core::ready; -use paste::paste; -use pin_project::pin_project; -use std::{ - future::Future, - marker::PhantomData, - pin::Pin, - task::{Context, Poll}, -}; use futures_core::future::LocalBoxFuture; -pub fn factory(factory: SF) -> BoxServiceFactory +pub fn factory(factory: SF) -> BoxServiceFactory where SF: ServiceFactory + 'static, Req: 'static, @@ -26,38 +13,34 @@ where SF::Service: 'static, SF::Future: 'static, SF::Error: 'static, - SF::InitError: 'static, { BoxServiceFactory(Box::new(FactoryWrapper(factory))) } -pub struct BoxServiceFactory(Inner); -impl ServiceFactory for BoxServiceFactory +pub struct BoxServiceFactory(Inner); +impl ServiceFactory for BoxServiceFactory where Req: 'static, Res: 'static, Err: 'static, - InitErr: 'static, { type Response = Res; type Error = Err; type Service = BoxService; - type InitError = InitErr; - type Config = C; - type Future = LocalBoxFuture<'static, Result>; + type Config = Cfg; + type Future = LocalBoxFuture<'static, Result>; - fn new_service(&self, cfg: C) -> Self::Future { self.0.new_service(cfg) } + fn new_service(&self, cfg: Cfg) -> Self::Future { self.0.new_service(cfg) } } -type Inner = Box< +type Inner = Box< dyn ServiceFactory< Req, - Config = C, + Config = Cfg, Response = Res, Error = Err, - InitError = InitErr, Service = BoxService, - Future = LocalBoxFuture<'static, Result, InitErr>>, + Future = LocalBoxFuture<'static, Result, Err>>, >, >; @@ -106,13 +89,12 @@ where struct FactoryWrapper(SF); -impl ServiceFactory for FactoryWrapper +impl ServiceFactory for FactoryWrapper where Req: 'static, Res: 'static, Err: 'static, - InitErr: 'static, - SF: ServiceFactory, + SF: ServiceFactory, SF::Future: 'static, SF::Service: 'static, >::Future: 'static, @@ -120,12 +102,11 @@ where type Response = Res; type Error = Err; type Service = BoxService; - type InitError = InitErr; type Config = Cfg; - type Future = LocalBoxFuture<'static, Result>; + type Future = LocalBoxFuture<'static, Result>; fn new_service(&self, cfg: Cfg) -> Self::Future { let f = self.0.new_service(cfg); - Box::pin(async { f.await.map(|s| Box::new(ServiceWrapper::new(s)) as _) }) + Box::pin(async { f.await.map(|s| Box::new(ServiceWrapper::new(s)) as Self::Service) }) } } diff --git a/rust-lib/flowy-sys/src/handler/handler.rs b/rust-lib/flowy-sys/src/service/handler.rs similarity index 85% rename from rust-lib/flowy-sys/src/handler/handler.rs rename to rust-lib/flowy-sys/src/service/handler.rs index f945756e54..a695402677 100644 --- a/rust-lib/flowy-sys/src/handler/handler.rs +++ b/rust-lib/flowy-sys/src/service/handler.rs @@ -1,16 +1,20 @@ -use crate::error::Error; -use crate::payload::Payload; -use crate::request::{FlowyRequest, FromRequest}; -use crate::response::{FlowyResponse, Responder}; -use crate::service::{Service, ServiceFactory, ServiceRequest, ServiceResponse}; -use crate::util::ready::*; +use std::{ + future::Future, + marker::PhantomData, + pin::Pin, + task::{Context, Poll}, +}; + use futures_core::ready; -use paste::paste; use pin_project::pin_project; -use std::future::Future; -use std::marker::PhantomData; -use std::pin::Pin; -use std::task::{Context, Poll}; + +use crate::{ + error::SystemError, + request::{payload::Payload, FlowyRequest, FromRequest}, + response::{FlowyResponse, Responder}, + service::{Service, ServiceFactory, ServiceRequest, ServiceResponse}, + util::ready::*, +}; pub trait Handler: Clone + 'static where @@ -69,15 +73,12 @@ where R::Output: Responder, { type Response = ServiceResponse; - type Error = Error; + type Error = SystemError; type Service = Self; - type InitError = (); type Config = (); - type Future = Ready>; + type Future = Ready>; - fn new_service(&self, _: ()) -> Self::Future { - ready(Ok(self.clone())) - } + fn new_service(&self, _: ()) -> Self::Future { ready(Ok(self.clone())) } } impl Service for HandlerService @@ -88,7 +89,7 @@ where R::Output: Responder, { type Response = ServiceResponse; - type Error = Error; + type Error = SystemError; type Future = HandlerServiceFuture; fn call(&self, req: ServiceRequest) -> Self::Future { @@ -117,9 +118,7 @@ where R: Future, R::Output: Responder, { - // Error type in this future is a placeholder type. - // all instances of error must be converted to ServiceResponse and return in Ok. - type Output = Result; + type Output = Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { loop { @@ -130,20 +129,21 @@ where let fut = handle.call(item); let state = HandlerServiceFuture::Handle(fut, req.take()); self.as_mut().set(state); - } + }, Err(err) => { let req = req.take().unwrap(); - let res = FlowyResponse::from_error(err.into()); + let system_err: SystemError = err.into(); + let res: FlowyResponse = system_err.into(); return Poll::Ready(Ok(ServiceResponse::new(req, res))); - } + }, }; - } + }, HandlerServiceProj::Handle(fut, req) => { let res = ready!(fut.poll(cx)); let req = req.take().unwrap(); let res = res.respond_to(&req); return Poll::Ready(Ok(ServiceResponse::new(req, res))); - } + }, } } } @@ -175,7 +175,7 @@ macro_rules! tuple_from_req ({$tuple_type:ident, $(($n:tt, $T:ident)),+} => { #[allow(unused_parens)] impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+) { - type Error = Error; + type Error = SystemError; type Future = $tuple_type<$($T),+>; fn from_request(req: &FlowyRequest, payload: &mut Payload) -> Self::Future { @@ -196,7 +196,7 @@ macro_rules! tuple_from_req ({$tuple_type:ident, $(($n:tt, $T:ident)),+} => { impl<$($T: FromRequest),+> Future for $tuple_type<$($T),+> { - type Output = Result<($($T,)+), Error>; + type Output = Result<($($T,)+), SystemError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let mut this = self.project(); @@ -233,11 +233,10 @@ factory_tuple! { A B C D E } #[rustfmt::skip] mod m { use super::*; + tuple_from_req!(TupleFromRequest1, (0, A)); tuple_from_req!(TupleFromRequest2, (0, A), (1, B)); tuple_from_req!(TupleFromRequest3, (0, A), (1, B), (2, C)); tuple_from_req!(TupleFromRequest4, (0, A), (1, B), (2, C), (3, D)); tuple_from_req!(TupleFromRequest5, (0, A), (1, B), (2, C), (3, D), (4, E)); } - - diff --git a/rust-lib/flowy-sys/src/handler/mod.rs b/rust-lib/flowy-sys/src/service/mod.rs similarity index 64% rename from rust-lib/flowy-sys/src/handler/mod.rs rename to rust-lib/flowy-sys/src/service/mod.rs index 7962f5ec2e..0dbc217430 100644 --- a/rust-lib/flowy-sys/src/handler/mod.rs +++ b/rust-lib/flowy-sys/src/service/mod.rs @@ -1,7 +1,7 @@ mod boxed; -mod dispatch; mod handler; +mod service; pub use boxed::*; -pub use dispatch::*; pub use handler::*; +pub use service::*; diff --git a/rust-lib/flowy-sys/src/service.rs b/rust-lib/flowy-sys/src/service/service.rs similarity index 51% rename from rust-lib/flowy-sys/src/service.rs rename to rust-lib/flowy-sys/src/service/service.rs index fba1440353..f66e5ac50b 100644 --- a/rust-lib/flowy-sys/src/service.rs +++ b/rust-lib/flowy-sys/src/service/service.rs @@ -1,8 +1,10 @@ -use crate::payload::Payload; -use crate::request::FlowyRequest; -use crate::response::{FlowyResponse, Responder, ResponseData}; use std::future::Future; +use crate::{ + request::{payload::Payload, FlowyRequest}, + response::{data::ResponseData, FlowyResponse}, +}; + pub trait Service { type Response; type Error; @@ -11,13 +13,12 @@ pub trait Service { fn call(&self, req: Request) -> Self::Future; } -pub trait ServiceFactory { +pub trait ServiceFactory { type Response; type Error; - type Service: Service; - type InitError; + type Service: Service; type Config; - type Future: Future>; + type Future: Future>; fn new_service(&self, cfg: Self::Config) -> Self::Future; } @@ -28,17 +29,10 @@ pub struct ServiceRequest { } impl ServiceRequest { - - pub fn new(req: FlowyRequest, payload: Payload) -> Self { - Self { - req, payload, - } - } + pub fn new(req: FlowyRequest, payload: Payload) -> Self { Self { req, payload } } #[inline] - pub fn into_parts(self) -> (FlowyRequest, Payload) { - (self.req, self.payload) - } + pub fn into_parts(self) -> (FlowyRequest, Payload) { (self.req, self.payload) } } pub struct ServiceResponse { @@ -47,7 +41,5 @@ pub struct ServiceResponse { } impl ServiceResponse { - pub fn new(request: FlowyRequest, response: FlowyResponse) -> Self { - ServiceResponse { request, response } - } + pub fn new(request: FlowyRequest, response: FlowyResponse) -> Self { ServiceResponse { request, response } } }