- 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
148 lines
6.5 KiB
C#
148 lines
6.5 KiB
C#
using System.Collections.Concurrent;
|
|
using Titano.Core.Model;
|
|
using Titano.Data;
|
|
using Titano.Data.Archiving;
|
|
using Titano.Data.Jobs;
|
|
using Titano.Server.Storage;
|
|
|
|
namespace Titano.Server.Tests;
|
|
|
|
/// <summary>
|
|
/// Stand-in for the archive module's ingest: files staged uploads as <c><folder>/originals/<name></c>, one
|
|
/// sequence per session key, and records every request it received.
|
|
/// </summary>
|
|
public sealed class FakeArchiveIngest(TitanoDatabase db) : IArchiveIngest
|
|
{
|
|
private readonly ConcurrentDictionary<string, Guid> _sessions = new(StringComparer.Ordinal);
|
|
private readonly SemaphoreSlim _gate = new(1, 1);
|
|
|
|
public ConcurrentQueue<IngestRequest> Requests { get; } = new();
|
|
|
|
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
|
|
{
|
|
Requests.Enqueue(request);
|
|
await _gate.WaitAsync(cancellationToken);
|
|
try
|
|
{
|
|
var archive = (await db.Archives.GetAsync(request.ArchiveId, cancellationToken))!;
|
|
var sequence = await SequenceForAsync(request, archive, cancellationToken);
|
|
var existing = (await db.Frames.FindBySha256Async(request.Sha256, cancellationToken)).FirstOrDefault(f => f.SequenceId == sequence.Id);
|
|
if (existing is not null)
|
|
{
|
|
File.Delete(request.StagedPath);
|
|
return new IngestResult(sequence.Id, existing.Id, existing.Index, existing.RelativePath, Duplicate: true);
|
|
}
|
|
var index = sequence.FrameCount;
|
|
var relative = $"{sequence.Folder}/originals/{index:D4}_{request.OriginalFileName}";
|
|
var target = Path.Combine(archive.RootPath, relative);
|
|
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
|
File.Move(request.StagedPath, target);
|
|
var frame = new Frame
|
|
{
|
|
Id = Guid.CreateVersion7(),
|
|
SequenceId = sequence.Id,
|
|
Index = index,
|
|
RelativePath = relative,
|
|
FileName = Path.GetFileName(relative),
|
|
OriginalFileName = request.OriginalFileName,
|
|
Size = request.Size,
|
|
Sha256 = request.Sha256,
|
|
CapturedAt = request.ClientCapturedAt,
|
|
};
|
|
await db.Frames.InsertAsync(frame, cancellationToken);
|
|
await db.Sequences.RefreshStatsAsync(sequence.Id, cancellationToken);
|
|
return new IngestResult(sequence.Id, frame.Id, index, relative, Duplicate: false);
|
|
}
|
|
finally
|
|
{
|
|
_gate.Release();
|
|
}
|
|
}
|
|
|
|
private async Task<Sequence> SequenceForAsync(IngestRequest request, Archive archive, CancellationToken cancellationToken)
|
|
{
|
|
Sequence? sequence = null;
|
|
if (request.SequenceId is { } id) sequence = await db.Sequences.GetAsync(id, cancellationToken);
|
|
else if (request.SessionKey is { } key && _sessions.TryGetValue(key, out var known)) sequence = await db.Sequences.GetAsync(known, cancellationToken);
|
|
if (sequence is null)
|
|
{
|
|
sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = archive.Id, Folder = string.Empty, Title = request.NewSequenceTitle, OwnerUserId = request.UserId };
|
|
if (request.SessionKey is { } key) _sessions[key] = sequence.Id;
|
|
}
|
|
if (string.IsNullOrEmpty(sequence.Folder))
|
|
{
|
|
sequence = sequence with { Folder = $"2026/{sequence.Id:N}", UpdatedAt = DateTimeOffset.UtcNow };
|
|
await db.Sequences.UpsertAsync(sequence, cancellationToken);
|
|
}
|
|
return sequence;
|
|
}
|
|
}
|
|
|
|
/// <summary>Proxies at <c><folder>/proxies/NNNN.jpg</c>; thumbnails as 64-byte slots of <c><folder>/.titano/thumbs.pack</c>.</summary>
|
|
public sealed class FakeAssetLocator : IFrameAssetLocator
|
|
{
|
|
public const int ThumbnailSize = 64;
|
|
|
|
/// <summary>When set, every lookup answers this location (path traversal tests).</summary>
|
|
public AssetLocation? Override { get; set; }
|
|
|
|
public ValueTask<AssetLocation?> LocateAsync(Archive archive, Sequence sequence, Frame frame, FrameAsset asset, CancellationToken cancellationToken)
|
|
{
|
|
if (Override is not null) return ValueTask.FromResult<AssetLocation?>(Override);
|
|
var folder = Path.Combine(archive.RootPath, sequence.Folder);
|
|
AssetLocation? location = asset == FrameAsset.Proxy
|
|
? new AssetLocation(Path.Combine(folder, "proxies", $"{frame.Index:D4}.jpg"), 0, -1, "image/jpeg")
|
|
: new AssetLocation(Path.Combine(folder, ".titano", "thumbs.pack"), (long)frame.Index * ThumbnailSize, ThumbnailSize, "image/jpeg");
|
|
if (!File.Exists(location.Path)) return ValueTask.FromResult<AssetLocation?>(null);
|
|
if (location.Length < 0) location = location with { Length = new FileInfo(location.Path).Length };
|
|
return ValueTask.FromResult<AssetLocation?>(location);
|
|
}
|
|
}
|
|
|
|
/// <summary>A clock tests move by hand (token expiry, heartbeat timeouts).</summary>
|
|
public sealed class ManualTimeProvider : TimeProvider
|
|
{
|
|
private long _ticks = DateTimeOffset.UtcNow.UtcTicks;
|
|
|
|
public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero);
|
|
|
|
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A job handler that reports progress and then waits until <see cref="Release"/> (or cancellation), so tests can
|
|
/// observe running, paused and cancelled states.
|
|
/// </summary>
|
|
public sealed class BlockingJobHandler(JobKind kind) : IJobHandler
|
|
{
|
|
private TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
public JobKind Kind => kind;
|
|
|
|
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
/// <summary>When set, the next run fails with this message.</summary>
|
|
public string? FailWith { get; set; }
|
|
|
|
public void Release() => _release.TrySetResult();
|
|
|
|
public async Task RunAsync(JobContext context)
|
|
{
|
|
await context.ReportAsync(1, 4, "started");
|
|
Started.TrySetResult();
|
|
if (FailWith is { } message)
|
|
{
|
|
FailWith = null;
|
|
throw new InvalidOperationException(message);
|
|
}
|
|
for (var i = 2; i <= 3; i++)
|
|
{
|
|
await Task.Delay(50, context.Cancellation);
|
|
await context.ReportAsync(i, 4);
|
|
}
|
|
await _release.Task.WaitAsync(context.Cancellation);
|
|
_release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
await context.ReportAsync(4, 4);
|
|
}
|
|
}
|