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

+228
View File
@@ -0,0 +1,228 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using static Febe.Data.Stores.EntryMapping;
namespace Febe.Data.Stores;
internal sealed class MediaStore(FebeDatabase db) : IMediaStore
{
public Task<Media?> GetAsync(long mediaId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
using var r = c.Command($"SELECT {MediaColumns} FROM media m WHERE m.id = @id").With("@id", mediaId).ExecuteReader();
return r.Read() ? ReadMedia(r) : null;
},
ct);
public Task<IReadOnlyList<Media>> ListByEntryAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<Media>>(c => ReadMediaOf(sql => c.Command(sql), entryId), ct);
public Task<IReadOnlyList<MediaLocation>> FindBySha256Async(string sha256, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sha256);
var key = sha256.Trim().ToLowerInvariant();
return db.ReadAsync<IReadOnlyList<MediaLocation>>(
c =>
{
using var r = c.Command($"""
SELECT {MediaColumns}, {EntryColumns}, a.username
FROM media m JOIN entry e ON e.id = m.entry_id JOIN account a ON a.id = e.account_id
WHERE m.sha256 = @h ORDER BY m.id
""").With("@h", key).ExecuteReader();
var list = new List<MediaLocation>();
while (r.Read())
{
list.Add(new MediaLocation(ReadMedia(r), ReadEntry(r, MediaColumnCount), r.GetString(MediaColumnCount + EntryColumnCount)));
}
return list;
},
ct);
}
public Task<IReadOnlyDictionary<string, long>> MapPathsAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<string, long>>(
c =>
{
using var r = c.Command("""
SELECT m.relative_path, m.entry_id FROM media m JOIN entry e ON e.id = m.entry_id
WHERE e.account_id = @a AND m.relative_path IS NOT NULL
""").With("@a", accountId).ExecuteReader();
var map = new Dictionary<string, long>(StringComparer.Ordinal);
while (r.Read())
{
map[r.GetString(0)] = r.GetInt64(1);
}
return map;
},
ct);
public Task<IReadOnlyList<PerceptualHashRecord>> LoadPerceptualHashesAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<PerceptualHashRecord>>(
c =>
{
// One pass over media in table order with a key lookup per row: CROSS JOIN keeps media as the outer loop
// and the unary + keeps SQLite off the phash and state indexes, which would turn the pass into random
// reads once ANALYZE statistics exist (several times slower on 200,000 files).
using var r = c.Command("""
SELECT m.id, e.account_id, m.phash FROM media m CROSS JOIN entry e ON e.id = m.entry_id
WHERE +m.phash IS NOT NULL AND +m.state IN ('Downloaded', 'Imported')
""").ExecuteReader();
var list = new List<PerceptualHashRecord>();
while (r.Read())
{
list.Add(new PerceptualHashRecord(r.GetInt64(0), r.GetInt64(1), unchecked((ulong)r.GetInt64(2))));
}
return list;
},
ct);
public Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<PendingDownload>>(
c =>
{
using var r = c.Command($"""
SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted'
ORDER BY (e.kind = 'Story') DESC, e.expires_at IS NULL, e.expires_at, e.discovered_at, m.entry_id, m.position
LIMIT @limit
""").With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader();
var list = new List<PendingDownload>();
while (r.Read())
{
var o = MediaColumnCount;
list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum<EntryKind>(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3)));
}
return list;
},
ct);
public Task<int> CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var command = accountId is { } a
? c.Command("""
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted' AND e.account_id = @a
""").With("@a", a)
: c.Command("""
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.state = 'ToDownload' AND e.state <> 'Deleted'
""");
return (int)command.ScalarInt64();
},
ct);
public Task MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(file);
if (!EntryStateRules.IsPresent(state))
{
throw new ArgumentException("Un file salvato è «scaricato» o «importato».", nameof(state));
}
return db.WriteAsync(
w =>
{
var entryId = EntryOf(w, mediaId);
w.Command("""
UPDATE media SET state = @state, relative_path = @path, bytes = @bytes, sha256 = @sha, phash = @phash,
width = COALESCE(@w, width), height = COALESCE(@h, height), duration_ms = COALESCE(@d, duration_ms),
has_thumbnail = @thumb, downloaded_at = @at, last_error = NULL, source_url = NULL, cover_url = NULL
WHERE id = @id
""")
.With("@state", Sql.Enum(state))
.With("@path", file.RelativePath)
.With("@bytes", file.Bytes)
.With("@sha", file.Sha256.ToLowerInvariant())
.With("@phash", Sql.Hash(file.PerceptualHash))
.With("@w", Sql.Int(file.Width))
.With("@h", Sql.Int(file.Height))
.With("@d", Sql.Duration(file.Duration))
.With("@thumb", Sql.Bool(file.HasThumbnail))
.With("@at", Sql.Time(at))
.With("@id", mediaId)
.ExecuteNonQuery();
RecomputeState(w, entryId, at);
},
ct);
}
public Task MarkFailedAsync(long mediaId, MediaState state, string? error, DateTimeOffset at, CancellationToken ct = default)
{
if (state is not (MediaState.Failed or MediaState.Expired or MediaState.Skipped or MediaState.ToDownload))
{
throw new ArgumentException("Uno scaricamento non riuscito porta a «fallito», «scaduto», «saltato» o di nuovo «da scaricare».", nameof(state));
}
return db.WriteAsync(
w =>
{
var entryId = EntryOf(w, mediaId);
w.Command("UPDATE media SET state = @state, last_error = @error, attempts = attempts + 1 WHERE id = @id")
.With("@state", Sql.Enum(state))
.With("@error", Sql.Text(error))
.With("@id", mediaId)
.ExecuteNonQuery();
RecomputeState(w, entryId, at);
},
ct);
}
public Task UpdateSourceAsync(long mediaId, string? sourceUrl, string? coverUrl, DateTimeOffset seenAt, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var entryId = EntryOf(w, mediaId);
w.Command("""
UPDATE media SET source_url = @u, cover_url = COALESCE(@c, cover_url), source_seen_at = @at,
state = CASE WHEN state IN ('Expired', 'Failed') THEN 'ToDownload' ELSE state END
WHERE id = @id
""")
.With("@u", Sql.Text(sourceUrl))
.With("@c", Sql.Text(coverUrl))
.With("@at", Sql.Time(seenAt))
.With("@id", mediaId)
.ExecuteNonQuery();
RecomputeState(w, entryId);
},
ct);
public Task SetThumbnailAsync(long mediaId, bool hasThumbnail, CancellationToken ct = default) =>
db.WriteAsync(
w => w.Command("UPDATE media SET has_thumbnail = @t WHERE id = @id").With("@t", Sql.Bool(hasThumbnail)).With("@id", mediaId).ExecuteNonQuery(),
ct);
public Task UpdateAsync(Media media, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(media);
return db.WriteAsync(
w =>
{
var entryId = EntryOf(w, media.Id);
var command = w.Command("""
UPDATE media SET position = @position, kind = @kind, instagram_id = @instagram_id, width = @width, height = @height,
duration_ms = @duration_ms, state = @state, relative_path = @relative_path, bytes = @bytes, sha256 = @sha256,
phash = @phash, has_thumbnail = @has_thumbnail, source_url = @source_url, cover_url = @cover_url,
source_seen_at = @source_seen_at, attempts = @attempts, last_error = @last_error, downloaded_at = @downloaded_at
WHERE id = @id
""");
BindMedia(command, media with { EntryId = entryId });
command.With("@id", media.Id).ExecuteNonQuery();
RecomputeState(w, entryId, media.DownloadedAt);
},
ct);
}
private static long EntryOf(WriteContext w, long mediaId)
{
var value = w.Command("SELECT entry_id FROM media WHERE id = @id").With("@id", mediaId).ExecuteScalar();
return value is long entryId ? entryId : throw new KeyNotFoundException($"File {mediaId} non trovato.");
}
}