feat(server): API v1 with auth, uploads, sync, jobs, render nodes and events
- Security: PBKDF2-SHA512 (210,000 iterations) hashes, opaque bearer tokens stored as SHA-256 with sliding expiry and revocation, HttpOnly/Secure/ SameSite=Strict admin cookie with a session-bound CSRF token, sign-in rate limit and lockout, role/permission metadata on every endpoint, audit log, first-run administrator bootstrap. - Sequences with keyset paging, ETags and settings_version conflicts; sync manifest; frames, proxies, thumbnails and exports streamed with Range. - Chunked resumable uploads with hash short-circuit, quota and disk checks, staging on the archive volume, SHA-256 verification and IArchiveIngest. - Job engine host, jobs API, render nodes with heartbeat timeout and reassignment, WebSocket events, LAN discovery beacon, upload cleanup. - Windows service host over advapi32 (--service, --install-service, --uninstall-service); fails fast without the archive module services. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
56 files changed
+4726
-108
No files matched your search
@@ -0,0 +1,313 @@
|
||||
using System.Buffers.Text;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Events;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/sequences</c>: library listing with filters and keyset paging, detail with ETag, edits with
|
||||
/// <c>settings_version</c> optimistic concurrency, the sync manifest, frames, analysis, statistics and renders.
|
||||
/// </summary>
|
||||
public static class SequenceEndpoints
|
||||
{
|
||||
private const int MaxTitle = 200;
|
||||
private const int MaxNotes = 2000;
|
||||
private const int MaxTags = 50;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
// Uploaders list sequences to pick an upload target.
|
||||
var sequences = api.MapGroup("/sequences").Requires(Permissions.Read | Permissions.Upload);
|
||||
sequences.MapGet("", ListAsync);
|
||||
sequences.MapPost("", CreateAsync).Requires(Permissions.Upload | Permissions.Edit);
|
||||
sequences.MapGet("/{id:guid}", GetAsync);
|
||||
sequences.MapPatch("/{id:guid}", UpdateAsync).Requires(Permissions.Edit);
|
||||
sequences.MapDelete("/{id:guid}", DeleteAsync).Requires(Permissions.Delete);
|
||||
sequences.MapGet("/{id:guid}/manifest", ManifestAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/frames", FramesAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/analysis", AnalysisAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read);
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status,
|
||||
string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller)
|
||||
{
|
||||
if (!TryParseStatus(status, out var with, out var without)) return ApiErrors.BadRequest(context, "invalid_filter", "status");
|
||||
if (!TryParseSort(sort, out var order)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
|
||||
Guid? ownerId = null;
|
||||
if (owner == "me") ownerId = caller.Id;
|
||||
else if (owner is not null && Guid.TryParse(owner, out var parsed)) ownerId = parsed;
|
||||
else if (owner is not null) return ApiErrors.BadRequest(context, "invalid_filter", "owner");
|
||||
|
||||
var query = new SequenceQuery
|
||||
{
|
||||
ArchiveId = archive.Id,
|
||||
Year = year,
|
||||
Camera = string.IsNullOrWhiteSpace(camera) ? null : camera,
|
||||
WithStatus = with,
|
||||
WithoutStatus = without,
|
||||
Tag = string.IsNullOrWhiteSpace(tag) ? null : tag,
|
||||
Text = string.IsNullOrWhiteSpace(q) ? null : q,
|
||||
OwnerUserId = ownerId,
|
||||
Sort = order,
|
||||
Limit = limit ?? 100,
|
||||
Cursor = string.IsNullOrEmpty(cursor) ? null : cursor,
|
||||
};
|
||||
var page = await db.Sequences.ListAsync(query, context.RequestAborted);
|
||||
long? total = query.Cursor is null ? await db.Sequences.CountAsync(query, context.RequestAborted) : null;
|
||||
return Results.Json(new Titano.Protocol.Page<SequenceDto>([.. page.Items.Select(Dto.Sequence)], page.NextCursor, total), ProtocolJson.Default.PageSequenceDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateSequenceRequest request, TitanoDatabase db, ServerArchive archive,
|
||||
AuditLog audit, EventHub events, TimeProvider time)
|
||||
{
|
||||
var title = request.Title?.Trim();
|
||||
if (title is { Length: > MaxTitle }) return ApiErrors.BadRequest(context, "bad_request", "title");
|
||||
var hint = request.CameraHint?.Trim();
|
||||
var sequence = new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = archive.Id,
|
||||
Title = string.IsNullOrEmpty(title) ? null : title,
|
||||
// Placed in the archive by the ingest when its first frame arrives.
|
||||
Folder = string.Empty,
|
||||
CameraModel = string.IsNullOrEmpty(hint) ? null : hint[..Math.Min(hint.Length, MaxTitle)],
|
||||
Origin = SequenceOrigin.Server,
|
||||
SyncState = SyncState.InSync,
|
||||
OwnerUserId = caller.Id,
|
||||
UpdatedAt = time.GetUtcNow(),
|
||||
};
|
||||
await db.Sequences.UpsertAsync(sequence, context.RequestAborted);
|
||||
await audit.WriteAsync(caller, context, "sequence_created", "sequence", sequence.Id.ToString(), sequence.DisplayTitle);
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "created", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
context.Response.Headers.ETag = ETag(sequence);
|
||||
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto, statusCode: StatusCodes.Status201Created);
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
var etag = ETag(sequence);
|
||||
if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified);
|
||||
context.Response.Headers.ETag = etag;
|
||||
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateSequenceRequest request, TitanoDatabase db,
|
||||
AuditLog audit, EventHub events)
|
||||
{
|
||||
if (request.Title is { Length: > MaxTitle }) return ApiErrors.BadRequest(context, "bad_request", "title");
|
||||
if (request.Notes is { Length: > MaxNotes }) return ApiErrors.BadRequest(context, "bad_request", "notes");
|
||||
if (request.Rating is < 0 or > 5) return ApiErrors.BadRequest(context, "bad_request", "rating");
|
||||
if (request.Tags is { } tags && (tags.Count > MaxTags || tags.Any(t => t is null || t.Trim().Length > TagRepository.MaxLength)))
|
||||
return ApiErrors.BadRequest(context, "bad_request", "tags");
|
||||
if (request.SettingsJson is not null && !IsJson(request.SettingsJson)) return ApiErrors.BadRequest(context, "invalid_settings");
|
||||
|
||||
var expected = request.ExpectedSettingsVersion ?? IfMatchVersion(context);
|
||||
var edit = new SequenceEdit { Title = request.Title, Tags = request.Tags, Rating = request.Rating, Notes = request.Notes, SettingsJson = request.SettingsJson };
|
||||
var result = await db.Sequences.EditAsync(id, edit, expected, context.RequestAborted);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case SequenceEditOutcome.NotFound:
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
case SequenceEditOutcome.Conflict:
|
||||
context.Response.Headers.ETag = ETag(result.Sequence!);
|
||||
return ApiErrors.Conflict(context, "settings_conflict", result.Sequence!.SettingsVersion.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
var sequence = result.Sequence!;
|
||||
await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), Changes(request));
|
||||
events.Publish(new SequenceChangedEvent(id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
context.Response.Headers.ETag = ETag(sequence);
|
||||
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a sequence from the index and moves its folder into the archive's trash (BRIEF §0.2 rule 8: nothing is
|
||||
/// erased). <c>?dryRun=true</c> only reports what would happen. Owners and admins only.
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, ServerArchive archive,
|
||||
ServerOptions options, AuditLog audit, EventHub events)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
|
||||
var folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePaths.Resolve(archive.Root, sequence.Folder);
|
||||
var trash = Path.Combine(options.TrashPath, id.ToString("N"));
|
||||
var hasFolder = folder is not null && Directory.Exists(folder);
|
||||
var plan = new SequenceDeletePlan(id, sequence.Folder, hasFolder ? Path.GetRelativePath(archive.Root, trash).Replace('\\', '/') : null,
|
||||
sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true);
|
||||
if (dryRun == true) return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
|
||||
|
||||
if (hasFolder)
|
||||
{
|
||||
Directory.CreateDirectory(options.TrashPath);
|
||||
Directory.Move(folder!, trash);
|
||||
}
|
||||
await db.Sequences.DeleteAsync(id, context.RequestAborted);
|
||||
await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", id.ToString(), sequence.DisplayTitle);
|
||||
events.Publish(new SequenceChangedEvent(id, "deleted", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
|
||||
}
|
||||
|
||||
/// <summary>Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5); ETag over the version counters.</summary>
|
||||
private static async Task<IResult> ManifestAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
var etag = string.Create(CultureInfo.InvariantCulture, $"\"m{sequence.SettingsVersion}-{sequence.FramesVersion}-{sequence.RenderedCount}\"");
|
||||
if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified);
|
||||
|
||||
var hasProxy = sequence.Status.HasFlag(SequenceStatus.ProxiesBuilt);
|
||||
var hasThumb = sequence.Status.HasFlag(SequenceStatus.ThumbsBuilt);
|
||||
var frames = new List<ManifestFrame>(sequence.FrameCount);
|
||||
var after = -1;
|
||||
while (true)
|
||||
{
|
||||
var batch = await db.Frames.ListBySequenceAsync(id, after, 1000, ct);
|
||||
frames.AddRange(batch.Select(f => new ManifestFrame(f.Id, f.Index, f.FileName, f.Size, f.Sha256 ?? string.Empty, hasProxy, hasThumb)));
|
||||
if (batch.Count < 1000) break;
|
||||
after = batch[^1].Index;
|
||||
}
|
||||
var renders = await db.Renders.ListBySequenceAsync(id, ct);
|
||||
context.Response.Headers.ETag = etag;
|
||||
return Results.Json(new SequenceManifest(id, sequence.FramesVersion, sequence.SettingsVersion, sequence.SettingsJson, sequence.Tags, frames,
|
||||
[.. renders.Select(Dto.Render)]), ProtocolJson.Default.SequenceManifest);
|
||||
}
|
||||
|
||||
private static async Task<IResult> FramesAsync(HttpContext context, Guid id, string? cursor, int? limit, TitanoDatabase db)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Sequences.GetAsync(id, ct) is null) return ApiErrors.NotFound(context, "sequence");
|
||||
var after = -1;
|
||||
if (!string.IsNullOrEmpty(cursor) && !FrameCursor.TryDecode(cursor, out after)) return ApiErrors.BadRequest(context, "invalid_cursor");
|
||||
var take = Math.Clamp(limit ?? 500, 1, 1000);
|
||||
var frames = await db.Frames.ListBySequenceAsync(id, after, take, ct);
|
||||
var next = frames.Count == take ? FrameCursor.Encode(frames[^1].Index) : null;
|
||||
return Results.Json(new Titano.Protocol.Page<FrameDto>([.. frames.Select(Dto.Frame)], next, null), ProtocolJson.Default.PageFrameDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> AnalysisAsync(HttpContext context, Guid id, TitanoDatabase db) =>
|
||||
await db.Sequences.GetAsync(id, context.RequestAborted) switch
|
||||
{
|
||||
null => ApiErrors.NotFound(context, "sequence"),
|
||||
{ AnalysisJson: { } json } => Results.Text(json, "application/json; charset=utf-8"),
|
||||
_ => ApiErrors.NotFound(context, "analysis"),
|
||||
};
|
||||
|
||||
private static async Task<IResult> StatsAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } s) return ApiErrors.NotFound(context, "sequence");
|
||||
var stats = await db.Frames.GetSequenceStatsAsync(id, context.RequestAborted);
|
||||
return Results.Json(new SequenceStatsDto(
|
||||
id, s.FrameCount, s.TotalBytes, s.FirstCapture, s.LastCapture, s.MedianInterval,
|
||||
[.. stats.ByFormat.Select(f => new KeyValueCount(f.Format.ToString().ToLowerInvariant(), f.Photos, f.Bytes))],
|
||||
stats.Missing, stats.Corrupt, stats.Duplicate, stats.Excluded), ProtocolJson.Default.SequenceStatsDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> RendersAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is null) return ApiErrors.NotFound(context, "sequence");
|
||||
var renders = await db.Renders.ListBySequenceAsync(id, context.RequestAborted);
|
||||
return Results.Json(renders.Select(Dto.Render).ToList(), ProtocolJson.Default.ListRenderDto);
|
||||
}
|
||||
|
||||
/// <summary>Changes whenever anything the sequence representation shows changes (versions, status, statistics).</summary>
|
||||
private static string ETag(Sequence s) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"\"{s.SettingsVersion}-{s.FramesVersion}-{s.UpdatedAt.UtcTicks}\"");
|
||||
|
||||
/// <summary>The settings version named by an <c>If-Match</c> ETag of <see cref="ETag"/>, if any.</summary>
|
||||
private static int? IfMatchVersion(HttpContext context)
|
||||
{
|
||||
var header = context.Request.Headers.IfMatch.ToString().Trim('"', ' ');
|
||||
var dash = header.IndexOf('-', StringComparison.Ordinal);
|
||||
return dash > 0 && int.TryParse(header.AsSpan(0, dash), NumberStyles.None, CultureInfo.InvariantCulture, out var version) ? version : null;
|
||||
}
|
||||
|
||||
private static bool TryParseStatus(string? text, out SequenceStatus with, out SequenceStatus without)
|
||||
{
|
||||
with = without = SequenceStatus.None;
|
||||
if (string.IsNullOrWhiteSpace(text)) return true;
|
||||
foreach (var part in text.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
var clear = part.StartsWith('-');
|
||||
var name = clear ? part[1..] : part;
|
||||
var flag = Enum.GetValues<SequenceStatus>().FirstOrDefault(v => v != SequenceStatus.None && v.ToString().Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (flag == SequenceStatus.None) return false;
|
||||
if (clear) without |= flag;
|
||||
else with |= flag;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryParseSort(string? text, out SequenceSort sort)
|
||||
{
|
||||
sort = SequenceSort.Newest;
|
||||
if (string.IsNullOrEmpty(text)) return true;
|
||||
foreach (var candidate in Enum.GetValues<SequenceSort>())
|
||||
{
|
||||
if (candidate.ToString().Equals(text, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
sort = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsJson(string text)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var _ = JsonDocument.Parse(text);
|
||||
return true;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Changes(UpdateSequenceRequest r)
|
||||
{
|
||||
var fields = new List<string>();
|
||||
if (r.Title is not null) fields.Add("title");
|
||||
if (r.Tags is not null) fields.Add("tags");
|
||||
if (r.Rating is not null) fields.Add("rating");
|
||||
if (r.Notes is not null) fields.Add("notes");
|
||||
if (r.SettingsJson is not null) fields.Add("settings");
|
||||
return string.Join(", ", fields);
|
||||
}
|
||||
|
||||
/// <summary>Opaque cursor of the frame listing: the index of the last frame returned.</summary>
|
||||
private static class FrameCursor
|
||||
{
|
||||
private const string Prefix = "frames|";
|
||||
|
||||
public static string Encode(int index) =>
|
||||
Base64Url.EncodeToString(Encoding.UTF8.GetBytes(Prefix + index.ToString(CultureInfo.InvariantCulture)));
|
||||
|
||||
public static bool TryDecode(string cursor, out int index)
|
||||
{
|
||||
index = -1;
|
||||
try
|
||||
{
|
||||
var text = Encoding.UTF8.GetString(Base64Url.DecodeFromChars(cursor));
|
||||
return text.StartsWith(Prefix, StringComparison.Ordinal)
|
||||
&& int.TryParse(text.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out index);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user