The first original of an upload now creates the server sequence through its session key (the archive ingest files API-created empty sequences nowhere), and settings sent after an upload are retried when the server's own analysis edits the new sequence meanwhile. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
121 lines
5.7 KiB
C#
121 lines
5.7 KiB
C#
using System.Security.Cryptography;
|
|
using Titano.Core.Codecs.Jpeg;
|
|
using Titano.Core.Model;
|
|
using Titano.Data;
|
|
using Titano.Data.Archiving;
|
|
using Titano.Data.Jobs;
|
|
using Titano.Data.Sync;
|
|
using Titano.Protocol.Client;
|
|
using Titano.Testing;
|
|
|
|
namespace Titano.Server.Tests.Sync;
|
|
|
|
/// <summary>A desktop client's sync side: its own index and archive, the sync engine and a job engine, signed in to a test server.</summary>
|
|
internal sealed class SyncClient : IAsyncDisposable
|
|
{
|
|
private readonly TestContext _context;
|
|
private readonly TitanoClient _client;
|
|
|
|
private SyncClient(TestContext context, TitanoDatabase db, ArchiveService archives, Archive archive, SyncService sync, TitanoClient client, JobEngine engine)
|
|
{
|
|
_context = context;
|
|
Db = db;
|
|
Archives = archives;
|
|
Archive = archive;
|
|
Sync = sync;
|
|
_client = client;
|
|
Engine = engine;
|
|
Remote = new TitanoSyncRemote(client, ownsClient: false);
|
|
}
|
|
|
|
public TitanoDatabase Db { get; }
|
|
public ArchiveService Archives { get; }
|
|
public Archive Archive { get; }
|
|
public SyncService Sync { get; }
|
|
public JobEngine Engine { get; }
|
|
|
|
/// <summary>The connection the table and the agent use (jobs get their own from the connector).</summary>
|
|
public TitanoSyncRemote Remote { get; }
|
|
|
|
public string Server => Remote.Server;
|
|
private CancellationToken Ct => _context.Cancellation;
|
|
|
|
public static async Task<SyncClient> StartAsync(TestContext context, TestServer server, string token, string name)
|
|
{
|
|
var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "titano.db")), context.Cancellation);
|
|
var options = new ArchiveServiceOptions { Owner = name, LeaseWait = TimeSpan.FromSeconds(20) };
|
|
var archives = new ArchiveService(db, options);
|
|
var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Main", cancellationToken: context.Cancellation);
|
|
var sync = new SyncService(db, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = context.CreateTempDirectory(name + "-proxies") });
|
|
var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), name) { Token = token };
|
|
var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. sync.CreateJobHandlers(new Connector(client))],
|
|
new JobEngineOptions { Workers = 2, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
|
await engine.StartAsync(context.Cancellation);
|
|
return new SyncClient(context, db, archives, archive, sync, client, engine);
|
|
}
|
|
|
|
/// <summary>Distinct JPEGs larger than one 64 KiB chunk.</summary>
|
|
public static byte[] Photo(int seed)
|
|
{
|
|
const int width = 512, height = 384;
|
|
var pixels = new byte[width * height * 3];
|
|
new Random(seed).NextBytes(pixels);
|
|
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 95 });
|
|
}
|
|
|
|
public static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
|
|
|
/// <summary>A local sequence committed through the archive ingest, optionally with project settings edited on this PC.</summary>
|
|
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> photos, string? settingsJson = null)
|
|
{
|
|
var staging = Path.Combine(Archive.RootPath, ".titano", "staging", "test");
|
|
Directory.CreateDirectory(staging);
|
|
Guid? id = null;
|
|
for (var i = 0; i < photos.Count; i++)
|
|
{
|
|
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
|
|
await File.WriteAllBytesAsync(path, photos[i], Ct);
|
|
var result = await Archives.Ingest.CommitAsync(new IngestRequest(Archive.Id, id, id is null ? title : null, null, path, $"IMG_{i + 1:0000}.JPG",
|
|
photos[i].Length, Sha(photos[i]), new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(10 * i), null), Ct);
|
|
id = result.SequenceId;
|
|
}
|
|
var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!;
|
|
if (settingsJson is null) return sequence;
|
|
var edited = await Db.Sequences.EditAsync(sequence.Id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, null, Ct);
|
|
return edited.Sequence!;
|
|
}
|
|
|
|
public async Task<Job> WaitAsync(Guid jobId, JobState state = JobState.Done)
|
|
{
|
|
var until = DateTime.UtcNow.AddSeconds(60);
|
|
while (true)
|
|
{
|
|
var job = await Db.Jobs.GetAsync(jobId, Ct);
|
|
if (job?.State == state) return job;
|
|
if (job?.State is JobState.Failed && state != JobState.Failed) Assert.Fail($"Job failed: {job.Error}\n{job.LogTail}");
|
|
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State})");
|
|
await Task.Delay(25, Ct);
|
|
}
|
|
}
|
|
|
|
public async Task<SyncEntry> EntryAsync(string title) => (await Sync.ListAsync(Server, Ct)).Single(e => e.Title == title);
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await Engine.DisposeAsync();
|
|
Remote.Dispose();
|
|
_client.Dispose();
|
|
await Db.DisposeAsync();
|
|
}
|
|
|
|
/// <summary>Every job gets its own remote over the shared signed-in client.</summary>
|
|
private sealed class Connector(TitanoClient client) : ISyncConnector
|
|
{
|
|
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
|
|
{
|
|
ISyncRemote remote = new TitanoSyncRemote(client, ownsClient: false);
|
|
return ValueTask.FromResult<ISyncRemote?>(remote.Server == server ? remote : null);
|
|
}
|
|
}
|
|
}
|