crb_agent/performers/
interrupt_performer.rs

1use crate::agent::Agent;
2use crate::context::Context;
3use crate::performers::{Next, StatePerformer, StopReason, Transition, TransitionCommand};
4use anyhow::Error;
5use async_trait::async_trait;
6use crb_runtime::ManagedContext;
7
8impl<A> Next<A>
9where
10    A: Agent,
11{
12    pub fn done() -> Self {
13        Self::new(StopPerformer {
14            call_interrupt: false,
15            reason: None,
16        })
17    }
18
19    pub fn interrupt() -> Self {
20        Self::new(StopPerformer {
21            call_interrupt: true,
22            reason: None,
23        })
24    }
25
26    pub fn stop() -> Self {
27        Self::stop_with_reason(StopReason::Stopped)
28    }
29
30    pub fn fail(err: Error) -> Self {
31        Self::stop_with_reason(StopReason::Failed(err))
32    }
33
34    pub fn todo(reason: impl ToString) -> Self {
35        let err = Error::msg(reason.to_string());
36        Self::stop_with_reason(StopReason::Failed(err))
37    }
38
39    pub fn stop_with_reason(reason: StopReason) -> Self {
40        Self::new(StopPerformer {
41            call_interrupt: false,
42            reason: Some(reason),
43        })
44    }
45}
46
47pub struct StopPerformer {
48    call_interrupt: bool,
49    reason: Option<StopReason>,
50}
51
52#[async_trait]
53impl<A> StatePerformer<A> for StopPerformer
54where
55    A: Agent,
56{
57    async fn perform(&mut self, mut agent: A, ctx: &mut Context<A>) -> Transition<A> {
58        if let Some(reason) = self.reason.take() {
59            let command = TransitionCommand::Stop(reason);
60            Transition::Continue { agent, command }
61        } else {
62            if self.call_interrupt {
63                agent.interrupt(ctx);
64            } else {
65                ctx.shutdown();
66            }
67            let command = TransitionCommand::ProcessEvents;
68            Transition::Continue { agent, command }
69        }
70    }
71}