statekit 0.4.0

An immutable state-machine for validating predefined transitions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use crate::{MachineBuilder, MachineInner, MachineInstance, StateError, Transition, Transitions};
use std::sync::Arc;

/// An immutable state-machine definition.
///
/// A `Machine` contains at least one transition. Every stored state name and
/// transition has already been validated by the builder.
#[derive(Debug, PartialEq, Eq)]
pub struct Machine {
    pub(crate) inner: Arc<MachineInner>,
}

impl Machine {
    /// Constructs a machine from validated transitions.
    pub(crate) fn new(transitions: Transitions) -> Self {
        let inner = MachineInner::new(transitions);

        Self {
            inner: Arc::new(inner),
        }
    }

    /// Constructs a machine handle from existing MachineInner.
    pub(crate) fn from_inner(inner: Arc<MachineInner>) -> Self {
        Self { inner }
    }

    /// Returns a builder for constructing a [`Machine`].
    ///
    /// This is the public entry point for creating machine definitions.
    pub fn builder() -> MachineBuilder {
        MachineBuilder::new()
    }

    /// Returns an instance of a mutable state machine instance.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::UnknownInitialState`] when `initial` is not an
    /// existing state.
    pub fn instance(&self, initial: &str) -> Result<MachineInstance, StateError> {
        MachineInstance::try_new(Arc::clone(&self.inner), initial.to_owned())
    }

    /// Returns whether the transition from `from` to `to` is allowed.
    ///
    /// State names are matched exactly. This method does not trim, normalize,
    /// or otherwise modify the supplied names.
    pub fn can_transition(&self, from: &str, to: &str) -> bool {
        self.inner.can_transition(from, to)
    }

    /// Validates that the transition from `from` to `to` is allowed.
    ///
    /// # Errors
    ///
    /// Returns [`StateError::InvalidTransition`] when the machine does not
    /// contain the requested transition.
    /// State names are matched exactly. This method does not trim, normalize,
    /// or otherwise modify the supplied names.
    pub fn validate_transition(&self, from: &str, to: &str) -> Result<(), StateError> {
        self.inner.validate_transition(from, to)
    }

    /// Returns the number of transitions in the state machine.
    pub fn transition_count(&self) -> usize {
        self.inner.transition_count()
    }

    /// Returns whether `state` appears as either endpoint of a transition.
    pub fn contains_state(&self, state: &str) -> bool {
        self.inner.contains_state(state)
    }

    /// Returns an iterator over states directly reachable from `from`.
    ///
    /// Returns `None` when `from` has no outgoing transitions, including when
    /// `from` is unknown or appears only as a transition target.
    ///
    /// The iteration order is unspecified.
    #[deprecated(since = "0.2.0", note = "use `targets_from` instead")]
    pub fn targets(&self, from: &str) -> Option<impl Iterator<Item = &str>> {
        let mut targets = self.targets_from(from).peekable();

        if targets.peek().is_none() {
            None
        } else {
            Some(targets)
        }
    }

    /// Returns an iterator over states directly reachable from `from`.
    ///
    /// Returns an empty iterator when `from` has no outgoing transitions,
    /// including when `from` is unknown or appears only as a transition target.
    ///
    /// The iteration order is unspecified.
    pub fn targets_from(&self, from: &str) -> impl Iterator<Item = &str> {
        self.inner.targets_from(from)
    }

    /// Returns an iterator over all source states.
    ///
    /// The iteration order is unspecified.
    pub fn sources(&self) -> impl Iterator<Item = &str> {
        self.inner.sources()
    }

    /// Returns an iterator over all unique source and target states.
    ///
    /// The iteration order is unspecified.
    pub fn states(&self) -> impl Iterator<Item = &str> {
        self.inner.states()
    }

    /// Returns an iterator over all the transitions in the state machine.
    ///
    /// The iteration order is unspecified.
    pub fn transitions(&self) -> impl Iterator<Item = &Transition> {
        self.inner.transitions()
    }

