chore: update documentation

This commit is contained in:
nathan 2022-12-01 10:59:22 +08:00
parent 96c427e869
commit bf36ef7fd9
13 changed files with 74 additions and 55 deletions

View File

@ -46,7 +46,7 @@ pub extern "C" fn async_event(port: i64, input: *const u8, len: usize) {
}
Some(e) => e.event_dispatcher.clone(),
};
let _ = AFPluginDispatcher::async_send_with_callback(dispatcher, request, move |resp: EventResponse| {
let _ = AFPluginDispatcher::async_send_with_callback(dispatcher, request, move |resp: AFPluginEventResponse| {
log::trace!("[FFI]: Post data to dart through {} port", port);
Box::pin(post_to_flutter(resp, port))
});
@ -83,7 +83,7 @@ pub extern "C" fn set_stream_port(port: i64) -> i32 {
pub extern "C" fn link_me_please() {}
#[inline(always)]
async fn post_to_flutter(response: EventResponse, port: i64) {
async fn post_to_flutter(response: AFPluginEventResponse, port: i64) {
let isolate = allo_isolate::Isolate::new(port);
match isolate
.catch_unwind(async {

View File

@ -1,5 +1,5 @@
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use lib_dispatch::prelude::{EventResponse, Payload, StatusCode};
use lib_dispatch::prelude::{AFPluginEventResponse, Payload, StatusCode};
#[derive(ProtoBuf_Enum, Clone, Copy)]
pub enum FFIStatusCode {
@ -23,8 +23,8 @@ pub struct FFIResponse {
code: FFIStatusCode,
}
impl std::convert::From<EventResponse> for FFIResponse {
fn from(resp: EventResponse) -> Self {
impl std::convert::From<AFPluginEventResponse> for FFIResponse {
fn from(resp: AFPluginEventResponse) -> Self {
let payload = match resp.payload {
Payload::Bytes(bytes) => bytes.to_vec(),
Payload::None => vec![],

View File

@ -1,7 +1,7 @@
use bytes::Bytes;
use flowy_derive::ProtoBuf;
use flowy_error_code::ErrorCode;
use lib_dispatch::prelude::{EventResponse, ResponseBuilder};
use lib_dispatch::prelude::{AFPluginEventResponse, ResponseBuilder};
use std::{convert::TryInto, fmt, fmt::Debug};
pub type FlowyResult<T> = std::result::Result<T, FlowyError>;
@ -93,7 +93,7 @@ impl fmt::Display for FlowyError {
}
impl lib_dispatch::Error for FlowyError {
fn as_response(&self) -> EventResponse {
fn as_response(&self) -> AFPluginEventResponse {
let bytes: Bytes = self.clone().try_into().unwrap();
println!("Serialize FlowyError: {:?} to event response", self);

View File

@ -1,7 +1,7 @@
use crate::FlowySDKTest;
use flowy_user::{entities::UserProfilePB, errors::FlowyError};
use lib_dispatch::prelude::{
AFPluginDispatcher, AFPluginFromBytes, AFPluginRequest, EventResponse, StatusCode, ToBytes, *,
AFPluginDispatcher, AFPluginEventResponse, AFPluginFromBytes, AFPluginRequest, StatusCode, ToBytes, *,
};
use std::{
convert::TryFrom,
@ -124,7 +124,7 @@ where
self.context.sdk.dispatcher()
}
fn get_response(&self) -> EventResponse {
fn get_response(&self) -> AFPluginEventResponse {
self.context
.response
.as_ref()
@ -141,7 +141,7 @@ where
pub struct TestContext {
pub sdk: FlowySDKTest,
request: Option<AFPluginRequest>,
response: Option<EventResponse>,
response: Option<AFPluginEventResponse>,
}
impl TestContext {

View File

@ -2,7 +2,7 @@ use crate::{
byte_trait::*,
errors::{DispatchError, InternalError},
request::{unexpected_none_payload, AFPluginEventRequest, FromAFPluginRequest, Payload},
response::{AFPluginResponder, EventResponse, ResponseBuilder},
response::{AFPluginEventResponse, AFPluginResponder, ResponseBuilder},
util::ready::{ready, Ready},
};
use bytes::Bytes;
@ -53,7 +53,7 @@ impl<T> AFPluginResponder for AFPluginData<T>
where
T: ToBytes,
{
fn respond_to(self, _request: &AFPluginEventRequest) -> EventResponse {
fn respond_to(self, _request: &AFPluginEventRequest) -> AFPluginEventResponse {
match self.into_inner().into_bytes() {
Ok(bytes) => {
log::trace!("Serialize Data: {:?} to event response", std::any::type_name::<T>());

View File

@ -2,7 +2,7 @@ use crate::runtime::AFPluginRuntime;
use crate::{
errors::{DispatchError, Error, InternalError},
module::{as_plugin_map, AFPlugin, AFPluginMap, AFPluginRequest},
response::EventResponse,
response::AFPluginEventResponse,
service::{AFPluginServiceFactory, Service},
};
use derivative::*;
@ -30,7 +30,7 @@ impl AFPluginDispatcher {
}
}
pub fn async_send<Req>(dispatch: Arc<AFPluginDispatcher>, request: Req) -> DispatchFuture<EventResponse>
pub fn async_send<Req>(dispatch: Arc<AFPluginDispatcher>, request: Req) -> DispatchFuture<AFPluginEventResponse>
where
Req: std::convert::Into<AFPluginRequest>,
{
@ -41,10 +41,10 @@ impl AFPluginDispatcher {
dispatch: Arc<AFPluginDispatcher>,
request: Req,
callback: Callback,
) -> DispatchFuture<EventResponse>
) -> DispatchFuture<AFPluginEventResponse>
where
Req: std::convert::Into<AFPluginRequest>,
Callback: FnOnce(EventResponse) -> BoxFuture<'static, ()> + 'static + Send + Sync,
Callback: FnOnce(AFPluginEventResponse) -> BoxFuture<'static, ()> + 'static + Send + Sync,
{
let request: AFPluginRequest = request.into();
let plugins = dispatch.plugins.clone();
@ -73,7 +73,7 @@ impl AFPluginDispatcher {
}
}
pub fn sync_send(dispatch: Arc<AFPluginDispatcher>, request: AFPluginRequest) -> EventResponse {
pub fn sync_send(dispatch: Arc<AFPluginDispatcher>, request: AFPluginRequest) -> AFPluginEventResponse {
futures::executor::block_on(async {
AFPluginDispatcher::async_send_with_callback(dispatch, request, |_| Box::pin(async {})).await
})
@ -105,7 +105,7 @@ where
}
}
pub type BoxFutureCallback = Box<dyn FnOnce(EventResponse) -> BoxFuture<'static, ()> + 'static + Send + Sync>;
pub type BoxFutureCallback = Box<dyn FnOnce(AFPluginEventResponse) -> BoxFuture<'static, ()> + 'static + Send + Sync>;
#[derive(Derivative)]
#[derivative(Debug)]
@ -127,7 +127,7 @@ pub(crate) struct DispatchService {
}
impl Service<DispatchContext> for DispatchService {
type Response = EventResponse;
type Response = AFPluginEventResponse;
type Error = DispatchError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

View File

@ -1,7 +1,7 @@
use crate::{
byte_trait::AFPluginFromBytes,
request::AFPluginEventRequest,
response::{EventResponse, ResponseBuilder},
response::{AFPluginEventResponse, ResponseBuilder},
};
use bytes::Bytes;
use dyn_clone::DynClone;
@ -10,7 +10,7 @@ use std::fmt;
use tokio::{sync::mpsc::error::SendError, task::JoinError};
pub trait Error: fmt::Debug + DynClone + Send + Sync {
fn as_response(&self) -> EventResponse;
fn as_response(&self) -> AFPluginEventResponse;
}
dyn_clone::clone_trait_object!(Error);
@ -80,7 +80,7 @@ impl AFPluginFromBytes for DispatchError {
}
}
impl From<DispatchError> for EventResponse {
impl From<DispatchError> for AFPluginEventResponse {
fn from(err: DispatchError) -> Self {
err.inner_error().as_response()
}
@ -121,7 +121,7 @@ impl fmt::Display for InternalError {
}
impl Error for InternalError {
fn as_response(&self) -> EventResponse {
fn as_response(&self) -> AFPluginEventResponse {
let error = format!("{}", self).into_bytes();
ResponseBuilder::Internal().data(error).build()
}

View File

@ -2,7 +2,7 @@ use crate::{
errors::{DispatchError, InternalError},
module::{container::AFPluginStateMap, AFPluginState},
request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
response::{AFPluginResponder, EventResponse},
response::{AFPluginEventResponse, AFPluginResponder},
service::{
factory, AFPluginHandler, AFPluginHandlerService, AFPluginServiceFactory, BoxService, BoxServiceFactory,
Service, ServiceRequest, ServiceResponse,
@ -45,9 +45,21 @@ impl<T: Display + Eq + Hash + Debug + Clone> std::convert::From<T> for AFPluginE
}
}
/// A plugin is used to handle the events that the plugin can handle.
///
/// When an event is a dispatched by the `AFPluginDispatcher`, the dispatcher will
/// find the corresponding plugin to handle the event. The name of the event must be unique,
/// which means only one handler will get called.
///
pub struct AFPlugin {
pub name: String,
/// a list of `AFPluginState` that the plugin registers. The state can be read by the plugin's handler.
states: Arc<AFPluginStateMap>,
/// Contains a list of factories that are used to generate the services used to handle the passed-in
/// `ServiceRequest`.
///
event_service_factory:
Arc<HashMap<AFPluginEvent, BoxServiceFactory<(), ServiceRequest, ServiceResponse, DispatchError>>>,
}
@ -89,12 +101,12 @@ impl AFPlugin {
{
let event: AFPluginEvent = event.into();
if self.event_service_factory.contains_key(&event) {
log::error!("Duplicate Event: {:?}", &event);
panic!("Register duplicate Event: {:?}", &event);
} else {
Arc::get_mut(&mut self.event_service_factory)
.unwrap()
.insert(event, factory(AFPluginHandlerService::new(handler)));
}
Arc::get_mut(&mut self.event_service_factory)
.unwrap()
.insert(event, factory(AFPluginHandlerService::new(handler)));
self
}
@ -103,6 +115,10 @@ impl AFPlugin {
}
}
/// A request that will be passed to the corresponding plugin.
///
/// Each request can carry the payload that will be deserialized into the corresponding data struct.
///
#[derive(Debug, Clone)]
pub struct AFPluginRequest {
pub id: String,
@ -138,7 +154,7 @@ impl std::fmt::Display for AFPluginRequest {
}
impl AFPluginServiceFactory<AFPluginRequest> for AFPlugin {
type Response = EventResponse;
type Response = AFPluginEventResponse;
type Error = DispatchError;
type Service = BoxService<AFPluginRequest, Self::Response, Self::Error>;
type Context = ();
@ -160,7 +176,7 @@ pub struct AFPluginService {
}
impl Service<AFPluginRequest> for AFPluginService {
type Response = EventResponse;
type Response = AFPluginEventResponse;
type Error = DispatchError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
@ -196,7 +212,7 @@ pub struct AFPluginServiceFuture {
}
impl Future for AFPluginServiceFuture {
type Output = Result<EventResponse, DispatchError>;
type Output = Result<AFPluginEventResponse, DispatchError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let (_, response) = ready!(self.as_mut().project().fut.poll(cx))?.into_parts();

View File

@ -1,6 +1,6 @@
use crate::{
request::Payload,
response::{EventResponse, StatusCode},
response::{AFPluginEventResponse, StatusCode},
};
macro_rules! static_response {
@ -30,8 +30,8 @@ impl ResponseBuilder {
self
}
pub fn build(self) -> EventResponse {
EventResponse {
pub fn build(self) -> AFPluginEventResponse {
AFPluginEventResponse {
payload: self.payload,
status_code: self.status,
}

View File

@ -2,18 +2,18 @@
use crate::errors::{DispatchError, InternalError};
use crate::{
request::AFPluginEventRequest,
response::{EventResponse, ResponseBuilder},
response::{AFPluginEventResponse, ResponseBuilder},
};
use bytes::Bytes;
pub trait AFPluginResponder {
fn respond_to(self, req: &AFPluginEventRequest) -> EventResponse;
fn respond_to(self, req: &AFPluginEventRequest) -> AFPluginEventResponse;
}
macro_rules! impl_responder {
($res: ty) => {
impl AFPluginResponder for $res {
fn respond_to(self, _: &AFPluginEventRequest) -> EventResponse {
fn respond_to(self, _: &AFPluginEventRequest) -> AFPluginEventResponse {
ResponseBuilder::Ok().data(self).build()
}
}
@ -32,7 +32,7 @@ where
T: AFPluginResponder,
E: Into<DispatchError>,
{
fn respond_to(self, request: &AFPluginEventRequest) -> EventResponse {
fn respond_to(self, request: &AFPluginEventRequest) -> AFPluginEventResponse {
match self {
Ok(val) => val.respond_to(request),
Err(e) => e.into().into(),

View File

@ -19,15 +19,15 @@ pub enum StatusCode {
// serde user guide: https://serde.rs/field-attrs.html
#[derive(Debug, Clone, Derivative)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize))]
pub struct EventResponse {
pub struct AFPluginEventResponse {
#[derivative(Debug = "ignore")]
pub payload: Payload,
pub status_code: StatusCode,
}
impl EventResponse {
impl AFPluginEventResponse {
pub fn new(status_code: StatusCode) -> Self {
EventResponse {
AFPluginEventResponse {
payload: Payload::None,
status_code,
}
@ -51,7 +51,7 @@ impl EventResponse {
}
}
impl std::fmt::Display for EventResponse {
impl std::fmt::Display for AFPluginEventResponse {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("Status_Code: {:?}", self.status_code))?;
@ -64,9 +64,9 @@ impl std::fmt::Display for EventResponse {
}
}
impl AFPluginResponder for EventResponse {
impl AFPluginResponder for AFPluginEventResponse {
#[inline]
fn respond_to(self, _: &AFPluginEventRequest) -> EventResponse {
fn respond_to(self, _: &AFPluginEventRequest) -> AFPluginEventResponse {
self
}
}

View File

@ -11,11 +11,12 @@ use pin_project::pin_project;
use crate::{
errors::DispatchError,
request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
response::{AFPluginResponder, EventResponse},
response::{AFPluginEventResponse, AFPluginResponder},
service::{AFPluginServiceFactory, Service, ServiceRequest, ServiceResponse},
util::ready::*,
};
/// A closure that is run every time for the specified plugin event
pub trait AFPluginHandler<T, R>: Clone + 'static + Sync + Send
where
R: Future + Send + Sync,
@ -135,7 +136,7 @@ where
Err(err) => {
let req = req.take().unwrap();
let system_err: DispatchError = err.into();
let res: EventResponse = system_err.into();
let res: AFPluginEventResponse = system_err.into();
return Poll::Ready(Ok(ServiceResponse::new(req, res)));
}
};

View File

@ -2,7 +2,7 @@ use std::future::Future;
use crate::{
request::{payload::Payload, AFPluginEventRequest},
response::EventResponse,
response::AFPluginEventResponse,
};
pub trait Service<Request> {
@ -13,6 +13,8 @@ pub trait Service<Request> {
fn call(&self, req: Request) -> Self::Future;
}
/// Returns a future that can handle the request. For the moment, the request will be the
/// `AFPluginRequest`
pub trait AFPluginServiceFactory<Request> {
type Response;
type Error;
@ -24,32 +26,32 @@ pub trait AFPluginServiceFactory<Request> {
}
pub(crate) struct ServiceRequest {
req: AFPluginEventRequest,
event_state: AFPluginEventRequest,
payload: Payload,
}
impl ServiceRequest {
pub(crate) fn new(req: AFPluginEventRequest, payload: Payload) -> Self {
Self { req, payload }
pub(crate) fn new(event_state: AFPluginEventRequest, payload: Payload) -> Self {
Self { event_state, payload }
}
#[inline]
pub(crate) fn into_parts(self) -> (AFPluginEventRequest, Payload) {
(self.req, self.payload)
(self.event_state, self.payload)
}
}
pub struct ServiceResponse {
request: AFPluginEventRequest,
response: EventResponse,
response: AFPluginEventResponse,
}
impl ServiceResponse {
pub fn new(request: AFPluginEventRequest, response: EventResponse) -> Self {
pub fn new(request: AFPluginEventRequest, response: AFPluginEventResponse) -> Self {
ServiceResponse { request, response }
}
pub fn into_parts(self) -> (AFPluginEventRequest, EventResponse) {
pub fn into_parts(self) -> (AFPluginEventRequest, AFPluginEventResponse) {
(self.request, self.response)
}
}