diff --git a/SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs b/SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs index 556d18f..44ee3b0 100644 --- a/SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs +++ b/SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs @@ -21,6 +21,9 @@ public interface IPlcSyncService /// Ends the write pause and drops the recipe notified during it: the PLC already holds the screen recipe. void EndWritePauseWithoutWrite(); + /// The PLC holds the screen recipe: sets the status to Synced, which clears the latch of a failed write. + void ConfirmInSync(); + /// /// Completes when the attempt in flight at the call has ended; throws when cancels first. /// diff --git a/SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs b/SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs index 7cf5588..bf893e5 100644 --- a/SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs +++ b/SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs @@ -2,28 +2,36 @@ using Microsoft.Extensions.Logging; +using SemiStep.Core.Plc.S7.Serialization; 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. +/// Answers to the offer a comparison made: the conflict answers, the conflict take and the reconnect take. Each +/// decision runs on the UI thread and counts only while its comparison is current. Both takes load through +/// , the one place that replaces the session recipe from the PLC. /// internal sealed class PlcComparisonAnswers( RecipeSession session, + IS7Connection connection, + IS7Reader reader, IPlcSyncService syncService, PlcComparisonState state, PlcSyncSwitch syncSwitch, PlcConflictNotifier conflictNotifier, + RecipeConverter recipeConverter, ILogger logger) { 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 RecipeConverter _recipeConverter = recipeConverter; private readonly ILogger _logger = logger; /// @@ -63,8 +71,8 @@ public Result ApplyRecipeFromPlc(Recipe recipe) return result; } - /// Returns whether the session recipe was replaced; an answer to a stale conflict changes nothing. - public Result ResolveConflict(long comparisonId, PlcConflictAnswer answer) + /// An answer to a stale conflict changes nothing. + public void ResolveConflict(long comparisonId, PlcConflictAnswer answer) { if (!Enum.IsDefined(answer)) { @@ -73,31 +81,146 @@ public Result ResolveConflict(long comparisonId, PlcConflictAnswer answer) lock (_state.Gate) { - if (_state.TakeOfferLocked(offer => offer.IsConflict && offer.ComparisonId == comparisonId) is not { } offer) + if (_state.TakeOfferLocked(offer => offer.IsConflict && offer.ComparisonId == comparisonId) is null) { _logger.LogInformation("PLC conflict answer {Answer} ignored: its comparison is stale", answer); - return Result.Ok(false); + return; + } + + if (answer == PlcConflictAnswer.KeepLocal) + { + _syncService.EndWritePause(_session.Current, _session.IsValid); + return; } - switch (answer) + _syncSwitch.PostTurnOff(_state.TurnOffLocked( + new ConflictUnresolvedError(answer == PlcConflictAnswer.DialogShowFailed))); + } + } + + /// + /// Reads the PLC recipe again for a conflict take and decides nothing. A recipe that is not committed reads as + /// empty; a failure or a throw reads as a failed result. + /// + public async Task> ReadForTakeAsync(CancellationToken ct) + { + try + { + var managingArea = await _reader.ReadManagingAreaAsync(ct); + if (managingArea.IsFailed) { - 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"); + return managingArea.ToResult(); } + + return managingArea.Value.Committed ? await _reader.ReadRecipeFromPlcAsync(ct) : Result.Ok(Recipe.Empty); + } + catch (OperationCanceledException ex) + { + _logger.LogInformation("Reading the PLC recipe for the conflict take was cancelled"); + return Result.Fail(new ExceptionalError(ex)); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Reading the PLC recipe for the conflict take threw"); + return Result.Fail(new ExceptionalError(ex)); + } + } + + /// False once a link drop, a newer comparison or sync off made the conflict stale, or it ended. + public bool IsConflictCurrent(long comparisonId) + { + lock (_state.Gate) + { + return _state.HasOfferLocked(offer => offer.IsConflict && offer.ComparisonId == comparisonId); } } - /// The load notifies sync while the pause holds, so ending the pause next drops that recipe. + /// + /// Ends the conflict with the recipe returned, unless the screen changed since the + /// operator agreed to drop . A failed read fails, also for a stale conflict. + /// + public Result TakeConflictRecipe(long comparisonId, Recipe screenRecipe, Result read) + { + bool isLinkLossDue; + Result result; + lock (_state.Gate) + { + result = DecideTakeLocked(comparisonId, screenRecipe, read, out isLinkLossDue); + } + + if (isLinkLossDue) + { + _connection.DeclareLinkLost(); + } + + return result; + } + + private Result DecideTakeLocked( + long comparisonId, + Recipe screenRecipe, + Result read, + out bool isLinkLossDue) + { + isLinkLossDue = false; + bool IsThisConflict(PlcRecipeOffer offer) + { + return offer.IsConflict && offer.ComparisonId == comparisonId; + } + + if (!_state.HasOfferLocked(IsThisConflict)) + { + _logger.LogInformation("PLC conflict take ignored: its comparison is stale"); + return read.IsFailed ? ReadFailed(read, isLinkLossDeclared: false) : Result.Ok(PlcTakeOutcome.NotReplaced); + } + + if (read.IsFailed) + { + _state.TakeOfferLocked(IsThisConflict); + isLinkLossDue = true; + return ReadFailed(read, isLinkLossDeclared: true); + } + + var plcRecipe = read.Value; + if (plcRecipe.Steps.Count == 0) + { + _state.TakeOfferLocked(IsThisConflict); + _syncService.EndWritePause(_session.Current, _session.IsValid); + return Result.Ok(PlcTakeOutcome.NotReplaced).WithSuccess(new PlcRecipeAbsentWarning()); + } + + if (PlcRecipeDataComparer.EncodesToSamePlcData(_recipeConverter, _session.Current, plcRecipe, _logger)) + { + _state.TakeOfferLocked(IsThisConflict); + _syncService.EndWritePauseWithoutWrite(); + _syncService.ConfirmInSync(); + return Result.Ok(PlcTakeOutcome.NotReplaced); + } + + if (!ReferenceEquals(_session.Current, screenRecipe)) + { + return Result.Ok(PlcTakeOutcome.ScreenChanged); + } + + _state.TakeOfferLocked(IsThisConflict); + var takeResult = TakeLocked(plcRecipe); + return takeResult.IsFailed + ? takeResult.ToResult() + : Result.Ok(PlcTakeOutcome.Replaced).WithReasons(takeResult.Reasons); + } + + private Result ReadFailed(Result read, bool isLinkLossDeclared) + { + _logger.LogWarning( + "Could not read the PLC recipe for the conflict take: {Errors}", + string.Join("; ", read.Errors.Select(e => e.Message))); + return Result.Fail(new PlcTakeReadFailedError(isLinkLossDeclared).CausedBy(read.Errors)); + } + + /// + /// The load notifies sync while the pause holds, so ending the pause next drops that recipe; the PLC holds the + /// screen recipe then. + /// private Result TakeLocked(Recipe plcRecipe) { Result loadResult; @@ -118,6 +241,7 @@ private Result TakeLocked(Recipe plcRecipe) } _syncService.EndWritePauseWithoutWrite(); + _syncService.ConfirmInSync(); return Result.Ok(true).WithReasons(loadResult.Reasons); } } diff --git a/SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs b/SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs index 22c47a1..b9f08b8 100644 --- a/SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs +++ b/SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs @@ -191,10 +191,15 @@ public bool WasTakeConvertedToConflict(long comparisonId) } } + public bool HasOfferLocked(Func matches) + { + return _offer is { } offer && IsCurrentLocked(offer.ComparisonId) && matches(offer); + } + /// 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)) + if (_offer is not { } offer || !HasOfferLocked(matches)) { return null; } diff --git a/SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs b/SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs index ebda2f8..83e8619 100644 --- a/SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs +++ b/SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs @@ -1,10 +1,12 @@ namespace SemiStep.Core.Plc; -/// The operator's answer to a recipe conflict, or the reason none came. +/// +/// The operator's answer to a recipe conflict, or the reason none came. Taking the PLC recipe is +/// , which reads the PLC again first. +/// public enum PlcConflictAnswer { KeepLocal, - TakePlc, Dismissed, DialogShowFailed } diff --git a/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs b/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs index c7994cf..b8f323f 100644 --- a/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs +++ b/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs @@ -55,6 +55,7 @@ public PlcLifecycleManager( _logger = logger; var lifetime = _lifetimeCts.Token; + var recipeConverter = new RecipeConverter(recipeMetadataRegistry); _syncSwitch = new PlcSyncSwitch( connection, reader, @@ -74,15 +75,18 @@ public PlcLifecycleManager( _syncSwitch, _conflictNotifier, _reconnectTake, - new RecipeConverter(recipeMetadataRegistry), + recipeConverter, logger, lifetime); _answers = new PlcComparisonAnswers( session, + connection, + reader, syncService, _comparisonState, _syncSwitch, _conflictNotifier, + recipeConverter, logger); } @@ -187,13 +191,31 @@ public void RegisterReconnectApplyCallback(Func> callback) _reconnectTake.RegisterApplyCallback(callback); } + /// Ends the conflict of ; an answer to a stale conflict changes nothing. + public void ResolveConflict(long comparisonId, PlcConflictAnswer answer) + { + _answers.ResolveConflict(comparisonId, answer); + } + + /// False once a link drop, a newer comparison or sync off made the conflict stale, or it ended. + public bool IsConflictCurrent(long comparisonId) + { + return _answers.IsConflictCurrent(comparisonId); + } + + /// Reads the PLC recipe again for a conflict take; a recipe that is not committed reads as empty. + public Task> ReadRecipeForTakeAsync(CancellationToken ct) + { + return _answers.ReadForTakeAsync(ct); + } + /// - /// Ends the conflict of . Returns whether the session recipe was replaced; an - /// answer to a stale conflict changes nothing. + /// Ends the conflict of with the recipe + /// returned: takes it, writes the screen recipe when the PLC holds none, or declares link loss on a failed read. /// - public Result ResolveConflict(long comparisonId, PlcConflictAnswer answer) + public Result TakeConflictRecipe(long comparisonId, Recipe screenRecipe, Result read) { - return _answers.ResolveConflict(comparisonId, answer); + return _answers.TakeConflictRecipe(comparisonId, screenRecipe, read); } private void OnConnectionStateChanged(PlcConnectionState state) diff --git a/SemiStep/SemiStep.Core/Plc/PlcTakeOutcome.cs b/SemiStep/SemiStep.Core/Plc/PlcTakeOutcome.cs new file mode 100644 index 0000000..e3a3d10 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/PlcTakeOutcome.cs @@ -0,0 +1,14 @@ +namespace SemiStep.Core.Plc; + +/// How a take of the conflict's PLC recipe ended. +public enum PlcTakeOutcome +{ + /// The PLC recipe replaced the screen recipe. + Replaced, + + /// The conflict ended, or was already stale, and the screen recipe stayed. + NotReplaced, + + /// The screen recipe changed after the operator chose; the offer stays for a new answer. + ScreenChanged +} diff --git a/SemiStep/SemiStep.Core/Plc/Sync/PlcRecipeAbsentWarning.cs b/SemiStep/SemiStep.Core/Plc/Sync/PlcRecipeAbsentWarning.cs new file mode 100644 index 0000000..c63bb91 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/Sync/PlcRecipeAbsentWarning.cs @@ -0,0 +1,8 @@ +using SemiStep.Core.Shared; + +namespace SemiStep.Core.Plc.Sync; + +/// The PLC recipe the operator chose to take was gone by the take, so the screen recipe was written. +public sealed class PlcRecipeAbsentWarning() : Warning("The PLC holds no recipe. The screen recipe was written.") +{ +} diff --git a/SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs b/SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs index 18bf274..3d14328 100644 --- a/SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs +++ b/SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs @@ -195,6 +195,16 @@ public void EndWritePauseWithoutWrite() }); } + /// The PLC holds the screen recipe, warnings included, so nothing is left unwritten. + public void ConfirmInSync() + { + Transition(() => + { + _isLatestRecipeValid = true; + return new TransitionResult(SetStatusLocked(PlcSyncStatus.Synced), null, null); + }); + } + public void UpdateConnectionState(PlcConnectionState state) { Transition(() => diff --git a/SemiStep/SemiStep.Core/Plc/Sync/PlcTakeReadFailedError.cs b/SemiStep/SemiStep.Core/Plc/Sync/PlcTakeReadFailedError.cs new file mode 100644 index 0000000..a7dfcd3 --- /dev/null +++ b/SemiStep/SemiStep.Core/Plc/Sync/PlcTakeReadFailedError.cs @@ -0,0 +1,10 @@ +using FluentResults; + +namespace SemiStep.Core.Plc.Sync; + +/// The read of the PLC recipe for a conflict take failed or passed its bound; nothing was taken. +public sealed class PlcTakeReadFailedError(bool isLinkLossDeclared) : Error("Could not read the recipe from the PLC.") +{ + /// The conflict was still current, so the failed read declared link loss and a link-loss fault follows. + public bool IsLinkLossDeclared { get; } = isLinkLossDeclared; +} diff --git a/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs index 86f5470..c4405ef 100644 --- a/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs +++ b/SemiStep/SemiStep.Tests/Domain/PlcLifecycleManagerReconnectTests.cs @@ -555,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, @@ -570,7 +570,7 @@ private static async Task> TakeConflictingPlcRecipeAsync( conflict.Should().NotBeNull(); var notificationsBefore = syncService.NotifyRecipeChangedCallCount; - var result = plc.ResolveConflict(conflict.ComparisonId, PlcConflictAnswer.TakePlc); + var result = plc.TakeConflictRecipe(conflict.ComparisonId, session.Current, Result.Ok(conflict.Plc)); result.IsFailed.Should().BeTrue(); session.Snapshot.Should().BeSameAs(snapshotBefore); diff --git a/SemiStep/SemiStep.Tests/Domain/PlcRunEndSyncTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcRunEndSyncTests.cs index 9aa0a65..c1216ad 100644 --- a/SemiStep/SemiStep.Tests/Domain/PlcRunEndSyncTests.cs +++ b/SemiStep/SemiStep.Tests/Domain/PlcRunEndSyncTests.cs @@ -185,7 +185,7 @@ private async Task KeepLocalDuringRunAsync() _s7Service.RaiseStateChanged(PlcConnectionState.Connected); await TestHelpers.WaitUntilAsync(() => conflict is not null, TestContext.Current.CancellationToken); - _plc.ResolveConflict(conflict!.ComparisonId, PlcConflictAnswer.KeepLocal).IsSuccess.Should().BeTrue(); + _plc.ResolveConflict(conflict!.ComparisonId, PlcConflictAnswer.KeepLocal); await TestHelpers.WaitUntilAsync( () => _faults.OfType().Any(), _syncTimeout, diff --git a/SemiStep/SemiStep.Tests/Domain/PlcWritePauseTests.cs b/SemiStep/SemiStep.Tests/Domain/PlcWritePauseTests.cs index 8e2e620..2e312a0 100644 --- a/SemiStep/SemiStep.Tests/Domain/PlcWritePauseTests.cs +++ b/SemiStep/SemiStep.Tests/Domain/PlcWritePauseTests.cs @@ -302,11 +302,10 @@ public async Task AnswerToAConflictANewerComparisonReplaced_WritesNothing() await CompareAsync(() => _conflicts.Count == 2); var stale = _conflicts.First(); - var result = _plc.ResolveConflict(stale.ComparisonId, PlcConflictAnswer.KeepLocal); + _plc.ResolveConflict(stale.ComparisonId, PlcConflictAnswer.KeepLocal); - result.Value.Should().BeFalse(); _syncService.WritePauseEnds.Should().BeEmpty(); - _plc.ResolveConflict(_conflicts.Last().ComparisonId, PlcConflictAnswer.KeepLocal).IsSuccess.Should().BeTrue(); + _plc.ResolveConflict(_conflicts.Last().ComparisonId, PlcConflictAnswer.KeepLocal); _syncService.WritePauseEnds.Should().ContainSingle("the current conflict still takes its answer"); } @@ -333,7 +332,7 @@ public async Task KeepLocal_EndsThePauseWithAWrite() await EnableAsync(); await CompareAsync(() => !_conflicts.IsEmpty); - _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal).IsSuccess.Should().BeTrue(); + _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal); _syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeSameAs(_session.Current); } @@ -347,7 +346,7 @@ public async Task TakePlc_FailingTheCheck_TurnsSyncOff() await EnableAsync(); await CompareAsync(() => !_conflicts.IsEmpty); - var result = _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.TakePlc); + var result = TakeConflict(_conflicts.Single()); result.IsFailed.Should().BeTrue(); await WaitAsync(() => !_plc.IsSyncEnabled && !_turnOffReasons.IsEmpty); @@ -364,7 +363,7 @@ public async Task ConflictEndedWithoutAChoice_TurnsSyncOff(PlcConflictAnswer ans await EnableAsync(); await CompareAsync(() => !_conflicts.IsEmpty); - _plc.ResolveConflict(_conflicts.Single().ComparisonId, answer).IsSuccess.Should().BeTrue(); + _plc.ResolveConflict(_conflicts.Single().ComparisonId, answer); await WaitAsync(() => !_plc.IsSyncEnabled && !_turnOffReasons.IsEmpty); _turnOffReasons.OfType().Should().ContainSingle() @@ -442,9 +441,8 @@ public async Task AnswerClickedBeforeALinkDrop_WritesNothing() await CompareAsync(() => !_conflicts.IsEmpty); _s7Service.RaiseStateChanged(PlcConnectionState.Disconnected); - var result = _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal); + _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal); - result.Value.Should().BeFalse(); _syncService.WritePauseEnds.Should().BeEmpty(); _syncService.IsWritePaused.Should().BeTrue(); } @@ -471,7 +469,7 @@ public async Task TakePlc_ThatThrows_TurnsSyncOff() await CompareAsync(() => !_conflicts.IsEmpty); _syncService.OnNextNotifyRecipeChanged = () => throw new InvalidOperationException("sync notify failed"); - var answer = () => _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.TakePlc); + var answer = () => TakeConflict(_conflicts.Single()); answer.Should().NotThrow().Which.IsFailed.Should().BeTrue(); await WaitAsync(() => !_plc.IsSyncEnabled && !_turnOffReasons.IsEmpty); @@ -498,10 +496,135 @@ public async Task ReconnectTake_AfterOpenLandedBeforeIt_RaisesTheConflictInstead _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(); + _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal); _syncService.WritePauseEnds.Should().ContainSingle("the conflict takes its answer"); } + [Fact] + public async Task ConflictTake_TakesTheRecipeReadAgain_NotTheOneTheComparisonOffered() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + var newerPlcRecipe = RecipeStubs.WithSteps(WaitActionId, 3); + _s7Service.RecipeToReturn = newerPlcRecipe; + + var result = await TakeAfterReadAsync(_conflicts.Single()); + + result.Value.Should().Be(PlcTakeOutcome.Replaced); + _session.Current.StepCount.Should().Be(newerPlcRecipe.StepCount); + _syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeNull("nothing is written back"); + } + + [Fact] + public async Task ConflictTake_FailedRead_EndsTheConflict_AndDeclaresLinkLoss() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + var screenRecipe = _session.Current; + _s7Service.ManagingAreaToReturn = null; + + var result = await TakeAfterReadAsync(_conflicts.Single()); + + result.HasError().Should().BeTrue(); + _s7Service.DeclareLinkLostCallCount.Should().Be(1); + _session.Current.Should().BeSameAs(screenRecipe); + _plc.ResolveConflict(_conflicts.Single().ComparisonId, PlcConflictAnswer.KeepLocal); + _syncService.WritePauseEnds.Should().BeEmpty("the failed read ended the conflict"); + _plc.IsSyncEnabled.Should().BeTrue(); + } + + [Fact] + public async Task ConflictTake_FailedReadOfAStaleConflict_StillFails_AndDeclaresNothing() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + _s7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + + var result = _plc.TakeConflictRecipe( + _conflicts.Single().ComparisonId, + _session.Current, + Result.Fail("read failed")); + + result.HasError().Should().BeTrue("the operator still learns the read failed"); + _s7Service.DeclareLinkLostCallCount.Should().Be(0); + } + + [Fact] + public async Task ConflictTake_SuccessfulReadOfAStaleConflict_TakesNothing() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + var screenRecipe = _session.Current; + var read = await _plc.ReadRecipeForTakeAsync(TestToken); + _s7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + + var result = _plc.TakeConflictRecipe(_conflicts.Single().ComparisonId, screenRecipe, read); + + result.Value.Should().Be(PlcTakeOutcome.NotReplaced); + _session.Current.Should().BeSameAs(screenRecipe); + _syncService.WritePauseEnds.Should().BeEmpty(); + _plc.IsConflictCurrent(_conflicts.Single().ComparisonId).Should().BeFalse(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ConflictTake_PlcRecipeGone_EndsWithAWriteOfTheScreenRecipe(bool committed) + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + var screenRecipe = _session.Current; + _s7Service.ManagingAreaToReturn = new PlcManagingAreaState(committed, RecipeLines: 0); + _s7Service.RecipeToReturn = Recipe.Empty; + + var result = await TakeAfterReadAsync(_conflicts.Single()); + + result.Value.Should().Be(PlcTakeOutcome.NotReplaced); + result.Successes.OfType().Should().ContainSingle(); + _session.Current.Should().BeSameAs(screenRecipe); + _syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeSameAs(screenRecipe); + } + + [Fact] + public async Task ConflictTake_PlcRecipeNowIdentical_EndsInSyncWithoutAWrite() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + var screenRecipe = _session.Current; + _s7Service.RecipeToReturn = RecipeStubs.DeepCopy(screenRecipe); + + var result = await TakeAfterReadAsync(_conflicts.Single()); + + result.Value.Should().Be(PlcTakeOutcome.NotReplaced); + _session.Current.Should().BeSameAs(screenRecipe); + _syncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeNull(); + _syncService.Status.Should().Be(PlcSyncStatus.Synced); + } + + [Fact] + public async Task ConflictTake_ScreenChangedSinceTheAnswer_KeepsTheOffer() + { + ArrangeConflict(); + await EnableAsync(); + await CompareAsync(() => !_conflicts.IsEmpty); + var answeredScreen = _session.Current; + _session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + var read = await _plc.ReadRecipeForTakeAsync(TestToken); + + var changed = _plc.TakeConflictRecipe(_conflicts.Single().ComparisonId, answeredScreen, read); + + changed.Value.Should().Be(PlcTakeOutcome.ScreenChanged); + _syncService.WritePauseEnds.Should().BeEmpty(); + _plc.TakeConflictRecipe(_conflicts.Single().ComparisonId, _session.Current, read) + .Value.Should().Be(PlcTakeOutcome.Replaced, "the offer stayed for the new 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() { @@ -553,6 +676,17 @@ private void ArrangeFailure(ComparisonFailure failure) } } + private async Task> TakeAfterReadAsync(PlcRecipeConflict conflict) + { + var read = await _plc.ReadRecipeForTakeAsync(TestToken); + return _plc.TakeConflictRecipe(conflict.ComparisonId, _session.Current, read); + } + + private Result TakeConflict(PlcRecipeConflict conflict) + { + return _plc.TakeConflictRecipe(conflict.ComparisonId, _session.Current, Result.Ok(conflict.Plc)); + } + private async Task EnableAsync() { (await _plc.EnableSync(PlcConfiguration.Default)).IsSuccess.Should().BeTrue(); diff --git a/SemiStep/SemiStep.Tests/Helpers/StubPlcSyncService.cs b/SemiStep/SemiStep.Tests/Helpers/StubPlcSyncService.cs index e4185a8..a00d5de 100644 --- a/SemiStep/SemiStep.Tests/Helpers/StubPlcSyncService.cs +++ b/SemiStep/SemiStep.Tests/Helpers/StubPlcSyncService.cs @@ -132,6 +132,18 @@ public void EndWritePauseWithoutWrite() WritePauseEnds.Add((null, false)); } + /// Sets to Synced and pushes a snapshot with it, as the real coordinator does. + public void ConfirmInSync() + { + Status = PlcSyncStatus.Synced; + _plcStateSubject.OnNext(_plcStateSubject.Value with + { + SyncStatus = PlcSyncStatus.Synced, + IsWritePaused = IsWritePaused, + NotWrittenCause = PlcNotWrittenCause.None + }); + } + public void SetSyncEnabled(bool value) { IsSyncEnabled = value; diff --git a/SemiStep/SemiStep.Tests/Helpers/StubS7Service.cs b/SemiStep/SemiStep.Tests/Helpers/StubS7Service.cs index cadbc32..aad722c 100644 --- a/SemiStep/SemiStep.Tests/Helpers/StubS7Service.cs +++ b/SemiStep/SemiStep.Tests/Helpers/StubS7Service.cs @@ -76,6 +76,9 @@ public void PushExecutionState(PlcExecutionInfo info) /// public ReadGate? ManagingAreaReadGate { get; set; } + /// When true, the wait ignores the token, as a read that never honours cancellation. + public bool ManagingAreaReadIgnoresCancellation { get; set; } + /// /// When set, awaits this gate (observing the token) before /// returning. Lets a test suspend the EnableSync handshake at the version read and cancel @@ -183,7 +186,7 @@ public Task> ReadManagingAreaAsync(CancellationToke private async Task> GateThenReadManagingAreaAsync(ReadGate gate, CancellationToken ct) { - await gate.WaitAsync(ct); + await gate.WaitAsync(ManagingAreaReadIgnoresCancellation ? CancellationToken.None : ct); return BuildManagingAreaResult(); } diff --git a/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorWritePauseTests.cs b/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorWritePauseTests.cs index 9f1ba21..f83ce93 100644 --- a/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorWritePauseTests.cs +++ b/SemiStep/SemiStep.Tests/S7/PlcSyncCoordinatorWritePauseTests.cs @@ -115,6 +115,44 @@ public async Task EndWritePauseWithoutWrite_DropsTheHeldRecipe_AndLetsTheNextEdi transport.WriteLog.Should().NotBeEmpty("the pause has ended"); } + [Fact] + public async Task ConfirmInSync_AfterAFailedWrite_SetsTheStatusToSynced() + { + var (coordinator, transport, _) = PlcSyncCoordinatorTests.Build(connected: true); + transport.WriteException = new InvalidOperationException("transport write blew up"); + var layout = PlcSyncCoordinatorTests.BuildTestConfiguration().Layout; + transport.SetReadResponseForDb(layout.IntDb.DbNumber, (_, count) => new byte[count]); + transport.SetReadResponseForDb(layout.FloatDb.DbNumber, (_, count) => new byte[count]); + transport.SetReadResponseForDb(layout.StringDb.DbNumber, (_, count) => new byte[count]); + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: true); + await WaitForAsync(() => coordinator.Status == PlcSyncStatus.Failed); + var snapshots = new List(); + using var subscription = coordinator.PlcState.Subscribe(snapshots.Add); + + coordinator.ConfirmInSync(); + + coordinator.Status.Should().Be(PlcSyncStatus.Synced); + snapshots.Last().SyncStatus.Should().Be(PlcSyncStatus.Synced, "the link slot clears its error latch on it"); + } + + [Fact] + public void ConfirmInSync_AfterATakeWithWarnings_EndsWithASnapshotThatHoldsNothingUnwritten() + { + var (coordinator, _, _) = PlcSyncCoordinatorTests.Build(connected: true); + var snapshots = new List(); + using var subscription = coordinator.PlcState.Subscribe(snapshots.Add); + coordinator.HandleConnectionLost(); + coordinator.NotifyRecipeChanged(Recipe.Empty, isValid: false); + + coordinator.EndWritePauseWithoutWrite(); + coordinator.ConfirmInSync(); + + snapshots.Last().Should().Match(snapshot => + snapshot.SyncStatus == PlcSyncStatus.Synced + && !snapshot.IsWritePaused + && snapshot.NotWrittenCause == PlcNotWrittenCause.None); + } + [Fact] public async Task EditAfterSyncOff_StartsNoWrite() { diff --git a/SemiStep/SemiStep.Tests/UI/Localization/CoreErrorLocalizationCoverageTests.cs b/SemiStep/SemiStep.Tests/UI/Localization/CoreErrorLocalizationCoverageTests.cs index 941674a..3aefd00 100644 --- a/SemiStep/SemiStep.Tests/UI/Localization/CoreErrorLocalizationCoverageTests.cs +++ b/SemiStep/SemiStep.Tests/UI/Localization/CoreErrorLocalizationCoverageTests.cs @@ -68,6 +68,10 @@ public sealed class CoreErrorLocalizationCoverageTests new ConflictUnresolvedError(dialogShowFailed: false), [typeof(PlcRecipeNotLoadedError)] = new PlcRecipeNotLoadedError([new Error("x")]), + [typeof(PlcTakeReadFailedError)] = + new PlcTakeReadFailedError(isLinkLossDeclared: true), + [typeof(PlcRecipeAbsentWarning)] = + new PlcRecipeAbsentWarning(), [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 ceea405..5992c9f 100644 --- a/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowConflictResolutionTests.cs +++ b/SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowConflictResolutionTests.cs @@ -67,6 +67,7 @@ public async Task KeepLocal_EndsThePauseWithAWriteOfTheScreenRecipe() public async Task LoadFromPlc_TakesThePlcRecipe_AndEndsThePauseWithoutAWrite() { _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(false)); + _fixture.Session.MarkSaved(); var plcRecipe = await RaiseConflictAsync(); await WaitUntilAsync(() => _fixture.PlcSyncService.WritePauseEnds.Count > 0); @@ -81,6 +82,7 @@ public async Task LoadFromPlc_TakesThePlcRecipe_AndEndsThePauseWithoutAWrite() public async Task LoadFromPlc_FailingTheCheck_TurnsSyncOff_AndKeepsTheScreenRecipe() { _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(false)); + _fixture.Session.MarkSaved(); var recipeBefore = _fixture.Coordinator.CurrentRecipe; await RaiseConflictAsync(RecipeStubs.LoopsNestedDeeperThanLimit()); diff --git a/SemiStep/SemiStep.Tests/UI/MainWindow/PlcRecipeTakeDuringSaveTests.cs b/SemiStep/SemiStep.Tests/UI/MainWindow/PlcRecipeTakeDuringSaveTests.cs new file mode 100644 index 0000000..64aed8f --- /dev/null +++ b/SemiStep/SemiStep.Tests/UI/MainWindow/PlcRecipeTakeDuringSaveTests.cs @@ -0,0 +1,94 @@ +using System.Reactive.Linq; +using System.Reactive.Threading.Tasks; + +using Avalonia.Headless.XUnit; +using Avalonia.Threading; + +using AwesomeAssertions; + +using SemiStep.Core.Plc.State; +using SemiStep.Tests.Core.Helpers; +using SemiStep.Tests.Helpers; +using SemiStep.Tests.UI.Helpers; + +using SemiStep.UI.Localization; +using SemiStep.UI.MainWindow; +using SemiStep.UI.RecipeFile; + +using Xunit; + +namespace SemiStep.Tests.UI.MainWindow; + +/// A save command holds the conflict take, so the saved file name never lands on the taken recipe. +[Trait("Component", "UI")] +[Trait("Area", "PlcConflict")] +[Trait("Category", "Integration")] +public sealed class PlcRecipeTakeDuringSaveTests : IAsyncLifetime +{ + private readonly UIFixture _fixture; + private readonly string _savedAsFilePath = + Path.Combine(Path.GetTempPath(), $"take-during-save-{Guid.NewGuid():N}.csv"); + private HeldCsvService _heldCsvService = null!; + private MainWindowViewModel _viewModel = null!; + + public PlcRecipeTakeDuringSaveTests() + { + _fixture = new UIFixture(serializer => _heldCsvService = new HeldCsvService(serializer)); + } + + public async ValueTask InitializeAsync() + { + await _fixture.InitializeAsync(); + _fixture.SeedRecipe(2); + _viewModel = _fixture.CreateMainWindowViewModel(); + } + + public async ValueTask DisposeAsync() + { + _viewModel.Dispose(); + await _fixture.DisposeAsync(); + File.Delete(_savedAsFilePath); + } + + [AvaloniaFact] + public async Task SaveThatOutlivesATake_LeavesTheTakenRecipeUntitled() + { + _viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(_savedAsFilePath)); + _viewModel.RecipeFile.UnsavedChangesInteraction.RegisterHandler( + context => context.SetOutput(UnsavedChangesChoice.DontSave)); + var conflictDialogCount = 0; + _viewModel.ResolveConflictInteraction.RegisterHandler(context => + { + conflictDialogCount++; + context.SetOutput(false); + }); + var save = _viewModel.RecipeFile.SaveAsRecipeCommand.Execute().ToTask(); + await _heldCsvService.SaveEntered; + + var plcRecipe = RecipeStubs.WithSteps(RecipeTestDriver.WaitActionId, 3); + _fixture.S7Service.ManagingAreaToReturn = + new PlcManagingAreaState(Committed: true, RecipeLines: plcRecipe.StepCount); + _fixture.S7Service.RecipeToReturn = plcRecipe; + (await _fixture.Coordinator.EnableSync()).IsSuccess.Should().BeTrue(); + _fixture.S7Service.RaiseStateChanged(PlcConnectionState.Connected); + await WaitUntilAsync(() => conflictDialogCount == 1); + _heldCsvService.Release(); + (await save).Should().BeTrue(); + await WaitUntilAsync(() => _fixture.PlcSyncService.WritePauseEnds.Count > 0 && !_viewModel.IsBusy); + + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(plcRecipe.StepCount); + _viewModel.RecipeFile.CurrentFilePath.Should().BeNull(); + _viewModel.WindowTitle.Should().Be("SemiStep - " + Resources.WindowTitlePlcRecipe + " *"); + } + + 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/PlcRecipeTakeTests.cs b/SemiStep/SemiStep.Tests/UI/MainWindow/PlcRecipeTakeTests.cs new file mode 100644 index 0000000..033dc61 --- /dev/null +++ b/SemiStep/SemiStep.Tests/UI/MainWindow/PlcRecipeTakeTests.cs @@ -0,0 +1,662 @@ +using System.Collections.Concurrent; +using System.Reactive.Linq; + +using Avalonia.Controls; +using Avalonia.Headless; +using Avalonia.Headless.XUnit; +using Avalonia.Input; +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; +using SemiStep.UI.MainWindow; +using SemiStep.UI.MessageService; +using SemiStep.UI.Plc; +using SemiStep.UI.RecipeFile; + +using Xunit; + +using MainWindowView = SemiStep.UI.MainWindow.MainWindow; + +namespace SemiStep.Tests.UI.MainWindow; + +/// The conflict take and the reconnect take: the prompt, the read again, and the untitled result. +[Trait("Component", "UI")] +[Trait("Area", "PlcConflict")] +[Trait("Category", "Integration")] +public sealed class PlcRecipeTakeTests : IAsyncLifetime +{ + private const string TitlePrefix = "SemiStep - "; + private const int PlcStepCount = 3; + + private readonly UIFixture _fixture = new(); + private readonly ConcurrentQueue _turnOffReasons = new(); + private readonly string _savedAsFilePath = + Path.Combine(Path.GetTempPath(), $"take-saved-as-{Guid.NewGuid():N}.csv"); + private MainWindowViewModel _viewModel = null!; + private IDisposable? _turnOffSubscription; + private int _conflictDialogCount; + private int _promptCount; + + private static string PlcRecipeTitle => TitlePrefix + Resources.WindowTitlePlcRecipe + " *"; + + public async ValueTask InitializeAsync() + { + await _fixture.InitializeAsync(); + _fixture.SeedRecipe(2); + _viewModel = _fixture.CreateMainWindowViewModel(); + _turnOffSubscription = _fixture.Plc.SyncTurnOffs.Subscribe(_turnOffReasons.Enqueue); + } + + public async ValueTask DisposeAsync() + { + _turnOffSubscription?.Dispose(); + _viewModel.Dispose(); + await _fixture.DisposeAsync(); + File.Delete(_savedAsFilePath); + } + + [AvaloniaFact] + public async Task Clean_TakesTheRecipeReadAgain_UntitledAndUnsaved_WithNothingWrittenBack() + { + _fixture.Session.MarkSaved(); + var newerPlcRecipe = RecipeStubs.WithSteps(RecipeTestDriver.WaitActionId, PlcStepCount + 1); + AnswerConflict(() => _fixture.S7Service.RecipeToReturn = newerPlcRecipe, false); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(newerPlcRecipe.StepCount); + _fixture.Coordinator.IsDirty.Should().BeTrue(); + _fixture.Coordinator.CanUndo.Should().BeFalse(); + _fixture.PlcSyncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeNull(); + _viewModel.RecipeFile.CurrentFilePath.Should().BeNull(); + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeTrue(); + _viewModel.WindowTitle.Should().Be(PlcRecipeTitle); + _viewModel.IsBusy.Should().BeFalse(); + _promptCount.Should().Be(0); + } + + [AvaloniaFact] + public async Task Dirty_AsksFirst_AndDontSaveTakes_ClearingUndoAndRedo() + { + _fixture.Coordinator.Undo().IsSuccess.Should().BeTrue(); + _fixture.Coordinator.CanRedo.Should().BeTrue(); + AnswerPrompt(UnsavedChangesChoice.DontSave); + AnswerConflict(null, false); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + + _promptCount.Should().Be(1); + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(PlcStepCount); + _fixture.Coordinator.CanUndo.Should().BeFalse(); + _fixture.Coordinator.CanRedo.Should().BeFalse(); + _viewModel.WindowTitle.Should().Be(PlcRecipeTitle); + } + + [AvaloniaFact] + public async Task Dirty_SaveOnAnUntitledRecipe_SavesAsFirst_ThenTakes() + { + var screenStepCount = _fixture.Coordinator.CurrentRecipe.StepCount; + AnswerPrompt(UnsavedChangesChoice.Save); + _viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(_savedAsFilePath)); + AnswerConflict(null, false); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + + var saved = await _fixture.CsvService.LoadAsync(_savedAsFilePath); + saved.Value.StepCount.Should().Be(screenStepCount, "the screen recipe was saved before the take"); + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(PlcStepCount); + _viewModel.RecipeFile.CurrentFilePath.Should().BeNull(); + _viewModel.WindowTitle.Should().Be(PlcRecipeTitle); + } + + [AvaloniaFact] + public async Task Dirty_CancelInThePrompt_ShowsTheConflictDialogAgain() + { + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + AnswerPrompt(UnsavedChangesChoice.Cancel); + AnswerConflict(null, false, true); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + + ShouldHaveReturnedToTheDialog(screenRecipe); + } + + [AvaloniaTheory] + [InlineData(true)] + [InlineData(false)] + public async Task Dirty_SaveThatIsCancelledOrFails_ShowsTheConflictDialogAgain(bool isPickerCancelled) + { + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + var path = isPickerCancelled + ? null + : Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}", "recipe.csv"); + AnswerPrompt(UnsavedChangesChoice.Save); + _viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(path)); + AnswerConflict(null, false, true); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + + ShouldHaveReturnedToTheDialog(screenRecipe); + } + + [AvaloniaFact] + public async Task EditDuringTheRead_AsksBeforeTaking() + { + _fixture.Session.MarkSaved(); + var gate = new ReadGate(); + AnswerPrompt(UnsavedChangesChoice.DontSave); + AnswerConflict(() => _fixture.S7Service.ManagingAreaReadGate = gate, false); + await RaiseConflictAsync(); + await WaitUntilAsync(() => _viewModel.IsBusy); + + _fixture.Coordinator.AppendStep(RecipeTestDriver.WaitActionId).IsSuccess.Should().BeTrue(); + _fixture.S7Service.ManagingAreaReadGate = null; + gate.Release(); + await WaitForPauseEndAsync(); + + _promptCount.Should().Be(1, "the screen gained an unsaved change during the read"); + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(PlcStepCount); + } + + [AvaloniaFact] + public async Task ReadAgainFails_ChangesNothing_ReportsIt_AndDeclaresLinkLoss() + { + _fixture.Session.MarkSaved(); + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + var titleBefore = _viewModel.WindowTitle; + AnswerConflict(() => _fixture.S7Service.ManagingAreaToReturn = null, false); + + await RaiseConflictAsync(); + await WaitUntilAsync(() => _fixture.S7Service.DeclareLinkLostCallCount > 0); + + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(screenRecipe); + _viewModel.WindowTitle.Should().Be(titleBefore); + _fixture.PlcSyncService.WritePauseEnds.Should().BeEmpty(); + _fixture.Coordinator.IsSyncEnabled.Should().BeTrue(); + _viewModel.IsBusy.Should().BeFalse(); + ShouldReportTheTakeReadFailure(); + + _fixture.PlcSyncService.PushFault(new ConnectionLostError()); + Dispatcher.UIThread.RunJobs(); + + ShouldReportTheTakeReadFailure(); + } + + [AvaloniaFact] + public async Task ReadThatNeverReturns_EndsTheBusyLookAtTheBound() + { + _fixture.Session.MarkSaved(); + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + var gate = new ReadGate(); + AnswerConflict( + () => + { + _fixture.S7Service.ManagingAreaReadGate = gate; + _fixture.S7Service.ManagingAreaReadIgnoresCancellation = true; + }, + false); + await RaiseConflictAsync(); + await WaitUntilAsync(() => _viewModel.IsBusy); + _viewModel.PlcLink.View.Kind.Should().Be(PlcLinkKind.TakeReading); + + _fixture.Scheduler.AdvanceBy(PlcRecipeTake.ReadBound - TimeSpan.FromMilliseconds(1)); + Dispatcher.UIThread.RunJobs(); + _viewModel.IsBusy.Should().BeTrue(); + _fixture.Scheduler.AdvanceBy(TimeSpan.FromMilliseconds(1)); + await WaitUntilAsync(() => !_viewModel.IsBusy); + + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(screenRecipe); + _fixture.S7Service.DeclareLinkLostCallCount.Should().Be(1); + _viewModel.PlcLink.View.Kind.Should().NotBe(PlcLinkKind.TakeReading); + ShouldReportTheTakeReadFailure(); + gate.Release(); + } + + [AvaloniaFact] + public async Task PlcRecipeNowIdentical_EndsInSync_WithoutAWrite() + { + _fixture.Session.MarkSaved(); + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + AnswerConflict(() => _fixture.S7Service.RecipeToReturn = RecipeStubs.DeepCopy(screenRecipe), false); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + + _fixture.PlcSyncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeNull(); + _fixture.PlcSyncService.Status.Should().Be(PlcSyncStatus.Synced); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(screenRecipe); + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeFalse(); + } + + [AvaloniaTheory] + [InlineData(false)] + [InlineData(true)] + public async Task PlcRecipeGone_EndsWithAWriteOfTheScreenRecipe_AndSaysSo(bool committed) + { + _fixture.Session.MarkSaved(); + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + AnswerConflict( + () => + { + _fixture.S7Service.ManagingAreaToReturn = new PlcManagingAreaState(committed, RecipeLines: 0); + _fixture.S7Service.RecipeToReturn = Recipe.Empty; + }, + false); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + + _fixture.PlcSyncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeSameAs(screenRecipe); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(screenRecipe); + _fixture.MessagePanel.Entries.Should().Contain(entry => + entry.Severity == MessageSeverity.Warning + && entry.Message == ReasonLocalizer.Localize(new PlcRecipeAbsentWarning())); + } + + [AvaloniaFact] + public async Task CheckFails_ChangesNothing_AndTurnsSyncOff() + { + _fixture.Session.MarkSaved(); + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + var titleBefore = _viewModel.WindowTitle; + AnswerConflict( + () => _fixture.S7Service.RecipeToReturn = RecipeStubs.LoopsNestedDeeperThanLimit(), + false); + + await RaiseConflictAsync(); + await WaitForSyncOffAsync(); + + _turnOffReasons.OfType().Should().ContainSingle(); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(screenRecipe); + _viewModel.WindowTitle.Should().Be(titleBefore); + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeFalse(); + _fixture.PlcSyncService.WritePauseEnds.Should().BeEmpty(); + } + + [AvaloniaFact] + public async Task AfterAFailedWrite_ShowsConnected() + { + _fixture.Session.MarkSaved(); + AnswerConflict( + () => _fixture.PlcSyncService.PushPlcState( + new PlcSessionSnapshot(PlcConnectionState.Connected, PlcSyncStatus.Failed, IsSyncEnabled: true)), + false); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + Dispatcher.UIThread.RunJobs(); + + _viewModel.PlcLink.View.Kind.Should().Be(PlcLinkKind.Connected); + } + + [AvaloniaFact] + public async Task AfterATake_SaveOpensSaveAs_AndTheNameEndsOnlyWhenItSucceeds() + { + await TakeCleanAsync(); + var pickedPaths = new Queue([null, _savedAsFilePath]); + var saveAsCount = 0; + _viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => + { + saveAsCount++; + context.SetOutput(pickedPaths.Dequeue()); + }); + + (await _viewModel.RecipeFile.SaveRecipeCommand.Execute()).Should().BeFalse(); + + saveAsCount.Should().Be(1); + _viewModel.WindowTitle.Should().Be(PlcRecipeTitle, "a cancelled save keeps the name"); + + (await _viewModel.RecipeFile.SaveRecipeCommand.Execute()).Should().BeTrue(); + + saveAsCount.Should().Be(2); + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeFalse(); + _viewModel.WindowTitle.Should().Be(TitlePrefix + Path.GetFileNameWithoutExtension(_savedAsFilePath)); + } + + [AvaloniaFact] + public async Task AfterATake_New_EndsTheName() + { + await TakeCleanAsync(); + AnswerPrompt(UnsavedChangesChoice.DontSave); + + await _viewModel.RecipeFile.NewRecipeCommand.Execute(); + + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeFalse(); + _viewModel.WindowTitle.Should().Be(TitlePrefix + Resources.WindowTitleNewRecipe); + } + + [AvaloniaFact] + public async Task KeyDuringTheTake_ChangesNothing() + { + _viewModel.RecipeGrid.Initialize(); + var window = new MainWindowView { ViewModel = _viewModel }; + window.Show(); + Dispatcher.UIThread.RunJobs(); + try + { + _fixture.Session.MarkSaved(); + var gate = new ReadGate(); + AnswerConflict(() => _fixture.S7Service.ManagingAreaReadGate = gate, false); + await RaiseConflictAsync(); + await WaitUntilAsync(() => _viewModel.IsBusy); + var overlay = window.FindControl("BusyOverlay"); + overlay.Should().NotBeNull(); + overlay.IsVisible.Should().BeTrue(); + _viewModel.RecipeGrid.UpdateSelection([0]); + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + + window.KeyPressQwerty(PhysicalKey.Delete, RawInputModifiers.None); + window.KeyPressQwerty(PhysicalKey.N, RawInputModifiers.Control | RawInputModifiers.Shift); + Dispatcher.UIThread.RunJobs(); + + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(screenRecipe); + window.OwnedWindows.Should().BeEmpty(); + gate.Release(); + await WaitForPauseEndAsync(); + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(PlcStepCount); + } + finally + { + _fixture.Session.MarkSaved(); + window.Close(); + } + } + + [AvaloniaFact] + public async Task ReconnectTake_LoadsUntitledAndUnsaved_WithoutAReadAgain() + { + _fixture.Coordinator.NewRecipe().IsSuccess.Should().BeTrue(); + ArrangePlcRecipe(RecipeStubs.WithSteps(RecipeTestDriver.WaitActionId, PlcStepCount)); + + await ReconnectAsync(); + await WaitForPauseEndAsync(); + + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(PlcStepCount); + _fixture.Coordinator.IsDirty.Should().BeTrue(); + _fixture.Coordinator.CanUndo.Should().BeFalse(); + _fixture.PlcSyncService.WritePauseEnds.Should().ContainSingle().Which.Recipe.Should().BeNull(); + _fixture.S7Service.ReadRecipeFromPlcCallCount.Should().Be(1); + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeTrue(); + _viewModel.WindowTitle.Should().Be(PlcRecipeTitle); + } + + [AvaloniaFact] + public async Task ReconnectTake_OverAnEmptyRecipeWithUnsavedChanges_RaisesTheConflictInstead() + { + _fixture.Session.MarkSaved(); + _fixture.Coordinator.RemoveSteps([0, 1]).IsSuccess.Should().BeTrue(); + AnswerConflict(null, true); + ArrangePlcRecipe(RecipeStubs.WithSteps(RecipeTestDriver.WaitActionId, PlcStepCount)); + + await ReconnectAsync(); + await WaitUntilAsync(() => _conflictDialogCount == 1); + + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(0); + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeFalse(); + } + + [AvaloniaFact] + public async Task ReconnectTake_FailingTheCheck_ChangesNothing_AndTurnsSyncOff() + { + _fixture.Coordinator.NewRecipe().IsSuccess.Should().BeTrue(); + var titleBefore = _viewModel.WindowTitle; + ArrangePlcRecipe(RecipeStubs.LoopsNestedDeeperThanLimit()); + + await ReconnectAsync(); + await WaitForSyncOffAsync(); + + _turnOffReasons.OfType().Should().ContainSingle(); + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(0); + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeFalse(); + _viewModel.WindowTitle.Should().Be(titleBefore); + } + + [AvaloniaFact] + public async Task CloseRequestDuringTheTake_IsRefused() + { + _viewModel.RecipeGrid.Initialize(); + var window = new MainWindowView { ViewModel = _viewModel }; + window.Show(); + Dispatcher.UIThread.RunJobs(); + try + { + _fixture.Session.MarkSaved(); + var gate = new ReadGate(); + AnswerConflict(() => _fixture.S7Service.ManagingAreaReadGate = gate, false); + await RaiseConflictAsync(); + await WaitUntilAsync(() => _viewModel.IsBusy); + + window.Close(); + Dispatcher.UIThread.RunJobs(); + + window.IsVisible.Should().BeTrue("the busy look refuses a close request"); + window.OwnedWindows.Should().BeEmpty(); + gate.Release(); + await WaitForPauseEndAsync(); + } + finally + { + _fixture.Session.MarkSaved(); + window.Close(); + } + } + + [AvaloniaTheory] + [InlineData(UnsavedChangesChoice.DontSave)] + [InlineData(UnsavedChangesChoice.Cancel)] + public async Task LinkDropDuringThePrompt_EndsTheTake_WithoutAReadOrTheDialogAgain(UnsavedChangesChoice choice) + { + var screenRecipe = _fixture.Coordinator.CurrentRecipe; + var readsAtThePrompt = -1; + _viewModel.RecipeFile.UnsavedChangesInteraction.RegisterHandler(context => + { + _promptCount++; + readsAtThePrompt = _fixture.S7Service.ReadManagingAreaCallCount; + _fixture.S7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + context.SetOutput(choice); + }); + AnswerConflict(null, false, true); + + await RaiseConflictAsync(); + await WaitUntilAsync(() => _promptCount == 1); + await SettleAsync(); + + _fixture.S7Service.ReadManagingAreaCallCount.Should().Be(readsAtThePrompt, "a stale conflict reads nothing"); + _conflictDialogCount.Should().Be(1, "a stale conflict dialog is not shown again"); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(screenRecipe); + _fixture.PlcSyncService.WritePauseEnds.Should().BeEmpty(); + _viewModel.IsBusy.Should().BeFalse(); + } + + [AvaloniaFact] + public async Task FailedReadOfAStaleConflict_LeavesTheNextLinkLossReported() + { + _fixture.Session.MarkSaved(); + var gate = new ReadGate(); + AnswerConflict(() => _fixture.S7Service.ManagingAreaReadGate = gate, false); + await RaiseConflictAsync(); + await WaitUntilAsync(() => _viewModel.IsBusy); + + _fixture.S7Service.RaiseStateChanged(PlcConnectionState.Disconnected); + _fixture.S7Service.ManagingAreaToReturn = null; + gate.Release(); + await WaitUntilAsync(() => !_viewModel.IsBusy); + ShouldReportTheTakeReadFailure(); + _fixture.S7Service.DeclareLinkLostCallCount.Should().Be(0); + + _fixture.PlcSyncService.PushFault(new ConnectionLostError()); + Dispatcher.UIThread.RunJobs(); + + ShouldReportTheLinkLoss(); + } + + [AvaloniaFact] + public async Task LinkLossAfterTheDroppedOne_IsReported() + { + _fixture.Session.MarkSaved(); + AnswerConflict(() => _fixture.S7Service.ManagingAreaToReturn = null, false); + await RaiseConflictAsync(); + await WaitUntilAsync(() => _fixture.S7Service.DeclareLinkLostCallCount > 0); + _fixture.PlcSyncService.PushFault(new ConnectionLostError()); + Dispatcher.UIThread.RunJobs(); + ShouldReportTheTakeReadFailure(); + + _fixture.PlcSyncService.PushFault(new ConnectionLostError()); + Dispatcher.UIThread.RunJobs(); + + ShouldReportTheLinkLoss(); + } + + [AvaloniaFact] + public async Task Dirty_SaveOnARecipeWithAFile_SavesToIt_ThenTakes() + { + (await _fixture.CsvService.SaveAsync(_fixture.Coordinator.CurrentRecipe, _savedAsFilePath)).IsSuccess + .Should().BeTrue(); + _fixture.Session.MarkSaved(); + _viewModel.RecipeFile.OpenFileInteraction.RegisterHandler(context => context.SetOutput(_savedAsFilePath)); + await _viewModel.RecipeFile.LoadRecipeCommand.Execute(); + _viewModel.RecipeFile.CurrentFilePath.Should().Be(_savedAsFilePath); + _fixture.Coordinator.AppendStep(RecipeTestDriver.WaitActionId).IsSuccess.Should().BeTrue(); + var editedStepCount = _fixture.Coordinator.CurrentRecipe.StepCount; + var saveAsCount = 0; + _viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => + { + saveAsCount++; + context.SetOutput(null); + }); + AnswerPrompt(UnsavedChangesChoice.Save); + AnswerConflict(null, false); + + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + + saveAsCount.Should().Be(0, "a recipe with a file saves to it"); + (await _fixture.CsvService.LoadAsync(_savedAsFilePath)).Value.StepCount.Should().Be(editedStepCount); + _fixture.Coordinator.CurrentRecipe.StepCount.Should().Be(PlcStepCount); + _viewModel.RecipeFile.CurrentFilePath.Should().BeNull(); + _viewModel.WindowTitle.Should().Be(PlcRecipeTitle); + } + + private async Task TakeCleanAsync() + { + _fixture.Session.MarkSaved(); + AnswerConflict(null, false); + await RaiseConflictAsync(); + await WaitForPauseEndAsync(); + _viewModel.WindowTitle.Should().Be(PlcRecipeTitle); + } + + private void ShouldHaveReturnedToTheDialog(Recipe screenRecipe) + { + _conflictDialogCount.Should().Be(2); + _promptCount.Should().Be(1); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs(screenRecipe); + _fixture.PlcSyncService.WritePauseEnds.Should().ContainSingle("the second answer keeps the local recipe") + .Which.Recipe.Should().BeSameAs(screenRecipe); + _viewModel.RecipeFile.IsTakenFromPlc.Should().BeFalse(); + } + + private void ShouldReportTheLinkLoss() + { + _fixture.MessagePanel.Entries.Should().Contain(entry => + entry.Message == ReasonLocalizer.Localize(new ConnectionLostError())); + } + + private static async Task SettleAsync() + { + for (var i = 0; i < 10; i++) + { + Dispatcher.UIThread.RunJobs(); + await Task.Delay(10, TestContext.Current.CancellationToken); + } + } + + private void ShouldReportTheTakeReadFailure() + { + _fixture.MessagePanel.Entries.Should().Contain(entry => + entry.Severity == MessageSeverity.Error + && entry.Message == ReasonLocalizer.Localize(new PlcTakeReadFailedError(isLinkLossDeclared: true))); + } + + /// Answers each conflict dialog in turn; runs inside every one. + private void AnswerConflict(Action? beforeAnswer, params bool?[] answers) + { + var pending = new Queue(answers); + _viewModel.ResolveConflictInteraction.RegisterHandler(context => + { + _conflictDialogCount++; + beforeAnswer?.Invoke(); + context.SetOutput(pending.Dequeue()); + }); + } + + private void AnswerPrompt(UnsavedChangesChoice choice) + { + _viewModel.RecipeFile.UnsavedChangesInteraction.RegisterHandler(context => + { + _promptCount++; + context.SetOutput(choice); + }); + } + + private void ArrangePlcRecipe(Recipe plcRecipe) + { + _fixture.S7Service.ManagingAreaToReturn = + new PlcManagingAreaState(Committed: true, RecipeLines: plcRecipe.StepCount); + _fixture.S7Service.RecipeToReturn = plcRecipe; + } + + /// Turns sync on over the screen recipe and raises a reconnect whose PLC recipe differs. + private async Task RaiseConflictAsync() + { + ArrangePlcRecipe(RecipeStubs.WithSteps(RecipeTestDriver.WaitActionId, PlcStepCount)); + var conflictRaised = false; + _fixture.Plc.PlcRecipeConflictDetected += _ => conflictRaised = true; + + await ReconnectAsync(); + await WaitUntilAsync(() => conflictRaised); + } + + private async Task ReconnectAsync() + { + (await _fixture.Coordinator.EnableSync()).IsSuccess.Should().BeTrue(); + _fixture.S7Service.RaiseStateChanged(PlcConnectionState.Connected); + } + + private Task WaitForPauseEndAsync() + { + return WaitUntilAsync(() => _fixture.PlcSyncService.WritePauseEnds.Count > 0 && !_viewModel.IsBusy); + } + + 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/Plc/PlcLinkViewModelTests.cs b/SemiStep/SemiStep.Tests/UI/Plc/PlcLinkViewModelTests.cs index 7aa4668..2571cb5 100644 --- a/SemiStep/SemiStep.Tests/UI/Plc/PlcLinkViewModelTests.cs +++ b/SemiStep/SemiStep.Tests/UI/Plc/PlcLinkViewModelTests.cs @@ -28,6 +28,7 @@ public sealed class PlcLinkViewModelTests : IAsyncLifetime private readonly UIFixture _fixture = new(); private readonly Subject _toggle = new(); + private readonly Subject _takeReading = new(); private PlcLinkViewModel _viewModel = null!; public async ValueTask InitializeAsync() @@ -40,6 +41,7 @@ public ValueTask DisposeAsync() { _viewModel.Dispose(); _toggle.Dispose(); + _takeReading.Dispose(); return _fixture.DisposeAsync(); } @@ -372,6 +374,7 @@ private PlcLinkViewModel Create(PlcLinkAddress address) _fixture.Coordinator, address, _toggle.AsObservable(), + _takeReading.AsObservable(), _fixture.Scheduler); } diff --git a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs index 9b178b0..d5bc86b 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorTests.cs @@ -2,6 +2,8 @@ using AwesomeAssertions; +using FluentResults; + using SemiStep.Core.Plc; using SemiStep.Core.Plc.State; using SemiStep.Core.Plc.Sync; @@ -511,7 +513,10 @@ await TestHelpers.WaitUntilAsync( var sink = new RecordingRecipeSink(); _fixture.Coordinator.Mutated += sink.OnMutation; - var result = _fixture.Coordinator.ResolveConflict(conflict!.ComparisonId, PlcConflictAnswer.TakePlc); + var result = _fixture.Coordinator.TakeConflictRecipe( + conflict!.ComparisonId, + _fixture.Coordinator.CurrentRecipe, + Result.Ok(conflict.Plc)); 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 3b1494d..00ab6d1 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs @@ -11,6 +11,7 @@ using SemiStep.Tests.Helpers; using SemiStep.Tests.UI.Helpers; using SemiStep.UI.MainWindow; +using SemiStep.UI.RecipeFile; using SemiStep.UI.RecipeGrid; using Xunit; @@ -171,6 +172,8 @@ public async Task ConflictResolvedWithThePlcRecipe_StartsWithoutMarks() var plcRecipe = new Recipe([waitStep, waitStep, waitStep, waitStep]); ChangeAction(0, RecipeTestDriver.ForLoopActionId); _viewModel.ResolveConflictInteraction.RegisterHandler(context => context.SetOutput(false)); + _viewModel.RecipeFile.UnsavedChangesInteraction.RegisterHandler( + context => context.SetOutput(UnsavedChangesChoice.DontSave)); _fixture.S7Service.ManagingAreaToReturn = new PlcManagingAreaState(Committed: true, RecipeLines: 4); _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 4fdc557..963b9ec 100644 --- a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs +++ b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs @@ -1,4 +1,5 @@ -using System.Reactive.Linq; +using System.Reactive.Disposables; +using System.Reactive.Linq; using System.Reactive.Subjects; using Avalonia.Threading; @@ -37,6 +38,11 @@ public sealed class RecipeCoordinator : IDisposable private PlcConnectionState _connectionState = PlcConnectionState.Disconnected; private bool _disposed; private bool _initialized; + private bool _isLinkLossExplainedByTake; + + // UI thread only: a save command holds every take until it ends. + private int _takeHolds; + private TaskCompletionSource _takesAllowed = CompletedTakesAllowed(); private IDisposable? _plcFaultsSubscription; private IDisposable? _plcStateSubscription; private IDisposable? _syncTurnOffsSubscription; @@ -95,6 +101,9 @@ public RecipeCoordinator( public event Action? Mutated; + /// The session recipe was replaced by the PLC recipe, by a conflict take or a reconnect take. + public event Action? PlcRecipeTaken; + public Recipe CurrentRecipe => _session.Current; public RecipeSnapshot Snapshot => _session.Snapshot.IsSuccess @@ -206,28 +215,80 @@ public async Task DisableSync() _logger.LogInformation("PLC sync disabled"); } - /// A take whose check fails turns sync off; Core reports the reason on . - public Result ResolveConflict(long comparisonId, PlcConflictAnswer answer) + /// An answer that turns sync off is reported by Core on . + public void ResolveConflict(long comparisonId, PlcConflictAnswer answer) { _logger.LogInformation( "PLC recipe conflict resolution: Comparison={ComparisonId}, Answer={Answer}", comparisonId, answer); - var result = _plc.ResolveConflict(comparisonId, answer); + _plc.ResolveConflict(comparisonId, answer); + } - if (result.IsFailed) + public Task> ReadRecipeForTakeAsync(CancellationToken ct) + { + return _plc.ReadRecipeForTakeAsync(ct); + } + + public bool IsConflictCurrent(long comparisonId) + { + return _plc.IsConflictCurrent(comparisonId); + } + + /// + /// Holds every take of the PLC recipe until the returned scope ends, so a save that outlives a take cannot give + /// the taken recipe the saved file name. UI thread only. + /// + public IDisposable HoldTakes() + { + if (_takeHolds++ == 0) { - _logger.LogWarning("PLC recipe conflict resolution failed: {Errors}", result.FormatErrors()); + _takesAllowed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); } - else if (result.Value) + + return Disposable.Create(ReleaseTakeHold); + } + + /// Completes on the UI thread once no save holds takes. + public async Task WaitForTakesAllowedAsync() + { + while (_takeHolds > 0) { - DispatchMutation(new MutationSignal.RecipeReplaced()); + await _takesAllowed.Task; + } + } + + /// + /// The conflict take after its read. A failed read is reported here; a take whose check fails turns sync off, and + /// Core reports that reason. + /// + public Result TakeConflictRecipe(long comparisonId, Recipe screenRecipe, Result read) + { + _logger.LogInformation("PLC recipe conflict take: Comparison={ComparisonId}", comparisonId); + + var result = _plc.TakeConflictRecipe(comparisonId, screenRecipe, read); + if (result.Errors.OfType().FirstOrDefault() is { } readFailed) + { + _isLinkLossExplainedByTake = readFailed.IsLinkLossDeclared; + _messagePanel.ReportFailure(result); + } + else if (result.IsFailed) + { + _logger.LogWarning("PLC recipe conflict take failed: {Errors}", result.FormatErrors()); + } + else if (result.Value == PlcTakeOutcome.Replaced) + { + CompleteTake(); + } + else + { + _messagePanel.ReportWarnings(result); } RebuildMessagePanel(); - return result.ToResult(); + return result; } public Result AppendStep(int actionId) @@ -382,8 +443,9 @@ public async Task SaveRecipeAsync(string filePath) private async Task ApplyReconnectPlcRecipeAsync(Recipe recipe) { // Reconnect reconciliation resumes off-thread; marshal to the UI dispatcher before mutating. - return await Dispatcher.UIThread.InvokeAsync(() => + return await Dispatcher.UIThread.InvokeAsync(async () => { + await WaitForTakesAllowedAsync(); var applyResult = _plc.ApplyRecipeFromPlc(recipe); if (applyResult.IsFailed) { @@ -404,13 +466,34 @@ private async Task ApplyReconnectPlcRecipeAsync(Recipe recipe) "Reconnect reconciliation applied PLC recipe: {StepCount} steps", _session.Current.StepCount); - DispatchMutation(new MutationSignal.RecipeReplaced()); + CompleteTake(); RebuildMessagePanel(); return applyResult.ToResult(); }); } + private static TaskCompletionSource CompletedTakesAllowed() + { + var completed = new TaskCompletionSource(); + completed.SetResult(); + return completed; + } + + private void ReleaseTakeHold() + { + if (--_takeHolds == 0) + { + _takesAllowed.TrySetResult(); + } + } + + private void CompleteTake() + { + DispatchMutation(new MutationSignal.RecipeReplaced()); + PlcRecipeTaken?.Invoke(); + } + private Result Track(Result result, MutationSignal signal) { RebuildMessagePanel(); @@ -480,9 +563,16 @@ private void OnPlcStateChanged(PlcSessionSnapshot snapshot) LogPlcStateChange(snapshot); + if (snapshot.ConnectionState == PlcConnectionState.Connected + && _connectionState != PlcConnectionState.Connected) + { + _isLinkLossExplainedByTake = false; + } + // 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(); @@ -501,6 +591,13 @@ private void OnPlcFault(IError error) return; } + if (error is ConnectionLostError && _isLinkLossExplainedByTake) + { + _isLinkLossExplainedByTake = false; + _logger.LogInformation("PLC link loss after a failed take read; the take failure stays in the panel"); + return; + } + if (error is RecipeActiveError) { _logger.LogInformation("PLC sync deferred: {Message}", error.Message); diff --git a/SemiStep/SemiStep.UI/Localization/ReasonLocalizer.cs b/SemiStep/SemiStep.UI/Localization/ReasonLocalizer.cs index 53ee86b..ce2c931 100644 --- a/SemiStep/SemiStep.UI/Localization/ReasonLocalizer.cs +++ b/SemiStep/SemiStep.UI/Localization/ReasonLocalizer.cs @@ -61,6 +61,8 @@ public static string Localize(IReason reason) PlcRecipeNotLoadedError error => Format( Resources.SyncOffPlcRecipeNotLoadedFormat, string.Join("; ", error.Causes.Select(Localize))), + PlcTakeReadFailedError => Resources.ErrorPlcTakeReadFailed, + PlcRecipeAbsentWarning => Resources.WarningPlcRecipeAbsent, 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 8aba879..d508f59 100644 --- a/SemiStep/SemiStep.UI/Localization/Resources.resx +++ b/SemiStep/SemiStep.UI/Localization/Resources.resx @@ -214,6 +214,9 @@ New Recipe + + Recipe from PLC + Local steps: {0} @@ -529,6 +532,9 @@ PLC: connecting… + + PLC: reading recipe… + PLC: disconnecting… @@ -841,6 +847,12 @@ The PLC recipe was not loaded: {0}. Sync is turned off. + + Could not read the recipe from the PLC. + + + The PLC holds no recipe. The screen recipe was written. + 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 1533fa8..1e42bbb 100644 --- a/SemiStep/SemiStep.UI/Localization/Resources.ru.resx +++ b/SemiStep/SemiStep.UI/Localization/Resources.ru.resx @@ -214,6 +214,9 @@ Новый рецепт + + Рецепт из ПЛК + Локально шагов: {0} @@ -529,6 +532,9 @@ ПЛК: подключение… + + ПЛК: чтение рецепта… + ПЛК: отключение… @@ -841,6 +847,12 @@ Рецепт из ПЛК не загружен: {0}. Синхронизация выключена. + + Не удалось прочитать рецепт из ПЛК. + + + Рецепт в ПЛК отсутствует. Записан рецепт с экрана. + Не удалось сообщить об ошибке ПЛК diff --git a/SemiStep/SemiStep.UI/MainWindow/MainWindow.axaml b/SemiStep/SemiStep.UI/MainWindow/MainWindow.axaml index 77568f3..360adcf 100644 --- a/SemiStep/SemiStep.UI/MainWindow/MainWindow.axaml +++ b/SemiStep/SemiStep.UI/MainWindow/MainWindow.axaml @@ -53,6 +53,13 @@ + + diff --git a/SemiStep/SemiStep.UI/MainWindow/MainWindow.axaml.cs b/SemiStep/SemiStep.UI/MainWindow/MainWindow.axaml.cs index 9becf7a..2143ad6 100644 --- a/SemiStep/SemiStep.UI/MainWindow/MainWindow.axaml.cs +++ b/SemiStep/SemiStep.UI/MainWindow/MainWindow.axaml.cs @@ -4,6 +4,7 @@ using Avalonia.Controls; using Avalonia.Input; +using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Platform.Storage; @@ -29,6 +30,7 @@ public MainWindow() InitializeComponent(); Closing += OnWindowClosing; + AddHandler(KeyDownEvent, OnBusyKeyDown, RoutingStrategies.Tunnel); this.WhenActivated(disposables => { @@ -72,6 +74,15 @@ public MainWindow() }); } + /// The busy look takes every key, so no grid key or menu gesture runs. + private void OnBusyKeyDown(object? sender, KeyEventArgs e) + { + if (ViewModel is { IsBusy: true }) + { + e.Handled = true; + } + } + /// Runs the menu item a key no control took names; from a text box only Ctrl+Shift+T runs. protected override void OnKeyDown(KeyEventArgs e) { @@ -118,7 +129,7 @@ private async void OnWindowClosing(object? sender, WindowClosingEventArgs e) return; } - if (_exitChoiceInProgress) + if (_exitChoiceInProgress || ViewModel is { IsBusy: true }) { e.Cancel = true; diff --git a/SemiStep/SemiStep.UI/MainWindow/MainWindowViewModel.cs b/SemiStep/SemiStep.UI/MainWindow/MainWindowViewModel.cs index 206ea0f..51b6ef3 100644 --- a/SemiStep/SemiStep.UI/MainWindow/MainWindowViewModel.cs +++ b/SemiStep/SemiStep.UI/MainWindow/MainWindowViewModel.cs @@ -32,6 +32,7 @@ public class MainWindowViewModel : ReactiveObject, IDisposable private readonly Func _gridStyleEditorViewModelFactory; private readonly ObservableAsPropertyHelper _isTransposedOrientation; private readonly ObservableAsPropertyHelper _windowTitle; + private readonly ObservableAsPropertyHelper _isBusy; private bool _isSyncShownEnabled; public MainWindowViewModel( @@ -67,7 +68,14 @@ public MainWindowViewModel( ToggleToolBarCommand = ReactiveCommand.Create(ExecuteToggleToolBar); ToggleOrientationCommand = ReactiveCommand.Create(recipeGrid.ToggleOrientation); - PlcLink = new PlcLinkViewModel(coordinator, linkAddress, _syncToggle.AsObservable(), scheduler) + PlcTake = new PlcRecipeTake(coordinator, recipeFile, scheduler, logger); + var isTakeReading = PlcTake.WhenAnyValue(x => x.IsReading); + + PlcLink = new PlcLinkViewModel(coordinator, linkAddress, _syncToggle.AsObservable(), isTakeReading, scheduler) + .DisposeWith(_disposables); + + _isBusy = isTakeReading + .ToProperty(this, x => x.IsBusy) .DisposeWith(_disposables); _isTransposedOrientation = recipeGrid @@ -96,6 +104,7 @@ public MainWindowViewModel( _windowTitle = Observable.CombineLatest( recipeFile.WhenAnyValue(x => x.CurrentFilePath), + recipeFile.WhenAnyValue(x => x.IsTakenFromPlc), isDirty, plcMonitor.WhenAnyValue(x => x.IsRecipeActive), BuildWindowTitle) @@ -141,6 +150,8 @@ public MainWindowViewModel( public PlcLinkViewModel PlcLink { get; } + public PlcRecipeTake PlcTake { get; } + public ReactiveCommand ExitCommand { get; } public ReactiveCommand ToggleSyncCommand { get; } @@ -161,6 +172,9 @@ public bool IsToolBarVisible public string WindowTitle => _windowTitle.Value; + /// The busy look: the window takes no pointer or key input and shows a wait cursor. + public bool IsBusy => _isBusy.Value; + public bool IsDirty => _coordinator.IsDirty; public bool CanUndo => _coordinator.CanUndo; public bool CanRedo => _coordinator.CanRedo; @@ -232,26 +246,33 @@ private async Task ExecuteToggleSyncAsync() } /// - /// 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. + /// Every way out of the dialog ends the conflict: closing it without a choice, or failing to show it, turns sync + /// off, and a throw during the take counts as a dialog that could not be shown. Cancel in the take prompt shows + /// the dialog again. Core reports each turn-off reason, a failed take check included. /// internal async Task HandleConflictAsync(PlcRecipeConflict conflict) { PlcConflictAnswer answer; try { - var keepLocal = await ResolveConflictInteraction.Handle( - new PlcConflictDialogViewModel(conflict.Local.StepCount, conflict.Plc.StepCount)); - answer = keepLocal switch + bool? keepLocal; + do { - true => PlcConflictAnswer.KeepLocal, - false => PlcConflictAnswer.TakePlc, - null => PlcConflictAnswer.Dismissed - }; + keepLocal = await ResolveConflictInteraction.Handle( + new PlcConflictDialogViewModel(conflict.Local.StepCount, conflict.Plc.StepCount)); + } + while (keepLocal is false && !await PlcTake.RunAsync(conflict.ComparisonId)); + + if (keepLocal is false) + { + return; + } + + answer = keepLocal is true ? PlcConflictAnswer.KeepLocal : PlcConflictAnswer.Dismissed; } catch (Exception ex) { - _logger.LogWarning("Unexpected error while showing PLC conflict dialog: {Message}", ex.Message); + _logger.LogWarning(ex, "Unexpected error while showing the PLC conflict dialog or taking the PLC recipe"); answer = PlcConflictAnswer.DialogShowFailed; } @@ -302,10 +323,12 @@ private void RaiseConnectionStateProperties() this.RaisePropertyChanged(nameof(IsSyncEnabled)); } - private static string BuildWindowTitle(string? filePath, bool isDirty, bool isRecipeActive) + private static string BuildWindowTitle(string? filePath, bool isTakenFromPlc, bool isDirty, bool isRecipeActive) { var fileName = filePath is not null ? Path.GetFileNameWithoutExtension(filePath) + : isTakenFromPlc + ? Resources.WindowTitlePlcRecipe : Resources.WindowTitleNewRecipe; var dirtyIndicator = isDirty ? " *" : ""; var runningIndicator = isRecipeActive ? Resources.WindowTitleRunningSuffix : ""; diff --git a/SemiStep/SemiStep.UI/Plc/PlcLinkView.cs b/SemiStep/SemiStep.UI/Plc/PlcLinkView.cs index 6d75edc..5c8c1aa 100644 --- a/SemiStep/SemiStep.UI/Plc/PlcLinkView.cs +++ b/SemiStep/SemiStep.UI/Plc/PlcLinkView.cs @@ -8,6 +8,7 @@ namespace SemiStep.UI.Plc; public enum PlcLinkKind { + TakeReading, Disconnecting, SyncOff, Connecting, @@ -26,7 +27,8 @@ public sealed record PlcLinkView(PlcLinkKind Kind, string Text, string ToolTip) public bool IsRedDot => Kind is PlcLinkKind.NoLink or PlcLinkKind.Conflict or PlcLinkKind.SyncError; - public bool IsHollowDot => Kind is PlcLinkKind.Connecting or PlcLinkKind.Disconnecting or PlcLinkKind.Comparing; + public bool IsHollowDot => + Kind is PlcLinkKind.TakeReading or PlcLinkKind.Connecting or PlcLinkKind.Disconnecting or PlcLinkKind.Comparing; public bool IsGreyDot => Kind == PlcLinkKind.NotWritten; @@ -40,6 +42,7 @@ public static PlcLinkView Build( var age = lastExchange is null ? Resources.LinkNever : FormatAge(now - lastExchange.Value); var text = kind switch { + PlcLinkKind.TakeReading => Resources.LinkTakeReading, PlcLinkKind.Disconnecting => Resources.LinkDisconnecting, PlcLinkKind.SyncOff => Resources.LinkSyncOff, PlcLinkKind.Connecting => Resources.LinkConnecting, diff --git a/SemiStep/SemiStep.UI/Plc/PlcLinkViewModel.cs b/SemiStep/SemiStep.UI/Plc/PlcLinkViewModel.cs index 31d7e65..85e24fa 100644 --- a/SemiStep/SemiStep.UI/Plc/PlcLinkViewModel.cs +++ b/SemiStep/SemiStep.UI/Plc/PlcLinkViewModel.cs @@ -12,7 +12,10 @@ namespace SemiStep.UI.Plc; -/// The status-bar link slot: one state over the PLC snapshots, the open conflict and the sync toggle. +/// +/// The status-bar link slot: one state over the PLC snapshots, the open conflict, the sync toggle and the read of a +/// PLC recipe take. +/// public sealed class PlcLinkViewModel : ReactiveObject, IDisposable { private readonly CompositeDisposable _disposables = []; @@ -22,6 +25,7 @@ public PlcLinkViewModel( RecipeCoordinator coordinator, PlcLinkAddress address, IObservable syncToggle, + IObservable isTakeReading, IScheduler scheduler) { var latchedSnapshots = coordinator.PlcStateChanged @@ -38,6 +42,10 @@ public PlcLinkViewModel( .StartWith(SyncToggleDirection.None) .DistinctUntilChanged(); + var takeReading = isTakeReading + .StartWith(false) + .DistinctUntilChanged(); + var ageTicks = Observable.Interval(TimeSpan.FromSeconds(1), scheduler) .Select(_ => Unit.Default) .StartWith(Unit.Default); @@ -46,10 +54,11 @@ public PlcLinkViewModel( .CombineLatest( conflictOpen, toggleDirection, + takeReading, ageTicks, - (latched, isConflictOpen, direction, _) => (latched, isConflictOpen, direction)) + (latched, isConflictOpen, direction, isReading, _) => (latched, isConflictOpen, direction, isReading)) .Select(input => PlcLinkView.Build( - Resolve(input.latched, input.isConflictOpen, input.direction), + input.isReading ? PlcLinkKind.TakeReading : Resolve(input.latched, input.isConflictOpen, input.direction), input.latched.Snapshot.NotWrittenCause, address, coordinator.LastExchangeTime, diff --git a/SemiStep/SemiStep.UI/Plc/PlcRecipeTake.cs b/SemiStep/SemiStep.UI/Plc/PlcRecipeTake.cs new file mode 100644 index 0000000..2d941d8 --- /dev/null +++ b/SemiStep/SemiStep.UI/Plc/PlcRecipeTake.cs @@ -0,0 +1,111 @@ +using System.Reactive.Concurrency; +using System.Reactive.Linq; + +using FluentResults; + +using Microsoft.Extensions.Logging; + +using ReactiveUI; + +using SemiStep.Core.Plc; +using SemiStep.Core.Recipes; + +using SemiStep.UI.Coordinator; +using SemiStep.UI.RecipeFile; + +namespace SemiStep.UI.Plc; + +/// +/// The conflict answer "load from the PLC": the unsaved-changes prompt, then the read again and the take under the +/// busy look. is the busy look and the link slot's reading state. +/// +public sealed class PlcRecipeTake( + RecipeCoordinator coordinator, + RecipeFileViewModel recipeFile, + IScheduler scheduler, + ILogger logger) : ReactiveObject +{ + internal static readonly TimeSpan ReadBound = TimeSpan.FromSeconds(10); + + private readonly RecipeCoordinator _coordinator = coordinator; + private readonly RecipeFileViewModel _recipeFile = recipeFile; + private readonly IScheduler _scheduler = scheduler; + private readonly ILogger _logger = logger; + + public bool IsReading + { + get; + private set => this.RaiseAndSetIfChanged(ref field, value); + } + + /// + /// Returns false when the operator went back to the conflict dialog: Cancel in the prompt, or a save that failed + /// or was cancelled. Otherwise the conflict has ended, a stale one included. + /// + public async Task RunAsync(long comparisonId) + { + while (true) + { + var screenRecipe = _coordinator.CurrentRecipe; + var mayDropScreen = await _recipeFile.ConfirmDiscardAsync(); + if (!_coordinator.IsConflictCurrent(comparisonId)) + { + _logger.LogInformation("The PLC conflict went stale during the take prompt; the take is abandoned"); + return true; + } + + if (!mayDropScreen) + { + return false; + } + + await _coordinator.WaitForTakesAllowedAsync(); + if (!_coordinator.IsConflictCurrent(comparisonId)) + { + _logger.LogInformation("The PLC conflict went stale during a save; the take is abandoned"); + return true; + } + + if (TakeOutcome(await ReadAndTakeAsync(comparisonId, screenRecipe)) != PlcTakeOutcome.ScreenChanged) + { + return true; + } + + _logger.LogInformation("The screen recipe changed during the PLC take read; asking again"); + } + } + + private async Task> ReadAndTakeAsync(long comparisonId, Recipe screenRecipe) + { + IsReading = true; + try + { + var read = await ReadBoundedAsync(); + return _coordinator.TakeConflictRecipe(comparisonId, screenRecipe, read); + } + finally + { + IsReading = false; + } + } + + /// The UI stops waiting at the bound whether or not the read honours the cancellation. + private async Task> ReadBoundedAsync() + { + try + { + return await Observable.FromAsync(_coordinator.ReadRecipeForTakeAsync) + .Timeout(ReadBound, _scheduler); + } + catch (TimeoutException) + { + _logger.LogWarning("The PLC recipe read for the take passed {Bound}", ReadBound); + return Result.Fail("The PLC recipe read passed its bound"); + } + } + + private static PlcTakeOutcome TakeOutcome(Result result) + { + return result.IsSuccess ? result.Value : PlcTakeOutcome.NotReplaced; + } +} diff --git a/SemiStep/SemiStep.UI/RecipeFile/RecipeFileViewModel.cs b/SemiStep/SemiStep.UI/RecipeFile/RecipeFileViewModel.cs index b320880..ec64d44 100644 --- a/SemiStep/SemiStep.UI/RecipeFile/RecipeFileViewModel.cs +++ b/SemiStep/SemiStep.UI/RecipeFile/RecipeFileViewModel.cs @@ -23,6 +23,7 @@ public class RecipeFileViewModel : ReactiveObject, IDisposable private readonly CompositeDisposable _disposables = []; private readonly ILogger _logger; private readonly MessagePanelViewModel _messagePanel; + private int _takesFromPlc; public RecipeFileViewModel( RecipeCoordinator coordinator, @@ -59,6 +60,9 @@ public RecipeFileViewModel( NewRecipeCommand.ReportThrownExceptions(_messagePanel, _logger, new LocalizedText(nameof(Resources.NewRecipeFailed))) .DisposeWith(_disposables); + + _coordinator.PlcRecipeTaken += OnPlcRecipeTaken; + _disposables.Add(Disposable.Create(() => _coordinator.PlcRecipeTaken -= OnPlcRecipeTaken)); } public Interaction OpenFileInteraction { get; } @@ -81,6 +85,13 @@ public string? CurrentFilePath private set => this.RaiseAndSetIfChanged(ref field, value); } + /// The recipe was taken from the PLC and has no file until a Save As, New or Open succeeds. + public bool IsTakenFromPlc + { + get; + private set => this.RaiseAndSetIfChanged(ref field, value); + } + public void Dispose() { _disposables.Dispose(); @@ -98,7 +109,8 @@ public async Task ResolveUnsavedChangesAsync(UnsavedChangesChoice choice) }; } - private async Task ConfirmDiscardAsync() + /// Asks before a dirty recipe is dropped; true when the caller may drop it. + public async Task ConfirmDiscardAsync() { if (!_coordinator.IsDirty) { @@ -131,11 +143,13 @@ private async Task SaveBeforeDiscardAsync() private async Task SaveRecipeAsync() { + using var takeHold = _coordinator.HoldTakes(); return CurrentFilePath is not null ? await SaveToFileAsync(CurrentFilePath) : await SaveAsRecipeAsync(); } private async Task SaveAsRecipeAsync() { + using var takeHold = _coordinator.HoldTakes(); var suggestedName = CurrentFilePath is not null ? Path.GetFileNameWithoutExtension(CurrentFilePath) : null; @@ -144,8 +158,10 @@ private async Task SaveAsRecipeAsync() return filePath is not null && await SaveToFileAsync(filePath); } + /// A take that lands during the write keeps the taken recipe untitled. private async Task SaveToFileAsync(string filePath) { + var takesBefore = _takesFromPlc; var result = await _coordinator.SaveRecipeAsync(filePath); if (result.IsFailed) @@ -155,7 +171,11 @@ private async Task SaveToFileAsync(string filePath) return false; } - CurrentFilePath = filePath; + if (_takesFromPlc == takesBefore) + { + SetFile(filePath); + } + _messagePanel.ReportSuccess( string.Format(CultureInfo.InvariantCulture, Resources.SavedFormat, Path.GetFileName(filePath))); @@ -183,7 +203,7 @@ private async Task LoadRecipeAsync() return; } - CurrentFilePath = filePath; + SetFile(filePath); if (result.Successes.OfType().Any()) { @@ -212,7 +232,20 @@ private async Task NewRecipeAsync() return; } + SetFile(null); + } + + private void OnPlcRecipeTaken() + { + _takesFromPlc++; CurrentFilePath = null; + IsTakenFromPlc = true; + } + + private void SetFile(string? filePath) + { + CurrentFilePath = filePath; + IsTakenFromPlc = false; } /// Reports a run that started while a New or Open dialog was open; true stops the action. diff --git a/docs/architecture/dialogs-and-interactions.md b/docs/architecture/dialogs-and-interactions.md index 7522d12..921b515 100644 --- a/docs/architecture/dialogs-and-interactions.md +++ b/docs/architecture/dialogs-and-interactions.md @@ -26,10 +26,29 @@ VM-driven dialog follows an established pattern rather than inventing one. 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. + `true` to `KeepLocal` and `null` to `Dismissed`, and passes the answer to + `PlcLifecycleManager.ResolveConflict` with the conflict's comparison ID. A handler that throws or is + missing, and a throw during the take, is `DialogShowFailed`. `Dismissed` and `DialogShowFailed` turn sync + off. An answer whose comparison a link drop, a newer comparison or sync off made stale changes nothing. +- `false` runs `PlcRecipeTake.RunAsync`, the conflict take. On a dirty recipe it first asks through + `RecipeFileViewModel.ConfirmDiscardAsync` (see "Unsaved changes"); a `false` answer there shows the + conflict dialog again. Then `IsReading` turns on the busy look (`MainWindow`'s transparent `BusyOverlay` + with a wait cursor, and a tunnel `KeyDown` handler that marks every key handled) and the link slot's + `TakeReading` kind. The take reads the PLC recipe again through `PlcLifecycleManager.ReadRecipeForTakeAsync`, + and stops waiting after `PlcRecipeTake.ReadBound` (10 s) on the injected scheduler, whether or not the + read honours its cancellation. `PlcLifecycleManager.TakeConflictRecipe` then decides on the UI thread: + a failed read ends the conflict with `PlcTakeReadFailedError` and declares link loss; an empty or + uncommitted PLC recipe ends it with a write of the screen recipe and `PlcRecipeAbsentWarning`; an + identical one ends it in sync; a screen recipe that changed since the answer returns + `ScreenChanged`, and the take asks again; otherwise the PLC recipe is loaded. Both takes, this one and + the reconnect take, load through `PlcComparisonAnswers.TakeLocked`, which ends the write pause without a + write and sets the sync status to `Synced`. `RecipeCoordinator` then raises `PlcRecipeTaken`, and + `RecipeFileViewModel` drops the file name and sets `IsTakenFromPlc`, so the title shows the + `WindowTitlePlcRecipe` name (Recipe from PLC) and Save opens save-as until a save-as, New or Open succeeds. + A save command holds every take (`RecipeCoordinator.HoldTakes`) until it ends, and a take that lands during + the write keeps the recipe untitled. Before the read the take checks that its conflict is still current; + a conflict a link drop made stale during the prompt ends the take without a read and without showing the + dialog again. A close request while `IsBusy` is cancelled. - `RequestCloseInteraction` (`Interaction`) — `File > Exit`. The handler calls `Close()`, which runs `OnWindowClosing`'s dirty-close guard (see `exit-flow.md`). diff --git a/docs/architecture/error-reporting.md b/docs/architecture/error-reporting.md index 4cc7b82..063b9ff 100644 --- a/docs/architecture/error-reporting.md +++ b/docs/architecture/error-reporting.md @@ -352,6 +352,13 @@ always English; only the panel seams localize. `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. +- **The conflict take** reports its own outcome on the operation channel. + `RecipeCoordinator.TakeConflictRecipe` routes a failed or timed-out read (`PlcTakeReadFailedError`) + through `ReportFailure` and a PLC recipe that was gone by the take (`PlcRecipeAbsentWarning`) through + `ReportWarnings`. When the conflict was still current, the failed read declares link loss + (`PlcTakeReadFailedError.IsLinkLossDeclared`), so a `ConnectionLostError` follows on `Faults`. `OnPlcFault` + drops the first such fault, so the take failure stays in the slot; a reconnect also ends that rule, and a + read on a stale conflict sets nothing. - **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/readme.md b/docs/readme.md index da7d898..f71a640 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -441,13 +441,32 @@ _Окно установки RIE в транспонированном пред > **Диалог конфликта** предлагает сохранить локальную версию или загрузить версию из ПЛК. Пока диалог открыт, приложение ничего не пишет в ПЛК. «Оставить локальный» записывает в ПЛК рецепт с экрана; рецепт с предупреждениями не записывается. «Загрузить из ПЛК» загружает рецепт из ПЛК и ничего не пишет обратно. +**Загрузка рецепта из ПЛК.** Если в рецепте на экране есть несохранённые изменения, «Загрузить из ПЛК» сначала показывает вопрос «Сохранить изменения?»: + +- «Сохранить» сохраняет рецепт в его файл, а для рецепта без файла открывает «Сохранить как». Загрузка идёт, только если сохранение удалось. +- «Не сохранять» загружает рецепт из ПЛК, изменения на экране теряются. +- «Отмена» или крестик возвращают к диалогу конфликта. Неудачное или отменённое сохранение тоже возвращает к диалогу конфликта. + +Затем приложение заново читает рецепт из ПЛК, потому что диалог мог быть открыт долго. Во время чтения окно не принимает щелчков и клавиш и не закрывается, курсор показывает ожидание, а слот связи показывает «ПЛК: чтение рецепта…». Чтение длится не больше 10 с. Загруженный рецепт не имеет файла: заголовок окна — «SemiStep - Рецепт из ПЛК *», рецепт отмечен как несохранённый, история отмены и повтора очищена. Ctrl+S открывает «Сохранить как». Имя «Рецепт из ПЛК» сменяется после успешного «Сохранить как», «Создать рецепт» или «Открыть рецепт». В ПЛК ничего не записывается, а слот связи показывает «ПЛК: подключено», даже если до конфликта запись завершилась ошибкой. + +Исходы повторного чтения: + +| Результат чтения | Действие | +| ---------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| Рецепт отличается от рецепта на экране | Рецепт из ПЛК загружается, как описано выше | +| Рецепт совпал с рецептом на экране | Конфликт завершается, ничего не загружается и не записывается | +| Рецепт в ПЛК пуст или не зафиксирован | В ПЛК записывается рецепт с экрана; сообщение «Рецепт в ПЛК отсутствует. Записан рецепт с экрана.» | +| Чтение не удалось или не уложилось в 10 с | Ничего не меняется; сообщение «Не удалось прочитать рецепт из ПЛК.»; приложение разрывает связь и после переподключения снова сравнивает рецепты | + +Если за время чтения рецепт на экране изменился, приложение снова задаёт вопрос «Сохранить изменения?» и читает рецепт ещё раз. Если пока открыт вопрос «Сохранить изменения?» связь с ПЛК пропала, загрузка отменяется без чтения, а после переподключения рецепты сравниваются снова. Пока идёт сохранение, загрузка ждёт его конца. + Если диалог конфликта закрыт без выбора (крестиком, клавишей Esc или Alt+F4) или не может быть показан, синхронизация выключается. Ничего не записывается и не заменяется, а в панели уведомлений появляется сообщение «Синхронизация выключена: конфликт рецептов не решён.» Повторное включение синхронизации снова сравнивает рецепты. Сообщение о том, почему синхронизация выключилась, остаётся в панели уведомлений при правке рецепта и исчезает, когда синхронизацию включают снова. Если рецепт из ПЛК не проходит проверку при загрузке (например, циклы вложены глубже 3 уровней), рецепт на экране не меняется, синхронизация выключается, а в панели уведомлений появляется сообщение «Рецепт из ПЛК не загружен: <причина>. Синхронизация выключена.» Это правило действует и для кнопки «Загрузить из ПЛК», и для автоматической загрузки в пустой рецепт. -Автоматическая загрузка в пустой рецепт выполняется, только если рецепт на экране всё ещё пуст и не содержит несохранённых изменений. Если за время чтения из ПЛК рецепт на экране изменился (например, открыт файл) или пустой рецепт получен удалением всех шагов, вместо загрузки появляется диалог конфликта. +Автоматическая загрузка в пустой рецепт выполняется, только если рецепт на экране всё ещё пуст и не содержит несохранённых изменений. Если за время чтения из ПЛК рецепт на экране изменился (например, открыт файл) или пустой рецепт получен удалением всех шагов, вместо загрузки появляется диалог конфликта. Автоматически загруженный рецепт тоже не имеет файла: заголовок «SemiStep - Рецепт из ПЛК *», Ctrl+S открывает «Сохранить как». Если чтение версии протокола, управляющей области или рецепта не удалось или не уложилось в 5 с, приложение ничего не пишет в ПЛК, разрывает связь и переподключается; после переподключения согласование повторяется. Три неудачных согласования подряд в одном сеансе синхронизации выключают синхронизацию с сообщением «Не удалось прочитать рецепт из ПЛК. Синхронизация выключена.» Полный перечень веток согласования и их уровни в журнале — в разделе 5. @@ -474,6 +493,7 @@ _Окно установки RIE в транспонированном пред | Состояние | Точка | Текст | | ---------------------------------------------------------- | ----------------- | ------------------------------------------------------ | +| Рецепт из ПЛК читается для загрузки | полая серая | «ПЛК: чтение рецепта…» | | Выключение синхронизации выполняется | полая серая | «ПЛК: отключение…» | | Синхронизация выключена | нет | «синхронизация выключена» | | Включение синхронизации выполняется, связи ещё нет | полая серая | «ПЛК: подключение…» | @@ -486,7 +506,7 @@ _Окно установки RIE в транспонированном пред Возраст последнего обмена отсчитывается от последнего успешного чтения из ПЛК: опроса исполнения (при каждом опросе, 10 раз в секунду), keep-alive и любого другого чтения. Возраст показывается ступенями: «7 с назад», «> 30 с назад», «> 1 мин назад», «> 1 ч назад»; «никогда» — за этот сеанс не было ни одного успешного чтения. Подсказка слота содержит адрес ПЛК («ПЛК: 192.168.0.150:102») и возраст обмена. При сравнении и конфликте подсказка добавляет, чего ждёт запись в ПЛК, а при «рецепт не записан» — причину: «в рецепте есть предупреждения» или «идёт выполнение рецепта». Если адрес задан ключом `--plc-endpoint` и отличается от `connection.yaml`, к тексту в статус-баре добавляется хост без порта («ПЛК: подключено, 127.0.0.1»), кроме состояния «нет связи». Щелчок по слоту открывает журнал сообщений, если в нём есть записи. -Ошибка синхронизации держится, пока не придёт успешная запись (`Synced`) или пока синхронизацию не выключат; подробности — в журнале. Если ПЛК выполняет рецепт, когда приложение должно записать локальный рецепт (например, после кнопки «Оставить локальный» в диалоге конфликта), это не ошибка: запись ждёт конца исполнения, слот показывает «ПЛК: рецепт не записан», а в журнал попадает информационная запись. Когда исполнение заканчивается, приложение записывает рецепт в ПЛК. Рецепт с предупреждениями в ПЛК не записывается, и слот тоже показывает «ПЛК: рецепт не записан». Обычная запись после правки (секунда ожидания и сама запись) оставляет слот зелёным. +Ошибка синхронизации держится, пока не придёт успешная запись или загрузка рецепта из ПЛК (`Synced`) или пока синхронизацию не выключат; подробности — в журнале. Если ПЛК выполняет рецепт, когда приложение должно записать локальный рецепт (например, после кнопки «Оставить локальный» в диалоге конфликта), это не ошибка: запись ждёт конца исполнения, слот показывает «ПЛК: рецепт не записан», а в журнал попадает информационная запись. Когда исполнение заканчивается, приложение записывает рецепт в ПЛК. Рецепт с предупреждениями в ПЛК не записывается, и слот тоже показывает «ПЛК: рецепт не записан». Обычная запись после правки (секунда ожидания и сама запись) оставляет слот зелёным. Слот исполнения показывает «Не выполняется» или «► Выполняется: шаг 5 из 8» со значком замка: пока ПЛК выполняет рецепт, правка недоступна, копирование работает. Номер шага — строка ПЛК плюс 1, проходы циклов на него не влияют. Если ПЛК выполняет шаг за пределами рецепта ПК, слот показывает номер шага ПЛК без общего числа: «► Выполняется: шаг 12». До первого шага слот показывает «► Выполняется» без номера, а пока ПЛК завершает последний шаг, «шаг 8 из 8». Без связи с ПЛК (синхронизация выключена, идёт подключение, нет связи) состояние исполнения неизвестно: слот показывает «нет данных», замка нет, оба таймера показывают «—», заголовок окна без суффикса. Во время цикла справа выводятся проходы от внутреннего цикла к внешнему: «цикл 2 из 5 › 1 из 3»; номер прохода берётся из счётчика ПЛК, число проходов — из рецепта. Не уместившийся текст обрезается многоточием, а подсказка слота перечисляет все уровни. Заголовок окна во время исполнения получает « [выполняется]».