From e08b71168e64928f0664eab2b7c070b9d20b6783 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 1 Apr 2025 19:14:06 -0500 Subject: wip --- .../Migrations/TransferStateMigration_04012025.cs | 144 +++++++++++++++++++++ src/slskd/Core/Migrator.cs | 93 +++++++++++++ src/slskd/Program.cs | 4 + 3 files changed, 241 insertions(+) create mode 100644 src/slskd/Core/Migrations/TransferStateMigration_04012025.cs create mode 100644 src/slskd/Core/Migrator.cs (limited to 'src') diff --git a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs new file mode 100644 index 00000000..6b03567a --- /dev/null +++ b/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs @@ -0,0 +1,144 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Migrations; + +using System; +using System.IO; +using Microsoft.Data.Sqlite; + +public class TransferStateMigration_04012025 : IMigration +{ + public void Apply() + { + + } + + static void AddStateDescriptionColumn(string dbPath) + { + if (!File.Exists(dbPath)) + { + Console.WriteLine("Database file not found."); + return; + } + + string connectionString = $"Data Source={dbPath};Version=3;"; + + using (var connection = new SqliteConnection(connectionString)) + { + connection.Open(); + + // Check if the column exists + bool columnExists = false; + using (var command = new SqliteCommand("PRAGMA table_info(Transfers);", connection)) + using (var reader = command.ExecuteReader()) + { + while (reader.Read()) + { + string columnName = reader["name"].ToString(); + if (columnName.Equals("StateDescription", StringComparison.OrdinalIgnoreCase)) + { + columnExists = true; + break; + } + } + } + + if (columnExists) + { + Console.WriteLine("Column 'StateDescription' already exists."); + return; + } + + Console.WriteLine("Adding 'StateDescription' column..."); + + using (var transaction = connection.BeginTransaction()) + { + try + { + // Rename old table + using (var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection)) + { + renameCommand.ExecuteNonQuery(); + } + + // Create new table with StateDescription after State + string createNewTableSQL = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State TEXT NOT NULL, + StateDescription TEXT, -- New column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + );"; + + using (var createCommand = new SqliteCommand(createNewTableSQL, connection)) + { + createCommand.ExecuteNonQuery(); + } + + // Copy data into the new table + string copyDataSQL = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using (var copyCommand = new SqliteCommand(copyDataSQL, connection)) + { + copyCommand.ExecuteNonQuery(); + } + + // Drop the old table + using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection)) + { + dropCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + Console.WriteLine("Column 'StateDescription' added successfully."); + } + catch (Exception ex) + { + transaction.Rollback(); + Console.WriteLine($"Error: {ex.Message}"); + } + } + + connection.Close(); + } + } +} diff --git a/src/slskd/Core/Migrator.cs b/src/slskd/Core/Migrator.cs new file mode 100644 index 00000000..a83f4764 --- /dev/null +++ b/src/slskd/Core/Migrator.cs @@ -0,0 +1,93 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd; + +using System; +using System.Collections.Generic; +using System.IO; +using Serilog; +using slskd.Migrations; + +public interface IMigration +{ + public void Apply(); +} + +public class Migrator +{ + private string HistoryFile { get; } = Path.Combine(Program.DataDirectory, "misc", "migration.history"); + private ILogger Log { get; } = Serilog.Log.ForContext(); + + private Dictionary Migrations { get; } = new() + { + { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, + }; + + public void Migrate() + { + Dictionary history = new(); + + try + { + if (File.Exists(HistoryFile)) + { + try + { + var txt = File.ReadAllText(HistoryFile); + history = txt.FromJson>(); + + Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFile, history); + } + catch (Exception ex) + { + Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFile, ex.Message); + Log.Warning("Migration history will be overwritten and all migrations will be applied"); + } + } + + foreach (var migration in Migrations) + { + if (history.TryGetValue(migration.Key, out var timestamp)) + { + Log.Debug("Migration {Name} was already applied {Date}", migration.Key, timestamp); + continue; + } + + try + { + migration.Value.Apply(); + history[migration.Key] = DateTime.UtcNow; + + Log.Information("Migration {Name} was applied successfully", migration.Key); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to apply migration {Name}: {Message}", migration.Key, ex.Message); + throw; + } + } + + File.WriteAllText(HistoryFile, history.ToJson()); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to apply migrations: {Message}", ex.Message); + throw; + } + } +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b7fa47d2..50ae7a07 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -596,6 +596,10 @@ namespace slskd services.AddDbContext(DiskConnectionString("transfers")); services.AddDbContext(DiskConnectionString("messaging")); services.AddDbContext(DiskConnectionString("events")); + + // we're working with non-volatile database files, so register a Migrator to be used later in the + // bootup process. the presence of a Migrator instance in DI determines whether a migration is needed. + services.AddSingleton(_ => new Migrator()); } services.AddSingleton(); -- cgit v1.2.3 From 47ea1847f89df9ca2ab2e7a51e29bab27f60f89b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 2 Apr 2025 20:42:35 -0500 Subject: migrate if migrator exists --- src/slskd/Core/Migrator.cs | 8 ++++++++ src/slskd/Program.cs | 7 +++++++ 2 files changed, 15 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Migrator.cs b/src/slskd/Core/Migrator.cs index a83f4764..23580336 100644 --- a/src/slskd/Core/Migrator.cs +++ b/src/slskd/Core/Migrator.cs @@ -20,6 +20,7 @@ namespace slskd; using System; using System.Collections.Generic; using System.IO; +using System.Linq; using Serilog; using slskd.Migrations; @@ -60,6 +61,13 @@ public class Migrator } } + var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); + + if (!migrationsNotYetApplied.Any()) + { + Log.Debug("No migrations need to be applied"); + } + foreach (var migration in Migrations) { if (history.TryGetValue(migration.Key, out var timestamp)) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 50ae7a07..8fbc0522 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -494,6 +494,13 @@ namespace slskd var app = builder.Build(); + var migrator = app.Services.GetService(); + + if (migrator is not null) + { + migrator.Migrate(); + } + // hack: services that exist only to subscribe to the event bus are not referenced by anything else // and are thus never instantiated. force a reference here so they are created. _ = app.Services.GetService(); -- cgit v1.2.3 From 3004a4297466d97b258033c874580a10536716be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 2 Apr 2025 21:44:24 -0500 Subject: add option to force --- config/slskd.example.yml | 1 + src/slskd/Core/Migrator.cs | 2 +- src/slskd/Core/Options.cs | 8 ++++++++ src/slskd/Program.cs | 2 +- 4 files changed, 11 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 9cd9584f..621b5564 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -10,6 +10,7 @@ # no_connect: false # no_share_scan: false # force_share_scan: false +# force_migrations: false # no_version_check: false # log_sql: false # experimental: false diff --git a/src/slskd/Core/Migrator.cs b/src/slskd/Core/Migrator.cs index 23580336..b9e98f4c 100644 --- a/src/slskd/Core/Migrator.cs +++ b/src/slskd/Core/Migrator.cs @@ -39,7 +39,7 @@ public class Migrator { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, }; - public void Migrate() + public void Migrate(bool force = false) { Dictionary history = new(); diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 266d04aa..870a1e83 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -391,6 +391,14 @@ namespace slskd [RequiresRestart] public bool ForceShareScan { get; init; } = false; + /// + /// Gets a value indicating whether to force database migrations to be applied on startup. + /// + [Argument(default, "force-migrations")] + [EnvironmentVariable("FORCE_MIGRATIONS")] + [Description("force database migrations to be applied on startup")] + public bool ForceMigrations { get; init; } = false; + /// /// Gets a value indicating whether the application should check for a newer version on startup. /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 8fbc0522..068e62ae 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -498,7 +498,7 @@ namespace slskd if (migrator is not null) { - migrator.Migrate(); + migrator.Migrate(force: OptionsAtStartup.Flags.ForceMigrations); } // hack: services that exist only to subscribe to the event bus are not referenced by anything else -- cgit v1.2.3 From 571617de9bff8d4a045c1857da97cc2ba787d5ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Apr 2025 20:17:03 -0500 Subject: run migrations when non-volatile --- src/slskd/Program.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 068e62ae..690960a7 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -494,11 +494,10 @@ namespace slskd var app = builder.Build(); - var migrator = app.Services.GetService(); - - if (migrator is not null) + if (!OptionsAtStartup.Flags.Volatile) { - migrator.Migrate(force: OptionsAtStartup.Flags.ForceMigrations); + // note: if this ever throws, we've forgotten to register a Migrator following database DI config + app.Services.GetService().Migrate(force: OptionsAtStartup.Flags.ForceMigrations); } // hack: services that exist only to subscribe to the event bus are not referenced by anything else @@ -606,7 +605,9 @@ namespace slskd // we're working with non-volatile database files, so register a Migrator to be used later in the // bootup process. the presence of a Migrator instance in DI determines whether a migration is needed. - services.AddSingleton(_ => new Migrator()); + // it's important that we keep this list of databases in sync with those used by the application; anything + // not in this list will not be able to be migrated. + services.AddSingleton(_ => new Migrator(databases: ["search", "transfers", "messaging", "events"])); } services.AddSingleton(); -- cgit v1.2.3 From 5e99dd513de1eb886803495ba144ffdeaa46cd1f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Apr 2025 20:17:15 -0500 Subject: finish migrator implementation --- src/slskd/Core/Migrator.cs | 173 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 147 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Migrator.cs b/src/slskd/Core/Migrator.cs index b9e98f4c..86056751 100644 --- a/src/slskd/Core/Migrator.cs +++ b/src/slskd/Core/Migrator.cs @@ -19,83 +19,204 @@ namespace slskd; using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; using Serilog; using slskd.Migrations; +/// +/// A database migration. +/// public interface IMigration { - public void Apply(); + /// + /// Apply the database migration. + /// + /// + /// The database list is included to help ensure that we're backing up databases before we start. Migrations + /// must check the supplied list to ensure the database(s) they are attempting to migrate are included; if + /// they are missing they haven't been backed up. + /// + /// A list of known databases. + public void Apply(IEnumerable databases); } +/// +/// Applies database migrations. +/// public class Migrator { - private string HistoryFile { get; } = Path.Combine(Program.DataDirectory, "misc", "migration.history"); + /// + /// Initializes a new instance of the class. + /// + /// A list of known databases. + public Migrator(params string[] databases) + { + Databases = databases; + } + + private string HistoryFileName { get; } = Path.Combine(Program.DataDirectory, "migration.history"); + private IEnumerable Databases { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + /// + /// A map of all migrations, to be applied in the order they are specified (descending). + /// private Dictionary Migrations { get; } = new() { { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, }; + /// + /// Applies database migrations. + /// + /// Apply all migrations, regardless of whether there's evidence they have been applied already. public void Migrate(bool force = false) { - Dictionary history = new(); + Dictionary history = []; - try + Log.Information("Checking for outstanding database migrations..."); + + // load migration history from the history file in the root of the data directory. this file contains a key/value + // pair for each migration that's been applied, along with the migration date. + // if force=true, we don't care about the history and there's no reason to look at it. + if (!force) { - if (File.Exists(HistoryFile)) + try { - try + if (File.Exists(HistoryFileName)) { - var txt = File.ReadAllText(HistoryFile); + var txt = File.ReadAllText(HistoryFileName); history = txt.FromJson>(); - Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFile, history); + Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFileName, history); } - catch (Exception ex) + else { - Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFile, ex.Message); - Log.Warning("Migration history will be overwritten and all migrations will be applied"); + Log.Debug("Migration history file {HistoryFile} was not found", HistoryFileName); } } + catch (Exception ex) + { + // log a message but don't throw; migrations are (should be!) idempotent, so there's no harm in running them, + // it just takes unnecessary time. + Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFileName, ex.Message); + Log.Warning("Migration history will be overwritten and all migrations will be applied"); + } + } + + // figure out which migrations need to be applied by taking the set difference of the migration list and the history contents + var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); + + if (!migrationsNotYetApplied.Any()) + { + Log.Information("Databases are up to date"); + return; + } + + Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); - var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); + // take some simple backups before we do anything. this gives users a way to get back to a working configuration + // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files + // must be left in place after the migration completes, and they'll be overwritten the next time a migration is applied + try + { + Log.Information("Backing up existing databases..."); - if (!migrationsNotYetApplied.Any()) + foreach (var database in Databases) { - Log.Debug("No migrations need to be applied"); + var name = Path.Combine(Program.DataDirectory, database); + var src = $"{name}.db"; + var dest = $"{name}.db.pre-migration"; + + File.Copy(src, dest, overwrite: true); + + Log.Information("Backed database {Original} up to {Backup}", src, dest); } - foreach (var migration in Migrations) + Log.Information("Databases backed up successfully"); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to back up one or more database(s) prior to migration, operation cannot continue: {Message}", ex.Message); + Log.Fatal("Try again, revert the application to the previous version, or delete existing databases (warning: history will be lost!) to continue"); + throw; + } + + // we know which migrations to apply, and we've backed all of the databases up. let's go! + try + { + Log.Warning("Beginning migration(s)"); + Log.Warning("This may take some time. Avoid stopping the application before the process is complete. If the process is interrupted it may be necessary to manually revert to backups."); + + var overallSw = new Stopwatch(); + overallSw.Start(); + + var current = 0; + var total = migrationsNotYetApplied.Count(); + + var currentSw = new Stopwatch(); + + foreach (var migration in migrationsNotYetApplied) { - if (history.TryGetValue(migration.Key, out var timestamp)) - { - Log.Debug("Migration {Name} was already applied {Date}", migration.Key, timestamp); - continue; - } + current++; + currentSw.Restart(); + + Log.Warning("Applying migration {Name} ({Current} of {Total})", migration, current, total); try { - migration.Value.Apply(); - history[migration.Key] = DateTime.UtcNow; + Migrations[migration].Apply(Databases); + history[migration] = DateTime.UtcNow; - Log.Information("Migration {Name} was applied successfully", migration.Key); + Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); } catch (Exception ex) { - Log.Fatal(ex, "Failed to apply migration {Name}: {Message}", migration.Key, ex.Message); + Log.Fatal(ex, "Failed to apply migration {Name}: {Message}", migration, ex.Message); throw; } } - File.WriteAllText(HistoryFile, history.ToJson()); + Log.Information("{Count} migration(s) applied successfully (elapsed: {Duration}ms elapsed)", total, overallSw.ElapsedMilliseconds); } catch (Exception ex) { - Log.Fatal(ex, "Failed to apply migrations: {Message}", ex.Message); + Log.Fatal(ex, "Failed to apply one or more migration(s): {Message}", ex.Message); + + try + { + Log.Information("Attempting to restore databases from backups..."); + + foreach (var database in Databases) + { + var name = Path.Combine(Program.DataDirectory, database); + var src = $"{name}.db.pre-migration"; + var dest = $"{name}.db"; + + // note: leave the backup in place to give users peace of mind + File.Copy(src, dest, overwrite: true); + + Log.Information("Restored {Original} from {Backup}", dest, src); + } + + Log.Information("Databases restored successfully"); + } + catch (Exception restoreEx) + { + Log.Fatal(restoreEx, "Failed to restore one or more databases from backup: {Message}", restoreEx.Message); + Log.Fatal("Restore manually by renaming '.db.pre-migration' to '.db' prior to starting the application again."); + throw; + } + throw; } + + var newHistory = history.ToJson(); + File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present + Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); + + Log.Information("Migration(s) complete"); } } \ No newline at end of file -- cgit v1.2.3 From bc5026519568bedaf49bc7aba20458d08a8656d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Apr 2025 20:17:31 -0500 Subject: update signature, throw on missing database --- src/slskd/Core/Migrations/TransferStateMigration_04012025.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs index 6b03567a..ea295851 100644 --- a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs +++ b/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs @@ -18,14 +18,21 @@ namespace slskd.Migrations; using System; +using System.Collections.Generic; using System.IO; +using System.Linq; using Microsoft.Data.Sqlite; public class TransferStateMigration_04012025 : IMigration { - public void Apply() - { + private string DbName => "transfers"; + public void Apply(IEnumerable databases) + { + if (!databases.Contains(DbName)) + { + throw new SlskdException($"Attempting to migrate database {DbName} but {DbName} is not in the list of known databases ({string.Join(",", databases)}). This is a precautionary check to ensure databases are properly backed up prior to migration, and the check has failed. Only an application update can fix this; please create an urgent issue: {Program.IssuesUrl}"); + } } static void AddStateDescriptionColumn(string dbPath) -- cgit v1.2.3 From 8f4dea8f4fe7708ddc8dd1f15dc8579dfab8b4d5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Apr 2025 14:21:24 -0500 Subject: stop msbuild from complaining about analyzers being newer --- src/slskd/slskd.csproj | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 0a5d0683..2c836ce4 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -13,6 +13,7 @@ true true false + <_SkipUpgradeNetAnalyzersNuGetWarning>true -- cgit v1.2.3 From 534d8824c4a3f1aae0448a17f734b57ea395c59f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Apr 2025 19:01:17 -0500 Subject: wip --- src/slskd/Common/Waiter.cs | 2 +- src/slskd/Core/Data/Migrations/Migration.cs | 82 ++++++++ .../Migrations/TransferStateMigration_04012025.cs | 155 ++++++++++++++ src/slskd/Core/Data/Migrator.cs | 204 +++++++++++++++++++ .../Migrations/TransferStateMigration_04012025.cs | 151 -------------- src/slskd/Core/Migrator.cs | 222 --------------------- src/slskd/Program.cs | 2 + 7 files changed, 444 insertions(+), 374 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/Migration.cs create mode 100644 src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs create mode 100644 src/slskd/Core/Data/Migrator.cs delete mode 100644 src/slskd/Core/Migrations/TransferStateMigration_04012025.cs delete mode 100644 src/slskd/Core/Migrator.cs (limited to 'src') diff --git a/src/slskd/Common/Waiter.cs b/src/slskd/Common/Waiter.cs index f8b3d305..d32f23b4 100644 --- a/src/slskd/Common/Waiter.cs +++ b/src/slskd/Common/Waiter.cs @@ -450,7 +450,7 @@ namespace slskd if (disposing) { CancellationTokenRegistration.Dispose(); - TimeoutTokenSource.Dispose(); + TimeoutTokenSource?.Dispose(); TimeoutTokenRegistration.Dispose(); } diff --git a/src/slskd/Core/Data/Migrations/Migration.cs b/src/slskd/Core/Data/Migrations/Migration.cs new file mode 100644 index 00000000..02f87a9c --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Migration.cs @@ -0,0 +1,82 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Migrations; + +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Data.Sqlite; + +public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); + +public abstract class Migration +{ + public Migration(string databaseName) + { + DatabaseName = databaseName; + } + + public string DatabaseName { get; } + public string DatabaseFileName => Path.Combine(Program.DataDirectory, DatabaseName); + public string ConnectionString => $"Data Source={DatabaseFileName}.db"; + + public abstract void Apply(); + + protected Dictionary> GetDatabaseSchema() + { + try + { + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + var dict = new Dictionary>(); + + using var tableCommand = new SqliteCommand("SELECT name FROM sqlite_master WHERE type='table';", connection); + using var tableReader = tableCommand.ExecuteReader(); + + while (tableReader.Read()) + { + var table = tableReader.GetString(0); + + var columns = new List(); + + using var columnCommand = new SqliteCommand($"PRAGMA table_info({table});", connection); + using var cr = columnCommand.ExecuteReader(); + + while (cr.Read()) + { + columns.Add(new ColumnInfo( + Cid: cr.GetInt64(cr.GetOrdinal("cid")), + Name: cr.GetString(cr.GetOrdinal("name")), + Type: cr.GetString(cr.GetOrdinal("type")), + NotNull: cr.GetInt64(cr.GetOrdinal("notnull")) > 0, + DefaultValue: cr["dflt_value"], + PrimaryKey: cr.GetInt64(cr.GetOrdinal("pk")) > 0)); + } + + dict[table] = columns; + } + + return dict; + } + catch (Exception ex) + { + throw new SlskdException($"Failed to retrieve schema information for database '{DatabaseName}'. The database might be corrupt or in use by another application; if the problem persists the file ({DatabaseFileName}) may need to be deleted", ex); + } + } +} \ No newline at end of file diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs new file mode 100644 index 00000000..37171a77 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -0,0 +1,155 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Migrations; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to: +/// +/// * Add a new StatusDescription (TEXT) column +/// * Copy the current (string) contents of the Status column to StatusDescription +/// * Change the type of the Status column to INTEGER +/// * Set the contents of the Status column to the numeric representation of the existing Status +/// +/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored +/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't +/// work against strings. Not sure why EF didn't complain about this, but here we are. +/// +public class TransferStateMigration_04012025 : Migration +{ + public TransferStateMigration_04012025(string databasName) + : base(databasName) + { + } + + private string DbName => "transfers"; + private ILogger Log { get; } = Serilog.Log.ForContext(); + + public override void Apply() + { + // first, check the existing database to see if the StatusDescription column exists + // if it does, the migration has already been applied + var schema = GetDatabaseSchema(); + var txfers = schema["Transfers"]; + + if (txfers.Any(c => c.Name == "StatusDescription")) + { + Log.Information("Migration {Name} has already been applied", nameof(TransferStateMigration_04012025)); + return; + } + + AddStateDescriptionColumn(Path.Combine(Program.DataDirectory, "transfers.db")); + } + + static void AddStateDescriptionColumn(string dbPath) + { + if (!File.Exists(dbPath)) + { + Console.WriteLine("Database file not found."); + return; + } + + string connectionString = $"Data Source={dbPath};"; + + using (var connection = new SqliteConnection(connectionString)) + { + connection.Open(); + + using (var transaction = connection.BeginTransaction()) + { + try + { + // Rename old table + using (var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection)) + { + renameCommand.ExecuteNonQuery(); + } + + // Create new table with StateDescription after State + string createNewTableSQL = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State INTEGER NOT NULL, + StateDescription TEXT, -- New column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + );"; + + using (var createCommand = new SqliteCommand(createNewTableSQL, connection)) + { + createCommand.ExecuteNonQuery(); + } + + // Copy data into the new table + string copyDataSQL = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using (var copyCommand = new SqliteCommand(copyDataSQL, connection)) + { + copyCommand.ExecuteNonQuery(); + } + + // Drop the old table + using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection)) + { + dropCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + Console.WriteLine("Column 'StateDescription' added successfully."); + } + catch (Exception ex) + { + transaction.Rollback(); + Console.WriteLine($"Error: {ex.Message}"); + } + } + + connection.Close(); + } + } +} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs new file mode 100644 index 00000000..f3543ca9 --- /dev/null +++ b/src/slskd/Core/Data/Migrator.cs @@ -0,0 +1,204 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using Serilog; +using slskd.Migrations; + +/// +/// Applies database migrations. +/// +public class Migrator +{ + /// + /// Initializes a new instance of the class. + /// + /// A list of known databases. + public Migrator(params string[] databases) + { + Databases = databases; + } + + private string HistoryFileName { get; } = Path.Combine(Program.DataDirectory, "migration.history"); + private IEnumerable Databases { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// A map of all migrations, to be applied in the order they are specified (descending). + /// + private Dictionary Migrations { get; } = new() + { + { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025("transfers") }, + }; + + /// + /// Applies database migrations. + /// + /// Apply all migrations, regardless of whether there's evidence they have been applied already. + public void Migrate(bool force = false) + { + Dictionary history = []; + + Log.Information("Checking for outstanding database migrations..."); + + // load migration history from the history file in the root of the data directory. this file contains a key/value + // pair for each migration that's been applied, along with the migration date. + // if force=true, we don't care about the history and there's no reason to look at it. + if (!force) + { + try + { + if (File.Exists(HistoryFileName)) + { + var txt = File.ReadAllText(HistoryFileName); + history = txt.FromJson>(); + + Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFileName, history); + } + else + { + Log.Debug("Migration history file {HistoryFile} was not found", HistoryFileName); + } + } + catch (Exception ex) + { + // log a message but don't throw; migrations are (should be!) idempotent, so there's no harm in running them, + // it just takes unnecessary time. + Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFileName, ex.Message); + Log.Warning("Migration history will be overwritten and all migrations will be applied"); + } + } + + // figure out which migrations need to be applied by taking the set difference of the migration list and the history contents + var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); + + if (!migrationsNotYetApplied.Any()) + { + Log.Information("Databases are up to date"); + return; + } + + Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); + + // take some simple backups before we do anything. this gives users a way to get back to a working configuration + // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files + // must be left in place after the migration completes, and they'll be overwritten the next time a migration is applied + try + { + Log.Information("Backing up existing databases..."); + + foreach (var database in Databases) + { + var name = Path.Combine(Program.DataDirectory, database); + var src = $"{name}.db"; + var dest = $"{name}.db.pre-migration"; + + File.Copy(src, dest, overwrite: true); + + Log.Information("Backed database {Original} up to {Backup}", src, dest); + } + + Log.Information("Databases backed up successfully"); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to back up one or more database(s) prior to migration, operation cannot continue: {Message}", ex.Message); + Log.Fatal("Try again, revert the application to the previous version, or delete existing databases (warning: history will be lost!) to continue"); + throw; + } + + // we know which migrations to apply, and we've backed all of the databases up. let's go! + try + { + Log.Warning("Beginning migration(s)"); + Log.Warning("This may take some time. Avoid stopping the application before the process is complete. If the process is interrupted it may be necessary to manually revert to backups."); + + var overallSw = new Stopwatch(); + overallSw.Start(); + + var current = 0; + var total = migrationsNotYetApplied.Count(); + + var currentSw = new Stopwatch(); + + foreach (var migration in migrationsNotYetApplied) + { + current++; + currentSw.Restart(); + + Log.Warning("Applying migration {Name} ({Current} of {Total})", migration, current, total); + + try + { + Migrations[migration].Apply(); + history[migration] = DateTime.UtcNow; + + Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to apply migration {Name}: {Message}", migration, ex.Message); + throw; + } + } + + Log.Information("{Count} migration(s) applied successfully (elapsed: {Duration}ms elapsed)", total, overallSw.ElapsedMilliseconds); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to apply one or more migration(s): {Message}", ex.Message); + + try + { + Log.Information("Attempting to restore databases from backups..."); + + foreach (var database in Databases) + { + var name = Path.Combine(Program.DataDirectory, database); + var src = $"{name}.db.pre-migration"; + var dest = $"{name}.db"; + + // note: leave the backup in place to give users peace of mind + File.Copy(src, dest, overwrite: true); + + Log.Information("Restored {Original} from {Backup}", dest, src); + } + + Log.Information("Databases restored successfully"); + } + catch (Exception restoreEx) + { + Log.Fatal(restoreEx, "Failed to restore one or more databases from backup: {Message}", restoreEx.Message); + Log.Fatal("Restore manually by renaming '.db.pre-migration' to '.db' prior to starting the application again."); + } + + throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); + } + + var newHistory = history.ToJson(); + File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present + Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); + + Log.Information("Migration(s) complete"); + } +} \ No newline at end of file diff --git a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs deleted file mode 100644 index ea295851..00000000 --- a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs +++ /dev/null @@ -1,151 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Migrations; - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Microsoft.Data.Sqlite; - -public class TransferStateMigration_04012025 : IMigration -{ - private string DbName => "transfers"; - - public void Apply(IEnumerable databases) - { - if (!databases.Contains(DbName)) - { - throw new SlskdException($"Attempting to migrate database {DbName} but {DbName} is not in the list of known databases ({string.Join(",", databases)}). This is a precautionary check to ensure databases are properly backed up prior to migration, and the check has failed. Only an application update can fix this; please create an urgent issue: {Program.IssuesUrl}"); - } - } - - static void AddStateDescriptionColumn(string dbPath) - { - if (!File.Exists(dbPath)) - { - Console.WriteLine("Database file not found."); - return; - } - - string connectionString = $"Data Source={dbPath};Version=3;"; - - using (var connection = new SqliteConnection(connectionString)) - { - connection.Open(); - - // Check if the column exists - bool columnExists = false; - using (var command = new SqliteCommand("PRAGMA table_info(Transfers);", connection)) - using (var reader = command.ExecuteReader()) - { - while (reader.Read()) - { - string columnName = reader["name"].ToString(); - if (columnName.Equals("StateDescription", StringComparison.OrdinalIgnoreCase)) - { - columnExists = true; - break; - } - } - } - - if (columnExists) - { - Console.WriteLine("Column 'StateDescription' already exists."); - return; - } - - Console.WriteLine("Adding 'StateDescription' column..."); - - using (var transaction = connection.BeginTransaction()) - { - try - { - // Rename old table - using (var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection)) - { - renameCommand.ExecuteNonQuery(); - } - - // Create new table with StateDescription after State - string createNewTableSQL = @" - CREATE TABLE Transfers ( - Id TEXT NOT NULL, - Username TEXT, - Direction TEXT NOT NULL, - Filename TEXT, - Size INTEGER NOT NULL, - StartOffset INTEGER NOT NULL, - State TEXT NOT NULL, - StateDescription TEXT, -- New column - RequestedAt TEXT NOT NULL, - EnqueuedAt TEXT, - StartedAt TEXT, - EndedAt TEXT, - BytesTransferred INTEGER NOT NULL, - AverageSpeed REAL NOT NULL, - PlaceInQueue INTEGER, - Exception TEXT, - Removed INTEGER NOT NULL, - CONSTRAINT PK_Transfers PRIMARY KEY(Id) - );"; - - using (var createCommand = new SqliteCommand(createNewTableSQL, connection)) - { - createCommand.ExecuteNonQuery(); - } - - // Copy data into the new table - string copyDataSQL = @" - INSERT INTO Transfers ( - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - ) - SELECT - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;"; - - using (var copyCommand = new SqliteCommand(copyDataSQL, connection)) - { - copyCommand.ExecuteNonQuery(); - } - - // Drop the old table - using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection)) - { - dropCommand.ExecuteNonQuery(); - } - - transaction.Commit(); - Console.WriteLine("Column 'StateDescription' added successfully."); - } - catch (Exception ex) - { - transaction.Rollback(); - Console.WriteLine($"Error: {ex.Message}"); - } - } - - connection.Close(); - } - } -} diff --git a/src/slskd/Core/Migrator.cs b/src/slskd/Core/Migrator.cs deleted file mode 100644 index 86056751..00000000 --- a/src/slskd/Core/Migrator.cs +++ /dev/null @@ -1,222 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd; - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using Serilog; -using slskd.Migrations; - -/// -/// A database migration. -/// -public interface IMigration -{ - /// - /// Apply the database migration. - /// - /// - /// The database list is included to help ensure that we're backing up databases before we start. Migrations - /// must check the supplied list to ensure the database(s) they are attempting to migrate are included; if - /// they are missing they haven't been backed up. - /// - /// A list of known databases. - public void Apply(IEnumerable databases); -} - -/// -/// Applies database migrations. -/// -public class Migrator -{ - /// - /// Initializes a new instance of the class. - /// - /// A list of known databases. - public Migrator(params string[] databases) - { - Databases = databases; - } - - private string HistoryFileName { get; } = Path.Combine(Program.DataDirectory, "migration.history"); - private IEnumerable Databases { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// A map of all migrations, to be applied in the order they are specified (descending). - /// - private Dictionary Migrations { get; } = new() - { - { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, - }; - - /// - /// Applies database migrations. - /// - /// Apply all migrations, regardless of whether there's evidence they have been applied already. - public void Migrate(bool force = false) - { - Dictionary history = []; - - Log.Information("Checking for outstanding database migrations..."); - - // load migration history from the history file in the root of the data directory. this file contains a key/value - // pair for each migration that's been applied, along with the migration date. - // if force=true, we don't care about the history and there's no reason to look at it. - if (!force) - { - try - { - if (File.Exists(HistoryFileName)) - { - var txt = File.ReadAllText(HistoryFileName); - history = txt.FromJson>(); - - Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFileName, history); - } - else - { - Log.Debug("Migration history file {HistoryFile} was not found", HistoryFileName); - } - } - catch (Exception ex) - { - // log a message but don't throw; migrations are (should be!) idempotent, so there's no harm in running them, - // it just takes unnecessary time. - Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFileName, ex.Message); - Log.Warning("Migration history will be overwritten and all migrations will be applied"); - } - } - - // figure out which migrations need to be applied by taking the set difference of the migration list and the history contents - var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); - - if (!migrationsNotYetApplied.Any()) - { - Log.Information("Databases are up to date"); - return; - } - - Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); - - // take some simple backups before we do anything. this gives users a way to get back to a working configuration - // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files - // must be left in place after the migration completes, and they'll be overwritten the next time a migration is applied - try - { - Log.Information("Backing up existing databases..."); - - foreach (var database in Databases) - { - var name = Path.Combine(Program.DataDirectory, database); - var src = $"{name}.db"; - var dest = $"{name}.db.pre-migration"; - - File.Copy(src, dest, overwrite: true); - - Log.Information("Backed database {Original} up to {Backup}", src, dest); - } - - Log.Information("Databases backed up successfully"); - } - catch (Exception ex) - { - Log.Fatal(ex, "Failed to back up one or more database(s) prior to migration, operation cannot continue: {Message}", ex.Message); - Log.Fatal("Try again, revert the application to the previous version, or delete existing databases (warning: history will be lost!) to continue"); - throw; - } - - // we know which migrations to apply, and we've backed all of the databases up. let's go! - try - { - Log.Warning("Beginning migration(s)"); - Log.Warning("This may take some time. Avoid stopping the application before the process is complete. If the process is interrupted it may be necessary to manually revert to backups."); - - var overallSw = new Stopwatch(); - overallSw.Start(); - - var current = 0; - var total = migrationsNotYetApplied.Count(); - - var currentSw = new Stopwatch(); - - foreach (var migration in migrationsNotYetApplied) - { - current++; - currentSw.Restart(); - - Log.Warning("Applying migration {Name} ({Current} of {Total})", migration, current, total); - - try - { - Migrations[migration].Apply(Databases); - history[migration] = DateTime.UtcNow; - - Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); - } - catch (Exception ex) - { - Log.Fatal(ex, "Failed to apply migration {Name}: {Message}", migration, ex.Message); - throw; - } - } - - Log.Information("{Count} migration(s) applied successfully (elapsed: {Duration}ms elapsed)", total, overallSw.ElapsedMilliseconds); - } - catch (Exception ex) - { - Log.Fatal(ex, "Failed to apply one or more migration(s): {Message}", ex.Message); - - try - { - Log.Information("Attempting to restore databases from backups..."); - - foreach (var database in Databases) - { - var name = Path.Combine(Program.DataDirectory, database); - var src = $"{name}.db.pre-migration"; - var dest = $"{name}.db"; - - // note: leave the backup in place to give users peace of mind - File.Copy(src, dest, overwrite: true); - - Log.Information("Restored {Original} from {Backup}", dest, src); - } - - Log.Information("Databases restored successfully"); - } - catch (Exception restoreEx) - { - Log.Fatal(restoreEx, "Failed to restore one or more databases from backup: {Message}", restoreEx.Message); - Log.Fatal("Restore manually by renaming '.db.pre-migration' to '.db' prior to starting the application again."); - throw; - } - - throw; - } - - var newHistory = history.ToJson(); - File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present - Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); - - Log.Information("Migration(s) complete"); - } -} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 690960a7..763b345a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -500,6 +500,8 @@ namespace slskd app.Services.GetService().Migrate(force: OptionsAtStartup.Flags.ForceMigrations); } + Environment.Exit(1); + // hack: services that exist only to subscribe to the event bus are not referenced by anything else // and are thus never instantiated. force a reference here so they are created. _ = app.Services.GetService(); -- cgit v1.2.3 From 6b1e7dbb741b284a788f97fb7d08991e11ef8c50 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Apr 2025 19:50:31 -0500 Subject: more wip --- .../Migrations/TransferStateMigration_04012025.cs | 108 ++++++++++++--------- 1 file changed, 61 insertions(+), 47 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs index 37171a77..ae9ada21 100644 --- a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -24,6 +24,7 @@ using System.Linq; using System.Text.Json; using Microsoft.Data.Sqlite; using Serilog; +using Soulseek; /// /// Updates the Transfers table to: @@ -44,7 +45,6 @@ public class TransferStateMigration_04012025 : Migration { } - private string DbName => "transfers"; private ILogger Log { get; } = Serilog.Log.ForContext(); public override void Apply() @@ -60,35 +60,46 @@ public class TransferStateMigration_04012025 : Migration return; } - AddStateDescriptionColumn(Path.Combine(Program.DataDirectory, "transfers.db")); + using var connection = new SqliteConnection($"Data Source={Path.Combine(Program.DataDirectory, "transfers.db")}"); + connection.Open(); + + // get a distinct list of states from the existing data and translate each into the corresponding integer + var stateMapping = GetStateMapping(connection); + + AddStateDescriptionColumn(connection, stateMapping); } - static void AddStateDescriptionColumn(string dbPath) + private Dictionary GetStateMapping(SqliteConnection connection) { - if (!File.Exists(dbPath)) + Log.Debug("Fetching states and mapping to integers..."); + + using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); + using var reader = command.ExecuteReader(); + + var dict = new Dictionary(); + + while (reader.Read()) { - Console.WriteLine("Database file not found."); - return; + var state = reader.GetString(0); + dict[state] = (int)Enum.Parse(typeof(TransferStates), state); } - string connectionString = $"Data Source={dbPath};"; + Log.Debug("State -> int map: {Map}", dict); + return dict; + } - using (var connection = new SqliteConnection(connectionString)) + private void AddStateDescriptionColumn(SqliteConnection connection, Dictionary stateMapping) + { + using (var transaction = connection.BeginTransaction()) { - connection.Open(); - - using (var transaction = connection.BeginTransaction()) + try { - try - { - // Rename old table - using (var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection)) - { - renameCommand.ExecuteNonQuery(); - } - - // Create new table with StateDescription after State - string createNewTableSQL = @" + // rename old table + var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection, transaction)) + renameCommand.ExecuteNonQuery(); + + // create new table with StateDescription after State + var createCommand = new SqliteCommand(@" CREATE TABLE Transfers ( Id TEXT NOT NULL, Username TEXT, @@ -97,7 +108,7 @@ public class TransferStateMigration_04012025 : Migration Size INTEGER NOT NULL, StartOffset INTEGER NOT NULL, State INTEGER NOT NULL, - StateDescription TEXT, -- New column + StateDescription TEXT, -- new column RequestedAt TEXT NOT NULL, EnqueuedAt TEXT, StartedAt TEXT, @@ -108,15 +119,11 @@ public class TransferStateMigration_04012025 : Migration Exception TEXT, Removed INTEGER NOT NULL, CONSTRAINT PK_Transfers PRIMARY KEY(Id) - );"; - - using (var createCommand = new SqliteCommand(createNewTableSQL, connection)) - { - createCommand.ExecuteNonQuery(); - } + );", connection, transaction); + createCommand.ExecuteNonQuery(); - // Copy data into the new table - string copyDataSQL = @" + // copy the old data into the new table + var copyCommand = new SqliteCommand(@" INSERT INTO Transfers ( Id, Username, Direction, Filename, Size, StartOffset, State, RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, @@ -126,30 +133,37 @@ public class TransferStateMigration_04012025 : Migration Id, Username, Direction, Filename, Size, StartOffset, State, RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;"; + FROM Transfers_old;", + connection, transaction); + copyCommand.ExecuteNonQuery(); - using (var copyCommand = new SqliteCommand(copyDataSQL, connection)) - { - copyCommand.ExecuteNonQuery(); - } + // copy the status from Status to StatusDescription + var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); + copyColumnCommand.ExecuteNonQuery(); - // Drop the old table - using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection)) - { - dropCommand.ExecuteNonQuery(); - } + // todo: set Status to the integer representation of the column + foreach (var state in stateMapping) + { + Log.Debug("Set {String} to {Int}", state.Key, state.Value); - transaction.Commit(); - Console.WriteLine("Column 'StateDescription' added successfully."); + var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = {state.Key}"); + mapCommand.ExecuteNonQuery(); } - catch (Exception ex) + + // Drop the old table + using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction)) { - transaction.Rollback(); - Console.WriteLine($"Error: {ex.Message}"); + dropCommand.ExecuteNonQuery(); } - } - connection.Close(); + transaction.Commit(); + Console.WriteLine("Column 'StateDescription' added successfully."); + } + catch (Exception ex) + { + transaction.Rollback(); + Console.WriteLine($"Error: {ex.Message}"); + } } } } -- cgit v1.2.3 From a21903811d39a978e2c6acc275bba670abee5574 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 5 Apr 2025 15:01:47 -0500 Subject: formatting. make state updates work --- .../Migrations/TransferStateMigration_04012025.cs | 179 ++++++++++++--------- 1 file changed, 105 insertions(+), 74 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs index ae9ada21..a3da5435 100644 --- a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -19,9 +19,9 @@ namespace slskd.Migrations; using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; -using System.Text.Json; using Microsoft.Data.Sqlite; using Serilog; using Soulseek; @@ -66,7 +66,7 @@ public class TransferStateMigration_04012025 : Migration // get a distinct list of states from the existing data and translate each into the corresponding integer var stateMapping = GetStateMapping(connection); - AddStateDescriptionColumn(connection, stateMapping); + ModifyTableAndMassageData(connection, stateMapping); } private Dictionary GetStateMapping(SqliteConnection connection) @@ -88,82 +88,113 @@ public class TransferStateMigration_04012025 : Migration return dict; } - private void AddStateDescriptionColumn(SqliteConnection connection, Dictionary stateMapping) + private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) { - using (var transaction = connection.BeginTransaction()) + using var transaction = connection.BeginTransaction(); + + try { - try - { - // rename old table - var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection, transaction)) - renameCommand.ExecuteNonQuery(); - - // create new table with StateDescription after State - var createCommand = new SqliteCommand(@" - CREATE TABLE Transfers ( - Id TEXT NOT NULL, - Username TEXT, - Direction TEXT NOT NULL, - Filename TEXT, - Size INTEGER NOT NULL, - StartOffset INTEGER NOT NULL, - State INTEGER NOT NULL, - StateDescription TEXT, -- new column - RequestedAt TEXT NOT NULL, - EnqueuedAt TEXT, - StartedAt TEXT, - EndedAt TEXT, - BytesTransferred INTEGER NOT NULL, - AverageSpeed REAL NOT NULL, - PlaceInQueue INTEGER, - Exception TEXT, - Removed INTEGER NOT NULL, - CONSTRAINT PK_Transfers PRIMARY KEY(Id) - );", connection, transaction); - createCommand.ExecuteNonQuery(); - - // copy the old data into the new table - var copyCommand = new SqliteCommand(@" - INSERT INTO Transfers ( - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - ) - SELECT - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;", - connection, transaction); - copyCommand.ExecuteNonQuery(); - - // copy the status from Status to StatusDescription - var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); - copyColumnCommand.ExecuteNonQuery(); - - // todo: set Status to the integer representation of the column - foreach (var state in stateMapping) - { - Log.Debug("Set {String} to {Int}", state.Key, state.Value); - - var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = {state.Key}"); - mapCommand.ExecuteNonQuery(); - } - - // Drop the old table - using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction)) - { - dropCommand.ExecuteNonQuery(); - } - - transaction.Commit(); - Console.WriteLine("Column 'StateDescription' added successfully."); - } - catch (Exception ex) + /* + rename old table so we can create the new one with the layout we want + while preserving the existing data + */ + var rename = @" + ALTER TABLE Transfers RENAME TO Transfers_old; + "; + + using var renameCommand = new SqliteCommand(rename, connection, transaction); + renameCommand.ExecuteNonQuery(); + + /* + create the new table with StateDescription appearing after State + */ + var create = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State INTEGER NOT NULL, + StateDescription TEXT, -- new column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + ); + "; + + using var createCommand = new SqliteCommand(create, connection, transaction); + createCommand.ExecuteNonQuery(); + + /* + copy the existing data into the new table + */ + var copy = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using var copyCommand = new SqliteCommand(copy, connection, transaction); + copyCommand.ExecuteNonQuery(); + + /* + we no longer need the old table, so drop it + */ + using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); + dropCommand.ExecuteNonQuery(); + + /* + copy the existing (string) State value from State to StateDescription + */ + var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); + copyColumnCommand.ExecuteNonQuery(); + + /* + for each of the distinct State values that exist in the data, convert the string + representation into the numeric + + there surely exist better ways to do this, but the reality is that 99% of the records + will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" + sprinkled in. this should run in reasonable time for large collections + + todo: benchmark this against a db with a lot of transfers + */ + var sw = new Stopwatch(); + + foreach (var state in stateMapping) { - transaction.Rollback(); - Console.WriteLine($"Error: {ex.Message}"); + sw.Reset(); + Log.Debug("Setting {String} to {Int}", state.Key, state.Value); + + var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); + mapCommand.ExecuteNonQuery(); + + Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); } + + Log.Debug("Committing transation..."); + transaction.Commit(); + Log.Debug("Transaction committed!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; } } } -- cgit v1.2.3 From 836934203dc314e08b3e351f60bbf70f14a1d1fc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 5 Apr 2025 16:55:54 -0500 Subject: more wip --- src/slskd/Core/Data/Migrations/Migration.cs | 82 ---------------------- .../Core/Data/Migrations/TEMP_SeedTransfers.cs | 56 +++++++++++++++ .../Migrations/TransferStateMigration_04012025.cs | 15 ++-- src/slskd/Core/Data/Migrator.cs | 64 +++++++++++++++-- 4 files changed, 122 insertions(+), 95 deletions(-) delete mode 100644 src/slskd/Core/Data/Migrations/Migration.cs create mode 100644 src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Migration.cs b/src/slskd/Core/Data/Migrations/Migration.cs deleted file mode 100644 index 02f87a9c..00000000 --- a/src/slskd/Core/Data/Migrations/Migration.cs +++ /dev/null @@ -1,82 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Migrations; - -using System; -using System.Collections.Generic; -using System.IO; -using Microsoft.Data.Sqlite; - -public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); - -public abstract class Migration -{ - public Migration(string databaseName) - { - DatabaseName = databaseName; - } - - public string DatabaseName { get; } - public string DatabaseFileName => Path.Combine(Program.DataDirectory, DatabaseName); - public string ConnectionString => $"Data Source={DatabaseFileName}.db"; - - public abstract void Apply(); - - protected Dictionary> GetDatabaseSchema() - { - try - { - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - var dict = new Dictionary>(); - - using var tableCommand = new SqliteCommand("SELECT name FROM sqlite_master WHERE type='table';", connection); - using var tableReader = tableCommand.ExecuteReader(); - - while (tableReader.Read()) - { - var table = tableReader.GetString(0); - - var columns = new List(); - - using var columnCommand = new SqliteCommand($"PRAGMA table_info({table});", connection); - using var cr = columnCommand.ExecuteReader(); - - while (cr.Read()) - { - columns.Add(new ColumnInfo( - Cid: cr.GetInt64(cr.GetOrdinal("cid")), - Name: cr.GetString(cr.GetOrdinal("name")), - Type: cr.GetString(cr.GetOrdinal("type")), - NotNull: cr.GetInt64(cr.GetOrdinal("notnull")) > 0, - DefaultValue: cr["dflt_value"], - PrimaryKey: cr.GetInt64(cr.GetOrdinal("pk")) > 0)); - } - - dict[table] = columns; - } - - return dict; - } - catch (Exception ex) - { - throw new SlskdException($"Failed to retrieve schema information for database '{DatabaseName}'. The database might be corrupt or in use by another application; if the problem persists the file ({DatabaseFileName}) may need to be deleted", ex); - } - } -} \ No newline at end of file diff --git a/src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs b/src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs new file mode 100644 index 00000000..9f973023 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs @@ -0,0 +1,56 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Migrations; + +using System; +using System.IO; +using Microsoft.Data.Sqlite; +using Serilog; + +public class TEMP_SeedTransfers : IMigration +{ + private ILogger Log { get; } = Serilog.Log.ForContext(); + + public void Apply() + { + using var connection = new SqliteConnection($"Data Source={Path.Combine(Program.DataDirectory, "transfers.db")}"); + connection.Open(); + + Log.Warning("Staring seed"); + + for (long i = 0; i < 10_000; i++) + { + string s(Guid id) => @$" + INSERT INTO Transfers (Id, Username, Direction, Filename, Size, StartOffset, State, RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, AverageSpeed, PlaceInQueue, Removed) + VALUES ('{id}', 'Username', 'Download', 'Foo.mp3', 42, 0, 'Completed, Succeeded', '1/1/1970 0:0:0', '1/1/1970 0:0:0', '1/1/1970 0:0:0', '1/1/1970 0:0:0', 42, 0, 0, 1); + "; + + string sql = ""; + + for (int j = 0; j < 5_000; j++) + { + sql += s(Guid.NewGuid()); + } + + using var cmd = new SqliteCommand(sql, connection); + + cmd.ExecuteNonQuery(); + Log.Warning("Completed {i}", i * 5000); + } + } +} diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs index a3da5435..6d8b4cfc 100644 --- a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -38,20 +38,17 @@ using Soulseek; /// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't /// work against strings. Not sure why EF didn't complain about this, but here we are. /// -public class TransferStateMigration_04012025 : Migration +public class TransferStateMigration_04012025 : IMigration { - public TransferStateMigration_04012025(string databasName) - : base(databasName) - { - } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private string DatabaseName { get; } = "transfers"; + private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; - public override void Apply() + public void Apply() { // first, check the existing database to see if the StatusDescription column exists // if it does, the migration has already been applied - var schema = GetDatabaseSchema(); + var schema = Migrator.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; if (txfers.Any(c => c.Name == "StatusDescription")) @@ -60,7 +57,7 @@ public class TransferStateMigration_04012025 : Migration return; } - using var connection = new SqliteConnection($"Data Source={Path.Combine(Program.DataDirectory, "transfers.db")}"); + using var connection = new SqliteConnection(ConnectionString); connection.Open(); // get a distinct list of states from the existing data and translate each into the corresponding integer diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index f3543ca9..152624ba 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -22,9 +22,15 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; +using Microsoft.Data.Sqlite; using Serilog; using slskd.Migrations; +public interface IMigration +{ + void Apply(); +} + /// /// Applies database migrations. /// @@ -46,9 +52,10 @@ public class Migrator /// /// A map of all migrations, to be applied in the order they are specified (descending). /// - private Dictionary Migrations { get; } = new() + private Dictionary Migrations { get; } = new() { - { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025("transfers") }, + // { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, + { nameof(TEMP_SeedTransfers), new TEMP_SeedTransfers() }, }; /// @@ -100,6 +107,10 @@ public class Migrator Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); + var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss"); + + Log.Warning("-----> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups. <-----", migrationId); + // take some simple backups before we do anything. this gives users a way to get back to a working configuration // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files // must be left in place after the migration completes, and they'll be overwritten the next time a migration is applied @@ -111,7 +122,7 @@ public class Migrator { var name = Path.Combine(Program.DataDirectory, database); var src = $"{name}.db"; - var dest = $"{name}.db.pre-migration"; + var dest = $"{name}.pre-migration.{migrationId}.db"; File.Copy(src, dest, overwrite: true); @@ -189,7 +200,7 @@ public class Migrator catch (Exception restoreEx) { Log.Fatal(restoreEx, "Failed to restore one or more databases from backup: {Message}", restoreEx.Message); - Log.Fatal("Restore manually by renaming '.db.pre-migration' to '.db' prior to starting the application again."); + Log.Fatal($"Restore manually by renaming '.pre-migration.{migrationId}.db' to '.db' prior to starting the application again."); } throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); @@ -201,4 +212,49 @@ public class Migrator Log.Information("Migration(s) complete"); } + + public static Dictionary> GetDatabaseSchema(string connectionString) + { + try + { + using var connection = new SqliteConnection(connectionString); + connection.Open(); + + var dict = new Dictionary>(); + + using var tableCommand = new SqliteCommand("SELECT name FROM sqlite_master WHERE type='table';", connection); + using var tableReader = tableCommand.ExecuteReader(); + + while (tableReader.Read()) + { + var table = tableReader.GetString(0); + + var columns = new List(); + + using var columnCommand = new SqliteCommand($"PRAGMA table_info({table});", connection); + using var cr = columnCommand.ExecuteReader(); + + while (cr.Read()) + { + columns.Add(new ColumnInfo( + Cid: cr.GetInt64(cr.GetOrdinal("cid")), + Name: cr.GetString(cr.GetOrdinal("name")), + Type: cr.GetString(cr.GetOrdinal("type")), + NotNull: cr.GetInt64(cr.GetOrdinal("notnull")) > 0, + DefaultValue: cr["dflt_value"], + PrimaryKey: cr.GetInt64(cr.GetOrdinal("pk")) > 0)); + } + + dict[table] = columns; + } + + return dict; + } + catch (Exception ex) + { + throw new SlskdException($"Failed to retrieve schema information for database '{connectionString}'. The database might be corrupt or in use by another application; if the problem persists the backing file may need to be deleted", ex); + } + } + + public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); } \ No newline at end of file -- cgit v1.2.3 From e4d5e2cce9f4400c901284da5d5c4f7be548bd88 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 May 2025 17:19:44 -0500 Subject: make a dedicated backup directory --- src/slskd/Program.cs | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 763b345a..f1cb441f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -187,6 +187,11 @@ namespace slskd /// public static string DataDirectory { get; private set; } = null; + /// + /// Gets the path where database migration information is saved. + /// + public static string DataMigrationsDirectory { get; private set; } = null; + /// /// Gets the default fully qualified path to the configuration file. /// @@ -353,6 +358,7 @@ namespace slskd { VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(DataDirectory, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(DataMigrationsDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(ScriptDirectory, createIfMissing: true, verifyWriteable: false); VerifyDirectory(DefaultDownloadsDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(DefaultIncompleteDirectory, createIfMissing: true, verifyWriteable: true); @@ -496,10 +502,13 @@ namespace slskd if (!OptionsAtStartup.Flags.Volatile) { + Log.Debug($"Running migrations..."); + // note: if this ever throws, we've forgotten to register a Migrator following database DI config app.Services.GetService().Migrate(force: OptionsAtStartup.Flags.ForceMigrations); } + // todo: don't forget to take this out Environment.Exit(1); // hack: services that exist only to subscribe to the event bus are not referenced by anything else -- cgit v1.2.3 From 69bceab8a86fc5b0481b03816879aae9d6dbf96c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 May 2025 17:20:29 -0500 Subject: split schema inspection, tweak paths --- src/slskd/Core/Data/Migrator.cs | 65 +++++---------------------- src/slskd/Core/Data/SchemaInspector.cs | 82 ++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 55 deletions(-) create mode 100644 src/slskd/Core/Data/SchemaInspector.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 152624ba..69294cf5 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -22,7 +22,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; -using Microsoft.Data.Sqlite; using Serilog; using slskd.Migrations; @@ -45,7 +44,7 @@ public class Migrator Databases = databases; } - private string HistoryFileName { get; } = Path.Combine(Program.DataDirectory, "migration.history"); + private string HistoryFileName { get; } = Path.Combine(Program.DataMigrationsDirectory, "history"); private IEnumerable Databases { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -54,8 +53,7 @@ public class Migrator /// private Dictionary Migrations { get; } = new() { - // { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, - { nameof(TEMP_SeedTransfers), new TEMP_SeedTransfers() }, + { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, }; /// @@ -109,7 +107,7 @@ public class Migrator var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss"); - Log.Warning("-----> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups. <-----", migrationId); + Log.Warning("-----> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups, should manual cleanup be needed. <-----", migrationId); // take some simple backups before we do anything. this gives users a way to get back to a working configuration // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files @@ -120,9 +118,8 @@ public class Migrator foreach (var database in Databases) { - var name = Path.Combine(Program.DataDirectory, database); - var src = $"{name}.db"; - var dest = $"{name}.pre-migration.{migrationId}.db"; + var src = MakeSourceDatabasePath(database); + var dest = MakeBackupDatabasePath(database, migrationId); File.Copy(src, dest, overwrite: true); @@ -186,10 +183,10 @@ public class Migrator foreach (var database in Databases) { var name = Path.Combine(Program.DataDirectory, database); - var src = $"{name}.db.pre-migration"; - var dest = $"{name}.db"; + var src = MakeBackupDatabasePath(database, migrationId); + var dest = MakeSourceDatabasePath(database); - // note: leave the backup in place to give users peace of mind + // note: leave the backup in place just in case; automatic cleanup will delete them later File.Copy(src, dest, overwrite: true); Log.Information("Restored {Original} from {Backup}", dest, src); @@ -213,48 +210,6 @@ public class Migrator Log.Information("Migration(s) complete"); } - public static Dictionary> GetDatabaseSchema(string connectionString) - { - try - { - using var connection = new SqliteConnection(connectionString); - connection.Open(); - - var dict = new Dictionary>(); - - using var tableCommand = new SqliteCommand("SELECT name FROM sqlite_master WHERE type='table';", connection); - using var tableReader = tableCommand.ExecuteReader(); - - while (tableReader.Read()) - { - var table = tableReader.GetString(0); - - var columns = new List(); - - using var columnCommand = new SqliteCommand($"PRAGMA table_info({table});", connection); - using var cr = columnCommand.ExecuteReader(); - - while (cr.Read()) - { - columns.Add(new ColumnInfo( - Cid: cr.GetInt64(cr.GetOrdinal("cid")), - Name: cr.GetString(cr.GetOrdinal("name")), - Type: cr.GetString(cr.GetOrdinal("type")), - NotNull: cr.GetInt64(cr.GetOrdinal("notnull")) > 0, - DefaultValue: cr["dflt_value"], - PrimaryKey: cr.GetInt64(cr.GetOrdinal("pk")) > 0)); - } - - dict[table] = columns; - } - - return dict; - } - catch (Exception ex) - { - throw new SlskdException($"Failed to retrieve schema information for database '{connectionString}'. The database might be corrupt or in use by another application; if the problem persists the backing file may need to be deleted", ex); - } - } - - public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); + private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db"); + private string MakeBackupDatabasePath(string database, string timestamp) => Path.Combine(Program.DataMigrationsDirectory, $"{database}.pre-migration-backup.{timestamp}.db"); } \ No newline at end of file diff --git a/src/slskd/Core/Data/SchemaInspector.cs b/src/slskd/Core/Data/SchemaInspector.cs new file mode 100644 index 00000000..234b9100 --- /dev/null +++ b/src/slskd/Core/Data/SchemaInspector.cs @@ -0,0 +1,82 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd; + +using System; +using System.Collections.Generic; +using Microsoft.Data.Sqlite; + +/// +/// Assistive class for inspecting SQLite database schemas. +/// +public static class SchemaInspector +{ + /// + /// Retrieves the schema information for the specified SQLite database. + /// + /// The connection string for the database. + /// The schema information. + /// Thrown if the database can't be accessed, or something else goes wrong. + public static Dictionary> GetDatabaseSchema(string connectionString) + { + try + { + using var connection = new SqliteConnection(connectionString); + connection.Open(); + + var dict = new Dictionary>(); + + using var tableCommand = new SqliteCommand("SELECT name FROM sqlite_master WHERE type='table';", connection); + using var tableReader = tableCommand.ExecuteReader(); + + while (tableReader.Read()) + { + var table = tableReader.GetString(0); + + var columns = new List(); + + using var columnCommand = new SqliteCommand($"PRAGMA table_info({table});", connection); + using var cr = columnCommand.ExecuteReader(); + + while (cr.Read()) + { + columns.Add(new ColumnInfo( + Cid: cr.GetInt64(cr.GetOrdinal("cid")), + Name: cr.GetString(cr.GetOrdinal("name")), + Type: cr.GetString(cr.GetOrdinal("type")), + NotNull: cr.GetInt64(cr.GetOrdinal("notnull")) > 0, + DefaultValue: cr["dflt_value"], + PrimaryKey: cr.GetInt64(cr.GetOrdinal("pk")) > 0)); + } + + dict[table] = columns; + } + + return dict; + } + catch (Exception ex) + { + throw new SlskdException($"Failed to retrieve schema information for database '{connectionString}'. The database might be corrupt or in use by another application; if the problem persists the backing file may need to be deleted", ex); + } + } + + /// + /// Represents a SQLite database column. + /// + public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); +} \ No newline at end of file -- cgit v1.2.3 From 8d348b053fba4c7152bf460eb81432db698b7161 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 May 2025 17:20:39 -0500 Subject: document migrations --- src/slskd/Core/Data/Migrations/README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/slskd/Core/Data/Migrations/README.md (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md new file mode 100644 index 00000000..1f603b42 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/README.md @@ -0,0 +1,27 @@ +# Database Migrations + +In the hopefully unlikely event that a migration is necessary, a migration must be written. + +Migrations are applied by the `Migrator` at startup. + +The `history` file in the data directory is used to attempt to track whether migrations have already been applied. If a migration appears in the history file it won't be run again. Users can delete or modify the `history` file or use the `force` flag to apply them, meaning migrations **MUST** be idempotent. + +The `Migrator` creates a backup of each database prior to running any migrations, and if an exception is thrown at any time during the process the `Migrator` will revert to these backups automatically. The backup files are left in place when the migration is complete so that users can manually revert if the migration left their application in a bad state or destroyed or lost data. + +## Creating a Migration + +Each migration must be created as a class that implements the `IMigration` interface. + +Migrations MUST: + +* Figure out where on disk the associated database(s) are located. This is accomplished by combining the static `Program.DataDirectory` variable +and the name(s) of the table(s) that need to be migrated. +* Log progress, so users can see that the application is performing work while records are updated. +* Use transactions when performing database operations and using/try catch where appropriate to avoid partially applied migrations. +* Inspect the target database(s) schema to determine whether the migration needs to be applied (if possible) + +When the migration is complete, edit the `Migrations` property in the `Migrator` to add the migration to the list in the proper order. + +### Above all else, each and every migration **MUST** be idempotent. + +Users can delete the history file or use the `force` flag to cause migrations to be run again. We can inspect schemas to determine whether re-running is necessary, but there may be cases where that's not enough. \ No newline at end of file -- cgit v1.2.3 From d43c1aba9c07258d9f7f0b9ba59eb6fe33d4bb2c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 May 2025 17:21:02 -0500 Subject: delete seed migration, tweak reference to schema inspector --- .../Core/Data/Migrations/TEMP_SeedTransfers.cs | 56 ---------------------- .../Migrations/TransferStateMigration_04012025.cs | 4 +- 2 files changed, 1 insertion(+), 59 deletions(-) delete mode 100644 src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs b/src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs deleted file mode 100644 index 9f973023..00000000 --- a/src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Migrations; - -using System; -using System.IO; -using Microsoft.Data.Sqlite; -using Serilog; - -public class TEMP_SeedTransfers : IMigration -{ - private ILogger Log { get; } = Serilog.Log.ForContext(); - - public void Apply() - { - using var connection = new SqliteConnection($"Data Source={Path.Combine(Program.DataDirectory, "transfers.db")}"); - connection.Open(); - - Log.Warning("Staring seed"); - - for (long i = 0; i < 10_000; i++) - { - string s(Guid id) => @$" - INSERT INTO Transfers (Id, Username, Direction, Filename, Size, StartOffset, State, RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, AverageSpeed, PlaceInQueue, Removed) - VALUES ('{id}', 'Username', 'Download', 'Foo.mp3', 42, 0, 'Completed, Succeeded', '1/1/1970 0:0:0', '1/1/1970 0:0:0', '1/1/1970 0:0:0', '1/1/1970 0:0:0', 42, 0, 0, 1); - "; - - string sql = ""; - - for (int j = 0; j < 5_000; j++) - { - sql += s(Guid.NewGuid()); - } - - using var cmd = new SqliteCommand(sql, connection); - - cmd.ExecuteNonQuery(); - Log.Warning("Completed {i}", i * 5000); - } - } -} diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs index 6d8b4cfc..7229eee4 100644 --- a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -48,7 +48,7 @@ public class TransferStateMigration_04012025 : IMigration { // first, check the existing database to see if the StatusDescription column exists // if it does, the migration has already been applied - var schema = Migrator.GetDatabaseSchema(ConnectionString); + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; if (txfers.Any(c => c.Name == "StatusDescription")) @@ -168,8 +168,6 @@ public class TransferStateMigration_04012025 : IMigration there surely exist better ways to do this, but the reality is that 99% of the records will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" sprinkled in. this should run in reasonable time for large collections - - todo: benchmark this against a db with a lot of transfers */ var sw = new Stopwatch(); -- cgit v1.2.3 From 207a645006f75a0fb96f2a1b6a72017f94d42c80 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 May 2025 17:53:05 -0500 Subject: adjust logs --- src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs | 8 ++++++++ src/slskd/Core/Data/Migrator.cs | 8 ++++---- src/slskd/Program.cs | 3 ++- 3 files changed, 14 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs index 7229eee4..1ea3ca87 100644 --- a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -131,6 +131,8 @@ public class TransferStateMigration_04012025 : IMigration using var createCommand = new SqliteCommand(create, connection, transaction); createCommand.ExecuteNonQuery(); + Log.Information("Schema changes applied, copying data..."); + /* copy the existing data into the new table */ @@ -149,6 +151,8 @@ public class TransferStateMigration_04012025 : IMigration using var copyCommand = new SqliteCommand(copy, connection, transaction); copyCommand.ExecuteNonQuery(); + Log.Information("Data copied, adjusting columns..."); + /* we no longer need the old table, so drop it */ @@ -170,10 +174,13 @@ public class TransferStateMigration_04012025 : IMigration sprinkled in. this should run in reasonable time for large collections */ var sw = new Stopwatch(); + var step = 1; foreach (var state in stateMapping) { sw.Reset(); + Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); + Log.Debug("Setting {String} to {Int}", state.Key, state.Value); var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); @@ -185,6 +192,7 @@ public class TransferStateMigration_04012025 : IMigration Log.Debug("Committing transation..."); transaction.Commit(); Log.Debug("Transaction committed!"); + Log.Information("Done!"); } catch (Exception) { diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 69294cf5..ffaae586 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -99,7 +99,7 @@ public class Migrator if (!migrationsNotYetApplied.Any()) { - Log.Information("Databases are up to date"); + Log.Information("Databases are up to date!"); return; } @@ -107,7 +107,7 @@ public class Migrator var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss"); - Log.Warning("-----> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups, should manual cleanup be needed. <-----", migrationId); + Log.Warning("--> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups, should manual cleanup be needed. <--", migrationId); // take some simple backups before we do anything. this gives users a way to get back to a working configuration // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files @@ -170,7 +170,7 @@ public class Migrator } } - Log.Information("{Count} migration(s) applied successfully (elapsed: {Duration}ms elapsed)", total, overallSw.ElapsedMilliseconds); + Log.Information("{Count} migration(s) applied successfully (elapsed: {Duration}ms)", total, overallSw.ElapsedMilliseconds); } catch (Exception ex) { @@ -207,7 +207,7 @@ public class Migrator File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); - Log.Information("Migration(s) complete"); + Log.Information("Migration(s) complete!"); } private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db"); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f1cb441f..f1e9e7f5 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -341,6 +341,7 @@ namespace slskd // derive the application directory value and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; DataDirectory = Path.Combine(AppDirectory, "data"); + DataMigrationsDirectory = Path.Combine(DataDirectory, "migrations"); LogDirectory = Path.Combine(AppDirectory, "logs"); ScriptDirectory = Path.Combine(AppDirectory, "scripts"); @@ -502,7 +503,7 @@ namespace slskd if (!OptionsAtStartup.Flags.Volatile) { - Log.Debug($"Running migrations..."); + Log.Information($"Running migrations..."); // note: if this ever throws, we've forgotten to register a Migrator following database DI config app.Services.GetService().Migrate(force: OptionsAtStartup.Flags.ForceMigrations); -- cgit v1.2.3 From 3c70698c39ec1fbe4d522f5c0cdde978d84c1cc0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 May 2025 18:01:19 -0500 Subject: docs, rename migration --- src/slskd/Core/Data/Migrations/README.md | 14 +- .../Migrations/TransferStateMigration_04012025.cs | 203 -------------------- .../Migrations/z04012025_TransferStateMigration.cs | 204 +++++++++++++++++++++ src/slskd/Core/Data/Migrator.cs | 2 +- 4 files changed, 214 insertions(+), 209 deletions(-) delete mode 100644 src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs create mode 100644 src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index 1f603b42..0cafbe6a 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -1,6 +1,6 @@ # Database Migrations -In the hopefully unlikely event that a migration is necessary, a migration must be written. +In the hopefully unlikely event that a non-backwards-compatible schema change to a database migration is necessary, a migration must be written. Migrations are applied by the `Migrator` at startup. @@ -10,17 +10,21 @@ The `Migrator` creates a backup of each database prior to running any migrations ## Creating a Migration -Each migration must be created as a class that implements the `IMigration` interface. +Each migration must be created as a class that implements the `IMigration` interface. The naming convention for migration classes is: + +``` +z_Migration +``` Migrations MUST: * Figure out where on disk the associated database(s) are located. This is accomplished by combining the static `Program.DataDirectory` variable and the name(s) of the table(s) that need to be migrated. -* Log progress, so users can see that the application is performing work while records are updated. -* Use transactions when performing database operations and using/try catch where appropriate to avoid partially applied migrations. * Inspect the target database(s) schema to determine whether the migration needs to be applied (if possible) +* Use transactions when performing database operations and using/try catch where appropriate to avoid partially applied migrations. +* Log progress, so users can see that the application is performing work while records are updated. -When the migration is complete, edit the `Migrations` property in the `Migrator` to add the migration to the list in the proper order. +The new `IMigration` implementation must be added to the dictionary in the `Migrations` property of the `Migrator` in the desired order so that it can be run. ### Above all else, each and every migration **MUST** be idempotent. diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs deleted file mode 100644 index 1ea3ca87..00000000 --- a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs +++ /dev/null @@ -1,203 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Migrations; - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using Soulseek; - -/// -/// Updates the Transfers table to: -/// -/// * Add a new StatusDescription (TEXT) column -/// * Copy the current (string) contents of the Status column to StatusDescription -/// * Change the type of the Status column to INTEGER -/// * Set the contents of the Status column to the numeric representation of the existing Status -/// -/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored -/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't -/// work against strings. Not sure why EF didn't complain about this, but here we are. -/// -public class TransferStateMigration_04012025 : IMigration -{ - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string DatabaseName { get; } = "transfers"; - private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; - - public void Apply() - { - // first, check the existing database to see if the StatusDescription column exists - // if it does, the migration has already been applied - var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); - var txfers = schema["Transfers"]; - - if (txfers.Any(c => c.Name == "StatusDescription")) - { - Log.Information("Migration {Name} has already been applied", nameof(TransferStateMigration_04012025)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - // get a distinct list of states from the existing data and translate each into the corresponding integer - var stateMapping = GetStateMapping(connection); - - ModifyTableAndMassageData(connection, stateMapping); - } - - private Dictionary GetStateMapping(SqliteConnection connection) - { - Log.Debug("Fetching states and mapping to integers..."); - - using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); - using var reader = command.ExecuteReader(); - - var dict = new Dictionary(); - - while (reader.Read()) - { - var state = reader.GetString(0); - dict[state] = (int)Enum.Parse(typeof(TransferStates), state); - } - - Log.Debug("State -> int map: {Map}", dict); - return dict; - } - - private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) - { - using var transaction = connection.BeginTransaction(); - - try - { - /* - rename old table so we can create the new one with the layout we want - while preserving the existing data - */ - var rename = @" - ALTER TABLE Transfers RENAME TO Transfers_old; - "; - - using var renameCommand = new SqliteCommand(rename, connection, transaction); - renameCommand.ExecuteNonQuery(); - - /* - create the new table with StateDescription appearing after State - */ - var create = @" - CREATE TABLE Transfers ( - Id TEXT NOT NULL, - Username TEXT, - Direction TEXT NOT NULL, - Filename TEXT, - Size INTEGER NOT NULL, - StartOffset INTEGER NOT NULL, - State INTEGER NOT NULL, - StateDescription TEXT, -- new column - RequestedAt TEXT NOT NULL, - EnqueuedAt TEXT, - StartedAt TEXT, - EndedAt TEXT, - BytesTransferred INTEGER NOT NULL, - AverageSpeed REAL NOT NULL, - PlaceInQueue INTEGER, - Exception TEXT, - Removed INTEGER NOT NULL, - CONSTRAINT PK_Transfers PRIMARY KEY(Id) - ); - "; - - using var createCommand = new SqliteCommand(create, connection, transaction); - createCommand.ExecuteNonQuery(); - - Log.Information("Schema changes applied, copying data..."); - - /* - copy the existing data into the new table - */ - var copy = @" - INSERT INTO Transfers ( - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - ) - SELECT - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;"; - - using var copyCommand = new SqliteCommand(copy, connection, transaction); - copyCommand.ExecuteNonQuery(); - - Log.Information("Data copied, adjusting columns..."); - - /* - we no longer need the old table, so drop it - */ - using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); - dropCommand.ExecuteNonQuery(); - - /* - copy the existing (string) State value from State to StateDescription - */ - var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); - copyColumnCommand.ExecuteNonQuery(); - - /* - for each of the distinct State values that exist in the data, convert the string - representation into the numeric - - there surely exist better ways to do this, but the reality is that 99% of the records - will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" - sprinkled in. this should run in reasonable time for large collections - */ - var sw = new Stopwatch(); - var step = 1; - - foreach (var state in stateMapping) - { - sw.Reset(); - Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); - - Log.Debug("Setting {String} to {Int}", state.Key, state.Value); - - var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); - mapCommand.ExecuteNonQuery(); - - Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); - } - - Log.Debug("Committing transation..."); - transaction.Commit(); - Log.Debug("Transaction committed!"); - Log.Information("Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs new file mode 100644 index 00000000..2210ba13 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs @@ -0,0 +1,204 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. + +// + +namespace slskd.Migrations; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using Soulseek; + +/// +/// Updates the Transfers table to: +/// +/// * Add a new StatusDescription (TEXT) column +/// * Copy the current (string) contents of the Status column to StatusDescription +/// * Change the type of the Status column to INTEGER +/// * Set the contents of the Status column to the numeric representation of the existing Status +/// +/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored +/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't +/// work against strings. Not sure why EF didn't complain about this, but here we are. +/// +public class z04012025_TransferStateMigration : IMigration +{ + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string DatabaseName { get; } = "transfers"; + private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; + + public void Apply() + { + // first, check the existing database to see if the StatusDescription column exists + // if it does, the migration has already been applied + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var txfers = schema["Transfers"]; + + if (txfers.Any(c => c.Name == "StatusDescription")) + { + Log.Information("Migration {Name} has already been applied", nameof(z04012025_TransferStateMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + // get a distinct list of states from the existing data and translate each into the corresponding integer + var stateMapping = GetStateMapping(connection); + + ModifyTableAndMassageData(connection, stateMapping); + } + + private Dictionary GetStateMapping(SqliteConnection connection) + { + Log.Debug("Fetching states and mapping to integers..."); + + using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); + using var reader = command.ExecuteReader(); + + var dict = new Dictionary(); + + while (reader.Read()) + { + var state = reader.GetString(0); + dict[state] = (int)Enum.Parse(typeof(TransferStates), state); + } + + Log.Debug("State -> int map: {Map}", dict); + return dict; + } + + private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) + { + using var transaction = connection.BeginTransaction(); + + try + { + /* + rename old table so we can create the new one with the layout we want + while preserving the existing data + */ + var rename = @" + ALTER TABLE Transfers RENAME TO Transfers_old; + "; + + using var renameCommand = new SqliteCommand(rename, connection, transaction); + renameCommand.ExecuteNonQuery(); + + /* + create the new table with StateDescription appearing after State + */ + var create = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State INTEGER NOT NULL, + StateDescription TEXT, -- new column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + ); + "; + + using var createCommand = new SqliteCommand(create, connection, transaction); + createCommand.ExecuteNonQuery(); + + Log.Information("Schema changes applied, copying data..."); + + /* + copy the existing data into the new table + */ + var copy = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using var copyCommand = new SqliteCommand(copy, connection, transaction); + copyCommand.ExecuteNonQuery(); + + Log.Information("Data copied, adjusting columns..."); + + /* + we no longer need the old table, so drop it + */ + using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); + dropCommand.ExecuteNonQuery(); + + /* + copy the existing (string) State value from State to StateDescription + */ + var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); + copyColumnCommand.ExecuteNonQuery(); + + /* + for each of the distinct State values that exist in the data, convert the string + representation into the numeric + + there surely exist better ways to do this, but the reality is that 99% of the records + will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" + sprinkled in. this should run in reasonable time for large collections + */ + var sw = new Stopwatch(); + var step = 1; + + foreach (var state in stateMapping) + { + sw.Reset(); + Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); + + Log.Debug("Setting {String} to {Int}", state.Key, state.Value); + + var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); + mapCommand.ExecuteNonQuery(); + + Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); + } + + Log.Debug("Committing transation..."); + transaction.Commit(); + Log.Debug("Transaction committed!"); + Log.Information("Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index ffaae586..14c97272 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -53,7 +53,7 @@ public class Migrator /// private Dictionary Migrations { get; } = new() { - { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, + { nameof(z04012025_TransferStateMigration), new z04012025_TransferStateMigration() }, }; /// -- cgit v1.2.3 From 7477d42487237d231fa8f9203ddbe567e03bf616 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 May 2025 14:48:31 -0500 Subject: remove early exit --- src/slskd/Program.cs | 3 --- 1 file changed, 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f1e9e7f5..49c46902 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -509,9 +509,6 @@ namespace slskd app.Services.GetService().Migrate(force: OptionsAtStartup.Flags.ForceMigrations); } - // todo: don't forget to take this out - Environment.Exit(1); - // hack: services that exist only to subscribe to the event bus are not referenced by anything else // and are thus never instantiated. force a reference here so they are created. _ = app.Services.GetService(); -- cgit v1.2.3 From 96e716e9d3d4ac522497d7a231f95e02273261da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 May 2025 14:48:42 -0500 Subject: fix header --- .../Core/Data/Migrations/z04012025_TransferStateMigration.cs | 7 +++---- src/slskd/Core/Data/Migrator.cs | 8 +++++++- src/slskd/Program.cs | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs index 2210ba13..7df435b6 100644 --- a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs @@ -13,7 +13,6 @@ // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see https://www.gnu.org/licenses/. - // namespace slskd.Migrations; @@ -39,9 +38,9 @@ using Soulseek; /// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't /// work against strings. Not sure why EF didn't complain about this, but here we are. /// -public class z04012025_TransferStateMigration : IMigration +public class Z04012025_TransferStateMigration : IMigration { - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); private string DatabaseName { get; } = "transfers"; private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; @@ -54,7 +53,7 @@ public class z04012025_TransferStateMigration : IMigration if (txfers.Any(c => c.Name == "StatusDescription")) { - Log.Information("Migration {Name} has already been applied", nameof(z04012025_TransferStateMigration)); + Log.Information("Migration {Name} has already been applied", nameof(Z04012025_TransferStateMigration)); return; } diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 14c97272..1312681c 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -25,8 +25,14 @@ using System.Linq; using Serilog; using slskd.Migrations; +/// +/// Applies database migrations. +/// public interface IMigration { + /// + /// Applies the migration. + /// void Apply(); } @@ -53,7 +59,7 @@ public class Migrator /// private Dictionary Migrations { get; } = new() { - { nameof(z04012025_TransferStateMigration), new z04012025_TransferStateMigration() }, + { nameof(Z04012025_TransferStateMigration), new Z04012025_TransferStateMigration() }, }; /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 49c46902..844d8a27 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -503,7 +503,7 @@ namespace slskd if (!OptionsAtStartup.Flags.Volatile) { - Log.Information($"Running migrations..."); + Log.Debug($"Running Migrate()..."); // note: if this ever throws, we've forgotten to register a Migrator following database DI config app.Services.GetService().Migrate(force: OptionsAtStartup.Flags.ForceMigrations); -- cgit v1.2.3 From 41725681ffe4164d4acfcfb259eab976541dc00f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 May 2025 16:55:10 -0500 Subject: adjust transfers db --- src/slskd/Transfers/TransfersDbContext.cs | 19 ++++++++++++++----- src/slskd/Transfers/Types/Transfer.cs | 12 +++++++++++- 2 files changed, 25 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index f31b6da8..cd721539 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -31,6 +31,20 @@ namespace slskd.Transfers public DbSet Transfers { get; set; } + public override int SaveChanges(bool acceptAllChangesOnSuccess) + { + // this is absolutely NOT IDEAL and will accellerate the move away from EF + foreach (var entry in ChangeTracker.Entries()) + { + if (entry.State == EntityState.Added || entry.State == EntityState.Modified) + { + entry.Entity.StateDescription = entry.Entity.State.ToString(); + } + } + + return base.SaveChanges(acceptAllChangesOnSuccess); + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder @@ -47,11 +61,6 @@ namespace slskd.Transfers .Entity() .Property(d => d.Direction) .HasConversion(new EnumToStringConverter()); - - modelBuilder - .Entity() - .Property(d => d.State) - .HasConversion(new EnumToStringConverter()); } } } diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index ddb3e017..338aba38 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -37,7 +37,17 @@ namespace slskd.Transfers public long Size { get; set; } public long StartOffset { get; init; } - public TransferStates State { get; set; } + public TransferStates State { get; set; } = TransferStates.None; + + /// + /// Gets the string representation of the transfer . + /// + /// + /// This is a hack to get the string into the database. *DO NOT* use this property in code + /// and especially **DO NOT** set the value. The getter and setter can't be protected because + /// EF Core needs them to be public. + /// + public string StateDescription { get; set; } public DateTime RequestedAt { get; set; } public DateTime? EnqueuedAt { get; set; } public DateTime? StartedAt { get; set; } -- cgit v1.2.3 From 646446c556524674b2c7b87dfd545cb92447e060 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 May 2025 16:55:31 -0500 Subject: migrator wip --- .../Migrations/z04012025_TransferStateMigration.cs | 25 +++--- src/slskd/Core/Data/Migrator.cs | 94 +++++++++++++++++++--- 2 files changed, 98 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs index 7df435b6..f18aba55 100644 --- a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -29,10 +29,10 @@ using Soulseek; /// /// Updates the Transfers table to: /// -/// * Add a new StatusDescription (TEXT) column -/// * Copy the current (string) contents of the Status column to StatusDescription -/// * Change the type of the Status column to INTEGER -/// * Set the contents of the Status column to the numeric representation of the existing Status +/// * Add a new StateDescription (TEXT) column +/// * Copy the current (string) contents of the State column to StateDescription +/// * Change the type of the State column to INTEGER +/// * Set the contents of the State column to the numeric representation of the existing State /// /// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored /// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't @@ -44,16 +44,21 @@ public class Z04012025_TransferStateMigration : IMigration private string DatabaseName { get; } = "transfers"; private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; - public void Apply() + public bool NeedsToBeApplied() { - // first, check the existing database to see if the StatusDescription column exists - // if it does, the migration has already been applied + // first, check the existing database to see if the StateDescription column exists + // if it does, the migration has already been applied, or the database has been recreated var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; - if (txfers.Any(c => c.Name == "StatusDescription")) + return !txfers.Any(c => c.Name == "StateDescription"); + } + + public void Apply() + { + if (!NeedsToBeApplied()) { - Log.Information("Migration {Name} has already been applied", nameof(Z04012025_TransferStateMigration)); + Log.Information("Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); return; } diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 1312681c..56f77dd9 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -30,6 +30,12 @@ using slskd.Migrations; /// public interface IMigration { + /// + /// Determines whether the migration needs to be applied. + /// + /// A value indicating whether the migration needs to be applied. + bool NeedsToBeApplied(); + /// /// Applies the migration. /// @@ -50,6 +56,13 @@ public class Migrator Databases = databases; } + private enum MigrationDisposition + { + AlreadyAppliedPerHistoryFile, + ApplicationNotNeededPerMigration, + ApplicationRequired, + } + private string HistoryFileName { get; } = Path.Combine(Program.DataMigrationsDirectory, "history"); private IEnumerable Databases { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -72,9 +85,11 @@ public class Migrator Log.Information("Checking for outstanding database migrations..."); - // load migration history from the history file in the root of the data directory. this file contains a key/value - // pair for each migration that's been applied, along with the migration date. - // if force=true, we don't care about the history and there's no reason to look at it. + /* + load migration history from the history file in the root of the data directory. this file contains a key/value + pair for each migration that's been applied, along with the migration date. + if force=true, we're going to disregard history and overwrite it. + */ if (!force) { try @@ -100,16 +115,69 @@ public class Migrator } } - // figure out which migrations need to be applied by taking the set difference of the migration list and the history contents - var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); + /* + // + disposition each of the registered migrations into one of three dispositions: + - applied (per history file) + - not needed (per migration logic) + - required (does not appear in history and migration logic indicates it needs to be applied)) + */ + var migrationDispositions = new Dictionary(); + + try + { + foreach (var migration in Migrations.Keys) + { + if (history.ContainsKey(migration)) + { + migrationDispositions[migration] = MigrationDisposition.AlreadyAppliedPerHistoryFile; + } + else if (Migrations[migration].NeedsToBeApplied()) // warning: performs I/O + { + migrationDispositions[migration] = MigrationDisposition.ApplicationRequired; + } + else + { + migrationDispositions[migration] = MigrationDisposition.ApplicationNotNeededPerMigration; + } + } + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to disposition migrations: {Message}", ex.Message); + throw; + } + + Log.Debug("Migration dispositions: {Dispositions}", migrationDispositions); + + var migrationsToApply = migrationDispositions + .Where(disposition => disposition.Value == MigrationDisposition.ApplicationRequired) + .Select(disposition => disposition.Key); - if (!migrationsNotYetApplied.Any()) + Log.Debug("Migrations to apply: {Migrations}", migrationsToApply); + + if (!migrationsToApply.Any()) { + // we don't have to migrate anything! however, any migration that 1) isn't in history and 2) reported + // that it didn't need to be applied needs to be added to the history file so we can avoid doing that + // I/O each time the application starts. + foreach (var migration in migrationDispositions.Where(disposition => disposition.Value == MigrationDisposition.ApplicationNotNeededPerMigration)) + { + // note that we might get here if the 'force' option was used. we'll just overwrite the timestamp. + history[migration.Key] = DateTime.UtcNow; + } + + UpdateHistoryFile(history); + Log.Information("Databases are up to date!"); return; } - Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); + /* + MIGRATION TIME! + --------------------------------------------------------------------------------------------------------------------------------------------------- + */ + Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsToApply.Count()); var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss"); @@ -151,11 +219,11 @@ public class Migrator overallSw.Start(); var current = 0; - var total = migrationsNotYetApplied.Count(); + var total = migrationsToApply.Count(); var currentSw = new Stopwatch(); - foreach (var migration in migrationsNotYetApplied) + foreach (var migration in migrationsToApply) { current++; currentSw.Restart(); @@ -209,11 +277,15 @@ public class Migrator throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); } + UpdateHistoryFile(history); + Log.Information("Migration(s) complete!"); + } + + private void UpdateHistoryFile(Dictionary history) + { var newHistory = history.ToJson(); File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); - - Log.Information("Migration(s) complete!"); } private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db"); -- cgit v1.2.3 From b504ac11e081496ddb2cde14b46851a22f9219e4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 May 2025 16:55:53 -0500 Subject: force rename to fix git --- .../foo-Z04012025_TransferStateMigration.cs | 208 +++++++++++++++++++++ .../Migrations/z04012025_TransferStateMigration.cs | 208 --------------------- 2 files changed, 208 insertions(+), 208 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/foo-Z04012025_TransferStateMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/foo-Z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/foo-Z04012025_TransferStateMigration.cs new file mode 100644 index 00000000..f18aba55 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/foo-Z04012025_TransferStateMigration.cs @@ -0,0 +1,208 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Migrations; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using Soulseek; + +/// +/// Updates the Transfers table to: +/// +/// * Add a new StateDescription (TEXT) column +/// * Copy the current (string) contents of the State column to StateDescription +/// * Change the type of the State column to INTEGER +/// * Set the contents of the State column to the numeric representation of the existing State +/// +/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored +/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't +/// work against strings. Not sure why EF didn't complain about this, but here we are. +/// +public class Z04012025_TransferStateMigration : IMigration +{ + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string DatabaseName { get; } = "transfers"; + private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; + + public bool NeedsToBeApplied() + { + // first, check the existing database to see if the StateDescription column exists + // if it does, the migration has already been applied, or the database has been recreated + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var txfers = schema["Transfers"]; + + return !txfers.Any(c => c.Name == "StateDescription"); + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + // get a distinct list of states from the existing data and translate each into the corresponding integer + var stateMapping = GetStateMapping(connection); + + ModifyTableAndMassageData(connection, stateMapping); + } + + private Dictionary GetStateMapping(SqliteConnection connection) + { + Log.Debug("Fetching states and mapping to integers..."); + + using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); + using var reader = command.ExecuteReader(); + + var dict = new Dictionary(); + + while (reader.Read()) + { + var state = reader.GetString(0); + dict[state] = (int)Enum.Parse(typeof(TransferStates), state); + } + + Log.Debug("State -> int map: {Map}", dict); + return dict; + } + + private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) + { + using var transaction = connection.BeginTransaction(); + + try + { + /* + rename old table so we can create the new one with the layout we want + while preserving the existing data + */ + var rename = @" + ALTER TABLE Transfers RENAME TO Transfers_old; + "; + + using var renameCommand = new SqliteCommand(rename, connection, transaction); + renameCommand.ExecuteNonQuery(); + + /* + create the new table with StateDescription appearing after State + */ + var create = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State INTEGER NOT NULL, + StateDescription TEXT, -- new column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + ); + "; + + using var createCommand = new SqliteCommand(create, connection, transaction); + createCommand.ExecuteNonQuery(); + + Log.Information("Schema changes applied, copying data..."); + + /* + copy the existing data into the new table + */ + var copy = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using var copyCommand = new SqliteCommand(copy, connection, transaction); + copyCommand.ExecuteNonQuery(); + + Log.Information("Data copied, adjusting columns..."); + + /* + we no longer need the old table, so drop it + */ + using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); + dropCommand.ExecuteNonQuery(); + + /* + copy the existing (string) State value from State to StateDescription + */ + var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); + copyColumnCommand.ExecuteNonQuery(); + + /* + for each of the distinct State values that exist in the data, convert the string + representation into the numeric + + there surely exist better ways to do this, but the reality is that 99% of the records + will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" + sprinkled in. this should run in reasonable time for large collections + */ + var sw = new Stopwatch(); + var step = 1; + + foreach (var state in stateMapping) + { + sw.Reset(); + Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); + + Log.Debug("Setting {String} to {Int}", state.Key, state.Value); + + var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); + mapCommand.ExecuteNonQuery(); + + Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); + } + + Log.Debug("Committing transation..."); + transaction.Commit(); + Log.Debug("Transaction committed!"); + Log.Information("Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs deleted file mode 100644 index f18aba55..00000000 --- a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs +++ /dev/null @@ -1,208 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Migrations; - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using Soulseek; - -/// -/// Updates the Transfers table to: -/// -/// * Add a new StateDescription (TEXT) column -/// * Copy the current (string) contents of the State column to StateDescription -/// * Change the type of the State column to INTEGER -/// * Set the contents of the State column to the numeric representation of the existing State -/// -/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored -/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't -/// work against strings. Not sure why EF didn't complain about this, but here we are. -/// -public class Z04012025_TransferStateMigration : IMigration -{ - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string DatabaseName { get; } = "transfers"; - private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; - - public bool NeedsToBeApplied() - { - // first, check the existing database to see if the StateDescription column exists - // if it does, the migration has already been applied, or the database has been recreated - var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); - var txfers = schema["Transfers"]; - - return !txfers.Any(c => c.Name == "StateDescription"); - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - // get a distinct list of states from the existing data and translate each into the corresponding integer - var stateMapping = GetStateMapping(connection); - - ModifyTableAndMassageData(connection, stateMapping); - } - - private Dictionary GetStateMapping(SqliteConnection connection) - { - Log.Debug("Fetching states and mapping to integers..."); - - using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); - using var reader = command.ExecuteReader(); - - var dict = new Dictionary(); - - while (reader.Read()) - { - var state = reader.GetString(0); - dict[state] = (int)Enum.Parse(typeof(TransferStates), state); - } - - Log.Debug("State -> int map: {Map}", dict); - return dict; - } - - private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) - { - using var transaction = connection.BeginTransaction(); - - try - { - /* - rename old table so we can create the new one with the layout we want - while preserving the existing data - */ - var rename = @" - ALTER TABLE Transfers RENAME TO Transfers_old; - "; - - using var renameCommand = new SqliteCommand(rename, connection, transaction); - renameCommand.ExecuteNonQuery(); - - /* - create the new table with StateDescription appearing after State - */ - var create = @" - CREATE TABLE Transfers ( - Id TEXT NOT NULL, - Username TEXT, - Direction TEXT NOT NULL, - Filename TEXT, - Size INTEGER NOT NULL, - StartOffset INTEGER NOT NULL, - State INTEGER NOT NULL, - StateDescription TEXT, -- new column - RequestedAt TEXT NOT NULL, - EnqueuedAt TEXT, - StartedAt TEXT, - EndedAt TEXT, - BytesTransferred INTEGER NOT NULL, - AverageSpeed REAL NOT NULL, - PlaceInQueue INTEGER, - Exception TEXT, - Removed INTEGER NOT NULL, - CONSTRAINT PK_Transfers PRIMARY KEY(Id) - ); - "; - - using var createCommand = new SqliteCommand(create, connection, transaction); - createCommand.ExecuteNonQuery(); - - Log.Information("Schema changes applied, copying data..."); - - /* - copy the existing data into the new table - */ - var copy = @" - INSERT INTO Transfers ( - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - ) - SELECT - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;"; - - using var copyCommand = new SqliteCommand(copy, connection, transaction); - copyCommand.ExecuteNonQuery(); - - Log.Information("Data copied, adjusting columns..."); - - /* - we no longer need the old table, so drop it - */ - using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); - dropCommand.ExecuteNonQuery(); - - /* - copy the existing (string) State value from State to StateDescription - */ - var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); - copyColumnCommand.ExecuteNonQuery(); - - /* - for each of the distinct State values that exist in the data, convert the string - representation into the numeric - - there surely exist better ways to do this, but the reality is that 99% of the records - will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" - sprinkled in. this should run in reasonable time for large collections - */ - var sw = new Stopwatch(); - var step = 1; - - foreach (var state in stateMapping) - { - sw.Reset(); - Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); - - Log.Debug("Setting {String} to {Int}", state.Key, state.Value); - - var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); - mapCommand.ExecuteNonQuery(); - - Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); - } - - Log.Debug("Committing transation..."); - transaction.Commit(); - Log.Debug("Transaction committed!"); - Log.Information("Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} -- cgit v1.2.3 From 27e20078a745c42141fff8922da23e1070017157 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 May 2025 16:56:09 -0500 Subject: rename back --- .../Migrations/Z04012025_TransferStateMigration.cs | 208 +++++++++++++++++++++ .../foo-Z04012025_TransferStateMigration.cs | 208 --------------------- 2 files changed, 208 insertions(+), 208 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/foo-Z04012025_TransferStateMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs new file mode 100644 index 00000000..f18aba55 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs @@ -0,0 +1,208 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Migrations; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using Soulseek; + +/// +/// Updates the Transfers table to: +/// +/// * Add a new StateDescription (TEXT) column +/// * Copy the current (string) contents of the State column to StateDescription +/// * Change the type of the State column to INTEGER +/// * Set the contents of the State column to the numeric representation of the existing State +/// +/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored +/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't +/// work against strings. Not sure why EF didn't complain about this, but here we are. +/// +public class Z04012025_TransferStateMigration : IMigration +{ + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string DatabaseName { get; } = "transfers"; + private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; + + public bool NeedsToBeApplied() + { + // first, check the existing database to see if the StateDescription column exists + // if it does, the migration has already been applied, or the database has been recreated + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var txfers = schema["Transfers"]; + + return !txfers.Any(c => c.Name == "StateDescription"); + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + // get a distinct list of states from the existing data and translate each into the corresponding integer + var stateMapping = GetStateMapping(connection); + + ModifyTableAndMassageData(connection, stateMapping); + } + + private Dictionary GetStateMapping(SqliteConnection connection) + { + Log.Debug("Fetching states and mapping to integers..."); + + using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); + using var reader = command.ExecuteReader(); + + var dict = new Dictionary(); + + while (reader.Read()) + { + var state = reader.GetString(0); + dict[state] = (int)Enum.Parse(typeof(TransferStates), state); + } + + Log.Debug("State -> int map: {Map}", dict); + return dict; + } + + private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) + { + using var transaction = connection.BeginTransaction(); + + try + { + /* + rename old table so we can create the new one with the layout we want + while preserving the existing data + */ + var rename = @" + ALTER TABLE Transfers RENAME TO Transfers_old; + "; + + using var renameCommand = new SqliteCommand(rename, connection, transaction); + renameCommand.ExecuteNonQuery(); + + /* + create the new table with StateDescription appearing after State + */ + var create = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State INTEGER NOT NULL, + StateDescription TEXT, -- new column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + ); + "; + + using var createCommand = new SqliteCommand(create, connection, transaction); + createCommand.ExecuteNonQuery(); + + Log.Information("Schema changes applied, copying data..."); + + /* + copy the existing data into the new table + */ + var copy = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using var copyCommand = new SqliteCommand(copy, connection, transaction); + copyCommand.ExecuteNonQuery(); + + Log.Information("Data copied, adjusting columns..."); + + /* + we no longer need the old table, so drop it + */ + using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); + dropCommand.ExecuteNonQuery(); + + /* + copy the existing (string) State value from State to StateDescription + */ + var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); + copyColumnCommand.ExecuteNonQuery(); + + /* + for each of the distinct State values that exist in the data, convert the string + representation into the numeric + + there surely exist better ways to do this, but the reality is that 99% of the records + will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" + sprinkled in. this should run in reasonable time for large collections + */ + var sw = new Stopwatch(); + var step = 1; + + foreach (var state in stateMapping) + { + sw.Reset(); + Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); + + Log.Debug("Setting {String} to {Int}", state.Key, state.Value); + + var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); + mapCommand.ExecuteNonQuery(); + + Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); + } + + Log.Debug("Committing transation..."); + transaction.Commit(); + Log.Debug("Transaction committed!"); + Log.Information("Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/foo-Z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/foo-Z04012025_TransferStateMigration.cs deleted file mode 100644 index f18aba55..00000000 --- a/src/slskd/Core/Data/Migrations/foo-Z04012025_TransferStateMigration.cs +++ /dev/null @@ -1,208 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Migrations; - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using Soulseek; - -/// -/// Updates the Transfers table to: -/// -/// * Add a new StateDescription (TEXT) column -/// * Copy the current (string) contents of the State column to StateDescription -/// * Change the type of the State column to INTEGER -/// * Set the contents of the State column to the numeric representation of the existing State -/// -/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored -/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't -/// work against strings. Not sure why EF didn't complain about this, but here we are. -/// -public class Z04012025_TransferStateMigration : IMigration -{ - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string DatabaseName { get; } = "transfers"; - private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; - - public bool NeedsToBeApplied() - { - // first, check the existing database to see if the StateDescription column exists - // if it does, the migration has already been applied, or the database has been recreated - var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); - var txfers = schema["Transfers"]; - - return !txfers.Any(c => c.Name == "StateDescription"); - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - // get a distinct list of states from the existing data and translate each into the corresponding integer - var stateMapping = GetStateMapping(connection); - - ModifyTableAndMassageData(connection, stateMapping); - } - - private Dictionary GetStateMapping(SqliteConnection connection) - { - Log.Debug("Fetching states and mapping to integers..."); - - using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); - using var reader = command.ExecuteReader(); - - var dict = new Dictionary(); - - while (reader.Read()) - { - var state = reader.GetString(0); - dict[state] = (int)Enum.Parse(typeof(TransferStates), state); - } - - Log.Debug("State -> int map: {Map}", dict); - return dict; - } - - private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) - { - using var transaction = connection.BeginTransaction(); - - try - { - /* - rename old table so we can create the new one with the layout we want - while preserving the existing data - */ - var rename = @" - ALTER TABLE Transfers RENAME TO Transfers_old; - "; - - using var renameCommand = new SqliteCommand(rename, connection, transaction); - renameCommand.ExecuteNonQuery(); - - /* - create the new table with StateDescription appearing after State - */ - var create = @" - CREATE TABLE Transfers ( - Id TEXT NOT NULL, - Username TEXT, - Direction TEXT NOT NULL, - Filename TEXT, - Size INTEGER NOT NULL, - StartOffset INTEGER NOT NULL, - State INTEGER NOT NULL, - StateDescription TEXT, -- new column - RequestedAt TEXT NOT NULL, - EnqueuedAt TEXT, - StartedAt TEXT, - EndedAt TEXT, - BytesTransferred INTEGER NOT NULL, - AverageSpeed REAL NOT NULL, - PlaceInQueue INTEGER, - Exception TEXT, - Removed INTEGER NOT NULL, - CONSTRAINT PK_Transfers PRIMARY KEY(Id) - ); - "; - - using var createCommand = new SqliteCommand(create, connection, transaction); - createCommand.ExecuteNonQuery(); - - Log.Information("Schema changes applied, copying data..."); - - /* - copy the existing data into the new table - */ - var copy = @" - INSERT INTO Transfers ( - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - ) - SELECT - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;"; - - using var copyCommand = new SqliteCommand(copy, connection, transaction); - copyCommand.ExecuteNonQuery(); - - Log.Information("Data copied, adjusting columns..."); - - /* - we no longer need the old table, so drop it - */ - using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); - dropCommand.ExecuteNonQuery(); - - /* - copy the existing (string) State value from State to StateDescription - */ - var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); - copyColumnCommand.ExecuteNonQuery(); - - /* - for each of the distinct State values that exist in the data, convert the string - representation into the numeric - - there surely exist better ways to do this, but the reality is that 99% of the records - will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" - sprinkled in. this should run in reasonable time for large collections - */ - var sw = new Stopwatch(); - var step = 1; - - foreach (var state in stateMapping) - { - sw.Reset(); - Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); - - Log.Debug("Setting {String} to {Int}", state.Key, state.Value); - - var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); - mapCommand.ExecuteNonQuery(); - - Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); - } - - Log.Debug("Committing transation..."); - transaction.Commit(); - Log.Debug("Transaction committed!"); - Log.Information("Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} -- cgit v1.2.3 From 3fed167896a1376bedf9f5997887674bc1b1e2ea Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 May 2025 09:06:11 -0500 Subject: refactor migrator to respect NeedsToBeApplied() --- src/slskd/Core/Data/Migrator.cs | 51 +++++++++++++++++------------------------ 1 file changed, 21 insertions(+), 30 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 56f77dd9..9f28d747 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -115,30 +115,35 @@ public class Migrator } } + Log.Debug("Current history: {History}", history); + /* - // - disposition each of the registered migrations into one of three dispositions: - - applied (per history file) - - not needed (per migration logic) - - required (does not appear in history and migration logic indicates it needs to be applied)) + determine which migrations need to be applied + + first, take the set difference (Except()) of the list of registered migrations and the history file. this gives + us a list of t he migrations that are not in the history file. + + next, check each of the migrations not in history to see if they need to be applied. if they _don't_, then + add them directly to the history dictionary. if they do, add them to the list of migrations to apply. + + the result is: + - an updated history dictionary, containing the dict loaded from disk plus any new migrations that _don't_ need to be applied + - a list of migrations that need to be applied */ - var migrationDispositions = new Dictionary(); + List migrationsToApply = []; try { - foreach (var migration in Migrations.Keys) + foreach (var migration in Migrations.Keys.Except(history.Keys)) { - if (history.ContainsKey(migration)) - { - migrationDispositions[migration] = MigrationDisposition.AlreadyAppliedPerHistoryFile; - } - else if (Migrations[migration].NeedsToBeApplied()) // warning: performs I/O + if (!Migrations[migration].NeedsToBeApplied()) // warning: performs I/O { - migrationDispositions[migration] = MigrationDisposition.ApplicationRequired; + Log.Debug("Migration {Name} does not need to be applied", migration); + history[migration] = DateTime.UtcNow; } else { - migrationDispositions[migration] = MigrationDisposition.ApplicationNotNeededPerMigration; + migrationsToApply.Add(migration); } } } @@ -148,25 +153,11 @@ public class Migrator throw; } - Log.Debug("Migration dispositions: {Dispositions}", migrationDispositions); - - var migrationsToApply = migrationDispositions - .Where(disposition => disposition.Value == MigrationDisposition.ApplicationRequired) - .Select(disposition => disposition.Key); - + Log.Debug("Updated history: {History}", history); Log.Debug("Migrations to apply: {Migrations}", migrationsToApply); - if (!migrationsToApply.Any()) + if (migrationsToApply.Count == 0) { - // we don't have to migrate anything! however, any migration that 1) isn't in history and 2) reported - // that it didn't need to be applied needs to be added to the history file so we can avoid doing that - // I/O each time the application starts. - foreach (var migration in migrationDispositions.Where(disposition => disposition.Value == MigrationDisposition.ApplicationNotNeededPerMigration)) - { - // note that we might get here if the 'force' option was used. we'll just overwrite the timestamp. - history[migration.Key] = DateTime.UtcNow; - } - UpdateHistoryFile(history); Log.Information("Databases are up to date!"); -- cgit v1.2.3 From 9d2050a21996df047e20ca4a5da5da346d560008 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 May 2025 09:10:37 -0500 Subject: final tweaks? --- src/slskd/Core/Data/Migrations/README.md | 4 +++- src/slskd/Core/Data/Migrator.cs | 24 ++++++++---------------- 2 files changed, 11 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index 0cafbe6a..cae058b2 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -13,7 +13,7 @@ The `Migrator` creates a backup of each database prior to running any migrations Each migration must be created as a class that implements the `IMigration` interface. The naming convention for migration classes is: ``` -z_Migration +Z_Migration ``` Migrations MUST: @@ -24,6 +24,8 @@ and the name(s) of the table(s) that need to be migrated. * Use transactions when performing database operations and using/try catch where appropriate to avoid partially applied migrations. * Log progress, so users can see that the application is performing work while records are updated. +Review the `IMigration` interface to determine implementation details. + The new `IMigration` implementation must be added to the dictionary in the `Migrations` property of the `Migrator` in the desired order so that it can be run. ### Above all else, each and every migration **MUST** be idempotent. diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 9f28d747..02b65c0c 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -33,6 +33,9 @@ public interface IMigration /// /// Determines whether the migration needs to be applied. /// + /// + /// This method MUST be read-only and should contain no side effects. + /// /// A value indicating whether the migration needs to be applied. bool NeedsToBeApplied(); @@ -56,13 +59,6 @@ public class Migrator Databases = databases; } - private enum MigrationDisposition - { - AlreadyAppliedPerHistoryFile, - ApplicationNotNeededPerMigration, - ApplicationRequired, - } - private string HistoryFileName { get; } = Path.Combine(Program.DataMigrationsDirectory, "history"); private IEnumerable Databases { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -120,15 +116,9 @@ public class Migrator /* determine which migrations need to be applied - first, take the set difference (Except()) of the list of registered migrations and the history file. this gives - us a list of t he migrations that are not in the history file. - - next, check each of the migrations not in history to see if they need to be applied. if they _don't_, then - add them directly to the history dictionary. if they do, add them to the list of migrations to apply. - - the result is: - - an updated history dictionary, containing the dict loaded from disk plus any new migrations that _don't_ need to be applied - - a list of migrations that need to be applied + take the set difference between all registered migrations and the history file, then for each of the migrations + in that set, check to see if it needs to be applied. if it doesn't, add it to the history file with the current + timestamp. if it does, add it to the list of migrations to apply. */ List migrationsToApply = []; @@ -158,6 +148,8 @@ public class Migrator if (migrationsToApply.Count == 0) { + // write the history file to disk; if there are new migrations that didn't need to be applied, or the user + // used the 'force' flag, the history file on disk and in memory will have diverged. UpdateHistoryFile(history); Log.Information("Databases are up to date!"); -- cgit v1.2.3 From 5d5a79e06c187cedde3682805d259d50ea0e72c7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 May 2025 15:43:54 -0500 Subject: copy the TransferStates enum into the migration to ensure it remains stable --- .../Migrations/Z04012025_TransferStateMigration.cs | 28 ++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs index f18aba55..bf034d6f 100644 --- a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs @@ -24,7 +24,6 @@ using System.IO; using System.Linq; using Microsoft.Data.Sqlite; using Serilog; -using Soulseek; /// /// Updates the Transfers table to: @@ -83,7 +82,7 @@ public class Z04012025_TransferStateMigration : IMigration while (reader.Read()) { var state = reader.GetString(0); - dict[state] = (int)Enum.Parse(typeof(TransferStates), state); + dict[state] = (int)Enum.Parse(typeof(Z04012025_TransferStateMigration_TransferStates), state); } Log.Debug("State -> int map: {Map}", dict); @@ -205,4 +204,29 @@ public class Z04012025_TransferStateMigration : IMigration throw; } } + +#pragma warning disable SA1201 // Elements should appear in the correct order + /// + /// This is a copy of the TransferStates enum as it was at the time this migration was written. This exists to ensure + /// that the migration can be applied to any version of the database, even if the enum changes in the future. + /// + [Flags] + private enum Z04012025_TransferStateMigration_TransferStates + { + None = 0, + Requested = 1, + Queued = 2, + Initializing = 4, + InProgress = 8, + Completed = 16, + Succeeded = 32, + Cancelled = 64, + TimedOut = 128, + Errored = 256, + Rejected = 512, + Aborted = 1024, + Locally = 2048, + Remotely = 4096, + } +#pragma warning restore SA1201 // Elements should appear in the correct order } -- cgit v1.2.3 From 85ba3a74f27c753c08af970d4217ed9fc4a85b54 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 May 2025 12:21:36 -0500 Subject: remove migration history file --- docs/migrations.md | 5 --- src/slskd/Core/Data/Migrations/README.md | 11 +++-- src/slskd/Core/Data/Migrator.cs | 69 ++++++-------------------------- 3 files changed, 17 insertions(+), 68 deletions(-) (limited to 'src') diff --git a/docs/migrations.md b/docs/migrations.md index 6f1ec5f5..2b6450ca 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -10,13 +10,8 @@ When the application detects that a migration is required, it performs the follo 2. Apply migrations: The application applies the necessary changes to the database schema and data. -3. Save migration history: After successfully applying migrations, the application updates the migration history file to record the applied changes. - At the start of each migration a unique `migration id` is generated. If anything goes wrong, this ID can be used to locate the backup files created before the error occured (as subsequent migration attempts/retries will generate new backups, which may contain partially applied migrations). -History is stored in the `migrations` directory so that the application can avoid running migrations that have already been applied. If this file is deleted, moved, or becomes corrupted, -all migrations will be applied the next time the application starts. Avoid deleting, moving or modifying this file. - ## What to Do If a Migration Fails If a migration fails, the application will attempt to restore the databases from the backups created before the migration. However, if the automatic restoration process fails, you can manually recover your data by following these steps: diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index cae058b2..e8630265 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -1,11 +1,9 @@ # Database Migrations -In the hopefully unlikely event that a non-backwards-compatible schema change to a database migration is necessary, a migration must be written. +In the hopefully unlikely event that a schema change more complex than the simple addition of a column to a database migration is necessary, a migration must be written. Migrations are applied by the `Migrator` at startup. -The `history` file in the data directory is used to attempt to track whether migrations have already been applied. If a migration appears in the history file it won't be run again. Users can delete or modify the `history` file or use the `force` flag to apply them, meaning migrations **MUST** be idempotent. - The `Migrator` creates a backup of each database prior to running any migrations, and if an exception is thrown at any time during the process the `Migrator` will revert to these backups automatically. The backup files are left in place when the migration is complete so that users can manually revert if the migration left their application in a bad state or destroyed or lost data. ## Creating a Migration @@ -18,11 +16,12 @@ Z_Migration Migrations MUST: -* Figure out where on disk the associated database(s) are located. This is accomplished by combining the static `Program.DataDirectory` variable -and the name(s) of the table(s) that need to be migrated. +* Be idempotent. The migration must be able to be run any number of times without corrupting the database or losing data. * Inspect the target database(s) schema to determine whether the migration needs to be applied (if possible) * Use transactions when performing database operations and using/try catch where appropriate to avoid partially applied migrations. -* Log progress, so users can see that the application is performing work while records are updated. +* Figure out where on disk the associated database(s) are located. This is accomplished by combining the static `Program.DataDirectory` variable +and the name(s) of the table(s) that need to be migrated. +* Log progress (with logs prefixed by >), so users can see that the application is performing work while records are updated. Review the `IMigration` interface to determine implementation details. diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 02b65c0c..4adc22fb 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -77,62 +77,31 @@ public class Migrator /// Apply all migrations, regardless of whether there's evidence they have been applied already. public void Migrate(bool force = false) { - Dictionary history = []; - - Log.Information("Checking for outstanding database migrations..."); - - /* - load migration history from the history file in the root of the data directory. this file contains a key/value - pair for each migration that's been applied, along with the migration date. - if force=true, we're going to disregard history and overwrite it. - */ - if (!force) - { - try - { - if (File.Exists(HistoryFileName)) - { - var txt = File.ReadAllText(HistoryFileName); - history = txt.FromJson>(); - - Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFileName, history); - } - else - { - Log.Debug("Migration history file {HistoryFile} was not found", HistoryFileName); - } - } - catch (Exception ex) - { - // log a message but don't throw; migrations are (should be!) idempotent, so there's no harm in running them, - // it just takes unnecessary time. - Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFileName, ex.Message); - Log.Warning("Migration history will be overwritten and all migrations will be applied"); - } - } - - Log.Debug("Current history: {History}", history); + List migrationsToApply = []; + List migrationsToSkip = []; /* determine which migrations need to be applied - take the set difference between all registered migrations and the history file, then for each of the migrations - in that set, check to see if it needs to be applied. if it doesn't, add it to the history file with the current - timestamp. if it does, add it to the list of migrations to apply. - */ - List migrationsToApply = []; + for the time being, we'll rely on each of the migrations to determine whether they need to be applied + this will work until: + 1) there's a migration that isn't idempotent (can't tell whether it needs to be applied on its own), or.. + 2) there are > ~20 migrations, making repeated I/O of database files too slow/expensive on low spec hardware + when the time comes, migration history should be stored within the database files themselves. + */ try { - foreach (var migration in Migrations.Keys.Except(history.Keys)) + foreach (var migration in Migrations.Keys) { if (!Migrations[migration].NeedsToBeApplied()) // warning: performs I/O { Log.Debug("Migration {Name} does not need to be applied", migration); - history[migration] = DateTime.UtcNow; + migrationsToSkip.Add(migration); } else { + Log.Debug("Migration {Name} needs to be applied", migration); migrationsToApply.Add(migration); } } @@ -143,15 +112,10 @@ public class Migrator throw; } - Log.Debug("Updated history: {History}", history); - Log.Debug("Migrations to apply: {Migrations}", migrationsToApply); + Log.Debug("Migrations: {Migrations}", new { migrationsToApply, migrationsToSkip }); if (migrationsToApply.Count == 0) { - // write the history file to disk; if there are new migrations that didn't need to be applied, or the user - // used the 'force' flag, the history file on disk and in memory will have diverged. - UpdateHistoryFile(history); - Log.Information("Databases are up to date!"); return; } @@ -216,7 +180,6 @@ public class Migrator try { Migrations[migration].Apply(); - history[migration] = DateTime.UtcNow; Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); } @@ -260,17 +223,9 @@ public class Migrator throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); } - UpdateHistoryFile(history); Log.Information("Migration(s) complete!"); } - private void UpdateHistoryFile(Dictionary history) - { - var newHistory = history.ToJson(); - File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present - Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); - } - private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db"); private string MakeBackupDatabasePath(string database, string timestamp) => Path.Combine(Program.DataMigrationsDirectory, $"{database}.pre-migration-backup.{timestamp}.db"); } \ No newline at end of file -- cgit v1.2.3 From 4efad204276f9f9e1896f25c5c7c4d7aa06b4260 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 May 2025 12:57:59 -0500 Subject: tweak logs --- .../Core/Data/Migrations/Z04012025_TransferStateMigration.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs index bf034d6f..f7af80f5 100644 --- a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs @@ -57,7 +57,7 @@ public class Z04012025_TransferStateMigration : IMigration { if (!NeedsToBeApplied()) { - Log.Information("Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); return; } @@ -135,7 +135,7 @@ public class Z04012025_TransferStateMigration : IMigration using var createCommand = new SqliteCommand(create, connection, transaction); createCommand.ExecuteNonQuery(); - Log.Information("Schema changes applied, copying data..."); + Log.Information("> Schema changes applied, copying data..."); /* copy the existing data into the new table @@ -155,7 +155,7 @@ public class Z04012025_TransferStateMigration : IMigration using var copyCommand = new SqliteCommand(copy, connection, transaction); copyCommand.ExecuteNonQuery(); - Log.Information("Data copied, adjusting columns..."); + Log.Information("> Data copied, adjusting columns..."); /* we no longer need the old table, so drop it @@ -196,7 +196,7 @@ public class Z04012025_TransferStateMigration : IMigration Log.Debug("Committing transation..."); transaction.Commit(); Log.Debug("Transaction committed!"); - Log.Information("Done!"); + Log.Information("> Done!"); } catch (Exception) { -- cgit v1.2.3 From 7a44729293863b494fd929b91f349f47b8603e7c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 May 2025 12:58:05 -0500 Subject: migrations -> backups --- src/slskd/Core/Data/Migrator.cs | 6 +++--- src/slskd/Program.cs | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 4adc22fb..4cc56147 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -59,7 +59,6 @@ public class Migrator Databases = databases; } - private string HistoryFileName { get; } = Path.Combine(Program.DataMigrationsDirectory, "history"); private IEnumerable Databases { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -94,7 +93,8 @@ public class Migrator { foreach (var migration in Migrations.Keys) { - if (!Migrations[migration].NeedsToBeApplied()) // warning: performs I/O + // warning: performs I/O + if (!Migrations[migration].NeedsToBeApplied()) { Log.Debug("Migration {Name} does not need to be applied", migration); migrationsToSkip.Add(migration); @@ -227,5 +227,5 @@ public class Migrator } private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db"); - private string MakeBackupDatabasePath(string database, string timestamp) => Path.Combine(Program.DataMigrationsDirectory, $"{database}.pre-migration-backup.{timestamp}.db"); + private string MakeBackupDatabasePath(string database, string timestamp) => Path.Combine(Program.DataBackupDirectory, $"{database}.pre-migration-backup.{timestamp}.db"); } \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 844d8a27..0537824f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -188,9 +188,9 @@ namespace slskd public static string DataDirectory { get; private set; } = null; /// - /// Gets the path where database migration information is saved. + /// Gets the path where backups of persistent data saved. /// - public static string DataMigrationsDirectory { get; private set; } = null; + public static string DataBackupDirectory { get; private set; } = null; /// /// Gets the default fully qualified path to the configuration file. @@ -341,7 +341,7 @@ namespace slskd // derive the application directory value and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; DataDirectory = Path.Combine(AppDirectory, "data"); - DataMigrationsDirectory = Path.Combine(DataDirectory, "migrations"); + DataBackupDirectory = Path.Combine(DataDirectory, "backups"); LogDirectory = Path.Combine(AppDirectory, "logs"); ScriptDirectory = Path.Combine(AppDirectory, "scripts"); @@ -359,7 +359,7 @@ namespace slskd { VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(DataDirectory, createIfMissing: true, verifyWriteable: true); - VerifyDirectory(DataMigrationsDirectory, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(DataBackupDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(ScriptDirectory, createIfMissing: true, verifyWriteable: false); VerifyDirectory(DefaultDownloadsDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(DefaultIncompleteDirectory, createIfMissing: true, verifyWriteable: true); -- cgit v1.2.3 From 930df71e94dedd5de5267418c3e7666a86eea416 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 May 2025 17:53:31 -0500 Subject: final tweaks --- docs/migrations.md | 6 ++--- src/slskd/Core/Data/IMigration.cs | 38 ++++++++++++++++++++++++++++++++ src/slskd/Core/Data/Migrations/README.md | 4 +--- src/slskd/Core/Data/Migrator.cs | 20 ----------------- 4 files changed, 42 insertions(+), 26 deletions(-) create mode 100644 src/slskd/Core/Data/IMigration.cs (limited to 'src') diff --git a/docs/migrations.md b/docs/migrations.md index 2b6450ca..2fec53bd 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -6,7 +6,7 @@ Database migrations are used to update the structure of the application's databa When the application detects that a migration is required, it performs the following steps: -1. Back up existing databases: Before applying any changes, the application creates a backup of each database. These backups are stored in the `migrations` directory within the application's data directory. The backup files are named using the format `.pre-migration-backup..db`. +1. Back up existing databases: Before applying any changes, the application creates a backup of each database. These backups are stored in the `backups` directory within the application's data directory. The backup files are named using the format `.pre-migration-backup..db`. 2. Apply migrations: The application applies the necessary changes to the database schema and data. @@ -18,12 +18,12 @@ If a migration fails, the application will attempt to restore the databases from 1. Locate the Backup Files: - Find the _first_ failed migration attempt and note the associated ID (it will be in application logs). If it can't be located, it is safe to assume that the oldest ID is the correct one. - - Navigate to the `migrations` directory within the application's data directory. + - Navigate to the `backups` directory within the application's data directory. - Look for files named `.pre-migration-backup..db`. 2. Restore the Backup: - Rename the backup file to replace the current database file. For example, rename `transfers.pre-migration-backup.040123_123456.db` to `transfers.db`. - - Ensure the restored file is placed in the root of the application's data directory (move it up, out of the `migrations` directory). + - Ensure the restored file is placed in the root of the application's data directory (move it up, out of the `backups` directory). 3. Restart the Application: - Start the application again. It will detect the restored database and attempt to reapply the migration. diff --git a/src/slskd/Core/Data/IMigration.cs b/src/slskd/Core/Data/IMigration.cs new file mode 100644 index 00000000..18b198b2 --- /dev/null +++ b/src/slskd/Core/Data/IMigration.cs @@ -0,0 +1,38 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd; + +/// +/// Applies database migrations. +/// +public interface IMigration +{ + /// + /// Determines whether the migration needs to be applied. + /// + /// + /// This method MUST be read-only and should contain no side effects. + /// + /// A value indicating whether the migration needs to be applied. + bool NeedsToBeApplied(); + + /// + /// Applies the migration. + /// + void Apply(); +} \ No newline at end of file diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index e8630265..2b5fd6f4 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -27,6 +27,4 @@ Review the `IMigration` interface to determine implementation details. The new `IMigration` implementation must be added to the dictionary in the `Migrations` property of the `Migrator` in the desired order so that it can be run. -### Above all else, each and every migration **MUST** be idempotent. - -Users can delete the history file or use the `force` flag to cause migrations to be run again. We can inspect schemas to determine whether re-running is necessary, but there may be cases where that's not enough. \ No newline at end of file +### Above all else, each and every migration **MUST** be idempotent; they'll be evaluated and run each time the app starts. \ No newline at end of file diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 4cc56147..e359d334 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -25,26 +25,6 @@ using System.Linq; using Serilog; using slskd.Migrations; -/// -/// Applies database migrations. -/// -public interface IMigration -{ - /// - /// Determines whether the migration needs to be applied. - /// - /// - /// This method MUST be read-only and should contain no side effects. - /// - /// A value indicating whether the migration needs to be applied. - bool NeedsToBeApplied(); - - /// - /// Applies the migration. - /// - void Apply(); -} - /// /// Applies database migrations. /// -- cgit v1.2.3 From 9964d73a431a869175f88468496ac58b97fc246f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 May 2025 17:49:46 -0500 Subject: eliminate HasFlag workaround --- src/slskd/Application.cs | 12 +++--------- .../Transfers/API/Controllers/TransfersController.cs | 7 ++----- src/slskd/Transfers/Downloads/DownloadService.cs | 16 ++++++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 20 ++++++++------------ 4 files changed, 21 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 2449e8e0..e0570ef6 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -313,9 +313,7 @@ namespace slskd // records to be updated if the application has started to shut down so that we can do this cleanup and properly // disposition them as having failed due to an application shutdown, instead of some random exception thrown while // things are being disposed. - var activeUploads = Transfers.Uploads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true) - .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280 - .ToList(); + var activeUploads = Transfers.Uploads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true); foreach (var upload in activeUploads) { @@ -326,9 +324,7 @@ namespace slskd Transfers.Uploads.Update(upload); } - var activeDownloads = Transfers.Downloads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true) - .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280 - .ToList(); + var activeDownloads = Transfers.Downloads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true); foreach (var download in activeDownloads) { @@ -344,9 +340,7 @@ namespace slskd when the search is complete, so when a search 'dangles' all responses have been lost. to avoid discrepancies, we need to zero the response and file counts as well as set the state and EndedAt. */ - var activeSearches = (await Search.ListAsync(s => s.EndedAt == null || !s.State.HasFlag(SearchStates.Completed))) - .Where(s => s.EndedAt == null || !s.State.HasFlag(SearchStates.Completed)) // https://github.com/slskd/slskd/issues/1280 - .ToList(); + var activeSearches = await Search.ListAsync(s => s.EndedAt == null || !s.State.HasFlag(SearchStates.Completed)); foreach (var search in activeSearches) { diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index f143e4a7..fdbca1dc 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -111,9 +111,7 @@ namespace slskd.Transfers.API return Forbid(); } - var transfers = Transfers.Downloads - .List() // https://github.com/dotnet/efcore/issues/10434 - .Where(t => t.State.HasFlag(Soulseek.TransferStates.Completed)); + var transfers = Transfers.Downloads.List(t => t.State.HasFlag(Soulseek.TransferStates.Completed)); foreach (var id in transfers.Select(t => t.Id)) { @@ -182,8 +180,7 @@ namespace slskd.Transfers.API // get all the transfers that aren't removed var transfers = Transfers.Uploads - .List(t => true, includeRemoved: false) // https://github.com/dotnet/efcore/issues/10434 - .Where(t => t.State.HasFlag(Soulseek.TransferStates.Completed)); + .List(t => t.State.HasFlag(Soulseek.TransferStates.Completed), includeRemoved: false); foreach (var id in transfers.Select(t => t.Id)) { diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 37df355c..63b04394 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -87,9 +87,9 @@ namespace slskd.Transfers.Downloads /// Removes downloads older than the specified . /// /// The age after which downloads are eligible for pruning, in hours. - /// An optional, additional state by which downloads are filtered for pruning. + /// An optional, additional state by which downloads are filtered for pruning. /// The number of pruned downloads. - int Prune(int age, TransferStates state = TransferStates.Completed); + int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed); /// /// Removes the download matching the specified . @@ -531,13 +531,13 @@ namespace slskd.Transfers.Downloads /// Removes downloads older than the specified . /// /// The age after which downloads are eligible for pruning, in hours. - /// An optional, additional state by which downloads are filtered for pruning. + /// An optional, additional state by which downloads are filtered for pruning. /// The number of pruned downloads. - public int Prune(int age, TransferStates state = TransferStates.Completed) + public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) { - if (!state.HasFlag(TransferStates.Completed)) + if (!stateHasFlag.HasFlag(TransferStates.Completed)) { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(state)); + throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); } try @@ -550,7 +550,7 @@ namespace slskd.Transfers.Downloads .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State == state) // https://github.com/dotnet/efcore/issues/20094 + .Where(t => t.State == stateHasFlag) .ToList(); foreach (var tx in expired) @@ -562,7 +562,7 @@ namespace slskd.Transfers.Downloads if (pruned > 0) { - Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, state); + Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag); } return pruned; diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index dff1252b..1dcd7406 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -95,9 +95,9 @@ namespace slskd.Transfers.Uploads /// Removes uploads older than the specified . /// /// The age after which uploads are eligible for pruning, in minutes. - /// An optional, additional state by which uploads are filtered for pruning. + /// An optional, additional state by which uploads are filtered for pruning. /// The number of pruned uploads. - int Prune(int age, TransferStates state = TransferStates.Completed); + int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed); /// /// Removes the upload matching the specified . @@ -541,13 +541,13 @@ namespace slskd.Transfers.Uploads /// Removes uploads older than the specified . /// /// The age after which uploads are eligible for pruning, in minutes. - /// An optional, additional state by which uploads are filtered for pruning. + /// An optional, additional state by which uploads are filtered for pruning. /// The number of pruned uploads. - public int Prune(int age, TransferStates state = TransferStates.Completed) + public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) { - if (!state.HasFlag(TransferStates.Completed)) + if (!stateHasFlag.HasFlag(TransferStates.Completed)) { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(state)); + throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); } try @@ -560,11 +560,7 @@ namespace slskd.Transfers.Uploads .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - - // note: don't try HasFlag() here: https://github.com/dotnet/efcore/issues/20094 - // this won't work because the state is stored as a comma separated string (which we've done deliberately) - // and EF won't do the necessary work to generate the required SQL - .Where(t => t.State == state) + .Where(t => t.State.HasFlag(stateHasFlag)) .ToList(); foreach (var tx in expired) @@ -576,7 +572,7 @@ namespace slskd.Transfers.Uploads if (pruned > 0) { - Log.Debug("Pruned {Count} expired uploads with state {State}", pruned, state); + Log.Debug("Pruned {Count} expired uploads with state {State}", pruned, stateHasFlag); } return pruned; -- cgit v1.2.3 From d57d8a065bc384442199a91a7a388dc14b733f9e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 May 2025 17:50:08 -0500 Subject: update typo'ed error message --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 0537824f..dd85bc21 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -674,7 +674,7 @@ namespace slskd if (SQLitePCL.raw.sqlite3_config(SQLitePCL.raw.SQLITE_CONFIG_SERIALIZED) != SQLitePCL.raw.SQLITE_OK) { - throw new InvalidOperationException($"SQLite threading mode could not be set to . Please create a GitHub issue to report this and include details about your environment."); + throw new InvalidOperationException($"SQLite threading mode could not be set to SERIALIZED ({SQLitePCL.raw.SQLITE_CONFIG_SERIALIZED}). Please create a GitHub issue to report this and include details about your environment."); } Log.Debug("SQLite threading mode set to {Mode} ({Number})", "SERIALIZED", SQLitePCL.raw.SQLITE_CONFIG_SERIALIZED); -- cgit v1.2.3 From 068542fc0d07840eb49dc5f70c578ae31ace1048 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 May 2025 17:50:18 -0500 Subject: add context to note --- src/slskd/Transfers/Uploads/UploadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 1dcd7406..7e96533e 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -489,7 +489,7 @@ namespace slskd.Transfers.Uploads .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(expression) - .GroupBy(t => true) // https://stackoverflow.com/a/25489456 + .GroupBy(t => true) // https://stackoverflow.com/a/25489456: The GroupBy(x => true) statement places all items into a single group. The Select statement the allows operations against each group. .Select(t => new { Files = t.Count(), -- cgit v1.2.3 From 99d510d1d3fe4daf9e2ada01432e6fd68b3a1c96 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 19 Jun 2025 12:28:34 -0500 Subject: bump Soulseek.NET to 7.1.0 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index cfb39234..b136b728 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From be947ef10e44d96ff795a312da4d6f7ea10bad68 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 19 Jun 2025 19:27:58 -0500 Subject: tweak logging of diagnostics --- src/slskd/Application.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e0570ef6..6ed8a9d4 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -808,8 +808,9 @@ namespace slskd { static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch { + DiagnosticLevel.Trace => LogEventLevel.Verbose, DiagnosticLevel.Debug => LogEventLevel.Debug, - DiagnosticLevel.Info => LogEventLevel.Debug, + DiagnosticLevel.Info => LogEventLevel.Information, DiagnosticLevel.Warning => LogEventLevel.Warning, DiagnosticLevel.None => default, _ => default, -- cgit v1.2.3 From 3d7b89592b12b2d98ec2f8360511ad2f9e5099e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 28 Jun 2025 17:10:51 -0500 Subject: move json serialization options and logic into WebhookService to guard against regressions --- src/slskd/Integrations/Webhooks/WebhookService.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Integrations/Webhooks/WebhookService.cs b/src/slskd/Integrations/Webhooks/WebhookService.cs index 62f097b7..b08b0484 100644 --- a/src/slskd/Integrations/Webhooks/WebhookService.cs +++ b/src/slskd/Integrations/Webhooks/WebhookService.cs @@ -25,6 +25,9 @@ using System.Linq; using System.Net; using System.Net.Http; using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading.Tasks; using Serilog; using slskd.Events; @@ -40,6 +43,15 @@ public class WebhookService OptionsMonitor = optionsMonitor; HttpClientFactory = httpClientFactory; + var json = new JsonSerializerOptions(); + json.Converters.Add(new IPAddressConverter()); + json.Converters.Add(new JsonStringEnumConverter()); + json.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + json.DefaultIgnoreCondition = JsonIgnoreCondition.Never; // include properties with null values + json.Encoder = JavaScriptEncoder.Default; // IMPORTANT! don't change this to 'UnsafeRelaxedJsonEscaping'; as the name implies, it's unsafe! + + JsonSerializerOptions = json; + Events.Subscribe(nameof(WebhookService), HandleEvent); Log.Debug("{Service} initialized", nameof(WebhookService)); @@ -49,6 +61,7 @@ public class WebhookService private IOptionsMonitor OptionsMonitor { get; } private EventBus Events { get; } private IHttpClientFactory HttpClientFactory { get; } + private JsonSerializerOptions JsonSerializerOptions { get; } private async Task HandleEvent(Event data) { @@ -80,7 +93,10 @@ public class WebhookService http.DefaultRequestHeaders.TryAddWithoutValidation(header.Name, header.Value); } - var content = new StringContent(data.ToJson(), Encoding.UTF8, "application/json"); + var content = new StringContent( + content: JsonSerializer.Serialize(data, JsonSerializerOptions), + encoding: Encoding.UTF8, + mediaType: "application/json"); HttpStatusCode? statusCode = null; -- cgit v1.2.3 From 500573a450e5420a55196fcbf4897fb2bece69dc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Jul 2025 19:07:19 -0500 Subject: move serializer options for scripts --- src/slskd/Integrations/Scripts/ScriptService.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 05769a6d..109cf5ff 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -22,6 +22,9 @@ namespace slskd.Integrations.Scripts; using System; using System.Diagnostics; using System.Linq; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; using System.Text.RegularExpressions; using System.Threading.Tasks; using Serilog; @@ -37,6 +40,15 @@ public class ScriptService Events = eventBus; OptionsMonitor = optionsMonitor; + var json = new JsonSerializerOptions(); + json.Converters.Add(new IPAddressConverter()); + json.Converters.Add(new JsonStringEnumConverter()); + json.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + json.DefaultIgnoreCondition = JsonIgnoreCondition.Never; // include properties with null values + json.Encoder = JavaScriptEncoder.Default; // IMPORTANT! don't change this to 'UnsafeRelaxedJsonEscaping'; as the name implies, it's unsafe! + + JsonSerializerOptions = json; + Events.Subscribe(nameof(ScriptService), HandleEvent); if (OperatingSystem.IsWindows()) @@ -64,6 +76,7 @@ public class ScriptService private EventBus Events { get; } private string DefaultExecutable { get; } private string DefaultCommandPrefix { get; } + private JsonSerializerOptions JsonSerializerOptions { get; } private async Task HandleEvent(Event data) { @@ -167,7 +180,7 @@ public class ScriptService Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, run.Args ?? string.Join(' ', run.Arglist ?? []), processId); var sw = Stopwatch.StartNew(); - process.StartInfo.EnvironmentVariables["SLSKD_SCRIPT_DATA"] = data.ToJson(); + process.StartInfo.EnvironmentVariables["SLSKD_SCRIPT_DATA"] = JsonSerializer.Serialize(data, JsonSerializerOptions); process.Start(); process.WaitForExit(); -- cgit v1.2.3