using System.IO; using Chronos.App.Infrastructure; using Chronos.App.Jobs; using Chronos.Testing; namespace Chronos.App.Tests.Infrastructure; /// Owner review 2, R10: the housekeeping trims the cache to its limit, oldest files first, never what is in use or kept whole. public sealed class CacheStoreTests(TestContext context) { private static readonly DateTime Start = new(2026, 9, 1, 8, 0, 0, DateTimeKind.Utc); /// A cache file of last written days after . private static string Write(string folder, string name, int bytes, int day) { var path = Path.Combine(folder, name); Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllBytes(path, new byte[bytes]); File.SetLastWriteTimeUtc(path, Start.AddDays(day)); return path; } [Test] public void TheOldestFilesGoFirstUntilTheCacheFits() { var cache = context.CreateTempDirectory("cache"); CacheStore.Prepare(cache); var oldest = Write(cache, "spill-1.bin", 400, 1); var older = Write(cache, Path.Combine("render", "spill-2.bin"), 400, 2); var recent = Write(cache, "spill-3.bin", 400, 3); var size = CacheStore.Size(cache); var result = Assert.NotNull(CacheStore.Trim(cache, size - 500)); // 400 bytes were not enough: the two oldest went, the newest and the marker stay. Assert.Equal((size, 800L, 2), (result.Before, result.Freed, result.Deleted)); Assert.Equal(size - 800, result.After); Assert.False(File.Exists(oldest)); Assert.False(File.Exists(older)); Assert.True(File.Exists(recent)); Assert.True(CacheStore.IsOwned(cache), "the marker stays"); // Within the limit: nothing to do. Assert.Equal(0, CacheStore.Trim(cache, 1L << 30)!.Deleted); } [Test] public void FilesInUseAndKeptFoldersStay() { var cache = context.CreateTempDirectory("cache"); CacheStore.Prepare(cache); var proxies = Write(cache, Path.Combine("proxies", "server", "sequence", "frame.jpg"), 1000, 0); var busy = Write(cache, "spill-busy.bin", 1000, 1); var free = Write(cache, "spill-free.bin", 1000, 2); using (new FileStream(busy, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var result = Assert.NotNull(CacheStore.Trim(cache, 0, CacheTrimStep.Kept)); Assert.Equal((1000L, 1), (result.Freed, result.Deleted)); } Assert.True(File.Exists(proxies), "a kept folder is never trimmed"); Assert.True(File.Exists(busy), "a file in use is skipped"); Assert.False(File.Exists(free)); } [Test] public void AFolderChronosDidNotMakeIsLeftAlone() { var folder = context.CreateTempDirectory("photos"); var photo = Write(folder, "IMG_0001.JPG", 1000, 0); Assert.Null(CacheStore.Trim(folder, 0)); Assert.True(File.Exists(photo)); Assert.Equal((0L, 0L, 0), CacheStore.Trim(Path.Combine(folder, "missing"), 0) is { } none ? (none.Before, none.Freed, none.Deleted) : (-1L, -1L, -1)); } }