feat: run rustfmt with custom defined fmt configuration (#1848)

* chore: update rustfmt

* chore: apply rustfmt format
This commit is contained in:
Nathan.fooo 2023-02-13 09:29:49 +08:00 committed by GitHub
parent e2496e734c
commit 6bb1c4e89c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
459 changed files with 50554 additions and 46600 deletions

View file

@ -1,59 +1,66 @@
use std::{
any::{Any, TypeId},
collections::HashMap,
any::{Any, TypeId},
collections::HashMap,
};
#[derive(Default, Debug)]
pub struct AFPluginStateMap(HashMap<TypeId, Box<dyn Any + Sync + Send>>);
impl AFPluginStateMap {
#[inline]
pub fn new() -> AFPluginStateMap {
AFPluginStateMap(HashMap::default())
}
#[inline]
pub fn new() -> AFPluginStateMap {
AFPluginStateMap(HashMap::default())
}
pub fn insert<T>(&mut self, val: T) -> Option<T>
where
T: 'static + Send + Sync,
{
self.0.insert(TypeId::of::<T>(), Box::new(val)).and_then(downcast_owned)
}
pub fn insert<T>(&mut self, val: T) -> Option<T>
where
T: 'static + Send + Sync,
{
self
.0
.insert(TypeId::of::<T>(), Box::new(val))
.and_then(downcast_owned)
}
pub fn remove<T>(&mut self) -> Option<T>
where
T: 'static + Send + Sync,
{
self.0.remove(&TypeId::of::<T>()).and_then(downcast_owned)
}
pub fn remove<T>(&mut self) -> Option<T>
where
T: 'static + Send + Sync,
{
self.0.remove(&TypeId::of::<T>()).and_then(downcast_owned)
}
pub fn get<T>(&self) -> Option<&T>
where
T: 'static + Send + Sync,
{
self.0.get(&TypeId::of::<T>()).and_then(|boxed| boxed.downcast_ref())
}
pub fn get<T>(&self) -> Option<&T>
where
T: 'static + Send + Sync,
{
self
.0
.get(&TypeId::of::<T>())
.and_then(|boxed| boxed.downcast_ref())
}
pub fn get_mut<T>(&mut self) -> Option<&mut T>
where
T: 'static + Send + Sync,
{
self.0
.get_mut(&TypeId::of::<T>())
.and_then(|boxed| boxed.downcast_mut())
}
pub fn get_mut<T>(&mut self) -> Option<&mut T>
where
T: 'static + Send + Sync,
{
self
.0
.get_mut(&TypeId::of::<T>())
.and_then(|boxed| boxed.downcast_mut())
}
pub fn contains<T>(&self) -> bool
where
T: 'static + Send + Sync,
{
self.0.contains_key(&TypeId::of::<T>())
}
pub fn contains<T>(&self) -> bool
where
T: 'static + Send + Sync,
{
self.0.contains_key(&TypeId::of::<T>())
}
pub fn extend(&mut self, other: AFPluginStateMap) {
self.0.extend(other.0);
}
pub fn extend(&mut self, other: AFPluginStateMap) {
self.0.extend(other.0);
}
}
fn downcast_owned<T: 'static + Send + Sync>(boxed: Box<dyn Any + Send + Sync>) -> Option<T> {
boxed.downcast().ok().map(|boxed| *boxed)
boxed.downcast().ok().map(|boxed| *boxed)
}

View file

