diff --git a/EvenBetterFastSim.Tests/ConnectionNodeTests.cs b/EvenBetterFastSim.Tests/ConnectionNodeTests.cs new file mode 100644 index 0000000..9679b6e --- /dev/null +++ b/EvenBetterFastSim.Tests/ConnectionNodeTests.cs @@ -0,0 +1,160 @@ +using System.Linq; +using System.Text.Json; +using System.Windows; +using EvenBetterFastSim.WPF.ViewModels; +using EvenBetterFastSim.WPF.ViewModels.Graph; +using MessagePack; +using SecsGemScenarioEngine.Models; +using Xunit; + +namespace EvenBetterFastSim.Tests; + +/// +/// The nodes Drop connection and Wait for communication on the canvas (GitLab secsgem/evencoolerfastsim#25). Their +/// parameter is a time in ms as text in TransactionName. The engine reads it as digits only (white space around them +/// ignored) and lets the node fail for anything else, so the title has to say when the value is not a time. +/// +public class ConnectionNodeTests +{ + [Theory] + [InlineData("5000", "Drop connection · 5000 ms")] + [InlineData("0", "Drop connection · 0 ms")] + [InlineData("007", "Drop connection · 7 ms")] + [InlineData(" 250 ", "Drop connection · 250 ms")] + [InlineData("\t250\r\n", "Drop connection · 250 ms")] + // The engine trims every kind of white space here (string.Trim), also a non-breaking space. + [InlineData(" 250", "Drop connection · 250 ms")] + [InlineData("2147483647", "Drop connection · 2147483647 ms")] + [InlineData("2147483648", "Drop connection (invalid: 2147483648)")] + [InlineData("+5", "Drop connection (invalid: +5)")] + [InlineData("-1", "Drop connection (invalid: -1)")] + [InlineData("5 s", "Drop connection (invalid: 5 s)")] + [InlineData("1,5", "Drop connection (invalid: 1,5)")] + [InlineData("15​00", "Drop connection (invalid: 15[U+200B]00)")] + [InlineData("500​", "Drop connection (invalid: 500[U+200B])")] + [InlineData("", "Drop connection (no downtime set)")] + [InlineData(" ", "Drop connection (no downtime set)")] + [InlineData(null, "Drop connection (no downtime set)")] + public void Drop_connection_shows_its_downtime_or_what_is_wrong_with_it(string? text, string title) + { + var node = new ScenarioNodeViewModel { Type = NodeType.DropConnection, TransactionName = text }; + + Assert.Equal(title, node.Title); + } + + [Theory] + [InlineData("20000", "Wait for communication · max 20000 ms")] + [InlineData("1", "Wait for communication · max 1 ms")] + [InlineData(" 250 ", "Wait for communication · max 250 ms")] + [InlineData("0", "Wait for communication · no timeout")] + [InlineData("000", "Wait for communication · no timeout")] + [InlineData("2147483648", "Wait for communication (invalid: 2147483648)")] + [InlineData("+5", "Wait for communication (invalid: +5)")] + [InlineData("-0", "Wait for communication (invalid: -0)")] + [InlineData("20 s", "Wait for communication (invalid: 20 s)")] + [InlineData("20​", "Wait for communication (invalid: 20[U+200B])")] + [InlineData("", "Wait for communication (no timeout set)")] + [InlineData(null, "Wait for communication (no timeout set)")] + public void Wait_for_communication_shows_its_timeout_or_what_is_wrong_with_it(string? text, string title) + { + var node = new ScenarioNodeViewModel { Type = NodeType.WaitForCommunication, TransactionName = text }; + + Assert.Equal(title, node.Title); + } + + /// The title follows the value, and a DisplayName from a file does not replace it. + [Theory] + [InlineData(NodeType.DropConnection, "Drop connection · 100 ms", "Drop connection · 0 ms")] + [InlineData(NodeType.WaitForCommunication, "Wait for communication · max 100 ms", "Wait for communication · no timeout")] + public void Title_follows_the_value_and_is_not_replaced_by_a_display_name(NodeType type, string first, string then) + { + var node = new ScenarioNodeViewModel { Type = type, TransactionName = "100", DisplayName = "Pause" }; + Assert.Equal(first, node.Title); + + node.TransactionName = "0"; + + Assert.Equal(then, node.Title); + } + + /// + /// Both nodes fail in normal use (no connection to drop, communication not back in time). Without a failure + /// output such a failure could not be handled in the scenario and would end the whole run. + /// + [Theory] + [InlineData(NodeType.DropConnection, "5000", "Drop connection · 5000 ms")] + [InlineData(NodeType.WaitForCommunication, "20000", "Wait for communication · max 20000 ms")] + public void Node_from_the_palette_has_its_default_and_a_failure_output(NodeType type, string value, string title) + { + var node = ScenarioNodeViewModel.CreateStructural(type, new Point(120, 80)); + + Assert.Equal(type, node.Type); + Assert.Equal(value, node.TransactionName); + Assert.Equal(title, node.Title); + Assert.Equal(new Point(120, 80), node.Location); + Assert.Equal(["In"], node.Input.Select(connector => connector.Title)); + Assert.Equal(["Success", "Failure"], node.Output.Select(connector => connector.Title)); + Assert.True(node.IsDeletable); + Assert.False(node.CanToggleMode); + Assert.False(node.IsSendNode); + Assert.False(node.IsReceiveNode); + } + + /// The numbers are what files store; they must stay what the engine package defines. + [Fact] + public void Node_types_keep_their_numbers() + { + Assert.Equal(8, (int)NodeType.DropConnection); + Assert.Equal(9, (int)NodeType.WaitForCommunication); + } + + /// + /// Type, value and the failure edge survive saving and loading, as a MessagePack file and as a JSON file (the + /// calls of ScenariosViewModel). The type is stored as a number. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Nodes_and_their_failure_edge_survive_saving_and_loading(bool asJson) + { + var drop = ScenarioNodeViewModel.CreateStructural(NodeType.DropConnection, new Point(5, 6)); + drop.TransactionName = "1500"; + var wait = ScenarioNodeViewModel.CreateStructural(NodeType.WaitForCommunication, new Point(7, 8)); + wait.TransactionName = "0"; + var end = new ScenarioNodeViewModel { Type = NodeType.End }; + var graph = new ScenarioGraph + { + Name = "s", + Nodes = [drop.ToModel(), wait.ToModel(), end.ToModel()], + Edges = + [ + new ScenarioEdge { SourceNodeId = drop.Id, TargetNodeId = wait.Id, IsFailurePath = false }, + new ScenarioEdge { SourceNodeId = drop.Id, TargetNodeId = end.Id, IsFailurePath = true }, + new ScenarioEdge { SourceNodeId = wait.Id, TargetNodeId = end.Id, IsFailurePath = true } + ] + }; + + ScenarioGraph loaded; + if (asJson) + { + var json = JsonSerializer.Serialize(graph, new JsonSerializerOptions { WriteIndented = true }); + Assert.Contains("\"Type\": 8", json); + Assert.Contains("\"Type\": 9", json); + loaded = JsonSerializer.Deserialize(json)!; + } + else + { + var cancellation = TestContext.Current.CancellationToken; + var bytes = MessagePackSerializer.Serialize(ScenarioGraphDto.From(graph), cancellationToken: cancellation); + loaded = MessagePackSerializer.Deserialize(bytes, cancellationToken: cancellation).ToModel(); + } + + var nodes = loaded.Nodes.Select(ScenarioNodeViewModel.FromModel).ToList(); + Assert.Equal([NodeType.DropConnection, NodeType.WaitForCommunication, NodeType.End], nodes.Select(n => n.Type)); + Assert.Equal(["1500", "0", null], nodes.Select(n => n.TransactionName)); + Assert.Equal(["Drop connection · 1500 ms", "Wait for communication · no timeout", "END"], nodes.Select(n => n.Title)); + Assert.Equal([drop.Id, wait.Id, end.Id], nodes.Select(n => n.Id)); + Assert.Equal( + [(drop.Id, wait.Id, false), (drop.Id, end.Id, true), (wait.Id, end.Id, true)], + loaded.Edges.Select(edge => (edge.SourceNodeId, edge.TargetNodeId, edge.IsFailurePath))); + } +} diff --git a/EvenBetterFastSim.Tests/NodeMillisecondsViewModelTests.cs b/EvenBetterFastSim.Tests/NodeMillisecondsViewModelTests.cs index a8364c5..a1d1617 100644 --- a/EvenBetterFastSim.Tests/NodeMillisecondsViewModelTests.cs +++ b/EvenBetterFastSim.Tests/NodeMillisecondsViewModelTests.cs @@ -206,5 +206,80 @@ public void Minimum_decides_whether_zero_is_allowed() Assert.Contains(" 1 ", new NodeMillisecondsViewModel("t", "l", null, minimum: 1).Error); } + /// + /// Drop connection and Wait for communication use the same editor with their own texts (GitLab + /// secsgem/evencoolerfastsim#25). 0 is a value of its own there, so it is allowed and the hint says what it does. + /// + [Theory] + [InlineData(NodeType.DropConnection, "Drop connection", "Downtime (ms)", "With 0 a new connection is set up right away")] + [InlineData(NodeType.WaitForCommunication, "Wait for communication", "Timeout (ms)", "With 0 the node waits as long as the run may take")] + public void Connection_nodes_get_the_editor_with_their_own_texts_and_zero_allowed( + NodeType type, string header, string label, string note) + { + var node = new ScenarioNodeViewModel { Type = type, TransactionName = "5 s" }; + var editor = NodeMillisecondsViewModel.For(node)!; + + Assert.Equal(header, editor.HeaderText); + Assert.Equal(label, editor.Label); + Assert.StartsWith("Whole number from 0 to 2147483647. ", editor.Hint); + Assert.Contains(note, editor.Hint); + Assert.Equal("5 s", editor.Text); + Assert.Equal("This is not a whole number from 0 to 2147483647. Use digits only, for example 1500.", editor.Error); + Assert.False(editor.AcceptButtonClickCommand.CanExecute(null)); + + editor.Text = "0"; + Assert.Null(editor.Error); + editor.AcceptButtonClickCommand.Execute(null); + editor.ApplyTo(node); + + Assert.Equal("0", node.TransactionName); + } + + /// What the editor accepts, the engine reads: digits only, also for these two node types. + [Theory] + [InlineData(NodeType.DropConnection, "+5")] + [InlineData(NodeType.DropConnection, "-1")] + [InlineData(NodeType.DropConnection, "1.5")] + [InlineData(NodeType.WaitForCommunication, "+5")] + [InlineData(NodeType.WaitForCommunication, "2147483648")] + [InlineData(NodeType.WaitForCommunication, "")] + public void Connection_nodes_take_digits_only(NodeType type, string text) + { + var node = new ScenarioNodeViewModel { Type = type, TransactionName = "100" }; + var editor = NodeMillisecondsViewModel.For(node)!; + + editor.Text = text; + editor.AcceptButtonClickCommand.Execute(null); + editor.ApplyTo(node); + + Assert.NotNull(editor.Error); + Assert.False(editor.Accepted); + Assert.Equal("100", node.TransactionName); + } + + [Fact] + public void Wait_node_gets_its_editor_and_does_not_allow_zero() + { + var editor = NodeMillisecondsViewModel.For(WaitNode("0"))!; + + Assert.Equal("Wait", editor.HeaderText); + Assert.Equal("Wait time (ms)", editor.Label); + Assert.Equal("Whole number from 1 to 2147483647.", editor.Hint); + Assert.NotNull(editor.Error); + } + + [Theory] + [InlineData(NodeType.Start)] + [InlineData(NodeType.End)] + [InlineData(NodeType.And)] + [InlineData(NodeType.Send)] + [InlineData(NodeType.SendAndWait)] + [InlineData(NodeType.Receive)] + [InlineData(NodeType.Condition)] + public void Node_types_without_a_time_have_no_such_editor(NodeType type) + { + Assert.Null(NodeMillisecondsViewModel.For(new ScenarioNodeViewModel { Type = type })); + } + private static ScenarioNodeViewModel WaitNode(string? time) => new() { Type = NodeType.Wait, TransactionName = time }; } diff --git a/EvenBetterFastSim.Tests/PortHoldTests.cs b/EvenBetterFastSim.Tests/PortHoldTests.cs new file mode 100644 index 0000000..f6d5a54 --- /dev/null +++ b/EvenBetterFastSim.Tests/PortHoldTests.cs @@ -0,0 +1,114 @@ +using EvenBetterFastSim.Services; +using SecsGemScenarioEngine.Models; +using Xunit; + +namespace EvenBetterFastSim.Tests; + +/// +/// While a Drop connection node keeps the port closed, the Connect button is disabled: a click would open the port in +/// the middle of the downtime (GitLab secsgem/evencoolerfastsim#25). The node reports Waiting for that time. +/// +public class PortHoldTests +{ + [Fact] + public void Port_is_held_from_the_waiting_report_until_the_node_is_done() + { + var hold = new PortHold(); + var run = hold.Begin(); + Assert.False(hold.Active); + + hold.Report(run, "drop", ScenarioNodeRunState.Running); + Assert.False(hold.Active); + + hold.Report(run, "drop", ScenarioNodeRunState.Waiting); + Assert.True(hold.Active); + + hold.Report(run, "drop", ScenarioNodeRunState.Succeeded); + Assert.False(hold.Active); + } + + [Theory] + [InlineData(ScenarioNodeRunState.Failed)] + [InlineData(ScenarioNodeRunState.Idle)] + [InlineData(ScenarioNodeRunState.Running)] + public void Any_other_report_for_the_node_ends_the_hold(ScenarioNodeRunState state) + { + var hold = new PortHold(); + var run = hold.Begin(); + hold.Report(run, "drop", ScenarioNodeRunState.Waiting); + + hold.Report(run, "drop", state); + + Assert.False(hold.Active); + } + + /// A run that is cancelled during the downtime reports nothing more for the node. + [Fact] + public void End_of_the_run_ends_the_hold() + { + var hold = new PortHold(); + var run = hold.Begin(); + hold.Report(run, "drop", ScenarioNodeRunState.Waiting); + + hold.End(run); + + Assert.False(hold.Active); + } + + /// + /// A report can still be on its way to the UI thread when the run ends. It must not disable the button for good. + /// + [Fact] + public void Report_after_the_end_of_the_run_is_ignored() + { + var hold = new PortHold(); + var run = hold.Begin(); + hold.End(run); + + hold.Report(run, "drop", ScenarioNodeRunState.Waiting); + + Assert.False(hold.Active); + } + + /// Several scenarios can run at once, and all share the one connection. + [Fact] + public void Each_run_and_each_node_holds_on_its_own() + { + var hold = new PortHold(); + var first = hold.Begin(); + var second = hold.Begin(); + hold.Report(first, "drop", ScenarioNodeRunState.Waiting); + hold.Report(second, "drop", ScenarioNodeRunState.Waiting); + hold.Report(second, "other", ScenarioNodeRunState.Waiting); + + hold.End(first); + Assert.True(hold.Active); + + hold.Report(second, "other", ScenarioNodeRunState.Succeeded); + // The second run's "drop" is still held: the end of the first run, which held the same id, did not take it. + Assert.True(hold.Active); + + hold.Report(second, "drop", ScenarioNodeRunState.Succeeded); + Assert.False(hold.Active); + } + + /// + /// Two runs can hold a node with the same id: a scenario that was imported twice keeps the ids of its file, and + /// both copies can run at once. A report of one run must not end the hold of the other. + /// + [Fact] + public void Report_of_one_run_does_not_end_the_hold_of_another_run_on_the_same_node_id() + { + var hold = new PortHold(); + var first = hold.Begin(); + var second = hold.Begin(); + hold.Report(first, "drop", ScenarioNodeRunState.Waiting); + hold.Report(second, "drop", ScenarioNodeRunState.Waiting); + + hold.Report(second, "drop", ScenarioNodeRunState.Succeeded); + Assert.True(hold.Active); + + hold.Report(first, "drop", ScenarioNodeRunState.Succeeded); + Assert.False(hold.Active); + } +} diff --git a/EvenBetterFastSim.Tests/ScenarioRunTests.cs b/EvenBetterFastSim.Tests/ScenarioRunTests.cs index 08ea18d..459b161 100644 --- a/EvenBetterFastSim.Tests/ScenarioRunTests.cs +++ b/EvenBetterFastSim.Tests/ScenarioRunTests.cs @@ -228,7 +228,8 @@ public void Copy_keeps_every_property_of_an_edge() /// /// No library transaction is copied into nodes that carry their own, nodes whose TransactionName is a parameter - /// (Wait: ms), and nodes with a name the library does not know (the engine reports those). + /// (Wait, Drop connection, Wait for communication: ms), and nodes with a name the library does not know (the + /// engine reports those). /// [Fact] public void Other_nodes_keep_what_they_have() @@ -241,6 +242,8 @@ public void Other_nodes_keep_what_they_have() [ new ScenarioNode { Type = NodeType.Send, TransactionName = transaction.PrimaryMessage.Name, TransactionJson = own }, new ScenarioNode { Type = NodeType.Wait, TransactionName = transaction.PrimaryMessage.Name }, + new ScenarioNode { Type = NodeType.DropConnection, TransactionName = transaction.PrimaryMessage.Name }, + new ScenarioNode { Type = NodeType.WaitForCommunication, TransactionName = transaction.PrimaryMessage.Name }, new ScenarioNode { Type = NodeType.Receive, TransactionName = "not in the library" }, new ScenarioNode { Type = NodeType.Send, TransactionName = " " } ] diff --git a/EvenBetterFastSim.Tests/WaitNodeTests.cs b/EvenBetterFastSim.Tests/WaitNodeTests.cs index 69bebc9..1aa5854 100644 --- a/EvenBetterFastSim.Tests/WaitNodeTests.cs +++ b/EvenBetterFastSim.Tests/WaitNodeTests.cs @@ -12,8 +12,8 @@ namespace EvenBetterFastSim.Tests; /// /// A Wait node can be made on the canvas and shows its time (GitLab secsgem/evencoolerfastsim#18). The time is text in -/// TransactionName; the engine waits only for a whole number greater than 0 and takes anything else as "no wait" -/// without an error, so the title has to say when the value is not a time. +/// TransactionName; the engine waits only for a whole number greater than 0. For anything else the node still +/// succeeds without waiting, so the title has to say when the value is not a time. /// public class WaitNodeTests { @@ -29,6 +29,7 @@ public class WaitNodeTests [InlineData("99999999999", "Wait (invalid: 99999999999)")] [InlineData("2147483647", "Wait 2147483647 ms")] [InlineData("2147483648", "Wait (invalid: 2147483648)")] + [InlineData("+5", "Wait 5 ms")] [InlineData("\t250\r\n", "Wait 250 ms")] [InlineData("\t20 s\r\n", "Wait (invalid: 20 s)")] [InlineData("", "Wait (no time set)")] @@ -60,30 +61,26 @@ public void Title_shows_characters_nobody_can_see(string text, string title) } /// - /// A leading sign is the one thing the engine versions read differently: up to package 1.0.0-build-0027 with - /// the culture of the computer, later with the invariant culture. The culture decides which characters are the - /// signs: Windows takes them from the regional settings of the user, and ICU data write the plus sign of Persian - /// or Hebrew with a direction mark in front (U+200E U+002B). On a computer with such a plus sign "+5" is a - /// number for one engine and not for the other, so the title must not promise a wait. The culture is made by - /// hand, so the test does not depend on the culture data of the computer it runs on. + /// The title reads the time like the engine: with the invariant culture, whatever the culture of the computer is. + /// The culture decides which characters are the signs: Windows takes them from the regional settings of the user, + /// and ICU data write the plus sign of Persian or Hebrew with a direction mark in front (U+200E U+002B). A read + /// with such a culture does not take "+5" as a number. The culture is made by hand, so the test does not depend + /// on the culture data of the computer it runs on. /// [Fact] - public void Title_promises_a_wait_only_if_every_engine_version_reads_the_time() + public void Title_reads_the_time_like_the_engine_whatever_the_culture_of_the_computer() { var withMark = (CultureInfo)CultureInfo.InvariantCulture.Clone(); withMark.NumberFormat.PositiveSign = "\u200E+"; var before = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; - Assert.Equal("Wait 5 ms", WaitTime.Title("+5")); - CultureInfo.CurrentCulture = withMark; // The culture is in effect: a read with the culture of the computer takes the other spelling. Assert.False(int.TryParse("+5", out _)); Assert.True(int.TryParse("\u200E+5", out _)); - Assert.Equal("Wait (invalid: +5)", WaitTime.Title("+5")); + Assert.Equal("Wait 5 ms", WaitTime.Title("+5")); Assert.Equal("Wait (invalid: [U+200E]+5)", WaitTime.Title("\u200E+5")); Assert.Equal("Wait 12600 ms", WaitTime.Title("12600")); } diff --git a/EvenBetterFastSim/EvenBetterFastSim.csproj b/EvenBetterFastSim/EvenBetterFastSim.csproj index d882e64..7b1d45d 100644 --- a/EvenBetterFastSim/EvenBetterFastSim.csproj +++ b/EvenBetterFastSim/EvenBetterFastSim.csproj @@ -45,8 +45,8 @@ - - + + diff --git a/EvenBetterFastSim/Services/PortHold.cs b/EvenBetterFastSim/Services/PortHold.cs new file mode 100644 index 0000000..9000195 --- /dev/null +++ b/EvenBetterFastSim/Services/PortHold.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using SecsGemScenarioEngine.Models; + +namespace EvenBetterFastSim.Services; + +/// +/// Knows whether a running scenario keeps the port closed right now. A Drop connection node with a downtime reports +/// for as long as it keeps the port closed. The Connect button is disabled +/// meanwhile: a click would open the port in the middle of the downtime (GitLab secsgem/evencoolerfastsim#25). +/// Not thread-safe; used on the UI thread. +/// +public sealed class PortHold +{ + /// One run of a scenario. Reports that arrive after are ignored. + public sealed class Run + { + internal bool Ended { get; set; } + } + + private readonly HashSet<(Run Run, string NodeId)> holders = []; + + /// True while at least one Drop connection node of a run that has not ended keeps the port closed. + public bool Active => holders.Count > 0; + + public Run Begin() => new(); + + /// Takes a progress report for a Drop connection node of the run. + public void Report(Run run, string nodeId, ScenarioNodeRunState state) + { + if (run.Ended) return; + if (state == ScenarioNodeRunState.Waiting) + holders.Add((run, nodeId)); + else + holders.Remove((run, nodeId)); + } + + /// + /// The run is over, however it ended. A run that is cancelled during the downtime reports nothing more for the + /// node; the engine opens the port again on its way out. + /// + public void End(Run run) + { + run.Ended = true; + holders.RemoveWhere(holder => holder.Run == run); + } +} diff --git a/EvenBetterFastSim/WPF/ViewModels/Graph/CommunicationTimeout.cs b/EvenBetterFastSim/WPF/ViewModels/Graph/CommunicationTimeout.cs new file mode 100644 index 0000000..125644a --- /dev/null +++ b/EvenBetterFastSim/WPF/ViewModels/Graph/CommunicationTimeout.cs @@ -0,0 +1,27 @@ +namespace EvenBetterFastSim.WPF.ViewModels.Graph; + +/// +/// The timeout of a Wait for communication node, in milliseconds, kept as text in +/// ScenarioNode.TransactionName. The node waits until data messages can be exchanged again (HSMS selected and +/// communication established); with 0 as long as the run may take (GitLab secsgem/evencoolerfastsim#25). +/// +public static class CommunicationTimeout +{ + /// The timeout a Wait for communication node gets when it is dragged from the palette. + public const int DefaultMilliseconds = 20000; + + /// + /// The node's title: "Wait for communication · max 20000 ms", or what is wrong with the value. The engine lets + /// the node fail for a value it cannot read (), also for a missing one. + /// + public static string Title(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + return "Wait for communication (no timeout set)"; + if (!NodeMilliseconds.TryReadDigits(text, out var milliseconds)) + return $"Wait for communication (invalid: {NodeMilliseconds.Visible(text.Trim())})"; + return milliseconds == 0 + ? "Wait for communication · no timeout" + : $"Wait for communication · max {NodeMilliseconds.Format(milliseconds)} ms"; + } +} diff --git a/EvenBetterFastSim/WPF/ViewModels/Graph/DropConnectionTime.cs b/EvenBetterFastSim/WPF/ViewModels/Graph/DropConnectionTime.cs new file mode 100644 index 0000000..772dfd7 --- /dev/null +++ b/EvenBetterFastSim/WPF/ViewModels/Graph/DropConnectionTime.cs @@ -0,0 +1,25 @@ +namespace EvenBetterFastSim.WPF.ViewModels.Graph; + +/// +/// The downtime of a Drop connection node, in milliseconds, kept as text in ScenarioNode.TransactionName. The +/// node aborts the connection with a TCP reset. With 0 a new connection is set up right away; with more the port +/// stays closed that long (GitLab secsgem/evencoolerfastsim#25). +/// +public static class DropConnectionTime +{ + /// The downtime a Drop connection node gets when it is dragged from the palette. + public const int DefaultMilliseconds = 5000; + + /// + /// The node's title: "Drop connection · 5000 ms", or what is wrong with the value. The engine lets the node fail + /// for a value it cannot read (), also for a missing one. + /// + public static string Title(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + return "Drop connection (no downtime set)"; + return NodeMilliseconds.TryReadDigits(text, out var milliseconds) + ? $"Drop connection · {NodeMilliseconds.Format(milliseconds)} ms" + : $"Drop connection (invalid: {NodeMilliseconds.Visible(text.Trim())})"; + } +} diff --git a/EvenBetterFastSim/WPF/ViewModels/Graph/NodeMilliseconds.cs b/EvenBetterFastSim/WPF/ViewModels/Graph/NodeMilliseconds.cs new file mode 100644 index 0000000..3924d4e --- /dev/null +++ b/EvenBetterFastSim/WPF/ViewModels/Graph/NodeMilliseconds.cs @@ -0,0 +1,59 @@ +using System.Globalization; +using System.Text; + +namespace EvenBetterFastSim.WPF.ViewModels.Graph; + +/// +/// For scenario nodes whose parameter is a time in milliseconds, kept as text in ScenarioNode.TransactionName: +/// Wait (), Drop connection () and Wait for communication +/// (). +/// +public static class NodeMilliseconds +{ + public static string Format(int milliseconds) => milliseconds.ToString(CultureInfo.InvariantCulture); + + /// + /// Reads the text the way the scenario engine reads the parameter of a Drop connection and a Wait for + /// communication node (TryParseMilliseconds in ScenarioExecutionService): the digits 0-9 only, within the range of + /// an int, white space around them ignored. Such a node fails when its parameter is anything else. + /// + public static bool TryReadDigits(string? text, out int milliseconds) => + int.TryParse(text?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out milliseconds); + + /// + /// A character nobody can see in a title or a text box: white space other than the space, control characters and + /// format characters (a non-breaking space, a tab, a zero-width space, a byte order mark). + /// + public static bool IsHidden(char character) => + character != ' ' && + (char.IsWhiteSpace(character) || char.IsControl(character) || + char.GetUnicodeCategory(character) == UnicodeCategory.Format); + + /// + /// Writes characters nobody can see as [U+00A0]. A value from a hand-edited file with a non-breaking space or a + /// zero-width character in it would otherwise show as "Wait (invalid: 1500)", which looks like a valid time. + /// + public static string Visible(string text) + { + var visible = new StringBuilder(text.Length); + foreach (var character in text) + { + if (IsHidden(character)) + visible.Append(CultureInfo.InvariantCulture, $"[U+{(int)character:X4}]"); + else + visible.Append(character); + } + return visible.ToString(); + } + + /// The text without the spaces and the characters nobody can see at its two ends. + public static string TrimEnds(string? text) + { + if (text is null) return string.Empty; + var start = 0; + var end = text.Length; + while (start < end && (text[start] == ' ' || IsHidden(text[start]))) start++; + while (end > start && (text[end - 1] == ' ' || IsHidden(text[end - 1]))) end--; + return text[start..end]; + } +} diff --git a/EvenBetterFastSim/WPF/ViewModels/Graph/ScenarioNodeViewModel.cs b/EvenBetterFastSim/WPF/ViewModels/Graph/ScenarioNodeViewModel.cs index f1a19d4..7325eee 100644 --- a/EvenBetterFastSim/WPF/ViewModels/Graph/ScenarioNodeViewModel.cs +++ b/EvenBetterFastSim/WPF/ViewModels/Graph/ScenarioNodeViewModel.cs @@ -96,13 +96,19 @@ public string? BindingSummary public bool IsDeletable => Type is not (NodeType.Start or NodeType.End); /// - /// A node dragged from the palette (And, Wait). A Wait node starts with - /// ; double-click it to change the time. + /// A node dragged from the palette (And, Wait, Drop connection, Wait for communication). A node with a time in ms + /// starts with its default; double-click it to change the time. /// public static ScenarioNodeViewModel CreateStructural(NodeType type, Point location) => new() { Type = type, - TransactionName = type == NodeType.Wait ? WaitTime.Format(WaitTime.DefaultMilliseconds) : null, + TransactionName = type switch + { + NodeType.Wait => NodeMilliseconds.Format(WaitTime.DefaultMilliseconds), + NodeType.DropConnection => NodeMilliseconds.Format(DropConnectionTime.DefaultMilliseconds), + NodeType.WaitForCommunication => NodeMilliseconds.Format(CommunicationTimeout.DefaultMilliseconds), + _ => null + }, Location = location }; @@ -158,6 +164,10 @@ private void InitializeConnectors() NodeType.Receive => ["Success", "Failure"], NodeType.Condition => ["YES", "NO"], NodeType.And => ["Out"], + // Both fail in normal use (no connection to drop, communication not back in time), so they need the + // failure output; without it a failure ends the whole run. + NodeType.DropConnection => ["Success", "Failure"], + NodeType.WaitForCommunication => ["Success", "Failure"], _ => ["Done"], }; @@ -191,6 +201,8 @@ private void UpdateTitleFromType() NodeType.Send => label ?? "Send", NodeType.Condition => label ?? "If", NodeType.Wait => WaitTime.Title(TransactionName), + NodeType.DropConnection => DropConnectionTime.Title(TransactionName), + NodeType.WaitForCommunication => CommunicationTimeout.Title(TransactionName), NodeType.Receive => label ?? "Receive", NodeType.And => "AND", _ => label ?? Type.ToString() diff --git a/EvenBetterFastSim/WPF/ViewModels/Graph/WaitTime.cs b/EvenBetterFastSim/WPF/ViewModels/Graph/WaitTime.cs index 951e214..6eb0bfe 100644 --- a/EvenBetterFastSim/WPF/ViewModels/Graph/WaitTime.cs +++ b/EvenBetterFastSim/WPF/ViewModels/Graph/WaitTime.cs @@ -1,5 +1,4 @@ using System.Globalization; -using System.Text; namespace EvenBetterFastSim.WPF.ViewModels.Graph; @@ -15,22 +14,18 @@ public static class WaitTime private static readonly char[] SkippedByTheEngine = [' ', '\t', '\n', '\v', '\f', '\r']; /// - /// True for a text that every version of the scenario engine reads as the same whole number (int.TryParse - /// in ExecuteWaitAsync): the digits 0-9, within the range of an int, with spaces around them and a leading sign - /// allowed. The engine waits only if that number is greater than 0; anything else is no wait, without an error. + /// Reads the text the way the scenario engine does (int.TryParse with NumberStyles.Integer and the + /// invariant culture in ExecuteWaitAsync): the digits 0-9, within the range of an int, with spaces around them and + /// a leading sign allowed. The engine waits only if that number is greater than 0; 0 does not wait. A text it + /// cannot read this way and a negative number do not wait either: the node still succeeds, and the engine logs + /// a warning. /// /// - /// The engine up to package 1.0.0-build-0027 reads with the culture of the computer, a later one with the - /// invariant culture. The two can differ only in the sign, because the culture decides which characters are the - /// plus and the minus sign (Windows takes them from the regional settings of the user). "+5" is then a number - /// for one engine and not for the other. Such a text does not count as a time here, so the title never promises - /// a wait that the engine in use skips. On a computer where the plus sign is "+" this changes nothing. + /// The engine reads this way since package 1.0.0-build-0029. Up to 1.0.0-build-0027 it read with the + /// culture of the computer, which could take a leading sign differently. /// public static bool TryRead(string? text, out int milliseconds) => - int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out milliseconds) && - int.TryParse(text, NumberStyles.Integer, CultureInfo.CurrentCulture, out _); - - public static string Format(int milliseconds) => milliseconds.ToString(CultureInfo.InvariantCulture); + int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out milliseconds); /// /// The node's title: "Wait 12600 ms", or what is wrong with the value. Until GitLab secsgem/evencoolerfastsim#18 @@ -41,44 +36,7 @@ public static string Title(string? text) if (string.IsNullOrWhiteSpace(text)) return "Wait (no time set)"; return TryRead(text, out var milliseconds) && milliseconds >= 0 - ? $"Wait {Format(milliseconds)} ms" - : $"Wait (invalid: {Visible(text.Trim(SkippedByTheEngine))})"; - } - - /// - /// A character nobody can see in a title or a text box: white space other than the space, control characters and - /// format characters (a non-breaking space, a tab, a zero-width space, a byte order mark). - /// - public static bool IsHidden(char character) => - character != ' ' && - (char.IsWhiteSpace(character) || char.IsControl(character) || - char.GetUnicodeCategory(character) == UnicodeCategory.Format); - - /// - /// Writes characters nobody can see as [U+00A0]. A value from a hand-edited file with a non-breaking space or a - /// zero-width character in it would otherwise show as "Wait (invalid: 1500)", which looks like a valid time. - /// - public static string Visible(string text) - { - var visible = new StringBuilder(text.Length); - foreach (var character in text) - { - if (IsHidden(character)) - visible.Append(CultureInfo.InvariantCulture, $"[U+{(int)character:X4}]"); - else - visible.Append(character); - } - return visible.ToString(); - } - - /// The text without the spaces and the characters nobody can see at its two ends. - public static string TrimEnds(string? text) - { - if (text is null) return string.Empty; - var start = 0; - var end = text.Length; - while (start < end && (text[start] == ' ' || IsHidden(text[start]))) start++; - while (end > start && (text[end - 1] == ' ' || IsHidden(text[end - 1]))) end--; - return text[start..end]; + ? $"Wait {NodeMilliseconds.Format(milliseconds)} ms" + : $"Wait (invalid: {NodeMilliseconds.Visible(text.Trim(SkippedByTheEngine))})"; } } diff --git a/EvenBetterFastSim/WPF/ViewModels/MainViewModel.cs b/EvenBetterFastSim/WPF/ViewModels/MainViewModel.cs index 0928e74..0395f1d 100644 --- a/EvenBetterFastSim/WPF/ViewModels/MainViewModel.cs +++ b/EvenBetterFastSim/WPF/ViewModels/MainViewModel.cs @@ -141,6 +141,11 @@ public MainViewModel(CommunicationHandler messageHandler, EventLibraryManager = eventLibraryManager; this.eventReportHandler = eventReportHandler; ScenariosVm = scenariosVm; + ScenariosVm.PropertyChanged += (_, e) => + { + if (e.PropertyName == nameof(ScenariosViewModel.PortClosedByScenario)) + ConnectCommand.NotifyCanExecuteChanged(); + }; SecsGemEventCollection = eventLibraryManager.EventCollection; SecsGemReportCollection = eventLibraryManager.ReportCollection; @@ -328,7 +333,10 @@ private bool CanMoveSelectedItemDown() return false; } - [RelayCommand(AllowConcurrentExecutions = false)] + // Not while a scenario keeps the port closed: the click would open it in the middle of the downtime. + private bool CanConnect() => !ScenariosVm.PortClosedByScenario; + + [RelayCommand(AllowConcurrentExecutions = false, CanExecute = nameof(CanConnect))] private async Task Connect() { try diff --git a/EvenBetterFastSim/WPF/ViewModels/NodeMillisecondsViewModel.cs b/EvenBetterFastSim/WPF/ViewModels/NodeMillisecondsViewModel.cs index 22678ae..e6d04db 100644 --- a/EvenBetterFastSim/WPF/ViewModels/NodeMillisecondsViewModel.cs +++ b/EvenBetterFastSim/WPF/ViewModels/NodeMillisecondsViewModel.cs @@ -3,18 +3,19 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using EvenBetterFastSim.WPF.ViewModels.Graph; +using SecsGemScenarioEngine.Models; namespace EvenBetterFastSim.WPF.ViewModels; /// -/// Editor for a scenario node's parameter in milliseconds, such as the time of a Wait node. Hosted in the shared -/// DialogWindow, whose OK button binds to -/// (GitLab secsgem/evencoolerfastsim#18). +/// Editor for a scenario node's parameter in milliseconds: the time of a Wait node, the downtime of a Drop connection +/// node, the timeout of a Wait for communication node. Hosted in the shared DialogWindow, whose OK button +/// binds to (GitLab secsgem/evencoolerfastsim#18 and #25). /// /// /// -/// The engine reads a Wait node's time with int.TryParse and treats everything it cannot read as "no wait", without an -/// error. So the editor only accepts a whole number written in digits, and the node stores it in that form. +/// The engine does not wait for a Wait node's time it cannot read, and it lets the other two node types fail. So the +/// editor only accepts a whole number written in digits, and the node stores it in that form. /// /// /// Not an ObservableValidator on purpose: DialogWindow binds its content to the view model itself, and WPF then draws @@ -55,8 +56,8 @@ public string? Error { if (TryParse(Text, minimum, out _)) return null; // A character nobody can see inside the number (from a file or pasted): the box shows "1500", so say why. - var entered = WaitTime.TrimEnds(Text); - var visible = WaitTime.Visible(entered); + var entered = NodeMilliseconds.TrimEnds(Text); + var visible = NodeMilliseconds.Visible(entered); return visible != entered ? $"The text contains characters that cannot be seen: {visible}. Type the number again, in digits only." : $"This is not a whole number from {minimum} to {int.MaxValue}. Use digits only, for example 1500."; @@ -64,25 +65,48 @@ public string? Error } /// Smallest value the editor accepts (1 for a time that has to be greater than 0). - public NodeMillisecondsViewModel(string headerText, string label, string? text, int minimum) + /// What a special value means, added to the hint; for example what 0 does. + public NodeMillisecondsViewModel(string headerText, string label, string? text, int minimum, string? note = null) { HeaderText = headerText; Label = label; this.minimum = minimum; - Hint = $"Whole number from {minimum} to {int.MaxValue}."; - this.text = WaitTime.TrimEnds(text); + Hint = $"Whole number from {minimum} to {int.MaxValue}." + (note is null ? string.Empty : " " + note); + this.text = NodeMilliseconds.TrimEnds(text); } - /// The editor for the time of a Wait node; it starts with the node's current text, also when that is invalid. + /// + /// The editor for a node with a time in ms, or null for a node type without one. It starts with the node's + /// current text, also when that is invalid. + /// + public static NodeMillisecondsViewModel? For(ScenarioNodeViewModel node) => node.Type switch + { + NodeType.Wait => ForWait(node), + NodeType.DropConnection => ForDropConnection(node), + NodeType.WaitForCommunication => ForWaitForCommunication(node), + _ => null + }; + + /// The editor for the time of a Wait node. public static NodeMillisecondsViewModel ForWait(ScenarioNodeViewModel node) => new("Wait", "Wait time (ms)", node.TransactionName, minimum: 1); + /// The editor for the downtime of a Drop connection node. + public static NodeMillisecondsViewModel ForDropConnection(ScenarioNodeViewModel node) => + new("Drop connection", "Downtime (ms)", node.TransactionName, minimum: 0, + note: "With 0 a new connection is set up right away; with more the port stays closed that long."); + + /// The editor for the timeout of a Wait for communication node. + public static NodeMillisecondsViewModel ForWaitForCommunication(ScenarioNodeViewModel node) => + new("Wait for communication", "Timeout (ms)", node.TransactionName, minimum: 0, + note: "With 0 the node waits as long as the run may take."); + /// /// Digits only, within the range of an int and not below the minimum. Spaces and characters nobody can see at - /// the two ends are ignored (); OK writes the bare digits. + /// the two ends are ignored (); OK writes the bare digits. /// public static bool TryParse(string? text, int minimum, out int milliseconds) => - int.TryParse(WaitTime.TrimEnds(text), NumberStyles.None, CultureInfo.InvariantCulture, out milliseconds) && + int.TryParse(NodeMilliseconds.TrimEnds(text), NumberStyles.None, CultureInfo.InvariantCulture, out milliseconds) && milliseconds >= minimum; [RelayCommand(CanExecute = nameof(CanAccept))] @@ -100,6 +124,6 @@ private void AcceptButtonClick() public void ApplyTo(ScenarioNodeViewModel node) { if (Accepted) - node.TransactionName = WaitTime.Format(Milliseconds); + node.TransactionName = NodeMilliseconds.Format(Milliseconds); } } diff --git a/EvenBetterFastSim/WPF/ViewModels/ScenariosViewModel.cs b/EvenBetterFastSim/WPF/ViewModels/ScenariosViewModel.cs index 24e4459..c99e27e 100644 --- a/EvenBetterFastSim/WPF/ViewModels/ScenariosViewModel.cs +++ b/EvenBetterFastSim/WPF/ViewModels/ScenariosViewModel.cs @@ -74,6 +74,15 @@ public partial class ScenariosViewModel : ObservableObject /// Scenarios currently executing (a one-off run or a loop), each with its own cancellation source. private readonly Dictionary activeRuns = []; + private readonly Services.PortHold portHold = new(); + + /// + /// True while a Drop connection node of a running scenario keeps the port closed. The Connect button is disabled + /// meanwhile: a click would open the port in the middle of the downtime (GitLab secsgem/evencoolerfastsim#25). + /// + [ObservableProperty] + private bool portClosedByScenario; + public ICommand DisconnectConnectorCommand { get; } public ICommand DeleteSelectionCommand { get; } @@ -299,6 +308,7 @@ private async Task RunOnceAsync( System.Collections.Concurrent.ConcurrentDictionary? consumed, CancellationToken token) { + var portHoldRun = portHold.Begin(); try { // Build from the scenario's own canvas so a loop keeps running even while another @@ -316,10 +326,18 @@ private async Task RunOnceAsync( if (canvasNodes != null) foreach (var n in canvasNodes) { n.RunState = ScenarioNodeRunState.Idle; n.RunDetail = null; } - IProgress? progress = canvasNodes is null ? null + // Which Drop connection node keeps the port closed is tracked also for a scenario that runs from its + // stored graph (never opened on the canvas). + var dropNodes = graph.Nodes.Where(n => n.Type == NodeType.DropConnection).Select(n => n.Id).ToHashSet(); + IProgress? progress = canvasNodes is null && dropNodes.Count == 0 ? null : new Progress(p => { - if (canvasNodes.FirstOrDefault(n => n.Id == p.NodeId) is not { } vm) return; + if (dropNodes.Contains(p.NodeId)) + { + portHold.Report(portHoldRun, p.NodeId, p.State); + PortClosedByScenario = portHold.Active; + } + if (canvasNodes?.FirstOrDefault(n => n.Id == p.NodeId) is not { } vm) return; if (Services.ScenarioRun.IsStale(vm.RunState, p)) return; vm.RunState = p.State; vm.RunDetail = p.Detail; @@ -359,6 +377,21 @@ or ScenarioNodeRunState.Waiting { LogError($"Scenario '{scenario.Name}' errored: {ex.Message}"); } + finally + { + // A run that ends during the downtime (cancelled, timed out, failed in another branch) reports nothing + // more for the node; the engine has opened the port again on its way out. + portHold.End(portHoldRun); + PortClosedByScenario = portHold.Active; + // So the node's hourglass "port closed, opens again in N ms" must not stay either. + if (scenario.CachedNodes is { } shownNodes) + foreach (var node in shownNodes) + if (node.Type == NodeType.DropConnection && node.RunState == ScenarioNodeRunState.Waiting) + { + node.RunState = ScenarioNodeRunState.Idle; + node.RunDetail = null; + } + } } /// Stops a scenario's run or loop, if any. @@ -553,7 +586,8 @@ private void AddNodeToCanvas(object? parameter) /// /// Opens the editor for a node: match conditions for a Receive node, response values for a - /// Send node, the time for a Wait node. Invoked by right-click / double-click / Enter on the canvas. + /// Send node, the time in ms for a Wait, Drop connection or Wait for communication node. + /// Invoked by right-click / double-click / Enter on the canvas. /// [RelayCommand] private void OpenNodeEditor(ScenarioNodeViewModel? node) @@ -575,9 +609,9 @@ private void OpenNodeEditor(ScenarioNodeViewModel? node) windowManager.ShowDialog(vm); break; } - case NodeType.Wait: + case NodeType.Wait or NodeType.DropConnection or NodeType.WaitForCommunication: { - var vm = NodeMillisecondsViewModel.ForWait(node); + if (NodeMillisecondsViewModel.For(node) is not { } vm) break; windowManager.ShowDialog(vm); vm.ApplyTo(node); break; diff --git a/EvenBetterFastSim/WPF/Windows/MainWindow.xaml b/EvenBetterFastSim/WPF/Windows/MainWindow.xaml index f9ceb91..a942399 100644 --- a/EvenBetterFastSim/WPF/Windows/MainWindow.xaml +++ b/EvenBetterFastSim/WPF/Windows/MainWindow.xaml @@ -617,6 +617,14 @@ + + + + + + + + @@ -796,6 +804,22 @@ ToolTip="Wait: pauses for a time in ms before the scenario continues (double-click the node to set it)"> + + + + + +