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

+230
View File
@@ -0,0 +1,230 @@
using Febe.Core.Storage;
using Febe.Data.Stores;
using Microsoft.Data.Sqlite;
namespace Febe.Data;
/// <summary>
/// The SQLite database of Febe (spec §8): <c>Dati/febe.sqlite</c> in WAL mode, foreign keys on, busy timeout,
/// numbered migrations applied at start-up. All writes go through one queue and one connection
/// (<see cref="SqliteWriter"/>); reads use separate pooled read-only connections and never block the writer.
/// </summary>
public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
{
/// <summary>File name inside the Data folder.</summary>
public const string FileName = "febe.sqlite";
private const int BusyTimeoutMs = 10_000;
private readonly SqliteConnection _writerConnection;
private readonly string _readConnectionString;
private int _disposed;
private FebeDatabase(string path, SqliteConnection writerConnection, string readConnectionString, int schemaVersion)
{
DatabasePath = path;
_writerConnection = writerConnection;
_readConnectionString = readConnectionString;
SchemaVersion = schemaVersion;
Writer = new SqliteWriter(writerConnection);
Accounts = new AccountStore(this);
Entries = new EntryStore(this);
Media = new MediaStore(this);
Highlights = new HighlightStore(this);
Duplicates = new DuplicateStore(this);
Tasks = new TaskStore(this);
ActionLog = new ActionLogStore(this);
Sessions = new SessionStore(this);
Incidents = new IncidentStore(this);
Events = new EventStore(this);
Following = new FollowingStore(this);
Imports = new ImportStore(this);
Settings = new SettingsStore(this);
}
public IAccountStore Accounts { get; }
public IEntryStore Entries { get; }
public IMediaStore Media { get; }
public IHighlightStore Highlights { get; }
public IDuplicateStore Duplicates { get; }
public ITaskStore Tasks { get; }
public IActionLogStore ActionLog { get; }
public ISessionStore Sessions { get; }
public IIncidentStore Incidents { get; }
public IEventStore Events { get; }
public IFollowingStore Following { get; }
public IImportStore Imports { get; }
public ISettingsStore Settings { get; }
public IDatabaseMaintenance Maintenance => this;
public string DatabasePath { get; }
public int SchemaVersion { get; }
internal SqliteWriter Writer { get; }
/// <summary>Opens (or creates) <c>febe.sqlite</c> inside the Data folder and applies pending migrations.</summary>
public static Task<FebeDatabase> OpenAsync(string dataFolder, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
return OpenFileAsync(Path.Combine(dataFolder, FileName), ct);
}
/// <summary>Opens (or creates) a database file and applies pending migrations.</summary>
public static Task<FebeDatabase> OpenFileAsync(string databasePath, CancellationToken ct = default) =>
Task.FromResult(Open(databasePath, MigrationRunner.LoadEmbedded(), ct));
internal static FebeDatabase Open(string databasePath, IReadOnlyList<Migration> migrations, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(databasePath);
ct.ThrowIfCancellationRequested();
var path = Path.GetFullPath(databasePath);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var writerConnectionString = new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = SqliteOpenMode.ReadWriteCreate,
Cache = SqliteCacheMode.Private,
Pooling = false,
ForeignKeys = true,
DefaultTimeout = BusyTimeoutMs / 1000,
}.ToString();
var readConnectionString = new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = SqliteOpenMode.ReadOnly,
Cache = SqliteCacheMode.Private,
Pooling = true,
DefaultTimeout = BusyTimeoutMs / 1000,
}.ToString();
var connection = new SqliteConnection(writerConnectionString);
try
{
connection.Open();
var mode = connection.Command("PRAGMA journal_mode = WAL").ExecuteScalar() as string;
if (!string.Equals(mode, "wal", StringComparison.OrdinalIgnoreCase))
{
throw new DatabaseMigrationException(
$"Febe non riesce a mettere il database in modalità WAL (modalità attuale: {mode}). La cartella dei dati deve stare su un disco locale.");
}
connection.Command("PRAGMA synchronous = NORMAL").ExecuteNonQuery();
connection.Command($"PRAGMA busy_timeout = {BusyTimeoutMs}").ExecuteNonQuery();
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
var version = MigrationRunner.Apply(connection, migrations);
return new FebeDatabase(path, connection, readConnectionString, version);
}
catch
{
connection.Dispose();
throw;
}
}
/// <summary>Queues a write; the task completes after the commit.</summary>
internal Task<T> WriteAsync<T>(Func<WriteContext, T> work, CancellationToken ct) => Writer.ExecuteAsync(work, ct);
internal Task WriteAsync(Action<WriteContext> work, CancellationToken ct) => Writer.ExecuteAsync(work, ct);
/// <summary>Runs a read on its own read-only connection.</summary>
internal Task<T> ReadAsync<T>(Func<SqliteConnection, T> work, CancellationToken ct)
{
if (ct.IsCancellationRequested)
{
return Task.FromCanceled<T>(ct);
}
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
try
{
using var connection = OpenReadConnection();
return Task.FromResult(work(connection));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
return Task.FromException<T>(ex);
}
}
internal SqliteConnection OpenReadConnection()
{
var connection = new SqliteConnection(_readConnectionString);
connection.Open();
return connection;
}
public Task BackupToAsync(string destinationFile, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(destinationFile);
var destination = Path.GetFullPath(destinationFile);
if (File.Exists(destination))
{
throw new IOException($"La copia {destination} esiste già: Febe non la sovrascrive.");
}
Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
return ReadAsync(
connection =>
{
// VACUUM INTO reads a consistent snapshot; it works on a read-only connection and does not block the writer.
connection.Command("VACUUM INTO @destination").With("@destination", destination).ExecuteNonQuery();
return true;
},
ct);
}
public Task<bool> CheckIntegrityAsync(CancellationToken ct = default) =>
ReadAsync(
connection =>
{
using var reader = connection.Command("PRAGMA quick_check").ExecuteReader();
return reader.Read() && string.Equals(reader.GetString(0), "ok", StringComparison.OrdinalIgnoreCase) && !reader.Read();
},
ct);
public Task OptimizeAsync(CancellationToken ct = default) =>
WriteAsync(context => context.Command("PRAGMA optimize").ExecuteNonQuery(), ct);
public ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return ValueTask.CompletedTask;
}
Writer.Dispose();
try
{
_writerConnection.Command("PRAGMA wal_checkpoint(TRUNCATE)").ExecuteNonQuery();
}
catch (SqliteException)
{
// A reader may still hold a snapshot: the checkpoint is an optimization, not a requirement.
}
_writerConnection.Dispose();
using (var pooled = new SqliteConnection(_readConnectionString))
{
SqliteConnection.ClearPool(pooled);
}
return ValueTask.CompletedTask;
}
}