Skip to main content

vortex_scan/execution/planning/
next.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Handoff between stages: the `Next` constructor.
5
6use std::sync::Arc;
7
8use vortex_error::VortexResult;
9
10use crate::planning::planner::Planner;
11
12/// A reusable constructor for a stage's successor.
13///
14/// A stage calls it from its own `compute()` and emits the planner it returns, so a constructor
15/// failure fails that compute. Constructors only store their input: substantial planning belongs
16/// in the successor's `compute()`.
17pub type Next<Input> = Arc<dyn Fn(Input) -> VortexResult<Box<dyn Planner>> + Send + Sync>;
18
19/// Builds a `Next` from a closure that returns a concrete planner.
20pub fn next_fn<Input, F, P>(f: F) -> Next<Input>
21where
22    F: Fn(Input) -> VortexResult<P> + Send + Sync + 'static,
23    P: Planner + 'static,
24{
25    Arc::new(move |input: Input| f(input).map(|planner| Box::new(planner) as Box<dyn Planner>))
26}
27
28#[cfg(test)]
29mod tests {
30    use vortex_error::vortex_bail;
31    use vortex_io::request::IoConsumer;
32    use vortex_io::request::IoRequestId;
33    use vortex_io::request::IoResult;
34
35    use super::*;
36    use crate::planning::planner::PlannerOutput;
37    use crate::planning::planner::State;
38
39    struct Finished;
40
41    impl IoConsumer for Finished {
42        fn set_io_result(&mut self, _request: IoRequestId, _result: IoResult) {}
43    }
44
45    impl Planner for Finished {
46        fn state(&self) -> State {
47            State::Done
48        }
49
50        fn compute(&mut self) -> VortexResult<PlannerOutput> {
51            Ok(PlannerOutput::Done)
52        }
53    }
54
55    #[test]
56    fn next_fn_boxes_the_planner() -> VortexResult<()> {
57        let next: Next<u32> = next_fn(|_input: u32| Ok(Finished));
58        assert_eq!(next(7)?.state(), State::Done);
59        Ok(())
60    }
61
62    #[test]
63    fn next_fn_reports_constructor_errors() {
64        let next: Next<u32> = next_fn(|input: u32| -> VortexResult<Finished> {
65            vortex_bail!("constructor rejected {input}")
66        });
67        let err = next(7).err().map(|e| e.to_string());
68        assert!(
69            err.as_deref()
70                .is_some_and(|m| m.contains("constructor rejected 7")),
71            "{err:?}"
72        );
73    }
74}