dispatcher.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. use crate::runtime::AFPluginRuntime;
  2. use crate::{
  3. errors::{DispatchError, Error, InternalError},
  4. module::{as_plugin_map, AFPlugin, AFPluginMap, AFPluginRequest},
  5. response::AFPluginEventResponse,
  6. service::{AFPluginServiceFactory, Service},
  7. };
  8. use derivative::*;
  9. use futures_core::future::BoxFuture;
  10. use futures_util::task::Context;
  11. use pin_project::pin_project;
  12. use std::{future::Future, sync::Arc};
  13. use tokio::macros::support::{Pin, Poll};
  14. pub struct AFPluginDispatcher {
  15. plugins: AFPluginMap,
  16. runtime: AFPluginRuntime,
  17. }
  18. impl AFPluginDispatcher {
  19. pub fn construct<F>(runtime: AFPluginRuntime, module_factory: F) -> AFPluginDispatcher
  20. where
  21. F: FnOnce() -> Vec<AFPlugin>,
  22. {
  23. let plugins = module_factory();
  24. tracing::trace!("{}", plugin_info(&plugins));
  25. AFPluginDispatcher {
  26. plugins: as_plugin_map(plugins),
  27. runtime,
  28. }
  29. }
  30. pub fn async_send<Req>(dispatch: Arc<AFPluginDispatcher>, request: Req) -> DispatchFuture<AFPluginEventResponse>
  31. where
  32. Req: std::convert::Into<AFPluginRequest>,
  33. {
  34. AFPluginDispatcher::async_send_with_callback(dispatch, request, |_| Box::pin(async {}))
  35. }
  36. pub fn async_send_with_callback<Req, Callback>(
  37. dispatch: Arc<AFPluginDispatcher>,
  38. request: Req,
  39. callback: Callback,
  40. ) -> DispatchFuture<AFPluginEventResponse>
  41. where
  42. Req: std::convert::Into<AFPluginRequest>,
  43. Callback: FnOnce(AFPluginEventResponse) -> BoxFuture<'static, ()> + 'static + Send + Sync,
  44. {
  45. let request: AFPluginRequest = request.into();
  46. let plugins = dispatch.plugins.clone();
  47. let service = Box::new(DispatchService { plugins });
  48. tracing::trace!("Async event: {:?}", &request.event);
  49. let service_ctx = DispatchContext {
  50. request,
  51. callback: Some(Box::new(callback)),
  52. };
  53. let join_handle = dispatch.runtime.spawn(async move {
  54. service.call(service_ctx).await.unwrap_or_else(|e| {
  55. tracing::error!("Dispatch runtime error: {:?}", e);
  56. InternalError::Other(format!("{:?}", e)).as_response()
  57. })
  58. });
  59. DispatchFuture {
  60. fut: Box::pin(async move {
  61. join_handle.await.unwrap_or_else(|e| {
  62. let msg = format!("EVENT_DISPATCH join error: {:?}", e);
  63. tracing::error!("{}", msg);
  64. let error = InternalError::JoinError(msg);
  65. error.as_response()
  66. })
  67. }),
  68. }
  69. }
  70. pub fn sync_send(dispatch: Arc<AFPluginDispatcher>, request: AFPluginRequest) -> AFPluginEventResponse {
  71. futures::executor::block_on(async {
  72. AFPluginDispatcher::async_send_with_callback(dispatch, request, |_| Box::pin(async {})).await
  73. })
  74. }
  75. pub fn spawn<F>(&self, f: F)
  76. where
  77. F: Future<Output = ()> + Send + 'static,
  78. {
  79. self.runtime.spawn(f);
  80. }
  81. }
  82. #[pin_project]
  83. pub struct DispatchFuture<T: Send + Sync> {
  84. #[pin]
  85. pub fut: Pin<Box<dyn Future<Output = T> + Sync + Send>>,
  86. }
  87. impl<T> Future for DispatchFuture<T>
  88. where
  89. T: Send + Sync,
  90. {
  91. type Output = T;
  92. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  93. let this = self.as_mut().project();
  94. Poll::Ready(futures_core::ready!(this.fut.poll(cx)))
  95. }
  96. }
  97. pub type BoxFutureCallback = Box<dyn FnOnce(AFPluginEventResponse) -> BoxFuture<'static, ()> + 'static + Send + Sync>;
  98. #[derive(Derivative)]
  99. #[derivative(Debug)]
  100. pub struct DispatchContext {
  101. pub request: AFPluginRequest,
  102. #[derivative(Debug = "ignore")]
  103. pub callback: Option<BoxFutureCallback>,
  104. }
  105. impl DispatchContext {
  106. pub(crate) fn into_parts(self) -> (AFPluginRequest, Option<BoxFutureCallback>) {
  107. let DispatchContext { request, callback } = self;
  108. (request, callback)
  109. }
  110. }
  111. pub(crate) struct DispatchService {
  112. pub(crate) plugins: AFPluginMap,
  113. }
  114. impl Service<DispatchContext> for DispatchService {
  115. type Response = AFPluginEventResponse;
  116. type Error = DispatchError;
  117. type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
  118. #[cfg_attr(
  119. feature = "use_tracing",
  120. tracing::instrument(name = "DispatchService", level = "debug", skip(self, ctx))
  121. )]
  122. fn call(&self, ctx: DispatchContext) -> Self::Future {
  123. let module_map = self.plugins.clone();
  124. let (request, callback) = ctx.into_parts();
  125. Box::pin(async move {
  126. let result = {
  127. // print_module_map_info(&module_map);
  128. match module_map.get(&request.event) {
  129. Some(module) => {
  130. tracing::trace!("Handle event: {:?} by {:?}", &request.event, module.name);
  131. let fut = module.new_service(());
  132. let service_fut = fut.await?.call(request);
  133. service_fut.await
  134. }
  135. None => {
  136. let msg = format!("Can not find the event handler. {:?}", request);
  137. tracing::error!("{}", msg);
  138. Err(InternalError::HandleNotFound(msg).into())
  139. }
  140. }
  141. };
  142. let response = result.unwrap_or_else(|e| e.into());
  143. tracing::trace!("Dispatch result: {:?}", response);
  144. if let Some(callback) = callback {
  145. callback(response.clone()).await;
  146. }
  147. Ok(response)
  148. })
  149. }
  150. }
  151. #[allow(dead_code)]
  152. fn plugin_info(plugins: &[AFPlugin]) -> String {
  153. let mut info = format!("{} plugins loaded\n", plugins.len());
  154. for module in plugins {
  155. info.push_str(&format!("-> {} loaded \n", module.name));
  156. }
  157. info
  158. }
  159. #[allow(dead_code)]
  160. fn print_plugins(plugins: &AFPluginMap) {
  161. plugins.iter().for_each(|(k, v)| {
  162. tracing::info!("Event: {:?} plugin : {:?}", k, v.name);
  163. })
  164. }