statecraft 0.1.0

State machines with compile-time enforced 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#![doc = include_str!("../README.md")]

#[macro_use]
mod macros;

/// Derive for [`State`] trait
/// ```
/// # use statecraft::*;
/// #[derive(State)]
/// struct MyState;
/// ```
pub use statecraft_derive::State;

/// Derive for [`Stateful`] trait
///
/// Users of this derive must specify the [`State`] with an attribute. For example:
/// ```
/// # use statecraft::*;
/// #[derive(Stateful)]
/// #[state(S)]
/// struct MyMachine<S: State> {
///     state: S,
/// }
/// ```
pub use statecraft_derive::Stateful;

/// Derive for [`SelfTransitionable`]
///
/// Users must also implement [`Stateful`], and can do so via the provided derive
/// ```
/// # use statecraft::*;
/// #[derive(Stateful, SelfTransitionable)]
/// #[state(S)]
/// struct MyMachine<S: State> {
///     state: S,
/// }
/// ```
pub use statecraft_derive::SelfTransitionable;

/// A state which a [`Stateful`] can be in
///
/// The [`State`] trait itself is bare, only used for type enforcement of generic [`Stateful`] objects.
pub trait State {}

/// Types which can be in one of any given number of [`State`]s at a given time
pub trait Stateful {
    /// The `State` type a given `Stateful` can be in
    type State: State;
}

/// [`Stateful`]s which can transition between different [`State`]s
///
/// A transition between [`State`]s for [`Stateful`]s implementing [`Transitionable`] **must** be
/// successful. If the transition between different [`State`]s can fail, see the
/// [`TryTransitionable`] trait.
pub trait Transitionable<N>: Stateful
where
    N: State,
{
    /// The [`Stateful`] that the transition will force the current [`Stateful`] into
    type NextStateful: Stateful<State = N>;

    /// Transition [`Self`] into the [`Self::NextStateful`]
    ///
    /// Note that [`Self`] is consumed by this method. This enforces that a [`Stateful`] cannot
    /// exist in multiple [`State`]s at the same time.
    fn transition(self) -> Self::NextStateful;
}

mod async_transitionable {
    use super::*;

    /// Async variant of [`Transitionable`]
    #[trait_variant::make(AsyncTransitionable: Send)]
    #[allow(dead_code)]
    pub trait LocalAsyncTransitionable<N>: Stateful
    where
        N: State,
    {
        /// The [`Stateful`] that the transition will force the current [`Stateful`] into
        type NextStateful: Stateful<State = N>;

        /// Transition [`Self`] into the [`Self::NextStateful`]
        ///
        /// Note that [`Self`] is consumed by this method. This enforces that a [`Stateful`] cannot
        /// exist in multiple [`State`]s at the same time.
        async fn transition(self) -> Self::NextStateful;
    }
}
pub use async_transitionable::AsyncTransitionable;

impl<S, N> AsyncTransitionable<N> for S
where
    S: Stateful + Transitionable<N> + Send,
    N: State,
{
    type NextStateful = S::NextStateful;

    async fn transition(self) -> Self::NextStateful {
        <Self as Transitionable<N>>::transition(self)
    }
}

/// [`Stateful`]s which can transition back to themselves
///
/// This is a helper trait enabling simpler implementations of [`TryTransitionable`] for
/// [`Stateful`]s where the [`TryTransitionable::FailureStateful`] is the current [`Stateful`]. A
/// blanket implementation for [`Transitionable`] exists so that all [`SelfTransitionable`]
/// [`Stateful`]s can transition back to themselves.
pub trait SelfTransitionable: Stateful {}

impl<S: SelfTransitionable> Transitionable<S::State> for S {
    type NextStateful = Self;
    fn transition(self) -> Self::NextStateful {
        self
    }
}

/// Message-only error produced by the [`return_recover!`](crate::return_recover) macro family
///
/// The macros convert this into the implementor's error type via `Into`, so implementors with a
/// [`TryTransitionable::Error`] other than `TransitionError` must provide a
/// `From<TransitionError>` impl to use them:
///
/// ```
/// use statecraft::{return_recover, Recovered, SelfTransitionable, State, Stateful, TransitionError, Transitionable, TryTransitionable};
///
/// # #[derive(State)]
/// # struct Init;
/// # #[derive(State)]
/// # struct Running;
/// # #[derive(Stateful, SelfTransitionable)]
/// # #[state(S)]
/// # struct Server<S: State> {
/// #     state: S,
/// # }
/// #[derive(Debug)]
/// enum ServerError {
///     Transition(TransitionError),
/// }
///
/// impl From<TransitionError> for ServerError {
///     fn from(err: TransitionError) -> Self {
///         ServerError::Transition(err)
///     }
/// }
///
/// impl TryTransitionable<Running, Init> for Server<Init> {
///     type SuccessStateful = Server<Running>;
///     type FailureStateful = Server<Init>;
///     type Error = ServerError;
///
///     fn try_transition(
///         self,
///     ) -> Result<Self::SuccessStateful, Recovered<Self::FailureStateful, Self::Error>> {
///         return_recover!(self, "We always fail :(")
///     }
/// }
/// ```
///
/// A `TransitionError` [`TryTransitionable::Error`] converts as-is, and a boxed error type like
/// `Box<dyn std::error::Error + Send + Sync>` converts through the standard library's blanket
/// boxing impl.
#[derive(Debug)]
pub struct TransitionError {
    message: String,
}

