Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
<PackageVersion Include="Avalonia.Desktop" Version="12.1.2" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.2" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageVersion Include="Microsoft.Data.Sqlite.Core" Version="10.0.12" />
<PackageVersion Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
<PackageVersion Include="xunit.v3" Version="3.2.0" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
</ItemGroup>
Expand Down
4 changes: 3 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 7 additions & 3 deletions docs/architecture/persistence.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions src/Fadrio.Infrastructure/Fadrio.Infrastructure.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite.Core" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" />
<ProjectReference Include="../Fadrio.Core/Fadrio.Core.csproj" />
<ProjectReference Include="../Fadrio.Application/Fadrio.Application.csproj" />
</ItemGroup>
Expand Down
40 changes: 40 additions & 0 deletions src/Fadrio.Infrastructure/FadrioDataPaths.cs
Original file line number Diff line number Diff line change
@@ -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<string, string?> 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");
}
}
}
130 changes: 130 additions & 0 deletions src/Fadrio.Infrastructure/FadrioDatabase.cs
Original file line number Diff line number Diff line change
@@ -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<int, (string Name, string Checksum)>();
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);
}
7 changes: 6 additions & 1 deletion src/Fadrio.UI/Program.cs
Original file line number Diff line number Diff line change
@@ -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<App>().UsePlatformDetect();
}
159 changes: 159 additions & 0 deletions tests/Fadrio.Infrastructure.Tests/FadrioPersistenceTests.cs
Original file line number Diff line number Diff line change
@@ -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<string, string>
{
["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<InvalidDataException>(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<InvalidDataException>(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<SqliteException>(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();
}
}
Loading