merge: deterministic sync tests and a current-log download that survives new lines

This commit is contained in:
Claude committed 2026-10-06 22:22:47 +00:00
commit 01f301f970
5 files changed
+175 -27

No files matched your search

+4 -3
View File
@@ -29,10 +29,11 @@ public static class AdminEndpoints
ProtocolJson.Default.ListLogFileDto));
logs.MapGet("/files/{name}", (HttpContext context, string name, ServerOptions options) =>
{
// Only names of existing log files are served: the name never becomes part of a path.
// Only names of existing log files are served: the name never becomes part of a path. The current log keeps
// growing while it is sent, so the response holds the bytes it had when listed, as its Content-Length says.
if (LogFiles(options).FirstOrDefault(f => f.Name == name) is not { } file) return ApiErrors.NotFound(context, "log");
context.Response.Headers.CacheControl = "no-store";
return Results.File(file.FullName, "text/plain; charset=utf-8", file.Name, file.LastWriteTimeUtc, enableRangeProcessing: true);
return FileResponses.Serve(context, file, 0, file.Length, "text/plain; charset=utf-8", "no-store", downloadName: file.Name)
?? ApiErrors.NotFound(context, "log");
});
}
+75 -16
View File
@@ -9,6 +9,9 @@ namespace Titano.Data.Tests.Sync;
[Category("sync")]
public sealed class SyncAgentTests(TestContext context)
{
/// <summary>How long any wait may take on a loaded runner; every wait ends as soon as what it waits for happened.</summary>
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(30);
/// <summary>Full comparisons only at start, so anything later comes from events or explicit requests.</summary>
private static readonly SyncAgentOptions EventsOnly = new()
{
@@ -31,14 +34,20 @@ public sealed class SyncAgentTests(TestContext context)
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
var first = agent.Snapshot!;
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
await WaitAsync(async () => SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
await ComparedAfterAsync(f, () =>
{
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
}, "the comparison of the server's edit");
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
"the server's edit reached this PC");
var created = f.Remote.Add("New on the server", f.NewPhotos(1));
f.Remote.Publish(new SequenceChangedEvent(created.Id, "created", 1, 1));
await WaitAsync(async () => (await f.Sync.ListAsync(f.Server, f.Ct)).Any(e => e.Title == "New on the server"), "a sequence created on the server");
await ComparedAfterAsync(f, () =>
{
var created = f.Remote.Add("New on the server", f.NewPhotos(1));
f.Remote.Publish(new SequenceChangedEvent(created.Id, "created", 1, 1));
}, "the comparison of a sequence created on the server");
Assert.Contains(await f.Sync.ListAsync(f.Server, f.Ct), e => e.Title == "New on the server");
Assert.Same(first, agent.Snapshot);
}
@@ -49,11 +58,17 @@ public sealed class SyncAgentTests(TestContext context)
f.Remote.Add("Harbour", f.NewPhotos(1));
f.Remote.FailingListings = 3;
var changes = 0;
var compared = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
agent.Changed += () => Interlocked.Increment(ref changes);
// The agent stores the snapshot, then clears the last error, then raises Changed: only Changed sees both.
agent.Changed += () =>
{
Interlocked.Increment(ref changes);
if (agent.Snapshot is not null) compared.TrySetResult();
};
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "a comparison after the failures");
await SignalAsync(compared.Task, "a comparison after the failures");
Assert.Null(agent.LastError);
Assert.Equal(0, f.Remote.FailingListings);
Assert.GreaterOrEqual(changes, 4);
@@ -72,13 +87,19 @@ public sealed class SyncAgentTests(TestContext context)
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
f.Remote.TimeoutOnce = remote.Id;
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
await WaitAsync(async () => (await f.EntryAsync("Harbour")).Link!.Error is not null, "the timeout recorded on the sequence");
await ComparedAfterAsync(f, () =>
{
f.Remote.TimeoutOnce = remote.Id;
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
}, "the comparison that timed out");
Assert.NotNull((await f.EntryAsync("Harbour")).Link!.Error);
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
await WaitAsync(async () => SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
await ComparedAfterAsync(f, () =>
{
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
}, "the comparison of a later event");
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
"a later event still reaches this PC");
Assert.Null((await f.EntryAsync("Harbour")).Link!.Error);
}
@@ -105,7 +126,10 @@ public sealed class SyncAgentTests(TestContext context)
keep = true;
await agent.RefreshAsync(f.Ct);
await WaitAsync(() => f.Sync.OpenRemote(f.Server, opened.Id) is { CachedCount: 3 }, "the stale cache brought up to date");
// The download writes the cache, then the link, and only then ends: until it ends its row shows a transfer.
var refresh = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id);
await f.Archive.WaitForAsync(refresh.Id, JobState.Done);
Assert.Equal(3, Assert.NotNull(f.Sync.OpenRemote(f.Server, opened.Id)).CachedCount, "the stale cache brought up to date");
Assert.Null(f.Sync.OpenRemote(f.Server, never.Id));
var entries = await f.Sync.ListAsync(f.Server, f.Ct);
Assert.Equal(SyncStatus.ProxiesOnly, entries.Single(e => e.Title == "Construction cam").Status);
@@ -138,11 +162,46 @@ public sealed class SyncAgentTests(TestContext context)
private static async Task<IReadOnlyList<Job>> DownloadsAsync(SyncFixture f) =>
(await f.Db.Jobs.ListAsync(null, JobKind.Download, 100, null, f.Ct)).Items;
/// <summary>
/// Runs <paramref name="cause"/> and returns once the comparison it starts has finished. The engine raises
/// <see cref="SyncService.Changed"/> after a comparison stored every link and state, the moment the Server screen
/// reloads; a poll could instead see the local copy updated before the link that goes with it is stored. No other
/// comparison may be running.
/// </summary>
private async Task ComparedAfterAsync(SyncFixture f, Action cause, string what)
{
// Continuations run on the pool, not inside the agent loop that raises Changed and that the test later stops.
var compared = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
Action<string> onChanged = _ => compared.TrySetResult();
f.Sync.Changed += onChanged;
try
{
cause();
await SignalAsync(compared.Task, what);
}
finally
{
f.Sync.Changed -= onChanged;
}
}
private async Task SignalAsync(Task signal, string what)
{
try
{
await signal.WaitAsync(Deadline, context.Cancellation);
}
catch (TimeoutException)
{
Assert.Fail("Timed out waiting for " + what);
}
}
private async Task WaitAsync(Func<bool> condition, string what) => await WaitAsync(() => Task.FromResult(condition()), what);
private async Task WaitAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(30);
var until = DateTime.UtcNow + Deadline;
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
@@ -1,7 +1,10 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Nodes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Titano.Protocol;
using Titano.Server.Hosting;
using Titano.Testing;
namespace Titano.Server.Tests.Api;
@@ -66,6 +69,45 @@ public sealed class AdminTests(TestContext context)
await traversal.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
[Test]
public async Task TheCurrentLogDownloadsWhileTheServerKeepsLogging()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = Microsoft.Extensions.Logging.LogLevel.Information);
var admin = await server.AdminAsync();
using var files = await admin.GetAsync("/api/v1/logs/files");
var name = (await files.ReadAsync(ProtocolJson.Default.ListLogFileDto)).First().Name;
// Jobs, uploads and sign-ins keep writing to the file an administrator downloads: a log of a few megabytes takes
// a while to send, and a line lands about every millisecond meanwhile. Only to the file and never in a tight loop:
// engine code of every test server in this process logs through the last one started, so this server's console
// and file lock are shared with the tests running alongside.
var logger = server.Services.GetServices<ILoggerProvider>().OfType<FileLoggerProvider>().Single().CreateLogger("Titano.Server.Tests");
var block = new string('x', 64 * 1024);
for (var i = 0; i < 32; i++) logger.LogInformation("{Block}", block);
using var stop = new CancellationTokenSource();
var logging = Task.Factory.StartNew(() =>
{
while (!stop.IsCancellationRequested)
{
logger.LogInformation("Busy");
Thread.Sleep(1);
}
}, TaskCreationOptions.LongRunning);
try
{
for (var i = 0; i < 5; i++)
{
using var download = await admin.GetAsync($"/api/v1/logs/files/{name}");
await download.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(download.Content.Headers.ContentLength, (await download.Content.ReadAsByteArrayAsync()).LongLength);
}
}
finally
{
await stop.CancelAsync();
await logging;
}
}
[Test]
public async Task ArchiveSettingsValidateTemplatesAndJobsNeedHandlers()
{
@@ -101,18 +101,20 @@ public sealed class RenderNodeClientTests(TestContext context)
var job = await CreateRenderAsync(server, editor, sequenceId, Mjpeg with { Batch = ["gif-preview"] });
var gif = (await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Render)).Items.Single(j => j.Id != job.Id);
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
var claims = new CountClaims(new SocketsHttpHandler());
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc", claims) { Token = token };
var cache = context.CreateTempDirectory("node");
// Claims only when started and after each job: between them only heartbeats reach the server.
var node = Node(client, cache, poll: TimeSpan.FromMinutes(5), heartbeat: TimeSpan.FromMilliseconds(100));
node.Start();
await JobApiTests.WaitForAsync(editor, job.Id, "done");
await JobApiTests.WaitForAsync(editor, gif.Id, "done");
// Past the claim that found the queue empty, only heartbeats move the node's last sign of life.
await Task.Delay(300);
// Past the claim that found the queue empty (the server touched the node before answering it), only heartbeats
// move the node's last sign of life.
await UntilAsync(() => Task.FromResult(claims.Answered >= 3), "the claim that found the queue empty");
var beat = (await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat;
await Task.Delay(400);
Assert.Greater((await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat.Ticks, beat.Ticks);
await UntilAsync(async () => (await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat > beat, "a heartbeat");
Assert.Equal(3, claims.Answered, "no claim since the queue was empty");
await node.DisposeAsync();
Assert.True(node.Completion.IsCompleted, "stopped");
@@ -312,6 +314,21 @@ public sealed class RenderNodeClientTests(TestContext context)
}
}
/// <summary>Counts the node's claims the server answered.</summary>
private sealed class CountClaims(HttpMessageHandler inner) : DelegatingHandler(inner)
{
private int _answered;
public int Answered => Volatile.Read(ref _answered);
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (request.RequestUri!.AbsolutePath.EndsWith("/claim", StringComparison.Ordinal)) Interlocked.Increment(ref _answered);
return response;
}
}
/// <summary>The first <c>cut</c> bytes, then a reset connection.</summary>
private sealed class CutStream(byte[] data, int cut) : MemoryStream(data, 0, cut)
{
@@ -325,6 +342,16 @@ public sealed class RenderNodeClientTests(TestContext context)
private static int Check(int read) => read > 0 ? read : throw new IOException("Connection reset by peer");
}
private static async Task UntilAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(30);
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(25);
}
}
private static async Task<JobDto> CreateRenderAsync(TestServer server, HttpClient editor, Guid sequenceId, ExportSettings? export = null)
{
var sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
@@ -22,6 +22,9 @@ public sealed class SyncServerTests(TestContext context)
private const string Window41 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""";
private const string Window33 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}""";
/// <summary>How long any wait may take on a loaded runner; every wait ends as soon as what it waits for happened.</summary>
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(60);
[Test]
public async Task ASequenceUploadedFromOnePcDownloadsIdenticallyOnAnother()
{
@@ -147,12 +150,16 @@ public sealed class SyncServerTests(TestContext context)
var hub = server.Services.GetRequiredService<EventHub>();
await UntilAsync(() => Task.FromResult(agent.Snapshot is not null && hub.SubscriberCount > 0), "the agent's first comparison and event socket");
// Someone edits the project on the server (web or another PC).
// Someone edits the project on the server (web or another PC). The comparison its event starts writes the
// settings on this PC before the link that records the agreement: wait for the comparison, not for the settings.
var compared = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
studio.Sync.Changed += _ => compared.TrySetResult();
using (var patch = await http.PatchAsJsonAsync($"/api/v1/sequences/{remoteId}",
new UpdateSequenceRequest(null, null, null, null, Window33, null), ProtocolJson.Default.UpdateSequenceRequest))
await patch.ExpectAsync(HttpStatusCode.OK);
await UntilAsync(async () => ProjectSettings.FromJson((await studio.Db.Sequences.GetAsync(local.Id))!.SettingsJson ?? "{}").Exposure.DeflickerWindow.Manual == 33,
await SignalAsync(compared.Task, "the comparison of the edit");
Assert.Equal(33, ProjectSettings.FromJson((await studio.Db.Sequences.GetAsync(local.Id))!.SettingsJson ?? "{}").Exposure.DeflickerWindow.Manual,
"the edit reached this PC");
Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Harbour sunset")).Status);
}
@@ -247,11 +254,23 @@ public sealed class SyncServerTests(TestContext context)
private async Task UntilAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(60);
var until = DateTime.UtcNow + Deadline;
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(50, context.Cancellation);
}
}
private async Task SignalAsync(Task signal, string what)
{
try
{
await signal.WaitAsync(Deadline, context.Cancellation);
}
catch (TimeoutException)
{
Assert.Fail("Timed out waiting for " + what);
}
}
}