@ -1,7 +1,7 @@
use crate::{
errors::{DispatchError, InternalError},
request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
util::ready::{ready, Ready},
errors::{DispatchError, InternalError},
request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
util::ready::{ready, Ready},
};
use std::{any::type_name, ops::Deref, sync::Arc};
@ -9,61 +9,64 @@ pub struct AFPluginState<T: ?Sized + Send + Sync>(Arc<T>);
impl<T> AFPluginState<T>
where
T: Send + Sync,
T: Send + Sync,
{
pub fn new(data: T) -> Self {
AFPluginState(Arc::new(data))
}
pub fn new(data: T) -> Self {
AFPluginState(Arc::new(data))
}
pub fn get_ref(&self) -> &T {
self.0.as_ref()
}
pub fn get_ref(&self) -> &T {
self.0.as_ref()
}
}
impl<T> Deref for AFPluginState<T>
where
T: ?Sized + Send + Sync,
T: ?Sized + Send + Sync,
{
type Target = Arc<T>;
type Target = Arc<T>;
fn deref(&self) -> &Arc<T> {
&self.0
}
fn deref(&self) -> &Arc<T> {
&self.0
}
}
impl<T> Clone for AFPluginState<T>
where
T: ?Sized + Send + Sync,
T: ?Sized + Send + Sync,
{
fn clone(&self) -> AFPluginState<T> {
AFPluginState(self.0.clone())
}
fn clone(&self) -> AFPluginState<T> {
AFPluginState(self.0.clone())
}
}
impl<T> From<Arc<T>> for AFPluginState<T>
where
T: ?Sized + Send + Sync,
T: ?Sized + Send + Sync,
{
fn from(arc: Arc<T>) -> Self {
AFPluginState(arc)
}
fn from(arc: Arc<T>) -> Self {
AFPluginState(arc)
}
}
impl<T> FromAFPluginRequest for AFPluginState<T>
where
T: ?Sized + Send + Sync + 'static,
T: ?Sized + Send + Sync + 'static,
{
type Error = DispatchError;
type Future = Ready<Result<Self, DispatchError>>;
type Error = DispatchError;
type Future = Ready<Result<Self, DispatchError>>;
#[inline]
fn from_request(req: &AFPluginEventRequest, _: &mut Payload) -> Self::Future {
if let Some(state) = req.get_state::<AFPluginState<T>>() {
ready(Ok(state.clone()))
} else {
let msg = format!("Failed to get the plugin state of type: {}", type_name::<T>());
log::error!("{}", msg,);
ready(Err(InternalError::Other(msg).into()))
}
#[inline]
fn from_request(req: &AFPluginEventRequest, _: &mut Payload) -> Self::Future {
if let Some(state) = req.get_state::<AFPluginState<T>>() {
ready(Ok(state.clone()))
} else {
let msg = format!(
"Failed to get the plugin state of type: {}",
type_name::<T>()
);
log::error!("{}", msg,);
ready(Err(InternalError::Other(msg).into()))
}
}
}

View file

@ -1,12 +1,12 @@
use crate::{
errors::{DispatchError, InternalError},
module::{container::AFPluginStateMap, AFPluginState},
request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
response::{AFPluginEventResponse, AFPluginResponder},
service::{
factory, AFPluginHandler, AFPluginHandlerService, AFPluginServiceFactory, BoxService, BoxServiceFactory,
Service, ServiceRequest, ServiceResponse,
},
errors::{DispatchError, InternalError},
module::{container::AFPluginStateMap, AFPluginState},
request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
response::{AFPluginEventResponse, AFPluginResponder},
service::{
factory, AFPluginHandler, AFPluginHandlerService, AFPluginServiceFactory, BoxService,
BoxServiceFactory, Service, ServiceRequest, ServiceResponse,
},
};
use futures_core::future::BoxFuture;
use futures_core::ready;
@ -14,35 +14,35 @@ use nanoid::nanoid;
use pin_project::pin_project;
use std::sync::Arc;
use std::{
collections::HashMap,
fmt,
fmt::{Debug, Display},
future::Future,
hash::Hash,
pin::Pin,
task::{Context, Poll},
collections::HashMap,
fmt,
fmt::{Debug, Display},
future::Future,
hash::Hash,
pin::Pin,
task::{Context, Poll},
};
pub type AFPluginMap = Arc<HashMap<AFPluginEvent, Arc<AFPlugin>>>;
pub(crate) fn as_plugin_map(plugins: Vec<AFPlugin>) -> AFPluginMap {
let mut plugin_map = HashMap::new();
plugins.into_iter().for_each(|m| {
let events = m.events();
let plugins = Arc::new(m);
events.into_iter().for_each(|e| {
plugin_map.insert(e, plugins.clone());
});
let mut plugin_map = HashMap::new();
plugins.into_iter().for_each(|m| {
let events = m.events();
let plugins = Arc::new(m);
events.into_iter().for_each(|e| {
plugin_map.insert(e, plugins.clone());
});
Arc::new(plugin_map)
});
Arc::new(plugin_map)
}
#[derive(PartialEq, Eq, Hash, Debug, Clone)]
pub struct AFPluginEvent(pub String);
impl<T: Display + Eq + Hash + Debug + Clone> std::convert::From<T> for AFPluginEvent {
fn from(t: T) -> Self {
AFPluginEvent(format!("{}", t))
}
fn from(t: T) -> Self {
AFPluginEvent(format!("{}", t))
}
}
/// A plugin is used to handle the events that the plugin can handle.
@ -52,67 +52,74 @@ impl<T: Display + Eq + Hash + Debug + Clone> std::convert::From<T> for AFPluginE
/// which means only one handler will get called.
///
pub struct AFPlugin {
pub name: String,
pub name: String,
/// a list of `AFPluginState` that the plugin registers. The state can be read by the plugin's handler.
states: Arc<AFPluginStateMap>,
/// 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>>>,
/// 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>>,
>,
}
impl std::default::Default for AFPlugin {
fn default() -> Self {
Self {
name: "".to_owned(),
states: Arc::new(AFPluginStateMap::new()),
event_service_factory: Arc::new(HashMap::new()),
}
fn default() -> Self {
Self {
name: "".to_owned(),
states: Arc::new(AFPluginStateMap::new()),
event_service_factory: Arc::new(HashMap::new()),
}
}
}
impl AFPlugin {
pub fn new() -> Self {
AFPlugin::default()
}
pub fn new() -> Self {
AFPlugin::default()
}
pub fn name(mut self, s: &str) -> Self {
self.name = s.to_owned();
self
}
pub fn name(mut self, s: &str) -> Self {
self.name = s.to_owned();
self
}
pub fn state<D: 'static + Send + Sync>(mut self, data: D) -> Self {
Arc::get_mut(&mut self.states).unwrap().insert(AFPluginState::new(data));
pub fn state<D: 'static + Send + Sync>(mut self, data: D) -> Self {
Arc::get_mut(&mut self.states)
.unwrap()
.insert(AFPluginState::new(data));
self
}
self
}
pub fn event<E, H, T, R>(mut self, event: E, handler: H) -> Self
where
H: AFPluginHandler<T, R>,
T: FromAFPluginRequest + 'static + Send + Sync,
<T as FromAFPluginRequest>::Future: Sync + Send,
R: Future + 'static + Send + Sync,
R::Output: AFPluginResponder + 'static,
E: Eq + Hash + Debug + Clone + Display,
{
let event: AFPluginEvent = event.into();
if self.event_service_factory.contains_key(&event) {
panic!("Register duplicate Event: {:?}", &event);
} else {
Arc::get_mut(&mut self.event_service_factory)
.unwrap()
.insert(event, factory(AFPluginHandlerService::new(handler)));
}
self
pub fn event<E, H, T, R>(mut self, event: E, handler: H) -> Self
where
H: AFPluginHandler<T, R>,
T: FromAFPluginRequest + 'static + Send + Sync,
<T as FromAFPluginRequest>::Future: Sync + Send,
R: Future + 'static + Send + Sync,
R::Output: AFPluginResponder + 'static,
E: Eq + Hash + Debug + Clone + Display,
{
let event: AFPluginEvent = event.into();
if self.event_service_factory.contains_key(&event) {
panic!("Register duplicate Event: {:?}", &event);
} else {
Arc::get_mut(&mut self.event_service_factory)
.unwrap()
.insert(event, factory(AFPluginHandlerService::new(handler)));
}
self
}
pub fn events(&self) -> Vec<AFPluginEvent> {
self.event_service_factory.keys().cloned().collect::<Vec<_>>()
}
pub fn events(&self) -> Vec<AFPluginEvent> {
self
.event_service_factory
.keys()
.cloned()
.collect::<Vec<_>>()
}
}
/// A request that will be passed to the corresponding plugin.
@ -121,101 +128,106 @@ impl AFPlugin {
///
#[derive(Debug, Clone)]
pub struct AFPluginRequest {
pub id: String,
pub event: AFPluginEvent,
pub(crate) payload: Payload,
pub id: String,
pub event: AFPluginEvent,
pub(crate) payload: Payload,
}
impl AFPluginRequest {
pub fn new<E>(event: E) -> Self
where
E: Into<AFPluginEvent>,
{
Self {
id: nanoid!(6),
event: event.into(),
payload: Payload::None,
}
pub fn new<E>(event: E) -> Self
where
E: Into<AFPluginEvent>,
{
Self {
id: nanoid!(6),
event: event.into(),
payload: Payload::None,
}
}
pub fn payload<P>(mut self, payload: P) -> Self
where
P: Into<Payload>,
{
self.payload = payload.into();
self
}
pub fn payload<P>(mut self, payload: P) -> Self
where
P: Into<Payload>,
{
self.payload = payload.into();
self
}
}
impl std::fmt::Display for AFPluginRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{:?}", self.id, self.event)
}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{:?}", self.id, self.event)
}
}
impl AFPluginServiceFactory<AFPluginRequest> for AFPlugin {
type Response = AFPluginEventResponse;
type Error = DispatchError;
type Service = BoxService<AFPluginRequest, Self::Response, Self::Error>;
type Context = ();
type Future = BoxFuture<'static, Result<Self::Service, Self::Error>>;
type Response = AFPluginEventResponse;
type Error = DispatchError;
type Service = BoxService<AFPluginRequest, Self::Response, Self::Error>;
type Context = ();
type Future = BoxFuture<'static, Result<Self::Service, Self::Error>>;
fn new_service(&self, _cfg: Self::Context) -> Self::Future {
let services = self.event_service_factory.clone();
let states = self.states.clone();
Box::pin(async move {
let service = AFPluginService { services, states };
Ok(Box::new(service) as Self::Service)
})
}
fn new_service(&self, _cfg: Self::Context) -> Self::Future {
let services = self.event_service_factory.clone();
let states = self.states.clone();
Box::pin(async move {
let service = AFPluginService { services, states };
Ok(Box::new(service) as Self::Service)
})
}
}
pub struct AFPluginService {
services: Arc<HashMap<AFPluginEvent, BoxServiceFactory<(), ServiceRequest, ServiceResponse, DispatchError>>>,
states: Arc<AFPluginStateMap>,
services: Arc<
HashMap<AFPluginEvent, BoxServiceFactory<(), ServiceRequest, ServiceResponse, DispatchError>>,
>,
states: Arc<AFPluginStateMap>,
}
impl Service<AFPluginRequest> for AFPluginService {
type Response = AFPluginEventResponse;
type Error = DispatchError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
type Response = AFPluginEventResponse;
type Error = DispatchError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn call(&self, request: AFPluginRequest) -> Self::Future {
let AFPluginRequest { id, event, payload } = request;
let states = self.states.clone();
let request = AFPluginEventRequest::new(id, event, states);
fn call(&self, request: AFPluginRequest) -> Self::Future {
let AFPluginRequest { id, event, payload } = request;
let states = self.states.clone();
let request = AFPluginEventRequest::new(id, event, states);
match self.services.get(&request.event) {
Some(factory) => {
let service_fut = factory.new_service(());
let fut = AFPluginServiceFuture {
fut: Box::pin(async {
let service = service_fut.await?;
let service_req = ServiceRequest::new(request, payload);
service.call(service_req).await
}),
};
Box::pin(async move { Ok(fut.await.unwrap_or_else(|e| e.into())) })
}
None => {
let msg = format!("Can not find service factory for event: {:?}", request.event);
Box::pin(async { Err(InternalError::ServiceNotFound(msg).into()) })
}
}
match self.services.get(&request.event) {
Some(factory) => {
let service_fut = factory.new_service(());
let fut = AFPluginServiceFuture {
fut: Box::pin(async {
let service = service_fut.await?;
let service_req = ServiceRequest::new(request, payload);
service.call(service_req).await
}),
};
Box::pin(async move { Ok(fut.await.unwrap_or_else(|e| e.into())) })
},
None => {
let msg = format!(
"Can not find service factory for event: {:?}",
request.event
);
Box::pin(async { Err(InternalError::ServiceNotFound(msg).into()) })
},
}
}
}
#[pin_project]
pub struct AFPluginServiceFuture {
#[pin]
fut: BoxFuture<'static, Result<ServiceResponse, DispatchError>>,
#[pin]
fut: BoxFuture<'static, Result<ServiceResponse, DispatchError>>,
}
impl Future for AFPluginServiceFuture {
type Output = Result<AFPluginEventResponse, 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();
Poll::Ready(Ok(response))
}
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();
Poll::Ready(Ok(response))
}
}