using Febe.Core.Storage;
using Febe.Data.Stores;
using Microsoft.Data.Sqlite;
namespace Febe.Data;
///
/// The SQLite database of Febe (spec §8): Dati/febe.sqlite in WAL mode, foreign keys on, busy timeout,
/// numbered migrations applied at start-up. All writes go through one queue and one connection
/// (); reads use separate pooled read-only connections and never block the writer.
///
public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
{
/// File name inside the Data folder.
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);
Exports = new ExportStore(this);
VideoAnalyses = new VideoAnalysisStore(this);
Conversions = new MediaConversionStore(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 IExportStore Exports { get; }
public IVideoAnalysisStore VideoAnalyses { get; }
public IMediaConversionStore Conversions { get; }
public ISettingsStore Settings { get; }
public IDatabaseMaintenance Maintenance => this;
public string DatabasePath { get; }
public int SchemaVersion { get; }
internal SqliteWriter Writer { get; }
/// Opens (or creates) febe.sqlite inside the Data folder and applies pending migrations.
public static Task OpenAsync(string dataFolder, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
return OpenFileAsync(Path.Combine(dataFolder, FileName), ct);
}
/// Opens (or creates) a database file and applies pending migrations.
public static Task OpenFileAsync(string databasePath, CancellationToken ct = default) =>
Task.FromResult(Open(databasePath, MigrationRunner.LoadEmbedded(), ct));
internal static FebeDatabase Open(string databasePath, IReadOnlyList 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.Scalar("PRAGMA journal_mode = WAL") 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.Execute("PRAGMA synchronous = NORMAL");
connection.Execute($"PRAGMA busy_timeout = {BusyTimeoutMs}");
connection.Execute("PRAGMA foreign_keys = ON");
var version = MigrationRunner.Apply(connection, migrations);
return new FebeDatabase(path, connection, readConnectionString, version);
}
catch
{
connection.Dispose();
throw;
}
}
/// Queues a write; the task completes after the commit.
internal Task WriteAsync(Func work, CancellationToken ct) => Writer.ExecuteAsync(work, ct);
internal Task WriteAsync(Action work, CancellationToken ct) => Writer.ExecuteAsync(work, ct);
/// Runs a read on its own read-only connection.
internal Task ReadAsync(Func work, CancellationToken ct)
{
if (ct.IsCancellationRequested)
{
return Task.FromCanceled(ct);
}
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
try
{
using var connection = OpenReadConnection();
using var commands = CommandScope.Begin(); // disposed first: the connection then really closes
return Task.FromResult(work(connection));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
return Task.FromException(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.
using var vacuum = connection.Command("VACUUM INTO @destination").With("@destination", destination);
vacuum.ExecuteNonQuery();
return true;
},
ct);
}
public Task 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();
// The idle read connections close first, so the writer is the last connection: only the writer can checkpoint
// and delete febe.sqlite-wal and -shm when it closes (a read-only connection leaves them behind).
using (var pooled = new SqliteConnection(_readConnectionString))
{
SqliteConnection.ClearPool(pooled);
}
try
{
_writerConnection.Execute("PRAGMA wal_checkpoint(TRUNCATE)");
}
catch (SqliteException)
{
// A reader may still hold a snapshot: the checkpoint is an optimization, not a requirement.
}
_writerConnection.Dispose();
return ValueTask.CompletedTask;
}
}