dptree/lib.rs
1//! An implementation of the [chain (tree) of responsibility] pattern.
2//!
3//! [[`examples/web_server.rs`](https://github.com/teloxide/dptree/blob/master/examples/web_server.rs)]
4//! ```rust
5//! use dptree::prelude::*;
6//!
7//! type WebHandler = Endpoint<'static, String>;
8//!
9//! #[rustfmt::skip]
10//! #[tokio::main(flavor = "current_thread")]
11//! async fn main() {
12//! let web_server = dptree::entry()
13//! .branch(smiles_handler())
14//! .branch(sqrt_handler())
15//! .branch(not_found_handler());
16//!
17//! assert_eq!(
18//! web_server.dispatch(dptree::deps!["/smile"]).await,
19//! ControlFlow::Break("🙃".to_owned())
20//! );
21//! assert_eq!(
22//! web_server.dispatch(dptree::deps!["/sqrt 16"]).await,
23//! ControlFlow::Break("4".to_owned())
24//! );
25//! assert_eq!(
26//! web_server.dispatch(dptree::deps!["/lol"]).await,
27//! ControlFlow::Break("404 Not Found".to_owned())
28//! );
29//! }
30//!
31//! fn smiles_handler() -> WebHandler {
32//! dptree::filter(|req: &'static str| req.starts_with("/smile"))
33//! .endpoint(|| async { "🙃".to_owned() })
34//! }
35//!
36//! fn sqrt_handler() -> WebHandler {
37//! dptree::filter_map(|req: &'static str| {
38//! if req.starts_with("/sqrt") {
39//! let (_, n) = req.split_once(' ')?;
40//! n.parse::<f64>().ok()
41//! } else {
42//! None
43//! }
44//! })
45//! .endpoint(|n: f64| async move { format!("{}", n.sqrt()) })
46//! }
47//!
48//! fn not_found_handler() -> WebHandler {
49//! dptree::endpoint(|| async { "404 Not Found".to_owned() })
50//! }
51//! ```
52//!
53//! For a high-level overview, please see [`README.md`](https://github.com/teloxide/dptree).
54//!
55//! [chain (tree) of responsibility]: https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
56
57mod handler;
58
59pub mod di;
60pub mod prelude;
61pub mod send;
62
63pub use handler::*;
64
65/// Filters an enumeration, passing its payload forwards.
66///
67/// This macro expands to a [`crate::Handler`] that acts on your enumeration
68/// type: if the enumeration is of a certain variant, the execution continues;
69/// otherwise, `dptree` will try the next branch. This is very useful for
70/// dialogue FSM transitions and incoming command filtering; for a real-world
71/// example, please see teloxide's [`examples/purchase.rs`].
72///
73/// Variants can take the following forms:
74///
75/// - `Enum::MyVariant` for empty variants;
76/// - `Enum::MyVariant(param1, ..., paramN)` for tuple-like variants;
77/// - `Enum::MyVariant { param1, ..., paramN }` for `struct`-like variants.
78///
79/// In the first case, this macro results in a simple [`crate::filter`]; in the
80/// second and third cases, this macro results in [`crate::filter_map`] that
81/// passes the payload of `MyVariant` to the next handler if the match occurs.
82/// (This next handler can be an endpoint or a more complex one.) The payload
83/// format depend on the form of `MyVariant`:
84///
85/// - For `Enum::MyVariant(param)` and `Enum::MyVariant { param }`, the payload
86/// is `param`.
87/// - For `Enum::MyVariant(param,)` and `Enum::MyVariant { param, }`, the
88/// payload is `(param,)`.
89/// - For `Enum::MyVariant(param1, ..., paramN)` and `Enum::MyVariant { param1,
90/// ..., paramN }`, the payload is `(param1, ..., paramN)` (where `N`>1).
91///
92/// ## Dependency requirements
93///
94/// - Your enumeration `Enum`.
95///
96/// ## Examples
97///
98/// ```rust
99/// use dptree::prelude::*;
100///
101/// # #[tokio::main(flavor = "current_thread")]
102/// # async fn main() {
103/// #[derive(Clone)]
104/// enum Command {
105/// Meow,
106/// Add(i32, i32),
107/// }
108///
109/// let h: Handler<_> = dptree::entry()
110/// .branch(dptree::case![Command::Meow].endpoint(|| async move { format!("Meow!") }))
111/// .branch(
112/// dptree::case![Command::Add(x, y)]
113/// .endpoint(|(x, y): (i32, i32)| async move { format!("{}", x + y) }),
114/// );
115///
116/// assert_eq!(
117/// h.dispatch(dptree::deps![Command::Meow]).await,
118/// ControlFlow::Break("Meow!".to_owned())
119/// );
120/// assert_eq!(
121/// h.dispatch(dptree::deps![Command::Add(1, 2)]).await,
122/// ControlFlow::Break("3".to_owned())
123/// );
124/// # }
125/// ```
126///
127/// [`examples/purchase.rs`]: https://github.com/teloxide/teloxide/blob/master/examples/purchase.rs
128#[macro_export]
129macro_rules! case {
130 ($($variant:ident)::+) => {
131 $crate::filter(|x| matches!(x, $($variant)::+))
132 };
133 ($($variant:ident)::+ ($param:ident)) => {
134 $crate::filter_map(|x| match x {
135 $($variant)::+($param) => Some($param),
136 _ => None,
137 })
138 };
139 ($($variant:ident)::+ ($($param:ident),+ $(,)?)) => {
140 $crate::filter_map(|x| match x {
141 $($variant)::+($($param),+) => Some(($($param),+ ,)),
142 _ => None,
143 })
144 };
145 ($($variant:ident)::+ {$param:ident}) => {
146 $crate::filter_map(|x| match x {
147 $($variant)::+{$param} => Some($param),
148 _ => None,
149 })
150 };
151 ($($variant:ident)::+ {$($param:ident),+ $(,)?}) => {
152 $crate::filter_map(|x| match x {
153 $($variant)::+ { $($param),+ } => Some(($($param),+ ,)),
154 _ => None,
155 })
156 };
157}
158
159/// Conditionally applies `#[tokio::test]`/`#[test]` for native builds
160/// and `#[wasm_bindgen_test]` for Wasm targets.
161#[cfg(test)]
162macro_rules! cross_test {
163 () => {};
164 ($(#[$($attr:tt)*])* async fn $name:ident() $body:block $($rest:tt)*) => {
165 #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
166 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
167 $(#[$($attr)*])*
168 async fn $name() $body
169
170 crate::cross_test! { $($rest)* }
171 };
172 ($(#[$($attr:tt)*])* fn $name:ident() $body:block $($rest:tt)*) => {
173 #[cfg_attr(not(target_arch = "wasm32"), test)]
174 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
175 $(#[$($attr)*])*
176 fn $name() $body
177
178 crate::cross_test! { $($rest)* }
179 };
180}
181
182#[cfg(test)]
183pub(crate) use cross_test;
184
185#[cfg(test)]
186mod tests {
187 use std::ops::ControlFlow;
188
189 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
190 enum State {
191 A,
192 B(i32),
193 C(i32, &'static str),
194 D { foo: i32 },
195 E { foo: i32, bar: &'static str },
196 Other,
197 }
198
199 crate::cross_test! {
200 async fn handler_empty_variant() {
201 let input = State::A;
202 let h: crate::Handler<_> = case![State::A].endpoint(|| async move { 123 });
203
204 assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
205 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
206 }
207
208 async fn handler_single_fn_variant() {
209 let input = State::B(42);
210 let h: crate::Handler<_> = case![State::B(x)].endpoint(|x: i32| async move {
211 assert_eq!(x, 42);
212 123
213 });
214
215 assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
216 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
217 }
218
219 async fn handler_single_fn_variant_trailing_comma() {
220 let input = State::B(42);
221 let h: crate::Handler<_> = case![State::B(x,)].endpoint(|(x,): (i32,)| async move {
222 assert_eq!(x, 42);
223 123
224 });
225
226 assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
227 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
228 }
229
230 async fn handler_fn_variant() {
231 let input = State::C(42, "abc");
232 let h: crate::Handler<_> =
233 case![State::C(x, y)].endpoint(|(x, str): (i32, &'static str)| async move {
234 assert_eq!(x, 42);
235 assert_eq!(str, "abc");
236 123
237 });
238
239 assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
240 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
241 }
242
243 async fn handler_single_struct_variant() {
244 let input = State::D { foo: 42 };
245 let h: crate::Handler<_> = case![State::D { foo }].endpoint(|x: i32| async move {
246 assert_eq!(x, 42);
247 123
248 });
249
250 assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
251 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
252 }
253
254 async fn handler_single_struct_variant_trailing_comma() {
255 let input = State::D { foo: 42 };
256 #[rustfmt::skip] // rustfmt removes the trailing comma from `State::D { foo, }`, but it plays a vital role in this test.
257 let h: crate::Handler<_> = case![State::D { foo, }].endpoint(|(x,): (i32,)| async move {
258 assert_eq!(x, 42);
259 123
260 });
261
262 assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
263 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
264 }
265
266 async fn handler_struct_variant() {
267 let input = State::E { foo: 42, bar: "abc" };
268 let h: crate::Handler<_> =
269 case![State::E { foo, bar }].endpoint(|(x, str): (i32, &'static str)| async move {
270 assert_eq!(x, 42);
271 assert_eq!(str, "abc");
272 123
273 });
274
275 assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
276 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
277 }
278 }
279}