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!; } /// One more photo imported into a local sequence, captured at (before others: it is inserted). public async Task AddPhotoAsync(Guid sequenceId, byte[] photo, DateTime captured) { var staging = Path.Combine(Archive.RootPath, ".titano", "staging", "test"); Directory.CreateDirectory(staging); var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part"); await File.WriteAllBytesAsync(path, photo, Ct); return await Archives.Ingest.CommitAsync(new IngestRequest(Archive.Id, sequenceId, null, null, path, $"IMG_{captured:HHmmss}.JPG", photo.Length, Sha(photo), captured, null), Ct); } /// An edit on this PC, as the editor makes it (project file and index, settings version + 1). public async Task EditSettingsAsync(Guid sequenceId, string settingsJson) { var sequence = (await Db.Sequences.GetAsync(sequenceId, Ct))!; await File.WriteAllTextAsync(new Titano.Core.Archiving.ArchivePaths(Archive.RootPath).Sequence(sequence.Folder).ProjectPath, settingsJson, Ct); return (await Db.Sequences.EditAsync(sequenceId, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, sequence.SettingsVersion, Ct)) .Sequence!; } /// A render of made on this PC: its file in the sequence's exports and its row. public async Task RenderAsync(Sequence sequence, string fileName, byte[] bytes) { var exports = Path.Combine(Archive.RootPath, sequence.Folder, "exports"); Directory.CreateDirectory(exports); await File.WriteAllBytesAsync(Path.Combine(exports, fileName), bytes, Ct); var render = new Render { Id = Guid.CreateVersion7(), SequenceId = sequence.Id, PresetName = "4K HEVC", OutputPath = sequence.Folder + "/exports/" + fileName, Codec = "hevc", Width = 3840, Height = 2160, Fps = 30, DurationSeconds = 10, Bytes = bytes.Length, Created = DateTimeOffset.UtcNow, ProducedBy = "studio", }; await Db.Renders.InsertAsync(render, Ct); return render; } public string RenderFile(Render render) => Path.Combine(Archive.RootPath, render.OutputPath); 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); } } }