From 883ba2ca880759d90b9915e40f383438c9eeeb3c Mon Sep 17 00:00:00 2001 From: Oleg <18466855+EvaTheSalmon@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:09:29 +0300 Subject: [PATCH] fix(plc): pause writes until the comparison decides Sync wrote the screen recipe to the PLC before the reconnect comparison read the PLC recipe (#181). An edit after a link drop started the 1 s debounce, and a reconnect inside it wrote that edit over a recipe the comparison had not seen yet. The same happened to an edit made while sync on was still connecting. A failed comparison read also wrote the screen recipe, a conflict dialog closed without a choice left sync on for the next edit to overwrite the PLC, an answer from before a link drop still acted, and a version mismatch on reconnect disconnected from inside the comparison, waiting on the reconnect loop, and turned sync off without a message. PlcSyncCoordinator now holds a write pause. Sync on and a link loss start it and drop a debounced write; a write already in flight ends as before. Edits during the pause stay on screen and are kept, and no debounce, run end or finished write starts a new write while it holds. PlcLifecycleManager gives each comparison an ID, which a link drop, a newer comparison or sync off makes stale. Each current outcome ends the pause in one step with the ID check: identical, PLC empty or not committed end it with a write of the newest screen recipe, a conflict keeps it, a take ends it without a write. Stale results and answers change nothing. A failed, deadline-passed or throwing comparison read closes the client and declares link loss through IS7Connection.DeclareLinkLost, so the reconnect loop compares again. A comparison cut by a link drop counts as failed too, so the count does not depend on whether the drop or the failed read arrives first. Three in a row turn sync off. A version mismatch on reconnect turns sync off with the version message. The first-connect comparison runs after EnableSync's version read and skips its own, so a mismatched PLC is never compared or written. The conflict answers carry the comparison ID. Closing the dialog without a choice (X, Esc, Alt+F4; Esc gets a handler) or a dialog that cannot be shown turns sync off, and so does a PLC recipe that fails the take check, in the dialog or on the reconnect take. Sync on and off run one at a time behind one gate, and a comparison starts only while the sync-on flag, kept under the comparison lock, is set. The app posts its turn-offs so the comparison and the reconnect loop never wait on them; each is checked again when it runs and does nothing after sync off, in a newer sync-on period, or for the failure cap once a later comparison decided. The switch acts in the direction it showed at the press, so a press during an app turn-off cannot turn sync back on. A conflict handler that throws, or a take that throws, also ends the conflict with sync off instead of holding the pause with no dialog. The reconnect take checks again on the UI thread that the screen recipe is empty and saved; an Open that landed during the read gets the conflict instead. Each turn-off reason reaches the notification panel as a typed error on PlcLifecycleManager.SyncTurnOffs and stays there through edits until sync is turned on again. PlcLifecycleManager is now a facade over PlcSyncSwitch, PlcComparisonState, PlcReconnectComparison, PlcConflictNotifier, PlcReconnectTake and PlcComparisonAnswers. S7Service.DeclareLinkLost marks the link lost before it closes the client, so the close cannot hit a link the reconnect loop opened. Closes #181 Co-Authored-By: Claude Opus 5.5 --- SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs | 8 + SemiStep/SemiStep.Core/Plc/IS7Connection.cs | 3 + .../SemiStep.Core/Plc/PlcComparisonAnswers.cs | 123 ++++ .../SemiStep.Core/Plc/PlcComparisonState.cs | 218 +++++++ .../SemiStep.Core/Plc/PlcConflictAnswer.cs | 10 + .../SemiStep.Core/Plc/PlcConflictNotifier.cs | 54 ++ .../SemiStep.Core/Plc/PlcLifecycleManager.cs | 547 +++-------------- .../SemiStep.Core/Plc/PlcRecipeConflict.cs | 6 + SemiStep/SemiStep.Core/Plc/PlcRecipeOffer.cs | 6 + .../SemiStep.Core/Plc/PlcReconciliationLog.cs | 90 +++ .../Plc/PlcReconciliationOutcome.cs | 5 +- .../Plc/PlcReconnectComparison.cs | 323 ++++++++++ .../SemiStep.Core/Plc/PlcReconnectTake.cs | 88 +++ SemiStep/SemiStep.Core/Plc/PlcSyncSwitch.cs | 248 ++++++++ SemiStep/SemiStep.Core/Plc/S7/S7Service.cs | 42 +- .../Plc/Sync/ComparisonReadsFailedError.cs | 9 + .../Plc/Sync/ConflictUnresolvedError.cs | 13 + .../Plc/Sync/PlcRecipeNotLoadedError.cs | 10 + .../Plc/Sync/PlcSyncCoordinator.cs | 79 ++- SemiStep/SemiStep.Core/Plc/SyncTurnOff.cs | 9 + .../Domain/PlcComparisonStateTests.cs | 123 ++++ .../PlcLifecycleManagerReconnectTests.cs | 81 ++- .../PlcReconciliationOutcomeLogTests.cs | 58 +- .../Domain/PlcRunEndSyncTests.cs | 10 +- .../Domain/PlcWritePauseSyncTests.cs | 190 ++++++ .../Domain/PlcWritePauseTests.cs | 578 ++++++++++++++++++ .../Helpers/StubPlcSyncService.cs | 51 +- .../SemiStep.Tests/Helpers/StubS7Service.cs | 42 +- .../SemiStep.Tests/S7/Helpers/FakeS7Driver.cs | 5 +- .../S7/Helpers/StubS7ServiceForSync.cs | 4 + .../S7/PlcSyncCoordinatorInterleavingTests.cs | 2 + .../S7/PlcSyncCoordinatorTests.cs | 4 + .../S7/PlcSyncCoordinatorWritePauseTests.cs | 136 +++++ SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs | 42 ++ .../SemiStep.Tests/S7/ShutdownOrderTests.cs | 5 + .../CoreErrorLocalizationCoverageTests.cs | 6 + .../MainWindowConflictResolutionTests.cs | 189 ++++-- .../UI/MainWindow/SyncToggleTests.cs | 18 + .../UI/Plc/PlcConflictDialogTests.cs | 36 ++ .../UI/RecipeCoordinatorTests.cs | 9 +- .../UI/RecipeGrid/ChangeMarkUndoTests.cs | 3 + .../Coordinator/RecipeCoordinator.cs | 71 ++- .../Localization/ReasonLocalizer.cs | 9 + .../SemiStep.UI/Localization/Resources.resx | 18 +- .../Localization/Resources.ru.resx | 18 +- .../MainWindow/MainWindowViewModel.cs | 53 +- .../MessageService/MessagePanelViewModel.cs | 31 + .../Plc/PlcConflictDialog.axaml.cs | 13 + docs/architecture/dialogs-and-interactions.md | 13 +- docs/architecture/error-reporting.md | 11 + docs/architecture/exit-flow.md | 6 +- ...0261130-recipe-replace-save-exit-safety.md | 2 +- docs/readme.md | 38 +- 53 files changed, 3094 insertions(+), 672 deletions(-) create mode 100644 SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcConflictNotifier.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcRecipeConflict.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcRecipeOffer.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcReconciliationLog.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcReconnectComparison.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcReconnectTake.cs create mode 100644 SemiStep/SemiStep.Core/Plc/PlcSyncSwitch.cs create mode 100644 SemiStep/SemiStep.Core/Plc/Sync/ComparisonReadsFailedError.cs create mode 100644 SemiStep/SemiStep.Core/Plc/Sync/ConflictUnresolvedError.cs create mode 100644 SemiStep/SemiStep.Core/Plc/Sync/PlcRecipeNotLoadedError.cs create mode 100644 SemiStep/SemiStep.Core/Plc/SyncTurnOff.cs create mode 100644 SemiStep/SemiStep.Tests/Domain/PlcComparisonStateTests.cs create mode 100644 SemiStep/SemiStep.Tests/Domain/PlcWritePauseSyncTests.cs create mode 100644 SemiStep/SemiStep.Tests/Domain/PlcWritePauseTests.cs create mode 100644 SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorWritePauseTests.cs create mode 100644 SemiStep/SemiStep.Tests/UI/Plc/PlcConflictDialogTests.cs diff --git a/SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs b/SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs index 4eb6a5bc..607ad8d2 100644 --- a/SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs +++ b/SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs @@ -13,6 +13,14 @@ public interface IPlcSyncService void HandleConnectionLost(); + /// + /// Ends the write pause and writes the newest recipe notified during it, or if none was. + /// + void EndWritePause(Recipe screenRecipe, bool isValid); + + /// Ends the write pause and drops the recipe notified during it: the PLC already holds the screen recipe. + void EndWritePauseWithoutWrite(); + /// /// Completes when the attempt in flight at the call has ended; throws when cancels first. /// diff --git a/SemiStep/SemiStep.Core/Plc/IS7Connection.cs b/SemiStep/SemiStep.Core/Plc/IS7Connection.cs index 63d29273..2ff52b0e 100644 --- a/SemiStep/SemiStep.Core/Plc/IS7Connection.cs +++ b/SemiStep/SemiStep.Core/Plc/IS7Connection.cs @@ -10,4 +10,7 @@ public interface IS7Connection : IAsyncDisposable event Action? StateChanged; Task ConnectAsync(PlcConnectionSettings settings); Task DisconnectAsync(); + + /// Closes the client and runs the link-loss path, as a failed keep-alive probe does. + void DeclareLinkLost(); } diff --git a/SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs b/SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs new file mode 100644 index 00000000..7cf55884 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs @@ -0,0 +1,123 @@ +using FluentResults; + +using Microsoft.Extensions.Logging; + +using SemiStep.Core.Plc.Sync; +using SemiStep.Core.Recipes; + +namespace SemiStep.Core.Plc; + +/// +/// Answers to the offer a comparison made: the conflict answers and the reconnect take. Each runs on the UI thread +/// and counts only while its comparison is current. +/// +internal sealed class PlcComparisonAnswers( + RecipeSession session, + IPlcSyncService syncService, + PlcComparisonState state, + PlcSyncSwitch syncSwitch, + PlcConflictNotifier conflictNotifier, + ILogger logger) +{ + private readonly RecipeSession _session = session; + private readonly IPlcSyncService _syncService = syncService; + private readonly PlcComparisonState _state = state; + private readonly PlcSyncSwitch _syncSwitch = syncSwitch; + private readonly PlcConflictNotifier _conflictNotifier = conflictNotifier; + private readonly ILogger _logger = logger; + + /// + /// The comparison saw an empty screen recipe off the UI thread. A screen that has steps or unsaved changes by now + /// gets the conflict instead of the take. + /// + public Result ApplyRecipeFromPlc(Recipe recipe) + { + PlcRecipeConflict? conflict = null; + Result result; + lock (_state.Gate) + { + if (_state.TakeOfferLocked(offer => !offer.IsConflict && ReferenceEquals(offer.PlcRecipe, recipe)) is not + { } offer) + { + _logger.LogInformation("PLC recipe take ignored: its comparison is stale"); + return Result.Ok(false); + } + + if (_session.Current.Steps.Count > 0 || _session.IsDirty) + { + _state.ConvertTakeToConflictLocked(offer); + conflict = new PlcRecipeConflict(offer.ComparisonId, _session.Current, recipe); + result = Result.Ok(false); + } + else + { + result = TakeLocked(recipe); + } + } + + if (conflict is not null) + { + _conflictNotifier.Raise(conflict); + } + + return result; + } + + /// Returns whether the session recipe was replaced; an answer to a stale conflict changes nothing. + public Result ResolveConflict(long comparisonId, PlcConflictAnswer answer) + { + if (!Enum.IsDefined(answer)) + { + throw new ArgumentOutOfRangeException(nameof(answer), answer, "Unnamed conflict answer"); + } + + lock (_state.Gate) + { + if (_state.TakeOfferLocked(offer => offer.IsConflict && offer.ComparisonId == comparisonId) is not { } offer) + { + _logger.LogInformation("PLC conflict answer {Answer} ignored: its comparison is stale", answer); + return Result.Ok(false); + } + + switch (answer) + { + case PlcConflictAnswer.KeepLocal: + _syncService.EndWritePause(_session.Current, _session.IsValid); + return Result.Ok(false); + case PlcConflictAnswer.TakePlc: + return TakeLocked(offer.PlcRecipe); + case PlcConflictAnswer.Dismissed: + case PlcConflictAnswer.DialogShowFailed: + _syncSwitch.PostTurnOff(_state.TurnOffLocked( + new ConflictUnresolvedError(answer == PlcConflictAnswer.DialogShowFailed))); + return Result.Ok(false); + default: + throw new ArgumentOutOfRangeException(nameof(answer), answer, "Unnamed conflict answer"); + } + } + } + + /// The load notifies sync while the pause holds, so ending the pause next drops that recipe. + private Result TakeLocked(Recipe plcRecipe) + { + Result loadResult; + try + { + loadResult = _session.LoadAsCurrentValidated(plcRecipe); + } + catch (Exception ex) + { + _logger.LogError(ex, "Taking the PLC recipe threw"); + loadResult = Result.Fail(new ExceptionalError(ex)); + } + + if (loadResult.IsFailed) + { + _syncSwitch.PostTurnOff(_state.TurnOffLocked(new PlcRecipeNotLoadedError(loadResult.Errors))); + return Result.Fail(loadResult.Errors); + } + + _syncService.EndWritePauseWithoutWrite(); + return Result.Ok(true).WithReasons(loadResult.Reasons); + } +} diff --git a/SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs b/SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs new file mode 100644 index 00000000..4a251f2c --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs @@ -0,0 +1,218 @@ +using FluentResults; + +using SemiStep.Core.Plc.Sync; + +namespace SemiStep.Core.Plc; + +/// +/// The comparison bookkeeping under one lock: the sync-on flag and period, the current comparison ID, its offer and +/// the failures in a row. A member named *Locked expects the caller to hold . +/// +internal sealed class PlcComparisonState +{ + internal const int FailedComparisonLimit = 3; + + // Every field below is guarded by Gate. It is taken by the UI thread (sync switch, conflict answers, the + // reconnect take), the S7 connection callback, and the comparison task and posted turn-offs on the thread pool. + private bool _isSyncOn; + private long _syncPeriod; + private bool _isEnabling; + private bool _isConnectedDuringEnable; + private long _lastComparisonId; + private long _currentComparisonId; + private bool _isComparisonRunning; + private int _failedComparisonsInRow; + private PlcRecipeOffer? _offer; + private long _takeConvertedToConflictId; + + public Lock Gate { get; } = new(); + + /// Starts a sync-on period; runs under the same lock. + public void TurnOn(Action turnOnLocked) + { + lock (Gate) + { + _syncPeriod++; + _failedComparisonsInRow = 0; + InvalidateLocked(); + _isEnabling = true; + _isConnectedDuringEnable = false; + _isSyncOn = true; + turnOnLocked(); + } + } + + /// Ends the period and makes every comparison ID stale; runs under the same lock. + public void TurnOff(Action turnOffLocked) + { + lock (Gate) + { + InvalidateLocked(); + _isSyncOn = false; + _isEnabling = false; + _isConnectedDuringEnable = false; + turnOffLocked(); + } + } + + /// Returns whether the connect raised Connected, so the first comparison is due. + public bool EndEnabling() + { + lock (Gate) + { + var isComparisonDue = _isEnabling && _isConnectedDuringEnable; + _isEnabling = false; + _isConnectedDuringEnable = false; + + return isComparisonDue; + } + } + + /// + /// Null while sync is off. A Connected raised during the enable only marks the first comparison as due: it starts + /// after the version read. + /// + public long? TryBeginComparison(bool isFromConnectedEvent) + { + lock (Gate) + { + if (!_isSyncOn) + { + return null; + } + + if (isFromConnectedEvent && _isEnabling) + { + _isConnectedDuringEnable = true; + return null; + } + + _currentComparisonId = ++_lastComparisonId; + _isComparisonRunning = true; + _offer = null; + + return _currentComparisonId; + } + } + + /// + /// A comparison the drop cuts counts as failed here, whichever of the drop and its failed read comes first: the + /// read that passed the transport deadline also raises the drop, on another thread. + /// + public SyncTurnOff? LoseLink(Action pauseLocked) + { + lock (Gate) + { + if (!_isSyncOn) + { + return null; + } + + var isComparisonCut = _isComparisonRunning; + InvalidateLocked(); + pauseLocked(); + + return isComparisonCut ? CountFailureLocked() : null; + } + } + + /// Returns false for a stale failure, which neither closes the link nor counts. + public bool TryFail(long comparisonId, out SyncTurnOff? failureCapTurnOff) + { + lock (Gate) + { + failureCapTurnOff = null; + if (!IsCurrentLocked(comparisonId) || !_isComparisonRunning) + { + return false; + } + + InvalidateLocked(); + failureCapTurnOff = CountFailureLocked(); + return true; + } + } + + public bool TryDecideLocked(long comparisonId) + { + if (!IsCurrentLocked(comparisonId) || !_isComparisonRunning) + { + return false; + } + + _isComparisonRunning = false; + _failedComparisonsInRow = 0; + return true; + } + + public bool IsCurrentLocked(long comparisonId) + { + return comparisonId != 0 && comparisonId == _currentComparisonId; + } + + public void OfferLocked(PlcRecipeOffer offer) + { + _offer = offer; + } + + /// The screen changed before the reconnect take, so the same comparison offers a conflict instead. + public void ConvertTakeToConflictLocked(PlcRecipeOffer takeOffer) + { + _offer = takeOffer with { IsConflict = true }; + _takeConvertedToConflictId = takeOffer.ComparisonId; + } + + public bool WasTakeConvertedToConflict(long comparisonId) + { + lock (Gate) + { + return comparisonId != 0 && comparisonId == _takeConvertedToConflictId; + } + } + + /// An offer is taken once; a stale or mismatched request leaves it in place. + public PlcRecipeOffer? TakeOfferLocked(Func matches) + { + if (_offer is not { } offer || !IsCurrentLocked(offer.ComparisonId) || !matches(offer)) + { + return null; + } + + _offer = null; + return offer; + } + + public SyncTurnOff TurnOffLocked(IError reason) + { + return new SyncTurnOff(_syncPeriod, reason, IsFailureCap: false); + } + + /// + /// Checked when a posted turn-off runs: it is skipped when sync went off, a newer period started, or a later + /// comparison decided and reset the failures it counted. + /// + public bool IsDue(SyncTurnOff turnOff) + { + lock (Gate) + { + return _isSyncOn + && turnOff.SyncPeriod == _syncPeriod + && (!turnOff.IsFailureCap || _failedComparisonsInRow >= FailedComparisonLimit); + } + } + + private SyncTurnOff? CountFailureLocked() + { + _failedComparisonsInRow++; + return _failedComparisonsInRow >= FailedComparisonLimit + ? new SyncTurnOff(_syncPeriod, new ComparisonReadsFailedError(), IsFailureCap: true) + : null; + } + + private void InvalidateLocked() + { + _currentComparisonId = 0; + _isComparisonRunning = false; + _offer = null; + } +} diff --git a/SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs b/SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs new file mode 100644 index 00000000..ebda2f80 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs @@ -0,0 +1,10 @@ +namespace SemiStep.Core.Plc; + +/// The operator's answer to a recipe conflict, or the reason none came. +public enum PlcConflictAnswer +{ + KeepLocal, + TakePlc, + Dismissed, + DialogShowFailed +} diff --git a/SemiStep/SemiStep.Core/Plc/PlcConflictNotifier.cs b/SemiStep/SemiStep.Core/Plc/PlcConflictNotifier.cs new file mode 100644 index 00000000..472bf85f --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcConflictNotifier.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Logging; + +using SemiStep.Core.Plc.Sync; + +namespace SemiStep.Core.Plc; + +/// Raises a recipe conflict to the UI, and ends it as a dialog not shown when nobody can answer it. +internal sealed class PlcConflictNotifier(PlcComparisonState state, PlcSyncSwitch syncSwitch, ILogger logger) +{ + private readonly PlcComparisonState _state = state; + private readonly PlcSyncSwitch _syncSwitch = syncSwitch; + private readonly ILogger _logger = logger; + + public event Action? ConflictDetected; + + public bool HasSubscriber => ConflictDetected is not null; + + /// No subscriber, or one that throws, leaves the conflict without an answer, so sync turns off. + public void Raise(PlcRecipeConflict conflict) + { + try + { + if (ConflictDetected is not { } handler) + { + EndUnshownConflict(conflict.ComparisonId); + return; + } + + handler(conflict); + } + catch (Exception ex) + { + _logger.LogError(ex, "The PLC recipe conflict handler threw"); + EndUnshownConflict(conflict.ComparisonId); + } + } + + private void EndUnshownConflict(long comparisonId) + { + SyncTurnOff? turnOff = null; + lock (_state.Gate) + { + if (_state.TakeOfferLocked(offer => offer.IsConflict && offer.ComparisonId == comparisonId) is not null) + { + turnOff = _state.TurnOffLocked(new ConflictUnresolvedError(dialogShowFailed: true)); + } + } + + if (turnOff is { } dueTurnOff) + { + _syncSwitch.PostTurnOff(dueTurnOff); + } + } +} diff --git a/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs b/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs index f9832049..d08196da 100644 --- a/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs +++ b/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs @@ -3,60 +3,75 @@ using Microsoft.Extensions.Logging; using SemiStep.Core.Plc.Configuration; -using SemiStep.Core.Plc.S7.Protocol; using SemiStep.Core.Plc.S7.Serialization; using SemiStep.Core.Plc.State; -using SemiStep.Core.Plc.Sync; using SemiStep.Core.Plc.Sync.Ownership; using SemiStep.Core.Recipes; namespace SemiStep.Core.Plc; -public sealed class PlcLifecycleManager( - RecipeSession session, - IS7Connection connection, - IS7Reader reader, - IS7ExecutionStream executionStream, - IPlcSyncService syncService, - IPlcSyncOwnership syncOwnership, - RecipeMetadataRegistry recipeMetadataRegistry, - ILogger logger) : IDisposable +/// +/// The PLC facade the UI talks to. Sync on and off live in , the reconnect comparison in +/// , the answers to its offers in , and the +/// write pause they end in . +/// +public sealed class PlcLifecycleManager : IDisposable { - internal const string SyncEnableCancelledMessage = "PLC sync enable cancelled"; - - internal const string ReconciliationStartedMessage = - "PLC reconciliation started: the connection reported Connected while sync is enabled."; - - internal const string ReconciliationOutcomePrefix = "PLC reconciliation outcome "; - - /// - /// Used alone where no PLC-side fact was established. - /// - private const string ShortOutcomeTemplate = - ReconciliationOutcomePrefix + "{Outcome}: local {LocalStepCount} steps (valid {LocalValid})"; - - private const string LongOutcomeTemplate = - ShortOutcomeTemplate - + ", PLC {PlcStepCount} steps, committed {Committed}, conflict subscriber {HasConflictSubscriber}"; - - private static readonly TimeSpan _disableWriteWaitTimeout = TimeSpan.FromSeconds(5); - - private readonly IS7Connection _connection = connection; - private readonly IS7ExecutionStream _executionStream = executionStream; + internal const string SyncEnableCancelledMessage = PlcSyncSwitch.SyncEnableCancelledMessage; + internal const string ReconciliationStartedMessage = PlcReconnectComparison.StartedMessage; + internal const string ReconciliationOutcomePrefix = PlcReconciliationLog.OutcomePrefix; + internal const int FailedComparisonLimit = PlcComparisonState.FailedComparisonLimit; + + private readonly IS7Connection _connection; + private readonly IS7ExecutionStream _executionStream; + private readonly IPlcSyncService _syncService; + private readonly ILogger _logger; private readonly CancellationTokenSource _lifetimeCts = new(); - private readonly ILogger _logger = logger; - private readonly Lock _pendingLock = new(); - private readonly IS7Reader _reader = reader; - private readonly RecipeConverter _recipeConverter = new(recipeMetadataRegistry); - private readonly RecipeSession _session = session; - private readonly IPlcSyncOwnership _syncOwnership = syncOwnership; - private readonly IPlcSyncService _syncService = syncService; + private readonly PlcSyncSwitch _syncSwitch; + private readonly PlcConflictNotifier _conflictNotifier; + private readonly PlcReconnectTake _reconnectTake; + private readonly PlcReconnectComparison _comparison; + private readonly PlcComparisonAnswers _answers; private Action? _connectionStateHandler; - private bool _disposed; private bool _initialized; - private ISyncOwnershipLease? _ownershipLease; - private Recipe? _pendingPlcRecipe; - private Func>? _reconnectApplyCallback; + + // Written by Dispose (UI or teardown thread), read by the S7 connection callback; Interlocked. + private int _disposed; + + public PlcLifecycleManager( + RecipeSession session, + IS7Connection connection, + IS7Reader reader, + IS7ExecutionStream executionStream, + IPlcSyncService syncService, + IPlcSyncOwnership syncOwnership, + RecipeMetadataRegistry recipeMetadataRegistry, + ILogger logger) + { + _connection = connection; + _executionStream = executionStream; + _syncService = syncService; + _logger = logger; + + var lifetime = _lifetimeCts.Token; + var state = new PlcComparisonState(); + _syncSwitch = new PlcSyncSwitch(connection, reader, syncService, syncOwnership, state, logger, lifetime); + _conflictNotifier = new PlcConflictNotifier(state, _syncSwitch, logger); + _reconnectTake = new PlcReconnectTake(state, _syncSwitch, logger); + _comparison = new PlcReconnectComparison( + session, + connection, + reader, + syncService, + state, + _syncSwitch, + _conflictNotifier, + _reconnectTake, + new RecipeConverter(recipeMetadataRegistry), + logger, + lifetime); + _answers = new PlcComparisonAnswers(session, syncService, state, _syncSwitch, _conflictNotifier, logger); + } public bool IsSyncEnabled => _syncService.IsSyncEnabled; public bool IsConnected => _connection.IsConnected; @@ -70,7 +85,16 @@ public sealed class PlcLifecycleManager( public IObservable Faults => _syncService.Faults; - public event Action? PlcRecipeConflictDetected; + /// The reason of each turn-off the app makes by itself, emitted after sync is off. + public IObservable SyncTurnOffs => _syncSwitch.TurnOffs; + + public event Action? PlcRecipeConflictDetected + { + add => _conflictNotifier.ConflictDetected += value; + remove => _conflictNotifier.ConflictDetected -= value; + } + + private bool IsDisposed => Volatile.Read(ref _disposed) == 1; public void Initialize() { @@ -86,153 +110,49 @@ public void Initialize() public void Dispose() { - if (_disposed) + if (Interlocked.Exchange(ref _disposed, 1) == 1) { return; } - _disposed = true; - if (_connectionStateHandler is not null) { _connection.StateChanged -= _connectionStateHandler; } - try - { - _lifetimeCts.Cancel(); - } - catch (ObjectDisposedException) - { - } - + _lifetimeCts.Cancel(); _lifetimeCts.Dispose(); - ReleaseOwnershipLease(); + _syncSwitch.Dispose(); } public async Task EnableSync(PlcConfiguration config) { - if (_syncService.IsSyncEnabled) - { - return Result.Ok(); - } - - var ownershipResult = _syncOwnership.TryAcquire(config.Connection); - if (ownershipResult.IsFailed) - { - _logger.LogWarning( - "PLC sync ownership refused: {Errors}", - string.Join("; ", ownershipResult.Errors.Select(e => e.Message))); - return ownershipResult.ToResult(); - } - - _ownershipLease = ownershipResult.Value; - - var lifeToken = _lifetimeCts.Token; - - try - { - _syncService.SetSyncEnabled(true); - await _connection.ConnectAsync(config.Connection); - - var versionResult = await ValidateProtocolVersionAsync(lifeToken); - if (versionResult.IsFailed) - { - await FailProtocolVersionHandshakeAsync(); - return versionResult; - } - - return Result.Ok(); - } - catch (OperationCanceledException) when (lifeToken.IsCancellationRequested) - { - RollbackSyncEnable(); - return Result.Fail(SyncEnableCancelledMessage); - } - catch (Exception ex) + var (result, isComparisonDue) = await _syncSwitch.EnableAsync(config); + if (isComparisonDue) { - RollbackSyncEnable(); - _logger.LogWarning("Enabling PLC sync failed: {Message}", ex.Message); - return Result.Fail(ex.Message); + _comparison.Start(isFirstConnect: true); } - } - private async Task ValidateProtocolVersionAsync(CancellationToken ct) - { - var versionResult = await _reader.ReadProtocolVersionAsync(ct); - return versionResult.IsFailed - ? versionResult.ToResult() - : versionResult.Value != ProtocolConstants.ProtocolVersion - ? Result.Fail( - new ProtocolVersionMismatchError(ProtocolConstants.ProtocolVersion, versionResult.Value)) - : Result.Ok(); - } - - private async Task FailProtocolVersionHandshakeAsync() - { - RollbackSyncEnable(); - await _connection.DisconnectAsync(); - } - - private void RollbackSyncEnable() - { - _syncService.SetSyncEnabled(false); - ReleaseOwnershipLease(); + return result; } /// /// The lease is released last: until the write in flight and the session end, another instance must not write. + /// A call while sync is already off does nothing. /// - public async Task DisableSync() + public Task DisableSync() { - _syncService.SetSyncEnabled(false); - _syncService.ResetForDisable(); - await WaitForWriteInFlightAsync(); - - try - { - await _connection.DisconnectAsync(); - } - catch (Exception ex) - { - _logger.LogWarning("Error while disconnecting from PLC: {Message}", ex.Message); - } - finally - { - ReleaseOwnershipLease(); - } - } - - private async Task WaitForWriteInFlightAsync() - { - using var timeout = new CancellationTokenSource(_disableWriteWaitTimeout); - try - { - await _syncService.WaitForPendingSyncAsync(timeout.Token); - } - catch (OperationCanceledException) when (timeout.IsCancellationRequested) - { - _logger.LogWarning( - "Sync attempt did not finish within {Timeout}; disconnecting from PLC anyway", - _disableWriteWaitTimeout); - } + return _syncSwitch.DisableAsync(); } - private void ReleaseOwnershipLease() - { - var lease = _ownershipLease; - if (lease is null) - { - return; - } - - _ownershipLease = null; - lease.Dispose(); - } - - public Result ApplyRecipeFromPlc(Recipe recipe) + /// + /// Takes the PLC recipe the current comparison offered on reconnect. Returns whether the session recipe was + /// replaced: false for a stale offer, or for a screen that gained steps or unsaved changes, which gets the + /// conflict instead. + /// + public Result ApplyRecipeFromPlc(Recipe recipe) { - return _session.LoadAsCurrentValidated(recipe); + return _answers.ApplyRecipeFromPlc(recipe); } /// @@ -243,59 +163,29 @@ public Result ApplyRecipeFromPlc(Recipe recipe) /// public void RegisterReconnectApplyCallback(Func> callback) { - ArgumentNullException.ThrowIfNull(callback); - - if (_reconnectApplyCallback is not null) - { - throw new InvalidOperationException( - "Reconnect apply callback has already been registered."); - } - - _reconnectApplyCallback = callback; + _reconnectTake.RegisterApplyCallback(callback); } - public Result ResolveConflict(bool keepLocal) + /// + /// Ends the conflict of . Returns whether the session recipe was replaced; an + /// answer to a stale conflict changes nothing. + /// + public Result ResolveConflict(long comparisonId, PlcConflictAnswer answer) { - if (keepLocal) - { - lock (_pendingLock) - { - _pendingPlcRecipe = null; - } - - _syncService.NotifyRecipeChanged(_session.Current, _session.IsValid); - - return Result.Ok(); - } - - Recipe? pending; - lock (_pendingLock) - { - pending = _pendingPlcRecipe; - _pendingPlcRecipe = null; - } - - if (pending is null) - { - _logger.LogWarning("ResolveConflict called with keepLocal=false but no pending PLC recipe exists."); - - return Result.Fail("No pending PLC recipe to resolve."); - } - - return ApplyRecipeFromPlc(pending); + return _answers.ResolveConflict(comparisonId, answer); } private void OnConnectionStateChanged(PlcConnectionState state) { _syncService.UpdateConnectionState(state); - if (state == PlcConnectionState.Disconnected && _syncService.IsSyncEnabled) + if (state == PlcConnectionState.Disconnected) { - _syncService.HandleConnectionLost(); + _comparison.OnLinkLost(); } else if (state == PlcConnectionState.Connected && _syncService.IsSyncEnabled) { - if (_disposed) + if (IsDisposed) { _logger.LogWarning( "PLC reconciliation dropped: the lifecycle manager was disposed while the connection " @@ -303,252 +193,7 @@ private void OnConnectionStateChanged(PlcConnectionState state) return; } - _logger.LogInformation(ReconciliationStartedMessage); - - var token = _lifetimeCts.Token; - _ = PerformReconnectReconciliationAsync(token).ContinueWith( - t => _logger.LogError(t.Exception, "Unhandled error in reconnect reconciliation"), - TaskContinuationOptions.OnlyOnFaulted); + _comparison.Start(isFirstConnect: false); } } - - private async Task PerformReconnectReconciliationAsync(CancellationToken cancellationToken) - { - try - { - LogOutcome(await RunReconciliationAsync(cancellationToken)); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - LogOutcome(BuildResultFromSession(PlcReconciliationOutcome.Cancelled)); - } - catch (OperationCanceledException ex) - { - // Unfiltered: a filter mirroring the one above would leave the exception uncaught when - // Dispose cancels the lifetime token between the two filter evaluations, and the run - // would end with a begin line and no outcome line. - LogOutcome(BuildResultFromSession(PlcReconciliationOutcome.TimedOut), ex); - } - } - - private async Task RunReconciliationAsync(CancellationToken cancellationToken) - { - var versionResult = await ValidateProtocolVersionAsync(cancellationToken); - if (versionResult.IsFailed) - { - _logger.LogWarning( - "Aborting reconnect reconciliation: protocol version validation failed: {Errors}", - string.Join("; ", versionResult.Errors.Select(e => e.Message))); - await FailProtocolVersionHandshakeAsync(); - - return BuildResultFromSession(versionResult.HasError() - ? PlcReconciliationOutcome.ProtocolVersionMismatch - : PlcReconciliationOutcome.ProtocolVersionCheckFailed); - } - - var managingAreaResult = await _reader.ReadManagingAreaAsync(cancellationToken); - - if (managingAreaResult.IsFailed) - { - _logger.LogWarning( - "Could not read managing area during reconnect reconciliation: {Errors}", - string.Join("; ", managingAreaResult.Errors.Select(e => e.Message))); - var (pushedRecipe, pushedValid) = NotifyLocalRecipe(); - return BuildResult(PlcReconciliationOutcome.ManagingAreaReadFailed, pushedRecipe, pushedValid, null, null); - } - - var committed = managingAreaResult.Value.Committed; - - if (!committed) - { - var (pushedRecipe, pushedValid) = NotifyLocalRecipe(); - return BuildResult(PlcReconciliationOutcome.NotCommitted, pushedRecipe, pushedValid, null, committed); - } - - return await CompareWithPlcRecipeAsync(committed, cancellationToken); - } - - private async Task CompareWithPlcRecipeAsync( - bool committed, - CancellationToken cancellationToken) - { - var plcRecipeResult = await _reader.ReadRecipeFromPlcAsync(cancellationToken); - - if (plcRecipeResult.IsFailed) - { - _logger.LogWarning( - "Could not read PLC recipe during reconciliation: {Errors}", - string.Join("; ", plcRecipeResult.Errors.Select(e => e.Message))); - var (pushedRecipe, pushedValid) = NotifyLocalRecipe(); - return BuildResult(PlcReconciliationOutcome.RecipeReadFailed, pushedRecipe, pushedValid, null, committed); - } - - var plcRecipe = plcRecipeResult.Value; - - // Both fields are read before the decision, and the pair is still not atomic: a UI-thread - // mutation between the two reads pairs the step count of one recipe with the validity of another. - var localRecipe = _session.Current; - var localValid = _session.IsValid; - - return await ResolveRecipeDifferenceAsync(localRecipe, localValid, plcRecipe, committed); - } - - private async Task ResolveRecipeDifferenceAsync( - Recipe localRecipe, - bool localValid, - Recipe plcRecipe, - bool committed) - { - var plcStepCount = plcRecipe.Steps.Count; - - if (localRecipe.Steps.Count == 0 && plcStepCount > 0) - { - var applied = await ApplyReconnectPlcRecipeAsync(plcRecipe); - - // The snapshot, not the session: a successful apply has already replaced the session recipe - // with the PLC one, and logging that would report the PLC recipe as the local side. - return BuildResult( - applied ? PlcReconciliationOutcome.AppliedFromPlc : PlcReconciliationOutcome.ApplyFromPlcFailed, - localRecipe, - localValid, - plcStepCount, - committed); - } - - if (plcStepCount > 0 && !PlcRecipeDataComparer.EncodesToSamePlcData(_recipeConverter, localRecipe, plcRecipe, _logger)) - { - lock (_pendingLock) - { - _pendingPlcRecipe = plcRecipe; - } - - PlcRecipeConflictDetected?.Invoke(localRecipe, plcRecipe); - - return BuildResult( - PlcReconciliationOutcome.ConflictRaised, localRecipe, localValid, plcStepCount, committed); - } - - var (pushedRecipe, pushedValid) = NotifyLocalRecipe(); - - return BuildResult( - plcStepCount == 0 ? PlcReconciliationOutcome.PlcEmpty : PlcReconciliationOutcome.Identical, - pushedRecipe, - pushedValid, - plcStepCount, - committed); - } - - private PlcReconciliationResult BuildResultFromSession(PlcReconciliationOutcome outcome) - { - return BuildResult(outcome, _session.Current, _session.IsValid, null, null); - } - - private PlcReconciliationResult BuildResult( - PlcReconciliationOutcome outcome, - Recipe localRecipe, - bool localValid, - int? plcStepCount, - bool? committed) - { - return new PlcReconciliationResult( - outcome, - localRecipe.Steps.Count, - localValid, - plcStepCount, - committed, - PlcRecipeConflictDetected is not null); - } - - private void LogOutcome(PlcReconciliationResult result, Exception? exception = null) - { - var level = ResolveOutcomeLevel(result.Outcome); - - if (result.PlcStepCount is null && result.Committed is null) - { - _logger.Log( - level, - exception, - ShortOutcomeTemplate, - result.Outcome, - result.LocalStepCount, - result.LocalValid); - return; - } - - _logger.Log( - level, - exception, - LongOutcomeTemplate, - result.Outcome, - result.LocalStepCount, - result.LocalValid, - result.PlcStepCount, - result.Committed, - result.HasConflictSubscriber); - } - - private static LogLevel ResolveOutcomeLevel(PlcReconciliationOutcome outcome) - { - return outcome switch - { - PlcReconciliationOutcome.AppliedFromPlc => LogLevel.Information, - PlcReconciliationOutcome.ConflictRaised => LogLevel.Information, - PlcReconciliationOutcome.PlcEmpty => LogLevel.Information, - PlcReconciliationOutcome.Identical => LogLevel.Information, - PlcReconciliationOutcome.Cancelled => LogLevel.Information, - PlcReconciliationOutcome.ProtocolVersionMismatch => LogLevel.Warning, - PlcReconciliationOutcome.ProtocolVersionCheckFailed => LogLevel.Warning, - PlcReconciliationOutcome.ManagingAreaReadFailed => LogLevel.Warning, - PlcReconciliationOutcome.NotCommitted => LogLevel.Warning, - PlcReconciliationOutcome.RecipeReadFailed => LogLevel.Warning, - PlcReconciliationOutcome.ApplyFromPlcFailed => LogLevel.Warning, - PlcReconciliationOutcome.TimedOut => LogLevel.Warning, - _ => throw new ArgumentOutOfRangeException(nameof(outcome), outcome, "Unnamed reconciliation outcome") - }; - } - - private async Task ApplyReconnectPlcRecipeAsync(Recipe plcRecipe) - { - var callback = _reconnectApplyCallback; - if (callback is null) - { - _logger.LogWarning( - "Reconnect reconciliation discarded PLC recipe: no apply callback registered."); - return false; - } - - Result applyResult; - try - { - applyResult = await callback(plcRecipe); - } - catch (Exception ex) - { - _logger.LogError(ex, "Reconnect apply callback threw"); - return false; - } - - if (applyResult.IsFailed) - { - _logger.LogWarning( - "PLC recipe analysis errors during reconnect: {Errors}", - string.Join("; ", applyResult.Errors.Select(e => e.Message))); - return false; - } - - return true; - } - - /// - /// The UI thread can replace the session recipe at any moment, so a caller that read the session - /// again to log what it pushed would name a different recipe than the one the executor received. - /// - private (Recipe Recipe, bool Valid) NotifyLocalRecipe() - { - var localRecipe = _session.Current; - var localValid = _session.IsValid; - _syncService.NotifyRecipeChanged(localRecipe, localValid); - - return (localRecipe, localValid); - } } diff --git a/SemiStep/SemiStep.Core/Plc/PlcRecipeConflict.cs b/SemiStep/SemiStep.Core/Plc/PlcRecipeConflict.cs new file mode 100644 index 00000000..540ba66f --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcRecipeConflict.cs @@ -0,0 +1,6 @@ +using SemiStep.Core.Recipes; + +namespace SemiStep.Core.Plc; + +/// A comparison found a different PLC recipe; an answer counts only while its comparison is current. +public sealed record PlcRecipeConflict(long ComparisonId, Recipe Local, Recipe Plc); diff --git a/SemiStep/SemiStep.Core/Plc/PlcRecipeOffer.cs b/SemiStep/SemiStep.Core/Plc/PlcRecipeOffer.cs new file mode 100644 index 00000000..22507437 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcRecipeOffer.cs @@ -0,0 +1,6 @@ +using SemiStep.Core.Recipes; + +namespace SemiStep.Core.Plc; + +/// The PLC recipe a comparison offered: to a conflict answer, or to the reconnect take. +internal readonly record struct PlcRecipeOffer(long ComparisonId, Recipe PlcRecipe, bool IsConflict); diff --git a/SemiStep/SemiStep.Core/Plc/PlcReconciliationLog.cs b/SemiStep/SemiStep.Core/Plc/PlcReconciliationLog.cs new file mode 100644 index 00000000..f2ee0e02 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcReconciliationLog.cs @@ -0,0 +1,90 @@ +using Microsoft.Extensions.Logging; + +using SemiStep.Core.Recipes; + +namespace SemiStep.Core.Plc; + +/// Writes the one outcome line every reconciliation ends with, at the level its outcome deserves. +internal sealed class PlcReconciliationLog(ILogger logger) +{ + internal const string OutcomePrefix = "PLC reconciliation outcome "; + + /// + /// Used alone where no PLC-side fact was established. + /// + private const string ShortOutcomeTemplate = + OutcomePrefix + "{Outcome}: local {LocalStepCount} steps (valid {LocalValid})"; + + private const string LongOutcomeTemplate = + ShortOutcomeTemplate + + ", PLC {PlcStepCount} steps, committed {Committed}, conflict subscriber {HasConflictSubscriber}"; + + private readonly ILogger _logger = logger; + + public static PlcReconciliationResult BuildResult( + PlcReconciliationOutcome outcome, + Recipe localRecipe, + bool localValid, + int? plcStepCount, + bool? committed, + bool hasConflictSubscriber) + { + return new PlcReconciliationResult( + outcome, + localRecipe.Steps.Count, + localValid, + plcStepCount, + committed, + hasConflictSubscriber); + } + + public void Log(PlcReconciliationResult result, Exception? exception = null) + { + var level = ResolveOutcomeLevel(result.Outcome); + + if (result.PlcStepCount is null && result.Committed is null) + { + _logger.Log( + level, + exception, + ShortOutcomeTemplate, + result.Outcome, + result.LocalStepCount, + result.LocalValid); + return; + } + + _logger.Log( + level, + exception, + LongOutcomeTemplate, + result.Outcome, + result.LocalStepCount, + result.LocalValid, + result.PlcStepCount, + result.Committed, + result.HasConflictSubscriber); + } + + private static LogLevel ResolveOutcomeLevel(PlcReconciliationOutcome outcome) + { + return outcome switch + { + PlcReconciliationOutcome.AppliedFromPlc => LogLevel.Information, + PlcReconciliationOutcome.ConflictRaised => LogLevel.Information, + PlcReconciliationOutcome.PlcEmpty => LogLevel.Information, + PlcReconciliationOutcome.Identical => LogLevel.Information, + PlcReconciliationOutcome.Stale => LogLevel.Information, + PlcReconciliationOutcome.Cancelled => LogLevel.Information, + PlcReconciliationOutcome.ProtocolVersionMismatch => LogLevel.Warning, + PlcReconciliationOutcome.ProtocolVersionCheckFailed => LogLevel.Warning, + PlcReconciliationOutcome.ManagingAreaReadFailed => LogLevel.Warning, + PlcReconciliationOutcome.NotCommitted => LogLevel.Warning, + PlcReconciliationOutcome.RecipeReadFailed => LogLevel.Warning, + PlcReconciliationOutcome.ApplyFromPlcFailed => LogLevel.Warning, + PlcReconciliationOutcome.TimedOut => LogLevel.Warning, + PlcReconciliationOutcome.Faulted => LogLevel.Warning, + _ => throw new ArgumentOutOfRangeException(nameof(outcome), outcome, "Unnamed reconciliation outcome") + }; + } +} diff --git a/SemiStep/SemiStep.Core/Plc/PlcReconciliationOutcome.cs b/SemiStep/SemiStep.Core/Plc/PlcReconciliationOutcome.cs index e7bef3d5..3e914e5e 100644 --- a/SemiStep/SemiStep.Core/Plc/PlcReconciliationOutcome.cs +++ b/SemiStep/SemiStep.Core/Plc/PlcReconciliationOutcome.cs @@ -1,8 +1,7 @@ namespace SemiStep.Core.Plc; /// -/// Every reconciliation produces exactly one of these, including the two paths that unwind through -/// an . +/// Every reconciliation produces exactly one of these, including the paths that unwind through an exception. /// internal enum PlcReconciliationOutcome { @@ -17,5 +16,7 @@ internal enum PlcReconciliationOutcome PlcEmpty, Identical, TimedOut, + Faulted, + Stale, Cancelled } diff --git a/SemiStep/SemiStep.Core/Plc/PlcReconnectComparison.cs b/SemiStep/SemiStep.Core/Plc/PlcReconnectComparison.cs new file mode 100644 index 00000000..14d4e6f7 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcReconnectComparison.cs @@ -0,0 +1,323 @@ +using FluentResults; + +using Microsoft.Extensions.Logging; + +using SemiStep.Core.Plc.S7.Protocol; +using SemiStep.Core.Plc.S7.Serialization; +using SemiStep.Core.Plc.Sync; +using SemiStep.Core.Recipes; + +namespace SemiStep.Core.Plc; + +/// +/// The reconnect comparison: reads the PLC recipe, compares it with the screen recipe, and ends or keeps the write +/// pause by the outcome. Every exit, exceptions included, ends in one of: write, no write, keep, sync off. +/// +internal sealed class PlcReconnectComparison( + RecipeSession session, + IS7Connection connection, + IS7Reader reader, + IPlcSyncService syncService, + PlcComparisonState state, + PlcSyncSwitch syncSwitch, + PlcConflictNotifier conflictNotifier, + PlcReconnectTake reconnectTake, + RecipeConverter recipeConverter, + ILogger logger, + CancellationToken lifetime) +{ + internal const string StartedMessage = + "PLC reconciliation started: the connection reported Connected while sync is enabled."; + + private readonly RecipeSession _session = session; + private readonly IS7Connection _connection = connection; + private readonly IS7Reader _reader = reader; + private readonly IPlcSyncService _syncService = syncService; + private readonly PlcComparisonState _state = state; + private readonly PlcSyncSwitch _syncSwitch = syncSwitch; + private readonly PlcConflictNotifier _conflictNotifier = conflictNotifier; + private readonly PlcReconnectTake _reconnectTake = reconnectTake; + private readonly RecipeConverter _recipeConverter = recipeConverter; + private readonly ILogger _logger = logger; + private readonly PlcReconciliationLog _reconciliationLog = new(logger); + private readonly CancellationToken _lifetime = lifetime; + + /// The first comparison of a sync-on period reuses the version read of the enable. + public void Start(bool isFirstConnect) + { + if (_state.TryBeginComparison(isFromConnectedEvent: !isFirstConnect) is not { } comparisonId) + { + return; + } + + _logger.LogInformation(StartedMessage); + _ = RunAsync(comparisonId, isFirstConnect).ContinueWith( + t => _logger.LogError(t.Exception, "Unhandled error in reconnect reconciliation"), + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted, + TaskScheduler.Default); + } + + public void OnLinkLost() + { + if (_state.LoseLink(_syncService.HandleConnectionLost) is { } failureCapTurnOff) + { + _syncSwitch.PostTurnOff(failureCapTurnOff); + } + } + + private async Task RunAsync(long comparisonId, bool isFirstConnect) + { + try + { + _reconciliationLog.Log(await CompareAsync(comparisonId, isFirstConnect)); + } + catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) + { + _reconciliationLog.Log(BuildResult(PlcReconciliationOutcome.Cancelled)); + } + catch (OperationCanceledException ex) + { + // Unfiltered: a filter mirroring the one above would leave the exception uncaught when + // Dispose cancels the lifetime token between the two filter evaluations, and the run + // would end with a begin line and no outcome line. + _reconciliationLog.Log(Fail(comparisonId, PlcReconciliationOutcome.TimedOut), ex); + } + catch (Exception ex) + { + _reconciliationLog.Log(Fail(comparisonId, PlcReconciliationOutcome.Faulted), ex); + } + } + + private async Task CompareAsync(long comparisonId, bool isFirstConnect) + { + if (!isFirstConnect) + { + var versionResult = await _reader.ReadProtocolVersionAsync(_lifetime); + if (versionResult.IsFailed) + { + LogReadFailure("protocol version", versionResult); + return Fail(comparisonId, PlcReconciliationOutcome.ProtocolVersionCheckFailed); + } + + if (versionResult.Value != ProtocolConstants.ProtocolVersion) + { + return TurnOffOnVersionMismatch(comparisonId, versionResult.Value); + } + } + + var managingAreaResult = await _reader.ReadManagingAreaAsync(_lifetime); + if (managingAreaResult.IsFailed) + { + LogReadFailure("managing area", managingAreaResult); + return Fail(comparisonId, PlcReconciliationOutcome.ManagingAreaReadFailed); + } + + var committed = managingAreaResult.Value.Committed; + if (!committed) + { + return EndPauseWithWrite(comparisonId, PlcReconciliationOutcome.NotCommitted, null, committed); + } + + var plcRecipeResult = await _reader.ReadRecipeFromPlcAsync(_lifetime); + if (plcRecipeResult.IsFailed) + { + LogReadFailure("PLC recipe", plcRecipeResult); + return Fail(comparisonId, PlcReconciliationOutcome.RecipeReadFailed, committed); + } + + return await ResolveDifferenceAsync(comparisonId, plcRecipeResult.Value, committed); + } + + private async Task ResolveDifferenceAsync( + long comparisonId, + Recipe plcRecipe, + bool committed) + { + // Both fields are read before the decision, and the pair is still not atomic: a UI-thread + // mutation between the two reads pairs the step count of one recipe with the validity of another. + var localRecipe = _session.Current; + var localValid = _session.IsValid; + var plcStepCount = plcRecipe.Steps.Count; + + if (localRecipe.Steps.Count == 0 && plcStepCount > 0) + { + return await TakeOnReconnectAsync(comparisonId, localRecipe, localValid, plcRecipe, committed); + } + + if (plcStepCount > 0 + && !PlcRecipeDataComparer.EncodesToSamePlcData(_recipeConverter, localRecipe, plcRecipe, _logger)) + { + return RaiseConflictOnce(comparisonId, localRecipe, localValid, plcRecipe, committed); + } + + return EndPauseWithWrite( + comparisonId, + plcStepCount == 0 ? PlcReconciliationOutcome.PlcEmpty : PlcReconciliationOutcome.Identical, + plcStepCount, + committed); + } + + /// + /// The UI thread can replace the session recipe at any moment, so the result names the recipe handed to the + /// sync service, read under the same lock that ends the pause. + /// + private PlcReconciliationResult EndPauseWithWrite( + long comparisonId, + PlcReconciliationOutcome outcome, + int? plcStepCount, + bool committed) + { + lock (_state.Gate) + { + if (!_state.TryDecideLocked(comparisonId)) + { + return BuildResult(PlcReconciliationOutcome.Stale, plcStepCount, committed); + } + + var localRecipe = _session.Current; + var localValid = _session.IsValid; + _syncService.EndWritePause(localRecipe, localValid); + + return BuildResult(outcome, localRecipe, localValid, plcStepCount, committed); + } + } + + private PlcReconciliationResult RaiseConflictOnce( + long comparisonId, + Recipe localRecipe, + bool localValid, + Recipe plcRecipe, + bool committed) + { + var plcStepCount = plcRecipe.Steps.Count; + lock (_state.Gate) + { + if (!_state.TryDecideLocked(comparisonId)) + { + return BuildResult(PlcReconciliationOutcome.Stale, plcStepCount, committed); + } + + _state.OfferLocked(new PlcRecipeOffer(comparisonId, plcRecipe, IsConflict: true)); + } + + _conflictNotifier.Raise(new PlcRecipeConflict(comparisonId, localRecipe, plcRecipe)); + + return BuildResult(PlcReconciliationOutcome.ConflictRaised, localRecipe, localValid, plcStepCount, committed); + } + + private async Task TakeOnReconnectAsync( + long comparisonId, + Recipe localRecipe, + bool localValid, + Recipe plcRecipe, + bool committed) + { + var plcStepCount = plcRecipe.Steps.Count; + lock (_state.Gate) + { + if (!_state.TryDecideLocked(comparisonId)) + { + return BuildResult(PlcReconciliationOutcome.Stale, plcStepCount, committed); + } + + _state.OfferLocked(new PlcRecipeOffer(comparisonId, plcRecipe, IsConflict: false)); + } + + var applyResult = await _reconnectTake.RunAsync(comparisonId, plcRecipe); + + // The snapshot, not the session: a successful apply has already replaced the session recipe + // with the PLC one, and logging that would report the PLC recipe as the local side. + var outcome = _state.WasTakeConvertedToConflict(comparisonId) + ? PlcReconciliationOutcome.ConflictRaised + : applyResult.IsSuccess + ? PlcReconciliationOutcome.AppliedFromPlc + : PlcReconciliationOutcome.ApplyFromPlcFailed; + + return BuildResult( + outcome, + localRecipe, + localValid, + plcStepCount, + committed); + } + + /// The reconnect loop must not wait on the disconnect, so the turn-off is posted. + private PlcReconciliationResult TurnOffOnVersionMismatch(long comparisonId, int actualVersion) + { + _logger.LogWarning( + "Aborting reconnect reconciliation: the PLC reports protocol version {Actual}, expected {Expected}", + actualVersion, + ProtocolConstants.ProtocolVersion); + + SyncTurnOff turnOff; + lock (_state.Gate) + { + if (!_state.TryDecideLocked(comparisonId)) + { + return BuildResult(PlcReconciliationOutcome.Stale); + } + + turnOff = _state.TurnOffLocked( + new ProtocolVersionMismatchError(ProtocolConstants.ProtocolVersion, actualVersion)); + } + + _syncSwitch.PostTurnOff(turnOff); + return BuildResult(PlcReconciliationOutcome.ProtocolVersionMismatch); + } + + /// + /// The pause holds. A current failure declares link loss, so the reconnect loop compares again; the last one + /// allowed turns sync off instead. + /// + private PlcReconciliationResult Fail(long comparisonId, PlcReconciliationOutcome outcome, bool? committed = null) + { + if (!_state.TryFail(comparisonId, out var failureCapTurnOff)) + { + return BuildResult(PlcReconciliationOutcome.Stale, null, committed); + } + + if (failureCapTurnOff is { } turnOff) + { + _syncSwitch.PostTurnOff(turnOff); + } + else + { + _connection.DeclareLinkLost(); + } + + return BuildResult(outcome, null, committed); + } + + private void LogReadFailure(string subject, IResultBase result) + { + _logger.LogWarning( + "Could not read the {Subject} during reconnect reconciliation: {Errors}", + subject, + string.Join("; ", result.Errors.Select(e => e.Message))); + } + + private PlcReconciliationResult BuildResult( + PlcReconciliationOutcome outcome, + int? plcStepCount = null, + bool? committed = null) + { + return BuildResult(outcome, _session.Current, _session.IsValid, plcStepCount, committed); + } + + private PlcReconciliationResult BuildResult( + PlcReconciliationOutcome outcome, + Recipe localRecipe, + bool localValid, + int? plcStepCount, + bool? committed) + { + return PlcReconciliationLog.BuildResult( + outcome, + localRecipe, + localValid, + plcStepCount, + committed, + _conflictNotifier.HasSubscriber); + } +} diff --git a/SemiStep/SemiStep.Core/Plc/PlcReconnectTake.cs b/SemiStep/SemiStep.Core/Plc/PlcReconnectTake.cs new file mode 100644 index 00000000..09b6d23c --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcReconnectTake.cs @@ -0,0 +1,88 @@ +using FluentResults; + +using Microsoft.Extensions.Logging; + +using SemiStep.Core.Plc.Sync; +using SemiStep.Core.Recipes; + +namespace SemiStep.Core.Plc; + +/// +/// Hands the offered PLC recipe to the UI callback, which takes it through +/// . A take offer still in place afterwards was never taken, and +/// nothing else would end the pause, so sync turns off. +/// +internal sealed class PlcReconnectTake(PlcComparisonState state, PlcSyncSwitch syncSwitch, ILogger logger) +{ + private readonly PlcComparisonState _state = state; + private readonly PlcSyncSwitch _syncSwitch = syncSwitch; + private readonly ILogger _logger = logger; + private Func>? _applyCallback; + + public void RegisterApplyCallback(Func> callback) + { + ArgumentNullException.ThrowIfNull(callback); + + if (_applyCallback is not null) + { + throw new InvalidOperationException("Reconnect apply callback has already been registered."); + } + + _applyCallback = callback; + } + + public async Task RunAsync(long comparisonId, Recipe plcRecipe) + { + var applyResult = await ApplyAsync(plcRecipe); + EndUntakenOffer(comparisonId, applyResult); + + return applyResult; + } + + private async Task ApplyAsync(Recipe plcRecipe) + { + if (_applyCallback is not { } callback) + { + _logger.LogWarning("Reconnect reconciliation discarded PLC recipe: no apply callback registered."); + return Result.Fail("No reconnect apply callback is registered"); + } + + Result applyResult; + try + { + applyResult = await callback(plcRecipe); + } + catch (Exception ex) + { + _logger.LogError(ex, "Reconnect apply callback threw"); + return Result.Fail(new ExceptionalError(ex)); + } + + if (applyResult.IsFailed) + { + _logger.LogWarning( + "PLC recipe analysis errors during reconnect: {Errors}", + string.Join("; ", applyResult.Errors.Select(e => e.Message))); + } + + return applyResult; + } + + private void EndUntakenOffer(long comparisonId, Result applyResult) + { + SyncTurnOff? turnOff = null; + lock (_state.Gate) + { + if (_state.TakeOfferLocked(offer => !offer.IsConflict && offer.ComparisonId == comparisonId) is not null) + { + var causes = applyResult.IsFailed ? applyResult.Errors : [new Error("The PLC recipe was not taken")]; + turnOff = _state.TurnOffLocked(new PlcRecipeNotLoadedError(causes)); + } + } + + if (turnOff is { } dueTurnOff) + { + _syncSwitch.PostTurnOff(dueTurnOff); + } + } +} diff --git a/SemiStep/SemiStep.Core/Plc/PlcSyncSwitch.cs b/SemiStep/SemiStep.Core/Plc/PlcSyncSwitch.cs new file mode 100644 index 00000000..e25a9f35 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcSyncSwitch.cs @@ -0,0 +1,248 @@ +using System.Reactive.Linq; +using System.Reactive.Subjects; + +using FluentResults; + +using Microsoft.Extensions.Logging; + +using SemiStep.Core.Plc.Configuration; +using SemiStep.Core.Plc.S7.Protocol; +using SemiStep.Core.Plc.Sync.Ownership; + +namespace SemiStep.Core.Plc; + +/// +/// Turns sync on and off one at a time behind one gate, the turn-offs the app posts included, and owns the sync +/// ownership lease and the version handshake of sync on. +/// +internal sealed class PlcSyncSwitch( + IS7Connection connection, + IS7Reader reader, + IPlcSyncService syncService, + IPlcSyncOwnership syncOwnership, + PlcComparisonState state, + ILogger logger, + CancellationToken lifetime) : IDisposable +{ + internal const string SyncEnableCancelledMessage = "PLC sync enable cancelled"; + + private static readonly TimeSpan _disableWriteWaitTimeout = TimeSpan.FromSeconds(5); + + private readonly IS7Connection _connection = connection; + private readonly IS7Reader _reader = reader; + private readonly IPlcSyncService _syncService = syncService; + private readonly IPlcSyncOwnership _syncOwnership = syncOwnership; + private readonly PlcComparisonState _state = state; + private readonly ILogger _logger = logger; + private readonly CancellationToken _lifetime = lifetime; + private readonly SemaphoreSlim _gate = new(1, 1); + + // Emitted under the comparison state lock, which serializes the posted turn-offs of several pool threads. + private readonly Subject _turnOffs = new(); + + // Written by Dispose (UI or teardown thread), read by the posted turn-offs on the thread pool; Interlocked. + private int _disposed; + private ISyncOwnershipLease? _ownershipLease; + + /// The reason of each turn-off the app makes by itself, emitted after the turn-off ends. + public IObservable TurnOffs => _turnOffs.AsObservable(); + + private bool IsDisposed => Volatile.Read(ref _disposed) == 1; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) + { + return; + } + + ReleaseOwnershipLease(); + lock (_state.Gate) + { + _turnOffs.OnCompleted(); + _turnOffs.Dispose(); + } + } + + /// Returns whether the connect raised Connected, so the first comparison is due. + public async Task<(Result Result, bool IsComparisonDue)> EnableAsync(PlcConfiguration config) + { + await _gate.WaitAsync(); + try + { + if (_syncService.IsSyncEnabled) + { + return (Result.Ok(), false); + } + + var ownershipResult = _syncOwnership.TryAcquire(config.Connection); + if (ownershipResult.IsFailed) + { + _logger.LogWarning( + "PLC sync ownership refused: {Errors}", + string.Join("; ", ownershipResult.Errors.Select(e => e.Message))); + return (ownershipResult.ToResult(), false); + } + + Volatile.Write(ref _ownershipLease, ownershipResult.Value); + var result = await TurnOnAsync(config); + var isComparisonDue = _state.EndEnabling(); + + return (result, result.IsSuccess && isComparisonDue); + } + finally + { + _gate.Release(); + } + } + + /// A call while sync is already off does nothing. + public async Task DisableAsync() + { + await _gate.WaitAsync(); + try + { + if (_syncService.IsSyncEnabled) + { + await TurnOffAsync(); + } + } + finally + { + _gate.Release(); + } + } + + /// + /// Runs after the switch in progress, never inside the comparison or the reconnect loop, and is checked again + /// when it runs (). + /// + public void PostTurnOff(SyncTurnOff turnOff) + { + _ = Task.Run(() => RunTurnOffAsync(turnOff)).ContinueWith( + task => _logger.LogError(task.Exception, "Turning PLC sync off failed"), + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted, + TaskScheduler.Default); + } + + private async Task RunTurnOffAsync(SyncTurnOff turnOff) + { + await _gate.WaitAsync(); + try + { + if (IsDisposed || !_state.IsDue(turnOff)) + { + _logger.LogInformation("PLC sync turn-off skipped: it is no longer due ({Reason})", turnOff.Reason.Message); + return; + } + + _logger.LogWarning("Turning PLC sync off: {Reason}", turnOff.Reason.Message); + await TurnOffAsync(); + + lock (_state.Gate) + { + if (!IsDisposed) + { + _turnOffs.OnNext(turnOff.Reason); + } + } + } + finally + { + _gate.Release(); + } + } + + /// The version is read before a comparison may start, so a mismatched PLC is never compared or written. + private async Task TurnOnAsync(PlcConfiguration config) + { + _state.TurnOn(() => _syncService.SetSyncEnabled(true)); + try + { + await _connection.ConnectAsync(config.Connection); + + var versionResult = await ReadMatchingProtocolVersionAsync(); + if (versionResult.IsFailed) + { + RollBack(); + await _connection.DisconnectAsync(); + } + + return versionResult; + } + catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) + { + RollBack(); + return Result.Fail(SyncEnableCancelledMessage); + } + catch (Exception ex) + { + RollBack(); + _logger.LogWarning("Enabling PLC sync failed: {Message}", ex.Message); + return Result.Fail(ex.Message); + } + } + + private async Task ReadMatchingProtocolVersionAsync() + { + var versionResult = await _reader.ReadProtocolVersionAsync(_lifetime); + return versionResult.IsFailed + ? versionResult.ToResult() + : versionResult.Value != ProtocolConstants.ProtocolVersion + ? Result.Fail(new ProtocolVersionMismatchError(ProtocolConstants.ProtocolVersion, versionResult.Value)) + : Result.Ok(); + } + + private void RollBack() + { + _state.TurnOff(TurnSyncServiceOff); + ReleaseOwnershipLease(); + } + + /// The lease is released last: until the write in flight and the session end, another instance must not write. + private async Task TurnOffAsync() + { + _state.TurnOff(TurnSyncServiceOff); + await WaitForWriteInFlightAsync(); + + try + { + await _connection.DisconnectAsync(); + } + catch (Exception ex) + { + _logger.LogWarning("Error while disconnecting from PLC: {Message}", ex.Message); + } + finally + { + ReleaseOwnershipLease(); + } + } + + private void TurnSyncServiceOff() + { + _syncService.SetSyncEnabled(false); + _syncService.ResetForDisable(); + } + + private async Task WaitForWriteInFlightAsync() + { + using var timeout = new CancellationTokenSource(_disableWriteWaitTimeout); + try + { + await _syncService.WaitForPendingSyncAsync(timeout.Token); + } + catch (OperationCanceledException) when (timeout.IsCancellationRequested) + { + _logger.LogWarning( + "Sync attempt did not finish within {Timeout}; disconnecting from PLC anyway", + _disableWriteWaitTimeout); + } + } + + private void ReleaseOwnershipLease() + { + Interlocked.Exchange(ref _ownershipLease, null)?.Dispose(); + } +} diff --git a/SemiStep/SemiStep.Core/Plc/S7/S7Service.cs b/SemiStep/SemiStep.Core/Plc/S7/S7Service.cs index d4282db9..49f399d8 100644 --- a/SemiStep/SemiStep.Core/Plc/S7/S7Service.cs +++ b/SemiStep/SemiStep.Core/Plc/S7/S7Service.cs @@ -180,17 +180,29 @@ public async Task> ReadProtocolVersionAsync(CancellationToken ct = d } internal void OnConnectionLost() + { + if (TryMarkLinkLost()) + { + CompleteLinkLoss(); + } + } + + private bool TryMarkLinkLost() { lock (_stateLock) { if (_state != PlcConnectionState.Connected) { - return; + return false; } _state = PlcConnectionState.Disconnected; + return true; } + } + private void CompleteLinkLoss() + { StateChanged?.Invoke(PlcConnectionState.Disconnected); _ = StopKeepAlive(); @@ -200,6 +212,34 @@ internal void OnConnectionLost() StartReconnectLoop(); } + public void DeclareLinkLost() + { + // The caller can be a StateChanged subscriber, and OnConnectionLost raises StateChanged synchronously. + _ = Task.Run(CloseAndDeclareLinkLostAsync).ContinueWith( + task => _logger.LogError(task.Exception, "Declaring PLC link loss after a failed read failed"), + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted, + TaskScheduler.Default); + } + + /// The reconnect loop starts only after the close, so the close cannot hit a new link. + private async Task CloseAndDeclareLinkLostAsync() + { + if (!TryMarkLinkLost()) + { + return; + } + + try + { + await _s7Driver.DisconnectAsync(); + } + finally + { + CompleteLinkLoss(); + } + } + private void OnRequestDeadlinePassed() { // The timed-out request can be the execution poll, and OnConnectionLost waits for that poll to stop. diff --git a/SemiStep/SemiStep.Core/Plc/Sync/ComparisonReadsFailedError.cs b/SemiStep/SemiStep.Core/Plc/Sync/ComparisonReadsFailedError.cs new file mode 100644 index 00000000..e34fcef1 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/Sync/ComparisonReadsFailedError.cs @@ -0,0 +1,9 @@ +using FluentResults; + +namespace SemiStep.Core.Plc.Sync; + +/// Sync turned off: three recipe comparisons in a row failed to read the PLC in one sync-on period. +public sealed class ComparisonReadsFailedError() + : Error("Could not read the recipe from the PLC. Sync is turned off.") +{ +} diff --git a/SemiStep/SemiStep.Core/Plc/Sync/ConflictUnresolvedError.cs b/SemiStep/SemiStep.Core/Plc/Sync/ConflictUnresolvedError.cs new file mode 100644 index 00000000..24525b5f --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/Sync/ConflictUnresolvedError.cs @@ -0,0 +1,13 @@ +using FluentResults; + +namespace SemiStep.Core.Plc.Sync; + +/// Sync turned off: the recipe conflict dialog closed without a choice, or could not be shown. +public sealed class ConflictUnresolvedError(bool dialogShowFailed) + : Error( + dialogShowFailed + ? "Failed to show PLC conflict dialog. Sync is turned off: the recipe conflict is not resolved." + : "Sync is turned off: the recipe conflict is not resolved.") +{ + public bool DialogShowFailed { get; } = dialogShowFailed; +} diff --git a/SemiStep/SemiStep.Core/Plc/Sync/PlcRecipeNotLoadedError.cs b/SemiStep/SemiStep.Core/Plc/Sync/PlcRecipeNotLoadedError.cs new file mode 100644 index 00000000..ac984b26 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/Sync/PlcRecipeNotLoadedError.cs @@ -0,0 +1,10 @@ +using FluentResults; + +namespace SemiStep.Core.Plc.Sync; + +/// Sync turned off: the PLC recipe failed the check when the app took it. +public sealed class PlcRecipeNotLoadedError(IReadOnlyList causes) + : Error($"The PLC recipe was not loaded: {string.Join("; ", causes.Select(cause => cause.Message))}. Sync is turned off.") +{ + public IReadOnlyList Causes { get; } = causes; +} diff --git a/SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs b/SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs index 94f308b0..29dfab69 100644 --- a/SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs +++ b/SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs @@ -12,8 +12,8 @@ namespace SemiStep.Core.Plc.Sync; /// -/// The sync state machine: status, debounce, pending recipe, in-flight attempt and its write token -/// under one state lock. +/// The sync state machine: status, debounce, pending recipe, in-flight attempt, its write token and the write +/// pause under one state lock. /// internal sealed class PlcSyncCoordinator : IPlcSyncService, IDisposable { @@ -41,6 +41,8 @@ internal sealed class PlcSyncCoordinator : IPlcSyncService, IDisposable private bool _isLatestRecipeValid; private bool _isParkedUntilRunEnd; private bool _hasRunEndedDuringAttempt; + private bool _isWritePaused; + private bool _hasRecipeSincePauseStart; private CancellationTokenSource? _debounceCts; private CancellationTokenSource? _runningAttempt; private CancellationTokenSource? _writeCts; @@ -94,14 +96,23 @@ public PlcSyncStatus Status public IObservable Faults => _faults; + /// + /// Ignored while sync is off: the caller checks the flag before it notifies, and a turn-off can land in between. + /// public void NotifyRecipeChanged(Recipe recipe, bool isValid) { if (!isValid) { Transition(() => { + if (!_isSyncEnabled) + { + return default; + } + _pendingRecipe = null; _isLatestRecipeValid = false; + _hasRecipeSincePauseStart = true; return new TransitionResult(SetStatusLocked(PlcSyncStatus.OutOfSync), null, null); }); return; @@ -109,8 +120,20 @@ public void NotifyRecipeChanged(Recipe recipe, bool isValid) StartDebounceWhen(() => { + if (!_isSyncEnabled) + { + return false; + } + _pendingRecipe = recipe; _isLatestRecipeValid = true; + _hasRecipeSincePauseStart = true; + if (_isWritePaused) + { + _logger.LogDebug("Write pause holds, keeping the new recipe"); + return false; + } + if (_runningAttempt is null) { return true; @@ -121,12 +144,43 @@ public void NotifyRecipeChanged(Recipe recipe, bool isValid) }); } + /// Sync on starts a write pause; only a comparison outcome ends it. public void SetSyncEnabled(bool value) { Transition(() => { _isSyncEnabled = value; - return new TransitionResult(SnapshotLocked(), null, null); + var retired = value ? BeginWritePauseLocked() : null; + _isWritePaused = value; + return new TransitionResult(SnapshotLocked(), null, retired); + }); + } + + public void EndWritePause(Recipe screenRecipe, bool isValid) + { + Transition(() => + { + var isNotifiedDuringPause = _isWritePaused && _hasRecipeSincePauseStart; + _isWritePaused = false; + if (!isNotifiedDuringPause) + { + _pendingRecipe = isValid ? screenRecipe : null; + _isLatestRecipeValid = isValid; + } + + var snapshot = _isLatestRecipeValid ? null : SetStatusLocked(PlcSyncStatus.OutOfSync); + var retired = _pendingRecipe is not null && _runningAttempt is null ? StartDebounceLocked() : null; + return new TransitionResult(snapshot, null, retired); + }); + } + + public void EndWritePauseWithoutWrite() + { + Transition(() => + { + _isWritePaused = false; + _pendingRecipe = null; + return default; }); } @@ -152,11 +206,20 @@ public void HandleConnectionLost() return new TransitionResult( snapshot, new ConnectionLostError(), - CancelAttemptLocked(), + BeginWritePauseLocked(), TakeWriteSourceLocked()); }); } + /// Drops a debounced write; the caller decides whether to cancel the token of a write in flight. + private CancellationTokenSource? BeginWritePauseLocked() + { + _isWritePaused = true; + _hasRecipeSincePauseStart = false; + + return CancelAttemptLocked(); + } + public async Task WaitForPendingSyncAsync(CancellationToken ct = default) { Task? taskToWait; @@ -439,7 +502,7 @@ private void ReleaseWriteSource(CancellationTokenSource writeCts) private TransitionResult CompleteWriteLocked() { var snapshot = SetStatusLocked(PlcSyncStatus.Synced); - if (_pendingRecipe is null) + if (_pendingRecipe is null || _isWritePaused) { _runningAttempt = null; return new TransitionResult(snapshot, null, null); @@ -484,7 +547,7 @@ private TransitionResult ParkUntilRunEndLocked(Recipe recipeToSync, RecipeActive _pendingRecipe ??= recipeToSync; } - if (_hasRunEndedDuringAttempt && _pendingRecipe is not null) + if (_hasRunEndedDuringAttempt && _pendingRecipe is not null && !_isWritePaused) { return new TransitionResult(null, recipeActive, StartDebounceLocked()); } @@ -504,7 +567,7 @@ private void OnRunEnded() return false; } - return _isParkedUntilRunEnd && _pendingRecipe is not null; + return _isParkedUntilRunEnd && _pendingRecipe is not null && !_isWritePaused; }); } @@ -518,7 +581,7 @@ private void EndAttempt(CancellationTokenSource attempt) } _runningAttempt = null; - return _pendingRecipe is not null; + return _pendingRecipe is not null && !_isWritePaused; }); } diff --git a/SemiStep/SemiStep.Core/Plc/SyncTurnOff.cs b/SemiStep/SemiStep.Core/Plc/SyncTurnOff.cs new file mode 100644 index 00000000..3f6a8042 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/SyncTurnOff.cs @@ -0,0 +1,9 @@ +using FluentResults; + +namespace SemiStep.Core.Plc; + +/// +/// A turn-off the app decided in ; a failure-cap turn-off holds only while the +/// failures it counted still stand. +/// +internal readonly record struct SyncTurnOff(long SyncPeriod, IError Reason, bool IsFailureCap); diff --git a/SemiStep/SemiStep.Tests/Domain/PlcComparisonStateTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcComparisonStateTests.cs new file mode 100644 index 00000000..51cdb744 --- /dev/null +++ b/SemiStep/SemiStep.Tests/Domain/PlcComparisonStateTests.cs @@ -0,0 +1,123 @@ +using AwesomeAssertions; + +using FluentResults; + +using SemiStep.Core.Plc; +using SemiStep.Core.Recipes; + +using Xunit; + +namespace SemiStep.Tests.Domain; + +/// A posted turn-off is checked again when it runs; these are the cases that skip it. +[Trait("Component", "Domain")] +[Trait("Area", "WritePause")] +[Trait("Category", "Unit")] +public sealed class PlcComparisonStateTests +{ + private readonly PlcComparisonState _state = new(); + + [Fact] + public void FailureCapTurnOff_IsSkipped_WhenALaterComparisonDecided() + { + var turnOff = ReachTheFailureCap(); + var comparisonId = BeginComparison(); + + lock (_state.Gate) + { + _state.TryDecideLocked(comparisonId).Should().BeTrue(); + } + + _state.IsDue(turnOff).Should().BeFalse("the decision reset the failures the turn-off counted"); + } + + [Fact] + public void FailureCapTurnOff_IsDue_WhileItsFailuresStand() + { + var turnOff = ReachTheFailureCap(); + + _state.IsDue(turnOff).Should().BeTrue(); + } + + [Fact] + public void TurnOff_FromAnOlderSyncOnPeriod_IsSkipped() + { + TurnOn(); + SyncTurnOff turnOff; + lock (_state.Gate) + { + turnOff = _state.TurnOffLocked(new Error("conflict not answered")); + } + + _state.TurnOff(() => { }); + TurnOn(); + + _state.IsDue(turnOff).Should().BeFalse("sync was turned off and on since the turn-off was posted"); + } + + [Fact] + public void TurnOff_AfterSyncWentOff_IsSkipped() + { + TurnOn(); + SyncTurnOff turnOff; + lock (_state.Gate) + { + turnOff = _state.TurnOffLocked(new Error("conflict not answered")); + } + + _state.TurnOff(() => { }); + + _state.IsDue(turnOff).Should().BeFalse(); + } + + [Fact] + public void Comparison_DoesNotStart_WhileSyncIsOff() + { + _state.TryBeginComparison(isFromConnectedEvent: true).Should().BeNull(); + + TurnOn(); + _state.TurnOff(() => { }); + + _state.TryBeginComparison(isFromConnectedEvent: false).Should().BeNull(); + } + + [Fact] + public void StaleOffer_IsNotTaken_AndDoesNotClearTheCurrentOne() + { + TurnOn(); + var staleId = BeginComparison(); + var currentId = BeginComparison(); + var currentOffer = new PlcRecipeOffer(currentId, Recipe.Empty, IsConflict: true); + + lock (_state.Gate) + { + _state.OfferLocked(currentOffer); + _state.TakeOfferLocked(offer => offer.ComparisonId == staleId).Should().BeNull(); + _state.TakeOfferLocked(offer => offer.ComparisonId == currentId).Should().Be(currentOffer); + } + } + + private SyncTurnOff ReachTheFailureCap() + { + TurnOn(); + SyncTurnOff? turnOff = null; + for (var failure = 0; failure < PlcComparisonState.FailedComparisonLimit; failure++) + { + _state.TryFail(BeginComparison(), out turnOff).Should().BeTrue(); + } + + return turnOff ?? throw new InvalidOperationException("The last allowed failure posts no turn-off"); + } + + private void TurnOn() + { + _state.TurnOn(() => { }); + _state.EndEnabling(); + } + + private long BeginComparison() + { + return _state.TryBeginComparison(isFromConnectedEvent: false) + ?? throw new InvalidOperationException("Sync is off"); + } +} diff --git a/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs index 8890e44b..86f54700 100644 --- a/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs +++ b/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs @@ -88,7 +88,7 @@ private static Recipe RoundTripThroughPlcData(RecipeConverter converter, Recipe return converter.ToRecipe(converter.FromRecipe(recipe).Value).Value; } - private static async Task ReconcileAndReportConflictAsync( + private static async Task ReconcileAndReportConflictAsync( PlcLifecycleManager plc, StubS7Service s7Service, StubPlcSyncService syncService, @@ -100,17 +100,17 @@ private static async Task ReconcileAndReportConflictAsync( var enableResult = await plc.EnableSync(PlcConfiguration.Default); enableResult.IsSuccess.Should().BeTrue(); - var conflictFired = false; - plc.PlcRecipeConflictDetected += (_, _) => conflictFired = true; - var countBeforeStateChange = syncService.NotifyRecipeChangedCallCount; + PlcRecipeConflict? conflict = null; + plc.PlcRecipeConflictDetected += raised => conflict = raised; + var endsBeforeStateChange = syncService.WritePauseEnds.Count; s7Service.RaiseStateChanged(PlcConnectionState.Connected); await TestHelpers.WaitUntilAsync( - () => conflictFired || syncService.NotifyRecipeChangedCallCount > countBeforeStateChange, + () => conflict is not null || syncService.WritePauseEnds.Count > endsBeforeStateChange, cancellationToken: TestContext.Current.CancellationToken); - return conflictFired; + return conflict; } private static async Task AssertIdenticalOutcomeLoggedAsync(RecordingLogger logger) @@ -146,10 +146,10 @@ public async Task StateChanged_Connected_WhenRecipesDiffer_FiresConflictDetected Recipe? conflictLocalRecipe = null; Recipe? conflictPlcRecipe = null; - plc.PlcRecipeConflictDetected += (local, plcRec) => + plc.PlcRecipeConflictDetected += conflict => { - conflictLocalRecipe = local; - conflictPlcRecipe = plcRec; + conflictLocalRecipe = conflict.Local; + conflictPlcRecipe = conflict.Plc; }; s7Service.RaiseStateChanged(PlcConnectionState.Connected); @@ -180,16 +180,15 @@ public async Task StateChanged_Connected_WhenRecipesIdentical_DoesNotFireConflic enableResult.IsSuccess.Should().BeTrue(); var conflictFired = false; - plc.PlcRecipeConflictDetected += (_, _) => conflictFired = true; - - var countBeforeStateChange = syncService.NotifyRecipeChangedCallCount; + plc.PlcRecipeConflictDetected += _ => conflictFired = true; s7Service.RaiseStateChanged(PlcConnectionState.Connected); await TestHelpers.WaitUntilAsync( - () => syncService.NotifyRecipeChangedCallCount > countBeforeStateChange, + () => syncService.WritePauseEnds.Count > 0, cancellationToken: TestContext.Current.CancellationToken); + syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeSameAs(session.Current); conflictFired.Should().BeFalse( "identical PLC and PC recipe content must not raise PlcRecipeConflictDetected"); } @@ -204,16 +203,14 @@ public async Task StateChanged_Connected_WhenNotCommitted_PushesLocalRecipe() var enableResult = await plc.EnableSync(PlcConfiguration.Default); enableResult.IsSuccess.Should().BeTrue(); - var countBeforeStateChange = syncService.NotifyRecipeChangedCallCount; - s7Service.RaiseStateChanged(PlcConnectionState.Connected); await TestHelpers.WaitUntilAsync( - () => syncService.NotifyRecipeChangedCallCount > countBeforeStateChange, + () => syncService.WritePauseEnds.Count > 0, cancellationToken: TestContext.Current.CancellationToken); - syncService.NotifyRecipeChangedCallCount.Should().BeGreaterThan(countBeforeStateChange, - "when committed=false the manager must push the local recipe to the PLC via NotifyRecipeChanged"); + syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().NotBeNull( + "when committed=false the comparison ends the write pause with a write of the local recipe"); } [Fact] @@ -364,10 +361,10 @@ public async Task EnableSync_WhenVersionReadFails_FailsAndDisconnects() [Fact] public async Task EnableSync_WhenConnectedFiresDuringConnect_AndVersionMismatches_DoesNotReadOrApply() { - var (plc, _, s7Service, _, _, _) = await BuildAsync(); + var (plc, _, s7Service, syncService, _, _) = await BuildAsync(); - // Mirror the real S7Service: Connected is published synchronously inside ConnectAsync, - // triggering reconnect reconciliation before the EnableSync version handshake finishes. + // Mirror the real S7Service: Connected is published synchronously inside ConnectAsync, before the + // EnableSync version handshake finishes. s7Service.RaiseConnectedDuringConnect = true; s7Service.ProtocolVersionToReturn = Result.Ok(2); s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 1); @@ -377,18 +374,10 @@ public async Task EnableSync_WhenConnectedFiresDuringConnect_AndVersionMismatche enableResult.IsFailed.Should().BeTrue("a version mismatch must fail EnableSync"); enableResult.HasError().Should().BeTrue(); - - // Wait until both the EnableSync handshake and the fire-and-forget reconciliation triggered - // during connect have disconnected on the version mismatch. Both abort via the same - // FailProtocolVersionHandshakeAsync path that disconnects before reading the managing area, - // so two disconnects deterministically signal that reconciliation has fully aborted. - await TestHelpers.WaitUntilAsync( - () => s7Service.DisconnectCallCount == 2, - cancellationToken: TestContext.Current.CancellationToken); - + s7Service.DisconnectCallCount.Should().Be(1, "only the switch reports the mismatch and disconnects"); s7Service.ReadManagingAreaCallCount.Should().Be(0, - "reconnect reconciliation triggered by Connected-during-connect must gate on the version " - + "check and never read the managing area or apply a recipe on a version mismatch"); + "the first-connect comparison starts only after the version read passed"); + syncService.WritePauseEnds.Should().BeEmpty("nothing is written to a mismatched PLC"); } [Fact] @@ -466,9 +455,9 @@ public async Task StateChanged_Connected_WhenCsvShapedStepMatchesPlcData_DoesNot var plcRecipe = RoundTripThroughPlcData(converter, localRecipe); - var conflictFired = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); + var conflict = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); - conflictFired.Should().BeFalse( + conflict.Should().BeNull( "a blank comment cell and the empty string the PLC holds are the same PLC data"); await AssertIdenticalOutcomeLoggedAsync(logger); } @@ -484,9 +473,9 @@ public async Task StateChanged_Connected_WhenOneValueDiffersInPlcData_FiresConfl var plcRecipe = Recipe.Empty.AppendStep( roundTrip.Steps[0].WithProperty(RecipeTestDriver.StepDurationColumn, PropertyValue.FromFloat(11f))); - var conflictFired = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); + var conflict = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); - conflictFired.Should().BeTrue("a step duration that differs in the PLC is a different recipe"); + conflict.Should().NotBeNull("a step duration that differs in the PLC is a different recipe"); } [Fact] @@ -498,9 +487,9 @@ public async Task StateChanged_Connected_WhenRieEtchStepOmitsInactiveColumns_Doe var plcRecipe = RoundTripThroughPlcData(converter, session.Current); - var conflictFired = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); + var conflict = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); - conflictFired.Should().BeFalse( + conflict.Should().BeNull( "inactive capacitor columns are written as zero, which is what the PLC holds"); await AssertIdenticalOutcomeLoggedAsync(logger); } @@ -516,9 +505,9 @@ public async Task StateChanged_Connected_WhenLocalValueHasWrongType_FiresConflic session.LoadAsCurrent(localRecipe).IsSuccess.Should().BeTrue(); var plcRecipe = RoundTripThroughPlcData(converter, BuildWaitRecipeWithoutCommentKey()); - var conflictFired = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); + var conflict = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); - conflictFired.Should().BeTrue("a local recipe the PC cannot encode is not proven equal to the PLC"); + conflict.Should().NotBeNull("a local recipe the PC cannot encode is not proven equal to the PLC"); logger.Snapshot() .Where(entry => entry.Level == LogLevel.Warning && entry.Properties.ContainsKey("StepNumber")) .Should().ContainSingle() @@ -536,9 +525,9 @@ public async Task StateChanged_Connected_WhenPlcHoldsValueInKeyLocalOmits_FiresC var plcRecipe = Recipe.Empty.AppendStep( roundTrip.Steps[0].WithProperty(CommentKey, PropertyValue.FromString("x"))); - var conflictFired = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); + var conflict = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); - conflictFired.Should().BeTrue("a missing local key matches only the type default, not a value the PLC holds"); + conflict.Should().NotBeNull("a missing local key matches only the type default, not a value the PLC holds"); } [Fact] @@ -566,7 +555,7 @@ public async Task ResolveConflict_TakePlcRecipeFailingImportCheck_LeavesSessionU } /// Raises a conflict over a saved local recipe with undo history, then takes the PLC recipe. - private static async Task TakeConflictingPlcRecipeAsync( + private static async Task> TakeConflictingPlcRecipeAsync( PlcLifecycleManager plc, RecipeSession session, StubS7Service s7Service, @@ -577,11 +566,11 @@ private static async Task TakeConflictingPlcRecipeAsync( session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); session.MarkSaved(); var snapshotBefore = session.Snapshot; - var conflictFired = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); - conflictFired.Should().BeTrue(); + var conflict = await ReconcileAndReportConflictAsync(plc, s7Service, syncService, plcRecipe); + conflict.Should().NotBeNull(); var notificationsBefore = syncService.NotifyRecipeChangedCallCount; - var result = plc.ResolveConflict(keepLocal: false); + var result = plc.ResolveConflict(conflict.ComparisonId, PlcConflictAnswer.TakePlc); result.IsFailed.Should().BeTrue(); session.Snapshot.Should().BeSameAs(snapshotBefore); diff --git a/SemiStep/SemiStep.Tests/Domain/PlcReconciliationOutcomeLogTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcReconciliationOutcomeLogTests.cs index 30b106d1..d27950bd 100644 --- a/SemiStep/SemiStep.Tests/Domain/PlcReconciliationOutcomeLogTests.cs +++ b/SemiStep/SemiStep.Tests/Domain/PlcReconciliationOutcomeLogTests.cs @@ -127,8 +127,8 @@ private static void ShouldUseShortTemplate(RecordingLogger. } /// - /// Drives one of the five exits that hand the local recipe to the sync executor while the session - /// is edited inside the push. + /// Drives one of the three exits that end the write pause with a write while the session is edited inside + /// that call. /// private async Task AssertLoggedRecipeIsThePushedOneAsync(PlcReconciliationOutcome outcome) { @@ -140,16 +140,14 @@ private async Task AssertLoggedRecipeIsThePushedOneAsync(PlcReconciliationOutcom var enableResult = await plc.EnableSync(PlcConfiguration.Default); enableResult.IsSuccess.Should().BeTrue(); - var pushIndex = syncService.NotifyRecipeChangedCallCount; - // Stands in for the UI thread appending a step while the reconciliation is inside the push. - syncService.OnNextNotifyRecipeChanged = () => session.AppendStep(WaitActionId); + syncService.OnNextWritePauseEnd = () => session.AppendStep(WaitActionId); s7Service.RaiseStateChanged(PlcConnectionState.Connected); var entry = await WaitForOutcomeAsync(logger, outcome); - syncService.NotifyRecipeChangedCalls[pushIndex].Recipe.Steps.Count.Should().Be(1, + syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe!.Steps.Count.Should().Be(1, "the push captured the recipe as it stood before the edit"); session.Current.Steps.Count.Should().Be(2, "the edit landed after the push"); entry.Properties.Should().Contain(LocalStepCountField, 1, @@ -163,16 +161,9 @@ private static void ArrangePushExit( { switch (outcome) { - case PlcReconciliationOutcome.ManagingAreaReadFailed: - // ManagingAreaToReturn left null: the stub answers the read with a failure. - break; case PlcReconciliationOutcome.NotCommitted: s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: false, RecipeLines: 0); break; - case PlcReconciliationOutcome.RecipeReadFailed: - // RecipeToReturn left null: the stub answers the recipe read with a failure. - s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 1); - break; case PlcReconciliationOutcome.PlcEmpty: s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 0); s7Service.RecipeToReturn = Recipe.Empty; @@ -185,7 +176,7 @@ private static void ArrangePushExit( throw new ArgumentOutOfRangeException( nameof(outcome), outcome, - "Only the five exits that push the local recipe are arranged here"); + "Only the three exits that end the pause with a write are arranged here"); } } @@ -227,25 +218,22 @@ public async Task Reconciliation_WhenProtocolVersionReadFails_LogsProtocolVersio } [Fact] - public async Task Reconciliation_WhenManagingAreaReadFails_LogsManagingAreaReadFailedAndPushesLocal() + public async Task Reconciliation_WhenManagingAreaReadFails_LogsManagingAreaReadFailedAndWritesNothing() { var (plc, _, s7Service, syncService, logger) = await BuildAsync(); var enableResult = await plc.EnableSync(PlcConfiguration.Default); enableResult.IsSuccess.Should().BeTrue(); - var pushesBefore = syncService.NotifyRecipeChangedCallCount; - // ManagingAreaToReturn left null: the stub answers the read with a failure. s7Service.RaiseStateChanged(PlcConnectionState.Connected); var entry = await WaitForOutcomeAsync(logger, PlcReconciliationOutcome.ManagingAreaReadFailed); - entry.Level.Should().Be(LogLevel.Warning, - "a read failure that still pushes the local recipe over the PLC is a suspicious outcome"); + entry.Level.Should().Be(LogLevel.Warning); ShouldUseShortTemplate(entry); - syncService.NotifyRecipeChangedCallCount.Should().Be(pushesBefore + 1, - "this exit hands the local recipe to the sync executor, which this slice must not change"); + syncService.WritePauseEnds.Should().BeEmpty("a failed read keeps the write pause"); + s7Service.DeclareLinkLostCallCount.Should().Be(1, "a failed comparison read declares link loss"); } [Fact] @@ -269,7 +257,7 @@ public async Task Reconciliation_WhenNotCommitted_LogsNotCommittedAtWarning() } [Fact] - public async Task Reconciliation_WhenRecipeReadFails_LogsRecipeReadFailedAndPushesLocal() + public async Task Reconciliation_WhenRecipeReadFails_LogsRecipeReadFailedAndWritesNothing() { var (plc, _, s7Service, syncService, logger) = await BuildAsync(); @@ -278,8 +266,6 @@ public async Task Reconciliation_WhenRecipeReadFails_LogsRecipeReadFailedAndPush var enableResult = await plc.EnableSync(PlcConfiguration.Default); enableResult.IsSuccess.Should().BeTrue(); - var pushesBefore = syncService.NotifyRecipeChangedCallCount; - // RecipeToReturn left null: the stub answers the recipe read with a failure. s7Service.RaiseStateChanged(PlcConnectionState.Connected); @@ -288,8 +274,8 @@ public async Task Reconciliation_WhenRecipeReadFails_LogsRecipeReadFailedAndPush entry.Level.Should().Be(LogLevel.Warning); entry.Properties.Should().Contain(CommittedField, true, "the managing area was read on this exit even though the recipe was not"); - syncService.NotifyRecipeChangedCallCount.Should().Be(pushesBefore + 1, - "this exit hands the local recipe to the sync executor, which this slice must not change"); + syncService.WritePauseEnds.Should().BeEmpty("a failed read keeps the write pause"); + s7Service.DeclareLinkLostCallCount.Should().Be(1, "a failed comparison read declares link loss"); } [Fact] @@ -391,7 +377,7 @@ public async Task Reconciliation_WhenRecipesDiffer_LogsConflictRaisedAtInformati var enableResult = await plc.EnableSync(PlcConfiguration.Default); enableResult.IsSuccess.Should().BeTrue(); - plc.PlcRecipeConflictDetected += (_, _) => { }; + plc.PlcRecipeConflictDetected += _ => { }; s7Service.RaiseStateChanged(PlcConnectionState.Connected); @@ -418,8 +404,6 @@ public async Task Reconciliation_WhenPlcRecipeEmpty_LogsPlcEmptyAndPushesLocal() var enableResult = await plc.EnableSync(PlcConfiguration.Default); enableResult.IsSuccess.Should().BeTrue(); - var pushesBefore = syncService.NotifyRecipeChangedCallCount; - // No conflict handler is attached here, which is the one case that reads the subscriber field // as False. s7Service.RaiseStateChanged(PlcConnectionState.Connected); @@ -429,8 +413,8 @@ public async Task Reconciliation_WhenPlcRecipeEmpty_LogsPlcEmptyAndPushesLocal() entry.Level.Should().Be(LogLevel.Information); entry.Properties.Should().Contain(HasConflictSubscriberField, false, "the subscriber field separates 'Core never raised the conflict' from 'the UI hop dropped it'"); - syncService.NotifyRecipeChangedCallCount.Should().Be(pushesBefore + 1, - "this exit hands the local recipe to the sync executor, which this slice must not change"); + syncService.WritePauseEnds.Should().ContainSingle("this exit ends the write pause with a write") + .Which.Recipe.Should().NotBeNull(); } [Fact] @@ -562,24 +546,12 @@ public async Task Reconciliation_OnOneConnectedEdge_LogsExactlyOneOutcomeLine() "one reconciliation must produce exactly one outcome line, so the field log pairs begin with outcome"); } - [Fact] - public async Task Reconciliation_WhenSessionChangesDuringManagingAreaReadFailedPush_LogsPushedRecipe() - { - await AssertLoggedRecipeIsThePushedOneAsync(PlcReconciliationOutcome.ManagingAreaReadFailed); - } - [Fact] public async Task Reconciliation_WhenSessionChangesDuringNotCommittedPush_LogsPushedRecipe() { await AssertLoggedRecipeIsThePushedOneAsync(PlcReconciliationOutcome.NotCommitted); } - [Fact] - public async Task Reconciliation_WhenSessionChangesDuringRecipeReadFailedPush_LogsPushedRecipe() - { - await AssertLoggedRecipeIsThePushedOneAsync(PlcReconciliationOutcome.RecipeReadFailed); - } - [Fact] public async Task Reconciliation_WhenSessionChangesDuringPlcEmptyPush_LogsPushedRecipe() { diff --git a/SemiStep/SemiStep.Tests/Domain/PlcRunEndSyncTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcRunEndSyncTests.cs index a408cd3b..9aa0a65c 100644 --- a/SemiStep/SemiStep.Tests/Domain/PlcRunEndSyncTests.cs +++ b/SemiStep/SemiStep.Tests/Domain/PlcRunEndSyncTests.cs @@ -149,7 +149,7 @@ public async Task LinkLossWhileParked_WritesNothingUntilReconnect_ThenReconciles _statuses.Should().NotContain(PlcSyncStatus.Syncing, "a link loss clears the park"); var conflictRaised = false; - _plc.PlcRecipeConflictDetected += (_, _) => conflictRaised = true; + _plc.PlcRecipeConflictDetected += _ => conflictRaised = true; _s7Service.RaiseStateChanged(PlcConnectionState.Connected); await TestHelpers.WaitUntilAsync(() => conflictRaised, TestContext.Current.CancellationToken); _statuses.Should().NotContain(PlcSyncStatus.Syncing, "the reconnect reconciliation decides the next write"); @@ -180,12 +180,12 @@ private async Task KeepLocalDuringRunAsync() await SetRunActiveAsync(true); (await _plc.EnableSync(_configuration.PlcConfiguration)).IsSuccess.Should().BeTrue(); - var conflictRaised = false; - _plc.PlcRecipeConflictDetected += (_, _) => conflictRaised = true; + PlcRecipeConflict? conflict = null; + _plc.PlcRecipeConflictDetected += raised => conflict = raised; _s7Service.RaiseStateChanged(PlcConnectionState.Connected); - await TestHelpers.WaitUntilAsync(() => conflictRaised, TestContext.Current.CancellationToken); + await TestHelpers.WaitUntilAsync(() => conflict is not null, TestContext.Current.CancellationToken); - _plc.ResolveConflict(keepLocal: true).IsSuccess.Should().BeTrue(); + _plc.ResolveConflict(conflict!.ComparisonId, PlcConflictAnswer.KeepLocal).IsSuccess.Should().BeTrue(); await TestHelpers.WaitUntilAsync( () => _faults.OfType().Any(), _syncTimeout, diff --git a/SemiStep/SemiStep.Tests/Domain/PlcWritePauseSyncTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcWritePauseSyncTests.cs new file mode 100644 index 00000000..b1c866a4 --- /dev/null +++ b/SemiStep/SemiStep.Tests/Domain/PlcWritePauseSyncTests.cs @@ -0,0 +1,190 @@ +using System.Collections.Concurrent; + +using AwesomeAssertions; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; + +using SemiStep.Core.Configuration; +using SemiStep.Core.Configuration.Facade; +using SemiStep.Core.Plc; +using SemiStep.Core.Plc.S7.Serialization; +using SemiStep.Core.Plc.State; +using SemiStep.Core.Plc.Sync; +using SemiStep.Core.Plc.Sync.Ownership; +using SemiStep.Core.Recipes; +using SemiStep.Core.Recipes.Clipboard; +using SemiStep.Core.Recipes.Import; +using SemiStep.Tests.Helpers; +using SemiStep.Tests.S7.Helpers; + +using Xunit; + +namespace SemiStep.Tests.Domain; + +/// +/// The #181 race end to end, with the real sync coordinator: nothing reaches the PLC between sync on or a link drop +/// and the comparison that decides. +/// +[Trait("Component", "Domain")] +[Trait("Area", "WritePause")] +[Trait("Category", "Integration")] +public sealed class PlcWritePauseSyncTests : IAsyncLifetime +{ + private const int WaitActionId = 10; + + private static readonly TimeSpan _syncTimeout = TimeSpan.FromSeconds(5); + private static readonly TimeSpan _pollInterval = TimeSpan.FromMilliseconds(20); + + // Past the 1 s debounce, so a write the pause failed to hold would have started. + private static readonly TimeSpan _quietPeriod = TimeSpan.FromMilliseconds(1500); + + private readonly StubS7Service _s7Service = new(); + private readonly StoringS7Transport _transport = new(); + private readonly ConcurrentQueue _statuses = new(); + private ServiceProvider _services = null!; + private PlcLifecycleManager _plc = null!; + private RecipeSession _session = null!; + private PlcTransactionExecutor _executor = null!; + private AppConfiguration _configuration = null!; + private IDisposable? _subscription; + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + public async ValueTask InitializeAsync() + { + var loaded = await ConfigFacade.LoadAndValidateAsync(TestConfigLocator.GetConfigDirectory()); + _configuration = loaded.Value; + + _services = new ServiceCollection() + .AddLogging() + .AddSingleton(_configuration) + .AddRecipe() + .AddCsv() + .AddClipboard() + .AddSingleton(_s7Service) + .AddSingleton(_s7Service) + .AddSingleton(_s7Service) + .AddSingleton(sp => BuildCoordinator(sp.GetRequiredService())) + .AddSingleton() + .BuildServiceProvider(); + + _session = _services.GetRequiredService(); + _plc = _services.GetRequiredService(); + _plc.Initialize(); + _session.Reset(); + _subscription = _plc.PlcState.Subscribe(snapshot => _statuses.Enqueue(snapshot.SyncStatus)); + } + + public async ValueTask DisposeAsync() + { + _subscription?.Dispose(); + _plc.Dispose(); + await _services.DisposeAsync(); + } + + [Fact] + public async Task EditDuringTheConnect_WritesNothingBeforeTheComparison() + { + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: false, RecipeLines: 0); + _s7Service.RaiseConnectedDuringConnect = true; + var connectGate = new ReadGate(); + _s7Service.ConnectGate = connectGate; + var comparisonGate = new ReadGate(); + _s7Service.ManagingAreaReadGate = comparisonGate; + + var enable = _plc.EnableSync(_configuration.PlcConfiguration); + await connectGate.Entered.WaitAsync(TestToken); + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + await Task.Delay(_quietPeriod, TestToken); + connectGate.Release(); + (await enable).IsSuccess.Should().BeTrue(); + await comparisonGate.Entered.WaitAsync(TestToken); + await Task.Delay(_quietPeriod, TestToken); + + _statuses.Should().NotContain(PlcSyncStatus.Syncing, "the comparison has not decided yet"); + + comparisonGate.Release(); + await WaitForPlcToHoldTheScreenRecipeAsync(); + } + + [Fact] + public async Task ReconnectInsideTheDebounce_WritesNothingBeforeTheComparison() + { + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: false, RecipeLines: 0); + (await _plc.EnableSync(_configuration.PlcConfiguration)).IsSuccess.Should().BeTrue(); + _s7Service.RaiseStateChanged(PlcConnectionState.Connected); + await WaitForPlcToHoldTheScreenRecipeAsync(); + var writesBefore = _statuses.Count(status => status == PlcSyncStatus.Syncing); + + _s7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + var comparisonGate = new ReadGate(); + _s7Service.ManagingAreaReadGate = comparisonGate; + _s7Service.RaiseStateChanged(PlcConnectionState.Connected); + await comparisonGate.Entered.WaitAsync(TestToken); + await Task.Delay(_quietPeriod, TestToken); + + _statuses.Count(status => status == PlcSyncStatus.Syncing).Should().Be(writesBefore, + "the edit made during the outage waits for the comparison of the reconnect"); + + comparisonGate.Release(); + await WaitForPlcToHoldTheScreenRecipeAsync(writesBefore); + } + + [Fact] + public async Task NewDuringThePause_IsNotWritten_AndThePlcRecipeReplacesIt() + { + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + var plcRecipe = RecipeStubs.WithSteps(WaitActionId, 2); + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 2); + _s7Service.RecipeToReturn = plcRecipe; + _plc.RegisterReconnectApplyCallback(recipe => Task.FromResult(_plc.ApplyRecipeFromPlc(recipe).ToResult())); + (await _plc.EnableSync(_configuration.PlcConfiguration)).IsSuccess.Should().BeTrue(); + var comparisonGate = new ReadGate(); + _s7Service.ManagingAreaReadGate = comparisonGate; + _s7Service.RaiseStateChanged(PlcConnectionState.Connected); + await comparisonGate.Entered.WaitAsync(TestToken); + + _session.Reset().IsSuccess.Should().BeTrue(); + await Task.Delay(_quietPeriod, TestToken); + comparisonGate.Release(); + await TestHelpers.WaitUntilAsync( + () => _session.Current.StepCount == plcRecipe.StepCount, + _syncTimeout, + _pollInterval, + TestToken); + await Task.Delay(_quietPeriod, TestToken); + + _statuses.Should().NotContain(PlcSyncStatus.Syncing, "neither the new recipe nor the taken one is written"); + } + + private async Task WaitForPlcToHoldTheScreenRecipeAsync(int writesBefore = 0) + { + await TestHelpers.WaitUntilAsync( + () => _statuses.Count(status => status == PlcSyncStatus.Syncing) > writesBefore + && _plc.SyncStatus == PlcSyncStatus.Synced, + _syncTimeout, + _pollInterval, + TestToken); + + var written = await _executor.ReadRecipeFromPlcAsync(TestToken); + written.IsSuccess.Should().BeTrue(); + written.Value.Should().Be(_session.Current, "the pause ends with a write of the newest screen recipe"); + } + + private PlcSyncCoordinator BuildCoordinator(RecipeMetadataRegistry registry) + { + var plcConfiguration = _configuration.PlcConfiguration; + var layout = plcConfiguration.Layout; + var arrayCodec = new ArrayCodec(layout.IntDb, layout.FloatDb, layout.StringDb, registry.GetStringMaxLength()); + _executor = new PlcTransactionExecutor( + _transport, + new RecipeConverter(registry), + arrayCodec, + plcConfiguration, + NullLogger.Instance); + + return new PlcSyncCoordinator(_executor, _s7Service, _s7Service, NullLoggerFactory.Instance); + } +} diff --git a/SemiStep/SemiStep.Tests/Domain/PlcWritePauseTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcWritePauseTests.cs new file mode 100644 index 00000000..8e2e6202 --- /dev/null +++ b/SemiStep/SemiStep.Tests/Domain/PlcWritePauseTests.cs @@ -0,0 +1,578 @@ +using System.Collections.Concurrent; + +using AwesomeAssertions; + +using FluentResults; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using SemiStep.Core.Configuration.Facade; +using SemiStep.Core.Plc; +using SemiStep.Core.Plc.Configuration; +using SemiStep.Core.Plc.S7.Protocol; +using SemiStep.Core.Plc.State; +using SemiStep.Core.Plc.Sync; +using SemiStep.Core.Plc.Sync.Ownership; +using SemiStep.Core.Recipes; +using SemiStep.Core.Recipes.Clipboard; +using SemiStep.Core.Recipes.Import; +using SemiStep.Tests.Helpers; + +using Xunit; + +namespace SemiStep.Tests.Domain; + +/// Which end of the write pause each comparison outcome picks, and which comparison IDs still count. +[Trait("Component", "Domain")] +[Trait("Area", "WritePause")] +[Trait("Category", "Integration")] +public sealed class PlcWritePauseTests : IAsyncLifetime +{ + private const int WaitActionId = 10; + + public enum ComparisonFailure + { + VersionRead, + ManagingAreaRead, + RecipeRead, + Throws + } + + private readonly StubS7Service _s7Service = new(); + private readonly StubPlcSyncService _syncService = new(); + private readonly ConcurrentQueue _turnOffReasons = new(); + private readonly ConcurrentQueue _conflicts = new(); + private readonly RecordingLogger _logger = new(); + private ServiceProvider _services = null!; + private PlcLifecycleManager _plc = null!; + private RecipeSession _session = null!; + private IDisposable? _turnOffSubscription; + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + public async ValueTask InitializeAsync() + { + var loaded = await ConfigFacade.LoadAndValidateAsync(TestConfigLocator.GetConfigDirectory("Standard")); + _services = new ServiceCollection() + .AddLogging() + .AddSingleton>(_logger) + .AddSingleton(loaded.Value) + .AddRecipe() + .AddCsv() + .AddClipboard() + .AddSingleton(_s7Service) + .AddSingleton(_s7Service) + .AddSingleton(_s7Service) + .AddSingleton(_syncService) + .AddSingleton() + .BuildServiceProvider(); + + _session = _services.GetRequiredService(); + _plc = _services.GetRequiredService(); + _plc.Initialize(); + _session.Reset(); + _plc.PlcRecipeConflictDetected += _conflicts.Enqueue; + _turnOffSubscription = _plc.SyncTurnOffs.Subscribe(_turnOffReasons.Enqueue); + } + + public async ValueTask DisposeAsync() + { + _turnOffSubscription?.Dispose(); + _plc.Dispose(); + _s7Service.Dispose(); + await _services.DisposeAsync(); + } + + [Fact] + public async Task SyncOn_StartsAWritePause() + { + await EnableAsync(); + + _syncService.IsWritePaused.Should().BeTrue(); + _syncService.WritePauseEnds.Should().BeEmpty("no comparison ran yet"); + } + + [Fact] + public async Task LinkDrop_StartsAWritePause() + { + await EnableAsync(); + _syncService.EndWritePauseWithoutWrite(); + + _s7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + + _syncService.IsWritePaused.Should().BeTrue(); + } + + [Theory] + [InlineData(false, 0)] + [InlineData(true, 0)] + [InlineData(true, -1)] + public async Task Comparison_PlcUncommittedEmptyOrIdentical_EndsThePauseWithAWrite(bool committed, int plcSteps) + { + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(committed, RecipeLines: 1); + _s7Service.RecipeToReturn = plcSteps < 0 ? RecipeStubs.DeepCopy(_session.Current) : Recipe.Empty; + await EnableAsync(); + + await CompareAsync(() => _syncService.WritePauseEnds.Count > 0); + + _syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeSameAs(_session.Current); + _syncService.IsWritePaused.Should().BeFalse(); + } + + [Fact] + public async Task Comparison_RecipesDiffer_RaisesAConflict_AndKeepsThePause() + { + ArrangeConflict(); + await EnableAsync(); + + await CompareAsync(() => !_conflicts.IsEmpty); + + _syncService.IsWritePaused.Should().BeTrue(); + _syncService.WritePauseEnds.Should().BeEmpty(); + } + + [Fact] + public async Task ReconnectTake_EndsThePauseWithoutAWrite() + { + var plcRecipe = ArrangeReconnectTake(); + _plc.RegisterReconnectApplyCallback(recipe => Task.FromResult(_plc.ApplyRecipeFromPlc(recipe).ToResult())); + await EnableAsync(); + + await CompareAsync(() => _syncService.WritePauseEnds.Count > 0); + + _syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeNull(); + _session.Current.StepCount.Should().Be(plcRecipe.StepCount); + _plc.IsSyncEnabled.Should().BeTrue(); + } + + [Fact] + public async Task ReconnectTake_FailingTheCheck_TurnsSyncOff() + { + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 5); + _s7Service.RecipeToReturn = RecipeStubs.LoopsNestedDeeperThanLimit(); + _plc.RegisterReconnectApplyCallback(recipe => Task.FromResult(_plc.ApplyRecipeFromPlc(recipe).ToResult())); + await EnableAsync(); + + await CompareAsync(() => !_plc.IsSyncEnabled); + + await WaitAsync(() => !_turnOffReasons.IsEmpty); + _turnOffReasons.OfType().Should().ContainSingle(); + _syncService.WritePauseEnds.Should().BeEmpty(); + _session.Current.StepCount.Should().Be(0); + } + + [Fact] + public async Task ReconnectTake_CallbackThatThrows_TurnsSyncOff() + { + ArrangeReconnectTake(); + _plc.RegisterReconnectApplyCallback(_ => throw new InvalidOperationException("apply blew up")); + await EnableAsync(); + + await CompareAsync(() => !_plc.IsSyncEnabled); + + await WaitAsync(() => !_turnOffReasons.IsEmpty); + _turnOffReasons.OfType().Should().ContainSingle(); + } + + [Theory] + [InlineData(ComparisonFailure.VersionRead)] + [InlineData(ComparisonFailure.ManagingAreaRead)] + [InlineData(ComparisonFailure.RecipeRead)] + [InlineData(ComparisonFailure.Throws)] + public async Task Comparison_ReadThatFailsOrThrows_DeclaresLinkLoss_AndKeepsThePause(ComparisonFailure failure) + { + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + await EnableAsync(); + ArrangeFailure(failure); + + await CompareAsync(() => _s7Service.DeclareLinkLostCallCount > 0); + + _s7Service.DeclareLinkLostCallCount.Should().Be(1); + _syncService.WritePauseEnds.Should().BeEmpty("nothing is written after a failed read"); + _syncService.IsWritePaused.Should().BeTrue(); + _plc.IsSyncEnabled.Should().BeTrue(); + } + + [Fact] + public async Task ThreeFailedComparisonsInARow_TurnSyncOff() + { + await EnableAsync(); + + for (var attempt = 1; attempt <= PlcLifecycleManager.FailedComparisonLimit; attempt++) + { + await CompareAsync(() => _s7Service.DeclareLinkLostCallCount == attempt || !_plc.IsSyncEnabled); + } + + await WaitAsync(() => !_plc.IsSyncEnabled && !_turnOffReasons.IsEmpty); + _turnOffReasons.OfType().Should().ContainSingle(); + _s7Service.DeclareLinkLostCallCount.Should().Be(PlcLifecycleManager.FailedComparisonLimit - 1, + "the third failure turns sync off instead of reconnecting"); + } + + [Fact] + public async Task TwoFailures_ThenADecision_ResetTheCount() + { + await EnableAsync(); + await CompareAsync(() => _s7Service.DeclareLinkLostCallCount == 1); + await CompareAsync(() => _s7Service.DeclareLinkLostCallCount == 2); + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: false, RecipeLines: 0); + await CompareAsync(() => _syncService.WritePauseEnds.Count == 1); + _s7Service.ManagingAreaToReturn = null; + + await CompareAsync(() => _s7Service.DeclareLinkLostCallCount == 3); + await CompareAsync(() => _s7Service.DeclareLinkLostCallCount == 4); + + _plc.IsSyncEnabled.Should().BeTrue(); + } + + [Fact] + public async Task LinkDropBeforeTheFailedRead_CountsTheComparisonOnce() + { + await EnableAsync(); + await CompareAsync(() => _s7Service.DeclareLinkLostCallCount == 1); + await CompareAsync(() => _s7Service.DeclareLinkLostCallCount == 2); + + // The third comparison is cut by a drop that arrives before its failed read returns, as the + // transport deadline does on another thread. + var gate = new ReadGate(); + _s7Service.ManagingAreaReadGate = gate; + _s7Service.RaiseStateChanged(PlcConnectionState.Connected); + await gate.Entered.WaitAsync(TestToken); + _s7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + gate.Release(); + + await WaitAsync(() => !_plc.IsSyncEnabled); + _turnOffReasons.OfType().Should().ContainSingle(); + _s7Service.DeclareLinkLostCallCount.Should().Be(2, "the late failed read is stale and closes nothing"); + } + + [Fact] + public async Task VersionMismatchOnReconnect_TurnsSyncOff_WithTheVersionMessage() + { + await EnableAsync(); + _s7Service.ProtocolVersionToReturn = Result.Ok(ProtocolConstants.ProtocolVersion + 1); + + await CompareAsync(() => !_plc.IsSyncEnabled); + + await WaitAsync(() => !_turnOffReasons.IsEmpty); + _turnOffReasons.OfType().Should().ContainSingle(); + _s7Service.ReadManagingAreaCallCount.Should().Be(0); + _syncService.WritePauseEnds.Should().BeEmpty(); + _s7Service.DeclareLinkLostCallCount.Should().Be(0, "a mismatch is not a link loss"); + } + + [Fact] + public async Task FirstConnectComparison_RunsAfterTheEnableVersionRead_AndSkipsItsOwn() + { + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: false, RecipeLines: 0); + _s7Service.RaiseConnectedDuringConnect = true; + + await EnableAsync(); + await WaitAsync(() => _syncService.WritePauseEnds.Count > 0); + + _s7Service.ReadProtocolVersionCallCount.Should().Be(1, "the comparison reuses the enable version read"); + } + + [Fact] + public async Task ResultOfAComparisonCutByALinkDrop_IsIgnored() + { + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: false, RecipeLines: 0); + await EnableAsync(); + var gate = new ReadGate(); + _s7Service.ManagingAreaReadGate = gate; + + _s7Service.RaiseStateChanged(PlcConnectionState.Connected); + await gate.Entered.WaitAsync(TestToken); + _s7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + gate.Release(); + await WaitForOutcomeAsync(PlcReconciliationOutcome.Stale); + + _syncService.WritePauseEnds.Should().BeEmpty("the drop made the comparison stale"); + _syncService.IsWritePaused.Should().BeTrue(); + } + + [Fact] + public async Task AnswerToAConflictANewerComparisonReplaced_WritesNothing() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => _conflicts.Count == 1); + await CompareAsync(() => _conflicts.Count == 2); + var stale = _conflicts.First(); + + var result = _plc.ResolveConflict(stale.ComparisonId, PlcConflictAnswer.KeepLocal); + + result.Value.Should().BeFalse(); + _syncService.WritePauseEnds.Should().BeEmpty(); + _plc.ResolveConflict(_conflicts.Last().ComparisonId, PlcConflictAnswer.KeepLocal).IsSuccess.Should().BeTrue(); + _syncService.WritePauseEnds.Should().ContainSingle("the current conflict still takes its answer"); + } + + [Fact] + public async Task AnswerToAConflict_CountsOnce() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + var conflict = _conflicts.Single(); + + _plc.ResolveConflict(conflict.ComparisonId, PlcConflictAnswer.KeepLocal); + _plc.ResolveConflict(conflict.ComparisonId, PlcConflictAnswer.Dismissed); + + _syncService.WritePauseEnds.Should().ContainSingle(); + _logger.Snapshot().Should().ContainSingle(entry => entry.Message.Contains("Dismissed ignored"), + "the second answer found no conflict to end, so it posted no turn-off"); + } + + [Fact] + public async Task KeepLocal_EndsThePauseWithAWrite() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + + _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal).IsSuccess.Should().BeTrue(); + + _syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeSameAs(_session.Current); + } + + [Fact] + public async Task TakePlc_FailingTheCheck_TurnsSyncOff() + { + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 5); + _s7Service.RecipeToReturn = RecipeStubs.LoopsNestedDeeperThanLimit(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + + var result = _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.TakePlc); + + result.IsFailed.Should().BeTrue(); + await WaitAsync(() => !_plc.IsSyncEnabled && !_turnOffReasons.IsEmpty); + _turnOffReasons.OfType().Should().ContainSingle(); + _syncService.WritePauseEnds.Should().BeEmpty(); + } + + [Theory] + [InlineData(PlcConflictAnswer.Dismissed)] + [InlineData(PlcConflictAnswer.DialogShowFailed)] + public async Task ConflictEndedWithoutAChoice_TurnsSyncOff(PlcConflictAnswer answer) + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + + _plc.ResolveConflict(_conflicts.Single().ComparisonId, answer).IsSuccess.Should().BeTrue(); + + await WaitAsync(() => !_plc.IsSyncEnabled && !_turnOffReasons.IsEmpty); + _turnOffReasons.OfType().Should().ContainSingle() + .Which.DialogShowFailed.Should().Be(answer == PlcConflictAnswer.DialogShowFailed); + _syncService.WritePauseEnds.Should().BeEmpty(); + } + + [Fact] + public async Task SwitchPressedOnDuringAnAppTurnOff_ActsAfterIt() + { + var pendingWrite = await HoldAnAppTurnOffAsync(); + + var enable = _plc.EnableSync(PlcConfiguration.Default); + enable.IsCompleted.Should().BeFalse("sync on waits for the turn-off in progress"); + + pendingWrite.SetResult(); + (await enable.WaitAsync(TimeSpan.FromSeconds(10), TestToken)).IsSuccess.Should().BeTrue(); + + _plc.IsSyncEnabled.Should().BeTrue("the press acted after the app turned sync off"); + _turnOffReasons.OfType().Should().ContainSingle(); + _s7Service.ConnectCallCount.Should().Be(2); + } + + [Fact] + public async Task SwitchPressedOffDuringAnAppTurnOff_FindsSyncOff_AndDoesNothing() + { + var pendingWrite = await HoldAnAppTurnOffAsync(); + + var disable = _plc.DisableSync(); + pendingWrite.SetResult(); + await disable.WaitAsync(TimeSpan.FromSeconds(10), TestToken); + + _plc.IsSyncEnabled.Should().BeFalse(); + _s7Service.DisconnectCallCount.Should().Be(1, "only the app turn-off disconnected"); + } + + [Fact] + public async Task ConnectedRaisedAsSyncTurnsOff_StartsNoComparison() + { + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: false, RecipeLines: 0); + await EnableAsync(); + Task? disable = null; + _syncService.OnNextIsSyncEnabledRead = () => disable = _plc.DisableSync(); + + _s7Service.RaiseStateChanged(PlcConnectionState.Connected); + await disable!.WaitAsync(TestToken); + + _s7Service.ReadManagingAreaCallCount.Should().Be(0, "no comparison starts after sync off"); + _syncService.WritePauseEnds.Should().BeEmpty(); + _conflicts.Should().BeEmpty(); + } + + [Fact] + public async Task SyncOff_MakesARunningComparisonStale() + { + await EnableAsync(); + var gate = new ReadGate(); + _s7Service.ManagingAreaReadGate = gate; + _s7Service.RaiseStateChanged(PlcConnectionState.Connected); + await gate.Entered.WaitAsync(TestToken); + + await _plc.DisableSync(); + gate.Release(); + await WaitForOutcomeAsync(PlcReconciliationOutcome.Stale); + + _s7Service.DeclareLinkLostCallCount.Should().Be(0, "a stale failed read closes nothing"); + _syncService.WritePauseEnds.Should().BeEmpty(); + } + + [Fact] + public async Task AnswerClickedBeforeALinkDrop_WritesNothing() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + + _s7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + var result = _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal); + + result.Value.Should().BeFalse(); + _syncService.WritePauseEnds.Should().BeEmpty(); + _syncService.IsWritePaused.Should().BeTrue(); + } + + [Fact] + public async Task ConflictHandlerThatThrows_TurnsSyncOff_AsADialogNotShown() + { + ArrangeConflict(); + _plc.PlcRecipeConflictDetected += _ => throw new InvalidOperationException("dialog wiring failed"); + await EnableAsync(); + + await CompareAsync(() => !_plc.IsSyncEnabled && !_turnOffReasons.IsEmpty); + + _turnOffReasons.OfType().Should().ContainSingle() + .Which.DialogShowFailed.Should().BeTrue(); + _syncService.WritePauseEnds.Should().BeEmpty(); + } + + [Fact] + public async Task TakePlc_ThatThrows_TurnsSyncOff() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + _syncService.OnNextNotifyRecipeChanged = () => throw new InvalidOperationException("sync notify failed"); + + var answer = () => _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.TakePlc); + + answer.Should().NotThrow().Which.IsFailed.Should().BeTrue(); + await WaitAsync(() => !_plc.IsSyncEnabled && !_turnOffReasons.IsEmpty); + _turnOffReasons.OfType().Should().ContainSingle(); + } + + [Fact] + public async Task ReconnectTake_AfterOpenLandedBeforeIt_RaisesTheConflictInstead() + { + var plcRecipe = ArrangeReconnectTake(); + var openedRecipe = RecipeStubs.WithSteps(WaitActionId, 1); + _plc.RegisterReconnectApplyCallback(recipe => + { + _session.LoadAsCurrent(openedRecipe).IsSuccess.Should().BeTrue(); + _session.MarkSaved(); + return Task.FromResult(_plc.ApplyRecipeFromPlc(recipe).ToResult()); + }); + await EnableAsync(); + + await CompareAsync(() => !_conflicts.IsEmpty); + await WaitForOutcomeAsync(PlcReconciliationOutcome.ConflictRaised); + + _conflicts.Single().Plc.Should().BeSameAs(plcRecipe); + _session.Current.StepCount.Should().Be(1, "the opened recipe stays"); + _syncService.WritePauseEnds.Should().BeEmpty(); + _plc.IsSyncEnabled.Should().BeTrue(); + _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal).IsSuccess.Should().BeTrue(); + _syncService.WritePauseEnds.Should().ContainSingle("the conflict takes its answer"); + } + + /// Dismisses a conflict, so the app turns sync off, and holds that turn-off at its wait for a write. + private async Task HoldAnAppTurnOffAsync() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + var pendingWrite = new TaskCompletionSource(); + _syncService.PendingSync = pendingWrite.Task; + _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.Dismissed); + await WaitAsync(() => !_plc.IsSyncEnabled); + + return pendingWrite; + } + + private void ArrangeConflict() + { + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 1); + _s7Service.RecipeToReturn = RecipeStubs.WithSteps(WaitActionId, 1); + } + + private Recipe ArrangeReconnectTake() + { + var plcRecipe = RecipeStubs.WithSteps(WaitActionId, 2); + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 2); + _s7Service.RecipeToReturn = plcRecipe; + + return plcRecipe; + } + + private void ArrangeFailure(ComparisonFailure failure) + { + switch (failure) + { + case ComparisonFailure.VersionRead: + _s7Service.ProtocolVersionToReturn = Result.Fail("version read failed"); + break; + case ComparisonFailure.ManagingAreaRead: + break; + case ComparisonFailure.RecipeRead: + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 1); + break; + case ComparisonFailure.Throws: + _s7Service.ManagingAreaReadException = new InvalidOperationException("comparison blew up"); + break; + default: + throw new ArgumentOutOfRangeException(nameof(failure), failure, "Not a failed read"); + } + } + + private async Task EnableAsync() + { + (await _plc.EnableSync(PlcConfiguration.Default)).IsSuccess.Should().BeTrue(); + } + + private async Task CompareAsync(Func until) + { + _s7Service.RaiseStateChanged(PlcConnectionState.Connected); + await WaitAsync(until); + } + + private Task WaitForOutcomeAsync(PlcReconciliationOutcome outcome) + { + return WaitAsync(() => _logger.Snapshot().Any(entry => + entry.Message.StartsWith(PlcLifecycleManager.ReconciliationOutcomePrefix, StringComparison.Ordinal) + && outcome.Equals(entry.Properties.GetValueOrDefault(nameof(PlcReconciliationResult.Outcome))))); + } + + private static Task WaitAsync(Func predicate) + { + return TestHelpers.WaitUntilAsync(predicate, TestToken); + } +} diff --git a/SemiStep/SemiStep.Tests/Helpers/StubPlcSyncService.cs b/SemiStep/SemiStep.Tests/Helpers/StubPlcSyncService.cs index f2e3cfe4..84a8acb0 100644 --- a/SemiStep/SemiStep.Tests/Helpers/StubPlcSyncService.cs +++ b/SemiStep/SemiStep.Tests/Helpers/StubPlcSyncService.cs @@ -14,7 +14,26 @@ public sealed class StubPlcSyncService : IPlcSyncService, IDisposable PlcSessionSnapshot.InitialState); private readonly Subject _faultsSubject = new(); - public bool IsSyncEnabled { get; private set; } + /// + /// Reads the flag first and then runs , so a test can turn sync off between + /// a caller's check and its next step. + /// + public bool IsSyncEnabled + { + get + { + var isSyncEnabled = field; + var hook = OnNextIsSyncEnabledRead; + OnNextIsSyncEnabledRead = null; + hook?.Invoke(); + + return isSyncEnabled; + } + private set; + } + + /// Runs once, inside the next read of , and is then cleared. + public Action? OnNextIsSyncEnabledRead { get; set; } public PlcSyncStatus Status { get; set; } = PlcSyncStatus.Idle; @@ -44,6 +63,18 @@ public sealed class StubPlcSyncService : IPlcSyncService, IDisposable public Task PendingSync { get; set; } = Task.CompletedTask; + /// True from sync on or a link loss until a call ends the write pause. + public bool IsWritePaused { get; private set; } + + /// + /// Calls that ended the write pause, in order: the recipe passed and its validity for a pause that ends with a + /// write, null for one that ends without a write. + /// + public List<(Recipe? Recipe, bool IsValid)> WritePauseEnds { get; } = []; + + /// Runs once, at the end of the next call, and is then cleared. + public Action? OnNextWritePauseEnd { get; set; } + /// Pushes a new PLC state snapshot to subscribers of . public void PushPlcState(PlcSessionSnapshot state) { @@ -79,11 +110,29 @@ public void ResetForDisable() public void HandleConnectionLost() { WasHandleConnectionLostCalled = true; + IsWritePaused = true; + } + + public void EndWritePause(Recipe screenRecipe, bool isValid) + { + IsWritePaused = false; + WritePauseEnds.Add((screenRecipe, isValid)); + + var hook = OnNextWritePauseEnd; + OnNextWritePauseEnd = null; + hook?.Invoke(); + } + + public void EndWritePauseWithoutWrite() + { + IsWritePaused = false; + WritePauseEnds.Add((null, false)); } public void SetSyncEnabled(bool value) { IsSyncEnabled = value; + IsWritePaused = value; } public void UpdateConnectionState(PlcConnectionState state) diff --git a/SemiStep/SemiStep.Tests/Helpers/StubS7Service.cs b/SemiStep/SemiStep.Tests/Helpers/StubS7Service.cs index ae7ed111..cadbc328 100644 --- a/SemiStep/SemiStep.Tests/Helpers/StubS7Service.cs +++ b/SemiStep/SemiStep.Tests/Helpers/StubS7Service.cs @@ -83,6 +83,21 @@ public void PushExecutionState(PlcExecutionInfo info) /// public ReadGate? ProtocolVersionReadGate { get; set; } + /// When set, awaits this gate before it reports the connect. + public ReadGate? ConnectGate { get; set; } + + /// When set, throws it, standing in for a comparison that throws. + public Exception? ManagingAreaReadException { get; set; } + + /// Number of times was called. + public int DeclareLinkLostCallCount { get; private set; } + + /// + /// When true (the default), raises with + /// , as the real link-loss path does. + /// + public bool RaiseDisconnectedOnLinkLoss { get; set; } = true; + /// Raises with the given state. public void RaiseStateChanged(PlcConnectionState state) { @@ -92,10 +107,15 @@ public void RaiseStateChanged(PlcConnectionState state) /// Number of times was called. public int ConnectCallCount { get; private set; } - public Task ConnectAsync(PlcConnectionSettings settings) + public async Task ConnectAsync(PlcConnectionSettings settings) { ConnectCallCount++; + if (ConnectGate is not null) + { + await ConnectGate.WaitAsync(CancellationToken.None); + } + if (ConnectShouldFail) { throw new InvalidOperationException("Stub PLC connection failure"); @@ -105,8 +125,16 @@ public Task ConnectAsync(PlcConnectionSettings settings) { StateChanged?.Invoke(PlcConnectionState.Connected); } + } - return Task.CompletedTask; + public void DeclareLinkLost() + { + DeclareLinkLostCallCount++; + + if (RaiseDisconnectedOnLinkLoss) + { + StateChanged?.Invoke(PlcConnectionState.Disconnected); + } } /// Number of times was called. @@ -143,6 +171,11 @@ public Task> ReadManagingAreaAsync(CancellationToke ReadManagingAreaCallCount++; + if (ManagingAreaReadException is not null) + { + throw ManagingAreaReadException; + } + return ManagingAreaReadGate is not null ? GateThenReadManagingAreaAsync(ManagingAreaReadGate, ct) : Task.FromResult(BuildManagingAreaResult()); @@ -171,10 +204,15 @@ public Task> ReadRecipeFromPlcAsync(CancellationToken ct = defaul : Task.FromResult(Result.Fail("Not connected")); } + /// Number of times was called. + public int ReadProtocolVersionCallCount { get; private set; } + public Task> ReadProtocolVersionAsync(CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); + ReadProtocolVersionCallCount++; + return ProtocolVersionReadShouldThrowCanceled ? throw new TaskCanceledException("Stub protocol version read timed out") : ProtocolVersionReadGate is not null diff --git a/SemiStep/SemiStep.Tests/S7/Helpers/FakeS7Driver.cs b/SemiStep/SemiStep.Tests/S7/Helpers/FakeS7Driver.cs index 5624f4df..c72afda9 100644 --- a/SemiStep/SemiStep.Tests/S7/Helpers/FakeS7Driver.cs +++ b/SemiStep/SemiStep.Tests/S7/Helpers/FakeS7Driver.cs @@ -65,10 +65,13 @@ public Task ConnectAsync(PlcConnectionSettings settings) return Task.CompletedTask; } + /// When set, throws it after it marks the driver disconnected. + public Exception? DisconnectException { get; set; } + public Task DisconnectAsync() { IsConnected = false; - return Task.CompletedTask; + return DisconnectException is { } exception ? Task.FromException(exception) : Task.CompletedTask; } public ValueTask DisposeAsync() diff --git a/SemiStep/SemiStep.Tests/S7/Helpers/StubS7ServiceForSync.cs b/SemiStep/SemiStep.Tests/S7/Helpers/StubS7ServiceForSync.cs index d4d1a291..fd65532c 100644 --- a/SemiStep/SemiStep.Tests/S7/Helpers/StubS7ServiceForSync.cs +++ b/SemiStep/SemiStep.Tests/S7/Helpers/StubS7ServiceForSync.cs @@ -44,6 +44,10 @@ public Task DisconnectAsync() return Task.CompletedTask; } + public void DeclareLinkLost() + { + } + public ValueTask DisposeAsync() { _executionState.Dispose(); diff --git a/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorInterleavingTests.cs b/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorInterleavingTests.cs index a8bcf77a..2da521d0 100644 --- a/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorInterleavingTests.cs +++ b/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorInterleavingTests.cs @@ -156,6 +156,7 @@ public async Task RecipeQueuedAfterResetDuringHeldWrite_StartsSecondTransactionA { var (coordinator, transport, hold) = BuildHeld(); coordinator.SetSyncEnabled(true); + coordinator.EndWritePauseWithoutWrite(); coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); await hold.Reached.WaitAsync(_waitTimeout, TestToken); @@ -163,6 +164,7 @@ public async Task RecipeQueuedAfterResetDuringHeldWrite_StartsSecondTransactionA coordinator.SetSyncEnabled(false); coordinator.ResetForDisable(); coordinator.SetSyncEnabled(true); + coordinator.EndWritePauseWithoutWrite(); coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); hold.Release(); diff --git a/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorTests.cs b/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorTests.cs index 5a43e8fa..f719ba72 100644 --- a/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorTests.cs +++ b/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorTests.cs @@ -58,6 +58,10 @@ internal static ( var coordinator = new PlcSyncCoordinator( executor, connectionService, connectionService, loggerFactory ?? NullLoggerFactory.Instance); + // Sync on with the comparison already decided, so an edit writes as in a running session. + coordinator.SetSyncEnabled(true); + coordinator.EndWritePauseWithoutWrite(); + return (coordinator, transport, connectionService); } diff --git a/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorWritePauseTests.cs b/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorWritePauseTests.cs new file mode 100644 index 00000000..9f1ba21c --- /dev/null +++ b/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorWritePauseTests.cs @@ -0,0 +1,136 @@ +using AwesomeAssertions; + +using SemiStep.Core.Plc.State; +using SemiStep.Core.Recipes; +using SemiStep.Tests.Helpers; +using SemiStep.Tests.S7.Helpers; + +using Xunit; + +namespace SemiStep.Tests.S7; + +[Trait("Component", "S7")] +[Trait("Area", "WritePause")] +[Trait("Category", "Unit")] +public sealed class PlcSyncCoordinatorWritePauseTests +{ + private const int LastReadOfTransaction = 2; + + private static readonly TimeSpan _waitTimeout = TimeSpan.FromSeconds(5); + private static readonly TimeSpan _pollInterval = TimeSpan.FromMilliseconds(20); + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task SyncOn_HoldsANotifiedRecipe_UntilThePauseEndsWithAWrite() + { + var (coordinator, transport, _) = PlcSyncCoordinatorTests.Build(connected: true); + coordinator.SetSyncEnabled(true); + + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + await coordinator.WaitForPendingSyncAsync(TestToken); + transport.WriteLog.Should().BeEmpty("sync on starts a write pause"); + + coordinator.EndWritePause(Recipe.Empty, isValid: true); + + await WaitForAsync(() => coordinator.Status == PlcSyncStatus.Synced); + transport.WriteLog.Should().NotBeEmpty(); + } + + [Fact] + public async Task EndWritePause_WithNothingNotified_WritesTheScreenRecipe() + { + var (coordinator, transport, _) = PlcSyncCoordinatorTests.Build(connected: true); + coordinator.SetSyncEnabled(true); + + coordinator.EndWritePause(Recipe.Empty, isValid: true); + + await WaitForAsync(() => coordinator.Status == PlcSyncStatus.Synced); + transport.WriteLog.Should().NotBeEmpty(); + } + + [Fact] + public async Task LinkLoss_DropsTheDebouncedWrite_AndHoldsEditsAfterIt() + { + var (coordinator, transport, _) = PlcSyncCoordinatorTests.Build(connected: true); + + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + coordinator.HandleConnectionLost(); + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + await coordinator.WaitForPendingSyncAsync(TestToken); + + transport.WriteLog.Should().BeEmpty("the link loss starts a write pause"); + } + + [Fact] + public async Task WriteInFlightAtLinkLoss_EndsWithItsTokenCancelled_AndStartsNoOtherWrite() + { + var (coordinator, transport, _) = PlcSyncCoordinatorTests.Build(connected: true); + var hold = new TransportHold( + PlcSyncCoordinatorTests.BuildTestConfiguration().Layout.StringDb.DbNumber, + LastReadOfTransaction, + TaskCreationOptions.RunContinuationsAsynchronously); + transport.BeforeRead = hold.OnCall; + + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + await hold.Reached.WaitAsync(_waitTimeout, TestToken); + var transactionWrites = transport.WriteLog.Count; + coordinator.HandleConnectionLost(); + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + + hold.HeldToken.IsCancellationRequested.Should().BeTrue("the link loss cancels the token of the write in flight"); + hold.Release(); + await coordinator.WaitForPendingSyncAsync(TestToken); + await coordinator.WaitForPendingSyncAsync(TestToken); + + transport.WriteLog.Should().HaveCount(transactionWrites, "the edit made during the pause waits for its end"); + } + + [Fact] + public async Task EndWritePause_WithARecipeThatHasWarnings_WritesNothing() + { + var (coordinator, transport, _) = PlcSyncCoordinatorTests.Build(connected: true); + coordinator.SetSyncEnabled(true); + + coordinator.EndWritePause(Recipe.Empty, isValid: false); + await coordinator.WaitForPendingSyncAsync(TestToken); + + transport.WriteLog.Should().BeEmpty(); + coordinator.Status.Should().Be(PlcSyncStatus.OutOfSync); + } + + [Fact] + public async Task EndWritePauseWithoutWrite_DropsTheHeldRecipe_AndLetsTheNextEditWrite() + { + var (coordinator, transport, _) = PlcSyncCoordinatorTests.Build(connected: true); + coordinator.SetSyncEnabled(true); + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + + coordinator.EndWritePauseWithoutWrite(); + await coordinator.WaitForPendingSyncAsync(TestToken); + transport.WriteLog.Should().BeEmpty("the PLC already holds the screen recipe"); + + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + await WaitForAsync(() => coordinator.Status == PlcSyncStatus.Synced); + transport.WriteLog.Should().NotBeEmpty("the pause has ended"); + } + + [Fact] + public async Task EditAfterSyncOff_StartsNoWrite() + { + var (coordinator, transport, _) = PlcSyncCoordinatorTests.Build(connected: true); + coordinator.SetSyncEnabled(true); + coordinator.EndWritePauseWithoutWrite(); + coordinator.SetSyncEnabled(false); + + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + await coordinator.WaitForPendingSyncAsync(TestToken); + + transport.WriteLog.Should().BeEmpty("an edit that read the flag before an app turn-off must not write after it"); + } + + private static Task WaitForAsync(Func predicate) + { + return TestHelpers.WaitUntilAsync(predicate, _waitTimeout, _pollInterval, TestToken); + } +} diff --git a/SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs b/SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs index 9dde90eb..b03c9438 100644 --- a/SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs +++ b/SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs @@ -114,6 +114,48 @@ await TestHelpers.WaitUntilAsync( await service.DisposeAsync(); } + [Fact] + public async Task DeclareLinkLost_ClosesTheClient_EmitsDisconnected_AndReconnects() + { + var configuration = BuildConfiguration(keepAliveIntervalMs: 100000, pollingIntervalMs: 100000); + var (service, driver) = BuildService(configuration); + var emittedStates = new List(); + service.StateChanged += emittedStates.Add; + await service.ConnectAsync(PlcConnectionSettings.Default); + + service.DeclareLinkLost(); + + await TestHelpers.WaitUntilAsync( + () => emittedStates.Contains(PlcConnectionState.Disconnected), + cancellationToken: TestContext.Current.CancellationToken); + driver.IsConnected.Should().BeFalse("a failed comparison read closes the client, as a passed deadline does"); + await TestHelpers.WaitUntilAsync( + () => driver.ConnectCount >= 2, + cancellationToken: TestContext.Current.CancellationToken); + + await service.DisposeAsync(); + } + + [Fact] + public async Task DeclareLinkLost_WhenTheCloseThrows_StillEmitsDisconnected_AndReconnects() + { + var configuration = BuildConfiguration(keepAliveIntervalMs: 100000, pollingIntervalMs: 100000); + var (service, driver) = BuildService(configuration); + var emittedStates = new List(); + service.StateChanged += emittedStates.Add; + await service.ConnectAsync(PlcConnectionSettings.Default); + driver.DisconnectException = new IOException("close failed"); + + service.DeclareLinkLost(); + + await TestHelpers.WaitUntilAsync( + () => emittedStates.Contains(PlcConnectionState.Disconnected) && driver.ConnectCount >= 2, + cancellationToken: TestContext.Current.CancellationToken); + + driver.DisconnectException = null; + await service.DisposeAsync(); + } + [Fact] public async Task ExecutionMonitorCallback_WhenPlcNotConnected_EmitsDisconnected() { diff --git a/SemiStep/SemiStep.Tests/S7/ShutdownOrderTests.cs b/SemiStep/SemiStep.Tests/S7/ShutdownOrderTests.cs index be474232..a9ff6a9e 100644 --- a/SemiStep/SemiStep.Tests/S7/ShutdownOrderTests.cs +++ b/SemiStep/SemiStep.Tests/S7/ShutdownOrderTests.cs @@ -185,6 +185,11 @@ public Task DisconnectAsync() return service.DisconnectAsync(); } + public void DeclareLinkLost() + { + service.DeclareLinkLost(); + } + public ValueTask DisposeAsync() { throw new InvalidOperationException("connection teardown failure"); diff --git a/SemiStep/SemiStep.Tests/UI/Localization/CoreErrorLocalizationCoverageTests.cs b/SemiStep/SemiStep.Tests/UI/Localization/CoreErrorLocalizationCoverageTests.cs index 756de9be..941674aa 100644 --- a/SemiStep/SemiStep.Tests/UI/Localization/CoreErrorLocalizationCoverageTests.cs +++ b/SemiStep/SemiStep.Tests/UI/Localization/CoreErrorLocalizationCoverageTests.cs @@ -62,6 +62,12 @@ public sealed class CoreErrorLocalizationCoverageTests new WriteVerificationFailedError(3), [typeof(PlcCommandFailedError)] = new PlcCommandFailedError(), + [typeof(ComparisonReadsFailedError)] = + new ComparisonReadsFailedError(), + [typeof(ConflictUnresolvedError)] = + new ConflictUnresolvedError(dialogShowFailed: false), + [typeof(PlcRecipeNotLoadedError)] = + new PlcRecipeNotLoadedError([new Error("x")]), [typeof(OwnedByAnotherInstanceError)] = new OwnedByAnotherInstanceError(new OwnerInfo(1, "MACHINE", "alice", DateTimeOffset.UnixEpoch)), [typeof(FormulaComputationFailedError)] = diff --git a/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowConflictResolutionTests.cs b/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowConflictResolutionTests.cs index 188a45c7..3f3f3559 100644 --- a/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowConflictResolutionTests.cs +++ b/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowConflictResolutionTests.cs @@ -1,8 +1,17 @@ -using Avalonia.Headless.XUnit; +using System.Collections.Concurrent; + +using Avalonia.Headless.XUnit; +using Avalonia.Threading; using AwesomeAssertions; +using FluentResults; + +using SemiStep.Core.Plc.State; +using SemiStep.Core.Plc.Sync; using SemiStep.Core.Recipes; +using SemiStep.Tests.Core.Helpers; +using SemiStep.Tests.Helpers; using SemiStep.Tests.UI.Helpers; using SemiStep.UI.Localization; @@ -13,100 +22,188 @@ namespace SemiStep.Tests.UI.MainWindow; +/// Raises real conflicts through the stub PLC, so every answer carries a live comparison ID. [Trait("Component", "UI")] [Trait("Area", "PlcConflict")] [Trait("Category", "Integration")] public sealed class MainWindowConflictResolutionTests : IAsyncLifetime { private readonly UIFixture _fixture = new(); + private readonly ConcurrentQueue _turnOffReasons = new(); private MainWindowViewModel _viewModel = null!; + private IDisposable? _turnOffSubscription; public async ValueTask InitializeAsync() { await _fixture.InitializeAsync(); + _fixture.SeedRecipe(2); _viewModel = _fixture.CreateMainWindowViewModel(); + _turnOffSubscription = _fixture.Plc.SyncTurnOffs.Subscribe(_turnOffReasons.Enqueue); } public ValueTask DisposeAsync() { + _turnOffSubscription?.Dispose(); _viewModel.Dispose(); return _fixture.DisposeAsync(); } [AvaloniaFact] - public async Task HandleConflict_KeepLocal_ResolvesKeepingLocalRecipe() + public async Task KeepLocal_EndsThePauseWithAWriteOfTheScreenRecipe() { _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(true)); - var callsBefore = _fixture.PlcSyncService.NotifyRecipeChangedCallCount; - await _viewModel.HandleConflictAsync(CurrentRecipe, CurrentRecipe); + await RaiseConflictAsync(); + await WaitUntilAsync(() => _fixture.PlcSyncService.WritePauseEnds.Count > 0); - _fixture.PlcSyncService.NotifyRecipeChangedCallCount.Should().Be( - callsBefore + 1, - "keeping local must resolve the conflict by pushing the local recipe back to the PLC"); - _fixture.MessagePanel.Entries.Should().NotContain( - entry => entry.Severity == MessageSeverity.Error, - "a successful keep-local resolution must not report an error"); + _fixture.PlcSyncService.WritePauseEnds.Should().ContainSingle() + .Which.Recipe.Should().BeSameAs(_fixture.Coordinator.CurrentRecipe); + _fixture.PlcSyncService.IsWritePaused.Should().BeFalse(); + _fixture.Coordinator.IsSyncEnabled.Should().BeTrue(); } [AvaloniaFact] - public async Task HandleConflict_LoadFromPlc_ResolvesLoadingPlcRecipe() + public async Task LoadFromPlc_TakesThePlcRecipe_AndEndsThePauseWithoutAWrite() { _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(false)); - var callsBefore = _fixture.PlcSyncService.NotifyRecipeChangedCallCount; - - await _viewModel.HandleConflictAsync(CurrentRecipe, CurrentRecipe); - - // HandleConflictAsync is driven directly, so no pending PLC recipe was seeded by a real - // conflict; the load branch therefore fails on the missing pending recipe. That failure is - // the faithful observable proof that keepLocal=false reached RecipeCoordinator.ResolveConflict, - // distinct from the keep-local branch which pushes via NotifyRecipeChanged instead. - _fixture.PlcSyncService.NotifyRecipeChangedCallCount.Should().Be( - callsBefore, - "loading from the PLC must not push the local recipe back"); - _fixture.MessagePanel.Entries.Should().Contain( - entry => entry.Severity == MessageSeverity.Error && entry.Message.Contains("pending PLC recipe"), - "the load-from-PLC branch must route through ResolveConflict(false)"); + + var plcRecipe = await RaiseConflictAsync(); + await WaitUntilAsync(() => _fixture.PlcSyncService.WritePauseEnds.Count > 0); + + _fixture.PlcSyncService.WritePauseEnds.Should().ContainSingle() + .Which.Recipe.Should().BeNull("the PLC already holds the recipe the screen now shows"); + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(plcRecipe.StepCount); + _fixture.Coordinator.IsSyncEnabled.Should().BeTrue(); } [AvaloniaFact] - public async Task HandleConflict_Cancel_DoesNothing() + public async Task LoadFromPlc_FailingTheCheck_TurnsSyncOff_AndKeepsTheScreenRecipe() { - _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(null)); - var callsBefore = _fixture.PlcSyncService.NotifyRecipeChangedCallCount; + _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(false)); + var recipeBefore = _fixture.Coordinator.CurrentRecipe; + + await RaiseConflictAsync(RecipeStubs.LoopsNestedDeeperThanLimit()); + await WaitForSyncOffAsync(); - await _viewModel.HandleConflictAsync(CurrentRecipe, CurrentRecipe); + _turnOffReasons.OfType().Should().ContainSingle(); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(recipeBefore); + _fixture.PlcSyncService.WritePauseEnds.Should().BeEmpty("nothing was written or replaced"); + } - _fixture.PlcSyncService.NotifyRecipeChangedCallCount.Should().Be( - callsBefore, - "cancelling the dialog must not resolve the conflict either way"); - _fixture.MessagePanel.Entries.Should().NotContain( - entry => entry.Severity == MessageSeverity.Error, - "cancelling must not report any error"); + [AvaloniaFact] + public async Task ClosedWithoutAChoice_TurnsSyncOff_AndReportsTheUnresolvedConflict() + { + _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(null)); + var recipeBefore = _fixture.Coordinator.CurrentRecipe; + + await RaiseConflictAsync(); + await WaitForSyncOffAsync(); + + _turnOffReasons.OfType().Should().ContainSingle() + .Which.DialogShowFailed.Should().BeFalse(); + _fixture.PlcSyncService.WritePauseEnds.Should().BeEmpty("nothing is written or replaced"); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(recipeBefore); + await WaitUntilAsync(() => _fixture.MessagePanel.Entries.Any(entry => + entry.Severity == MessageSeverity.Error + && entry.Message == ReasonLocalizer.Localize(new ConflictUnresolvedError(dialogShowFailed: false)))); + } + + [AvaloniaFact] + public async Task SyncTurnedOffMessage_OutlivesEdits_UntilSyncTurnsOnAgain() + { + _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(null)); + var message = ReasonLocalizer.Localize(new ConflictUnresolvedError(dialogShowFailed: false)); + await RaiseConflictAsync(); + await WaitForSyncOffAsync(); + await WaitUntilAsync(() => _fixture.MessagePanel.Entries.Any(entry => entry.Message == message)); + + _fixture.Coordinator.AppendStep(RecipeTestDriver.WaitActionId).IsSuccess.Should().BeTrue(); + _fixture.MessagePanel.ClearOperation(); + Dispatcher.UIThread.RunJobs(); + + _fixture.MessagePanel.Entries.Should().Contain(entry => entry.Message == message, + "an edit does not clear the reason sync turned off"); + + (await _fixture.Coordinator.EnableSync()).IsSuccess.Should().BeTrue(); + _fixture.PlcSyncService.PushPlcState( + new PlcSessionSnapshot(PlcConnectionState.Connecting, PlcSyncStatus.Idle, IsSyncEnabled: true)); + await WaitUntilAsync(() => _fixture.MessagePanel.Entries.All(entry => entry.Message != message)); } [AvaloniaFact] - public async Task HandleConflict_HandlerThrows_ContainsFaultAndReports() + public async Task DialogThatThrows_TurnsSyncOff_AndReportsTheShowFailure() { _viewModel.ResolveConflictInteraction.RegisterHandler( _ => throw new InvalidOperationException("dialog boom")); - var act = async () => await _viewModel.HandleConflictAsync(CurrentRecipe, CurrentRecipe); + await RaiseConflictAsync(); + await WaitForSyncOffAsync(); + + _turnOffReasons.OfType().Should().ContainSingle() + .Which.DialogShowFailed.Should().BeTrue(); + _fixture.PlcSyncService.WritePauseEnds.Should().BeEmpty(); + await WaitUntilAsync(() => _fixture.MessagePanel.Entries.Any(entry => + entry.Severity == MessageSeverity.Error && entry.Message.Contains(Resources.PlcConflictDialogShowFailed))); + } + + [AvaloniaFact] + public async Task NoHandlerRegistered_TurnsSyncOff_AsADialogThatCannotBeShown() + { + await RaiseConflictAsync(); + await WaitForSyncOffAsync(); - await act.Should().NotThrowAsync("a dialog fault must be contained on the fire-and-forget path"); - _fixture.MessagePanel.Entries.Should().Contain( - entry => entry.Severity == MessageSeverity.Error && entry.Message == Resources.PlcConflictDialogShowFailed); + _turnOffReasons.OfType().Should().ContainSingle() + .Which.DialogShowFailed.Should().BeTrue(); } [AvaloniaFact] - public async Task HandleConflict_NoHandlerRegistered_ReportsInsteadOfVanishing() + public async Task KeepLocal_ClickedAfterALinkDrop_WritesNothing() { - await _viewModel.HandleConflictAsync(CurrentRecipe, CurrentRecipe); + var answer = new TaskCompletionSource(); + _viewModel.ResolveConflictInteraction.RegisterHandler(async context => + context.SetOutput(await answer.Task)); + + await RaiseConflictAsync(); + _fixture.S7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + answer.SetResult(true); + Dispatcher.UIThread.RunJobs(); + + _fixture.PlcSyncService.WritePauseEnds.Should().BeEmpty("the answer belongs to a comparison the drop made stale"); + _fixture.PlcSyncService.IsWritePaused.Should().BeTrue(); + _fixture.Coordinator.IsSyncEnabled.Should().BeTrue(); + } - _fixture.MessagePanel.Entries.Should().Contain( - entry => entry.Severity == MessageSeverity.Error && entry.Message == Resources.PlcConflictDialogShowFailed, - "an unhandled interaction must convert today's silent drop into a report"); + /// Turns sync on over a local recipe and raises a reconnect whose PLC recipe differs. + private async Task RaiseConflictAsync(Recipe? plcRecipe = null) + { + var conflictingRecipe = plcRecipe ?? RecipeStubs.WithSteps(RecipeTestDriver.WaitActionId, 1); + _fixture.S7Service.ManagingAreaToReturn = + new PlcManagingAreaState(Committed: true, RecipeLines: conflictingRecipe.StepCount); + _fixture.S7Service.RecipeToReturn = conflictingRecipe; + (await _fixture.Coordinator.EnableSync()).IsSuccess.Should().BeTrue(); + + var conflictRaised = false; + _fixture.Plc.PlcRecipeConflictDetected += _ => conflictRaised = true; + _fixture.S7Service.RaiseStateChanged(PlcConnectionState.Connected); + await WaitUntilAsync(() => conflictRaised); + Dispatcher.UIThread.RunJobs(); + + return conflictingRecipe; } - private Recipe CurrentRecipe => _fixture.Coordinator.CurrentRecipe; + private Task WaitForSyncOffAsync() + { + return WaitUntilAsync(() => !_fixture.Coordinator.IsSyncEnabled && !_turnOffReasons.IsEmpty); + } + + private static async Task WaitUntilAsync(Func predicate) + { + await TestHelpers.WaitUntilAsync( + () => + { + Dispatcher.UIThread.RunJobs(); + return predicate(); + }, + TestContext.Current.CancellationToken); + } } diff --git a/SemiStep/SemiStep.Tests/UI/MainWindow/SyncToggleTests.cs b/SemiStep/SemiStep.Tests/UI/MainWindow/SyncToggleTests.cs index 4aaaef8b..2e27572b 100644 --- a/SemiStep/SemiStep.Tests/UI/MainWindow/SyncToggleTests.cs +++ b/SemiStep/SemiStep.Tests/UI/MainWindow/SyncToggleTests.cs @@ -170,6 +170,24 @@ await TestHelpers.WaitUntilAsync( MenuItemOf(window).Command!.CanExecute(null).Should().BeTrue(); } + [AvaloniaFact] + public async Task Toggle_PressedWhileTheAppTurnsSyncOff_KeepsTheDirectionItShowed() + { + var window = ShowMainWindow(); + await _viewModel.ToggleSyncCommand.Execute(); + Dispatcher.UIThread.RunJobs(); + ToggleOf(window).IsChecked.Should().BeTrue("precondition: sync is on"); + var connectsBefore = _fixture.StubS7.ConnectCallCount; + + // An app turn-off has cleared the sync flag, and its snapshot has not reached the switch yet. + _fixture.PlcSyncService.SetSyncEnabled(false); + await _viewModel.ToggleSyncCommand.Execute(); + Dispatcher.UIThread.RunJobs(); + + _fixture.StubS7.ConnectCallCount.Should().Be(connectsBefore, "the operator pressed a switch that showed on"); + _viewModel.IsSyncEnabled.Should().BeFalse(); + } + [AvaloniaFact] public void Toggle_CheckedTrack_IsNeutralGrey() { diff --git a/SemiStep/SemiStep.Tests/UI/Plc/PlcConflictDialogTests.cs b/SemiStep/SemiStep.Tests/UI/Plc/PlcConflictDialogTests.cs new file mode 100644 index 00000000..4c0df037 --- /dev/null +++ b/SemiStep/SemiStep.Tests/UI/Plc/PlcConflictDialogTests.cs @@ -0,0 +1,36 @@ +using Avalonia.Controls; +using Avalonia.Headless; +using Avalonia.Headless.XUnit; +using Avalonia.Input; +using Avalonia.Threading; + +using AwesomeAssertions; + +using SemiStep.UI.Plc; + +using Xunit; + +namespace SemiStep.Tests.UI.Plc; + +[Trait("Component", "UI")] +[Trait("Area", "PlcConflict")] +[Trait("Category", "Integration")] +public sealed class PlcConflictDialogTests +{ + [AvaloniaFact] + public void Escape_ClosesTheDialogWithoutAChoice() + { + var owner = new Window(); + owner.Show(); + var dialog = new PlcConflictDialog(new PlcConflictDialogViewModel(localStepCount: 2, plcStepCount: 1)); + var shown = dialog.ShowDialog(owner); + Dispatcher.UIThread.RunJobs(); + + dialog.KeyPressQwerty(PhysicalKey.Escape, RawInputModifiers.None); + Dispatcher.UIThread.RunJobs(); + + shown.IsCompleted.Should().BeTrue("Esc closes the dialog"); + dialog.Confirmed.Should().BeFalse("closing without a choice is neither answer"); + owner.Close(); + } +} diff --git a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs index 2464eb87..9b178b00 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs @@ -2,6 +2,7 @@ using AwesomeAssertions; +using SemiStep.Core.Plc; using SemiStep.Core.Plc.State; using SemiStep.Core.Plc.Sync; using SemiStep.Core.Recipes; @@ -496,8 +497,8 @@ public async Task ResolveConflict_TakePlcRecipeFailingAnalysis_EmitsNoSignalAndL { _fixture.SeedRecipe(2); var recipeBefore = _fixture.Coordinator.CurrentRecipe; - var conflictFired = false; - _fixture.Plc.PlcRecipeConflictDetected += (_, _) => conflictFired = true; + PlcRecipeConflict? conflict = null; + _fixture.Plc.PlcRecipeConflictDetected += raised => conflict = raised; var plcRecipe = RecipeStubs.LoopsNestedDeeperThanLimit(); _fixture.S7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: plcRecipe.StepCount); @@ -505,12 +506,12 @@ public async Task ResolveConflict_TakePlcRecipeFailingAnalysis_EmitsNoSignalAndL (await _fixture.Coordinator.EnableSync()).IsSuccess.Should().BeTrue(); _fixture.S7Service.RaiseStateChanged(PlcConnectionState.Connected); await TestHelpers.WaitUntilAsync( - () => conflictFired, + () => conflict is not null, cancellationToken: TestContext.Current.CancellationToken); var sink = new RecordingRecipeSink(); _fixture.Coordinator.Mutated += sink.OnMutation; - var result = _fixture.Coordinator.ResolveConflict(keepLocal: false); + var result = _fixture.Coordinator.ResolveConflict(conflict!.ComparisonId, PlcConflictAnswer.TakePlc); result.HasError().Should().BeTrue(); sink.Signals.Should().BeEmpty(); diff --git a/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs index 17295fb3..3b1494d1 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs @@ -189,6 +189,9 @@ public async Task ReconnectApply_StartsWithoutMarks() var plcRecipe = new Recipe([.. CurrentRecipe.Steps]); ChangeAction(0, RecipeTestDriver.ForLoopActionId); _fixture.Coordinator.RemoveSteps([0, 1, 2]); + + // An empty recipe with unsaved changes gets the conflict, not the take. + _fixture.Session.MarkSaved(); _fixture.S7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 3); _fixture.S7Service.RecipeToReturn = plcRecipe; (await _fixture.Coordinator.EnableSync()).IsSuccess.Should().BeTrue(); diff --git a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs index ea0bfec8..44daa676 100644 --- a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs +++ b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs @@ -30,7 +30,7 @@ public sealed class RecipeCoordinator : IDisposable private readonly ILogger _logger; private readonly MessagePanelViewModel _messagePanel; private readonly PlcLifecycleManager _plc; - private readonly Subject<(Recipe Local, Recipe Plc)> _plcRecipeConflictDetected = new(); + private readonly Subject _plcRecipeConflictDetected = new(); private readonly Subject _plcStateChanged = new(); private readonly RecipeMetadataRegistry _recipeMetadataRegistry; private readonly RecipeSession _session; @@ -39,6 +39,7 @@ public sealed class RecipeCoordinator : IDisposable private bool _initialized; private IDisposable? _plcFaultsSubscription; private IDisposable? _plcStateSubscription; + private IDisposable? _syncTurnOffsSubscription; public RecipeCoordinator( RecipeSession session, @@ -81,7 +82,7 @@ public RecipeCoordinator( // PlcRecipeConflictDetected, PlcStateChanged and ExecutionState hop to MainThreadScheduler once and are // shared via Publish().RefCount(); subscribers add no ObserveOn. - public IObservable<(Recipe Local, Recipe Plc)> PlcRecipeConflictDetected { get; } + public IObservable PlcRecipeConflictDetected { get; } public IObservable PlcStateChanged { get; } public IObservable ExecutionState { get; } @@ -122,11 +123,15 @@ public RecipeCoordinator Initialize() _plcStateSubscription = _plc.PlcState .ObserveOn(RxSchedulers.MainThreadScheduler) - .Subscribe(OnPlcStateChanged); + .Subscribe(OnPlcStateChanged, OnPlcStreamError); _plcFaultsSubscription = _plc.Faults .ObserveOn(RxSchedulers.MainThreadScheduler) - .Subscribe(OnPlcFault); + .Subscribe(OnPlcFault, OnPlcStreamError); + + _syncTurnOffsSubscription = _plc.SyncTurnOffs + .ObserveOn(RxSchedulers.MainThreadScheduler) + .Subscribe(OnSyncTurnedOff, OnPlcStreamError); } catch { @@ -154,6 +159,7 @@ public void Dispose() _plcStateSubscription?.Dispose(); _plcFaultsSubscription?.Dispose(); + _syncTurnOffsSubscription?.Dispose(); _canEditRecipeConnection.Dispose(); _plcRecipeConflictDetected.Dispose(); @@ -193,24 +199,28 @@ public async Task DisableSync() _logger.LogInformation("PLC sync disabled"); } - public Result ResolveConflict(bool keepLocal) + /// A take whose check fails turns sync off; Core reports the reason on . + public Result ResolveConflict(long comparisonId, PlcConflictAnswer answer) { - _logger.LogInformation("PLC recipe conflict resolution: KeepLocal={KeepLocal}", keepLocal); + _logger.LogInformation( + "PLC recipe conflict resolution: Comparison={ComparisonId}, Answer={Answer}", + comparisonId, + answer); - var result = _plc.ResolveConflict(keepLocal); + var result = _plc.ResolveConflict(comparisonId, answer); if (result.IsFailed) { _logger.LogWarning("PLC recipe conflict resolution failed: {Errors}", result.FormatErrors()); } - else if (!keepLocal) + else if (result.Value) { DispatchMutation(new MutationSignal.RecipeReplaced()); } RebuildMessagePanel(); - return result; + return result.ToResult(); } public Result AppendStep(int actionId) @@ -370,12 +380,17 @@ private async Task ApplyReconnectPlcRecipeAsync(Recipe recipe) var applyResult = _plc.ApplyRecipeFromPlc(recipe); if (applyResult.IsFailed) { + // Core turns sync off and reports the reason on Faults. RebuildMessagePanel(); _logger.LogWarning( "Reconnect reconciliation failed to apply PLC recipe: {Errors}", applyResult.FormatErrors()); - _messagePanel.ReportFailure(applyResult, Resources.PlcReconnect); - return applyResult; + return applyResult.ToResult(); + } + + if (!applyResult.Value) + { + return Result.Ok(); } _logger.LogInformation( @@ -385,7 +400,7 @@ private async Task ApplyReconnectPlcRecipeAsync(Recipe recipe) DispatchMutation(new MutationSignal.RecipeReplaced()); RebuildMessagePanel(); - return applyResult; + return applyResult.ToResult(); }); } @@ -461,6 +476,10 @@ private void OnPlcStateChanged(PlcSessionSnapshot snapshot) // Cache before the emit: the VM subscriber re-reads IsConnecting synchronously on this // snapshot, so assigning after OnNext would surface a value stale by one snapshot. _connectionState = snapshot.ConnectionState; + if (snapshot.IsSyncEnabled) + { + _messagePanel.ClearSyncTurnedOff(); + } _plcStateChanged.OnNext(snapshot); } @@ -487,6 +506,30 @@ private void OnPlcFault(IError error) } } + /// The reason stays in the panel until sync is turned on again. + private void OnSyncTurnedOff(IError reason) + { + lock (_disposeLock) + { + if (_disposed) + { + return; + } + + _logger.LogWarning("PLC sync turned off: {Reason}", reason.Message); + _messagePanel.ReportSyncTurnedOff(ReasonLocalizer.Localize(reason)); + } + } + + private void OnPlcStreamError(Exception exception) + { + ExceptionReporter.ReportAndLog( + _messagePanel, + _logger, + new LocalizedText(nameof(Resources.PlcFaultReportFailed)), + exception); + } + private void LogPlcStateChange(PlcSessionSnapshot snapshot) { _logger.LogInformation( @@ -496,7 +539,7 @@ private void LogPlcStateChange(PlcSessionSnapshot snapshot) snapshot.IsSyncEnabled); } - private void OnPlcRecipeConflictDetected(Recipe local, Recipe plc) + private void OnPlcRecipeConflictDetected(PlcRecipeConflict conflict) { lock (_disposeLock) { @@ -505,7 +548,7 @@ private void OnPlcRecipeConflictDetected(Recipe local, Recipe plc) return; } - _plcRecipeConflictDetected.OnNext((local, plc)); + _plcRecipeConflictDetected.OnNext(conflict); } } diff --git a/SemiStep/SemiStep.UI/Localization/ReasonLocalizer.cs b/SemiStep/SemiStep.UI/Localization/ReasonLocalizer.cs index fc7ce0e2..53ee86b4 100644 --- a/SemiStep/SemiStep.UI/Localization/ReasonLocalizer.cs +++ b/SemiStep/SemiStep.UI/Localization/ReasonLocalizer.cs @@ -52,6 +52,15 @@ public static string Localize(IReason reason) WriteVerificationFailedError error => Format( Resources.ErrorWriteVerificationFailed, error.Attempts), PlcCommandFailedError => Resources.ErrorPlcCommandFailed, + ComparisonReadsFailedError => Resources.SyncOffComparisonReadsFailed, + ConflictUnresolvedError { DialogShowFailed: true } => Format( + Resources.SyncOffConflictDialogShowFailedFormat, + Resources.PlcConflictDialogShowFailed, + Resources.SyncOffConflictUnresolved), + ConflictUnresolvedError => Resources.SyncOffConflictUnresolved, + PlcRecipeNotLoadedError error => Format( + Resources.SyncOffPlcRecipeNotLoadedFormat, + string.Join("; ", error.Causes.Select(Localize))), OwnedByAnotherInstanceError error => Format( Resources.ErrorOwnedByAnotherInstance, error.Holder.UserName, diff --git a/SemiStep/SemiStep.UI/Localization/Resources.resx b/SemiStep/SemiStep.UI/Localization/Resources.resx index 5afe00ba..75dd0bc4 100644 --- a/SemiStep/SemiStep.UI/Localization/Resources.resx +++ b/SemiStep/SemiStep.UI/Localization/Resources.resx @@ -475,9 +475,6 @@ A recipe is running: a recipe cannot be opened or created. - - PLC reconnect - Step {0} @@ -808,4 +805,19 @@ enter a number from {0} to {1} + + Could not read the recipe from the PLC. Sync is turned off. + + + Sync is turned off: the recipe conflict is not resolved. + + + {0}. {1} + + + The PLC recipe was not loaded: {0}. Sync is turned off. + + + Failed to report a PLC fault + diff --git a/SemiStep/SemiStep.UI/Localization/Resources.ru.resx b/SemiStep/SemiStep.UI/Localization/Resources.ru.resx index 2d83020d..df9de5e6 100644 --- a/SemiStep/SemiStep.UI/Localization/Resources.ru.resx +++ b/SemiStep/SemiStep.UI/Localization/Resources.ru.resx @@ -475,9 +475,6 @@ Идёт выполнение рецепта: открыть или создать рецепт нельзя. - - Переподключение ПЛК - Шаг {0} @@ -808,4 +805,19 @@ введите число от {0} до {1} + + Не удалось прочитать рецепт из ПЛК. Синхронизация выключена. + + + Синхронизация выключена: конфликт рецептов не решён. + + + {0}. {1} + + + Рецепт из ПЛК не загружен: {0}. Синхронизация выключена. + + + Не удалось сообщить об ошибке ПЛК + diff --git a/SemiStep/SemiStep.UI/MainWindow/MainWindowViewModel.cs b/SemiStep/SemiStep.UI/MainWindow/MainWindowViewModel.cs index 1a80fe26..206ea0f4 100644 --- a/SemiStep/SemiStep.UI/MainWindow/MainWindowViewModel.cs +++ b/SemiStep/SemiStep.UI/MainWindow/MainWindowViewModel.cs @@ -10,7 +10,7 @@ using ReactiveUI; using SemiStep.Core.Configuration; -using SemiStep.Core.Recipes; +using SemiStep.Core.Plc; using SemiStep.UI.Clipboard; using SemiStep.UI.Coordinator; @@ -32,6 +32,7 @@ public class MainWindowViewModel : ReactiveObject, IDisposable private readonly Func _gridStyleEditorViewModelFactory; private readonly ObservableAsPropertyHelper _isTransposedOrientation; private readonly ObservableAsPropertyHelper _windowTitle; + private bool _isSyncShownEnabled; public MainWindowViewModel( RecipeCoordinator coordinator, @@ -114,14 +115,14 @@ public MainWindowViewModel( .Subscribe( conflict => Guarded( new LocalizedText(nameof(Resources.PlcConflictHandlingFailed)), - () => _ = HandleConflictAsync(conflict.Local, conflict.Plc)), + () => _ = HandleConflictAsync(conflict)), OnSubscriptionError(new LocalizedText(nameof(Resources.PlcConflictHandlingFailed)))) .DisposeWith(_disposables); } public Interaction ShowStyleEditorInteraction { get; } - // Result: null = cancel, true = keep local, false = load from PLC. + // Result: null = closed without a choice, true = keep local, false = load from PLC. internal Interaction ResolveConflictInteraction { get; } public Interaction RequestCloseInteraction { get; } @@ -198,9 +199,13 @@ private async Task ExecuteOpenStyleEditorAsync() await ShowStyleEditorInteraction.Handle(viewModel); } + /// + /// The direction is the one the switch showed at the press: an app turn-off in progress has already cleared the + /// sync flag, and reading it would turn a press to turn off into a turn-on. + /// private async Task ExecuteToggleSyncAsync() { - var isDisabling = _coordinator.IsSyncEnabled; + var isDisabling = _isSyncShownEnabled; _syncToggle.OnNext(isDisabling ? SyncToggleDirection.Disabling : SyncToggleDirection.Enabling); try { @@ -226,38 +231,35 @@ private async Task ExecuteToggleSyncAsync() RaiseConnectionStateProperties(); } - internal async Task HandleConflictAsync(Recipe local, Recipe plc) + /// + /// Every way out of the dialog answers the conflict: closing it without a choice, or failing to show it, turns + /// sync off. Core reports each turn-off reason, a failed take check included. + /// + internal async Task HandleConflictAsync(PlcRecipeConflict conflict) { - bool? keepLocal; + PlcConflictAnswer answer; try { - keepLocal = await ResolveConflictInteraction.Handle( - new PlcConflictDialogViewModel(local.StepCount, plc.StepCount)); + var keepLocal = await ResolveConflictInteraction.Handle( + new PlcConflictDialogViewModel(conflict.Local.StepCount, conflict.Plc.StepCount)); + answer = keepLocal switch + { + true => PlcConflictAnswer.KeepLocal, + false => PlcConflictAnswer.TakePlc, + null => PlcConflictAnswer.Dismissed + }; } catch (Exception ex) { _logger.LogWarning("Unexpected error while showing PLC conflict dialog: {Message}", ex.Message); - MessagePanel.ReportError(Resources.PlcConflictDialogShowFailed); - - return; - } - - if (keepLocal is null) - { - return; + answer = PlcConflictAnswer.DialogShowFailed; } // The conflict callback runs fire-and-forget, so a throw in the post-dialog resolution would // fault the discarded task and surface only through the nondeterministic TaskScheduler hook. - Guarded(new LocalizedText(nameof(Resources.PlcConflictResolutionFailed)), () => - { - var result = _coordinator.ResolveConflict(keepLocal.Value); - - if (result.IsFailed) - { - MessagePanel.ReportFailure(result); - } - }); + Guarded( + new LocalizedText(nameof(Resources.PlcConflictResolutionFailed)), + () => _coordinator.ResolveConflict(conflict.ComparisonId, answer)); } private void OnCoordinatorMutated(MutationSignal signal) @@ -296,6 +298,7 @@ private void RaiseAllStateProperties() private void RaiseConnectionStateProperties() { + _isSyncShownEnabled = _coordinator.IsSyncEnabled; this.RaisePropertyChanged(nameof(IsSyncEnabled)); } diff --git a/SemiStep/SemiStep.UI/MessageService/MessagePanelViewModel.cs b/SemiStep/SemiStep.UI/MessageService/MessagePanelViewModel.cs index 0e43ab48..5fbd45ab 100644 --- a/SemiStep/SemiStep.UI/MessageService/MessagePanelViewModel.cs +++ b/SemiStep/SemiStep.UI/MessageService/MessagePanelViewModel.cs @@ -30,6 +30,7 @@ public class MessagePanelViewModel : ReactiveObject, IDisposable private readonly List _validationEntries = []; private MessageEntry? _operationEntry; + private MessageEntry? _syncTurnedOffEntry; public MessagePanelViewModel() { @@ -177,6 +178,30 @@ public void ReportError(string message) ReportOperation(MessageSeverity.Error, message); } + /// A reason sync turned off; edits and leave it, sync on clears it. + public void ReportSyncTurnedOff(string message) + { + PostOnUiThread(() => + { + _syncTurnedOffEntry = new MessageEntry(MessageSeverity.Error, message); + Rebuild(); + }); + } + + public void ClearSyncTurnedOff() + { + PostOnUiThread(() => + { + if (_syncTurnedOffEntry is null) + { + return; + } + + _syncTurnedOffEntry = null; + Rebuild(); + }); + } + public void ClearOperation() { PostOnUiThread(() => @@ -199,6 +224,11 @@ private void Rebuild() { Entries.Clear(); + if (_syncTurnedOffEntry is not null) + { + Entries.Add(_syncTurnedOffEntry); + } + if (_operationEntry is not null) { Entries.Add(_operationEntry); @@ -229,6 +259,7 @@ private void RecountAndNotify() ErrorCount = _validationEntries.Count(e => e.IsError); WarningCount = _validationEntries.Count(e => e.IsWarning); HasEntries = _validationEntries.Count > 0 + || _syncTurnedOffEntry is not null || _operationEntry is { Severity: MessageSeverity.Error or MessageSeverity.Warning }; } diff --git a/SemiStep/SemiStep.UI/Plc/PlcConflictDialog.axaml.cs b/SemiStep/SemiStep.UI/Plc/PlcConflictDialog.axaml.cs index 92082fcb..efee3f9b 100644 --- a/SemiStep/SemiStep.UI/Plc/PlcConflictDialog.axaml.cs +++ b/SemiStep/SemiStep.UI/Plc/PlcConflictDialog.axaml.cs @@ -1,4 +1,5 @@ using Avalonia.Controls; +using Avalonia.Input; using Avalonia.Interactivity; namespace SemiStep.UI.Plc; @@ -15,6 +16,18 @@ internal PlcConflictDialog(PlcConflictDialogViewModel viewModel) DataContext = viewModel; } + /// Esc closes without a choice, as the title bar X and Alt+F4 do. + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + + if (e.Key == Key.Escape && !e.Handled) + { + e.Handled = true; + Close(); + } + } + private void OnKeepLocalClick(object? sender, RoutedEventArgs e) { KeepLocal = true; diff --git a/docs/architecture/dialogs-and-interactions.md b/docs/architecture/dialogs-and-interactions.md index 29eef7ad..7522d126 100644 --- a/docs/architecture/dialogs-and-interactions.md +++ b/docs/architecture/dialogs-and-interactions.md @@ -22,9 +22,14 @@ VM-driven dialog follows an established pattern rather than inventing one. The VM builds and `LoadAsync`es the editor view model, then hands it to the interaction; the handler news `GridStyleEditorWindow { DataContext = context.Input }`. - `ResolveConflictInteraction` (`Interaction`) — the PLC recipe - conflict dialog. Output encodes the three outcomes: `null` = cancelled, `true` = keep local, - `false` = load from PLC. The handler news `PlcConflictDialog(context.Input)` and reports - `dialog.Confirmed ? dialog.KeepLocal : null`. + conflict dialog. Output encodes the three outcomes: `null` = closed without a choice (title bar X, + Esc, Alt+F4), `true` = keep local, `false` = load from PLC. The handler news + `PlcConflictDialog(context.Input)` and reports `dialog.Confirmed ? dialog.KeepLocal : null`; + `PlcConflictDialog.OnKeyDown` closes the dialog on Esc. `MainWindowViewModel.HandleConflictAsync` maps + the output to a `PlcConflictAnswer` and passes it to `PlcLifecycleManager.ResolveConflict` with the + conflict's comparison ID: `null` is `Dismissed`, and a handler that throws or is missing is + `DialogShowFailed`. Both turn sync off. An answer whose comparison a link drop, a newer comparison or + sync off made stale changes nothing. - `RequestCloseInteraction` (`Interaction`) — `File > Exit`. The handler calls `Close()`, which runs `OnWindowClosing`'s dirty-close guard (see `exit-flow.md`). @@ -34,7 +39,7 @@ before "Создать рецепт" or "Открыть рецепт" drops a di Because the dialog now goes through an interaction, the flow is unit-testable headless: a test registers a fake handler and asserts the VM behavior with no `Window` in play. A missing handler raises `UnhandledInteractionException` instead of silently dropping the dialog, so the conflict flow's -try/catch turns that into a reported failure rather than a no-op. +try/catch turns that into the `DialogShowFailed` answer rather than a no-op. ## The view-side boundary diff --git a/docs/architecture/error-reporting.md b/docs/architecture/error-reporting.md index d3826969..4cc7b828 100644 --- a/docs/architecture/error-reporting.md +++ b/docs/architecture/error-reporting.md @@ -341,6 +341,17 @@ always English; only the panel seams localize. recipe-active, write-verification, not-committed, command — see "PLC faults localize by type"); an untyped fault still falls through to its English `.Message`. The persistent "disconnected" label stays in the status bar. +- **Sync turned off by the app** arrives on its own stream, `PlcLifecycleManager.SyncTurnOffs`, which + carries the reason of each turn-off the app makes by itself. The reasons are typed: + `ComparisonReadsFailedError` (three failed comparisons in a row), `ConflictUnresolvedError` (the + conflict dialog closed without a choice, or could not be shown, `DialogShowFailed`), + `PlcRecipeNotLoadedError` (the taken PLC recipe failed the check or the take threw, its `Causes` + localize one by one) and `ProtocolVersionMismatchError` (a mismatch on reconnect). Core emits the + reason after the turn-off ends, so no view model reports the failed take or the closed dialog itself. + `RecipeCoordinator.OnSyncTurnedOff` puts the localized reason into a third panel slot, + `MessagePanelViewModel.ReportSyncTurnedOff`. Edits and `ClearOperation` leave that slot alone; the + first snapshot with sync on clears it (`ClearSyncTurnedOff`). Like the operation slot, it is not + counted in the status-bar totals. - **Command exceptions** (a `ReactiveCommand` fault on `ThrownExceptions`) are not `Result`-based; they route through `ReportThrownExceptions` (see below) rather than a hand-written handler. - **One deliberate exception** to the `"; "` idiom: the clipboard *paste* failure lists each error on diff --git a/docs/architecture/exit-flow.md b/docs/architecture/exit-flow.md index affde27f..6d2c01d7 100644 --- a/docs/architecture/exit-flow.md +++ b/docs/architecture/exit-flow.md @@ -34,7 +34,11 @@ app exit now routes through `MainWindow.Close()` and runs the dirty guard. A recipe write runs on its own cancellation token, separate from the sync debounce. A sync disable does not cancel it: `PlcLifecycleManager.DisableSync` waits for it up to 5 s, then disconnects, then releases the sync ownership lease. The write therefore ends whole unless the connection drops, the -PLC stalls past the bound, or the process dies. The exit keeps the same order, see +PLC stalls past the bound, or the process dies. Sync on and sync off run one at a time behind one gate +in `PlcSyncSwitch`. A turn-off the app makes by itself takes the same path; it is posted to the thread +pool, so neither the reconnect comparison nor the reconnect loop waits for it. When it runs, +`PlcComparisonState.IsDue` checks it again: it does nothing when sync is already off, when sync was +turned off and on since it was posted, or, for the three-failure cap, when a later comparison decided. The exit keeps the same order, see [Service teardown at exit](#service-teardown-at-exit). ## Service teardown at exit diff --git a/docs/plans/20261130-recipe-replace-save-exit-safety.md b/docs/plans/20261130-recipe-replace-save-exit-safety.md index dafd7e40..1e0bf188 100644 --- a/docs/plans/20261130-recipe-replace-save-exit-safety.md +++ b/docs/plans/20261130-recipe-replace-save-exit-safety.md @@ -18,7 +18,7 @@ and the PLC disagree without saying so: After this work, one rule holds everywhere: while sync is on, the PLC gets only the screen recipe, and only after the operator could see any difference. The link slot never claims the PLC matches when it does not. When the app cannot keep this true, it turns sync off and says why in the -notification panel, which keeps the message until the operator dismisses it. A dialog appears only +notification panel, which keeps the message until sync is turned on again. A dialog appears only when the operator has a choice to make. A local file changes only when the operator saves. Scope guard: diff --git a/docs/readme.md b/docs/readme.md index 1115c32c..c4a485b3 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -414,6 +414,10 @@ _Окно установки RIE в транспонированном пред 2. Выполняется согласование версии протокола и состояния рецепта (см. разделы 4.2 и 7.3). 3. При каждом успешном изменении рецепта запускается отложенная (≈1 с) запись в ПЛК. +От включения синхронизации до результата согласования приложение ничего не пишет в ПЛК (пауза записи). Правки, сделанные в это время, остаются на экране. Если согласование решает записать рецепт, в ПЛК уходит последний рецепт с экрана. Пауза записи начинается и при обрыве связи: правки, сделанные без связи, ждут согласования после переподключения. Запись, которая уже шла в момент обрыва, завершается или завершается с ошибкой, как раньше. + +Включение и выключение синхронизации выполняются по одному. Нажатие переключателя действует в том направлении, которое переключатель показывал в момент нажатия. Если приложение в этот момент само выключает синхронизацию, нажатие выполняется после этого; нажатие «выключить» тогда ничего не делает, потому что синхронизация уже выключена. + При отключении синхронизации соединение разрывается, мониторинг исполнения останавливается. Если в момент отключения идёт запись рецепта, приложение ждёт её завершения до 5 с и только затем разрывает соединение; переключатель и пункт меню на это время неактивны. Если запись не завершилась за 5 с, в журнал пишется предупреждение. При закрытии приложения синхронизация завершается в том же порядке: начатая запись рецепта завершается (до 5 с), затем соединение с ПЛК разрывается, затем приложение освобождает владение синхронизацией. Изменение, внесённое менее чем за 1 с до закрытия, в ПЛК не записывается: в ПЛК остаётся последний записанный рецепт, и при следующем включении синхронизации согласование сравнит его с рецептом ПК (раздел 4.2). После закрытия окна процесс может работать ещё до 10 с; если завершение не уложилось в этот срок, в журнал пишется предупреждение, и приложение всё равно завершается. @@ -435,11 +439,19 @@ _Окно установки RIE в транспонированном пред | зафиксирован, ПЛК ≠ ПК, ПК пустой | ПЛК непустой | Загрузить рецепт из ПЛК в ПК автоматически | | зафиксирован, ПЛК ≠ ПК, оба непустые | оба непустые | Показать диалог конфликта — пользователь выбирает источник | -> **Диалог конфликта** предлагает сохранить локальную версию или загрузить версию из ПЛК. +> **Диалог конфликта** предлагает сохранить локальную версию или загрузить версию из ПЛК. Пока диалог открыт, приложение ничего не пишет в ПЛК. «Оставить локальный» записывает в ПЛК рецепт с экрана; рецепт с предупреждениями не записывается. «Загрузить из ПЛК» загружает рецепт из ПЛК и ничего не пишет обратно. + +Если диалог конфликта закрыт без выбора (крестиком, клавишей Esc или Alt+F4) или не может быть показан, синхронизация выключается. Ничего не записывается и не заменяется, а в панели уведомлений появляется сообщение «Синхронизация выключена: конфликт рецептов не решён.» Повторное включение синхронизации снова сравнивает рецепты. + +Сообщение о том, почему синхронизация выключилась, остаётся в панели уведомлений при правке рецепта и исчезает, когда синхронизацию включают снова. -> Таблица не покрывает сбой чтения управляющей области и сбой чтения рецепта: на обеих ветках рецепт ПК отдаётся на запись в ПЛК без запроса. Полный перечень веток согласования и их уровни в журнале — в разделе 5. +Если рецепт из ПЛК не проходит проверку при загрузке (например, циклы вложены глубже 3 уровней), рецепт на экране не меняется, синхронизация выключается, а в панели уведомлений появляется сообщение «Рецепт из ПЛК не загружен: <причина>. Синхронизация выключена.» Это правило действует и для кнопки «Загрузить из ПЛК», и для автоматической загрузки в пустой рецепт. -При несовпадении версии протокола синхронизация не выполняется (см. раздел 7.3). +Автоматическая загрузка в пустой рецепт выполняется, только если рецепт на экране всё ещё пуст и не содержит несохранённых изменений. Если за время чтения из ПЛК рецепт на экране изменился (например, открыт файл) или пустой рецепт получен удалением всех шагов, вместо загрузки появляется диалог конфликта. + +Если чтение версии протокола, управляющей области или рецепта не удалось или не уложилось в 5 с, приложение ничего не пишет в ПЛК, разрывает связь и переподключается; после переподключения согласование повторяется. Три неудачных согласования подряд в одном сеансе синхронизации выключают синхронизацию с сообщением «Не удалось прочитать рецепт из ПЛК. Синхронизация выключена.» Полный перечень веток согласования и их уровни в журнале — в разделе 5. + +При несовпадении версии протокола синхронизация не выполняется (см. раздел 7.3). Если ПЛК сообщает другую версию при переподключении, синхронизация выключается с тем же сообщением о версии. --- @@ -527,24 +539,28 @@ _Сообщение об ошибке соединения с ПЛК в пане 2026-08-07 12:31:04.402 [INF] SemiStep.Core.Plc.PlcLifecycleManager: PLC reconciliation outcome ConflictRaised: local 12 steps (valid True), PLC 9 steps, committed True, conflict subscriber True ``` -Поля строки результата: `local N steps` — число шагов рецепта на ПК; `valid` — проходит ли локальный рецепт валидацию (при `False` в ПЛК ничего не записывается); `PLC N steps` — число шагов, прочитанных из ПЛК; `committed` — флаг фиксации рецепта в управляющей области; `conflict subscriber` — подписан ли интерфейс на событие конфликта. У веток `NotCommitted` и `RecipeReadFailed` рецепт из ПЛК не читался, и строка содержит `PLC null steps`. Ветки, на которых неизвестны оба этих значения (`ProtocolVersionMismatch`, `ProtocolVersionCheckFailed`, `ManagingAreaReadFailed`, `TimedOut`, `Cancelled`), пишут укороченный вариант — только результат и поля `local N steps` и `valid`. +Поля строки результата: `local N steps` — число шагов рецепта на ПК; `valid` — проходит ли локальный рецепт валидацию (при `False` в ПЛК ничего не записывается); `PLC N steps` — число шагов, прочитанных из ПЛК; `committed` — флаг фиксации рецепта в управляющей области; `conflict subscriber` — подписан ли интерфейс на событие конфликта. У веток `NotCommitted` и `RecipeReadFailed` рецепт из ПЛК не читался, и строка содержит `PLC null steps`. Ветки, на которых неизвестны оба этих значения (`ProtocolVersionMismatch`, `ProtocolVersionCheckFailed`, `ManagingAreaReadFailed`, `TimedOut`, `Faulted`, `Cancelled`), пишут укороченный вариант — только результат и поля `local N steps` и `valid`. | Результат | Уровень | Что произошло | | ---------------------------- | ----------- | ----------------------------------------------------------------------- | -| `ProtocolVersionMismatch` | Warning | Версия протокола ПЛК не совпала с ожидаемой; синхронизация отменена | -| `ProtocolVersionCheckFailed` | Warning | Версию протокола не удалось прочитать; синхронизация отменена | -| `ManagingAreaReadFailed` | Warning | Управляющая область не прочитана; рецепт ПК отдан на запись в ПЛК | +| `ProtocolVersionMismatch` | Warning | Версия протокола ПЛК не совпала с ожидаемой; синхронизация выключается | +| `ProtocolVersionCheckFailed` | Warning | Версию протокола не удалось прочитать; неудачное чтение | +| `ManagingAreaReadFailed` | Warning | Управляющая область не прочитана; неудачное чтение | | `NotCommitted` | Warning | Рецепт в ПЛК не зафиксирован; рецепт ПК отдан на запись в ПЛК | -| `RecipeReadFailed` | Warning | Рецепт из ПЛК не прочитан; рецепт ПК отдан на запись в ПЛК | +| `RecipeReadFailed` | Warning | Рецепт из ПЛК не прочитан; неудачное чтение | | `AppliedFromPlc` | Information | Локальный рецепт был пуст; рецепт загружен из ПЛК | -| `ApplyFromPlcFailed` | Warning | Загрузка рецепта из ПЛК не выполнена; прочитанный рецепт отброшен | +| `ApplyFromPlcFailed` | Warning | Загрузка рецепта из ПЛК не выполнена; синхронизация выключается | | `ConflictRaised` | Information | Рецепты различаются (раздел 4.2); поднято событие конфликта | | `PlcEmpty` | Information | В ПЛК нет шагов; рецепт ПК отдан на запись в ПЛК | | `Identical` | Information | Рецепты совпали по правилу раздела 4.2; рецепт ПК отдан на запись в ПЛК | -| `TimedOut` | Warning | Чтение из ПЛК не ответило вовремя; согласование прервано | +| `TimedOut` | Warning | Чтение из ПЛК не ответило вовремя; неудачное чтение | +| `Faulted` | Warning | Согласование завершилось исключением; неудачное чтение | +| `Stale` | Information | Связь оборвалась, началось новое согласование или синхронизацию выключили; результат отброшен | | `Cancelled` | Information | Приложение завершает работу; согласование прервано | -> Строка начала без строки результата означает, что согласование началось и не завершилось. Единственный случай, когда результат не пишется, — непредвиденное исключение внутри согласования; оно попадает в журнал отдельной записью уровня `Error` с текстом `Unhandled error in reconnect reconciliation`. +После неудачного чтения приложение ничего не пишет в ПЛК, разрывает связь и переподключается; третье неудачное согласование подряд выключает синхронизацию (раздел 4.2). + +> Строка начала без строки результата означает, что согласование началось и не завершилось. Исключение внутри согласования пишется как результат `Faulted` вместе с исключением. **Запись рецепта в ПЛК.** Если при отключении синхронизации запись рецепта не завершилась за 5 с, источник `SemiStep.Core.Plc.PlcLifecycleManager` пишет предупреждение и затем разрывает соединение: