-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathActiveStateMachine.cs
More file actions
369 lines (321 loc) · 14 KB
/
ActiveStateMachine.cs
File metadata and controls
369 lines (321 loc) · 14 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
// <copyright file="ActiveStateMachine.cs" company="Appccelerate">
// Copyright (c) 2008-2019 Appccelerate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace Appccelerate.StateMachine
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Machine;
using Machine.Events;
using Persistence;
/// <summary>
/// An active state machine.
/// This state machine reacts to events on its own worker thread and the <see cref="Fire(TEvent,object)"/> or
/// <see cref="FirePriority(TEvent,object)"/> methods return immediately back to the caller.
/// </summary>
/// <typeparam name="TState">The type of the state.</typeparam>
/// <typeparam name="TEvent">The type of the event.</typeparam>
public class ActiveStateMachine<TState, TEvent> :
IStateMachine<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
private readonly StateMachine<TState, TEvent> stateMachine;
private readonly StateContainer<TState, TEvent> stateContainer;
private readonly IStateDefinitionDictionary<TState, TEvent> stateDefinitions;
private readonly LinkedList<EventInformation<TEvent>> queue;
private readonly TState initialState;
private Task? worker;
private CancellationTokenSource stopToken = new CancellationTokenSource();
public ActiveStateMachine(
StateMachine<TState, TEvent> stateMachine,
StateContainer<TState, TEvent> stateContainer,
IStateDefinitionDictionary<TState, TEvent> stateDefinitions,
TState initialState)
{
this.stateMachine = stateMachine;
this.stateContainer = stateContainer;
this.stateDefinitions = stateDefinitions;
this.initialState = initialState;
this.queue = new LinkedList<EventInformation<TEvent>>();
}
/// <summary>
/// Occurs when no transition could be executed.
/// </summary>
public event EventHandler<TransitionEventArgs<TState, TEvent>> TransitionDeclined
{
add => this.stateMachine.TransitionDeclined += value;
remove => this.stateMachine.TransitionDeclined -= value;
}
/// <summary>
/// Occurs when an exception was thrown inside a transition of the state machine.
/// </summary>
public event EventHandler<TransitionExceptionEventArgs<TState, TEvent>> TransitionExceptionThrown
{
add => this.stateMachine.TransitionExceptionThrown += value;
remove => this.stateMachine.TransitionExceptionThrown -= value;
}
/// <summary>
/// Occurs when a transition begins.
/// </summary>
public event EventHandler<TransitionEventArgs<TState, TEvent>> TransitionBegin
{
add => this.stateMachine.TransitionBegin += value;
remove => this.stateMachine.TransitionBegin -= value;
}
/// <summary>
/// Occurs when a transition completed.
/// </summary>
public event EventHandler<TransitionCompletedEventArgs<TState, TEvent>> TransitionCompleted
{
add => this.stateMachine.TransitionCompleted += value;
remove => this.stateMachine.TransitionCompleted -= value;
}
/// <summary>
/// Gets a value indicating whether this instance is running. The state machine is running if if was started and not yet stopped.
/// </summary>
/// <value><c>true</c> if this instance is running; otherwise, <c>false</c>.</value>
public bool IsRunning => this.worker != null && !this.worker.IsCompleted;
/// <summary>
/// Fires the specified event.
/// </summary>
/// <param name="eventId">The event.</param>
public void Fire(TEvent eventId)
{
this.Fire(eventId, null);
}
/// <summary>
/// Fires the specified event.
/// </summary>
/// <param name="eventId">The event.</param>
/// <param name="eventArgument">The event argument.</param>
public void Fire(TEvent eventId, object? eventArgument)
{
lock (this.queue)
{
this.queue.AddLast(new EventInformation<TEvent>(eventId, eventArgument));
Monitor.Pulse(this.queue);
}
this.stateContainer.ForEach(extension => extension.EventQueued(this.stateContainer, eventId, eventArgument));
}
/// <summary>
/// Fires the specified priority event. The event will be handled before any already queued event.
/// </summary>
/// <param name="eventId">The event.</param>
public void FirePriority(TEvent eventId)
{
this.FirePriority(eventId, null);
}
/// <summary>
/// Fires the specified priority event. The event will be handled before any already queued event.
/// </summary>
/// <param name="eventId">The event.</param>
/// <param name="eventArgument">The event argument.</param>
public void FirePriority(TEvent eventId, object? eventArgument)
{
lock (this.queue)
{
this.queue.AddFirst(new EventInformation<TEvent>(eventId, eventArgument));
Monitor.Pulse(this.queue);
}
this.stateContainer.ForEach(extension => extension.EventQueuedWithPriority(this.stateContainer, eventId, eventArgument));
}
/// <summary>
/// Saves the current state and history states to a persisted state. Can be restored using <see cref="Load"/>.
/// </summary>
/// <param name="stateMachineSaver">Data to be persisted is passed to the saver.</param>
public void Save(IStateMachineSaver<TState> stateMachineSaver)
{
Guard.AgainstNullArgument(nameof(stateMachineSaver), stateMachineSaver);
stateMachineSaver.SaveCurrentState(this.stateContainer.CurrentStateId);
var historyStates = this.stateContainer
.LastActiveStates
.ToDictionary(
pair => pair.Key,
pair => pair.Value.Id);
stateMachineSaver.SaveHistoryStates(historyStates);
}
/// <summary>
/// Loads the current state and history states from a persisted state (<see cref="Save"/>).
/// The loader should return exactly the data that was passed to the saver.
/// </summary>
/// <param name="stateMachineLoader">Loader providing persisted data.</param>
public void Load(IStateMachineLoader<TState> stateMachineLoader)
{
Guard.AgainstNullArgument(nameof(stateMachineLoader), stateMachineLoader);
this.CheckThatNotAlreadyInitialized();
var loadedCurrentState = stateMachineLoader.LoadCurrentState();
var historyStates = stateMachineLoader.LoadHistoryStates();
SetCurrentState();
LoadHistoryStates();
NotifyExtensions();
void SetCurrentState()
{
this.stateContainer.CurrentState = loadedCurrentState.Map(x => this.stateDefinitions[x]);
}
void LoadHistoryStates()
{
foreach (var historyState in historyStates)
{
var superState = this.stateDefinitions[historyState.Key];
var lastActiveState = this.stateDefinitions[historyState.Value];
if (!superState.SubStates.Contains(lastActiveState))
{
throw new InvalidOperationException(ExceptionMessages.CannotSetALastActiveStateThatIsNotASubState);
}
this.stateContainer.SetLastActiveStateFor(superState.Id, lastActiveState);
}
}
void NotifyExtensions()
{
this.stateContainer.Extensions.ForEach(
extension => extension.Loaded(
this.stateContainer,
loadedCurrentState,
historyStates));
}
}
/// <summary>
/// Starts the state machine. Events will be processed.
/// If the state machine is not started then the events will be queued until the state machine is started.
/// Already queued events are processed.
/// </summary>
public void Start()
{
if (this.IsRunning)
{
return;
}
this.stopToken = new CancellationTokenSource();
this.worker = Task.Factory.StartNew(
() => this.ProcessEventQueue(this.stopToken.Token),
this.stopToken.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
this.stateContainer.ForEach(extension => extension.StartedStateMachine(this.stateContainer));
}
/// <summary>
/// Stops the state machine. Events will be queued until the state machine is started.
/// </summary>
public void Stop()
{
if (!this.IsRunning || this.stopToken.IsCancellationRequested)
{
return;
}
lock (this.queue)
{
this.stopToken.Cancel();
Monitor.Pulse(this.queue); // wake up task to get a chance to stop
}
try
{
this.worker?.Wait();
}
catch (AggregateException)
{
// in case the task was stopped before it could actually start, it will be canceled.
if (this.worker?.IsFaulted ?? false)
{
throw;
}
}
this.worker = null;
this.stateContainer.ForEach(extension => extension.StoppedStateMachine(this.stateContainer));
}
/// <summary>
/// Adds an extension.
/// </summary>
/// <param name="extension">The extension.</param>
public void AddExtension(IExtension<TState, TEvent> extension)
{
this.stateContainer.Extensions.Add(extension);
}
/// <summary>
/// Clears all extensions.
/// </summary>
public void ClearExtensions()
{
this.stateContainer.Extensions.Clear();
}
/// <summary>
/// Creates a state machine report with the specified generator.
/// </summary>
/// <param name="reportGenerator">The report generator.</param>
public void Report(IStateMachineReport<TState, TEvent> reportGenerator)
{
reportGenerator.Report(this.ToString(), this.stateDefinitions.Values, this.initialState);
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return this.stateContainer.Name ?? this.GetType().FullName;
}
private void ProcessEventQueue(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
this.InitializeStateMachineIfInitializationIsPending();
EventInformation<TEvent> eventInformation;
lock (this.queue)
{
if (this.queue.Count > 0)
{
eventInformation = this.queue.First.Value;
this.queue.RemoveFirst();
}
else
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalse because it is multi-threaded and can change in the mean time
if (!cancellationToken.IsCancellationRequested)
{
Monitor.Wait(this.queue);
}
continue;
}
}
this.stateMachine.Fire(
eventInformation.EventId,
eventInformation.EventArgument,
this.stateContainer,
this.stateContainer,
this.stateDefinitions);
}
}
private void InitializeStateMachineIfInitializationIsPending()
{
if (this.stateContainer.CurrentState.IsInitialized)
{
return;
}
this.stateMachine.EnterInitialState(this.stateContainer, this.stateContainer, this.stateDefinitions, this.initialState);
}
private void CheckThatNotAlreadyInitialized()
{
if (this.stateContainer.CurrentState.IsInitialized)
{
throw new InvalidOperationException(ExceptionMessages.StateMachineIsAlreadyInitialized);
}
}
}
}