M1 Dati e libreria: modello, archivi SQLite con scrittore unico, nomi dei file, scrittura sicura, miniature, impronte, _febe.jsonl, copie, eliminazione e ricostruzione

Modello del dominio e interfacce degli archivi in Febe.Core; implementazione SQLite in Febe.Data (WAL, chiavi esterne, migrazioni numerate in transazione, coda di scrittura su un solo thread); logica della libreria in Febe.Core/Library; 164 prove MSTest, compresa la ricostruzione del database da una libreria di prova e la scala a 200.000 elementi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 16:06:15 +00:00
1 parent c803bd98b5
commit 3aeaa17da7
69 files changed
+12472

No files matched your search

@@ -0,0 +1,253 @@
using System.Buffers.Binary;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Data;
using SkiaSharp;
namespace Febe.Tests.Support;
/// <summary>A temporary folder removed at the end of a test.</summary>
internal sealed class TempFolder : IDisposable
{
public TempFolder(string prefix = "febe")
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "febe-prove", prefix + "-" + Guid.NewGuid().ToString("N")[..10]);
Directory.CreateDirectory(Path);
}
public string Path { get; }
public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]);
public void Dispose()
{
try
{
Directory.Delete(Path, recursive: true);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
}
/// <summary>A clock moved by hand, in Alberto's zone.</summary>
internal sealed class ManualClock(DateTimeOffset start, TimeZoneInfo? zone = null) : IClock
{
public DateTimeOffset Now { get; set; } = start;
public TimeZoneInfo LocalZone { get; } = zone ?? TestZones.Rome;
public Task Delay(TimeSpan time, CancellationToken ct)
{
Now += time;
return Task.CompletedTask;
}
}
internal static class TestZones
{
/// <summary>Europe/Rome, or an equivalent custom zone when the system has no time zone data.</summary>
public static TimeZoneInfo Rome { get; } = LoadRome();
private static TimeZoneInfo LoadRome()
{
foreach (var id in new[] { "Europe/Rome", "W. Europe Standard Time" })
{
try
{
return TimeZoneInfo.FindSystemTimeZoneById(id);
}
catch (TimeZoneNotFoundException)
{
}
catch (InvalidTimeZoneException)
{
}
}
var start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday);
var end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 5, DayOfWeek.Sunday);
var rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, TimeSpan.FromHours(1), start, end);
return TimeZoneInfo.CreateCustomTimeZone("Europe/Rome", TimeSpan.FromHours(1), "Europe/Rome", "CET", "CEST", [rule]);
}
}
/// <summary>Builders of domain records for tests.</summary>
internal static class Make
{
public static readonly DateTimeOffset T0 = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero);
public static Account Account(string username, string? instagramId = null, bool mine = false) =>
Core.Domain.Account.Create(username, StartingPoint.EverythingAndKeepUpdated, T0, TestZones.Rome, isMine: mine) with
{
InstagramId = instagramId ?? ((uint)username.GetHashCode(StringComparison.Ordinal)).ToString(System.Globalization.CultureInfo.InvariantCulture),
};
public static Entry Entry(long accountId, string instagramId, DateTimeOffset publishedAt, EntryKind kind = EntryKind.Post, string? caption = null) => new()
{
AccountId = accountId,
Kind = kind,
InstagramId = instagramId,
Code = "C" + instagramId,
PublishedAt = publishedAt,
Caption = caption,
DiscoveredAt = T0,
};
public static Media Photo(int position = 1, MediaState state = MediaState.ToDownload) =>
new() { Position = position, Kind = MediaKind.Photo, State = state, Width = 1080, Height = 1350 };
public static Media Video(int position = 1, MediaState state = MediaState.ToDownload) =>
new() { Position = position, Kind = MediaKind.Video, State = state, Width = 1080, Height = 1920, Duration = TimeSpan.FromSeconds(15) };
public static Media Stored(Media media, string sha, string path) =>
media with { State = MediaState.Downloaded, Sha256 = sha, RelativePath = path, Bytes = 1000 };
public static string Sha(int n) => n.ToString("x64", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>Opens test databases.</summary>
internal static class TestDatabase
{
public static Task<FebeDatabase> OpenAsync(TempFolder folder, string name = "dati") => FebeDatabase.OpenAsync(folder.Combine(name));
}
/// <summary>Generated images: «photos» made of gradients, shapes, lines and grain, reproducible from a seed.</summary>
internal static class TestImages
{
public static SKBitmap Scene(int seed, int width = 1200, int height = 900)
{
var random = new Random(seed);
var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(bitmap);
SKColor RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));
using (var background = new SKPaint())
{
var angle = random.NextDouble() * Math.PI * 2;
var dx = (float)Math.Cos(angle) * width / 2;
var dy = (float)Math.Sin(angle) * height / 2;
background.Shader = SKShader.CreateLinearGradient(
new SKPoint((width / 2f) - dx, (height / 2f) - dy),
new SKPoint((width / 2f) + dx, (height / 2f) + dy),
[RandomColor(), RandomColor(), RandomColor()],
null,
SKShaderTileMode.Clamp);
canvas.DrawRect(0, 0, width, height, background);
}
using var paint = new SKPaint { IsAntialias = true };
var shapes = 10 + random.Next(10);
for (var i = 0; i < shapes; i++)
{
paint.Color = RandomColor().WithAlpha((byte)(160 + random.Next(96)));
paint.Style = random.Next(4) == 0 ? SKPaintStyle.Stroke : SKPaintStyle.Fill;
paint.StrokeWidth = 4 + random.Next(30);
var x = (float)(random.NextDouble() * width);
var y = (float)(random.NextDouble() * height);
var w = (float)((0.05 + (random.NextDouble() * 0.4)) * width);
var h = (float)((0.05 + (random.NextDouble() * 0.4)) * height);
switch (random.Next(4))
{
case 0:
canvas.DrawRect(x - (w / 2), y - (h / 2), w, h, paint);
break;
case 1:
canvas.DrawCircle(x, y, Math.Min(w, h) / 2, paint);
break;
case 2:
canvas.DrawOval(new SKRect(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2)), paint);
break;
default:
paint.StrokeWidth = 6 + random.Next(20);
canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), paint);
break;
}
}
// Fine grain, as in a photo.
using var grain = new SKPaint { IsAntialias = false };
for (var i = 0; i < width * height / 60; i++)
{
var v = (byte)random.Next(256);
grain.Color = new SKColor(v, v, v, 28);
canvas.DrawPoint(random.Next(width), random.Next(height), grain);
}
return bitmap;
}
public static byte[] Jpeg(SKBitmap bitmap, int quality = 90)
{
using var image = SKImage.FromBitmap(bitmap);
using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality);
return data.ToArray();
}
public static byte[] Png(SKBitmap bitmap)
{
using var image = SKImage.FromBitmap(bitmap);
using var data = image.Encode(SKEncodedImageFormat.Png, 100);
return data.ToArray();
}
public static SKBitmap Resize(SKBitmap source, int width, int height)
{
var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(result);
using var image = SKImage.FromBitmap(source);
canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
return result;
}
public static SKBitmap Crop(SKBitmap source, SKRectI area)
{
var result = new SKBitmap(new SKImageInfo(area.Width, area.Height, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(result);
using var image = SKImage.FromBitmap(source);
canvas.DrawImage(image, area, new SKRect(0, 0, area.Width, area.Height), new SKSamplingOptions(SKFilterMode.Nearest), null);
return result;
}
/// <summary>Decodes a JPEG/PNG back to a bitmap.</summary>
public static SKBitmap Decode(byte[] encoded) => SKBitmap.Decode(encoded) ?? throw new InvalidOperationException("decode");
/// <summary>Rotates pixels 90° counter-clockwise (what a camera stores before tagging orientation 6).</summary>
public static SKBitmap RotateCounterClockwise(SKBitmap source)
{
var result = new SKBitmap(new SKImageInfo(source.Height, source.Width, SKColorType.Rgba8888, SKAlphaType.Premul));
using var canvas = new SKCanvas(result);
canvas.Translate(0, source.Width);
canvas.RotateDegrees(-90);
canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null);
return result;
}
/// <summary>Inserts an EXIF APP1 segment with the given orientation right after the SOI marker of a JPEG.</summary>
public static byte[] WithExifOrientation(byte[] jpeg, ushort orientation)
{
if (jpeg.Length < 2 || jpeg[0] != 0xFF || jpeg[1] != 0xD8)
{
throw new ArgumentException("Not a JPEG.", nameof(jpeg));
}
var app1 = new byte[36];
app1[0] = 0xFF;
app1[1] = 0xE1;
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(2), 34); // length, including these two bytes
"Exif\0\0"u8.CopyTo(app1.AsSpan(4));
"MM\0*"u8.CopyTo(app1.AsSpan(10)); // TIFF header, big endian
BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(14), 8); // offset of IFD0
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(18), 1); // one entry
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(20), 0x0112); // Orientation
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(22), 3); // SHORT
BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(24), 1); // count
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(28), orientation);
BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(32), 0); // no next IFD
return [.. jpeg.AsSpan(0, 2), .. app1, .. jpeg.AsSpan(2)];
}
}
+96
View File
@@ -0,0 +1,96 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Data;
namespace Febe.Tests.Support;
/// <summary>A library with its Data folder, database and services, in a temporary folder.</summary>
internal sealed class TestLibrary : IAsyncDisposable
{
private TestLibrary(TempFolder temp, FebeDatabase db, ManualClock clock)
{
Temp = temp;
Db = db;
Clock = clock;
Data = new DataFolderLayout(temp.Combine("dati"));
Layout = new LibraryLayout(temp.Combine("libreria"));
Thumbnails = new ThumbnailStore(Data.Thumbnails);
Index = new PerceptualHashIndex();
Journal = new AccountJournal(clock);
Ingest = new LibraryIngest(db, Layout, LibraryNaming.Default, Journal, clock, Thumbnails, Index);
}
public TempFolder Temp { get; }
public FebeDatabase Db { get; private set; }
public ManualClock Clock { get; }
public DataFolderLayout Data { get; }
public LibraryLayout Layout { get; }
public ThumbnailStore Thumbnails { get; }
public PerceptualHashIndex Index { get; }
public AccountJournal Journal { get; }
public LibraryIngest Ingest { get; private set; }
public static async Task<TestLibrary> CreateAsync(TempFolder temp)
{
var db = await FebeDatabase.OpenAsync(temp.Combine("dati"));
return new TestLibrary(temp, db, new ManualClock(Make.T0));
}
/// <summary>Records an entry and stores its files as the collection pipeline would, then writes the journal line.</summary>
public async Task<EntryWithMedia> SaveAsync(Account account, Entry entry, IReadOnlyList<TestFile> files, string? highlightTitle = null)
{
var added = await Db.Entries.AddAsync(entry, files.Select(f => f.Media).ToList());
foreach (var (media, file) in added.Stored.Media.Zip(files.OrderBy(f => f.Media.Position)))
{
await Ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(file.Bytes), Extension = file.Extension }, highlightTitle);
}
await Ingest.AppendJournalAsync(added.Stored.Entry.Id);
return (await Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!;
}
/// <summary>Simulates the loss of the database: closes it, deletes the file and opens an empty one.</summary>
public async Task LoseDatabaseAsync()
{
await Db.DisposeAsync();
foreach (var suffix in new[] { string.Empty, "-wal", "-shm" })
{
File.Delete(Data.Database + suffix);
}
Db = await FebeDatabase.OpenAsync(Data.Root);
Ingest = new LibraryIngest(Db, Layout, LibraryNaming.Default, Journal, Clock, Thumbnails, Index);
}
public ValueTask DisposeAsync() => Db.DisposeAsync();
}
/// <summary>A file to store: its record and its bytes.</summary>
internal sealed record TestFile(Media Media, byte[] Bytes, string Extension)
{
private static int videoSeed;
public static TestFile Photo(int position, int scene, int width = 1080, int height = 1350) =>
new(Make.Photo(position), PhotoBytes(scene, width, height), ".jpg");
public static TestFile Video(int position, int size = 50_000)
{
var bytes = new byte[size];
new Random(Interlocked.Increment(ref videoSeed)).NextBytes(bytes);
return new TestFile(Make.Video(position), bytes, ".mp4");
}
public static byte[] PhotoBytes(int scene, int width = 1080, int height = 1350)
{
using var bitmap = TestImages.Scene(scene, width, height);
return TestImages.Jpeg(bitmap, 88);
}
}