    ///Returns true when the `state` has no outgoing transitions.
    pub fn is_terminal(&self, state: &str) -> bool {
        self.inner.is_terminal(state)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod validate_transition {
        use super::*;

        #[test]
        fn validate_transition_accepts_configured_transition() -> Result<(), StateError> {
            let builder = Machine::builder()
                .try_allow("start", "finish")?
                .try_allow("1", "2")?;

            let m = builder.build()?;

            assert!(m.validate_transition("start", "finish").is_ok());

            Ok(())
        }

        #[test]
        fn validate_transition_not_exists_returns_invalid_error() -> Result<(), StateError> {
            let builder = Machine::builder().try_allow("start", "finish")?;

            let m = builder.build()?;

            assert_eq!(
                m.validate_transition("start", "invalid"),
                Err(StateError::InvalidTransition {
                    from: "start".to_string(),
                    to: "invalid".to_string(),
                })
            );

            Ok(())
        }
    }

    mod transition_count {
        use super::*;

        #[test]
        fn transition_count_counts_transitions() -> Result<(), StateError> {
            let builder = Machine::builder()
                .try_allow("start", "finish")?
                .try_allow("1", "2")?;

            let m = builder.build()?;

            assert_eq!(m.transition_count(), 2);

            Ok(())
        }
    }

    mod can_transition {
        use super::*;

        #[test]
        fn can_transition_exists_returns_true() -> Result<(), StateError> {
            let builder = Machine::builder().try_allow("start", "finish")?;

            let m = builder.build()?;

            assert!(m.can_transition("start", "finish"));

            Ok(())
        }

        #[test]
        fn can_transition_not_exists_returns_false() -> Result<(), StateError> {
            let builder = Machine::builder().try_allow("start", "finish")?;

            let m = builder.build()?;

            assert!(!m.can_transition("start", "invalid"));

            Ok(())
        }
    }

    mod contains_state {
        use super::*;

        #[test]
        fn contains_state_finds_target_only_state() -> Result<(), StateError> {
            let builder = Machine::builder().try_allow("start", "finish")?;

            let m = builder.build()?;

            assert!(m.contains_state("finish"));

            Ok(())
        }

        #[test]
        fn contains_state_rejects_unknown_state() -> Result<(), StateError> {
            let builder = Machine::builder().try_allow("start", "finish")?;

            let m = builder.build()?;

            assert!(!m.contains_state("other"));

            Ok(())
        }

        #[test]
        fn contains_state_finds_source_state() -> Result<(), StateError> {
            let builder = Machine::builder()
                .try_allow("start", "end")?
                .try_allow("rest", "finish")?;

            let m = builder.build()?;

            assert!(m.contains_state("rest"));

            Ok(())
        }
    }

    mod targets_from {
        use super::*;

        #[test]
        fn targets_from_one_transition_key_does_not_exist_returns_empty() -> Result<(), StateError>
        {
            let builder = Machine::builder().try_allow("start", "finish")?;

            let m = builder.build()?;
            let collected: Vec<_> = m.targets_from("other").collect();

            assert!(collected.is_empty());

            Ok(())
        }

        #[test]
        fn targets_from_one_transition_one_value() -> Result<(), StateError> {
            let builder = Machine::builder().try_allow("start", "finish")?;

            let m = builder.build()?;
            let collected: Vec<_> = m.targets_from("start").collect();

            assert_eq!(collected, vec!["finish"]);

            Ok(())
        }
    }

    mod targets {
        use super::*;

        #[allow(deprecated)]
        #[test]
        fn targets_returns_none_when_source_has_no_outgoing_transitions() -> Result<(), StateError>
        {
            let machine = Machine::builder().try_allow("start", "finish")?.build()?;

            assert!(machine.targets("finish").is_none());
            assert!(machine.targets("unknown").is_none());

            Ok(())
        }

        #[allow(deprecated)]
        #[test]
        fn targets_returns_some_when_source_has_outgoing_transitions() -> Result<(), StateError> {
            let machine = Machine::builder().try_allow("start", "finish")?.build()?;

            assert!(machine.targets("start").is_some());

            Ok(())
        }
    }

    mod sources {
        use super::*;

        #[test]
        fn returns_all_source_states() -> Result<(), StateError> {
            let machine = Machine::builder()
                .try_allow("1", "0")?
                .try_allow("2", "0")?
                .try_allow("3", "0")?
                .build()?;

            let mut sources: Vec<_> = machine.sources().collect();
            sources.sort();

            assert_eq!(sources, vec!["1", "2", "3"]);

            Ok(())
        }
    }

    mod states {
        use super::*;

        #[test]
        fn returns_unique_source_and_target_states() -> Result<(), StateError> {
            let machine = Machine::builder()
                .try_allow("1", "2")?
                .try_allow("1", "3")?
                .try_allow("2", "3")?
                .try_allow("3", "4")?
                .build()?;

            let mut states: Vec<_> = machine.states().collect();
            states.sort();

            assert_eq!(states, vec!["1", "2", "3", "4"]);

            Ok(())
        }
    }

    mod transitions {
        use super::*;

        #[test]
        fn one_transition_returns_matching_fields() -> Result<(), StateError> {
            let machine = Machine::builder().try_allow("1", "2")?.build()?;

            let transitions: Vec<_> = machine.transitions().collect();

            assert_eq!(transitions[0].source(), "1");
            assert_eq!(transitions[0].target(), "2");

            Ok(())
        }

        #[test]
        fn one_transition_returns_one_item() -> Result<(), StateError> {
            let machine = Machine::builder().try_allow("1", "2")?.build()?;

            let transitions: Vec<_> = machine.transitions().collect();

            assert_eq!(transitions.len(), 1);

            Ok(())
        }
    }

    mod is_terminal {
        use super::*;

        #[test]
        fn source_is_not_terminal() -> Result<(), StateError> {
            let machine = Machine::builder().try_allow("1", "2")?.build()?;

            assert!(!machine.is_terminal("1"));

            Ok(())
        }

        #[test]
        fn target_with_no_outgoing_source_is_terminal() -> Result<(), StateError> {
            let machine = Machine::builder().try_allow("1", "2")?.build()?;

            assert!(machine.is_terminal("2"));

            Ok(())
        }
    }

    mod equality {
        use super::*;

        #[test]
        fn similar_machines_are_equal() -> Result<(), StateError> {
            let machine1 = Machine::builder().try_allow("1", "2")?.build()?;
            let machine2 = Machine::builder().try_allow("1", "2")?.build()?;

            assert_eq!(machine1, machine2);

            Ok(())
        }

        #[test]
        fn different_machines_are_not_equal() -> Result<(), StateError> {
            let machine1 = Machine::builder().try_allow("1", "2")?.build()?;
            let machine2 = Machine::builder().try_allow("1", "3")?.build()?;

            assert_ne!(machine1, machine2);

            Ok(())
        }
    }
}