add ToBytes and FromBytes trait, generic handle input&output params

This commit is contained in:
appflowy 2021-07-01 15:40:26 +08:00
parent 678dd84f93
commit 2d3e50c017
12 changed files with 87 additions and 77 deletions

View File

@ -22,6 +22,8 @@ protobuf = {version = "2.20.0"}
lazy_static = {version = "1.4.0"}
tokio = { version = "1", features = ["sync"] }
log = "0.4.14"
serde = { version = "1.0", features = ["derive"] }
serde_json = {version = "1.0"}
flowy-sys = {path = "../flowy-sys"}
flowy-sdk = {path = "../flowy-sdk"}

View File

@ -36,7 +36,7 @@ pub extern "C" fn async_command(port: i64, input: *const u8, len: usize) {
});
if !payload.is_empty() {
request = request.payload(Payload::Bytes(bytes));
request = request.payload(Payload::Bytes(payload));
}
async_send(request);

View File

@ -22,11 +22,11 @@ thread-id = "3.3.0"
lazy_static = "1.4.0"
dyn-clone = "1.0"
derivative = "2.2.0"
serde_json = {version = "1.0"}
serde = { version = "1.0", features = ["derive"] }
#optional crate
bincode = { version = "1.3", optional = true}
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = {version = "1.0", optional = true}
protobuf = {version = "2.24.1", optional = true}
[dev-dependencies]
@ -34,5 +34,5 @@ tokio = { version = "1", features = ["full"] }
futures-util = "0.3.15"
[features]
use_serde = ["bincode", "serde", "serde_json"]
use_serde = ["bincode"]
use_protobuf= ["protobuf"]

View File

