using System.ComponentModel; using System.IO; using Titano.Core.Diagnostics; using Titano.Protocol.Client; namespace Titano.Uploader.Uploads; /// What the upload engine is doing. public enum EngineStatus { Idle, Running, Paused, WaitingForServer, } /// Queue control used by the window and the tray. public interface IUploadEngine : INotifyPropertyChanged { EngineStatus Status { get; } /// Current throughput over the last seconds. double BytesPerSecond { get; } /// Raised when the last pending item finished (balloon on completion). event EventHandler? Drained; /// Starts work for newly queued items without waiting for the next tick. void Pump(); void Pause(); void Resume(); /// Stops every transfer and clears the queue; files already uploaded stay on the server. void StopAndClear(); /// Puts a failed item back in line with a fresh retry budget. void Retry(UploadItem item); } /// /// Works through the with concurrent files: hash, upload /// (resumable chunks; the server verifies the SHA-256), then optionally delete the source whose bytes the server /// received and verified. A file the server already held is kept: no copy of it was verified on this run. /// Lives on the UI thread: state changes happen there while hashing and HTTP run on the thread pool. /// public sealed class UploadEngine : IUploadEngine, IDisposable { public const int Parallelism = 2; private readonly UploadQueue _queue; private readonly IUploadTransport _transport; private readonly Func _deleteAfterUpload; private readonly TimeProvider _time; private readonly long _origin; private readonly RateMeter _meter = new(); private readonly Dictionary _running = []; private readonly Dictionary> _creating = []; private readonly CancellationTokenSource _lifetime = new(); private EngineStatus _status; private double _bytesPerSecond; private bool _hadWork; public UploadEngine(UploadQueue queue, IUploadTransport transport, Func deleteAfterUpload, TimeProvider? time = null) { _queue = queue; _transport = transport; _deleteAfterUpload = deleteAfterUpload; _time = time ?? TimeProvider.System; _origin = _time.GetTimestamp(); _transport.ReadyChanged += (_, _) => Pump(); } public event PropertyChangedEventHandler? PropertyChanged; public event EventHandler? Drained; /// Raised when the server confirmed an item (verified or already present). public event EventHandler? ItemConfirmed; public EngineStatus Status { get => _status; private set { if (_status == value) return; _status = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Status))); } } public double BytesPerSecond { get => _bytesPerSecond; private set { if (_bytesPerSecond.Equals(value)) return; _bytesPerSecond = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BytesPerSecond))); } } private TimeSpan Now => _time.GetElapsedTime(_origin); private DateTime UtcNow => _time.GetUtcNow().UtcDateTime; /// Starts the once-a-second pump on the calling (UI) thread. public void Start() => _ = TickAsync(_lifetime.Token); /// Starts work for newly queued items without waiting for the next tick. public void Pump() { if (_lifetime.IsCancellationRequested) return; while (!_queue.IsPaused && _transport.IsReady && _running.Count < Parallelism) { var item = _queue.NextReady(UtcNow); if (item is null) break; Begin(item); } Refresh(); } public void Pause() { _queue.IsPaused = true; CancelRunning(); Refresh(); } public void Resume() { _queue.IsPaused = false; Pump(); } public void StopAndClear() { CancelRunning(); _queue.Clear(); _creating.Clear(); _meter.Reset(); _hadWork = false; Refresh(); } public void Retry(UploadItem item) { _queue.Requeue(item); Pump(); } public void Dispose() { _lifetime.Cancel(); CancelRunning(); _lifetime.Dispose(); } private async Task TickAsync(CancellationToken ct) { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), _time); try { do { Pump(); } while (await timer.WaitForNextTickAsync(ct)); } catch (OperationCanceledException) { } } private void Begin(UploadItem item) { if (item.State == UploadItemState.Failed) { item.Retries++; item.NextRetryUtc = null; item.Failure = UploadFailure.None; item.FailureDetail = null; } // Leaving Queued/Failed synchronously keeps NextReady from handing the item out twice. item.State = UploadItemState.Hashing; var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); _running[item] = cts; _hadWork = true; _ = RunAsync(item, cts); } private async Task RunAsync(UploadItem item, CancellationTokenSource cts) { var ct = cts.Token; try { await HashIfNeededAsync(item, ct); if (item.State == UploadItemState.Failed) return; item.State = UploadItemState.Uploading; item.BytesSent = 0; var batch = _queue.GetBatch(item.BatchId); Guid? sequenceId = batch?.Mode switch { UploadTargetMode.Sequence => batch.SequenceId, UploadTargetMode.NewSequence => await EnsureSequenceAsync(batch, ct), _ => null, }; var baseline = true; var progress = new Progress(p => { if (item.State != UploadItemState.Uploading) return; // The first report of a resumed upload counts chunks the server already had: not throughput. if (!baseline) _meter.Add(Math.Max(0, p.BytesSent - item.BytesSent), Now); baseline = false; item.BytesSent = p.BytesSent; }); var (outcome, frameId) = await _transport.UploadAsync(item, sequenceId, item.Sha256!, progress, ct); item.FrameId = frameId; item.BytesSent = item.Size; item.State = outcome == UploadOutcome.Verified ? UploadItemState.Verified : UploadItemState.Skipped; _queue.OnChanged(); ItemConfirmed?.Invoke(this, item); if (outcome == UploadOutcome.Verified && _deleteAfterUpload()) DeleteConfirmedSource(item); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { Requeue(item); } catch (ServerUnavailableException ex) { Log.Info("upload", $"{item.FileName} waits for the server ({ex.Problem})"); Requeue(item); } catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) { _queue.Fail(item, UploadFailure.FileMissing, null, UtcNow); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("upload", $"Cannot read {item.Path}", ex); _queue.Fail(item, File.Exists(item.Path) ? UploadFailure.FileUnreadable : UploadFailure.FileMissing, null, UtcNow); } catch (TitanoApiException ex) { Log.Warning("upload", $"Server refused {item.Path}: {ex.Error.Code}", ex); _queue.Fail(item, UploadFailure.ServerRejected, ex.Error.Message, UtcNow); } catch (Exception ex) { // Worker boundary: nothing may leave an item stuck in an active state. Log.Error("upload", $"Upload of {item.Path} failed", ex); _queue.Fail(item, UploadFailure.Unexpected, null, UtcNow); } finally { _running.Remove(item); cts.Dispose(); Pump(); } } /// Hashes when the file is new or changed; a file that changes while being read fails for a later retry. private async Task HashIfNeededAsync(UploadItem item, CancellationToken ct) { var file = new FileInfo(item.Path); if (!file.Exists) { _queue.Fail(item, UploadFailure.FileMissing, null, UtcNow); return; } if (file.Length != item.Size || file.LastWriteTimeUtc != item.ModifiedUtc) { item.Sha256 = null; item.Size = file.Length; item.ModifiedUtc = file.LastWriteTimeUtc; } if (item.Sha256 is not null) return; var sha = await Task.Run(() => TitanoClient.HashFileAsync(item.Path, ct), ct); file.Refresh(); if (!file.Exists || file.Length != item.Size || file.LastWriteTimeUtc != item.ModifiedUtc) { _queue.Fail(item, UploadFailure.FileChanged, null, UtcNow); return; } item.Sha256 = sha; _queue.OnChanged(); } /// Creates the batch's sequence once, shared by concurrent items of the same batch. private async Task EnsureSequenceAsync(UploadBatch batch, CancellationToken ct) { if (batch.SequenceId is { } known) return known; if (!_creating.TryGetValue(batch.Id, out var creation)) { creation = _transport.CreateSequenceAsync(batch.Title, _lifetime.Token); _creating[batch.Id] = creation; } try { var id = await creation.WaitAsync(ct); batch.SequenceId = id; _queue.OnChanged(); return id; } catch when (creation.IsFaulted || creation.IsCanceled) { _creating.Remove(batch.Id); throw; } } /// /// BRIEF ยง0.2 rule 8: deletes only a file whose bytes the server received and verified by hash before committing /// them, and only when it is still exactly the bytes that were hashed (same size and write time). /// private static void DeleteConfirmedSource(UploadItem item) { try { var file = new FileInfo(item.Path); if (!file.Exists) return; if (file.Length != item.Size || file.LastWriteTimeUtc != item.ModifiedUtc) { Log.Warning("upload", $"Kept {item.Path}: it changed after the server verified it"); return; } file.Delete(); Log.Info("upload", $"Deleted {item.Path} after the server confirmed SHA-256 {item.Sha256}"); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("upload", $"Could not delete {item.Path}", ex); } } private void Requeue(UploadItem item) { if (!item.IsActive) return; item.State = UploadItemState.Queued; item.BytesSent = 0; } private void CancelRunning() { foreach (var cts in _running.Values.ToList()) cts.Cancel(); } private void Refresh() { BytesPerSecond = _meter.BytesPerSecond(Now); var pending = _queue.HasPending; Status = _queue.IsPaused && pending ? EngineStatus.Paused : pending && !_transport.IsReady ? EngineStatus.WaitingForServer : pending || _running.Count > 0 ? EngineStatus.Running : EngineStatus.Idle; if (_hadWork && !pending && _running.Count == 0) { _hadWork = false; _meter.Reset(); Drained?.Invoke(this, EventArgs.Empty); } } }