246 lines
7.1 KiB
Rust
Raw Normal View History

2021-06-25 23:53:13 +08:00
use std::{
collections::HashMap,
2021-07-03 14:14:10 +08:00
fmt,
fmt::{Debug, Display},
2021-06-25 23:53:13 +08:00
future::Future,
hash::Hash,
2021-06-25 23:53:13 +08:00
pin::Pin,
task::{Context, Poll},
};
use futures_core::ready;
use pin_project::pin_project;
2021-06-25 23:53:13 +08:00
use crate::{
errors::{DispatchError, InternalError},
2022-02-25 22:27:44 +08:00
module::{container::ModuleDataMap, AppData},
request::{payload::Payload, EventRequest, FromRequest},
response::{EventResponse, Responder},
service::{
2022-01-23 12:14:00 +08:00
factory, BoxService, BoxServiceFactory, Handler, HandlerService, Service, ServiceFactory, ServiceRequest,
ServiceResponse,
},
};
use futures_core::future::BoxFuture;
2022-04-11 15:27:03 +08:00
use nanoid::nanoid;
use std::sync::Arc;
pub type ModuleMap = Arc<HashMap<Event, Arc<Module>>>;
pub(crate) fn as_module_map(modules: Vec<Module>) -> ModuleMap {
let mut module_map = HashMap::new();
modules.into_iter().for_each(|m| {
let events = m.events();
let module = Arc::new(m);
events.into_iter().for_each(|e| {
module_map.insert(e, module.clone());
});
});
Arc::new(module_map)
}
#[derive(PartialEq, Eq, Hash, Debug, Clone)]
pub struct Event(String);
impl<T: Display + Eq + Hash + Debug + Clone> std::convert::From<T> for Event {
2022-01-23 12:14:00 +08:00
fn from(t: T) -> Self {
Event(format!("{}", t))
}
}
2021-09-04 15:12:53 +08:00
pub type EventServiceFactory = BoxServiceFactory<(), ServiceRequest, ServiceResponse, DispatchError>;
2021-06-25 23:53:13 +08:00
pub struct Module {
2021-07-03 14:14:10 +08:00
pub name: String,
2021-07-09 17:47:15 +08:00
module_data: Arc<ModuleDataMap>,
service_map: Arc<HashMap<Event, EventServiceFactory>>,
2021-06-25 23:53:13 +08:00
}
2021-11-27 19:19:41 +08:00
impl std::default::Default for Module {
fn default() -> Self {
2021-06-25 23:53:13 +08:00
Self {
name: "".to_owned(),
2021-07-09 17:47:15 +08:00
module_data: Arc::new(ModuleDataMap::new()),
service_map: Arc::new(HashMap::new()),
2021-06-25 23:53:13 +08:00
}
}
2021-11-27 19:19:41 +08:00
}
impl Module {
2022-01-23 12:14:00 +08:00
pub fn new() -> Self {
Module::default()
}
2021-06-25 23:53:13 +08:00
pub fn name(mut self, s: &str) -> Self {
self.name = s.to_owned();
self
}
pub fn data<D: 'static + Send + Sync>(mut self, data: D) -> Self {
2022-02-25 22:27:44 +08:00
Arc::get_mut(&mut self.module_data).unwrap().insert(AppData::new(data));
2021-07-09 17:47:15 +08:00
2021-06-25 23:53:13 +08:00
self
}
pub fn event<E, H, T, R>(mut self, event: E, handler: H) -> Self
2021-06-25 23:53:13 +08:00
where
H: Handler<T, R>,
T: FromRequest + 'static + Send + Sync,
<T as FromRequest>::Future: Sync + Send,
R: Future + 'static + Send + Sync,
2021-06-25 23:53:13 +08:00
R::Output: Responder + 'static,
E: Eq + Hash + Debug + Clone + Display,
2021-06-25 23:53:13 +08:00
{
let event: Event = event.into();
2021-06-27 15:11:41 +08:00
if self.service_map.contains_key(&event) {
log::error!("Duplicate Event: {:?}", &event);
2021-06-27 15:11:41 +08:00
}
Arc::get_mut(&mut self.service_map)
2021-06-27 22:07:33 +08:00
.unwrap()
.insert(event, factory(HandlerService::new(handler)));
2021-06-25 23:53:13 +08:00
self
}
2021-06-26 23:52:03 +08:00
2022-01-23 12:14:00 +08:00
pub fn events(&self) -> Vec<Event> {
self.service_map.keys().cloned().collect::<Vec<_>>()
}
2021-06-25 23:53:13 +08:00
}
2021-09-04 15:12:53 +08:00
#[derive(Debug, Clone)]
pub struct ModuleRequest {
pub id: String,
pub event: Event,
2021-07-09 17:47:15 +08:00
pub(crate) payload: Payload,
}
impl ModuleRequest {
pub fn new<E>(event: E) -> Self
where
E: Into<Event>,
{
Self {
2022-04-11 15:27:03 +08:00
id: nanoid!(6),
2021-07-09 17:47:15 +08:00
event: event.into(),
payload: Payload::None,
}
}
pub fn payload<P>(mut self, payload: P) -> Self
where
P: Into<Payload>,
{
self.payload = payload.into();
self
}
}
2021-07-03 14:14:10 +08:00
impl std::fmt::Display for ModuleRequest {
2022-01-23 12:14:00 +08:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{:?}", self.id, self.event)
}
2021-07-03 14:14:10 +08:00
}
impl ServiceFactory<ModuleRequest> for Module {
2021-06-28 14:27:16 +08:00
type Response = EventResponse;
type Error = DispatchError;
type Service = BoxService<ModuleRequest, Self::Response, Self::Error>;
type Context = ();
type Future = BoxFuture<'static, Result<Self::Service, Self::Error>>;
2021-06-27 22:07:33 +08:00
fn new_service(&self, _cfg: Self::Context) -> Self::Future {
2021-06-27 22:07:33 +08:00
let service_map = self.service_map.clone();
2021-07-09 17:47:15 +08:00
let module_data = self.module_data.clone();
2021-06-27 22:07:33 +08:00
Box::pin(async move {
let service = ModuleService {
service_map,
module_data,
};
2021-06-27 22:07:33 +08:00
let module_service = Box::new(service) as Self::Service;
Ok(module_service)
})
}
}
pub struct ModuleService {
service_map: Arc<HashMap<Event, EventServiceFactory>>,
2021-07-09 17:47:15 +08:00
module_data: Arc<ModuleDataMap>,
2021-06-27 22:07:33 +08:00
}
impl Service<ModuleRequest> for ModuleService {
2021-06-28 14:27:16 +08:00
type Response = EventResponse;
type Error = DispatchError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
2021-06-27 22:07:33 +08:00
fn call(&self, request: ModuleRequest) -> Self::Future {
2021-07-09 17:47:15 +08:00
let ModuleRequest { id, event, payload } = request;
let module_data = self.module_data.clone();
2021-11-27 19:19:41 +08:00
let request = EventRequest::new(id, event, module_data);
2021-07-09 17:47:15 +08:00
match self.service_map.get(&request.event) {
2021-06-27 22:07:33 +08:00
Some(factory) => {
let service_fut = factory.new_service(());
2021-06-27 22:07:33 +08:00
let fut = ModuleServiceFuture {
fut: Box::pin(async {
let service = service_fut.await?;
2021-07-09 17:47:15 +08:00
let service_req = ServiceRequest::new(request, payload);
service.call(service_req).await
}),
2021-06-27 22:07:33 +08:00
};
2021-06-28 14:27:16 +08:00
Box::pin(async move { Ok(fut.await.unwrap_or_else(|e| e.into())) })
2022-01-23 12:14:00 +08:00
}
None => {
2021-09-04 15:12:53 +08:00
let msg = format!("Can not find service factory for event: {:?}", request.event);
Box::pin(async { Err(InternalError::ServiceNotFound(msg).into()) })
2022-01-23 12:14:00 +08:00
}
2021-06-27 22:07:33 +08:00
}
}
}
2021-06-26 23:52:03 +08:00
#[pin_project]
pub struct ModuleServiceFuture {
2021-06-25 23:53:13 +08:00
#[pin]
fut: BoxFuture<'static, Result<ServiceResponse, DispatchError>>,
2021-06-25 23:53:13 +08:00
}
2021-06-26 23:52:03 +08:00
impl Future for ModuleServiceFuture {
type Output = Result<EventResponse, DispatchError>;
2021-06-25 23:53:13 +08:00
2021-06-26 23:52:03 +08:00
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2021-11-27 19:19:41 +08:00
let (_, response) = ready!(self.as_mut().project().fut.poll(cx))?.into_parts();
Poll::Ready(Ok(response))
2021-06-26 23:52:03 +08:00
}
2021-06-25 23:53:13 +08:00
}
2021-06-28 14:27:16 +08:00
// #[cfg(test)]
// mod tests {
// use super::*;
// use crate::rt::Runtime;
// use futures_util::{future, pin_mut};
// use tokio::sync::mpsc::unbounded_channel;
// pub async fn hello_service() -> String { "hello".to_string() }
// #[test]
// fn test() {
// let runtime = Runtime::new().unwrap();
// runtime.block_on(async {
// let (sys_tx, mut sys_rx) = unbounded_channel::<SystemCommand>();
// let event = "hello".to_string();
// let module = Module::new(sys_tx).event(event.clone(),
// hello_service); let req_tx = module.req_tx();
// let event = async move {
// let request = EventRequest::new(event.clone());
// req_tx.send(request).unwrap();
//
// match sys_rx.recv().await {
// Some(cmd) => {
2021-11-03 15:37:38 +08:00
// tracing::info!("{:?}", cmd);
2021-06-28 14:27:16 +08:00
// },
// None => panic!(""),
// }
// };
//
// pin_mut!(module, event);
// future::select(module, event).await;
// });
// }
// }