impl TransitionError {
    pub fn new(message: impl Into<String>) -> Self {
        TransitionError {
            message: message.into(),
        }
    }
}

impl std::fmt::Display for TransitionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for TransitionError {}

/// The error value of a failed [`TryTransitionable`]
///
/// If a [`TryTransitionable::try_transition`] fails, a [`Recovered`] struct is returned. This
/// struct contains the recovered stateful of the failed transition, and an error value which
/// caused the [`TryTransitionable::try_transition`] to fail.
#[derive(Debug)]
pub struct Recovered<S, E> {
    /// The new [`Stateful`] after a failed [`TryTransitionable::try_transition`]
    pub stateful: S,

    /// The error which caused [`TryTransitionable::try_transition`] to fail
    pub error: E,
}

impl<S, E> Recovered<S, E> {
    /// Convenience function to create a new [`Recovered`] struct
    pub fn new(stateful: S, error: E) -> Self {
        Recovered { stateful, error }
    }
}

/// [`Stateful`]s which can transition between different [`State`]s, but **may fail** when
/// attempting to do so
///
/// A transition between [`State`]s for a [`Stateful`] implementing [`TryTransitionable`] **may
/// fail**. If the [`Self::try_transition`] succeeds, a new [`TryTransitionable::SuccessStateful`]
/// is returned. However if the [`Self::try_transition`] fails, a [`Recovered`] is returned. Type
/// bounds on the [`Self::FailureStateful`] type ensures that the current [`Stateful`] can
/// [`Transitionable::transition`] to [`Self::FailureStateful`] without error.
///
/// Many implementors will return the current [`Stateful`] if they fail. [`Stateful`]s with this
/// behavior should implement the [`SelfTransitionable`] trait.
pub trait TryTransitionable<N, R>: Transitionable<R>
where
    N: State,
    R: State,
{
    /// New [`Stateful`] if the [`Self::try_transition`] succeeds
    type SuccessStateful: Stateful<State = N>;

    /// New [`Stateful`] if the [`Self::try_transition`] fails. This will be encapsulated in a
    /// [`Recovered`]
    type FailureStateful: Stateful<State = R>;

    /// The error which caused the [`Self::try_transition`] to fail
    type Error;

    /// Attempt to transition the current [`Stateful`] into [`Self::SuccessStateful`]
    ///
    /// On success, a new [`Self::SuccessStateful`] is returned. On failure, a [`Recovered`] is
    /// returned, with the new [`Self::FailureStateful`] and the error which caused the failure
    fn try_transition(
        self,
    ) -> Result<Self::SuccessStateful, Recovered<Self::FailureStateful, Self::Error>>;
}

mod async_try_transitionable {
    use super::*;

    /// Async variant of [`TryTransitionable`]
    #[trait_variant::make(AsyncTryTransitionable: Send)]
    #[allow(dead_code)]
    pub trait LocalAsyncTryTransitionable<N, R>: AsyncTransitionable<R>
    where
        N: State,
        R: State,
    {
        /// New [`Stateful`] if the [`Self::try_transition`] succeeds
        type SuccessStateful: Stateful<State = N>;

        /// New [`Stateful`] if the [`Self::try_transition`] fails. This will be encapsulated in a
        /// [`Recovered`]
        type FailureStateful: Stateful<State = R>;

        /// The error which caused the [`Self::try_transition`] to fail
        type Error;

        /// Attempt to transition the current [`Stateful`] into [`Self::SuccessStateful`]
        ///
        /// On success, a new [`Self::SuccessStateful`] is returned. On failure, a [`Recovered`] is
        /// returned, with the new [`Self::FailureStateful`] and the error which caused the failure
        async fn try_transition(
            self,
        ) -> Result<Self::SuccessStateful, Recovered<Self::FailureStateful, Self::Error>>;
    }
}
pub use async_try_transitionable::AsyncTryTransitionable;

/// Convenience trait to convert [`Result<S, Recovered<F, E>>`] into the error `E`
///
/// Useful for when users of a [`TryTransitionable`] [`Stateful`] do not want to recover the state
/// machine in the [`Recovered`] state.
///
/// Note this is implemented via a blanket implementation on all [`Result<S, Recovered<F, E>>`]
/// types. It should probably not be implemented manually.
pub trait Bailable<N, R>
where
    N: State,
    R: State,
{
    /// The [`Stateful`] a [`TryTransitionable`] returns on success
    type SuccessStateful: Stateful<State = N>;
    /// The error a [`TryTransitionable`] returns via [`Recovered`] on error
    type Error;

    /// Get the underlying error from a failed [`TryTransitionable::try_transition`], or the new
    /// [`Stateful`] if the transition was successful.
    fn into_error(self) -> Result<Self::SuccessStateful, Self::Error>;
}

