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

+521
View File
@@ -0,0 +1,521 @@
using System.Text;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
using static Febe.Data.Stores.EntryMapping;
namespace Febe.Data.Stores;
internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{
public Task<Entry?> GetAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync(c => ReadEntryById(sql => c.Command(sql), entryId), ct);
public Task<EntryWithMedia?> GetWithMediaAsync(long entryId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var entry = ReadEntryById(sql => c.Command(sql), entryId);
return entry is null ? null : new EntryWithMedia(entry, ReadMediaOf(sql => c.Command(sql), entryId));
},
ct);
public Task<Entry?> FindAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
return db.ReadAsync(c => FindIdentity(sql => c.Command(sql), accountId, kind, instagramId.Trim()), ct);
}
public async Task<bool> IsKnownAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default) =>
await FindAsync(accountId, kind, instagramId, ct).ConfigureAwait(false) is not null;
public Task<IReadOnlySet<string>> GetKnownInstagramIdsAsync(long accountId, EntryKind kind, IReadOnlyCollection<string> instagramIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(instagramIds);
var ids = instagramIds.Where(i => !string.IsNullOrWhiteSpace(i)).Select(i => i.Trim()).Distinct(StringComparer.Ordinal).ToList();
return db.ReadAsync<IReadOnlySet<string>>(
c =>
{
var known = new HashSet<string>(StringComparer.Ordinal);
foreach (var chunk in ids.Chunk(500))
{
var command = c.Command(string.Empty).With("@a", accountId).With("@k", Sql.Enum(kind));
var list = command.AddList("i", chunk);
command.CommandText = $"SELECT instagram_id FROM entry WHERE account_id = @a AND kind = @k AND instagram_id IN ({list})";
using var r = command.ExecuteReader();
while (r.Read())
{
known.Add(r.GetString(0));
}
}
return known;
},
ct);
}
public Task<IReadOnlyList<Entry>> FindByInstagramIdAsync(long accountId, string instagramId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
return db.ReadAsync<IReadOnlyList<Entry>>(
c => ReadEntries(c.Command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.instagram_id = @i ORDER BY e.id")
.With("@a", accountId).With("@i", instagramId.Trim())),
ct);
}
public Task<Entry?> FindByPublicationTimeAsync(long accountId, EntryKind kind, DateTimeOffset publishedAt, TimeSpan tolerance, CancellationToken ct = default)
{
var ms = Sql.Time(publishedAt);
var tol = (long)Math.Abs(tolerance.TotalMilliseconds);
return db.ReadAsync(
c =>
{
using var r = c.Command($"""
SELECT {EntryColumns} FROM entry e
WHERE e.account_id = @a AND e.kind = @k AND e.published_at BETWEEN @from AND @to
ORDER BY abs(e.published_at - @p), e.id LIMIT 1
""")
.With("@a", accountId).With("@k", Sql.Enum(kind)).With("@from", ms - tol).With("@to", ms + tol).With("@p", ms)
.ExecuteReader();
return r.Read() ? ReadEntry(r) : null;
},
ct);
}
public Task<AddEntryResult> AddAsync(Entry entry, IReadOnlyList<Media> media, CancellationToken ct = default)
{
Validate(entry, media);
return db.WriteAsync(w => Add(w, entry, media), ct);
}
public Task<IReadOnlyList<AddEntryResult>> AddManyAsync(IReadOnlyList<NewEntry> entries, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entries);
foreach (var item in entries)
{
Validate(item.Entry, item.Media);
}
return db.WriteAsync<IReadOnlyList<AddEntryResult>>(w => entries.Select(item => Add(w, item.Entry, item.Media)).ToList(), ct);
}
public Task UpdateAsync(Entry entry, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entry);
return db.WriteAsync(
w =>
{
var c = w.Command("""
UPDATE entry SET instagram_id = @instagram_id, code = @code, published_at = @published_at, caption = @caption,
author_username = @author_username, author_instagram_id = @author_instagram_id, state = @state,
provenance = @provenance, discovered_at = @discovered_at, downloaded_at = @downloaded_at,
deleted_at = @deleted_at, expires_at = @expires_at, search_text = @search_text
WHERE id = @id
""");
BindEntry(c, entry);
c.With("@id", entry.Id);
try
{
if (c.ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Elemento {entry.Id} non trovato.");
}
}
catch (SqliteException ex) when (ex.IsUniqueViolation())
{
throw new DuplicateRecordException("Esiste già un elemento con lo stesso identificativo Instagram per questo account e tipo.", ex);
}
},
ct);
}
public Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
if (w.Command("UPDATE entry SET state = @s WHERE id = @id").With("@s", Sql.Enum(state)).With("@id", entryId).ExecuteNonQuery() == 0)
{
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
}
},
ct);
public Task<EntryState> RecomputeStateAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync(w => RecomputeState(w, entryId), ct);
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync(
w =>
{
var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id")
.With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery();
if (rows == 0)
{
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
}
w.Command("""
UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL
WHERE entry_id = @id
""").With("@id", entryId).ExecuteNonQuery();
},
ct);
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct);
public Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default)
{
options ??= new EntryListOptions();
return db.ReadAsync<IReadOnlyList<Entry>>(
c =>
{
var command = c.Command(string.Empty).With("@a", accountId).With("@limit", (long)Math.Clamp(options.Limit, 1, 10_000));
var sql = new StringBuilder($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a");
if (options.Kind is { } kind)
{
sql.Append(" AND e.kind = @k");
command.With("@k", Sql.Enum(kind));
}
if (options.States is { Count: > 0 } states)
{
sql.Append(" AND e.state IN (").Append(command.AddList("s", states.Select(s => s.ToString()))).Append(')');
}
if (options.Before is { } before)
{
sql.Append(" AND (e.published_at, e.id) < (@bp, @bi)");
command.With("@bp", Sql.Time(before.PublishedAt)).With("@bi", before.EntryId);
}
sql.Append(" ORDER BY e.published_at DESC, e.id DESC LIMIT @limit");
command.CommandText = sql.ToString();
return ReadEntries(command);
},
ct);
}
public Task<int> CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) =>
db.ReadAsync(
c => (int)c.Command("""
SELECT COUNT(*) FROM entry WHERE account_id = @a AND kind = @k AND discovered_at >= @f AND discovered_at < @t
""").With("@a", accountId).With("@k", Sql.Enum(kind)).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).ScalarInt64(),
ct);
public Task<LibraryPage> QueryLibraryAsync(LibraryQuery query, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(query);
var limit = Math.Clamp(query.Limit, 1, 1000);
return db.ReadAsync(
c =>
{
// Phase 1: keys only, so that sorting never computes the tile columns of rows outside the window.
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, query.Filter);
var newer = query.Direction == LibraryDirection.Newer;
var sql = new StringBuilder($"SELECT e.id FROM entry e WHERE {where}");
if (query.Cursor is { } cursor)
{
sql.Append(newer ? " AND (e.published_at, e.id) > (@cp, @ci)" : " AND (e.published_at, e.id) < (@cp, @ci)");
command.With("@cp", Sql.Time(cursor.PublishedAt)).With("@ci", cursor.EntryId);
}
// With a text search the whole table is scanned and the matches sorted: about a tenth of a second on
// 200,000 entries whether the word is rare or common, instead of walking the index row by row.
var order = string.IsNullOrWhiteSpace(query.Filter.Search) ? "e.published_at" : "+e.published_at";
sql.Append(newer ? $" ORDER BY {order} ASC, e.id ASC" : $" ORDER BY {order} DESC, e.id DESC");
sql.Append(" LIMIT @limit");
command.With("@limit", (long)limit + 1);
command.CommandText = sql.ToString();
var ids = new List<long>(limit + 1);
using (var r = command.ExecuteReader())
{
while (r.Read())
{
ids.Add(r.GetInt64(0));
}
}
var moreInDirection = ids.Count > limit;
if (moreInDirection)
{
ids.RemoveAt(ids.Count - 1);
}
if (newer)
{
ids.Reverse();
}
// Phase 2: the tiles of the window, in display order.
var tiles = TilesOf(c, ids);
if (tiles.Count == 0)
{
return new LibraryPage(tiles, null, null);
}
var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId);
var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId);
bool hasOlder, hasNewer;
if (newer)
{
hasNewer = moreInDirection;
hasOlder = Exists(c, query.Filter, last, older: true);
}
else
{
hasOlder = moreInDirection;
hasNewer = query.Cursor is not null && Exists(c, query.Filter, first, older: false);
}
return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null);
},
ct);
}
public Task<LibraryTotals> GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
return db.ReadAsync(
c =>
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT COUNT(*), COUNT(DISTINCT e.account_id) FROM entry e WHERE {where}";
using var r = command.ExecuteReader();
r.Read();
return new LibraryTotals(r.GetInt32(0), r.GetInt32(1));
},
ct);
}
public Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
ArgumentNullException.ThrowIfNull(zone);
return db.ReadAsync<IReadOnlyList<DayCount>>(
c =>
{
// Stream the publication times in index order and fold them into local days here: no time zone logic
// in SQL, no sort, and the day bounds are computed once per day rather than once per entry.
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at";
var days = new List<DayCount>();
long dayStart = long.MaxValue, dayEnd = long.MinValue;
DateOnly day = default;
var count = 0;
using (var r = command.ExecuteReader())
{
while (r.Read())
{
var ms = r.GetInt64(0);
if (ms < dayStart || ms >= dayEnd)
{
if (count > 0)
{
days.Add(new DayCount(day, count));
}
day = LocalCalendar.Today(Sql.ToTime(ms), zone);
var (start, end) = LocalCalendar.DayBounds(day, zone);
(dayStart, dayEnd, count) = (Sql.Time(start), Sql.Time(end), 0);
}
count++;
}
}
if (count > 0)
{
days.Add(new DayCount(day, count));
}
days.Reverse();
return days;
},
ct);
}
public Task<IReadOnlyList<LibraryTile>> GetTilesAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entryIds);
return db.ReadAsync<IReadOnlyList<LibraryTile>>(c => TilesOf(c, entryIds), ct);
}
// ---------------------------------------------------------------------------------------------
/// <summary>Tiles of the given entries, in the given order (unknown keys are skipped).</summary>
private static List<LibraryTile> TilesOf(SqliteConnection c, IReadOnlyList<long> entryIds)
{
var byId = new Dictionary<long, LibraryTile>(entryIds.Count);
foreach (var chunk in entryIds.Distinct().Chunk(500))
{
using var command = c.Command(string.Empty);
var list = command.AddList("i", chunk);
command.CommandText = $"SELECT {TileColumns} {TileFrom} WHERE e.id IN ({list})";
using var r = command.ExecuteReader();
while (r.Read())
{
var tile = ReadTile(r);
byId[tile.EntryId] = tile;
}
}
return entryIds.Where(byId.ContainsKey).Select(id => byId[id]).ToList();
}
private static void Validate(Entry entry, IReadOnlyList<Media> media)
{
ArgumentNullException.ThrowIfNull(entry);
ArgumentNullException.ThrowIfNull(media);
if (media.Select(m => m.Position).Distinct().Count() != media.Count)
{
throw new ArgumentException("Le posizioni dei file di un elemento devono essere distinte.", nameof(media));
}
if (media.Any(m => m.Position < 1))
{
throw new ArgumentException("Le posizioni dei file partono da 1.", nameof(media));
}
}
private static AddEntryResult Add(WriteContext w, Entry entry, IReadOnlyList<Media> media)
{
var instagramId = NormalizeId(entry.InstagramId);
if (instagramId is not null && FindIdentity(w.Command, entry.AccountId, entry.Kind, instagramId) is { } existing)
{
return new AddEntryResult(new EntryWithMedia(existing, ReadMediaOf(w.Command, existing.Id)), false);
}
var state = EntryStateRules.FromMedia(entry.State, entry.Provenance, media.Select(m => m.State).ToList());
var stored = entry with { InstagramId = instagramId, State = state };
var insert = w.Command("""
INSERT INTO entry (account_id, kind, instagram_id, code, published_at, caption, author_username, author_instagram_id, state,
provenance, discovered_at, downloaded_at, deleted_at, expires_at, search_text)
VALUES (@account_id, @kind, @instagram_id, @code, @published_at, @caption, @author_username, @author_instagram_id, @state,
@provenance, @discovered_at, @downloaded_at, @deleted_at, @expires_at, @search_text)
""");
BindEntry(insert, stored);
insert.ExecuteNonQuery();
var entryId = w.LastInsertRowId();
stored = stored with { Id = entryId };
var files = new List<Media>(media.Count);
foreach (var file in media.OrderBy(m => m.Position))
{
var row = file with { EntryId = entryId, Sha256 = file.Sha256?.ToLowerInvariant(), InstagramId = NormalizeId(file.InstagramId) };
var command = w.Command(InsertMediaSql);
BindMedia(command, row);
command.ExecuteNonQuery();
files.Add(row with { Id = w.LastInsertRowId() });
}
return new AddEntryResult(new EntryWithMedia(stored, files), true);
}
private static Entry? FindIdentity(Func<string, SqliteCommand> command, long accountId, EntryKind kind, string instagramId)
{
using var r = command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.kind = @k AND e.instagram_id = @i")
.With("@a", accountId).With("@k", Sql.Enum(kind)).With("@i", instagramId).ExecuteReader();
return r.Read() ? ReadEntry(r) : null;
}
private static List<Entry> ReadEntries(SqliteCommand command)
{
using var r = command.ExecuteReader();
var list = new List<Entry>();
while (r.Read())
{
list.Add(ReadEntry(r));
}
return list;
}
private static bool Exists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older)
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi))";
command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId);
return command.ScalarInt64() != 0;
}
/// <summary>The WHERE clause of a library filter on <c>entry e</c>; parameters are added to <paramref name="command"/>.</summary>
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter)
{
var parts = new List<string>();
var states = filter.States is { Count: > 0 } s ? s : EntryStateRules.Visible;
// The unary + keeps SQLite from using the state and kind indexes for these broad terms: the keyset scan of the
// publication index is what keeps a window fast over 200,000 entries, with or without ANALYZE statistics.
parts.Add($"+e.state IN ({command.AddList("st", states.Select(x => x.ToString()))})");
parts.Add(filter.Kind switch
{
LibraryKindFilter.All => "+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged')",
LibraryKindFilter.Posts => "e.kind = 'Post'",
LibraryKindFilter.Photos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Photo')",
LibraryKindFilter.Videos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Video')",
LibraryKindFilter.Stories => "e.kind = 'Story'",
LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))",
LibraryKindFilter.Tagged => "e.kind = 'Tagged'",
LibraryKindFilter.ProfilePictures => "e.kind = 'ProfilePicture'",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter.Kind, null),
});
if (filter.AccountIds is { } accounts)
{
parts.Add($"e.account_id IN ({command.AddList("ac", accounts)})");
}
if (filter.From is { } from)
{
parts.Add("e.published_at >= @from");
command.With("@from", Sql.Time(from));
}
if (filter.To is { } to)
{
parts.Add("e.published_at < @to");
command.With("@to", Sql.Time(to));
}
if (filter.Provenance is { } provenance)
{
parts.Add("e.provenance = @prov");
command.With("@prov", Sql.Enum(provenance));
}
var term = TextSearch.Normalize(filter.Search);
if (term.Length > 0)
{
// Accounts are few: match their names here, accent-insensitively, then filter entries by key.
var matching = new List<long>();
using (var r = c.Command("SELECT id, username, display_name FROM account").ExecuteReader())
{
while (r.Read())
{
var name = TextSearch.Normalize(r.GetString(1));
var display = TextSearch.Normalize(r.GetTextOrNull(2));
var bare = term.TrimStart('@');
if (name.Contains(bare, StringComparison.Ordinal) || display.Contains(term, StringComparison.Ordinal))
{
matching.Add(r.GetInt64(0));
}
}
}
command.With("@q", TextSearch.LikePattern(term));
parts.Add(matching.Count == 0
? "e.search_text LIKE @q ESCAPE '\\'"
: $"(e.search_text LIKE @q ESCAPE '\\' OR e.account_id IN ({command.AddList("sa", matching)}))");
}
return string.Join(" AND ", parts);
}
}