-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathAsyncPassiveStateMachine.cs
More file actions
352 lines (302 loc) · 13.7 KB
/
Copy pathAsyncPassiveStateMachine.cs
File metadata and controls
352 lines (302 loc) · 13.7 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
// <copyright file="AsyncPassiveStateMachine.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.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using AsyncMachine;
using AsyncMachine.Events;
using Persistence;
public class AsyncPassiveStateMachine<TState, TEvent> : IAsyncStateMachine<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
private readonly StateMachine<TState, TEvent> stateMachine;
private readonly ConcurrentQueue<EventInformation<TEvent>> events;
private readonly ConcurrentStack<EventInformation<TEvent>> priorityEvents;
private readonly StateContainer<TState, TEvent> stateContainer;
private readonly IStateDefinitionDictionary<TState, TEvent> stateDefinitions;
private readonly TState initialState;
private bool executing;
public AsyncPassiveStateMachine(
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.events = new ConcurrentQueue<EventInformation<TEvent>>();
this.priorityEvents = new ConcurrentStack<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
{
get; private set;
}
/// <summary>
/// Fires the specified event.
/// </summary>
/// <param name="eventId">The event.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task Fire(TEvent eventId)
{
await this.Fire(eventId, Missing.Value).ConfigureAwait(false);
}
/// <summary>
/// Fires the specified event.
/// </summary>
/// <param name="eventId">The event.</param>
/// <param name="eventArgument">The event argument.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task Fire(TEvent eventId, object? eventArgument)
{
this.events.Enqueue(new EventInformation<TEvent>(eventId, eventArgument));
await this.stateContainer
.ForEach(extension => extension.EventQueued(this.stateContainer, eventId, eventArgument))
.ConfigureAwait(false);
await this.Execute().ConfigureAwait(false);
}
/// <summary>
/// Fires the specified priority event. The event will be handled before any already queued event.
/// </summary>
/// <param name="eventId">The event.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task FirePriority(TEvent eventId)
{
await this.FirePriority(eventId, null).ConfigureAwait(false);
}
/// <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>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task FirePriority(TEvent eventId, object? eventArgument)
{
this.priorityEvents.Push(new EventInformation<TEvent>(eventId, eventArgument));
await this.stateContainer
.ForEach(extension => extension.EventQueuedWithPriority(this.stateContainer, eventId, eventArgument))
.ConfigureAwait(false);
await this.Execute().ConfigureAwait(false);
}
/// <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>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task Start()
{
this.IsRunning = true;
await this.stateContainer.ForEach(extension => extension.StartedStateMachine(this.stateContainer))
.ConfigureAwait(false);
await this.Execute().ConfigureAwait(false);
}
/// <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);
}
public override string ToString()
{
return this.stateContainer.Name ?? this.GetType().FullName;
}
/// <summary>
/// Stops the state machine. Events will be queued until the state machine is started.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task Stop()
{
this.IsRunning = false;
await this.stateContainer.ForEach(extension => extension.StoppedStateMachine(this.stateContainer))
.ConfigureAwait(false);
}
/// <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>
/// 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>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task Save(IAsyncStateMachineSaver<TState> stateMachineSaver)
{
Guard.AgainstNullArgument(nameof(stateMachineSaver), stateMachineSaver);
await stateMachineSaver.SaveCurrentState(this.stateContainer.CurrentStateId)
.ConfigureAwait(false);
var historyStates = this.stateContainer
.LastActiveStates
.ToDictionary(
pair => pair.Key,
pair => pair.Value.Id);
await stateMachineSaver.SaveHistoryStates(historyStates)
.ConfigureAwait(false);
}
/// <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>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task Load(IAsyncStateMachineLoader<TState> stateMachineLoader)
{
Guard.AgainstNullArgument(nameof(stateMachineLoader), stateMachineLoader);
this.CheckThatNotAlreadyInitialized();
var loadedCurrentState = await stateMachineLoader.LoadCurrentState().ConfigureAwait(false);
var historyStates = await stateMachineLoader.LoadHistoryStates().ConfigureAwait(false);
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));
}
}
private void CheckThatNotAlreadyInitialized()
{
if (this.stateContainer.CurrentState.IsInitialized)
{
throw new InvalidOperationException(ExceptionMessages.StateMachineIsAlreadyInitialized);
}
}
private async Task Execute()
{
if (this.executing || !this.IsRunning)
{
return;
}
this.executing = true;
try
{
await this.ProcessQueuedEvents().ConfigureAwait(false);
}
finally
{
this.executing = false;
}
}
private async Task ProcessQueuedEvents()
{
await this.InitializeStateMachineIfInitializationIsPending()
.ConfigureAwait(false);
while (this.priorityEvents.TryPop(out var eventInformation))
{
await this.stateMachine.Fire(
eventInformation.EventId,
eventInformation.EventArgument,
this.stateContainer,
this.stateContainer,
this.stateDefinitions)
.ConfigureAwait(false);
}
while (this.events.TryDequeue(out var eventInformation))
{
await this.stateMachine.Fire(
eventInformation.EventId,
eventInformation.EventArgument,
this.stateContainer,
this.stateContainer,
this.stateDefinitions)
.ConfigureAwait(false);
}
}
private async Task InitializeStateMachineIfInitializationIsPending()
{
if (this.stateContainer.CurrentState.IsInitialized)
{
return;
}
await this.stateMachine.EnterInitialState(this.stateContainer, this.stateContainer, this.stateDefinitions, this.initialState)
.ConfigureAwait(false);
}
}
}