From 25ed47e4bc0cd2c57a3b1e51932cf2919d574a5c Mon Sep 17 00:00:00 2001 From: endercodezz Date: Sun, 22 Nov 2026 03:45:02 +0200 Subject: [PATCH] Journal updates and confirm readiness of a new version A persisted, atomically written journal tracks staged, applying, pending confirmation, confirmed and rolled back phases. User data is snapshotted before the first run of a new version; a local readiness check (UI up, user data loaded, versions consistent; no engines or network) confirms it. After two unconfirmed starts automatic updates pause with a clear message; missing or unreadable user data is restored from the snapshot. Package-manager installs are never touched. Velopack stays the only updater and no binary rollback is claimed. Closes #412 --- docs/BUILD.md | 64 ++ docs/TESTING.md | 30 + src/Bydlo.App/App.axaml.cs | 3 + src/Bydlo.App/Assets/Strings/en.json | 5 + src/Bydlo.App/Assets/Strings/ru.json | 5 + src/Bydlo.App/Services/AppServices.cs | 39 +- src/Bydlo.App/Services/DesktopIntegration.cs | 3 + src/Bydlo.App/Services/PackagedAppUpdater.cs | 3 + src/Bydlo.App/ViewModels/MainViewModel.cs | 25 + .../ViewModels/SettingsViewModel.Updates.cs | 37 +- .../Diagnostics/AutomaticAppUpdater.cs | 29 +- src/Bydlo.Core/Diagnostics/UpdateRecovery.cs | 609 ++++++++++++++++++ src/Bydlo.Core/Serialization/BydloJson.cs | 1 + tests/Bydlo.Tests/AppUpdateOwnershipTests.cs | 2 + tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs | 1 + tests/Bydlo.Tests/FirstRunConsentTests.cs | 2 + tests/Bydlo.Tests/UpdateRecoveryTests.cs | 482 ++++++++++++++ 17 files changed, 1323 insertions(+), 17 deletions(-) create mode 100644 src/Bydlo.Core/Diagnostics/UpdateRecovery.cs create mode 100644 tests/Bydlo.Tests/UpdateRecoveryTests.cs diff --git a/docs/BUILD.md b/docs/BUILD.md index 8e902251..32db9830 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -342,6 +342,70 @@ Velopack использует стабильные GitHub Releases и отдел Автоматическая проверка Sigstore-attestation клиентом остаётся отдельным этапом дорожной карты и здесь не заявляется. +#### Восстановление после обновления (#412) + +Velopack остаётся единственным механизмом применения. Вокруг него работает локальный +recovery-протокол `UpdateRecovery` (`src/Bydlo.Core/Diagnostics/UpdateRecovery.cs`): +он не устанавливает файлы сам, а фиксирует переход, сохраняет снимок пользовательских +данных, подтверждает готовность новой версии и останавливает автообновление, если она +не поднялась. Второго updater нет. + +Журнал фаз — `/update-recovery.json`, запись атомарная (временный файл, `fsync`, +переименование). Фазы: `Staged` (пакет скачан и проверен, снимок есть, файлы не заменены), +`Applying` (пакет передан установщику, процесс завершается), `PendingConfirmation` +(новая версия запущена, готовность ещё не подтверждена), `Confirmed` (готовность +подтверждена), `RolledBack` (протокол вернулся к последнему рабочему состоянию). +Обрезанный, повреждённый или отсутствующий журнал означает «журнала нет»: recovery ничего +не делает и не угадывает, повреждённый файл сохраняется как `update-recovery.json.corrupt-*`, +незавершённый временный файл игнорируется. + +Снимок — `/update-recovery/snapshot/` с копиями `settings.json` и `profiles.json`, +сделанными до первой замены файлов. Секреты лежат в `/secrets/` (DPAPI в Windows, +системное хранилище или AES-файл на других ОС); обновление их не трогает, поэтому копировать +их не нужно. Снимок удаляется после подтверждения готовности. При исчерпании попыток +восстанавливаются только отсутствующие или нечитаемые файлы: читаемый файл никогда не +перезаписывается, чтобы не потерять изменения, сделанные в новой версии. + +Подтверждение готовности выполняется локально после открытия окна и проверяет: UI запущен, +`settings.json` и `profiles.json` прочитаны без сброса в пустой документ, версия приложения +совпадает с версией из журнала, хеш закреплённого `engines.lock.json` совпадает с записанным +при staging. Туннели, движки, драйверы, службы и сетевые запросы не запускаются. Версия +установленного привилегированного helper сравнивается и попадает в журнал как замечание, +но не блокирует запуск и никогда не переустанавливается скрытно: обновление helper идёт +отдельно через существующие разрешения и повышение прав. + +Попытки ограничены: новая версия может запуститься без подтверждения не более двух раз +(`UpdateRecovery.MaxAttempts`). После этого фаза становится `RolledBack`, автоматические +загрузка и установка выключаются, а пользователь видит локализованное сообщение. Навсегда +заблокировать обновления нельзя: явная кнопка «Скачать и установить» снимает блок и повторяет +попытку. Прерванная установка (фаза `Applying`, но запустилась прежняя версия) тоже считается +попыткой и после второй блокирует автообновление. + +Пакет применяется только при журнале в фазе `Staged` и существующем снимке +(`UpdateRecovery.CanApply`). Если снимок или журнал записать не удалось (нет прав, нет места, +каталог данных недоступен), пакет остаётся скачанным и не устанавливается. Отдельной проверки +свободного места нет: нехватка места проявляется как ошибка записи снимка или журнала. +Применение по-прежнему происходит только после успешного `ShutdownAsync`: закрытие в трей +и force-kill пакет не применяют. + +Для установок из `.deb`, Arch и Nix recovery не выполняется вообще: журнал не читается и не +перезаписывается, снимок не создаётся, файлами владеет пакетный менеджер (#413). + +##### Фактические гарантии по ОС + +| ОС | Что делает Velopack 1.2.161 | Что добавляет BYDLO | Что не заявлено | +|---|---|---|---| +| Windows | распаковка во временный каталог и замена `current`; `Update.exe` и каталог `packages/` остаются рядом | журнал фаз, снимок данных, подтверждение готовности, остановка автообновления | автоматический откат на предыдущий пакет BYDLO не вызывает и не проверял | +| Linux (AppImage) | замена файла AppImage | то же | предыдущий AppImage BYDLO не сохраняет; возврат только ручной переустановкой | +| macOS | swap/fallback по upstream | то же | поведение fallback BYDLO не проверял | + +Если установщик оставил рядом полный пакет другой версии (`packages/*-full.nupkg`), BYDLO +сообщает, что вернуться к предыдущей версии можно без повторной загрузки, но откат не +запускает. Если такого пакета нет, сообщение честно говорит, что нужна ручная переустановка +со страницы релизов. Автоматический откат бинарников не реализован ни на одной ОС. + +Ручные прогоны замены файлов на каждой ОС остаются за сопровождающим (#402). + ### Нативные пакеты и подпись (#215) `scripts/package-native.ps1` использует закреплённые Velopack SDK/CLI **1.2.161**. diff --git a/docs/TESTING.md b/docs/TESTING.md index 3dd97760..e6d7a243 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -790,3 +790,33 @@ Velopack, дождаться загрузки, продолжить работу не применяется, в журнале нет секретов. Для `.deb`, Arch, Nix и portable убедиться, что флажка нет, а текст объясняет обновление через соответствующий менеджер или вручную. Реальная замена файлов и работа пакетных менеджеров автоматическими тестами не проверяются. + +## Восстановление после обновления (#412) + +`UpdateRecoveryTests` работают только с временными каталогами и поддельными объектами: +`FakeRollbackProbe` отвечает про сохранённый пакет, `FakeBackend` — про загрузку и применение, +`FileSystemRollbackProbe` проверяется на настоящем временном дереве `current/` + `packages/`. +Установщик, движки, драйверы и сеть не запускаются. + +Проверяются: атомарная запись журнала без временного файла; обрезанный журнал (fault injection +прерванной записи) и оставшийся `.tmp` не ломают запуск, повреждённый файл сохраняется как +`update-recovery.json.corrupt-*`; применение пакета только при фазе `Staged` и существующем +снимке; удалённый снимок и недоступный каталог данных (fault injection нехватки места и прав) +оставляют пакет скачанным; подтверждение готовности снимает снимок; две неудачные проверки +подряд дают `RolledBack` и блокировку автообновления, третий запуск ничего не повторяет; +прерванная установка возвращает прежнюю версию и после второй попытки блокирует обновления; +снимок восстанавливает только отсутствующие или нечитаемые файлы и не перезаписывает читаемые; +установка из `.deb` не читает и не перезаписывает журнал Velopack; явная загрузка снимает блок, +а автоматическая — нет; строки сообщений есть в `en.json` и `ru.json`. + +```powershell +. ./scripts/env.ps1 +dotnet test tests/Bydlo.Tests -c Release --filter "FullyQualifiedName~UpdateRecoveryTests" +``` + +Ручная проверка мейнтейнером на каждой платформе (#402): установить предыдущую версию, +включить автообновление, дождаться загрузки и выйти; после запуска новой версии убедиться, +что журнал перешёл в `Confirmed`, а снимок удалён. Затем повторить с намеренно испорченным +`settings.json` и проверить, что после двух запусков появляется сообщение, автообновление +остановлено, а настройки восстановлены из снимка. Реальная замена файлов, откат установщика +и поведение Velopack на каждой ОС автоматическими тестами не проверяются. diff --git a/src/Bydlo.App/App.axaml.cs b/src/Bydlo.App/App.axaml.cs index 07c92534..a2bc26f3 100644 --- a/src/Bydlo.App/App.axaml.cs +++ b/src/Bydlo.App/App.axaml.cs @@ -106,6 +106,9 @@ public override void OnFrameworkInitializationCompleted() else if (ApplicationLifetime is ISingleViewApplicationLifetime single) { single.MainView = new MainView { DataContext = shell }; + // No window event on this head: the view exists, so the readiness confirmation can run (issue #412). + Services.ConfirmUpdateReadiness(); + shell.ShowUpdateRecoveryToast(); } base.OnFrameworkInitializationCompleted(); diff --git a/src/Bydlo.App/Assets/Strings/en.json b/src/Bydlo.App/Assets/Strings/en.json index 17e9f8dc..0d3f4b39 100644 --- a/src/Bydlo.App/Assets/Strings/en.json +++ b/src/Bydlo.App/Assets/Strings/en.json @@ -781,6 +781,11 @@ "settings.update.manual.unknown": "This copy was not installed by a supported package, so automatic updates are unavailable. Install a release package to receive updates.", "settings.update.detail.unavailable": "This copy runs from an archive and cannot update itself. Install the Setup.exe build to receive updates.", "settings.update.detail.consent": "Automatic updates are off. Allow them under GitHub access.", + "settings.update.recovery.blocked": "The last update did not confirm readiness. Automatic updates are paused until you download an update manually.", + "settings.update.recovery.previous": "The installer kept the previous package in the installation folder, so a return to the previous version is possible without downloading it again. BYDLO does not run that rollback automatically: reinstall the previous release from the release page.", + "settings.update.recovery.manual": "The previous package is not kept on this platform, so returning to the working version requires a manual reinstall from the release page.", + "update.recovery.blocked": "The last update did not confirm readiness. Automatic updates are paused; BYDLO {0} is running. Settings or profiles that could not be read were restored from the snapshot taken before the update.", + "update.recovery.interrupted": "The update was interrupted before it replaced any files. BYDLO {0} is still running; download the update again to retry.", "update.trust.catalog": "The update catalog could not be verified, so nothing was installed. The current version is kept.", "update.trust.expired": "The update catalog has expired or the system clock is wrong, so nothing was installed. Check the date and time and try again.", "update.trust.unsupported": "This update is not offered for your platform or channel, so nothing was installed. The current version is kept.", diff --git a/src/Bydlo.App/Assets/Strings/ru.json b/src/Bydlo.App/Assets/Strings/ru.json index 89460462..f5cdd607 100644 --- a/src/Bydlo.App/Assets/Strings/ru.json +++ b/src/Bydlo.App/Assets/Strings/ru.json @@ -780,6 +780,11 @@ "settings.update.manual.nix": "BYDLO установлен из flake Nix, поэтому обновлением управляет Nix. Обновите его командой nix profile upgrade или пересборкой конфигурации NixOS.", "settings.update.manual.portable": "Эта копия запущена из переносимой папки или старого ZIP-архива. Чтобы обновиться, полностью закройте BYDLO, замените всю папку новой версией и сохраните каталог данных. Автоматического перехода на установленную сборку нет.", "settings.update.manual.unknown": "Эта копия не установлена поддерживаемым пакетом, поэтому автоматические обновления недоступны. Установите пакет из релиза, чтобы получать обновления.", + "settings.update.recovery.blocked": "Последнее обновление не подтвердило готовность. Автоматические обновления приостановлены, пока вы не скачаете обновление вручную.", + "settings.update.recovery.previous": "Установщик сохранил предыдущий пакет в каталоге установки, поэтому вернуться к предыдущей версии можно без повторной загрузки. BYDLO не выполняет такой откат автоматически: переустановите предыдущий релиз со страницы релизов.", + "settings.update.recovery.manual": "На этой платформе предыдущий пакет не сохраняется, поэтому для возврата к рабочей версии нужна ручная переустановка со страницы релизов.", + "update.recovery.blocked": "Последнее обновление не подтвердило готовность. Автоматические обновления приостановлены; работает BYDLO {0}. Настройки или профили, которые не удалось прочитать, восстановлены из снимка, сделанного перед обновлением.", + "update.recovery.interrupted": "Обновление прервалось до замены файлов. Работает BYDLO {0}; чтобы повторить, скачайте обновление снова.", "update.trust.catalog": "Не удалось проверить каталог обновлений, поэтому ничего не установлено. Текущая версия сохранена.", "update.trust.expired": "Срок действия каталога обновлений истёк или системные часы неверны, поэтому ничего не установлено. Проверьте дату и время и повторите попытку.", "update.trust.unsupported": "Это обновление не предлагается для вашей платформы или канала, поэтому ничего не установлено. Текущая версия сохранена.", diff --git a/src/Bydlo.App/Services/AppServices.cs b/src/Bydlo.App/Services/AppServices.cs index a7e4ea8c..bf5c3cb9 100644 --- a/src/Bydlo.App/Services/AppServices.cs +++ b/src/Bydlo.App/Services/AppServices.cs @@ -38,6 +38,9 @@ private AppServices(string[] args, IPrivilegeService? privileges) Http = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; Http.DefaultRequestHeaders.UserAgent.ParseAdd(Bydlo.Core.AppVersion.UserAgent); Lock = EngineLock.LoadEmbedded(); + InstallKind = AppInstallLocator.CreateDefault().Detect(AppContext.BaseDirectory, Environment.ProcessPath); + UpdateRecovery = new UpdateRecovery(Paths.DataDirectory, AppContext.BaseDirectory, InstallKind, + Bydlo.Core.AppVersion.Current, EngineLock.BundleVersion); Installer = new EngineInstaller(Http, Lock, Paths.EnginesDirectory); Locator = new EngineLocator(Installer, PlatformInfo.Current); ZapretFirewall = new ZapretFirewall(Runner, Installer.UserDataDirectory); @@ -60,7 +63,8 @@ private AppServices(string[] args, IPrivilegeService? privileges) AutomaticUpdates = new(() => new PackagedAppUpdater(Paths.DataDirectory, Http)) { // Package markers decide who owns updates; a writable path alone never enables the built-in updater. - InstallKind = AppInstallLocator.CreateDefault().Detect(AppContext.BaseDirectory, Environment.ProcessPath), + InstallKind = InstallKind, + Recovery = UpdateRecovery, }; } @@ -137,6 +141,12 @@ private AppServices(string[] args, IPrivilegeService? privileges) public AutomaticAppUpdater AutomaticUpdates { get; } + /// How this copy was installed (issue #413). + public AppInstallKind InstallKind { get; } + + /// Local update recovery journal and readiness confirmation (issue #412). + public UpdateRecovery UpdateRecovery { get; } + /// Whether privileged engines are delegated to the installed helper. public bool UsesPrivilegedHelper => HelperManagement.IsSupported && !Privileges.IsElevated && !IsMock && !NetworkSafetyGuard.IsLocked && HelperManagement.IsInstalled; @@ -147,6 +157,8 @@ private AppServices(string[] args, IPrivilegeService? privileges) public static async Task CreateAsync(string[] args, IPrivilegeService? privileges = null) { var s = new AppServices(args, privileges); + // Recovery runs before any user data is read: a snapshot restored here is what the app then loads (issue #412). + s.UpdateRecovery.PrepareStartup(); var firstRun = !File.Exists(s.Paths.SettingsFile); s.Settings = await s.SettingsStore.LoadAsync().ConfigureAwait(false); if (firstRun) @@ -184,6 +196,31 @@ public static async Task CreateAsync(string[] args, IPrivilegeServi public Task SaveSettingsAsync() => SettingsStore.SaveAsync(Settings); + /// + /// Local readiness confirmation for a freshly installed version (issue #412). Called once the UI is up; + /// it only inspects local state and never starts a tunnel, an engine, a driver or a network request. + /// + public void ConfirmUpdateReadiness() + { + if (!UpdateRecovery.IsPending) { return; } + var readiness = new UpdateReadiness( + uiStarted: true, + userDataLoaded: IsUserDataLoaded(SettingsStore.LoadStatus) && IsUserDataLoaded(Profiles.LoadStatus), + componentsConsistent: UpdateRecovery.ComponentsConsistent(Bydlo.Core.AppVersion.Current, EngineLock.BundleVersion), + helperCompatible: !HelperManagement.IsOutdated(ExpectedHelperBuild)); + var result = UpdateRecovery.Confirm(readiness); + Log.Info("update", $"Update readiness: {result}. Phase: {UpdateRecovery.Journal?.Phase}. " + + $"Failed checks: {string.Join(',', readiness.Failures)}. Notes: {string.Join(',', readiness.Notes)}."); + if (result == UpdateRecoveryConfirmation.RolledBack) + { + Log.Error("update", "The new version did not confirm readiness; automatic updates are paused."); + } + } + + /// A missing file is fine; a reset or unreadable one means the new version did not load user data. + private static bool IsUserDataLoaded(StoreLoadStatus status) => + status is StoreLoadStatus.Ok or StoreLoadStatus.Missing or StoreLoadStatus.RecoveredFromBackup; + public async Task RestoreBackupAsync(Bydlo.Core.Backup.BackupData data, Bydlo.Core.Backup.BackupImportMode mode) { var restored = Bydlo.Core.Backup.BackupArchive.ImportSettings(data, Settings, mode); diff --git a/src/Bydlo.App/Services/DesktopIntegration.cs b/src/Bydlo.App/Services/DesktopIntegration.cs index ff11f69e..de074bff 100644 --- a/src/Bydlo.App/Services/DesktopIntegration.cs +++ b/src/Bydlo.App/Services/DesktopIntegration.cs @@ -145,6 +145,9 @@ private async void OnOpened(object? sender, EventArgs e) if (_startupHandled) { return; } _startupHandled = true; var services = _shell.Services; + // The window is up: this is the local readiness confirmation of a freshly installed version (issue #412). + services.ConfirmUpdateReadiness(); + _shell.ShowUpdateRecoveryToast(); if (services.Args.Contains("--autostart", StringComparer.Ordinal) && services.Settings.OnboardingCompleted && services.Settings.MinimizeToTray && _tray.NativeMenuExporter is not null) { _window.Hide(); } diff --git a/src/Bydlo.App/Services/PackagedAppUpdater.cs b/src/Bydlo.App/Services/PackagedAppUpdater.cs index 50dfdd3f..595e08ce 100644 --- a/src/Bydlo.App/Services/PackagedAppUpdater.cs +++ b/src/Bydlo.App/Services/PackagedAppUpdater.cs @@ -22,6 +22,9 @@ internal sealed class PackagedAppUpdater(string dataDirectory, HttpClient http) public bool IsInstalled => !File.Exists(Path.Combine(AppContext.BaseDirectory, "portable.txt")) && AutomaticAppUpdater.HasSeparateDataDirectory(AppContext.BaseDirectory, dataDirectory) && _manager.IsInstalled; + /// Version Velopack will install on the next exit; the recovery journal records it (issue #412). + public string? PendingVersion => _manager.UpdatePendingRestart?.Version?.ToString(); + public async Task DownloadLatestAsync(IProgress? progress, CancellationToken ct) { NetworkSafetyGuard.EnsureAllowed("download application update"); diff --git a/src/Bydlo.App/ViewModels/MainViewModel.cs b/src/Bydlo.App/ViewModels/MainViewModel.cs index f593b0e5..30f2950d 100644 --- a/src/Bydlo.App/ViewModels/MainViewModel.cs +++ b/src/Bydlo.App/ViewModels/MainViewModel.cs @@ -114,6 +114,7 @@ public MainViewModel(AppServices services, Bydlo.Core.Import.SubscriptionClient? Loc.Instance.PropertyChanged += (_, _) => OnNoticeLanguageChanged(); RefreshCrashReports(); ShowStoreRecoveryToasts(); + ShowUpdateRecoveryToast(); _ = RunStartupChecksAsync(); services.StartSubscriptionAutoRefresh(Connections.RunAutoRefreshAsync); } @@ -141,6 +142,30 @@ private void ShowStoreRecoveryToasts() } } + private UpdateRecoveryStartup? _shownUpdateRecovery; + + /// + /// Explains an interrupted or unconfirmed update. Called once at startup and again after the readiness + /// confirmation, which may turn the state into (issue #412). + /// + public void ShowUpdateRecoveryToast() + { + var startup = Services.UpdateRecovery.Startup; + if (startup == _shownUpdateRecovery) { return; } + _shownUpdateRecovery = startup; + switch (startup) + { + case UpdateRecoveryStartup.Blocked: + ShowToast(Loc.T("update.recovery.blocked", Bydlo.Core.AppVersion.Current), isError: true, + localizationKey: "update.recovery.blocked", localizationArguments: [Bydlo.Core.AppVersion.Current]); + break; + case UpdateRecoveryStartup.Interrupted: + ShowToast(Loc.T("update.recovery.interrupted", Bydlo.Core.AppVersion.Current), isError: true, + localizationKey: "update.recovery.interrupted", localizationArguments: [Bydlo.Core.AppVersion.Current]); + break; + } + } + public AppServices Services { get; } public HomeViewModel Home { get; } diff --git a/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs b/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs index 0d37eac2..7a3b69a4 100644 --- a/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs +++ b/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs @@ -47,18 +47,21 @@ partial void OnAutoUpdateAppChanged(bool value) /// /// Single status line. The packaged update state is authoritative, so a release notification can never - /// replace "downloaded, installs on exit" with "new version available" (issue #413). + /// replace "downloaded, installs on exit" with "new version available" (issue #413). A failed confirmation + /// of the previous version wins over both, because automatic updates are paused (issue #412). /// - public string UpdateStatus => Services.AutomaticUpdates.State switch - { - AppUpdateState.Downloading => L["settings.update.downloading"], - AppUpdateState.Ready => L["settings.update.ready"], - AppUpdateState.Deferred => L["settings.update.deferred"], - AppUpdateState.Failed => _updateFailureStatus ?? L["settings.update.error"], - AppUpdateState.Available when Services.AutomaticUpdates.AvailableVersion is { } version => - Loc.T("settings.update.available", version), - _ => _updateCheckStatus, - }; + public string UpdateStatus => Services.UpdateRecovery.AutoApplyBlocked + ? L["settings.update.recovery.blocked"] + : Services.AutomaticUpdates.State switch + { + AppUpdateState.Downloading => L["settings.update.downloading"], + AppUpdateState.Ready => L["settings.update.ready"], + AppUpdateState.Deferred => L["settings.update.deferred"], + AppUpdateState.Failed => _updateFailureStatus ?? L["settings.update.error"], + AppUpdateState.Available when Services.AutomaticUpdates.AvailableVersion is { } version => + Loc.T("settings.update.available", version), + _ => _updateCheckStatus, + }; /// Secondary line: last check time or live progress. [ObservableProperty] @@ -113,9 +116,15 @@ public void RefreshUpdateState() var blocked = Services.IsMock || NetworkSafetyGuard.IsLocked; OnPropertyChanged(nameof(SupportsAutomaticUpdates)); IsAutoUpdateAvailable = SupportsAutomaticUpdates && !blocked && Services.AutomaticUpdates.IsAvailable(); - UpdateGuidanceText = SupportsAutomaticUpdates - ? (blocked ? L["settings.update.auto.unavailable"] : "") - : L[UpdateGuidance.KeyFor(Services.AutomaticUpdates.InstallKind)]; + // Only mention the kept package when the installer really left one next to the app (issue #412). + var recoveryGuidance = Services.UpdateRecovery.PreviousPackageAvailable + ? "settings.update.recovery.previous" + : "settings.update.recovery.manual"; + UpdateGuidanceText = Services.UpdateRecovery.AutoApplyBlocked + ? L[recoveryGuidance] + : SupportsAutomaticUpdates + ? (blocked ? L["settings.update.auto.unavailable"] : "") + : L[UpdateGuidance.KeyFor(Services.AutomaticUpdates.InstallKind)]; RefreshUpdateDetail(); OnPropertyChanged(nameof(UpdateStatus)); } diff --git a/src/Bydlo.Core/Diagnostics/AutomaticAppUpdater.cs b/src/Bydlo.Core/Diagnostics/AutomaticAppUpdater.cs index 2cba2bd1..3045413e 100644 --- a/src/Bydlo.Core/Diagnostics/AutomaticAppUpdater.cs +++ b/src/Bydlo.Core/Diagnostics/AutomaticAppUpdater.cs @@ -6,6 +6,10 @@ namespace Bydlo.Core.Diagnostics; public interface IAppUpdateBackend { bool IsInstalled { get; } + + /// Version of the package that installs on the next exit, if one is downloaded (issue #412). + string? PendingVersion { get; } + Task DownloadLatestAsync(IProgress? progress, CancellationToken ct); void ApplyOnExit(); } @@ -34,6 +38,12 @@ public static bool HasSeparateDataDirectory(string applicationDirectory, string /// Who owns updates for this copy. Only a Velopack install may update itself. public AppUpdateOwner Owner => AppUpdateOwnership.OwnerOf(InstallKind); + /// + /// Local recovery protocol (issue #412). When it is set, a package is applied only after the journal and + /// the user-data snapshot exist, and a failed confirmation stops automatic updates. + /// + public UpdateRecovery? Recovery { get; set; } + /// Single user-visible state shared by the release check and the packaged updater. public AppUpdateState State { get; private set; } @@ -119,6 +129,8 @@ public async Task DownloadIfDueAsync(AppSettings settings, bool blocked, public Task DownloadNowAsync(AppSettings settings, bool blocked, IProgress? progress = null, CancellationToken ct = default) { + // An explicit request is the only way out of a failed-confirmation block (issue #412). + Recovery?.ClearBlock(); if (!AllowsUpdates(settings) || blocked || _busy) { return Task.FromResult(false); } return DownloadAsync(settings, progress, ct); } @@ -126,9 +138,11 @@ public Task DownloadNowAsync(AppSettings settings, bool blocked, /// /// The packaged update needs both the explicit GitHub consent and the download opt-in (issue #438). /// Revoking either one stops future downloads and blocks a package that is already staged. + /// A failed confirmation of the previous version also stops automatic updates (issue #412). /// - private static bool AllowsUpdates(AppSettings settings) => - settings.AutoUpdateApp && FeatureConsent.From(settings).Allows(OptionalFeature.AutomaticUpdates); + private bool AllowsUpdates(AppSettings settings) => + settings.AutoUpdateApp && FeatureConsent.From(settings).Allows(OptionalFeature.AutomaticUpdates) && + Recovery?.AutoApplyBlocked != true; private async Task DownloadAsync(AppSettings settings, IProgress? progress, CancellationToken ct) { @@ -165,6 +179,12 @@ private async Task DownloadAsync(AppSettings settings, IProgress? pro State = AvailableVersion is null ? AppUpdateState.Idle : AppUpdateState.Available; return false; } + // A package without a recovery journal and snapshot is never applied (issue #412). + if (Recovery is not null && !Recovery.Stage(backend.PendingVersion)) + { + State = AppUpdateState.Deferred; + return false; + } // Turning the opt-in off during the download keeps the package but never applies it. State = settings.AutoUpdateApp && !ct.IsCancellationRequested ? AppUpdateState.Ready @@ -190,6 +210,11 @@ public AppUpdateApplyResult ApplyOnExit(AppSettings settings, bool blocked) } try { + // Without a durable journal and snapshot the package stays downloaded (issue #412). + if (Recovery is not null && (!Recovery.CanApply(_backend!.PendingVersion) || !Recovery.MarkApplying())) + { + return AppUpdateApplyResult.Deferred; + } _backend!.ApplyOnExit(); } catch (Exception) diff --git a/src/Bydlo.Core/Diagnostics/UpdateRecovery.cs b/src/Bydlo.Core/Diagnostics/UpdateRecovery.cs new file mode 100644 index 00000000..e0066711 --- /dev/null +++ b/src/Bydlo.Core/Diagnostics/UpdateRecovery.cs @@ -0,0 +1,609 @@ +using System.Text.Json; +using Bydlo.Core.Serialization; +using Bydlo.Core.Storage; + +namespace Bydlo.Core.Diagnostics; + +/// Phase of the local update recovery journal (issue #412). +public enum UpdateRecoveryPhase +{ + /// The package is downloaded and verified, the snapshot exists, no file was replaced yet. + Staged, + + /// The package was handed to the installer and this process is exiting. + Applying, + + /// The new version started but has not confirmed readiness yet. + PendingConfirmation, + + /// The new version started, the UI came up, user data loaded and the components match. + Confirmed, + + /// + /// The protocol returned to the last known-good state: the previous version is running again or the + /// snapshot was restored. BYDLO never replaces application files itself, so this is not a binary rollback. + /// + RolledBack, +} + +/// Why the protocol stopped trying (issue #412). +public enum UpdateRecoveryReason +{ + None, + + /// The installer never replaced the files: the previous version started again. + Interrupted, + + /// The new version started but failed the readiness check too many times. + NotReady, +} + +/// What the startup recovery decided; drives the localized message and the auto-apply guard. +public enum UpdateRecoveryStartup +{ + /// This copy is not a Velopack install: recovery never touches it. + Ignored, + + /// No journal, or the last update was already confirmed. + Nothing, + + /// The new version is running and waits for the UI to confirm readiness. + AwaitingConfirmation, + + /// The installer did not replace the files; the previous version is running. + Interrupted, + + /// The attempt budget is exhausted: automatic updates stay off until the user asks explicitly. + Blocked, +} + +/// Outcome of . +public enum UpdateRecoveryConfirmation +{ + /// No confirmation was pending. + Nothing, + + /// The new version is proven and the snapshot was dropped. + Confirmed, + + /// The check failed but the attempt budget is not exhausted; the next start retries. + Retry, + + /// The budget is exhausted: automatic updates are paused and the next start restores the snapshot. + RolledBack, +} + +/// +/// Durable record of one update transition (issue #412). Written atomically before the installer runs and +/// updated at every phase, so an interrupted write or a crash at any step leaves a readable state. +/// +public sealed class UpdateRecoveryJournal +{ + public int Version { get; set; } = 1; + + public UpdateRecoveryPhase Phase { get; set; } + + public UpdateRecoveryReason Reason { get; set; } + + /// Version that was running when the package was staged. + public string? FromVersion { get; set; } + + /// Version the staged package installs. + public string? ToVersion { get; set; } + + /// Hash of the pinned engine lock the staged package was built with. + public string? EngineBundleVersion { get; set; } + + /// Starts of the new version that did not confirm readiness, or interrupted applies. + public int Attempts { get; set; } + + /// Automatic downloads and installs stay off until the user asks explicitly. + public bool AutoApplyBlocked { get; set; } + + /// Directory of the user-data snapshot taken before the first run of the new version. + public string? SnapshotDirectory { get; set; } + + public DateTimeOffset UpdatedAt { get; set; } + + /// Blocking readiness checks that failed, as short identifiers. + public List FailedChecks { get; set; } = []; + + /// Informational findings, e.g. an outdated privileged helper. + public List Notes { get; set; } = []; +} + +/// +/// Local readiness of a freshly installed version (issue #412). Only local state is inspected: no tunnel, +/// engine, driver, service or network request is involved. +/// +public sealed class UpdateReadiness +{ + public UpdateReadiness(bool uiStarted, bool userDataLoaded, bool componentsConsistent, bool helperCompatible) + { + UiStarted = uiStarted; + UserDataLoaded = userDataLoaded; + ComponentsConsistent = componentsConsistent; + HelperCompatible = helperCompatible; + var failures = new List(); + if (!uiStarted) { failures.Add("ui"); } + if (!userDataLoaded) { failures.Add("user-data"); } + if (!componentsConsistent) { failures.Add("components"); } + Failures = failures; + // An outdated helper degrades privileged features but never blocks the app: it is reported, not fatal. + Notes = helperCompatible ? [] : ["helper"]; + } + + public bool UiStarted { get; } + + /// Settings and profiles parsed without falling back to an empty document. + public bool UserDataLoaded { get; } + + /// Running application and pinned engine bundle match the versions recorded at staging. + public bool ComponentsConsistent { get; } + + /// Installed privileged helper matches this build, or no helper is installed. + public bool HelperCompatible { get; } + + public bool IsReady => UiStarted && UserDataLoaded && ComponentsConsistent; + + public IReadOnlyList Failures { get; } + + public IReadOnlyList Notes { get; } +} + +/// +/// Answers whether the installer kept a full package of another version next to the application (issue #412). +/// BYDLO mentions that path only when the file is really there and never runs the installer itself. +/// +public interface IUpdateRollbackProbe +{ + bool HasPreviousPackage(string applicationDirectory, string currentVersion); +} + +/// Read-only directory probe; a missing or unreadable folder means "no previous package". +public sealed class FileSystemRollbackProbe : IUpdateRollbackProbe +{ + public bool HasPreviousPackage(string applicationDirectory, string currentVersion) + { + // Without the application directory the layout is unknown, so no rollback path is promised. + if (!Directory.Exists(applicationDirectory)) { return false; } + // Windows keeps /current next to /packages; other layouts simply have no such folder. + foreach (var directory in new[] + { + Path.Combine(applicationDirectory, "packages"), + Path.Combine(applicationDirectory, "..", "packages"), + }) + { + try + { + if (!Directory.Exists(directory)) { continue; } + foreach (var file in Directory.EnumerateFiles(directory, "*-full.nupkg")) + { + if (!Path.GetFileName(file).Contains("-" + currentVersion + "-", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + return false; + } +} + +/// +/// Copies the user data files the updater must never lose (issue #412). Secrets live in the secret store, +/// which the updater does not touch, so they are not copied here. +/// +public sealed class UpdateSnapshot(string directoryPath) +{ + public const string SettingsFileName = "settings.json"; + + public const string ProfilesFileName = "profiles.json"; + + private static readonly string[] Files = [SettingsFileName, ProfilesFileName]; + + public string DirectoryPath { get; } = directoryPath; + + /// Copies the user data files that exist. False means the snapshot could not be written. + public bool TryCreate(string dataDirectory) + { + try + { + Directory.CreateDirectory(DirectoryPath); + foreach (var name in Files) + { + var source = Path.Combine(dataDirectory, name); + if (File.Exists(source)) + { + File.Copy(source, Path.Combine(DirectoryPath, name), overwrite: true); + } + } + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } + + /// + /// Restores only files that are missing or no longer parse. A readable file is never overwritten, so + /// changes made in the new version are not silently discarded. + /// + public IReadOnlyList RestoreMissingOrBroken(string dataDirectory) + { + var restored = new List(); + foreach (var name in Files) + { + var source = Path.Combine(DirectoryPath, name); + if (!File.Exists(source)) { continue; } + var target = Path.Combine(dataDirectory, name); + if (File.Exists(target) && Parses(target)) { continue; } + try + { + File.Copy(source, target, overwrite: true); + restored.Add(name); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + return restored; + } + + public void Delete() + { + try + { + if (Directory.Exists(DirectoryPath)) { Directory.Delete(DirectoryPath, recursive: true); } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + + private static bool Parses(string path) + { + try + { + using var stream = File.OpenRead(path); + using var document = JsonDocument.Parse(stream); + return true; + } + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + { + return false; + } + } +} + +/// +/// Atomic, corruption-tolerant journal file (issue #412). A missing, truncated or unreadable file means +/// "no journal": recovery then does nothing instead of guessing, and the broken file is kept for diagnostics. +/// +public sealed class UpdateRecoveryStore(string path) +{ + /// Journal format this build understands. A newer file is ignored instead of guessed. + public const int CurrentVersion = 1; + + public string Path { get; } = path; + + public UpdateRecoveryJournal? Load() + { + try + { + if (!File.Exists(Path)) { return null; } + using var stream = File.OpenRead(Path); + var journal = JsonSerializer.Deserialize(stream, JsonDefaults.Options.Info()); + return journal is { Version: > 0 and <= CurrentVersion, ToVersion.Length: > 0 } ? journal : null; + } + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + { + JsonDefaults.SaveCorruptCopy(Path); + return null; + } + } + + /// Writes through a temporary file and a rename: a crash leaves the old or the new file, never half of it. + public bool TrySave(UpdateRecoveryJournal journal) + { + var tmp = Path + ".tmp"; + try + { + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Path)!); + using (var stream = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None)) + { + JsonSerializer.Serialize(stream, journal, JsonDefaults.Options.Info()); + stream.Flush(flushToDisk: true); + } + File.Move(tmp, Path, overwrite: true); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + try { File.Delete(tmp); } + catch (Exception cleanup) when (cleanup is IOException or UnauthorizedAccessException) { } + return false; + } + } +} + +/// +/// Minimal recovery protocol around the existing Velopack updater (issue #412). It never installs anything +/// itself: it records the transition, snapshots user data, confirms the new version locally and stops +/// automatic updates when the new version does not come up. Package-manager installs are never touched. +/// +public sealed class UpdateRecovery +{ + /// Starts of an unconfirmed version (or interrupted applies) before automatic updates stop. + public const int MaxAttempts = 2; + + public const string JournalFileName = "update-recovery.json"; + + public const string SnapshotDirectoryName = "update-recovery"; + + public const string SnapshotFolderName = "snapshot"; + + private readonly UpdateRecoveryStore _store; + private readonly UpdateSnapshot _snapshot; + private readonly IUpdateRollbackProbe _rollback; + private readonly TimeProvider _time; + private readonly AppInstallKind _installKind; + private readonly string _applicationDirectory; + private readonly string _currentVersion; + private readonly string _engineBundleVersion; + private bool? _previousPackageAvailable; + + public UpdateRecovery(string dataDirectory, string applicationDirectory, AppInstallKind installKind, + string currentVersion, string engineBundleVersion, IUpdateRollbackProbe? rollback = null, + TimeProvider? time = null) + { + DataDirectory = dataDirectory; + _applicationDirectory = applicationDirectory; + _installKind = installKind; + _currentVersion = currentVersion; + _engineBundleVersion = engineBundleVersion; + _rollback = rollback ?? new FileSystemRollbackProbe(); + _time = time ?? TimeProvider.System; + _store = new UpdateRecoveryStore(Path.Combine(dataDirectory, JournalFileName)); + _snapshot = new UpdateSnapshot(Path.Combine(dataDirectory, SnapshotDirectoryName, SnapshotFolderName)); + } + + public string DataDirectory { get; } + + public UpdateRecoveryJournal? Journal { get; private set; } + + /// What decided for this start. + public UpdateRecoveryStartup Startup { get; private set; } = UpdateRecoveryStartup.Nothing; + + /// Only a Velopack install may run the protocol; deb, Arch and Nix copies are owned by their manager. + public bool IsOwned => _installKind == AppInstallKind.Velopack; + + public bool AutoApplyBlocked => Journal?.AutoApplyBlocked == true; + + /// True while the running version still has to confirm readiness. + public bool IsPending => Journal?.Phase == UpdateRecoveryPhase.PendingConfirmation; + + /// True only when the installer really kept a package of another version next to the app. + public bool PreviousPackageAvailable => _previousPackageAvailable ??= + IsOwned && _rollback.HasPreviousPackage(_applicationDirectory, _currentVersion); + + /// + /// Runs before any user data is read. Decides the phase for this start, counts the attempt and, when the + /// budget is exhausted, restores the snapshot so the app starts from the last known-good data. + /// + public UpdateRecoveryStartup PrepareStartup() + { + if (!IsOwned) + { + Startup = UpdateRecoveryStartup.Ignored; + return Startup; + } + + Journal = _store.Load(); + if (Journal is not { } journal) + { + Startup = UpdateRecoveryStartup.Nothing; + return Startup; + } + + if (journal.Phase == UpdateRecoveryPhase.Confirmed) + { + Startup = UpdateRecoveryStartup.Nothing; + return Startup; + } + + if (journal.Phase == UpdateRecoveryPhase.RolledBack) + { + // The restore always happens here, before user data is read, so the app starts from the snapshot. + if (journal.AutoApplyBlocked && _snapshot.RestoreMissingOrBroken(DataDirectory).Count > 0) + { + journal.Notes.Add("snapshot-restored"); + Save(journal); + } + Startup = journal.AutoApplyBlocked ? UpdateRecoveryStartup.Blocked : UpdateRecoveryStartup.Nothing; + return Startup; + } + + var runningTarget = SameVersion(journal.ToVersion, _currentVersion); + if (journal.Phase == UpdateRecoveryPhase.Staged && !runningTarget) + { + // The package is downloaded but the installer never ran: nothing was replaced and nothing is lost. + Startup = UpdateRecoveryStartup.Nothing; + return Startup; + } + + if ((journal.Phase is UpdateRecoveryPhase.Staged or UpdateRecoveryPhase.Applying) && runningTarget) + { + // The new version is running; the UI confirms readiness later in this start. + journal.Phase = UpdateRecoveryPhase.PendingConfirmation; + journal.Attempts = 1; + Save(journal); + Startup = UpdateRecoveryStartup.AwaitingConfirmation; + return Startup; + } + + if (journal.Phase == UpdateRecoveryPhase.Applying) + { + // The installer ran but the previous version started again. + return RollBack(journal, UpdateRecoveryReason.Interrupted); + } + + if (!runningTarget) + { + // PendingConfirmation for another version: the new one never started. + return RollBack(journal, UpdateRecoveryReason.Interrupted); + } + + // Another start of the version that still has not confirmed readiness. + journal.Attempts++; + if (journal.Attempts > MaxAttempts) + { + return RollBack(journal, UpdateRecoveryReason.NotReady); + } + Save(journal); + Startup = UpdateRecoveryStartup.AwaitingConfirmation; + return Startup; + } + + /// + /// Records a verified package and snapshots user data before anything is replaced. False means the journal + /// or the snapshot could not be written: the package must then never be applied. + /// + public bool Stage(string? toVersion) + { + if (!IsOwned || string.IsNullOrWhiteSpace(toVersion)) { return false; } + if (!_snapshot.TryCreate(DataDirectory)) { return false; } + // An interrupted apply keeps its count, so a package that never replaces the files cannot loop forever. + var previous = Journal ?? _store.Load(); + var attempts = previous is { Phase: UpdateRecoveryPhase.RolledBack, Reason: UpdateRecoveryReason.Interrupted } + ? previous.Attempts + : 0; + var journal = new UpdateRecoveryJournal + { + Phase = UpdateRecoveryPhase.Staged, + FromVersion = _currentVersion, + ToVersion = toVersion, + EngineBundleVersion = _engineBundleVersion, + Attempts = attempts, + SnapshotDirectory = _snapshot.DirectoryPath, + UpdatedAt = _time.GetUtcNow(), + }; + if (!_store.TrySave(journal)) { return false; } + Journal = journal; + return true; + } + + /// + /// Marks the hand-over to the installer. False means the journal cannot be written, so the package must not + /// be applied: without a durable journal there is no recovery. + /// + public bool MarkApplying() + { + if (!IsOwned || Journal is not { } journal || journal.Phase != UpdateRecoveryPhase.Staged) { return false; } + journal.Phase = UpdateRecoveryPhase.Applying; + journal.UpdatedAt = _time.GetUtcNow(); + return _store.TrySave(journal); + } + + /// True only when a staged journal and its snapshot exist for the package that is about to install. + public bool CanApply(string? pendingVersion) + { + if (!IsOwned || Journal is not { } journal || journal.Phase != UpdateRecoveryPhase.Staged) { return false; } + if (pendingVersion is { Length: > 0 } && !SameVersion(journal.ToVersion, pendingVersion)) + { + return false; + } + return journal.SnapshotDirectory is { Length: > 0 } && Directory.Exists(journal.SnapshotDirectory); + } + + /// Compares the running build with the versions recorded when the package was staged. + public bool ComponentsConsistent(string appVersion, string engineBundleVersion) => + Journal is not { } journal || + (SameVersion(journal.ToVersion, appVersion) && + string.Equals(journal.EngineBundleVersion, engineBundleVersion, StringComparison.Ordinal)); + + /// Records the local readiness result of the running version. + public UpdateRecoveryConfirmation Confirm(UpdateReadiness readiness) + { + if (!IsOwned || Journal is not { } journal || journal.Phase != UpdateRecoveryPhase.PendingConfirmation) + { + return UpdateRecoveryConfirmation.Nothing; + } + + journal.FailedChecks = [.. readiness.Failures]; + journal.Notes = [.. readiness.Notes]; + if (readiness.IsReady) + { + journal.Phase = UpdateRecoveryPhase.Confirmed; + journal.Reason = UpdateRecoveryReason.None; + journal.Attempts = 0; + journal.AutoApplyBlocked = false; + Save(journal); + // The new version is proven; the snapshot of the previous one is no longer needed. + _snapshot.Delete(); + Startup = UpdateRecoveryStartup.Nothing; + return UpdateRecoveryConfirmation.Confirmed; + } + + if (journal.Attempts >= MaxAttempts) + { + journal.Phase = UpdateRecoveryPhase.RolledBack; + journal.Reason = UpdateRecoveryReason.NotReady; + journal.AutoApplyBlocked = true; + // The snapshot is restored by the next start, before any user data is read. + Save(journal); + Startup = UpdateRecoveryStartup.Blocked; + return UpdateRecoveryConfirmation.RolledBack; + } + + Save(journal); + return UpdateRecoveryConfirmation.Retry; + } + + /// Explicit user request: allows automatic updates again after a failed confirmation. + public void ClearBlock() + { + if (Journal is not { AutoApplyBlocked: true } journal) { return; } + journal.AutoApplyBlocked = false; + Save(journal); + Startup = UpdateRecoveryStartup.Nothing; + } + + private UpdateRecoveryStartup RollBack(UpdateRecoveryJournal journal, UpdateRecoveryReason reason) + { + journal.Phase = UpdateRecoveryPhase.RolledBack; + journal.Reason = reason; + journal.Attempts++; + journal.AutoApplyBlocked = journal.Attempts >= MaxAttempts; + if (journal.AutoApplyBlocked && _snapshot.RestoreMissingOrBroken(DataDirectory).Count > 0) + { + journal.Notes.Add("snapshot-restored"); + } + Save(journal); + Startup = journal.AutoApplyBlocked ? UpdateRecoveryStartup.Blocked : UpdateRecoveryStartup.Interrupted; + return Startup; + } + + private void Save(UpdateRecoveryJournal journal) + { + journal.UpdatedAt = _time.GetUtcNow(); + // A failed write keeps the previous phase, which is safe: the next start re-evaluates the same state. + _store.TrySave(journal); + } + + /// + /// Velopack reports 0.4.5 while the assembly may report 0.4.5.0; both name the same release. + /// + private static bool SameVersion(string? left, string? right) + { + if (string.Equals(left, right, StringComparison.Ordinal)) { return true; } + return Version.TryParse(left, out var a) && Version.TryParse(right, out var b) && + a.Major == b.Major && a.Minor == b.Minor && + Math.Max(a.Build, 0) == Math.Max(b.Build, 0) && + Math.Max(a.Revision, 0) == Math.Max(b.Revision, 0); + } +} diff --git a/src/Bydlo.Core/Serialization/BydloJson.cs b/src/Bydlo.Core/Serialization/BydloJson.cs index f4fa04a4..c033cb13 100644 --- a/src/Bydlo.Core/Serialization/BydloJson.cs +++ b/src/Bydlo.Core/Serialization/BydloJson.cs @@ -71,6 +71,7 @@ internal sealed partial class CoreJsonContext : JsonSerializerContext; [JsonSerializable(typeof(ProxyChain))] [JsonSerializable(typeof(ProfileDocument))] [JsonSerializable(typeof(BackupData))] +[JsonSerializable(typeof(UpdateRecoveryJournal))] internal sealed partial class CoreStoreJsonContext : JsonSerializerContext; /// De-duplication key of an imported profile (property order is the serialized identity). diff --git a/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs b/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs index 38d2d3cf..89fbb2fb 100644 --- a/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs +++ b/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs @@ -352,6 +352,8 @@ private sealed class FakeBackend : IAppUpdateBackend { public bool IsInstalled { get; set; } = true; + public string? PendingVersion { get; set; } = "0.4.4"; + public int Applied { get; private set; } public Exception? ApplyError { get; set; } diff --git a/tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs b/tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs index b640e109..98d0831e 100644 --- a/tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs +++ b/tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs @@ -185,6 +185,7 @@ public async Task Unpackaged_build_never_downloads_or_applies() private sealed class FakeBackend : IAppUpdateBackend { public bool IsInstalled { get; set; } = true; + public string? PendingVersion { get; set; } = "0.4.4"; public int Downloads { get; private set; } public int Applied { get; private set; } public IProgress? Progress { get; private set; } diff --git a/tests/Bydlo.Tests/FirstRunConsentTests.cs b/tests/Bydlo.Tests/FirstRunConsentTests.cs index 9e4411ff..ca9ca03c 100644 --- a/tests/Bydlo.Tests/FirstRunConsentTests.cs +++ b/tests/Bydlo.Tests/FirstRunConsentTests.cs @@ -292,6 +292,8 @@ private sealed class FakeBackend : IAppUpdateBackend { public bool IsInstalled => true; + public string? PendingVersion => "0.4.4"; + public int Downloads { get; private set; } public int Applied { get; private set; } diff --git a/tests/Bydlo.Tests/UpdateRecoveryTests.cs b/tests/Bydlo.Tests/UpdateRecoveryTests.cs new file mode 100644 index 00000000..af4ebc82 --- /dev/null +++ b/tests/Bydlo.Tests/UpdateRecoveryTests.cs @@ -0,0 +1,482 @@ +using Bydlo.Core.Diagnostics; +using Bydlo.Core.Models; + +namespace Bydlo.Tests; + +/// +/// Issue #412: the local recovery protocol around the Velopack updater. Every test uses a temporary directory +/// and fakes; no installer, engine, driver or network request is involved. +/// +public sealed class UpdateRecoveryTests +{ + private const string OldVersion = "0.4.4"; + private const string NewVersion = "0.4.5"; + private const string Bundle = "bundle-a"; + + private static UpdateRecovery Recovery(string dataDirectory, string currentVersion = OldVersion, + AppInstallKind kind = AppInstallKind.Velopack, bool previousPackage = false) => + new(dataDirectory, Path.Combine(dataDirectory, "app"), kind, currentVersion, Bundle, + new FakeRollbackProbe(previousPackage)); + + private static UpdateReadiness Ready() => new(uiStarted: true, userDataLoaded: true, + componentsConsistent: true, helperCompatible: true); + + private static UpdateReadiness NotReady() => new(uiStarted: false, userDataLoaded: true, + componentsConsistent: true, helperCompatible: true); + + private static string JournalPath(string dataDirectory) => + Path.Combine(dataDirectory, UpdateRecovery.JournalFileName); + + [Fact] + public void Journal_round_trip_is_atomic_and_leaves_no_temporary_file() + { + var dir = TestDirs.New("recovery-roundtrip"); + var store = new UpdateRecoveryStore(JournalPath(dir)); + var journal = new UpdateRecoveryJournal + { + Phase = UpdateRecoveryPhase.PendingConfirmation, + FromVersion = OldVersion, + ToVersion = NewVersion, + EngineBundleVersion = Bundle, + Attempts = 1, + SnapshotDirectory = Path.Combine(dir, "snapshot"), + }; + + Assert.True(store.TrySave(journal)); + var loaded = store.Load(); + Assert.NotNull(loaded); + Assert.Equal(UpdateRecoveryPhase.PendingConfirmation, loaded.Phase); + Assert.Equal(NewVersion, loaded.ToVersion); + Assert.Equal(1, loaded.Attempts); + Assert.False(File.Exists(store.Path + ".tmp")); + } + + [Fact] + public async Task Truncated_journal_is_ignored_and_kept_for_diagnostics() + { + var dir = TestDirs.New("recovery-truncated"); + // Fault injection: the process died in the middle of the journal write. + await File.WriteAllTextAsync(JournalPath(dir), "{\"Version\":1,\"Phase\":\"Appli"); + + var recovery = Recovery(dir); + Assert.Equal(UpdateRecoveryStartup.Nothing, recovery.PrepareStartup()); + Assert.Null(recovery.Journal); + Assert.Single(Directory.GetFiles(dir, UpdateRecovery.JournalFileName + ".corrupt-*")); + + // The next download replaces the broken file instead of failing forever. + Assert.True(recovery.Stage(NewVersion)); + Assert.Equal(UpdateRecoveryPhase.Staged, new UpdateRecoveryStore(JournalPath(dir)).Load()!.Phase); + } + + [Fact] + public async Task Leftover_temporary_file_does_not_break_the_journal() + { + var dir = TestDirs.New("recovery-tmp"); + await File.WriteAllTextAsync(JournalPath(dir) + ".tmp", "{\"Version\":1,\"Phase\":\"Appl"); + + var recovery = Recovery(dir); + Assert.Equal(UpdateRecoveryStartup.Nothing, recovery.PrepareStartup()); + Assert.True(recovery.Stage(NewVersion)); + Assert.False(File.Exists(JournalPath(dir) + ".tmp")); + } + + [Fact] + public async Task Journal_from_a_newer_format_is_ignored_instead_of_guessed() + { + var dir = TestDirs.New("recovery-newer"); + await File.WriteAllTextAsync(JournalPath(dir), + "{\"Version\":99,\"Phase\":\"Applying\",\"ToVersion\":\"0.4.5\"}"); + + var recovery = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.Nothing, recovery.PrepareStartup()); + Assert.Null(recovery.Journal); + // The unknown file is left untouched for the version that wrote it. + Assert.Contains("\"Version\":99", await File.ReadAllTextAsync(JournalPath(dir)), StringComparison.Ordinal); + } + + [Fact] + public void Package_is_applied_only_with_a_staged_journal_and_snapshot() + { + var dir = TestDirs.New("recovery-canapply"); + var recovery = Recovery(dir); + + Assert.False(recovery.CanApply(NewVersion)); + Assert.True(recovery.Stage(NewVersion)); + Assert.True(recovery.CanApply(NewVersion)); + Assert.True(recovery.CanApply("0.4.5.0")); + Assert.False(recovery.CanApply("0.4.6")); + Assert.True(recovery.MarkApplying()); + Assert.False(recovery.CanApply(NewVersion)); + + // A deleted snapshot removes the recovery guarantee, so the package must not install. + var second = Recovery(dir); + Assert.True(second.Stage(NewVersion)); + Directory.Delete(Path.Combine(dir, UpdateRecovery.SnapshotDirectoryName), recursive: true); + Assert.False(second.CanApply(NewVersion)); + } + + [Fact] + public async Task New_version_confirms_readiness_and_drops_the_snapshot() + { + var dir = TestDirs.New("recovery-confirm"); + await File.WriteAllTextAsync(Path.Combine(dir, "settings.json"), "{}"); + + var old = Recovery(dir); + Assert.True(old.Stage(NewVersion)); + Assert.True(old.MarkApplying()); + + var next = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, next.PrepareStartup()); + Assert.True(next.ComponentsConsistent(NewVersion, Bundle)); + Assert.Equal(UpdateRecoveryConfirmation.Confirmed, next.Confirm(Ready())); + Assert.Equal(UpdateRecoveryPhase.Confirmed, next.Journal!.Phase); + Assert.Equal(0, next.Journal.Attempts); + Assert.False(next.AutoApplyBlocked); + Assert.False(Directory.Exists(Path.Combine(dir, UpdateRecovery.SnapshotDirectoryName, UpdateRecovery.SnapshotFolderName))); + + // A later start of the confirmed version does nothing. + Assert.Equal(UpdateRecoveryStartup.Nothing, Recovery(dir, NewVersion).PrepareStartup()); + } + + [Fact] + public void Failed_confirmation_is_bounded_and_stops_automatic_updates() + { + var dir = TestDirs.New("recovery-fail"); + var old = Recovery(dir); + Assert.True(old.Stage(NewVersion)); + Assert.True(old.MarkApplying()); + + // First start of the new version: one attempt, the check fails, the next start retries. + var first = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, first.PrepareStartup()); + Assert.Equal(UpdateRecoveryConfirmation.Retry, first.Confirm(NotReady())); + Assert.Equal(1, first.Journal!.Attempts); + Assert.False(first.AutoApplyBlocked); + + // Second start: the budget is exhausted, the protocol stops and blocks automatic updates. + var second = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, second.PrepareStartup()); + Assert.Equal(UpdateRecoveryConfirmation.RolledBack, second.Confirm(NotReady())); + Assert.Equal(UpdateRecoveryPhase.RolledBack, second.Journal!.Phase); + Assert.Equal(UpdateRecoveryReason.NotReady, second.Journal.Reason); + Assert.True(second.AutoApplyBlocked); + + // Third start: no further attempt, no loop, and a late success cannot silently unblock. + var third = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.Blocked, third.PrepareStartup()); + Assert.Equal(UpdateRecoveryConfirmation.Nothing, third.Confirm(Ready())); + Assert.Equal(2, third.Journal!.Attempts); + Assert.True(third.AutoApplyBlocked); + } + + [Fact] + public void Interrupted_apply_returns_to_the_previous_version_and_is_bounded() + { + var dir = TestDirs.New("recovery-interrupted"); + var old = Recovery(dir); + Assert.True(old.Stage(NewVersion)); + Assert.True(old.MarkApplying()); + + // The installer never replaced the files: the previous version starts again. + var again = Recovery(dir); + Assert.Equal(UpdateRecoveryStartup.Interrupted, again.PrepareStartup()); + Assert.Equal(UpdateRecoveryPhase.RolledBack, again.Journal!.Phase); + Assert.Equal(UpdateRecoveryReason.Interrupted, again.Journal.Reason); + Assert.False(again.AutoApplyBlocked); + + // A second interrupted apply exhausts the budget instead of retrying forever. + Assert.True(again.Stage(NewVersion)); + Assert.Equal(1, again.Journal!.Attempts); + Assert.True(again.MarkApplying()); + var twice = Recovery(dir); + Assert.Equal(UpdateRecoveryStartup.Blocked, twice.PrepareStartup()); + Assert.True(twice.AutoApplyBlocked); + } + + [Fact] + public async Task Snapshot_restores_missing_or_broken_user_data_only() + { + var dir = TestDirs.New("recovery-snapshot"); + var settings = Path.Combine(dir, "settings.json"); + var profiles = Path.Combine(dir, "profiles.json"); + await File.WriteAllTextAsync(settings, "{\"Language\":\"ru\"}"); + await File.WriteAllTextAsync(profiles, "{\"Version\":1,\"Profiles\":[]}"); + + var old = Recovery(dir); + Assert.True(old.Stage(NewVersion)); + Assert.True(old.MarkApplying()); + + // The new version breaks the settings file and loses the profile list. + await File.WriteAllTextAsync(settings, "{ broken"); + File.Delete(profiles); + + var first = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, first.PrepareStartup()); + Assert.Equal(UpdateRecoveryConfirmation.Retry, first.Confirm(NotReady())); + // Nothing is restored while the budget is not exhausted. + Assert.Equal("{ broken", await File.ReadAllTextAsync(settings)); + + var second = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, second.PrepareStartup()); + Assert.Equal(UpdateRecoveryConfirmation.RolledBack, second.Confirm(NotReady())); + // The restore happens on the next start, before any user data is read. + Assert.Equal("{ broken", await File.ReadAllTextAsync(settings)); + + var third = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.Blocked, third.PrepareStartup()); + Assert.Contains("snapshot-restored", third.Journal!.Notes); + Assert.Contains("ru", await File.ReadAllTextAsync(settings)); + Assert.Contains("Profiles", await File.ReadAllTextAsync(profiles)); + } + + [Fact] + public async Task Readable_user_data_is_never_overwritten_by_the_snapshot() + { + var dir = TestDirs.New("recovery-snapshot-keep"); + var settings = Path.Combine(dir, "settings.json"); + await File.WriteAllTextAsync(settings, "{\"Language\":\"ru\"}"); + + var old = Recovery(dir); + Assert.True(old.Stage(NewVersion)); + Assert.True(old.MarkApplying()); + + // The user changed a setting in the new version; the file is readable, so it must survive the rollback. + await File.WriteAllTextAsync(settings, "{\"Language\":\"en\"}"); + var first = Recovery(dir, NewVersion); + first.PrepareStartup(); + first.Confirm(NotReady()); + var second = Recovery(dir, NewVersion); + second.PrepareStartup(); + Assert.Equal(UpdateRecoveryConfirmation.RolledBack, second.Confirm(NotReady())); + var third = Recovery(dir, NewVersion); + Assert.Equal(UpdateRecoveryStartup.Blocked, third.PrepareStartup()); + + Assert.Equal("{\"Language\":\"en\"}", await File.ReadAllTextAsync(settings)); + } + + [Fact] + public void Package_manager_install_never_runs_recovery() + { + var dir = TestDirs.New("recovery-deb"); + var deb = Recovery(dir, kind: AppInstallKind.Debian); + Assert.False(deb.Stage(NewVersion)); + Assert.Equal(UpdateRecoveryStartup.Ignored, deb.PrepareStartup()); + Assert.False(Directory.Exists(Path.Combine(dir, UpdateRecovery.SnapshotDirectoryName))); + + // A journal left by a Velopack install is not touched by a package-manager copy. + var velopack = Recovery(dir); + Assert.True(velopack.Stage(NewVersion)); + Assert.True(velopack.MarkApplying()); + var debAgain = Recovery(dir, NewVersion, AppInstallKind.Debian); + Assert.Equal(UpdateRecoveryStartup.Ignored, debAgain.PrepareStartup()); + Assert.Null(debAgain.Journal); + Assert.Contains("Applying", File.ReadAllText(JournalPath(dir)), StringComparison.Ordinal); + } + + [Fact] + public void Readiness_requires_ui_user_data_and_matching_components() + { + Assert.True(Ready().IsReady); + Assert.False(new UpdateReadiness(false, true, true, true).IsReady); + Assert.False(new UpdateReadiness(true, false, true, true).IsReady); + Assert.False(new UpdateReadiness(true, true, false, true).IsReady); + Assert.Equal(["ui", "user-data", "components"], new UpdateReadiness(false, false, false, true).Failures); + + // An outdated privileged helper is reported but never blocks the app and is never reinstalled. + var helper = new UpdateReadiness(true, true, true, helperCompatible: false); + Assert.True(helper.IsReady); + Assert.Equal(["helper"], helper.Notes); + } + + [Fact] + public void Components_must_match_the_staged_package() + { + var dir = TestDirs.New("recovery-components"); + var recovery = Recovery(dir); + Assert.True(recovery.Stage(NewVersion)); + + Assert.True(recovery.ComponentsConsistent(NewVersion, Bundle)); + Assert.False(recovery.ComponentsConsistent(OldVersion, Bundle)); + Assert.False(recovery.ComponentsConsistent(NewVersion, "bundle-b")); + } + + [Fact] + public async Task Updater_stages_the_journal_and_requires_it_before_applying() + { + var dir = TestDirs.New("recovery-updater"); + var recovery = Recovery(dir); + var backend = new FakeBackend(); + var updater = new AutomaticAppUpdater(() => backend) + { + InstallKind = AppInstallKind.Velopack, + Recovery = recovery, + }; + var settings = new AppSettings { AutoUpdateApp = true, ConsentAutomaticUpdates = true }; + + Assert.True(await updater.DownloadIfDueAsync(settings, false)); + Assert.Equal(UpdateRecoveryPhase.Staged, recovery.Journal!.Phase); + Assert.Equal(OldVersion, recovery.Journal.FromVersion); + Assert.Equal(NewVersion, recovery.Journal.ToVersion); + Assert.Equal(AppUpdateApplyResult.Applied, updater.ApplyOnExit(settings, false)); + Assert.Equal(UpdateRecoveryPhase.Applying, recovery.Journal.Phase); + Assert.Equal(1, backend.Applied); + } + + [Fact] + public async Task Updater_does_not_apply_when_the_snapshot_is_missing() + { + var dir = TestDirs.New("recovery-updater-nosnapshot"); + var recovery = Recovery(dir); + var backend = new FakeBackend(); + var updater = new AutomaticAppUpdater(() => backend) + { + InstallKind = AppInstallKind.Velopack, + Recovery = recovery, + }; + var settings = new AppSettings { AutoUpdateApp = true, ConsentAutomaticUpdates = true }; + + Assert.True(await updater.DownloadIfDueAsync(settings, false)); + Directory.Delete(Path.Combine(dir, UpdateRecovery.SnapshotDirectoryName), recursive: true); + Assert.Equal(AppUpdateApplyResult.Deferred, updater.ApplyOnExit(settings, false)); + Assert.Equal(0, backend.Applied); + } + + [Fact] + public async Task Package_is_not_applied_when_the_snapshot_cannot_be_written() + { + var dir = TestDirs.New("recovery-nosnapshot"); + var data = Path.Combine(dir, "data"); + // Fault injection: the data directory is a file, so neither the snapshot nor the journal can be written. + await File.WriteAllTextAsync(data, "not a directory"); + var recovery = new UpdateRecovery(data, Path.Combine(dir, "app"), AppInstallKind.Velopack, + OldVersion, Bundle, new FakeRollbackProbe(false)); + var backend = new FakeBackend(); + var updater = new AutomaticAppUpdater(() => backend) + { + InstallKind = AppInstallKind.Velopack, + Recovery = recovery, + }; + var settings = new AppSettings { AutoUpdateApp = true, ConsentAutomaticUpdates = true }; + + Assert.False(await updater.DownloadIfDueAsync(settings, false)); + Assert.Equal(AppUpdateState.Deferred, updater.State); + Assert.Equal(AppUpdateApplyResult.Deferred, updater.ApplyOnExit(settings, false)); + Assert.Equal(0, backend.Applied); + } + + [Fact] + public async Task Blocked_recovery_stops_automatic_updates_until_an_explicit_request() + { + var dir = TestDirs.New("recovery-blocked"); + var old = Recovery(dir); + Assert.True(old.Stage(NewVersion)); + Assert.True(old.MarkApplying()); + var first = Recovery(dir, NewVersion); + first.PrepareStartup(); + first.Confirm(NotReady()); + var second = Recovery(dir, NewVersion); + second.PrepareStartup(); + Assert.Equal(UpdateRecoveryConfirmation.RolledBack, second.Confirm(NotReady())); + Assert.True(second.AutoApplyBlocked); + + var backend = new FakeBackend(); + var updater = new AutomaticAppUpdater(() => backend) + { + InstallKind = AppInstallKind.Velopack, + Recovery = second, + }; + var settings = new AppSettings { AutoUpdateApp = true, ConsentAutomaticUpdates = true }; + + Assert.False(await updater.DownloadIfDueAsync(settings, false)); + Assert.Equal(0, backend.Downloads); + Assert.Equal(AppUpdateApplyResult.Nothing, updater.ApplyOnExit(settings, false)); + Assert.Equal(0, backend.Applied); + + // Only an explicit user request clears the block. + Assert.True(await updater.DownloadNowAsync(settings, false)); + Assert.False(second.AutoApplyBlocked); + Assert.Equal(1, backend.Downloads); + } + + [Fact] + public void Previous_package_is_reported_only_when_the_probe_finds_one() + { + var dir = TestDirs.New("recovery-probe"); + Assert.True(Recovery(dir, NewVersion, previousPackage: true).PreviousPackageAvailable); + Assert.False(Recovery(dir, NewVersion, previousPackage: false).PreviousPackageAvailable); + // A package-manager copy never offers a rollback path. + Assert.False(Recovery(dir, NewVersion, AppInstallKind.Debian, previousPackage: true).PreviousPackageAvailable); + } + + [Fact] + public async Task File_system_probe_finds_a_kept_package_next_to_the_application() + { + var root = TestDirs.New("recovery-packages"); + var application = Path.Combine(root, "current"); + Directory.CreateDirectory(application); + var packages = Path.Combine(root, "packages"); + Directory.CreateDirectory(packages); + await File.WriteAllTextAsync(Path.Combine(packages, "BydloDesktop-0.4.4-full.nupkg"), "package"); + + var probe = new FileSystemRollbackProbe(); + Assert.True(probe.HasPreviousPackage(application, NewVersion)); + Assert.False(probe.HasPreviousPackage(application, OldVersion)); + Assert.False(probe.HasPreviousPackage(Path.Combine(root, "missing"), NewVersion)); + } + + [Fact] + public void Recovery_strings_exist_in_both_languages() + { + var root = RepositoryRoot(); + var en = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "en.json")); + var ru = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "ru.json")); + foreach (var key in new[] + { + "settings.update.recovery.blocked", + "settings.update.recovery.previous", + "settings.update.recovery.manual", + "update.recovery.blocked", + "update.recovery.interrupted", + }) + { + Assert.Contains($"\"{key}\"", en, StringComparison.Ordinal); + Assert.Contains($"\"{key}\"", ru, StringComparison.Ordinal); + } + } + + private static string RepositoryRoot() + { + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) + { + if (File.Exists(Path.Combine(dir.FullName, "BYDLO.slnx"))) + { + return dir.FullName; + } + } + throw new DirectoryNotFoundException("Repository root not found."); + } + + private sealed class FakeRollbackProbe(bool hasPreviousPackage) : IUpdateRollbackProbe + { + public bool HasPreviousPackage(string applicationDirectory, string currentVersion) => hasPreviousPackage; + } + + private sealed class FakeBackend : IAppUpdateBackend + { + public bool IsInstalled { get; set; } = true; + + public string? PendingVersion { get; set; } = NewVersion; + + public int Downloads { get; private set; } + + public int Applied { get; private set; } + + public Task DownloadLatestAsync(IProgress? progress, CancellationToken ct) + { + Downloads++; + return Task.FromResult(true); + } + + public void ApplyOnExit() => Applied++; + } +}