From fddb7f4ea4314fceeb831c4f90d0cf9322d12bbb Mon Sep 17 00:00:00 2001 From: Damian Date: Tue, 2 Jun 2026 19:59:41 -0400 Subject: [PATCH 1/5] Updated notes --- readme.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/readme.md b/readme.md index bfe8b7f..2c88b08 100644 --- a/readme.md +++ b/readme.md @@ -52,7 +52,7 @@ _Thread safe and most customizations can be set on-the-fly!_ * Allows users to hook to external messaging services (TCP/IP, RabbitMQ, DBus, etc.) * State Transition Triggers: * Transitions are triggered by setting the context's next state result: - * On Success: `context.NextState(Result.Ok);` + * On Success: `context.NextState(Result.Success);` * On Error: `context.NextState(Result.Error);` * On Failure: : `context.NextState(Result.Failure);` * State Handlers: @@ -115,7 +115,7 @@ public class BasicState1() : BaseState public async Task OnEnter(Context context) { await Task.Yield(); // Your async work here... - context.NextState(Result.Ok); + context.NextState(Result.Success); } } @@ -124,7 +124,7 @@ public class BasicState2() : BaseState public Task OnEnter(Context context) { // Notice, we did not async/await this method - context.NextState(Result.Ok); + context.NextState(Result.Success); return Task.CompletedTask; } } @@ -133,7 +133,7 @@ public class BasicState3() : BaseState { public Task OnEnter(Context context) { - context.NextState(Result.Ok); + context.NextState(Result.Success); return Task.CompletedTask; } } @@ -190,7 +190,7 @@ public class Composite_State1() : BaseState var cnt = context.ParameterAsInt(ParameterType.Counter); var blank = context.ParameterAsBool(ParameterType.DummyBool); - context.NextState(Result.Ok); + context.NextState(Result.Success); return Task.CompletedTask; } } @@ -200,14 +200,14 @@ public class Composite_State2() : BaseState public override Task OnEnter(Context context) { // Signify we're ready to go to sub-states - context.NextState(Result.Ok); + context.NextState(Result.Success); return Task.CompletedTask; } public override Task OnExit(Context context) { // Signify we're ready to go to next state after composite - context.NextState(Result.Ok); + context.NextState(Result.Success); return Task.CompletedTask; } } @@ -219,7 +219,7 @@ public class Composite_State2_Sub1() : BaseState // Safely add/update key-value in Context context.Parameters.SafeAdd("StringBasedParamKey", SUCCESS); - context.NextState(Result.Ok); + context.NextState(Result.Success); return Task.CompletedTask; } } @@ -228,7 +228,7 @@ public class Composite_State2_Sub2() : BaseState { public override Task OnEnter(Context context) { - context.NextState(Result.Ok); + context.NextState(Result.Success); return Task.CompletedTask; } } @@ -237,7 +237,7 @@ public class Composite_State3() : BaseState { public override Task OnEnter(Context context) { - context.NextState(Result.Ok); + context.NextState(Result.Success); return Task.CompletedTask; } } From ff69315edbc6cde15a675bcdb6d70cf7f41448ae Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sat, 14 Nov 2026 20:20:20 -0500 Subject: [PATCH 2/5] Added example using Lite.EventIPC instead of the built in EventAggregator --- Directory.Packages.props | 3 +- samples/Sample06.PassingEvents/Program.cs | 2 + .../Sample06.PassingEvents.csproj | 2 +- .../Sample10.UsingEventIPC/CompletedState.cs | 22 ++++ .../Sample10.UsingEventIPC/EventIpcAdapter.cs | 89 +++++++++++++++ .../Sample10.UsingEventIPC/PreparingState.cs | 22 ++++ samples/Sample10.UsingEventIPC/Program.cs | 43 +++++++- .../Sample10.UsingEventIPC.csproj | 10 +- samples/Sample10.UsingEventIPC/StartWork.cs | 6 ++ samples/Sample10.UsingEventIPC/StateId.cs | 11 ++ .../Sample10.UsingEventIPC/WaitingState.cs | 66 ++++++++++++ samples/Sample10.UsingEventIPC/WorkRequest.cs | 6 ++ .../Sample10.UsingEventIPC/WorkResponse.cs | 6 ++ samples/Sample10.UsingEventIPC/readme.md | 68 +++++++++++- .../Lite.StateMachine.Tests.csproj | 3 +- .../StateTests/EventIpcAdapterTests.cs | 102 ++++++++++++++++++ .../Lite.StateMachine.csproj | 2 +- 17 files changed, 454 insertions(+), 9 deletions(-) create mode 100644 samples/Sample10.UsingEventIPC/CompletedState.cs create mode 100644 samples/Sample10.UsingEventIPC/EventIpcAdapter.cs create mode 100644 samples/Sample10.UsingEventIPC/PreparingState.cs create mode 100644 samples/Sample10.UsingEventIPC/StartWork.cs create mode 100644 samples/Sample10.UsingEventIPC/StateId.cs create mode 100644 samples/Sample10.UsingEventIPC/WaitingState.cs create mode 100644 samples/Sample10.UsingEventIPC/WorkRequest.cs create mode 100644 samples/Sample10.UsingEventIPC/WorkResponse.cs create mode 100644 source/Lite.StateMachine.Tests/StateTests/EventIpcAdapterTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index b6c8bc4..fa87d25 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -4,6 +4,7 @@ + @@ -21,4 +22,4 @@ --> - \ No newline at end of file + diff --git a/samples/Sample06.PassingEvents/Program.cs b/samples/Sample06.PassingEvents/Program.cs index d1d7bdd..78417fe 100644 --- a/samples/Sample06.PassingEvents/Program.cs +++ b/samples/Sample06.PassingEvents/Program.cs @@ -1,6 +1,8 @@ // Copyright Xeno Innovations, Inc. 2026 // See the LICENSE file in the project root for more information. +using System; + namespace Sample06.PassingEvents; internal class Program diff --git a/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj b/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj index ed9781c..2f6f13c 100644 --- a/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj +++ b/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj @@ -3,7 +3,7 @@ Exe net10.0 - enable + disable enable diff --git a/samples/Sample10.UsingEventIPC/CompletedState.cs b/samples/Sample10.UsingEventIPC/CompletedState.cs new file mode 100644 index 0000000..7a6bb0e --- /dev/null +++ b/samples/Sample10.UsingEventIPC/CompletedState.cs @@ -0,0 +1,22 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Threading.Tasks; +using Lite.StateMachine; + +namespace Sample10.UsingEventIPC; + +internal sealed class CompletedState : IState +{ + public Task OnEnter(Context context) + { + Console.WriteLine($"Completed: {context.Parameters["Response"]}"); + context.NextState(Result.Success); + return Task.CompletedTask; + } + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) => Task.CompletedTask; +} diff --git a/samples/Sample10.UsingEventIPC/EventIpcAdapter.cs b/samples/Sample10.UsingEventIPC/EventIpcAdapter.cs new file mode 100644 index 0000000..8cad152 --- /dev/null +++ b/samples/Sample10.UsingEventIPC/EventIpcAdapter.cs @@ -0,0 +1,89 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using IpcEvents = Lite.EventIpc.IEventAggregator; + +namespace Sample10.UsingEventIPC; + +/// Adapts the sample's known event types to the state machine's event contract. +internal sealed class EventIpcAdapter(IpcEvents events) : Lite.StateMachine.IEventAggregator +{ + private readonly Dictionary _bindings = []; + + public void Publish(object message) + { + if (message is null) + return; + + // Publishing as object directly through EventIPC would select object + // subscribers, so dispatch using the message's exact runtime type. + GetBinding(message.GetType()).Publish(message); + } + + // Register all message types before starting the machine. This also defines + // the universe of messages delivered to a wildcard subscription. + public EventIpcAdapter RegisterMessageType() + { + _bindings.Add(typeof(T), new MessageBinding( + message => events.Publish((T)message), + handler => + { + Action forward = message => handler(message!); + events.Subscribe(forward); + + // Keep the delegate alive: Lite.EventIpc stores weak references. + return new Subscription(() => events.Unsubscribe(forward)); + })); + return this; + } + + public IDisposable Subscribe(Action handler) => Subscribe(handler, []); + + public IDisposable Subscribe(Action handler, params Type[] messageTypes) + { + ArgumentNullException.ThrowIfNull(handler); + Type[] types1 = [.. _bindings.Keys]; + var types = messageTypes is null || messageTypes.Length == 0 + ? types1 + : [.. messageTypes.Where(type => type is not null).Distinct()]; + + // Validate before subscribing so an unknown type cannot leak subscriptions. + var bindings = types.Select(GetBinding).ToArray(); + var subscriptions = bindings.Select(binding => binding.Subscribe(message => + { + // Match the built-in aggregator's exception isolation. + try + { + handler(message); + } + catch + { + // One subscriber must not interrupt publication to other subscribers. + } + })).ToArray(); + + return new Subscription(() => + { + foreach (var subscription in subscriptions) + subscription.Dispose(); + }); + } + + private MessageBinding GetBinding(Type type) => + _bindings.TryGetValue(type, out var binding) + ? binding + : throw new NotSupportedException($"Register message type '{type.Name}' with RegisterMessageType() first."); + + private sealed record MessageBinding(Action Publish, Func, IDisposable> Subscribe); + + private sealed class Subscription(Action unsubscribe) : IDisposable + { + private Action? _unsubscribe = unsubscribe; + + public void Dispose() => Interlocked.Exchange(ref _unsubscribe, null)?.Invoke(); + } +} diff --git a/samples/Sample10.UsingEventIPC/PreparingState.cs b/samples/Sample10.UsingEventIPC/PreparingState.cs new file mode 100644 index 0000000..1f1974e --- /dev/null +++ b/samples/Sample10.UsingEventIPC/PreparingState.cs @@ -0,0 +1,22 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Threading.Tasks; +using Lite.StateMachine; + +namespace Sample10.UsingEventIPC; + +internal sealed class PreparingState : IState +{ + public Task OnEnter(Context context) + { + Console.WriteLine("Preparing: starting the sample."); + context.NextState(Result.Success); + return Task.CompletedTask; + } + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) => Task.CompletedTask; +} diff --git a/samples/Sample10.UsingEventIPC/Program.cs b/samples/Sample10.UsingEventIPC/Program.cs index a0c54c5..686efea 100644 --- a/samples/Sample10.UsingEventIPC/Program.cs +++ b/samples/Sample10.UsingEventIPC/Program.cs @@ -1,12 +1,51 @@ // Copyright Xeno Innovations, Inc. 2026 // See the LICENSE file in the project root for more information. +using System; +using System.Threading; +using System.Threading.Tasks; +using Lite.StateMachine; +using IpcEventAggregator = Lite.EventIpc.EventAggregator; + namespace Sample10.UsingEventIPC; internal class Program { - private static void Main(string[] args) + private static async Task Main() { - Console.WriteLine("Coming Soon!"); + var events = new IpcEventAggregator(); + var adapter = new EventIpcAdapter(events) + .RegisterMessageType(); + + // Retain this delegate until the machine finishes (EventIPC uses weak references). + Func> worker = async request => + { + Console.WriteLine($"Worker: processing '{request.Text}'..."); + await Task.Delay(100); + return new WorkResponse(request.Text.ToUpperInvariant()); + }; + + events.SubscribeRequest(worker); + + try + { + var machine = new StateMachine( + containerFactory: type => (type == typeof(WaitingState)) ? new WaitingState(events) : Activator.CreateInstance(type), + eventAggregator: adapter) + .RegisterState(StateId.Preparing, onSuccess: StateId.Waiting) + .RegisterState(StateId.Waiting, onSuccess: StateId.Completed) + .RegisterState(StateId.Completed); + + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await machine.RunAsync(StateId.Preparing, cancellation.Token); + + // RunAsync can also return after cancellation; require actual completion. + if (machine.Context.CurrentStateId != StateId.Completed) + throw new InvalidOperationException("The sample did not reach the completed state."); + } + finally + { + events.UnsubscribeRequest(worker); + } } } diff --git a/samples/Sample10.UsingEventIPC/Sample10.UsingEventIPC.csproj b/samples/Sample10.UsingEventIPC/Sample10.UsingEventIPC.csproj index ed9781c..3d13820 100644 --- a/samples/Sample10.UsingEventIPC/Sample10.UsingEventIPC.csproj +++ b/samples/Sample10.UsingEventIPC/Sample10.UsingEventIPC.csproj @@ -1,10 +1,16 @@ - + Exe net10.0 - enable + disable enable + + + + + + diff --git a/samples/Sample10.UsingEventIPC/StartWork.cs b/samples/Sample10.UsingEventIPC/StartWork.cs new file mode 100644 index 0000000..8411425 --- /dev/null +++ b/samples/Sample10.UsingEventIPC/StartWork.cs @@ -0,0 +1,6 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +namespace Sample10.UsingEventIPC; + +internal sealed record StartWork(string Text); diff --git a/samples/Sample10.UsingEventIPC/StateId.cs b/samples/Sample10.UsingEventIPC/StateId.cs new file mode 100644 index 0000000..8cd3ac1 --- /dev/null +++ b/samples/Sample10.UsingEventIPC/StateId.cs @@ -0,0 +1,11 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +namespace Sample10.UsingEventIPC; + +internal enum StateId +{ + Preparing, + Waiting, + Completed, +} diff --git a/samples/Sample10.UsingEventIPC/WaitingState.cs b/samples/Sample10.UsingEventIPC/WaitingState.cs new file mode 100644 index 0000000..9a67e98 --- /dev/null +++ b/samples/Sample10.UsingEventIPC/WaitingState.cs @@ -0,0 +1,66 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Lite.StateMachine; +using IpcEvents = Lite.EventIpc.IEventAggregator; + +namespace Sample10.UsingEventIPC; + +internal sealed class WaitingState(IpcEvents events) : ICommandState +{ + public IReadOnlyCollection SubscribedMessageTypes => [typeof(StartWork)]; + + // The request's own deadline is shorter than the command state's timeout. + public int? TimeoutMs => 5000; + + public Task OnEnter(Context context) + { + Console.WriteLine("Waiting: publishing StartWork through the adapter."); + + // The machine subscribes before OnEnter. No delay is needed for readiness. + // An external component could equivalently call events.Publish(new StartWork(...)). + context.EventAggregator!.Publish(new StartWork("hello from Lite.EventIPC")); + return Task.CompletedTask; + } + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) => Task.CompletedTask; + + public async Task OnMessage(Context context, object message) + { + if (message is not StartWork start) + return; + + Console.WriteLine("Waiting.OnMessage: awaiting WorkResponse..."); + try + { + // Use the native EventIPC interface for request/response. Publish and + // PublishAsync do not await the state machine's async OnMessage callback. + var response = await events.RequestAsync(new WorkRequest(start.Text)) + .WaitAsync(TimeSpan.FromSeconds(2)) + ?? throw new InvalidOperationException("The worker returned no response."); + + context.Parameters["Response"] = response.Text; + + Console.WriteLine($"Waiting.OnMessage: received '{response.Text}'."); + context.NextState(Result.Success); + } + catch (Exception exception) + { + // OnMessage exceptions are otherwise swallowed by the state machine. + Console.WriteLine($"Waiting.OnMessage: {exception.Message}"); + context.NextState(Result.Error); + } + } + + public Task OnTimeout(Context context) + { + Console.WriteLine("Waiting: command timed out."); + context.NextState(Result.Error); + return Task.CompletedTask; + } +} diff --git a/samples/Sample10.UsingEventIPC/WorkRequest.cs b/samples/Sample10.UsingEventIPC/WorkRequest.cs new file mode 100644 index 0000000..b498a8f --- /dev/null +++ b/samples/Sample10.UsingEventIPC/WorkRequest.cs @@ -0,0 +1,6 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +namespace Sample10.UsingEventIPC; + +internal sealed record WorkRequest(string Text); diff --git a/samples/Sample10.UsingEventIPC/WorkResponse.cs b/samples/Sample10.UsingEventIPC/WorkResponse.cs new file mode 100644 index 0000000..d7b1794 --- /dev/null +++ b/samples/Sample10.UsingEventIPC/WorkResponse.cs @@ -0,0 +1,6 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +namespace Sample10.UsingEventIPC; + +internal sealed record WorkResponse(string Text); diff --git a/samples/Sample10.UsingEventIPC/readme.md b/samples/Sample10.UsingEventIPC/readme.md index 8e36786..3fa74c5 100644 --- a/samples/Sample10.UsingEventIPC/readme.md +++ b/samples/Sample10.UsingEventIPC/readme.md @@ -1,3 +1,69 @@ # Sample 10 - Using Lite.EventIPC for External Event Aggregator -_Coming Soon_ +Lite.StateMachine can use an external event aggregator through its constructor's +`eventAggregator` parameter. The interfaces in the two libraries differ, so this +sample supplies `EventIpcAdapter`, which implements `Lite.StateMachine.IEventAggregator` +and delegates event delivery to the NuGet package `Lite.EventIpc` (1.3.2). +The core state machine library requires no changes. + +Run from the repository root with the .NET 10 SDK or newer: + +```powershell +dotnet run --project samples/Sample10.UsingEventIPC +``` + +## State flow + +1. `PreparingState` performs a basic setup step and advances to `WaitingState`. +2. `WaitingState` is an `ICommandState` subscribed to `StartWork`. + Its `OnEnter` publishes that event through `context.EventAggregator`. + The machine has already subscribed, so the message reaches `OnMessage`. +3. Inside `OnMessage`, the state calls the native EventIPC + `RequestAsync` and **awaits the response** from an + asynchronous worker. It saves the response in the context, then calls + `context.NextState(Result.Success)`. +4. `CompletedState` prints the saved response and finishes the machine. + +Expected output: + +```text +Preparing: starting the sample. +Waiting: publishing StartWork through the adapter. +Waiting.OnMessage: awaiting WorkResponse... +Worker: processing 'hello from Lite.EventIPC'... +Waiting.OnMessage: received 'HELLO FROM LITE.EVENTIPC'. +Completed: HELLO FROM LITE.EVENTIPC +``` + +## Adapter and async behavior + +```csharp +var events = new Lite.EventIpc.EventAggregator(); +var adapter = new EventIpcAdapter(events) + .RegisterMessageType(); + +var machine = new StateMachine(eventAggregator: adapter); +``` + +Register every one-way message type with the adapter before running the machine. +It preserves exact runtime type dispatch, deduplicates subscription types, and +implements wildcard subscriptions over those registered types. Unknown types +throw `NotSupportedException`. Native request/response types (`WorkRequest` and +`WorkResponse`) need no adapter registration because they use EventIPC directly. +Other components can publish typed events directly on the same `events` instance. + +Subscriptions retain their delegates because EventIPC uses weak references. +Disposing a state machine subscription unsubscribes its EventIPC delegates; +the sample also explicitly unregisters its worker when finished. + +The state machine's subscription API accepts `Action`, so neither +`Publish` nor EventIPC's `PublishAsync` waits for an asynchronous `OnMessage` to +finish. Instead, await `machine.RunAsync(...)` for the state flow and call +`NextState` only after awaited work completes. The example uses `WaitAsync` to +bound the response wait to two seconds, a five-second command timeout, and a +ten-second run cancellation guard. The response deadline stops waiting; it does +not cancel the worker. Errors and timeouts end the flow without reaching +`CompletedState`, and the executable reports failure. + +This sample uses EventIPC's **local** event aggregator and request/response +support. It does not configure a named pipe, TCP, or other IPC transport. diff --git a/source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj b/source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj index bcc24c4..5130ec1 100644 --- a/source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj +++ b/source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -12,6 +12,7 @@ + diff --git a/source/Lite.StateMachine.Tests/StateTests/EventIpcAdapterTests.cs b/source/Lite.StateMachine.Tests/StateTests/EventIpcAdapterTests.cs new file mode 100644 index 0000000..4afc5bf --- /dev/null +++ b/source/Lite.StateMachine.Tests/StateTests/EventIpcAdapterTests.cs @@ -0,0 +1,102 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Sample10.UsingEventIPC; +using IpcEventAggregator = Lite.EventIpc.EventAggregator; + +namespace Lite.StateMachine.Tests.StateTests; + +[TestClass] +public class EventIpcAdapterTests +{ + [TestMethod] + public void RuntimeTypesWildcardsAndDisposalTest() + { + var events = new IpcEventAggregator(); + var adapter = new EventIpcAdapter(events) + .RegisterMessageType() + .RegisterMessageType(); + + IEventAggregator machineEvents = adapter; + var typedCount = 0; + var wildcardCount = 0; + var nativeCount = 0; + + Action nativeHandler = _ => nativeCount++; + events.Subscribe(nativeHandler); + + var typed = adapter.Subscribe(_ => typedCount++, typeof(string), typeof(string)); + var wildcard = adapter.Subscribe(_ => wildcardCount++); + + // Subscriptions must retain EventIPC's weak delegates while active. + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + // Both the object and generic contract must select the runtime string type. + machineEvents.Publish((object)"first"); + machineEvents.Publish("second"); + events.Publish(42); + Assert.AreEqual(2, typedCount); + Assert.AreEqual(3, wildcardCount); + Assert.AreEqual(2, nativeCount); + + typed.Dispose(); + typed.Dispose(); + events.Publish("third"); + Assert.AreEqual(2, typedCount); + Assert.AreEqual(4, wildcardCount); + + wildcard.Dispose(); + events.Publish("fourth"); + Assert.AreEqual(4, wildcardCount); + events.Unsubscribe(nativeHandler); + } + + [TestMethod] + public async Task OnMessageAwaitsResponseBeforeTransitionAsync() + { + var events = new IpcEventAggregator(); + var adapter = new EventIpcAdapter(events).RegisterMessageType(); + var response = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var requested = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + Func> worker = request => + { + requested.SetResult(); + return response.Task; + }; + + events.SubscribeRequest(worker); + + var machine = new StateMachine( + containerFactory: type => type == typeof(WaitingState) + ? new WaitingState(events) + : Activator.CreateInstance(type), + eventAggregator: adapter) + .RegisterState(StateId.Preparing, onSuccess: StateId.Waiting) + .RegisterState(StateId.Waiting, onSuccess: StateId.Completed) + .RegisterState(StateId.Completed); + + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + try + { + var running = machine.RunAsync(StateId.Preparing, cancellation.Token); + await requested.Task.WaitAsync(cancellation.Token); + Assert.IsFalse(running.IsCompleted); + Assert.AreEqual(StateId.Waiting, machine.Context.CurrentStateId); + + response.SetResult(new WorkResponse("Worker finished")); + await running.WaitAsync(cancellation.Token); + Assert.AreEqual(StateId.Completed, machine.Context.CurrentStateId); + Assert.AreEqual("Worker finished", machine.Context.Parameters["Response"]); + } + finally + { + events.UnsubscribeRequest(worker); + } + } +} diff --git a/source/Lite.StateMachine/Lite.StateMachine.csproj b/source/Lite.StateMachine/Lite.StateMachine.csproj index 08e3beb..c02812e 100644 --- a/source/Lite.StateMachine/Lite.StateMachine.csproj +++ b/source/Lite.StateMachine/Lite.StateMachine.csproj @@ -1,7 +1,7 @@  - net10.0 + net10.0 From 6d171adc70e31384317ad1e5f1dda2313031ada4 Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sat, 14 Nov 2026 20:32:12 -0500 Subject: [PATCH 3/5] support .net 11 --- Directory.Build.props | 4 ++-- source/Lite.StateMachine/Lite.StateMachine.csproj | 5 ----- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 3a3a01b..3707c69 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,10 +1,10 @@ - net10.0 + net10.0;net11.0 latest True - 2.4.1 + 2.4.2 ../../output/$(MSBuildProjectName) true diff --git a/source/Lite.StateMachine/Lite.StateMachine.csproj b/source/Lite.StateMachine/Lite.StateMachine.csproj index c02812e..902e73b 100644 --- a/source/Lite.StateMachine/Lite.StateMachine.csproj +++ b/source/Lite.StateMachine/Lite.StateMachine.csproj @@ -1,9 +1,4 @@  - - - net10.0 - - Lite State Machine Flexible lightweight finite state machine (FSM) for .NET supporting shared context for passing parameters, composite (sub) states, command states, lazy-loading and thread safe. Cross-platform and optimized for speed for use in enterprise, robotic and even tiny applications. From f439661da81cb0b7f895fa36d7a3bb292efd03eb Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sat, 14 Nov 2026 20:42:41 -0500 Subject: [PATCH 4/5] Added Command State and PassingEvents samples --- samples/Sample05.CommandStates/Program.cs | 145 ++++++++++++++++- .../Sample05.CommandStates.csproj | 6 +- samples/Sample05.CommandStates/readme.md | 30 +++- samples/Sample06.PassingEvents/Program.cs | 148 +++++++++++++++++- .../Sample06.PassingEvents.csproj | 6 +- samples/Sample06.PassingEvents/readme.md | 33 +++- 6 files changed, 358 insertions(+), 10 deletions(-) diff --git a/samples/Sample05.CommandStates/Program.cs b/samples/Sample05.CommandStates/Program.cs index fd3bfc6..0ab3b80 100644 --- a/samples/Sample05.CommandStates/Program.cs +++ b/samples/Sample05.CommandStates/Program.cs @@ -1,12 +1,153 @@ // Copyright Xeno Innovations, Inc. 2026 // See the LICENSE file in the project root for more information. +using Lite.StateMachine; + namespace Sample05.CommandStates; +/// +/// Demonstrates command states that request simulated device actions and wait +/// for their results in OnMessage before choosing the next state. +/// +/// +/// State1 connects successfully; +/// State2 deliberately fails to start the device; +/// State3 recovers by closing its safety door; +/// State4 simulates a sensor error; +/// and State5 cleans up and disconnects. +/// +/// Console output explains each action, result, and transition +/// through the success, failure, and error paths. +/// +/// All states and the simulated worker are defined in this file; no hardware is required. +/// internal class Program { - private static void Main(string[] args) + private enum StateId + { + State1, + State2, + State3, + State4, + State5, + } + + private static async Task Main() + { + Console.WriteLine("Command states: perform actions and follow their results."); + Console.WriteLine("Expected: State1 --Success--> State2 --Failure--> State3 --Success--> State4 --Error--> State5."); + var events = new EventAggregator(); + + // A stand-in for a device or application service. Failures are deliberate + // so every run demonstrates success, expected failure, and error handling. + using var worker = events.Subscribe(message => + { + if (message is not ActionCommand command) + return; + + var result = command.State switch + { + StateId.State2 => Result.Failure, + StateId.State4 => Result.Error, + _ => Result.Success, + }; + Console.WriteLine($" Worker: {command.Action} => {result}"); + events.Publish(new ActionCompleted(command.State, result)); + }, + typeof(ActionCommand)); + + var machine = new StateMachine(eventAggregator: events) + .RegisterState(StateId.State1, onSuccess: StateId.State2) + .RegisterState(StateId.State2, onFailure: StateId.State3) + .RegisterState(StateId.State3, onSuccess: StateId.State4) + .RegisterState(StateId.State4, onError: StateId.State5) + .RegisterState(StateId.State5); + + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await machine.RunAsync(StateId.State1, cancellation.Token); + + if (machine.Context.CurrentStateId != StateId.State5 || + !machine.Context.ParameterAsBool("Completed")) + { + throw new InvalidOperationException("The sample did not complete its expected actions."); + } + + Console.WriteLine("Done: success, failure recovery, and error cleanup were demonstrated."); + } + + private sealed record ActionCommand(StateId State, string Action); + + private sealed record ActionCompleted(StateId State, Result Result); + + // Shared command plumbing; each numbered state below defines its action. + private abstract class CommandState : ICommandState + { + public IReadOnlyCollection SubscribedMessageTypes => [typeof(ActionCompleted)]; + + protected abstract string Action { get; } + + public Task OnEnter(Context context) + { + Console.WriteLine($"{context.CurrentStateId}: requesting '{Action}'. Waiting for ActionCompleted in OnMessage."); + context.EventAggregator!.Publish(new ActionCommand(context.CurrentStateId, Action)); + + // Returning from OnEnter does not advance a command state. + // OnMessage must call NextState after receiving the action's result. + return Task.CompletedTask; + } + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) + { + Console.WriteLine($"{context.CurrentStateId}: exiting."); + return Task.CompletedTask; + } + + public Task OnMessage(Context context, object message) + { + if (message is ActionCompleted completed && completed.State == context.CurrentStateId) + { + Console.WriteLine($"{context.CurrentStateId}.OnMessage: action returned {completed.Result}."); + if (context.CurrentStateId == StateId.State5 && completed.Result == Result.Success) + context.Parameters["Completed"] = true; + + context.NextState(completed.Result); + } + + return Task.CompletedTask; + } + + public Task OnTimeout(Context context) + { + Console.WriteLine($"{context.CurrentStateId}: no action result arrived; ending with Error."); + context.NextState(Result.Error); + return Task.CompletedTask; + } + } + + private sealed class State1 : CommandState + { + protected override string Action => "Connect to the device (success expected)"; + } + + private sealed class State2 : CommandState + { + protected override string Action => "Start the device while its safety door is open (failure expected)"; + } + + private sealed class State3 : CommandState + { + protected override string Action => "Recover from State2's failure by closing the safety door (success expected)"; + } + + private sealed class State4 : CommandState + { + protected override string Action => "Read a sensor with a simulated communication fault (error expected)"; + } + + private sealed class State5 : CommandState { - Console.WriteLine("Coming Soon!"); + protected override string Action => "Clean up after State4's error and disconnect (success expected)"; } } diff --git a/samples/Sample05.CommandStates/Sample05.CommandStates.csproj b/samples/Sample05.CommandStates/Sample05.CommandStates.csproj index ed9781c..4e9e710 100644 --- a/samples/Sample05.CommandStates/Sample05.CommandStates.csproj +++ b/samples/Sample05.CommandStates/Sample05.CommandStates.csproj @@ -1,4 +1,4 @@ - + Exe @@ -7,4 +7,8 @@ enable + + + + diff --git a/samples/Sample05.CommandStates/readme.md b/samples/Sample05.CommandStates/readme.md index 936c98f..a51822c 100644 --- a/samples/Sample05.CommandStates/readme.md +++ b/samples/Sample05.CommandStates/readme.md @@ -1,5 +1,31 @@ # Sample 05 - Command States -_Coming Soon_ +All states (`State1` through `State5`), messages, and the simulated worker are in +`Program.cs`. Each state implements `ICommandState` through a small shared +`CommandState` base class that handles subscriptions, results, and timeouts. -See, Unit Tests, for an example of how to use Command States for now. +Run from the repository root: + +```powershell +dotnet run --project samples/Sample05.CommandStates --framework net10.0 +``` + +| State | Intended action | Result | Next state | +| --- | --- | --- | --- | +| State1 | Connect to a device | Success | State2 | +| State2 | Try starting with the safety door open | Failure | State3 | +| State3 | Recover by closing the door | Success | State4 | +| State4 | Read a sensor with a simulated communication fault | Error | State5 | +| State5 | Clean up and disconnect | Success | End | + +`OnEnter` publishes an `ActionCommand` to a simulated device service using the +built-in event aggregator. The service prints its action and publishes an +`ActionCompleted` result. The active state's `OnMessage` checks the state ID and +calls `context.NextState(result)` to select `onSuccess`, `onFailure`, or `onError`. +Returning from `OnEnter` alone does not advance a command state. + +The worker deliberately returns `Failure` for State2 and `Error` for State4 so +every run demonstrates all three outcomes. No hardware or external service is +required. Each state logs its request, received result, and exit. Missing results +use the machine's default command timeout; the executable also has a ten-second +cancellation guard and verifies that cleanup completed. diff --git a/samples/Sample06.PassingEvents/Program.cs b/samples/Sample06.PassingEvents/Program.cs index 78417fe..47c06f9 100644 --- a/samples/Sample06.PassingEvents/Program.cs +++ b/samples/Sample06.PassingEvents/Program.cs @@ -2,13 +2,157 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Lite.StateMachine; namespace Sample06.PassingEvents; +/// +/// Demonstrates passing typed order data through command states using the +/// built-in event aggregator and each state's OnMessage handler. +/// +/// +/// State1 creates an order for three notebooks; +/// State2 awaits a simulated price lookup and calculates the total; +/// State3 prints the receipt. +/// +/// The shared context holds each outgoing payload until the next state subscribes and publishes it, +/// because the aggregator does not queue events for future states. +/// +/// Console output traces the messages and their data. +/// All states and message types are defined in this file. +/// internal class Program { - private static void Main(string[] args) + private enum StateId { - Console.WriteLine("Coming Soon!"); + State1, + State2, + State3, + } + + private static async Task Main() + { + Console.WriteLine("Passing events: State1 creates an order, State2 prices it, State3 prints the receipt."); + var events = new EventAggregator(); + var machine = new StateMachine(eventAggregator: events) + .RegisterState(StateId.State1, onSuccess: StateId.State2) + .RegisterState(StateId.State2, onSuccess: StateId.State3) + .RegisterState(StateId.State3); + + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await machine.RunAsync(StateId.State1, cancellation.Token); + + if (!machine.Context.ParameterAsBool("Completed")) + throw new InvalidOperationException("The sample did not produce its receipt."); + + Console.WriteLine("Done: each state received its typed payload through OnMessage."); + } + + private sealed record OrderCreated(string Product, int Quantity); + + private sealed record PriceRequested(string Product, int Quantity); + + private sealed record OrderPriced(string Product, int Quantity, decimal Total); + + // The aggregator only delivers to the current command state; it does not + // queue events for future states. Context carries each outgoing payload until + // the next state's OnEnter publishes it after that state's subscription exists. + private abstract class EventState : ICommandState + { + public abstract IReadOnlyCollection SubscribedMessageTypes { get; } + + public abstract Task OnEnter(Context context); + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) => Task.CompletedTask; + + public abstract Task OnMessage(Context context, object message); + + public Task OnTimeout(Context context) + { + Console.WriteLine($"{context.CurrentStateId}: timed out waiting for its event."); + context.NextState(Result.Error); + return Task.CompletedTask; + } + } + + private sealed class State1 : EventState + { + public override IReadOnlyCollection SubscribedMessageTypes => [typeof(OrderCreated)]; + + public override Task OnEnter(Context context) + { + Console.WriteLine("State1: publishing OrderCreated for 3 notebooks."); + context.EventAggregator!.Publish(new OrderCreated("Notebook", 3)); + return Task.CompletedTask; + } + + public override Task OnMessage(Context context, object message) + { + if (message is OrderCreated order) + { + Console.WriteLine($"State1.OnMessage: received {order.Product}, quantity {order.Quantity}; passing data to State2."); + context.Parameters["NextMessage"] = new PriceRequested(order.Product, order.Quantity); + context.NextState(Result.Success); + } + + return Task.CompletedTask; + } + } + + private sealed class State2 : EventState + { + public override IReadOnlyCollection SubscribedMessageTypes => [typeof(PriceRequested)]; + + public override Task OnEnter(Context context) + { + Console.WriteLine("State2: publishing the PriceRequested payload passed from State1."); + context.EventAggregator!.Publish((PriceRequested)context.Parameters["NextMessage"]!); + return Task.CompletedTask; + } + + public override async Task OnMessage(Context context, object message) + { + if (message is not PriceRequested order) + return; + + Console.WriteLine($"State2.OnMessage: looking up the price for {order.Product}..."); + + await Task.Delay(100); // Simulate an asynchronous price lookup. + + var total = order.Quantity * 4.50m; + Console.WriteLine($"State2.OnMessage: {order.Quantity} x 4.50 = {total:F2}; passing data to State3."); + context.Parameters["NextMessage"] = new OrderPriced(order.Product, order.Quantity, total); + context.NextState(Result.Success); + } + } + + private sealed class State3 : EventState + { + public override IReadOnlyCollection SubscribedMessageTypes => [typeof(OrderPriced)]; + + public override Task OnEnter(Context context) + { + Console.WriteLine("State3: publishing the OrderPriced payload passed from State2."); + context.EventAggregator!.Publish((OrderPriced)context.Parameters["NextMessage"]!); + return Task.CompletedTask; + } + + public override Task OnMessage(Context context, object message) + { + if (message is OrderPriced order) + { + Console.WriteLine($"State3.OnMessage: receipt - {order.Quantity} x {order.Product}, total {order.Total:F2}."); + context.Parameters.Remove("NextMessage"); + context.Parameters["Completed"] = true; + context.NextState(Result.Success); + } + + return Task.CompletedTask; + } } } diff --git a/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj b/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj index 2f6f13c..50d9689 100644 --- a/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj +++ b/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj @@ -1,4 +1,4 @@ - + Exe @@ -7,4 +7,8 @@ enable + + + + diff --git a/samples/Sample06.PassingEvents/readme.md b/samples/Sample06.PassingEvents/readme.md index 2e2811c..9e450ec 100644 --- a/samples/Sample06.PassingEvents/readme.md +++ b/samples/Sample06.PassingEvents/readme.md @@ -1,5 +1,34 @@ # Sample 06 - Event Aggregator for Passing Events -_Coming Soon_ +All states (`State1`, `State2`, and `State3`) and message records are in `Program.cs`. +This sample uses the built-in `Lite.StateMachine.EventAggregator` with typed +subscriptions on command states. -See, Unit Tests, for an example of how to use Event Aggregator for Passing Events for now. +Run from the repository root: + +```powershell +dotnet run --project samples/Sample06.PassingEvents --framework net10.0 +``` + +1. State1 publishes `OrderCreated` for three notebooks. Its `OnMessage` receives + the product and quantity and prepares a `PriceRequested` payload for State2. +2. State2 publishes that payload after entering. Its `OnMessage` awaits a + simulated price lookup, calculates `3 x 4.50 = 13.50`, and prepares an + `OrderPriced` payload for State3. +3. State3 publishes the priced payload after entering. Its `OnMessage` prints + the receipt and completes the flow. + +Each state's `SubscribedMessageTypes` declares the exact message type it accepts. +The shared `EventState` base class provides the empty lifecycle hooks and timeout +handling so the numbered states focus on sending and receiving data. + +The aggregator delivers immediately to current subscribers and does not buffer +messages for future states. To pass data safely between states, each `OnMessage` +stores the next payload in `context.Parameters["NextMessage"]` before advancing. +The next state's `OnEnter` republishes it after the machine has subscribed that +state. This keeps the handoff explicit and avoids losing events during transitions. + +`Publish` returns without awaiting asynchronous `OnMessage` work. State2 calls +`NextState(Result.Success)` only after its awaited work and payload preparation +finish. The program awaits `RunAsync`, uses a ten-second cancellation guard, and +verifies that State3 produced its receipt. From 2980da7a3cec65588c6291e453f6e1e879eb83e4 Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sat, 14 Nov 2026 20:51:13 -0500 Subject: [PATCH 5/5] Build script support for .NET 11 --- .github/workflows/build-github.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-github.yml b/.github/workflows/build-github.yml index a5d01eb..ed26324 100644 --- a/.github/workflows/build-github.yml +++ b/.github/workflows/build-github.yml @@ -32,7 +32,10 @@ jobs: - name: 2) Setup .NET SDK uses: actions/setup-dotnet@v4 with: - dotnet-version: '10.0.x' # Change to your target version + # Match the target frameworks in Directory.Build.props. + dotnet-version: | + 10.0.x + 11.0.x # 3. Restore dependencies - name: 3) Restore dependencies