feat(packaging): add staged install transaction and logged file removal

Extracted files land in a staging folder inside the target and are moved into
place with backups of replaced files; a failed move rolls everything back.
Removal deletes only logged payload paths and prunes folders left empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:56:37 +00:00
1 parent d79ab1e41b
commit fc8df1f411
2 files changed
+278

No files matched your search

@@ -0,0 +1,175 @@
using Titano.Core.Diagnostics;
namespace Titano.Core.Packaging;
/// <summary>
/// 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); <see cref="Commit"/> 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.
/// </summary>
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; }
/// <summary>Where the new files are written before <see cref="Commit"/>.</summary>
public string StagingDirectory { get; }
/// <summary>Moves the staged files (payload-relative paths) into the target, all or nothing.</summary>
public void Commit(IReadOnlyCollection<string> 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);
}
}
}
/// <summary>Removes staging/backup folders left by an interrupted earlier run (they are always ours by name).</summary>
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);
}
}
}
/// <summary>Removes installed files by their logged payload paths, never anything else under the folder.</summary>
public static class InstalledFiles
{
/// <summary>
/// Deletes each listed file under <paramref name="root"/> and prunes folders the deletion left empty (the root
/// itself only when <paramref name="removeEmptyRoot"/>). Missing files count as removed; returns the paths that
/// could not be deleted, for example because a program still holds them open.
/// </summary>
public static IReadOnlyList<string> Remove(string root, IEnumerable<string> relativePaths, bool removeEmptyRoot = false)
{
var fullRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
var failed = new List<string>();
var folders = new HashSet<string>(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;
}
}
}
@@ -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<Exception>(() => 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<PayloadException>(() => 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);
}
}