forked from dotnet-state-machine/stateless
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateMachine.cs
More file actions
589 lines (524 loc) · 26.1 KB
/
StateMachine.cs
File metadata and controls
589 lines (524 loc) · 26.1 KB
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
using Stateless.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Stateless
{
/// <summary>
/// Enum for the different modes used when Fire-ing a trigger
/// </summary>
public enum FiringMode
{
/// <summary> Use immediate mode when the queing of trigger events are not needed. Care must be taken when using this mode, as there is no run-to-completion guaranteed.</summary>
Immediate,
/// <summary> Use the queued Fire-ing mode when run-to-completion is required. This is the recommended mode.</summary>
Queued
}
/// <summary>
/// Models behaviour as transitions between a finite set of states.
/// </summary>
/// <typeparam name="TState">The type used to represent the states.</typeparam>
/// <typeparam name="TTrigger">The type used to represent the triggers that cause state transitions.</typeparam>
public partial class StateMachine<TState, TTrigger>
{
private readonly IDictionary<TState, StateRepresentation> _stateConfiguration = new Dictionary<TState, StateRepresentation>();
private readonly IDictionary<TTrigger, TriggerWithParameters> _triggerConfiguration = new Dictionary<TTrigger, TriggerWithParameters>();
private readonly Func<TState> _stateAccessor;
private readonly Action<TState> _stateMutator;
private UnhandledTriggerAction _unhandledTriggerAction;
private OnTransitionedEvent _onTransitionedEvent;
private readonly FiringMode _firingMode;
private class QueuedTrigger
{
public TTrigger Trigger { get; set; }
public object[] Args { get; set; }
}
private readonly Queue<QueuedTrigger> _eventQueue = new Queue<QueuedTrigger>();
private bool _firing;
/// <summary>
/// Construct a state machine with external state storage.
/// </summary>
/// <param name="stateAccessor">A function that will be called to read the current state value.</param>
/// <param name="stateMutator">An action that will be called to write new state values.</param>
public StateMachine(Func<TState> stateAccessor, Action<TState> stateMutator) :this(stateAccessor, stateMutator, FiringMode.Queued)
{
}
/// <summary>
/// Construct a state machine.
/// </summary>
/// <param name="initialState">The initial state.</param>
public StateMachine(TState initialState) : this(initialState, FiringMode.Queued)
{
}
/// <summary>
/// Construct a state machine with external state storage.
/// </summary>
/// <param name="stateAccessor">A function that will be called to read the current state value.</param>
/// <param name="stateMutator">An action that will be called to write new state values.</param>
/// <param name="firingMode">Optional specification of fireing mode.</param>
public StateMachine(Func<TState> stateAccessor, Action<TState> stateMutator, FiringMode firingMode) : this()
{
_stateAccessor = stateAccessor ?? throw new ArgumentNullException(nameof(stateAccessor));
_stateMutator = stateMutator ?? throw new ArgumentNullException(nameof(stateMutator));
_firingMode = firingMode;
}
/// <summary>
/// Construct a state machine.
/// </summary>
/// <param name="initialState">The initial state.</param>
/// <param name="firingMode">Optional specification of fireing mode.</param>
public StateMachine(TState initialState, FiringMode firingMode) : this()
{
var reference = new StateReference { State = initialState };
_stateAccessor = () => reference.State;
_stateMutator = s => reference.State = s;
_firingMode = firingMode;
}
/// <summary>
/// Default constuctor
/// </summary>
StateMachine()
{
_unhandledTriggerAction = new UnhandledTriggerAction.Sync(DefaultUnhandledTriggerAction);
_onTransitionedEvent = new OnTransitionedEvent();
}
/// <summary>
/// The current state.
/// </summary>
public TState State
{
get
{
return _stateAccessor();
}
private set
{
_stateMutator(value);
}
}
/// <summary>
/// The currently-permissible trigger values.
/// </summary>
public IEnumerable<TTrigger> PermittedTriggers
{
get
{
return GetPermittedTriggers();
}
}
/// <summary>
/// The currently-permissible trigger values.
/// </summary>
public IEnumerable<TTrigger> GetPermittedTriggers(params object[] args)
{
return CurrentRepresentation.GetPermittedTriggers(args);
}
StateRepresentation CurrentRepresentation
{
get
{
return GetRepresentation(State);
}
}
/// <summary>
/// Provides an info object which exposes the states, transitions, and actions of this machine.
/// </summary>
public StateMachineInfo GetInfo()
{
var representations = _stateConfiguration.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var behaviours = _stateConfiguration.SelectMany(kvp => kvp.Value.TriggerBehaviours.SelectMany(b => b.Value.OfType<TransitioningTriggerBehaviour>().Select(tb => tb.Destination))).ToList();
behaviours.AddRange(_stateConfiguration.SelectMany(kvp => kvp.Value.TriggerBehaviours.SelectMany(b => b.Value.OfType<ReentryTriggerBehaviour>().Select(tb => tb.Destination))).ToList());
var reachable = behaviours
.Distinct()
.Except(representations.Keys)
.Select(underlying => new StateRepresentation(underlying))
.ToArray();
foreach (var representation in reachable)
representations.Add(representation.UnderlyingState, representation);
var info = representations.ToDictionary(kvp => kvp.Key, kvp => StateInfo.CreateStateInfo(kvp.Value));
foreach (var state in info)
StateInfo.AddRelationships(state.Value, representations[state.Key], k => info[k]);
return new StateMachineInfo(info.Values, typeof(TState), typeof(TTrigger));
}
StateRepresentation GetRepresentation(TState state)
{
if (!_stateConfiguration.TryGetValue(state, out StateRepresentation result))
{
result = new StateRepresentation(state);
_stateConfiguration.Add(state, result);
}
return result;
}
/// <summary>
/// Begin configuration of the entry/exit actions and allowed transitions
/// when the state machine is in a particular state.
/// </summary>
/// <param name="state">The state to configure.</param>
/// <returns>A configuration object through which the state can be configured.</returns>
public StateConfiguration Configure(TState state)
{
return new StateConfiguration(this, GetRepresentation(state), GetRepresentation);
}
/// <summary>
/// Transition from the current state via the specified trigger.
/// The target state is determined by the configuration of the current state.
/// Actions associated with leaving the current state and entering the new one
/// will be invoked.
/// </summary>
/// <param name="trigger">The trigger to fire.</param>
/// <exception cref="System.InvalidOperationException">The current state does
/// not allow the trigger to be fired.</exception>
public void Fire(TTrigger trigger)
{
InternalFire(trigger, new object[0]);
}
/// <summary>
/// Transition from the current state via the specified trigger.
/// The target state is determined by the configuration of the current state.
/// Actions associated with leaving the current state and entering the new one
/// will be invoked.
/// </summary>
/// <typeparam name="TArg0">Type of the first trigger argument.</typeparam>
/// <param name="trigger">The trigger to fire.</param>
/// <param name="arg0">The first argument.</param>
/// <exception cref="System.InvalidOperationException">The current state does
/// not allow the trigger to be fired.</exception>
public void Fire<TArg0>(TriggerWithParameters<TArg0> trigger, TArg0 arg0)
{
if (trigger == null) throw new ArgumentNullException(nameof(trigger));
InternalFire(trigger.Trigger, arg0);
}
/// <summary>
/// Transition from the current state via the specified trigger.
/// The target state is determined by the configuration of the current state.
/// Actions associated with leaving the current state and entering the new one
/// will be invoked.
/// </summary>
/// <typeparam name="TArg0">Type of the first trigger argument.</typeparam>
/// <typeparam name="TArg1">Type of the second trigger argument.</typeparam>
/// <param name="arg0">The first argument.</param>
/// <param name="arg1">The second argument.</param>
/// <param name="trigger">The trigger to fire.</param>
/// <exception cref="System.InvalidOperationException">The current state does
/// not allow the trigger to be fired.</exception>
public void Fire<TArg0, TArg1>(TriggerWithParameters<TArg0, TArg1> trigger, TArg0 arg0, TArg1 arg1)
{
if (trigger == null) throw new ArgumentNullException(nameof(trigger));
InternalFire(trigger.Trigger, arg0, arg1);
}
/// <summary>
/// Transition from the current state via the specified trigger.
/// The target state is determined by the configuration of the current state.
/// Actions associated with leaving the current state and entering the new one
/// will be invoked.
/// </summary>
/// <typeparam name="TArg0">Type of the first trigger argument.</typeparam>
/// <typeparam name="TArg1">Type of the second trigger argument.</typeparam>
/// <typeparam name="TArg2">Type of the third trigger argument.</typeparam>
/// <param name="arg0">The first argument.</param>
/// <param name="arg1">The second argument.</param>
/// <param name="arg2">The third argument.</param>
/// <param name="trigger">The trigger to fire.</param>
/// <exception cref="System.InvalidOperationException">The current state does
/// not allow the trigger to be fired.</exception>
public void Fire<TArg0, TArg1, TArg2>(TriggerWithParameters<TArg0, TArg1, TArg2> trigger, TArg0 arg0, TArg1 arg1, TArg2 arg2)
{
if (trigger == null) throw new ArgumentNullException(nameof(trigger));
InternalFire(trigger.Trigger, arg0, arg1, arg2);
}
/// <summary>
/// Activates current state. Actions associated with activating the currrent state
/// will be invoked. The activation is idempotent and subsequent activation of the same current state
/// will not lead to re-execution of activation callbacks.
/// </summary>
public void Activate()
{
var representativeState = GetRepresentation(State);
representativeState.Activate();
}
/// <summary>
/// Deactivates current state. Actions associated with deactivating the currrent state
/// will be invoked. The deactivation is idempotent and subsequent deactivation of the same current state
/// will not lead to re-execution of deactivation callbacks.
/// </summary>
public void Deactivate()
{
var representativeState = GetRepresentation(State);
representativeState.Deactivate();
}
/// <summary>
/// Determine how to Fire the trigger
/// </summary>
/// <param name="trigger">The trigger. </param>
/// <param name="args">A variable-length parameters list containing arguments. </param>
void InternalFire(TTrigger trigger, params object[] args)
{
switch (_firingMode)
{
case FiringMode.Immediate:
InternalFireOne(trigger, args);
break;
case FiringMode.Queued:
InternalFireQueued(trigger, args);
break;
default:
// If something is completely messed up we let the user know ;-)
throw new InvalidOperationException("The firing mode has not been configured!");
}
}
/// <summary>
/// Queue events and then fire in order.
/// If only one event is queued, this behaves identically to the non-queued version.
/// </summary>
/// <param name="trigger"> The trigger. </param>
/// <param name="args"> A variable-length parameters list containing arguments. </param>
private void InternalFireQueued(TTrigger trigger, params object[] args)
{
// If a trigger is already being handled then the trigger will be queued (FIFO) and processed later.
if (_firing)
{
_eventQueue.Enqueue(new QueuedTrigger { Trigger = trigger, Args = args });
return;
}
try
{
_firing = true;
InternalFireOne(trigger, args);
// Check if any other triggers have been queued, and fire those as well.
while (_eventQueue.Count != 0)
{
var queuedEvent = _eventQueue.Dequeue();
InternalFireOne(queuedEvent.Trigger, queuedEvent.Args);
}
}
finally
{
_firing = false;
}
}
/// <summary>
/// This method handles the execution of a trigger handler. It finds a
/// handle, then updates the current state information.
/// </summary>
/// <param name="trigger"></param>
/// <param name="args"></param>
void InternalFireOne(TTrigger trigger, params object[] args)
{
// If this is a trigger with parameters, we must validate the parameter(s)
if (_triggerConfiguration.TryGetValue(trigger, out TriggerWithParameters configuration))
configuration.ValidateParameters(args);
var source = State;
var representativeState = GetRepresentation(source);
// Try to find a trigger handler, either in the current state or a super state.
if (!representativeState.TryFindHandler(trigger, args, out TriggerBehaviourResult result))
{
_unhandledTriggerAction.Execute(representativeState.UnderlyingState, trigger, result?.UnmetGuardConditions);
return;
}
switch (result.Handler)
{
// Check if this trigger should be ignored
case IgnoredTriggerBehaviour _:
return;
// Handle special case, re-entry in superstate
// Check if it is an internal transition, or a transition from one state to another.
case ReentryTriggerBehaviour handler:
{
// Handle transition, and set new state
var transition = new Transition(source, handler.Destination, trigger);
HandleReentryTrigger(args, representativeState, transition);
break;
}
case DynamicTriggerBehaviour _ when (result.Handler.ResultsInTransitionFrom(source, args, out var destination)):
case TransitioningTriggerBehaviour _ when (result.Handler.ResultsInTransitionFrom(source, args, out destination)):
{
// Handle transition, and set new state
var transition = new Transition(source, destination, trigger);
HandleTransitioningTrigger(args, representativeState, transition);
break;
}
case InternalTriggerBehaviour _:
{
// Internal transitions does not update the current state, but must execute the associated action.
var transition = new Transition(source, source, trigger);
CurrentRepresentation.InternalAction(transition, args);
break;
}
default:
throw new InvalidOperationException("State machine configuration incorrect, no handler for trigger.");
}
}
private void HandleReentryTrigger(object[] args, StateRepresentation representativeState, Transition transition)
{
StateRepresentation representation;
transition = representativeState.Exit(transition);
var newRepresentation = GetRepresentation(transition.Destination);
if (!transition.Source.Equals(transition.Destination))
{
// Then Exit the final superstate
transition = new Transition(transition.Destination, transition.Destination, transition.Trigger);
newRepresentation.Exit(transition);
_onTransitionedEvent.Invoke(transition);
representation = EnterState(newRepresentation, transition, args);
}
else
{
_onTransitionedEvent.Invoke(transition);
representation = EnterState(newRepresentation, transition, args);
}
State = representation.UnderlyingState;
}
private void HandleTransitioningTrigger( object[] args, StateRepresentation representativeState, Transition transition)
{
transition = representativeState.Exit(transition);
State = transition.Destination;
var newRepresentation = GetRepresentation(transition.Destination);
//Alert all listeners of state transition
_onTransitionedEvent.Invoke(transition);
var representation = EnterState(newRepresentation, transition, args);
State = representation.UnderlyingState;
}
private StateRepresentation EnterState(StateRepresentation representation, Transition transition, object [] args)
{
// Enter the new state
representation.Enter(transition, args);
// Recursively enter substates that have an initial transition
if (representation.HasInitialTransition)
{
// Verify that the target state is a substate
// Check if state has substate(s), and if an initial transition(s) has been set up.
if (!representation.GetSubstates().Any(s => s.UnderlyingState.Equals(representation.InitialTransitionTarget)))
{
throw new InvalidOperationException($"The target ({representation.InitialTransitionTarget}) for the initial transition is not a substate.");
}
var initialTransition = new Transition(transition.Source, representation.InitialTransitionTarget, transition.Trigger);
representation = GetRepresentation(representation.InitialTransitionTarget);
representation = EnterState(representation, initialTransition, args);
}
return representation;
}
/// <summary>
/// Override the default behaviour of throwing an exception when an unhandled trigger
/// is fired.
/// </summary>
/// <param name="unhandledTriggerAction">An action to call when an unhandled trigger is fired.</param>
public void OnUnhandledTrigger(Action<TState, TTrigger> unhandledTriggerAction)
{
if (unhandledTriggerAction == null) throw new ArgumentNullException(nameof(unhandledTriggerAction));
_unhandledTriggerAction = new UnhandledTriggerAction.Sync((s, t, c) => unhandledTriggerAction(s, t));
}
/// <summary>
/// Override the default behaviour of throwing an exception when an unhandled trigger
/// is fired.
/// </summary>
/// <param name="unhandledTriggerAction">An action to call when an unhandled trigger is fired.</param>
public void OnUnhandledTrigger(Action<TState, TTrigger, ICollection<string>> unhandledTriggerAction)
{
if (unhandledTriggerAction == null) throw new ArgumentNullException(nameof(unhandledTriggerAction));
_unhandledTriggerAction = new UnhandledTriggerAction.Sync(unhandledTriggerAction);
}
/// <summary>
/// Determine if the state machine is in the supplied state.
/// </summary>
/// <param name="state">The state to test for.</param>
/// <returns>True if the current state is equal to, or a substate of,
/// the supplied state.</returns>
public bool IsInState(TState state)
{
return CurrentRepresentation.IsIncludedIn(state);
}
/// <summary>
/// Returns true if <paramref name="trigger"/> can be fired
/// in the current state.
/// </summary>
/// <param name="trigger">Trigger to test.</param>
/// <returns>True if the trigger can be fired, false otherwise.</returns>
public bool CanFire(TTrigger trigger)
{
return CurrentRepresentation.CanHandle(trigger);
}
/// <summary>
/// A human-readable representation of the state machine.
/// </summary>
/// <returns>A description of the current state and permitted triggers.</returns>
public override string ToString()
{
return string.Format(
"StateMachine {{ State = {0}, PermittedTriggers = {{ {1} }}}}",
State,
string.Join(", ", GetPermittedTriggers().Select(t => t.ToString()).ToArray()));
}
/// <summary>
/// Specify the arguments that must be supplied when a specific trigger is fired.
/// </summary>
/// <typeparam name="TArg0">Type of the first trigger argument.</typeparam>
/// <param name="trigger">The underlying trigger value.</param>
/// <returns>An object that can be passed to the Fire() method in order to
/// fire the parameterised trigger.</returns>
public TriggerWithParameters<TArg0> SetTriggerParameters<TArg0>(TTrigger trigger)
{
var configuration = new TriggerWithParameters<TArg0>(trigger);
SaveTriggerConfiguration(configuration);
return configuration;
}
/// <summary>
/// Specify the arguments that must be supplied when a specific trigger is fired.
/// </summary>
/// <typeparam name="TArg0">Type of the first trigger argument.</typeparam>
/// <typeparam name="TArg1">Type of the second trigger argument.</typeparam>
/// <param name="trigger">The underlying trigger value.</param>
/// <returns>An object that can be passed to the Fire() method in order to
/// fire the parameterised trigger.</returns>
public TriggerWithParameters<TArg0, TArg1> SetTriggerParameters<TArg0, TArg1>(TTrigger trigger)
{
var configuration = new TriggerWithParameters<TArg0, TArg1>(trigger);
SaveTriggerConfiguration(configuration);
return configuration;
}
/// <summary>
/// Specify the arguments that must be supplied when a specific trigger is fired.
/// </summary>
/// <typeparam name="TArg0">Type of the first trigger argument.</typeparam>
/// <typeparam name="TArg1">Type of the second trigger argument.</typeparam>
/// <typeparam name="TArg2">Type of the third trigger argument.</typeparam>
/// <param name="trigger">The underlying trigger value.</param>
/// <returns>An object that can be passed to the Fire() method in order to
/// fire the parameterised trigger.</returns>
public TriggerWithParameters<TArg0, TArg1, TArg2> SetTriggerParameters<TArg0, TArg1, TArg2>(TTrigger trigger)
{
var configuration = new TriggerWithParameters<TArg0, TArg1, TArg2>(trigger);
SaveTriggerConfiguration(configuration);
return configuration;
}
void SaveTriggerConfiguration(TriggerWithParameters trigger)
{
if (_triggerConfiguration.ContainsKey(trigger.Trigger))
throw new InvalidOperationException(
string.Format(StateMachineResources.CannotReconfigureParameters, trigger));
_triggerConfiguration.Add(trigger.Trigger, trigger);
}
void DefaultUnhandledTriggerAction(TState state, TTrigger trigger, ICollection<string> unmetGuardConditions)
{
if (unmetGuardConditions?.Any() ?? false)
throw new InvalidOperationException(
string.Format(
StateMachineResources.NoTransitionsUnmetGuardConditions,
trigger, state, string.Join(", ", unmetGuardConditions)));
throw new InvalidOperationException(
string.Format(
StateMachineResources.NoTransitionsPermitted,
trigger, state));
}
/// <summary>
/// Registers a callback that will be invoked every time the statemachine
/// transitions from one state into another.
/// </summary>
/// <param name="onTransitionAction">The action to execute, accepting the details
/// of the transition.</param>
public void OnTransitioned(Action<Transition> onTransitionAction)
{
if (onTransitionAction == null) throw new ArgumentNullException(nameof(onTransitionAction));
_onTransitionedEvent.Register(onTransitionAction);
}
}
}