tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
feat(cli): collect the Trash automatically by age and size
- Commit
00b1f9a1832546048679be9f8b513e9573519edc- Author
- Leitwolf11 ·
- Parents
f97f2014b518
Changes
CHANGELOG.md | 3 + docs/commands.md | 7 ++ src/Progmasoft.Tazel/Cli/Commands.cs | 43 +++++++++++-- src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs | 5 ++ src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs | 44 ++++++++++++- src/Progmasoft.Tazel/Project/Trash.cs | 66 +++++++++++++++++++ tests/Progmasoft.Tazel.Tests/TrashTests.cs | 78 +++++++++++++++++++++++ 7 files changed, 239 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16e222d..aea8357 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ - Files copied by Tazel (test data now, cache outputs later) are cloned where the file system allows: `ioctl(FICLONE)` on Linux (Btrfs, XFS, bcachefs) and `clonefile` on macOS (APFS), for files of 64 KiB and more; elsewhere they are copied as before. Windows block cloning is not wired yet. +- Automatic Trash GC after a successful `build`, `run`, `test`, `coverage`, `fetch` or `vendor`, at most once a day under + a lock: entries older than `trash-max-age` days (default 30), then the oldest above `trash-max-size` MiB (default + 10240). Both options are read only from `$TAZEL_HOME/User/tazel_options.txt`. ## 0.5.0 - 2026-12-03 diff --git a/docs/commands.md b/docs/commands.md index 1fb41b5..9a8dc31 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -216,8 +216,15 @@ microvm-memory: 2048; # MiB, or "auto" microvm-cpus: "auto"; platform: linux-amd64; dotnet-settings: [ "GCHeapHardLimit=512M" 'GCSettings.LatencyMode=Interactive' ]; +trash-max-age: 30; # days; only in $TAZEL_HOME/User/tazel_options.txt +trash-max-size: 10240; # MiB; only in $TAZEL_HOME/User/tazel_options.txt ``` +`trash-max-age` and `trash-max-size` steer the automatic Trash GC. After a successful `build`, `run`, `test`, +`coverage`, `fetch` or `vendor`, at most once a day and only when no other Tazel is collecting, Tazel removes Trash +entries older than `trash-max-age` days, then the oldest while the Trash holds more than `trash-max-size` MiB. The GC +never changes the command's result. Only the user's own file may set these two; a project that sets them is refused. + Configuration comes in layers, lowest first: the user's (`$TAZEL_HOME/User/`), every directory above the current one, the farthest first, this machine's settings of the project (`$TAZEL_HOME/Projects/<key>/`, outside the module), and the current directory; the command line is above them all. Each option comes from the highest layer that sets it, an diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 4f34f5e..65e2e55 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -35,15 +35,15 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector ArgumentNullException.ThrowIfNull(command); return command switch { - BuildCommand build => BuildAsync(build.Labels, build.Flags, BuildKind.Build, null, cancel), - TestCommand test => BuildAsync(test.Labels, test.Flags, BuildKind.Test, null, cancel), - CoverageCommand coverage => BuildAsync(coverage.Labels, coverage.Flags, BuildKind.Coverage, null, cancel), - RunCommand run => BuildAsync(run.Label is null ? [] : [run.Label], run.Flags, BuildKind.Run, run.Arguments, cancel), + BuildCommand build => ThenCollectTrash(BuildAsync(build.Labels, build.Flags, BuildKind.Build, null, cancel)), + TestCommand test => ThenCollectTrash(BuildAsync(test.Labels, test.Flags, BuildKind.Test, null, cancel)), + CoverageCommand coverage => ThenCollectTrash(BuildAsync(coverage.Labels, coverage.Flags, BuildKind.Coverage, null, cancel)), + RunCommand run => ThenCollectTrash(BuildAsync(run.Label is null ? [] : [run.Label], run.Flags, BuildKind.Run, run.Arguments, cancel)), QueryCommand query => QueryAsync(query), - FetchCommand fetch => FetchAsync(fetch), + FetchCommand fetch => ThenCollectTrash(FetchAsync(fetch)), ModulesCommand modules => new ModulesCommands(reporter, workingDirectory, TazelVersion).RunAsync(modules, cancel), UpdateCommand update => new ModulesCommands(reporter, workingDirectory, TazelVersion).UpdateAsync(update, cancel), - VendorCommand => VendorAsync(cancel), + VendorCommand => ThenCollectTrash(VendorAsync(cancel)), PackageCommand package => PackageAsync(package), GitAddCommand => new GitCommands(reporter, workingDirectory).AddAsync(TazelVersion), NewCommand create => Task.FromResult(new NewInitCommands(reporter, workingDirectory).New(create.Name, create.Force)), @@ -302,6 +302,37 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; } + /// <summary> + /// After a successful build, run, test, coverage, fetch or vendor: the automatic Trash GC, at most once a day, by the + /// user's <c>trash-max-age</c> and <c>trash-max-size</c>. It never changes the command's result. + /// </summary> + private async Task<int> ThenCollectTrash(Task<int> command) + { + var status = await command.ConfigureAwait(false); + if (status != 0) + { + return status; + } + + try + { + var options = Dsl.Options.TazelOptionsFile.Effective(workingDirectory).Options; + var removed = Project.Trash.Collect( + TimeSpan.FromDays(options.TrashMaxAgeDays), (long)options.TrashMaxSizeMiB * 1024 * 1024, TimeSpan.FromDays(1)); + if (removed.Count > 0) + { + reporter.Status($"removed {removed.Count} old entries from the Trash ({removed.Sum(entry => entry.Bytes)} bytes)"); + } + } + catch (Exception problem) when (problem is IOException or UnauthorizedAccessException or Project.TrashException or + Dsl.Options.TazelOptionsException or Dsl.Configuration.ConfigurationHomeException) + { + reporter.Warning($"the automatic Trash GC did not run: {problem.Message}"); + } + + return status; + } + private int Clean(bool expunge, bool dryRun) { var root = ModuleFiles.FindRoot(workingDirectory); diff --git a/src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs b/src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs index db73161..712a5d6 100644 --- a/src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs +++ b/src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs @@ -60,6 +60,11 @@ internal sealed class ConfigurationCommands(Reporter reporter, string workingDir new("platform", "a platform name, as --platform takes it", "this machine's", "The platform commands build for unless --platform names one. It is chosen before what depends on target_system " + "is read, so it may not be set inside a condition on target_system."), + new("trash-max-age", "a whole number of days from 0 to 36500", "30", + "The automatic Trash GC removes entries older than this. Only the user's own tazel_options.txt may set it."), + new("trash-max-size", "a whole number of MiB from 0 to 16777216", "10240", + "The automatic Trash GC removes the oldest entries while the Trash holds more. Only the user's own " + + "tazel_options.txt may set it."), new("dotnet-settings", "a list of strings, Name=Value each: [ \"GCHeapHardLimit=512M\" ]", "none", "Settings of the .NET runtime of the Tazel process, merged name by name across the layers, before those of " + "--dotnet-settings. tazel help dotnet --long lists the thirteen."), diff --git a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs index eee6bd3..4ada9ea 100644 --- a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs +++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs @@ -48,6 +48,18 @@ public sealed record TazelOptions /// those of <c>--dotnet-settings</c>; none by default. /// </summary> public IReadOnlyList<Runtime.DotnetSetting> DotnetSettings { get; init; } = []; + + /// <summary> + /// <c>trash-max-age</c>: the automatic Trash GC removes entries older than this many days; default 30. Read only + /// from the user's own <c>tazel_options.txt</c>. + /// </summary> + public int TrashMaxAgeDays { get; init; } = 30; + + /// <summary> + /// <c>trash-max-size</c>: the automatic Trash GC removes the oldest entries while the Trash holds more than this + /// many MiB; default 10240 (10 GiB). Read only from the user's own <c>tazel_options.txt</c>. + /// </summary> + public int TrashMaxSizeMiB { get; init; } = 10240; } /// <summary>The options that hold in a directory, with the layer each came from and the layers read.</summary> @@ -98,7 +110,14 @@ public static class TazelOptionsFile private const int MaxCpus = 256; private static readonly string[] Keys = - ["sandboxing-with-microvm", "microvm-network", "microvm-memory", "microvm-cpus", "platform", "dotnet-settings"]; + ["sandboxing-with-microvm", "microvm-network", "microvm-memory", "microvm-cpus", "platform", "dotnet-settings", + "trash-max-age", "trash-max-size"]; + + /// <summary>The options only the user's own <c>tazel_options.txt</c> may set: a project cannot change them.</summary> + public static IReadOnlyList<string> UserOnly { get; } = ["trash-max-age", "trash-max-size"]; + + private const int MaxTrashAgeDays = 36_500; + private const int MaxTrashSizeMiB = 1_048_576 * 16; /// <summary> /// Reads the text of a <c>tazel_options.txt</c>, with the comments and strings of <c>tazel_custom.txt</c>. @@ -237,6 +256,13 @@ public static class TazelOptionsFile var (options, keys) = Read(text, layer.File, layer.File, context); foreach (var key in keys) { + if (layer.Kind != Configuration.LayerKind.User && UserOnly.Contains(key, StringComparer.Ordinal)) + { + throw new TazelOptionsException( + $"{layer.File} sets {key}, which only the user's own {TazelOptions.FileName} in " + + $"$TAZEL_HOME/User/ may set: a project does not decide how a user's Trash is collected"); + } + origins[key] = layer; merged = key switch { @@ -245,6 +271,8 @@ public static class TazelOptionsFile "microvm-memory" => merged with { MicroVMMemory = options.MicroVMMemory }, "microvm-cpus" => merged with { MicroVMCpus = options.MicroVMCpus }, "platform" => merged with { Platform = options.Platform }, + "trash-max-age" => merged with { TrashMaxAgeDays = options.TrashMaxAgeDays }, + "trash-max-size" => merged with { TrashMaxSizeMiB = options.TrashMaxSizeMiB }, _ => merged, }; } @@ -328,6 +356,8 @@ public static class TazelOptionsFile "microvm-network" => options with { MicroVMNetwork = Boolean(value) }, "microvm-memory" => options with { MicroVMMemory = Amount(value, MinMemory, MaxMemory, "MiB") }, "microvm-cpus" => options with { MicroVMCpus = Amount(value, 1, MaxCpus, "processors") }, + "trash-max-age" => options with { TrashMaxAgeDays = Whole(value, 0, MaxTrashAgeDays, "days") }, + "trash-max-size" => options with { TrashMaxSizeMiB = Whole(value, 0, MaxTrashSizeMiB, "MiB") }, _ => options with { Platform = PlatformOf(value) }, }; @@ -420,6 +450,18 @@ public static class TazelOptionsFile "It is a yes-or-no question. Tazel accepts no 'maybe'."); // "auto" is a string, in any of the three quotes; a number stands bare. + private int Whole(Token value, int min, int max, string unit) + { + if (int.TryParse(value.Text, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, + out var number) && number >= min && number <= max) + { + return number; + } + + throw Fail(Output.ErrorCodes.OptionsOutOfRange, value, $"'{value.Text}' is not a whole number of {unit} from {min} to {max}", + "this value", $"write a whole number of {unit}, such as {min + 1}", "Tazel counts in whole numbers here."); + } + private Allocation Amount(Token value, int min, int max, string unit) { if (value.Kind == TokenKind.String) diff --git a/src/Progmasoft.Tazel/Project/Trash.cs b/src/Progmasoft.Tazel/Project/Trash.cs index 6fa6d51..ec919bc 100644 --- a/src/Progmasoft.Tazel/Project/Trash.cs +++ b/src/Progmasoft.Tazel/Project/Trash.cs @@ -167,6 +167,72 @@ public static class Trash return chosen; } + /// <summary>The file in <c>$TAZEL_HOME</c> whose time records the last automatic GC; it is also its lock.</summary> + public static string CollectStamp { get; } = "trash-gc.stamp"; + + /// <summary> + /// The automatic GC: unless it ran less than <paramref name="interval"/> ago, or another Tazel holds its lock, + /// removes the entries older than <paramref name="maxAge"/>, then the oldest while the Trash holds more than + /// <paramref name="maxBytes"/>. Returns what it removed. + /// </summary> + public static IReadOnlyList<Entry> Collect(TimeSpan maxAge, long maxBytes, TimeSpan interval) + { + var home = TazelHome.Directory(); + if (!Directory.Exists(Path.Combine(home, "Projects"))) + { + return []; + } + + var stamp = Path.Combine(home, CollectStamp); + if (File.Exists(stamp) && DateTime.UtcNow - File.GetLastWriteTimeUtc(stamp) < interval) + { + return []; + } + + FileStream gate; + try + { + gate = new FileStream(stamp, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + } + catch (IOException) + { + return []; + } + + using (gate) + { + var now = DateTimeOffset.UtcNow; + var entries = List(); + var removed = entries.Where(entry => now - entry.MovedAt > maxAge).ToList(); + var left = entries.Except(removed).OrderBy(entry => entry.MovedAt).ToList(); + var total = left.Sum(entry => entry.Bytes); + foreach (var entry in left) + { + if (total <= maxBytes) + { + break; + } + + removed.Add(entry); + total -= entry.Bytes; + } + + foreach (var entry in removed) + { + Directory.Delete(entry.Directory, recursive: true); + File.Delete(InfoPath(entry.Directory)); + } + + // Written through the locked handle itself, which also moves the file's time to now: no second handle, + // which Windows would refuse while this one holds the file. + var when = Encoding.UTF8.GetBytes(DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture) + "\n"); + gate.SetLength(0); + gate.Write(when); + gate.Flush(flushToDisk: true); + return removed; + } + } + /// <summary>The fingerprint of a directory's contents: 64 lowercase hexadecimal digits.</summary> public static string Fingerprint(string directory) { diff --git a/tests/Progmasoft.Tazel.Tests/TrashTests.cs b/tests/Progmasoft.Tazel.Tests/TrashTests.cs index 92636bf..642a70f 100644 --- a/tests/Progmasoft.Tazel.Tests/TrashTests.cs +++ b/tests/Progmasoft.Tazel.Tests/TrashTests.cs @@ -3,6 +3,7 @@ using System; using System.IO; +using System.Linq; using System.Threading.Tasks; using Progmasoft.Tazel.Cli; using Progmasoft.Tazel.Dsl.Configuration; @@ -166,6 +167,83 @@ public sealed class TrashTests : IDisposable Assert.False(Directory.Exists(destination + ".partial")); } + private Trash.Entry Expunge(string text) + { + FillState(text); + return Trash.MoveIn(_module.Root, State); + } + + private void Age(Trash.Entry entry, TimeSpan by) + { + var info = entry.Directory + Trash.InfoSuffix; + var record = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(info))!; + record["MovedAt"] = entry.MovedAt - by; + File.WriteAllText(info, record.ToJsonString()); + } + + [Fact] + public void TheAutomaticGcRemovesByAgeThenOldestBySize() + { + var old = Expunge("old"); + Age(old, TimeSpan.FromDays(40)); + var middle = Expunge("middle entry"); + Age(middle, TimeSpan.FromDays(2)); + var young = Expunge("young"); + + var removed = Trash.Collect(TimeSpan.FromDays(30), young.Bytes + 4, TimeSpan.Zero); + Assert.Equal([old.Fingerprint, middle.Fingerprint], removed.Select(entry => entry.Fingerprint).Order()); + Assert.Equal(young.Fingerprint, Assert.Single(Trash.List()).Fingerprint); + } + + [Fact] + public void TheAutomaticGcRunsAtMostOncePerInterval() + { + var entry = Expunge("aged"); + Age(entry, TimeSpan.FromDays(40)); + File.WriteAllText(Path.Combine(_home, Trash.CollectStamp), "recent"); + + Assert.Empty(Trash.Collect(TimeSpan.FromDays(30), long.MaxValue, TimeSpan.FromDays(1))); + Assert.Single(Trash.List()); + File.SetLastWriteTimeUtc(Path.Combine(_home, Trash.CollectStamp), DateTime.UtcNow.AddDays(-2)); + Assert.Single(Trash.Collect(TimeSpan.FromDays(30), long.MaxValue, TimeSpan.FromDays(1))); + } + + [Fact] + public void TheAutomaticGcSkipsWhileAnotherTazelHoldsItsLock() + { + var entry = Expunge("aged"); + Age(entry, TimeSpan.FromDays(40)); + using var held = new FileStream(Path.Combine(_home, Trash.CollectStamp), FileMode.Create, FileAccess.ReadWrite, FileShare.None); + Assert.Empty(Trash.Collect(TimeSpan.FromDays(30), long.MaxValue, TimeSpan.Zero)); + Assert.Single(Trash.List()); + } + + [Fact] + public void TrashLimitsComeFromTheUsersOptionsOnly() + { + Directory.CreateDirectory(Path.Combine(_home, "User")); + File.WriteAllText(Path.Combine(_home, "User", "tazel_options.txt"), "trash-max-age: 7;\ntrash-max-size: 512;\n"); + var options = Dsl.Options.TazelOptionsFile.Effective(_module.Root).Options; + Assert.Equal(7, options.TrashMaxAgeDays); + Assert.Equal(512, options.TrashMaxSizeMiB); + + _module.Write("tazel_options.txt", "trash-max-age: 1;\n"); + var error = Assert.Throws<Dsl.Options.TazelOptionsException>(() => Dsl.Options.TazelOptionsFile.Effective(_module.Root)); + Assert.Contains("only the user's own", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void TrashLimitsKeepTheirDefaultsAndRefuseBadValues() + { + var defaults = new Dsl.Options.TazelOptions(); + Assert.Equal(30, defaults.TrashMaxAgeDays); + Assert.Equal(10240, defaults.TrashMaxSizeMiB); + + Directory.CreateDirectory(Path.Combine(_home, "User")); + File.WriteAllText(Path.Combine(_home, "User", "tazel_options.txt"), "trash-max-age: soon;\n"); + Assert.Throws<Dsl.Options.TazelOptionsException>(() => Dsl.Options.TazelOptionsFile.Effective(_module.Root)); + } + [Theory] [InlineData("trash")] [InlineData("trash lst")]