Files
Chronos/tests/Chronos.Server.Tests/Fakes.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-23 12:45:18 +02:00

148 lines
6.5 KiB
C#

using System.Collections.Concurrent;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Server.Storage;
namespace Chronos.Server.Tests;
/// <summary>
/// Stand-in for the archive module's ingest: files staged uploads as <c>&lt;folder&gt;/originals/&lt;name&gt;</c>, one
/// sequence per session key, and records every request it received.
/// </summary>
public sealed class FakeArchiveIngest(ChronosDatabase 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>&lt;folder&gt;/proxies/NNNN.jpg</c>; thumbnails as 64-byte slots of <c>&lt;folder&gt;/.chronos/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, ".chronos", "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);
}
}