dispatcher.rs 5.7 KB

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