dispatch.rs 5.7 KB

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