impl<N, R, S, F, E> Bailable<N, R> for Result<S, Recovered<F, E>>
where
    N: State,
    R: State,
    S: Stateful<State = N>,
    F: Stateful<State = R>,
{
    type SuccessStateful = S;
    type Error = E;

    fn into_error(self) -> Result<Self::SuccessStateful, Self::Error> {
        self.map_err(|recovered| recovered.error)
    }
}

#[cfg(test)]
mod test {
    use crate::{
        AsyncTryTransitionable, Recovered, SelfTransitionable, State, Stateful, TransitionError,
        Transitionable, TryTransitionable,
    };

    use test_log::test;

    macro_rules! empty_states {
        ($($state:ident),+) => {
            $(
                #[derive(State, Debug, Eq, PartialEq)]
                struct $state;
            )*
        };
    }

    macro_rules! transitions {
        ($machine:ident, $(($start:ident,$end:ident)),+) => {
            #[derive(Stateful, Debug, Eq, PartialEq)]
            #[state(S)]
            struct $machine<S: State> {
                state: S
            }
            $(
                impl Transitionable<$end> for $machine<$start> {
                    type NextStateful = $machine<$end>;

                    fn transition(self) -> Self::NextStateful {
                        $machine { state: $end }
                    }
                }
            )*
        };
    }

    #[test]
    fn stateful_derive_with_preceding_attrs() {
        empty_states!(A);

        /// Doc comment preceding the state attribute
        #[derive(Stateful, Debug)]
        #[state(A)]
        struct Machine {
            state: A,
        }

        let machine = Machine { state: A };
        assert_eq!(machine.state, A);
    }

    #[test]
    fn two_state() {
        empty_states!(A, B);
        transitions!(Machine, (A, B), (B, A));

        let a = Machine { state: A };
        let b: Machine<B> = a.transition();
        assert_eq!(b.state, B);
    }

    #[test]
    fn several_state() {
        empty_states!(A, B, C, D, E);
        transitions!(
            Machine,
            (A, B),
            (B, C),
            (C, D),
            (D, E),
            (E, A),
            (D, C),
            (D, B)
        );

        let a = Machine { state: A };
        let b: Machine<B> = a.transition();
        let c: Machine<C> = b.transition();
        let d: Machine<D> = c.transition();
        let b: Machine<B> = <_ as Transitionable<B>>::transition(d);
        assert_eq!(b.state, B);
        let c: Machine<C> = b.transition();
        let d: Machine<D> = c.transition();
        let c: Machine<C> = <_ as Transitionable<C>>::transition(d);
        assert_eq!(c.state, C);
        let d: Machine<D> = c.transition();
        assert_eq!(d.state, D);
        let e: Machine<E> = <_ as Transitionable<E>>::transition(d);
        assert_eq!(e.state, E);
        let a: Machine<A> = e.transition();
        assert_eq!(a.state, A);
    }

    #[test(tokio::test)]
    async fn fallible_transition() {
        empty_states!(A, B, C);
        transitions!(Machine, (A, B), (B, A), (C, A));

        impl Machine<B> {
            fn should_transition(&mut self) -> bool {
                use std::sync::atomic::{AtomicBool, Ordering};

                static SHOULD_TRANSITION: AtomicBool = AtomicBool::new(false);
                SHOULD_TRANSITION.swap(true, Ordering::Relaxed)
            }
        }

        impl TryTransitionable<C, A> for Machine<B> {
            type SuccessStateful = Machine<C>;
            type FailureStateful = Machine<A>;
            type Error = Box<dyn std::error::Error + Send + Sync>;

            fn try_transition(
                mut self,
            ) -> Result<Self::SuccessStateful, Recovered<Self::FailureStateful, Self::Error>>
            {
                if self.should_transition() {
                    Ok(Machine { state: C })
                } else {
                    Err(Recovered {
                        stateful: Machine { state: A },
                        error: "Failed".into(),
                    })
                }
            }
        }

        let a = Machine { state: A };
        let b: Machine<B> = a.transition();

        let recovered = b.try_transition().err().unwrap();
        assert_eq!(recovered.stateful.state, A);

        let success = recovered.stateful.transition().try_transition().unwrap();
        assert_eq!(success.state, C);
    }

    #[test(tokio::test)]
    async fn async_macro_recovery() {
        empty_states!(A, B);

        #[derive(Stateful, SelfTransitionable, Debug, Eq, PartialEq)]
        #[state(S)]
        struct Machine<S: State> {
            state: S,
        }

        impl AsyncTryTransitionable<B, A> for Machine<A> {
            type SuccessStateful = Machine<B>;
            type FailureStateful = Machine<A>;
            type Error = TransitionError;

            async fn try_transition(
                self,
            ) -> Result<Self::SuccessStateful, Recovered<Self::FailureStateful, Self::Error>>
            {
                return_recover_async!(self, "always fails");
            }
        }

        let a = Machine { state: A };
        let recovered = try_transition_async!(a, B).err().unwrap();
        assert_eq!(recovered.stateful.state, A);
    }
}