Skip to main content

crux_core/core/
request.rs

1use std::fmt::{self, Debug};
2
3use crate::{
4    capability::Operation,
5    core::resolve::{RequestHandle, Resolvable, ResolveError},
6};
7
8/// Request represents an effect request from the core to the shell.
9///
10/// The `operation` is the input needed to process the effect, and will be one
11/// of the capabilities' [`Operation`] types.
12///
13/// The request can be resolved by passing it to `Core::resolve` along with the
14/// corresponding result of type `Operation::Output`.
15pub struct Request<Op>
16where
17    Op: Operation,
18{
19    pub operation: Op,
20    pub handle: RequestHandle<Op::Output>,
21}
22
23impl<Op> Request<Op>
24where
25    Op: Operation,
26{
27    /// Resolve the request with the given output.
28    /// # Errors
29    /// Returns an error if the request does not expect to be resolved.
30    pub fn resolve(&mut self, output: Op::Output) -> Result<(), ResolveError> {
31        self.handle.resolve(output)
32    }
33
34    pub fn split(self) -> (Op, RequestHandle<Op::Output>) {
35        (self.operation, self.handle)
36    }
37
38    pub(crate) fn resolves_never(operation: Op) -> Self {
39        Self {
40            operation,
41            handle: RequestHandle::Never,
42        }
43    }
44
45    pub(crate) fn resolves_once<F>(operation: Op, resolve: F) -> Self
46    where
47        F: FnOnce(Op::Output) + Send + 'static,
48    {
49        Self {
50            operation,
51            handle: RequestHandle::Once(Box::new(resolve)),
52        }
53    }
54
55    pub(crate) fn resolves_many_times<F>(operation: Op, resolve: F) -> Self
56    where
57        F: Fn(Op::Output) -> Result<(), ()> + Send + 'static,
58    {
59        Self {
60            operation,
61            handle: RequestHandle::Many(Box::new(resolve)),
62        }
63    }
64}
65
66impl<Op> Resolvable<Op::Output> for Request<Op>
67where
68    Op: Operation,
69{
70    /// Resolve the request with the given output.
71    ///
72    /// Note: This method should only be used in tests that work directly with
73    /// [`Command`](crate::command::Command).
74    /// If you are using [`AppTester`](crate::testing::AppTester) to test your app,
75    /// you should use [`AppTester::resolve`](crate::testing::AppTester::resolve) instead.
76    ///
77    /// # Errors
78    ///
79    /// Errors if the request cannot (or should not) be resolved.
80    fn resolve(&mut self, output: Op::Output) -> Result<(), ResolveError> {
81        self.resolve(output)
82    }
83}
84
85impl<Op> fmt::Debug for Request<Op>
86where
87    Op: Operation + Debug,
88{
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.debug_tuple("Request").field(&self.operation).finish()
91    }
92}