merge: Titano Uploader (queue, watch folders, tray, resumable uploads)
This commit is contained in:
52 files changed
+6384
-1
No files matched your search
@@ -0,0 +1,18 @@
|
||||
using System.IO;
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Infrastructure;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class CoalescingWriterTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void KeepsTheNewestContent()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "uploader-queue.json");
|
||||
var writer = new CoalescingWriter();
|
||||
for (var i = 0; i < 50; i++) writer.Write(path, [(byte)i]);
|
||||
writer.Flush(TimeSpan.FromSeconds(10));
|
||||
Assert.SequenceEqual([(byte)49], File.ReadAllBytes(path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Infrastructure;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class CommandLineTests
|
||||
{
|
||||
[Test]
|
||||
public void PathsAndOptionsAreSeparated()
|
||||
{
|
||||
var c = CommandLine.Parse([@"E:\", "--tray", @"D:\Cam\IMG_0001.CR2"]);
|
||||
Assert.SequenceEqual([@"E:\", @"D:\Cam\IMG_0001.CR2"], c.Paths);
|
||||
Assert.True(c.StartInTray);
|
||||
Assert.Null(c.CaptureDirectory);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CaptureTakesAnOptionalDirectory()
|
||||
{
|
||||
Assert.Equal("out/shots", CommandLine.Parse(["--capture", "out/shots"]).CaptureDirectory);
|
||||
Assert.Equal("screenshots", CommandLine.Parse(["--capture"]).CaptureDirectory);
|
||||
Assert.Equal("screenshots", CommandLine.Parse(["--capture", "--tray"]).CaptureDirectory);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HandOverMessageRoundTrips()
|
||||
{
|
||||
string[] args = [@"E:\", @"\\garage-pi\cam\IMG 1.jpg"];
|
||||
Assert.SequenceEqual(args, SingleInstance.Decode(SingleInstance.Encode(args))!);
|
||||
Assert.Empty(SingleInstance.Decode(SingleInstance.Encode([]))!);
|
||||
Assert.Null(SingleInstance.Decode("hello\nE:\\"u8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.IO;
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Sources;
|
||||
using Titano.Uploader.Watching;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class ProcessedFileMemoryTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTime Written = new(2026, 9, 28, 16, 2, 11, DateTimeKind.Utc);
|
||||
|
||||
[Test]
|
||||
public void RemembersPathSizeAndWriteTime()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "roof");
|
||||
var photo = Path.Combine(root, "100CANON", "IMG_0413.CR2");
|
||||
var memory = new ProcessedFileMemory();
|
||||
Assert.False(memory.Contains(root, photo, 25_000_000, Written));
|
||||
|
||||
memory.Add(root, photo, 25_000_000, Written);
|
||||
Assert.True(memory.IsDirty);
|
||||
Assert.True(memory.Contains(root, photo, 25_000_000, Written));
|
||||
Assert.False(memory.Contains(root, photo, 25_000_001, Written), "a resized file is new");
|
||||
Assert.False(memory.Contains(root, photo, 25_000_000, Written.AddSeconds(1)), "a rewritten file is new");
|
||||
Assert.False(memory.Contains(Path.Combine(Path.GetTempPath(), "garden"), photo, 25_000_000, Written), "folders are separate");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PruneForgetsFilesNoLongerInTheFolder()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "roof");
|
||||
var kept = Path.Combine(root, "a.jpg");
|
||||
var gone = Path.Combine(root, "b.jpg");
|
||||
var memory = new ProcessedFileMemory();
|
||||
memory.Add(root, kept, 1, Written);
|
||||
memory.Add(root, gone, 2, Written);
|
||||
|
||||
memory.Prune(root, [kept]);
|
||||
Assert.True(memory.Contains(root, kept, 1, Written));
|
||||
Assert.False(memory.Contains(root, gone, 2, Written));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RoundTripKeepsFilesAndTheLastSession()
|
||||
{
|
||||
var dir = context.CreateTempDirectory();
|
||||
var root = Path.Combine(dir, "cam");
|
||||
var photo = Path.Combine(root, "IMG_0001.JPG");
|
||||
var memory = new ProcessedFileMemory();
|
||||
memory.Add(root, photo, 4_200_000, Written);
|
||||
memory.SetSession(root, new SessionContinuation("1a2b3c4d-20260928-180000", new DateTime(2026, 9, 28, 18, 40, 0)));
|
||||
|
||||
var path = Path.Combine(dir, "uploader-watch.json");
|
||||
File.WriteAllBytes(path, memory.Serialize());
|
||||
Assert.False(memory.IsDirty);
|
||||
var restored = ProcessedFileMemory.Load(path);
|
||||
|
||||
Assert.True(restored.Contains(root, photo, 4_200_000, Written));
|
||||
Assert.Equal(new SessionContinuation("1a2b3c4d-20260928-180000", new DateTime(2026, 9, 28, 18, 40, 0)), restored.GetSession(root));
|
||||
Assert.False(restored.IsDirty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RemovedFolderIsForgotten()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "roof");
|
||||
var memory = new ProcessedFileMemory();
|
||||
memory.Add(root, Path.Combine(root, "a.jpg"), 1, Written);
|
||||
memory.SetSession(root, new SessionContinuation("k", Written));
|
||||
memory.RemoveFolder(root);
|
||||
Assert.False(memory.Contains(root, Path.Combine(root, "a.jpg"), 1, Written));
|
||||
Assert.Null(memory.GetSession(root));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CorruptFileGivesAnEmptyMemory()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "uploader-watch.json");
|
||||
File.WriteAllText(path, "[1,2");
|
||||
var memory = ProcessedFileMemory.Load(path);
|
||||
Assert.False(memory.Contains("x", "x/a.jpg", 1, Written));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Server;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class ServerAddressTests
|
||||
{
|
||||
[Theory]
|
||||
[Case("nas.local:8443", "https://nas.local:8443/")]
|
||||
[Case("https://nas.local:8443", "https://nas.local:8443/")]
|
||||
[Case(" http://192.168.1.20:8080/titano ", "http://192.168.1.20:8080/titano/")]
|
||||
[Case("https://nas.local/?x=1#y", "https://nas.local/")]
|
||||
public void ServerAddressesBecomeApiBases(string typed, string expected)
|
||||
{
|
||||
Assert.True(ServerAddress.TryParse(typed, out var uri));
|
||||
Assert.Equal(expected, uri.ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("")]
|
||||
[Case(" ")]
|
||||
[Case("ftp://nas.local")]
|
||||
[Case("https://")]
|
||||
public void InvalidServerAddressesAreRejected(string typed) => Assert.False(ServerAddress.TryParse(typed, out _));
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.IO;
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Sources;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class SessionGrouperTests
|
||||
{
|
||||
private static readonly DateTime Evening = new(2026, 9, 28, 18, 0, 0);
|
||||
|
||||
[Test]
|
||||
public void SplitsWhereTheGapExceedsFortyFiveMinutes()
|
||||
{
|
||||
var times = Series(Evening, 10).Concat(Series(Evening.AddMinutes(9 + 46), 10)).ToList();
|
||||
var result = SessionGrouper.Assign(times, "abcd1234");
|
||||
Assert.Equal(2, result.Keys.Distinct().Count());
|
||||
Assert.Equal("abcd1234-20260928-180000", result.Keys[0]);
|
||||
Assert.Equal("abcd1234-20260928-185500", result.Keys[^1]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GapOfExactlyFortyFiveMinutesStaysInOneSession()
|
||||
{
|
||||
var times = Series(Evening, 10).Concat(Series(Evening.AddMinutes(9 + 45), 10)).ToList();
|
||||
Assert.Equal(1, SessionGrouper.Assign(times, "t").Keys.Distinct().Count());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestShotsAfterASessionMergeIntoIt()
|
||||
{
|
||||
var times = Series(Evening, 20).Concat(Series(Evening.AddHours(3), 3)).ToList();
|
||||
var result = SessionGrouper.Assign(times, "t");
|
||||
Assert.Equal(1, result.Keys.Distinct().Count());
|
||||
Assert.Equal(Evening.AddHours(3).AddMinutes(2), result.Last!.LastCapture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LeadingTestShotsJoinTheFollowingSession()
|
||||
{
|
||||
var times = Series(Evening, 3).Concat(Series(Evening.AddHours(2), 30)).ToList();
|
||||
var result = SessionGrouper.Assign(times, "t");
|
||||
Assert.Equal(1, result.Keys.Distinct().Count());
|
||||
Assert.Equal("t-20260928-180000", result.Keys[0]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void KeysFollowTheInputOrder()
|
||||
{
|
||||
var first = Series(Evening, 10);
|
||||
var second = Series(Evening.AddHours(5), 10);
|
||||
var shuffled = new List<DateTime> { second[3], first[7], second[0], first[0] };
|
||||
shuffled.AddRange(first.Skip(1).Take(6));
|
||||
shuffled.AddRange(second.Skip(4));
|
||||
var result = SessionGrouper.Assign(shuffled, "t");
|
||||
Assert.Equal("t-20260928-230000", result.Keys[0]);
|
||||
Assert.Equal("t-20260928-180000", result.Keys[1]);
|
||||
Assert.Equal(result.Keys[0], result.Keys[2]);
|
||||
Assert.Equal(result.Keys[1], result.Keys[3]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NewFramesWithinTheGapContinueThePreviousSession()
|
||||
{
|
||||
var previous = new SessionContinuation("t-20260928-180000", Evening.AddMinutes(30));
|
||||
var result = SessionGrouper.Assign(Series(Evening.AddMinutes(40), 2), "t", previous);
|
||||
Assert.SequenceEqual(["t-20260928-180000", "t-20260928-180000"], result.Keys);
|
||||
Assert.Equal(Evening.AddMinutes(41), result.Last!.LastCapture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NewFramesAfterTheGapStartANewSession()
|
||||
{
|
||||
var previous = new SessionContinuation("t-20260928-180000", Evening.AddMinutes(30));
|
||||
var result = SessionGrouper.Assign(Series(Evening.AddHours(2), 10), "t", previous);
|
||||
Assert.Equal("t-20260928-200000", result.Keys[0]);
|
||||
Assert.Equal("t-20260928-200000", result.Last!.Key);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyInputKeepsThePreviousSession()
|
||||
{
|
||||
var previous = new SessionContinuation("k", Evening);
|
||||
var result = SessionGrouper.Assign([], "t", previous);
|
||||
Assert.Empty(result.Keys);
|
||||
Assert.Same(previous, result.Last);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SourceTagIsStableShortAndPerFolder()
|
||||
{
|
||||
var a = SessionGrouper.SourceTag(Path.Combine(Path.GetTempPath(), "cam", "roof"));
|
||||
Assert.Equal(8, a.Length);
|
||||
Assert.True(a.All(Uri.IsHexDigit));
|
||||
Assert.Equal(a, SessionGrouper.SourceTag(Path.Combine(Path.GetTempPath(), "cam", "roof") + Path.DirectorySeparatorChar));
|
||||
Assert.NotEqual(a, SessionGrouper.SourceTag(Path.Combine(Path.GetTempPath(), "cam", "garden")));
|
||||
}
|
||||
|
||||
private static List<DateTime> Series(DateTime start, int count) => [.. Enumerable.Range(0, count).Select(i => start.AddMinutes(i))];
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
/// <summary>Runs async test code on one thread, as the UI dispatcher does for the upload engine.</summary>
|
||||
internal sealed class SingleThreadedContext : SynchronizationContext
|
||||
{
|
||||
private readonly BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = [];
|
||||
|
||||
public override void Post(SendOrPostCallback d, object? state)
|
||||
{
|
||||
try
|
||||
{
|
||||
_queue.Add((d, state));
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Late progress reports after the test body finished are dropped.
|
||||
}
|
||||
}
|
||||
|
||||
public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException();
|
||||
|
||||
public static void Run(Func<Task> body)
|
||||
{
|
||||
var previous = Current;
|
||||
var context = new SingleThreadedContext();
|
||||
SetSynchronizationContext(context);
|
||||
try
|
||||
{
|
||||
var task = body();
|
||||
task.ContinueWith(_ => context._queue.CompleteAdding(), TaskScheduler.Default);
|
||||
foreach (var (callback, state) in context._queue.GetConsumingEnumerable()) callback(state);
|
||||
task.GetAwaiter().GetResult();
|
||||
}
|
||||
finally
|
||||
{
|
||||
SetSynchronizationContext(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Watching;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class StableFileTrackerTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 9, 28, 16, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
[Test]
|
||||
public void FileIsStableAfterTwoIdenticalChecks()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
var photo = new FileObservation("a.cr2", 25_000_000, T0);
|
||||
Assert.Empty(tracker.Check([photo]));
|
||||
Assert.Equal(1, tracker.PendingCount);
|
||||
Assert.SequenceEqual([photo], tracker.Check([photo]));
|
||||
Assert.Equal(0, tracker.PendingCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GrowingFileWaitsUntilItStopsGrowing()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
Assert.Empty(tracker.Check([new("a.cr2", 1_000, T0)]));
|
||||
Assert.Empty(tracker.Check([new("a.cr2", 9_000, T0.AddSeconds(1))]));
|
||||
Assert.Empty(tracker.Check([new("a.cr2", 25_000, T0.AddSeconds(2))]));
|
||||
Assert.Count(1, tracker.Check([new("a.cr2", 25_000, T0.AddSeconds(2))]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TouchedFileWithSameSizeRestartsTheCount()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
Assert.Empty(tracker.Check([new("a.jpg", 500, T0)]));
|
||||
Assert.Empty(tracker.Check([new("a.jpg", 500, T0.AddSeconds(5))]));
|
||||
Assert.Count(1, tracker.Check([new("a.jpg", 500, T0.AddSeconds(5))]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FileMissingFromAScanIsForgotten()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
var photo = new FileObservation("a.jpg", 500, T0);
|
||||
Assert.Empty(tracker.Check([photo]));
|
||||
Assert.Empty(tracker.Check([]));
|
||||
Assert.Empty(tracker.Check([photo]));
|
||||
Assert.Count(1, tracker.Check([photo]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FilesProgressIndependently()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
var done = new FileObservation("done.jpg", 500, T0);
|
||||
Assert.Empty(tracker.Check([done, new("growing.jpg", 10, T0)]));
|
||||
var stable = tracker.Check([done, new("growing.jpg", 20, T0.AddSeconds(1))]);
|
||||
Assert.SequenceEqual([done], stable);
|
||||
Assert.Equal(1, tracker.PendingCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SingleObservationsUseTheSameRule()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
var photo = new FileObservation("a.nef", 42, T0);
|
||||
Assert.False(tracker.Observe(photo));
|
||||
Assert.True(tracker.Observe(photo));
|
||||
Assert.False(tracker.Observe(photo));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Infrastructure;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class TokenProtectorTests
|
||||
{
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TokenRoundTripsThroughDpapiWithoutPlainText()
|
||||
{
|
||||
const string token = "ttn_4f9a1c2e7b";
|
||||
var blob = TokenProtector.Protect(token);
|
||||
Assert.False(blob.Contains(token, StringComparison.Ordinal));
|
||||
Assert.Equal(token, TokenProtector.Unprotect(blob));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void DamagedBlobsGiveNoToken()
|
||||
{
|
||||
var blob = Convert.FromBase64String(TokenProtector.Protect("secret"));
|
||||
blob[^1] ^= 0xFF;
|
||||
Assert.Null(TokenProtector.Unprotect(Convert.ToBase64String(blob)));
|
||||
Assert.Null(TokenProtector.Unprotect("not base64!"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Uploads;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class UploadEngineTests(TestContext context)
|
||||
{
|
||||
private readonly ManualTime _time = new();
|
||||
|
||||
[Test]
|
||||
public void VerifiedUploadsKeepTheSourceByDefault() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 2);
|
||||
var transport = new FakeTransport();
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
var confirmed = new List<UploadItem>();
|
||||
engine.ItemConfirmed += (_, item) => confirmed.Add(item);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => queue.Items.All(i => i.IsDone));
|
||||
|
||||
Assert.True(queue.Items.All(i => i.State == UploadItemState.Verified && i.FrameId is not null));
|
||||
Assert.True(queue.Items.All(i => File.Exists(i.Path)));
|
||||
// Two workers hash in parallel, so calls arrive in either order.
|
||||
foreach (var item in queue.Items) Assert.Equal(Sha256(item.Path), transport.Calls.Single(c => c.Path == item.Path).Sha256);
|
||||
Assert.Equal(2, confirmed.Count);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void DeleteAfterUploadRemovesOnlyConfirmedUnchangedFiles() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 3);
|
||||
var (verified, existing, changed) = (queue.Items[0], queue.Items[1], queue.Items[2]);
|
||||
var transport = new FakeTransport
|
||||
{
|
||||
Respond = item =>
|
||||
{
|
||||
if (item == existing) return (UploadOutcome.AlreadyOnServer, null);
|
||||
// Written to after it was hashed: the bytes on disk are no longer the verified ones.
|
||||
if (item == changed) File.AppendAllText(item.Path, "more");
|
||||
return (UploadOutcome.Verified, Guid.CreateVersion7());
|
||||
},
|
||||
};
|
||||
using var engine = new UploadEngine(queue, transport, () => true, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => queue.Items.All(i => i.IsDone));
|
||||
|
||||
Assert.Equal(UploadItemState.Skipped, existing.State);
|
||||
Assert.False(File.Exists(verified.Path));
|
||||
Assert.False(File.Exists(existing.Path));
|
||||
Assert.True(File.Exists(changed.Path), "a file changed after verification is kept");
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void RejectedFileIsRetriedAfterThirtySeconds() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 1);
|
||||
var item = queue.Items[0];
|
||||
var attempts = 0;
|
||||
var transport = new FakeTransport
|
||||
{
|
||||
Respond = _ => ++attempts == 1
|
||||
? throw new TitanoApiException(HttpStatusCode.UnprocessableEntity, new ApiError("hash_mismatch", "Hash mismatch"))
|
||||
: (UploadOutcome.Verified, Guid.CreateVersion7()),
|
||||
};
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => item.State == UploadItemState.Failed);
|
||||
Assert.Equal(UploadFailure.ServerRejected, item.Failure);
|
||||
Assert.Equal("Hash mismatch", item.FailureDetail);
|
||||
Assert.Equal(_time.UtcNow + UploadQueue.RetryDelay, item.NextRetryUtc);
|
||||
|
||||
_time.Advance(TimeSpan.FromSeconds(29));
|
||||
engine.Pump();
|
||||
Assert.Equal(UploadItemState.Failed, item.State);
|
||||
|
||||
_time.Advance(TimeSpan.FromSeconds(1));
|
||||
engine.Pump();
|
||||
await Until(() => item.IsDone);
|
||||
Assert.Equal(1, item.Retries);
|
||||
Assert.Equal(UploadFailure.None, item.Failure);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void UnreachableServerRequeuesWithoutSpendingARetry() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 1);
|
||||
var item = queue.Items[0];
|
||||
var transport = new FakeTransport();
|
||||
transport.Respond = _ =>
|
||||
{
|
||||
transport.SetReady(false);
|
||||
throw new ServerUnavailableException(ServerProblem.Unreachable);
|
||||
};
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => item.State == UploadItemState.Queued && transport.Calls.Count == 1);
|
||||
Assert.Equal(0, item.Retries);
|
||||
Assert.NotNull(item.Sha256);
|
||||
Assert.Equal(EngineStatus.WaitingForServer, engine.Status);
|
||||
|
||||
transport.Respond = _ => (UploadOutcome.Verified, Guid.CreateVersion7());
|
||||
transport.SetReady(true);
|
||||
await Until(() => item.IsDone);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void NewSequenceIsCreatedOnceForTheBatch() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.NewSequence, 3);
|
||||
var transport = new FakeTransport();
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => queue.Items.All(i => i.IsDone));
|
||||
|
||||
Assert.Equal(1, transport.SequencesCreated);
|
||||
Assert.True(transport.Calls.All(c => c.SequenceId == FakeTransport.CreatedSequence));
|
||||
Assert.Equal(FakeTransport.CreatedSequence, queue.Batches.Single().SequenceId);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void AtMostTwoFilesAreInFlightAndPauseRequeuesThem() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 4);
|
||||
var transport = new FakeTransport { Block = true };
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => queue.Items.Count(i => i.State == UploadItemState.Uploading) == UploadEngine.Parallelism);
|
||||
Assert.Equal(UploadEngine.Parallelism, queue.Items.Count(i => i.IsActive));
|
||||
|
||||
engine.Pause();
|
||||
await Until(() => queue.Items.All(i => i.State == UploadItemState.Queued));
|
||||
Assert.Equal(EngineStatus.Paused, engine.Status);
|
||||
|
||||
transport.Block = false;
|
||||
engine.Resume();
|
||||
await Until(() => queue.Items.All(i => i.IsDone));
|
||||
Assert.False(queue.IsPaused);
|
||||
});
|
||||
|
||||
private UploadQueue Queue(UploadTargetMode mode, int count)
|
||||
{
|
||||
var dir = context.CreateTempDirectory();
|
||||
var queue = new UploadQueue();
|
||||
var entries = Enumerable.Range(0, count).Select(i =>
|
||||
{
|
||||
var path = Path.Combine(dir, $"IMG_{i:0000}.JPG");
|
||||
File.WriteAllBytes(path, RandomNumberGenerator.GetBytes(4096 + i));
|
||||
var info = new FileInfo(path);
|
||||
return new QueueEntry(path, info.Length, info.LastWriteTimeUtc, info.LastWriteTime, "k", null);
|
||||
}).ToList();
|
||||
queue.Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = mode, Title = mode == UploadTargetMode.NewSequence ? "Roof" : null }, entries);
|
||||
return queue;
|
||||
}
|
||||
|
||||
private static string Sha256(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
|
||||
|
||||
private static async Task Until(Func<bool> condition)
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
while (!condition())
|
||||
{
|
||||
if (clock.Elapsed > TimeSpan.FromSeconds(15)) throw new TimeoutException("Condition not reached");
|
||||
await Task.Delay(5);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ManualTime : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = new(2026, 9, 28, 18, 0, 0, TimeSpan.Zero);
|
||||
|
||||
public DateTime UtcNow => _now.UtcDateTime;
|
||||
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
}
|
||||
|
||||
private sealed class FakeTransport : IUploadTransport
|
||||
{
|
||||
public static readonly Guid CreatedSequence = Guid.CreateVersion7();
|
||||
|
||||
public event EventHandler? ReadyChanged;
|
||||
|
||||
public bool IsReady { get; private set; } = true;
|
||||
public bool Block { get; set; }
|
||||
public int SequencesCreated { get; private set; }
|
||||
public List<(string Path, Guid? SequenceId, string Sha256)> Calls { get; } = [];
|
||||
public Func<UploadItem, (UploadOutcome, Guid?)> Respond { get; set; } = _ => (UploadOutcome.Verified, Guid.CreateVersion7());
|
||||
|
||||
public void SetReady(bool ready)
|
||||
{
|
||||
IsReady = ready;
|
||||
ReadyChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public async Task<(UploadOutcome Outcome, Guid? FrameId)> UploadAsync(UploadItem item, Guid? sequenceId, string sha256, IProgress<UploadProgress> progress, CancellationToken ct)
|
||||
{
|
||||
Calls.Add((item.Path, sequenceId, sha256));
|
||||
progress.Report(new UploadProgress(0, item.Size));
|
||||
while (Block) await Task.Delay(5, ct);
|
||||
await Task.Yield();
|
||||
progress.Report(new UploadProgress(item.Size, item.Size));
|
||||
return Respond(item);
|
||||
}
|
||||
|
||||
public Task<Guid> CreateSequenceAsync(string? title, CancellationToken ct)
|
||||
{
|
||||
SequencesCreated++;
|
||||
return Task.FromResult(CreatedSequence);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.IO;
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Uploads;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class UploadQueueTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTime Now = new(2026, 9, 28, 18, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
[Test]
|
||||
public void PersistenceRoundTripKeepsBatchesItemsAndStates()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
var sessions = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
|
||||
var created = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.NewSequence, Title = "Harbour sunset", SequenceId = Guid.CreateVersion7() };
|
||||
queue.Add(sessions, [Entry("a.cr2", "k1", @"D:\Cam\Roof"), Entry("b.cr2", "k1", null)]);
|
||||
queue.Add(created, [Entry("c.jpg", null, null)]);
|
||||
var verified = queue.Items[0];
|
||||
verified.State = UploadItemState.Verified;
|
||||
verified.Sha256 = new string('a', 64);
|
||||
verified.FrameId = Guid.CreateVersion7();
|
||||
var failed = queue.Items[1];
|
||||
failed.Retries = 2;
|
||||
queue.Fail(failed, UploadFailure.ServerRejected, "quota exceeded", Now);
|
||||
queue.IsPaused = true;
|
||||
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "uploader-queue.json");
|
||||
File.WriteAllBytes(path, QueueStore.Serialize(queue));
|
||||
var restored = new UploadQueue();
|
||||
QueueStore.Load(path, restored);
|
||||
|
||||
Assert.True(restored.IsPaused);
|
||||
Assert.Equal(2, restored.Batches.Count);
|
||||
Assert.Equal("Harbour sunset", restored.GetBatch(created.Id)!.Title);
|
||||
Assert.Equal(created.SequenceId, restored.GetBatch(created.Id)!.SequenceId);
|
||||
Assert.Equal(3, restored.Items.Count);
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var (a, b) = (queue.Items[i], restored.Items[i]);
|
||||
Assert.Equal(a.Id, b.Id);
|
||||
Assert.Equal(a.BatchId, b.BatchId);
|
||||
Assert.Equal(a.Path, b.Path);
|
||||
Assert.Equal(a.Size, b.Size);
|
||||
Assert.Equal(a.ModifiedUtc, b.ModifiedUtc);
|
||||
Assert.Equal(a.CapturedAt, b.CapturedAt);
|
||||
Assert.Equal(a.SessionKey, b.SessionKey);
|
||||
Assert.Equal(a.WatchRoot, b.WatchRoot);
|
||||
Assert.Equal(a.State, b.State);
|
||||
}
|
||||
Assert.Equal(verified.Sha256, restored.Items[0].Sha256);
|
||||
Assert.Equal(verified.FrameId, restored.Items[0].FrameId);
|
||||
Assert.Equal(UploadFailure.ServerRejected, restored.Items[1].Failure);
|
||||
Assert.Equal("quota exceeded", restored.Items[1].FailureDetail);
|
||||
Assert.Equal(2, restored.Items[1].Retries);
|
||||
Assert.Equal(Now + UploadQueue.RetryDelay, restored.Items[1].NextRetryUtc);
|
||||
Assert.True(restored.ContainsPath("c.jpg"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InterruptedTransfersResumeAsQueued()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
queue.Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions }, [Entry("a.cr2", null, null), Entry("b.cr2", null, null)]);
|
||||
queue.Items[0].State = UploadItemState.Uploading;
|
||||
queue.Items[0].Sha256 = new string('b', 64);
|
||||
queue.Items[1].State = UploadItemState.Hashing;
|
||||
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "q.json");
|
||||
File.WriteAllBytes(path, QueueStore.Serialize(queue));
|
||||
var restored = new UploadQueue();
|
||||
QueueStore.Load(path, restored);
|
||||
|
||||
Assert.Equal(UploadItemState.Queued, restored.Items[0].State);
|
||||
Assert.Equal(UploadItemState.Queued, restored.Items[1].State);
|
||||
// The known hash is kept: the server resumes from the chunks it already holds.
|
||||
Assert.Equal(new string('b', 64), restored.Items[0].Sha256);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CorruptOrMissingFileGivesAnEmptyQueue()
|
||||
{
|
||||
var dir = context.CreateTempDirectory();
|
||||
var corrupt = Path.Combine(dir, "q.json");
|
||||
File.WriteAllText(corrupt, "{ not json");
|
||||
var queue = new UploadQueue();
|
||||
QueueStore.Load(corrupt, queue);
|
||||
QueueStore.Load(Path.Combine(dir, "missing.json"), queue);
|
||||
Assert.Empty(queue.Items);
|
||||
Assert.False(queue.IsPaused);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AddingSkipsPathsAlreadyQueued()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
|
||||
Assert.Equal(2, queue.Add(batch, [Entry("a.jpg", null, null), Entry("b.jpg", null, null)]));
|
||||
Assert.Equal(1, queue.Add(batch, [Entry("b.jpg", null, null), Entry("c.jpg", null, null)]));
|
||||
Assert.Equal(3, queue.Items.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedItemsComeBackAfterTheDelayUntilRetriesRunOut()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
queue.Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions }, [Entry("a.jpg", null, null)]);
|
||||
var item = queue.Items[0];
|
||||
item.State = UploadItemState.Hashing;
|
||||
queue.Fail(item, UploadFailure.FileUnreadable, null, Now);
|
||||
Assert.Null(queue.NextReady(Now.AddSeconds(29)));
|
||||
Assert.Same(item, queue.NextReady(Now + UploadQueue.RetryDelay));
|
||||
Assert.True(queue.HasPending);
|
||||
|
||||
item.Retries = UploadQueue.MaxRetries;
|
||||
queue.Fail(item, UploadFailure.FileUnreadable, null, Now);
|
||||
Assert.Null(item.NextRetryUtc);
|
||||
Assert.Null(queue.NextReady(Now.AddDays(1)));
|
||||
Assert.False(queue.HasPending);
|
||||
|
||||
queue.Requeue(item);
|
||||
Assert.Equal(0, item.Retries);
|
||||
Assert.Same(item, queue.NextReady(Now));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RemovingCompletedItemsKeepsTheRest()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
|
||||
queue.Add(batch, [Entry("a.jpg", null, null), Entry("b.jpg", null, null), Entry("c.jpg", null, null)]);
|
||||
queue.Items[0].State = UploadItemState.Verified;
|
||||
queue.Items[2].State = UploadItemState.Skipped;
|
||||
queue.RemoveCompleted();
|
||||
Assert.Equal(1, queue.Items.Count);
|
||||
Assert.False(queue.ContainsPath("a.jpg"));
|
||||
Assert.True(queue.ContainsPath("b.jpg"));
|
||||
Assert.Equal(1, queue.Batches.Count);
|
||||
}
|
||||
|
||||
private static QueueEntry Entry(string name, string? session, string? watchRoot) =>
|
||||
new(name, 1_000 + name.Length, new DateTime(2026, 9, 28, 16, 2, 11, DateTimeKind.Utc), new DateTime(2026, 9, 28, 18, 2, 11), session, watchRoot);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System.Globalization;
|
||||
using Titano.Testing;
|
||||
using Titano.Uploader.Text;
|
||||
using Titano.Uploader.Uploads;
|
||||
|
||||
namespace Titano.App.Tests.Uploader;
|
||||
|
||||
public sealed class UploaderTextTests
|
||||
{
|
||||
private static readonly CultureInfo En = CultureInfo.GetCultureInfo("en");
|
||||
private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it");
|
||||
|
||||
private static readonly QueueSummary Mockup = new(4_812, 96_200_000_000, 2_214, 2_201, 0, 0, 44_000_000_000, "2026-09-28_18-02-11_0413.CR2")
|
||||
{
|
||||
RemainingBytes = 93_480_000_000,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void QueueLineMatchesTheMockup()
|
||||
{
|
||||
var left = RateMeter.TimeLeft(Mockup.RemainingBytes, 38_000_000);
|
||||
Assert.Equal("4,812 files · 96.2 GB · 38 MB/s · 41 min left", UploaderText.QueueLine(Mockup, QueueActivity.Running, 38_000_000, left, En));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void QueueLineFollowsTheCulture()
|
||||
{
|
||||
Assert.Equal("4.812 file · 96,2 GB · 38 MB/s · mancano 41 min", UploaderText.QueueLine(Mockup, QueueActivity.Running, 38_000_000, TimeSpan.FromMinutes(41), It));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void QueueLineNamesTheActivityWhenNotRunning()
|
||||
{
|
||||
Assert.Equal("4,812 files · 96.2 GB · Paused", UploaderText.QueueLine(Mockup, QueueActivity.Paused, 0, null, En));
|
||||
Assert.Equal("4,812 files · 96.2 GB · Waiting for server", UploaderText.QueueLine(Mockup, QueueActivity.WaitingForServer, 0, null, En));
|
||||
Assert.Equal("1 file · 25 MB · Done", UploaderText.QueueLine(Mockup with { Files = 1, Bytes = 25_000_000 }, QueueActivity.Done, 0, null, En));
|
||||
Assert.Equal("Nothing queued", UploaderText.QueueLine(default, QueueActivity.Idle, 0, null, En));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RunningLineOmitsRateAndTimeUntilKnown()
|
||||
{
|
||||
Assert.Equal("4,812 files · 96.2 GB", UploaderText.QueueLine(Mockup, QueueActivity.Running, 0, null, En));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProgressLineMatchesTheMockup()
|
||||
{
|
||||
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 0 retries", UploaderText.ProgressLine(Mockup, En));
|
||||
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 1 retry · 3 failed", UploaderText.ProgressLine(Mockup with { Retries = 1, Failed = 3 }, En));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(0.0, "0 B/s")]
|
||||
[Case(950_000.0, "950 KB/s")]
|
||||
[Case(4_240_000.0, "4.2 MB/s")]
|
||||
[Case(38_400_000.0, "38 MB/s")]
|
||||
[Case(1_260_000_000.0, "1.3 GB/s")]
|
||||
public void RatesUseDecimalUnits(double bytesPerSecond, string expected) =>
|
||||
Assert.Equal(expected, UploaderText.Rate(bytesPerSecond, En));
|
||||
|
||||
[Theory]
|
||||
[Case(40.0, "40 s")]
|
||||
[Case(299.0, "5 min")]
|
||||
[Case(3_590.0, "1 h 00 m")]
|
||||
[Case(7_500.0, "2 h 05 m")]
|
||||
[Case(93_600.0, "1 d 2 h")]
|
||||
public void DurationsAreCompact(double seconds, string expected) =>
|
||||
Assert.Equal(expected, UploaderText.Duration(TimeSpan.FromSeconds(seconds), En));
|
||||
|
||||
[Theory]
|
||||
[Case(999L, "999 B")]
|
||||
[Case(1_536L, "1.5 KB")]
|
||||
[Case(96_200_000_000L, "96.2 GB")]
|
||||
[Case(1_900_000_000_000L, "1.9 TB")]
|
||||
public void SizesUseDecimalUnits(long bytes, string expected) => Assert.Equal(expected, UploaderText.Bytes(bytes, En));
|
||||
|
||||
[Test]
|
||||
public void TimeLeftNeedsAUsableRate()
|
||||
{
|
||||
Assert.Equal(TimeSpan.FromMinutes(41), RateMeter.TimeLeft(93_480_000_000, 38_000_000));
|
||||
Assert.Equal(TimeSpan.Zero, RateMeter.TimeLeft(0, 0));
|
||||
Assert.Null(RateMeter.TimeLeft(1_000, 10));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RateMeterAveragesTheWindowAndDecaysWhenStalled()
|
||||
{
|
||||
var meter = new RateMeter(TimeSpan.FromSeconds(10));
|
||||
Assert.Equal(0.0, meter.BytesPerSecond(TimeSpan.Zero));
|
||||
for (var s = 0; s <= 20; s++) meter.Add(4_000_000, TimeSpan.FromSeconds(s));
|
||||
Assert.Approximately(4_000_000, meter.BytesPerSecond(TimeSpan.FromSeconds(20)), 1);
|
||||
// Nothing sent for 20 s: the window holds no transfer any more.
|
||||
Assert.Equal(0.0, meter.BytesPerSecond(TimeSpan.FromSeconds(40)));
|
||||
meter.Reset();
|
||||
Assert.Equal(0.0, meter.BytesPerSecond(TimeSpan.FromSeconds(40)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SummaryCountsStatesAndBytes()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
queue.Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions },
|
||||
Enumerable.Range(0, 5).Select(i => new QueueEntry($"{i}.jpg", 100, DateTime.UtcNow, null, null, null)));
|
||||
queue.Items[0].State = UploadItemState.Verified;
|
||||
queue.Items[1].State = UploadItemState.Skipped;
|
||||
queue.Items[2].State = UploadItemState.Uploading;
|
||||
queue.Items[2].BytesSent = 40;
|
||||
queue.Items[3].State = UploadItemState.Failed;
|
||||
queue.Items[3].Retries = 1;
|
||||
|
||||
var s = QueueSummary.From(queue.Items);
|
||||
Assert.Equal(5, s.Files);
|
||||
Assert.Equal(500L, s.Bytes);
|
||||
Assert.Equal(2, s.Sent);
|
||||
Assert.Equal(2, s.Verified);
|
||||
Assert.Equal(1, s.Failed);
|
||||
Assert.Equal(1, s.Retries);
|
||||
Assert.Equal(240L, s.DoneBytes);
|
||||
Assert.Equal(160L, s.RemainingBytes);
|
||||
Assert.Equal("2.jpg", s.CurrentFile);
|
||||
Assert.Approximately(0.48, s.Progress, 1e-9);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user