diff --git a/src/SopHelper.Avalonia/Models/StepCountsStore.cs b/src/SopHelper.Avalonia/Models/StepCountsStore.cs index c152b73..65eada1 100644 --- a/src/SopHelper.Avalonia/Models/StepCountsStore.cs +++ b/src/SopHelper.Avalonia/Models/StepCountsStore.cs @@ -35,7 +35,15 @@ public sealed class StepCountsStore(string root) : IStepCountStore { lock (FileGate) { - var all = Read(); + Dictionary> all; + try { all = Read(); } + catch (Exception error) when (error is JsonException or InvalidDataException) + { + // 只归档内容损坏的文件。访问失败应由调用者报告,避免误覆盖原有数据。 + var backup = FilePath + ".corrupt-" + Guid.NewGuid().ToString("N"); + File.Move(FilePath, backup); + all = new(StringComparer.OrdinalIgnoreCase); + } all[recipeName] = new(counts); Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); var temporary = FilePath + ".tmp"; diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs index c888fe8..bb9a67a 100644 --- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs +++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs @@ -93,7 +93,13 @@ public partial class SopEngine statistics = new SopRunStatistics(); if (StepCountStore is { } store) { - statistics.RestoreStepCounts(store.Load(recipeName)); + try { statistics.RestoreStepCounts(store.Load(recipeName)); } + catch (Exception error) when (error is IOException or UnauthorizedAccessException + or InvalidDataException or System.Text.Json.JsonException) + { + // 统计读取失败时以空计数继续,保留配方加载及运行能力。 + Log("warn", "累计次数读取失败,本次从零开始:" + error.Message); + } statistics.StepCountsChanged += counts => { try { store.Save(recipeName, counts); } diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs index 14e5f5c..1de099c 100644 --- a/tests/Avalonia.Smoke/Program.cs +++ b/tests/Avalonia.Smoke/Program.cs @@ -920,6 +920,24 @@ internal static class Smoke } finally{Directory.Delete(countStore.FilePath+".tmp");} engine.Stop();model.IsRunning=false; + + // 模拟工位上次中断写入后的损坏文件,检查启动、切换配方与后续落盘。 + const string invalidCounts = "{"; + File.WriteAllText(countStore.FilePath, invalidCounts); + AfterRestart(fresh => + { + Check(fresh.ActiveRecipe == name + ".yaml" && fresh.StepCards.Count == 2 + && fresh.StepCards.All(card => card.NormalCount == 0 && card.AbnormalCount == 0), + "损坏的累计次数文件不会阻止启动应用配方"); + fresh.SelectedRecipe = "demo.yaml"; + fresh.ApplyRecipeCommand.Execute(); + Check(fresh.ActiveRecipe == "demo.yaml", "存在损坏文件时仍可切换配方"); + }); + Check(File.ReadAllText(countStore.FilePath) == invalidCounts, "读取失败后保留原统计文件"); + countStore.Save(name, new Dictionary{{1,new(1,0)}}); + var archived = Directory.GetFiles(Path.GetDirectoryName(countStore.FilePath)!, "step-counts.json.corrupt-*").Single(); + Check(File.ReadAllText(archived) == invalidCounts && countStore.Load(name)[1].NormalCount == 1, + "首次写入时归档损坏文件并恢复计数持久化"); } private static async Task CheckRuntimeStatistics(App app,SopPageViewModel sop,Window window)