merge: P2 photo lookup endpoint and uploads into a target
Brings in the owner review 6 parcel P2: the photo lookup endpoint and the copy path for uploads into an existing sequence, with Server tests. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
3518d0f1bd
8 files changed
+926
-7
No files matched your search
@@ -0,0 +1,46 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Http.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/photos/lookup</c> (owner review 6, #73; capability <see cref="ServerCapabilities.PhotoLookup"/>): which
|
||||
/// sequences of the served archive hold photos a client sampled from its own sequences (<see cref="PhotoLookup"/>). Needs
|
||||
/// the Read right; at most <see cref="PhotoLookupRequest.MaxProbes"/> probes and <see cref="PhotoLookupRequest.MaxItems"/>
|
||||
/// items, 413 <c>too_many</c> beyond.
|
||||
/// </summary>
|
||||
public static class PhotoLookupEndpoints
|
||||
{
|
||||
/// <summary>
|
||||
/// The body a full request may take: 20,000 items of about 70 bytes each are beyond the small limit of the other JSON
|
||||
/// endpoints (<see cref="Hosting.ServerHost.JsonBodyLimit"/>).
|
||||
/// </summary>
|
||||
private const long MaxBodyBytes = 4L * 1024 * 1024;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(api);
|
||||
api.MapPost("/photos/lookup", LookupAsync).Requires(Permissions.Read).WithMetadata(new LookupBodyLimit());
|
||||
}
|
||||
|
||||
private static async Task<IResult> LookupAsync(HttpContext context, PhotoLookupRequest request, PhotoLookup lookup)
|
||||
{
|
||||
if (request.Probes is null) return ApiErrors.BadRequest(context, "bad_request", "probes");
|
||||
if (PhotoLookup.TooMany(request))
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status413PayloadTooLarge, "too_many",
|
||||
PhotoLookupRequest.MaxItems.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
return Results.Json(await lookup.LookupAsync(request, context.RequestAborted), ProtocolJson.Default.PhotoLookupResponse);
|
||||
}
|
||||
|
||||
/// <summary>The lookup's body limit, applied by routing as it selects the endpoint (as the chunk route's is).</summary>
|
||||
private sealed class LookupBodyLimit : IRequestSizeLimitMetadata
|
||||
{
|
||||
public long? MaxRequestBodySize => MaxBodyBytes;
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,8 @@ public sealed class ServerState
|
||||
public string Database { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>What this server offers clients (<see cref="ServerInfo.Capabilities"/>; <see cref="ServerCapabilities"/> names those clients act on).</summary>
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects, ServerCapabilities.Videos];
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects, ServerCapabilities.Videos,
|
||||
ServerCapabilities.PhotoLookup, ServerCapabilities.UploadInto];
|
||||
|
||||
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
@@ -245,6 +245,7 @@ public static class ServerHost
|
||||
services.AddSingleton<ServerSettingsStore>();
|
||||
services.AddSingleton<UploadStore>();
|
||||
services.AddSingleton<UploadService>();
|
||||
services.AddSingleton<PhotoLookup>();
|
||||
services.AddSingleton<RenderStore>();
|
||||
services.AddSingleton<RenderUploads>();
|
||||
services.AddSingleton<SequenceJobs>();
|
||||
@@ -311,6 +312,7 @@ public static class ServerHost
|
||||
AuthEndpoints.Map(api);
|
||||
UserEndpoints.Map(api);
|
||||
SequenceEndpoints.Map(api);
|
||||
PhotoLookupEndpoints.Map(api);
|
||||
ProjectEndpoints.Map(api);
|
||||
LibraryEndpoints.Map(api);
|
||||
FileEndpoints.Map(api);
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Chronos.Data;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/photos/lookup</c> (owner review 6, #73): which sequences of the served archive hold the photos a client
|
||||
/// sampled from its own sequences, so it recognises the same time-lapse filed under another id. Each probe's hashes are
|
||||
/// looked up in the frames and the tombstones, its unhashed photos by size and capture time to the millisecond, and its
|
||||
/// back-reference key in the session keys. The answer names only sequence ids and counts, never files or titles; another
|
||||
/// archive of the index is never looked at.
|
||||
/// </summary>
|
||||
public sealed class PhotoLookup(ChronosDatabase db, ServerArchive archive)
|
||||
{
|
||||
/// <summary>Parameters of one statement: the archive id and the values of one batch.</summary>
|
||||
private const int BatchParameters = 500;
|
||||
|
||||
private const int BatchValues = BatchParameters - 1;
|
||||
|
||||
/// <summary>The unhashed range query binds the archive and the two ends of the range besides the sizes.</summary>
|
||||
private const int UnhashedBatchValues = BatchParameters - 3;
|
||||
|
||||
/// <summary>
|
||||
/// The request goes beyond <see cref="PhotoLookupRequest.MaxProbes"/> probes or <see cref="PhotoLookupRequest.MaxItems"/>
|
||||
/// items (413 <c>too_many</c>).
|
||||
/// </summary>
|
||||
public static bool TooMany(PhotoLookupRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var probes = request.Probes ?? [];
|
||||
if (probes.Count > PhotoLookupRequest.MaxProbes) return true;
|
||||
long items = 0;
|
||||
foreach (var probe in probes)
|
||||
{
|
||||
if (probe is null) continue;
|
||||
items += (probe.Sha256?.Count ?? 0) + (probe.Unhashed?.Count ?? 0) + (probe.SessionKey is null ? 0 : 1);
|
||||
}
|
||||
return items > PhotoLookupRequest.MaxItems;
|
||||
}
|
||||
|
||||
/// <summary>One result per probe, in the request's order; a probe that hit nothing has no hits.</summary>
|
||||
public async Task<PhotoLookupResponse> LookupAsync(PhotoLookupRequest request, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var probes = (request.Probes ?? []).Select(Normalize).ToList();
|
||||
var hashes = probes.SelectMany(p => p.Hashes).Distinct(StringComparer.Ordinal).ToList();
|
||||
var keys = probes.SelectMany(p => p.Unhashed).Distinct().ToList();
|
||||
var sessions = probes.Where(p => p.SessionKey is not null).Select(p => p.SessionKey!).Distinct(StringComparer.Ordinal).ToList();
|
||||
|
||||
var held = new Dictionary<string, HashSet<Guid>>(StringComparer.Ordinal);
|
||||
var removed = new Dictionary<string, HashSet<Guid>>(StringComparer.Ordinal);
|
||||
var byKey = new Dictionary<PhotoKey, HashSet<Guid>>();
|
||||
var bySession = new Dictionary<string, HashSet<Guid>>(StringComparer.Ordinal);
|
||||
|
||||
var archiveId = archive.Id;
|
||||
await using (var session = await db.Database.OpenAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
foreach (var batch in hashes.Chunk(BatchValues))
|
||||
{
|
||||
var (list, parameters) = InList(archiveId, batch);
|
||||
await foreach (var row in session.QueryAsync(
|
||||
"SELECT f.sequence_id, f.sha256 FROM frames f JOIN sequences s ON s.id = f.sequence_id " +
|
||||
$"WHERE s.archive_id = $1 AND f.sha256 IN ({list})", parameters, ct).ConfigureAwait(false))
|
||||
Add(held, row.GetString(1), row.GetGuid(0));
|
||||
}
|
||||
var wanted = hashes.ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var batch in hashes.Chunk(BatchValues))
|
||||
{
|
||||
var (list, parameters) = InList(archiveId, batch);
|
||||
await foreach (var row in session.QueryAsync(
|
||||
"SELECT r.sequence_id, r.sha256, r.replacement_sha256 FROM frame_removals r JOIN sequences s ON s.id = r.sequence_id " +
|
||||
$"WHERE s.archive_id = $1 AND (r.sha256 IN ({list}) OR r.replacement_sha256 IN ({list}))", parameters, ct).ConfigureAwait(false))
|
||||
{
|
||||
var sequence = row.GetGuid(0);
|
||||
if (wanted.Contains(row.GetString(1))) Add(removed, row.GetString(1), sequence);
|
||||
if (row.GetStringOrNull(2) is { } replacement && wanted.Contains(replacement)) Add(removed, replacement, sequence);
|
||||
}
|
||||
}
|
||||
// Sorted by capture time, so each batch asks for a narrow range of the frames.
|
||||
foreach (var batch in keys.OrderBy(k => k.CaptureTicks).Chunk(UnhashedBatchValues))
|
||||
{
|
||||
var wantedKeys = batch.ToHashSet();
|
||||
var parameters = new List<DbParam>
|
||||
{
|
||||
archiveId,
|
||||
new(new DateTime(batch[0].CaptureTicks, DateTimeKind.Unspecified), DbValueType.LocalDateTime),
|
||||
new(new DateTime(batch[^1].CaptureTicks + TimeSpan.TicksPerMillisecond - 1, DateTimeKind.Unspecified), DbValueType.LocalDateTime),
|
||||
};
|
||||
var sizes = new StringBuilder();
|
||||
foreach (var size in batch.Select(k => k.Size).Distinct())
|
||||
{
|
||||
parameters.Add(size);
|
||||
if (sizes.Length > 0) sizes.Append(", ");
|
||||
sizes.Append('$').Append(parameters.Count.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
await foreach (var row in session.QueryAsync(
|
||||
"SELECT f.sequence_id, f.size, f.captured_at FROM frames f JOIN sequences s ON s.id = f.sequence_id " +
|
||||
$"WHERE s.archive_id = $1 AND f.captured_at >= $2 AND f.captured_at <= $3 AND f.size IN ({sizes})",
|
||||
[.. parameters], ct).ConfigureAwait(false))
|
||||
{
|
||||
if (row.GetDateTimeOrNull(2) is not { } captured) continue;
|
||||
var key = new PhotoKey(row.GetInt64(1), Millisecond(captured));
|
||||
if (wantedKeys.Contains(key)) Add(byKey, key, row.GetGuid(0));
|
||||
}
|
||||
}
|
||||
foreach (var batch in sessions.Chunk(BatchValues))
|
||||
{
|
||||
var (list, parameters) = InList(archiveId, batch);
|
||||
await foreach (var row in session.QueryAsync(
|
||||
$"SELECT session_key, sequence_id FROM sequence_sessions WHERE archive_id = $1 AND session_key IN ({list})",
|
||||
parameters, ct).ConfigureAwait(false))
|
||||
Add(bySession, row.GetString(0), row.GetGuid(1));
|
||||
}
|
||||
}
|
||||
|
||||
var results = new List<ProbeResult>(probes.Count);
|
||||
foreach (var probe in probes)
|
||||
{
|
||||
var counts = new Dictionary<Guid, Counts>();
|
||||
foreach (var hash in probe.Hashes)
|
||||
{
|
||||
var holders = held.GetValueOrDefault(hash);
|
||||
foreach (var sequence in holders ?? []) Get(counts, sequence).Hashes++;
|
||||
// A tombstone of content the sequence still holds in a frame is stale: the photo counts once, as held.
|
||||
foreach (var sequence in removed.GetValueOrDefault(hash) ?? [])
|
||||
{
|
||||
if (holders?.Contains(sequence) != true) Get(counts, sequence).Removed++;
|
||||
}
|
||||
}
|
||||
foreach (var key in probe.Unhashed)
|
||||
{
|
||||
foreach (var sequence in byKey.GetValueOrDefault(key) ?? []) Get(counts, sequence).Unhashed++;
|
||||
}
|
||||
if (probe.SessionKey is { } sessionKey)
|
||||
{
|
||||
foreach (var sequence in bySession.GetValueOrDefault(sessionKey) ?? []) Get(counts, sequence).SessionKey = true;
|
||||
}
|
||||
results.Add(new ProbeResult(probe.Key, [.. counts
|
||||
.OrderByDescending(c => (c.Value.SessionKey ? 1 : 0, c.Value.Hashes + c.Value.Removed + c.Value.Unhashed))
|
||||
.ThenBy(c => c.Key)
|
||||
.Select(c => new PhotoLookupHit(c.Key, c.Value.Hashes, c.Value.Removed, c.Value.Unhashed, c.Value.SessionKey))]));
|
||||
}
|
||||
return new PhotoLookupResponse(results);
|
||||
}
|
||||
|
||||
/// <summary>A probe as a set: lower-case hashes, keys to the millisecond, a trimmed session key; each counted once.</summary>
|
||||
private static Probe Normalize(PhotoProbe? probe) =>
|
||||
probe is null
|
||||
? new Probe(string.Empty, [], [], null)
|
||||
: new Probe(
|
||||
probe.Key ?? string.Empty,
|
||||
[.. (probe.Sha256 ?? []).Where(h => h is { Length: 64 }).Select(h => h.ToLowerInvariant()).Distinct(StringComparer.Ordinal)],
|
||||
[.. (probe.Unhashed ?? []).Where(k => k is not null).Select(k => new PhotoKey(k.Size, Millisecond(k.CapturedAt))).Distinct()],
|
||||
string.IsNullOrWhiteSpace(probe.SessionKey) ? null : probe.SessionKey.Trim());
|
||||
|
||||
/// <summary>
|
||||
/// A capture time to the millisecond, as a wall-clock time whatever kind it came with (as
|
||||
/// <c>SequenceRepository.Wall</c> stores it): the index keeps microseconds, a client may send ticks.
|
||||
/// </summary>
|
||||
private static long Millisecond(DateTime value) => value.Ticks - value.Ticks % TimeSpan.TicksPerMillisecond;
|
||||
|
||||
/// <summary><c>$2, $3, …</c> for <paramref name="values"/>, after the archive id as <c>$1</c>.</summary>
|
||||
private static (string List, DbParam[] Parameters) InList(Guid archiveId, string[] values)
|
||||
{
|
||||
var parameters = new DbParam[values.Length + 1];
|
||||
parameters[0] = archiveId;
|
||||
var list = new StringBuilder();
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
{
|
||||
parameters[i + 1] = values[i];
|
||||
if (i > 0) list.Append(", ");
|
||||
list.Append('$').Append((i + 2).ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
return (list.ToString(), parameters);
|
||||
}
|
||||
|
||||
private static void Add<TKey>(Dictionary<TKey, HashSet<Guid>> map, TKey key, Guid sequence) where TKey : notnull
|
||||
{
|
||||
if (!map.TryGetValue(key, out var set)) map[key] = set = [];
|
||||
set.Add(sequence);
|
||||
}
|
||||
|
||||
private static Counts Get(Dictionary<Guid, Counts> counts, Guid sequence)
|
||||
{
|
||||
if (!counts.TryGetValue(sequence, out var found)) counts[sequence] = found = new Counts();
|
||||
return found;
|
||||
}
|
||||
|
||||
private readonly record struct PhotoKey(long Size, long CaptureTicks);
|
||||
|
||||
private sealed record Probe(string Key, IReadOnlyList<string> Hashes, IReadOnlyList<PhotoKey> Unhashed, string? SessionKey);
|
||||
|
||||
private sealed class Counts
|
||||
{
|
||||
public int Hashes { get; set; }
|
||||
|
||||
public int Removed { get; set; }
|
||||
|
||||
public int Unhashed { get; set; }
|
||||
|
||||
public bool SessionKey { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -47,13 +47,31 @@ public static class UploadRules
|
||||
/// <summary>
|
||||
/// The frame that stands for an upload of content the archive already has (<paramref name="copies"/>): an intact copy,
|
||||
/// the one in the upload's <paramref name="target"/> sequence first. Null when there is none, or when the target holds
|
||||
/// the content only in damaged copies: the upload's bytes repair them, whatever other sequences hold.
|
||||
/// the content only in damaged copies: the upload's bytes repair them, whatever other sequences hold. With
|
||||
/// <paramref name="intoTarget"/> (<c>StartUploadRequest.IntoTarget</c>, owner review 6, #73) only an intact copy in the
|
||||
/// target stands in: the photo is to be filed there, a copy elsewhere is no answer.
|
||||
/// </summary>
|
||||
public static Frame? StandIn(string archiveRoot, IReadOnlyList<Frame> copies, Guid? target)
|
||||
public static Frame? StandIn(string archiveRoot, IReadOnlyList<Frame> copies, Guid? target, bool intoTarget = false)
|
||||
{
|
||||
var intact = copies.Where(f => IsIntact(archiveRoot, f)).ToList();
|
||||
if (copies.Any(f => f.SequenceId == target) && !intact.Any(f => f.SequenceId == target)) return null;
|
||||
return intact.FirstOrDefault(f => f.SequenceId == target) ?? intact.FirstOrDefault();
|
||||
return intact.FirstOrDefault(f => f.SequenceId == target) ?? (intoTarget ? null : intact.FirstOrDefault());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The file the server copies into <paramref name="target"/> for an upload into it (owner review 6, #73): an intact copy
|
||||
/// held by another sequence of the served archive <paramref name="archiveId"/>, resolved under that archive's
|
||||
/// <paramref name="archiveRoot"/>. A frame of a sequence of another archive of the index (<paramref name="archiveOf"/>
|
||||
/// names each copy's sequence's archive; a desktop sharing its library keeps other archives' frames in the same index)
|
||||
/// is never a source. Null when there is none.
|
||||
/// </summary>
|
||||
public static Frame? CopySource(string archiveRoot, IReadOnlyList<Frame> copies, Guid target, Guid archiveId,
|
||||
IReadOnlyDictionary<Guid, Guid> archiveOf)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(copies);
|
||||
ArgumentNullException.ThrowIfNull(archiveOf);
|
||||
return copies.FirstOrDefault(f => f.SequenceId != target && archiveOf.TryGetValue(f.SequenceId, out var archive) && archive == archiveId
|
||||
&& IsIntact(archiveRoot, f));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -2,6 +2,8 @@ using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
@@ -56,7 +58,18 @@ public sealed class UploadService(
|
||||
if (request.Size <= 0) return Fail<StartUploadResponse>(400, "bad_request", "size");
|
||||
if (request.Size > options.MaxUploadBytes) return Fail<StartUploadResponse>(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture));
|
||||
if (request.SessionKey is { Length: > 200 }) return Fail<StartUploadResponse>(400, "bad_request", "sessionKey");
|
||||
if (request.SequenceId is { } requested && await db.Sequences.GetAsync(requested, cancellationToken) is null)
|
||||
if (request.IntoTarget)
|
||||
{
|
||||
// Authorised here, never trusted to the client (owner review 6, #73): the served archive's sequence, which the
|
||||
// caller owns or may edit, and never a tombstone dropped through a copy the server makes itself.
|
||||
if (request.SequenceId is not { } into) return Fail<StartUploadResponse>(400, "bad_request", "sequenceId");
|
||||
if (request.Restore) return Fail<StartUploadResponse>(400, "bad_request", "restore");
|
||||
if (await ServedItems.SequenceAsync(db, archive, into, cancellationToken) is not { } intoSequence)
|
||||
return Fail<StartUploadResponse>(404, "not_found", "sequence");
|
||||
if (intoSequence.OwnerUserId != caller.Id && !caller.IsAdmin && !caller.Has(Permissions.Edit))
|
||||
return Fail<StartUploadResponse>(403, "forbidden");
|
||||
}
|
||||
else if (request.SequenceId is { } requested && await db.Sequences.GetAsync(requested, cancellationToken) is null)
|
||||
return Fail<StartUploadResponse>(404, "not_found", "sequence");
|
||||
|
||||
var sha = request.Sha256.ToLowerInvariant();
|
||||
@@ -70,9 +83,16 @@ public sealed class UploadService(
|
||||
var removed = await UploadRules.RemovedFromTargetAsync(db, sha, target, copies, cancellationToken);
|
||||
if (removed && !request.Restore) return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null);
|
||||
// Only a copy that is still whole stands for the upload: a client may delete its file on this answer. A photo
|
||||
// brought back is filed into its sequence, whatever other sequences hold it.
|
||||
if (UploadRules.StandIn(archive.Root, removed ? [] : copies, target) is { } known)
|
||||
// brought back is filed into its sequence, whatever other sequences hold it. An upload into the target hears only of
|
||||
// a copy there.
|
||||
if (UploadRules.StandIn(archive.Root, removed ? [] : copies, target, request.IntoTarget) is { } known)
|
||||
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, known.Id);
|
||||
// Into a target that holds no copy, while another sequence of the served archive holds an intact one: the server
|
||||
// files its own file there, no bytes on the wire. A copy that does not read back as the request's content leaves
|
||||
// the client to send the bytes.
|
||||
if (request.IntoTarget && target is { } targetId && !copies.Any(f => f.SequenceId == targetId)
|
||||
&& await CopyIntoAsync(caller, sha, targetId, copies, cancellationToken) is { } copied)
|
||||
return copied;
|
||||
|
||||
var resumable = await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken);
|
||||
if (resumable is not null && resumable.Size == request.Size && resumable.SequenceId == request.SequenceId && store.Exists(resumable.Id))
|
||||
@@ -325,6 +345,96 @@ public sealed class UploadService(
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Files into <paramref name="target"/> the server's own file of <paramref name="sha"/> held by another sequence of the
|
||||
/// served archive (<see cref="StartUploadRequest.IntoTarget"/>, owner review 6, #73): checked against the caller's quota
|
||||
/// and the archive's room, copied to staging and read back (<see cref="VerifiedCopy"/>), its SHA-256 compared with the
|
||||
/// request's, and committed as an upload of it would be, refusing a photo the target deleted. Used bytes grow only when
|
||||
/// a new frame was filed. Null when there is no such file, or when the copy is not the request's content (a damaged
|
||||
/// source): the client then sends the bytes.
|
||||
/// </summary>
|
||||
private async Task<Outcome<StartUploadResponse>?> CopyIntoAsync(Caller caller, string sha, Guid target, IReadOnlyList<Frame> copies,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var archiveOf = new Dictionary<Guid, Guid>();
|
||||
foreach (var sequenceId in copies.Select(f => f.SequenceId).Distinct())
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sequenceId, cancellationToken) is { } sequence) archiveOf[sequenceId] = sequence.ArchiveId;
|
||||
}
|
||||
if (UploadRules.CopySource(archive.Root, copies, target, archive.Id, archiveOf) is not { } source
|
||||
|| ArchivePathGuard.ExistingFile(archive.Root, source.RelativePath) is not { } file)
|
||||
return null;
|
||||
|
||||
if (caller.User.QuotaBytes > 0)
|
||||
{
|
||||
var pending = await db.Uploads.PendingBytesAsync(caller.Id, cancellationToken);
|
||||
if (caller.User.UsedBytes + pending + source.Size > caller.User.QuotaBytes)
|
||||
return Fail<StartUploadResponse>(403, "quota_exceeded", caller.User.QuotaBytes.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
if (volumes.Measure(archive.Root) is { } volume && volume.FreeBytes < source.Size + DiskReserve)
|
||||
return Fail<StartUploadResponse>(507, "insufficient_storage");
|
||||
|
||||
// Runs to the end once started, even if the client disconnects, as a completion does.
|
||||
var stopping = lifetime.ApplicationStopping;
|
||||
var staged = Path.Combine(options.StagingPath, Guid.CreateVersion7().ToString("N") + Path.GetExtension(source.FileName).ToLowerInvariant());
|
||||
try
|
||||
{
|
||||
var copied = await VerifiedCopy.CopyAsync(file.FullName, staged, verify: true, cancellationToken: stopping);
|
||||
if (copied != sha)
|
||||
{
|
||||
logger.LogWarning("Frame {Frame} ({File}) holds SHA-256 {Actual} instead of {Expected}: not copied into sequence {Target}, the client sends the photo",
|
||||
source.Id, source.RelativePath, copied, sha, target);
|
||||
UploadStore.TryDelete(staged);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
logger.LogWarning(ex, "Frame {Frame} ({File}) could not be copied into sequence {Target}: the client sends the photo", source.Id, source.RelativePath, target);
|
||||
UploadStore.TryDelete(staged);
|
||||
return null;
|
||||
}
|
||||
|
||||
IngestResult result;
|
||||
try
|
||||
{
|
||||
result = await ingest.CommitAsync(new IngestRequest(archive.Id, target, NewSequenceTitle: null, SessionKey: null, staged,
|
||||
source.OriginalFileName ?? source.FileName, source.Size, sha, source.CapturedAt, caller.Id, RefuseRemoved: true), stopping);
|
||||
}
|
||||
catch (PhotoRemovedException)
|
||||
{
|
||||
// Deleted from the target since the start checked: it stays deleted.
|
||||
UploadStore.TryDelete(staged);
|
||||
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null);
|
||||
}
|
||||
catch (Exception ex) when (ex is LeaseUnavailableException or ArchiveOfflineException or SequenceFolderMovedException or FolderMovedException)
|
||||
{
|
||||
logger.LogWarning("Frame {Frame} not copied into sequence {Target} for now: {Reason}", source.Id, target, ex.Message);
|
||||
UploadStore.TryDelete(staged);
|
||||
return Fail<StartUploadResponse>(503, ex switch
|
||||
{
|
||||
ArchiveOfflineException => "archive_offline",
|
||||
SequenceFolderMovedException or FolderMovedException => "folder_moved",
|
||||
_ => "sequence_busy",
|
||||
});
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Copying frame {Frame} into sequence {Target} failed", source.Id, target);
|
||||
UploadStore.TryDelete(staged);
|
||||
return Fail<StartUploadResponse>(503, "commit_failed");
|
||||
}
|
||||
|
||||
if (File.Exists(staged)) UploadStore.TryDelete(staged);
|
||||
if (!result.Duplicate && !result.Repaired) await db.Users.AddUsedBytesAsync(caller.Id, source.Size, CancellationToken.None);
|
||||
if (await db.Sequences.GetAsync(result.SequenceId, CancellationToken.None) is { } filed)
|
||||
{
|
||||
await sequenceJobs.FramesAddedAsync(filed, CancellationToken.None);
|
||||
events.Publish(new SequenceChangedEvent(filed.Id, "frames", filed.FramesVersion, filed.SettingsVersion));
|
||||
}
|
||||
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, result.FrameId, Copied: true);
|
||||
}
|
||||
|
||||
private async Task FailAsync(Upload upload)
|
||||
{
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None);
|
||||
|
||||
Reference in new issue
Block a user