diff --git a/src/Titano.Core/Packaging/InstallTransaction.cs b/src/Titano.Core/Packaging/InstallTransaction.cs new file mode 100644 index 00000000..fc606eaf --- /dev/null +++ b/src/Titano.Core/Packaging/InstallTransaction.cs @@ -0,0 +1,175 @@ +using Titano.Core.Diagnostics; + +namespace Titano.Core.Packaging; + +/// +/// Installs a verified file set without leaving a half-updated folder. Files are first written into a staging +/// folder inside the target (same volume, so moves are renames); then moves them into place, +/// parking every replaced file in a backup folder. If any move fails, completed moves are undone in reverse order +/// and the previous install is restored. Staging and backup folders are removed on dispose. +/// +public sealed class InstallTransaction : IDisposable +{ + private const string StagingPrefix = ".setup-staging-"; + private const string BackupPrefix = ".setup-backup-"; + private readonly string _backup; + + public InstallTransaction(string targetDirectory) + { + TargetDirectory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(targetDirectory)); + Directory.CreateDirectory(TargetDirectory); + RemoveStaleFolders(TargetDirectory); + var id = Guid.NewGuid().ToString("N")[..8]; + StagingDirectory = Path.Combine(TargetDirectory, StagingPrefix + id); + _backup = Path.Combine(TargetDirectory, BackupPrefix + id); + Directory.CreateDirectory(StagingDirectory); + } + + public string TargetDirectory { get; } + + /// Where the new files are written before . + public string StagingDirectory { get; } + + /// Moves the staged files (payload-relative paths) into the target, all or nothing. + public void Commit(IReadOnlyCollection relativePaths) + { + var completed = new List<(string Staged, string Target, string? Backup)>(relativePaths.Count); + try + { + foreach (var relative in relativePaths) + { + var staged = PayloadPath.Resolve(StagingDirectory, relative); + var target = PayloadPath.Resolve(TargetDirectory, relative); + if (!File.Exists(staged)) throw new FileNotFoundException($"Staged file '{relative}' is missing.", staged); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + string? backup = null; + if (File.Exists(target)) + { + backup = PayloadPath.Resolve(_backup, relative); + Directory.CreateDirectory(Path.GetDirectoryName(backup)!); + File.Move(target, backup); + } + try + { + File.Move(staged, target); + } + catch + { + if (backup is not null) File.Move(backup, target); + throw; + } + completed.Add((staged, target, backup)); + } + } + catch + { + Rollback(completed); + throw; + } + } + + public void Dispose() + { + TryDeleteTree(StagingDirectory); + TryDeleteTree(_backup); + } + + private static void Rollback(List<(string Staged, string Target, string? Backup)> completed) + { + for (var i = completed.Count - 1; i >= 0; i--) + { + var (staged, target, backup) = completed[i]; + try + { + File.Move(target, staged, overwrite: true); + if (backup is not null) File.Move(backup, target); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Error("setup", $"Rollback could not restore '{target}'", ex); + } + } + } + + /// Removes staging/backup folders left by an interrupted earlier run (they are always ours by name). + private static void RemoveStaleFolders(string target) + { + foreach (var dir in Directory.EnumerateDirectories(target, ".setup-*")) + { + var name = Path.GetFileName(dir); + if (name.StartsWith(StagingPrefix, StringComparison.Ordinal) || name.StartsWith(BackupPrefix, StringComparison.Ordinal)) + TryDeleteTree(dir); + } + } + + private static void TryDeleteTree(string path) + { + try + { + if (Directory.Exists(path)) Directory.Delete(path, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Could not remove '{path}'", ex); + } + } +} + +/// Removes installed files by their logged payload paths, never anything else under the folder. +public static class InstalledFiles +{ + /// + /// Deletes each listed file under and prunes folders the deletion left empty (the root + /// itself only when ). Missing files count as removed; returns the paths that + /// could not be deleted, for example because a program still holds them open. + /// + public static IReadOnlyList Remove(string root, IEnumerable relativePaths, bool removeEmptyRoot = false) + { + var fullRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); + var failed = new List(); + var folders = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var relative in relativePaths) + { + var path = PayloadPath.Resolve(fullRoot, relative); + try + { + if (File.Exists(path)) + { + File.SetAttributes(path, FileAttributes.Normal); + File.Delete(path); + } + folders.Add(Path.GetDirectoryName(path)!); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Could not remove '{path}'", ex); + failed.Add(relative); + } + } + + // Deepest folders first, so a parent is examined after its children were pruned. + foreach (var folder in folders.OrderByDescending(f => f.Length)) + { + for (var dir = folder; dir.Length > fullRoot.Length; dir = Path.GetDirectoryName(dir)!) + { + if (!TryRemoveEmpty(dir)) break; + } + } + if (removeEmptyRoot) TryRemoveEmpty(fullRoot); + return failed; + } + + private static bool TryRemoveEmpty(string dir) + { + try + { + if (!Directory.Exists(dir) || Directory.EnumerateFileSystemEntries(dir).Any()) return false; + Directory.Delete(dir); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } +} diff --git a/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs b/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs new file mode 100644 index 00000000..c79e980b --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs @@ -0,0 +1,103 @@ +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class InstallTransactionTests(TestContext context) +{ + [Test] + public void CommitReplacesFilesAndCleansUp() + { + var target = context.CreateTempDirectory(); + File.WriteAllText(Path.Combine(target, "Titano.exe"), "old"); + File.WriteAllText(Path.Combine(target, "user-notes.txt"), "keep"); + + using (var tx = new InstallTransaction(target)) + { + Write(tx.StagingDirectory, "Titano.exe", "new"); + Write(tx.StagingDirectory, "lib/new.dll", "dll"); + tx.Commit(["Titano.exe", "lib/new.dll"]); + } + + Assert.Equal("new", File.ReadAllText(Path.Combine(target, "Titano.exe"))); + Assert.Equal("dll", File.ReadAllText(Path.Combine(target, "lib", "new.dll"))); + Assert.Equal("keep", File.ReadAllText(Path.Combine(target, "user-notes.txt"))); + Assert.Empty(Directory.GetDirectories(target, ".setup-*")); + } + + [Test] + public void FailedCommitRestoresThePreviousInstall() + { + var target = context.CreateTempDirectory(); + File.WriteAllText(Path.Combine(target, "Titano.exe"), "old"); + // A folder where the new version has a file makes the second move fail. + Directory.CreateDirectory(Path.Combine(target, "blocked")); + File.WriteAllText(Path.Combine(target, "blocked", "inside.txt"), "x"); + + using (var tx = new InstallTransaction(target)) + { + Write(tx.StagingDirectory, "Titano.exe", "new"); + Write(tx.StagingDirectory, "added.dll", "added"); + Write(tx.StagingDirectory, "blocked", "file"); + // Linux reports IOException, Windows UnauthorizedAccessException for a file moved onto a folder. + var ex = Assert.Throws(() => tx.Commit(["Titano.exe", "added.dll", "blocked"])); + Assert.True(ex is IOException or UnauthorizedAccessException, ex.GetType().Name); + } + + Assert.Equal("old", File.ReadAllText(Path.Combine(target, "Titano.exe"))); + Assert.FileMissing(Path.Combine(target, "added.dll")); + Assert.Equal("x", File.ReadAllText(Path.Combine(target, "blocked", "inside.txt"))); + Assert.Empty(Directory.GetDirectories(target, ".setup-*")); + } + + [Test] + public void StaleStagingFoldersFromAnInterruptedRunAreRemoved() + { + var target = context.CreateTempDirectory(); + Directory.CreateDirectory(Path.Combine(target, ".setup-staging-deadbeef", "sub")); + Directory.CreateDirectory(Path.Combine(target, ".setup-other")); + using (new InstallTransaction(target)) + { + } + Assert.False(Directory.Exists(Path.Combine(target, ".setup-staging-deadbeef"))); + Assert.True(Directory.Exists(Path.Combine(target, ".setup-other"))); + } + + [Test] + public void RemoveDeletesOnlyLoggedFilesAndPrunesEmptyFolders() + { + var root = context.CreateTempDirectory(); + Write(root, "Titano.exe", "a"); + Write(root, "lib/x/y.dll", "b"); + Write(root, "lib/keep.txt", "user"); + + var failed = InstalledFiles.Remove(root, ["Titano.exe", "lib/x/y.dll", "already-gone.dll"], removeEmptyRoot: true); + + Assert.Empty(failed); + Assert.FileMissing(Path.Combine(root, "Titano.exe")); + Assert.False(Directory.Exists(Path.Combine(root, "lib", "x"))); + Assert.Equal("user", File.ReadAllText(Path.Combine(root, "lib", "keep.txt"))); + Assert.True(Directory.Exists(root), "root keeps unlisted files"); + + InstalledFiles.Remove(root, ["lib/keep.txt"], removeEmptyRoot: true); + Assert.False(Directory.Exists(root)); + } + + [Test] + public void RemoveRefusesPathsOutsideTheRoot() + { + var parent = context.CreateTempDirectory(); + var root = Path.Combine(parent, "install"); + Directory.CreateDirectory(root); + Write(parent, "outside.txt", "precious"); + Assert.Throws(() => InstalledFiles.Remove(root, ["../outside.txt"])); + Assert.FileExists(Path.Combine(parent, "outside.txt")); + } + + private static void Write(string root, string relative, string content) + { + var path = Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + } +}