aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-09-11 18:13:24 -0500
committerGitHub <noreply@github.com>2022-09-11 18:13:24 -0500
commite7b57da3dad5dacb6dbbc59c1464950eb170b0b4 (patch)
tree951f5f3531e3d69c99c9fd202d4467b4ff1d46ad /src
parent3d657ed87cfdab4089c72d9e6532d9b2cc83aa4e (diff)
parenta596dfe252ef53e41b91ec6773aec93307c41f1e (diff)
downloadslskd-e7b57da3dad5dacb6dbbc59c1464950eb170b0b4.tar.gz
Merge pull request #641 from slskd/in-memory
Refactor share options, add option to allow users to select between on-disk and in-memory share caching
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs26
-rw-r--r--src/slskd/Common/CommonExtensions.cs11
-rw-r--r--src/slskd/Core/ConnectionStrings.cs1
-rw-r--r--src/slskd/Core/Options.cs111
-rw-r--r--src/slskd/Core/Types/StorageMode.cs (renamed from src/slskd/Core/Filenames.cs)19
-rw-r--r--src/slskd/Integrations/FTP/FTPClientFactory.cs16
-rw-r--r--src/slskd/Program.cs39
-rw-r--r--src/slskd/Shares/ShareService.cs8
-rw-r--r--src/slskd/Shares/SharedFileCache.cs160
-rw-r--r--src/slskd/Transfers/Uploads/UploadQueue.cs6
10 files changed, 263 insertions, 134 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index f3feec23..cab2b649 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -428,7 +428,7 @@ namespace slskd
BrowseResponse response = default;
- var cacheFilename = Path.Combine(Program.DataDirectory, Filenames.BrowseCache);
+ var cacheFilename = Path.Combine(Program.DataDirectory, "browse.cache");
var cacheFileInfo = new FileInfo(cacheFilename);
if (!cacheFileInfo.Exists)
@@ -780,15 +780,15 @@ namespace slskd
pendingReconnect |= requiresReconnect;
}
- if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any()
- || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any())
+ if (PreviousOptions.Shares.Directories.Except(newOptions.Shares.Directories).Any()
+ || newOptions.Shares.Directories.Except(PreviousOptions.Shares.Directories).Any())
{
State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } });
Log.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect.");
}
- if (PreviousOptions.Filters.Share.Except(newOptions.Filters.Share).Any()
- || newOptions.Filters.Share.Except(PreviousOptions.Filters.Share).Any())
+ if (PreviousOptions.Shares.Filters.Except(newOptions.Shares.Filters).Any()
+ || newOptions.Shares.Filters.Except(PreviousOptions.Shares.Filters).Any())
{
State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } });
Log.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect.");
@@ -989,7 +989,17 @@ namespace slskd
SharesRefreshStarted = DateTime.UtcNow;
State.SetValue(s => s with { Shares = current });
- Log.Information("Scanning shares");
+ Log.Information("Share scan started");
+
+ try
+ {
+ System.IO.File.Delete(Path.Combine(Program.DataDirectory, "browse.cache"));
+ Log.Information("Cleared browse response cache");
+ }
+ catch
+ {
+ // noop
+ }
}
else if (previous.Scanning && !current.Scanning)
{
@@ -1022,7 +1032,7 @@ namespace slskd
{
// the share transitioned into ready without completing a scan; it was loaded from disk
State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } });
- Log.Information("Shares loaded from disk successfully. Sharing {Directories} directories and {Files}", current.Directories, current.Files);
+ Log.Information("Share cache loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files);
_ = CacheBrowseResponse();
}
else
@@ -1045,7 +1055,7 @@ namespace slskd
var response = new BrowseResponse(directories);
Log.Information("Warming browse response cache...");
- System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, Filenames.BrowseCache), response.ToByteArray());
+ System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, "browse.cache"), response.ToByteArray());
Log.Information("Browse response cached successfully");
}
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 6f39d17f..9b6a3c6c 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -360,6 +360,17 @@ namespace slskd
}
/// <summary>
+ /// Casts the string to <typeparamref name="T"/>.
+ /// </summary>
+ /// <typeparam name="T">The Enum type to which to cast.</typeparam>
+ /// <param name="str">The string to cast.</param>
+ /// <returns>The cast enum</returns>
+ public static T ToEnum<T>(this string str)
+ {
+ return (T)Enum.Parse(typeof(T), str, ignoreCase: true);
+ }
+
+ /// <summary>
/// Deserializes this string from json to an object of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type to which to deserialize the string.</typeparam>
diff --git a/src/slskd/Core/ConnectionStrings.cs b/src/slskd/Core/ConnectionStrings.cs
index e5bd4f05..6afab93f 100644
--- a/src/slskd/Core/ConnectionStrings.cs
+++ b/src/slskd/Core/ConnectionStrings.cs
@@ -24,6 +24,7 @@ namespace slskd
{
public string Transfers { get; init; }
public string Shares { get; init; }
+ public string SharesBackup { get; init; }
public string Search { get; init; }
}
}
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index d6d4b04c..2d561e29 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -197,6 +197,12 @@ namespace slskd
public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions();
/// <summary>
+ /// Gets share options.
+ /// </summary>
+ [Validate]
+ public SharesOptions Shares { get; init; } = new SharesOptions();
+
+ /// <summary>
/// Gets global options.
/// </summary>
[Validate]
@@ -324,7 +330,7 @@ namespace slskd
/// <summary>
/// Directory options.
/// </summary>
- public class DirectoriesOptions : IValidatableObject
+ public class DirectoriesOptions
{
/// <summary>
/// Gets the path where incomplete downloads are saved.
@@ -345,14 +351,50 @@ namespace slskd
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Downloads { get; init; } = Program.DefaultDownloadsDirectory;
+ }
+ /// <summary>
+ /// Share options.
+ /// </summary>
+ public class SharesOptions : IValidatableObject
+ {
/// <summary>
/// Gets the list of paths to shared files.
/// </summary>
[Argument('s', "shared")]
[EnvironmentVariable("SHARED_DIR")]
- [Description("path to shared files")]
- public string[] Shared { get; init; } = Array.Empty<string>();
+ [Description("paths to shared files")]
+ public string[] Directories { get; init; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets the list of shared file filters.
+ /// </summary>
+ [Argument(default, "share-filter")]
+ [EnvironmentVariable("SHARE_FILTER")]
+ [Description("regular expressions to filter files from shares")]
+ public string[] Filters { get; init; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Share caching options.
+ /// </summary>
+ [Validate]
+ public ShareCacheOptions Cache { get; init; } = new ShareCacheOptions();
+
+ /// <summary>
+ /// Share caching options.
+ /// </summary>
+ public class ShareCacheOptions
+ {
+ /// <summary>
+ /// Gets the type of storage to use for the share cache.
+ /// </summary>
+ [Argument(default, "share-cache-storage-mode")]
+ [EnvironmentVariable("SHARE_CACHE_STORAGE_MODE")]
+ [Description("the type of storage to use for the cache")]
+ [Enum(typeof(StorageMode))]
+ [RequiresRestart]
+ public string StorageMode { get; init; } = slskd.StorageMode.Memory.ToString().ToLowerInvariant();
+ }
/// <summary>
/// Extended validation.
@@ -363,17 +405,27 @@ namespace slskd
{
var results = new List<ValidationResult>();
+ results.AddRange(ValidateShares());
+ results.AddRange(ValidateFilters());
+
+ return results;
+ }
+
+ private IEnumerable<ValidationResult> ValidateShares()
+ {
+ var results = new List<ValidationResult>();
+
bool IsBlankPath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])$");
- Shared.Where(share => IsBlankPath(share)).ToList()
+ Directories.Where(share => IsBlankPath(share)).ToList()
.ForEach(blank => results.Add(new ValidationResult($"Share {blank} doees not specify a path")));
bool IsRootMount(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])/$");
- Shared.Where(share => IsRootMount(share)).ToList()
+ Directories.Where(share => IsRootMount(share)).ToList()
.ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported.")));
// starts with '/', 'X:', or '\\'
bool IsAbsolutePath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$");
- Shared.Where(share => !IsAbsolutePath(share)).ToList()
+ Directories.Where(share => !IsAbsolutePath(share)).ToList()
.ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported.")));
(string Raw, string Alias, string Path) Digest(string share)
@@ -388,7 +440,7 @@ namespace slskd
return (share, share.Split(new[] { '/', '\\' }).Last(), share);
}
- var digestedShared = Shared
+ var digestedShared = Directories
.Select(share => Digest(share.TrimEnd('/', '\\')))
.ToHashSet();
@@ -415,6 +467,21 @@ namespace slskd
return results;
}
+
+ private IEnumerable<ValidationResult> ValidateFilters()
+ {
+ var results = new List<ValidationResult>();
+
+ foreach (var filter in Filters)
+ {
+ if (!filter.IsValidRegex())
+ {
+ results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression"));
+ }
+ }
+
+ return results;
+ }
}
/// <summary>
@@ -642,43 +709,15 @@ namespace slskd
/// <summary>
/// Filter options.
/// </summary>
- public class FiltersOptions : IValidatableObject
+ public class FiltersOptions
{
/// <summary>
- /// Gets the list of shared file filters.
- /// </summary>
- [Argument(default, "share-filter")]
- [EnvironmentVariable("SHARE_FILTER")]
- [Description("regular expressions to filter files from shares")]
- public string[] Share { get; init; } = Array.Empty<string>();
-
- /// <summary>
/// Gets search filter options.
/// </summary>
[Validate]
public SearchOptions Search { get; init; } = new SearchOptions();
/// <summary>
- /// Extended validation.
- /// </summary>
- /// <param name="validationContext"></param>
- /// <returns></returns>
- public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
- {
- var results = new List<ValidationResult>();
-
- foreach (var filter in Share)
- {
- if (!filter.IsValidRegex())
- {
- results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression"));
- }
- }
-
- return results;
- }
-
- /// <summary>
/// Search filter options.
/// </summary>
public class SearchOptions : IValidatableObject
diff --git a/src/slskd/Core/Filenames.cs b/src/slskd/Core/Types/StorageMode.cs
index 0fc55fc5..aced3050 100644
--- a/src/slskd/Core/Filenames.cs
+++ b/src/slskd/Core/Types/StorageMode.cs
@@ -1,4 +1,4 @@
-// <copyright file="Filenames.cs" company="slskd Team">
+// <copyright file="StorageMode.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -18,13 +18,18 @@
namespace slskd
{
/// <summary>
- /// Application files.
+ /// Storage mode.
/// </summary>
- public static class Filenames
+ public enum StorageMode
{
- public static readonly string TransfersDb = "transfers.db";
- public static readonly string SharesDb = "shares.db";
- public static readonly string SearchDb = "search.db";
- public static readonly string BrowseCache = "browse.cache";
+ /// <summary>
+ /// Stored in memory.
+ /// </summary>
+ Memory = 0,
+
+ /// <summary>
+ /// Stored on disk.
+ /// </summary>
+ Disk = 1,
}
}
diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs
index 2e41ab03..70cfbc03 100644
--- a/src/slskd/Integrations/FTP/FTPClientFactory.cs
+++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs
@@ -47,24 +47,10 @@ namespace slskd.Integrations.FTP
public FtpClient CreateFtpClient()
{
var client = new FtpClient(FtpOptions.Address, FtpOptions.Port, FtpOptions.Username, FtpOptions.Password);
- client.EncryptionMode = ParseFtpEncryptionMode(FtpOptions.EncryptionMode);
+ client.EncryptionMode = FtpOptions.EncryptionMode.ToEnum<FtpEncryptionMode>();
client.ValidateAnyCertificate = FtpOptions.IgnoreCertificateErrors;
return client;
}
-
- private FtpEncryptionMode ParseFtpEncryptionMode(string encryptionMode)
- {
- try
- {
- return (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), encryptionMode, ignoreCase: true);
- }
- catch (Exception ex)
- {
- // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this
- // throws there's a bug somewhere.
- throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex);
- }
- }
}
} \ No newline at end of file
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index f4e59456..e828f242 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -255,16 +255,8 @@ namespace slskd
// the application isn't being run in command mode. derive the application directory value
// and defaults that are dependent upon it
AppDirectory ??= DefaultAppDirectory;
-
DataDirectory = Path.Combine(AppDirectory, "data");
- ConnectionStrings = new()
- {
- Search = $"Data Source={Path.Combine(DataDirectory, Filenames.SearchDb)};Cache=shared;Pooling=True;",
- Transfers = $"Data Source={Path.Combine(DataDirectory, Filenames.TransfersDb)};Cache=shared;Pooling=True;",
- Shares = $"Data Source={Path.Combine(DataDirectory, Filenames.SharesDb)};Cache=shared",
- };
-
DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml");
DefaultDownloadsDirectory = Path.Combine(AppDirectory, "downloads");
DefaultIncompleteDirectory = Path.Combine(AppDirectory, "incomplete");
@@ -341,11 +333,38 @@ namespace slskd
Log.Information("Process ID: {ProcessId}", ProcessId);
Log.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName);
+ // SQLite must have specific capabilities to function properly. this shouldn't be a concern for shrinkwrapped
+ // binaries or in Docker, but if someone builds from source weird things can happen.
+ InitSQLiteOrFailFast();
+
Log.Information("Using application directory {AppDirectory}", AppDirectory);
Log.Information("Using configuration file {ConfigurationFile}", ConfigurationFile);
+ Log.Information("Storing application data in {DataDirectory}", DataDirectory);
RecreateConfigurationFileIfMissing(ConfigurationFile);
+ // configure connection strings and configure SQLite
+ string shareDbDataSource = default;
+
+ if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum<StorageMode>() == StorageMode.Disk)
+ {
+ Log.Information("Using on-disk shared file cache");
+ shareDbDataSource = Path.Combine(DataDirectory, "shares.db");
+ }
+ else
+ {
+ Log.Information("Using in-memory shared file cache");
+ shareDbDataSource = "file:shares?mode=memory";
+ }
+
+ ConnectionStrings = new()
+ {
+ Search = $"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;",
+ Transfers = $"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;",
+ Shares = $"Data Source={shareDbDataSource};Cache=shared",
+ SharesBackup = $"Data Source={Path.Combine(DataDirectory, "shares.db.bak")};",
+ };
+
if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki))
{
Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki);
@@ -465,8 +484,6 @@ namespace slskd
services.AddSingleton<IConnectionWatchdog, ConnectionWatchdog>();
- ConfigureSQLite();
-
services.AddDbContext<SearchDbContext>(ConnectionStrings.Search);
services.AddDbContext<TransfersDbContext>(ConnectionStrings.Transfers);
@@ -492,7 +509,7 @@ namespace slskd
return services;
}
- private static void ConfigureSQLite()
+ private static void InitSQLiteOrFailFast()
{
// initialize
// avoids: System.Exception: You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index 316e6b2f..dd808360 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -41,7 +41,7 @@ namespace slskd.Shares
IOptionsMonitor<Options> optionsMonitor,
ISharedFileCache sharedFileCache = null)
{
- Cache = sharedFileCache ?? new SharedFileCache();
+ Cache = sharedFileCache ?? new SharedFileCache(storageMode: optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum<StorageMode>());
Cache.StateMonitor.OnChange(cacheState =>
{
var (previous, current) = cacheState;
@@ -180,21 +180,21 @@ namespace slskd.Shares
try
{
- var optionsHash = Compute.Sha1Hash(string.Join(';', options.Directories.Shared));
+ var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories));
if (optionsHash == LastOptionsHash)
{
return;
}
- var shares = options.Directories.Shared
+ var shares = options.Shares.Directories
.Select(share => share.TrimEnd('/', '\\'))
.ToHashSet() // remove duplicates
.Select(share => new Share(share)) // convert to Shares
.OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent
.ToList();
- var regexes = options.Filters.Share
+ var regexes = options.Shares.Filters
.Select(filter => new Regex(filter, RegexOptions.Compiled))
.ToList();
diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs
index c7c1d30a..e865ff8d 100644
--- a/src/slskd/Shares/SharedFileCache.cs
+++ b/src/slskd/Shares/SharedFileCache.cs
@@ -22,6 +22,7 @@ namespace slskd.Shares
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+ using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
@@ -39,9 +40,11 @@ namespace slskd.Shares
/// <summary>
/// Initializes a new instance of the <see cref="SharedFileCache"/> class.
/// </summary>
+ /// <param name="storageMode"></param>
/// <param name="soulseekFileFactory"></param>
- public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null)
+ public SharedFileCache(StorageMode storageMode, ISoulseekFileFactory soulseekFileFactory = null)
{
+ StorageMode = storageMode;
SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory();
}
@@ -50,6 +53,7 @@ namespace slskd.Shares
/// </summary>
public IStateMonitor<SharedFileCacheState> StateMonitor => State;
+ private StorageMode StorageMode { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>();
private List<Share> Shares { get; set; }
private ISoulseekFileFactory SoulseekFileFactory { get; }
@@ -144,19 +148,24 @@ namespace slskd.Shares
try
{
+ // drop and recreate the tables to clear them
+ // note: leave the backup in place. this will leave the app in a better position if the app stops during the scan.
+ CreateTables();
+
State.SetValue(state => state with
{
Filling = true,
Filled = false,
FillProgress = 0,
+ Directories = 0,
+ Files = 0,
+ ExcludedDirectories = 0,
});
Log.Debug("Starting shared file scan");
await Task.Yield();
- ResetCache();
-
var sw = new Stopwatch();
var swSnapshot = 0L;
sw.Start();
@@ -301,6 +310,10 @@ namespace slskd.Shares
Log.Debug("Inserted {Files} records in {Elapsed}ms", cached, sw.ElapsedMilliseconds - swSnapshot);
+ Log.Debug("Backing up shared file cache database...");
+ Backup();
+ Log.Debug("Shared file cache database backup complete");
+
State.SetValue(state => state with
{
Filling = false,
@@ -437,24 +450,43 @@ namespace slskd.Shares
{
try
{
- if (TableExists("directories") && TableExists("filenames") && TableExists("files") && TableExists("exclusions"))
+ // see if we need to 'restore' the database from disk, and do so
+ if (StorageMode == StorageMode.Memory || (StorageMode == StorageMode.Disk && !ValidateTables(Program.ConnectionStrings.Shares)))
{
- // todo: check columns
+ Log.Debug($"Share cache {(StorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup...");
- State.SetValue(state => state with
+ // the backup is missing; we can't do anything but recreate it from scratch
+ if (!ValidateTables(Program.ConnectionStrings.SharesBackup))
{
- Filling = false,
- Faulted = false,
- Filled = true,
- FillProgress = 1,
- Directories = CountDirectories(),
- Files = CountFiles(),
- });
-
- return true;
+ Log.Debug("Share cache backup is missing; unable to restore");
+ return false;
+ }
+
+ Log.Debug("Share cache backup located. Attempting to restore...");
+
+ using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup);
+ using var conn = GetConnection();
+ backupConn.BackupDatabase(conn);
+
+ Log.Debug("Share cache successfully restored from backup");
}
- return false;
+ // one of several thigns happened above before we got here:
+ // the storage mode is memory, and we loaded the in-memory db from a valid backup
+ // the storage mode is disk, and the file is there and valid
+ // the storage mode is disk but either missing or invalid, and we restored from a valid backup
+ // at this point there is a valid (existing, schema matching expected schema) database at the primary connection string
+ State.SetValue(state => state with
+ {
+ Filling = false,
+ Faulted = false,
+ Filled = true,
+ FillProgress = 1,
+ Directories = CountDirectories(),
+ Files = CountFiles(),
+ });
+
+ return true;
}
catch (Exception ex)
{
@@ -463,6 +495,66 @@ namespace slskd.Shares
}
}
+ private bool ValidateTables(string connectionString)
+ {
+ var schema = new Dictionary<string, string>()
+ {
+ { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY)" },
+ { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" },
+ { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL)" },
+ };
+
+ try
+ {
+ Log.Debug("Validating shares database with connection string {String}", connectionString);
+
+ using var conn = GetConnection(connectionString);
+ using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table' AND name IN ('directories', 'filenames', 'files');", conn);
+
+ var reader = cmd.ExecuteReader();
+ var rows = 0;
+
+ while (reader.Read())
+ {
+ var table = reader.GetString(0);
+ var expectedSql = reader.GetString(1);
+
+ if (schema.TryGetValue(table, out var actualSql))
+ {
+ if (actualSql != expectedSql)
+ {
+ throw new MissingFieldException($"Expected {table} schema to be {expectedSql}, found {actualSql}");
+ }
+ else
+ {
+ Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql);
+ }
+ }
+
+ rows++;
+ }
+
+ if (rows != schema.Count)
+ {
+ throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}");
+ }
+
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}");
+ return false;
+ }
+ }
+
+ private void Backup()
+ {
+ using var sourceConn = GetConnection();
+ using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup);
+ sourceConn.BackupDatabase(backupConn);
+ }
+
private int CountDirectories()
{
using var conn = GetConnection();
@@ -494,9 +586,9 @@ namespace slskd.Shares
"extension TEXT, attributeJson TEXT NOT NULL);");
}
- private SqliteConnection GetConnection()
+ private SqliteConnection GetConnection(string connectionString = null)
{
- var conn = new SqliteConnection(Program.ConnectionStrings.Shares);
+ var conn = new SqliteConnection(connectionString ?? Program.ConnectionStrings.Shares);
conn.Open();
return conn;
}
@@ -594,37 +686,5 @@ namespace slskd.Shares
cmd?.Dispose();
}
}
-
- private void ResetCache()
- {
- CreateTables();
-
- try
- {
- System.IO.File.Delete(Path.Combine(Program.DataDirectory, Filenames.BrowseCache));
- }
- catch (FileNotFoundException)
- {
- // noop
- }
-
- State.SetValue(state => state with { Directories = 0, Files = 0 });
- }
-
- private bool TableExists(string table)
- {
- using var conn = GetConnection();
- using var cmd = new SqliteCommand("SELECT name from sqlite_master WHERE type = 'table' AND name = @table;", conn);
- cmd.Parameters.AddWithValue("table", table);
- var reader = cmd.ExecuteReader();
-
- if (reader.Read())
- {
- var fetchedTable = reader.GetString(0);
- return table == fetchedTable;
- }
-
- return false;
- }
}
} \ No newline at end of file
diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs
index 54b9a6c3..2c7e3eac 100644
--- a/src/slskd/Transfers/Uploads/UploadQueue.cs
+++ b/src/slskd/Transfers/Uploads/UploadQueue.cs
@@ -402,7 +402,7 @@ namespace slskd.Transfers
Priority = options.Groups.Default.Upload.Priority,
Slots = Math.Min(options.Groups.Default.Upload.Slots, GlobalSlots),
UsedSlots = GetExistingUsedSlotsOrDefault(Application.DefaultGroup),
- Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Default.Upload.Strategy, true),
+ Strategy = options.Groups.Default.Upload.Strategy.ToEnum<QueueStrategy>(),
},
new UploadGroup()
{
@@ -410,7 +410,7 @@ namespace slskd.Transfers
Priority = options.Groups.Leechers.Upload.Priority,
Slots = Math.Min(options.Groups.Leechers.Upload.Slots, GlobalSlots),
UsedSlots = GetExistingUsedSlotsOrDefault(Application.LeecherGroup),
- Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Leechers.Upload.Strategy, true),
+ Strategy = options.Groups.Leechers.Upload.Strategy.ToEnum<QueueStrategy>(),
},
};
@@ -421,7 +421,7 @@ namespace slskd.Transfers
Priority = kvp.Value.Upload.Priority,
Slots = Math.Min(kvp.Value.Upload.Slots, GlobalSlots),
UsedSlots = GetExistingUsedSlotsOrDefault(kvp.Key),
- Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true),
+ Strategy = kvp.Value.Upload.Strategy.ToEnum<QueueStrategy>(),
}));
Groups = groups.ToDictionary(g => g.Name);