Skip to main content

dptree/handler/
endpoint.rs

1use super::core::from_fn_with_flow;
2use crate::{
3    description,
4    di::Injectable,
5    send::{MaybeSend, MaybeSync},
6    Handler, HandlerDescription, HandlerSignature,
7};
8
9use std::{collections::BTreeSet, ops::ControlFlow, sync::Arc};
10
11use futures::FutureExt;
12
13/// Constructs a handler that has no further handlers in a chain.
14///
15/// An endpoint is a handler that _always_ breaks handler execution after its
16/// completion. So, you can use it when your chain of responsibility must end
17/// up, and handle an incoming event.
18#[must_use]
19#[track_caller]
20pub fn endpoint<'a, F, Output, FnArgs, Descr>(f: F) -> Endpoint<'a, Output, Descr>
21where
22    F: Injectable<Output, FnArgs> + MaybeSend + MaybeSync + 'a,
23    Output: 'static,
24    Descr: HandlerDescription,
25{
26    let f = Arc::new(f);
27
28    from_fn_with_flow(
29        Descr::endpoint(),
30        move |x, _cont| {
31            let f = Arc::clone(&f);
32            async move {
33                let f = f.inject(&x);
34                f().map(ControlFlow::Break).await
35            }
36        },
37        HandlerSignature::Other {
38            obligations: F::obligations(),
39            guaranteed_outcomes: BTreeSet::default(),
40            conditional_outcomes: BTreeSet::default(),
41            continues: false,
42        },
43        false,
44    )
45}
46
47/// A handler with no further handlers in a chain.
48pub type Endpoint<'a, Output, Descr = description::Unspecified> = Handler<'a, Output, Descr>;
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53    use crate::{deps, help_inference};
54
55    crate::cross_test! {
56        async fn test_endpoint() {
57            let input = 123;
58            let output = 7;
59
60            let result = help_inference(endpoint(move |num: i32| async move {
61                assert_eq!(num, input);
62                output
63            }))
64            .dispatch(deps![input])
65            .await;
66
67            let result = match result {
68                ControlFlow::Break(b) => b,
69                _ => panic!("Unexpected: handler return ControlFlow::Break"),
70            };
71            assert_eq!(result, output);
72        }
73    }
74}