A sequence created with POST /api/v1/sequences had no folder, and the ingest looked for its sidecar at the archive root: every upload into it failed with 503 commit_failed, so the Uploader's "New sequence" target never worked. Its first frame now claims a folder by the rules of a sequence created by an upload (folder template with its title, unique variant, sidecar with the row's id, title, tags, rating, notes and project), and the row takes the folder in one transaction (DOCKER-1). A frame flagged missing or corrupt, or whose file is gone or has another size, no longer stands for an upload: the start short-circuit and crash recovery match only intact frames still on disk, and the ingest repairs such a frame with the verified copy (same id and position, flags cleared, a damaged file kept beside it as name.damaged-<time>) instead of calling it a duplicate. The Uploader deletes a source only after the server received and verified its bytes in that upload, never on "already on the server" (SRV-1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
367 lines
12 KiB
C#
367 lines
12 KiB
C#
using System.ComponentModel;
|
|
using System.IO;
|
|
using Titano.Core.Diagnostics;
|
|
using Titano.Protocol.Client;
|
|
|
|
namespace Titano.Uploader.Uploads;
|
|
|
|
/// <summary>What the upload engine is doing.</summary>
|
|
public enum EngineStatus
|
|
{
|
|
Idle,
|
|
Running,
|
|
Paused,
|
|
WaitingForServer,
|
|
}
|
|
|
|
/// <summary>Queue control used by the window and the tray.</summary>
|
|
public interface IUploadEngine : INotifyPropertyChanged
|
|
{
|
|
EngineStatus Status { get; }
|
|
|
|
/// <summary>Current throughput over the last seconds.</summary>
|
|
double BytesPerSecond { get; }
|
|
|
|
/// <summary>Raised when the last pending item finished (balloon on completion).</summary>
|
|
event EventHandler? Drained;
|
|
|
|
/// <summary>Starts work for newly queued items without waiting for the next tick.</summary>
|
|
void Pump();
|
|
|
|
void Pause();
|
|
void Resume();
|
|
|
|
/// <summary>Stops every transfer and clears the queue; files already uploaded stay on the server.</summary>
|
|
void StopAndClear();
|
|
|
|
/// <summary>Puts a failed item back in line with a fresh retry budget.</summary>
|
|
void Retry(UploadItem item);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Works through the <see cref="UploadQueue"/> with <see cref="Parallelism"/> 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.
|
|
/// </summary>
|
|
public sealed class UploadEngine : IUploadEngine, IDisposable
|
|
{
|
|
public const int Parallelism = 2;
|
|
|
|
private readonly UploadQueue _queue;
|
|
private readonly IUploadTransport _transport;
|
|
private readonly Func<bool> _deleteAfterUpload;
|
|
private readonly TimeProvider _time;
|
|
private readonly long _origin;
|
|
private readonly RateMeter _meter = new();
|
|
private readonly Dictionary<UploadItem, CancellationTokenSource> _running = [];
|
|
private readonly Dictionary<Guid, Task<Guid>> _creating = [];
|
|
private readonly CancellationTokenSource _lifetime = new();
|
|
private EngineStatus _status;
|
|
private double _bytesPerSecond;
|
|
private bool _hadWork;
|
|
|
|
public UploadEngine(UploadQueue queue, IUploadTransport transport, Func<bool> 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;
|
|
|
|
/// <summary>Raised when the server confirmed an item (verified or already present).</summary>
|
|
public event EventHandler<UploadItem>? 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;
|
|
|
|
/// <summary>Starts the once-a-second pump on the calling (UI) thread.</summary>
|
|
public void Start() => _ = TickAsync(_lifetime.Token);
|
|
|
|
/// <summary>Starts work for newly queued items without waiting for the next tick.</summary>
|
|
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<UploadProgress>(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();
|
|
}
|
|
}
|
|
|
|
/// <summary>Hashes when the file is new or changed; a file that changes while being read fails for a later retry.</summary>
|
|
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();
|
|
}
|
|
|
|
/// <summary>Creates the batch's sequence once, shared by concurrent items of the same batch.</summary>
|
|
private async Task<Guid> 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;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
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);
|
|
}
|
|
}
|
|
}
|