aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-07-05 17:51:23 -0500
committerGitHub <noreply@github.com>2025-07-05 17:51:23 -0500
commit8551ea1930b6639007d18fdca35bfb4073b16914 (patch)
tree2430f701f8359e602f4c16847331c588cb473cca
parent8ab0cda52fda8b7e4f0353065c6f0dc5caeeb1f1 (diff)
parent4914c3832358218d28f977baed2ddfb1e7e92723 (diff)
downloadslskd-8551ea1930b6639007d18fdca35bfb4073b16914.tar.gz
Merge branch 'master' into dependabot/npm_and_yarn/src/web/http-proxy-middleware-2.0.9
-rw-r--r--Dockerfile7
-rw-r--r--config/slskd.example.yml1
-rw-r--r--docs/README.md6
-rw-r--r--docs/config.md37
-rw-r--r--docs/migrations.md44
-rw-r--r--src/slskd/Application.cs15
-rw-r--r--src/slskd/Common/Waiter.cs2
-rw-r--r--src/slskd/Core/Data/IMigration.cs38
-rw-r--r--src/slskd/Core/Data/Migrations/README.md30
-rw-r--r--src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs232
-rw-r--r--src/slskd/Core/Data/Migrator.cs211
-rw-r--r--src/slskd/Core/Data/SchemaInspector.cs82
-rw-r--r--src/slskd/Core/Options.cs8
-rw-r--r--src/slskd/Integrations/Scripts/ScriptService.cs15
-rw-r--r--src/slskd/Integrations/Webhooks/WebhookService.cs18
-rw-r--r--src/slskd/Program.cs23
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs7
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs16
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs19
-rw-r--r--src/slskd/Transfers/Types/Transfer.cs12
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs22
-rw-r--r--src/slskd/slskd.csproj3
22 files changed, 791 insertions, 57 deletions
diff --git a/Dockerfile b/Dockerfile
index cc7484a1..5b174a0a 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -57,13 +57,14 @@ RUN bash -c 'mkdir -p /app/{incomplete,downloads} \
VOLUME /app
-HEALTHCHECK --interval=60s --timeout=3s --start-period=5s --retries=3 CMD wget -q -O - http://localhost:${SLSKD_HTTP_PORT}/health
+HEALTHCHECK --interval=60s --timeout=3s --start-period=60m --retries=3 CMD wget -q -O - http://localhost:${SLSKD_HTTP_PORT}/health
-ENV DOTNET_EnableDiagnostics=0 \
+ENV SHELL=/usr/bin/bash \
+ DOTNET_EnableDiagnostics=0 \
DOTNET_BUNDLE_EXTRACT_BASE_DIR=/.net \
DOTNET_gcServer=0 \
DOTNET_gcConcurrent=1 \
- DOTNET_GCHeapHardLimit=1F400000 \
+ DOTNET_GCHeapHardLimit=0x80000000 \
DOTNET_GCConserveMemory=9 \
SLSKD_UMASK=0022 \
SLSKD_HTTP_PORT=5030 \
diff --git a/config/slskd.example.yml b/config/slskd.example.yml
index c73118e5..86e272ef 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/docs/README.md b/docs/README.md
index ce8316a7..eb08d969 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -17,4 +17,8 @@
## Building slskd from Source
-### [Build](https://github.com/slskd/slskd/blob/master/docs/build.md) \ No newline at end of file
+### [Build](https://github.com/slskd/slskd/blob/master/docs/build.md)
+
+## Troubleshooting
+
+### [Migrations](https://github.com/slskd/slskd/blob/master/docs/migrations.md) \ No newline at end of file
diff --git a/docs/config.md b/docs/config.md
index 78d1db48..6f01c2af 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -1033,11 +1033,23 @@ integration:
### Scripts
-User-defined scripts can be configured to run when application events are raised. Scripts are given a name (useful for troubleshooting!), a list of triggering events, and a `run` command that's used to execute the script.
+User-defined scripts can be configured to run when application events are raised. Scripts are given a name (useful for troubleshooting!), a list of triggering events, and a `run` configuration that's used to execute the script.
-The `run` command must be at least one word, with the first word identifying the executable to run and the rest of the string being the command and arguments that will be passed to the executable when the script is run. The executable needs to be on the system's PATH, otherwise it must be the fully qualified path to the file on disk.
+The `run` configuration can take a few different forms (see examples below), but in all cases a new process is started using either the `executable` you specify or, if you don't specify one, the executable set in your system's `$SHELL` environment variable, or `cmd.exe` on Windows.
-A reserved placeholder value `$DATA` is replaced with the stringified JSON data associated with the event that caused the script to run. It's the responsibility of the script to parse and handle this JSON.
+Processes are started in the `/scripts` directory (meaning the working directory), and stdout and stderr are redirected to slskd for logging purposes. Depending on the `run` configuration your defined command will be passed as either a single argument or list of arguments, with the latter being easier to properly quote and escape.
+
+The data associated with the event that's invoking your script is stringified to JSON and set as the value of the `SLSKD_SCRIPT_DATA` environment variable. Whatever command or script you specify will need to read this value and handle the data.
+
+> [!CAUTION]
+> **Remote Code Execution Risk**: The event data in `$SLSKD_SCRIPT_DATA` originates from the Soulseek network and may contain malicious content. Passing this data as command-line arguments could allow attackers to inject shell commands through specially crafted filenames, usernames, or other fields. For example, a filename like `song"; rm -rf /; echo "` could delete your entire filesystem if passed unsafely to a shell command.
+>
+> **Best practices:**
+> - ✅ Read `$SLSKD_SCRIPT_DATA` as an environment variable
+> - ✅ Parse the JSON and validate/sanitize individual fields before use
+> - ✅ Use programming languages with proper JSON parsing (Python, Node.js, etc.)
+> - ❌ Avoid using `$SLSKD_SCRIPT_DATA` in shell command substitution like `$(echo $SLSKD_SCRIPT_DATA)`
+> - ❌ Avoid passing the raw data as arguments: `my_script.sh "$SLSKD_SCRIPT_DATA"`
#### **YAML**
```yaml
@@ -1047,11 +1059,22 @@ integration:
on:
- DownloadFileComplete
- DownloadDirectoryComplete
- run: /bin/sh data/my_script.sh --json-to-process "$DATA" # Linux/macOS
+ run:
+ command: "echo "new event!" >> event_log.txt # command is run with system $SHELL/cmd.exe on Windows
my_logging_script:
on:
- - All
- run: cmd.exe echo $DATA >> event_log.txt # Windows
+ - All
+ run:
+ executable: /bin/sh # explicitly setting executable; if omitted, $SHELL/cmd.exe is used
+ args: '-c "echo "new event!" >> event_log.txt"'
+ another_script:
+ on:
+ - All
+ run:
+ executable: /bin/sh # as above, can omit to use $SHELL/cmd.exe
+ arglist: # easier to properly quote
+ - /c
+ - 'echo "new event!" >> event_log.txt'
```
## System-Defined
@@ -1231,6 +1254,7 @@ Several additional feature flags are provided to change the application's runtim
| `--no-connect` | `SLSKD_NO_CONNECT` | Start the application, but don't connect to the server |
| `--no-share-scan` | `SLSKD_NO_SHARE_SCAN` | Don't perform a scan of shared directories on startup |
| `--force-share-scan` | `SLSKD_FORCE_SHARE_SCAN` | Force a scan of shared directories on startup |
+| `--force-migrations` | `SLSKD_FORCE_MIGRATIONS` | Force database migrations to be applied on startup |
| `--no-version-check` | `SLSKD_NO_VERSION_CHECK` | Don't perform a version check on startup |
| `--log-sql` | `SLSKD_LOG_SQL` | Log SQL queries generated by Entity Framework |
| `--volatile` | `SLSKD_VOLATILE` | Use volatile data storage (all data will be lost at shutdown) |
@@ -1247,6 +1271,7 @@ flags:
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/docs/migrations.md b/docs/migrations.md
new file mode 100644
index 00000000..2fec53bd
--- /dev/null
+++ b/docs/migrations.md
@@ -0,0 +1,44 @@
+# Database Migrations
+
+Database migrations are used to update the structure of the application's databases to support new features or improve functionality. These migrations are applied automatically when the application starts. If a migration fails, the application will attempt to restore the database to its pre-migration state using backups created before the migration process began.
+
+## Migration Process
+
+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 `backups` directory within the application's data directory. The backup files are named using the format `<database>.pre-migration-backup.<migration id>.db`.
+
+2. Apply migrations: The application applies the necessary changes to the database schema and data.
+
+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).
+
+## 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:
+
+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 `backups` directory within the application's data directory.
+ - Look for files named `<database>.pre-migration-backup.<migration id>.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 `backups` directory).
+
+3. Restart the Application:
+ - Start the application again. It will detect the restored database and attempt to reapply the migration.
+
+## If the Migration Continues to Fail
+
+If the application gets "stuck" in a reboot loop and can't complete migration(s) successfully, you will need to rename (or delete) the existing database files and allow the application to re-generate them.
+
+It should be possible to recover the old data, but the process will need to be manual. Create a GitHub issue and provide logs from the failing migration(s).
+
+## Preventing Migration Issues
+
+To minimize the risk of migration failures:
+
+- Ensure Sufficient Disk Space: Verify that there is enough disk space available for creating backups and applying migrations.
+- Avoid Interruptions: Do not stop the application while a migration is in progress.
+- Monitor Logs: Check the application logs for detailed information about the migration process and any errors encountered.
+
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 2449e8e0..6ed8a9d4 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)
{
@@ -814,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,
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/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 file="IMigration.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd;
+
+/// <summary>
+/// Applies database migrations.
+/// </summary>
+public interface IMigration
+{
+ /// <summary>
+ /// Determines whether the migration needs to be applied.
+ /// </summary>
+ /// <remarks>
+ /// This method MUST be read-only and should contain no side effects.
+ /// </remarks>
+ /// <returns>A value indicating whether the migration needs to be applied.</returns>
+ bool NeedsToBeApplied();
+
+ /// <summary>
+ /// Applies the migration.
+ /// </summary>
+ 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
new file mode 100644
index 00000000..2b5fd6f4
--- /dev/null
+++ b/src/slskd/Core/Data/Migrations/README.md
@@ -0,0 +1,30 @@
+# Database Migrations
+
+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 `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. The naming convention for migration classes is:
+
+```
+Z<MMDDYYYY>_<ShortDescription>Migration
+```
+
+Migrations MUST:
+
+* 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.
+* 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.
+
+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; they'll be evaluated and run each time the app starts. \ No newline at end of file
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..f7af80f5
--- /dev/null
+++ b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs
@@ -0,0 +1,232 @@
+// <copyright file="Z04012025_TransferStateMigration.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Migrations;
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using Microsoft.Data.Sqlite;
+using Serilog;
+
+/// <summary>
+/// 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.
+/// </summary>
+public class Z04012025_TransferStateMigration : IMigration
+{
+ private ILogger Log { get; } = Serilog.Log.ForContext<Z04012025_TransferStateMigration>();
+ 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<string, int> 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<string, int>();
+
+ while (reader.Read())
+ {
+ var state = reader.GetString(0);
+ dict[state] = (int)Enum.Parse(typeof(Z04012025_TransferStateMigration_TransferStates), state);
+ }
+
+ Log.Debug("State -> int map: {Map}", dict);
+ return dict;
+ }
+
+ private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary<string, int> 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;
+ }
+ }
+
+#pragma warning disable SA1201 // Elements should appear in the correct order
+ /// <summary>
+ /// 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.
+ /// </summary>
+ [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
+}
diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs
new file mode 100644
index 00000000..e359d334
--- /dev/null
+++ b/src/slskd/Core/Data/Migrator.cs
@@ -0,0 +1,211 @@
+// <copyright file="Migrator.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd;
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using Serilog;
+using slskd.Migrations;
+
+/// <summary>
+/// Applies database migrations.
+/// </summary>
+public class Migrator
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Migrator"/> class.
+ /// </summary>
+ /// <param name="databases">A list of known databases.</param>
+ public Migrator(params string[] databases)
+ {
+ Databases = databases;
+ }
+
+ private IEnumerable<string> Databases { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<Migrator>();
+
+ /// <summary>
+ /// A map of all migrations, to be applied in the order they are specified (descending).
+ /// </summary>
+ private Dictionary<string, IMigration> Migrations { get; } = new()
+ {
+ { nameof(Z04012025_TransferStateMigration), new Z04012025_TransferStateMigration() },
+ };
+
+ /// <summary>
+ /// Applies database migrations.
+ /// </summary>
+ /// <param name="force">Apply all migrations, regardless of whether there's evidence they have been applied already.</param>
+ public void Migrate(bool force = false)
+ {
+ List<string> migrationsToApply = [];
+ List<string> migrationsToSkip = [];
+
+ /*
+ determine which migrations need to be applied
+
+ 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)
+ {
+ // warning: performs I/O
+ if (!Migrations[migration].NeedsToBeApplied())
+ {
+ Log.Debug("Migration {Name} does not need to be applied", migration);
+ migrationsToSkip.Add(migration);
+ }
+ else
+ {
+ Log.Debug("Migration {Name} needs to be applied", migration);
+ migrationsToApply.Add(migration);
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, "Failed to disposition migrations: {Message}", ex.Message);
+ throw;
+ }
+
+ Log.Debug("Migrations: {Migrations}", new { migrationsToApply, migrationsToSkip });
+
+ if (migrationsToApply.Count == 0)
+ {
+ Log.Information("Databases are up to date!");
+ return;
+ }
+
+ /*
+ 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");
+
+ 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
+ // 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 src = MakeSourceDatabasePath(database);
+ var dest = MakeBackupDatabasePath(database, migrationId);
+
+ 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 = migrationsToApply.Count();
+
+ var currentSw = new Stopwatch();
+
+ foreach (var migration in migrationsToApply)
+ {
+ current++;
+ currentSw.Restart();
+
+ Log.Warning("Applying migration {Name} ({Current} of {Total})", migration, current, total);
+
+ try
+ {
+ Migrations[migration].Apply();
+
+ 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)", 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 = MakeBackupDatabasePath(database, migrationId);
+ var dest = MakeSourceDatabasePath(database);
+
+ // 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);
+ }
+
+ 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 '<database>.pre-migration.{migrationId}.db' to '<database>.db' prior to starting the application again.");
+ }
+
+ throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex);
+ }
+
+ Log.Information("Migration(s) complete!");
+ }
+
+ private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.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/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 file="SchemaInspector.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd;
+
+using System;
+using System.Collections.Generic;
+using Microsoft.Data.Sqlite;
+
+/// <summary>
+/// Assistive class for inspecting SQLite database schemas.
+/// </summary>
+public static class SchemaInspector
+{
+ /// <summary>
+ /// Retrieves the schema information for the specified SQLite database.
+ /// </summary>
+ /// <param name="connectionString">The connection string for the database.</param>
+ /// <returns>The schema information.</returns>
+ /// <exception cref="SlskdException">Thrown if the database can't be accessed, or something else goes wrong.</exception>
+ public static Dictionary<string, IEnumerable<ColumnInfo>> GetDatabaseSchema(string connectionString)
+ {
+ try
+ {
+ using var connection = new SqliteConnection(connectionString);
+ connection.Open();
+
+ var dict = new Dictionary<string, IEnumerable<ColumnInfo>>();
+
+ 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<ColumnInfo>();
+
+ 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);
+ }
+ }
+
+ /// <summary>
+ /// Represents a SQLite database column.
+ /// </summary>
+ public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey);
+} \ No newline at end of file
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index cc662444..1fed70f5 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -392,6 +392,14 @@ namespace slskd
public bool ForceShareScan { get; init; } = false;
/// <summary>
+ /// Gets a value indicating whether to force database migrations to be applied on startup.
+ /// </summary>
+ [Argument(default, "force-migrations")]
+ [EnvironmentVariable("FORCE_MIGRATIONS")]
+ [Description("force database migrations to be applied on startup")]
+ public bool ForceMigrations { get; init; } = false;
+
+ /// <summary>
/// Gets a value indicating whether the application should check for a newer version on startup.
/// </summary>
[Argument(default, "no-version-check")]
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<Event>(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();
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<Event>(nameof(WebhookService), HandleEvent);
Log.Debug("{Service} initialized", nameof(WebhookService));
@@ -49,6 +61,7 @@ public class WebhookService
private IOptionsMonitor<Options> 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;
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index b7fa47d2..dd85bc21 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -188,6 +188,11 @@ namespace slskd
public static string DataDirectory { get; private set; } = null;
/// <summary>
+ /// Gets the path where backups of persistent data saved.
+ /// </summary>
+ public static string DataBackupDirectory { get; private set; } = null;
+
+ /// <summary>
/// Gets the default fully qualified path to the configuration file.
/// </summary>
public static string DefaultConfigurationFile { get; private set; }
@@ -336,6 +341,7 @@ namespace slskd
// derive the application directory value and defaults that are dependent upon it
AppDirectory ??= DefaultAppDirectory;
DataDirectory = Path.Combine(AppDirectory, "data");
+ DataBackupDirectory = Path.Combine(DataDirectory, "backups");
LogDirectory = Path.Combine(AppDirectory, "logs");
ScriptDirectory = Path.Combine(AppDirectory, "scripts");
@@ -353,6 +359,7 @@ namespace slskd
{
VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true);
VerifyDirectory(DataDirectory, 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);
@@ -494,6 +501,14 @@ namespace slskd
var app = builder.Build();
+ if (!OptionsAtStartup.Flags.Volatile)
+ {
+ Log.Debug($"Running Migrate()...");
+
+ // note: if this ever throws, we've forgotten to register a Migrator following database DI config
+ app.Services.GetService<Migrator>().Migrate(force: OptionsAtStartup.Flags.ForceMigrations);
+ }
+
// 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<ScriptService>();
@@ -596,6 +611,12 @@ namespace slskd
services.AddDbContext<TransfersDbContext>(DiskConnectionString("transfers"));
services.AddDbContext<MessagingDbContext>(DiskConnectionString("messaging"));
services.AddDbContext<EventsDbContext>(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.
+ // 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<Migrator>(_ => new Migrator(databases: ["search", "transfers", "messaging", "events"]));
}
services.AddSingleton<EventService>();
@@ -653,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);
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 <see cref="TransferStates.Completed"/> downloads older than the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age after which downloads are eligible for pruning, in hours.</param>
- /// <param name="state">An optional, additional state by which downloads are filtered for pruning.</param>
+ /// <param name="stateHasFlag">An optional, additional state by which downloads are filtered for pruning.</param>
/// <returns>The number of pruned downloads.</returns>
- int Prune(int age, TransferStates state = TransferStates.Completed);
+ int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed);
/// <summary>
/// Removes the download matching the specified <paramref name="id"/>.
@@ -531,13 +531,13 @@ namespace slskd.Transfers.Downloads
/// Removes <see cref="TransferStates.Completed"/> downloads older than the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age after which downloads are eligible for pruning, in hours.</param>
- /// <param name="state">An optional, additional state by which downloads are filtered for pruning.</param>
+ /// <param name="stateHasFlag">An optional, additional state by which downloads are filtered for pruning.</param>
/// <returns>The number of pruned downloads.</returns>
- 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/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<Transfer> 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<Transfer>())
+ {
+ 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<Transfer>()
.Property(d => d.Direction)
.HasConversion(new EnumToStringConverter<Soulseek.TransferDirection>());
-
- modelBuilder
- .Entity<Transfer>()
- .Property(d => d.State)
- .HasConversion(new EnumToStringConverter<Soulseek.TransferStates>());
}
}
}
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;
+
+ /// <summary>
+ /// Gets the string representation of the transfer <see cref="State"/>.
+ /// </summary>
+ /// <remarks>
+ /// 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.
+ /// </remarks>
+ public string StateDescription { get; set; }
public DateTime RequestedAt { get; set; }
public DateTime? EnqueuedAt { get; set; }
public DateTime? StartedAt { get; set; }
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index dff1252b..7e96533e 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -95,9 +95,9 @@ namespace slskd.Transfers.Uploads
/// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age after which uploads are eligible for pruning, in minutes.</param>
- /// <param name="state">An optional, additional state by which uploads are filtered for pruning.</param>
+ /// <param name="stateHasFlag">An optional, additional state by which uploads are filtered for pruning.</param>
/// <returns>The number of pruned uploads.</returns>
- int Prune(int age, TransferStates state = TransferStates.Completed);
+ int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed);
/// <summary>
/// Removes the upload matching the specified <paramref name="id"/>.
@@ -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(),
@@ -541,13 +541,13 @@ namespace slskd.Transfers.Uploads
/// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age after which uploads are eligible for pruning, in minutes.</param>
- /// <param name="state">An optional, additional state by which uploads are filtered for pruning.</param>
+ /// <param name="stateHasFlag">An optional, additional state by which uploads are filtered for pruning.</param>
/// <returns>The number of pruned uploads.</returns>
- 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;
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 39248289..b136b728 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -13,6 +13,7 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
+ <_SkipUpgradeNetAnalyzersNuGetWarning>true</_SkipUpgradeNetAnalyzersNuGetWarning>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
@@ -67,7 +68,7 @@
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" />
<PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" />
- <PackageReference Include="Soulseek" Version="7.0.3" />
+ <PackageReference Include="Soulseek" Version="7.1.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>