Merge branch 'fix/proxies-render-sync': proxies from clients and nodes, node manifests, sync and mass-rename fixes, server polling
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
45 files changed
+1833
-179
No files matched your search
@@ -1,10 +1,14 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Archiving;
|
||||
@@ -57,6 +61,45 @@ public sealed class RenderNodeClientTests(TestContext context)
|
||||
Assert.False(Directory.EnumerateFileSystemEntries(Path.Combine(cache, "jobs")).Any(), "job folder removed");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ANodeSkipsMissingFramesFetchesUnhashedOnesAndSendsTheProxiesAskedFor()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
|
||||
var sequenceId = await UploadSequenceAsync(editor, Photos()[..3]);
|
||||
await Uploads.UploadAsync(editor, [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. Uploads.Photo(2000, 9)], "IMG_0004.HEIC", sequenceId);
|
||||
var frames = await server.Database.Frames.ListBySequenceAsync(sequenceId);
|
||||
// Frame 1 is gone from the server, frame 2 was adopted and never hashed, frame 3 is damaged (the server could not
|
||||
// decode it) and frame 4 is a HEIF the server cannot decode.
|
||||
File.Delete(Path.Combine(server.Options.ArchivePath, frames[0].RelativePath));
|
||||
await server.Database.Frames.UpdateFlagsAsync([frames[0].Id], FrameFlags.Missing, FrameFlags.None);
|
||||
await server.Database.Frames.UpdateFlagsAsync([frames[2].Id, frames[3].Id], FrameFlags.Undecodable, FrameFlags.None);
|
||||
await using (var session = await server.Database.Database.OpenAsync(context.Cancellation))
|
||||
{
|
||||
await session.ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE id = $1", [frames[1].Id], context.Cancellation);
|
||||
await session.ExecuteAsync("UPDATE frames SET format = $1 WHERE id = $2", [(int)ImageFileFormat.Heif, frames[3].Id], context.Cancellation);
|
||||
}
|
||||
var job = await CreateRenderAsync(server, editor, sequenceId);
|
||||
|
||||
var requests = new RecordPaths(new SocketsHttpHandler());
|
||||
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc", requests) { Token = token };
|
||||
// This PC decodes HEIF (WIC with the HEIF extension on Windows).
|
||||
await using var node = Node(client, context.CreateTempDirectory("node"), decoder: new ImageDecoder([new SolidHeif(), new ManagedDecoderProvider()]));
|
||||
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
|
||||
|
||||
var done = await JobApiTests.GetAsync(editor, job.Id);
|
||||
Assert.Equal("done", done.State, done.Error);
|
||||
Assert.DoesNotContain($"/api/v1/frames/{frames[0].Id}/original", requests.Paths);
|
||||
Assert.Contains($"/api/v1/frames/{frames[1].Id}/original", requests.Paths);
|
||||
// The damaged frame stays out, as in the server's own render; the HEIF renders from its original here.
|
||||
Assert.DoesNotContain($"/api/v1/frames/{frames[2].Id}/original", requests.Paths);
|
||||
Assert.Contains($"/api/v1/frames/{frames[3].Id}/original", requests.Paths);
|
||||
var sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
|
||||
var proxy = new ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder).Proxy(frames[3].Index);
|
||||
Assert.Equal(frames[3].CapturedAt, MetadataReader.Read(proxy).CapturedAt, "the proxy the server asked for, with the frame's capture time");
|
||||
Assert.Equal((96, 64), MetadataReader.Read(proxy).OrientedSize);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ANodeReportsWhyItCouldNotRender()
|
||||
{
|
||||
@@ -263,8 +306,8 @@ public sealed class RenderNodeClientTests(TestContext context)
|
||||
Assert.FileExists(part[..^".part".Length]);
|
||||
}
|
||||
|
||||
private static RenderNodeClient Node(TitanoClient client, string cache, TimeSpan? poll = null, TimeSpan? heartbeat = null) =>
|
||||
new(client, new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer() } },
|
||||
private static RenderNodeClient Node(TitanoClient client, string cache, TimeSpan? poll = null, TimeSpan? heartbeat = null, ImageDecoder? decoder = null) =>
|
||||
new(client, new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = decoder ?? DecoderFactory.CreateServer() } },
|
||||
new RenderNodeOptions
|
||||
{
|
||||
ClientName = "studio-pc",
|
||||
@@ -314,6 +357,35 @@ public sealed class RenderNodeClientTests(TestContext context)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Records the path of every request.</summary>
|
||||
private sealed class RecordPaths(HttpMessageHandler inner) : DelegatingHandler(inner)
|
||||
{
|
||||
private readonly ConcurrentQueue<string> _paths = new();
|
||||
|
||||
public IReadOnlyCollection<string> Paths => _paths;
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
_paths.Enqueue(request.RequestUri!.AbsolutePath);
|
||||
return base.SendAsync(request, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Decodes every HEIF as a mid-grey 96 × 64 frame, as a native HEIF decoder would decode a real one.</summary>
|
||||
private sealed class SolidHeif : IImageDecoderProvider
|
||||
{
|
||||
public string Name => "heif-test";
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Heif ? DecodeTier.Native : null;
|
||||
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var image = new ImageBuffer(96, 64);
|
||||
for (var c = 0; c < 3; c++) image.Plane(c).Fill(0.2f);
|
||||
return new DecodedImage(image, DecodeTier.Native, Name, 96, 64);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Counts the node's claims the server answered.</summary>
|
||||
private sealed class CountClaims(HttpMessageHandler inner) : DelegatingHandler(inner)
|
||||
{
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using System.Net;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Storage;
|
||||
using Titano.Testing;
|
||||
|
||||
@@ -61,11 +64,70 @@ public sealed class ArchiveModuleTests(TestContext context)
|
||||
Assert.Equal(server.Database.SchemaVersion, summary.SchemaVersion);
|
||||
}
|
||||
|
||||
private static byte[] Photo()
|
||||
[Test]
|
||||
public async Task PhotosAlreadyInTheArchiveAndAddedLaterAreIndexedByPolling()
|
||||
{
|
||||
var photo = Photo();
|
||||
// An adopted folder that already holds photos.
|
||||
await using var server = await TestServer.StartAsync(context, options =>
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(options.ArchivePath, "roof"));
|
||||
File.WriteAllBytes(Path.Combine(options.ArchivePath, "roof", "IMG_0001.JPG"), photo);
|
||||
}, ArchiveModule.Register);
|
||||
var archive = server.Services.GetRequiredService<ServerArchive>();
|
||||
await UntilIndexedAsync(server, archive.Id, "roof");
|
||||
await UntilScannedAsync(server);
|
||||
|
||||
// Another writer adds a folder: the next poll queues a scan, but not while one is pending.
|
||||
Directory.CreateDirectory(Path.Combine(server.Options.ArchivePath, "garden"));
|
||||
File.WriteAllBytes(Path.Combine(server.Options.ArchivePath, "garden", "IMG_0002.JPG"), Photo(seed: 3));
|
||||
var polling = server.Services.GetRequiredService<ArchivePolling>();
|
||||
var paused = new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = JobKind.Scan,
|
||||
TargetIds = [archive.Id],
|
||||
State = JobState.Paused,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await server.Database.Jobs.EnqueueAsync(paused, context.Cancellation);
|
||||
Assert.Null(await polling.PollAsync(context.Cancellation));
|
||||
await server.Services.GetRequiredService<JobEngineHost>().Engine.CancelAsync(paused.Id, context.Cancellation);
|
||||
|
||||
var scan = Assert.NotNull(await polling.PollAsync(context.Cancellation));
|
||||
Assert.Equal(JobPriority.Background, scan.Priority);
|
||||
await UntilIndexedAsync(server, archive.Id, "garden");
|
||||
}
|
||||
|
||||
private static async Task UntilIndexedAsync(TestServer server, Guid archiveId, string folder)
|
||||
{
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (!(await server.Database.Sequences.ListLocationsAsync(archiveId)).Any(l => l.Folder == folder))
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, $"{folder} was not indexed");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for the scan queued at start to finish: its sequences are indexed before it ends.</summary>
|
||||
private static async Task UntilScannedAsync(TestServer server)
|
||||
{
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running })
|
||||
{
|
||||
while ((await server.Database.Jobs.ListAsync(state, JobKind.Scan)).Items.Count > 0)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, "the scan at start did not finish");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Photo(int seed = 0)
|
||||
{
|
||||
const int width = 96, height = 64;
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)(i * 7 % 251);
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed) % 251);
|
||||
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Storage;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Proxies of originals the server cannot decode (BRIEF §2.3: HEIF) arrive from clients and render nodes through
|
||||
/// <c>PUT /api/v1/frames/{id}/proxy</c> and become the frame's proxy and thumbnail.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class ProxyUploadTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task AProxySentForAFrameTheServerCannotDecodeIsCheckedKeptAndThumbnailed()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var (viewer, _, _) = await server.UserAsync("vera", "viewer");
|
||||
var upload = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
|
||||
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(upload.FrameId));
|
||||
Assert.Equal(ImageFileFormat.Heif, frame.Format);
|
||||
|
||||
var manifest = await ManifestAsync(editor, upload.SequenceId);
|
||||
Assert.Equal((true, false), (manifest.Frames.Single().WantsProxy, manifest.Frames.Single().HasProxy));
|
||||
Assert.Equal(new ProxySpec(1920, 92), manifest.Proxies);
|
||||
|
||||
using (var garbage = await PutAsync(editor, frame.Id, "not a photo"u8.ToArray()))
|
||||
await garbage.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "invalid_proxy");
|
||||
using (var other = await PutAsync(editor, frame.Id, Proxy(frame.CapturedAt!.Value.AddSeconds(1))))
|
||||
await other.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "proxy_mismatch");
|
||||
var proxy = Proxy(frame.CapturedAt!.Value);
|
||||
using (var refused = await PutAsync(viewer, frame.Id, proxy))
|
||||
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
using (var missing = await PutAsync(editor, Guid.CreateVersion7(), proxy))
|
||||
await missing.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
|
||||
using (var stored = await PutAsync(editor, frame.Id, proxy))
|
||||
await stored.ExpectAsync(HttpStatusCode.NoContent);
|
||||
|
||||
await Http.BytesEqualAsync(proxy, editor.GetByteArrayAsync($"/api/v1/frames/{frame.Id}/proxy"));
|
||||
var after = (await ManifestAsync(editor, upload.SequenceId)).Frames.Single();
|
||||
Assert.Equal((false, true), (after.WantsProxy, after.HasProxy));
|
||||
|
||||
// The thumbnail job the proxy queued draws the frame from it.
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (true)
|
||||
{
|
||||
using var thumb = await editor.GetAsync($"/api/v1/frames/{frame.Id}/thumb");
|
||||
if (thumb.StatusCode == HttpStatusCode.OK)
|
||||
{
|
||||
var jpeg = await thumb.Content.ReadAsByteArrayAsync();
|
||||
Assert.Equal((320, 240), (JpegDecoder.ReadInfo(jpeg).Width, JpegDecoder.ReadInfo(jpeg).Height));
|
||||
break;
|
||||
}
|
||||
Assert.True(DateTime.UtcNow < until, $"thumbnail not built: {(int)thumb.StatusCode}");
|
||||
await Task.Delay(100);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FramesTheServerDecodesAskForNoProxy()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var upload = await Uploads.UploadAsync(editor, Proxy(new DateTime(2026, 9, 28, 18, 2, 11)), "IMG_0001.JPG", sessionKey: "roof");
|
||||
|
||||
Assert.False((await ManifestAsync(editor, upload.SequenceId)).Frames.Single().WantsProxy);
|
||||
// Nor takes one: renders and remote views keep the proxy the server makes itself.
|
||||
using var refused = await PutAsync(editor, upload.FrameId, Proxy(new DateTime(2026, 9, 28, 18, 2, 11)));
|
||||
await refused.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "proxy_not_wanted");
|
||||
}
|
||||
|
||||
/// <summary>A HEIF file as far as signature sniffing goes (an <c>ftyp</c> box naming heic), with no pixels the server can read.</summary>
|
||||
private static byte[] Heif(int seed) => [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. Uploads.Photo(2000, seed)];
|
||||
|
||||
/// <summary>A 320 × 240 JPEG with <paramref name="captured"/> in its Exif, as a client makes a proxy.</summary>
|
||||
private static byte[] Proxy(DateTime captured)
|
||||
{
|
||||
using var image = new ImageBuffer(320, 240);
|
||||
for (var c = 0; c < 3; c++) image.Plane(c).Fill(0.3f + c * 0.1f);
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { CapturedAt = captured, Software = "Titano" });
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
private static Task<HttpResponseMessage> PutAsync(HttpClient client, Guid frameId, byte[] body)
|
||||
{
|
||||
var content = new ByteArrayContent(body);
|
||||
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
||||
return client.PutAsync($"/api/v1/frames/{frameId}/proxy", content);
|
||||
}
|
||||
|
||||
private static async Task<SequenceManifest> ManifestAsync(HttpClient client, Guid sequenceId)
|
||||
{
|
||||
using var response = await client.GetAsync($"/api/v1/sequences/{sequenceId}/manifest");
|
||||
return await response.ReadAsync(ProtocolJson.Default.SequenceManifest);
|
||||
}
|
||||
}
|
||||
@@ -112,16 +112,19 @@ public sealed class SyncServerTests(TestContext context)
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
|
||||
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
|
||||
var photos = Enumerable.Range(20, 3).Select(SyncClient.Photo).ToList();
|
||||
var photos = Enumerable.Range(20, 4).Select(SyncClient.Photo).ToList();
|
||||
var local = await studio.LocalAsync("Aurora", photos);
|
||||
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
|
||||
var remoteId = (await studio.EntryAsync("Aurora")).Link!.RemoteId;
|
||||
|
||||
// An earlier attempt left half of one original, and a damaged half of another.
|
||||
// An earlier attempt left half of one original, a damaged half of another, a third complete (stopped while it was
|
||||
// being hashed) and a fourth longer than the file: the server cannot resume either of the last two (416).
|
||||
var staging = Path.Combine(laptop.Archive.RootPath, ".titano", "staging", "sync-" + remoteId.ToString("N"));
|
||||
Directory.CreateDirectory(staging);
|
||||
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[0]) + ".jpg.part"), photos[0][..(photos[0].Length / 2)]);
|
||||
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[1]) + ".jpg.part"), new byte[photos[1].Length / 2]);
|
||||
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[2]) + ".jpg.part"), photos[2]);
|
||||
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[3]) + ".jpg.part"), [.. photos[3], .. new byte[64]]);
|
||||
|
||||
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
|
||||
var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Aurora", SyncDownloadMode.Originals, laptop.Archive.Id);
|
||||
|
||||
Reference in new issue
Block a user