dispatcher.rs 5.7 KB

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