use std::{future::Future, pin::Pin, sync::Arc};
use bytes::Bytes;
use super::envelope::{Envelope, Packet};
use crate::{
middleware::{HandlerService, Transform},
request::{RequestBodyStream, RequestParts},
response::Response,
};
pub type Handler<E> = Arc<dyn Fn(&E) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
pub type ResponseHandler<E> = Arc<
dyn for<'request> Fn(
&'request E,
)
-> Pin<Box<dyn Future<Output = Response<Envelope, ()>> + Send + 'request>>
+ Send
+ Sync,
>;
pub(crate) enum Route<E: Packet> {
Unit(Handler<E>),
Response(ResponseHandler<E>),
}
impl<E: Packet> Clone for Route<E> {
fn clone(&self) -> Self {
match self {
Self::Unit(handler) => Self::Unit(Arc::clone(handler)),
Self::Response(handler) => Self::Response(Arc::clone(handler)),
}
}
}
pub type StreamingHandler = Arc<
dyn Fn(RequestParts, RequestBodyStream) -> Pin<Box<dyn Future<Output = Option<Bytes>> + Send>>
+ Send
+ Sync,
>;
pub trait Middleware<E: Packet>:
Transform<HandlerService<E>, Output = HandlerService<E>> + Send + Sync
{
}
impl<E: Packet, T> Middleware<E> for T where
T: Transform<HandlerService<E>, Output = HandlerService<E>> + Send + Sync
{
}
#[cfg(test)]
mod tests {
use super::*;
async fn echo_after_yield(request: &Envelope) -> Response<Envelope, ()> {
tokio::task::yield_now().await;
Response::Single(Envelope::new(request.id, None, request.payload.clone()))
}
#[tokio::test]
async fn response_handler_may_borrow_the_request() {
let handler: ResponseHandler<Envelope> =
Arc::new(|request: &Envelope| Box::pin(echo_after_yield(request)));
let request = Envelope::new(7, None, vec![1]);
let response = handler(&request).await;
assert!(
matches!(response, Response::Single(frame) if frame.id == 7),
"the handler must see the borrowed request after awaiting"
);
}
}