flow_runner/run/mod.rs
1//! Running a flow: one call to [`Flow::run`] enters a node, follows jumps,
2//! and stops at a value, an ask, or nothing to do. Everything the instance
3//! needs to continue later is in the returned [`Token`].
4
5mod token;
6mod walk;
7
8pub use token::{Token, TokenInfo};
9
10use self::walk::Run;
11use crate::common::error::{InputError, RunError};
12use crate::common::limits::Limits;
13use crate::flow::Flow;
14use indexmap::IndexMap;
15use std::fmt;
16use temple_dsl::Value;
17
18/// What the host asks a flow to do. Build one with [`Input::start`] or
19/// [`Input::resume`], then add to it. A mistake, such as a param on a resume,
20/// is reported by [`Flow::run`], not dropped.
21#[derive(Debug, Clone)]
22pub struct Input {
23 begin: Begin,
24 event: Option<Event>,
25 data: Value,
26 params: IndexMap<String, Value>,
27 result: Option<Value>,
28 failure: Option<Value>,
29}
30
31/// Where a run begins.
32#[derive(Debug, Clone)]
33enum Begin {
34 Entry(String),
35 Token(Token),
36}
37
38impl Input {
39 /// Start a new instance at `entry`, with `data` as `input.data`.
40 pub fn start(entry: impl Into<String>, data: impl Into<Value>) -> Input {
41 Input::new(Begin::Entry(entry.into()), data.into())
42 }
43
44 /// Continue the instance `token` belongs to, with `data` as `input.data`.
45 pub fn resume(token: Token, data: impl Into<Value>) -> Input {
46 Input::new(Begin::Token(token), data.into())
47 }
48
49 fn new(begin: Begin, data: Value) -> Input {
50 Input {
51 begin,
52 event: None,
53 data,
54 params: IndexMap::new(),
55 result: None,
56 failure: None,
57 }
58 }
59
60 /// Deliver an event: a declared one, or `tick`. Expressions read its
61 /// name as `input.event` and `payload` as `input.payload`.
62 pub fn event(mut self, name: impl Into<String>, payload: impl Into<Value>) -> Input {
63 self.event = Some(Event {
64 name: name.into(),
65 payload: payload.into(),
66 });
67 self
68 }
69
70 /// Set a param. Only a start takes params.
71 pub fn param(mut self, name: impl Into<String>, value: impl Into<Value>) -> Input {
72 self.params.insert(name.into(), value.into());
73 self
74 }
75
76 /// Answer the ask a resumed token waits on.
77 pub fn result(mut self, value: impl Into<Value>) -> Input {
78 self.result = Some(value.into());
79 self
80 }
81
82 /// Say why the ask a resumed token waits on couldn't be answered. The
83 /// reason can't be `null`, which reads as no failure.
84 pub fn failure(mut self, reason: impl Into<Value>) -> Input {
85 self.failure = Some(reason.into());
86 self
87 }
88
89 /// Whether it answers an ask, with a result or a failure.
90 fn answers(&self) -> bool {
91 self.result.is_some() || self.failure.is_some()
92 }
93}
94
95/// Something that happened, delivered to the node an instance is parked at.
96#[derive(Debug, Clone)]
97struct Event {
98 /// A declared event, or `tick`.
99 name: String,
100 /// What came with it, as `input.payload`.
101 payload: Value,
102}
103
104/// How a run ended.
105#[derive(Debug, Clone, PartialEq)]
106#[non_exhaustive]
107pub enum Decision {
108 /// The instance is parked at `node`, with a value for the host.
109 Value {
110 /// What the flow decided.
111 value: Value,
112 /// The node the instance is parked at.
113 node: String,
114 /// The token to store and resume with.
115 token: Token,
116 /// When to send a `tick` event, in epoch seconds.
117 wake_at: Option<i64>,
118 },
119 /// The flow needs the host to do something: run the ask, then resume the
120 /// token with a `result` or a `failure`.
121 Ask {
122 /// The ask's name.
123 name: String,
124 /// What to ask with.
125 payload: Value,
126 /// The node the run continues at with the answer.
127 node: String,
128 /// The token to store and resume with the answer.
129 token: Token,
130 },
131 /// The run reached `ignore`; nothing changed. Keep the token you had.
132 Ignored,
133 /// The run failed. Nothing was performed; fix the data or the flow and
134 /// retry with `token`, or start again when it is `None`.
135 Error {
136 /// What failed.
137 error: RunError,
138 /// The token the run resumed; `None` for a start.
139 token: Option<Token>,
140 },
141}
142
143impl Decision {
144 /// The token to store, if the decision has one.
145 pub fn token(&self) -> Option<&Token> {
146 match self {
147 Decision::Value { token, .. } | Decision::Ask { token, .. } => Some(token),
148 Decision::Error { token, .. } => token.as_ref(),
149 Decision::Ignored => None,
150 }
151 }
152
153 /// Whether the run failed.
154 pub fn is_error(&self) -> bool {
155 matches!(self, Decision::Error { .. })
156 }
157}
158
159/// Where a run went, for answering "why did this happen?". Holds node names
160/// and branch positions only, never values.
161#[derive(Debug, Clone, Default, PartialEq, Eq)]
162pub struct Trace {
163 /// The branches taken, in order.
164 pub branches: Vec<BranchTaken>,
165 /// Evaluation steps the run used.
166 pub steps_used: u64,
167}
168
169/// One branch a run took.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct BranchTaken {
172 /// The node the branch is in.
173 pub node: String,
174 /// Index of the branch taken, counting from 0 in source order.
175 pub branch: usize,
176 /// What the branch did.
177 pub kind: BranchKind,
178}
179
180/// What a branch did.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182#[non_exhaustive]
183pub enum BranchKind {
184 /// Jumped to another node.
185 Jump,
186 /// Ended the run with a value.
187 Value,
188 /// Ended the run with an ask.
189 Ask,
190 /// Ended the run with nothing to do.
191 Ignore,
192 /// An expression in the branch failed.
193 Error,
194}
195
196impl BranchKind {
197 /// The kind as a word: `jump`, `value`, `ask`, `ignore` or `error`.
198 pub fn as_str(self) -> &'static str {
199 match self {
200 BranchKind::Jump => "jump",
201 BranchKind::Value => "value",
202 BranchKind::Ask => "ask",
203 BranchKind::Ignore => "ignore",
204 BranchKind::Error => "error",
205 }
206 }
207}
208
209impl fmt::Display for BranchKind {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 f.write_str(self.as_str())
212 }
213}
214
215impl Flow {
216 /// Run the flow once. `Err` means the host passed something wrong and
217 /// nothing ran; every other ending is a [`Decision`].
218 pub fn run(&self, input: Input, limits: &Limits) -> Result<Decision, InputError> {
219 Ok(Run::begin(self, input, limits, None)?.walk())
220 }
221
222 /// Like [`run`](Self::run), also returning the path the run took.
223 pub fn run_traced(
224 &self,
225 input: Input,
226 limits: &Limits,
227 ) -> Result<(Decision, Trace), InputError> {
228 let mut trace = Trace::default();
229 let decision = Run::begin(self, input, limits, Some(&mut trace))?.walk();
230 Ok((decision, trace))
231 }
232}