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;
/// A desktop client's sync side: its own index and archive, the sync engine and a job engine, signed in to a test server.
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; }
/// The connection the table and the agent use (jobs get their own from the connector).
public TitanoSyncRemote Remote { get; }
public string Server => Remote.Server;
private CancellationToken Ct => _context.Cancellation;
public static async Task 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);
}
/// Distinct JPEGs larger than one 64 KiB chunk.
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));
/// A local sequence committed through the archive ingest, optionally with project settings edited on this PC.
public async Task LocalAsync(string title, IReadOnlyList 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 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 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();
}
/// Every job gets its own remote over the shared signed-in client.
private sealed class Connector(TitanoClient client) : ISyncConnector
{
public ValueTask ConnectAsync(string server, CancellationToken cancellationToken)
{
ISyncRemote remote = new TitanoSyncRemote(client, ownsClient: false);
return ValueTask.FromResult(remote.Server == server ? remote : null);
}
}
}