@ -1,14 +1,12 @@
use crate::{
request::EventRequest,
response::{EventResponse, EventResponseBuilder, StatusCode},
response::{EventResponse, ResponseBuilder, StatusCode},
};
use dyn_clone::DynClone;
use serde::{Serialize, Serializer};
use std::{fmt, option::NoneError};
use tokio::sync::mpsc::error::SendError;
#[cfg(feature = "use_serde")]
use serde::{Serialize, Serializer};
pub trait Error: fmt::Debug + fmt::Display + DynClone {
fn status_code(&self) -> StatusCode;
@ -109,11 +107,10 @@ where
}
.into();
EventResponseBuilder::Err().error(error).build()
ResponseBuilder::Err().error(error).build()
}
}
#[cfg(feature = "use_serde")]
impl Serialize for SystemError {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where

View File

@ -1,3 +1,5 @@
mod error;
pub type ResponseResult<T, E> = std::result::Result<crate::request::Data<T>, E>;
pub use error::*;

View File

@ -8,6 +8,7 @@ use crate::{
util::ready::{ready, Ready},
};
use crate::response::{EventResponse, ResponseBuilder};
use futures_core::ready;
use std::{
fmt::Debug,
@ -105,24 +106,24 @@ where
}
}
pub struct In<T>(pub T);
pub struct Data<T>(pub T);
impl<T> In<T> {
impl<T> Data<T> {
pub fn into_inner(self) -> T { self.0 }
}
impl<T> ops::Deref for In<T> {
impl<T> ops::Deref for Data<T> {
type Target = T;
fn deref(&self) -> &T { &self.0 }
}
impl<T> ops::DerefMut for In<T> {
impl<T> ops::DerefMut for Data<T> {
fn deref_mut(&mut self) -> &mut T { &mut self.0 }
}
#[cfg(feature = "use_serde")]
impl<T> FromRequest for In<T>
impl<T> FromRequest for Data<T>
where
T: serde::de::DeserializeOwned + 'static,
{
@ -135,16 +136,20 @@ where
Payload::None => ready(Err(unexpected_none_payload(req))),
Payload::Bytes(bytes) => {
let data: T = bincode::deserialize(bytes).unwrap();
ready(Ok(In(data)))
ready(Ok(Data(data)))
},
}
}
}
#[cfg(feature = "use_protobuf")]
impl<T> FromRequest for In<T>
pub trait FromBytes: Sized {
fn parse_from_bytes(bytes: &Vec<u8>) -> Result<Self, SystemError>;
}
#[cfg(not(feature = "use_serde"))]
impl<T> FromRequest for Data<T>
where
T: ::protobuf::Message + 'static,
T: FromBytes + 'static,
{
type Error = SystemError;
type Future = Ready<Result<Self, SystemError>>;
@ -154,8 +159,8 @@ where
match payload {
Payload::None => ready(Err(unexpected_none_payload(req))),
Payload::Bytes(bytes) => {
let data: T = ::protobuf::Message::parse_from_bytes(bytes).unwrap();
ready(Ok(In(data)))
let data = T::parse_from_bytes(bytes).unwrap();
ready(Ok(Data(data)))
},
}
}

View File

@ -6,19 +6,19 @@ use crate::{
macro_rules! static_response {
($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)]
pub fn $name() -> EventResponseBuilder { EventResponseBuilder::new($status) }
pub fn $name() -> ResponseBuilder { ResponseBuilder::new($status) }
};
}
pub struct EventResponseBuilder<T = ResponseData> {
pub struct ResponseBuilder<T = ResponseData> {
pub data: T,
pub status: StatusCode,
pub error: Option<SystemError>,
}
impl EventResponseBuilder {
impl ResponseBuilder {
pub fn new(status: StatusCode) -> Self {
EventResponseBuilder {
ResponseBuilder {
data: ResponseData::None,
status,
error: None,

View File

@ -1,10 +1,9 @@
use bytes::{Buf, Bytes};
#[cfg(feature = "use_serde")]
use serde::{Deserialize, Serialize};
use std::{fmt, fmt::Formatter};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
// #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
pub enum ResponseData {
Bytes(Vec<u8>),
None,

View File

@ -1,7 +1,7 @@
use crate::{
error::SystemError,
request::EventRequest,
response::{EventResponse, EventResponseBuilder},
request::{Data, EventRequest},
response::{EventResponse, ResponseBuilder},
};
use bytes::Bytes;
use std::ops;
@ -14,7 +14,7 @@ macro_rules! impl_responder {
($res: ty) => {
impl Responder for $res {
fn respond_to(self, _: &EventRequest) -> EventResponse {
EventResponseBuilder::Ok().data(self).build()
ResponseBuilder::Ok().data(self).build()
}
}
};
@ -38,56 +38,46 @@ where
}
}
pub struct Out<T>(pub T);
impl<T> Out<T> {
pub fn into_inner(self) -> T { self.0 }
}
impl<T> ops::Deref for Out<T> {
type Target = T;
fn deref(&self) -> &T { &self.0 }
}
impl<T> ops::DerefMut for Out<T> {
fn deref_mut(&mut self) -> &mut T { &mut self.0 }
pub trait ToBytes {
fn into_bytes(self) -> Result<Vec<u8>, SystemError>;
}
#[cfg(feature = "use_serde")]
impl<T> Responder for Out<T>
impl<T> Responder for Data<T>
where
T: serde::Serialize,
{
fn respond_to(self, request: &EventRequest) -> EventResponse {
let bytes: Vec<u8> = bincode::serialize(&self.0).unwrap();
EventResponseBuilder::Ok().data(bytes).build()
}
}
#[cfg(feature = "use_serde")]
impl<T> std::convert::From<T> for Out<T>
where
T: serde::Serialize,
{
fn from(val: T) -> Self { Out(val) }
}
#[cfg(feature = "use_protobuf")]
impl<T> Responder for Out<T>
where
T: ::protobuf::Message,
{
fn respond_to(self, _request: &EventRequest) -> EventResponse {
let bytes: Vec<u8> = self.write_to_bytes().unwrap();
EventResponseBuilder::Ok().data(bytes).build()
let bytes: Vec<u8> = bincode::serialize(&self.0).unwrap();
ResponseBuilder::Ok().data(bytes).build()
}
}
#[cfg(feature = "use_protobuf")]
impl<T> std::convert::From<T> for Out<T>
#[cfg(feature = "use_serde")]
impl<T> std::convert::From<T> for Data<T>
where
T: ::protobuf::Message,
T: serde::Serialize,
{
fn from(val: T) -> Self { Out(val) }
fn from(val: T) -> Self { Data(val) }
}
#[cfg(not(feature = "use_serde"))]
impl<T> Responder for Data<T>
where
T: ToBytes,
{
fn respond_to(self, _request: &EventRequest) -> EventResponse {
match self.into_inner().into_bytes() {
Ok(bytes) => ResponseBuilder::Ok().data(bytes.to_vec()).build(),
Err(e) => e.into(),
}
}
}
#[cfg(not(feature = "use_serde"))]
impl<T> std::convert::From<T> for Data<T>
where
T: ToBytes,
{
fn from(val: T) -> Self { Data(val) }
}

View File

@ -4,12 +4,12 @@ use crate::{
response::{data::ResponseData, Responder},
};
#[cfg(feature = "use_serde")]
use crate::request::Data;
use serde::{Deserialize, Serialize, Serializer};
use std::{fmt, fmt::Formatter};
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
// #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
pub enum StatusCode {
Ok = 0,
Err = 1,
@ -17,7 +17,7 @@ pub enum StatusCode {
// serde user guide: https://serde.rs/field-attrs.html
#[derive(Debug, Clone)]
#[cfg_attr(feature = "use_serde", derive(Serialize))]
// #[cfg_attr(feature = "use_serde", derive(Serialize))]
pub struct EventResponse {
pub data: ResponseData,
pub status: StatusCode,
@ -79,3 +79,10 @@ where
ResponseData::None => serializer.serialize_str(""),
}
}
pub fn response_ok<T, E>(data: T) -> Result<Data<T>, E>
where
E: Into<SystemError>,
{
Ok(Data(data))
}

View File

@ -7,7 +7,7 @@ edition = "2018"
[dependencies]
derive_more = {version = "0.99", features = ["display"]}
flowy-sys = { path = "../flowy-sys", features = ["use_serde"] }
flowy-sys = { path = "../flowy-sys" }
flowy-log = { path = "../flowy-log" }
tracing = { version = "0.1", features = ["log"] }
bytes = "0.5"

View File

@ -1,6 +1,6 @@
use crate::domain::{User, UserEmail, UserName};
use bytes::Bytes;
use flowy_sys::prelude::{In, Out};
use flowy_sys::prelude::{response_ok, Data, FromBytes, ResponseResult, SystemError, ToBytes};
use std::convert::TryInto;
// tracing instrument 👉🏻 https://docs.rs/tracing/0.1.26/tracing/attr.instrument.html
@ -12,10 +12,10 @@ use std::convert::TryInto;
name = %data.name
)
)]
pub async fn user_check(data: In<UserData>) -> Result<Out<UserStatus>, String> {
pub async fn user_check(data: Data<UserData>) -> ResponseResult<UserStatus, String> {
let user: User = data.into_inner().try_into()?;
Ok(UserStatus { is_login: false }.into())
response_ok(UserStatus { is_login: false })
}
#[derive(serde::Serialize)]
@ -23,6 +23,14 @@ pub struct UserStatus {
is_login: bool,
}
impl FromBytes for UserData {
fn parse_from_bytes(bytes: &Vec<u8>) -> Result<UserData, SystemError> { unimplemented!() }
}
impl ToBytes for UserStatus {
fn into_bytes(self) -> Result<Vec<u8>, SystemError> { unimplemented!() }
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserData {
name: String,