From 6d6f33d1db556371a26b7b26171e0b1e243922ee Mon Sep 17 00:00:00 2001 From: Flavio Giacchetti Date: Thu, 24 Sep 2026 19:55:16 +0200 Subject: [PATCH] feat: bootstrap XDG SQLite persistence --- CHANGELOG.md | 1 + Directory.Packages.props | 2 + ROADMAP.md | 4 +- docs/architecture/persistence.md | 10 +- .../Fadrio.Infrastructure.csproj | 2 + src/Fadrio.Infrastructure/FadrioDataPaths.cs | 40 +++++ src/Fadrio.Infrastructure/FadrioDatabase.cs | 130 ++++++++++++++ src/Fadrio.UI/Program.cs | 7 +- .../FadrioPersistenceTests.cs | 159 ++++++++++++++++++ 9 files changed, 350 insertions(+), 5 deletions(-) create mode 100644 src/Fadrio.Infrastructure/FadrioDataPaths.cs create mode 100644 src/Fadrio.Infrastructure/FadrioDatabase.cs create mode 100644 tests/Fadrio.Infrastructure.Tests/FadrioPersistenceTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5629861..9f09135 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes will be documented here. The format follows [Keep a Changelo - `FAD-0204` Optional Snap identity from corroborated wrapper metadata without invoking or depending on Snap tooling. - `FAD-0206` Advanced `fadrioctl inspect` diagnostics for canonical identity evidence and per-session audio state, with deterministic share-safe redaction. - `REL-00003` Firefox qualification covers the installed `firefox-bin` runtime, one-row grouping, visible launcher/icon preference, ambiguity safety, and executable fallback. +- `FAD-0301` XDG user-data paths and SQLite startup with versioned, checksummed, transactional schema migrations. ### Changed diff --git a/Directory.Packages.props b/Directory.Packages.props index 78d722f..0136221 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,6 +7,8 @@ + + diff --git a/ROADMAP.md b/ROADMAP.md index e981fee..36f20dc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -157,7 +157,9 @@ Canonical ticket format: ## 0.3 — Persistence -- [ ] `FAD-0301` `P0` Implement XDG data paths, SQLite bootstrap, and deterministic migrations. +- [x] `FAD-0301` `P0` Implement XDG data paths, SQLite bootstrap, and deterministic migrations. + - Scope: resolve config/data/cache/state directories from absolute XDG overrides or user-home fallbacks; initialize the per-user SQLite database on app startup; record versioned SQL migrations and checksums. + - Acceptance: fresh and repeat startup preserve settings, unsupported future schemas fail without changes, and a failed migration rolls back its history; managed/native validation passes. - [ ] `FAD-0302` `P1` Persist application identity evidence and user overrides without raw sensitive process context. - [ ] `FAD-0303` `P1` Implement pin, hide, ordering, and inactive-stream grace behavior. - [ ] `FAD-0304` `P0` Implement remembered/fixed/follow-current volume policies with confidence safeguards. diff --git a/docs/architecture/persistence.md b/docs/architecture/persistence.md index 889ca4c..d815a8a 100644 --- a/docs/architecture/persistence.md +++ b/docs/architecture/persistence.md @@ -1,5 +1,9 @@ -# Persistence +# Persistence foundation -SQLite is planned for structured durable state under XDG data paths. Live meter samples and transient runtime sessions do not belong in the database. +`FAD-0301` establishes per-user paths and a SQLite schema bootstrap. The desktop app initializes the database before creating its window. The CLI does not create a database just to inspect live audio. -Every schema change requires a numbered, transactional migration and upgrade tests. Resolver changes must not silently delete identities, mappings, bindings, or user personalization. Persistence is not implemented in M0. +The config, data, cache, and state directories use absolute `XDG_*_HOME` values with standard home-directory fallbacks. Structured data is stored at `$XDG_DATA_HOME/fadrio/fadrio.db` (or `~/.local/share/fadrio/fadrio.db`). A newly created Fadrio data directory is private to the current user. + +Migration 1 creates `settings` and records its version, name, and SQL checksum in `schema_migrations`. Startup verifies SQLite integrity and the migration history before applying missing migrations in a transaction. Unknown future versions, changed checksums, and failed SQL stop startup without resetting user data. Later persistence work adds application records and migration backups; the initial database has no user identity data yet. + +Live meter samples and transient runtime sessions do not belong in the database. Resolver changes must never silently delete identities, mappings, bindings, or user personalization. Each later schema change needs a numbered transactional migration and an upgrade test from the previous release schema. diff --git a/src/Fadrio.Infrastructure/Fadrio.Infrastructure.csproj b/src/Fadrio.Infrastructure/Fadrio.Infrastructure.csproj index 6e1a4b5..93c0c8e 100644 --- a/src/Fadrio.Infrastructure/Fadrio.Infrastructure.csproj +++ b/src/Fadrio.Infrastructure/Fadrio.Infrastructure.csproj @@ -1,5 +1,7 @@ + + diff --git a/src/Fadrio.Infrastructure/FadrioDataPaths.cs b/src/Fadrio.Infrastructure/FadrioDataPaths.cs new file mode 100644 index 0000000..aa33d0f --- /dev/null +++ b/src/Fadrio.Infrastructure/FadrioDataPaths.cs @@ -0,0 +1,40 @@ +namespace Fadrio.Infrastructure; + +public sealed record FadrioDataPaths( + string ConfigDirectory, + string DataDirectory, + string CacheDirectory, + string StateDirectory) +{ + public string DatabasePath => Path.Combine(DataDirectory, "fadrio.db"); + + public static FadrioDataPaths Resolve() => Resolve( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + Environment.GetEnvironmentVariable); + + public static FadrioDataPaths Resolve(string userHome, Func getEnvironmentVariable) + { + ArgumentException.ThrowIfNullOrWhiteSpace(userHome); + ArgumentNullException.ThrowIfNull(getEnvironmentVariable); + if (!Path.IsPathFullyQualified(userHome)) + { + throw new ArgumentException("The user home path must be absolute.", nameof(userHome)); + } + + string home = Path.GetFullPath(userHome); + return new( + AppDirectory("XDG_CONFIG_HOME", ".config"), + AppDirectory("XDG_DATA_HOME", ".local/share"), + AppDirectory("XDG_CACHE_HOME", ".cache"), + AppDirectory("XDG_STATE_HOME", ".local/state")); + + string AppDirectory(string variable, string fallback) + { + string? configured = getEnvironmentVariable(variable); + string baseDirectory = !string.IsNullOrWhiteSpace(configured) && Path.IsPathFullyQualified(configured) + ? configured + : Path.Combine(home, fallback); + return Path.Combine(Path.GetFullPath(baseDirectory), "fadrio"); + } + } +} diff --git a/src/Fadrio.Infrastructure/FadrioDatabase.cs b/src/Fadrio.Infrastructure/FadrioDatabase.cs new file mode 100644 index 0000000..7dfa101 --- /dev/null +++ b/src/Fadrio.Infrastructure/FadrioDatabase.cs @@ -0,0 +1,130 @@ +using System.Security.Cryptography; +using System.Text; +using Microsoft.Data.Sqlite; + +namespace Fadrio.Infrastructure; + +public sealed class FadrioDatabase(string databasePath) +{ + private static readonly Migration[] Migrations = + [ + new(1, "bootstrap-settings", """ + CREATE TABLE settings ( + key TEXT NOT NULL PRIMARY KEY, + value TEXT NOT NULL + ); + """) + ]; + + public string DatabasePath { get; } = ValidatePath(databasePath); + + public int CurrentSchemaVersion => Migrations[^1].Version; + + public void Initialize() + { + SQLitePCL.Batteries_V2.Init(); + string directory = Path.GetDirectoryName(DatabasePath)!; + if (OperatingSystem.IsWindows()) + { + Directory.CreateDirectory(directory); + } + else + { + Directory.CreateDirectory(directory, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + var builder = new SqliteConnectionStringBuilder + { + DataSource = DatabasePath, + Mode = SqliteOpenMode.ReadWriteCreate, + Pooling = false + }; + using var connection = new SqliteConnection(builder.ToString()); + connection.Open(); + using (var integrity = connection.CreateCommand()) + { + integrity.CommandText = "PRAGMA quick_check;"; + if (!string.Equals(integrity.ExecuteScalar()?.ToString(), "ok", StringComparison.Ordinal)) + { + throw new InvalidDataException("The Fadrio database failed SQLite integrity checking."); + } + } + + using var transaction = connection.BeginTransaction(); + Execute(connection, transaction, """ + CREATE TABLE IF NOT EXISTS schema_migrations ( + version INTEGER NOT NULL PRIMARY KEY, + name TEXT NOT NULL, + checksum TEXT NOT NULL + ); + """); + + var applied = new Dictionary(); + using (var command = connection.CreateCommand()) + { + command.Transaction = transaction; + command.CommandText = "SELECT version, name, checksum FROM schema_migrations ORDER BY version;"; + using SqliteDataReader reader = command.ExecuteReader(); + while (reader.Read()) + { + applied.Add(reader.GetInt32(0), (reader.GetString(1), reader.GetString(2))); + } + } + + if (applied.Keys.Any(version => version > CurrentSchemaVersion || version < 1)) + { + throw new InvalidDataException("The database has a schema version this build does not support."); + } + + foreach (Migration migration in Migrations) + { + string checksum = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(migration.Sql))); + if (applied.TryGetValue(migration.Version, out (string Name, string Checksum) recorded)) + { + if (recorded.Name != migration.Name || recorded.Checksum != checksum) + { + throw new InvalidDataException($"Migration {migration.Version} does not match the recorded schema."); + } + + continue; + } + + if (applied.Keys.Any(version => version > migration.Version)) + { + throw new InvalidDataException($"Migration {migration.Version} is missing from the recorded history."); + } + + Execute(connection, transaction, migration.Sql); + using var insert = connection.CreateCommand(); + insert.Transaction = transaction; + insert.CommandText = "INSERT INTO schema_migrations (version, name, checksum) VALUES ($version, $name, $checksum);"; + insert.Parameters.AddWithValue("$version", migration.Version); + insert.Parameters.AddWithValue("$name", migration.Name); + insert.Parameters.AddWithValue("$checksum", checksum); + insert.ExecuteNonQuery(); + } + + transaction.Commit(); + } + + private static string ValidatePath(string path) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + if (!Path.IsPathFullyQualified(path)) + { + throw new ArgumentException("The database path must be absolute.", nameof(path)); + } + + return Path.GetFullPath(path); + } + + private static void Execute(SqliteConnection connection, SqliteTransaction transaction, string sql) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = sql; + command.ExecuteNonQuery(); + } + + private sealed record Migration(int Version, string Name, string Sql); +} diff --git a/src/Fadrio.UI/Program.cs b/src/Fadrio.UI/Program.cs index f2f2586..f3f4473 100644 --- a/src/Fadrio.UI/Program.cs +++ b/src/Fadrio.UI/Program.cs @@ -1,11 +1,16 @@ using Avalonia; +using Fadrio.Infrastructure; namespace Fadrio.UI; internal static class Program { [STAThread] - public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + public static void Main(string[] args) + { + new FadrioDatabase(FadrioDataPaths.Resolve().DatabasePath).Initialize(); + BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + } public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure().UsePlatformDetect(); } diff --git a/tests/Fadrio.Infrastructure.Tests/FadrioPersistenceTests.cs b/tests/Fadrio.Infrastructure.Tests/FadrioPersistenceTests.cs new file mode 100644 index 0000000..b0d6814 --- /dev/null +++ b/tests/Fadrio.Infrastructure.Tests/FadrioPersistenceTests.cs @@ -0,0 +1,159 @@ +using Fadrio.Infrastructure; +using Microsoft.Data.Sqlite; + +namespace Fadrio.Infrastructure.Tests; + +public sealed class FadrioPersistenceTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"fadrio-persistence-{Guid.NewGuid():N}"); + + [Fact] + public void XdgPathsUseAbsoluteOverridesAndHomeFallbacks() + { + string home = Path.Combine(_root, "home"); + var variables = new Dictionary + { + ["XDG_CONFIG_HOME"] = Path.Combine(_root, "config"), + ["XDG_DATA_HOME"] = "relative-data", + ["XDG_CACHE_HOME"] = Path.Combine(_root, "cache"), + ["XDG_STATE_HOME"] = "" + }; + + FadrioDataPaths paths = FadrioDataPaths.Resolve(home, name => variables.GetValueOrDefault(name)); + + Assert.Equal(Path.Combine(_root, "config", "fadrio"), paths.ConfigDirectory); + Assert.Equal(Path.Combine(home, ".local", "share", "fadrio"), paths.DataDirectory); + Assert.Equal(Path.Combine(_root, "cache", "fadrio"), paths.CacheDirectory); + Assert.Equal(Path.Combine(home, ".local", "state", "fadrio"), paths.StateDirectory); + Assert.Equal(Path.Combine(paths.DataDirectory, "fadrio.db"), paths.DatabasePath); + } + + [Fact] + public void FreshDatabaseBootstrapsOnceAndKeepsExistingSettings() + { + var database = new FadrioDatabase(Path.Combine(_root, "data", "fadrio.db")); + database.Initialize(); + + using (SqliteConnection connection = Open(database.DatabasePath)) + { + Assert.Equal(1L, ScalarLong(connection, "SELECT COUNT(*) FROM schema_migrations;")); + Assert.Equal(1L, ScalarLong(connection, "SELECT version FROM schema_migrations;")); + Execute(connection, "INSERT INTO settings (key, value) VALUES ('theme', 'dark');"); + } + + database.Initialize(); + + using SqliteConnection reopened = Open(database.DatabasePath); + Assert.Equal(1L, ScalarLong(reopened, "SELECT COUNT(*) FROM schema_migrations;")); + using var command = reopened.CreateCommand(); + command.CommandText = "SELECT value FROM settings WHERE key = 'theme';"; + Assert.Equal("dark", command.ExecuteScalar()); + } + + [Fact] + public void FutureSchemaIsRejectedWithoutModifyingItsHistory() + { + var database = new FadrioDatabase(Path.Combine(_root, "future", "fadrio.db")); + database.Initialize(); + using (SqliteConnection connection = Open(database.DatabasePath)) + { + Execute(connection, "INSERT INTO schema_migrations (version, name, checksum) VALUES (99, 'future', 'fixture');"); + } + + Assert.Throws(database.Initialize); + + using SqliteConnection reopened = Open(database.DatabasePath); + Assert.Equal(2L, ScalarLong(reopened, "SELECT COUNT(*) FROM schema_migrations;")); + } + + [Fact] + public void ChangedMigrationChecksumIsRejectedWithoutModifyingSettings() + { + var database = new FadrioDatabase(Path.Combine(_root, "checksum", "fadrio.db")); + database.Initialize(); + using (SqliteConnection connection = Open(database.DatabasePath)) + { + Execute(connection, "INSERT INTO settings (key, value) VALUES ('theme', 'dark');"); + Execute(connection, "UPDATE schema_migrations SET checksum = 'changed' WHERE version = 1;"); + } + + Assert.Throws(database.Initialize); + + using SqliteConnection reopened = Open(database.DatabasePath); + using var command = reopened.CreateCommand(); + command.CommandText = "SELECT value FROM settings WHERE key = 'theme';"; + Assert.Equal("dark", command.ExecuteScalar()); + } + + [Fact] + public void NewDataDirectoryIsPrivateToTheCurrentUser() + { + if (OperatingSystem.IsWindows()) + { + return; + } + + var database = new FadrioDatabase(Path.Combine(_root, "private", "fadrio.db")); + database.Initialize(); + + Assert.Equal( + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute, + File.GetUnixFileMode(Path.GetDirectoryName(database.DatabasePath)!)); + } + + [Fact] + public void FailedInitialMigrationRollsBackItsHistory() + { + string path = Path.Combine(_root, "conflict", "fadrio.db"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using (SqliteConnection connection = Open(path)) + { + Execute(connection, "CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);"); + } + + var database = new FadrioDatabase(path); + Assert.Throws(database.Initialize); + + using SqliteConnection reopened = Open(path); + Assert.Equal(0L, ScalarLong(reopened, + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations';")); + Assert.Equal(1L, ScalarLong(reopened, + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'settings';")); + } + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + + GC.SuppressFinalize(this); + } + + private static SqliteConnection Open(string path) + { + SQLitePCL.Batteries_V2.Init(); + var connection = new SqliteConnection(new SqliteConnectionStringBuilder + { + DataSource = path, + Pooling = false + }.ToString()); + connection.Open(); + return connection; + } + + private static long ScalarLong(SqliteConnection connection, string sql) + { + using var command = connection.CreateCommand(); + command.CommandText = sql; + return (long)command.ExecuteScalar()!; + } + + private static void Execute(SqliteConnection connection, string sql) + { + using var command = connection.CreateCommand(); + command.CommandText = sql; + command.ExecuteNonQuery(); + } +}