diff --git a/.github/workflows/build-github.yml b/.github/workflows/build-github.yml index ed26324..c9a08a8 100644 --- a/.github/workflows/build-github.yml +++ b/.github/workflows/build-github.yml @@ -13,6 +13,7 @@ env: BASE_VERSION: "2.1" PATH_SLNX: "Lite.StateMachine.slnx" PATH_LIB: "source\\Lite.StateMachine\\Lite.StateMachine.csproj" + PATH_DOTGRAPH: "source\\Lite.StateMachine.DotGraph\\Lite.StateMachine.DotGraph.csproj" PATH_ARTIFACTS: ${{github.workspace}}\artifacts jobs: @@ -82,9 +83,16 @@ jobs: if ($prerelease) { Write-Host "Version suffix=$prerelease" } # 7. Pack NuGet - - name: 7) Pack NuGet + - name: 7) Pack NuGet Packages # Optionally, "--include-symbols" - run: dotnet pack ${{env.PATH_LIB}} --configuration Release --no-build --output ${{env.PATH_ARTIFACTS}} + shell: pwsh + run: | + foreach ($project in @($env:PATH_LIB, $env:PATH_DOTGRAPH)) { + dotnet pack $project --configuration Release --no-build --output $env:PATH_ARTIFACTS -m:1 + if ($LASTEXITCODE -ne 0) { + throw "NuGet packing failed for $project" + } + } # dotnet pack source/Lite.StateMachine/Lite.StateMachine.csproj --configuration Release --no-build --output ./artifacts #- name: Pack NuGet # shell: pwsh @@ -125,13 +133,13 @@ jobs: ## steps: ## 10) Publish to NuGet.org (master branch, push events only) - - name: 8) NuGet Push Package + - name: 8) NuGet Push Packages env: NUGET_API_URL: "https://api.nuget.org/v3/index.json" ## Optionally pass, `--skip-duplicate` if a pkg version already exists on NuGet.org if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/') - run: dotnet nuget push ${{env.PATH_ARTIFACTS}}\*.nupkg -k ${{secrets.NUGET_AUTH_TOKEN}} -s ${{env.NUGET_API_URL}} + run: dotnet nuget push ${{env.PATH_ARTIFACTS}}\*.nupkg -k ${{secrets.NUGET_AUTH_TOKEN}} -s ${{env.NUGET_API_URL}} --skip-duplicate #- name: Publish to NuGet.org # if: github.ref_name == 'master' && github.event_name == 'push' diff --git a/.github/workflows/dotgraph.yml b/.github/workflows/dotgraph.yml new file mode 100644 index 0000000..d844031 --- /dev/null +++ b/.github/workflows/dotgraph.yml @@ -0,0 +1,42 @@ +name: DOT rendering on Windows, Linux, and macOS + +on: + push: + branches: [master, develop] + pull_request: + branches: [master, develop] + +jobs: + render: + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 10.0.x + 11.0.x + - name: Install Graphviz on Windows + if: runner.os == 'Windows' + run: choco install graphviz --no-progress -y + - name: Install Graphviz on Linux + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y graphviz + - name: Install Graphviz on macOS + if: runner.os == 'macOS' + run: brew install graphviz + - name: Test rendering + shell: pwsh + run: | + if ($IsWindows) { + $env:GRAPHVIZ_DOT = 'C:\Program Files\Graphviz\bin\dot.exe' + } else { + $env:GRAPHVIZ_DOT = 'dot' + } + dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release --verbosity normal + - name: Pack standalone renderer + run: dotnet pack source/Lite.StateMachine.DotGraph -c Release --no-build diff --git a/Lite.StateMachine.slnx b/Lite.StateMachine.slnx index a57be99..1ec63a7 100644 --- a/Lite.StateMachine.slnx +++ b/Lite.StateMachine.slnx @@ -7,6 +7,7 @@ + @@ -20,8 +21,10 @@ + + diff --git a/readme.md b/readme.md index 2c88b08..318c7a1 100644 --- a/readme.md +++ b/readme.md @@ -142,9 +142,24 @@ public class BasicState3() : BaseState ### Generate DOT Graph (GraphViz) ```cs -var uml = machine.ExportUml(includeSubmachines: true); +var uml = machine.ExportUml(); ``` +To generate SVG or PNG files from DOT, use the optional +[Lite.StateMachine.DotGraph](source/Lite.StateMachine.DotGraph/readme.md) package: + +```cs +using Lite.StateMachine.DotGraph; + +var renderer = new GraphvizRenderer(); +await renderer.RenderAsync(machine.ExportUml(), "machine.svg"); +await renderer.RenderFileAsync("machine.dot", "machine.png", DotGraphFormat.Png); +``` + +The renderer requires an installed or application-supplied [Graphviz](https://graphviz.org/download/) +executable. It is independent of the core library and uses portable .NET process APIs +for Windows, Linux, and macOS. See the package README for deployment requirements. + ![Sample Composite State Image](https://raw.githubusercontent.com/SuessLabs/Lite.StateMachine/develop/docs/SampleGraphviz-1080.png) ### Composite States diff --git a/samples/Sample11.GenerateDotGraph/.gitignore b/samples/Sample11.GenerateDotGraph/.gitignore new file mode 100644 index 0000000..1de3a3e --- /dev/null +++ b/samples/Sample11.GenerateDotGraph/.gitignore @@ -0,0 +1,3 @@ +*.png +*.svg +*.dot diff --git a/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 b/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 new file mode 100644 index 0000000..c69ac52 --- /dev/null +++ b/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 @@ -0,0 +1,66 @@ +<# +.SYNOPSIS +Builds the sample, loads its DLL, and renders the same diagrams as the console app. +.EXAMPLE +./Generate-Diagrams.ps1 -DotPath 'C:/Program Files/Graphviz/bin/dot.exe' +#> +#Requires -Version 7.0 + +[CmdletBinding()] +param( + [string] $OutputDirectory = (Join-Path $PSScriptRoot 'diagrams'), + [string] $DotPath = 'dot', + [ValidateSet('Debug', 'Release')] + [string] $Configuration = 'Release', + [switch] $SkipBuild +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +if ([Environment]::Version.Major -lt 10) { + throw 'Use PowerShell hosted on .NET 10 or later (for example PowerShell 7.6). Windows PowerShell 5.1 is not supported.' +} + +$project = Join-Path $PSScriptRoot 'Sample11.GenerateDotGraph.csproj' +if (-not $SkipBuild) { + dotnet build $project -c $Configuration -f net10.0 + if ($LASTEXITCODE -ne 0) { + throw 'Sample build failed.' + } +} + +# Matches this repository's Directory.Build.props output layout. +$assemblyDirectory = [IO.Path]::GetFullPath( + (Join-Path $PSScriptRoot "../../output/Sample11.GenerateDotGraph/$Configuration/net10.0")) + +foreach ($assemblyName in @('Lite.StateMachine.dll', 'Lite.StateMachine.DotGraph.dll', 'Sample11.GenerateDotGraph.dll')) +{ + $assemblyPath = Join-Path $assemblyDirectory $assemblyName + if (-not (Test-Path -LiteralPath $assemblyPath -PathType Leaf)) { + throw "Assembly not found: $assemblyPath. Build the sample first or omit -SkipBuild." + } + [void][Reflection.Assembly]::LoadFrom($assemblyPath) +} + +$OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory) +[void][IO.Directory]::CreateDirectory($OutputDirectory) +$renderer = [Lite.StateMachine.DotGraph.GraphvizRenderer]::new($DotPath, [TimeSpan]::FromSeconds(30)) +$token = [Threading.CancellationToken]::None + +foreach ($includeLegend in @($false, $true)) { + $name = if ($includeLegend) { 'machine-legend' } else { 'machine' } + + # This calls a public DLL method, not the console application's entry point. + $dot = [Sample11.GenerateDotGraph.WorkflowDiagram]::ExportDot($includeLegend) + + [IO.File]::WriteAllText((Join-Path $OutputDirectory "$name.dot"), $dot) + + [void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.svg"), + [Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult() + + [void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.png"), + [Lite.StateMachine.DotGraph.DotGraphFormat]::Png, $token).GetAwaiter().GetResult() + + Write-Output "Generated $name.dot, $name.svg, and $name.png in $OutputDirectory" +} diff --git a/samples/Sample11.GenerateDotGraph/Program.cs b/samples/Sample11.GenerateDotGraph/Program.cs new file mode 100644 index 0000000..acf8488 --- /dev/null +++ b/samples/Sample11.GenerateDotGraph/Program.cs @@ -0,0 +1,48 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; +using System.Threading.Tasks; +using Lite.StateMachine.DotGraph; + +namespace Sample11.GenerateDotGraph; + +internal static class Program +{ + private static async Task Main(string[] args) + { + if (args.Length > 2) + { + Console.Error.WriteLine("Usage: Sample11.GenerateDotGraph [output-directory] [dot-executable]"); + return 1; + } + + var outputDirectory = Path.GetFullPath(args.Length > 0 + ? args[0] + : Path.Combine(AppContext.BaseDirectory, "diagrams")); + + var renderer = new GraphvizRenderer(args.Length > 1 + ? args[1] + : "dot"); + + Directory.CreateDirectory(outputDirectory); + + foreach (var includeLegend in new[] { false, true }) + { + var name = includeLegend ? "machine-legend" : "machine"; + + // Create state machine and export DOT graph without running any states. + var dot = SampleStateMachine.ExportDot(includeLegend); + var dotPath = Path.Combine(outputDirectory, name + ".dot"); + + await File.WriteAllTextAsync(dotPath, dot); + await renderer.RenderAsync(dot, Path.Combine(outputDirectory, name + ".svg")); + await renderer.RenderAsync(dot, Path.Combine(outputDirectory, name + ".png"), DotGraphFormat.Png); + + Console.WriteLine($"Generated {name}.dot, {name}.svg, and {name}.png in {outputDirectory}"); + } + + return 0; + } +} diff --git a/samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj b/samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj new file mode 100644 index 0000000..49c78a9 --- /dev/null +++ b/samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj @@ -0,0 +1,14 @@ + + + Exe + false + net10.0 + disable + enable + + + + + + + diff --git a/samples/Sample11.GenerateDotGraph/SampleStateMachine.cs b/samples/Sample11.GenerateDotGraph/SampleStateMachine.cs new file mode 100644 index 0000000..8f39f7c --- /dev/null +++ b/samples/Sample11.GenerateDotGraph/SampleStateMachine.cs @@ -0,0 +1,59 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using Lite.StateMachine; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Sample11.GenerateDotGraph; + +/// Exports the same topology as DiMsTests.Basic_GeneratesExportUml_SuccessTestAsync. +public static class SampleStateMachine +{ + /// Builds the configured machine and exports DOT without running any states. + /// Whether to add the Graphviz legend. + /// DOT text with Entry as the initial state. + public static string ExportDot(bool includeLegend) + { + // Configure DI + using var services = new ServiceCollection() + .AddLogging(builder => builder.AddSimpleConsole()) + .AddSingleton() + .AddTransient() + .AddTransient() + .AddTransient() + .AddTransient() + .AddTransient() + .AddTransient() + .AddTransient() + .BuildServiceProvider(); + + // Factory uses DI to construct states + var aggregator = services.GetRequiredService(); + Func factory = type => ActivatorUtilities.CreateInstance(services, type); + + // Create State Machine + var machine = new StateMachine(factory, aggregator); + + machine.RegisterState(CompositeMsgStateId.Entry, CompositeMsgStateId.Parent); + machine.RegisterComposite( + stateId: CompositeMsgStateId.Parent, + initialChildStateId: CompositeMsgStateId.Parent_Fetch, + onSuccess: CompositeMsgStateId.Done, + onError: CompositeMsgStateId.Error, + onFailure: CompositeMsgStateId.Failure); + + //// Substates of ParentState + machine.RegisterSubState(CompositeMsgStateId.Parent_Fetch, CompositeMsgStateId.Parent, CompositeMsgStateId.Parent_WaitMessage); + machine.RegisterSubState(CompositeMsgStateId.Parent_WaitMessage, CompositeMsgStateId.Parent); + + // End of substates + machine.RegisterState(CompositeMsgStateId.Done); + machine.RegisterState(CompositeMsgStateId.Error, CompositeMsgStateId.Parent); + machine.RegisterState(CompositeMsgStateId.Failure, CompositeMsgStateId.Parent); + + // Export the DOT graph with Entry as the initial state. + return machine.ExportUml([CompositeMsgStateId.Entry], includeLegend: includeLegend); + } +} diff --git a/samples/Sample11.GenerateDotGraph/WorkflowStates.cs b/samples/Sample11.GenerateDotGraph/WorkflowStates.cs new file mode 100644 index 0000000..c090912 --- /dev/null +++ b/samples/Sample11.GenerateDotGraph/WorkflowStates.cs @@ -0,0 +1,65 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System.Threading.Tasks; +using Lite.StateMachine; +using Microsoft.Extensions.Logging; + +namespace Sample11.GenerateDotGraph; + +#pragma warning disable SA1402 // Keep the small diagram-only state definitions together. +#pragma warning disable SA1649 // File groups related state definitions. + +/// State identifiers matching the composite export test. +public enum CompositeMsgStateId +{ + Entry, + Parent, + Parent_Fetch, + Parent_WaitMessage, + Done, + Error, + Failure, +} + +public sealed class EntryState(ILogger logger) : DiagramState(logger); + +public sealed class ParentState(ILogger logger) : DiagramState(logger); + +public sealed class ParentSub_FetchState(ILogger logger) : DiagramState(logger); + +public sealed class ParentSub_WaitMessageState(ILogger logger) + : DiagramState(logger), ICommandState +{ + public Task OnMessage(Context context, object message) => Task.CompletedTask; + + public Task OnTimeout(Context context) + { + context.NextState(Result.Failure); + return Task.CompletedTask; + } +} + +public sealed class DoneState(ILogger logger) : DiagramState(logger); + +public sealed class ErrorState(ILogger logger) : DiagramState(logger); + +public sealed class FailureState(ILogger logger) : DiagramState(logger); + +/// Minimal state behavior; diagram generation never executes these handlers. +public abstract class DiagramState(ILogger logger) : IState +{ + public Task OnEnter(Context context) + { + logger.LogInformation("Entered {StateId}", context.CurrentStateId); + context.NextState(Result.Success); + return Task.CompletedTask; + } + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) => Task.CompletedTask; +} + +#pragma warning restore SA1649 // File groups related state definitions. +#pragma warning restore SA1402 // Keep the small diagram-only state definitions together. diff --git a/samples/Sample11.GenerateDotGraph/readme.md b/samples/Sample11.GenerateDotGraph/readme.md new file mode 100644 index 0000000..1977b62 --- /dev/null +++ b/samples/Sample11.GenerateDotGraph/readme.md @@ -0,0 +1,67 @@ +# Sample 11: Generate DOT, SVG, and PNG diagrams + +This sample uses `Lite.StateMachine.DotGraph` to render the same topology as +`Basic_GeneratesExportUml_SuccessTestAsync` in `DiMsTests.cs`: + +* `Entry` transitions to the composite `Parent` state. +* `Parent` starts at `Parent_Fetch`, which transitions to `Parent_WaitMessage`. +* `Parent` has `Success`, `Error`, and `Failure` transitions to `Done`, `Error`, and `Failure`. +* `Error` and `Failure` transition back to `Parent`; +* `Done` is the terminal final state. + +The DI factory, state identifiers, transition registrations, initial Entry marker, +and legend options match the test. State handlers are minimal diagram-only examples; +the test's message service, counters, and workflow execution are not needed to export +the topology. Neither generation path runs the workflow. + +## Requirements + +* Install .NET 10 or 11 +* Install [Graphviz](https://graphviz.org/download/). +* Add Graphviz's `bin` directory to PATH, or pass its `dot`/`dot.exe` path explicitly. + +The project references the local core and renderer projects; it does not reference +or reuse the unit-test assembly. + +## Console application + +From the repository root: + +```powershell +dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- samples/Sample11.GenerateDotGraph/diagrams + +# Optional second argument: the Graphviz executable (quote paths with spaces). +dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- samples/Sample11.GenerateDotGraph/diagrams 'C:/Program Files/Graphviz/bin/dot.exe' +``` + +Use `-f net11.0` to run on .NET 11. With no application arguments, diagrams are +written to a `diagrams` directory beside the built executable. + +## External PowerShell generation + +Use PowerShell hosted on .NET 10 or later, such as PowerShell 7.6. +Run a fresh process to avoid conflicts with previously loaded DLL versions: + +```powershell +pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 + +# Optional output folder and Graphviz path: +pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -OutputDirectory ./output/sample11-powershell -DotPath 'C:/Program Files/Graphviz/bin/dot.exe' +``` + +The script builds `net10.0`, loads the sample DLL and its libraries, and calls +`WorkflowDiagram.ExportDot(bool)` directly. It then renders the returned DOT through +`GraphvizRenderer`; it does not launch the sample executable. `-SkipBuild` reuses a +previous build, and `-Configuration Debug` selects Debug output instead of Release. +By default, the script writes to this sample's `diagrams` directory. + +Both generation paths produce six files, replacing existing images on success: + +| Version | DOT | SVG | PNG | +| --- | --- | --- | --- | +| Without legend | `machine.dot` | `machine.svg` | `machine.png` | +| With legend | `machine-legend.dot` | `machine-legend.svg` | `machine-legend.png` | + +The checked-in `diagrams` directory contains generated examples. DOT text is the +same from both paths; image layout may vary with the installed Graphviz version +and fonts. diff --git a/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs b/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs new file mode 100644 index 0000000..b10a9d6 --- /dev/null +++ b/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs @@ -0,0 +1,163 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Lite.StateMachine.DotGraph; + +[assembly: Parallelize(Scope = ExecutionScope.MethodLevel)] + +namespace Lite.StateMachine.DotGraph.Tests; + +[TestClass] +public sealed class GraphvizRendererTests +{ + private const string Graph = "digraph { subgraph cluster_child { label=\"Child\"; a [label=\"Prépare\"]; a -> b [label=\"Success\"]; } b -> c [label=\"Failure\"]; }"; + private readonly string _directory = Path.Combine(Path.GetTempPath(), "DotGraph tests " + Guid.NewGuid()); + + [TestCleanup] + public void Cleanup() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + [TestMethod] + public async Task MissingExecutableExplainsInstallationAsync() + { + var renderer = new GraphvizRenderer(Path.Combine(_directory, "missing-dot")); + var exception = await Assert.ThrowsAsync(() => renderer.RenderAsync(Graph, Output("machine.svg"))); + StringAssert.Contains(exception.Message, "Install Graphviz"); + Assert.IsEmpty(Directory.GetFiles(_directory)); + } + + [TestMethod] + public async Task ValidationRejectsInvalidArgumentsBeforeStartingGraphvizAsync() + { + Assert.Throws(() => new GraphvizRenderer(" ")); + Assert.Throws(() => new GraphvizRenderer(timeout: TimeSpan.Zero)); + var renderer = new GraphvizRenderer("missing-dot"); + Assert.Throws(() => renderer.RenderAsync(" ", Output("machine.svg"))); + await Assert.ThrowsAsync(() => renderer.RenderAsync(Graph, Output("machine.svg"), (DotGraphFormat)99)); + Assert.Throws(() => renderer.RenderFileAsync(Output("missing.dot"), Output("machine.svg"))); + Directory.CreateDirectory(_directory); + var input = Output("machine.dot"); + await File.WriteAllTextAsync(input, Graph); + Assert.Throws(() => renderer.RenderFileAsync(input, input)); + Assert.AreEqual(Graph, await File.ReadAllTextAsync(input)); + } + + [TestMethod] + public async Task PreCanceledRequestDoesNotCreateOutputAsync() + { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + await Assert.ThrowsAsync(() => new GraphvizRenderer().RenderAsync(Graph, Output("machine.svg"), cancellationToken: cancellation.Token)); + Assert.IsFalse(Directory.Exists(_directory)); + } + + [TestMethod] + [TestCategory("Graphviz")] + public async Task RendersTextAsUtf8SvgAndReplacesExistingImageAsync() + { + var renderer = CreateRenderer(); + var output = Output("nested [states]/machine ü.svg"); + await renderer.RenderAsync(Graph, output); + var svg = await File.ReadAllTextAsync(output); + StringAssert.Contains(svg, "(() => renderer.RenderAsync("invalid dot", output)); + StringAssert.Contains(exception.Message, "Graphviz exited with code"); + StringAssert.Contains(exception.Message, "syntax error"); + Assert.AreEqual("previous image", await File.ReadAllTextAsync(output)); + Assert.HasCount(1, Directory.GetFiles(_directory)); + } + + [TestMethod] + [TestCategory("Graphviz")] + public async Task LargeInvalidInputDoesNotMaskDiagnosticsWithBrokenPipeAsync() + { + var renderer = CreateRenderer(); + var dot = "invalid dot " + new string('x', 1024 * 1024); + var exception = await Assert.ThrowsAsync(() => renderer.RenderAsync(dot, Output("machine.svg"))); + StringAssert.Contains(exception.Message, "Graphviz exited with code"); + Assert.IsEmpty(Directory.GetFiles(_directory)); + } + + [TestMethod] + [TestCategory("Graphviz")] + public async Task TimeoutPreservesImageAndCleansTemporaryOutputAsync() + { + var renderer = CreateRenderer(TimeSpan.FromMilliseconds(1)); + Directory.CreateDirectory(_directory); + var output = Output("existing.svg"); + await File.WriteAllTextAsync(output, "previous image"); + await Assert.ThrowsAsync(() => renderer.RenderAsync(LargeGraph(), output)); + Assert.AreEqual("previous image", await File.ReadAllTextAsync(output)); + Assert.HasCount(1, Directory.GetFiles(_directory)); + } + + [TestMethod] + [TestCategory("Graphviz")] + public async Task CancellationStopsRenderingAndCleansTemporaryOutputAsync() + { + var renderer = CreateRenderer(); + var graph = LargeGraph(); + using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + await Assert.ThrowsAsync(() => renderer.RenderAsync(graph, Output("machine.svg"), cancellationToken: cancellation.Token)); + Assert.IsEmpty(Directory.GetFiles(_directory)); + } + + private static GraphvizRenderer CreateRenderer(TimeSpan? timeout = null) + { + var executable = Environment.GetEnvironmentVariable("GRAPHVIZ_DOT"); + if (string.IsNullOrWhiteSpace(executable)) + Assert.Inconclusive("Set GRAPHVIZ_DOT to dot or its full path to run Graphviz integration tests."); + + return new GraphvizRenderer(executable, timeout); + } + + private static string LargeGraph() + { + var graph = new StringBuilder("digraph {"); + for (var i = 0; i < 20000; ++i) + graph.Append("n").Append(i).Append(" -> n").Append(i + 1).Append(';'); + + return graph.Append('}').ToString(); + } + + private string Output(string name) => Path.Combine(_directory, name); +} diff --git a/source/Lite.StateMachine.DotGraph.Tests/Lite.StateMachine.DotGraph.Tests.csproj b/source/Lite.StateMachine.DotGraph.Tests/Lite.StateMachine.DotGraph.Tests.csproj new file mode 100644 index 0000000..4efc4fe --- /dev/null +++ b/source/Lite.StateMachine.DotGraph.Tests/Lite.StateMachine.DotGraph.Tests.csproj @@ -0,0 +1,11 @@ + + + false + true + + + + + + + diff --git a/source/Lite.StateMachine.DotGraph/DotGraphFormat.cs b/source/Lite.StateMachine.DotGraph/DotGraphFormat.cs new file mode 100644 index 0000000..5f5537f --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/DotGraphFormat.cs @@ -0,0 +1,14 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +namespace Lite.StateMachine.DotGraph; + +/// Supported image formats. +public enum DotGraphFormat +{ + /// Scalable Vector Graphics. + Svg, + + /// Portable Network Graphics. + Png, +} diff --git a/source/Lite.StateMachine.DotGraph/GraphvizRenderer.cs b/source/Lite.StateMachine.DotGraph/GraphvizRenderer.cs new file mode 100644 index 0000000..6a3f08c --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/GraphvizRenderer.cs @@ -0,0 +1,160 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Lite.StateMachine.DotGraph; + +/// Renders DOT using a separately installed or application-supplied Graphviz executable. +public sealed class GraphvizRenderer : IDotGraphRenderer +{ + private readonly string _executablePath; + private readonly TimeSpan _timeout; + + /// Initializes a new instance of the class. + /// Graphviz dot executable path, or "dot" to search PATH. + /// Maximum rendering duration. Defaults to 30 seconds. + public GraphvizRenderer(string executablePath = "dot", TimeSpan? timeout = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(executablePath); + _executablePath = executablePath; + _timeout = timeout ?? TimeSpan.FromSeconds(30); + if (_timeout <= TimeSpan.Zero || _timeout.TotalMilliseconds > uint.MaxValue - 1) + throw new ArgumentOutOfRangeException(nameof(timeout)); + } + + /// + public Task RenderAsync(string dot, string outputPath, DotGraphFormat format = DotGraphFormat.Svg, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dot); + return RenderCoreAsync(dot, null, outputPath, format, cancellationToken); + } + + /// + public Task RenderFileAsync(string inputPath, string outputPath, DotGraphFormat format = DotGraphFormat.Svg, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(inputPath); + var fullInputPath = Path.GetFullPath(inputPath); + if (!File.Exists(fullInputPath)) + throw new FileNotFoundException("DOT input file was not found.", fullInputPath); + + ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + if (string.Equals(fullInputPath, Path.GetFullPath(outputPath), comparison)) + throw new ArgumentException("Input and output paths must differ.", nameof(outputPath)); + + return RenderCoreAsync(null, fullInputPath, outputPath, format, cancellationToken); + } + + private async Task RenderCoreAsync(string? dot, string? inputPath, string outputPath, DotGraphFormat format, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); + var formatName = format switch + { + DotGraphFormat.Svg => "svg", + DotGraphFormat.Png => "png", + _ => throw new ArgumentOutOfRangeException(nameof(format)), + }; + cancellationToken.ThrowIfCancellationRequested(); + + var fullOutputPath = Path.GetFullPath(outputPath); + var outputDirectory = Path.GetDirectoryName(fullOutputPath)!; + + Directory.CreateDirectory(outputDirectory); + var temporaryPath = Path.Combine(outputDirectory, Path.GetRandomFileName()); + + using var timeout = new CancellationTokenSource(_timeout); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token); + using var process = new Process(); + + process.StartInfo = new ProcessStartInfo(_executablePath) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = dot is not null, + RedirectStandardError = true, + RedirectStandardOutput = true, + }; + + process.StartInfo.ArgumentList.Add("-T" + formatName); + process.StartInfo.ArgumentList.Add("-o"); + process.StartInfo.ArgumentList.Add(temporaryPath); + + if (inputPath is not null) + process.StartInfo.ArgumentList.Add(inputPath); + + try + { + try + { + process.Start(); + } + catch (Win32Exception ex) + { + throw new InvalidOperationException($"Could not start Graphviz '{_executablePath}'. Install Graphviz and add dot to PATH, or supply its executable path.", ex); + } + + // Drain both streams while writing input so large graphs/diagnostics cannot deadlock. + var diagnosticsTask = process.StandardError.ReadToEndAsync(); + var outputTask = process.StandardOutput.BaseStream.CopyToAsync(Stream.Null); + + try + { + IOException? inputError = null; + if (dot is not null) + { + try + { + // Close the pipe directly: closing the unused text writer can flush + // to an already-closed pipe and mask Graphviz's error on Unix. + await using var input = process.StandardInput.BaseStream; + await input.WriteAsync(Encoding.UTF8.GetBytes(dot), cancellation.Token).ConfigureAwait(false); + } + catch (IOException ex) + { + // Graphviz may close stdin early on invalid DOT. Prefer its diagnostics. + inputError = ex; + } + } + + await process.WaitForExitAsync(cancellation.Token).ConfigureAwait(false); + var diagnostics = await diagnosticsTask.ConfigureAwait(false); + await outputTask.ConfigureAwait(false); + cancellation.Token.ThrowIfCancellationRequested(); + + if (process.ExitCode != 0) + throw new InvalidOperationException($"Graphviz exited with code {process.ExitCode}: {diagnostics.Trim()}"); + + if (inputError is not null) + throw new IOException("Could not send DOT text to Graphviz.", inputError); + + if (!File.Exists(temporaryPath) || new FileInfo(temporaryPath).Length == 0) + throw new InvalidOperationException("Graphviz produced no image. " + diagnostics.Trim()); + + File.Move(temporaryPath, fullOutputPath, overwrite: true); + } + finally + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + + await process.WaitForExitAsync().ConfigureAwait(false); + await Task.WhenAll(diagnosticsTask, outputTask).ConfigureAwait(false); + } + } + catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested && timeout.IsCancellationRequested) + { + throw new TimeoutException($"Graphviz rendering exceeded {_timeout}.", ex); + } + finally + { + File.Delete(temporaryPath); + } + } +} diff --git a/source/Lite.StateMachine.DotGraph/IDotGraphRenderer.cs b/source/Lite.StateMachine.DotGraph/IDotGraphRenderer.cs new file mode 100644 index 0000000..aa0e959 --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/IDotGraphRenderer.cs @@ -0,0 +1,27 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System.Threading; +using System.Threading.Tasks; + +namespace Lite.StateMachine.DotGraph; + +/// Renders DOT graphs independently of the layout engine's deployment. +public interface IDotGraphRenderer +{ + /// Renders DOT text to an image file. + /// DOT text, for example from StateMachine.ExportUml(). + /// Destination image path. Existing files are replaced on success. + /// Output format, independent of the destination extension. + /// Cancellation token. + /// A task representing image generation. + Task RenderAsync(string dot, string outputPath, DotGraphFormat format = DotGraphFormat.Svg, CancellationToken cancellationToken = default); + + /// Renders an existing DOT file to an image file. + /// DOT file path. + /// Destination image path. Existing files are replaced on success. + /// Output format, independent of the destination extension. + /// Cancellation token. + /// A task representing image generation. + Task RenderFileAsync(string inputPath, string outputPath, DotGraphFormat format = DotGraphFormat.Svg, CancellationToken cancellationToken = default); +} diff --git a/source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj b/source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj new file mode 100644 index 0000000..3888ec9 --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj @@ -0,0 +1,21 @@ + + + Lite State Machine DOT Graph Rendering + Optional cross-platform Graphviz wrapper for rendering DOT text and files as SVG or PNG. Requires a Graphviz executable; independent of Lite.StateMachine. + $(AssemblyVersion) + true + true + https://github.com/SuessLabs/Lite.StateMachine + https://github.com/SuessLabs/Lite.StateMachine + graphviz;dot;svg;png;statemachine + readme.md + LICENSE.md + true + snupkg + true + + + + + + diff --git a/source/Lite.StateMachine.DotGraph/readme.md b/source/Lite.StateMachine.DotGraph/readme.md new file mode 100644 index 0000000..a82f45f --- /dev/null +++ b/source/Lite.StateMachine.DotGraph/readme.md @@ -0,0 +1,152 @@ +# Lite.StateMachine.DotGraph + +Optional DOT-to-SVG/PNG rendering for .NET. This package has no dependency on +Lite.StateMachine and accepts DOT from any source. The core state-machine package +is unchanged and does not depend on this renderer. + +## Requirements + +.NET 10 or 11 and a separately installed or application-supplied +[Graphviz](https://graphviz.org/download/) `dot` executable. The wrapper uses portable +.NET process APIs and is intended for Windows, Linux, and macOS desktop/server apps. +It does not bundle native binaries, install software, or download anything at runtime. +It is not a browser or mobile rendering backend. + +## Usage + +```csharp +using Lite.StateMachine.DotGraph; + +IDotGraphRenderer renderer = new GraphvizRenderer(); // dot on PATH + +// With Lite.StateMachine, pass machine.ExportUml() as the DOT text. +await renderer.RenderAsync(machine.ExportUml(), "images/machine.svg"); +await renderer.RenderAsync(machine.ExportUml(), "images/machine.png", DotGraphFormat.Png); + +// Or render an existing DOT file from any source. +await renderer.RenderFileAsync("machine.dot", "images/machine.svg"); + +// Optional application-supplied executable and timeout. +renderer = new GraphvizRenderer("/opt/graphviz/bin/dot", TimeSpan.FromMinutes(1)); +await renderer.RenderFileAsync("machine.dot", "machine.png", DotGraphFormat.Png, cancellationToken); +``` + +Output defaults to SVG; the format argument controls encoding rather than the file +extension. Parent directories are created automatically. Existing destinations are +replaced only after a successful render. Rendering errors include Graphviz's exit +code and diagnostics. Cancellation or the default 30-second timeout terminates the +Graphviz process and removes temporary output. Input DOT files are never modified. +Relative image references in DOT resolve from the application's working directory. + +`IDotGraphRenderer` keeps consumers independent of executable deployment, leaving +room for a future backend with bundled or embedded rendering. Cross-platform +deployment today still requires compatible Graphviz binaries and their dependencies +on each target OS/architecture. + +Build the NuGet package from the repository root: + +```sh +dotnet pack source/Lite.StateMachine.DotGraph -c Release +``` + +## Generate diagrams externally with PowerShell + +You can load the application's compiled DLL and the renderer DLL from an external +script. The application does **not** need a reference to the DotGraph NuGet package +or a rebuild for rendering. This works when an existing public factory or constructor +exposes the configured state machine, or an existing method returns DOT text. +The factory should register the topology without running the workflow. + +Prepare the script's environment: + +* Use PowerShell 7 running a compatible .NET runtime. Check + `[System.Environment]::Version`; Windows PowerShell 5.1 cannot load these assemblies. + For example, load the `net10.0` renderer with a .NET 10 PowerShell host. Installing + a newer .NET SDK does not change the runtime used by an existing PowerShell host. +* Build the renderer separately with + `dotnet build source/Lite.StateMachine.DotGraph -c Release -f net10.0`, or extract + `lib/net10.0/Lite.StateMachine.DotGraph.dll` from its `.nupkg` into a tooling folder. + No package reference is needed in the application project. +* Use the application's build/publish output, including its matching + `Lite.StateMachine.dll` and other dependencies. Load additional factory dependencies + explicitly if needed; applications requiring a custom host or DI container may need + that setup in the script too. +* Install Graphviz, or supply the path to an application-managed `dot` executable. + +Save this example as `Export-StateDiagram.ps1`. Replace the example paths, type, +and method with an **existing** API in your application. This example assumes a +public static, parameterless `MyApp.WorkflowFactory.Create()` method that returns +a configured `StateMachine`: + +```powershell +$ErrorActionPreference = 'Stop' + +# Paths are relative to this script; adjust to your build output/tooling folder. +$applicationDll = (Resolve-Path "$PSScriptRoot/app/MyApp.dll").Path +$rendererDll = (Resolve-Path "$PSScriptRoot/tooling/Lite.StateMachine.DotGraph.dll").Path +$applicationDirectory = Split-Path $applicationDll +$outputDirectory = Join-Path $PSScriptRoot 'diagrams' + +# Load the application's version of the core library, then the application. +[void][System.Reflection.Assembly]::LoadFrom( + (Join-Path $applicationDirectory 'Lite.StateMachine.dll')) +$application = [System.Reflection.Assembly]::LoadFrom($applicationDll) +[void][System.Reflection.Assembly]::LoadFrom($rendererDll) + +# Invoke an existing public static factory without starting the application. +$factoryType = $application.GetType('MyApp.WorkflowFactory', $true) +$factory = $factoryType.GetMethod('Create', [System.Type]::EmptyTypes) +if ($null -eq $factory -or -not $factory.IsStatic) { + throw 'Expected a public static, parameterless Create() factory.' +} +$machine = $factory.Invoke($null, [object[]]@()) +if ($null -eq $machine) { + throw 'The factory did not return a configured state machine.' +} +$dot = $machine.ExportUml() + +# Keep DOT as well as both image formats. No changes to the application project. +[void][System.IO.Directory]::CreateDirectory($outputDirectory) +[System.IO.File]::WriteAllText((Join-Path $outputDirectory 'machine.dot'), $dot) +$renderer = [Lite.StateMachine.DotGraph.GraphvizRenderer]::new( + 'dot', [TimeSpan]::FromSeconds(30)) # Or an absolute path to dot/dot.exe. +$token = [System.Threading.CancellationToken]::None +[void]$renderer.RenderAsync($dot, (Join-Path $outputDirectory 'machine.svg'), + [Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult() +[void]$renderer.RenderAsync($dot, (Join-Path $outputDirectory 'machine.png'), + [Lite.StateMachine.DotGraph.DotGraphFormat]::Png, $token).GetAwaiter().GetResult() +``` + +Run it in a fresh PowerShell process so previously loaded application assemblies +do not conflict with another build: + +```powershell +pwsh -NoProfile -File ./Export-StateDiagram.ps1 +``` + +For an existing public parameterless constructor, replace factory lookup/invocation +with `$machine = [System.Activator]::CreateInstance($application.GetType('MyApp.Workflow', $true))`. +If an existing method returns DOT directly, assign that result to `$dot` instead +of calling `ExportUml()`. If you already have a `.dot` file, skip loading the +application and core assemblies and call `RenderFileAsync()` on the renderer. + +This is API invocation, not automatic extraction from arbitrary compiled code. +If the application only creates a machine inside a local variable in `Run()` or +`Main()` and never exposes it, the script cannot recover that object without an +application API change. Likewise, it cannot infer transitions that have not been +registered; topology that depends on configuration needs the corresponding setup. + +## Tests + +The test project runs against both target frameworks. Set `GRAPHVIZ_DOT` to `dot` +or an executable's full path to enable the real rendering tests: + +```powershell +$env:GRAPHVIZ_DOT = 'dot' +dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release +``` + +Without this variable, the integration tests are marked inconclusive; argument +validation and missing-executable tests still run. The DOT rendering CI workflow +installs Graphviz and runs the full suite on Windows, Linux, and macOS. This workflow +also builds the NuGet package without publishing it. diff --git a/source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj b/source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj index 5130ec1..e28959f 100644 --- a/source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj +++ b/source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj @@ -13,6 +13,7 @@ + diff --git a/source/Lite.StateMachine.Tests/StateTests/DiagramSampleTests.cs b/source/Lite.StateMachine.Tests/StateTests/DiagramSampleTests.cs new file mode 100644 index 0000000..262acb5 --- /dev/null +++ b/source/Lite.StateMachine.Tests/StateTests/DiagramSampleTests.cs @@ -0,0 +1,20 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using Lite.StateMachine.Tests.TestData; +using Sample11.GenerateDotGraph; + +namespace Lite.StateMachine.Tests.StateTests; + +[TestClass] +public sealed class DiagramSampleTests +{ + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void Sample11MatchesCompositeExportTest(bool includeLegend) + { + var actual = SampleStateMachine.ExportDot(includeLegend); + AssertExtensions.AreEqualIgnoreLines(ExpectedUmlData.CompositeWithErrorFailure(includeLegend), actual); + } +}